feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
This commit is contained in:
@@ -1,17 +1,20 @@
|
||||
import type {SceneView} from "../../core/simulation/simulationLayout";
|
||||
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
|
||||
import { sceneClipBounds } from "../../core/simulation/sceneClip";
|
||||
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
|
||||
import { urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
|
||||
import { EditorCollisionLayer } from "./EditorCollisionLayer";
|
||||
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
||||
import { waypointHit } from "../../core/simulation/waypointHit";
|
||||
import { PlannerMarkers } from "./PlannerMarkers";
|
||||
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
|
||||
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
import { Application, Asset, Color, Entity, FILLMODE_NONE, Mat4, Quat, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
|
||||
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";
|
||||
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import { localScene } from "./localScene";
|
||||
import { EditorTerrain } from "./EditorTerrain";
|
||||
import { EditorCamera } from "./EditorCamera";
|
||||
import { EditorSurfacePicker } from "./EditorSurfacePicker";
|
||||
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
|
||||
|
||||
export interface EditorMarker { id: string; base: ScreenPoint; top: ScreenPoint; x: ScreenPoint; y: ScreenPoint; z: ScreenPoint }
|
||||
@@ -22,15 +25,21 @@ export class AiEditorRuntime {
|
||||
private scan: Entity;
|
||||
private asset: Asset | null = null;
|
||||
private controls: EditorCamera;
|
||||
private surfacePicker: EditorSurfacePicker;
|
||||
private collisionVisible = false;
|
||||
private annotations: PlannerMarkers;
|
||||
private preferences = DEFAULT_PLANNER_PREFERENCES;
|
||||
private selected: string|null = null;
|
||||
private terrain = new EditorTerrain();
|
||||
private urbanLayer: EditorUrbanMapLayer | null = null;
|
||||
private urbanBounds:number[][]=[];
|
||||
private cameraProject: ((q:[number,number,number,number])=>void)|null=null;
|
||||
private semanticProject: (()=>void)|null = null;
|
||||
private visualBounds:number[][]=[];
|
||||
private urbanVisible=false;
|
||||
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();
|
||||
@@ -40,6 +49,7 @@ export class AiEditorRuntime {
|
||||
private points: AiWaypoint[] = [];
|
||||
private route: number[][] = [];
|
||||
clip = Infinity;
|
||||
clipFloor = -Infinity;
|
||||
height: [number, number] = [0, 1];
|
||||
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
|
||||
private onProject: (markers: EditorMarker[]) => void,
|
||||
@@ -54,10 +64,19 @@ export class AiEditorRuntime {
|
||||
app.setCanvasFillMode(FILLMODE_NONE, 1, 1); app.setCanvasResolution(RESOLUTION_AUTO);
|
||||
this.camera.addComponent("camera", { nearClip: .05, farClip: 3000, fov: 60, clearColor: new Color(.025,.03,.04) });
|
||||
this.controls = new EditorCamera(canvas.parentElement!, canvas);
|
||||
this.surfacePicker = new EditorSurfacePicker(app, this.camera, canvas);
|
||||
app.root.addChild(this.camera);
|
||||
app.root.addChild(this.scan);
|
||||
this.annotations = new PlannerMarkers(app,this.camera,canvas);
|
||||
this.controls.pick = (x,y) => { const p=this.pick(x,y);return p?toEditor(p):null; };
|
||||
this.controls.pickSurface = async (x,y) => {
|
||||
this.syncCamera();
|
||||
if(this.scan.enabled && this.scan.gsplat) return this.surfacePicker.pick(x,y);
|
||||
if(!this.collisionVisible)return null;
|
||||
const from=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,.05);
|
||||
const to=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,2000);
|
||||
return this.terrain.pickSurface([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,false,this.clipFloor)?.toArray()??null;
|
||||
};
|
||||
const transform = new Mat4().set(localScene(cache).transforms.worldFromVisual);
|
||||
this.scan.setPosition(transform.getTranslation());
|
||||
this.scan.setRotation(new Quat().setFromMat4(transform));
|
||||
@@ -74,9 +93,10 @@ export class AiEditorRuntime {
|
||||
this.controls.update(dt); this.syncCamera();
|
||||
if (this.annotations.setRotationCenter(this.controls.rotationCenter)) app.renderNextFrame = true;
|
||||
if (this.annotations.update(dt)) app.renderNextFrame = true;
|
||||
const matrix = this.camera.getWorldTransform().data.join(",");
|
||||
const matrix = this.camera.getWorldTransform().data.join(",")+this.controls.camera.projectionMatrix.elements.join(",");
|
||||
if (matrix !== this.previous || this.dirty) {
|
||||
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
|
||||
this.semanticProject?.();this.cameraProject?.(this.controls.camera.quaternion.toArray());
|
||||
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) => {
|
||||
@@ -90,10 +110,9 @@ export class AiEditorRuntime {
|
||||
}
|
||||
async load() {
|
||||
const scene = localScene(this.cache);
|
||||
await this.terrain.load(scene.collision.meshUrl!, this.abort.signal, scene.transforms.worldFromCollision);
|
||||
if (scene.collision.available && scene.collision.meshUrl)
|
||||
await this.terrain.load(scene.collision.meshUrl, this.abort.signal, scene.transforms.worldFromCollision);
|
||||
if (this.disposed) return;
|
||||
this.height = [this.terrain.bounds.min.y, this.terrain.bounds.max.y];
|
||||
if (this.height[1] <= this.height[0]) this.height = [this.height[0]-.5,this.height[1]+.5];
|
||||
const asset = new Asset("Route editor", "gsplat", { url: scene.visual.streamedSogUrl! });
|
||||
this.asset = asset;
|
||||
await new Promise<void>((resolve,reject) => {
|
||||
@@ -102,44 +121,100 @@ export class AiEditorRuntime {
|
||||
});
|
||||
if (this.disposed) { asset.unload(); return; }
|
||||
this.scan.addComponent("gsplat", { asset, unified: true });
|
||||
const bounds = new BoundingBox();
|
||||
bounds.setFromTransformedAabb(this.scan.gsplat!.customAabb!, this.scan.getWorldTransform());
|
||||
const low=bounds.getMin(),high=bounds.getMax();
|
||||
this.visualBounds=[...Array(8)].map((_,i)=>[i&1?high.x:low.x,i&2?high.y:low.y,i&4?high.z:low.z]);
|
||||
const terrain=this.terrain.bounds;
|
||||
this.height = sceneClipBounds([low.y, high.y], terrain.isEmpty() ? null : [terrain.min.y, terrain.max.y]);
|
||||
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
|
||||
uniform float editorClip;
|
||||
uniform float editorFloor;
|
||||
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) color.a = 0.0;
|
||||
if (center.y > editorClip || center.y < editorFloor) color.a = 0.0;
|
||||
}` });
|
||||
this.setPreferences(this.preferences);
|
||||
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
|
||||
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
|
||||
else this.controls.sceneCenter = terrain.getCenter(this.controls.sceneCenter);
|
||||
if (!scene.collision.available) { this.controls.top(this.visualBounds); this.syncCamera(); }
|
||||
this.setClip(Infinity); this.dirty = true;
|
||||
}
|
||||
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;
|
||||
this.experiencePoints=points;this.onExperienceProject=callback;this.experienceLayer.setClip(this.clip,this.clipFloor);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;
|
||||
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;
|
||||
}
|
||||
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;
|
||||
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;}
|
||||
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;}
|
||||
watchSemantic(callback:(()=>void)|null) { this.semanticProject=callback;this.dirty=true; }
|
||||
projectSemantic(point:number[]): ScreenPoint {
|
||||
if(point[2]<this.clipFloor||point[2]>this.clip)return null;
|
||||
return this.project(...toEditor(point) as [number,number,number]);
|
||||
}
|
||||
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);
|
||||
semanticSegmentParameter(a:number[],b:number[],u:number) {
|
||||
if(isOrthographic(this.controls.camera))return u;
|
||||
const depth=(p:number[])=>new Vec3(...toEditor(p)).sub(this.camera.getPosition()).dot(this.camera.forward);
|
||||
const za=depth(a),zb=depth(b);
|
||||
return u*za/((1-u)*zb+u*za);
|
||||
}
|
||||
/** Explicit planar edit: preserve source elevation, never pretend a ray hit ground. */
|
||||
moveSemantic(point:number[],x:number,y:number,axis:import("../../core/simulation/semanticVector").SemanticAxis="xy") {
|
||||
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
|
||||
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
|
||||
const origin=toMission([from.x,from.y,from.z]),direction=toMission([to.x-from.x,to.y-from.y,to.z-from.z]);
|
||||
let result:number[]|null;
|
||||
if(axis.length===1)result=dragWaypoint(origin,direction,point,axis as "x"|"y"|"z");
|
||||
else {
|
||||
const normal=[0,1,2].find(k=>!axis.includes("xyz"[k]))!;
|
||||
if(Math.abs(direction[normal])<1e-8)return null;
|
||||
const t=(point[normal]-origin[normal])/direction[normal];if(t<0)return null;
|
||||
result=point.map((v,k)=>k===normal?v:origin[k]+t*direction[k]);
|
||||
}
|
||||
this.scan.enabled = mode === "visual" || mode === "combined";
|
||||
this.collisionLayer?.setMode(mode === "map" ? "visual" : mode);
|
||||
if(!result)return null;
|
||||
return result[2]>=this.clipFloor&&result[2]<=this.clip?result:null;
|
||||
}
|
||||
semanticGizmo(point:number[]) {
|
||||
const depth=new Vec3(...toEditor(point)).sub(this.camera.getPosition()).dot(this.camera.forward);
|
||||
const length=screenSpan(this.controls.camera,depth)*this.preferences.pivot.pixels*.7/Math.max(1,this.canvas.clientHeight);
|
||||
return {length,colors:this.preferences.pivot,base:this.projectSemantic(point),
|
||||
x:this.projectSemantic([point[0]+length,point[1],point[2]]),
|
||||
y:this.projectSemantic([point[0],point[1]+length,point[2]]),
|
||||
z:this.projectSemantic([point[0],point[1],point[2]+length])};
|
||||
}
|
||||
async pickSemanticSurface(x:number,y:number) {
|
||||
if(!this.scan.enabled||!this.scan.gsplat)return null;
|
||||
this.syncCamera();
|
||||
const hit=await this.surfacePicker.pick(x,y);
|
||||
if(!hit)return null;
|
||||
const q=toMission(hit);
|
||||
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; }
|
||||
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
|
||||
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
|
||||
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
|
||||
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
|
||||
this.collisionLayer.setClip(this.clip,this.clipFloor);
|
||||
}
|
||||
this.scan.enabled = gaussian;
|
||||
this.collisionLayer?.setMode(collision ? (gaussian ? "combined" : "collision") : "visual");
|
||||
this.dirty = true;
|
||||
}
|
||||
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
|
||||
top() {this.controls.top((this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor));this.syncCamera();this.dirty=true;}
|
||||
top() {const points=(this.urbanVisible&&this.urbanBounds.length?this.urbanBounds:this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor);this.controls.top(points.length?points:this.visualBounds);this.syncCamera();this.dirty=true;}
|
||||
setPoints(points: AiWaypoint[]) { this.points = points; this.annotations.set(points,this.selected,this.preferences);this.dirty = true; }
|
||||
setSelected(id: string|null) {this.selected=id;this.annotations.set(this.points,id,this.preferences);this.dirty=true;}
|
||||
setPreferences(preferences: PlannerPreferences) {
|
||||
@@ -153,12 +228,14 @@ export class AiEditorRuntime {
|
||||
}
|
||||
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
|
||||
}
|
||||
setClip(height: number) {
|
||||
this.clip = height;
|
||||
this.collisionLayer?.setClip(height);
|
||||
this.urbanLayer?.setClip(height);this.experienceLayer?.setClip(height);
|
||||
setClip(height: number, 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.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
|
||||
}
|
||||
this.dirty = true;
|
||||
@@ -166,9 +243,13 @@ export class AiEditorRuntime {
|
||||
setNavigation(enabled: boolean) {
|
||||
this.controls.setNavigation(enabled);
|
||||
}
|
||||
setSemanticSelection(active:boolean) {this.controls.semanticSelection=active;}
|
||||
setAddMode(add: boolean) { this.controls.setAddMode(add); }
|
||||
private syncCamera() {
|
||||
const { position:p, quaternion:q } = this.controls.camera;
|
||||
const c=this.controls.camera;
|
||||
this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE;
|
||||
if(isOrthographic(c))this.camera.camera!.orthoHeight=c.top;
|
||||
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);
|
||||
}
|
||||
home() {
|
||||
@@ -179,7 +260,7 @@ export class AiEditorRuntime {
|
||||
const width = this.canvas.clientWidth, height = this.canvas.clientHeight;
|
||||
const from = this.camera.camera!.screenToWorld(x*width,y*height,.05);
|
||||
const to = this.camera.camera!.screenToWorld(x*width,y*height,2000);
|
||||
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip);
|
||||
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,this.clipFloor);
|
||||
return hit ? toMission(hit.toArray()) : null;
|
||||
}
|
||||
pickWaypoint(x:number,y:number) {
|
||||
@@ -200,16 +281,17 @@ export class AiEditorRuntime {
|
||||
const hit = dragWaypoint([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],p,axis);
|
||||
if (!hit) return null;
|
||||
if (axis !== "xz") return toMission(hit);
|
||||
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip);
|
||||
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip,this.clipFloor);
|
||||
return ground ? toMission(ground.toArray()) : null;
|
||||
}
|
||||
private project(x:number,y:number,z:number): ScreenPoint {
|
||||
const point = this.camera.camera!.worldToScreen(new Vec3(x,y,z));
|
||||
return point.z > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
|
||||
return new Vec3(x,y,z).sub(this.camera.getPosition()).dot(this.camera.forward) > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
|
||||
}
|
||||
dispose() {
|
||||
this.disposed = true;
|
||||
this.controls.dispose();
|
||||
this.surfacePicker.dispose();
|
||||
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
|
||||
this.annotations.dispose();
|
||||
this.collisionLayer?.dispose();
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
|
||||
import {PlannerCameraTools} from "./PlannerCameraTools";
|
||||
import { heightSlice } from "../../core/heightSlice";
|
||||
import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
|
||||
import { PlannerLegend } from "./PlannerLegend";
|
||||
import { SemanticEditor } from "./SemanticEditor";
|
||||
import { PlannerExperience } from "./PlannerExperience";
|
||||
import { loadUrbanMap, URBAN_COLORS, URBAN_LABELS, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
||||
import { loadUrbanMap, type UrbanClassId, 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";
|
||||
@@ -8,7 +13,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
import { useEffect, useReducer, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, Icon, IconButton, LoadingRegion, RangeControl, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
|
||||
import { type EditorCache } from "../../core/simulation/aiEditor";
|
||||
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
|
||||
@@ -17,10 +22,14 @@ import { useLocalScene } from "./useLocalScene";
|
||||
import { useSimulationFullscreen } from "./useSimulationFullscreen";
|
||||
|
||||
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
|
||||
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, busy=false, preparedRoute=null }: {
|
||||
export type LocationMode = "view" | "semantic" | "planning";
|
||||
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, busy=false, preparedRoute=null }: {
|
||||
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
|
||||
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
|
||||
actionsHost: HTMLElement | null; headerActions: React.ReactNode;
|
||||
routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
|
||||
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void;
|
||||
}) {
|
||||
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
|
||||
const markerSvg=useRef<SVGSVGElement>(null);
|
||||
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
|
||||
const viewport = useRef<HTMLDivElement>(null), loadedPoints = useRef(initialPoints);
|
||||
@@ -33,44 +42,62 @@ 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|"map">("visual");
|
||||
const [layout,updateLayout]=useSimulationLayout();
|
||||
const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers});
|
||||
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
|
||||
const [urbanVisible,setUrbanVisible]=useState(false);
|
||||
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 [viewMode,setViewMode]=useState<"3d"|"top">("3d");
|
||||
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
||||
const [mode,setMode] = useState<"view" | "add">("view");
|
||||
const [clip,setClip] = useState(Infinity);
|
||||
const [clip,setClip] = useState<[number,number]|null>(null);
|
||||
const draftId = useRef(crypto.randomUUID().replaceAll("-",""));
|
||||
const drag = useRef<{ point: AiWaypoint; axis: WaypointAxis; offset: number[] } | null>(null);
|
||||
const callback = useRef(onDraft); callback.current = onDraft;
|
||||
useEffect(() => {
|
||||
if (cache?.status !== "ready" || !canvas.current) return;
|
||||
let active = true;
|
||||
let active = true, loaded=false;
|
||||
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);setUrbanVisible(false);setUrbanError(null);
|
||||
setReady(false); setError(null); setClip(Infinity); setLayerMode("visual");
|
||||
setUrbanMap(null);setUrbanError(null);
|
||||
setReady(false); setError(null); setClip(null);
|
||||
let view: AiEditorRuntime;
|
||||
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
|
||||
catch (e) { setError((e as Error).message); return; }
|
||||
catch (e) { clearInterval(timer);window.removeEventListener("pagehide",remember);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);
|
||||
const remembered=readSceneView(sceneKey),settings=getSimulationLayout();
|
||||
if(remembered){view.restoreView(remembered);setClip([remembered.clip[0]??view.height[0],remembered.clip[1]??view.height[1]]);}
|
||||
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); });
|
||||
return () => { active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
|
||||
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]);
|
||||
useEffect(() => {
|
||||
runtime.current?.setPoints(points);
|
||||
runtime.current?.setPoints(planning?points:[]);
|
||||
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
|
||||
}, [points,cache,ready,sequence]);
|
||||
}, [points,cache,ready,sequence,planning]);
|
||||
useEffect(()=>{
|
||||
runtime.current?.setRoute(preparedRoute?.preview_xyz??[]);
|
||||
if(preparedRoute && ready){runtime.current?.top();setViewMode("top");}
|
||||
},[preparedRoute?.sha256,ready]);
|
||||
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);}
|
||||
},[semantic,urbanMap,urbanVisible,urbanClasses]);
|
||||
useEffect(()=>{
|
||||
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
|
||||
|
||||
},[preparedRoute?.sha256,ready,planning]);
|
||||
useEffect(()=>{
|
||||
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]);
|
||||
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
|
||||
@@ -94,47 +121,60 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
const bytes = progress.reduce((n,f)=>n+f.uploaded_bytes,0), total = progress.reduce((n,f)=>n+f.byte_length,0);
|
||||
const message = cache?.status === "uploading" ? `Копируем сцену на диск · ${Math.round(bytes/Math.max(1,total)*100)}%`
|
||||
: 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}</>;
|
||||
return <div className="ai-polygon__stage" ref={host}>
|
||||
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
|
||||
{expanded ? <>
|
||||
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
|
||||
</> : <>
|
||||
{actionsHost ? createPortal(header,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>
|
||||
{urbanVisible && urbanMap ? <p>Генплан · {urbanMap.coverage.kind === "objects-only" ? `участок · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
|
||||
<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>
|
||||
{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)=>{
|
||||
if(!planning)return;
|
||||
const editable=!!(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"],.nodedc-workspace-window');
|
||||
const action=waypointShortcut(e,editable);
|
||||
if(!busy && ready && !drag.current && action){e.preventDefault();edit({type:action});setError(null);}
|
||||
}}>
|
||||
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning>
|
||||
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning routeEditing={planning} semantic={semantic}>
|
||||
{ready?<div className="ai-local-editor__tools nodedc-scene-controls" inert={busy}>
|
||||
{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:"Вместе"},...(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:"Не удалось показать слой коллизий.");}}}/>
|
||||
<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");}}
|
||||
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
|
||||
<div className="ai-local-editor__tool-row">
|
||||
{runtime.current&&viewport.current?<PlannerCameraTools runtime={runtime.current} viewport={viewport.current} semantic={semantic} disabled={busy}/>:null} {planning?<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
|
||||
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>:null}
|
||||
{planning&&points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
|
||||
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
|
||||
}}><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!}
|
||||
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!}
|
||||
runtime={runtime.current} viewport={viewport.current} active={semantic} busy={busy} source={urbanMap} headerHost={semanticHeader}/>:null}
|
||||
{semantic&&!urbanMap?<StatusBadge tone="neutral">Рассчитайте инфраструктуру для редактирования</StatusBadge>:null}
|
||||
</div>:null}
|
||||
</SimulationViewTools>
|
||||
<div className="ai-local-editor__surface"
|
||||
onPointerDownCapture={(e)=>{
|
||||
if(e.target!==canvas.current || e.button!==0 || busy || !ready)return;
|
||||
if(!planning || e.target!==canvas.current || e.button!==0 || busy || !ready)return;
|
||||
const id=runtime.current?.pickWaypoint(...position(e) as [number,number]);
|
||||
if(!id)return;
|
||||
e.preventDefault();e.stopPropagation();press.current=null;
|
||||
@@ -145,14 +185,14 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
drag.current={point:points.find(p=>p.id===id)!,axis:"xz",offset:base.map((v,i)=>v-position(e)[i])};
|
||||
runtime.current?.setNavigation(false);markerSvg.current!.setPointerCapture(e.pointerId);
|
||||
}}
|
||||
onPointerDown={(e)=>{if(e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
|
||||
onPointerDown={(e)=>{if(planning&&e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
|
||||
onPointerCancel={()=>{press.current=null;}}
|
||||
onPointerUp={(e)=>{
|
||||
const start=press.current;press.current=null;
|
||||
if(!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
|
||||
if(!planning||!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
|
||||
if(mode==="add")add(...position(e) as [number,number]);else edit({type:"select",id:null});
|
||||
}}><canvas ref={canvas} aria-label="Локальная Gaussian-сцена для маршрута" />
|
||||
<svg ref={markerSvg} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
|
||||
<svg ref={markerSvg} style={!planning?{display:"none"}:undefined} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
|
||||
onPointerMove={(e)=>{
|
||||
if (!drag.current) return;
|
||||
const d=drag.current, [x,y]=position(e);
|
||||
@@ -183,11 +223,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>
|
||||
{!ready && !error ? <div className="ai-polygon__preview-error"><LoadingRegion loading label={message} /></div>:null}
|
||||
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
|
||||
selected={urbanClasses} onChange={setUrbanClasses} 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={Number.isFinite(clip)?clip:runtime.current!.height[1]}
|
||||
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=v>=runtime.current!.height[1]?Infinity:v;setClip(next);runtime.current!.setClip(next);}}/></div>
|
||||
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></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>
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useState } from "react";
|
||||
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
|
||||
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
|
||||
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
|
||||
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
|
||||
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
|
||||
}) {
|
||||
const queue=useInfrastructureQueue();
|
||||
const [editing, setEditing] = useState<AiWorld | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [showRemoved, setShowRemoved] = useState(false);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const update = async (world: AiWorld, changes: {display_name?:string;removed?:boolean}) => {
|
||||
if (busy) return;
|
||||
setBusy(world.world_id); setError(null);
|
||||
try {
|
||||
await updateAiWorld(world.world_id, changes);
|
||||
await onChanged();
|
||||
setConfirming(false); setEditing(null);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "Не удалось сохранить изменения.");
|
||||
} finally { setBusy(null); }
|
||||
};
|
||||
return <>
|
||||
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
|
||||
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
|
||||
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
|
||||
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
|
||||
actions={<>
|
||||
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
|
||||
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
|
||||
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
|
||||
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
|
||||
<IconButton label={`Настройки ${world.name}`} onClick={() => {
|
||||
setEditing(world); setName(world.name); setConfirming(false); setError(null);
|
||||
}}><Icon name="settings"/></IconButton>
|
||||
</>}/>
|
||||
</li>;})}</ResourceList>
|
||||
{removedWorlds.length ? <>
|
||||
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
|
||||
Удалённые локации · {removedWorlds.length}</Button>
|
||||
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
|
||||
<Button disabled={busy !== null} loading={busy === world.world_id}
|
||||
onClick={() => void update(world, {removed:false})}>Восстановить</Button>}/>
|
||||
</li>)}</ResourceList> : null}
|
||||
</> : null}
|
||||
<Window open={!!editing && !confirming} title="Настройки локации" size="sm"
|
||||
onClose={() => {if (!busy) setEditing(null);}}
|
||||
footer={<WindowFooterActions>
|
||||
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
|
||||
onClick={() => setConfirming(true)}>Удалить локацию</Button>
|
||||
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
|
||||
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
|
||||
</WindowFooterActions>}>
|
||||
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
|
||||
onChange={event => setName(event.target.value)}/>
|
||||
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null}
|
||||
</Window>
|
||||
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
|
||||
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
|
||||
Восстановить её можно в списке удалённых локаций.</>}
|
||||
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
|
||||
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
|
||||
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
|
||||
onDismiss={() => setError(null)}/> : null}
|
||||
</>;
|
||||
}
|
||||
@@ -126,7 +126,7 @@ export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: {
|
||||
setClip(height); send({ action: "clip", amount: value, enabled: height != null });
|
||||
}} />
|
||||
</div> : null}
|
||||
{editing ? <div className="ai-route__tools">
|
||||
{editing ? <div className="ai-route__tools nodedc-viewport-controls">
|
||||
<SegmentedControl label="Инструмент маршрута" size="dense" value={mode} onChange={setMode}
|
||||
items={[{ value: "view", label: "Обзор" }, { value: "add", label: "Точка по клику" }]} />
|
||||
<Button disabled={!ready} onClick={() => send({ action: "add", x: .5, y: .5 })}>Добавить waypoint</Button>
|
||||
|
||||
@@ -1,24 +1,31 @@
|
||||
import type {SceneView} from "../../core/simulation/simulationLayout";
|
||||
import { DEFAULT_PLANNER_PREFERENCES, panSensitivity } from "../../core/simulation/plannerPreferences";
|
||||
import { zoomDisplacement } from "../../core/simulation/editorZoom";
|
||||
import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/editorNavigation";
|
||||
import { PerspectiveCamera, Vector3 } from "three";
|
||||
import {cameraRay,isOrthographic,switchProjection,type EditorProjection,type ProjectionCamera} from "../../core/simulation/editorProjection";
|
||||
|
||||
const KEYS = new Set(["KeyW","KeyA","KeyS","KeyD","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","KeyQ","KeyE","ShiftLeft","ShiftRight"]);
|
||||
/** Input/math only: PlayCanvas remains the sole renderer. */
|
||||
export class EditorCamera {
|
||||
readonly camera = new PerspectiveCamera(60, 1, .05, 3000);
|
||||
camera:ProjectionCamera = new PerspectiveCamera(60, 1, .05, 3000);
|
||||
private aspect=1;
|
||||
get projection():EditorProjection {return isOrthographic(this.camera)?"orthographic":"perspective";}
|
||||
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
|
||||
get rotationCenter(){return this.gesture&&!this.gesture.pan?this.gesture.anchor:null;}
|
||||
get rotationCenter(){return this.gesture&&!this.gesture.pan&&!this.gesture.pending?this.gesture.anchor:null;}
|
||||
private keys = new Set<string>();
|
||||
private enabled=true;
|
||||
private topPoints:number[][]|null=null;
|
||||
private addMode=false;
|
||||
private gesture: {id:number;x:number;y:number;anchor:Vector3;depth:number;distance:number;pan:boolean}|null=null;
|
||||
semanticSelection=false;
|
||||
private gesture: {id:number;x:number;y:number;nextX:number;nextY:number;anchor:Vector3;depth:number;distance:number;pan:boolean;pending:boolean}|null=null;
|
||||
private lastAnchor: Vector3|null = null;
|
||||
private forward = new Vector3();
|
||||
private right = new Vector3();
|
||||
private delta = new Vector3();
|
||||
sceneCenter = new Vector3();
|
||||
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) {
|
||||
surface.addEventListener("wheel",this.zoom,{passive:false});
|
||||
surface.addEventListener("pointerdown",this.pointerDown);
|
||||
@@ -34,68 +41,122 @@ export class EditorCamera {
|
||||
private anchor(x:number,y:number) {
|
||||
const hit=this.pick?.(x,y);
|
||||
if(hit)return new Vector3(...hit);
|
||||
// Empty sky has no surface; retain useful scale relative to the scene.
|
||||
return this.camera.getWorldDirection(new Vector3())
|
||||
.multiplyScalar(Math.max(2,this.camera.position.distanceTo(this.sceneCenter))).add(this.camera.position);
|
||||
// Empty sky: retain useful depth, but keep the pivot on the clicked ray.
|
||||
const depth=this.lastAnchor?navigationDepth(this.camera,this.lastAnchor):Math.max(2,this.camera.position.distanceTo(this.sceneCenter));
|
||||
const forward=this.camera.getWorldDirection(new Vector3());
|
||||
const ray=cameraRay(this.camera,x,y);
|
||||
return ray.at((depth-ray.origin.clone().sub(this.camera.position).dot(forward))/Math.max(.01,ray.direction.dot(forward)),new Vector3());
|
||||
}
|
||||
private pointerDown=(e:PointerEvent)=>{
|
||||
const editOrbit=this.semanticSelection&&e.ctrlKey&&[0,2].includes(e.button);
|
||||
// Ctrl-drag may start on a semantic gizmo as well as the underlying canvas.
|
||||
if(e.target!==this.canvas&&!(editOrbit&&(e.target as Element).closest("[data-semantic-axis],[data-semantic-handle]")))return;
|
||||
this.canvas.focus({preventScroll:true});
|
||||
if(!this.enabled || (e.target as Element).closest("[data-waypoint]") || ![0,1,2].includes(e.button))return;
|
||||
if(e.button===0 && this.addMode)return;
|
||||
const rect=this.canvas.getBoundingClientRect();
|
||||
const anchor=this.anchor((e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height);
|
||||
this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0};
|
||||
if(e.button===0&&(this.semanticSelection&&!editOrbit||this.addMode&&!editOrbit))return;
|
||||
if(editOrbit)e.preventDefault();
|
||||
this.cancelGesture();
|
||||
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
|
||||
const anchor=this.anchor(x,y);this.lastAnchor=anchor.clone();
|
||||
const g=this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,nextX:e.clientX,nextY:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0&&!editOrbit,pending:!!this.pickSurface};
|
||||
this.surface.setPointerCapture(e.pointerId);
|
||||
if(this.pickSurface)void this.pickSurface(x,y).catch(()=>null).then(hit=>{
|
||||
if(this.gesture!==g)return; // Released pointer, new gesture, resize or view change.
|
||||
if(hit?.length===3&&hit.every(Number.isFinite)){g.anchor.set(...hit as [number,number,number]);this.lastAnchor=g.anchor.clone();}
|
||||
g.depth=navigationDepth(this.camera,g.anchor);g.distance=this.camera.position.distanceTo(g.anchor);g.pending=false;
|
||||
this.moveGesture(g.nextX,g.nextY);
|
||||
});
|
||||
};
|
||||
private pointerMove=(e:PointerEvent)=>{
|
||||
const g=this.gesture;if(!g||g.id!==e.pointerId||!this.enabled)return;
|
||||
this.topPoints=null;
|
||||
const dx=e.clientX-g.x,dy=e.clientY-g.y;g.x=e.clientX;g.y=e.clientY;
|
||||
if(g.pan)panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);
|
||||
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
|
||||
g.nextX=e.clientX;g.nextY=e.clientY;
|
||||
if(!g.pending)this.moveGesture(e.clientX,e.clientY);
|
||||
};
|
||||
private moveGesture(x:number,y:number){
|
||||
const g=this.gesture;if(!g)return;
|
||||
const dx=x-g.x,dy=y-g.y;g.x=x;g.y=y;
|
||||
if(!dx&&!dy)return;
|
||||
this.topPoints=null;
|
||||
if(g.pan){const before=this.camera.position.clone();panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);this.lastAnchor?.add(this.camera.position.clone().sub(before));}
|
||||
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
|
||||
}
|
||||
private pointerEnd=(e:PointerEvent)=>{
|
||||
if(this.gesture?.id!==e.pointerId)return;
|
||||
this.gesture=null;
|
||||
if(this.surface.hasPointerCapture(e.pointerId))this.surface.releasePointerCapture(e.pointerId);
|
||||
this.cancelGesture();
|
||||
};
|
||||
private zoom=(e:WheelEvent)=>{
|
||||
if(!this.enabled)return;
|
||||
if(!this.enabled||e.target!==this.canvas)return;
|
||||
this.cancelGesture();
|
||||
this.topPoints=null;
|
||||
e.preventDefault();this.canvas.focus({preventScroll:true});
|
||||
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
|
||||
const ray=new Vector3(x*2-1,1-y*2,.5).unproject(this.camera).sub(this.camera.position).normalize();
|
||||
const depth=this.camera.position.distanceTo(this.anchor(x,y));
|
||||
const anchor=this.anchor(x,y),ray=cameraRay(this.camera,x,y).direction;
|
||||
const depth=this.camera.position.distanceTo(anchor);
|
||||
if(this.semanticSelection&&!e.ctrlKey&&!e.metaKey) {
|
||||
const before=this.camera.position.clone();panCamera(this.camera,navigationDepth(this.camera,anchor),e.deltaX,e.deltaY,this.canvas.clientHeight);
|
||||
this.lastAnchor=anchor.add(this.camera.position.clone().sub(before));
|
||||
this.camera.updateMatrixWorld();return;
|
||||
}
|
||||
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?rect.height:1);
|
||||
this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));this.camera.updateMatrixWorld();
|
||||
if(isOrthographic(this.camera)) {
|
||||
const factor=Math.exp(Math.max(-.8,Math.min(.8,delta*this.navigation.zoom*.002)));
|
||||
const next=Math.max(.05,Math.min(5000,this.camera.top*factor)),ratio=next/this.camera.top;
|
||||
const offset=anchor.clone().sub(this.camera.position);offset.addScaledVector(this.camera.getWorldDirection(new Vector3()),-navigationDepth(this.camera,anchor));
|
||||
this.camera.position.addScaledVector(offset,1-ratio);
|
||||
this.camera.top=next;this.camera.bottom=-next;this.camera.left=-next*this.aspect;this.camera.right=next*this.aspect;this.camera.updateProjectionMatrix();
|
||||
} else this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));
|
||||
this.lastAnchor=anchor;this.camera.updateMatrixWorld();
|
||||
};
|
||||
private keyDown=(e:KeyboardEvent)=>{
|
||||
if(document.activeElement!==this.canvas || e.ctrlKey || e.metaKey || e.altKey || !KEYS.has(e.code))return;
|
||||
e.preventDefault();this.keys.add(e.code);
|
||||
};
|
||||
private keyUp=(e:KeyboardEvent)=>{this.keys.delete(e.code);};
|
||||
private clear=()=>{this.keys.clear();this.gesture=null;};
|
||||
resize(width:number,height:number){this.camera.aspect=width/height;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
|
||||
private cancelGesture(){const id=this.gesture?.id;this.gesture=null;if(id!==undefined&&this.surface.hasPointerCapture(id))this.surface.releasePointerCapture(id);}
|
||||
private clear=()=>{this.keys.clear();this.cancelGesture();};
|
||||
resize(width:number,height:number){this.cancelGesture();this.aspect=width/height;if(isOrthographic(this.camera)){this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;}else this.camera.aspect=this.aspect;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
|
||||
setProjection(mode:EditorProjection){this.clear();this.camera=switchProjection(this.camera,mode,this.aspect,navigationDepth(this.camera,this.lastAnchor??this.sceneCenter));}
|
||||
view(direction:number[]){
|
||||
this.clear();this.topPoints=null;
|
||||
const depth=navigationDepth(this.camera,this.lastAnchor??this.sceneCenter),target=this.camera.position.clone().addScaledVector(this.camera.getWorldDirection(new Vector3()),depth);
|
||||
const d=new Vector3(...direction).normalize();this.camera.position.copy(target).addScaledVector(d,depth);
|
||||
this.camera.up.set(0,1,0);if(Math.abs(d.y)>.999)this.camera.up.set(0,0,-Math.sign(d.y));
|
||||
this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();this.lastAnchor=target;
|
||||
}
|
||||
home(point:number[]){
|
||||
this.clear();this.lastAnchor=null;
|
||||
this.topPoints=null;
|
||||
const target=new Vector3(...point);
|
||||
if(isOrthographic(this.camera)){this.camera.top=6.5;this.camera.bottom=-6.5;this.camera.left=-6.5*this.aspect;this.camera.right=6.5*this.aspect;this.camera.updateProjectionMatrix();}
|
||||
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
|
||||
}
|
||||
top(points:number[][]){
|
||||
if(!points.length)return;
|
||||
this.clear();this.lastAnchor=null;
|
||||
this.topPoints=points;
|
||||
const low=[0,1,2].map(i=>Math.min(...points.map(p=>p[i])));
|
||||
const high=[0,1,2].map(i=>Math.max(...points.map(p=>p[i])));
|
||||
const target=new Vector3(...low.map((v,i)=>(v+high[i])/2));
|
||||
const span=Math.max((high[0]-low[0])/this.camera.aspect,high[2]-low[2],10);
|
||||
const span=Math.max((high[0]-low[0])/this.aspect,high[2]-low[2],10);
|
||||
const distance=span/(2*Math.tan(Math.PI/6))*1.15+high[1]-low[1];
|
||||
this.camera.position.copy(target).add(new Vector3(0,distance,0));
|
||||
if(isOrthographic(this.camera)){this.camera.top=span*.575;this.camera.bottom=-this.camera.top;this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;this.camera.updateProjectionMatrix();}
|
||||
this.lastAnchor=target;this.camera.position.copy(target).add(new Vector3(0,distance,0));
|
||||
this.camera.up.set(0,0,-1);this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();
|
||||
}
|
||||
setAddMode(add:boolean){this.addMode=add;}
|
||||
snapshot(){return {position:this.camera.position.toArray(),quaternion:this.camera.quaternion.toArray(),anchor:this.lastAnchor?.toArray()??null,projection:this.projection,span:isOrthographic(this.camera)?this.camera.top:null};}
|
||||
restore(view:SceneView){
|
||||
this.clear();this.topPoints=null;this.setProjection(view.projection);
|
||||
this.camera.position.fromArray(view.position);this.camera.quaternion.fromArray(view.quaternion);
|
||||
this.lastAnchor=view.anchor?new Vector3(...view.anchor):null;
|
||||
if(isOrthographic(this.camera)&&view.span!==null){this.camera.top=view.span;this.camera.bottom=-view.span;this.camera.left=-view.span*this.aspect;this.camera.right=view.span*this.aspect;}
|
||||
this.camera.updateProjectionMatrix();this.camera.updateMatrixWorld();
|
||||
}
|
||||
setAddMode(add:boolean){this.cancelGesture();this.addMode=add;}
|
||||
invalidateSurface(){this.cancelGesture();this.lastAnchor=null;}
|
||||
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
|
||||
update(dt:number){
|
||||
if(!this.enabled||!this.keys.size)return;
|
||||
this.cancelGesture();
|
||||
this.topPoints=null;
|
||||
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
|
||||
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
|
||||
|
||||
@@ -35,9 +35,10 @@ export class EditorCollisionLayer {
|
||||
fragmentGLSL: `
|
||||
varying vec3 surfacePosition;
|
||||
uniform float surfaceClip;
|
||||
uniform float surfaceFloor;
|
||||
uniform float surfaceOpacity;
|
||||
void main(void) {
|
||||
if (surfacePosition.y > surfaceClip) discard;
|
||||
if (surfacePosition.y > surfaceClip || surfacePosition.y < surfaceFloor) discard;
|
||||
vec3 normal = normalize(cross(dFdx(surfacePosition), dFdy(surfacePosition)));
|
||||
float shade = 0.42 + 0.58 * abs(dot(normal, normalize(vec3(0.3, 1.0, 0.4))));
|
||||
gl_FragColor = vec4(vec3(0.2, 0.95, 0.42) * shade, surfaceOpacity);
|
||||
@@ -64,7 +65,8 @@ export class EditorCollisionLayer {
|
||||
this.material.depthWrite = true;
|
||||
this.material.update();
|
||||
}
|
||||
setClip(height: number) {
|
||||
setClip(height: number, floor = -Infinity) {
|
||||
this.material.setParameter("surfaceFloor", Number.isFinite(floor) ? floor : -1e9);
|
||||
this.material.setParameter("surfaceClip", Number.isFinite(height) ? height : 1e9);
|
||||
}
|
||||
dispose() {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Application, Entity, LAYERID_WORLD, Picker } from "playcanvas";
|
||||
|
||||
/** Visual navigation only. Gaussian depth never becomes a route/collision surface. */
|
||||
export class EditorSurfacePicker {
|
||||
private picker: Picker | null = null;
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
private request = 0;
|
||||
private disposed = false;
|
||||
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {}
|
||||
|
||||
pick(x: number, y: number): Promise<number[] | null> {
|
||||
const request = ++this.request;
|
||||
// Keep one GPU readback in flight; superseded clicks never resize its buffer.
|
||||
const result = this.tail.then(async () => {
|
||||
if (this.disposed || request !== this.request || x < 0 || x >= 1 || y < 0 || y >= 1) return null;
|
||||
const world = this.app.scene.layers.getLayerById(LAYERID_WORLD);
|
||||
if (!world) return null;
|
||||
const width = Math.max(1, Math.round(this.canvas.clientWidth));
|
||||
const height = Math.max(1, Math.round(this.canvas.clientHeight));
|
||||
this.picker ??= new Picker(this.app, width, height, true);
|
||||
this.picker.resize(width, height);
|
||||
// Exclude infrastructure, route markers and gizmos from the depth measurement.
|
||||
this.picker.prepare(this.camera.camera!, this.app.scene, [world]);
|
||||
const point = await this.picker.getWorldPointAsync(x * width, y * height);
|
||||
if (this.disposed || request !== this.request || !point) return null;
|
||||
const xyz = [point.x, point.y, point.z];
|
||||
return xyz.every(Number.isFinite) ? xyz : null;
|
||||
});
|
||||
this.tail = result.then(() => undefined, () => undefined);
|
||||
return result;
|
||||
}
|
||||
|
||||
invalidate() { this.request++; }
|
||||
dispose() {
|
||||
this.disposed = true; this.invalidate();
|
||||
this.picker?.destroy(); this.picker = null;
|
||||
}
|
||||
}
|
||||
@@ -54,16 +54,20 @@ export class EditorTerrain {
|
||||
indices: geometry.index!.array as Uint16Array | Uint32Array,
|
||||
}));
|
||||
}
|
||||
pick(origin: number[], direction: number[], clip = Infinity) {
|
||||
pick(origin: number[], direction: number[], clip = Infinity, floor = -Infinity) {
|
||||
return this.pickSurface(origin,direction,clip,true,floor);
|
||||
}
|
||||
/** Camera navigation may select walls; waypoint admission remains ground-only. */
|
||||
pickSurface(origin: number[], direction: number[], clip = Infinity, groundOnly = false, floor = -Infinity) {
|
||||
const ray = new Ray(new Vector3(...origin), new Vector3(...direction).normalize());
|
||||
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
|
||||
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
|
||||
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && (!groundOnly || Math.abs(hit.face?.normal.y ?? 0) > .35))
|
||||
.sort((a, b) => a.distance - b.distance)[0]?.point ?? null;
|
||||
}
|
||||
ground(x: number, z: number, near: number, clip = Infinity) {
|
||||
ground(x: number, z: number, near: number, clip = Infinity, floor = -Infinity) {
|
||||
const ray = new Ray(new Vector3(x, this.bounds.max.y + 1, z), new Vector3(0, -1, 0));
|
||||
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
|
||||
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
|
||||
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && Math.abs(hit.face?.normal.y ?? 0) > .35)
|
||||
.sort((a, b) => Math.abs(a.point.y - near) - Math.abs(b.point.y - near))[0]?.point ?? null;
|
||||
}
|
||||
dispose() { this.disposed = true; this.draco.dispose(); this.builder?.dispose(); this.builder = null; this.geometries.forEach((g) => g.dispose()); this.trees = []; }
|
||||
|
||||
@@ -1,38 +1,58 @@
|
||||
import { Application, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
|
||||
import { Application, BLEND_NORMAL, CULLFACE_NONE, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, PRIMITIVE_TRIANGLES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
|
||||
import { toEditor } from "../../core/simulation/aiEditor";
|
||||
import { URBAN_COLORS, urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import { URBAN_COLORS, urbanPaths, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import { urbanSurface } from "../../core/simulation/urbanSurface";
|
||||
|
||||
/** Read-only contours. This layer never enters terrain picking, collision or routing. */
|
||||
/** Read-only observed surfaces and physical contours; never routing or collision input. */
|
||||
export class EditorUrbanMapLayer {
|
||||
private entity: Entity;
|
||||
private mesh: Mesh;
|
||||
private material: ShaderMaterial;
|
||||
private meshes: Mesh[] = [];
|
||||
private groups = new Map<string,Entity>();
|
||||
private materials: ShaderMaterial[];
|
||||
private surfaceLayer = new Layer({ name: "Urban pedestrian coverage" });
|
||||
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[] = [];
|
||||
const at=app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1;
|
||||
app.scene.layers.insert(this.surfaceLayer,at);app.scene.layers.insert(this.layer,at+2);
|
||||
camera.camera!.layers = [...camera.camera!.layers, this.surfaceLayer.id, this.layer.id];
|
||||
this.materials=[false,true].map(surface=>{
|
||||
const material=new ShaderMaterial({ uniqueName: surface?"urban-ground-coverage":"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; uniform float mapFloor;
|
||||
void main(void) { if(mapHeight>mapClip || mapHeight<mapFloor) discard; gl_FragColor=mapColor; }` });
|
||||
material.depthTest=false;material.depthWrite=false;
|
||||
if(surface){material.blendType=BLEND_NORMAL;material.cull=CULLFACE_NONE;}
|
||||
return material;
|
||||
});
|
||||
this.entity = new Entity("Urban infrastructure",app);
|
||||
const groups = new Map<string, {positions:number[];colors:number[];surface:boolean}>();
|
||||
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);
|
||||
const surface=urbanSurface(feature),key=feature.properties.class+(surface?":surface":":line");
|
||||
if (!groups.has(key)) groups.set(key,{positions:[],colors:[],surface:!!surface});
|
||||
const group=groups.get(key)!;
|
||||
if(surface){
|
||||
for(const i of surface.indices){group.positions.push(...toEditor(surface.positions.slice(i*3,i*3+3)));group.colors.push(...color,48);}
|
||||
}else for (const ring of urbanPaths(feature)) for (let i=1;i<ring.length;i++) {
|
||||
group.positions.push(...toEditor(ring[i-1]), ...toEditor(ring[i]));
|
||||
group.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] });
|
||||
for (const [key,{positions,colors,surface}] of groups) {
|
||||
if (!positions.length) continue;
|
||||
const mesh=new Mesh(app.graphicsDevice);mesh.setPositions(positions);mesh.setColors32(colors);mesh.update(surface?PRIMITIVE_TRIANGLES:PRIMITIVE_LINES);this.meshes.push(mesh);
|
||||
const entity=new Entity(key,app);entity.addComponent("render",{meshInstances:[new MeshInstance(mesh,this.materials[surface?1:0])],layers:[surface?this.surfaceLayer.id:this.layer.id],castShadows:false,receiveShadows:false});
|
||||
this.entity.addChild(entity);this.groups.set(key,entity);
|
||||
}
|
||||
this.entity.enabled=false; app.root.addChild(this.entity); this.setClip(Infinity);
|
||||
}
|
||||
setClasses(selected:readonly UrbanClassId[]) {
|
||||
for (const [key,entity] of this.groups) entity.enabled=selected.includes(key.split(":")[0] as UrbanClassId);
|
||||
}
|
||||
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(); }
|
||||
setClip(height: number, floor = -Infinity) { for(const material of this.materials) { material.setParameter("mapClip",Number.isFinite(height)?height:1e9); material.setParameter("mapFloor",Number.isFinite(floor)?floor:-1e9); } }
|
||||
dispose() { this.camera.camera!.layers=this.camera.camera!.layers.filter(id=>id!==this.layer.id&&id!==this.surfaceLayer.id);this.app.scene.layers.remove(this.layer);this.app.scene.layers.remove(this.surfaceLayer);this.entity.destroy();for(const mesh of this.meshes)mesh.destroy();for(const material of this.materials)material.destroy(); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useState } from "react";
|
||||
import { Icon, IconButton, LayerStackIndicator, ProgressButton, ToastStack } from "@nodedc/ui-react";
|
||||
import type { UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import { analysisProgressLabel, useInfrastructureAnalysis } from "../../core/simulation/infrastructureAnalysis";
|
||||
export function InfrastructureAnalysis({worldId,worldSha,busy,hasMap,onMap}:{worldId:string;worldSha:string;busy:boolean;hasMap:boolean;onMap:(map:UrbanMap)=>void}) {
|
||||
const {job,error,clearError,sending,checking,start,cancel}=useInfrastructureAnalysis(worldId,worldSha,onMap);
|
||||
const [dismissedFailure,setDismissedFailure]=useState<string|null>(null);
|
||||
const pending=job?.status==="queued"||job?.status==="running";
|
||||
const phase=sending?(pending?"Отменяем расчёт":"Запускаем расчёт"):checking?"Проверяем состояние":pending?analysisProgressLabel(job):null;
|
||||
const recalculate=hasMap||job?.status==="ready";
|
||||
return <>
|
||||
{!phase&&!busy?<IconButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} title={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} onClick={()=>void start(recalculate)}><Icon name="layers"/></IconButton>:null}
|
||||
{phase?<ProgressButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"}
|
||||
icon={phase?<LayerStackIndicator/>:<Icon name="layers"/>} disabled={busy}
|
||||
title={pending?"Прогноз уточняется по выполненным этапам. Ожидание Worker и подготовка исходного проекта считаются отдельно.":undefined}
|
||||
progress={phase?{label:phase,value:pending&&!job.progress?.stale?job.progress?.fraction??undefined:undefined}:undefined}
|
||||
onClick={()=>void start(recalculate)}/>:null}
|
||||
{pending&&!job.cancel_requested?<IconButton label="Отменить расчёт инфраструктуры" loading={sending}
|
||||
onClick={()=>void cancel()}><Icon name="stop"/></IconButton>:null}
|
||||
{error?<ToastStack items={[{id:"infrastructure",tone:"error",title:"Не удалось выполнить расчёт",description:error}]} onDismiss={clearError}/>:null}
|
||||
{job?.status==="failed"&&job.error&&dismissedFailure!==job.key?<ToastStack items={[{id:job.key,tone:"error",title:"Расчёт не завершён",description:job.error}]} onDismiss={()=>setDismissedFailure(job.key)}/>:null}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {usePlannerPreferences} from "./usePlannerPreferences";
|
||||
import {useEffect,useState} from "react";
|
||||
import {Button,Dropdown,Icon,IconButton,NavigationCube} from "@nodedc/ui-react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {useSimulationLayout} from "./useSimulationLayout";
|
||||
import type {AiEditorRuntime} from "./AiEditorRuntime";
|
||||
export function PlannerCameraTools({runtime,viewport,disabled}:{runtime:AiEditorRuntime;viewport:HTMLElement;semantic:boolean;disabled:boolean}) {
|
||||
const [preferences]=usePlannerPreferences();
|
||||
const [layout,updateLayout]=useSimulationLayout();
|
||||
const projection=layout.projection;
|
||||
const [quaternion,setQuaternion]=useState<[number,number,number,number]>([0,0,0,1]);
|
||||
useEffect(()=>{viewport.style.setProperty("--planner-cube-size",`${preferences.cube.size}px`);return()=>{viewport.style.removeProperty("--planner-cube-size");};},[viewport,preferences.cube.size]);
|
||||
useEffect(()=>{runtime.watchCamera(setQuaternion);return()=>runtime.watchCamera(null);},[runtime]);
|
||||
useEffect(()=>{runtime.setProjection(projection);},[runtime,projection]);
|
||||
return <>
|
||||
<Dropdown placement="bottom-end" width={220} trigger={({toggle,setTriggerRef,open})=><IconButton ref={setTriggerRef}
|
||||
label={`Проекция: ${projection==="orthographic"?"ортографическая":"перспективная"}`} title="Выбрать проекцию" disabled={disabled} aria-expanded={open} onClick={toggle}><Icon name={projection}/></IconButton>}>
|
||||
{({close})=><div className="semantic-tools__menu">{([['orthographic','Ортографическая'],['perspective','Перспективная']] as const).map(([mode,label])=><Button key={mode} width="full" variant={projection===mode?"primary":"secondary"} tone="neutral" aria-pressed={projection===mode} onClick={()=>{updateLayout({projection:mode});close();}}>{label}</Button>)}</div>}
|
||||
</Dropdown>
|
||||
{createPortal(<div className="ai-local-editor__cube"><NavigationCube quaternion={quaternion} {...preferences.cube} disabled={disabled} onSelect={direction=>runtime.view(direction)}/></div>,viewport)}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import {ColorField,ControlRow,RangeControl} from "@nodedc/ui-react";
|
||||
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
|
||||
export function PlannerCubeSettings({value,set}:{value:PlannerPreferences["cube"];set:(key:string,value:string|number)=>void}) {
|
||||
return <>
|
||||
<RangeControl label="Размер 3D-куба" min={48} max={160} step={1} value={value.size} onChange={v=>set("size",v)} formatValue={v=>`${v} px`}/>
|
||||
<RangeControl label="Непрозрачность куба" min={.2} max={1} step={.05} value={value.opacity} onChange={v=>set("opacity",v)} formatValue={v=>`${Math.round(v*100)}%`}/>
|
||||
<RangeControl label="Прозрачность линий" min={0} max={1} step={.05} value={1-value.edgeOpacity} onChange={v=>set("edgeOpacity",1-v)} formatValue={v=>`${Math.round(v*100)}%`}/>
|
||||
{([["face","Грани"],["text","Подписи"],["edge","Рёбра"],["hover","Подсветка"],["hoverText","Подписи при наведении"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
|
||||
</>;
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import {useSimulationLayout} from "./useSimulationLayout";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Icon, IconButton } from "@nodedc/ui-react";
|
||||
import { Checker, Dropdown, SegmentedButton } 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;
|
||||
export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilityChange}: {
|
||||
worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;onVisibilityChange:(visible:boolean)=>void;
|
||||
}) {
|
||||
const [memory,setMemory]=useState<SpatialExperience|null>(null),[visible,setVisible]=useState(false);
|
||||
const [memory,setMemory]=useState<SpatialExperience|null>(null);
|
||||
const [layout,updateLayout]=useSimulationLayout();
|
||||
const visible=layout.memory,setVisible=(memory:boolean)=>updateLayout({memory});
|
||||
const [projected,setProjected]=useState<ScreenPoint[]>([]),[error,setError]=useState<string|null>(null);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||
@@ -22,10 +25,23 @@ export function PlannerExperience({worldId,worldSha,runtime,viewport}: {
|
||||
};
|
||||
void refresh();return ()=>{abort.abort();clearTimeout(timer);runtime.clearExperience();};
|
||||
},[worldId,worldSha,runtime]);
|
||||
useEffect(()=>runtime.showExperience(visible),[runtime,visible,memory]);
|
||||
useEffect(()=>{runtime.showExperience(visible);onVisibilityChange(visible&&!!memory);},[runtime,visible,memory,onVisibilityChange]);
|
||||
useEffect(()=>()=>onVisibilityChange(false),[onVisibilityChange]);
|
||||
return <>
|
||||
<IconButton label={error??(memory?`Память локации · посещено ${memory.visits.length} участков · ${memory.attempts.length} попыток`:"В этой локации ещё нет сохранённого опыта")}
|
||||
disabled={!memory} aria-pressed={visible} onClick={()=>setVisible(v=>!v)}><Icon name="database"/></IconButton>
|
||||
<Dropdown placement="bottom-start" width={340} surfaceRole="dialog"
|
||||
trigger={({open,toggle,setTriggerRef,surfaceId})=><SegmentedButton ref={setTriggerRef} aria-label="Память локации" active={visible||open}
|
||||
aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
|
||||
<div className="ai-polygon__layer-options">
|
||||
<strong>Память локации</strong>
|
||||
<p>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</p>
|
||||
{error?<p role="alert">{error}</p>:memory?<>
|
||||
<p>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</p>
|
||||
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
|
||||
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>}
|
||||
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p>
|
||||
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p>
|
||||
</div>
|
||||
</Dropdown>
|
||||
{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"];
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { GlassSurface, SegmentedControl } from "@nodedc/ui-react";
|
||||
import { URBAN_COLORS, URBAN_LABELS, availableUrbanClasses, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
|
||||
export function PlannerLegend({map,memory,selected,onChange,disabled=false}: {
|
||||
map:UrbanMap|null;memory:boolean;selected:readonly UrbanClassId[];
|
||||
onChange:(selected:UrbanClassId[])=>void;disabled?:boolean;
|
||||
}) {
|
||||
const classes=map?availableUrbanClasses(map):[];
|
||||
if(!classes.length&&!memory)return null;
|
||||
const swatch=(id:string)=><i className="ai-local-editor__legend-swatch" aria-hidden="true"
|
||||
style={{background:`rgb(${URBAN_COLORS[id].join(",")})`}}/>;
|
||||
return <div className="ai-local-editor__legend nodedc-scene-controls" inert={disabled}>
|
||||
{classes.length?<SegmentedControl label="Слои инфраструктуры" selectionMode="multiple"
|
||||
className="ai-local-editor__legend-controls" value={selected} onChange={onChange}
|
||||
items={classes.map(id=>({value:id,label:URBAN_LABELS[id],icon:swatch(id)}))}/>:null}
|
||||
{memory?<GlassSurface padding="sm" materialRim={false} aria-label="Легенда памяти">
|
||||
<span className="ai-inference-preview__legend">{[["visited","Проехал"],["attempt","Попытка проезда"],["revisited","Позже проехал"]].map(([id,label])=>
|
||||
<span key={id}>{swatch(id)}{label}</span>)}</span>
|
||||
</GlassSurface>:null}
|
||||
</div>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Application, BLEND_NORMAL, Color, Entity, Layer, StandardMaterial, Vec3 } from "playcanvas";
|
||||
import { Application, BLEND_NORMAL, Color, Entity, Layer, PROJECTION_ORTHOGRAPHIC, StandardMaterial, Vec3 } from "playcanvas";
|
||||
import { toEditor } from "../../core/simulation/aiEditor";
|
||||
import type { AiWaypoint } from "../../core/simulation/aiPolygon";
|
||||
import { axisWorldLength, DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
@@ -69,11 +69,14 @@ export class PlannerMarkers {
|
||||
if(point)this.centroid.setPosition(point.x,point.y,point.z);
|
||||
return changed;
|
||||
}
|
||||
private pixelLength(depth:number,pixels:number) {
|
||||
return this.camera.camera!.projection===PROJECTION_ORTHOGRAPHIC?2*this.camera.camera!.orthoHeight*pixels/Math.max(1,this.canvas.clientHeight):axisWorldLength(depth,this.canvas.clientHeight,pixels);
|
||||
}
|
||||
update(dt: number) {
|
||||
this.elapsed+=dt;
|
||||
if(this.centroid?.enabled) {
|
||||
const depth=this.centroid.getPosition().clone().sub(this.camera.getPosition()).dot(this.camera.forward);
|
||||
const size=axisWorldLength(depth,this.canvas.clientHeight,this.preferences.navigation.centroidPixels);
|
||||
const size=this.pixelLength(depth,this.preferences.navigation.centroidPixels);
|
||||
this.centroid.setLocalScale(size,size,size);
|
||||
}
|
||||
const w=this.preferences.waypoint,p=this.preferences.pivot;
|
||||
@@ -84,7 +87,7 @@ export class PlannerMarkers {
|
||||
const position=new Vec3(...toEditor(point.position));this.pivot.setPosition(position);
|
||||
const depth=position.clone().sub(this.camera.getPosition()).dot(this.camera.forward);
|
||||
this.pivot.enabled=depth>0;
|
||||
this.axisLength=axisWorldLength(depth,this.canvas.clientHeight,p.pixels);
|
||||
this.axisLength=this.pixelLength(depth,p.pixels);
|
||||
const unit=this.axisLength/p.pixels,tip=p.cone*unit,stem=this.axisLength-tip;
|
||||
for(const {axis,shaft,cone} of this.arrows) {
|
||||
const v=axis==="x"?new Vec3(1,0,0):axis==="y"?new Vec3(0,1,0):new Vec3(0,0,1);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
|
||||
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
import {PlannerCubeSettings} from "./PlannerCubeSettings";
|
||||
import {PlannerToolbarSettings} from "./PlannerToolbarSettings";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<HTMLDivElement|null>; onClose: () => void }) {
|
||||
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation">("pivot");
|
||||
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation"|"toolbar"|"cube">("pivot");
|
||||
const [saved,update] = usePlannerPreferences();
|
||||
const [value,setValue] = useState(saved);
|
||||
const [rect,setRect] = useState(()=>{
|
||||
@@ -38,13 +40,13 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
|
||||
window.removeEventListener("keydown",escape);
|
||||
};
|
||||
},[onClose]);
|
||||
const set = (group: "pivot"|"waypoint"|"navigation", key: string, next: string|number) => {
|
||||
const set = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, next: string|number|boolean) => {
|
||||
const base=pending.current??value;
|
||||
const changed={...base,[group]:{...base[group],[key]:next}};
|
||||
pending.current=changed;setValue(changed);
|
||||
if(!editing.current)commit();
|
||||
};
|
||||
const range = (group: "pivot"|"waypoint"|"navigation", key: string, label: string, min: number, max: number, step: number, unit: string) =>
|
||||
const range = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, label: string, min: number, max: number, step: number, unit: string) =>
|
||||
<RangeControl key={key} label={label} min={min} max={max} step={step}
|
||||
value={Number(value[group][key as keyof typeof value[typeof group]])} onChange={(v)=>set(group,key,v)}
|
||||
formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
|
||||
@@ -59,8 +61,8 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
|
||||
if((e.target as Element).matches('input[type="range"], [role="slider"]') && ["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(e.key))editing.current=true;
|
||||
}}>
|
||||
<Select label="Раздел настроек планировщика" value={section} onChange={setSection}
|
||||
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"}]}/>
|
||||
{section === "pivot" ? <>
|
||||
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"},{value:"toolbar",label:"Тулбар"},{value:"cube",label:"3D-куб"}]}/>
|
||||
{section === "cube" ? <PlannerCubeSettings value={value.cube} set={(key,v)=>set("cube",key,v)}/> : section === "toolbar" ? <PlannerToolbarSettings value={value.toolbar} set={(key,v)=>set("toolbar",key,v)}/> : section === "pivot" ? <>
|
||||
{range("pivot","pixels","Размер осей",50,220,5,"px")}
|
||||
{range("pivot","diameter","Диаметр стержня",2,16,1,"px")}
|
||||
{range("pivot","cone","Размер конусов",10,40,1,"px")}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import {Checker,ColorField,ControlRow,RangeControl,Select} from "@nodedc/ui-react";
|
||||
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
|
||||
type Settings=PlannerPreferences["toolbar"];
|
||||
export function PlannerToolbarSettings({value,set}:{value:Settings;set:(key:string,value:string|number|boolean)=>void}) {
|
||||
const range=(key:keyof Settings,label:string,min:number,max:number,step:number,unit:string)=><RangeControl label={label} value={Number(value[key])} min={min} max={max} step={step} onChange={v=>set(key,v)} formatValue={v=>`${unit==="с"?v/1000:v} ${unit}`}/>;
|
||||
return <>
|
||||
<Select label="Положение тулбара" value={value.placement} options={[{value:"left",label:"Слева"},{value:"right",label:"Справа"},{value:"top",label:"Сверху"},{value:"bottom",label:"Снизу"}]} onChange={v=>set("placement",v)}/>
|
||||
{range("minSize","Минимальный размер",18,42,1,"px")}
|
||||
{range("maxSize","Максимальный размер",value.minSize,88,1,"px")}
|
||||
{range("lensCount","Линза",1,13,2,"иконок")}
|
||||
{range("gap","Расстояние между кнопками",0,24,1,"px")}
|
||||
<Checker label="Автоскрытие" checked={value.autoHide} onChange={v=>set("autoHide",v)}/>
|
||||
{value.autoHide?range("hideDelay","Задержка скрытия",0,15000,250,"с"):null}
|
||||
{([["background","Фон"],["border","Рамка"],["outline","Подсветка"],["accent","Цвет инструментов"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {useEffect,useState} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {semanticPaths,semanticMembers,isRigidMarking} from "../../core/simulation/semanticEdits";
|
||||
import {curveControlScale,curveControlPoint} from "../../core/simulation/semanticCurveControls";
|
||||
import {editablePaths,knots} from "../../core/simulation/semanticVector";
|
||||
import {URBAN_COLORS} from "../../core/simulation/urbanMap";
|
||||
import {useSemanticGestures} from "./useSemanticGestures";
|
||||
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
|
||||
export type {SemanticChoice} from "./semanticEditorTypes";
|
||||
export function SemanticEditOverlay(props:SemanticOverlayProps) {
|
||||
const {runtime,viewport,map,original,layers,selected}=props;
|
||||
const [,redraw]=useState(0);
|
||||
const {hover,ghostMap,marquee,brush}=useSemanticGestures(props);
|
||||
useEffect(()=>{runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime]);
|
||||
const rect=viewport.querySelector("canvas")?.getBoundingClientRect();if(!rect)return null;
|
||||
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*rect.width,q[1]*rect.height]:null;};
|
||||
const line=(path:number[][])=>{const p=path.map(project);return p.map((v,i)=>v?`${i&&p[i-1]?"L":"M"}${v[0]},${v[1]}`:"").join(" ");};
|
||||
const selectedIds=new Set([...(selected?[selected.feature_id]:[]),...props.selection.map(v=>v.feature_id)]);
|
||||
const chosen=[...new Set([...selectedIds].flatMap(id=>semanticMembers(map,id)))],highlight=hover?semanticMembers(map,hover):[];
|
||||
const point=semanticAnchor(props),g=point?runtime.semanticGizmo(point):null,base=point?project(point):null;
|
||||
const featureColor=(id:string)=>`rgb(${(URBAN_COLORS[id]??URBAN_COLORS.road_boundary).join(",")})`;
|
||||
const color=featureColor(chosen[0]?.properties.class??layers.at(-1)??"road_boundary");
|
||||
const visible=map.features.filter(f=>layers.includes(f.properties.class as typeof layers[number])&&f.properties.review_status!=="rejected");
|
||||
const node=selected&&!selected.object&&chosen[0]&&!isRigidMarking(chosen[0])?knots(chosen[0],selected.path)[selected.index]:null;
|
||||
const handleScale=node?curveControlScale(knots(chosen[0],selected!.path),selected!.index,chosen[0].geometry.type==="Polygon",project):1;
|
||||
return createPortal(<svg className="ai-local-editor__markers" width="100%" height="100%" aria-label="Редактор контуров">
|
||||
{original?.features.filter(f=>f.properties.review_status!=="rejected").flatMap(f=>semanticPaths(f).map((r,i)=><path key={`${f.id}-${i}`} d={line(r)} fill="none" stroke={`rgb(${URBAN_COLORS[f.properties.class]?.join(",")??"255,255,255"})`} strokeWidth={1.5} strokeDasharray="5 5" opacity={.65}/>))}
|
||||
{visible.map(f=><g key={f.id} data-semantic-feature={f.id}>
|
||||
{semanticPaths(f).map((r,i)=><g key={i}>
|
||||
{chosen.includes(f)||highlight.includes(f)?<><path d={line(r)} fill="none" stroke="var(--nodedc-glass-panel-bg)" strokeWidth={6}/><path d={line(r)} fill="none" stroke={highlight.includes(f)?"var(--nodedc-text-primary)":featureColor(f.properties.class)} strokeWidth={3}/></>:null}
|
||||
</g>)}
|
||||
{props.editing&&!isRigidMarking(f)&&chosen.includes(f)?editablePaths(f).flatMap((r,i)=>r.slice(0,r.length-Number(f.geometry.type==="Polygon")).map((v,k)=>{const p=project(v);const active=props.selection.some(s=>!s.object&&s.feature_id===f.id&&s.path===i&&s.index===k);return p?<circle key={`${i}-${k}`} data-semantic-vertex={`${f.id}:${i}:${k}`} cx={p[0]} cy={p[1]} r={active?5:3} fill={active?"var(--nodedc-text-primary)":featureColor(f.properties.class)} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={1.5}/>:null;})):null}
|
||||
</g>)}
|
||||
{ghostMap?.features.map(f=><path key={f.id} d={semanticPaths(f).map(line).join(" ")} fill={color} fillRule="evenodd" fillOpacity={.4} stroke={color} strokeWidth={2}/>)}
|
||||
{brush.length?<><path d={line(brush)} fill="none" stroke={color} strokeWidth={2}/>{brush.map((v,i)=>{const p=project(v);return p?<circle key={i} cx={p[0]} cy={p[1]} r={i?3:6} fill={color}/>:null;})}</>:null}
|
||||
{marquee?<rect x={Math.min(marquee[0],marquee[2])} y={Math.min(marquee[1],marquee[3])} width={Math.abs(marquee[2]-marquee[0])} height={Math.abs(marquee[3]-marquee[1])} fill="var(--nodedc-text-primary)" fillOpacity={.1} stroke="var(--nodedc-text-primary)" strokeDasharray="4 3"/>:null}
|
||||
{props.editing&&!props.blocked&&base&&g?<g aria-label="Пивот перемещения">
|
||||
{(["x","y","z"] as const).map(axis=>{const end=g[axis];if(!end)return null;const p=[end[0]*rect.width,end[1]*rect.height],d=Math.hypot(p[0]-base[0],p[1]-base[1]);if(d<12)return null;
|
||||
const ux=(p[0]-base[0])/d,uy=(p[1]-base[1])/d;
|
||||
return <g key={axis} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
|
||||
<title>{`Переместить по ${axis.toUpperCase()}`}</title>
|
||||
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke="transparent" strokeWidth={18}/>
|
||||
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke={g.colors[axis]} strokeWidth={3}/>
|
||||
<path d={`M${p[0]},${p[1]} L${p[0]-ux*12-uy*5},${p[1]-uy*12+ux*5} L${p[0]-ux*12+uy*5},${p[1]-uy*12-ux*5} Z`} fill={g.colors[axis]}/>
|
||||
<text x={p[0]+7} y={p[1]-7} fill={g.colors[axis]} fontSize={12}>{axis.toUpperCase()}</text>
|
||||
</g>;
|
||||
})}
|
||||
<rect data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>{`Переместить: ${props.axis.toUpperCase()}`}</title></rect>
|
||||
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}><title>Повернуть элемент в плоскости</title></circle>:null}
|
||||
</g>:null}
|
||||
{props.editing&&node&&props.selection.length===1?(["incoming","outgoing"] as const).map(key=>{
|
||||
const a=project(node.point),b=project(curveControlPoint(node,key,handleScale));
|
||||
if(!a||!b||!node[key].some(Boolean))return null;
|
||||
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>Ручка кривой</title></circle></g>;
|
||||
}):null}
|
||||
</svg>,viewport);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import {useSimulationLayout} from "./useSimulationLayout";
|
||||
import {useEffect,useRef,useState} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {Button,Icon,IconButton,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
|
||||
import {URBAN_LABELS,availableUrbanClasses,visibleUrbanMap,type UrbanMap,type UrbanClassId} from "../../core/simulation/urbanMap";
|
||||
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticDraft,semanticOperation,semanticRequest,undoSemantic,
|
||||
type SemanticDraft,type SemanticOperation,type SemanticRevision,type Vertex} from "../../core/simulation/semanticEdits";
|
||||
import type {AiEditorRuntime} from "./AiEditorRuntime";
|
||||
import {SemanticEditOverlay,type SemanticChoice} from "./SemanticEditOverlay";
|
||||
import {SemanticTools} from "./SemanticTools";
|
||||
import type {SemanticTool} from "./semanticEditorTypes";
|
||||
import {duplicateIndex,type SemanticAxis} from "../../core/simulation/semanticVector";
|
||||
|
||||
export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,source,headerHost}:{
|
||||
headerHost:HTMLElement|null;worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;active:boolean;busy:boolean;source:UrbanMap;
|
||||
}) {
|
||||
const [revision,setRevision]=useState<SemanticRevision|null>(null);
|
||||
const [draft,setDraft]=useState<SemanticDraft|null>(null);
|
||||
const [error,setError]=useState<string|null>(null),[saving,setSaving]=useState(false);
|
||||
const [loading,setLoading]=useState(true);
|
||||
const [editing,setEditing]=useState(true);
|
||||
const [layout,updateLayout]=useSimulationLayout();
|
||||
const visible=layout.visible,setVisible=(v:typeof visible|((prior:typeof visible)=>typeof visible))=>updateLayout({visible:typeof v==="function"?v(visible):v});
|
||||
const [selection,setSelection]=useState<Vertex[]>([]),[wholeContour,setWholeContour]=useState(false);
|
||||
const selectVertices=(vertices:Vertex[],whole=false)=>{setSelection(vertices);setWholeContour(whole);};
|
||||
const axis=layout.axis,setAxis=(axis:SemanticAxis)=>updateLayout({axis});
|
||||
const areaMode=layout.areaMode,setAreaMode=(areaMode:typeof layout.areaMode)=>updateLayout({areaMode});
|
||||
const layers=layout.layers,setLayers=(layers:UrbanClassId[])=>updateLayout({layers});
|
||||
const selected=selection[0]??null;
|
||||
const setSelected=(v:Vertex|null)=>selectVertices(v?[v]:[]);
|
||||
const [choices,setChoices]=useState<SemanticChoice[]>([]);
|
||||
const [tool,setTool]=useState<SemanticTool>("select");
|
||||
const [template,setTemplate]=useState<string|null>(null);
|
||||
const [preview,setPreview]=useState<SemanticOperation|null>(null);
|
||||
const attempt=useRef<{key:string;signature:string}|null>(null);
|
||||
const current=useRef({draft,revision});current.current={draft,revision};
|
||||
const accept=(value:SemanticRevision)=>{
|
||||
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
|
||||
throw new Error("Правки относятся к другой сцене.");
|
||||
setRevision(value);setDraft(semanticDraft(value.edited));attempt.current=null;setSelected(null);
|
||||
|
||||
};
|
||||
useEffect(()=>{
|
||||
if(!active||revision)return;
|
||||
const abort=new AbortController();
|
||||
setLoading(true);setError(null);
|
||||
void semanticRequest(worldId,undefined,abort.signal).then(accept)
|
||||
.catch(e=>{if(!abort.signal.aborted)setError(e.message);})
|
||||
.finally(()=>{if(!abort.signal.aborted)setLoading(false);});
|
||||
return()=>abort.abort();
|
||||
},[active,worldId,worldSha,revision]);
|
||||
useEffect(()=>{if(active){setEditing(true);}},[active]);
|
||||
useEffect(()=>{runtime.setSemanticSelection(active&&editing);viewport.dataset.semanticEditing=String(active&&editing);
|
||||
return()=>{runtime.setSemanticSelection(false);delete viewport.dataset.semanticEditing;};},[runtime,viewport,active,editing]);
|
||||
const operate=(op:SemanticOperation)=>{
|
||||
if(busy||saving)return;
|
||||
try{const prior=current.current.draft!,next=commitSemantic(prior,op);setDraft(next);setError(null);
|
||||
if(op.kind==="duplicate_vertex"&&next!==prior)setSelected({feature_id:op.feature_id,path:op.path,index:duplicateIndex(op.index,prior.map.features.find(f=>f.id===op.feature_id)!.geometry.type==="Polygon",op.side)});
|
||||
if(op.kind==="duplicate_marking"&&next!==prior)setSelected({feature_id:op.new_feature_id,path:0,index:0,object:true});
|
||||
if(op.kind==="insert")setSelected({...op,index:op.index+1});
|
||||
}
|
||||
catch(e){setError((e as Error).message);}
|
||||
};
|
||||
const removeSelected=()=>{
|
||||
if(!selected||!draft)return;
|
||||
const f=draft.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
|
||||
operate(isRigidMarking(f)||selected.object?{kind:"remove",feature_id:f.id}:{kind:"delete_vertices",vertices:selection});setSelected(null);
|
||||
};
|
||||
const display=draft?.map??source;
|
||||
let overlay=display;
|
||||
if(preview)try{overlay=semanticOperation(display,preview);}catch{/* Retain the last valid preview. */}
|
||||
useEffect(()=>{
|
||||
if(!active)return;
|
||||
const hidden=editing&&selected&&preview?.kind!=="duplicate_marking"?semanticMembers(display,selected.feature_id):[];
|
||||
const rendered=hidden.length?{...display,features:display.features.filter(f=>!hidden.includes(f))}:display;
|
||||
runtime.setUrbanMap(rendered);runtime.setUrbanClasses(layers);runtime.showUrbanMap(visible.user);
|
||||
},[runtime,active,display,editing,selected?.feature_id,visible.user,preview?.kind,layers]);
|
||||
useEffect(()=>{
|
||||
if(!active)return;
|
||||
runtime.setAddMode(false);
|
||||
const keyboard=(e:KeyboardEvent)=>{
|
||||
if(!editing||busy||saving||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||document.querySelector('[data-dropdown-lineage]'))return;
|
||||
if((e.metaKey||e.ctrlKey)&&e.code==="KeyZ"){
|
||||
e.preventDefault();e.stopImmediatePropagation();setPreview(null);
|
||||
setDraft(s=>s?(e.shiftKey?redoSemantic(s):undoSemantic(s)):s);setSelected(null);
|
||||
}else if(!e.ctrlKey&&!e.metaKey&&["KeyV","KeyA","KeyP","KeyR"].includes(e.code)) {
|
||||
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id)),area=layers.some(id=>["pedestrian_area","sidewalk"].includes(id));
|
||||
if((e.code==="KeyA"&&!contours&&!selection.some(v=>{const f=display.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);}))||(["KeyP","KeyR"].includes(e.code)&&!area))return;
|
||||
e.preventDefault();e.stopImmediatePropagation();setTemplate(null);setTool(e.code==="KeyV"?"select":e.code==="KeyA"?"insert":e.code==="KeyP"?"pen":"rectangle");
|
||||
}else if((e.key==="Delete"||e.key==="Backspace")&&selected){
|
||||
e.preventDefault();e.stopImmediatePropagation();removeSelected();
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown",keyboard,true);
|
||||
return()=>document.removeEventListener("keydown",keyboard,true);
|
||||
},[active,editing,busy,saving,preview,selection,layers,viewport,runtime,display]);
|
||||
useEffect(()=>{
|
||||
if(!draft?.operations.length)return;
|
||||
const warn=(e:BeforeUnloadEvent)=>{e.preventDefault();};
|
||||
window.addEventListener("beforeunload",warn);return()=>window.removeEventListener("beforeunload",warn);
|
||||
},[draft?.operations.length]);
|
||||
const save=async()=>{
|
||||
const s=current.current;if(!s.draft?.operations.length||!s.revision||saving)return;
|
||||
const body={expected_revision:s.revision.revision,model_sha256:s.revision.model_sha256,operations:s.draft.operations};
|
||||
const signature=JSON.stringify(body);
|
||||
if(attempt.current?.signature!==signature)attempt.current={signature,key:crypto.randomUUID()};
|
||||
setSaving(true);setError(null);
|
||||
try{accept(await semanticRequest(worldId,{...body,request_id:attempt.current.key}));}
|
||||
catch(e){setError((e as Error).message);}
|
||||
finally{setSaving(false);}
|
||||
};
|
||||
if(!active)return null;
|
||||
const classes=availableUrbanClasses(display);
|
||||
if(!classes.includes("road_marking"))classes.push("road_marking");
|
||||
const overlaySelection=preview?.kind==="duplicate_marking"&&overlay!==display?[{feature_id:preview.new_feature_id,path:0,index:0,object:true as const}]:preview?.kind==="duplicate_vertex"&&overlay!==display?[{feature_id:preview.feature_id,path:preview.path,index:duplicateIndex(preview.index,display.features.find(f=>f.id===preview.feature_id)!.geometry.type==="Polygon",preview.side)}]:selection;
|
||||
const marking=layers.some(id=>["road_marking","crosswalk_marking"].includes(id));
|
||||
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id));
|
||||
const chooseTool=(next:SemanticTool)=>{setTool(next);setTemplate(null);setPreview(null);};
|
||||
const undo=()=>{setDraft(s=>s?undoSemantic(s):s);setSelected(null);};
|
||||
const redo=()=>{setDraft(s=>s?redoSemantic(s):s);setSelected(null);};
|
||||
const controls=<>
|
||||
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing}
|
||||
onClick={()=>{setEditing(v=>!v);setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
|
||||
{draft?.operations.length?<IconButton label="Сохранить правки" title="Сохранить правки" loading={saving} onClick={()=>void save()}><Icon name="save"/></IconButton>:null}
|
||||
</>;
|
||||
return <>
|
||||
{headerHost?createPortal(controls,headerHost):null}
|
||||
{!revision?<Button loading={loading} onClick={()=>{setLoading(true);setError(null);void semanticRequest(worldId).then(accept).catch(e=>setError(e.message)).finally(()=>setLoading(false));}}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
|
||||
{revision?<SemanticTools viewport={viewport} editing={editing&&visible.user&&layers.length>0&&!busy&&!saving} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
|
||||
area={layers.some(id=>["pedestrian_area","sidewalk"].includes(id))} template={template} setTemplate={id=>{setTemplate(id);setSelected(null);setTool("select");}}
|
||||
selection={selection} map={display} operate={operate} remove={removeSelected} undo={undo} redo={redo} canUndo={!!draft?.operations.length} canRedo={!!draft?.future.length}
|
||||
axis={axis} setAxis={setAxis} visible={visible} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
|
||||
{createPortal(<div className="ai-local-editor__legend nodedc-scene-controls">
|
||||
{classes.length?<SegmentedControl label="Видимые и редактируемые слои" selectionMode="multiple" value={layers} onChange={v=>{setLayers(v);setSelection(s=>s.filter(x=>v.includes(display.features.find(f=>f.id===x.feature_id)?.properties.class as UrbanClassId)));chooseTool("select");}}
|
||||
items={classes.map(id=>({value:id,label:URBAN_LABELS[id]}))}/>:null}
|
||||
</div>,viewport)}
|
||||
<SemanticEditOverlay runtime={runtime} viewport={viewport} map={visibleUrbanMap(overlay,visible.user?layers:[])}
|
||||
original={visible.model&&revision?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
|
||||
editing={editing&&visible.user&&layers.length>0} blocked={busy||saving} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
|
||||
axis={axis} areaMode={areaMode} onSelect={setSelected} onSelection={selectVertices} onChoose={setChoices} onOperation={operate} onPreview={setPreview} onError={setError}
|
||||
onExit={()=>{setEditing(false);setSelected(null);chooseTool("select");}}/>
|
||||
<Window open={choices.length>0} onClose={()=>setChoices([])} title="Выберите контур">
|
||||
{choices.map(({vertex,selection,wholeContour,operation},index)=><Button key={vertex.feature_id} onClick={()=>{selectVertices(selection,wholeContour);if(operation)operate(operation);setChoices([]);}}>{URBAN_LABELS[display.features.find(f=>f.id===vertex.feature_id)?.properties.class as UrbanClassId]} · {index+1}</Button>)}
|
||||
</Window>
|
||||
<ToastStack items={error?[{id:"semantic",tone:"error",title:"Не удалось выполнить действие",description:error}]:[]} onDismiss={()=>setError(null)}/>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {Button,Checker,Toolbar,type ToolbarItem} from "@nodedc/ui-react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {MARKING_TEMPLATES,isEditableMarking,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
|
||||
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
|
||||
import type {UrbanMap} from "../../core/simulation/urbanMap";
|
||||
import type {SemanticTool} from "./semanticEditorTypes";
|
||||
import {usePlannerPreferences} from "./usePlannerPreferences";
|
||||
export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:SemanticTool;setTool:(v:SemanticTool)=>void;marking:boolean;contours:boolean;area:boolean;template:string|null;setTemplate:(v:string)=>void;
|
||||
selection:Vertex[];map:UrbanMap;operate:(op:SemanticOperation)=>void;remove:()=>void;undo:()=>void;redo:()=>void;canUndo:boolean;canRedo:boolean;axis:SemanticAxis;setAxis:(v:SemanticAxis)=>void;
|
||||
visible:{model:boolean;user:boolean};setVisible:(v:{model:boolean;user:boolean})=>void;areaMode:"union"|"difference";setAreaMode:(m:"union"|"difference")=>void;onError:(s:string)=>void}) {
|
||||
const [prefs,update]=usePlannerPreferences();
|
||||
const items:ToolbarItem[]=[{id:"hold",label:prefs.toolbar.autoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!prefs.toolbar.autoHide,onSelect:()=>{try{update({...prefs,toolbar:{...prefs.toolbar,autoHide:!prefs.toolbar.autoHide}});}catch{p.onError("Не удалось сохранить закрепление тулбара.");}}}];
|
||||
const editableMarking=p.selection.some(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);});
|
||||
const menu=(children:React.ReactNode)=><div className="semantic-tools__menu">{children}</div>;
|
||||
if(p.editing){
|
||||
items.push({id:"select",label:"Выделение",shortcut:"V",icon:"select",active:p.tool==="select"&&!p.template,onSelect:()=>p.setTool("select")});
|
||||
if(p.contours||editableMarking)items.push({id:"insert",label:"Добавить точку на контур",shortcut:"A",icon:"add-point",active:p.tool==="insert",onSelect:()=>p.setTool("insert")});
|
||||
if(p.area){
|
||||
items.push({id:"pen",label:"Перо: замкните контур или Enter",shortcut:"P",icon:"pen",active:p.tool==="pen",onSelect:()=>p.setTool("pen")},
|
||||
{id:"rectangle",label:"Прямоугольник: два противоположных угла",shortcut:"R",icon:"rectangle",active:p.tool==="rectangle",onSelect:()=>p.setTool("rectangle")},
|
||||
{id:"area-mode",label:"Действие области",icon:p.areaMode==="union"?"plus":"trash",onSelect:()=>{},menu:close=>menu(([['union','Заполнить область'],['difference','Вырезать область']] as const).map(([id,label])=><Button key={id} width="full" variant={p.areaMode===id?"primary":"secondary"} tone="neutral" aria-pressed={p.areaMode===id} onClick={()=>{p.setAreaMode(id);close();}}>{label}</Button>))});
|
||||
}
|
||||
items.push({id:"axes",label:`Оси перемещения: ${p.axis.toUpperCase()}`,icon:"target",onSelect:()=>{},menu:close=>menu((["x","y","z","xy","xz","yz"] as const).map(axis=><Button key={axis} width="full" variant={p.axis===axis?"primary":"secondary"} tone="neutral" aria-pressed={p.axis===axis} onClick={()=>{p.setAxis(axis);close();}}>{axis.toUpperCase()}</Button>))});
|
||||
if(p.selection.length===1&&!p.selection[0].object){
|
||||
const v=p.selection[0],f=p.map.features.find(f=>f.id===v.feature_id),nodes=f?knots(f,v.path):[],n=nodes[v.index];
|
||||
const curved=!!n&&[...n.incoming,...n.outgoing].some(Boolean);
|
||||
if(n)items.push({id:"properties",label:"Свойства точки",icon:"curve",onSelect:()=>{},menu:close=>menu(<>
|
||||
<Button width="full" variant={!curved?"primary":"secondary"} tone="neutral" aria-pressed={!curved} onClick={()=>{p.operate({...v,kind:"curve",incoming:[0,0],outgoing:[0,0]});close();}}>Угловая точка</Button>
|
||||
<Button width="full" variant={curved?"primary":"secondary"} tone="neutral" aria-pressed={curved} onClick={()=>{
|
||||
const closed=f!.geometry.type==="Polygon",prev=nodes[v.index-1]??(closed?nodes.at(-1)!:n),next=nodes[v.index+1]??(closed?nodes[0]:n);
|
||||
const tangent=next.point.slice(0,2).map((a,k)=>a-prev.point[k]),length=Math.hypot(...tangent)||1;
|
||||
const before=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-prev.point[k]))/3,after=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-next.point[k]))/3;
|
||||
p.operate({...v,kind:"curve",incoming:tangent.map(x=>-x/length*before),outgoing:tangent.map(x=>x/length*after)});close();
|
||||
}}>Кривая с ручками</Button>
|
||||
</>)});
|
||||
}
|
||||
if(p.selection.length)items.push({id:"delete",label:"Удалить выделенное",shortcut:"Delete",icon:"trash",onSelect:p.remove});
|
||||
if(p.canUndo)items.push({id:"undo",label:"Отменить",shortcut:"Control+Z Meta+Z",icon:"undo",onSelect:p.undo});
|
||||
if(p.canRedo)items.push({id:"redo",label:"Повторить",shortcut:"Control+Shift+Z Meta+Shift+Z",icon:"redo",onSelect:p.redo});
|
||||
}
|
||||
items.push({id:"visibility",label:"Видимость разметки",icon:"eye",onSelect:()=>{},menu:menu(<>
|
||||
<Checker label="Алгоритмическая разметка" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>
|
||||
<Checker label="Ручная разметка" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
|
||||
</>)}, {id:"quality",label:"Качество Gaussian-сцены",icon:"sliders",onSelect:()=>{},menu:close=>menu(([["low","Низкое"],["medium","Среднее"],["high","Высокое"],["ultra","Ультра"],["maximum","Максимум"]] as const).map(([quality,label])=><Button key={quality} width="full" variant={prefs.quality===quality?"primary":"secondary"} tone="neutral" aria-pressed={prefs.quality===quality} onClick={()=>{try{update({...prefs,quality});close();}catch{p.onError("Не удалось сохранить качество.");}}}>{label}</Button>))});
|
||||
if(p.editing&&p.marking)items.push({id:"marking",label:"Добавить элемент разметки",icon:"plus",active:!!p.template,onSelect:()=>{},menu:close=>menu(MARKING_TEMPLATES.templates.filter(t=>!(t as {hidden?:boolean}).hidden).map(t=><Button key={t.id} width="full" onClick={()=>{p.setTemplate(t.id);close();}}>{t.label}</Button>))});
|
||||
return createPortal(<Toolbar container={p.viewport} {...prefs.toolbar} label="Инструменты семантики" items={items}/>,p.viewport);
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{
|
||||
const show=(id:string,checked:boolean)=>setLayout(value=>({...value,catalogVisible:checked?[...new Set([...(value.catalogVisible??[]),id])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:checked?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key==='Escape'&&effectiveFull&&!document.querySelector('[role=dialog],[role=listbox]')){setFull(null);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull]);
|
||||
return <div className="ai-polygon__observation">
|
||||
<div className="ai-polygon__observation-toolbar">
|
||||
<div className="ai-polygon__observation-toolbar nodedc-viewport-controls">
|
||||
{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}
|
||||
<Dropdown placement="bottom-end" width={340} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><Button ref={setTriggerRef} icon={<Icon name="layers"/>} aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Камеры и слои</Button>}>
|
||||
{({close})=><div className="ai-polygon__layer-options" role="group" aria-label="Камеры и слои">
|
||||
|
||||
@@ -3,26 +3,30 @@ import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { PlannerSettings } from "./PlannerSettings";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
|
||||
export function SimulationViewTools({expanded,toggle,planning=false,boundsRef,children}: {expanded:boolean;toggle:()=>void;planning?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
|
||||
export function SimulationViewTools({expanded,toggle,semantic=false,planning=false,routeEditing=planning,boundsRef,children}: {expanded:boolean;toggle:()=>void;semantic?:boolean;planning?:boolean;routeEditing?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
|
||||
const [prefs,update]=usePlannerPreferences();
|
||||
const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
return <>
|
||||
<div className="ai-simulation__view-tools nodedc-scene-controls">
|
||||
{children}
|
||||
<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
|
||||
<div className={`ai-simulation__view-tools nodedc-scene-controls ${planning?"ai-simulation__view-tools--planning":""}`}>
|
||||
{!planning?children:null}
|
||||
<div className="ai-simulation__display-tools">
|
||||
{!semantic?<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
|
||||
options={[{value:"low",label:"Низкое"},{value:"medium",label:"Среднее"},{value:"high",label:"Высокое"},{value:"ultra",label:"Ультра"},{value:"maximum",label:"Максимум"}]}
|
||||
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>
|
||||
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>:null}
|
||||
<IconButton label="Помощь по управлению" onClick={()=>setHelp(true)}><Icon name="info"/></IconButton>
|
||||
{planning?<IconButton label="Настройки планировщика" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
|
||||
{planning?<IconButton label="Настройки сцены" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
|
||||
<IconButton label={expanded?"Свернуть просмотр":"Развернуть просмотр"} onClick={toggle}><Icon name={expanded?"minimize":"expand"}/></IconButton>
|
||||
</div>
|
||||
{planning?children:null}
|
||||
</div>
|
||||
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
|
||||
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
|
||||
<div className="ai-polygon__form">{planning?<>
|
||||
<p>ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.</p>
|
||||
<p>Прокрутка — зум к курсору, в том числе в режиме добавления точек.</p>
|
||||
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p>
|
||||
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p>
|
||||
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
|
||||
<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>
|
||||
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null}
|
||||
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null}
|
||||
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
|
||||
</Window>
|
||||
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
|
||||
@@ -258,7 +258,7 @@ export function SimulationViewport({
|
||||
</StatusBadge>
|
||||
<span>Engine 2.21.4</span>
|
||||
</div>
|
||||
<div className="simulation-viewport__controls">
|
||||
<div className="simulation-viewport__controls nodedc-viewport-controls">
|
||||
<Select
|
||||
label="Качество Gaussian-сцены"
|
||||
value={quality}
|
||||
|
||||
@@ -13,7 +13,7 @@ export function localScene(cache: EditorCache): SimulationWorldManifest {
|
||||
return {
|
||||
schemaVersion: "missioncore.simulation-world-manifest/v1", projectId: cache.world.world_id,
|
||||
visual: { previewSogUrl: null, streamedSogUrl: saved?.visual_url ?? editorAssetUrl(cache.key,"scene.sog") },
|
||||
collision: { meshUrl: saved?.collision_url ?? editorAssetUrl(cache.key,"collision.glb"), available: true },
|
||||
collision: { meshUrl: saved ? saved.collision_url : editorAssetUrl(cache.key,"collision.glb"), available: saved ? !!saved.collision_url : true },
|
||||
transforms: { worldFromVisual: Array.from(visual.data),
|
||||
worldFromCollision: Array.from((saved ? matrix(saved.collision_rotation) : new Mat4()).data) },
|
||||
};
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {UrbanClassId,UrbanMap} from "../../core/simulation/urbanMap";
|
||||
import {isRigidMarking,semanticMembers,semanticPivot,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
|
||||
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
|
||||
import type {AiEditorRuntime} from "./AiEditorRuntime";
|
||||
export type SemanticTool="select"|"insert"|"pen"|"rectangle";
|
||||
export type SemanticChoice={vertex:Vertex;selection:Vertex[];wholeContour?:boolean;operation?:SemanticOperation};
|
||||
export interface SemanticOverlayProps {
|
||||
runtime:AiEditorRuntime;viewport:HTMLElement;map:UrbanMap;original:UrbanMap|null;layers:readonly UrbanClassId[];
|
||||
selected:Vertex|null;selection:Vertex[];wholeContour?:boolean;editing:boolean;blocked:boolean;tool:SemanticTool;template:string|null;
|
||||
axis:SemanticAxis;areaMode:"union"|"difference";
|
||||
onSelect:(v:Vertex|null)=>void;onSelection:(v:Vertex[],wholeContour?:boolean)=>void;onChoose:(v:SemanticChoice[])=>void;
|
||||
onPlaced:()=>void;onOperation:(op:SemanticOperation)=>void;onPreview:(op:SemanticOperation|null)=>void;
|
||||
onError:(message:string)=>void;onExit:()=>void;
|
||||
}
|
||||
export function semanticAnchor(p:SemanticOverlayProps) {
|
||||
const members=p.selected?semanticMembers(p.map,p.selected.feature_id):[];if(!members.length)return null;
|
||||
if(isRigidMarking(members[0])||p.selected?.object)return semanticPivot(members);
|
||||
const points=p.selection.flatMap(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);const q=f?knots(f,v.path)[v.index]?.point:null;return q?[q]:[];});
|
||||
return points.length?[0,1,2].map(k=>points.reduce((n,q)=>n+q[k],0)/points.length):null;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import {curveControlScale,moveCurveControl} from "../../core/simulation/semanticCurveControls";
|
||||
import {useEffect,useRef,useState} from "react";
|
||||
import {isMarking,isRigidMarking,semanticOperation,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
|
||||
import {semanticHits,semanticHitSelection} from "../../core/simulation/semanticPicking";
|
||||
import {duplicateSide,editablePaths,knots,type SemanticAxis} from "../../core/simulation/semanticVector";
|
||||
import {regionOperation} from "../../core/simulation/semanticArea";
|
||||
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
|
||||
export function useSemanticGestures(props:SemanticOverlayProps) {
|
||||
const latest=useRef(props);latest.current=props;
|
||||
const [hover,setHover]=useState<string|null>(null),[ghost,setGhost]=useState<SemanticOperation|null>(null);
|
||||
const [marquee,setMarquee]=useState<number[]|null>(null),[brush,setBrush]=useState<number[][]>([]);
|
||||
useEffect(()=>{
|
||||
const {runtime,viewport}=props,canvas=viewport.querySelector("canvas")!;
|
||||
let generation=0,disposed=false,picking=false,pending:number[]|null=null,placing=false;
|
||||
let shape:number[][]=[],rectangle:number[]|null=null,orbit:number|null=null;
|
||||
let box:{id:number;start:number[];shift:boolean}|null=null;
|
||||
let drag:{id:number;point:number[];start:number[];screen:number[];axis:SemanticAxis|"rotate";op:SemanticOperation|null;selected:Vertex;selection:Vertex[];map:SemanticOverlayProps["map"];handle?:"incoming"|"outgoing";handleScale?:number;handleStart?:number[];duplicate?:Vertex;copy?:{feature_id:string;new_feature_id:string}}|null=null;
|
||||
const stop=(e:Event)=>{e.preventDefault();e.stopImmediatePropagation();};
|
||||
const screen=(e:PointerEvent)=>{const r=canvas.getBoundingClientRect();return [e.clientX-r.left,e.clientY-r.top];};
|
||||
const norm=(e:PointerEvent)=>{const xy=screen(e);return [xy[0]/canvas.clientWidth,xy[1]/canvas.clientHeight];};
|
||||
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*canvas.clientWidth,q[1]*canvas.clientHeight]:null;};
|
||||
const hits=(e:PointerEvent)=>semanticHits(latest.current.map,latest.current.layers,screen(e),project,latest.current.tool==="select",latest.current.selection.map(v=>v.feature_id));
|
||||
const focus=()=>canvas.focus({preventScroll:true});
|
||||
const place=(position:number[],id:string):Extract<SemanticOperation,{kind:"place"}>=>({kind:"place",feature_id:id,template_id:latest.current.template!,position,surface:"gaussian-visual"});
|
||||
const pick=async()=>{
|
||||
if(picking||!pending)return;const xy=pending;pending=null;picking=true;const version=generation;
|
||||
try{const point=await runtime.pickSemanticSurface(xy[0],xy[1]);
|
||||
if(!disposed&&version===generation&&latest.current.template)setGhost(point?place(point,"user-preview-placement"):null);
|
||||
}catch{if(!disposed)setGhost(null);}finally{picking=false;if(pending&&!disposed)void pick();}
|
||||
};
|
||||
const release=(id:number)=>{if(viewport.hasPointerCapture(id))viewport.releasePointerCapture(id);};
|
||||
const finish=(cancel:boolean)=>{
|
||||
const d=drag;drag=null;latest.current.onPreview(null);
|
||||
if(d){if(!cancel&&d.op)latest.current.onOperation(d.op);release(d.id);}
|
||||
if(box){const id=box.id;box=null;release(id);}setMarquee(null);
|
||||
runtime.setNavigation(!latest.current.blocked);
|
||||
};
|
||||
const commitShape=(points:number[][])=>{
|
||||
try{const p=latest.current,f=p.map.features.find(f=>f.id===p.selected?.feature_id&&["pedestrian_area","sidewalk"].includes(f.properties.class));
|
||||
p.onOperation(regionOperation(f,[...points,points[0]],p.areaMode));
|
||||
}catch(e){latest.current.onError((e as Error).message);}
|
||||
shape=[];rectangle=null;setBrush([]);
|
||||
};
|
||||
const beginDrag=(e:PointerEvent,p:SemanticOverlayProps,selected:Vertex,selection:Vertex[],activeAxis:SemanticAxis|"rotate",handle?:"incoming"|"outgoing")=>{
|
||||
const f=p.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
|
||||
const copy=e.shiftKey&&!handle&&activeAxis!=="rotate"&&isMarking(f)&&(isRigidMarking(f)||selected.object);
|
||||
const duplicate=e.shiftKey&&!handle&&activeAxis!=="rotate"&&!copy&&!isRigidMarking(f);
|
||||
if(duplicate&&selection.length!==1){stop(e);p.onError("Для продолжения сплайна выберите одну точку.");return;}
|
||||
const point=semanticAnchor({...p,selected,selection});if(!point)return;
|
||||
const [x,y]=norm(e),start=runtime.moveSemantic(point,x,y,activeAxis==="rotate"?"xy":activeAxis);if(!start)return;
|
||||
stop(e);focus();drag={id:e.pointerId,point,start,screen:screen(e),axis:activeAxis,op:null,selected,selection,map:p.map,handle,
|
||||
duplicate:duplicate?{feature_id:selected.feature_id,path:selected.path,index:selected.index}:undefined,
|
||||
copy:copy?{feature_id:selected.feature_id,new_feature_id:`user-${crypto.randomUUID()}`}:undefined};
|
||||
if(handle){const nodes=knots(f,selected.path);drag.handleScale=curveControlScale(nodes,selected.index,f.geometry.type==="Polygon",project);drag.handleStart=nodes[selected.index][handle];}
|
||||
runtime.setNavigation(false);viewport.setPointerCapture(e.pointerId);
|
||||
};
|
||||
const down=(e:PointerEvent)=>{
|
||||
const p=latest.current;if(!p.editing||p.blocked)return;
|
||||
const target=e.target as Element,[x,y]=norm(e);
|
||||
if(e.ctrlKey&&[0,2].includes(e.button)&&(target===canvas||target.closest("[data-semantic-axis],[data-semantic-handle]"))){
|
||||
if(drag||box)return;
|
||||
generation++;pending=null;setGhost(null);setHover(null);orbit=e.pointerId;
|
||||
e.preventDefault();return; // Bubble to EditorCamera; never edit during this gesture.
|
||||
}
|
||||
if(e.button!==0)return;
|
||||
const axis=target.closest<SVGElement>("[data-semantic-axis]")?.dataset.semanticAxis as SemanticAxis|"rotate"|undefined;
|
||||
const handle=target.closest<SVGElement>("[data-semantic-handle]")?.dataset.semanticHandle as "incoming"|"outgoing"|undefined;
|
||||
if((axis||handle)&&p.selected){
|
||||
beginDrag(e,p,p.selected,p.selection,handle?"xy":axis!,handle);return;
|
||||
}
|
||||
if(e.target!==canvas)return;stop(e);focus();
|
||||
if(p.template){
|
||||
if(placing)return;placing=true;generation++;pending=null;const version=generation;
|
||||
void runtime.pickSemanticSurface(x,y).then(point=>{
|
||||
if(!disposed&&version===generation&&point){const op=place(point,`user-${crypto.randomUUID()}`);p.onOperation(op);p.onSelect({feature_id:op.feature_id,path:0,index:0,object:true});p.onPlaced();setGhost(null);}
|
||||
}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
|
||||
}
|
||||
if(p.tool==="pen"||p.tool==="rectangle"){
|
||||
if(shape.length>=128){p.onError("Замкните область: не более 128 точек за один контур.");return;}
|
||||
const first=shape[0]?project(shape[0]):null;
|
||||
if(p.tool==="pen"&&shape.length>=3&&first&&Math.hypot(screen(e)[0]-first[0],screen(e)[1]-first[1])<12){commitShape(shape);return;}
|
||||
const version=generation;
|
||||
if(p.tool==="rectangle"&&rectangle){const q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)commitShape([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]]]);return;}
|
||||
if(placing)return;placing=true;
|
||||
void runtime.pickSemanticSurface(x,y).then(point=>{if(!disposed&&version===generation&&point){
|
||||
if(p.tool==="rectangle")rectangle=point;shape=[...shape,point];setBrush(shape);
|
||||
}}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
|
||||
}
|
||||
const options=hits(e);
|
||||
if(!options.length){box={id:e.pointerId,start:screen(e),shift:e.shiftKey};viewport.setPointerCapture(e.pointerId);return;}
|
||||
const best=options[0],near=options.filter(c=>!!c.point===!!best.point&&c.distance<=best.distance+2);
|
||||
const ids=[...new Set(near.map(c=>c.vertex.feature_id))];
|
||||
const choice=(h:typeof best)=>{
|
||||
const s=h.segment,t=s?s.start+(s.end-s.start)*runtime.semanticSegmentParameter(s.a,s.b,s.t):h.t;
|
||||
const selection=p.tool==="select"?semanticHitSelection(p.map,h):[h.vertex],vertex=selection[0];
|
||||
return {vertex,selection,wholeContour:p.tool==="select"&&!h.point&&!vertex.object,operation:p.tool==="insert"&&t>0&&t<1?{...h.vertex,kind:"insert" as const,t}:undefined};
|
||||
};
|
||||
if(ids.length>1){p.onChoose(ids.map(id=>choice(near.find(c=>c.vertex.feature_id===id)!)));return;}
|
||||
const picked=choice(best),vertex=picked.vertex;
|
||||
if(p.tool==="select"&&!best.point&&!vertex.object){
|
||||
const selection=e.shiftKey?[...p.selection.filter(v=>!v.object),...picked.selection]:picked.selection;
|
||||
p.onSelection([...new Map(selection.map(v=>[JSON.stringify(v),v])).values()],!e.shiftKey);
|
||||
}else if(e.shiftKey&&p.tool==="select"&&!vertex.object){
|
||||
const previous=p.selection.filter(v=>!v.object),exists=previous.some(v=>JSON.stringify(v)===JSON.stringify(vertex));p.onSelection(exists?previous.filter(v=>JSON.stringify(v)!==JSON.stringify(vertex)):[...previous,vertex]);
|
||||
}else if(p.tool==="select"&&best.point){
|
||||
const selected=!p.wholeContour&&p.selection.some(v=>!v.object&&v.feature_id===vertex.feature_id&&v.path===vertex.path&&v.index===vertex.index)?p.selection:[vertex];
|
||||
p.onSelection(selected);beginDrag(e,p,vertex,selected,p.axis);
|
||||
}else p.onSelect(vertex);
|
||||
if(p.tool==="insert"&&choice(best).operation)p.onOperation(choice(best).operation!);
|
||||
};
|
||||
const move=(e:PointerEvent)=>{
|
||||
if(orbit===e.pointerId)return;
|
||||
const p=latest.current;
|
||||
if(box&&e.pointerId===box.id){stop(e);setMarquee([...box.start,...screen(e)]);return;}
|
||||
if(!drag){
|
||||
if(!p.editing||p.blocked||e.target!==canvas){setHover(null);return;}
|
||||
if(rectangle){const [x,y]=norm(e),q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)setBrush([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]],rectangle]);return;}
|
||||
if(p.template){pending=norm(e);void pick();}else setHover(hits(e)[0]?.vertex.feature_id??null);return;
|
||||
}
|
||||
if(e.pointerId!==drag.id)return;if(p.blocked){finish(true);return;}stop(e);
|
||||
if(Math.hypot(...screen(e).map((v,k)=>v-drag!.screen[k]))<2){drag.op=null;p.onPreview(null);return;}
|
||||
const [x,y]=norm(e),q=runtime.moveSemantic(drag.point,x,y,drag.axis==="rotate"?"xy":drag.axis);if(!q)return;
|
||||
const selected=drag.selected,selection=drag.selection,map=drag.map;
|
||||
if(drag.handle){const f=map.features.find(f=>f.id===selected.feature_id)!;const node=knots(f,selected.path)[selected.index];
|
||||
const value=moveCurveControl(drag.handleStart!,drag.start,q,drag.handleScale!);
|
||||
drag.op={kind:"curve",...selected,incoming:drag.handle==="incoming"?value:node.incoming,outgoing:drag.handle==="outgoing"?value:node.outgoing};
|
||||
}else if(drag.axis==="rotate"){
|
||||
const angle=Math.atan2(q[1]-drag.point[1],q[0]-drag.point[0])-Math.atan2(drag.start[1]-drag.point[1],drag.start[0]-drag.point[0]);
|
||||
drag.op={kind:"transform",feature_id:selected.feature_id,delta:[0,0],angle};
|
||||
}else {
|
||||
const delta=q.map((v,k)=>drag!.axis.includes("xyz"[k])?v-drag!.start[k]:0);
|
||||
drag.op=drag.copy?{kind:"duplicate_marking",...drag.copy,axis:drag.axis,delta}:drag.duplicate?{kind:"duplicate_vertex",...drag.duplicate,axis:drag.axis,delta,
|
||||
side:duplicateSide(knots(map.features.find(f=>f.id===drag!.duplicate!.feature_id)!,drag.duplicate.path),drag.duplicate.index,map.features.find(f=>f.id===drag!.duplicate!.feature_id)!.geometry.type==="Polygon",delta)}:
|
||||
{kind:!selected.object?"translate_vertices":"translate",feature_id:selected.feature_id,vertices:selection.filter(v=>!v.object),axis:drag.axis,delta};
|
||||
}
|
||||
p.onPreview(drag.op);
|
||||
};
|
||||
const up=(e:PointerEvent)=>{
|
||||
if(orbit===e.pointerId){orbit=null;return;}
|
||||
if(box&&box.id===e.pointerId){stop(e);const p=latest.current,end=screen(e),start=box.start;
|
||||
const selected:Vertex[]=box.shift?p.selection.filter(v=>!v.object):[];
|
||||
if(Math.hypot(end[0]-start[0],end[1]-start[1])>3)for(const f of p.map.features){
|
||||
if(!p.layers.includes(f.properties.class as typeof p.layers[number])||f.properties.review_status==="rejected"||isRigidMarking(f))continue;
|
||||
editablePaths(f).forEach((path,j)=>path.slice(0,path.length-Number(f.geometry.type==="Polygon")).forEach((v,i)=>{
|
||||
const q=project(v);if(q&&q.every((v,k)=>v>=Math.min(start[k],end[k])&&v<=Math.max(start[k],end[k])))selected.push({feature_id:f.id,path:j,index:i});
|
||||
}));
|
||||
}
|
||||
p.onSelection([...new Map(selected.map(v=>[JSON.stringify(v),v])).values()]);finish(true);
|
||||
}else if(drag&&e.pointerId===drag.id){stop(e);finish(false);}
|
||||
};
|
||||
const cancel=()=>{orbit=null;generation++;pending=null;finish(true);shape=[];rectangle=null;setBrush([]);setGhost(null);};
|
||||
const key=(e:KeyboardEvent)=>{
|
||||
const p=latest.current;if(!p.editing||p.blocked||e.defaultPrevented)return;
|
||||
if(e.key==="Escape"){
|
||||
// Dropdown gets the first Escape. Editor owns placement even after focus left canvas.
|
||||
if(document.querySelector('[data-dropdown-lineage]'))return;
|
||||
stop(e);
|
||||
if(drag||box||shape.length||p.template||p.tool!=="select"){cancel();p.onPlaced();}
|
||||
else if(p.selection.length)p.onSelection([]);else p.onExit();
|
||||
}else if(e.key==="Enter"&&shape.length>=3){stop(e);commitShape(shape);}
|
||||
};
|
||||
const leave=()=>{if(!drag&&!box){generation++;pending=null;setGhost(null);setHover(null);}};
|
||||
viewport.addEventListener("pointerdown",down,true);viewport.addEventListener("pointermove",move,true);viewport.addEventListener("pointerup",up,true);
|
||||
viewport.addEventListener("pointercancel",cancel,true);viewport.addEventListener("pointerleave",leave);document.addEventListener("keydown",key,true);
|
||||
window.addEventListener("blur",cancel);
|
||||
return()=>{disposed=true;cancel();viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
|
||||
},[props.runtime,props.viewport,props.editing,props.tool,props.template,props.layers]);
|
||||
const ghostMap=ghost?semanticOperation({...props.map,features:[]},ghost):null;
|
||||
return {hover,ghostMap,marquee,brush};
|
||||
}
|
||||
@@ -6,7 +6,7 @@ export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>)
|
||||
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
|
||||
const escape = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return;
|
||||
if (view.current.querySelector('[role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
|
||||
if (view.current.querySelector('[data-semantic-editing="true"], [role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void document.exitFullscreen().catch(() => undefined);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import {useSyncExternalStore} from "react";
|
||||
import {normalizeSimulationLayout,normalizeSceneView,type SimulationLayout,type SceneView} from "../../core/simulation/simulationLayout";
|
||||
const KEY="missioncore.simulation-layout/v1",SCENES="missioncore.simulation-cameras/v1";
|
||||
const listeners=new Set<()=>void>();
|
||||
function read(key:string){try{return JSON.parse(localStorage.getItem(key)??"null");}catch{return null;}}
|
||||
let current=normalizeSimulationLayout(read(KEY));
|
||||
export const getSimulationLayout=()=>current;
|
||||
export function updateSimulationLayout(patch:Partial<SimulationLayout>){
|
||||
const next=normalizeSimulationLayout({...current,...patch});
|
||||
// UI choices stay usable in private/blocked storage; no edits or observations are stored here.
|
||||
try{localStorage.setItem(KEY,JSON.stringify(next));}catch{/* Session-only fallback. */}
|
||||
current=next;listeners.forEach(fn=>fn());
|
||||
}
|
||||
window.addEventListener("storage",e=>{if(e.key!==KEY&&e.key!==null)return;current=normalizeSimulationLayout(read(KEY));listeners.forEach(fn=>fn());});
|
||||
export function useSimulationLayout(){return [useSyncExternalStore(fn=>{listeners.add(fn);return()=>{listeners.delete(fn);};},getSimulationLayout),updateSimulationLayout] as const;}
|
||||
export function readSceneView(key:string){return normalizeSceneView(read(SCENES)?.[key]);}
|
||||
export function writeSceneView(key:string,value:SceneView){
|
||||
const valid=normalizeSceneView(value);if(!valid)return;
|
||||
const old=read(SCENES),entries=old&&typeof old==="object"?Object.entries(old):[];
|
||||
const next=Object.fromEntries([...entries.filter(([k,v])=>k!==key&&normalizeSceneView(v)).slice(-15),[key,valid]]);
|
||||
try{localStorage.setItem(SCENES,JSON.stringify(next));}catch{/* Keep the live scene usable. */}
|
||||
}
|
||||
Reference in New Issue
Block a user