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,6 +1,6 @@
|
||||
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint, type AiWorld } from "./aiPolygon";
|
||||
export interface EditorCache {
|
||||
local_scene?: { visual_url: string; collision_url: string; visual_rotation: number[]; collision_rotation: number[] };
|
||||
local_scene?: { visual_url: string; collision_url: string | null; visual_rotation: number[]; collision_rotation: number[] };
|
||||
key: string; world: AiWorld; status: "queued" | "preparing" | "uploading" | "ready" | "failed";
|
||||
error: string | null;
|
||||
files: Record<string, { sha256: string; byte_length: number; uploaded_bytes: number }>;
|
||||
|
||||
@@ -31,6 +31,7 @@ export interface AiSource {
|
||||
description?: string;
|
||||
}
|
||||
export interface AiWorld extends AiSource {
|
||||
display_name?: string; removed?: boolean;
|
||||
local_scene?: { project_id: string };
|
||||
inference_ready?: boolean; inference_message?: string;
|
||||
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
|
||||
@@ -123,7 +124,7 @@ export interface AiPlanningCommand {
|
||||
point_id?: string; x?: number; y?: number; amount?: number; enabled?: boolean; axis?: "x" | "y" | "xy";
|
||||
}
|
||||
export interface AiCatalog {
|
||||
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
|
||||
sources: AiSource[]; worlds: AiWorld[]; removed_worlds?: AiWorld[]; runs: AiRun[];
|
||||
robots: AiRobot[];
|
||||
plans: AiPlan[];
|
||||
runtime: { available: boolean; active_run: AiRun | null };
|
||||
@@ -142,6 +143,8 @@ export async function polygonRequest<T>(path: string, init: RequestInit = {}): P
|
||||
}
|
||||
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
|
||||
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog");
|
||||
export const updateAiWorld = (id:string, changes:{display_name?:string;removed?:boolean}) =>
|
||||
polygonRequest<AiWorld>(`/worlds/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
|
||||
export const aiPlanName = (plan: AiPlan) => plan.display_name ?? plan.name;
|
||||
export const updateAiPlan = (id:string, changes:{display_name?:string;removed?:boolean}) =>
|
||||
polygonRequest<AiPlan>(`/plans/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { PerspectiveCamera, Quaternion, Vector3 } from "three";
|
||||
import { Quaternion, Vector3 } from "three";
|
||||
import {screenSpan,type ProjectionCamera} from "./editorProjection";
|
||||
const UP = new Vector3(0,1,0);
|
||||
/** Depth along the optical axis gives a metric screen-space pan at any zoom. */
|
||||
export function navigationDepth(camera: PerspectiveCamera, anchor: Vector3) {
|
||||
export function navigationDepth(camera: ProjectionCamera, anchor: Vector3) {
|
||||
return Math.max(.1, anchor.clone().sub(camera.position).dot(camera.getWorldDirection(new Vector3())));
|
||||
}
|
||||
export function panCamera(camera: PerspectiveCamera, depth: number, dx: number, dy: number, height: number) {
|
||||
const scale=2*depth*Math.tan(camera.fov*Math.PI/360)/Math.max(1,height);
|
||||
export function panCamera(camera: ProjectionCamera, depth: number, dx: number, dy: number, height: number) {
|
||||
const scale=screenSpan(camera,depth)/Math.max(1,height);
|
||||
camera.position.add(new Vector3(-dx*scale,dy*scale,0).applyQuaternion(camera.quaternion));
|
||||
camera.updateMatrixWorld();
|
||||
}
|
||||
/** Rotate the complete camera pose about the picked point: no lookAt snap.
|
||||
* The picked point keeps its screen coordinates, including off-centre clicks. */
|
||||
export function orbitCamera(camera: PerspectiveCamera, anchor: Vector3, dx: number, dy: number, height: number) {
|
||||
export function orbitCamera(camera: ProjectionCamera, anchor: Vector3, dx: number, dy: number, height: number) {
|
||||
const factor=2*Math.PI/Math.max(1,height);
|
||||
const yaw=new Quaternion().setFromAxisAngle(UP,-dx*factor);
|
||||
const forward=camera.getWorldDirection(new Vector3());
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import {OrthographicCamera,PerspectiveCamera,Ray,Vector3} from "three";
|
||||
export type EditorProjection = "orthographic"|"perspective";
|
||||
export type ProjectionCamera = OrthographicCamera|PerspectiveCamera;
|
||||
export const isOrthographic=(camera:ProjectionCamera):camera is OrthographicCamera=>"isOrthographicCamera" in camera;
|
||||
export function screenSpan(camera:ProjectionCamera,depth:number) {
|
||||
return isOrthographic(camera)?(camera.top-camera.bottom)/camera.zoom:2*depth*Math.tan(camera.fov*Math.PI/360)/camera.zoom;
|
||||
}
|
||||
export function cameraRay(camera:ProjectionCamera,x:number,y:number) {
|
||||
const near=new Vector3(x*2-1,1-y*2,-1).unproject(camera);
|
||||
const far=new Vector3(x*2-1,1-y*2,1).unproject(camera);
|
||||
return new Ray(near,far.sub(near).normalize());
|
||||
}
|
||||
/** Match scale on the focal plane; switching projection must never move geometry. */
|
||||
export function switchProjection(camera:ProjectionCamera,mode:EditorProjection,aspect:number,depth:number):ProjectionCamera {
|
||||
if(isOrthographic(camera)===(mode==="orthographic"))return camera;
|
||||
const span=screenSpan(camera,depth),half=span/2;
|
||||
const next=mode==="orthographic"?new OrthographicCamera(-half*aspect,half*aspect,half,-half,camera.near,camera.far):new PerspectiveCamera(60,aspect,camera.near,camera.far);
|
||||
next.position.copy(camera.position);next.quaternion.copy(camera.quaternion);next.up.copy(camera.up);
|
||||
if(mode==="perspective")next.position.addScaledVector(camera.getWorldDirection(new Vector3()),depth-half/Math.tan(Math.PI/6));
|
||||
next.updateProjectionMatrix();next.updateMatrixWorld();return next;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { loadUrbanMap, type UrbanMap } from "./urbanMap";
|
||||
export interface AnalysisProgress {label:string;stage:number|null;stages:number;fraction:number|null;eta_seconds:number|null;stale:boolean;eta_basis:string}
|
||||
export interface AnalysisJob {key:string;request_id?:string|null;status:"queued"|"running"|"ready"|"failed"|"cancelled";phase:string;completed:number;total:number;error:string|null;progress?:AnalysisProgress;cancel_requested?:boolean;queue?:{position:number|null;total:number;waiting:number}}
|
||||
export function analysisProgressLabel(job:AnalysisJob):string {
|
||||
const p=job.progress;
|
||||
if(!p)return job.status==="queued"?"Ожидание Worker":"Расчёт инфраструктуры";
|
||||
const stage=p.stage?` · этап ${p.stage} из ${p.stages}`:"";
|
||||
const eta=p.eta_seconds===null?"":` · ≈ ${Math.max(1,Math.ceil(p.eta_seconds/60))} мин${job.status==="queued"?" на расчёт":job.phase==="preparing"?" после подготовки":" осталось"}`;
|
||||
return `${p.stale?"Связь с расчётом потеряна":p.label}${job.status==="queued"&&job.queue?.position?` · №${job.queue.position}`:stage}${eta}`;
|
||||
}
|
||||
export function useInfrastructureAnalysis(worldId:string,worldSha:string,onMap:(map:UrbanMap)=>void) {
|
||||
const [job,setJob]=useState<AnalysisJob|null>(null),[error,setError]=useState<string|null>(null);
|
||||
const [sending,setSending]=useState(false),[checking,setChecking]=useState(true);
|
||||
const callback=useRef(onMap);callback.current=onMap;
|
||||
const lifecycle=useRef<AbortController|null>(null),generation=useRef(0),requestId=useRef<string|null>(null),commandPending=useRef(false);
|
||||
const endpoint=`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/infrastructure-analysis`;
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();lifecycle.current=abort;let timer:ReturnType<typeof setTimeout>;let loaded:string|null=null;
|
||||
generation.current++;requestId.current=null;commandPending.current=false;setJob(null);setError(null);setChecking(true);setSending(false);
|
||||
const refresh=async()=>{
|
||||
if(commandPending.current){timer=setTimeout(refresh,3000);return;}
|
||||
const revision=generation.current;
|
||||
try {
|
||||
const response=await fetch(endpoint,{signal:abort.signal,cache:"no-store"});
|
||||
if(!response.ok)throw new Error("Не удалось проверить расчёт инфраструктуры.");
|
||||
const row=await response.json() as AnalysisJob|null;
|
||||
if(abort.signal.aborted||revision!==generation.current)return;
|
||||
if(row?.request_id&&row.request_id===requestId.current)requestId.current=null;
|
||||
setJob(row);
|
||||
if(row?.status==="ready"&&loaded!==row.key){
|
||||
const map=await loadUrbanMap(worldId,worldSha,abort.signal);
|
||||
if(map&&!abort.signal.aborted&&revision===generation.current){callback.current(map);loaded=row.key;}
|
||||
}
|
||||
} catch(e){if(!abort.signal.aborted&&revision===generation.current)setError((e as Error).message);}
|
||||
finally{if(!abort.signal.aborted){setChecking(false);timer=setTimeout(refresh,3000);}}
|
||||
};
|
||||
void refresh();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[endpoint,worldId,worldSha]);
|
||||
const start=async(force:boolean)=>{
|
||||
const abort=lifecycle.current;if(!abort||abort.signal.aborted||commandPending.current)return;
|
||||
generation.current++;commandPending.current=true;setSending(true);setError(null);
|
||||
requestId.current??=crypto.randomUUID().replaceAll("-","");
|
||||
try {
|
||||
const response=await fetch(endpoint,{method:"POST",signal:abort.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({force,request_id:requestId.current})});
|
||||
const body=await response.json();
|
||||
if(!response.ok)throw new Error(typeof body.detail==="string"?body.detail:"Не удалось начать расчёт.");
|
||||
if(!abort.signal.aborted){setJob(body);requestId.current=null;}
|
||||
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
|
||||
finally{if(!abort.signal.aborted){commandPending.current=false;setSending(false);}}
|
||||
};
|
||||
const cancel=async()=>{
|
||||
const abort=lifecycle.current;if(!abort||abort.signal.aborted||!job||commandPending.current)return;
|
||||
generation.current++;commandPending.current=true;setSending(true);setError(null);
|
||||
try{
|
||||
const response=await fetch(`${endpoint}/${job.key}/cancel`,{method:"POST",signal:abort.signal});
|
||||
const row=await response.json();if(!response.ok)throw new Error(typeof row.detail==="string"?row.detail:"Не удалось отменить расчёт.");
|
||||
if(!abort.signal.aborted)setJob(row);
|
||||
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
|
||||
finally{if(!abort.signal.aborted){commandPending.current=false;setSending(false);}}
|
||||
};
|
||||
return {job,error,cancel,clearError:()=>setError(null),sending,checking,start};
|
||||
}
|
||||
|
||||
export function useInfrastructureQueue(){
|
||||
const [jobs,setJobs]=useState<(AnalysisJob&{world_id:string;name:string})[]>([]),[unavailable,setUnavailable]=useState(false);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||
const refresh=async()=>{
|
||||
try{const response=await fetch('/api/v1/ai-polygon/infrastructure-analysis/queue',{signal:abort.signal,cache:'no-store'});
|
||||
if(!response.ok)throw new Error('Queue unavailable');
|
||||
const value=await response.json();if(!abort.signal.aborted){setJobs(value.jobs);setUnavailable(false);}
|
||||
}catch{if(!abort.signal.aborted)setUnavailable(true);}
|
||||
finally{if(!abort.signal.aborted)timer=setTimeout(refresh,3000);}
|
||||
};
|
||||
void refresh();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[]);
|
||||
return {jobs,unavailable};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { planMatchesDraft } from "./planDraft";
|
||||
import type { AiPlan, AiRobot, AiWaypoint } from "./aiPolygon";
|
||||
import type { EditorCache } from "./aiEditor";
|
||||
import type { PreparedRoute } from "./routePreparation";
|
||||
|
||||
/** The same admission conditions drive visibility and command entry points. */
|
||||
export function plannerActions(input: {
|
||||
draft: {cache:EditorCache;points:AiWaypoint[]}|null; robot:AiRobot|undefined;
|
||||
plan:AiPlan|undefined; routeRequired:boolean; route:PreparedRoute|null; routeKey:string|null;
|
||||
busy:boolean; runtimeAvailable:boolean; inferenceReady:boolean; activeRun:boolean;
|
||||
}) {
|
||||
const {draft,robot,plan,routeRequired,route,routeKey,busy}=input;
|
||||
const pointsReady=!!draft && !!robot && draft.points.length>=2;
|
||||
const routeReady=pointsReady && (!routeRequired || (!!route && !!routeKey));
|
||||
const changed=!!draft && !!robot && (!planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points)
|
||||
|| (routeRequired && !!route && plan?.prepared_route?.sha256!==route.sha256));
|
||||
return {
|
||||
save:!busy && routeReady && changed,
|
||||
prepare:!busy && pointsReady && routeRequired && !routeReady && input.runtimeAvailable,
|
||||
launch:!busy && routeReady && input.runtimeAvailable && input.inferenceReady && !input.activeRun,
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
import type { GaussianQuality } from "./gaussianQuality";
|
||||
|
||||
export interface PlannerPreferences {
|
||||
cube: {size:number;face:string;text:string;edge:string;hover:string;hoverText:string;opacity:number;edgeOpacity:number};
|
||||
quality: GaussianQuality;
|
||||
toolbar: { placement:"left"|"right"|"top"|"bottom"; minSize:number; maxSize:number; lensCount:number; gap:number; autoHide:boolean; hideDelay:number; background:string; border:string; outline:string; accent:string };
|
||||
navigation: { nearDistance:number; farDistance:number; nearPan:number; farPan:number; zoom:number; centroidPixels:number; centroidColor:string; centroidOpacity:number };
|
||||
pivot: { pixels: number; diameter: number; cone: number; opacity: number; x: string; y: string; z: string };
|
||||
waypoint: { diameter: number; height: number; color: string; opacity: number; frequency: number; emission: number; emissionColor: string };
|
||||
}
|
||||
export const PLANNER_PREFERENCES_KEY = "missioncore.simulation-view/v1";
|
||||
export const DEFAULT_PLANNER_PREFERENCES: PlannerPreferences = {
|
||||
cube: {size:66,face:"#292929",text:"#eeeeee",edge:"#888888",hover:"#eeeeee",hoverText:"#161616",opacity:1,edgeOpacity:1},
|
||||
quality: "medium",
|
||||
toolbar: { placement:"right",minSize:25,maxSize:42,lensCount:3,gap:10,autoHide:true,hideDelay:5000,background:"#141416",border:"#141416",outline:"#3b3b3d",accent:"#edf0eb" },
|
||||
navigation: { nearDistance:3, farDistance:100, nearPan:1, farPan:1, zoom:1, centroidPixels:14, centroidColor:"#edf0eb", centroidOpacity:.8 },
|
||||
pivot: { pixels: 105, diameter: 5, cone: 22, opacity: 1, x: "#e85b54", y: "#83ca61", z: "#6499ed" },
|
||||
waypoint: { diameter: .35, height: 4.5, color: "#edf0eb", opacity: .65, frequency: .5, emission: 1.5, emissionColor: "#edf0eb" },
|
||||
@@ -21,7 +25,15 @@ export function normalizePlannerPreferences(value: unknown): PlannerPreferences
|
||||
const color = (x: unknown, fallback: string) => typeof x === "string" && /^#[0-9a-f]{6}$/i.test(x) ? x : fallback;
|
||||
const nav:Partial<PlannerPreferences["navigation"]>=v.navigation??{}, dn=d.navigation;
|
||||
const nearDistance=n(nav.nearDistance,dn.nearDistance,.5,50);
|
||||
const c:Partial<PlannerPreferences["cube"]>=v.cube??{},dc=d.cube;
|
||||
const t:Partial<PlannerPreferences["toolbar"]>=v.toolbar??{}, dt=d.toolbar;
|
||||
const minSize=n(t.minSize,dt.minSize,18,42), lens=Math.round(n(t.lensCount,dt.lensCount,1,13));
|
||||
return {
|
||||
cube:{size:n(c.size,dc.size,48,160),face:color(c.face,dc.face),text:color(c.text,dc.text),edge:color(c.edge,dc.edge),hover:color(c.hover,dc.hover),hoverText:color(c.hoverText,dc.hoverText),opacity:n(c.opacity,dc.opacity,.2,1),edgeOpacity:n(c.edgeOpacity,dc.edgeOpacity,0,1)},
|
||||
toolbar:{placement:["left","right","top","bottom"].includes(t.placement??"")?t.placement!:dt.placement,
|
||||
minSize,maxSize:Math.max(minSize,n(t.maxSize,dt.maxSize,18,88)),lensCount:lens%2?lens:Math.min(13,lens+1),gap:n(t.gap,dt.gap,0,24),
|
||||
autoHide:typeof t.autoHide==="boolean"?t.autoHide:dt.autoHide,hideDelay:n(t.hideDelay,dt.hideDelay,0,15000),
|
||||
background:color(t.background,dt.background),border:color(t.border,dt.border),outline:color(t.outline,dt.outline),accent:color(t.accent,dt.accent)},
|
||||
navigation: {nearDistance,farDistance:Math.max(nearDistance+1,n(nav.farDistance,dn.farDistance,2,500)),
|
||||
nearPan:n(nav.nearPan,dn.nearPan,.1,5),farPan:n(nav.farPan,dn.farPan,.1,5),zoom:n(nav.zoom,dn.zoom,.1,3),
|
||||
centroidPixels:n(nav.centroidPixels,dn.centroidPixels,6,64),centroidColor:color(nav.centroidColor,dn.centroidColor),centroidOpacity:n(nav.centroidOpacity,dn.centroidOpacity,.1,1)},
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Scene-space height range, independent of the reduced collision proxy. */
|
||||
export function sceneClipBounds(visual: readonly [number, number], collision: readonly [number, number] | null): [number, number] {
|
||||
const low = Math.floor(Math.min(visual[0], collision?.[0] ?? visual[0]));
|
||||
const high = Math.ceil(Math.max(500, visual[1], collision?.[1] ?? visual[1]));
|
||||
return [low, Math.max(low + 1, high)];
|
||||
}
|
||||
|
||||
/** Native range inputs can round a fractional max slightly down on readback. */
|
||||
export function sceneClipValue(value: number, [low, high]: readonly [number, number]): number {
|
||||
return value >= high - Math.max(1, high - low) * 1e-9 ? Infinity : value;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import clipping from "polygon-clipping";
|
||||
import type {UrbanMapFeature} from "./urbanMap";
|
||||
import {geometryPaths,type RegionOperation} from "./semanticVector";
|
||||
/** Retain existing heights; new intersection vertices interpolate the nearest measured edge. */
|
||||
export function regionOperation(feature:UrbanMapFeature|undefined,brush:number[][],mode:"union"|"difference"):RegionOperation {
|
||||
if(mode==="difference"&&!feature)throw new Error("Сначала выберите пешеходную область для вырезания.");
|
||||
if(brush.length<4)throw new Error("Замкните область минимум из трёх точек.");
|
||||
if(feature&&feature.geometry.type!=="Polygon")throw new Error("Выберите пешеходную область.");
|
||||
const old=feature?geometryPaths(feature):[],subject=old.map(r=>r.map(p=>p.slice(0,2) as [number,number]));
|
||||
const paint=[brush.map(p=>p.slice(0,2) as [number,number])];
|
||||
const result=mode==="union"?clipping.union(subject.length?subject:paint,paint):subject.length?clipping.difference(subject,paint):[];
|
||||
const seeds=[...old,brush];
|
||||
const height=(p:number[])=>{
|
||||
for(const ring of seeds)for(const q of ring)if(p[0]===q[0]&&p[1]===q[1])return q[2];
|
||||
let best=Infinity,z=brush[0][2];
|
||||
for(const ring of seeds)for(let i=0;i<ring.length-1;i++){
|
||||
const a=ring[i],b=ring[i+1],dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;
|
||||
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
|
||||
const d=Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy);
|
||||
if(d<best){best=d;z=a[2]+t*(b[2]-a[2]);}
|
||||
}return z;
|
||||
};
|
||||
return {kind:"region",feature_id:feature?.id??`user-${crypto.randomUUID()}`,token:crypto.randomUUID(),mode,brush,
|
||||
polygons:result.map(p=>p.map(r=>r.map(v=>[...v,height(v)])))};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type {Knot} from "./semanticVector";
|
||||
export function curveControlScale(nodes:Knot[],index:number,closed:boolean,project:(p:number[])=>number[]|null):number {
|
||||
const node=nodes[index],base=node&&project(node.point);if(!base)return 1;
|
||||
const neighbors=[nodes[index-1]??(closed?nodes.at(-1):undefined),nodes[index+1]??(closed?nodes[0]:undefined)];
|
||||
const lengths=neighbors.map(n=>n&&project(n.point)).filter((q):q is number[]=>!!q).map(q=>Math.hypot(q[0]-base[0],q[1]-base[1])/3).filter(d=>d>1e-6);
|
||||
return lengths.length?Math.max(1,36/Math.min(...lengths)):1;
|
||||
}
|
||||
export function curveControlPoint(node:Knot,key:"incoming"|"outgoing",scale:number):number[] {
|
||||
return [node.point[0]+node[key][0]*scale,node.point[1]+node[key][1]*scale,node.point[2]];
|
||||
}
|
||||
/** Drag starts at the displayed handle, but persists only the corresponding physical delta. */
|
||||
export function moveCurveControl(vector:number[],start:number[],current:number[],scale:number):number[] {
|
||||
return vector.map((v,k)=>v+(current[k]-start[k])/scale);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import {isMarking,isRigidMarking} from "./semanticFeaturePolicy";
|
||||
export {isMarking,isRigidMarking,isEditableMarking} from "./semanticFeaturePolicy";
|
||||
import {vectorOperation,knots,withKnots,insertKnot,type VectorOperation} from "./semanticVector";
|
||||
import MARKING_TEMPLATES from "../../../../../src/k1link/simulation/ai_polygon/marking-templates.json";
|
||||
import type { UrbanMap, UrbanMapFeature } from "./urbanMap";
|
||||
|
||||
export type Vertex = { feature_id:string; path:number; index:number; object?:true };
|
||||
export type VertexOperation = Vertex & (
|
||||
{kind:"move";position:number[]}|{kind:"insert";t:number}|{kind:"delete"}
|
||||
);
|
||||
export type SemanticOperation = VectorOperation | VertexOperation |
|
||||
{kind:"retemplate";feature_id:string;template_id:string;frame:number[][]} |
|
||||
{kind:"transform";feature_id:string;delta:number[];angle:number} |
|
||||
{kind:"remove";feature_id:string} |
|
||||
{kind:"place";feature_id:string;template_id:string;position:number[];surface:"gaussian-visual"};
|
||||
export {MARKING_TEMPLATES};
|
||||
export function semanticMembers(map:UrbanMap,id:string) {
|
||||
const f=map.features.find(f=>f.id===id);
|
||||
if(!f)return [];
|
||||
const group=f.properties.semantic_element_id;
|
||||
return group?map.features.filter(q=>q.properties.semantic_element_id===group):[f];
|
||||
}
|
||||
export function semanticPivot(features:UrbanMapFeature[]) {
|
||||
const points=features.flatMap(f=>semanticPaths(f).flat());
|
||||
return [0,1,2].map(k=>(Math.min(...points.map(p=>p[k]))+Math.max(...points.map(p=>p[k])))/2);
|
||||
}
|
||||
function objectOperation(map:UrbanMap,op:Exclude<SemanticOperation,VertexOperation|VectorOperation>):UrbanMap {
|
||||
if(op.kind==="retemplate") {
|
||||
const members=semanticMembers(map,op.feature_id),t=MARKING_TEMPLATES.templates.find(t=>t.id===op.template_id);
|
||||
if(members.length!==1||members[0].properties.class!=="road_marking"||members[0].properties.review_status==="rejected"||!t||t.polygons.length!==1||op.frame.length!==3||op.frame.some(v=>v.length!==3||v.some(x=>!Number.isFinite(x)||Math.abs(x)>1e6)))throw new Error("Некорректная замена шаблона.");
|
||||
const [o,a,b]=op.frame,la=Math.hypot(a[0],a[1]),lb=Math.hypot(b[0],b[1]);
|
||||
if([la,lb].some(n=>n<.01||n>100)||Math.abs(a[0]*b[0]+a[1]*b[1])>1e-8*la*lb||a[0]*b[1]-a[1]*b[0]<=0||Math.abs(a[2])>la||Math.abs(b[2])>lb)throw new Error("Некорректные оси шаблона.");
|
||||
const f=members[0],properties={...f.properties,template_id:t.id,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const};delete properties.editor_curves;
|
||||
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(q=>q===f?{...f,properties,geometry:{type:"Polygon",coordinates:t.polygons[0].map(r=>r.map(p=>o.map((v,k)=>v+p[0]*a[k]+p[1]*b[k])))}}:q)};
|
||||
}
|
||||
if(op.kind==="place") {
|
||||
const t=MARKING_TEMPLATES.templates.find(t=>t.id===op.template_id);
|
||||
if(!t||op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||map.features.some(f=>f.id===op.feature_id))throw new Error("Некорректное размещение.");
|
||||
const features:UrbanMapFeature[]=t.polygons.map((rings,i)=>({id:i?`${op.feature_id}-${i}`:op.feature_id,
|
||||
geometry:{type:"Polygon",coordinates:rings.map(r=>r.map(v=>[v[0]+op.position[0],v[1]+op.position[1],op.position[2]]))},
|
||||
properties:{class:"road_marking",authority:"observation-only",route_permission:"unassigned",...(op.template_id==="linear_marking"?{subtype:"linear_marking"}:{semantic_element_id:op.feature_id}),
|
||||
template_id:op.template_id,confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}}));
|
||||
return {...map,schema_version:"missioncore.urban-edit/v1",features:[...map.features,...features]};
|
||||
}
|
||||
const members=semanticMembers(map,op.feature_id);
|
||||
if(!members.length||members.some(f=>!isMarking(f)))throw new Error("Выберите элемент разметки.");
|
||||
if(op.kind==="transform" && (op.delta.length!==2||op.delta.some(v=>!Number.isFinite(v))||!Number.isFinite(op.angle)))throw new Error("Некорректное перемещение.");
|
||||
if(op.kind==="transform"&&!op.angle&&op.delta.every(v=>v===0))return map;
|
||||
const centre=semanticPivot(members);
|
||||
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(f=>{
|
||||
if(!members.includes(f))return f;
|
||||
const properties={...f.properties,confidence:null,confidence_status:"not-assessed" as const,review_status:op.kind==="remove"?"rejected" as const:"unreviewed" as const};
|
||||
if(op.kind==="remove")return {...f,properties};
|
||||
const c=Math.cos(op.angle),s=Math.sin(op.angle);
|
||||
const rings=semanticPaths(f).map(r=>r.map(p=>{
|
||||
let [x,y]=p;
|
||||
if(op.angle)[x,y]=[centre[0]+c*(x-centre[0])-s*(y-centre[1]),centre[1]+s*(x-centre[0])+c*(y-centre[1])];
|
||||
return [x+op.delta[0],y+op.delta[1],p[2]];
|
||||
}));
|
||||
if(f.properties.editor_curves)properties.editor_curves=Object.fromEntries(Object.entries(f.properties.editor_curves).map(([path,nodes])=>[path,nodes.map(n=>{
|
||||
const c=Math.cos(op.angle),s=Math.sin(op.angle),rotate=(v:number[])=>[c*v[0]-s*v[1],s*v[0]+c*v[1]];
|
||||
const relative=rotate([n.point[0]-centre[0],n.point[1]-centre[1]]);
|
||||
const point=op.angle?[centre[0]+relative[0]+op.delta[0],centre[1]+relative[1]+op.delta[1],n.point[2]]:[n.point[0]+op.delta[0],n.point[1]+op.delta[1],n.point[2]];
|
||||
return {...n,point,incoming:op.angle?rotate(n.incoming):n.incoming,outgoing:op.angle?rotate(n.outgoing):n.outgoing};
|
||||
})]));
|
||||
return {...f,properties,geometry:f.geometry.type==="Polygon"?{type:"Polygon" as const,coordinates:rings}:{type:"LineString" as const,coordinates:rings[0]}};
|
||||
})};
|
||||
}
|
||||
export interface SemanticRevision {
|
||||
schema_version:"missioncore.semantic-editor/v1";
|
||||
revision:string|null;model_sha256:string;latest_model_sha256:string;
|
||||
model:UrbanMap;edited:UrbanMap;
|
||||
history:{revision:string;created_at:string;actions:number}[];
|
||||
learning:{state:string;dataset_ready:boolean};
|
||||
}
|
||||
export const semanticPaths=(f:UrbanMapFeature):number[][][]=>
|
||||
f.geometry.type==="Polygon"?f.geometry.coordinates:[f.geometry.coordinates];
|
||||
|
||||
/** Copy only the edited feature. Untouched coordinates never round-trip through GPU. */
|
||||
export function semanticOperation(map:UrbanMap, op:SemanticOperation):UrbanMap {
|
||||
if(op.kind==="curve"||op.kind==="delete_vertices"||op.kind==="region"||op.kind==="translate"||op.kind==="translate_vertices"||op.kind==="duplicate_vertex"||op.kind==="duplicate_marking")return vectorOperation(map,op);
|
||||
if(op.kind==="place"||op.kind==="transform"||op.kind==="remove"||op.kind==="retemplate")return objectOperation(map,op);
|
||||
const feature=map.features.find(f=>f.id===op.feature_id);
|
||||
if(!feature)throw new Error("Контур не найден.");
|
||||
if(isRigidMarking(feature))throw new Error("Разметка редактируется целиком.");
|
||||
if(feature.properties.editor_curves?.[String(op.path)]) {
|
||||
let nodes=knots(feature,op.path).map(k=>({...k}));
|
||||
if(!nodes[op.index])throw new Error("Точка не найдена.");
|
||||
if(op.kind==="move") {
|
||||
if(op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||op.position[2]!==nodes[op.index].point[2])throw new Error("Редактирование сохраняет высоту.");
|
||||
nodes[op.index]={...nodes[op.index],point:op.position};
|
||||
} else if(op.kind==="insert")nodes=insertKnot(nodes,op.index,op.t,feature.geometry.type==="Polygon");
|
||||
else nodes.splice(op.index,1);
|
||||
return {...map,features:map.features.map(f=>f===feature?withKnots(f,op.path,nodes):f)};
|
||||
}
|
||||
const rings=semanticPaths(feature).map(p=>p.map(v=>[...v]));
|
||||
const points=rings[op.path],closed=feature.geometry.type==="Polygon";
|
||||
if(!points||op.index<0||op.index>=points.length-Number(closed))throw new Error("Точка не найдена.");
|
||||
if(op.kind==="insert"){
|
||||
if(op.index>=points.length-1||!(op.t>0&&op.t<1))throw new Error("Выберите середину сегмента.");
|
||||
const a=points[op.index],b=points[op.index+1];
|
||||
points.splice(op.index+1,0,a.map((v,k)=>v+op.t*(b[k]-v)));
|
||||
}else if(op.kind==="move"){
|
||||
if(op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||op.position[2]!==points[op.index][2])
|
||||
throw new Error("Редактирование в плане сохраняет высоту.");
|
||||
if(points[op.index].every((v,k)=>v===op.position[k]))return map;
|
||||
points[op.index]=[...op.position];
|
||||
}else{
|
||||
if(points.length<=(closed?4:2))throw new Error("В контуре недостаточно точек для удаления.");
|
||||
points.splice(op.index,1);
|
||||
}
|
||||
if(closed)points[points.length-1]=[...points[0]];
|
||||
const edited:UrbanMapFeature={...feature,geometry:closed?{type:"Polygon",coordinates:rings}:{type:"LineString",coordinates:rings[0]},
|
||||
properties:{...feature.properties,confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}};
|
||||
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(f=>f===feature?edited:f)};
|
||||
}
|
||||
export interface SemanticDraft {
|
||||
base:UrbanMap;map:UrbanMap;operations:SemanticOperation[];future:SemanticOperation[];
|
||||
}
|
||||
export const semanticDraft=(base:UrbanMap):SemanticDraft=>({base,map:base,operations:[],future:[]});
|
||||
export function commitSemantic(s:SemanticDraft,op:SemanticOperation):SemanticDraft {
|
||||
if(s.operations.length>=256)throw new Error("Сохраните изменения перед продолжением.");
|
||||
const map=semanticOperation(s.map,op);
|
||||
return map===s.map?s:{...s,map,operations:[...s.operations,op],future:[]};
|
||||
}
|
||||
export function undoSemantic(s:SemanticDraft):SemanticDraft {
|
||||
const last=s.operations.at(-1);if(!last)return s;
|
||||
const operations=s.operations.slice(0,-1);
|
||||
return {...s,operations,map:operations.reduce(semanticOperation,s.base),future:[last,...s.future]};
|
||||
}
|
||||
export function redoSemantic(s:SemanticDraft):SemanticDraft {
|
||||
const next=s.future[0];if(!next)return s;
|
||||
return {...commitSemantic(s,next),future:s.future.slice(1)};
|
||||
}
|
||||
/** CSS pixel distance; backing buffer DPR must not change the capture radius. */
|
||||
export function segmentHit(p:number[],a:number[],b:number[]) {
|
||||
const dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;
|
||||
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
|
||||
return {t,distance:Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy)};
|
||||
}
|
||||
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal):Promise<SemanticRevision> {
|
||||
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits`,{
|
||||
method:body?"POST":"GET",cache:"no-store",signal,
|
||||
...(body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}:{}),
|
||||
});
|
||||
if(!response.ok){
|
||||
const error=await response.json().catch(()=>null);
|
||||
throw new Error(typeof error?.detail==="string"?error.detail:"Не удалось открыть или сохранить правки.");
|
||||
}
|
||||
const result=await response.json() as SemanticRevision;
|
||||
if(result.schema_version!=="missioncore.semantic-editor/v1")throw new Error("Неизвестная версия редактора.");
|
||||
return result;
|
||||
}
|
||||
|
||||
export interface SemanticDelivery {revision:string|null;state:string;training_eligible:false}
|
||||
export async function semanticDelivery(worldId:string,signal:AbortSignal):Promise<SemanticDelivery> {
|
||||
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits/status`,{
|
||||
cache:"no-store",signal,
|
||||
});
|
||||
if(!response.ok)throw new Error("Не удалось обновить статус доставки.");
|
||||
return await response.json() as SemanticDelivery;
|
||||
}
|
||||
export function semanticDeliveryLabel(state:string):string {
|
||||
switch(state){
|
||||
case "received":return "На Worker · в очереди подготовки";
|
||||
case "building":return "Worker готовит пример";
|
||||
case "draft-ready":return "Пример на Worker · ожидает проверки";
|
||||
case "failed":return "Правки на Worker · подготовка не завершена";
|
||||
case "unavailable":return "Правки сохранены · статус доставки недоступен";
|
||||
default:return "Правки сохранены · ожидаем доставку на Worker";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import type {UrbanMapFeature} from "./urbanMap";
|
||||
export const isMarking=(f:UrbanMapFeature)=>["road_marking","crosswalk_marking"].includes(f.properties.class);
|
||||
/** Only explicit line classification admits vertex editing; unknown symbols stay rigid. */
|
||||
export const isEditableMarking=(f:UrbanMapFeature)=>f.properties.class==="road_marking"&&f.properties.subtype==="linear_marking"&&(!f.properties.template_id||f.properties.template_id==="linear_marking")&&!f.properties.semantic_element_id;
|
||||
export const isRigidMarking=(f:UrbanMapFeature)=>isMarking(f)&&!isEditableMarking(f);
|
||||
@@ -0,0 +1,53 @@
|
||||
import {editablePaths,knots,curvePoint} from "./semanticVector";
|
||||
import {isMarking,isRigidMarking,segmentHit,type Vertex} from "./semanticEdits";
|
||||
import type {UrbanMap,UrbanClassId} from "./urbanMap";
|
||||
export interface SemanticHit {vertex:Vertex;distance:number;t:number;point?:number[];segment?:{a:number[];b:number[];start:number;end:number;t:number}}
|
||||
export function semanticHits(map:UrbanMap,layers:UrbanClassId|readonly UrbanClassId[],at:number[],project:(v:number[])=>number[]|null,vertices:boolean,activeFeatures?:string|readonly string[]):SemanticHit[] {
|
||||
const hits:SemanticHit[]=[];
|
||||
const selected=new Set(typeof activeFeatures==="string"?[activeFeatures]:activeFeatures??[]);
|
||||
for(const f of map.features) {
|
||||
if(!(typeof layers==="string"?[layers]:layers).includes(f.properties.class as UrbanClassId)||f.properties.review_status==="rejected"||(!vertices&&isRigidMarking(f)))continue;
|
||||
editablePaths(f).forEach((path,pathIndex)=>{
|
||||
if(vertices&&!isRigidMarking(f)&&selected.has(f.id))path.slice(0,path.length-Number(f.geometry.type==="Polygon")).forEach((point,index)=>{
|
||||
const p=project(point),distance=p?Math.hypot(p[0]-at[0],p[1]-at[1]):Infinity;
|
||||
if(distance<=9)hits.push({vertex:{feature_id:f.id,path:pathIndex,index},distance,t:0,point});
|
||||
});
|
||||
const nodes=knots(f,pathIndex);
|
||||
for(let i=0;i<path.length-1;i++) {
|
||||
const n=nodes[i],next=nodes[(i+1)%nodes.length];
|
||||
const steps=n.outgoing.some(Boolean)||next.incoming.some(Boolean)?16:1;
|
||||
for(let j=0;j<steps;j++) {
|
||||
const A=steps===1?path[i]:curvePoint(n,next,j/steps),B=steps===1?path[i+1]:curvePoint(n,next,(j+1)/steps);
|
||||
const a=project(A),b=project(B);if(!a||!b)continue;
|
||||
const hit=segmentHit(at,a,b);
|
||||
if(hit.distance<=9)hits.push({vertex:{feature_id:f.id,path:pathIndex,index:i},distance:hit.distance,t:(j+hit.t)/steps,segment:{a:A,b:B,start:j/steps,end:(j+1)/steps,t:hit.t}});
|
||||
}
|
||||
}
|
||||
});
|
||||
// Pick the painted interior, excluding holes, for filled marking elements.
|
||||
if(f.geometry.type==="Polygon") {
|
||||
const inside=(ring:number[][])=>{
|
||||
const p=ring.map(project);if(p.some(v=>!v))return false;
|
||||
let yes=false;
|
||||
for(let i=1;i<p.length;i++) {const a=p[i-1]!,b=p[i]!;
|
||||
if((a[1]>at[1])!==(b[1]>at[1])&&at[0]<(b[0]-a[0])*(at[1]-a[1])/(b[1]-a[1])+a[0])yes=!yes;
|
||||
}return yes;
|
||||
};
|
||||
if(inside(f.geometry.coordinates[0])&&!f.geometry.coordinates.slice(1).some(inside))hits.push({vertex:{feature_id:f.id,path:0,index:0},distance:0,t:0});
|
||||
}
|
||||
}
|
||||
return hits.sort((a,b)=>Number(!!b.point)-Number(!!a.point)||a.distance-b.distance);
|
||||
}
|
||||
/** Preserve the gesture's grab offset. Non-selected axes never change. */
|
||||
export function semanticDrag(origin:number[],start:number[],hit:number[],axis:"x"|"y"|"xy") {
|
||||
return origin.map((v,k)=>k===2||(axis==="x"&&k!==0)||(axis==="y"&&k!==1)?v:v+(hit[k]-start[k]));
|
||||
}
|
||||
|
||||
/** A body hit selects every editable knot; only a visible vertex hit selects one. */
|
||||
export function semanticHitSelection(map:UrbanMap,hit:SemanticHit):Vertex[] {
|
||||
const f=map.features.find(f=>f.id===hit.vertex.feature_id);
|
||||
if(!f||f.properties.review_status==="rejected")return [];
|
||||
if(hit.point)return [hit.vertex];
|
||||
if(isMarking(f))return [{...hit.vertex,object:true}];
|
||||
return editablePaths(f).flatMap((_,path)=>knots(f,path).map((_,index)=>({feature_id:f.id,path,index})));
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import {isMarking,isRigidMarking} from "./semanticFeaturePolicy";
|
||||
import type {UrbanMap,UrbanMapFeature} from "./urbanMap";
|
||||
export interface Knot {point:number[]; incoming:number[]; outgoing:number[]}
|
||||
export interface CurveOperation {kind:"curve";feature_id:string;path:number;index:number;incoming:number[];outgoing:number[]}
|
||||
export interface GroupDelete {kind:"delete_vertices";vertices:{feature_id:string;path:number;index:number}[]}
|
||||
export interface RegionOperation {kind:"region";feature_id:string;token:string;mode:"union"|"difference";brush:number[][];polygons:number[][][][]}
|
||||
export type SemanticAxis="x"|"y"|"z"|"xy"|"xz"|"yz";
|
||||
export type TranslateOperation = ({kind:"translate"}|{kind:"translate_vertices"}) & {feature_id:string;vertices:{feature_id:string;path:number;index:number}[];delta:number[];axis:SemanticAxis}
|
||||
export interface DuplicateVertexOperation {kind:"duplicate_vertex";feature_id:string;path:number;index:number;delta:number[];axis:SemanticAxis;side?:"before"|"after"}
|
||||
/** Omitted side is the immutable legacy replay contract. New gestures persist their choice. */
|
||||
export const duplicateIndex=(index:number,closed:boolean,side?:"before"|"after")=>side?index+Number(side==="after"):!closed&&index===0?0:index+1;
|
||||
/** Compare local arms, not world-axis signs or unequal segment lengths. */
|
||||
export function duplicateSide(nodes:Knot[],index:number,closed:boolean,delta:number[]):"before"|"after" {
|
||||
const node=nodes[index];
|
||||
const alignment=(neighbor:Knot|undefined,handle:number[])=>{
|
||||
if(!neighbor)return null;
|
||||
const arm=handle.some(Boolean)?handle:neighbor.point.slice(0,2).map((v,k)=>v-node.point[k]);
|
||||
const length=Math.hypot(...arm);
|
||||
return length?arm.reduce((sum,v,k)=>sum+v*delta[k],0)/length:0;
|
||||
};
|
||||
const before=alignment(index>0?nodes[index-1]:closed?nodes.at(-1):undefined,node.incoming);
|
||||
const after=alignment(index+1<nodes.length?nodes[index+1]:closed?nodes[0]:undefined,node.outgoing);
|
||||
// At an open end a sideways drag continues around the corner. Insert inward
|
||||
// only when movement along the existing arm dominates its perpendicular part.
|
||||
// A tiny inward component must not turn an extension into a folded segment.
|
||||
const inward=Math.hypot(delta[0],delta[1])/Math.SQRT2;
|
||||
if(before===null)return after!==null&&after>inward?"after":"before";
|
||||
if(after===null)return before>inward?"before":"after";
|
||||
return before>after?"before":"after";
|
||||
}
|
||||
export interface DuplicateMarkingOperation {kind:"duplicate_marking";feature_id:string;new_feature_id:string;delta:number[];axis:SemanticAxis}
|
||||
export type VectorOperation=DuplicateMarkingOperation|CurveOperation|GroupDelete|RegionOperation|TranslateOperation|DuplicateVertexOperation;
|
||||
export const geometryPaths=(f:UrbanMapFeature):number[][][]=>f.geometry.type==="Polygon"?f.geometry.coordinates:[f.geometry.coordinates];
|
||||
export function knots(f:UrbanMapFeature,path:number):Knot[] {
|
||||
const saved=f.properties.editor_curves?.[String(path)];
|
||||
return saved??geometryPaths(f)[path].slice(0,geometryPaths(f)[path].length-Number(f.geometry.type==="Polygon")).map(point=>({point,incoming:[0,0],outgoing:[0,0]}));
|
||||
}
|
||||
export const editablePaths=(f:UrbanMapFeature)=>geometryPaths(f).map((_,i)=>{
|
||||
const points=knots(f,i).map(k=>k.point);return f.geometry.type==="Polygon"?[...points,points[0]]:points;
|
||||
});
|
||||
export function curvePoint(a:Knot,b:Knot,t:number) {
|
||||
const u=1-t;
|
||||
return [0,1].map(k=>u*u*u*a.point[k]+3*u*u*t*(a.point[k]+a.outgoing[k])+3*u*t*t*(b.point[k]+b.incoming[k])+t*t*t*b.point[k]).concat(a.point[2]+t*(b.point[2]-a.point[2]));
|
||||
}
|
||||
export function curvePath(nodes:Knot[],closed:boolean) {
|
||||
const path:number[][]=[];
|
||||
for(let i=0;i<nodes.length-Number(!closed);i++) {
|
||||
const a=nodes[i],b=nodes[(i+1)%nodes.length];path.push(a.point);
|
||||
if(a.outgoing.some(Boolean)||b.incoming.some(Boolean))for(let j=1;j<16;j++)path.push(curvePoint(a,b,j/16));
|
||||
}
|
||||
path.push(closed?nodes[0].point:nodes.at(-1)!.point);return path;
|
||||
}
|
||||
export function withKnots(f:UrbanMapFeature,path:number,nodes:Knot[]):UrbanMapFeature {
|
||||
const closed=f.geometry.type==="Polygon";
|
||||
if(nodes.length<(closed?3:2))throw new Error("В контуре недостаточно точек. Выберите весь контур для удаления.");
|
||||
const paths=geometryPaths(f).slice();paths[path]=curvePath(nodes,closed);
|
||||
return {...f,geometry:closed?{type:"Polygon",coordinates:paths}:{type:"LineString",coordinates:paths[0]},properties:{...f.properties,
|
||||
editor_curves:{...f.properties.editor_curves,[String(path)]:nodes},confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}};
|
||||
}
|
||||
export function vectorOperation(map:UrbanMap,op:VectorOperation):UrbanMap {
|
||||
let features=map.features;
|
||||
if(op.kind==="duplicate_marking") {
|
||||
const selected=features.find(f=>f.id===op.feature_id);
|
||||
if(!selected||selected.properties.review_status==="rejected"||!isMarking(selected)||!/^user-[a-zA-Z0-9-]{16,64}$/.test(op.new_feature_id))throw new Error("Выберите элемент разметки.");
|
||||
if(!["x","y","z","xy","xz","yz"].includes(op.axis)||op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
|
||||
if(op.delta.every(v=>v===0))return map;
|
||||
const group=selected.properties.semantic_element_id,members=group?features.filter(f=>f.properties.semantic_element_id===group):[selected];
|
||||
const moved=vectorOperation({...map,features:members},{kind:"translate",feature_id:op.feature_id,vertices:[],axis:op.axis,delta:op.delta});
|
||||
const copies=moved.features.map((f,i)=>{const q=structuredClone(f);q.id=i?`${op.new_feature_id}-${i}`:op.new_feature_id;
|
||||
if(group)q.properties.semantic_element_id=op.new_feature_id;
|
||||
delete q.properties.height_projection;q.properties.height_source="human-copy-unverified";return q;});
|
||||
if(copies.some(q=>features.some(f=>f.id===q.id||f.properties.semantic_element_id===op.new_feature_id)))throw new Error("Элемент уже существует.");
|
||||
features=[...features,...copies];
|
||||
} else if(op.kind==="duplicate_vertex") {
|
||||
const f=features.find(f=>f.id===op.feature_id);
|
||||
if(!f||f.properties.review_status==="rejected"||isRigidMarking(f))throw new Error("Выберите точку редактируемого контура.");
|
||||
if(!Number.isInteger(op.path)||!geometryPaths(f)[op.path]||!Number.isInteger(op.index))throw new Error("Точка не найдена.");
|
||||
const nodes=knots(f,op.path),n=nodes[op.index];if(!n)throw new Error("Точка не найдена.");
|
||||
if(!["x","y","z","xy","xz","yz"].includes(op.axis)||op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
|
||||
if(op.delta.every(v=>v===0))return map;
|
||||
if(!op.delta[0]&&!op.delta[1])throw new Error("Продолжение контура должно иметь длину в плане: используйте X, Y или плоскость.");
|
||||
if(nodes.length>=4095)throw new Error("Достигнут предел числа точек контура.");
|
||||
if(op.side!==undefined&&op.side!=="before"&&op.side!=="after")throw new Error("Некорректная сторона вставки.");
|
||||
const next=nodes.slice(),index=duplicateIndex(op.index,f.geometry.type==="Polygon",op.side);
|
||||
next.splice(index,0,{point:n.point.map((v,k)=>op.delta[k]===0?v:v+op.delta[k]),incoming:[...n.incoming],outgoing:[...n.outgoing]});
|
||||
const q=withKnots(f,op.path,next);delete q.properties.height_projection;q.properties.height_source="human-vertex-extension-unverified";
|
||||
features=features.map(v=>v===f?q:v);
|
||||
} else if(op.kind==="translate"||op.kind==="translate_vertices") {
|
||||
if(op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
|
||||
if(op.delta.every(v=>v===0))return map;
|
||||
const selected=features.find(f=>f.id===op.feature_id);if(!selected)throw new Error("Элемент не найден.");
|
||||
const group=selected.properties.semantic_element_id;
|
||||
const marking=op.kind==="translate"&&isMarking(selected);
|
||||
if(op.kind==="translate_vertices"&&op.vertices.some(v=>{const f=features.find(f=>f.id===v.feature_id);return !f||isRigidMarking(f);}))throw new Error("Выберите вершины редактируемого контура.");
|
||||
features=features.map(f=>{
|
||||
if(marking&&(f.id===selected.id||(group&&f.properties.semantic_element_id===group))) {
|
||||
const paths=geometryPaths(f).map(p=>p.map(v=>v.map((x,k)=>x+op.delta[k])));
|
||||
const properties={...f.properties,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const};
|
||||
if(f.properties.editor_curves)properties.editor_curves=Object.fromEntries(Object.entries(f.properties.editor_curves).map(([p,nodes])=>[p,nodes.map(n=>({...n,point:n.point.map((v,k)=>v+op.delta[k])}))]));
|
||||
return {...f,geometry:f.geometry.type==="Polygon"?{type:"Polygon",coordinates:paths}:{type:"LineString",coordinates:paths[0]},properties};
|
||||
}
|
||||
if(marking)return f;
|
||||
let q=f;
|
||||
geometryPaths(f).forEach((_,p)=>{const indices=new Set(op.vertices.filter(v=>v.feature_id===f.id&&v.path===p).map(v=>v.index));
|
||||
if(indices.size)q=withKnots(q,p,knots(f,p).map((n,i)=>indices.has(i)?{...n,point:n.point.map((v,k)=>v+op.delta[k])}:n));
|
||||
});return q;
|
||||
});
|
||||
} else if(op.kind==="region") {
|
||||
const previous=features.find(f=>f.id===op.feature_id);
|
||||
if(previous&&!['pedestrian_area','sidewalk'].includes(previous.properties.class))throw new Error("Выберите пешеходную область.");
|
||||
const properties={...previous?.properties,class:previous?.properties.class??"pedestrian_area",authority:"observation-only" as const,route_permission:"unassigned" as const,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const,editor_curves:undefined,region_origin_id:op.feature_id};
|
||||
const created=op.polygons.map((coordinates,i)=>({id:i?`${op.feature_id}-${op.token}-${i}`:op.feature_id,properties,geometry:{type:"Polygon" as const,coordinates}}));
|
||||
features=features.filter(f=>f!==previous);
|
||||
if(created.length)features=[...features,...created];
|
||||
else if(previous)features=[...features,{...previous,properties:{...properties,review_status:"rejected"}}];
|
||||
} else if(op.kind==="curve") {
|
||||
const f=features.find(f=>f.id===op.feature_id);if(!f)throw new Error("Контур не найден.");
|
||||
if(isRigidMarking(f))throw new Error("Разметка редактируется целиком.");
|
||||
const nodes=knots(f,op.path).map(k=>({...k}));
|
||||
if(nodes[op.index].incoming.every((v,k)=>v===op.incoming[k])&&nodes[op.index].outgoing.every((v,k)=>v===op.outgoing[k]))return map;
|
||||
nodes[op.index]={...nodes[op.index],incoming:op.incoming,outgoing:op.outgoing};
|
||||
const edited=withKnots(f,op.path,nodes);features=features.map(q=>q===f?edited:q);
|
||||
} else {
|
||||
features=features.map(f=>{
|
||||
const chosen=op.vertices.filter(v=>v.feature_id===f.id);if(!chosen.length)return f;
|
||||
if(isRigidMarking(f))throw new Error("Разметка редактируется целиком.");
|
||||
const paths=geometryPaths(f),all=paths.every((_,p)=>knots(f,p).every((_,i)=>chosen.some(v=>v.path===p&&v.index===i)));
|
||||
if(all)return {...f,properties:{...f.properties,review_status:"rejected" as const}};
|
||||
let edited=f;
|
||||
paths.forEach((_,p)=>{if(!chosen.some(v=>v.path===p))return;
|
||||
const nodes=knots(f,p).filter((_,i)=>!chosen.some(v=>v.path===p&&v.index===i));edited=withKnots(edited,p,nodes);
|
||||
});return edited;
|
||||
});
|
||||
}
|
||||
return {...map,schema_version:"missioncore.urban-edit/v1",features};
|
||||
}
|
||||
/** De Casteljau inserts an anchor without changing the physical cubic. */
|
||||
export function insertKnot(nodes:Knot[],i:number,t:number,closed:boolean) {
|
||||
const j=(i+1)%nodes.length;if(!closed&&j===0)throw new Error("Выберите сегмент.");
|
||||
const a=nodes[i],b=nodes[j],mix=(x:number[],y:number[])=>x.map((v,k)=>v+t*(y[k]-v));
|
||||
const A=a.point.slice(0,2),B=A.map((v,k)=>v+a.outgoing[k]),D=b.point.slice(0,2),C=D.map((v,k)=>v+b.incoming[k]);
|
||||
const ab=mix(A,B),bc=mix(B,C),cd=mix(C,D),abc=mix(ab,bc),bcd=mix(bc,cd),point=mix(abc,bcd);
|
||||
const sub=(x:number[],y:number[])=>x.map((v,k)=>v-y[k]);
|
||||
const next=nodes.map(k=>({...k}));next[i]={...a,outgoing:sub(ab,A)};next[j]={...b,incoming:sub(cd,D)};
|
||||
next.splice(i+1,0,{point:[...point,a.point[2]+t*(b.point[2]-a.point[2])],incoming:sub(abc,point),outgoing:sub(bcd,point)});return next;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type {UrbanClassId} from "./urbanMap";
|
||||
import type {EditorProjection} from "./editorProjection";
|
||||
import type {SemanticAxis} from "./semanticVector";
|
||||
export interface SimulationLayout {
|
||||
mode:"view"|"semantic"|"planning"; projection:EditorProjection;
|
||||
sceneLayers:{gaussian:boolean;collision:boolean}; infrastructure:boolean; memory:boolean;
|
||||
layers:UrbanClassId[]; urbanLayers:UrbanClassId[];
|
||||
visible:{model:boolean;user:boolean}; axis:SemanticAxis; areaMode:"union"|"difference";
|
||||
}
|
||||
const classes:UrbanClassId[]=["road_boundary","pedestrian_boundary","building_facade","curb","curb_cut","sidewalk","pedestrian_area","carriageway","service_lane","bike_lane","parking","crosswalk_area","crosswalk_marking","road_marking"];
|
||||
export const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",sceneLayers:{gaussian:true,collision:false},infrastructure:false,memory:false,layers:["road_boundary"],urbanLayers:classes,visible:{model:false,user:true},axis:"xy",areaMode:"union"};
|
||||
export function normalizeSimulationLayout(raw:unknown):SimulationLayout {
|
||||
const v=(raw&&typeof raw==="object"?raw:{}) as Partial<SimulationLayout>,d=DEFAULT_SIMULATION_LAYOUT;
|
||||
const pick=<T extends string>(x:unknown,values:readonly T[],fallback:T):T=>values.includes(x as T)?x as T:fallback;
|
||||
const bool=(x:unknown,f:boolean)=>typeof x==="boolean"?x:f;
|
||||
const layers=(x:unknown,f:UrbanClassId[])=>Array.isArray(x)?Array.from(new Set(x.filter((k):k is UrbanClassId=>classes.includes(k)))):f;
|
||||
return {mode:pick(v.mode,["view","semantic","planning"],d.mode),projection:pick(v.projection,["perspective","orthographic"],d.projection),
|
||||
sceneLayers:{gaussian:bool(v.sceneLayers?.gaussian,true),collision:bool(v.sceneLayers?.collision,false)},infrastructure:bool(v.infrastructure,false),memory:bool(v.memory,false),
|
||||
layers:layers(v.layers,d.layers),urbanLayers:layers(v.urbanLayers,d.urbanLayers),visible:{model:bool(v.visible?.model,false),user:bool(v.visible?.user,true)},
|
||||
axis:pick(v.axis,["x","y","z","xy","xz","yz"],d.axis),areaMode:pick(v.areaMode,["union","difference"],d.areaMode)};
|
||||
}
|
||||
export interface SceneView {position:number[];quaternion:number[];anchor:number[]|null;projection:EditorProjection;span:number|null;clip:[number|null,number|null]}
|
||||
export function normalizeSceneView(raw:unknown):SceneView|null {
|
||||
const v=raw as SceneView|undefined;
|
||||
const vec=(x:unknown,n:number)=>Array.isArray(x)&&x.length===n&&x.every(k=>typeof k==="number"&&Number.isFinite(k)&&Math.abs(k)<1e6);
|
||||
if(!v||!vec(v.position,3)||!vec(v.quaternion,4)||Math.abs(Math.hypot(...v.quaternion)-1)>1e-5||v.anchor!==null&&!vec(v.anchor,3)||!["perspective","orthographic"].includes(v.projection)||v.span!==null&&!(Number.isFinite(v.span)&&v.span>0&&v.span<=5000)||!Array.isArray(v.clip)||v.clip.length!==2||v.clip.some(x=>x!==null&&!(Number.isFinite(x)&&Math.abs(x)<1e6))||(v.clip[0]??-Infinity)>(v.clip[1]??Infinity))return null;
|
||||
return {position:v.position,quaternion:v.quaternion,anchor:v.anchor,projection:v.projection,span:v.span,clip:v.clip};
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
export interface UrbanMapFeature {
|
||||
id: string;
|
||||
properties: { class: string; authority: "observation-only"; route_permission: "unassigned"; confidence?: number; review_status?: "unreviewed"|"accepted"|"rejected" };
|
||||
properties: { subtype?:string; height_source?:string; editor_curves?:Record<string,import("./semanticVector").Knot[]>; semantic_element_id?:string; template_id?:string; class: string; authority: "observation-only"; route_permission: "unassigned"; height_projection?: {method:string;surface_sha256:string}; confidence?: number|null; confidence_status?: "not-assessed"; review_status?: "unreviewed"|"accepted"|"rejected" };
|
||||
geometry: { type: "Polygon"; coordinates: number[][][] } | { type: "LineString"; coordinates: number[][] };
|
||||
}
|
||||
export interface UrbanMap {
|
||||
schema_version: "missioncore.urban-map/v1"|"missioncore.urban-map/v2";
|
||||
source: { world_sha256: string; collider_sha256: string };
|
||||
schema_version: "missioncore.urban-map/v1"|"missioncore.urban-map/v2"|"missioncore.urban-map/v3"|"missioncore.urban-edit/v1";
|
||||
source: { world_sha256: string; collider_sha256: string|null };
|
||||
features: UrbanMapFeature[];
|
||||
analysis?: {scope:"whole-scene";tiles_total:number;tiles_mapped?:number;tiles_without_ground?:number};
|
||||
coverage: { accepted_cells: number; cell_m: number; kind?: "objects-only" };
|
||||
}
|
||||
export const URBAN_COLORS: Record<string, [number, number, number]> = {
|
||||
@@ -15,17 +16,23 @@ export const URBAN_COLORS: Record<string, [number, number, number]> = {
|
||||
carriageway: [90,130,200], service_lane: [110,150,210], bike_lane: [150,110,220], parking: [140,140,150],
|
||||
crosswalk_area: [255,225,35], crosswalk_marking: [255,225,35], road_marking: [245,245,245],
|
||||
};
|
||||
export const URBAN_LABELS: Record<string, string> = {
|
||||
// The new contours share the existing semantic renderer palette.
|
||||
URBAN_COLORS.road_boundary = URBAN_COLORS.curb;
|
||||
URBAN_COLORS.pedestrian_boundary = URBAN_COLORS.pedestrian_area;
|
||||
URBAN_COLORS.building_facade = URBAN_COLORS.carriageway;
|
||||
URBAN_COLORS.road_marking = URBAN_COLORS.crosswalk_marking;
|
||||
export const URBAN_LABELS = {
|
||||
road_boundary: "Граница дороги", pedestrian_boundary: "Граница пешеходной зоны", building_facade: "Фасад",
|
||||
curb: "Бордюр", curb_cut: "Съезд", sidewalk: "Тротуар", pedestrian_area: "Пешеходная зона",
|
||||
carriageway: "Проезжая часть", service_lane: "Служебный проезд", bike_lane: "Велополоса", parking: "Парковка",
|
||||
crosswalk_area: "Переход", crosswalk_marking: "Зебра", road_marking: "Разметка",
|
||||
};
|
||||
} as const;
|
||||
export async function loadUrbanMap(worldId: string, worldSha: string, signal: AbortSignal): Promise<UrbanMap|null> {
|
||||
const response = await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/urban-map`, { signal, cache: "no-store" });
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) throw new Error("Не удалось загрузить карту инфраструктуры.");
|
||||
const result = await response.json() as UrbanMap;
|
||||
if (!["missioncore.urban-map/v1","missioncore.urban-map/v2"].includes(result.schema_version) || result.source.world_sha256 !== worldSha) {
|
||||
if (!["missioncore.urban-map/v1","missioncore.urban-map/v2","missioncore.urban-map/v3"].includes(result.schema_version) || result.source.world_sha256 !== worldSha) {
|
||||
throw new Error("Карта относится к другой версии сцены.");
|
||||
}
|
||||
return result;
|
||||
@@ -34,3 +41,22 @@ export async function loadUrbanMap(worldId: string, worldSha: string, signal: Ab
|
||||
export function urbanPaths(feature: UrbanMapFeature): number[][][] {
|
||||
return feature.properties.review_status === "rejected" ? [] : feature.geometry.type === "Polygon" ? feature.geometry.coordinates : [feature.geometry.coordinates];
|
||||
}
|
||||
|
||||
export type UrbanClassId = keyof typeof URBAN_LABELS;
|
||||
export const ALL_URBAN_CLASSES = Object.keys(URBAN_LABELS) as UrbanClassId[];
|
||||
/** Legend choices describe the source map, even when every class is hidden. */
|
||||
export function availableUrbanClasses(map:UrbanMap):UrbanClassId[] {
|
||||
const present=new Set(map.features.filter(f=>f.properties.review_status!=="rejected").map(f=>f.properties.class));
|
||||
return ALL_URBAN_CLASSES.filter(id=>present.has(id));
|
||||
}
|
||||
export function visibleUrbanMap(map:UrbanMap, selected:readonly UrbanClassId[]):UrbanMap {
|
||||
return {...map,features:map.features.filter(f=>f.properties.review_status!=="rejected" && selected.includes(f.properties.class as UrbanClassId))};
|
||||
}
|
||||
|
||||
/** Bounded framing coordinates, including polygon holes and open line ends. */
|
||||
export function urbanExtent(map:UrbanMap):number[][] {
|
||||
const low=[Infinity,Infinity,Infinity],high=[-Infinity,-Infinity,-Infinity];
|
||||
for(const feature of map.features) for(const ring of urbanPaths(feature)) for(const point of ring)
|
||||
for(let i=0;i<3;i++){low[i]=Math.min(low[i],point[i]);high[i]=Math.max(high[i],point[i]);}
|
||||
return Number.isFinite(low[0])?[low,high]:[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ShapeUtils, Vector2 } from "three";
|
||||
import type { UrbanMapFeature } from "./urbanMap";
|
||||
|
||||
/** A coverage polygon is a surface, never a surveyed curb. Preserve its holes. */
|
||||
export function urbanSurface(feature: UrbanMapFeature): { positions: number[]; indices: number[] } | null {
|
||||
if (feature.properties.review_status === "rejected" || feature.properties.class !== "pedestrian_area"
|
||||
|| feature.geometry.type !== "Polygon" || !feature.properties.height_projection) return null;
|
||||
const rings = feature.geometry.coordinates.map(ring => ring.slice(0, -1));
|
||||
if (!rings.length || rings.some(ring => ring.length < 3)) return null;
|
||||
const planar = rings.map(ring => ring.map(point => new Vector2(point[0], point[1])));
|
||||
const faces = ShapeUtils.triangulateShape(planar[0], planar.slice(1));
|
||||
return { positions: rings.flat().flat(), indices: faces.flat() };
|
||||
}
|
||||
Reference in New Issue
Block a user