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
@@ -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)};