Add vector infrastructure maps and persistent location experience

This commit is contained in:
DCCONSTRUCTIONS
2026-10-10 14:35:50 +03:00
parent e095a43f00
commit 55f64f195b
38 changed files with 2317 additions and 14 deletions
@@ -1,3 +1,5 @@
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
import { urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
import { EditorCollisionLayer } from "./EditorCollisionLayer";
import type { SimulationViewMode } from "./PlayCanvasRuntime";
import { waypointHit } from "../../core/simulation/waypointHit";
@@ -24,6 +26,11 @@ export class AiEditorRuntime {
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private terrain = new EditorTerrain();
private urbanLayer: EditorUrbanMapLayer | null = null;
private experienceLayer: EditorUrbanMapLayer | null = null;
private experiencePoints: number[][] = [];
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
private urbanMap: UrbanMap | null = null;
private collisionLayer: EditorCollisionLayer | null = null;
private resize: ResizeObserver;
private abort = new AbortController();
@@ -70,6 +77,7 @@ export class AiEditorRuntime {
const matrix = this.camera.getWorldTransform().data.join(",");
if (matrix !== this.previous || this.dirty) {
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
this.onExperienceProject(this.experiencePoints.map(p=>this.project(...toEditor(p) as [number,number,number])));
this.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
this.onProject(this.points.map((p) => {
const [x,y,z] = toEditor(p.position);
@@ -106,13 +114,28 @@ export class AiEditorRuntime {
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
this.setClip(Infinity); this.dirty = true;
}
setViewMode(mode: SimulationViewMode) {
if (mode !== "visual" && !this.collisionLayer) {
setExperience(document: UrbanMap, points: number[][], callback: (p: ScreenPoint[])=>void) {
this.experienceLayer?.dispose();this.experienceLayer=new EditorUrbanMapLayer(this.app,this.camera,document);
this.experiencePoints=points;this.onExperienceProject=callback;this.experienceLayer.setClip(this.clip);this.dirty=true;
}
showExperience(visible: boolean) {this.experienceLayer?.setVisible(visible);this.dirty=true;}
clearExperience() {this.experienceLayer?.dispose();this.experienceLayer=null;this.experiencePoints=[];this.onExperienceProject=()=>undefined;this.dirty=true;}
setUrbanMap(document: UrbanMap) {
this.urbanLayer?.dispose(); this.urbanMap=document;
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip);this.dirty=true;
}
showUrbanMap(visible: boolean) { this.urbanLayer?.setVisible(visible);this.dirty=true; }
focusUrbanMap() {
const points=this.urbanMap?.features.flatMap(f=>urbanPaths(f).flat()).map(toEditor)??[];
if(points.length)this.controls.top(points);this.syncCamera();this.dirty=true;
}
setViewMode(mode: SimulationViewMode|"map") {
if (mode !== "visual" && mode !== "map" && !this.collisionLayer) {
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
this.collisionLayer.setClip(this.clip);
}
this.scan.enabled = mode !== "collision";
this.collisionLayer?.setMode(mode);
this.scan.enabled = mode === "visual" || mode === "combined";
this.collisionLayer?.setMode(mode === "map" ? "visual" : mode);
this.dirty = true;
}
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
@@ -133,6 +156,7 @@ export class AiEditorRuntime {
setClip(height: number) {
this.clip = height;
this.collisionLayer?.setClip(height);
this.urbanLayer?.setClip(height);this.experienceLayer?.setClip(height);
if (this.scan.gsplat) {
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
@@ -189,6 +213,7 @@ export class AiEditorRuntime {
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
this.annotations.dispose();
this.collisionLayer?.dispose();
this.urbanLayer?.dispose();this.clearExperience();
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
}
}
@@ -1,3 +1,5 @@
import { PlannerExperience } from "./PlannerExperience";
import { loadUrbanMap, URBAN_COLORS, URBAN_LABELS, type UrbanMap } from "../../core/simulation/urbanMap";
import type { SimulationViewMode } from "./PlayCanvasRuntime";
import type { PreparedRoute } from "../../core/simulation/routePreparation";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
@@ -31,7 +33,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const {points,selected,sequence} = editing;
const press=useRef<{id:number;x:number;y:number}|null>(null);
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
const [layerMode,setLayerMode]=useState<SimulationViewMode>("visual");
const [layerMode,setLayerMode]=useState<SimulationViewMode|"map">("visual");
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
const [urbanVisible,setUrbanVisible]=useState(false);
const [urbanError,setUrbanError]=useState<string|null>(null);
const [viewMode,setViewMode]=useState<"3d"|"top">("3d");
const [markers, setMarkers] = useState<EditorMarker[]>([]);
const [mode,setMode] = useState<"view" | "add">("view");
@@ -42,14 +47,21 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
useEffect(() => {
if (cache?.status !== "ready" || !canvas.current) return;
let active = true;
const abort=new AbortController();
setUrbanMap(null);setUrbanVisible(false);setUrbanError(null);
setReady(false); setError(null); setClip(Infinity); setLayerMode("visual");
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
catch (e) { setError((e as Error).message); return; }
runtime.current = view;
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
void view.load().then(() => { if (active) setReady(true); }).catch((e: Error) => { if (active) setError(e.message); });
return () => { active=false; runtime.current=null; view.dispose(); callback.current(null); };
void view.load().then(() => { if (active) {
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); });
return () => { active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
}, [cache?.key,cache?.status,retry]);
useEffect(() => {
runtime.current?.setPoints(points);
@@ -86,7 +98,13 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p></div>
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>
{urbanVisible && urbanMap ? <p>Генплан · {urbanMap.coverage.kind === "objects-only" ? `участок · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
</div>
{urbanVisible?<span className="ai-inference-preview__legend" aria-label="Классы инфраструктуры">
{Object.keys(URBAN_LABELS).filter(id=>urbanMap?.features.some(f=>f.properties.class===id)).map(id=>
<span key={id}><i style={{background:`rgb(${URBAN_COLORS[id].join(',')})`}}/>{URBAN_LABELS[id]}</span>)}
</span>:null}
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
onKeyDown={(e)=>{
@@ -99,11 +117,15 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
}}><Icon name="trash"/></IconButton>:null}
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!} runtime={runtime.current} viewport={viewport.current}/> : null}
<SegmentedControl label="Слои сцены" value={layerMode}
items={[{value:"visual",label:"Gaussian"},{value:"collision",label:"Коллизии"},{value:"combined",label:"Вместе"}]}
onChange={v=>{try {runtime.current?.setViewMode(v);setLayerMode(v);setError(null);}
items={[{value:"visual",label:"Gaussian"},{value:"collision",label:"Коллизии"},{value:"combined",label:"Вместе"},...(urbanMap?[{value:"map" as const,label:"Генплан"}]:[])]}
onChange={v=>{try {runtime.current?.setViewMode(v);setLayerMode(v);if(v==="map"){setUrbanVisible(true);runtime.current?.showUrbanMap(true);runtime.current?.focusUrbanMap();setViewMode("top");}setError(null);}
catch (e) {setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}/>
{preparedRoute?<SegmentedControl label="Ракурс маршрута" value={viewMode}
<IconButton label={urbanError??(urbanMap?"Карта дорожной инфраструктуры":"Карта инфраструктуры ещё не подготовлена")}
disabled={!urbanMap || layerMode==="map"} aria-pressed={urbanVisible} onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}><Icon name="layers"/></IconButton>
{urbanVisible?<IconButton label="Показать участок карты" onClick={()=>{runtime.current?.focusUrbanMap();setViewMode("top");}}><Icon name="plan"/></IconButton>:null}
{preparedRoute||urbanMap?<SegmentedControl label="Ракурс" value={viewMode}
items={[{value:"3d",label:"3D"},{value:"top",label:"Вид сверху"}]}
onChange={v=>{setViewMode(v);if(v==="top")runtime.current?.top();else runtime.current?.home();}}/>:null}
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
@@ -0,0 +1,38 @@
import { Application, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import { URBAN_COLORS, urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
/** Read-only contours. This layer never enters terrain picking, collision or routing. */
export class EditorUrbanMapLayer {
private entity: Entity;
private mesh: Mesh;
private material: ShaderMaterial;
private layer = new Layer({ name: "Urban infrastructure observations" });
constructor(private app: Application, private camera: Entity, document: UrbanMap) {
app.scene.layers.insert(this.layer, app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1);
camera.camera!.layers = [...camera.camera!.layers, this.layer.id];
this.material = new ShaderMaterial({ uniqueName: "urban-map-contours", attributes: { vertex_position: SEMANTIC_POSITION, vertex_color: SEMANTIC_COLOR },
vertexGLSL: `attribute vec3 vertex_position; attribute vec4 vertex_color;
uniform mat4 matrix_model; uniform mat4 matrix_viewProjection;
varying vec4 mapColor; varying float mapHeight;
void main(void) { vec4 p=matrix_model*vec4(vertex_position,1.0); mapColor=vertex_color; mapHeight=p.y; gl_Position=matrix_viewProjection*p; }`,
fragmentGLSL: `precision highp float; varying vec4 mapColor; varying float mapHeight; uniform float mapClip;
void main(void) { if(mapHeight>mapClip) discard; gl_FragColor=mapColor; }` });
this.material.depthTest = false; this.material.depthWrite = false;
const positions: number[] = [], colors: number[] = [];
for (const feature of document.features) {
const color = URBAN_COLORS[feature.properties.class]; if (!color) continue;
for (const ring of urbanPaths(feature)) for (let i=1;i<ring.length;i++) {
positions.push(...toEditor(ring[i-1]), ...toEditor(ring[i]));
colors.push(...color,255,...color,255);
}
}
this.mesh = new Mesh(app.graphicsDevice); this.mesh.setPositions(positions); this.mesh.setColors32(colors); this.mesh.update(PRIMITIVE_LINES);
this.entity = new Entity("Urban infrastructure",app);
this.entity.addComponent("render", { meshInstances: [new MeshInstance(this.mesh,this.material)], layers: [this.layer.id] });
this.entity.enabled=false; app.root.addChild(this.entity); this.setClip(Infinity);
}
setVisible(visible: boolean) { this.entity.enabled=visible; }
setClip(height: number) { this.material.setParameter("mapClip",Number.isFinite(height)?height:1e9); }
dispose() { this.camera.camera!.layers=this.camera.camera!.layers.filter(id=>id!==this.layer.id); this.app.scene.layers.remove(this.layer); this.entity.destroy();this.mesh.destroy();this.material.destroy(); }
}
@@ -0,0 +1,38 @@
import { useEffect, useState } from "react";
import { Icon, IconButton } from "@nodedc/ui-react";
import { createPortal } from "react-dom";
import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import type { AiEditorRuntime } from "./AiEditorRuntime";
import { URBAN_COLORS } from "../../core/simulation/urbanMap";
export function PlannerExperience({worldId,worldSha,runtime,viewport}: {
worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;
}) {
const [memory,setMemory]=useState<SpatialExperience|null>(null),[visible,setVisible]=useState(false);
const [projected,setProjected]=useState<ScreenPoint[]>([]),[error,setError]=useState<string|null>(null);
useEffect(()=>{
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const refresh=async()=>{
try {const value=await loadExperience(worldId,worldSha,abort.signal);
if(abort.signal.aborted)return;setMemory(value);setError(null);
if(value)runtime.setExperience(experienceMap(value),value.attempts.map(a=>a.xyz),setProjected);
} catch(e) {if(!abort.signal.aborted)setError((e as Error).message);}
if(!abort.signal.aborted)timer=setTimeout(refresh,5000);
};
void refresh();return ()=>{abort.abort();clearTimeout(timer);runtime.clearExperience();};
},[worldId,worldSha,runtime]);
useEffect(()=>runtime.showExperience(visible),[runtime,visible,memory]);
return <>
<IconButton label={error??(memory?`Память локации · посещено ${memory.visits.length} участков · ${memory.attempts.length} попыток`:"В этой локации ещё нет сохранённого опыта")}
disabled={!memory} aria-pressed={visible} onClick={()=>setVisible(v=>!v)}><Icon name="database"/></IconButton>
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
</g>;
})}
</svg>,viewport):null}
</>;
}
@@ -0,0 +1,34 @@
import type { UrbanMap, UrbanMapFeature } from "./urbanMap";
export interface PlaceAttempt {
id:string;xyz:number[];origin:number[];reason:string;status:"unresolved"|"revisited-successfully";
first_seen:number;last_seen:number;count:number;run_id:string;observation_id:string;
}
export interface SpatialExperience {
schema_version:"missioncore.spatial-experience/v1";
source:{world_sha256:string;collider_sha256:string;robot_sha256:string};
visits:{id:string;xyz:number[];count:number;last_seen:number}[];
attempts:PlaceAttempt[];
}
const REASONS:Record<string,string>={"no-path":"Путь не найден","no-permitted-goal":"Не найдена разрешённая поверхность","footprint":"Недостаточно места для корпуса",
"observed-unsafe-support":"Ненадёжная опора","forbidden-surface-sweep":"Запрещённая поверхность",
"detected-object-sweep":"Препятствие на пути"};
export function attemptLabel(a:PlaceAttempt) {
return `${a.status==="revisited-successfully"?"Позже проехал":"Попытка проезда"} · ${REASONS[a.reason]??a.reason} · ${a.count} · ${new Date(a.last_seen*1000).toLocaleString("ru")}`;
}
/** Cell marks and attempted direction; no invented connections between visits. */
export function experienceMap(memory:SpatialExperience):UrbanMap {
const feature=(id:string,cls:string,points:number[][]):UrbanMapFeature=>({id,
properties:{class:cls,authority:"observation-only",route_permission:"unassigned"},geometry:{type:"LineString",coordinates:points}});
return {schema_version:"missioncore.urban-map/v2",source:memory.source,coverage:{cell_m:.5,accepted_cells:memory.visits.length},features:[
...memory.visits.map(v=>feature(v.id,"visited",[[v.xyz[0]-.12,v.xyz[1],v.xyz[2]],[v.xyz[0]+.12,v.xyz[1],v.xyz[2]]])),
...memory.attempts.map(a=>feature(a.id,a.status==="unresolved"?"attempt":"revisited",[a.origin,a.xyz])),
]};
}
export async function loadExperience(worldId:string,worldSha:string,signal:AbortSignal):Promise<SpatialExperience|null> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/spatial-experience`,{signal,cache:"no-store"});
if(response.status===404)return null;
if(!response.ok)throw new Error("Не удалось загрузить память локации.");
const data=await response.json() as SpatialExperience;
if(data.schema_version!=="missioncore.spatial-experience/v1"||data.source.world_sha256!==worldSha)throw new Error("Память относится к другой локации.");
return data;
}
@@ -0,0 +1,36 @@
export interface UrbanMapFeature {
id: string;
properties: { class: string; authority: "observation-only"; route_permission: "unassigned"; confidence?: number; review_status?: "unreviewed"|"accepted"|"rejected" };
geometry: { type: "Polygon"; coordinates: number[][][] } | { type: "LineString"; coordinates: number[][] };
}
export interface UrbanMap {
schema_version: "missioncore.urban-map/v1"|"missioncore.urban-map/v2";
source: { world_sha256: string; collider_sha256: string };
features: UrbanMapFeature[];
coverage: { accepted_cells: number; cell_m: number; kind?: "objects-only" };
}
export const URBAN_COLORS: Record<string, [number, number, number]> = {
visited: [60,220,200], attempt: [245,130,48], revisited: [245,245,245],
curb: [245,130,48], curb_cut: [255,150,80], sidewalk: [60,220,200], pedestrian_area: [60,220,200],
carriageway: [90,130,200], service_lane: [110,150,210], bike_lane: [150,110,220], parking: [140,140,150],
crosswalk_area: [255,225,35], crosswalk_marking: [255,225,35], road_marking: [245,245,245],
};
export const URBAN_LABELS: Record<string, string> = {
curb: "Бордюр", curb_cut: "Съезд", sidewalk: "Тротуар", pedestrian_area: "Пешеходная зона",
carriageway: "Проезжая часть", service_lane: "Служебный проезд", bike_lane: "Велополоса", parking: "Парковка",
crosswalk_area: "Переход", crosswalk_marking: "Зебра", road_marking: "Разметка",
};
export async function loadUrbanMap(worldId: string, worldSha: string, signal: AbortSignal): Promise<UrbanMap|null> {
const response = await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/urban-map`, { signal, cache: "no-store" });
if (response.status === 404) return null;
if (!response.ok) throw new Error("Не удалось загрузить карту инфраструктуры.");
const result = await response.json() as UrbanMap;
if (!["missioncore.urban-map/v1","missioncore.urban-map/v2"].includes(result.schema_version) || result.source.world_sha256 !== worldSha) {
throw new Error("Карта относится к другой версии сцены.");
}
return result;
}
export function urbanPaths(feature: UrbanMapFeature): number[][][] {
return feature.properties.review_status === "rejected" ? [] : feature.geometry.type === "Polygon" ? feature.geometry.coordinates : [feature.geometry.coordinates];
}
@@ -77,7 +77,7 @@
.ai-simulation__speed { position: absolute; left: .75rem; bottom: .75rem; pointer-events: none; font-size: var(--nodedc-font-size-sm); }
/* Equal visible padding on all three sides; owner requested twice the radius-centred inset. */
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: var(--ai-clip-inset); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
.ai-local-editor__tools { display: flex; align-items: center; gap: .5rem; }
.ai-local-editor__tools { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: .5rem; max-width: 100%; }
.ai-local-editor .ai-route__tools { left: 5.5rem; right: .75rem; }
/* The renderer has no perimeter; canonical controls retain their focus indicators. */
.ai-local-editor canvas { outline: none; }