feat(semantics): version scene edits and refine paint geometry

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:55 +03:00
parent 7a3c3c00b3
commit b7b5ac9cf0
34 changed files with 3014 additions and 138 deletions
@@ -13,7 +13,7 @@ import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiE
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
import { localScene } from "./localScene";
import { EditorTerrain } from "./EditorTerrain";
import { EditorCamera } from "./EditorCamera";
import { EditorCamera, type NavigationOwner } from "./EditorCamera";
import { EditorSurfacePicker } from "./EditorSurfacePicker";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
@@ -240,8 +240,8 @@ export class AiEditorRuntime {
}
this.dirty = true;
}
setNavigation(enabled: boolean) {
this.controls.setNavigation(enabled);
setNavigation(enabled: boolean, owner: NavigationOwner = "planner") {
this.controls.setNavigation(enabled, owner);
}
setSemanticSelection(active:boolean) {this.controls.semanticSelection=active;}
setAddMode(add: boolean) { this.controls.setAddMode(add); }
@@ -5,6 +5,8 @@ import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/e
import { PerspectiveCamera, Vector3 } from "three";
import {cameraRay,isOrthographic,switchProjection,type EditorProjection,type ProjectionCamera} from "../../core/simulation/editorProjection";
export type NavigationOwner = "planner" | "semantic";
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 {
@@ -14,7 +16,8 @@ export class EditorCamera {
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
get rotationCenter(){return this.gesture&&!this.gesture.pan&&!this.gesture.pending?this.gesture.anchor:null;}
private keys = new Set<string>();
private enabled=true;
private navigationBlocks=new Set<NavigationOwner>();
private get enabled(){return this.navigationBlocks.size===0;}
private topPoints:number[][]|null=null;
private addMode=false;
semanticSelection=false;
@@ -153,7 +156,10 @@ export class EditorCamera {
}
setAddMode(add:boolean){this.cancelGesture();this.addMode=add;}
invalidateSurface(){this.cancelGesture();this.lastAnchor=null;}
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
setNavigation(enabled:boolean,owner:NavigationOwner="planner"){
if(enabled)this.navigationBlocks.delete(owner);else this.navigationBlocks.add(owner);
if(!this.enabled)this.clear();
}
update(dt:number){
if(!this.enabled||!this.keys.size)return;
this.cancelGesture();
@@ -15,7 +15,7 @@ export function PlannerCameraTools({runtime,viewport,disabled}:{runtime:AiEditor
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>}
{({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>)}<Button width="full" onClick={()=>{runtime.top();close();}}>Показать сцену целиком</Button></div>}
</Dropdown>
{createPortal(<div className="ai-local-editor__cube"><NavigationCube quaternion={quaternion} {...preferences.cube} disabled={disabled} onSelect={direction=>runtime.view(direction)}/></div>,viewport)}
</>;
@@ -11,7 +11,8 @@ 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]);
useEffect(()=>{if(!props.editing&&!original)return;runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime,props.editing,original]);
if(!props.editing&&!original)return null;
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(" ");};
@@ -20,7 +21,7 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
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 visible=map.features.filter(f=>(chosen.includes(f)||highlight.includes(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="Редактор контуров">
@@ -1,10 +1,11 @@
import {useSimulationLayout} from "./useSimulationLayout";
import {useSemanticDocument} from "./useSemanticDocument";
import {useEffect,useRef,useState} from "react";
import {createPortal} from "react-dom";
import {Button,Icon,IconButton,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
import {Button,FieldFrame,Icon,IconButton,Select,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 {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticOperation,undoSemantic,
type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import type {AiEditorRuntime} from "./AiEditorRuntime";
import {SemanticEditOverlay,type SemanticChoice} from "./SemanticEditOverlay";
import {SemanticTools} from "./SemanticTools";
@@ -14,12 +15,11 @@ import {duplicateIndex,type SemanticAxis} from "../../core/simulation/semanticVe
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 [error,setError]=useState<string|null>(null);
const [confirmDiscard,setConfirmDiscard]=useState(false);
const [layout,updateLayout]=useSimulationLayout();
const document=useSemanticDocument(worldId,worldSha,active,source,layout.semanticVersion,setError);
const {revision,draft,setDraft,saving,loading,editing,setEditing,save}=document;
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);};
@@ -32,28 +32,18 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
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]);
setSelected(null);setPreview(null);setTool("select");setTemplate(null);
if(!revision)return;
const available=availableUrbanClasses(revision.edited);
if(layers.length&&available.length&&!layers.some(layer=>available.includes(layer)))setLayers(available);
if(revision.revision)updateLayout({semanticVersion:"manual"});
},[revision]);
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;
if(busy||saving||loading||!editing||!document.canEdit||!current.current.draft)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});
@@ -79,7 +69,7 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
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(!editing||busy||saving||loading||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||window.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);
@@ -91,24 +81,14 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
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]);
window.document.addEventListener("keydown",keyboard,true);
return()=>window.document.removeEventListener("keydown",keyboard,true);
},[active,editing,busy,saving,loading,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");
@@ -119,29 +99,36 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
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}
{document.options.length?<FieldFrame label="Версия разметки" labelPlacement="below" className="ai-polygon__semantic-version-field"><Select label="Версия разметки" value={document.selected} options={document.options.map(option=>({...option,label:option.value===document.selected&&document.dirty?`${option.label} · несохранённые правки`:option.label}))}
disabled={loading||saving||document.dirty} onChange={v=>{document.select(v);updateLayout({semanticVersion:v.startsWith("manual:")?"manual":v as "raw"|"algorithmic"});}}/></FieldFrame>:null}
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={document.selected==="raw"?"Сырая разметка доступна только для просмотра":editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing} disabled={!document.canEdit||busy}
onClick={()=>{document.toggleEditing();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}
{document.dirty?<Button disabled={saving} onClick={()=>setConfirmDiscard(true)}>Отменить правки</Button>: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}
{loading||!revision?<Button loading={loading} onClick={document.refresh}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
{revision?<SemanticTools viewport={viewport} editing={editing&&document.canEdit&&visible.user&&layers.length>0&&!busy} 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}
axis={axis} setAxis={setAxis} visible={visible} compareAvailable={document.selected.startsWith("manual:")||document.dirty} 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")}
original={visible.model&&revision&&(document.selected.startsWith("manual:")||document.dirty)?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
editing={editing&&document.canEdit&&visible.user&&layers.length>0} blocked={busy||saving||loading} 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>
<Window open={confirmDiscard} onClose={()=>setConfirmDiscard(false)} title="Отменить несохранённые правки?">
<Button onClick={()=>setConfirmDiscard(false)}>Продолжить редактирование</Button>
<Button variant="danger" onClick={()=>{document.discard();setSelected(null);setConfirmDiscard(false);}}>Отменить правки</Button>
</Window>
<ToastStack items={error?[{id:"semantic",tone:"error",title:"Не удалось выполнить действие",description:error}]:[]} onDismiss={()=>setError(null)}/>
</>;
}
@@ -7,7 +7,7 @@ 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}) {
visible:{model:boolean;user:boolean};compareAvailable: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);});
@@ -39,8 +39,8 @@ export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:Seman
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})}/>
<Checker label="Показывать разметку" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
{p.compareAvailable?<Checker label="Сравнить с исходной алгоритмической" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>:null}
</>)}, {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);
@@ -0,0 +1,14 @@
import {useEffect,useMemo,useSyncExternalStore} from "react";
import {getSemanticSession,hasUnsavedSemanticSessions} from "../../core/simulation/semanticDocument";
// Protection belongs to all retained scenes, not only the mounted editor.
window.addEventListener("beforeunload",event=>{if(hasUnsavedSemanticSessions())event.preventDefault();});
export function useSemanticDocument(worldId:string,worldSha:string,active:boolean,source:object,preferred:string,onError:(error:string|null)=>void) {
const session=useMemo(()=>getSemanticSession(worldId,worldSha,preferred),[worldId,worldSha]);
const state=useSyncExternalStore(session.subscribe,session.snapshot);
useEffect(()=>{if(active)void session.open();else session.setEditing(false);},[session,active,source]);
useEffect(()=>{onError(state.error);},[state.error,onError]);
return {...state,options:session.options(),dirty:session.dirty,canEdit:session.canEdit,
select:session.select,setDraft:session.setDraft,setEditing:session.setEditing,
toggleEditing:session.toggleEditing,save:session.save,discard:session.discard,refresh:()=>void session.open()};
}
@@ -33,7 +33,7 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
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);
runtime.setNavigation(!latest.current.blocked,"semantic");
};
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));
@@ -52,7 +52,7 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
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);
runtime.setNavigation(false,"semantic");viewport.setPointerCapture(e.pointerId);
};
const down=(e:PointerEvent)=>{
const p=latest.current;if(!p.editing||p.blocked)return;
@@ -160,11 +160,13 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
}else if(e.key==="Enter"&&shape.length>=3){stop(e);commitShape(shape);}
};
const leave=()=>{if(!drag&&!box){generation++;pending=null;setGhost(null);setHover(null);}};
// Loading owns a temporary semantic lock; completion must restore input without blur.
runtime.setNavigation(!props.blocked,"semantic");
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]);
return()=>{disposed=true;cancel();runtime.setNavigation(true,"semantic");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.blocked,props.tool,props.template,props.layers]);
const ghostMap=ghost?semanticOperation({...props.map,features:[]},ghost):null;
return {hover,ghostMap,marquee,brush};
}
@@ -0,0 +1,90 @@
import {semanticDraft,semanticRequest,type SemanticDraft,type SemanticRevision} from "./semanticEdits";
import {checkSemanticWorld,chooseVersion,manualKey,semanticVersions,versionOptions,versionQuery,type SemanticVersions} from "./semanticVersions";
interface DocumentState {
revision:SemanticRevision|null;draft:SemanticDraft|null;versions:SemanticVersions|null;
selected:string;editing:boolean;saving:boolean;loading:boolean;error:string|null;
}
export interface SemanticDocumentApi {
versions:typeof semanticVersions;request:typeof semanticRequest;uuid:()=>string;
}
const api:SemanticDocumentApi={versions:semanticVersions,request:semanticRequest,uuid:()=>crypto.randomUUID()};
/** One session owns the draft AND its pending save across scene mounts. */
export class SemanticDocumentSession {
private value:DocumentState;
private listeners=new Set<()=>void>();
private generation=0;
private abort:AbortController|null=null;
private branch:string|null=null;
private attempt:{key:string;signature:string}|null=null;
constructor(readonly worldId:string,readonly worldSha:string,preferred:string,private transport=api){
this.value={revision:null,draft:null,versions:null,selected:preferred,editing:false,saving:false,loading:false,error:null};
}
snapshot=()=>this.value;
subscribe=(listener:()=>void)=>{this.listeners.add(listener);return()=>{this.listeners.delete(listener);};};
private update(patch:Partial<DocumentState>){this.value={...this.value,...patch};this.listeners.forEach(listener=>listener());}
get dirty(){return !!this.value.draft?.operations.length;}
get protected(){return this.dirty||this.value.saving;}
get canEdit(){return this.value.selected!=="raw"&&!this.value.loading&&!this.value.saving&&!!this.value.revision;}
async open(preferred=this.value.selected){
if(this.protected)return;
this.abort?.abort();const abort=this.abort=new AbortController(),id=++this.generation;
this.update({loading:true,editing:false,error:null});
try {
const versions=await this.transport.versions(this.worldId,abort.signal);
const selected=chooseVersion(preferred,versions);
const revision=await this.transport.request(this.worldId,undefined,abort.signal,versionQuery(selected,versions));
checkSemanticWorld(revision,this.worldSha);
if(abort.signal.aborted||id!==this.generation)return;
this.branch=null;this.attempt=null;
// Commit the identity, label and geometry together. A failed GET retains
// the previous view, and a late response cannot overwrite a newer view.
this.update({versions,selected,revision,draft:semanticDraft(revision.edited),loading:false});
} catch(error){if(!abort.signal.aborted&&id===this.generation)this.update({error:(error as Error).message,loading:false});}
}
select=(selected:string)=>{if(!this.protected&&!this.value.loading)void this.open(selected);};
setEditing=(next:boolean)=>{if(!next){this.update({editing:false});return;}if(!this.canEdit)return;
if(this.value.selected==="algorithmic"&&!this.branch)this.branch=this.transport.uuid();
this.update({editing:true});};
toggleEditing=()=>this.setEditing(!this.value.editing);
setDraft=(value:SemanticDraft|null|((prior:SemanticDraft|null)=>SemanticDraft|null))=>{
if(!this.canEdit||!this.value.editing)return;
this.update({draft:typeof value==="function"?value(this.value.draft):value});
};
discard=()=>{if(this.value.saving||!this.value.revision)return;this.branch=null;this.attempt=null;
this.update({draft:semanticDraft(this.value.revision.edited),editing:false});};
save=async()=>{
const {draft,revision,selected,versions}=this.value;
if(!draft?.operations.length||!revision||!versions||this.value.saving||selected==="raw")return;
const branch=selected==="algorithmic"?this.branch:revision.branch_id;
if(selected==="algorithmic"&&!branch){this.update({error:"Не удалось создать ручную версию."});return;}
const body={expected_revision:revision.revision,model_sha256:revision.model_sha256,operations:draft.operations,
...(branch?{branch_id:branch}:{})};
const signature=JSON.stringify(body);
if(this.attempt?.signature!==signature)this.attempt={signature,key:this.transport.uuid()};
this.update({saving:true,error:null});
try {
const saved=await this.transport.request(this.worldId,{...body,request_id:this.attempt.key});
checkSemanticWorld(saved,this.worldSha);
if(!saved.revision||saved.model_sha256!==revision.model_sha256||(saved.branch_id??null)!==(branch??null))
throw new Error("Ответ сохранения относится к другой версии. Черновик сохранён в этом окне.");
const row={branch_id:saved.branch_id??null,revision:saved.revision,model_sha256:saved.model_sha256,
created_at:saved.history.at(-1)!.created_at};
this.branch=null;this.attempt=null;
this.update({revision:saved,draft:semanticDraft(saved.edited),selected:manualKey(saved.branch_id??null),editing:false,
versions:{...versions,manual:[row,...versions.manual.filter(v=>v.branch_id!==row.branch_id)]}});
} catch(error){this.update({error:(error as Error).message});}
finally{this.update({saving:false});}
};
options=()=>this.value.versions?versionOptions(this.value.versions):[];
}
const sessions=new Map<string,SemanticDocumentSession>();
export function getSemanticSession(worldId:string,worldSha:string,preferred:string) {
for(const [key,session] of sessions)if(key!==worldSha&&!session.protected&&!session.snapshot().loading)sessions.delete(key);
let session=sessions.get(worldSha);
if(!session){session=new SemanticDocumentSession(worldId,worldSha,preferred);sessions.set(worldSha,session);}
return session;
}
export const hasUnsavedSemanticSessions=()=>[...sessions.values()].some(session=>session.protected);
@@ -68,7 +68,7 @@ function objectOperation(map:UrbanMap,op:Exclude<SemanticOperation,VertexOperati
}
export interface SemanticRevision {
schema_version:"missioncore.semantic-editor/v1";
revision:string|null;model_sha256:string;latest_model_sha256:string;
branch_id?:string|null;revision:string|null;model_sha256:string;latest_model_sha256:string|null;
model:UrbanMap;edited:UrbanMap;
history:{revision:string;created_at:string;actions:number}[];
learning:{state:string;dataset_ready:boolean};
@@ -138,8 +138,9 @@ export function segmentHit(p:number[],a:number[],b:number[]) {
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`,{
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal,query?:Record<string,string>):Promise<SemanticRevision> {
const search=query?`?${new URLSearchParams(query)}`:"";
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits${search}`,{
method:body?"POST":"GET",cache:"no-store",signal,
...(body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}:{}),
});
@@ -149,6 +150,7 @@ export async function semanticRequest(worldId:string,body?:object,signal?:AbortS
}
const result=await response.json() as SemanticRevision;
if(result.schema_version!=="missioncore.semantic-editor/v1")throw new Error("Неизвестная версия редактора.");
if(query?.source==="raw"&&(result as SemanticRevision&{read_only?:boolean}).read_only===true)result.edited=result.model;
return result;
}
@@ -0,0 +1,37 @@
import type {SemanticRevision} from "./semanticEdits";
export interface SemanticVersions {
raw_sha256:string|null; algorithmic_sha256:string|null;
manual:{branch_id:string|null;revision:string;model_sha256:string;created_at:string}[];
}
export const manualKey=(branch:string|null)=>`manual:${branch??"legacy"}`;
export function versionOptions(versions:SemanticVersions):{value:string;label:string;disabled?:boolean}[] {
return [
{value:"raw",label:"Сырая алгоритмическая",disabled:!versions.raw_sha256},
{value:"algorithmic",label:"Алгоритмическая",disabled:!versions.algorithmic_sha256},
...versions.manual.map((row,i)=>({value:manualKey(row.branch_id),
label:versions.manual.length===1?"Ручная":`Ручная · ${new Date(row.created_at).toLocaleString("ru-RU")}${i===0?" · последняя":""}`})),
];
}
export function versionQuery(key:string,versions:SemanticVersions):Record<string,string> {
if(key==="raw"||key==="algorithmic")return {source:key,
model_sha256:(key==="raw"?versions.raw_sha256:versions.algorithmic_sha256)??""};
const branch=versions.manual.find(row=>manualKey(row.branch_id)===key);
if(!branch)throw new Error("Ручная версия не найдена.");
return {source:"manual",...(branch.branch_id?{branch_id:branch.branch_id}:{})};
}
export function chooseVersion(preferred:string,versions:SemanticVersions):string {
if(preferred==="manual"&&versions.manual.length)return manualKey(versions.manual[0].branch_id);
const options=versionOptions(versions);
if(options.some(row=>row.value===preferred&&!row.disabled))return preferred;
return versions.algorithmic_sha256?"algorithmic":versions.manual.length?manualKey(versions.manual[0].branch_id):"raw";
}
export async function semanticVersions(worldId:string,signal?:AbortSignal):Promise<SemanticVersions> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-versions`,{cache:"no-store",signal});
if(!response.ok)throw new Error("Не удалось получить версии разметки.");
return response.json();
}
export function checkSemanticWorld(value:SemanticRevision,worldSha:string) {
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
throw new Error("Правки относятся к другой сцене.");
}
@@ -3,18 +3,20 @@ import type {EditorProjection} from "./editorProjection";
import type {SemanticAxis} from "./semanticVector";
export interface SimulationLayout {
mode:"view"|"semantic"|"planning"; projection:EditorProjection;
semanticVersion:"raw"|"algorithmic"|"manual";
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 const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",semanticVersion:"algorithmic",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),
semanticVersion:pick(v.semanticVersion,["raw","algorithmic","manual"],d.semanticVersion),
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)};
@@ -196,5 +196,6 @@
.semantic-tools__menu { display: flex; flex-direction: column; gap: .25rem; }
.ai-polygon__semantic-actions { display: contents; }
.ai-polygon__semantic-version-field { width: 18rem; min-width: 0; max-width: 100%; }
.ai-local-editor__cube { position: absolute; top: 8px; left: 4px; z-index: 5; }