fix(simulation): isolate semantics and correct clipping and orthographic LOD
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
import type {SceneView} from "../../core/simulation/simulationLayout";
|
||||
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
|
||||
import { sceneClipBounds } from "../../core/simulation/sceneClip";
|
||||
import { heightSlice } from "../../core/heightSlice";
|
||||
import { sceneClipBounds, sceneClipRange } from "../../core/simulation/sceneClip";
|
||||
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
|
||||
import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
|
||||
import { EditorCollisionLayer } from "./EditorCollisionLayer";
|
||||
import { waypointHit } from "../../core/simulation/waypointHit";
|
||||
import { PlannerMarkers } from "./PlannerMarkers";
|
||||
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
|
||||
import { QUALITY_PROFILES, orthographicLodFov } from "../../core/simulation/gaussianQuality";
|
||||
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
import { Application, Asset, BoundingBox, Color, Entity, FILLMODE_NONE, Mat4, Quat, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
|
||||
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
|
||||
@@ -37,6 +38,7 @@ export class AiEditorRuntime {
|
||||
private semanticProject: (()=>void)|null = null;
|
||||
private visualBounds:number[][]=[];
|
||||
private urbanVisible=false;
|
||||
private semanticMode=false;
|
||||
private experienceLayer: EditorUrbanMapLayer | null = null;
|
||||
private experiencePoints: number[][] = [];
|
||||
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
|
||||
@@ -130,11 +132,14 @@ export class AiEditorRuntime {
|
||||
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
|
||||
uniform float editorClip;
|
||||
uniform float editorFloor;
|
||||
uniform float editorClipEnabled;
|
||||
uniform float editorFloorEnabled;
|
||||
void modifySplatCenter(inout vec3 center) {}
|
||||
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
|
||||
void modifySplatColor(vec3 center, inout vec4 color) {
|
||||
// Unified work-buffer modifiers receive the calibrated world center.
|
||||
if (center.y > editorClip || center.y < editorFloor) color.a = 0.0;
|
||||
if ((editorClipEnabled > 0.5 && center.y > editorClip) ||
|
||||
(editorFloorEnabled > 0.5 && center.y < editorFloor)) color.a = 0.0;
|
||||
}` });
|
||||
this.setPreferences(this.preferences);
|
||||
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
|
||||
@@ -151,10 +156,10 @@ export class AiEditorRuntime {
|
||||
setUrbanMap(document: UrbanMap) {
|
||||
this.urbanBounds=urbanExtent(document);
|
||||
this.urbanLayer?.dispose();
|
||||
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.urbanVisible);this.dirty=true;
|
||||
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.semanticMode&&this.urbanVisible);this.dirty=true;
|
||||
}
|
||||
snapshotView():SceneView{return {...this.controls.snapshot(),clip:[Number.isFinite(this.clipFloor)?this.clipFloor:null,Number.isFinite(this.clip)?this.clip:null]};}
|
||||
restoreView(view:SceneView){this.setClip(view.clip[1]??Infinity,view.clip[0]??-Infinity);this.controls.restore(view);this.syncCamera();this.dirty=true;}
|
||||
restoreView(view:SceneView){const [floor,ceiling]=sceneClipRange(view.clip,this.height);this.setClip(ceiling,floor);this.controls.restore(view);this.syncCamera();this.dirty=true;}
|
||||
watchCamera(callback:((q:[number,number,number,number])=>void)|null) {this.cameraProject=callback;this.dirty=true;}
|
||||
setProjection(mode:EditorProjection){this.surfacePicker.invalidate();this.controls.setProjection(mode);this.syncCamera();this.dirty=true;}
|
||||
view(direction:number[]){this.surfacePicker.invalidate();this.controls.view(direction);this.syncCamera();this.dirty=true;}
|
||||
@@ -202,7 +207,8 @@ export class AiEditorRuntime {
|
||||
return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null;
|
||||
}
|
||||
setUrbanClasses(selected:readonly UrbanClassId[]) {this.urbanLayer?.setClasses(selected);this.dirty=true;}
|
||||
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(visible);this.dirty=true; }
|
||||
setSemanticMode(active: boolean) { this.semanticMode=active;this.urbanLayer?.setVisible(active&&this.urbanVisible);this.dirty=true; }
|
||||
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(this.semanticMode&&visible);this.dirty=true; }
|
||||
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
|
||||
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
|
||||
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
|
||||
@@ -229,13 +235,17 @@ export class AiEditorRuntime {
|
||||
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
|
||||
}
|
||||
setClip(height: number, floor = -Infinity) {
|
||||
const slice=heightSlice(sceneClipRange([floor,height],this.height),this.height);
|
||||
height=slice.ceiling??Infinity;floor=slice.floor??-Infinity;
|
||||
this.surfacePicker.invalidate();this.controls.invalidateSurface();
|
||||
this.clip = height; this.clipFloor = floor;
|
||||
this.collisionLayer?.setClip(height,floor);
|
||||
this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor);
|
||||
if (this.scan.gsplat) {
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
|
||||
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : -1e9);
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 0);
|
||||
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : 0);
|
||||
this.scan.gsplat.setParameter("editorClipEnabled", Number.isFinite(height) ? 1 : 0);
|
||||
this.scan.gsplat.setParameter("editorFloorEnabled", Number.isFinite(floor) ? 1 : 0);
|
||||
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
|
||||
}
|
||||
this.dirty = true;
|
||||
@@ -248,7 +258,10 @@ export class AiEditorRuntime {
|
||||
private syncCamera() {
|
||||
const c=this.controls.camera;
|
||||
this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE;
|
||||
if(isOrthographic(c))this.camera.camera!.orthoHeight=c.top;
|
||||
if(isOrthographic(c)){
|
||||
this.camera.camera!.orthoHeight=screenSpan(c,1)/2;
|
||||
this.camera.camera!.fov=orthographicLodFov(screenSpan(c,1)/2,this.controls.focusDepth);
|
||||
}else this.camera.camera!.fov=c.fov;
|
||||
const { position:p, quaternion:q } = c;
|
||||
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
|
||||
import {PlannerCameraTools} from "./PlannerCameraTools";
|
||||
import { heightSlice } from "../../core/heightSlice";
|
||||
import { sceneClipRange, sceneClipLabel } from "../../core/simulation/sceneClip";
|
||||
import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
|
||||
import { PlannerLegend } from "./PlannerLegend";
|
||||
import { SemanticEditor } from "./SemanticEditor";
|
||||
import { PlannerExperience } from "./PlannerExperience";
|
||||
import { loadUrbanMap, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import { loadUrbanMap, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import type { PreparedRoute } from "../../core/simulation/routePreparation";
|
||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
|
||||
@@ -23,11 +23,11 @@ import { useSimulationFullscreen } from "./useSimulationFullscreen";
|
||||
|
||||
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
|
||||
export type LocationMode = "view" | "semantic" | "planning";
|
||||
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, busy=false, preparedRoute=null }: {
|
||||
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, onBack, busy=false, preparedRoute=null }: {
|
||||
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
|
||||
actionsHost: HTMLElement | null; headerActions: React.ReactNode;
|
||||
routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
|
||||
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void;
|
||||
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void; onBack:()=>void;
|
||||
}) {
|
||||
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
|
||||
const markerSvg=useRef<SVGSVGElement>(null);
|
||||
@@ -46,10 +46,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers});
|
||||
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
|
||||
const semantic=sceneMode==="semantic", planning=sceneMode==="planning";
|
||||
const urbanVisible=layout.infrastructure,setUrbanVisible=(infrastructure:boolean)=>updateLayout({infrastructure});
|
||||
const urbanClasses=layout.urbanLayers,setUrbanClasses=(urbanLayers:UrbanClassId[])=>updateLayout({urbanLayers});
|
||||
const [memoryVisible,setMemoryVisible]=useState(false);
|
||||
const [urbanError,setUrbanError]=useState<string|null>(null);
|
||||
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
||||
const [mode,setMode] = useState<"view" | "add">("view");
|
||||
const [clip,setClip] = useState<[number,number]|null>(null);
|
||||
@@ -62,7 +59,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
const sceneKey=cache.world.sha256!,remember=()=>{if(loaded&&runtime.current)writeSceneView(sceneKey,runtime.current.snapshotView());};
|
||||
const timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember);
|
||||
const abort=new AbortController();
|
||||
setUrbanMap(null);setUrbanError(null);
|
||||
setUrbanMap(null);
|
||||
setReady(false); setError(null); setClip(null);
|
||||
let view: AiEditorRuntime;
|
||||
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
|
||||
@@ -71,12 +68,12 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
|
||||
void view.load().then(() => { if (active) {
|
||||
const remembered=readSceneView(sceneKey),settings=getSimulationLayout();
|
||||
if(remembered){view.restoreView(remembered);setClip([remembered.clip[0]??view.height[0],remembered.clip[1]??view.height[1]]);}
|
||||
if(remembered){view.restoreView(remembered);setClip(sceneClipRange(view.snapshotView().clip,view.height));}
|
||||
view.setProjection(settings.projection);view.setSceneLayers(settings.sceneLayers);
|
||||
loaded=true;setReady(true);
|
||||
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{
|
||||
if(active && map){view.setUrbanMap(map);setUrbanMap(map);}
|
||||
}).catch((e:Error)=>{if(active)setUrbanError(e.message);});
|
||||
}).catch((e:Error)=>{if(active)setError(e.message);});
|
||||
} }).catch((e: Error) => { if (active) setError(e.message); });
|
||||
return () => { remember();clearInterval(timer);window.removeEventListener("pagehide",remember);active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
|
||||
}, [cache?.key,cache?.status,retry]);
|
||||
@@ -85,8 +82,8 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
|
||||
}, [points,cache,ready,sequence,planning]);
|
||||
useEffect(()=>{
|
||||
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);}
|
||||
},[semantic,urbanMap,urbanVisible,urbanClasses]);
|
||||
runtime.current?.setSemanticMode(semantic);
|
||||
},[semantic,ready]);
|
||||
useEffect(()=>{
|
||||
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
|
||||
|
||||
@@ -95,8 +92,6 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
setMode("view");press.current=null;runtime.current?.setAddMode(false);
|
||||
if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}
|
||||
},[sceneMode,ready]);
|
||||
// SemanticEditor owns both the edited map and its layer mask in semantic mode.
|
||||
useEffect(()=>{if(!semantic)runtime.current?.setUrbanClasses(urbanClasses);},[semantic,urbanClasses,urbanMap,ready]);
|
||||
useEffect(()=>{if(ready)try{runtime.current?.setSceneLayers(sceneLayers);}catch(e){setError((e as Error).message);}},[sceneLayers,ready]);
|
||||
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
|
||||
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
|
||||
@@ -123,12 +118,20 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
|
||||
const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"};
|
||||
const infrastructure=semantic?<InfrastructureAnalysis worldId={world.world_id} worldSha={world.sha256!} busy={busy} hasMap={!!urbanMap}
|
||||
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setUrbanError(null);}}/>:null;
|
||||
const header=<>{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
|
||||
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
|
||||
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
|
||||
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
|
||||
</FieldFrame>{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}</>;
|
||||
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setError(null);}}/>:null;
|
||||
const header=<div className="ai-polygon__scene-actions">
|
||||
<div className="ai-polygon__context-actions">
|
||||
{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
|
||||
{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}
|
||||
</div>
|
||||
<div className="ai-polygon__mode-actions">
|
||||
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
|
||||
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
|
||||
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
|
||||
</FieldFrame>
|
||||
<IconButton label="Назад к локациям" disabled={busy} onClick={onBack}><Icon name="chevron-left"/></IconButton>
|
||||
</div>
|
||||
</div>;
|
||||
return <div className="ai-polygon__stage" ref={host}>
|
||||
{expanded ? <>
|
||||
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
|
||||
@@ -138,7 +141,6 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
|
||||
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge>
|
||||
{planning?<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>:null}
|
||||
{!semantic && urbanVisible && urbanMap ? <p>Инфраструктура · {urbanMap.coverage.kind === "objects-only" ? `${urbanMap.schema_version === "missioncore.urban-map/v3" ? "по скану" : urbanMap.analysis?.scope === "whole-scene" ? `обследовано ${urbanMap.analysis.tiles_total} участков · данные в ${urbanMap.analysis.tiles_mapped}` : "участок"} · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
|
||||
</div>
|
||||
<div className="ai-polygon__viewer">
|
||||
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
|
||||
@@ -158,13 +160,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
}}><Icon name="trash"/></IconButton>:null}
|
||||
</div>
|
||||
<SegmentedGroup label="Слои сцены" className="ai-local-editor__layers">
|
||||
{!semantic&&urbanMap?<SegmentedButton title={urbanError??"Карта дорожной инфраструктуры"}
|
||||
active={urbanVisible} aria-pressed={urbanVisible}
|
||||
onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}>Инфраструктура</SegmentedButton>:null}
|
||||
{(["gaussian","collision"] as const).map(key=><SegmentedButton key={key} active={sceneLayers[key]} aria-pressed={sceneLayers[key]}
|
||||
onClick={()=>{try {const next={...sceneLayers,[key]:!sceneLayers[key]};runtime.current?.setSceneLayers(next);setSceneLayers(next);setError(null);}
|
||||
catch(e){setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}>{key==="gaussian"?"Gaussian":"Коллизии"}</SegmentedButton>)}
|
||||
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
|
||||
{sceneMode!=="view" && runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
|
||||
runtime={runtime.current} viewport={viewport.current} onVisibilityChange={setMemoryVisible}/> : null}
|
||||
</SegmentedGroup>
|
||||
{urbanMap&&urbanMap.schema_version!=="missioncore.urban-map/v1"&&runtime.current&&viewport.current?<SemanticEditor key={world.sha256} worldId={world.world_id} worldSha={world.sha256!}
|
||||
@@ -223,13 +222,13 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
|
||||
</g>:null)}
|
||||
</svg></div>
|
||||
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
|
||||
selected={urbanClasses} onChange={setUrbanClasses} disabled={busy}/>:null}
|
||||
{planning?<PlannerLegend map={null} memory={memoryVisible}
|
||||
selected={[]} onChange={()=>undefined} disabled={busy}/>:null}
|
||||
{!ready && !error ? <LoadingRegion className="ai-local-editor__loading" loading label={message} />:null}
|
||||
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
|
||||
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={clip??runtime.current!.height}
|
||||
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
|
||||
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></div>
|
||||
formatValue={(v)=>sceneClipLabel(v,runtime.current!.height)} formatLimit={(v)=>sceneClipLabel(v,runtime.current!.height)}
|
||||
onChange={(v)=>{const view=runtime.current!;view.setClip(v[1],v[0]);setClip(sceneClipRange(view.snapshotView().clip,view.height));}}/></div>
|
||||
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
|
||||
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
|
||||
</div>
|
||||
|
||||
@@ -27,6 +27,7 @@ export class EditorCamera {
|
||||
private right = new Vector3();
|
||||
private delta = new Vector3();
|
||||
sceneCenter = new Vector3();
|
||||
get focusDepth(){return navigationDepth(this.camera,this.lastAnchor??this.sceneCenter);}
|
||||
pick: ((x:number,y:number)=>number[]|null)|null = null;
|
||||
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
|
||||
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
|
||||
|
||||
@@ -16,3 +16,10 @@ export const QUALITY_PROFILES: Record<GaussianQuality, {
|
||||
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 0, targetFps: 60 },
|
||||
};
|
||||
|
||||
|
||||
/** PlayCanvas 2.21 chooses streamed LOD from distance × tan(fov/2), even for
|
||||
* orthographic cameras. Supply the equivalent focal-plane FOV so an ortho zoom
|
||||
* refines the stream. The orthographic projection itself is unchanged. */
|
||||
export function orthographicLodFov(halfSpan: number, focusDepth: number): number {
|
||||
return 2 * Math.atan(halfSpan / focusDepth) * 180 / Math.PI;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import {heightSlice} from "../heightSlice";
|
||||
|
||||
/** Scene-space height range, independent of the reduced collision proxy. */
|
||||
export function sceneClipBounds(visual: readonly [number, number], collision: readonly [number, number] | null): [number, number] {
|
||||
const low = Math.floor(Math.min(visual[0], collision?.[0] ?? visual[0]));
|
||||
@@ -9,3 +11,14 @@ export function sceneClipBounds(visual: readonly [number, number], collision: re
|
||||
export function sceneClipValue(value: number, [low, high]: readonly [number, number]): number {
|
||||
return value >= high - Math.max(1, high - low) * 1e-9 ? Infinity : value;
|
||||
}
|
||||
|
||||
/** Project stored unbounded planes onto the finite slider without changing their meaning. */
|
||||
export function sceneClipRange(clip: readonly [number | null, number | null], [low, high]: readonly [number, number]): [number, number] {
|
||||
const lower=Math.max(low,Math.min(high,clip[0]??low));
|
||||
return [lower,Math.max(lower,Math.min(high,clip[1]??high))];
|
||||
}
|
||||
|
||||
export function sceneClipLabel(value: number, bounds: readonly [number, number]): string {
|
||||
const slice=heightSlice([value,value],bounds);
|
||||
return slice.floor===null ? "−∞" : slice.ceiling===null ? "+∞" : `${value.toFixed(1)} м`;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,10 @@
|
||||
.ai-polygon__planner-actions { justify-content: flex-end; }
|
||||
.ai-polygon__mode-field { width: 15rem; min-width: 0; }
|
||||
.ai-polygon__task-field { min-width: 0; }
|
||||
.ai-polygon__actions:has(> .ai-polygon__mode-field) { align-items: flex-start; }
|
||||
.ai-polygon__scene-actions { display: flex; align-items: flex-start; justify-content: flex-end; gap: .75rem; min-width: 0; }
|
||||
.ai-polygon__context-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: flex-start; gap: .75rem; min-width: 0; }
|
||||
.ai-polygon__context-actions:empty { display: none; }
|
||||
.ai-polygon__mode-actions { display: flex; align-items: flex-start; gap: .75rem; flex-shrink: 0; }
|
||||
.ai-polygon__location-actions > .ai-polygon__actions:empty,
|
||||
.ai-polygon__planner-actions > .ai-polygon__actions:empty { display: none; }
|
||||
.ai-polygon__robot-select { width: 12rem; flex: 0 0 12rem; }
|
||||
@@ -189,8 +192,21 @@
|
||||
.ai-polygon__run-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
/* Caption-bearing selectors align window actions to the control row. */
|
||||
.nodedc-application-panel__actions:has(.ai-polygon__mode-field) { align-items: flex-start; }
|
||||
/* Keep navigation in the same header cells when contextual controls appear.
|
||||
Flatten only this domain composition; canonical controls keep their styling. */
|
||||
.nodedc-application-panel:has(.ai-polygon__scene-actions) { container-type: inline-size; container-name: simulation-panel; }
|
||||
.nodedc-application-panel__head:has(.ai-polygon__scene-actions) { display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto; align-items: start; gap: .75rem; }
|
||||
.nodedc-application-panel__actions:has(.ai-polygon__scene-actions),
|
||||
.nodedc-application-panel__tools:has(.ai-polygon__scene-actions),
|
||||
.nodedc-application-panel__head .ai-polygon__scene-actions { display: contents; }
|
||||
.nodedc-application-panel__head:has(.ai-polygon__scene-actions) > .nodedc-application-panel__titles { grid-column: 1; grid-row: 1; }
|
||||
.nodedc-application-panel__head .ai-polygon__context-actions { grid-column: 2; grid-row: 1; }
|
||||
.nodedc-application-panel__head .ai-polygon__mode-actions { grid-column: 3; grid-row: 1; }
|
||||
.nodedc-application-panel__actions:has(.ai-polygon__scene-actions) > [data-action="close"] { grid-column: 4; grid-row: 1; }
|
||||
@container simulation-panel (max-width: 70rem) {
|
||||
.nodedc-application-panel__head:has(.ai-polygon__scene-actions) > .nodedc-application-panel__titles { grid-column: 1 / 3; }
|
||||
.nodedc-application-panel__head .ai-polygon__context-actions { grid-column: 1 / -1; grid-row: 2; justify-content: flex-start; }
|
||||
}
|
||||
|
||||
.ai-local-editor__marking-template { flex: 0 1 12rem; width: 12rem; max-width: 100%; }
|
||||
|
||||
|
||||
@@ -227,7 +227,7 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
|
||||
return <div className="ai-polygon">
|
||||
<header className="ai-polygon__head">
|
||||
<div className="ai-polygon__title">
|
||||
{selected ? <IconButton label="Назад к локациям" onClick={returnToLocations}>
|
||||
{selected && !planning ? <IconButton label="Назад к локациям" onClick={returnToLocations}>
|
||||
<Icon name="chevron-left" />
|
||||
</IconButton> : null}
|
||||
<h2>{selected?.name ?? "Доступные локации"}</h2>
|
||||
@@ -275,7 +275,7 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
|
||||
<LocalManualScene key={selected.world_id} world={selected} robot={robot} settings={roverSettings} actionsHost={headerToolsHost??actionsHost} headerActions={sceneActions} />
|
||||
</Suspense> : planning ? <Suspense fallback={<LoadingRegion loading label="Открываем редактор" />}>
|
||||
<AiLocalPlanner key={selected.world_id} world={selected} initialPoints={editorPlan?.points ?? EMPTY_POINTS}
|
||||
sceneMode={sceneMode} onSceneMode={setSceneMode}
|
||||
sceneMode={sceneMode} onSceneMode={setSceneMode} onBack={returnToLocations}
|
||||
busy={starting || saving || preparation.busy} preparedRoute={preparation.route} onDraft={setDraft}
|
||||
actionsHost={headerToolsHost??actionsHost} headerActions={taskSelector} routeActions={routeActions} routeActionsHost={actionsHost} />
|
||||
</Suspense> : <LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
|
||||
|
||||
@@ -6,6 +6,7 @@ import {PerspectiveCamera,Vector3} from 'three';
|
||||
import {Camera,GraphNode,ASPECT_MANUAL} from 'playcanvas';
|
||||
const url=s=>`data:text/javascript;base64,${Buffer.from(s).toString('base64')}`;
|
||||
function moduleUrl(p){return url(ts.transpileModule(readFileSync(p,'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText.replace(/from "([^"]+)"/g,(_,n)=>`from "${n.startsWith('.')?moduleUrl(new URL(n+'.ts',p)):import.meta.resolve(n)}"`));}
|
||||
const quality=moduleUrl(new URL('../src/core/simulation/gaussianQuality.ts',import.meta.url));
|
||||
const projection=moduleUrl(new URL('../src/core/simulation/editorProjection.ts',import.meta.url));
|
||||
const coordinates=moduleUrl(new URL('../src/core/simulation/aiEditorCoordinates.ts',import.meta.url));
|
||||
const drag=moduleUrl(new URL('../src/core/simulation/waypointDrag.ts',import.meta.url));
|
||||
@@ -16,14 +17,14 @@ const ast=ts.createSourceFile('runtime.ts',source,ts.ScriptTarget.Latest,true);
|
||||
const cls=ast.statements.find(s=>ts.isClassDeclaration(s));
|
||||
const names=new Set(['syncCamera','project','projectSemantic','moveSemantic','semanticGizmo','semanticSegmentParameter']);
|
||||
const methods=cls.members.filter(m=>names.has(m.name?.getText(ast))).map(m=>m.getText(ast)).join('\n');
|
||||
const actual=`import {Vec3,PROJECTION_ORTHOGRAPHIC,PROJECTION_PERSPECTIVE} from "${import.meta.resolve('playcanvas')}";import {isOrthographic,screenSpan} from "${projection}";import {toEditor,toMission} from "${coordinates}";import {dragWaypoint} from "${drag}";export class Runtime {${methods}}`;
|
||||
const actual=`import {orthographicLodFov} from "${quality}";import {Vec3,PROJECTION_ORTHOGRAPHIC,PROJECTION_PERSPECTIVE} from "${import.meta.resolve('playcanvas')}";import {isOrthographic,screenSpan} from "${projection}";import {toEditor,toMission} from "${coordinates}";import {dragWaypoint} from "${drag}";export class Runtime {${methods}}`;
|
||||
const {Runtime}=await import(url(ts.transpileModule(actual,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText));
|
||||
function fixture(mode){
|
||||
let c=new PerspectiveCamera(60,1.5,.05,3000);c.position.set(7,12,20);c.lookAt(0,0,0);c.updateMatrixWorld();
|
||||
c=switchProjection(c,mode,1.5,c.position.length());
|
||||
const pc=new Camera(),node=new GraphNode();pc.node=node;pc.aspectRatioMode=ASPECT_MANUAL;pc.aspectRatio=1.5;pc.fov=60;pc.nearClip=.05;pc.farClip=3000;
|
||||
node.camera={get projection(){return pc.projection;},set projection(v){pc.projection=v;},get orthoHeight(){return pc.orthoHeight;},set orthoHeight(v){pc.orthoHeight=v;},worldToScreen:p=>pc.worldToScreen(p,900,600),screenToWorld:(x,y,z)=>pc.screenToWorld(x,y,z,900,600)};
|
||||
const r=new Runtime();Object.assign(r,{camera:node,controls:{camera:c},canvas:{clientWidth:900,clientHeight:600},clip:Infinity,clipFloor:-Infinity,preferences:{pivot:{pixels:100}}});r.syncCamera();return {r,c,pc};
|
||||
const r=new Runtime();Object.assign(r,{camera:node,controls:{camera:c,focusDepth:c.position.length()},canvas:{clientWidth:900,clientHeight:600},clip:Infinity,clipFloor:-Infinity,preferences:{pivot:{pixels:100}}});r.syncCamera();return {r,c,pc};
|
||||
}
|
||||
for(const mode of ['orthographic','perspective']){
|
||||
test(`${mode}: render and overlay projection agree; axis/plane dragging lands under cursor`,()=>{
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
import {Camera,GraphNode,PROJECTION_ORTHOGRAPHIC,ASPECT_MANUAL,Mat4} from 'playcanvas';
|
||||
import {GSplatOctreeInstance} from '../node_modules/playcanvas/build/playcanvas/src/scene/gsplat-unified/gsplat-octree-instance.js';
|
||||
const result=await build({entryPoints:[new URL('../src/core/simulation/gaussianQuality.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {orthographicLodFov,QUALITY_PROFILES}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
// Exercise the installed engine LOD evaluator, rather than a copy of its distance formula.
|
||||
function lod(halfSpan,depth,compensated=true){
|
||||
const camera=new GraphNode();camera.setPosition(0,0,depth);
|
||||
camera.camera=new Camera();camera.camera.projection=PROJECTION_ORTHOGRAPHIC;
|
||||
camera.camera.aspectRatioMode=ASPECT_MANUAL;camera.camera.aspectRatio=1.5;camera.camera.orthoHeight=halfSpan;
|
||||
camera.camera.fov=compensated?orthographicLodFov(halfSpan,depth):60;
|
||||
const instance=Object.create(GSplatOctreeInstance.prototype);
|
||||
Object.assign(instance,{placement:{node:{getWorldTransform:()=>new Mat4()}},octree:{nodes:[{}],nodeBoundsMinMax:new Float32Array([-1,-1,0,1,1,0])},nodeInfos:[{}]});
|
||||
const p=QUALITY_PROFILES.maximum;
|
||||
instance.evaluateNodeLods(camera,6,p.lodBaseDistance,p.lodMultiplier,p.lodRangeMin,p.lodRangeMax,{lodBehindPenalty:1},1,false);
|
||||
return instance.nodeInfos[0].optimalLod;
|
||||
}
|
||||
test('orthographic zoom refines actual streamed LOD while distant camera stays put',()=>{
|
||||
assert.equal(lod(100,1000,false),5);
|
||||
assert.equal(lod(2,1000,false),5); // Reproduction: zoom was ignored.
|
||||
assert.ok(lod(100,1000)>lod(10,1000));
|
||||
assert.equal(lod(2,1000),0);
|
||||
});
|
||||
test('same orthographic screen scale selects the same detail at different camera depths',()=>{
|
||||
for(const span of [2,10,50,100])assert.equal(lod(span,50),lod(span,1000));
|
||||
});
|
||||
test('equivalent FOV preserves the perspective focal-plane scale',()=>{
|
||||
for(const depth of [1,25,1000]){
|
||||
assert.ok(Math.abs(orthographicLodFov(depth*Math.tan(Math.PI/6),depth)-60)<1e-10);
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/simulation/sceneClip.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {sceneClipBounds,sceneClipValue}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const {sceneClipBounds,sceneClipValue,sceneClipRange,sceneClipLabel}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
test('Gaussian clipping covers visual and collision extents with at least a 500 m ceiling',()=>{
|
||||
assert.deepEqual(sceneClipBounds([-51.4623,210.4],[-30,77.72065000000002]),[-52,500]);
|
||||
assert.deepEqual(sceneClipBounds([-60.3,912.7],null),[-61,913]);
|
||||
@@ -16,3 +16,14 @@ test('native rounded maximum disables clipping and returning to a finite height
|
||||
const bounds=sceneClipBounds([-51.4623,210.4],oldBounds);
|
||||
assert.deepEqual([40,500,40,500].map(v=>sceneClipValue(v,bounds)),[40,Infinity,40,Infinity]);
|
||||
});
|
||||
|
||||
test('stored open ends and out-of-range legacy values agree with the slider',()=>{
|
||||
const bounds=[-33,500];
|
||||
assert.deepEqual(sceneClipRange([null,null],bounds),bounds);
|
||||
assert.deepEqual(sceneClipRange([-100,900],bounds),bounds);
|
||||
assert.deepEqual(sceneClipRange([-20,null],bounds),[-20,500]);
|
||||
assert.deepEqual(sceneClipRange([null,120],bounds),[-33,120]);
|
||||
assert.equal(sceneClipLabel(-33,bounds),'−∞');
|
||||
assert.equal(sceneClipLabel(500,bounds),'+∞');
|
||||
assert.equal(sceneClipLabel(-20,bounds),'-20.0 м');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
let server,Runtime;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
||||
({AiEditorRuntime:Runtime}=await server.ssrLoadModule('/src/components/simulation/AiEditorRuntime.ts'));
|
||||
});
|
||||
after(async()=>{await server?.close();});
|
||||
|
||||
function runtime(){
|
||||
const value=Object.create(Runtime.prototype), parameters=new Map(), planes=[];
|
||||
Object.assign(value,{height:[-33,500],semanticMode:false,urbanVisible:false,
|
||||
surfacePicker:{invalidate(){}},controls:{invalidateSurface(){},restore(){},snapshot(){return {};}},
|
||||
syncCamera(){},scan:{gsplat:{setParameter:(k,v)=>parameters.set(k,v)}},
|
||||
urbanLayer:{setVisible(v){this.visible=v;},setClip:(...p)=>planes.push(p)},
|
||||
collisionLayer:{setClip:(...p)=>planes.push(p)},experienceLayer:{setClip:(...p)=>planes.push(p)}});
|
||||
return {value,parameters,planes};
|
||||
}
|
||||
test('semantic visibility cannot leak on mode exit or a late analysis callback',()=>{
|
||||
const {value}=runtime();
|
||||
value.showUrbanMap(true);assert.equal(value.urbanLayer.visible,false);
|
||||
value.setSemanticMode(true);assert.equal(value.urbanLayer.visible,true);
|
||||
value.setSemanticMode(false);assert.equal(value.urbanLayer.visible,false);
|
||||
value.showUrbanMap(true);assert.equal(value.urbanLayer.visible,false);
|
||||
value.setSemanticMode(true);assert.equal(value.urbanLayer.visible,true);
|
||||
value.showUrbanMap(false);assert.equal(value.urbanLayer.visible,false);
|
||||
value.setSemanticMode(false);value.setSemanticMode(true);
|
||||
assert.equal(value.urbanLayer.visible,false);
|
||||
});
|
||||
test('both full-range endpoints disable actual clipping and persist as open planes',()=>{
|
||||
const {value,parameters,planes}=runtime();
|
||||
value.setClip(200,-10);
|
||||
assert.equal(parameters.get('editorClipEnabled'),1);
|
||||
assert.equal(parameters.get('editorFloorEnabled'),1);
|
||||
assert.deepEqual(value.snapshotView().clip,[-10,200]);
|
||||
value.setClip(500,-33);
|
||||
assert.equal(parameters.get('editorClipEnabled'),0);
|
||||
assert.equal(parameters.get('editorFloorEnabled'),0);
|
||||
assert.deepEqual(value.snapshotView().clip,[null,null]);
|
||||
assert.deepEqual(planes.slice(-3),Array(3).fill([Infinity,-Infinity]));
|
||||
value.setClip(200,-33);
|
||||
assert.deepEqual(value.snapshotView().clip,[null,200]);
|
||||
value.setClip(500,-10);
|
||||
assert.deepEqual(value.snapshotView().clip,[-10,null]);
|
||||
});
|
||||
test('restoring old finite endpoint values cannot reopen invisible clipping planes',()=>{
|
||||
const {value,parameters}=runtime();
|
||||
value.restoreView({clip:[-33,500]});
|
||||
assert.deepEqual(value.snapshotView().clip,[null,null]);
|
||||
assert.equal(parameters.get('editorFloorEnabled'),0);
|
||||
value.restoreView({clip:[-200,900]});
|
||||
assert.deepEqual(value.snapshotView().clip,[null,null]);
|
||||
value.restoreView({clip:[-10,null]});
|
||||
assert.deepEqual(value.snapshotView().clip,[-10,null]);
|
||||
});
|
||||
@@ -494,7 +494,7 @@ test("vegetation realtime LAB uses one upstream Rerun clock and keeps archival r
|
||||
assert.match(rerunSource, /<RerunViewport/);
|
||||
assert.match(rerunSource, /ИСХ\. ТОЧКИ/);
|
||||
assert.match(rerunSource, /ЛОК\. SLAM/);
|
||||
assert.match(rerunSource, /resolveReplay\(resultId, value/);
|
||||
assert.match(rerunSource, /prepareLabReplay\(resultId, sessionId, resolveReplay/);
|
||||
assert.doesNotMatch(rerunSource, /canonical-overlay\.rrd/);
|
||||
assert.match(rerunSource, /unifiedPerception: splitView/);
|
||||
assert.match(rerunSource, /lockPerceptionCameraInteraction: false/);
|
||||
@@ -510,7 +510,7 @@ test("vegetation realtime LAB uses one upstream Rerun clock and keeps archival r
|
||||
assert.match(rerunSource, /<ToastStack items=\{toasts\}/);
|
||||
assert.match(rerunSource, /isRecordedPlaybackPresentationReady\(viewerStatus, playback\)/);
|
||||
assert.match(rerunSource, /data-presentation-state=\{presentationState\}/);
|
||||
assert.match(rerunSource, /<ActivityIndicator label="Загружаем синхронизированную запись"/);
|
||||
assert.match(rerunSource, /<LabReplayProgress progress=/);
|
||||
assert.match(rerunSource, /presentationReady && playback && playbackController/);
|
||||
assert.match(
|
||||
replayStyles,
|
||||
|
||||
Reference in New Issue
Block a user