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:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent f48411f8fe
commit 7878937691
40 changed files with 464 additions and 138 deletions
@@ -171,7 +171,7 @@ export function CanonicalRecordedLabReplay<
> >
{splitView || paneToolbarsAlwaysVisible ? ( {splitView || paneToolbarsAlwaysVisible ? (
<div <div
className="m4-replay-threat-visual__pane-toolbar" className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="media" data-pane-toolbar="media"
data-multi-semantic={mediaMultiLayer ? "true" : undefined} data-multi-semantic={mediaMultiLayer ? "true" : undefined}
> >
@@ -190,7 +190,7 @@ export function CanonicalRecordedLabReplay<
> >
{splitView || paneToolbarsAlwaysVisible ? ( {splitView || paneToolbarsAlwaysVisible ? (
<div <div
className="m4-replay-threat-visual__pane-toolbar" className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="spatial" data-pane-toolbar="spatial"
> >
{spatialLeadingControl} {spatialLeadingControl}
@@ -83,7 +83,7 @@ export function LaboratoryEvidenceViewer<
}, [expanded, onExpandedChange]); }, [expanded, onExpandedChange]);
const controls = ( const controls = (
<div className="laboratory-evidence-viewer__controls"> <div className="laboratory-evidence-viewer__controls nodedc-viewport-controls">
{actions} {actions}
{modeControlsVisible && secondaryMode ? ( {modeControlsVisible && secondaryMode ? (
<SegmentedControl <SegmentedControl
@@ -137,7 +137,7 @@ export function LaboratoryEvidenceViewer<
{children} {children}
</div> </div>
{transport ? ( {transport ? (
<div className="laboratory-evidence-viewer__transport"> <div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport} {transport}
</div> </div>
) : null} ) : null}
@@ -149,7 +149,7 @@ export function LaboratoryEvidenceViewer<
</div> </div>
{overlay} {overlay}
{transport ? ( {transport ? (
<div className="laboratory-evidence-viewer__transport"> <div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport} {transport}
</div> </div>
) : null} ) : null}
@@ -101,7 +101,7 @@ export function LaboratoryReviewWorkspaceFrame({
keepFocusInside(event, event.currentTarget); keepFocusInside(event, event.currentTarget);
}} }}
> >
<header className="laboratory-review-workspace__toolbar">{toolbar}</header> <header className="laboratory-review-workspace__toolbar nodedc-viewport-controls">{toolbar}</header>
<div className="laboratory-review-workspace__stage">{stage}</div> <div className="laboratory-review-workspace__stage">{stage}</div>
{inspector ? <footer className="laboratory-review-workspace__inspector">{inspector}</footer> : null} {inspector ? <footer className="laboratory-review-workspace__inspector">{inspector}</footer> : null}
{overlays} {overlays}
@@ -1,3 +1,4 @@
import {heightSlice} from "../../core/heightSlice";
import {useEffect,useRef,useState} from 'react'; import {useEffect,useRef,useState} from 'react';
import {Button,LoadingRegion,RangeControl} from '@nodedc/ui-react'; import {Button,LoadingRegion,RangeControl} from '@nodedc/ui-react';
import {createIsolatedRerunHost} from '../rerun/isolatedRerunHost'; import {createIsolatedRerunHost} from '../rerun/isolatedRerunHost';
@@ -26,16 +27,20 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
const optionsRef=useRef(options);optionsRef.current=options; const optionsRef=useRef(options);optionsRef.current=options;
const stateRef=useRef({active,revision});stateRef.current={active,revision}; const stateRef=useRef({active,revision});stateRef.current={active,revision};
const ceilingRef=useRef<number|null>(null); const ceilingRef=useRef<number|null>(null);
const floorRef=useRef<number|null>(null);
const boundsRef=useRef<{min:number;max:number}|null>(null); const boundsRef=useRef<{min:number;max:number}|null>(null);
const host=useRef<HTMLDivElement>(null); const host=useRef<HTMLDivElement>(null);
const [state,setState]=useState('loading'),[retry,setRetry]=useState(0); const [state,setState]=useState('loading'),[retry,setRetry]=useState(0);
const [bounds,setBounds]=useState<{min:number;max:number}|null>(null); const [bounds,setBounds]=useState<{min:number;max:number}|null>(null);
const [ceiling,setCeiling]=useState<number|null>(null); const [ceiling,setCeiling]=useState<number|null>(null);
const [floor,setFloor]=useState<number|null>(null);
useEffect(()=>{
ceilingRef.current=null;floorRef.current=null;setCeiling(null);setFloor(null);
},[runId]);
useEffect(()=>{ useEffect(()=>{
ceilingRef.current=null;
const next=heightBounds&&Number.isFinite(heightBounds.min)&&Number.isFinite(heightBounds.max)&&heightBounds.max>heightBounds.min?heightBounds:null; const next=heightBounds&&Number.isFinite(heightBounds.min)&&Number.isFinite(heightBounds.max)&&heightBounds.max>heightBounds.min?heightBounds:null;
boundsRef.current=next; boundsRef.current=next;
setBounds(next);setCeiling(null); setBounds(next);
},[runId,heightBounds?.min,heightBounds?.max]); },[runId,heightBounds?.min,heightBounds?.max]);
useEffect(()=>{ useEffect(()=>{
if(!host.current)return; if(!host.current)return;
@@ -54,6 +59,7 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
stopStream=startPlanningSceneStream({ stopStream=startPlanningSceneStream({
url:`${plannerBase}/live-tests/${runId}/scene-delta.rrd`, url:`${plannerBase}/live-tests/${runId}/scene-delta.rrd`,
snapshot:()=>({...stateRef.current,options:{...optionsRef.current, snapshot:()=>({...stateRef.current,options:{...optionsRef.current,
...(floorRef.current===null?{}:{floor_m:floorRef.current}),
...(ceilingRef.current===null?{}:{ceiling_m:ceilingRef.current})}}), ...(ceilingRef.current===null?{}:{ceiling_m:ceilingRef.current})}}),
apply:async(bytes,delivery)=>{ apply:async(bytes,delivery)=>{
if(disposed)return; if(disposed)return;
@@ -62,9 +68,6 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
const previous=boundsRef.current; const previous=boundsRef.current;
if(!previous||previous.min!==next.min||previous.max!==next.max){ if(!previous||previous.min!==next.min||previous.max!==next.max){
boundsRef.current=next;setBounds(next); boundsRef.current=next;setBounds(next);
if(ceilingRef.current!==null&&(ceilingRef.current<next.min||ceilingRef.current>next.max)){
ceilingRef.current=null;setCeiling(null);
}
} }
} }
sceneAvailable=true; sceneAvailable=true;
@@ -89,15 +92,15 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
return()=>{disposed=true;stopStream?.();reporter.dispose();clearTimeout(timeout);runtime.dispose();}; return()=>{disposed=true;stopStream?.();reporter.dispose();clearTimeout(timeout);runtime.dispose();};
},[runId,retry]); },[runId,retry]);
const sourceBounds=bounds??heightBounds; const sourceBounds=bounds??heightBounds;
const rangeBounds=sourceBounds?{min:Math.min(sourceBounds.min,0),max:CLIP_CEILING_M}:null; const rangeBounds=sourceBounds?{min:Math.min(sourceBounds.min,0,floor??Infinity),max:Math.max(CLIP_CEILING_M,sourceBounds.max,ceiling??-Infinity)}:null;
return <LoadingRegion loading={state==='loading'} label="Загрузка эталона и нового прохода" className="planning-live__scene"> return <LoadingRegion loading={state==='loading'} label="Загрузка эталона и нового прохода" className="planning-live__scene">
<div ref={host} className="session-overview__runtime rerun-single-view-content" style={{visibility:state==='ready'?'visible':'hidden'}} /> <div ref={host} className="session-overview__runtime rerun-single-view-content" style={{visibility:state==='ready'?'visible':'hidden'}} />
{rangeBounds&&state==='ready'&&<div className="session-overview__height"> {rangeBounds&&state==='ready'&&<div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={ceiling??rangeBounds.max} min={rangeBounds.min} max={rangeBounds.max} step="any" <RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor??rangeBounds.min,ceiling??rangeBounds.max]} min={rangeBounds.min} max={rangeBounds.max} step="any"
formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')} formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')}
onChange={value=>{ onChange={value=>{
const next=value>=rangeBounds.max-Math.max(1,rangeBounds.max-rangeBounds.min)*1e-9?null:value; const next=heightSlice(value,[rangeBounds.min,rangeBounds.max]);
ceilingRef.current=next;setCeiling(next); floorRef.current=next.floor;setFloor(next.floor);ceilingRef.current=next.ceiling;setCeiling(next.ceiling);
}}/> }}/>
</div>} </div>}
{state==='error'&&<div className="session-overview__empty"><span>Обновление сцены недоступно.</span><Button onClick={()=>setRetry(v=>v+1)}>Повторить подключение сцены</Button></div>} {state==='error'&&<div className="session-overview__empty"><span>Обновление сцены недоступно.</span><Button onClick={()=>setRetry(v=>v+1)}>Повторить подключение сцены</Button></div>}
@@ -7,11 +7,11 @@ export function ObservationMount({element,className='observation-mount'}:{elemen
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]); useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
return <div ref={ref} className={className}/>; return <div ref={ref} className={className}/>;
} }
export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,children}:{ export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,minimumSizes,children}:{
ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void; ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void;
labels:Record<string,string>;focusedId?:string|null;children:ReactNode; minimumSizes?:Record<string,{width:number;height:number}>; labels:Record<string,string>;focusedId?:string|null;children:ReactNode;
}){ }){
return <DockLayout tree={observationTree(layout,ids)} onTreeChange={onTreeChange} return <DockLayout tree={observationTree(layout,ids)} onTreeChange={onTreeChange}
focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id}))} focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id,minimumSize:minimumSizes?.[id],preferredSize:!layout.tree&&!Object.keys(layout.splits).length?minimumSizes?.[id]:undefined}))}
renderPanel={id=><ObservationMount element={mounts.get(id)!}/>}>{children}</DockLayout>; renderPanel={id=><ObservationMount element={mounts.get(id)!}/>}>{children}</DockLayout>;
} }
@@ -9,5 +9,5 @@ export function ObservationPanelHeader({children}:{children:ReactNode}) {
measure();const observer=new ResizeObserver(measure);observer.observe(header); measure();const observer=new ResizeObserver(measure);observer.observe(header);
return()=>observer.disconnect(); return()=>observer.disconnect();
},[]); },[]);
return <header ref={ref} className="observation-panel__header">{children}</header>; return <header ref={ref} className="observation-panel__header nodedc-viewport-controls">{children}</header>;
} }
@@ -1,3 +1,4 @@
import { heightSlice } from "../../core/heightSlice";
import { type ReactNode, useEffect, useRef, useState } from "react"; import { type ReactNode, useEffect, useRef, useState } from "react";
import { Button, LoadingRegion, RangeControl, SegmentedControl } from "@nodedc/ui-react"; import { Button, LoadingRegion, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost"; import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost";
@@ -11,6 +12,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const [retry, setRetry] = useState(0); const [retry, setRetry] = useState(0);
const [metadata, setMetadata] = useState<OverviewSpatialMetadata | null>(null); const [metadata, setMetadata] = useState<OverviewSpatialMetadata | null>(null);
const [ceiling, setCeiling] = useState<number | null>(null); const [ceiling, setCeiling] = useState<number | null>(null);
const [floor, setFloor] = useState<number | null>(null);
const [mode, setMode] = useState<OverviewViewMode>("3d"); const [mode, setMode] = useState<OverviewViewMode>("3d");
const [viewError, setViewError] = useState<string | null>(null); const [viewError, setViewError] = useState<string | null>(null);
const [visiblePoints, setVisiblePoints] = useState<number | null>(null); const [visiblePoints, setVisiblePoints] = useState<number | null>(null);
@@ -26,7 +28,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const abort = new AbortController(); const abort = new AbortController();
appliedMode.current = null; appliedMode.current = null;
setState("loading"); setState("loading");
setMetadata(null); setCeiling(null); setMode("3d"); setVisiblePoints(null); setViewError(null); setMetadata(null); setCeiling(null); setFloor(null); setMode("3d"); setVisiblePoints(null); setViewError(null);
setRepresentation("original"); setAppliedRepresentation("original"); setUpdating(false); setRepresentation("original"); setAppliedRepresentation("original"); setUpdating(false);
void fetchOverviewSpatial(sourceUrl, abort.signal).then(data => { void fetchOverviewSpatial(sourceUrl, abort.signal).then(data => {
if (disposed) return; if (disposed) return;
@@ -56,7 +58,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const timer = setTimeout(() => { const timer = setTimeout(() => {
const aspect = Math.max(.1, Math.min(20, (host.current?.clientWidth ?? 1) / Math.max(1, (host.current?.clientHeight ?? 1) - 28))); const aspect = Math.max(.1, Math.min(20, (host.current?.clientWidth ?? 1) / Math.max(1, (host.current?.clientHeight ?? 1) - 28)));
void updateOverviewSpatial(sourceUrl, ceiling, appliedMode.current === mode ? null : mode, aspect, abort.signal, void updateOverviewSpatial(sourceUrl, ceiling, appliedMode.current === mode ? null : mode, aspect, abort.signal,
comparison?.generation ?? null, comparison ? representation : "original").then(result => { comparison?.generation ?? null, comparison ? representation : "original", floor).then(result => {
if (abort.signal.aborted || !controller.current) return; if (abort.signal.aborted || !controller.current) return;
controller.current.channel.send_rrd(result.bytes); controller.current.channel.send_rrd(result.bytes);
appliedMode.current = mode; appliedMode.current = mode;
@@ -65,12 +67,12 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
}).catch(() => { if (!abort.signal.aborted) { setUpdating(false); setViewError("Не удалось обновить вид облака. Показан предыдущий вид."); } }); }).catch(() => { if (!abort.signal.aborted) { setUpdating(false); setViewError("Не удалось обновить вид облака. Показан предыдущий вид."); } });
}, 180); }, 180);
return () => { abort.abort(); clearTimeout(timer); }; return () => { abort.abort(); clearTimeout(timer); };
}, [state, metadata, sourceUrl, ceiling, mode, retry, comparison, representation]); }, [state, metadata, sourceUrl, ceiling, floor, mode, retry, comparison, representation]);
const low = comparison?.height_min_m ?? metadata?.height_min_m; const low = comparison?.height_min_m ?? metadata?.height_min_m;
const high = comparison?.height_max_m ?? metadata?.height_max_m; const high = comparison?.height_max_m ?? metadata?.height_max_m;
return <> return <>
<div className={`session-overview__scene-head ${hideTitle?"session-overview__scene-head--end":""}`}>{!hideTitle&&<h2>Облако и траектория</h2>} <div className={`session-overview__scene-head nodedc-viewport-controls ${hideTitle?"session-overview__scene-head--end":""}`}>{!hideTitle&&<h2>Облако и траектория</h2>}
{compareVersions && comparison && <SegmentedControl label="Версия облака" value={representation} onChange={setRepresentation} {compareVersions && comparison && <SegmentedControl label="Версия облака" value={representation} onChange={setRepresentation}
items={[{ value: "original", label: "Исходное", disabled: state !== "ready" }, { value: "corrected", label: "Исправленное", disabled: state !== "ready" }]} />} items={[{ value: "original", label: "Исходное", disabled: state !== "ready" }, { value: "corrected", label: "Исправленное", disabled: state !== "ready" }]} />}
<SegmentedControl label="Вид облака" value={mode} onChange={setMode} <SegmentedControl label="Вид облака" value={mode} onChange={setMode}
@@ -80,15 +82,15 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
<LoadingRegion loading={state === "loading" || (state === "ready" && !!metadata && visiblePoints === null && !viewError)} label="Загрузка облака" className="session-overview__scene"> <LoadingRegion loading={state === "loading" || (state === "ready" && !!metadata && visiblePoints === null && !viewError)} label="Загрузка облака" className="session-overview__scene">
<div ref={host} className={`session-overview__runtime ${hideTitle?"rerun-single-view-content":""}`} style={{ visibility: state === "ready" && metadata && visiblePoints !== null ? "visible" : "hidden" }} /> <div ref={host} className={`session-overview__runtime ${hideTitle?"rerun-single-view-content":""}`} style={{ visibility: state === "ready" && metadata && visiblePoints !== null ? "visible" : "hidden" }} />
{low != null && high != null && high > low && state === "ready" && <div className="session-overview__height"> {low != null && high != null && high > low && state === "ready" && <div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={ceiling ?? high} min={low} max={high} step="any" <RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor ?? low, ceiling ?? high]} min={low} max={high} step="any"
formatValue={value => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={value => value.toFixed(1).replace('.', ',')} formatValue={value => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={value => value.toFixed(1).replace('.', ',')}
onChange={value => setCeiling(value >= high - Math.max(1, high - low) * 1e-9 ? null : value)} /> onChange={value => { const next = heightSlice(value, [low, high]); setFloor(next.floor); setCeiling(next.ceiling); }} />
</div>} </div>}
{state === "error" && <div className="session-overview__empty"><span>Не удалось открыть облако.</span><Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>} {state === "error" && <div className="session-overview__empty"><span>Не удалось открыть облако.</span><Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
</LoadingRegion> </LoadingRegion>
<span className="session-overview__note" role="status" aria-busy={updating}> <span className="session-overview__note" role="status" aria-busy={updating}>
{updating ? "Обновление · " : comparison ? `${appliedRepresentation === "corrected" ? "Исправленное" : "Исходное"} · ` : ""} {updating ? "Обновление · " : comparison ? `${appliedRepresentation === "corrected" ? "Исправленное" : "Исходное"} · ` : ""}
{ceiling == null ? "Без среза" : `Высота ≤ ${ceiling.toFixed(1)} м`} · {visiblePoints?.toLocaleString("ru-RU") ?? "—"} точек {floor == null && ceiling == null ? "Без среза" : `${floor == null ? "" : `${floor.toFixed(1)} м ≤ `}Высота${ceiling == null ? "" : ` ≤ ${ceiling.toFixed(1)} м`}`} · {visiblePoints?.toLocaleString("ru-RU") ?? "—"} точек
{comparison && <><br />Выборка для просмотра. Исходная запись сохранена отдельно.</>} {comparison && <><br />Выборка для просмотра. Исходная запись сохранена отдельно.</>}
</span> </span>
{viewError && <div className="session-overview__note" role="alert">{viewError}<Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>} {viewError && <div className="session-overview__note" role="alert">{viewError}<Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
@@ -22,6 +22,7 @@
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; } .observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; } .observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
.observation-header-slot:has(> div:empty) { display:none; } .observation-header-slot:has(> div:empty) { display:none; }
.observation-panel__title .observation-header-slot, .observation-panel__title .observation-header-slot > div { min-width:0; max-width:100%; flex-shrink:1; }
.observation-layer-select { min-width:0; max-width:120px; } .observation-layer-select { min-width:0; max-width:120px; }
.observation-layer-select button { max-width:100%; } .observation-layer-select button { max-width:100%; }
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } .observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
@@ -29,6 +30,7 @@
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; } .observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; } .observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); } .observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
.observation-source__notice--centered { inset:var(--observation-overlay-header-space, 0px) 0 0; margin:0; padding:var(--nodedc-space-4); display:grid; place-content:center; font-size:var(--nodedc-font-size-sm); pointer-events:none; }
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; } .observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); } .observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); } .observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
@@ -45,10 +47,11 @@
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); } .observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
.observation-split:has(.observation-panel-drag.is-dragging), .observation-split:has(.observation-panel-drag.is-dragging),
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); } .observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
@container (max-width:340px) { @container (max-width:420px) {
.observation-panel__header { flex-wrap:wrap; } .observation-panel__header { flex-wrap:wrap; }
.observation-panel__title { min-width:80px; } .observation-panel__title { min-width:80px; }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; } .observation-panel__title:has(.rover-view__title) { min-width:min(160px, 100%); }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; gap:var(--nodedc-space-1); }
} }
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); } .observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
@@ -0,0 +1,6 @@
/** View-only bounds. Each full-range endpoint disables its own clipping plane. */
export function heightSlice([lower, upper]: readonly [number, number], [min, max]: readonly [number, number]) {
const tolerance = Math.max(1, max - min) * 1e-9;
return { floor: lower <= min + tolerance ? null : lower,
ceiling: upper >= max - tolerance ? null : upper };
}
@@ -2,7 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useRef, useState, ty
import { plannerBase, plannerRequest, type Draft } from './planner'; import { plannerBase, plannerRequest, type Draft } from './planner';
export interface PlanningLiveTest { export interface PlanningLiveTest {
schema_version: 'missioncore.planning-live-test/v1'; id: string; profile: 'planning'; plugin_id:string; draft: Draft; schema_version: 'missioncore.planning-live-test/v1'|'missioncore.planning-live-status/v1'; id: string; profile: 'planning'; plugin_id:string; draft: Omit<Draft,'route'> & {route:Omit<Draft['route'],'points'>};
state: 'preparing'|'waiting'|'running'|'completed'|'cancelled'|'error'|'interrupted'; state: 'preparing'|'waiting'|'running'|'completed'|'cancelled'|'error'|'interrupted';
planning_phase?: 'preparing'|'waiting-cloud'|'collecting'|'searching'|'refreshing'|'validating'|'tracking'|'lost'|'ended'; planning_phase?: 'preparing'|'waiting-cloud'|'collecting'|'searching'|'refreshing'|'validating'|'tracking'|'lost'|'ended';
tracking_state?: 'acquiring'|'tracking'|'lost'; tracking_state?: 'acquiring'|'tracking'|'lost';
@@ -40,7 +40,7 @@ export function PlanningTestProvider({children}:{children:ReactNode}) {
let disposed=false, timer:ReturnType<typeof setTimeout>; let disposed=false, timer:ReturnType<typeof setTimeout>;
const poll=async()=>{ const poll=async()=>{
const expected=generation.current; const expected=generation.current;
try { const next=await plannerRequest<PlanningLiveTest|null>(endpoint+'/active'); if(!disposed && expected===generation.current) {setTest(next);setPollError(null);} } try { const next=await plannerRequest<PlanningLiveTest|null>(endpoint+'/status'); if(!disposed && expected===generation.current) {setTest(next);setPollError(null);} }
catch(e) {if(!disposed && expected===generation.current)setPollError(e instanceof Error?e.message:'Исследование недоступно.');} catch(e) {if(!disposed && expected===generation.current)setPollError(e instanceof Error?e.message:'Исследование недоступно.');}
if(!disposed)timer=setTimeout(()=>void poll(),1500); if(!disposed)timer=setTimeout(()=>void poll(),1500);
};void poll();return()=>{disposed=true;clearTimeout(timer);}; };void poll();return()=>{disposed=true;clearTimeout(timer);};
@@ -22,13 +22,13 @@ export async function fetchOverviewSpatial(source: string, signal: AbortSignal):
return response.json(); return response.json();
} }
export async function updateOverviewSpatial(source: string, ceiling: number | null, mode: OverviewViewMode | null, aspect: number, signal: AbortSignal, export async function updateOverviewSpatial(source: string, ceiling: number | null, mode: OverviewViewMode | null, aspect: number, signal: AbortSignal,
comparisonGeneration: string | null = null, representation: OverviewRepresentation = "original") { comparisonGeneration: string | null = null, representation: OverviewRepresentation = "original", floor: number | null = null) {
if (representation === "corrected" && !comparisonGeneration) throw new Error("Исправленная версия недоступна."); if (representation === "corrected" && !comparisonGeneration) throw new Error("Исправленная версия недоступна.");
const url = endpoint(source); const url = endpoint(source);
const generation = url.searchParams.get("generation"); const generation = url.searchParams.get("generation");
url.search = ""; url.search = "";
const response = await fetch(url, { method: "POST", signal, headers: { "Content-Type": "application/json" }, const response = await fetch(url, { method: "POST", signal, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ generation, ceiling_m: ceiling, mode, aspect, body: JSON.stringify({ generation, ceiling_m: ceiling, floor_m: floor, mode, aspect,
comparison_generation: comparisonGeneration, representation }) }); comparison_generation: comparisonGeneration, representation }) });
if (!response.ok) throw new Error("Не удалось обновить вид облака."); if (!response.ok) throw new Error("Не удалось обновить вид облака.");
const bytes = new Uint8Array(await response.arrayBuffer()); const bytes = new Uint8Array(await response.arrayBuffer());
@@ -305,8 +305,6 @@
} }
.m4-replay-threat-visual__layer-with-settings > .nodedc-icon-button { .m4-replay-threat-visual__layer-with-settings > .nodedc-icon-button {
width: 1.75rem;
height: 1.75rem;
border: 0; border: 0;
outline: 0; outline: 0;
box-shadow: none; box-shadow: none;
@@ -439,7 +439,7 @@ export function E30EvidencePointCloud({ detail }: E30EvidencePointCloudProps) {
<p className="e30-evidence-scene__error">{renderError}</p> <p className="e30-evidence-scene__error">{renderError}</p>
) : null} ) : null}
</div> </div>
<div className="e30-evidence-scene__toolbar"> <div className="e30-evidence-scene__toolbar nodedc-viewport-controls">
<Button <Button
variant="secondary" variant="secondary"
size="compact" size="compact"
@@ -1,3 +1,4 @@
import { Button } from "@nodedc/ui-react";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import * as THREE from "three"; import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js"; import { OrbitControls } from "three/addons/controls/OrbitControls.js";
@@ -591,8 +592,8 @@ export function LidarGroundPointCloud({
<p className="lidar-ground-scene__error">{renderError}</p> <p className="lidar-ground-scene__error">{renderError}</p>
) : null} ) : null}
</div> </div>
<div className="lidar-ground-scene__toolbar"> <div className="lidar-ground-scene__toolbar nodedc-viewport-controls">
<button type="button" onClick={resetCamera}>Сбросить ракурс</button> <Button onClick={resetCamera}>Сбросить ракурс</Button>
<span>ЛКМ · вращение</span> <span>ЛКМ · вращение</span>
<span>Колесо · масштаб</span> <span>Колесо · масштаб</span>
<span>ПКМ · панорама</span> <span>ПКМ · панорама</span>
@@ -335,7 +335,7 @@ export function E34TemporalLayerScene({
<p className="e34-temporal-scene__error">{renderError}</p> <p className="e34-temporal-scene__error">{renderError}</p>
) : null} ) : null}
</div> </div>
<div className="e34-temporal-scene__toolbar"> <div className="e34-temporal-scene__toolbar nodedc-viewport-controls">
<Button <Button
variant="secondary" variant="secondary"
size="compact" size="compact"
@@ -591,7 +591,7 @@ export function L34AnnotationWorkspace({
: "L3.4" : "L3.4"
}`} }`}
> >
<header className="l34-annotation-workspace__toolbar"> <header className="l34-annotation-workspace__toolbar nodedc-viewport-controls">
<div className="l34-annotation-workspace__session-tools"> <div className="l34-annotation-workspace__session-tools">
<Select <Select
label="Сессия разметки" label="Сессия разметки"
@@ -372,7 +372,7 @@ export function L34FAdjudicationWorkspace({
aria-modal="true" aria-modal="true"
aria-label="Разбор конфликтов LAB L3.4F" aria-label="Разбор конфликтов LAB L3.4F"
> >
<header className="l34-annotation-workspace__toolbar"> <header className="l34-annotation-workspace__toolbar nodedc-viewport-controls">
<div className="l34-annotation-workspace__session-tools"> <div className="l34-annotation-workspace__session-tools">
<Select <Select
label="Сессия разбора конфликтов" label="Сессия разбора конфликтов"
@@ -273,7 +273,7 @@ export function WorldMapWorkspace({
/> />
) : null} ) : null}
<div className="mission-map__map-actions" aria-label="Управление картой"> <div className="mission-map__map-actions nodedc-viewport-controls" aria-label="Управление картой">
<IconButton <IconButton
className="mission-map__map-action" className="mission-map__map-action"
label="Настройки карты" label="Настройки карты"
@@ -0,0 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const result=await build({entryPoints:[new URL('../src/core/heightSlice.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
const {heightSlice}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
test('each boundary independently disables clipping and fractional native rounding restores full scene',()=>{
const bounds=[-51.4623,77.72065000000002];
assert.deepEqual(heightSlice([-51.4623,77.72065],bounds),{floor:null,ceiling:null});
assert.deepEqual(heightSlice([0,77.72065],bounds),{floor:0,ceiling:null});
assert.deepEqual(heightSlice([-51.4623,20],bounds),{floor:null,ceiling:20});
assert.deepEqual(heightSlice([2,20],bounds),{floor:2,ceiling:20});
assert.deepEqual(heightSlice([2,2],bounds),{floor:2,ceiling:2});
});
+2 -2
View File
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import { readFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import { after, before, test } from "node:test"; import { after, before, test } from "node:test";
import { createServer } from "vite"; import { createServer } from "./support/vite-server.mjs";
let server; let server;
let mapView; let mapView;
@@ -217,7 +217,7 @@ test("map workspace keeps the canonical top actions without a bottom toolbar", a
); );
assert.doesNotMatch(source, /<Toolbar/); assert.doesNotMatch(source, /<Toolbar/);
assert.match(source, /className="mission-map__map-actions"/); assert.match(source, /className="mission-map__map-actions nodedc-viewport-controls"/);
assert.match(source, /label="Настройки карты"/); assert.match(source, /label="Настройки карты"/);
assert.match(source, /label="Слои карты"/); assert.match(source, /label="Слои карты"/);
assert.doesNotMatch(source, /label="Сбросить камеру"/); assert.doesNotMatch(source, /label="Сбросить камеру"/);
@@ -10,6 +10,8 @@ test('planning live scene reuses the canonical vertical height range inside the
assert.match(source,/formatLimit=\{value=>value\.toFixed\(1\)\.replace\('\.',','\)\}/); assert.match(source,/formatLimit=\{value=>value\.toFixed\(1\)\.replace\('\.',','\)\}/);
assert.match(source,/heightBounds=null/); assert.match(source,/heightBounds=null/);
assert.match(source,/const CLIP_CEILING_M=80/); assert.match(source,/const CLIP_CEILING_M=80/);
assert.match(source,/max:CLIP_CEILING_M/); assert.match(source,/max:Math\.max\(CLIP_CEILING_M,sourceBounds\.max,ceiling\?\?-Infinity\)/);
assert.match(source,/setBounds\(next\);setCeiling\(null\);/); assert.match(source,/floor_m:floorRef\.current/);
assert.match(source,/value=\{\[floor\?\?rangeBounds\.min,ceiling\?\?rangeBounds\.max\]\}/);
assert.match(source,/floorRef\.current=null;setCeiling\(null\);setFloor\(null\);\s*\},\[runId\]\)/);
}); });
@@ -107,7 +107,7 @@ export function FloatingMediaWindow({title,subtitle,status,footer,children,index
resizable={resizable} resizable={resizable}
active={active} active={active}
zIndex={maximized ? 15 : active ? 9 : 7} zIndex={maximized ? 15 : active ? 9 : 7}
className={`floating-observation-window${hidden ? " floating-observation-window--hidden" : ""}`} className={`floating-observation-window nodedc-viewport-controls${hidden ? " floating-observation-window--hidden" : ""}`}
onPointerDownCapture={(event) => { onPointerDownCapture={(event) => {
if (!shouldCaptureWorkspacePointer(event.button, event.target as HTMLElement)) return; if (!shouldCaptureWorkspacePointer(event.button, event.target as HTMLElement)) return;
try { try {
+10 -17
View File
@@ -1,4 +1,4 @@
import { Button, Icon, Select } from "@nodedc/ui-react"; import { Button, Icon, IconButton, Select } from "@nodedc/ui-react";
import { MAX_ACCUMULATION_SECONDS } from "./sceneSettings"; import { MAX_ACCUMULATION_SECONDS } from "./sceneSettings";
type ObservationTimelineMode = "live-only" | "buffered" | "recorded"; type ObservationTimelineMode = "live-only" | "buffered" | "recorded";
@@ -66,7 +66,7 @@ export function ObservationTimeline({
: normalizeAccumulationSeconds(accumulationSeconds); : normalizeAccumulationSeconds(accumulationSeconds);
return ( return (
<div <div
className={`observation-timeline ${className}`.trim()} className={`observation-timeline nodedc-viewport-controls ${className}`.trim()}
data-active={active ? "true" : undefined} data-active={active ? "true" : undefined}
data-mode={mode} data-mode={mode}
data-accumulation={accumulationValue !== null ? "true" : undefined} data-accumulation={accumulationValue !== null ? "true" : undefined}
@@ -94,24 +94,18 @@ export function ObservationTimeline({
</div> </div>
) : null} ) : null}
<div className="observation-timeline__playback"> <div className="observation-timeline__playback">
<Button <IconButton
size="compact"
variant="ghost"
disabled={!buffered || !onSeek} disabled={!buffered || !onSeek}
aria-label="Перейти к началу" label="Перейти к началу"
onClick={() => playbackRange && onSeek?.(playbackRange.min)} onClick={() => playbackRange && onSeek?.(playbackRange.min)}
> >
<Icon name="chevron-left" /> <Icon name="chevron-left" />
</Button> </IconButton>
<Button <IconButton
className="observation-timeline__transport"
size="compact"
variant="ghost"
disabled={!buffered || !onPlayingChange} disabled={!buffered || !onPlayingChange}
aria-label={buffered ? (playing ? "Пауза" : "Воспроизвести") : "Только эфир"} label={buffered ? (playing ? "Пауза" : "Воспроизвести") : "Только эфир"}
icon={<Icon name={playing ? "stop" : "play"} />}
onClick={() => onPlayingChange?.(!playing)} onClick={() => onPlayingChange?.(!playing)}
/> ><Icon name={playing ? "stop" : "play"} /></IconButton>
{buffered && playbackRate !== undefined && onPlaybackRateChange ? ( {buffered && playbackRate !== undefined && onPlaybackRateChange ? (
<Select <Select
label="Скорость воспроизведения" label="Скорость воспроизведения"
@@ -151,15 +145,14 @@ export function ObservationTimeline({
</small> </small>
</div> </div>
{showJumpToEnd ? ( {showJumpToEnd ? (
<button <Button variant="ghost" shape="pill"
type="button"
className="observation-timeline__follow" className="observation-timeline__follow"
data-active={!buffered && active ? "true" : undefined} data-active={!buffered && active ? "true" : undefined}
disabled={buffered ? !onJumpToEnd : true} disabled={buffered ? !onJumpToEnd : true}
onClick={onJumpToEnd} onClick={onJumpToEnd}
> >
{buffered ? "К КОНЦУ" : "ЭФИР"} {buffered ? "К КОНЦУ" : "ЭФИР"}
</button> </Button>
) : null} ) : null}
</div> </div>
</div> </div>
+1 -1
View File
@@ -11,7 +11,7 @@ export function SpatialScene({viewportRef, focused, primaryFocused, mediaMaximiz
}) { }) {
const detailsHidden = primaryFocused || mediaMaximized; const detailsHidden = primaryFocused || mediaMaximized;
return <div className="spatial-workspace" data-focused={focused?'true':undefined}> return <div className="spatial-workspace" data-focused={focused?'true':undefined}>
<div className="spatial-toolbar" data-viewer-controls="v1"><div className="spatial-toolbar__actions">{toolbar}</div></div> <div className="spatial-toolbar" data-viewer-controls="v1"><div className="spatial-toolbar__actions nodedc-viewport-controls">{toolbar}</div></div>
<div ref={viewportRef} className="spatial-viewport-shell" data-primary-focused={primaryFocused?'true':undefined} data-media-maximized={mediaMaximized?'true':undefined}> <div ref={viewportRef} className="spatial-viewport-shell" data-primary-focused={primaryFocused?'true':undefined} data-media-maximized={mediaMaximized?'true':undefined}>
{renderer} {renderer}
{deviceControls&&<div className="scene-device-controls">{deviceControls}</div>} {deviceControls&&<div className="scene-device-controls">{deviceControls}</div>}
+1 -17
View File
@@ -377,12 +377,6 @@ i[data-availability="error"] {
flex: none; flex: none;
} }
.observation-timeline__transport {
width: var(--nodedc-control-height-compact);
padding: 0;
border-radius: var(--nodedc-radius-circle);
}
.observation-timeline__accumulation { .observation-timeline__accumulation {
display: grid; display: grid;
min-width: 0; min-width: 0;
@@ -450,17 +444,7 @@ i[data-availability="error"] {
white-space: nowrap; white-space: nowrap;
} }
.observation-timeline__follow { .observation-timeline__follow { color: var(--nodedc-text-muted); }
display: inline-flex;
align-items: center;
gap: 0.38rem;
color: var(--nodedc-text-muted);
border: 0;
background: transparent;
padding: 0.3rem 0.45rem;
font-size: 0.52rem;
font-weight: 820;
}
.observation-timeline__follow:not(:disabled) { .observation-timeline__follow:not(:disabled) {
cursor: pointer; cursor: pointer;
+18
View File
@@ -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
+38
View File
@@ -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
+13 -12
View File
@@ -5,26 +5,28 @@ import rerun as rr
from rerun import blueprint as rrb from rerun import blueprint as rrb
from .registration import transform from .registration import transform
from k1link.height_slice import height_mask
from .registration_colors import query_colors from .registration_colors import query_colors
def clip_reference(points, ceiling_m): def clip_reference(points, ceiling_m, floor_m=None):
if ceiling_m is None: if ceiling_m is None and floor_m is None:
return points return points
return points[points[:, 2] <= ceiling_m] return points[height_mask(points, floor_m, ceiling_m)]
def clip_query(points, matrix, ceiling_m): def clip_query(points, matrix, ceiling_m, floor_m=None):
if ceiling_m is None or not len(points): if (ceiling_m is None and floor_m is None) or not len(points):
return points return points
transformed = transform(points, matrix) 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): def log_base(recording, reference, reference_path, options):
size = options.get("point_size", 1.8) size = options.get("point_size", 1.8)
recording.log("world", rr.ViewCoordinates.RIGHT_HAND_Z_UP, static=True) 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( recording.log(
"world/reference", "world/reference",
rr.Points3D( 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 fitted, accepted = evidence
indices = np.asarray(accepted.get("matched_query_indices", []), dtype=int) indices = np.asarray(accepted.get("matched_query_indices", []), dtype=int)
indices = indices[(indices >= 0) & (indices < len(fitted["points"]))] indices = indices[(indices >= 0) & (indices < len(fitted["points"]))]
if accepted["status"] == "candidate" and len(indices): if accepted["status"] == "candidate" and len(indices):
points = transform(fitted["points"][indices], np.array(accepted["T_reference_query"])) points = transform(fitted["points"][indices], np.array(accepted["T_reference_query"]))
if ceiling_m is not None: points = points[height_mask(points, floor_m, ceiling_m)]
points = points[np.isfinite(points).all(axis=1) & (points[:, 2] <= ceiling_m)]
recording.log( recording.log(
"world/validated_query", "world/validated_query",
rr.Points3D( rr.Points3D(
@@ -148,7 +149,7 @@ def scene_bytes(
and options.get("query", True) and options.get("query", True)
): ):
t = np.array(result["T_reference_query"]) 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( recording.log(
"world/query", "world/query",
rr.Points3D( rr.Points3D(
@@ -165,7 +166,7 @@ def scene_bytes(
static=True, static=True,
) )
if evidence: 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() recording.flush()
return sink.read() return sink.read()
finally: finally:
+3 -3
View File
@@ -87,7 +87,7 @@ def scene_delta(
name = f"world/query/cloud/{slot}" name = f"world/query/cloud/{slot}"
# Empty Points3D replaces every component; no temporal history. # Empty Points3D replaces every component; no temporal history.
points = np.empty((0, 3)) if points is None else points 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( recording.log(
name, name,
rr.Points3D( rr.Points3D(
@@ -96,7 +96,7 @@ def scene_delta(
static=True, static=True,
) )
current_points = clip_query( 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: if live:
# Temporal head follows the scanner receipt sequence. Frozen chunks # Temporal head follows the scanner receipt sequence. Frozen chunks
@@ -137,7 +137,7 @@ def scene_delta(
if full or previous.get("evidence") != current["evidence"]: if full or previous.get("evidence") != current["evidence"]:
recording.log("world/validated_query", rr.Clear(recursive=True), static=True) recording.log("world/validated_query", rr.Clear(recursive=True), static=True)
if evidence and options.get("query", 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() recording.flush()
return sink.read(), token return sink.read(), token
finally: finally:
+30
View File
@@ -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)
+57 -25
View File
@@ -21,6 +21,7 @@ from .drafts import DraftConflict
from .live_display_buffer import LiveDisplayBuffer from .live_display_buffer import LiveDisplayBuffer
from .live_limits import live_route_limits from .live_limits import live_route_limits
from .live_presentation import PRESENTATION_POLICY, LivePresentation, stored_alignment from .live_presentation import PRESENTATION_POLICY, LivePresentation, stored_alignment
from .live_report_json import ReportJSONCache
from .live_scene import scene_bytes from .live_scene import scene_bytes
from .live_scene_delta import scene_delta from .live_scene_delta import scene_delta
from .observation_profiles import SCENE_INPUT from .observation_profiles import SCENE_INPUT
@@ -58,6 +59,7 @@ class PlanningLiveTests:
self.cancel = threading.Event() self.cancel = threading.Event()
self.thread = None self.thread = None
self.revision = 0 self.revision = 0
self._report_json = ReportJSONCache()
self.last_frame_ns = 0 self.last_frame_ns = 0
self.last_result_ns = 0 self.last_result_ns = 0
self.source = None self.source = None
@@ -189,36 +191,66 @@ class PlanningLiveTests:
self.revision += 1 self.revision += 1
self.persist() self.persist()
def get(self): def get_status(self):
return self.get(compact=True)
def get(self, *, compact=False):
with self.lock: with self.lock:
if self.run is None: if self.run is None:
return None return None
result = json.loads(json.dumps(self.run)) if compact:
now = time.monotonic_ns() from .live_status import status_document
result["frame_age_s"] = (now - self.last_frame_ns) / 1e9 if self.last_frame_ns else None result = status_document(self.run)
result["result_age_s"] = ( else:
(now - self.last_result_ns) / 1e9 if self.last_result_ns else None result = json.loads(json.dumps(self.run))
) fields = self._runtime_status(compact=compact)
result["stale"] = not self.last_frame_ns or now - self.last_frame_ns > 8_000_000_000 if not compact and self.display.packet is None and "display" in self.run:
result["scene_available"] = self.reference is not None fields.pop("display") # Preserve the independent report copy.
result["scene_height_min_m"], result["scene_height_max_m"] = self.scene_height_bounds() result.update(fields)
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()
return result 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): def scene_height_bounds(self):
# Reference arrays are frozen and replaced as a unit. Do not rescan # 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. # and copy a route-wide map under the consumer lock on every UI poll.
+4 -1
View File
@@ -9,6 +9,8 @@ import rerun as rr
from rerun import blueprint as rrb from rerun import blueprint as rrb
from rerun.experimental import RrdReader from rerun.experimental import RrdReader
from k1link.height_slice import height_mask
from .overview_comparison import OverviewComparison from .overview_comparison import OverviewComparison
@@ -87,6 +89,7 @@ def render_spatial_update(
aspect: float = 1.5, aspect: float = 1.5,
comparison: OverviewComparison | None = None, comparison: OverviewComparison | None = None,
representation: Literal["original", "corrected"] = "original", representation: Literal["original", "corrected"] = "original",
floor_m: float | None = None,
): ):
app_id, recording_id, xyz, colors = geometry(path) app_id, recording_id, xyz, colors = geometry(path)
if representation == "corrected" and comparison is None: if representation == "corrected" and comparison is None:
@@ -108,7 +111,7 @@ def render_spatial_update(
colors = np.column_stack( colors = np.column_stack(
[70 + 100 * normalized, 135 + 80 * normalized, 220 - 90 * normalized] [70 + 100 * normalized, 135 + 80 * normalized, 220 - 90 * normalized]
).astype(np.uint8) ).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) recording = rr.RecordingStream(app_id, recording_id=recording_id, send_properties=False)
sink = rr.binary_stream(recording) sink = rr.binary_stream(recording)
eye = None eye = None
+11 -1
View File
@@ -48,6 +48,11 @@ def build_planning_live_router(service):
except (ValueError, RuntimeError) as exc: except (ValueError, RuntimeError) as exc:
raise HTTPException(409, str(exc)) from 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") @router.get("/active")
async def active(request: Request): async def active(request: Request):
accepts_gzip = "gzip" in request.headers.get("accept-encoding", "") 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 # Returning its dict sends it through FastAPI's recursive encoder
# and gzip on the event loop, delaying unrelated control requests. # and gzip on the event loop, delaying unrelated control requests.
# Keep the exact JSON contract, but finish both operations here. # 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: if accepts_gzip and len(response.body) >= 1024:
return Response( return Response(
gzip.compress(response.body, compresslevel=5, mtime=0), gzip.compress(response.body, compresslevel=5, mtime=0),
@@ -109,6 +115,7 @@ def build_planning_live_router(service):
grid: bool = True, grid: bool = True,
point_size: float = Query(1.8, ge=0.5, le=12), point_size: float = Query(1.8, ge=0.5, le=12),
ceiling_m: float | None = Query(default=None, allow_inf_nan=False), ceiling_m: float | None = Query(default=None, allow_inf_nan=False),
floor_m: float | None = Query(default=None, allow_inf_nan=False),
): ):
options = dict( options = dict(
mode=mode, mode=mode,
@@ -118,6 +125,7 @@ def build_planning_live_router(service):
grid=grid, grid=grid,
point_size=point_size, point_size=point_size,
ceiling_m=ceiling_m, ceiling_m=ceiling_m,
floor_m=floor_m,
) )
return Response( return Response(
await call(service.scene, str(run_id), base, options), await call(service.scene, str(run_id), base, options),
@@ -138,6 +146,7 @@ def build_planning_live_router(service):
grid: bool = True, grid: bool = True,
point_size: float = Query(1.8, ge=0.5, le=12), point_size: float = Query(1.8, ge=0.5, le=12),
ceiling_m: float | None = Query(default=None, allow_inf_nan=False), ceiling_m: float | None = Query(default=None, allow_inf_nan=False),
floor_m: float | None = Query(default=None, allow_inf_nan=False),
): ):
options = dict( options = dict(
mode=mode, mode=mode,
@@ -148,6 +157,7 @@ def build_planning_live_router(service):
grid=grid, grid=grid,
point_size=point_size, point_size=point_size,
ceiling_m=ceiling_m, ceiling_m=ceiling_m,
floor_m=floor_m,
) )
payload, next_cursor, info = await call( payload, next_cursor, info = await call(
service.scene_update, str(run_id), cursor, base, options service.scene_update, str(run_id), cursor, base, options
+2
View File
@@ -16,6 +16,7 @@ class OverviewSpatialRequest(BaseModel):
model_config = ConfigDict(extra="forbid") model_config = ConfigDict(extra="forbid")
generation: str = Field(pattern="^[a-f0-9]{64}$") generation: str = Field(pattern="^[a-f0-9]{64}$")
ceiling_m: float | None = Field(default=None, allow_inf_nan=False) 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 mode: Literal["3d", "top"] | None = None
comparison_generation: str | None = Field(default=None, pattern="^[a-f0-9]{64}$") comparison_generation: str | None = Field(default=None, pattern="^[a-f0-9]{64}$")
representation: Literal["original", "corrected"] = "original" representation: Literal["original", "corrected"] = "original"
@@ -84,6 +85,7 @@ def build_session_overview_router(service: SessionOverviewService) -> APIRouter:
request.aspect, request.aspect,
comparison, comparison,
request.representation, request.representation,
request.floor_m,
) )
headers = {"Cache-Control": "no-store", "X-Overview-Visible-Points": str(visible)} headers = {"Cache-Control": "no-store", "X-Overview-Visible-Points": str(visible)}
if eye is not None: if eye is not None:
+31
View File
@@ -0,0 +1,31 @@
import numpy as np
import pytest
from k1link.height_slice import height_mask
from k1link.missions.live_scene import clip_reference, clip_query
def test_both_sides_are_inclusive_reversible_and_do_not_mutate_source():
points = np.array([[1., 0, -2], [2., 0, 0], [3., 0, 2], [4., 0, 6]])
original = points.copy()
np.testing.assert_equal(clip_reference(points, 2, 0), points[1:3])
np.testing.assert_equal(clip_reference(points, None, 2), points[2:])
np.testing.assert_equal(clip_reference(points, 0), points[:2])
np.testing.assert_equal(clip_reference(points, None), original)
np.testing.assert_equal(points, original)
def test_query_slices_in_calibrated_world_height_without_changing_local_coordinates():
points = np.array([[0., 0, -5], [0., 0, -3], [0., 0, 1]])
matrix = np.eye(4); matrix[2, 3] = 5
np.testing.assert_equal(clip_query(points, matrix, 3, 1), points[1:2])
np.testing.assert_equal(clip_query(points, matrix, None), points)
def test_invalid_bounds_rejected_and_empty_band_and_cloud_are_supported():
points = np.array([[0., 0, 0], [0., 0, 2], [0., 0, np.nan]])
np.testing.assert_equal(height_mask(points, 2, 2), [False, True, False])
assert not height_mask(points, 3, 4).any()
assert len(height_mask(np.empty((0, 3)), 0, 3)) == 0
for low, high in [(4, 3), (float('inf'), None), (None, float('nan'))]:
with pytest.raises(ValueError): height_mask(points, low, high)
+9 -10
View File
@@ -1,4 +1,5 @@
"""Periodic planning reports must not serialize/compress on the ASGI loop.""" """Periodic planning reports must not serialize/compress on the ASGI loop."""
import json
import threading import threading
from types import SimpleNamespace from types import SimpleNamespace
@@ -14,22 +15,19 @@ from k1link.web.response_compression import ResponseCompressionMiddleware
def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding): def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding):
document = {"state": "completed", "evidence": [{"label": "Проверка", "x": 1.25}] * 50} document = {"state": "completed", "evidence": [{"label": "Проверка", "x": 1.25}] * 50}
calls = [] calls = []
original_json = planning_live_api.JSONResponse
original_compress = planning_live_api.gzip.compress original_compress = planning_live_api.gzip.compress
class RecordedJSON(original_json): def encoded():
def render(self, content): calls.append(("json", threading.get_ident()))
calls.append(("json", threading.get_ident())) return json.dumps(document).encode()
return super().render(content)
def compress(*args, **kwargs): def compress(*args, **kwargs):
calls.append(("gzip", threading.get_ident())) calls.append(("gzip", threading.get_ident()))
return original_compress(*args, **kwargs) return original_compress(*args, **kwargs)
monkeypatch.setattr(planning_live_api, "JSONResponse", RecordedJSON)
monkeypatch.setattr(planning_live_api.gzip, "compress", compress) monkeypatch.setattr(planning_live_api.gzip, "compress", compress)
app = FastAPI() app = FastAPI()
app.include_router(planning_live_api.build_planning_live_router(SimpleNamespace(get=lambda: document))) app.include_router(planning_live_api.build_planning_live_router(SimpleNamespace(get_json=encoded)))
app.add_middleware(ResponseCompressionMiddleware) app.add_middleware(ResponseCompressionMiddleware)
@app.get("/loop-thread") @app.get("/loop-thread")
@@ -38,7 +36,8 @@ def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding)
with TestClient(app) as client: with TestClient(app) as client:
loop_id = client.get("/loop-thread").json() loop_id = client.get("/loop-thread").json()
result = client.get("/api/v1/mission-planner/live-tests/active", headers={"Accept-Encoding": encoding}) result = client.get("/api/v1/mission-planner/live-tests/active",
headers={"Accept-Encoding": encoding})
assert result.status_code == 200 assert result.status_code == 200
assert result.json() == document # Includes HTTP decompression; no double gzip. assert result.json() == document # Includes HTTP decompression; no double gzip.
assert result.headers["cache-control"] == "no-store" assert result.headers["cache-control"] == "no-store"
@@ -53,7 +52,7 @@ def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding)
def test_active_report_retains_empty_and_failure_contract(): def test_active_report_retains_empty_and_failure_contract():
service = SimpleNamespace(get=lambda: None) service = SimpleNamespace(get_json=lambda: b"null")
app = FastAPI() app = FastAPI()
app.include_router(planning_live_api.build_planning_live_router(service)) app.include_router(planning_live_api.build_planning_live_router(service))
with TestClient(app) as client: with TestClient(app) as client:
@@ -63,7 +62,7 @@ def test_active_report_retains_empty_and_failure_contract():
def fail(): def fail():
raise RuntimeError("synthetic unavailable report") raise RuntimeError("synthetic unavailable report")
service.get = fail service.get_json = fail
result = client.get("/api/v1/mission-planner/live-tests/active") result = client.get("/api/v1/mission-planner/live-tests/active")
assert result.status_code == 409 assert result.status_code == 409
assert result.json() == {"detail": "synthetic unavailable report"} assert result.json() == {"detail": "synthetic unavailable report"}
+4 -3
View File
@@ -122,8 +122,9 @@ def test_delta_sends_only_changed_chunks_pose_and_transform(monkeypatch):
) )
np.testing.assert_equal(dict((n, v) for n, v, _ in logs)["world/query/live"], [[1, 1, 0]]) np.testing.assert_equal(dict((n, v) for n, v, _ in logs)["world/query/live"], [[1, 1, 0]])
logs.clear() logs.clear()
render(options={"ceiling_m": -0.1}) for options in ({"ceiling_m": -0.1}, {"floor_m": 1.1}, {"floor_m": 1.1, "ceiling_m": 3}):
assert len(dict((n, v) for n, v, _ in logs)["world/query/live"]) == 0 render(options=options)
assert len(dict((n, v) for n, v, _ in logs)["world/query/live"]) == 0
logs.clear() logs.clear()
assert render(cursor)[0] == b"" assert render(cursor)[0] == b""
assert logs == [] assert logs == []
@@ -165,7 +166,7 @@ def test_presentation_changes_and_geometry_repairs_never_reset_camera(monkeypatc
assert render().startswith(b"RRF2") assert render().startswith(b"RRF2")
assert len(views) == 1 assert len(views) == 1
for options in ({"ceiling_m": 3}, {"reference": False}, {"query": False}, for options in ({"ceiling_m": 3}, {"floor_m": 0}, {"floor_m": 0, "ceiling_m": 3}, {"reference": False}, {"query": False},
{"trajectory": False}, {"point_size": 4}, {"grid": False}, {}): {"trajectory": False}, {"point_size": 4}, {"grid": False}, {}):
assert render(options).startswith(b"RRF2") assert render(options).startswith(b"RRF2")
assert len(views) == 1 assert len(views) == 1
+81
View File
@@ -0,0 +1,81 @@
"""Legacy full reports keep exact content without repeated evidence traversal."""
import json
import pytest
from test_planning_live import fixture_service
from test_planning_status import run_document
from k1link.missions.live_report_json import ReportJSONCache
class CountedEvidence(list):
traversals = 0
def __iter__(self):
self.traversals += 1
return super().__iter__()
def test_cached_evidence_is_not_traversed_and_dynamic_values_stay_fresh():
evidence = CountedEvidence([{"label": "Проверка", "values": [1, 2.5, None]}])
report = {"state": "completed", "evidence": evidence, "stale": False}
cache = ReportJSONCache()
first = json.loads(cache.encode(report, 1, {"stale": False, "age": 1}, cacheable=True))
second = json.loads(cache.encode(report, 1, {"stale": True, "age": 10}, cacheable=True))
assert evidence.traversals == 1
assert first == report | {"stale": False, "age": 1}
assert second == report | {"stale": True, "age": 10}
# A revised terminal report must never reuse older evidence.
evidence.append({"new": True})
assert json.loads(cache.encode(report, 2, {}, cacheable=True)) == report
assert evidence.traversals == 2
replacement = {"state": "completed", "evidence": [3]}
assert json.loads(cache.encode(replacement, 2, {}, cacheable=True)) == replacement
def test_active_reports_and_oversized_reports_are_not_retained():
evidence = CountedEvidence([1])
report = {"evidence": evidence}
cache = ReportJSONCache(max_bytes=16)
for n in range(2):
evidence.append(n)
assert json.loads(cache.encode(report, 1, {}, cacheable=False)) == report
assert evidence.traversals == 2
for _ in range(2):
assert json.loads(cache.encode(report, 1, {}, cacheable=True)) == report
assert evidence.traversals == 4
assert cache._prefix is None
@pytest.mark.parametrize("report,overlay", [({}, {}), ({"x": 1}, {}),
({}, {"x": 1}), ({"x": 1}, {"x": 2})])
def test_json_splice_is_single_object_without_duplicate_keys(report, overlay):
raw = ReportJSONCache().encode(report, 0, overlay, cacheable=True)
pairs = json.loads(raw, object_pairs_hook=list)
assert len(pairs) == len(dict(pairs))
assert dict(pairs) == report | overlay
def test_service_cached_json_matches_full_contract_and_invalidates(tmp_path, monkeypatch):
service, _, _, draft = fixture_service(tmp_path, monkeypatch)
assert service.get_json() == b"null"
service.run = run_document(draft) | {"state": "completed", "display": {"saved": [1]}}
service.run["calculation_history"] = CountedEvidence([{"kept": [1, 2]}])
clock = [10_000_000_000]
monkeypatch.setattr("k1link.missions.live_tests.time.monotonic_ns", lambda: clock[0])
monkeypatch.setattr(service, "persist", lambda: None)
service.last_frame_ns = service.last_result_ns = clock[0] - 1_000_000_000
first = json.loads(service.get_json())
assert first == service.get()
clock[0] += 10_000_000_000
second = json.loads(service.get_json())
assert second == service.get()
assert second["stale"] and second["frame_age_s"] == 11
assert first["frame_age_s"] == 1 and not first["stale"]
service.get()["display"]["saved"].append(2)
assert service.run["display"] == {"saved": [1]}
service.update(message="Revised terminal report")
assert json.loads(service.get_json()) == service.get()
assert json.loads(service.get_json())["message"] == "Revised terminal report"
service.run = None
assert service.get_json() == b"null" and service._report_json._prefix is None
+74
View File
@@ -0,0 +1,74 @@
"""Status polls stay independent of retained, potentially huge report evidence."""
import copy
import json
import time
from fastapi import FastAPI
from fastapi.testclient import TestClient
from test_planning_live import fixture_service
from k1link.web.planning_live_api import build_planning_live_router
class UnvisitedEvidence:
def __deepcopy__(self, memo):
raise AssertionError("status traversed full calculation evidence")
def run_document(draft):
return {"id": "1", "schema_version": "missioncore.planning-live-test/v1",
"profile": "planning", "plugin_id": "test-plugin", "draft": draft,
"state": "waiting", "query_session_id": None, "distance_m": 0,
"message": "Ожидаем запись", "result": None, "vehicle_control": False}
def test_status_copies_only_presentation_fields_and_tracks_transitions(tmp_path, monkeypatch):
service, source, lock, draft = fixture_service(tmp_path, monkeypatch)
assert service.get_status() is None
service.run = run_document(draft)
service.run["calculation_history"] = UnvisitedEvidence()
service.run["draft"]["route"]["points"] = UnvisitedEvidence()
service.run["result"] = {"status": "candidate", "overlap": .9, "inlier_rmse_m": .1,
"reasons": [], "matched_query_indices": UnvisitedEvidence(),
"initialization": UnvisitedEvidence()}
first = service.get_status()
assert first["schema_version"] == "missioncore.planning-live-status/v1"
assert len(json.dumps(first)) < 2500
assert first["query_session_id"] is None and first["state"] == "waiting"
assert first["draft"]["route"]["length_m"] == 20
assert "points" not in first["draft"]["route"]
assert "matched_query_indices" not in first["result"]
first["result"]["reasons"].append("only caller's copy")
first["draft"]["zone"]["label"] = "only caller's copy"
assert service.run["result"]["reasons"] == []
assert "label" not in service.run["draft"]["zone"]
service.run.update(state="running", query_session_id="B", query_generation=1,
planning_phase="collecting", tracking_state="acquiring")
service.last_frame_ns = time.monotonic_ns()
second = service.get_status()
assert second["state"] == "running" and second["query_session_id"] == "B"
assert second["planning_phase"] == "collecting" and not second["stale"]
assert second["frame_age_s"] >= 0
service.run.update(state="completed", planning_phase="ended")
assert service.get_status()["state"] == "completed"
assert not lock.locked() and source.owner is None
def test_status_api_does_not_read_report_and_report_remains_complete(tmp_path, monkeypatch):
service, _, _, draft = fixture_service(tmp_path, monkeypatch)
service.run = run_document(draft)
service.run["calculation_history"] = [{"synthetic": list(range(10))}]
original = copy.deepcopy(service.run)
app = FastAPI()
app.include_router(build_planning_live_router(service))
with TestClient(app) as client:
status = client.get("/api/v1/mission-planner/live-tests/status")
report = client.get("/api/v1/mission-planner/live-tests/active")
assert status.status_code == report.status_code == 200
assert status.headers["cache-control"] == "no-store"
assert "calculation_history" not in status.json()
assert report.json()["calculation_history"] == original["calculation_history"]
assert report.json()["draft"]["route"]["points"] == draft["route"]["points"]
assert service.run == original
service.run = None
assert client.get("/api/v1/mission-planner/live-tests/status").json() is None
+3 -2
View File
@@ -90,8 +90,8 @@ def test_height_slice_is_reversible_and_only_replaces_display_points(tmp_path):
recording.flush(); recording.disconnect() recording.flush(); recording.disconnect()
digest = hashlib.sha256(source.read_bytes()).hexdigest() digest = hashlib.sha256(source.read_bytes()).hexdigest()
assert spatial_metadata(source) == {'height_min_m': 0, 'height_max_m': 8, 'sample_points': 3} assert spatial_metadata(source) == {'height_min_m': 0, 'height_max_m': 8, 'sample_points': 3}
for ceiling, expected in [(3, 2), (-1, 0), (None, 3)]: for floor, ceiling, expected in [(None, 3, 2), (None, -1, 0), (2, None, 2), (2, 4, 1), (3, 3, 1), (None, None, 3)]:
data, count, eye = render_spatial_update(source, ceiling, 'top') data, count, eye = render_spatial_update(source, ceiling, 'top', floor_m=floor)
assert count == expected and eye['eyeUp'] == [0, 1, 0] assert count == expected and eye['eyeUp'] == [0, 1, 0]
assert eye['position'][2] > eye['lookTarget'][2] assert eye['position'][2] > eye['lookTarget'][2]
out = tmp_path / f'view-{expected}.rrd'; out.write_bytes(data) out = tmp_path / f'view-{expected}.rrd'; out.write_bytes(data)
@@ -99,6 +99,7 @@ def test_height_slice_is_reversible_and_only_replaces_display_points(tmp_path):
points = cloud.to_record_batch().column('Points3D:positions')[0].values.values.to_numpy().reshape(-1, 3) points = cloud.to_record_batch().column('Points3D:positions')[0].values.values.to_numpy().reshape(-1, 3)
assert len(points) == expected assert len(points) == expected
assert ceiling is None or np.all(points[:, 2] <= ceiling) assert ceiling is None or np.all(points[:, 2] <= ceiling)
assert floor is None or np.all(points[:, 2] >= floor)
assert RrdReader(out).recordings()[0].recording_id == RrdReader(source).recordings()[0].recording_id assert RrdReader(out).recordings()[0].recording_id == RrdReader(source).recordings()[0].recording_id
assert hashlib.sha256(source.read_bytes()).hexdigest() == digest assert hashlib.sha256(source.read_bytes()).hexdigest() == digest