Preserve installed operator workspace before consolidation

Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 09:59:51 +03:00
parent 97614742bb
commit d0e5f90952
368 changed files with 129172 additions and 1856 deletions
@@ -265,6 +265,8 @@ LaboratoryMetricEvidenceSceneHandle,
showCurrentIncrement: boolean;
showLocalSurface: boolean;
showRollingMap: boolean;
showReferenceGeometry?: boolean;
showRenderStats?: boolean;
showLowStep?: boolean;
pointSemanticClassIds?: readonly (number | null)[];
semanticClasses?: readonly RecordedEvidenceSemanticClass[];
@@ -287,6 +289,8 @@ LaboratoryMetricEvidenceSceneHandle,
showLocalSurface,
showRollingMap,
showLowStep = true,
showReferenceGeometry = true,
showRenderStats = true,
pointSemanticClassIds,
semanticClasses,
semanticPalette,
@@ -746,6 +750,7 @@ LaboratoryMetricEvidenceSceneHandle,
if (!host || !content) return;
clearGroup(content);
if (!showReferenceGeometry) { requestRenderRef.current(); return; }
const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM;
const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2;
const corridorMesh = new THREE.Mesh(
@@ -806,6 +811,7 @@ LaboratoryMetricEvidenceSceneHandle,
content.add(grid);
requestRenderRef.current();
}, [
showReferenceGeometry,
corridor.forwardLengthM,
corridor.halfWidthM,
corridor.rearMarginM,
@@ -912,7 +918,7 @@ LaboratoryMetricEvidenceSceneHandle,
{renderError ? <p>{renderError}</p> : null}
</div>
<div className="laboratory-metric-evidence-scene__legend">
{renderStats ? (
{showRenderStats && renderStats ? (
<span
data-decision="performance"
title="CPU-время отправки последнего WebGL render pass; это не GPU timer. В покое сцена не перерисовывается."
@@ -0,0 +1,17 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
import {DockLayout,type DockTree} from '@nodedc/ui-react';
import {observationTree,type ObservationLayout} from '../../core/fleet/observationLayout';
export function ObservationMount({element,className='observation-mount'}:{element:HTMLElement;className?:string}){
const ref=useRef<HTMLDivElement>(null);
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
return <div ref={ref} className={className}/>;
}
export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,children}:{
ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void;
labels:Record<string,string>;focusedId?:string|null;children:ReactNode;
}){
return <DockLayout tree={observationTree(layout,ids)} onTreeChange={onTreeChange}
focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id}))}
renderPanel={id=><ObservationMount element={mounts.get(id)!}/>}>{children}</DockLayout>;
}
@@ -0,0 +1,16 @@
import {useState} from 'react';
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function ObservationLayoutSaveWindow({onClose,onSave,initialName='',onRemove}:{onClose:()=>void;onSave:(name:string)=>boolean;initialName?:string;onRemove?:()=>boolean}) {
const [name,setName]=useState(initialName);
const save=()=>{if(name.trim()&&onSave(name))onClose();};
return <Window open title={onRemove?'Редактировать раскладку':'Сохранить расположение'} size="sm" onClose={onClose}
footer={<WindowFooterActions>
{onRemove&&<Button icon={<Icon name="trash"/>} onClick={()=>{if(onRemove())onClose();}}>Удалить раскладку</Button>}
<Button variant="primary" disabled={!name.trim()} onClick={save}>{onRemove?'Сохранить имя':'Сохранить'}</Button>
</WindowFooterActions>}>
<TextField label="Название раскладки" value={name} maxLength={120} onChange={event=>setName(event.target.value)}
onKeyDown={event=>{if(event.key==='Enter'&&!event.nativeEvent.isComposing){event.preventDefault();save();}}}
description={onRemove?undefined:'Сохраняются выбранные камеры, слои и расположение окон. Недоступные устройства появятся при подключении.'}/>
</Window>;
}
@@ -0,0 +1,13 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
export function ObservationPanelHeader({children}:{children:ReactNode}) {
const ref=useRef<HTMLElement>(null);
useLayoutEffect(()=>{
const header=ref.current!;
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
measure();const observer=new ResizeObserver(measure);observer.observe(header);
return()=>observer.disconnect();
},[]);
return <header ref={ref} className="observation-panel__header">{children}</header>;
}
@@ -0,0 +1,54 @@
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
.observation-toolbar h2, .observation-panel h3 { margin:0; }
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
.observation-actions { flex-shrink:0; }
.observation-deck { flex:1; min-height:0; min-width:0; }
.observation-layout { position:relative; height:100%; min-height:0; min-width:0; }
.observation-layout__slot { height:100%; min-height:0; }
.observation-layout__panel { position:absolute; min-height:0; min-width:0; }
.observation-layout__panel:has(.is-dragging) { z-index:var(--nodedc-layer-panel); }
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
.observation-panel__surface > .observation-mount { flex:1; }
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
.observation-header-slot:has(> div:empty) { display:none; }
.observation-layer-select { min-width:0; max-width:120px; }
.observation-layer-select button { max-width:100%; }
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
.observation-layer > * { min-width:0; width:100%; }
.observation-layer > .nodedc-switch { text-align:left; }
.observation-empty { display:grid; place-content:center; height:100%; text-align:center; }
.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; }
@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } }
.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; }
/* Transform the live panel as one item; reveal it across nested split boundaries. */
.observation-panel-drag { position:relative; height:100%; min-height:0; }
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
.observation-split:has(.observation-panel-drag.is-dragging),
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
@container (max-width:340px) {
.observation-panel__header { flex-wrap:wrap; }
.observation-panel__title { min-width:80px; }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
}
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
@@ -1,4 +1,4 @@
import { FieldFrame, Select } from "@nodedc/ui-react";
import { InspectorSelectField } from "@nodedc/ui-react";
import type { AiModules, AiSelection } from "../../core/simulation/aiPolygon";
const labels = { segmentation: "Поверхность", detection: "Объекты", geometry: "Рельеф",
@@ -8,10 +8,13 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
modules: AiModules; selection: AiSelection; disabled: boolean; onChange: (value: AiSelection) => void;
}) {
return <section className="ai-polygon__section" aria-label="Композиция AI">
<h3>Модули AI</h3>
{selection.selections.some(s=>s.module_id==="simulation-waypoint-mission")?<>
<InspectorSelectField label="Профиль движения" disabled={disabled} value={String(selection.selections.find(s=>s.module_id==="simulation-waypoint-mission")?.parameters.environment??"park")}
options={[{value:"natural",label:"Природа · пересечённая местность"},{value:"park",label:"Парк · дорожки"},{value:"urban",label:"Город · тротуары"}]}
onChange={environment=>onChange({...selection,selections:selection.selections.map(s=>s.module_id==="simulation-waypoint-mission"?{...s,parameters:{...s.parameters,environment}}:s)})}/>
</>:null}
{modules.catalog.groups.filter(({ modules: options }) => options.length > 0).map(({ group, modules: options }) =>
<FieldFrame key={group} label={labels[group]}>
<Select label={`Модуль: ${labels[group]}`} disabled={disabled}
<InspectorSelectField key={group} label={labels[group]} disabled={disabled}
value={selection.selections.find((row) => row.group === group)?.module_id ?? ""}
options={options.map((module) => ({ value: module.moduleId, label: module.label }))}
onChange={(value) => {
@@ -20,7 +23,6 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), {
group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults,
}] });
}} />
</FieldFrame>)}
}} />)}
</section>;
}
@@ -0,0 +1,58 @@
import {useEffect,useState} from 'react';
import {Button,Icon,InspectorSelectField,ToastStack} from '@nodedc/ui-react';
import type {AiModules,AiSelection} from '../../core/simulation/aiPolygon';
import {createAiProfile,fetchAiProfiles,sameAiIntent,updateAiProfile,type AiProfile} from '../../core/simulation/aiProfiles';
import {currentSelection} from '../../core/simulation/runConfiguration';
import {AiCompositionFields} from './AiCompositionFields';
import {AiProfileWindow} from './AiProfileWindow';
export function AiConfiguration({modules,selection,disabled,onChange}: {
modules:AiModules;selection:AiSelection;disabled:boolean;onChange:(selection:AiSelection)=>void;
}) {
const [profiles,setProfiles]=useState<AiProfile[]>([]);
const [picked,setPicked]=useState<string|null>(null);
const [modal,setModal]=useState<'save'|AiProfile|null>(null);
const [busy,setBusy]=useState(false);
const [error,setError]=useState<string|null>(null);
useEffect(()=>{let active=true;void fetchAiProfiles().then(rows=>{if(active)setProfiles(rows);})
.catch(e=>{if(active)setError(e.message);});return()=>{active=false;};},[]);
const current=picked===null?profiles.find(p=>sameAiIntent(p.composition,selection)):profiles.find(p=>p.profile_id===picked);
const changed=!!current&&!sameAiIntent(current.composition,selection);
const accept=(value:AiProfile)=>setProfiles(rows=>value.removed?rows.filter(p=>p.profile_id!==value.profile_id)
:[...rows.filter(p=>p.profile_id!==value.profile_id),value].sort((a,b)=>a.name.localeCompare(b.name)));
const save=async(name:string,removed=false)=>{
if(!modal||busy)return;setBusy(true);setError(null);
try {
const editing=modal==='save'?null:modal;
const composition=editing?undefined:currentSelection(selection,modules);
const value=editing?await updateAiProfile(editing,{name,removed})
:current&&name===current.name?await updateAiProfile(current,{composition})
:await createAiProfile(name,composition!);
accept(value);setModal(null);
if(!editing){setPicked(value.profile_id);onChange(value.composition);}
if(removed&&picked===value.profile_id)setPicked(null);
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');
void fetchAiProfiles().then(setProfiles).catch(()=>undefined);
}finally{setBusy(false);}
};
return <section className="ai-polygon__configuration-column" aria-label="Конфигурация AI">
<h3>Конфигурация AI</h3>
<div className="ai-polygon__profile-row">
<InspectorSelectField label="Профиль AI" value={current?.profile_id??''} disabled={disabled||busy}
options={[{value:'',label:'Своя конфигурация'},...profiles.map(p=>({value:p.profile_id,
label:p.name+(changed&&p===current?' · изменён':''),
action:{label:`Редактировать профиль «${p.name}»`,icon:<Icon name="edit"/>,disabled:disabled||busy,
onAction:()=>{setError(null);setModal(p);}}}))]}
onChange={id=>{if(!id){setPicked('');return;}const value=profiles.find(p=>p.profile_id===id);if(!value)return;
try{onChange(currentSelection(value.composition,modules));setPicked(id);setError(null);}
catch(e){setError(e instanceof Error?e.message:'Профиль недоступен.');}}}/>
<Button icon={<Icon name="save"/>} disabled={disabled||busy} onClick={()=>{setError(null);setModal('save');}}>Сохранить профиль</Button>
</div>
<AiCompositionFields modules={modules} selection={selection} disabled={disabled||busy} onChange={onChange}/>
{modal&&<AiProfileWindow key={modal==='save'?'save':modal.profile_id} editing={modal!=='save'} busy={busy}
initialName={modal==='save'?current?.name??'':modal.name} onClose={()=>setModal(null)} onSave={name=>void save(name)}
onRemove={modal==='save'?undefined:()=>void save(modal.name,true)}/>}
<ToastStack items={error?[{id:'ai-profile',tone:'error',title:'Профиль AI не сохранён',description:error}]:[]}
onDismiss={()=>setError(null)}/>
</section>;
}
@@ -0,0 +1,175 @@
import { waypointHit } from "../../core/simulation/waypointHit";
import { PlannerMarkers } from "./PlannerMarkers";
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { Application, Asset, Color, Entity, FILLMODE_NONE, Mat4, Quat, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
import { localScene } from "./localScene";
import { EditorTerrain } from "./EditorTerrain";
import { EditorCamera } from "./EditorCamera";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
export interface EditorMarker { id: string; base: ScreenPoint; top: ScreenPoint; x: ScreenPoint; y: ScreenPoint; z: ScreenPoint }
/** Local planning view. Lifecycle deliberately excludes Ammo, Isaac and inference. */
export class AiEditorRuntime {
private app: Application;
private camera: Entity;
private scan: Entity;
private asset: Asset | null = null;
private controls: EditorCamera;
private annotations: PlannerMarkers;
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private terrain = new EditorTerrain();
private resize: ResizeObserver;
private abort = new AbortController();
private disposed = false;
private dirty = true;
private previous = "";
private points: AiWaypoint[] = [];
clip = Infinity;
height: [number, number] = [0, 1];
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
private onProject: (markers: EditorMarker[]) => void) {
canvas.tabIndex = 0;
this.app = new Application(canvas, { graphicsDeviceOptions: { antialias: false, alpha: false,
preserveDrawingBuffer: false, powerPreference: "default" } });
const app = this.app;
this.camera = new Entity("Editor camera", app);
this.scan = new Entity("Editor Gaussian proxy", app);
app.autoRender = false; app.graphicsDevice.maxPixelRatio = 1;
app.setCanvasFillMode(FILLMODE_NONE, 1, 1); app.setCanvasResolution(RESOLUTION_AUTO);
this.camera.addComponent("camera", { nearClip: .05, farClip: 3000, fov: 60, clearColor: new Color(.025,.03,.04) });
this.controls = new EditorCamera(canvas.parentElement!, canvas);
app.root.addChild(this.camera);
app.root.addChild(this.scan);
this.annotations = new PlannerMarkers(app,this.camera,canvas);
this.controls.pick = (x,y) => { const p=this.pick(x,y);return p?toEditor(p):null; };
const transform = new Mat4().set(localScene(cache).transforms.worldFromVisual);
this.scan.setPosition(transform.getTranslation());
this.scan.setRotation(new Quat().setFromMat4(transform));
this.scan.setLocalScale(transform.getScale());
app.scene.gsplat.splatBudget = 0;
this.resize = new ResizeObserver(() => {
const rect = canvas.parentElement!.getBoundingClientRect();
app.resizeCanvas(Math.max(1,rect.width), Math.max(1,rect.height));
this.controls.resize(Math.max(1,rect.width), Math.max(1,rect.height)); this.dirty = true;
});
this.resize.observe(canvas.parentElement!);
app.systems.gsplat?.on("frame:request", () => { app.renderNextFrame = true; });
app.on("update", (dt: number) => {
this.controls.update(dt); this.syncCamera();
if (this.annotations.setRotationCenter(this.controls.rotationCenter)) app.renderNextFrame = true;
if (this.annotations.update(dt)) app.renderNextFrame = true;
const matrix = this.camera.getWorldTransform().data.join(",");
if (matrix !== this.previous || this.dirty) {
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
this.onProject(this.points.map((p) => {
const [x,y,z] = toEditor(p.position);
return { id:p.id, base:this.project(x,y,z), top:this.project(x,y+this.preferences.waypoint.height,z),
x:this.project(x+this.annotations.axisLength,y,z), y:this.project(x,y+this.annotations.axisLength,z), z:this.project(x,y,z+this.annotations.axisLength) };
}));
}
});
app.start(); this.home();
}
async load() {
const scene = localScene(this.cache);
await this.terrain.load(scene.collision.meshUrl!, this.abort.signal, scene.transforms.worldFromCollision);
if (this.disposed) return;
this.height = [this.terrain.bounds.min.y, this.terrain.bounds.max.y];
if (this.height[1] <= this.height[0]) this.height = [this.height[0]-.5,this.height[1]+.5];
const asset = new Asset("Route editor", "gsplat", { url: scene.visual.streamedSogUrl! });
this.asset = asset;
await new Promise<void>((resolve,reject) => {
asset.once("error", (e: string) => reject(new Error(e)));
asset.ready(() => resolve()); this.app.assets.add(asset); this.app.assets.load(asset);
});
if (this.disposed) { asset.unload(); return; }
this.scan.addComponent("gsplat", { asset, unified: true });
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
uniform float editorClip;
void modifySplatCenter(inout vec3 center) {}
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
void modifySplatColor(vec3 center, inout vec4 color) {
// Unified work-buffer modifiers receive the calibrated world center.
if (center.y > editorClip) color.a = 0.0;
}` });
this.setPreferences(this.preferences);
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
this.setClip(Infinity); this.dirty = true;
}
setPoints(points: AiWaypoint[]) { this.points = points; this.annotations.set(points,this.selected,this.preferences);this.dirty = true; }
setSelected(id: string|null) {this.selected=id;this.annotations.set(this.points,id,this.preferences);this.dirty=true;}
setPreferences(preferences: PlannerPreferences) {
this.controls.navigation=preferences.navigation;
this.preferences=preferences;this.annotations.set(this.points,this.selected,preferences);
const profile=QUALITY_PROFILES[preferences.quality];
this.app.scene.gsplat.splatBudget=profile.splatBudget;
this.app.graphicsDevice.maxPixelRatio=Math.min(window.devicePixelRatio||1,profile.pixelRatio);
if(this.scan.gsplat) {
Object.assign(this.scan.gsplat,{lodBaseDistance:profile.lodBaseDistance,lodMultiplier:profile.lodMultiplier,lodRangeMin:profile.lodRangeMin,lodRangeMax:profile.lodRangeMax});
}
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
}
setClip(height: number) {
this.clip = height;
if (this.scan.gsplat) {
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
}
this.dirty = true;
}
setNavigation(enabled: boolean) {
this.controls.setNavigation(enabled);
}
setAddMode(add: boolean) { this.controls.setAddMode(add); }
private syncCamera() {
const { position:p, quaternion:q } = this.controls.camera;
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
}
home() {
const first = this.points[0]?.position ?? [...this.cache.world.settings.spawn_xy, this.cache.world.settings.ground_z];
this.controls.home(toEditor(first)); this.syncCamera(); this.dirty = true;
}
pick(x: number,y: number) {
const width = this.canvas.clientWidth, height = this.canvas.clientHeight;
const from = this.camera.camera!.screenToWorld(x*width,y*height,.05);
const to = this.camera.camera!.screenToWorld(x*width,y*height,2000);
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip);
return hit ? toMission(hit.toArray()) : null;
}
pickWaypoint(x:number,y:number) {
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const direction=[to.x-from.x,to.y-from.y,to.z-from.z];
let nearest=Infinity, id:string|null=null;
for(const point of this.points) {
const t=waypointHit([from.x,from.y,from.z],direction,toEditor(point.position),this.preferences.waypoint.diameter/2,this.preferences.waypoint.height);
if(t!==null && t<nearest){nearest=t;id=point.id;}
}
return id;
}
move(point: AiWaypoint, x: number, y: number, axis: WaypointAxis) {
const p = toEditor(point.position);
const from = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const hit = dragWaypoint([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],p,axis);
if (!hit) return null;
if (axis !== "xz") return toMission(hit);
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip);
return ground ? toMission(ground.toArray()) : null;
}
private project(x:number,y:number,z:number): ScreenPoint {
const point = this.camera.camera!.worldToScreen(new Vec3(x,y,z));
return point.z > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
}
dispose() {
this.disposed = true;
this.controls.dispose();
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
this.annotations.dispose();
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
}
}
@@ -0,0 +1,42 @@
import { lazy, Suspense, useEffect, useState } from "react";
import { LoadingRegion } from "@nodedc/ui-react";
import { polygonRequest } from "../../core/simulation/aiPolygon";
const SpatialPreview=lazy(()=>import("./AiSpatialPreview").then(m=>({default:m.AiSpatialPreview})));
export interface InferencePreview {
frame_id:number;simulation_time_ns:number;received_at:string;environment:"park"|"natural"|"urban";
layers:({id:string;label:string;ports?:string[];legend?:{class_id:number;label:string;color:string}[]} & (
{kind?:"image";jpeg:string} | {kind:"points3d";points:[number,number,number][];source_count:number;frame:string}
))[];
}
export function useInferencePreview(runId:string|undefined,active:boolean) {
const [preview,setPreview]=useState<InferencePreview|null>(null);
useEffect(()=>{
setPreview(null);if(!runId || !active)return;
const abort=new AbortController();let timer=0;
const poll=async()=>{
try {
if(document.visibilityState==="visible") {
const value=await polygonRequest<InferencePreview|null>(`/runs/${runId}/inference-preview`,{signal:abort.signal});
if(!abort.signal.aborted)setPreview(value);
}
} catch { /* Main status owns connection errors; retain the dated last frame. */ }
if(!abort.signal.aborted)timer=window.setTimeout(()=>void poll(),500);
};
void poll();return()=>{abort.abort();clearTimeout(timer);};
},[runId,active]);
return preview;
}
export function AiInferencePreview({preview,layer}:{preview:InferencePreview;layer:string}) {
const selected=preview.layers.find(p=>p.id===layer);
if(!selected)return null;
return <div className="ai-inference-preview" aria-label={`Результат AI: ${selected.label}`}>
{selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}>
<SpatialPreview points={selected.points} label={selected.label}/>
</Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>}
<div className="ai-inference-preview__caption">
Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
{selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null}
{selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null}
</div>
</div>;
}
@@ -0,0 +1,156 @@
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, Icon, IconButton, LoadingRegion, RangeControl, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
import { type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
import type { WaypointAxis } from "../../core/simulation/waypointDrag";
import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, busy=false }: {
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean;
}) {
const markerSvg=useRef<SVGSVGElement>(null);
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
const viewport = useRef<HTMLDivElement>(null), loadedPoints = useRef(initialPoints);
const [preferences] = usePlannerPreferences();
const runtime = useRef<AiEditorRuntime | null>(null);
const { expanded, toggle } = useSimulationFullscreen(host);
const [ready, setReady] = useState(false), [retry,setRetry] = useState(0);
const { cache,error,setError } = useLocalScene(world,retry);
const [editing,edit] = useReducer(editWaypoints,initialPoints,waypointEditing);
const {points,selected,sequence} = editing;
const press=useRef<{id:number;x:number;y:number}|null>(null);
const [markers, setMarkers] = useState<EditorMarker[]>([]);
const [mode,setMode] = useState<"view" | "add">("view");
const [clip,setClip] = useState(Infinity);
const draftId = useRef(crypto.randomUUID().replaceAll("-",""));
const drag = useRef<{ point: AiWaypoint; axis: WaypointAxis; offset: number[] } | null>(null);
const callback = useRef(onDraft); callback.current = onDraft;
useEffect(() => {
if (cache?.status !== "ready" || !canvas.current) return;
let active = true;
setReady(false); setError(null); setClip(Infinity);
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers); }
catch (e) { setError((e as Error).message); return; }
runtime.current = view;
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
void view.load().then(() => { if (active) setReady(true); }).catch((e: Error) => { if (active) setError(e.message); });
return () => { active=false; runtime.current=null; view.dispose(); callback.current(null); };
}, [cache?.key,cache?.status,retry]);
useEffect(() => {
runtime.current?.setPoints(points);
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
}, [points,cache,ready,sequence]);
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
useEffect(()=>{
if(loadedPoints.current === initialPoints) return;
loadedPoints.current=initialPoints;
edit({type:"load",points:initialPoints});
},[initialPoints]);
const add = (x:number,y:number) => {
if (points.length >= 33) { setError("В задании может быть до 33 точек."); return; }
const position = runtime.current?.pick(x,y);
if (!position) { setError("Под курсором нет доступной поверхности. Измените ракурс или срез."); return; }
const point = { id:crypto.randomUUID().replaceAll("-","").slice(0,16),position };
edit({type:"replace",points:[...points,point],selected:point.id});
};
const position = (e: { clientX:number;clientY:number }) => {
const rect = canvas.current!.getBoundingClientRect();
return [(e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height];
};
const progress = cache ? Object.values(cache.files) : [];
const bytes = progress.reduce((n,f)=>n+f.uploaded_bytes,0), total = progress.reduce((n,f)=>n+f.byte_length,0);
const message = cache?.status === "uploading" ? `Копируем сцену на диск · ${Math.round(bytes/Math.max(1,total)*100)}%`
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
return <div className="ai-polygon__stage" ref={host}>
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
<p>{points.length} точек · первая — старт, последняя — финиш</p></div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
onKeyDown={(e)=>{
const editable=!!(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"],.nodedc-workspace-window');
const action=waypointShortcut(e,editable);
if(!busy && ready && !drag.current && action){e.preventDefault();edit({type:action});setError(null);}
}}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning>
{ready?<div className="ai-local-editor__tools nodedc-scene-controls" inert={busy}>
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
}}><Icon name="trash"/></IconButton>:null}
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
</div>:null}
</SimulationViewTools>
<div className="ai-local-editor__surface"
onPointerDownCapture={(e)=>{
if(e.target!==canvas.current || e.button!==0 || busy || !ready)return;
const id=runtime.current?.pickWaypoint(...position(e) as [number,number]);
if(!id)return;
e.preventDefault();e.stopPropagation();press.current=null;
canvas.current?.focus({preventScroll:true});edit({type:"select",id});
const base=markers.find(m=>m.id===id)?.base;
if(!base)return;
edit({type:"begin"});
drag.current={point:points.find(p=>p.id===id)!,axis:"xz",offset:base.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);markerSvg.current!.setPointerCapture(e.pointerId);
}}
onPointerDown={(e)=>{if(e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
onPointerCancel={()=>{press.current=null;}}
onPointerUp={(e)=>{
const start=press.current;press.current=null;
if(!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
if(mode==="add")add(...position(e) as [number,number]);else edit({type:"select",id:null});
}}><canvas ref={canvas} aria-label="Локальная Gaussian-сцена для маршрута" />
<svg ref={markerSvg} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
onPointerMove={(e)=>{
if (!drag.current) return;
const d=drag.current, [x,y]=position(e);
const moved=runtime.current?.move(d.point,x+d.offset[0],y+d.offset[1],d.axis);
if(moved)edit({type:"move",points:points.map(p=>p.id===d.point.id?{...p,position:moved}:p)});
}}
onPointerUp={(e)=>{
drag.current=null;edit({type:"commit"});
runtime.current?.setNavigation(!busy);if(e.currentTarget.hasPointerCapture(e.pointerId))e.currentTarget.releasePointerCapture(e.pointerId); }}
onPointerCancel={()=>{edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}}>
<path className="ai-route__line" d={markers.map((m,i)=>m.base?`${i&&markers[i-1].base?"L":"M"}${m.base[0]*1280},${m.base[1]*720}`:"").join(" ")} />
{markers.map((m,i)=>m.base&&m.top ? <g key={m.id} data-waypoint="true" className={`ai-route__marker ${selected===m.id?"is-selected":""}`}
onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
e.preventDefault();e.stopPropagation();edit({type:"select",id:m.id});edit({type:"begin"});
drag.current={point:points.find((p)=>p.id===m.id)!,axis:"xz",offset:m.base!.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
}}>
<text x={m.top[0]*1280+10} y={m.top[1]*720}>{i===0?"Старт":i===markers.length-1?`Финиш · ${i}`:i}</text>
{selected===m.id ? (["x","y","z"] as const).map((axis)=>m[axis] ? <g key={axis} className="ai-local-editor__axis-hit" onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
e.preventDefault();e.stopPropagation();edit({type:"begin"});drag.current={point:points.find((p)=>p.id===m.id)!,axis,offset:m.base!.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
}}><line x1={m.base![0]*1280} y1={m.base![1]*720} x2={m[axis]![0]*1280} y2={m[axis]![1]*720}/>
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
</g>:null)}
</svg></div>
{!ready && !error ? <div className="ai-polygon__preview-error"><LoadingRegion loading label={message} /></div>:null}
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={Number.isFinite(clip)?clip:runtime.current!.height[1]}
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
onChange={(v)=>{const next=v>=runtime.current!.height[1]?Infinity:v;setClip(next);runtime.current!.setClip(next);}}/></div>
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
</div>
</div>
</div>;
}
@@ -0,0 +1,16 @@
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave}: {
name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
onClose:()=>void;onSave:()=>void;
}) {
return <Window open title={launch?"Сохранить задание и запустить":"Сохранить задание"}
size="sm" onClose={()=>{if(!busy)onClose();}}
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
<div className="ai-polygon__form">
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
</div>
</Window>;
}
@@ -0,0 +1,18 @@
import {useState} from 'react';
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function AiProfileWindow({initialName='',editing=false,busy,onClose,onSave,onRemove}: {
initialName?:string;editing?:boolean;busy:boolean;onClose:()=>void;
onSave:(name:string)=>void;onRemove?:()=>void;
}) {
const [name,setName]=useState(initialName);
return <Window open size="sm" title={editing?'Редактировать профиль AI':'Сохранить профиль AI'}
onClose={()=>{if(!busy)onClose();}} footer={<WindowFooterActions>
{onRemove&&<Button icon={<Icon name="trash"/>} disabled={busy} onClick={onRemove}>Удалить профиль</Button>}
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={()=>onSave(name.trim())}>
{editing?'Сохранить имя':'Сохранить профиль'}</Button>
</WindowFooterActions>}>
<TextField label="Название профиля" maxLength={120} value={name} disabled={busy}
onChange={e=>setName(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!busy&&name.trim())onSave(name.trim());}}/>
</Window>;
}
@@ -0,0 +1,140 @@
import { useEffect, useRef, useState, type PointerEvent } from "react";
import { Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon";
import { useAiPlanningControls } from "./useAiPlanningControls";
const xy = (p: NonNullable<ScreenPoint>) => `${p[0] * 1280},${p[1] * 720}`;
function path(points: ScreenPoint[]) {
let drawing = false;
return points.map((p) => {
if (!p) { drawing = false; return ""; }
const command = `${drawing ? "L" : "M"}${xy(p)}`; drawing = true; return command;
}).join(" ");
}
type Drag = { start: [number, number]; last: [number, number]; at: number;
action: "orbit" | "pan" | "move"; point_id?: string; axis?: "x" | "y" | "xy";
base?: NonNullable<ScreenPoint>; moved: boolean };
/** Screen-space annotations only. All geometry/projection and terrain picking belong to Worker. */
export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: { run: AiRun; onChange: (run: AiRun) => void; videoReady: boolean; visible?: boolean }) {
const host = useRef<HTMLDivElement>(null);
const svg = useRef<SVGSVGElement>(null);
const drag = useRef<Drag | null>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const [selected, setSelected] = useState<string | null>(null);
const [mode, setMode] = useState<"view" | "add">("view");
const [clip, setClip] = useState<number | null>(null);
const editing = run.request?.purpose === "planning";
const data = run.telemetry?.route_overlay;
const draft = run.telemetry?.planning;
const cameraReady = videoReady && editing && !!draft && run.control !== "stop";
const { send, busy, error, keyDown, stopKeys } = useAiPlanningControls(run, onChange, cameraReady);
const pending = busy || (run.planning_sequence ?? 0) > (draft?.sequence ?? 0);
const ready = cameraReady && !pending && !draft?.camera_moving;
const low = draft?.height_min, high = draft?.height_max;
useEffect(() => { if (!pending) setClip(draft?.clip_height ?? null); }, [pending, draft?.clip_height]);
useEffect(() => {
if (!host.current) return;
const resize = new ResizeObserver(([entry]) => {
const width = (editing ? Math.min : Math.max)(entry.contentRect.width, entry.contentRect.height * 16 / 9);
setSize({ width, height: width * 9 / 16 });
});
resize.observe(host.current); return () => resize.disconnect();
}, []);
const controls = useRef({ send, cameraReady }); controls.current = { send, cameraReady };
useEffect(() => {
const element = host.current;
const wheel = (event: WheelEvent) => {
if (!(event.target instanceof Element) || !event.target.closest(".ai-route__canvas")) return;
if (!controls.current.cameraReady) return;
event.preventDefault();
const pixels = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 720 : 1);
controls.current.send({ action: "zoom", amount: Math.max(-3, Math.min(3, pixels * .006)) });
};
element?.addEventListener("wheel", wheel, { passive: false });
return () => element?.removeEventListener("wheel", wheel);
}, []);
const position = (event: { clientX: number; clientY: number }): [number, number] => {
const rect = svg.current!.getBoundingClientRect();
return [(event.clientX - rect.left) / rect.width, (event.clientY - rect.top) / rect.height];
};
const start = (event: PointerEvent<SVGElement>, point?: string, axis?: Drag["axis"]) => {
if (!cameraReady || (point && !ready)) return;
event.stopPropagation(); event.preventDefault();
svg.current?.focus({ preventScroll: true });
const marker = data?.markers.find((m) => m.id === point);
if (point) setSelected(point);
const p = position(event);
drag.current = { start: p, last: p, at: performance.now(), moved: false,
action: point ? "move" : event.shiftKey || event.button === 1 ? "pan" : "orbit",
point_id: point, axis, base: marker?.base ?? undefined };
svg.current?.setPointerCapture(event.pointerId);
};
const move = (event: PointerEvent<SVGSVGElement>) => {
const d = drag.current; if (!d) return;
const p = position(event);
d.moved ||= Math.hypot(p[0] - d.start[0], p[1] - d.start[1]) > .005;
if (d.action !== "move" && d.moved && performance.now() - d.at > 100) {
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
d.last = p; d.at = performance.now();
}
};
const end = (event: PointerEvent<SVGSVGElement>) => {
const d = drag.current; drag.current = null; if (!d) return;
const p = position(event);
if (d.action === "move" && d.moved && d.base) {
send({ action: "move", point_id: d.point_id, axis: d.axis ?? "xy",
x: Math.max(0, Math.min(1, d.base[0] + p[0] - d.start[0])),
y: Math.max(0, Math.min(1, d.base[1] + p[1] - d.start[1])) });
} else if (!d.moved && !d.point_id && mode === "add" && ready) send({ action: "add", x: p[0], y: p[1] });
else if (d.moved && d.action !== "move") {
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
}
if (svg.current?.hasPointerCapture(event.pointerId)) svg.current.releasePointerCapture(event.pointerId);
};
return <div className="ai-route" ref={host} hidden={!videoReady}>
{data && visible ? <svg ref={svg} viewBox="0 0 1280 720" style={size}
className={`ai-route__canvas ${editing ? "ai-route__canvas--editing" : ""}`}
tabIndex={editing ? 0 : undefined} onKeyDown={keyDown} onBlur={stopKeys}
aria-label="Маршрут и точки задания" onContextMenu={(e) => e.preventDefault()}
onPointerDown={(e) => start(e)} onPointerMove={move} onPointerUp={end}
onPointerCancel={() => { drag.current = null; }}>
<path className="ai-route__line" d={path(data.markers.map((m) => m.base))} />
<path className="ai-route__trace" d={path(data.trace)} />
{data.markers.map((m, i) => m.base && m.top ? <g key={m.id}
className={`ai-route__marker ${selected === m.id ? "is-selected" : ""} ${!editing && i === data.active_index ? "is-active" : ""}`}
onPointerDown={(e) => start(e, m.id, "xy")}>
<line className="ai-route__beam" x1={m.base[0]*1280} y1={m.base[1]*720} x2={m.top[0]*1280} y2={m.top[1]*720} />
<circle cx={m.base[0]*1280} cy={m.base[1]*720} r="8" />
<text x={m.top[0]*1280+10} y={m.top[1]*720}>{i === 0 ? "Старт" : i === data.markers.length-1 ? `Финиш · ${i}` : i}</text>
{editing && selected === m.id ? (["x", "y"] as const).map((axis) => {
const p = axis === "x" ? m.x_axis : m.y_axis;
return p ? <g key={axis} className="ai-route__axis" onPointerDown={(e) => start(e, m.id, axis)}>
<line x1={m.base![0]*1280} y1={m.base![1]*720} x2={p[0]*1280} y2={p[1]*720} />
<circle cx={p[0]*1280} cy={p[1]*720} r="12" />
</g> : null;
}) : null}
</g> : null)}
</svg> : null}
{editing && low != null && high != null && high > low ? <div className="ai-route__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={clip ?? high}
min={low} max={high} step="any" disabled={!cameraReady}
formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`}
formatLimit={(value) => value.toFixed(1).replace('.', ',')}
onChange={(value) => {
const height = value >= high - Math.max(1, high-low)*1e-9 ? null : value;
setClip(height); send({ action: "clip", amount: value, enabled: height != null });
}} />
</div> : null}
{editing ? <div className="ai-route__tools">
<SegmentedControl label="Инструмент маршрута" size="dense" value={mode} onChange={setMode}
items={[{ value: "view", label: "Обзор" }, { value: "add", label: "Точка по клику" }]} />
<Button disabled={!ready} onClick={() => send({ action: "add", x: .5, y: .5 })}>Добавить waypoint</Button>
<Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button>
<Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p>
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null}
</div> : null}
</div>;
}
@@ -14,12 +14,12 @@ export function AiRunActions({ run, onChange }: { run: AiRun; onChange: (run: Ai
};
return <>
{!terminal ? <>
<Button disabled={!!busy || pending || ["starting", "stopping", "disconnected"].includes(run.state)}
{run.state !== "stopping" && run.state !== "starting" ? <Button disabled={!!busy || pending || ["starting", "stopping", "disconnected"].includes(run.state)}
variant={run.state === "ready" ? "primary" : "secondary"}
loading={busy === "pause" || busy === "play"}
onClick={() => command(run.state === "running" ? "pause" : "play")}>
{run.state === "starting" ? "Подготовка…" : run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
</Button>
{run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
</Button> : null}
<Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"}
icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button>
</> : null}
@@ -0,0 +1,73 @@
import { Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
import type { AiModules, AiRun } from "../../core/simulation/aiPolygon";
import { AiSessionSection, useSessionLayout } from "./AiSessionSection";
const outcomes = {
"goal-reached": "Маршрут пройден", "time-limit": "Лимит времени",
"operator-stop": "Остановлен оператором", stuck: "Проезд не найден",
unstable: "Опасный наклон", error: "Ошибка выполнения", "not-evaluated": "Результат не определён",
};
const reasons: Record<string, string> = {
"stale-camera": "Устарел кадр камеры", "stale-command": "Устарело решение",
"inference-error": "Ошибка inference", "no-road": "Не найдена поверхность для движения",
obstacle: "Препятствие", waiting: "Ожидание пути", uncertain: "Недостаточно данных",
paused: "Пауза оператора", "goal-reached": "Достижение цели", stuck: "Нет проезда",
unstable: "Опасный наклон", unknown: "Причина не записана",
};
const measured = (value: number | null, unit: string, digits = 1) =>
value === null ? "Нет измерения" : `${value.toFixed(digits)} ${unit}`;
export function AiRunReport({ runs, modules, onRemove, removing, worldId }: { worldId:string; runs: AiRun[]; modules: AiModules|null;
onRemove:(run:AiRun)=>void; removing:string|null }) {
const [open,setOpen] = useSessionLayout(`${worldId}:runs`, []);
const names = new Map(modules?.catalog.groups.flatMap(g=>g.modules.map(m=>[m.moduleId,m.label] as const)) ?? []);
const available = runs.filter((run) => run.request?.purpose !== "planning");
return <AiSessionSection scope={`${worldId}:results`} title="Результаты сессии">
{available.length ? <Inspector variant="panel" openSections={open} onOpenSectionsChange={setOpen} className="ai-polygon__history" sections={available.map((run)=>({
id:run.run_id, icon:<Icon name="activity"/>,
label:`${run.created_at || run.report?.generated_at ? new Date(run.created_at ?? run.report!.generated_at).toLocaleString("ru-RU") : "Время не записано"} · ${run.robot?.name ?? "Ровер не записан"} · ${run.plan_display_name ?? run.plan?.name ?? "Без задания"}`,
description:`${run.report ? outcomes[run.report.mission_outcome] : run.message ?? "Прогон выполняется"} · ${(run.request?.composition?.selections ?? []).map(s=>names.get(s.module_id) ?? s.module_id).join(" · ") || "AI не запускался"}`,
content:<GlassSurface padding="md"><RunDetails run={run}/></GlassSurface>,
action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`,
icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
onAction:()=>onRemove(run)},
}))}/> : <p>В этой локации ещё нет прогонов.</p>}
</AiSessionSection>;
}
function RunDetails({run}:{run:AiRun}) {
if(!run.report)return <p>{run.message ?? "Отчёт появится после завершения прогона."}</p>;
const report=run.report;
return <div className="ai-polygon__form ai-polygon__report">
<StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}>
{outcomes[report.mission_outcome]}
</StatusBadge>
<dl>
{run.state==='failed'&&run.message?<div><dt>Причина остановки</dt><dd>{run.message}</dd></div>:null}
<div><dt>Задание</dt><dd>{run.plan_display_name ?? run.plan?.name ?? "Без сохранённого задания"}</dd></div>
<div><dt>Ровер</dt><dd>{run.robot?.name ?? "Не записан"}</dd></div>
{run.rover_configuration?<div><dt>Масса / груз</dt><dd>{run.rover_configuration.total_mass_kg} / {run.rover_configuration.settings.payload_mass_kg} кг</dd></div>:null}
{report.speed?<><div><dt>Скорость · заданная / пиковая</dt><dd>{measured(report.speed.requested_max_mps,"м/с",3)} / {measured(report.speed.measured_max_mps,"м/с",3)}</dd></div>
<div><dt>Максимальное превышение / длительность</dt><dd>{measured(report.speed.maximum_excess_mps,"м/с",4)} / {measured(report.speed.seconds_above_requested,"с",2)}</dd></div></>:null}
<div><dt>Цели после стартовой точки</dt><dd>{report.waypoints_reached === null ? "Нет измерения" : `${report.waypoints_reached} / ${report.waypoint_count}`}</dd></div>
<div><dt>Пройдено</dt><dd>{measured(report.distance_m, "м", 2)}</dd></div>
<div><dt>Время мира</dt><dd>{measured(report.simulation_seconds, "с")}</dd></div>
<div><dt>До конечной цели</dt><dd>{measured(report.goal_error_m, "м", 2)}</dd></div>
<div><dt>Решения AI / ошибки</dt><dd>{report.inference_count} / {report.inference_errors}</dd></div>
<div><dt>Задержка AI · медиана / P95</dt><dd>{measured(report.inference_ms_p50, "мс", 0)} / {measured(report.inference_ms_p95, "мс", 0)}</dd></div>
<div><dt>Столкновения</dt><dd>{report.collision_count === null ? "Учёт ещё не подключён" : report.collision_count}</dd></div>
</dl>
<h3>Остановки после начала движения</h3>
{report.stops.length ? <dl>{report.stops.map((stop) => <div key={stop.reason}>
<dt>{reasons[stop.reason] ?? stop.reason}</dt><dd>{stop.events} · {stop.seconds.toFixed(1)} с</dd>
</div>)}</dl> : <p>Переходов от движения к нулевой команде не записано.</p>}
<p>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</p>
<dl className="ai-polygon__report-identities">
<div><dt>Прогон</dt><dd>{report.run_id}</dd></div>
<div><dt>Профиль ровера</dt><dd>{report.robot_sha256 ?? "Не записан"}</dd></div>
<div><dt>Композиция AI</dt><dd>{report.composition_sha256 ?? "Не запускалась"}</dd></div>
<div><dt>SHA-256 отчёта</dt><dd>{report.report_sha256}</dd></div>
<div><dt>SHA-256 архива</dt><dd>{report.manifest_sha256}</dd></div>
</dl>
</div>;
}
@@ -1,4 +1,3 @@
import type { ReactNode } from "react";
import { StatusBadge } from "@nodedc/ui-react";
import { type AiRun } from "../../core/simulation/aiPolygon";
@@ -16,37 +15,42 @@ const REASONS: Record<string, string> = {
"goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон",
waiting: "Ожидаем возможность движения",
};
export function AiRunView({ run, connection }: { run: AiRun; connection: ReactNode }) {
export function AiRunView({ run }: { run: AiRun }) {
const terminal = ["completed", "stopped", "failed"].includes(run.state);
const telemetry = run.telemetry;
const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0);
const preparingModels = run.state === "running" && run.phase === "models";
const reason = telemetry?.stop_reason === "unstable" ? "Остановка: опасный наклон"
const missionStopped = ["stuck", "goal-reached", "unstable"].includes(telemetry?.decision?.reason ?? "");
const reason = missionStopped ? REASONS[telemetry!.decision!.reason] : telemetry?.stop_reason === "unstable" ? "Остановка: опасный наклон"
: telemetry?.stop_reason === "stale-camera" || telemetry?.stop_reason === "stale-command"
? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error"
? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01
? "Ровер не движется" : REASONS[telemetry?.decision?.reason ?? ""];
const showTelemetry = telemetry && !terminal && !["stopping", "disconnected"].includes(run.state);
const live = showTelemetry && run.state === "running";
const metrics = [
["Скорость", showTelemetry ? `${Math.abs(telemetry.speed_mps).toFixed(2)} м/с` : "—"],
["Пройдено", (terminal?run.report?.distance_m:telemetry?.distance_m) != null ? `${(terminal?run.report!.distance_m:telemetry!.distance_m)!.toFixed(1)} м` : "—"],
["Время мира", showTelemetry ? `${(telemetry.simulation_time_ns / 1e9).toFixed(1)} с` : "—"],
["Симуляция", live ? `${telemetry.rtf.toFixed(2)}×` : "—"],
["Камера", live ? `${telemetry.sensor_fps.toFixed(1)} FPS` : "—"],
["AI", live ? `${telemetry.ai_hz.toFixed(1)} решений/с` : "—"],
["Inference", live && telemetry.inference_ms !== null ? `${telemetry.inference_ms.toFixed(0)} мс` : "—"],
["Возраст кадра", live && telemetry.frame_age_ms !== null ? `${telemetry.frame_age_ms.toFixed(0)} мс` : "—"],
];
return <section className="ai-polygon__run" aria-label="Управление симуляцией">
<div className="ai-polygon__telemetry-row">
<div className="ai-polygon__facts">
{run.state !== "ready" && run.state !== "running" || preparingModels || pending ? <StatusBadge tone={run.state === "failed" || run.state === "disconnected" ? "warning" : "neutral"}>
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : STATES[run.state]}
</StatusBadge> : null}
{telemetry && !terminal && run.state !== "stopping" && run.state !== "disconnected" ? <div className="ai-polygon__facts">
{run.state === "running" && !preparingModels && reason ? <strong>{reason}</strong> : null}
<span>Скорость: {Math.abs(telemetry.speed_mps).toFixed(2)} м/с</span>
<span>Время мира: {(telemetry.simulation_time_ns / 1e9).toFixed(1)} с</span>
{run.state === "running" ? <>
<span>Симуляция: {telemetry.rtf.toFixed(2)}×</span>
<span>Камера: {telemetry.sensor_fps.toFixed(1)} FPS</span>
<span>AI: {telemetry.ai_hz.toFixed(1)} решений/с</span>
{telemetry.inference_ms !== null ? <span>Inference: {telemetry.inference_ms.toFixed(0)} мс</span> : null}
{telemetry.frame_age_ms !== null ? <span>Возраст кадра: {telemetry.frame_age_ms.toFixed(0)} мс</span> : null}
</> : null}
</div> : null}
</div>
{connection}
</div>
<dl className="ai-polygon__run-metrics">
<div className="ai-polygon__run-metric ai-polygon__run-metric--status">
<dt>Состояние</dt><dd>
<StatusBadge tone={run.state === "failed" || run.state === "disconnected" || (run.state === "running" && telemetry?.decision?.reason === "stuck") ? "warning" : run.state === "running" && !preparingModels && !pending ? "success" : "neutral"}>
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : run.state === "running" && reason ? reason : STATES[run.state]}
</StatusBadge>
</dd>
</div>
{metrics.map(([label, value]) => <div className="ai-polygon__run-metric" key={label}>
<dt>{label}</dt><dd>{value}</dd>
</div>)}
</dl>
{run.state === "failed" && run.message ? <p>{run.message}</p> : null}
</section>;
}
@@ -0,0 +1,27 @@
import { useState, type ReactNode } from "react";
import { GlassSurface, Icon, Inspector } from "@nodedc/ui-react";
/** Layout belongs to the operator and location, not a particular live run. */
export function useSessionLayout(scope: string, initial: string[]) {
const key = `nodedc.simulation.layout.v1:${scope}`;
const [open, setOpen] = useState<string[]>(() => {
try {
const value: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
if (Array.isArray(value) && value.every(id => typeof id === "string")) return value;
} catch { /* Private browsing or older invalid preferences use the default. */ }
return initial;
});
return [open, (ids: string[]) => {
setOpen(ids);
try { localStorage.setItem(key, JSON.stringify(ids)); } catch { /* This session still works. */ }
}] as const;
}
export function AiSessionSection({ scope, title, children, initiallyOpen = true }: {
scope: string; title: string; children: ReactNode; initiallyOpen?: boolean;
}) {
const [open, setOpen] = useSessionLayout(scope, initiallyOpen ? ["body"] : []);
return <Inspector variant="panel" openSections={open} onOpenSectionsChange={setOpen}
sections={[{ id: "body", label: title, icon: <Icon name={scope.endsWith("results") ? "activity" : "settings"} />,
content: <GlassSurface padding="md" className="ai-polygon__section">{children}</GlassSurface> }]} />;
}
@@ -0,0 +1,11 @@
import { LaboratoryMetricEvidenceScene, type LaboratoryMetricPoint3 } from "../laboratory/LaboratoryMetricEvidenceScene";
const EMPTY: [] = [];
// View framing only; no fabricated rig or corridor is drawn on sensor evidence.
const FRAMING = { forwardLengthM: 8, rearMarginM: 0, halfWidthM: 0 };
const NO_RIG = { lengthM: 0, widthM: 0, nominalSensorHeightM: 0 };
export function AiSpatialPreview({ points, label }: { points: LaboratoryMetricPoint3[]; label:string }) {
return <LaboratoryMetricEvidenceScene pointCloudBodyXyzM={points} localSurfaceBodyXyzM={EMPTY}
obstacles={EMPTY} rig={NO_RIG} corridor={FRAMING} occupiedVoxelSizeM={0.1} mode="3d" label={label}
showCurrentIncrement showLocalSurface={false} showRollingMap={false} showReferenceGeometry={false} showRenderStats={false}/>;
}
@@ -0,0 +1,39 @@
import { useState } from "react";
import { Button, Icon, InspectorSelectField, Select, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { aiPlanName, updateAiPlan, type AiPlan } from "../../core/simulation/aiPolygon";
export function AiTaskSelect({plans,value,disabled,onChange,onUpdated,inspector=false}: {
inspector?:boolean;plans:AiPlan[];value:string;disabled:boolean;onChange:(id:string)=>void;onUpdated:(plan:AiPlan)=>void;
}) {
const TaskSelect = inspector ? InspectorSelectField : Select;
const [editing,setEditing]=useState<AiPlan|null>(null);
const [name,setName]=useState("");
const [busy,setBusy]=useState(false);
const [error,setError]=useState<string|null>(null);
const save=(removed=false)=>{
if(!editing||busy)return;
setBusy(true);
void updateAiPlan(editing.plan_id,removed?{removed:true}:{display_name:name.trim()})
.then(plan=>{onUpdated(plan);setEditing(null);})
.catch((caught:Error)=>setError(caught.message)).finally(()=>setBusy(false));
};
return <>
<div className="ai-polygon__plan-select"><TaskSelect label="Задание" value={value} disabled={disabled}
onChange={onChange} options={[
{value:"",label:"Новое задание"},
...plans.map(plan=>({value:plan.plan_id,label:aiPlanName(plan),
description:`${plan.points.length} точек · ${plan.length_m.toFixed(1)} м`,
action:{label:`Редактировать задание «${aiPlanName(plan)}»`,icon:<Icon name="edit"/>,
onAction:()=>{setName(aiPlanName(plan));setEditing(plan);setError(null);}},
})),
]}/></div>
<Window open={!!editing} title="Редактировать задание" size="sm" onClose={()=>{if(!busy)setEditing(null);}}
footer={<WindowFooterActions>
<Button icon={<Icon name="trash"/>} disabled={busy} onClick={()=>save(true)}>Удалить задание</Button>
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={()=>save()}>Сохранить имя</Button>
</WindowFooterActions>}>
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={e=>setName(e.target.value)}/>
</Window>
{error?<ToastStack items={[{id:"task-edit",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</>;
}
@@ -1,12 +1,11 @@
import { useState } from "react";
import { Button, TextField, TextAreaField, ToastStack } from "@nodedc/ui-react";
import { Button, TextField, ToastStack } from "@nodedc/ui-react";
import { configureAiWorld, type AiWorld, type AiWorldSettings } from "../../core/simulation/aiPolygon";
export function AiWorldSetup({ world, disabled, onSaved }: {
world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void;
}) {
const [draft, setDraft] = useState<AiWorldSettings>(world.settings);
const [route, setRoute] = useState((world.settings.route_xy ?? []).map((p) => p.join(" ")).join("\n"));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const field = (label: string, value: number, change: (value: number) => void) =>
@@ -26,16 +25,9 @@ export function AiWorldSetup({ world, disabled, onSaved }: {
{field("Направление, °", draft.heading_degrees, (v) => setDraft({ ...draft, heading_degrees: v }))}
{field("Высота камеры, м", draft.camera_height_m, (v) => setDraft({ ...draft, camera_height_m: v }))}
{field("Скорость до, м/с", draft.max_speed_mps, (v) => setDraft({ ...draft, max_speed_mps: v }))}
<TextAreaField label="Точки маршрута, X Y в метрах" rows={3} value={route}
hint="Каждая точка — с новой строки. Пустое поле: движение по видимой тропе."
disabled={disabled || busy} onChange={(e) => setRoute(e.target.value)} />
<Button disabled={disabled} loading={busy} onClick={() => {
const points = route.trim() ? route.trim().split(/\n+/).map((line) => line.trim().split(/\s+/).map(Number)) : [];
if (points.length > 32 || points.some((p) => p.length !== 2 || p.some((v) => !Number.isFinite(v)))) {
setError("Укажите не более 32 точек: два числа X Y в каждой строке."); return;
}
setBusy(true); setError(null);
void configureAiWorld(world, { ...draft, route_xy: points as [number, number][], prepared: true }).then(onSaved)
void configureAiWorld(world, { ...draft, prepared: true }).then(onSaved)
.catch((caught: Error) => setError(caught.message)).finally(() => setBusy(false));
}}>Сохранить старт и масштаб</Button>
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Настройки не сохранены", description: error }]} onDismiss={() => setError(null)} /> : null}
@@ -1,88 +1,38 @@
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useCallback, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Button, Icon, IconButton, LoadingRegion, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
import { Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon";
import { WorkerVideo, type WorkerVideoState } from "./WorkerVideo";
import { AiRouteOverlay } from "./AiRouteOverlay";
import { useInferencePreview } from "./AiInferencePreview";
import { SimulationObservationDeck } from "./SimulationObservationDeck";
import { useObserverInput } from "./useObserverInput";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
// NVIDIA has process-global browser listeners. Serialize replacement/cleanup,
// including React StrictMode, without letting an old viewer terminate a new one.
let streamLifecycle: Promise<unknown> = Promise.resolve();
/** Decode the actual Worker stream. This component never loads a world or creates a 3D engine. */
export function AiWorldStream({ world, run, onBack, onChange, controls, headerActions, actionsHost }: {
world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode;
headerActions?: ReactNode; actionsHost?: HTMLElement | null;
}) {
const frame = useRef<HTMLDivElement>(null);
const video = useRef<HTMLVideoElement>(null);
const id = useId().replaceAll(":", "");
const frame = useRef<HTMLDivElement>(null), surface=useRef<HTMLDivElement>(null);
const { expanded, toggle } = useSimulationFullscreen(frame);
const [state, setState] = useState<"connecting" | "live" | "failed" | "stalled">("connecting");
const [state, setState] = useState<WorkerVideoState>("connecting");
const [fps, setFps] = useState<number | null>(null);
const [revision, setRevision] = useState(0);
const [cameraError, setCameraError] = useState(false);
const [routeVisible, setRouteVisible] = useState(true);
const endpoint = run?.worker?.stream;
const terminal = !run || ["completed", "stopped", "failed"].includes(run.state);
const connectable = !terminal && !!run?.telemetry?.stream_ready && !!endpoint;
const endpointKey = JSON.stringify(endpoint);
useEffect(() => {
if (!connectable || !endpoint || !video.current) return;
let disposed = false;
let stream: import("@nvidia/ov-web-rtc").AppStreamer | undefined;
let settle!: () => void;
const settled = new Promise<void>((resolve) => { settle = resolve; });
let callback = 0;
let lastFrame = performance.now();
let frames = 0;
let measuredAt = performance.now();
let connected = false;
setState("connecting"); setFps(null);
const element = video.current;
const received = () => {
if (disposed) return;
lastFrame = performance.now(); frames += 1; connected = true; setState("live");
callback = element.requestVideoFrameCallback(received);
};
callback = element.requestVideoFrameCallback(received);
const timer = setInterval(() => {
const now = performance.now();
setFps(frames * 1000 / (now - measuredAt));
frames = 0; measuredAt = now;
if (connected && now - lastFrame > 3000) setState("stalled");
}, 1000);
const setup = streamLifecycle.catch(() => undefined).then(async () => {
const sdk = await import("@nvidia/ov-web-rtc");
if (disposed) { settle(); return; }
stream = new sdk.AppStreamer();
await stream.connect({ streamSource: sdk.StreamType.DIRECT, logLevel: sdk.LogLevel.WARN,
streamConfig: { signalingServer: endpoint.server, signalingPort: endpoint.signaling_port,
signalingPath: "/", mediaServer: endpoint.server, mediaPort: endpoint.media_port,
width: endpoint.width, height: endpoint.height, fps: endpoint.fps,
videoElementId: `polygon-video-${id}`, audioElementId: `polygon-audio-${id}`,
autoLaunch: true, mic: false, enableAV1Support: false, fitStreamResolution: false,
maxReconnects: 1, reconnectDelay: 2000, connectivityTimeout: 5000,
onStart: (event) => {
if (event.status === sdk.EventStatus.SUCCESS || event.status === sdk.EventStatus.ERROR
|| event.status === sdk.EventStatus.CANCELED) settle();
if (!disposed && event.status === sdk.EventStatus.ERROR) setState("failed");
},
onStop: () => { settle(); if (!disposed) setState("stalled"); },
} });
if (stream.streamStatus !== sdk.StreamStatus.STARTING) settle();
}).catch(() => { settle(); if (!disposed) setState("failed"); });
streamLifecycle = setup;
return () => {
disposed = true; clearInterval(timer); element.cancelVideoFrameCallback(callback);
// connect() resolves with IN_PROGRESS; terminate() during STARTING does
// not dispose the SDK. Await its final callback before admitting a new owner.
streamLifecycle = setup.then(async () => {
await settled;
await stream?.terminate(false);
}).catch(() => undefined);
};
// A telemetry refresh must never reconnect or reload the stream.
}, [connectable, endpointKey, run?.run_id, id, revision]);
const mode = run?.camera ?? "follow";
const cameraOptions: { value: AiCamera; label: string; disabled: boolean }[] = [
{ value: "follow", label: "От третьего лица", disabled: terminal },
{ value: "overview", label: "Свободный обзор", disabled: terminal },
{ value: "camera", label: "От первого лица", disabled: terminal },
];
const preview=useInferencePreview(run?.run_id,!terminal);
const inputError=useCallback(()=>setCameraError(true),[]);
useObserverInput(surface,run?.run_id,mode,connectable&&state==="live",inputError);
const changeCamera = (camera: AiCamera) => {
if (!run) return;
setCameraError(false);
@@ -99,35 +49,33 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
</div> : null}
{controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null}
<div className="ai-polygon__viewer">
<div className="ai-polygon__viewer-toolbar">
<SegmentedControl<AiCamera> label="Вид симуляции" size="dense" value={mode} onChange={changeCamera}
items={[{ value: "follow", label: "За ровером", disabled: terminal },
{ value: "overview", label: "Обзор", disabled: terminal }, { value: "camera", label: "Камера AI", disabled: terminal }]} />
<div className="ai-polygon__actions">
{connectable ? <StatusBadge tone={state === "live" ? "success" : "warning"}>
{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : "Ожидаем видео"}
</StatusBadge> : null}
<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}>
<Icon name={expanded ? "minimize" : "expand"} />
</IconButton>
</div>
</div>
<SimulationObservationDeck preview={preview}
toolbar={<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}><Icon name={expanded ? "minimize" : "expand"} /></IconButton>}
videoActions={<Dropdown placement="bottom-end" width={280} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><IconButton ref={setTriggerRef} label="Настройки вида симуляции" aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}><Icon name="settings"/></IconButton>}>
<div className="ai-polygon__layer-options">
{run?.request?.purpose === "planning" ? <StatusBadge tone="neutral">Планирование маршрута</StatusBadge> : <Select<AiCamera> label="Вид симуляции" value={mode} onChange={changeCamera} options={cameraOptions} disabled={terminal} />}
{run?.telemetry?.route_overlay && run.request?.purpose !== "planning" ? <Checker label="Показывать маршрут" checked={routeVisible} onChange={setRouteVisible}/> : null}
</div>
</Dropdown>}
video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
<div className="ai-polygon__stream-picture">
{connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
<div className="ai-polygon__viewport">
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
<div className="ai-polygon__video" inert>
<video ref={video} id={`polygon-video-${id}`} autoPlay muted playsInline tabIndex={-1}
aria-label={`Видео симуляции ${world.name} с Worker`} />
<audio id={`polygon-audio-${id}`} muted />
{connectable&&endpoint&&state!=="failed"?<WorkerVideo key={`${run?.run_id}:${revision}`} endpoint={endpoint}
onState={(status,value)=>{setState(status);setFps(value);}}/>:null}
</div>
</LoadingRegion>
{!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null}
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div>
: connectable && (state === "failed" || state === "stalled") ? <div className="ai-polygon__preview-error" role="status">
<p>Видеопоток прерван. Состояние симуляции показано выше.</p>
<Button onClick={() => setRevision((value) => value + 1)}>Подключить видео</Button>
: connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
<p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
<Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
</div> : null}
</div>
</div>}/>
</div>
</div>;
}
@@ -0,0 +1,100 @@
import { DEFAULT_PLANNER_PREFERENCES, panSensitivity } from "../../core/simulation/plannerPreferences";
import { zoomDisplacement } from "../../core/simulation/editorZoom";
import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/editorNavigation";
import { PerspectiveCamera, Vector3 } from "three";
const KEYS = new Set(["KeyW","KeyA","KeyS","KeyD","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","KeyQ","KeyE","ShiftLeft","ShiftRight"]);
/** Input/math only: PlayCanvas remains the sole renderer. */
export class EditorCamera {
readonly camera = new PerspectiveCamera(60, 1, .05, 3000);
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
get rotationCenter(){return this.gesture&&!this.gesture.pan?this.gesture.anchor:null;}
private keys = new Set<string>();
private enabled=true;
private addMode=false;
private gesture: {id:number;x:number;y:number;anchor:Vector3;depth:number;distance:number;pan:boolean}|null=null;
private forward = new Vector3();
private right = new Vector3();
private delta = new Vector3();
sceneCenter = new Vector3();
pick: ((x:number,y:number)=>number[]|null)|null = null;
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
surface.addEventListener("wheel",this.zoom,{passive:false});
surface.addEventListener("pointerdown",this.pointerDown);
surface.addEventListener("pointermove",this.pointerMove);
surface.addEventListener("pointerup",this.pointerEnd);
surface.addEventListener("pointercancel",this.pointerEnd);
surface.addEventListener("lostpointercapture",this.pointerEnd);
window.addEventListener("keydown",this.keyDown);
window.addEventListener("keyup",this.keyUp);
window.addEventListener("blur",this.clear);
canvas.addEventListener("blur",this.clear);
}
private anchor(x:number,y:number) {
const hit=this.pick?.(x,y);
if(hit)return new Vector3(...hit);
// Empty sky has no surface; retain useful scale relative to the scene.
return this.camera.getWorldDirection(new Vector3())
.multiplyScalar(Math.max(2,this.camera.position.distanceTo(this.sceneCenter))).add(this.camera.position);
}
private pointerDown=(e:PointerEvent)=>{
this.canvas.focus({preventScroll:true});
if(!this.enabled || (e.target as Element).closest("[data-waypoint]") || ![0,1,2].includes(e.button))return;
if(e.button===0 && this.addMode)return;
const rect=this.canvas.getBoundingClientRect();
const anchor=this.anchor((e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height);
this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0};
this.surface.setPointerCapture(e.pointerId);
};
private pointerMove=(e:PointerEvent)=>{
const g=this.gesture;if(!g||g.id!==e.pointerId||!this.enabled)return;
const dx=e.clientX-g.x,dy=e.clientY-g.y;g.x=e.clientX;g.y=e.clientY;
if(g.pan)panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
};
private pointerEnd=(e:PointerEvent)=>{
if(this.gesture?.id!==e.pointerId)return;
this.gesture=null;
if(this.surface.hasPointerCapture(e.pointerId))this.surface.releasePointerCapture(e.pointerId);
};
private zoom=(e:WheelEvent)=>{
if(!this.enabled)return;
e.preventDefault();this.canvas.focus({preventScroll:true});
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const ray=new Vector3(x*2-1,1-y*2,.5).unproject(this.camera).sub(this.camera.position).normalize();
const depth=this.camera.position.distanceTo(this.anchor(x,y));
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?rect.height:1);
this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));this.camera.updateMatrixWorld();
};
private keyDown=(e:KeyboardEvent)=>{
if(document.activeElement!==this.canvas || e.ctrlKey || e.metaKey || e.altKey || !KEYS.has(e.code))return;
e.preventDefault();this.keys.add(e.code);
};
private keyUp=(e:KeyboardEvent)=>{this.keys.delete(e.code);};
private clear=()=>{this.keys.clear();this.gesture=null;};
resize(width:number,height:number){this.camera.aspect=width/height;this.camera.updateProjectionMatrix();}
home(point:number[]){
const target=new Vector3(...point);
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.addMode=add;}
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
update(dt:number){
if(!this.enabled||!this.keys.size)return;
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
this.delta.copy(this.forward).multiplyScalar(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown"))
.addScaledVector(this.right,pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft"));
this.delta.y+=pressed("KeyE")-pressed("KeyQ");
this.delta.normalize().multiplyScalar(Math.min(.1,Math.max(0,dt))*(pressed("ShiftLeft","ShiftRight")?16:4));
this.camera.position.add(this.delta);this.camera.updateMatrixWorld();
}
dispose(){
this.clear();this.surface.removeEventListener("wheel",this.zoom);
this.surface.removeEventListener("pointerdown",this.pointerDown);this.surface.removeEventListener("pointermove",this.pointerMove);
this.surface.removeEventListener("pointerup",this.pointerEnd);this.surface.removeEventListener("pointercancel",this.pointerEnd);
this.surface.removeEventListener("lostpointercapture",this.pointerEnd);
window.removeEventListener("keydown",this.keyDown);window.removeEventListener("keyup",this.keyUp);
window.removeEventListener("blur",this.clear);this.canvas.removeEventListener("blur",this.clear);
}
}
@@ -0,0 +1,63 @@
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Mesh, Matrix4, Ray, Vector3 } from "three";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { MeshBVH } from "three-mesh-bvh";
import { GenerateMeshBVHWorker } from "three-mesh-bvh/worker";
/** CPU picking only: no Three renderer, physical stepping, or AI in the editor. */
export class EditorTerrain {
private draco = new DRACOLoader().setDecoderPath({
js: "/vendor/playcanvas/draco/1.5.7/draco_wasm_wrapper_gltf.js",
wasm: "/vendor/playcanvas/draco/1.5.7/draco_decoder_gltf.wasm",
}).setWorkerLimit(1);
private builder: GenerateMeshBVHWorker | null = new GenerateMeshBVHWorker();
private trees: MeshBVH[] = [];
private geometries: BufferGeometry[] = [];
private disposed = false;
bounds = new Box3();
async load(url: string, signal: AbortSignal, transform?: number[]) {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error("Не удалось открыть поверхность локации.");
const gltf = await new GLTFLoader().setDRACOLoader(this.draco).parseAsync(await response.arrayBuffer(), "");
if (this.disposed || signal.aborted) {
gltf.scene.traverse((object) => { if (object instanceof Mesh) object.geometry.dispose(); });
throw new DOMException("Aborted", "AbortError");
}
if (transform) gltf.scene.applyMatrix4(new Matrix4().fromArray(transform));
gltf.scene.updateMatrixWorld(true);
gltf.scene.traverse((object) => {
if (!(object instanceof Mesh)) return;
const input = object.geometry;
const geometry = new BufferGeometry();
const position = input.getAttribute("position");
const xyz = new Float32Array(position.count * 3);
const p = new Vector3();
for (let i = 0; i < position.count; i++) {
p.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
xyz[i*3] = p.x; xyz[i*3+1] = p.y; xyz[i*3+2] = p.z;
}
geometry.setAttribute("position", new BufferAttribute(xyz, 3));
geometry.setIndex(input.index!.clone());
geometry.computeBoundingBox(); this.bounds.union(geometry.boundingBox!);
this.geometries.push(geometry); input.dispose();
});
for (const geometry of this.geometries) {
if (this.disposed || signal.aborted) throw new DOMException("Aborted", "AbortError");
this.trees.push(await this.builder!.generate(geometry, { maxLeafTris: 10 }));
}
this.builder?.dispose(); this.builder = null;
}
pick(origin: number[], direction: number[], clip = Infinity) {
const ray = new Ray(new Vector3(...origin), new Vector3(...direction).normalize());
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.sort((a, b) => a.distance - b.distance)[0]?.point ?? null;
}
ground(x: number, z: number, near: number, clip = Infinity) {
const ray = new Ray(new Vector3(x, this.bounds.max.y + 1, z), new Vector3(0, -1, 0));
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.sort((a, b) => Math.abs(a.point.y - near) - Math.abs(b.point.y - near))[0]?.point ?? null;
}
dispose() { this.disposed = true; this.draco.dispose(); this.builder?.dispose(); this.builder = null; this.geometries.forEach((g) => g.dispose()); this.trees = []; }
}
@@ -0,0 +1,55 @@
import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon";
import type { RoverSettings } from "../../core/simulation/roverSettings";
import { toEditor } from "../../core/simulation/aiEditor";
import { PlayCanvasRuntime } from "./PlayCanvasRuntime";
import { localScene } from "./localScene";
import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export function LocalManualScene({world,robot,settings,actionsHost,headerActions}: {
world:AiWorld; robot:AiRobot; settings?:RoverSettings; actionsHost:HTMLElement|null; headerActions:React.ReactNode;
}) {
const [preferences]=usePlannerPreferences();
const host=useRef<HTMLDivElement>(null), canvas=useRef<HTMLCanvasElement>(null);
const viewport=useRef<HTMLDivElement>(null);
const runtime=useRef<PlayCanvasRuntime|null>(null);
const [retry,setRetry]=useState(0), [ready,setReady]=useState(false), [speed,setSpeed]=useState(0);
const {cache,error,setError}=useLocalScene(world,retry);
const {expanded,toggle}=useSimulationFullscreen(host);
useEffect(()=>{
if(cache?.status!=="ready"||!canvas.current)return;
let active=true;
const view=new PlayCanvasRuntime(); runtime.current=view; setReady(false);
void (async()=>{
await view.mount(canvas.current!); if(!active)return;
view.setQuality(preferences.quality);
await view.loadWorld(localScene(cache)); if(!active)return;
const configured = settings ? {...robot,physics:{...robot.physics,mass_kg:settings.base_mass_kg+settings.payload_mass_kg}} : robot;
await view.setRobot(configured,toEditor([...world.settings.spawn_xy,world.settings.ground_z]),90+world.settings.heading_degrees,settings?.max_speed_mps);
if(!active)return;
await view.setControlMode("ugv"); if(active)setReady(true);
})().catch((e:Error)=>{if(active)setError(e.message);});
const timer=setInterval(()=>{if(active)setSpeed(view.speed);},250);
return ()=>{active=false;clearInterval(timer);view.dispose();runtime.current=null;};
},[cache?.key,cache?.status,robot.sha256,retry]);
useEffect(()=>{runtime.current?.setQuality(preferences.quality);},[preferences.quality,ready]);
return <div className="ai-polygon__stage" ref={host}>
{expanded?<div className="ai-polygon__actions">{headerActions}</div>:actionsHost?createPortal(headerActions,actionsHost):null}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready?"success":"neutral"}>{ready?"Ручное управление · локально":"Подготовка сцены"}</StatusBadge></div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport}/>
<canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} />
{ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null}
{!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null}
{error?<div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
</div>
</div>
</div>;
}
@@ -0,0 +1,99 @@
import { Application, BLEND_NORMAL, Color, Entity, Layer, StandardMaterial, Vec3 } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import type { AiWaypoint } from "../../core/simulation/aiPolygon";
import { axisWorldLength, DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
/** Operator-only geometry: never exported into the Worker scene or inference camera. */
export class PlannerMarkers {
private centroid:Entity|null=null;
private layer = new Layer({name:"Planner annotations", clearDepthBuffer:true});
private root = new Entity("Route annotations");
private materials: StandardMaterial[] = [];
private beams: { entity: Entity; material: StandardMaterial; index: number }[] = [];
private pivot = new Entity("Waypoint pivot");
private arrows: {shaft: Entity; cone: Entity; axis: "x"|"y"|"z"}[] = [];
private points: AiWaypoint[] = [];
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private elapsed = 0;
axisLength = 1;
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {
app.scene.layers.push(this.layer);
camera.camera!.layers=[...camera.camera!.layers,this.layer.id];
app.root.addChild(this.root); this.root.addChild(this.pivot);
const light = new Entity("Annotation light");
light.addComponent("light", {type:"directional",color:new Color(1,1,1),intensity:1,layers:[this.layer.id]});
light.setEulerAngles(35,25,0);this.root.addChild(light);
app.scene.ambientLight = new Color(.45,.45,.45);
}
private material(color: string, opacity: number) {
const m = new StandardMaterial(); m.diffuse.fromString(color);m.emissive.copy(m.diffuse).mulScalar(.12);
m.opacity=opacity;m.blendType=BLEND_NORMAL;m.depthWrite=false;m.update();this.materials.push(m);return m;
}
private shape(name: string, type: "cylinder"|"cone"|"sphere", material: StandardMaterial, parent: Entity) {
const entity=new Entity(name);entity.addComponent("render",{type,material,layers:[this.layer.id],castShadows:false,receiveShadows:false});parent.addChild(entity);return entity;
}
set(points: AiWaypoint[], selected: string|null, preferences: PlannerPreferences) {
if(this.centroid && this.selected===selected && this.preferences===preferences && points.length===this.points.length && points.every((v,i)=>v.id===this.points[i].id)) {
this.points=points;
this.beams.forEach(({entity},i)=>{const [x,y,z]=toEditor(points[i].position);entity.setPosition(x,y+preferences.waypoint.height/2,z);});
return;
}
this.points=points;this.selected=selected;this.preferences=preferences;
this.centroid?.destroy();this.centroid=null;
this.beams.forEach(({entity})=>entity.destroy());this.beams=[];
this.arrows.forEach(({shaft,cone})=>{shaft.destroy();cone.destroy();});this.arrows=[];
this.materials.forEach(m=>m.destroy());this.materials=[];
const w=preferences.waypoint,p=preferences.pivot,n=preferences.navigation;
this.centroid=this.shape("Rotation centre","sphere",this.material(n.centroidColor,n.centroidOpacity),this.root);
this.centroid.enabled=false;
for(const [index,point] of points.entries()) {
const [x,y,z]=toEditor(point.position),material=this.material(w.color,w.opacity);
material.emissive.fromString(w.emissionColor);material.emissiveIntensity=w.emission;material.update();
const entity=this.shape(point.id,"cylinder",material,this.root);
entity.setPosition(x,y+w.height/2,z);entity.setLocalScale(w.diameter,w.height,w.diameter);
this.beams.push({entity,material,index});
}
this.pivot.enabled=!!points.find(point=>point.id===selected);
if(this.pivot.enabled) for(const axis of ["x","y","z"] as const) {
const material=this.material(p[axis],p.opacity);
// Gizmo remains visible when its origin is inside the selected beam.
material.depthTest=false;material.update();
this.arrows.push({axis,shaft:this.shape(`${axis} shaft`,"cylinder",material,this.pivot),cone:this.shape(`${axis} cone`,"cone",material,this.pivot)});
}
}
setRotationCenter(point:{x:number;y:number;z:number}|null) {
if(!this.centroid)return false;
const changed=this.centroid.enabled!==!!point;
this.centroid.enabled=!!point;
if(point)this.centroid.setPosition(point.x,point.y,point.z);
return changed;
}
update(dt: number) {
this.elapsed+=dt;
if(this.centroid?.enabled) {
const depth=this.centroid.getPosition().clone().sub(this.camera.getPosition()).dot(this.camera.forward);
const size=axisWorldLength(depth,this.canvas.clientHeight,this.preferences.navigation.centroidPixels);
this.centroid.setLocalScale(size,size,size);
}
const w=this.preferences.waypoint,p=this.preferences.pivot;
const motion=window.matchMedia("(prefers-reduced-motion: reduce)").matches?0:w.frequency;
this.beams.forEach(({material,index})=>{material.opacity=w.opacity*(motion? .8+.2*Math.cos(this.elapsed*motion*Math.PI*2-index*.3):1);material.update();});
const point=this.points.find(v=>v.id===this.selected);
if(point) {
const position=new Vec3(...toEditor(point.position));this.pivot.setPosition(position);
const depth=position.clone().sub(this.camera.getPosition()).dot(this.camera.forward);
this.pivot.enabled=depth>0;
this.axisLength=axisWorldLength(depth,this.canvas.clientHeight,p.pixels);
const unit=this.axisLength/p.pixels,tip=p.cone*unit,stem=this.axisLength-tip;
for(const {axis,shaft,cone} of this.arrows) {
const v=axis==="x"?new Vec3(1,0,0):axis==="y"?new Vec3(0,1,0):new Vec3(0,0,1);
shaft.setLocalPosition(v.clone().mulScalar(stem/2));cone.setLocalPosition(v.clone().mulScalar(stem+tip/2));
for(const shape of [shaft,cone])shape.setLocalEulerAngles(axis==="z"?90:0,0,axis==="x"?-90:0);
shaft.setLocalScale(p.diameter*unit,stem,p.diameter*unit);cone.setLocalScale(tip*.7,tip,tip*.7);
}
}
return this.beams.length>0 && motion>0;
}
dispose() {this.app.scene.layers.remove(this.layer);this.root.destroy();this.materials.forEach(m=>m.destroy());}
}
@@ -0,0 +1,96 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<HTMLDivElement|null>; onClose: () => void }) {
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation">("pivot");
const [saved,update] = usePlannerPreferences();
const [value,setValue] = useState(saved);
const [rect,setRect] = useState(()=>{
const bounds=boundsRef.current?.getBoundingClientRect();
const y=(boundsRef.current?.querySelector(".ai-simulation__view-tools")?.getBoundingClientRect().height??48)+24;
return {x:96,y,width:400,height:Math.max(230,Math.min(490,(bounds?.height??600)-y-12))};
});
const [maximized,setMaximized] = useState(false);
const editing = useRef(false), pending = useRef<PlannerPreferences|null>(null);
const [error,setError] = useState<string|null>(null);
const commit = () => {
editing.current=false;
const next=pending.current; pending.current=null;
if(!next)return;
try { update(next);setError(null); }
catch { setError("Не удалось сохранить настройки в этом браузере."); }
};
const commitRef=useRef(commit);commitRef.current=commit;
useEffect(()=>{if(!editing.current)setValue(saved);},[saved]);
useEffect(()=>{
const release=()=>commitRef.current();
const escape=(e:KeyboardEvent)=>{
if(e.key!=="Escape" || e.defaultPrevented || document.querySelector(".nodedc-dropdown-surface"))return;
e.preventDefault();release();onClose();
};
window.addEventListener("pointerup",release);window.addEventListener("pointercancel",release);
window.addEventListener("keyup",release);window.addEventListener("blur",release);
window.addEventListener("keydown",escape);
return ()=>{
window.removeEventListener("pointerup",release);window.removeEventListener("pointercancel",release);
window.removeEventListener("keyup",release);window.removeEventListener("blur",release);
window.removeEventListener("keydown",escape);
};
},[onClose]);
const set = (group: "pivot"|"waypoint"|"navigation", key: string, next: string|number) => {
const base=pending.current??value;
const changed={...base,[group]:{...base[group],[key]:next}};
pending.current=changed;setValue(changed);
if(!editing.current)commit();
};
const range = (group: "pivot"|"waypoint"|"navigation", key: string, label: string, min: number, max: number, step: number, unit: string) =>
<RangeControl key={key} label={label} min={min} max={max} step={step}
value={Number(value[group][key as keyof typeof value[typeof group]])} onChange={(v)=>set(group,key,v)}
formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
return <WorkspaceWindow boundsRef={boundsRef} rect={rect} onRectChange={setRect}
resizeIndicator={false}
maximized={maximized} onMaximizedChange={setMaximized} minWidth={320} minHeight={230}
zIndex={100} title="Настройки планировщика" closeLabel="Закрыть настройки планировщика"
onClose={()=>{commit();onClose();}}>
<div className="ai-polygon__form" onPointerDownCapture={(e)=>{
if((e.target as Element).closest('input[type="range"], [role="slider"]'))editing.current=true;
}} onKeyDownCapture={(e)=>{
if((e.target as Element).matches('input[type="range"], [role="slider"]') && ["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(e.key))editing.current=true;
}}>
<Select label="Раздел настроек планировщика" value={section} onChange={setSection}
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"}]}/>
{section === "pivot" ? <>
{range("pivot","pixels","Размер осей",50,220,5,"px")}
{range("pivot","diameter","Диаметр стержня",2,16,1,"px")}
{range("pivot","cone","Размер конусов",10,40,1,"px")}
{range("pivot","opacity","Непрозрачность",.15,1,.05,"")}
{(["x","y","z"] as const).map((axis)=><ControlRow key={axis} label={`Цвет ${axis.toUpperCase()}`}><ColorField label={`Цвет ${axis.toUpperCase()}`} value={value.pivot[axis]} onChange={(v)=>set("pivot",axis,v)}/></ControlRow>)}
</> : section === "waypoint" ? <>
{range("waypoint","diameter","Диаметр",.05,3,.05,"м")}
{range("waypoint","height","Высота",.2,50,.1,"м")}
<ControlRow label="Цвет waypoint"><ColorField label="Цвет waypoint" value={value.waypoint.color} onChange={(v)=>set("waypoint","color",v)}/></ControlRow>
{range("waypoint","opacity","Непрозрачность",.1,1,.05,"")}
{range("waypoint","frequency","Пульсация",0,3,.1,"Гц")}
<strong>Свечение</strong>
{range("waypoint","emission","Сила эмиссии",0,5,.1,"")}
<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow>
</> : <>
<strong>Сдвиг камеры</strong>
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p>
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")}
{range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")}
{range("navigation","farPan","Чувствительность вдали",.1,5,.1,"×")}
<strong>Зум</strong>
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
<strong>Центр вращения</strong>
<p>Шарик появляется в точке нажатия на время вращения.</p>
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
</>}
{error?<ToastStack items={[{id:"preferences",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</div>
</WorkspaceWindow>;
}
@@ -1,3 +1,4 @@
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import {
Application,
Asset,
@@ -18,6 +19,7 @@ import {
type ModelComponent,
type ScriptType,
} from "playcanvas";
import type { AiRobot } from "../../core/simulation/aiPolygon";
import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs";
import {
@@ -76,24 +78,10 @@ const HOME_POSITION = new Vec3(0, 1, 0);
const HOME_FOCUS = new Vec3(1, 1, 0);
const DRACO_DECODER_ROOT = "/vendor/playcanvas/draco/1.5.7";
const QUALITY_PROFILES: Record<SimulationQuality, {
lodBaseDistance: number;
lodMultiplier: number;
lodRangeMin: number;
lodRangeMax: number;
pixelRatio: number;
splatBudget: number;
targetFps: number;
}> = {
low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 350_000, targetFps: 30 },
medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 700_000, targetFps: 45 },
high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 1_200_000, targetFps: 60 },
ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 2_500_000, targetFps: 60 },
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60 },
};
export class PlayCanvasRuntime implements SimulationRuntime {
private app: Application | null = null;
private robotAsset: Asset | null = null;
private canvas: HTMLCanvasElement | null = null;
private camera: Entity | null = null;
private cameraController: CameraController | null = null;
@@ -155,7 +143,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
antialias: true,
alpha: false,
preserveDrawingBuffer: false,
powerPreference: "high-performance",
powerPreference: "default",
},
});
this.app = app;
@@ -306,6 +294,27 @@ export class PlayCanvasRuntime implements SimulationRuntime {
}
}
async setRobot(robot: AiRobot, ground: number[], headingDegrees: number, maxSpeedMps = .5): Promise<void> {
const app = this.requiredApp();
const publicRoot = "apps/control-station/public/";
if (!robot.visual.source.startsWith(publicRoot)) throw new Error("Модель ровера недоступна.");
const asset = new Asset(robot.name,"container",{ url: "/"+robot.visual.source.slice(publicRoot.length) });
this.robotAsset = asset; app.assets.add(asset);
await new Promise<void>((resolve,reject) => {
asset.ready(()=>resolve()); asset.once("error",()=>reject(new Error("Модель ровера не загрузилась.")));
app.assets.load(asset);
});
if (this.disposed) { asset.unload(); return; }
const resource = asset.resource as ContainerResource;
this.setUgvPreset({ presetName: robot.name, massKg: robot.physics.mass_kg,
dimensionsMeters: { length:robot.physics.length_m, width:robot.physics.width_m,
height:robot.physics.height_m, groundClearance: .15 },
maxSpeedMetersPerSecond: maxSpeedMps, maxTurnRateDegrees: 45, invertSteering: false });
this.ugvController!.setRobot(()=>resource.instantiateRenderEntity(),new Vec3(...ground),headingDegrees,robot.visual.motion);
}
get speed(): number { return this.ugvController?.speed ?? 0; }
setQuality(quality: SimulationQuality): void {
this.quality = quality;
this.applyQuality();
@@ -380,6 +389,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
this.unloadWorld();
this.ugvController?.dispose();
this.ugvController = null;
this.robotAsset?.unload(); this.robotAsset = null;
if (this.app) {
this.app.autoRender = false;
this.app.renderNextFrame = false;
@@ -0,0 +1,33 @@
import { useState } from "react";
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import type { AiRobot } from "../../core/simulation/aiPolygon";
import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings";
export function RoverSettingsWindow({robot,value,manual,onApply,onClose}:{
robot:AiRobot; value:RoverSettings; manual:boolean;
onApply:(value:RoverSettings)=>void; onClose:()=>void;
}) {
const [draft,setDraft] = useState(value);
const field = (key:Exclude<keyof RoverSettings,"schema_version">, label:string, min:number, max:number|undefined, step:number) =>
<TextField label={label} type="number" min={min} max={max} step={step}
value={Number.isFinite(draft[key])?draft[key]:""}
onChange={e=>setDraft({...draft,[key]:e.target.value===""?NaN:Number(e.target.value)})}/>;
const valid=validRoverSettings(draft,robot);
return <Window open title={`Настройки ровера · ${robot.name}`} onClose={onClose}
footer={<WindowFooterActions>
<Button onClick={()=>setDraft(current=>({...defaultRoverSettings(robot,value.max_speed_mps),max_speed_mps:current.max_speed_mps}))}>Сбросить массу и нагрузку</Button>
<Button variant="primary" disabled={!valid} onClick={()=>onApply(draft)}>Применить</Button>
</WindowFooterActions>}>
<div className="ai-polygon__form ai-polygon__report">
{field("max_speed_mps","Скорость до, м/с",.05,undefined,.01)}
{field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)}
{field("payload_mass_kg","Дополнительный груз, кг",0,500,1)}
{field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)}
<p>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</p>
<p>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</p>
{manual?<p>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</p>:null}
<p>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</p>
{!valid?<p role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</p>:null}
</div>
</Window>;
}
@@ -0,0 +1,36 @@
import { Entity } from "playcanvas";
import { beltPose, type RoverMotion } from "../../core/simulation/roverMotion";
export class RoverTrackMotion {
private distance = { L:0, R:0 };
private links: { node:Entity; side:"L"|"R"; index:number }[] = [];
private wheels: { node:Entity; side:"L"|"R"; radius:number; angle:number }[] = [];
constructor(root: Entity, private motion: RoverMotion) {
const requireNode = (name: string) => {
const node = root.findByName(name) as Entity | null;
if (!node) throw new Error(`В модели отсутствует узел анимации ${name}`);
return node;
};
for (const side of ["L","R"] as const) {
for (let index=0;index<motion.link_count;index++) {
this.links.push({node:requireNode(`${side}_BELT_${String(index).padStart(2,"0")}`),side,index});
}
}
this.wheels = motion.wheels.map(w => ({node:requireNode(w.node),side:w.node[0] as "L"|"R",radius:w.radius_m,angle:0}));
}
update(dt: number, forwardSpeed: number, yawRate: number) {
// Local controller uses +Z forward, +Y up: positive yaw turns right.
const speed={L:forwardSpeed+yawRate*this.motion.track_width_m/2,R:forwardSpeed-yawRate*this.motion.track_width_m/2};
const step=Math.min(.1,Math.max(0,dt));
for (const side of ["L","R"] as const) this.distance[side]=(this.distance[side]+speed[side]*step)%this.motion.length_m;
for (const w of this.wheels) {
w.angle=(w.angle-speed[w.side]*step/w.radius)%(2*Math.PI);
w.node.setLocalEulerAngles(0,0,w.angle*180/Math.PI);
}
for (const link of this.links) {
const pose=beltPose(this.motion,this.distance[link.side],link.side,link.index);
link.node.setLocalPosition(pose.position[0],pose.position[1],pose.position[2]);
link.node.setLocalEulerAngles(0,0,pose.angle*180/Math.PI);
}
}
}
@@ -0,0 +1,56 @@
import {useEffect,useRef,useState,type ReactNode} from 'react';
import {createPortal} from 'react-dom';
import {Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout';
import {useObservationPresets} from '../../core/fleet/useObservationPresets';
import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets';
import {ObservationLayoutSaveWindow} from '../observation/ObservationLayoutSaveWindow';
import {ObservationDeck} from '../observation/ObservationDeck';
import {ObservationPanelHeader} from '../observation/ObservationPanelHeader';
import {AiInferencePreview,type InferencePreview} from './AiInferencePreview';
import '../observation/observation.css';
const storageKey='missioncore.simulation.observation.v1';
export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{video:ReactNode;videoActions:ReactNode;toolbar:ReactNode;preview:null|InferencePreview}){
const presets=useObservationPresets('missioncore.simulation.observation-presets.v1',storageKey);
const {layout,setLayout}=presets;
const [saving,setSaving]=useState(false);
const [editing,setEditing]=useState<string|null>(null);
const edited=presets.presets.find(p=>p.id===editing);
const [full,setFull]=useState<string|null>(null);
const mounts=useRef(new Map<string,HTMLElement>());
const sources=[{id:'video',label:'Симуляция'},...(preview?.layers??[])];
for(const source of sources)if(!mounts.current.has(source.id)){const element=document.createElement('div');element.className='observation-panel-mount';mounts.current.set(source.id,element);}
const ids=orderedObservationIDs(layout,sources.map(source=>source.id));
const visible=ids.filter(id=>!layout.hidden.includes(id)&&(id==='video'||layout.catalogVisible?.includes(id)));
const effectiveFull=full&&visible.includes(full)?full:null;
const show=(id:string,checked:boolean)=>setLayout(value=>({...value,catalogVisible:checked?[...new Set([...(value.catalogVisible??[]),id])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:checked?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key==='Escape'&&effectiveFull&&!document.querySelector('[role=dialog],[role=listbox]')){setFull(null);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull]);
return <div className="ai-polygon__observation">
<div className="ai-polygon__observation-toolbar">
{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}
<Dropdown placement="bottom-end" width={340} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><Button ref={setTriggerRef} icon={<Icon name="layers"/>} aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Камеры и слои</Button>}>
{({close})=><div className="ai-polygon__layer-options" role="group" aria-label="Камеры и слои">
<Select label="Расположение окон" value={presets.selected} options={[...observationArrangements,...presets.presets.map(p=>({value:p.id,label:p.name,action:{label:`Редактировать раскладку «${p.name}»`,icon:<Icon name="edit"/>,onAction:()=>{close();presets.clearError();setEditing(p.id);}}}))]} onChange={value=>{presets.select(value);setFull(null);}}/>
{ids.map(id=>{const source=sources.find(item=>item.id===id)!;return <Checker key={id} label={source.label} checked={visible.includes(id)} onChange={checked=>show(id,checked)}/>;})}
<Button onClick={()=>{const known=[...new Set([...ids,...(layout.catalogVisible??[])])].filter(id=>!layout.hidden.includes(id)&&(id==='video'||layout.catalogVisible?.includes(id)));const tree=observationTree(layout,known);if(tree)setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)));close();setSaving(true);}}>Сохранить расположение</Button>
</div>}
</Dropdown>
{toolbar}
</div>
<div className="observation-deck">{visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.id,source.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
{sources.filter(source=>visible.includes(source.id)).map(source=>createPortal(
<div className="observation-panel"><GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
<ObservationPanelHeader><DockHandle id={source.id} label={source.label}/><div className="observation-panel__title"><h3 title={source.label}>{source.label}</h3></div><div className="observation-actions">
{source.id==='video'&&videoActions}
<IconButton label={`${effectiveFull===source.id?'Восстановить':'Развернуть'} · ${source.label}`} onClick={()=>setFull(value=>value===source.id?null:source.id)}><Icon name={effectiveFull===source.id?'minimize':'expand'}/></IconButton>
<IconButton label={`Скрыть · ${source.label}`} onClick={()=>show(source.id,false)}><Icon name="close"/></IconButton>
</div></ObservationPanelHeader>
<div className="observation-mount">{source.id==='video'?video:preview&&<AiInferencePreview preview={preview} layer={source.id}/>}</div>
</GlassSurface></div>,mounts.current.get(source.id)!,source.id))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
<ToastStack items={presets.error?[{id:"layout-save",tone:"error",title:"Раскладка не сохранена",description:presets.error}]:[]} onDismiss={presets.clearError}/>
</div>;
}
@@ -0,0 +1,53 @@
import { useEffect, useState } from "react";
import { Button, LoadingRegion, Window } from "@nodedc/ui-react";
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
import { SimulationProjectWindow } from "./SimulationProjectWindow";
/** Reuses the existing resumable Gaussian Pipeline admission workflow. */
export function SimulationSourceImport({open,onClose,onPly,onReady}: {
open:boolean; onClose:()=>void; onPly:()=>void; onReady:(worldId:string)=>void;
}) {
const [archive,setArchive]=useState(false), [project,setProject]=useState<SimulationProject|null>(null);
const [error,setError]=useState<string|null>(null);
const [pending,setPending]=useState<SimulationProject[]>([]);
useEffect(()=>{
if(!open)return;
const abort=new AbortController();setError(null);
void fetchSimulationProjects(abort.signal).then(rows=>{
if(!abort.signal.aborted)setPending(rows.filter(p=>p.status!=='ready'));
}).catch(e=>{if(!abort.signal.aborted)setError(e.message);});
return()=>abort.abort();
},[open]);
useEffect(()=>{
if(!project||project.status==='ready'||project.status==='failed')return;
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const poll=async()=>{
try {
const projects=await fetchSimulationProjects(abort.signal);
const next=projects.find(p=>p.projectId===project.projectId);
if(abort.signal.aborted)return;
if(next?.status==='ready'){setProject(null);onReady(next.projectId.replace('sim-','aiworld-'));return;}
if(next){setProject(next);if(next.status==='failed')return;}
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
if(!abort.signal.aborted)timer=setTimeout(()=>void poll(),2000);
};
void poll();return()=>{abort.abort();clearTimeout(timer);};
},[project?.projectId,project?.status]);
return <>
<Window open={open} title="Импорт локации" onClose={onClose}><div className="ai-polygon__actions">
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
</div>
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><p>{p.name}</p>
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
{error?<p role="alert">{error}</p>:null}
</Window>
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
<p>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</p>
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
</LoadingRegion>
</Window>:null}
</>;
}
@@ -13,6 +13,8 @@ import {
} from "playcanvas";
import { MeshoptSimplifier } from "meshoptimizer/simplifier";
import type { SimulationUgvPreset } from "../../core/simulation/projects";
import type { RoverMotion } from "../../core/simulation/roverMotion";
import { RoverTrackMotion } from "./RoverTrackMotion";
const AMMO_MODULE_ROOT = "/vendor/playcanvas/ammo/2026-08-25";
const UGV_SPAWN_POSITION = new Vec3(0, 1.15, 0);
@@ -230,6 +232,12 @@ export class SimulationUgvController {
private orbitIdleSeconds = 0;
private cameraOrbitInitialized = false;
private active = false;
private disposed = false;
private spawnGround = new Vec3(0,0,0);
private spawnRotation = UGV_SPAWN_ROTATION.clone();
private visualFactory: (() => Entity) | null = null;
private motion: RoverMotion | undefined;
private trackMotion: RoverTrackMotion | null = null;
private vehicleEntity: Entity | null = null;
private vehicle: NativeRaycastVehicle | null = null;
private vehicleRaycaster: NativeObject | null = null;
@@ -251,6 +259,16 @@ export class SimulationUgvController {
this.settings = cloneUgvPreset(initialSettings);
}
setRobot(visualFactory: () => Entity, ground: Vec3, headingDegrees: number, motion?: RoverMotion): void {
if (this.active) throw new Error("Сначала остановите ручное управление.");
this.visualFactory = visualFactory;
this.motion = motion;
this.spawnGround.copy(ground);
this.spawnRotation.set(0,headingDegrees,0);
}
get speed(): number { return (this.vehicle?.getCurrentSpeedKmHour() ?? 0) / 3.6; }
get enabled(): boolean {
return this.active;
}
@@ -269,9 +287,11 @@ export class SimulationUgvController {
async enable(collisionWorld: Entity): Promise<void> {
if (this.active) return;
await nextAnimationFrame();
if (this.disposed) return;
try {
await this.createStaticCollisionBodies(collisionWorld);
await nextAnimationFrame();
if (this.disposed) { this.disable(); return; }
this.spawnPosition.copy(this.findSafeSpawnPosition());
this.createVehicle();
this.attachInput();
@@ -302,6 +322,7 @@ export class SimulationUgvController {
}
dispose(): void {
this.disposed = true;
this.disable();
}
@@ -309,7 +330,7 @@ export class SimulationUgvController {
const vehicleEntity = this.vehicleEntity as (Entity & NativeRigidBodyAccess) | null;
const rigidbody = vehicleEntity?.rigidbody;
if (!vehicleEntity || !rigidbody) return;
rigidbody.teleport(this.spawnPosition, UGV_SPAWN_ROTATION);
rigidbody.teleport(this.spawnPosition, this.spawnRotation);
rigidbody.linearVelocity = ZERO;
rigidbody.angularVelocity = ZERO;
this.vehicle?.resetSuspension();
@@ -455,6 +476,11 @@ export class SimulationUgvController {
}
body?.setActivationState(DISABLE_DEACTIVATION);
if (rigidbody && this.trackMotion) {
const forward = this.vehicleEntity.getRotation().transformVector(new Vec3(0,0,1));
const up = this.vehicleEntity.up;
this.trackMotion.update(deltaSeconds,rigidbody.linearVelocity.dot(forward),rigidbody.angularVelocity.dot(up));
}
if (this.vehicleEntity.getPosition().y < -8) this.reset();
this.updateCamera(deltaSeconds);
}
@@ -593,6 +619,7 @@ export class SimulationUgvController {
const rootInverse = collisionWorld.getWorldTransform().clone().invert();
for (let index = 0; index < meshInstances.length; index += 1) {
if (this.disposed) return;
const meshInstance = meshInstances[index];
const physicsMesh = createPhysicsProxyMesh(
this.app,
@@ -707,6 +734,15 @@ export class SimulationUgvController {
});
}
if (this.visualFactory) {
// Keep the physical contact proxy; the operator sees only the selected CAD model.
for (const render of vehicle.findComponents("render")) (render as { enabled: boolean }).enabled = false;
const visual = this.visualFactory();
visual.setLocalEulerAngles(0,-90,0); // glTF +X forward -> controller +Z forward
visual.setLocalPosition(0,-dimensions.originHeight,0);
vehicle.addChild(visual);
this.trackMotion = this.motion ? new RoverTrackMotion(visual,this.motion) : null;
}
vehicle.setLocalPosition(this.spawnPosition);
this.app.root.addChild(vehicle);
@@ -827,12 +863,12 @@ export class SimulationUgvController {
const heights: number[] = [];
let suitable = true;
for (const [sampleX, sampleZ] of footprint) {
const x = UGV_SPAWN_POSITION.x + offsetX + sampleX;
const z = UGV_SPAWN_POSITION.z + offsetZ + sampleZ;
from.set(x, 8, z);
to.set(x, -8, z);
const x = this.spawnGround.x + offsetX + sampleX;
const z = this.spawnGround.z + offsetZ + sampleZ;
from.set(x, this.spawnGround.y + 3, z);
to.set(x, this.spawnGround.y - 3, z);
const hit = physics.raycastFirst(from, to);
if (!hit || hit.normal.y < 0.72 || Math.abs(hit.point.y) > 2.5) {
if (!hit || hit.normal.y < 0.72 || Math.abs(hit.point.y - this.spawnGround.y) > 2.5) {
suitable = false;
break;
}
@@ -843,8 +879,8 @@ export class SimulationUgvController {
const maximum = Math.max(...heights);
if (maximum - minimum > 0.32) continue;
const x = UGV_SPAWN_POSITION.x + offsetX;
const z = UGV_SPAWN_POSITION.z + offsetZ;
const x = this.spawnGround.x + offsetX;
const z = this.spawnGround.z + offsetZ;
const ground = heights.reduce((sum, height) => sum + height, 0) / heights.length;
const clearanceHeight = ground + dimensions.originHeight;
const origin = new Vec3(x, clearanceHeight, z);
@@ -855,10 +891,11 @@ export class SimulationUgvController {
if (!blocked) return new Vec3(x, ground + dimensions.originHeight, z);
}
return UGV_SPAWN_POSITION.clone();
throw new Error("В месте старта нет опоры для ровера. Выберите другую точку старта.");
}
private destroyVehicle(): void {
this.trackMotion = null;
if (this.vehicle && this.dynamicsWorld) {
runCleanup("remove vehicle action", () => this.dynamicsWorld?.removeAction(this.vehicle as NativeObject));
}
@@ -890,6 +927,7 @@ export class SimulationUgvController {
window.addEventListener("keydown", this.onKeyDown, true);
window.addEventListener("keyup", this.onKeyUp, true);
window.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.addEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.addEventListener("pointerup", this.onOrbitPointerUp);
@@ -901,6 +939,7 @@ export class SimulationUgvController {
window.removeEventListener("keydown", this.onKeyDown, true);
window.removeEventListener("keyup", this.onKeyUp, true);
window.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.removeEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.removeEventListener("pointerup", this.onOrbitPointerUp);
@@ -965,7 +1004,7 @@ export class SimulationUgvController {
}
private onKeyDown = (event: KeyboardEvent): void => {
if (!this.active || isTextEntry(event.target)) return;
if (!this.active || document.activeElement !== this.canvas || isTextEntry(event.target)) return;
if (!UGV_KEYS.has(event.code)) return;
event.preventDefault();
event.stopPropagation();
@@ -0,0 +1,30 @@
import { useState, type ReactNode, type RefObject } from "react";
import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { PlannerSettings } from "./PlannerSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function SimulationViewTools({expanded,toggle,planning=false,boundsRef,children}: {expanded:boolean;toggle:()=>void;planning?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
const [prefs,update]=usePlannerPreferences();
const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState<string|null>(null);
return <>
<div className="ai-simulation__view-tools nodedc-scene-controls">
{children}
<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
options={[{value:"low",label:"Низкое"},{value:"medium",label:"Среднее"},{value:"high",label:"Высокое"},{value:"ultra",label:"Ультра"},{value:"maximum",label:"Максимум"}]}
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>
<IconButton label="Помощь по управлению" onClick={()=>setHelp(true)}><Icon name="info"/></IconButton>
{planning?<IconButton label="Настройки планировщика" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
<IconButton label={expanded?"Свернуть просмотр":"Развернуть просмотр"} onClick={toggle}><Icon name={expanded?"minimize":"expand"}/></IconButton>
</div>
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
<div className="ai-polygon__form">{planning?<>
<p>ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>Прокрутка — зум к курсору, в том числе в режиме добавления точек.</p>
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
</Window>
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</>;
}
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from "react";
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
import { streamRecovery } from "../../core/simulation/streamRecovery";
export type WorkerVideoState="connecting"|"live"|"failed";
export function WorkerVideo({endpoint,onState}:{endpoint:AiStreamEndpoint;onState:(state:WorkerVideoState,fps:number|null)=>void}){
const frame=useRef<HTMLIFrameElement>(null),callback=useRef(onState);callback.current=onState;
const [attempt,setAttempt]=useState(0);
useEffect(()=>{
const started=performance.now();let lastFrame:number|null=null,failedAt:number|null=null,finished=false;
callback.current("connecting",null);
const receive=(e:MessageEvent)=>{
if(finished||e.origin!==location.origin||e.source!==frame.current?.contentWindow||e.data?.type!=="missioncore-worker-video")return;
if(e.data.state==="live"&&Number.isFinite(e.data.fps)){
lastFrame=performance.now();failedAt=null;callback.current("live",e.data.fps);
}else if(e.data.state==="failed")failedAt??=performance.now();
};
const timer=setInterval(()=>{
const action=streamRecovery(performance.now(),started,lastFrame,failedAt,attempt);
if(finished||action==="wait")return;
finished=true;
if(action==="retry")setAttempt(n=>n+1);else callback.current("failed",null);
},500);
window.addEventListener("message",receive);
return ()=>{finished=true;clearInterval(timer);window.removeEventListener("message",receive);};
},[attempt]);
return <iframe key={attempt} ref={frame} className="ai-polygon__video-frame" title="Видеопоток Worker"
src="/simulation-stream.html" allow="autoplay" tabIndex={-1}
onLoad={()=>frame.current?.contentWindow?.postMessage({type:"missioncore-worker-connect",endpoint},location.origin)}/>;
}
@@ -0,0 +1,20 @@
import { Mat4, Quat, Vec3 } from "playcanvas";
import { editorAssetUrl, type EditorCache } from "../../core/simulation/aiEditor";
import type { SimulationWorldManifest } from "../../core/simulation/projects";
/** Both local modes consume the same disk-backed assets and metric transforms. */
export function localScene(cache: EditorCache): SimulationWorldManifest {
const saved = cache.local_scene;
const matrix = (r: number[]) => new Mat4().setFromEulerAngles(r[0],r[1],r[2]);
const visual = saved ? matrix(saved.visual_rotation) : new Mat4().mul2(
matrix([-90,0,0]), new Mat4().setTRS(new Vec3(),
new Quat().setFromEulerAngles(...cache.world.settings.rotation_degrees),
new Vec3().set(cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit)));
return {
schemaVersion: "missioncore.simulation-world-manifest/v1", projectId: cache.world.world_id,
visual: { previewSogUrl: null, streamedSogUrl: saved?.visual_url ?? editorAssetUrl(cache.key,"scene.sog") },
collision: { meshUrl: saved?.collision_url ?? editorAssetUrl(cache.key,"collision.glb"), available: true },
transforms: { worldFromVisual: Array.from(visual.data),
worldFromCollision: Array.from((saved ? matrix(saved.collision_rotation) : new Mat4()).data) },
};
}
@@ -0,0 +1,5 @@
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #000; }
body { display: grid; place-items: center; }
/* Round the decoded picture itself, including when the viewport letterboxes. */
video { display: block; width: 100%; height: 100%; object-fit: cover; }
audio { display: none; }
@@ -0,0 +1,47 @@
import { AppStreamer, StreamType, LogLevel, EventStatus } from "@nvidia/ov-web-rtc";
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
import "@nodedc/tokens/tokens.css";
import "./streamFrame.css";
// A dedicated document owns NVIDIA's window-global handlers and peer connection.
// Removing this iframe releases them even if the SDK is stuck in STARTING.
const video=document.getElementById("worker-video") as HTMLVideoElement;
const fitVideo=(width:number,height:number)=>{
if(!(width>0&&height>0))return;
video.style.setProperty("--stream-width-for-height",`${100*width/height}vh`);
video.style.setProperty("--stream-height-for-width",`${100*height/width}vw`);
};
video.addEventListener("loadedmetadata",()=>fitVideo(video.videoWidth,video.videoHeight));
let started=false;
const report=(state:string,fps=0)=>window.parent.postMessage({type:"missioncore-worker-video",state,fps},location.origin);
window.addEventListener("message",(e:MessageEvent)=>{
if(started || e.source!==window.parent || e.origin!==location.origin || e.data?.type!=="missioncore-worker-connect")return;
started=true;
const endpoint=e.data.endpoint as AiStreamEndpoint;
fitVideo(endpoint.width,endpoint.height);
let frames=0,measuredAt=performance.now(),decoded=0;
const frame=()=>{frames++;video.requestVideoFrameCallback(frame);};
video.requestVideoFrameCallback(frame);
setInterval(()=>{
const now=performance.now();
// Presentation callbacks can be throttled independently of decoding in a
// background view. Prefer decoded, non-dropped video frames for telemetry.
const quality=video.getVideoPlaybackQuality?.();
const total=quality?quality.totalVideoFrames-quality.droppedVideoFrames:decoded+frames;
const count=Math.max(0,total-decoded);
if(count>0)report("live",count*1000/(now-measuredAt));
decoded=total;frames=0;measuredAt=now;
},1000);
const stream=new AppStreamer();
void stream.connect({streamSource:StreamType.DIRECT,logLevel:LogLevel.WARN,streamConfig:{
signalingServer:endpoint.server,signalingPort:endpoint.signaling_port,signalingPath:"/",
mediaServer:endpoint.server,mediaPort:endpoint.media_port,
width:endpoint.width,height:endpoint.height,fps:endpoint.fps,
videoElementId:"worker-video",audioElementId:"worker-audio",
autoLaunch:true,mic:false,enableAV1Support:false,fitStreamResolution:false,
maxReconnects:0,connectivityTimeout:5000,
onStart:event=>{if(event.status===EventStatus.ERROR||event.status===EventStatus.CANCELED)report("failed");},
onStop:()=>report("failed"),
}}).catch(()=>report("failed"));
window.addEventListener("pagehide",()=>{void stream.terminate(false).catch(()=>undefined);},{once:true});
});
@@ -0,0 +1,99 @@
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { sendAiPlanningCommand, type AiPlanningCommand, type AiRun } from "../../core/simulation/aiPolygon";
const motion = new Set(["orbit", "pan", "zoom", "fly"]);
const keys = new Set(["KeyW", "KeyA", "KeyS", "KeyD", "KeyQ", "KeyE", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ShiftLeft", "ShiftRight"]);
const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value));
/** Bounded operator intents only; Worker integrates and renders the camera. */
export function useAiPlanningControls(run: AiRun, onChange: (run: AiRun) => void, enabled: boolean) {
const current = useRef({ run, onChange, enabled }); current.current = { run, onChange, enabled };
const queue = useRef<AiPlanningCommand[]>([]);
const sending = useRef(false);
const alive = useRef(true);
const held = useRef(new Set<string>());
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const flush = async () => {
if (sending.current || !alive.current) return;
sending.current = true;
try {
while (queue.current.length && alive.current && current.current.enabled) {
const run = current.current.run;
if ((run.planning_sequence ?? 0) - (run.telemetry?.planning?.sequence ?? 0) >= 4) {
await new Promise((resolve) => setTimeout(resolve, 100));
continue;
}
const command = queue.current.shift()!;
const updated = await sendAiPlanningCommand(current.current.run, command);
if (alive.current) current.current.onChange(updated);
}
} catch (caught) {
queue.current = []; held.current.clear();
if (alive.current) setError(caught instanceof Error ? caught.message : "Не удалось изменить обзор.");
} finally {
sending.current = false;
if (alive.current) setBusy(false);
}
};
const send = (command: AiPlanningCommand) => {
if (!current.current.enabled) return;
// Do not accumulate motion while Worker is behind; subsequent key ticks retry.
const pending = (current.current.run.planning_sequence ?? 0) - (current.current.run.telemetry?.planning?.sequence ?? 0);
if (motion.has(command.action) && pending >= 4) return;
const previous = queue.current.at(-1);
if (command.action === "clip" && previous?.action === "clip") queue.current.pop();
else if (motion.has(command.action) && previous?.action === command.action) {
queue.current.pop();
command = { ...command, x: clamp((previous.x ?? 0) + (command.x ?? 0), 1),
y: clamp((previous.y ?? 0) + (command.y ?? 0), 1),
amount: clamp((previous.amount ?? 0) + (command.amount ?? 0), 3) };
}
if (queue.current.length >= 8) return;
queue.current.push(command); setBusy(true); setError(null); void flush();
};
const sender = useRef(send); sender.current = send;
const stopKeys = () => {
held.current.clear();
queue.current = queue.current.filter((command) => command.action !== "fly");
};
useEffect(() => {
alive.current = true;
const release = (event: globalThis.KeyboardEvent) => held.current.delete(event.code);
const hide = () => { if (document.hidden) stopKeys(); };
window.addEventListener("keyup", release); window.addEventListener("blur", stopKeys);
document.addEventListener("visibilitychange", hide);
let last = performance.now();
const timer = setInterval(() => {
const now = performance.now(), dt = Math.min(.12, (now-last)/1000); last = now;
const h = held.current;
if (!current.current.enabled || document.hidden || !h.size) return;
const pressed = (...codes: string[]) => Number(codes.some((code) => h.has(code)));
const x = pressed("KeyD", "ArrowRight")-pressed("KeyA", "ArrowLeft");
const y = pressed("KeyW", "ArrowUp")-pressed("KeyS", "ArrowDown");
const z = pressed("KeyE")-pressed("KeyQ");
const length = Math.hypot(x, y, z); if (!length) return;
const distance = dt * (pressed("ShiftLeft", "ShiftRight") ? 8 : 2.5) / length;
sender.current({ action: "fly", x: x*distance, y: y*distance, amount: z*distance });
}, 100);
return () => {
alive.current = false; clearInterval(timer); stopKeys(); queue.current = [];
window.removeEventListener("keyup", release); window.removeEventListener("blur", stopKeys);
document.removeEventListener("visibilitychange", hide);
};
}, []);
useEffect(() => { if (!enabled) { stopKeys(); queue.current = []; } }, [enabled]);
const keyDown = (event: KeyboardEvent<SVGSVGElement>) => {
if (keys.has(event.code)) {
event.preventDefault(); event.stopPropagation();
if (!held.current.has(event.code) && !event.code.startsWith("Shift")) {
const x = Number(["KeyD", "ArrowRight"].includes(event.code))-Number(["KeyA", "ArrowLeft"].includes(event.code));
const y = Number(["KeyW", "ArrowUp"].includes(event.code))-Number(["KeyS", "ArrowDown"].includes(event.code));
send({ action: "fly", x: x*.1, y: y*.1, amount: (Number(event.code === "KeyE")-Number(event.code === "KeyQ"))*.1 });
}
held.current.add(event.code);
}
else if (event.code === "Home") { event.preventDefault(); send({ action: "home" }); }
};
return { send, busy, error, keyDown, stopKeys };
}
@@ -0,0 +1,23 @@
import { useEffect, useState } from "react";
import { fetchEditor, prepareEditor, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWorld } from "../../core/simulation/aiPolygon";
export function useLocalScene(world: AiWorld, retry: number) {
const [cache,setCache] = useState<EditorCache | null>(null);
const [error,setError] = useState<string | null>(null);
useEffect(() => {
const abort = new AbortController(); let timer: ReturnType<typeof setTimeout>;
const poll = async (key?: string) => {
try {
const value = key ? await fetchEditor(key,abort.signal) : await prepareEditor(world,abort.signal);
if (abort.signal.aborted) return;
setCache(value);
if (value.status === "failed") setError(value.error);
else if (value.status !== "ready") timer = setTimeout(() => void poll(value.key),1000);
} catch (e) { if (!abort.signal.aborted) setError((e as Error).message); }
};
setCache(null); setError(null); void poll();
return () => { abort.abort(); clearTimeout(timer); };
}, [world.world_id,retry]);
return { cache,error,setError };
}
@@ -0,0 +1,59 @@
import { useEffect, type RefObject } from "react";
import { polygonRequest, type AiCamera } from "../../core/simulation/aiPolygon";
/** Bounded, coalesced operator input. Never forwards device/drive commands. */
export function useObserverInput(surface:RefObject<HTMLDivElement|null>,runId:string|undefined,mode:AiCamera,enabled:boolean,onError:()=>void) {
useEffect(()=>{
const element=surface.current;if(!element || !runId || !enabled)return;
const input={session:crypto.randomUUID().replaceAll("-",""),sequence:0,orbit:[0,0],move:[0,0,0],zoom:0};
let gesture:{id:number;x:number;y:number;pan:boolean}|null=null, dirty=false, sending=false, closed=false;
const keys=new Set<string>();
const allowed=new Set(["KeyW","KeyS","KeyA","KeyD","KeyQ","KeyE","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","ShiftLeft","ShiftRight"]);
const clamp=(v:number)=>Math.max(-9999,Math.min(9999,v));
const down=(e:PointerEvent)=>{
if((e.target as Element).closest('button,[role="button"],[role="slider"],.nodedc-select-anchor') || ![0,1,2].includes(e.button))return;
e.preventDefault();element.focus({preventScroll:true});
gesture={id:e.pointerId,x:e.clientX,y:e.clientY,pan:e.button!==0};element.setPointerCapture(e.pointerId);
};
const move=(e:PointerEvent)=>{
if(!gesture || gesture.id!==e.pointerId)return;
const dx=e.clientX-gesture.x,dy=e.clientY-gesture.y;gesture.x=e.clientX;gesture.y=e.clientY;
if(gesture.pan){input.move[0]=clamp(input.move[0]-dx*.02);input.move[2]=clamp(input.move[2]+dy*.02);}
else{input.orbit[0]=clamp(input.orbit[0]-dx*.005);input.orbit[1]=clamp(input.orbit[1]-dy*.005);}
dirty=true;
};
const end=()=>{gesture=null;};
const wheel=(e:WheelEvent)=>{
if((e.target as Element).closest('button,.nodedc-select-anchor'))return;
e.preventDefault();input.zoom=clamp(input.zoom+e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?element.clientHeight:1)*.0015);dirty=true;
};
const keyDown=(e:KeyboardEvent)=>{if(document.activeElement!==element || e.ctrlKey || e.metaKey || e.altKey || !allowed.has(e.code))return;e.preventDefault();keys.add(e.code);};
const keyUp=(e:KeyboardEvent)=>keys.delete(e.code);
const clear=()=>{keys.clear();end();};
const context=(e:Event)=>e.preventDefault();
element.addEventListener("pointerdown",down);element.addEventListener("pointermove",move);element.addEventListener("pointerup",end);element.addEventListener("pointercancel",end);
element.addEventListener("wheel",wheel,{passive:false});element.addEventListener("contextmenu",context);element.addEventListener("blur",clear);
window.addEventListener("keydown",keyDown);window.addEventListener("keyup",keyUp);window.addEventListener("blur",clear);
let last=performance.now();
const tick=window.setInterval(()=>{
const now=performance.now(),dt=Math.min(.15,(now-last)/1000);last=now;
if(mode==="overview" && keys.size && document.visibilityState==="visible") {
const pressed=(...codes:string[])=>Number(codes.some(k=>keys.has(k)));
const speed=dt*(pressed("ShiftLeft","ShiftRight")?16:4);
input.move[0]=clamp(input.move[0]+speed*(pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft")));
input.move[1]=clamp(input.move[1]+speed*(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown")));
input.move[2]=clamp(input.move[2]+speed*(pressed("KeyE")-pressed("KeyQ")));dirty=true;
}
if(!dirty || sending)return;
dirty=false;sending=true;input.sequence++;
void polygonRequest(`/runs/${runId}/view`,{method:"PUT",body:JSON.stringify({camera:mode,navigation:input})})
.catch(()=>{if(!closed){dirty=true;onError();}}).finally(()=>{sending=false;});
},100);
return ()=>{
closed=true;clearInterval(tick);clear();
element.removeEventListener("pointerdown",down);element.removeEventListener("pointermove",move);element.removeEventListener("pointerup",end);element.removeEventListener("pointercancel",end);
element.removeEventListener("wheel",wheel);element.removeEventListener("contextmenu",context);element.removeEventListener("blur",clear);
window.removeEventListener("keydown",keyDown);window.removeEventListener("keyup",keyUp);window.removeEventListener("blur",clear);
};
},[surface,runId,mode,enabled,onError]);
}
@@ -0,0 +1,20 @@
import { useSyncExternalStore } from "react";
import { DEFAULT_PLANNER_PREFERENCES, normalizePlannerPreferences, PLANNER_PREFERENCES_KEY, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
const listeners = new Set<() => void>();
let current = DEFAULT_PLANNER_PREFERENCES;
try { current = normalizePlannerPreferences(JSON.parse(localStorage.getItem(PLANNER_PREFERENCES_KEY) ?? "null")); } catch { /* Defaults remain usable if storage is unavailable. */ }
window.addEventListener("storage", (event) => {
if (event.key !== PLANNER_PREFERENCES_KEY) return;
try { current = normalizePlannerPreferences(JSON.parse(event.newValue ?? "null")); } catch { return; }
listeners.forEach((notify) => notify());
});
export function usePlannerPreferences() {
const value = useSyncExternalStore((notify) => { listeners.add(notify); return () => { listeners.delete(notify); }; }, () => current);
const update = (next: PlannerPreferences) => {
const valid = normalizePlannerPreferences(next);
// Persist before accepting, so a quota/privacy failure is visible to the caller.
localStorage.setItem(PLANNER_PREFERENCES_KEY, JSON.stringify(valid));
current = valid; listeners.forEach((notify) => notify());
};
return [value, update] as const;
}
@@ -6,6 +6,7 @@ export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>)
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
const escape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return;
if (view.current.querySelector('[role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
event.preventDefault();
event.stopPropagation();
void document.exitFullscreen().catch(() => undefined);
@@ -1,5 +1,6 @@
import {decodeDockTree, reconcileDockTree, moveDockPanel, dockIds, type DockTree, type DockMove} from "@nodedc/ui-core";
export interface ObservationLayout {
version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
tree?:DockTree; version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
catalogVisible?:string[]; splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
}
export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'});
@@ -8,6 +9,7 @@ export function decodeObservationLayout(value:unknown):ObservationLayout {
const source=record(value),result=emptyObservationLayout();if(source.version!==1)return result;
const ids=(value:unknown)=>Array.isArray(value)?[...new Set(value.filter((v):v is string=>typeof v==='string'&&v.length<512))].slice(0,128):[];
if(source.catalogVisible!==undefined)result.catalogVisible=ids(source.catalogVisible);
const tree=decodeDockTree(source.tree);if(tree)result.tree=tree;
result.order=ids(source.order);result.hidden=ids(source.hidden);
result.layers=Object.fromEntries(Object.entries(record(source.layers)).filter(([k,v])=>k.length<512&&typeof v==='string'&&v.length<128).slice(0,128)) as Record<string,string>;
result.splits=Object.fromEntries(Object.entries(record(source.splits)).filter(([k,v])=>k.length<4096&&typeof v==='number'&&Number.isFinite(v)).slice(0,256).map(([k,v])=>[k,Math.min(80,Math.max(20,v as number))]));
@@ -20,5 +22,30 @@ export function orderedObservationIDs(layout:ObservationLayout,available:string[
export function moveObservation(layout:ObservationLayout,available:string[],from:string,to:string):ObservationLayout {
const order=orderedObservationIDs(layout,available);const source=order.indexOf(from),target=order.indexOf(to);
if(source<0||target<0||source===target)return layout;
if(layout.tree){const tree=moveDockPanel(layout.tree,{activeId:from,overId:to,position:"center"});if(tree)return withObservationTree(layout,tree);}
order.splice(source,1);order.splice(target,0,from);return {...layout,order};
}
/** Retain legacy defaults until the first edit; afterwards tree geometry owns placement. */
export function observationTree(layout:ObservationLayout,ids:string[]):DockTree|null {
if(layout.tree)return reconcileDockTree(layout.tree,ids);
const build=(keys:string[],depth=0):DockTree|null=>{
if(!keys.length)return null;
if(keys.length===1)return {id:keys[0]};
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&keys.some(id=>!['map','rover','telemetry'].includes(id));
const cameraCount=keys.filter(id=>!['map','rover','telemetry'].includes(id)).length;
const mid=defaultColumns&&cameraCount<keys.length?cameraCount:layout.arrangement==='auto'&&keys[0]==='map'&&keys.includes('rover')?1:Math.ceil(keys.length/2);
const axis=layout.arrangement==='rows'?'y':layout.arrangement==='columns'?'x':depth%2?'y':'x';
return {axis,ratio:layout.splits[JSON.stringify(keys)]??50,first:build(keys.slice(0,mid),depth+1)!,second:build(keys.slice(mid),depth+1)!};
};
return build(ids);
}
export function dockObservation(layout:ObservationLayout,ids:string[],move:DockMove):ObservationLayout {
const tree=moveDockPanel(observationTree(layout,ids),move);
return tree?withObservationTree(layout,tree):layout;
}
export function withObservationTree(layout:ObservationLayout,tree:DockTree):ObservationLayout {
const visible=dockIds(tree);
return {...layout,tree,order:[...visible,...layout.order.filter(id=>!visible.includes(id))]};
}
@@ -0,0 +1,71 @@
import {dockIds, type DockTree} from '@nodedc/ui-core';
import {decodeObservationLayout, type ObservationLayout} from './observationLayout';
export const observationArrangements = [
{value:'auto',label:'Автоматически'}, {value:'columns',label:'В ряд'},
{value:'rows',label:'Друг под другом'},
] as const;
export interface ObservationPreset {id:string;name:string;layout:ObservationLayout}
export interface ObservationPresets {version:1;selected:string;layout:ObservationLayout;presets:ObservationPreset[]}
const clone = (layout:unknown):ObservationLayout => JSON.parse(JSON.stringify(decodeObservationLayout(layout)));
export function decodeObservationPresets(value:unknown, legacy?:unknown):ObservationPresets {
const source = value && typeof value === 'object' ? value as Partial<ObservationPresets> : {};
const presets:ObservationPreset[] = [];
if(source.version === 1 && Array.isArray(source.presets)) for(const item of source.presets.slice(0,128)) {
if(!item || typeof item.id!=='string' || !item.id.startsWith('saved:') || item.id.length>128
|| typeof item.name!=='string' || !item.name.trim() || item.name.length>120
|| presets.some(p=>p.id===item.id || p.name===item.name.trim())) continue;
presets.push({id:item.id,name:item.name.trim(),layout:clone(item.layout)});
}
const layout=decodeObservationLayout(source.version===1 ? source.layout : legacy);
const selected=source.selected;
return {version:1,presets,layout,selected:typeof selected==='string' &&
(presets.some(p=>p.id===selected) || observationArrangements.some(p=>p.value===selected))
? selected : layout.arrangement};
}
export function selectObservationPreset(state:ObservationPresets,id:string):ObservationPresets {
const preset=state.presets.find(p=>p.id===id);
if(preset)return {...state,selected:id,layout:clone(preset.layout)};
const arrangement=observationArrangements.find(p=>p.value===id)?.value;
return arrangement ? {...state,selected:id,layout:{...state.layout,arrangement,tree:undefined,order:[],splits:{}}} : state;
}
export function saveObservationPreset(state:ObservationPresets,name:string,id:string):ObservationPresets {
name=name.trim();
if(!name || name.length>120)throw new Error('Укажите название раскладки.');
if(state.presets.some(p=>p.name.toLocaleLowerCase()===name.toLocaleLowerCase()) ||
observationArrangements.some(p=>p.label.toLocaleLowerCase()===name.toLocaleLowerCase()))
throw new Error('Раскладка с таким названием уже существует.');
if(state.presets.length>=128)throw new Error('Достигнут предел сохранённых раскладок.');
if(!id.startsWith('saved:') || state.presets.some(p=>p.id===id))throw new Error('Не удалось создать раскладку.');
return {...state,selected:id,presets:[...state.presets,{id,name,layout:clone(state.layout)}]};
}
export function renameObservationPreset(state:ObservationPresets,id:string,name:string):ObservationPresets {
const preset=state.presets.find(p=>p.id===id);
if(!preset)throw new Error('Раскладка не найдена.');
const validated=saveObservationPreset({...state,presets:state.presets.filter(p=>p.id!==id)},name,id);
return {...state,presets:state.presets.map(p=>p.id===id?{...p,name:validated.presets.at(-1)!.name}:p)};
}
export function removeObservationPreset(state:ObservationPresets,id:string):ObservationPresets {
return {...state,presets:state.presets.filter(p=>p.id!==id),
selected:state.selected===id?state.layout.arrangement:state.selected};
}
/** Reattach dormant branches after editing the visible projection. Availability
* never deletes a device or its split; returning devices recover their anchors. */
export function retainDormantObservationTree(previous:DockTree|undefined,next:DockTree):DockTree {
if(!previous)return next;
const present=new Set(dockIds(next));
const insert=(tree:DockTree,anchor:string,branch:DockTree,split:Exclude<DockTree,{id:string}>,first:boolean):DockTree=>{
if('id' in tree)return tree.id===anchor ? {...split,first:first?branch:tree,second:first?tree:branch} : tree;
return {...tree,first:insert(tree.first,anchor,branch,split,first),second:insert(tree.second,anchor,branch,split,first)};
};
const restore=(old:DockTree)=>{
if('id' in old)return;
const first=dockIds(old.first).find(id=>present.has(id));
const second=dockIds(old.second).find(id=>present.has(id));
if(!first && second)next=insert(next,second,old.first,old,true);
else if(first && !second)next=insert(next,first,old.second,old,false);
else if(first && second){restore(old.first);restore(old.second);}
};
restore(previous);return next;
}
@@ -0,0 +1,28 @@
import {useEffect,useState,type SetStateAction} from 'react';
import {type ObservationLayout} from './observationLayout';
import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets';
export function useObservationPresets(storageKey:string,legacyKey:string) {
const [state,setState]=useState(()=>{
const read=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}};
return decodeObservationPresets(read(storageKey),read(legacyKey));
});
const [error,setError]=useState<string|null>(null);
useEffect(()=>{
try{localStorage.setItem(storageKey,JSON.stringify(state));}
catch{setError('Браузер не сохранил раскладку. Проверьте доступное место и разрешение на хранение данных.');}
},[state,storageKey]);
const setLayout=(update:SetStateAction<ObservationLayout>)=>setState(current=>({...current,
layout:typeof update==='function'?update(current.layout):update}));
const commit=(update:()=>ObservationPresets)=>{
try{
const next=update();
localStorage.setItem(storageKey,JSON.stringify(next));setState(next);setError(null);return true;
}catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;}
};
return {...state,setLayout,save:(name:string)=>commit(()=>saveObservationPreset(state,name,`saved:${crypto.randomUUID()}`)),
rename:(id:string,name:string)=>commit(()=>renameObservationPreset(state,id,name)),
remove:(id:string)=>commit(()=>removeObservationPreset(state,id)),
select:(id:string)=>setState(current=>selectObservationPreset(current,id)),
error,clearError:()=>setError(null)};
}
@@ -0,0 +1,17 @@
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[] };
key: string; world: AiWorld; status: "queued" | "preparing" | "uploading" | "ready" | "failed";
error: string | null;
files: Record<string, { sha256: string; byte_length: number; uploaded_bytes: number }>;
}
export const prepareEditor = (world: AiWorld, signal?: AbortSignal) => polygonRequest<EditorCache>(
`/worlds/${world.world_id}/editor-cache`, { method: "POST", signal });
export const fetchEditor = (key: string, signal?: AbortSignal) => polygonRequest<EditorCache>(`/editor-cache/${key}`, { signal });
export const editorAssetUrl = (key: string, name: string) => `/api/v1/ai-polygon/editor-cache/${key}/${name}`;
export const saveLocalPlan = (cache: EditorCache, robot: AiRobot, points: AiWaypoint[], name: string,
draftId: string, sequence: number) => polygonRequest<AiPlan>("/plans", { method: "POST", body: JSON.stringify({
cache_key: cache.key, robot_id: robot.robot_id, robot_sha256: robot.sha256,
draft_id: draftId, sequence, points, name,
}) });
export { toEditor, toMission } from "./aiEditorCoordinates";
@@ -0,0 +1,3 @@
/** Isaac uses Z up; the glTF/PlayCanvas editor uses Y up. This preserves handedness. */
export const toEditor = ([x, y, z]: number[]): [number, number, number] => [x, z, -y];
export const toMission = ([x, y, z]: number[]): [number, number, number] => [x, -z, y];
@@ -1,4 +1,6 @@
import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition";
import type { RoverMotion } from "./roverMotion";
import type { RoverSettings } from "./roverSettings";
const API = "/api/v1/ai-polygon";
@@ -28,14 +30,29 @@ export interface AiSource {
description?: string;
}
export interface AiWorld extends AiSource {
local_scene?: { project_id: string };
inference_ready?: boolean; inference_message?: string;
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
status: "uploading" | "available"; sha256: string | null; splat_count: number | null;
settings: AiWorldSettings;
}
export interface AiRobot {
robot_id: string; name: string; revision: string; sha256: string;
visual: { dimensions_m: [number, number, number]; source: string; sha256: string; motion?: RoverMotion };
physics: { mass_kg: number; length_m: number; width_m: number; height_m: number };
control?: { max_side_speed_mps: number };
}
export interface AiRun {
run_id: string;
created_at?: string;
world: AiWorld;
request?: { composition?: AiSelection };
robot?: AiRobot | null;
report?: AiRunReport | null;
request?: { composition?: AiSelection; purpose?: "planning" | "evaluation"; rover_settings?: RoverSettings | null };
rover_configuration?: { sha256:string; total_mass_kg:number; effective_robot_sha256:string; settings:RoverSettings } | null;
plan?: AiPlan | null;
plan_display_name?: string | null;
planning_sequence?: number;
state: "starting" | "ready" | "running" | "paused" | "stopping" | "completed" | "stopped" | "failed" | "disconnected";
clock?: "lockstep" | "realtime";
control?: "play" | "pause" | "stop";
@@ -57,20 +74,57 @@ export interface AiRun {
road_fraction: number; obstacle_count: number };
};
}
export interface AiRunReport {
run_id: string; generated_at: string;
mission_outcome: "goal-reached" | "time-limit" | "operator-stop" | "stuck" | "unstable" | "error" | "not-evaluated";
distance_m: number | null; simulation_seconds: number | null; goal_error_m: number | null;
waypoint_count: number; waypoints_reached: number | null;
inference_count: number; inference_errors: number;
inference_ms_p50: number | null; inference_ms_p95: number | null;
stops: { reason: string; events: number; seconds: number }[];
collision_count: number | null;
robot_sha256: string | null; composition_sha256: string | null;
report_sha256: string; manifest_sha256: string; evidence_files: number; evidence_bytes: number;
speed?: {requested_max_mps:number; measured_max_mps:number|null; maximum_excess_mps:number|null; seconds_above_requested:number|null} | null;
}
export type AiCamera = "follow" | "overview" | "camera";
export interface AiStreamEndpoint {
server: string; signaling_port: number; media_port: number; width: number; height: number; fps: number;
}
export interface AiTelemetry {
distance_m?: number | null;
sequence: number; control_sequence: number; simulation_time_ns: number;
rtf: number; render_fps: number; sensor_fps: number; ai_hz: number;
inference_ms: number | null; frame_age_ms: number | null; command_age_ms: number | null;
speed_mps: number; applied_speed_mps: number; stop_reason: string;
ai_ready: boolean; stream_ready: boolean; camera: AiCamera;
decision: NonNullable<AiRun["last_sample"]>["decision"] | null;
planning?: AiPlanningState | null;
route_overlay?: AiRouteOverlay | null;
}
export interface AiWaypoint { id: string; position: [number, number, number] }
export type ScreenPoint = [number, number] | null;
export interface AiRouteOverlay {
markers: (AiWaypoint & { index: number; base: ScreenPoint; top: ScreenPoint;
x_axis: ScreenPoint; y_axis: ScreenPoint })[];
trace: ScreenPoint[]; active_index: number; view_revision: number;
}
export interface AiPlanningState { sequence: number; view_revision: number; points: AiWaypoint[];
error: string | null; can_undo: boolean; clip_height: number | null;
height_min?: number | null; height_max?: number | null; camera_moving?: boolean }
export interface AiPlan { plan_id: string; name: string; sha256: string; world_id: string;
settings?: Pick<AiWorldSettings, "max_speed_mps">;
display_name?: string; removed?: boolean;
editor_cache_key?: string;
robot_id: string; robot_sha256: string; points: AiWaypoint[]; length_m: number; created_at: string }
export interface AiPlanningCommand {
action: "orbit" | "pan" | "zoom" | "fly" | "home" | "add" | "move" | "delete" | "clear" | "clip" | "undo";
point_id?: string; x?: number; y?: number; amount?: number; enabled?: boolean; axis?: "x" | "y" | "xy";
}
export interface AiCatalog {
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
robots: AiRobot[];
plans: AiPlan[];
runtime: { available: boolean; active_run: AiRun | null };
}
@@ -87,13 +141,29 @@ 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 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)});
export const removeAiRun = (id:string, removed:boolean) =>
polygonRequest<AiRun>(`/runs/${id}`, {method:"PATCH",body:JSON.stringify({removed})});
export const configureAiWorld = (world: AiWorld, settings: AiWorldSettings) =>
polygonRequest<AiWorld>(`/worlds/${world.world_id}/settings`, {
method: "PUT", body: JSON.stringify(settings),
});
export const startAiRun = (world: AiWorld, composition?: AiSelection) => polygonRequest<AiRun>("/runs", {
export const startAiRun = (world: AiWorld, robot: AiRobot, composition?: AiSelection,
purpose: "planning" | "evaluation" = "evaluation", plan?: AiPlan, roverSettings?: RoverSettings) => polygonRequest<AiRun>("/runs", {
method: "POST", headers: { "Idempotency-Key": crypto.randomUUID() },
body: JSON.stringify({ world_id: world.world_id, clock: "realtime", start_paused: true, duration_seconds: 1800, composition }),
body: JSON.stringify({ world_id: world.world_id, robot_id: robot.robot_id, robot_sha256: robot.sha256,
clock: "realtime", start_paused: purpose === "planning",
composition, purpose, plan_id: plan?.plan_id, rover_settings:roverSettings }),
});
export const sendAiPlanningCommand = (run: AiRun, command: AiPlanningCommand) =>
polygonRequest<AiRun>(`/runs/${run.run_id}/planning`, { method: "PUT", body: JSON.stringify({
...command, request_id: crypto.randomUUID().replaceAll("-", ""),
view_revision: run.telemetry?.planning?.view_revision ?? 0,
}) });
export const saveAiPlan = (run: AiRun, name: string) => polygonRequest<AiPlan>(`/runs/${run.run_id}/plan`, {
method: "POST", body: JSON.stringify({ name, sequence: run.telemetry?.planning?.sequence ?? 0 }),
});
export const setAiCamera = (run: AiRun, camera: AiCamera) =>
polygonRequest<AiRun>(`/runs/${run.run_id}/view`, { method: "PUT", body: JSON.stringify({ camera }) });
@@ -0,0 +1,20 @@
import {polygonRequest,type AiSelection} from './aiPolygon';
export interface AiProfile {
profile_id:string; name:string; composition:AiSelection; revision:number; removed:boolean;
}
export const fetchAiProfiles=()=>polygonRequest<AiProfile[]>('/ai-profiles');
export const createAiProfile=(name:string,composition:AiSelection)=>polygonRequest<AiProfile>('/ai-profiles',
{method:'POST',body:JSON.stringify({name,composition})});
export const updateAiProfile=(profile:AiProfile,changes:{name?:string;composition?:AiSelection;removed?:boolean})=>
polygonRequest<AiProfile>(`/ai-profiles/${profile.profile_id}`,
{method:'PATCH',body:JSON.stringify({expected_revision:profile.revision,...changes})});
/** Saved intent survives installed module revisions; admission rebinds SHA-256. */
export function sameAiIntent(a:AiSelection,b:AiSelection):boolean {
const stable=(value:unknown):unknown=>Array.isArray(value)?value.map(stable):value&&typeof value==='object'
?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>[k,stable(v)])):value;
const intent=(value:AiSelection)=>value.selections.map(({group,module_id,parameters})=>({group,module_id,parameters}))
.sort((a,b)=>a.group.localeCompare(b.group));
return JSON.stringify(stable(intent(a)))===JSON.stringify(stable(intent(b)));
}
@@ -0,0 +1,25 @@
import { PerspectiveCamera, Quaternion, Vector3 } from "three";
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) {
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);
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) {
const factor=2*Math.PI/Math.max(1,height);
const yaw=new Quaternion().setFromAxisAngle(UP,-dx*factor);
const forward=camera.getWorldDirection(new Vector3());
const elevation=Math.asin(Math.max(-1,Math.min(1,forward.y)));
const pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,elevation-dy*factor))-elevation;
const right=new Vector3(1,0,0).applyQuaternion(camera.quaternion).applyQuaternion(yaw);
const rotation=new Quaternion().setFromAxisAngle(right,pitch).multiply(yaw);
camera.position.sub(anchor).applyQuaternion(rotation).add(anchor);
camera.quaternion.premultiply(rotation);
camera.updateMatrixWorld();
}
@@ -0,0 +1,4 @@
/** Exponential dolly in metres, independent of OrbitControls' target radius. */
export function zoomDisplacement(depth: number, wheelPixels: number): number {
return depth * (1 - Math.exp(Math.max(-.8, Math.min(.8,wheelPixels*.002))));
}
@@ -0,0 +1,18 @@
export type GaussianQuality = "low" | "medium" | "high" | "ultra" | "maximum";
// PlayCanvas: zero disables count-budget enforcement; quality uses LOD distances only.
export const QUALITY_PROFILES: Record<GaussianQuality, {
lodBaseDistance: number;
lodMultiplier: number;
lodRangeMin: number;
lodRangeMax: number;
pixelRatio: number;
splatBudget: number;
targetFps: number;
}> = {
low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 0, targetFps: 30 },
medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 0, targetFps: 45 },
high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 0, targetFps: 60 },
ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 0, targetFps: 60 },
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 0, targetFps: 60 },
};
@@ -0,0 +1,8 @@
import type { AiPlan, AiWaypoint } from "./aiPolygon";
/** A launch may reuse a saved task only when it represents this exact draft. */
export function planMatchesDraft(plan:AiPlan|undefined, cacheKey:string, robotSha:string, points:AiWaypoint[]) {
return !!plan && plan.editor_cache_key===cacheKey && plan.robot_sha256===robotSha
&& plan.points.length===points.length && plan.points.every((point,i)=>point.id===points[i].id
&& point.position.every((value,axis)=>value===points[i].position[axis]));
}
@@ -0,0 +1,42 @@
import type { GaussianQuality } from "./gaussianQuality";
export interface PlannerPreferences {
quality: GaussianQuality;
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 = {
quality: "medium",
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" },
};
/** Persisted operator preferences are untrusted input; old/invalid fields get defaults. */
export function normalizePlannerPreferences(value: unknown): PlannerPreferences {
const v = value && typeof value === "object" ? value as Partial<PlannerPreferences> : {};
const p: Partial<PlannerPreferences["pivot"]> = v.pivot ?? {}, w: Partial<PlannerPreferences["waypoint"]> = v.waypoint ?? {}, d = DEFAULT_PLANNER_PREFERENCES;
const n = (x: unknown, fallback: number, min: number, max: number) => typeof x === "number" && Number.isFinite(x) ? Math.max(min, Math.min(max,x)) : fallback;
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);
return {
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)},
quality: ["low","medium","high","ultra","maximum"].includes(v.quality ?? "") ? v.quality! : d.quality,
pivot: { pixels:n(p.pixels,d.pivot.pixels,50,220), diameter:n(p.diameter,d.pivot.diameter,2,16), cone:n(p.cone,d.pivot.cone,10,40), opacity:n(p.opacity,d.pivot.opacity,.15,1),
x:color(p.x,d.pivot.x), y:color(p.y,d.pivot.y), z:color(p.z,d.pivot.z) },
waypoint: { diameter:n(w.diameter,d.waypoint.diameter,.05,3), height:n(w.height,d.waypoint.height,.2,50), color:color(w.color,d.waypoint.color), opacity:n(w.opacity,d.waypoint.opacity,.1,1), frequency:n(w.frequency,d.waypoint.frequency,0,3), emission:n(w.emission,d.waypoint.emission,0,5), emissionColor:color(w.emissionColor,d.waypoint.emissionColor) },
};
}
export function axisWorldLength(depth: number, height: number, pixels: number) {
return Math.max(.01, depth) * 2 * Math.tan(Math.PI / 6) * pixels / Math.max(1,height);
}
export function panSensitivity(distance:number,navigation:PlannerPreferences["navigation"]) {
const t=Math.max(0,Math.min(1,(distance-navigation.nearDistance)/(navigation.farDistance-navigation.nearDistance)));
const smooth=t*t*(3-2*t);
return navigation.nearPan+(navigation.farPan-navigation.nearPan)*smooth;
}
@@ -0,0 +1,20 @@
export interface RoverMotion {
schema_version: "missioncore.rover-motion/v1";
length_m: number; pitch_m: number; phase_m: number; link_count: number;
track_width_m: number; track_centres_m: { L: number; R: number }; shift_m: number[];
segments: ["arc" | "line", number, number, number[]][];
wheels: { node: string; radius_m: number }[];
}
export function beltPose(motion: RoverMotion, distance: number, side: "L" | "R", index: number) {
const s = ((distance + motion.phase_m + index*motion.pitch_m) % motion.length_m + motion.length_m) % motion.length_m;
const segment = motion.segments.find(([, start, length]) => s <= start+length+1e-10)!;
const [kind,start,,d] = segment, t = s-start;
let x: number, z: number, angle: number;
if (kind === "arc") {
const [cx,cz,r,a] = d, q = a-t/r;
x=cx+r*Math.cos(q); z=cz+r*Math.sin(q); angle=q-Math.PI/2;
} else {
x=d[0]+d[2]*t; z=d[1]+d[3]*t; angle=Math.atan2(d[3],d[2]);
}
return { position:[x+motion.shift_m[0],z+motion.shift_m[2],-motion.track_centres_m[side]-motion.shift_m[1]], angle };
}
@@ -0,0 +1,32 @@
import type { AiRobot } from "./aiPolygon";
export interface RoverSettings {
schema_version: "missioncore.rover-settings/v2";
max_speed_mps: number;
base_mass_kg: number;
payload_mass_kg: number;
payload_height_m: number;
}
export const roverSettingsKey = (robot: AiRobot) => `nodedc.simulation.rover.v1:${robot.robot_id}:${robot.sha256}`;
export function defaultRoverSettings(robot: AiRobot, speed: number): RoverSettings {
return { schema_version: "missioncore.rover-settings/v2",
max_speed_mps: Math.max(.05, Number.isFinite(speed) ? speed : .3),
base_mass_kg: robot.physics.mass_kg, payload_mass_kg: 0,
payload_height_m: Math.round((robot.physics.height_m + .1) * 100) / 100 };
}
export function validRoverSettings(value: RoverSettings, _robot: AiRobot): boolean {
const within = (v:number, min:number, max:number) => Number.isFinite(v) && v>=min && v<=max;
return value.schema_version === "missioncore.rover-settings/v2"
&& within(value.max_speed_mps, .05, Infinity)
&& within(value.base_mass_kg,10,1000) && within(value.payload_mass_kg,0,500)
&& within(value.payload_height_m,.1,3);
}
export function parseRoverSettings(raw: string | null, robot: AiRobot): RoverSettings | undefined {
try {
const value = JSON.parse(raw ?? "null");
if (value?.schema_version === "missioncore.rover-settings/v1") value.schema_version = "missioncore.rover-settings/v2";
if (!value || !validRoverSettings(value,robot)
|| Object.keys(value).sort().join() !== "base_mass_kg,max_speed_mps,payload_height_m,payload_mass_kg,schema_version") return;
return value;
} catch { return; }
}
@@ -0,0 +1,36 @@
import type { AiModules, AiSelection } from "./aiPolygon";
const SCHEMA = "missioncore.observatory-ai-composition/v1";
const GROUPS = new Set(["segmentation", "detection", "geometry", "range", "motion", "policy"]);
/** Stored intent is untrusted. Worker admission still owns executable contracts. */
export function parseSavedSelection(raw: string | null): AiSelection | undefined {
try {
const value = JSON.parse(raw ?? "null");
if (value?.schema_version !== SCHEMA || !Array.isArray(value.selections)
|| !value.selections.length || value.selections.length > GROUPS.size) return;
const groups = new Set<string>();
for (const row of value.selections) {
if (!row || !GROUPS.has(row.group) || groups.has(row.group)
|| typeof row.module_id !== "string" || !/^[a-z0-9][a-z0-9-]{0,127}$/.test(row.module_id)
|| typeof row.module_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.module_sha256)
|| !row.parameters || typeof row.parameters !== "object" || Array.isArray(row.parameters)) return;
groups.add(row.group);
}
return value as AiSelection;
} catch { return; }
}
/** Rebind every chosen provider, including alternatives absent from defaults. */
export function currentSelection(selection: AiSelection, installed: AiModules): AiSelection {
return { ...selection, selections: selection.selections.map(row => {
const module = installed.catalog.groups.find(group => group.group === row.group)
?.modules.find(candidate => candidate.moduleId === row.module_id);
if (!module) throw new Error("Выбранный AI-модуль больше недоступен. Проверьте конфигурацию AI.");
return { ...row, module_sha256: module.moduleSha256,
parameters: { ...module.defaults, ...row.parameters } };
}) };
}
export const selectionStorageKey = (world: string, robot: string) =>
`nodedc.simulation.composition.v1:${world}:${robot}`;
@@ -0,0 +1,5 @@
/** A bounded first-frame/stall watchdog, independent of SDK callbacks. */
export function streamRecovery(now:number,started:number,lastFrame:number|null,failedAt:number|null,attempt:number) {
const expired=failedAt!==null ? now-failedAt>=2000 : lastFrame===null ? now-started>=20000 : now-lastFrame>=10000;
return !expired?"wait":attempt<2?"retry":"failed";
}
@@ -0,0 +1,20 @@
import { useMemo, useState } from "react";
import type { AiModules, AiSelection } from "./aiPolygon";
import { parseSavedSelection, selectionStorageKey } from "./runConfiguration";
/** Location/robot intent survives reload; changing location never carries it over. */
export function useAiSelection(world: string | null, robot: string | null, modules: AiModules | null) {
const scope = world && robot ? selectionStorageKey(world, robot) : null;
const [draft, setDraft] = useState<{ scope: string | null; value: AiSelection } | null>(null);
const saved = useMemo(() => {
try { return scope ? parseSavedSelection(localStorage.getItem(scope)) : undefined; }
catch { return undefined; }
}, [scope]);
const selection = draft?.scope === scope ? draft.value : saved ?? modules?.selection;
const setSelection = (value: AiSelection) => {
setDraft({ scope, value });
try { if (scope) localStorage.setItem(scope, JSON.stringify(value)); }
catch { /* In-memory intent remains usable if browser storage is unavailable. */ }
};
return [selection, setSelection] as const;
}
@@ -0,0 +1,20 @@
import { useMemo, useState } from "react";
import type { AiRobot } from "./aiPolygon";
import { defaultRoverSettings, parseRoverSettings, roverSettingsKey, type RoverSettings } from "./roverSettings";
export function useRoverSettings(robot: AiRobot | undefined, speed: number) {
const scope = robot ? roverSettingsKey(robot) : null;
const [draft,setDraft] = useState<{scope:string;value:RoverSettings}|null>(null);
const saved = useMemo(()=>{
try { return robot && scope ? parseRoverSettings(localStorage.getItem(scope),robot) : undefined; }
catch { return undefined; }
},[scope]);
const value = draft?.scope===scope ? draft.value : saved ?? (robot ? defaultRoverSettings(robot,speed) : undefined);
const update = (next:RoverSettings) => {
if(!scope)return;
setDraft({scope,value:next});
// Keep usable in-memory intent, but let the caller report persistence failure.
localStorage.setItem(scope,JSON.stringify(next));
};
return [value,update] as const;
}
@@ -0,0 +1,8 @@
import type { AiCatalog, AiRun } from "./aiPolygon";
/** Read-only catalog refreshes never claim a browser's video session. */
export function viewedAiRun(catalog:AiCatalog|null,worldId:string,runId:string|null):AiRun|undefined {
if(!catalog||!runId)return undefined;
const active=catalog.runtime.active_run;
if(active?.run_id===runId&&active.world.world_id===worldId)return active;
return catalog.runs.find(r=>r.run_id===runId&&r.world.world_id===worldId);
}
@@ -0,0 +1,17 @@
export type WaypointAxis = "x" | "y" | "z" | "xz";
/** Closest point on the selected axis to the screen ray. Null at a parallel view. */
export function dragWaypoint(origin: number[], direction: number[], point: number[], axis: WaypointAxis): number[] | null {
const norm = Math.hypot(...direction);
if (norm < 1e-9) return null;
const d = direction.map(v => v / norm);
if (axis === "xz") {
if (Math.abs(d[1]) < 1e-5) return null;
const t = (point[1] - origin[1]) / d[1];
return t < 0 ? null : origin.map((v,i) => v + t*d[i]);
}
const index = {x:0,y:1,z:2}[axis], denominator = 1-d[index]**2;
if (denominator < 1e-5) return null;
const v = point.map((p,i) => p-origin[i]);
const distance = (d[index]*v.reduce((sum,p,i) => sum+p*d[i],0)-v[index])/denominator;
return point.map((p,i) => p+(i===index?distance:0));
}
@@ -0,0 +1,34 @@
import type { AiWaypoint } from "./aiPolygon";
interface Snapshot { points: AiWaypoint[]; selected: string|null }
export interface WaypointEditing extends Snapshot { history:Snapshot[]; gesture:Snapshot|null; sequence:number }
export type WaypointEdit = {type:"select";id:string|null}|{type:"replace"|"move"|"load";points:AiWaypoint[];selected?:string|null}
|{type:"delete"|"undo"|"begin"|"commit"|"cancel"};
export function waypointEditing(points:AiWaypoint[]):WaypointEditing {return {points,selected:null,history:[],gesture:null,sequence:0};}
const snapshot=(s:WaypointEditing):Snapshot=>({points:s.points,selected:s.selected});
const same=(a:AiWaypoint[],b:AiWaypoint[])=>a.length===b.length&&a.every((p,i)=>p.id===b[i].id&&p.position.every((v,j)=>v===b[i].position[j]));
export function editWaypoints(s:WaypointEditing,a:WaypointEdit):WaypointEditing {
const commit=(prior:Snapshot,points:AiWaypoint[],selected:string|null):WaypointEditing=>({
points,selected,gesture:null,history:[...s.history.slice(-49),prior],sequence:s.sequence+1,
});
switch(a.type){
case "select":return {...s,selected:a.id};
case "load":return {...waypointEditing(a.points),sequence:s.sequence+1};
case "replace":return same(s.points,a.points)?s:commit(snapshot(s),a.points,a.selected??null);
case "delete":return s.gesture||!s.points.some(p=>p.id===s.selected)?s:commit(snapshot(s),s.points.filter(p=>p.id!==s.selected),null);
case "begin":return {...s,gesture:snapshot(s)};
case "move":return s.gesture?{...s,points:a.points}:s;
case "cancel":return s.gesture?{...s,...s.gesture,gesture:null}:s;
case "commit":return !s.gesture?s:same(s.gesture.points,s.points)?{...s,gesture:null}:commit(s.gesture,s.points,s.selected);
case "undo":{
if(s.gesture)return {...s,...s.gesture,gesture:null};
const prior=s.history.at(-1);return prior?{...s,...prior,history:s.history.slice(0,-1),sequence:s.sequence+1}:s;
}
}
}
/** Keyboard shortcuts are local to the scene; native text undo remains native. */
export function waypointShortcut(e:{key:string;code:string;ctrlKey:boolean;metaKey:boolean;altKey:boolean;shiftKey:boolean},editable:boolean):"undo"|"delete"|null {
if(editable||e.altKey)return null;
if((e.ctrlKey||e.metaKey)&&!e.shiftKey&&e.code==="KeyZ")return "undo";
if(!e.ctrlKey&&!e.metaKey&&(e.key==="Delete"||e.key==="Backspace"))return "delete";
return null;
}
@@ -0,0 +1,16 @@
/** Exact closed vertical cylinder, including caps. Ray need not be normalized. */
export function waypointHit(origin:number[], direction:number[], base:number[], radius:number, height:number):number|null {
const [ox,oy,oz]=origin.map((v,i)=>v-base[i]), [dx,dy,dz]=direction;
const candidates:number[]=[];
const a=dx*dx+dz*dz,b=2*(ox*dx+oz*dz),c=ox*ox+oz*oz-radius*radius;
if(a>1e-14) {
const discriminant=b*b-4*a*c;
if(discriminant>=0)for(const t of [(-b-Math.sqrt(discriminant))/(2*a),(-b+Math.sqrt(discriminant))/(2*a)])
if(t>=0 && oy+t*dy>=0 && oy+t*dy<=height)candidates.push(t);
}
if(Math.abs(dy)>1e-14)for(const y of [0,height]) {
const t=(y-oy)/dy;
if(t>=0 && (ox+t*dx)**2+(oz+t*dz)**2<=radius*radius)candidates.push(t);
}
return candidates.length?Math.min(...candidates):null;
}
+147 -3
View File
@@ -1,12 +1,21 @@
.simulation-profiles { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-height: 0; }
.simulation-profiles > .nodedc-select-anchor { justify-self: start; }
.ai-polygon { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; min-width: 0; min-height: 0; overflow: hidden; }
.ai-polygon { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-width: 0; min-height: 0; overflow: hidden; }
.ai-polygon__content { min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: 1rem; }
.ai-polygon__head, .ai-polygon__row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
.ai-polygon__actions, .ai-polygon__facts { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
.ai-polygon__robot-select { width: 12rem; flex: 0 0 12rem; }
.ai-polygon__report { font-size: var(--nodedc-font-size-sm); }
.ai-polygon__report dl { margin: 0; display: grid; gap: .5rem; }
.ai-polygon__report dl > div { display: flex; justify-content: space-between; gap: 1rem; }
.ai-polygon__report dt, .ai-polygon__report p { color: var(--nodedc-text-muted); }
.ai-polygon__report dd { margin: 0; text-align: right; }
.ai-polygon__report h3 { margin: .5rem 0 0; font-size: var(--nodedc-font-size-md); }
.ai-polygon__report-identities dd { overflow-wrap: anywhere; max-width: 65%; }
.ai-polygon__telemetry-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
.ai-polygon__telemetry-row > .ai-polygon__facts { flex: 1; min-width: 0; }
.ai-polygon__telemetry-row > :last-child { flex-shrink: 0; }
.ai-polygon__telemetry-row--local { justify-content: flex-start; flex-wrap: wrap; }
.ai-polygon__section, .ai-polygon__run, .ai-polygon__form { display: grid; gap: .75rem; }
.ai-polygon h2, .ai-polygon h3, .ai-polygon p { margin: 0; }
.ai-polygon h2 { font-size: var(--nodedc-font-size-title); }
@@ -17,9 +26,12 @@
.ai-polygon__title { display: flex; align-items: center; gap: 1rem; }
.ai-polygon__stage { display: flex; flex-direction: column; gap: .75rem; min-width: 0; }
.ai-polygon__content--local { display: flex; flex-direction: column; gap: .75rem; overflow: hidden; padding-bottom: 0; }
.ai-polygon__content--local > .ai-polygon__section,
.ai-polygon__content--local .ai-polygon__stage { display: flex; flex-direction: column; flex: 1; min-height: 0; }
.ai-polygon__content--local .ai-polygon__viewer { flex: 1; height: auto; min-height: 0; }
.ai-polygon__viewer { display: flex; flex-direction: column; min-height: 24rem; height: min(65vh, 48rem); overflow: hidden; border-radius: var(--nodedc-radius-panel); background: var(--nodedc-canvas); }
.ai-polygon__viewer-toolbar { display: flex; justify-content: space-between; align-items: flex-start; padding: .5rem; gap: .5rem; }
.ai-polygon__viewport { flex: 1; position: relative; min-height: 0; overflow: hidden; }
.ai-polygon__viewport { flex: 1; position: relative; min-height: 0; overflow: hidden; border-radius: inherit; }
.ai-polygon__viewport[hidden] { display: none; }
.ai-polygon__viewport .nodedc-loading-region { height: 100%; }
.ai-polygon__video { width: 100%; height: 100%; pointer-events: none; }
@@ -27,3 +39,135 @@
.ai-polygon__preview-error { position: absolute; inset: 0; display: grid; place-content: center; gap: .75rem; background: var(--nodedc-canvas); }
.ai-polygon__stage:fullscreen { height: 100%; box-sizing: border-box; padding: .75rem; overflow: auto; background: var(--nodedc-canvas); }
.ai-polygon__stage:fullscreen .ai-polygon__viewer { flex: 1; height: auto; min-height: 12rem; }
.ai-polygon__plan-select { width: 16rem; flex: 0 0 16rem; }
@media (max-width: 1600px) {
.ai-polygon__robot-select { width: 8rem; flex-basis: 8rem; }
.ai-polygon__plan-select { width: 10rem; flex-basis: 10rem; }
}
.ai-route { position: absolute; inset: 0; pointer-events: none; }
.ai-route__canvas { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); overflow: hidden; }
.ai-route__canvas--editing { pointer-events: auto; touch-action: none; cursor: grab; }
.ai-route__tools { position: absolute; bottom: .75rem; left: .75rem; right: 5rem; display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; pointer-events: auto; }
.ai-route__tools p { flex-basis: 100%; padding: .25rem .5rem; background: var(--nodedc-canvas-soft); border-radius: var(--nodedc-radius-control); }
.ai-route__height { position: absolute; top: 44px; right: 12px; bottom: 12px; width: 58px; display: flex; flex-direction: column; align-items: center; gap: 6px; pointer-events: auto; color: var(--nodedc-text-muted); font-size: var(--nodedc-font-size-xs); }
.ai-route__height > .nodedc-range-scale { flex: 1; min-height: 0; }
.ai-route__line { fill: none; stroke: var(--nodedc-text-primary); stroke-width: 3; stroke-dasharray: 8 5; opacity: .8; pointer-events: none; }
.ai-route__trace { fill: none; stroke: rgb(var(--nodedc-success-rgb)); stroke-width: 4; pointer-events: none; }
.ai-route__marker { fill: var(--nodedc-text-primary); stroke: var(--nodedc-canvas); stroke-width: 2; cursor: pointer; }
.ai-route__beam { stroke: var(--nodedc-text-primary); stroke-width: 7; animation: ai-route-pulse 2s ease-in-out infinite; }
.ai-route__marker text { font: 600 16px var(--nodedc-font-family); paint-order: stroke; stroke-width: 3; }
.ai-route__marker.is-selected, .ai-route__marker.is-active { fill: rgb(var(--nodedc-accent-rgb)); }
.ai-route__marker.is-selected .ai-route__beam, .ai-route__marker.is-active .ai-route__beam { stroke: rgb(var(--nodedc-accent-rgb)); }
.ai-route__axis { stroke: rgb(var(--nodedc-accent-rgb)); stroke-width: 5; cursor: move; }
.ai-route__axis path { fill: rgb(var(--nodedc-accent-rgb)); stroke-width: 2; }
.ai-route__axis text { stroke: none; fill: var(--nodedc-text-primary); font-size: 16px; }
@keyframes ai-route-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .4; } }
@media (prefers-reduced-motion: reduce) { .ai-route__beam { animation: none; } }
.ai-local-editor__surface { position: absolute; inset: 0; touch-action: none; }
.ai-local-editor > canvas, .ai-local-editor__surface > canvas { display: block; width: 100%; height: 100%; touch-action: none; }
.ai-local-editor__markers { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
.ai-local-editor__markers .ai-route__marker { pointer-events: auto; touch-action: none; }
.ai-local-editor__markers .ai-route__beam { stroke-width: 21; }
/* View controls float above the render target; there is no separate header strip. */
.ai-simulation__view-tools { max-width: calc(100% - 6rem); flex-wrap: wrap; justify-content: flex-end; position: absolute; z-index: 3; top: .5rem; right: .5rem; display: flex; align-items: center; gap: .5rem; }
.ai-simulation__view-tools > .nodedc-select-anchor { width: 10rem; }
.ai-simulation__speed { position: absolute; left: .75rem; bottom: .75rem; pointer-events: none; font-size: var(--nodedc-font-size-sm); }
/* Equal visible padding on all three sides; owner requested twice the radius-centred inset. */
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: var(--ai-clip-inset); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
.ai-local-editor__tools { display: flex; align-items: center; gap: .5rem; }
.ai-local-editor .ai-route__tools { left: 5.5rem; right: .75rem; }
/* The renderer has no perimeter; canonical controls retain their focus indicators. */
.ai-local-editor canvas { outline: none; }
.ai-local-editor__hit, .ai-local-editor__axis-hit line { stroke: transparent; stroke-width: 28; pointer-events: stroke; }
.ai-local-editor__axis-hit { cursor: move; }
.ai-local-editor__axis-hit text { stroke: none; fill: var(--nodedc-text-primary); pointer-events: none; }
.ai-polygon__history { width: 100%; }
.ai-polygon__stream-bounds { container-type: size; }
/* Video and its projected route use the same cover transform, with one outer clip. */
.ai-polygon__stream-picture { position: absolute; inset: 0; border-radius: var(--nodedc-radius-panel); overflow: hidden; }
.ai-polygon__stream-tools { position: absolute; z-index: 3; top: 1.5rem; left: 1.5rem; right: 1.5rem; display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; pointer-events: none; }
.ai-polygon__stream-fps { flex-shrink: 0; }
.ai-polygon__stream-actions { margin-left: auto; display: flex; align-items: center; gap: .5rem; pointer-events: auto; }
.ai-polygon__video-frame { display: block; width: 100%; height: 100%; border: 0; pointer-events: none; }
.ai-polygon__stream-bounds { outline: none; touch-action: none; }
.ai-polygon__stream-actions { flex-wrap: wrap; justify-content: flex-end; max-width: 100%; }
.ai-polygon__camera-select { display: none; width: 13rem; max-width: 100%; }
@container (max-width: 45rem) {
.ai-polygon__camera-tabs { display: none; }
.ai-polygon__camera-select { display: block; }
}
.ai-polygon__inference-tools { position: absolute; z-index: 3; bottom: 1.5rem; right: 1.5rem; left: 1.5rem; display: flex; justify-content: flex-end; flex-wrap: wrap; gap: .5rem; pointer-events: none; }
.ai-polygon__inference-tools > * { pointer-events: auto; }
.ai-polygon__layer-options { display: grid; gap: .5rem; }
.ai-inference-preview { flex: 1; min-width: 0; position: relative; overflow: hidden; border-radius: var(--nodedc-radius-panel); background: var(--nodedc-canvas); }
.ai-inference-preview > img { display: block; width: 100%; height: 100%; object-fit: contain; }
.ai-inference-preview__tools { position: absolute; top: 1.5rem; left: 1.5rem; right: 1.5rem; display: flex; align-items: center; justify-content: space-between; gap: .5rem; }
.ai-inference-preview__caption { position: absolute; bottom: 1.5rem; left: 1.5rem; right: 1.5rem; display: grid; gap: .5rem; font-size: var(--nodedc-font-size-sm); }
.ai-inference-preview__legend { display: flex; flex-wrap: wrap; gap: .35rem .75rem; }
.ai-inference-preview__legend > span { display: inline-flex; align-items: center; gap: .3rem; }
.ai-inference-preview__legend i { width: .65rem; height: .65rem; border-radius: 50%; }
.ai-inference-preview__caption { background: var(--nodedc-surface-overlay, #272729); padding: .75rem; border-radius: 1rem; }
.ai-polygon__configuration-columns { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:var(--nodedc-space-6); align-items:start; }
.ai-polygon__configuration-column { display:grid; gap:var(--nodedc-space-4); min-width:0; }
.ai-polygon__configuration-fields { display: grid; gap: 1rem; width: 100%; }
.ai-polygon__profile-row { display:flex; align-items:flex-end; gap:var(--nodedc-space-2); flex-wrap:wrap; }
.ai-polygon__profile-row > :first-child { flex:1; min-width:12rem; }
@media (max-width: 800px) { .ai-polygon__configuration-columns { grid-template-columns:minmax(0,1fr); } }
.ai-polygon__rover-row { display: flex; align-items: flex-end; gap: .5rem; min-width: 0; }
.ai-polygon__rover-row > .ai-polygon__robot-select { flex: 1; width: auto; min-width: 0; }
/* Stable grid cells keep the one Worker video connection mounted as panes change. */
.ai-polygon__viewports { flex: 1; min-height: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-auto-rows: minmax(18rem, 1fr); gap: .75rem; overflow: auto; }
.ai-polygon__viewports[data-panes="1"] { grid-template-columns: minmax(0, 1fr); }
.ai-polygon__viewports > * { min-width: 0; min-height: 0; }
.ai-inference-preview:fullscreen { width: 100%; height: 100%; }
.ai-inference-preview__tools { z-index: 2; pointer-events: none; }
.ai-inference-preview__tools > * { pointer-events: auto; }
.ai-inference-preview__caption { pointer-events: none; }
.ai-polygon__viewer:has(> .ai-polygon__viewports) { background: transparent; }
@media (max-width: 800px) {
.ai-polygon__viewports { grid-template-columns: minmax(0, 1fr); }
}
.ai-polygon__configuration-fields > .ai-polygon__robot-select,
.ai-polygon__configuration-fields > .ai-polygon__plan-select { width: 100%; }
.ai-polygon__observation { display:flex; flex-direction:column; flex:1; min-width:0; min-height:0; gap:var(--nodedc-space-2); }
.ai-polygon__observation-toolbar { display:flex; justify-content:flex-end; gap:var(--nodedc-space-2); }
.ai-polygon__observation .ai-polygon__viewport, .ai-polygon__observation .ai-inference-preview { height:100%; min-height:0; }
.ai-polygon__observation .ai-polygon__stream-fps { position:absolute; bottom:var(--nodedc-space-3); left:var(--nodedc-space-3); z-index:2; }
.ai-polygon__observation .observation-panel__header { z-index:4; }
.ai-polygon__viewer:has(> .ai-polygon__observation) { background:transparent; }
/* Fixed telemetry slots keep changing status and digit counts independent. */
.ai-polygon__run { container-type: inline-size; }
.ai-polygon__run-metrics {
display: grid;
grid-template-columns: repeat(9, minmax(0, 1fr));
gap: .75rem;
width: 100%;
margin: 0;
padding: .5rem .25rem;
box-sizing: border-box;
font-size: var(--nodedc-font-size-sm);
}
.ai-polygon__run-metric { min-width: 0; text-align: center; }
.ai-polygon__run-metric dt { margin-bottom: .25rem; color: var(--nodedc-text-muted); }
.ai-polygon__run-metric dd {
margin: 0;
min-height: 2.5em;
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
.ai-polygon__run-metric--status dd { display: flex; justify-content: center; }
@container (max-width: 64rem) {
.ai-polygon__run-metrics { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@container (max-width: 32rem) {
.ai-polygon__run-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@@ -1,9 +1,9 @@
import {useEffect,useLayoutEffect,useMemo,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
import {Button,DragDropRoot,DraggableItem,DropZone,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,Window} from '@nodedc/ui-react';
import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,Window} from '@nodedc/ui-react';
import {useDevicePluginHost} from '../../../core/device-plugins/DevicePluginHost';
import {createFleetSensorTransport} from '../../../core/fleet/sensorTransport';
import {decodeObservationLayout,emptyObservationLayout,moveObservation,orderedObservationIDs} from '../../../core/fleet/observationLayout';
import {decodeObservationLayout,emptyObservationLayout,moveObservation,withObservationTree,orderedObservationIDs} from '../../../core/fleet/observationLayout';
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
@@ -45,21 +45,19 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
useEffect(()=>{try{localStorage.setItem(storageKey,JSON.stringify(layout));}catch{/* The workspace remains usable without browser storage. */}},[storageKey,layout]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,catalogVisible:show?[...new Set([...(value.catalogVisible??[]),...(sources.find(source=>source.key===id)?.catalog?[id]:[])])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
const layerFor=(key:string,view:SensorObservationView)=>view.layers?.find(layer=>layer.value===layout.layers[key])?.value??view.layers?.[0]?.value??view.id;
const navigationActions=<><IconButton label="Конфигуратор" onClick={configure}><Icon name="sliders"/></IconButton><IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton></>;
return <>{headerToolsHost&&!expanded&&createPortal(navigationActions,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&navigationActions}<Button onClick={()=>{setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
<DragDropRoot onDragEnd={({activeId,overId})=>{if(overId)setLayout(value=>moveObservation(value,ids,activeId,overId));}}>
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={effectiveFull?[effectiveFull]:visible} mounts={mounts.current} layout={layout} onSplit={(key,value)=>setLayout(current=>({...current,splits:{...current.splits,[key]:value}}))}/>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>{setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,tree))}>
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
<DropZone id={source.key} className="observation-panel">
<DraggableItem id={source.key} className="observation-panel-drag">{({handle})=>
<div className="observation-panel">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
<ObservationPanelHeader>
{handle}
<DockHandle id={source.key} label={source.view.label}/>
<div className="observation-panel__title"><h3 title={source.view.label}>{source.view.label}</h3><ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
<div className="observation-actions">
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
@@ -71,9 +69,8 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
</ObservationPanelHeader>
<ObservationMount element={media.current.get(source.key)!}/>
</GlassSurface>
}</DraggableItem>
</DropZone>,mounts.current.get(source.key)!,source.key))}
</DragDropRoot>
</div>,mounts.current.get(source.key)!,source.key))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
{groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} enabled={enabled&&inventory?.fresh!==false&&device.online} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить в конфигураторе</Button></div></div>,media.current.get(source.key)!,source.key))}
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
@@ -81,9 +78,9 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state}/>,media.current.get('telemetry')!,'telemetry-session')}
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement}))}/>
<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement,tree:undefined,splits:{}}))}/>
{ids.map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.catalog?`${source.view.label} · Источник не подключён`:source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
<Button onClick={()=>{setLayout(emptyObservationLayout());setFull(null);}}>Восстановить расположение</Button>
<Button onClick={()=>{setLayout(current=>({...current,tree:undefined,order:[],splits:{},arrangement:'auto'}));setFull(null);}}>Восстановить расположение</Button>
</div></Window>
</section>,portal)}</>;
}
@@ -1,18 +1 @@
import {useLayoutEffect,useRef} from 'react';
import {SplitPane} from '@nodedc/ui-react';
import type {ObservationLayout} from '../../../core/fleet/observationLayout';
/** Moving a mount preserves media elements, peer lifetimes and native renderer state. */
export function ObservationMount({element,className='observation-mount'}:{element:HTMLElement;className?:string}){
const ref=useRef<HTMLDivElement>(null);
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
return <div ref={ref} className={className}/>;
}
export function ObservationDeck({ids,mounts,layout,onSplit,depth=0}:{ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onSplit:(key:string,value:number)=>void;depth?:number}){
if(!ids.length)return null;
if(ids.length===1)return <ObservationMount element={mounts.get(ids[0])!}/>;
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&ids.some(id=>!['map','rover','telemetry'].includes(id));
const cameraCount=ids.filter(id=>!['map','rover','telemetry'].includes(id)).length;
const mid=defaultColumns&&cameraCount<ids.length?cameraCount:layout.arrangement==='auto'&&ids[0]==='map'&&ids.includes('rover')?1:Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical';
return <SplitPane separatorAppearance="invisible" className="observation-split" orientation={orientation} primarySize={layout.splits[key]??50} onPrimarySizeChange={value=>onSplit(key,value)} separatorLabel="Изменить размеры окон" primary={<ObservationDeck ids={ids.slice(0,mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>} secondary={<ObservationDeck ids={ids.slice(mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>}/>;
}
export {ObservationDeck,ObservationMount} from "../../../components/observation/ObservationDeck";
@@ -1,13 +1 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
export function ObservationPanelHeader({children}:{children:ReactNode}) {
const ref=useRef<HTMLElement>(null);
useLayoutEffect(()=>{
const header=ref.current!;
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
measure();const observer=new ResizeObserver(measure);observer.observe(header);
return()=>observer.disconnect();
},[]);
return <header ref={ref} className="observation-panel__header">{children}</header>;
}
export {ObservationPanelHeader} from "../../../components/observation/ObservationPanelHeader";
@@ -1,50 +1 @@
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
.observation-toolbar h2, .observation-panel h3 { margin:0; }
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
.observation-actions { flex-shrink:0; }
.observation-deck { flex:1; min-height:0; min-width:0; }
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
.observation-panel__surface > .observation-mount { flex:1; }
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
.observation-header-slot:has(> div:empty) { display:none; }
.observation-layer-select { min-width:0; max-width:120px; }
.observation-layer-select button { max-width:100%; }
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
.observation-layer > * { min-width:0; width:100%; }
.observation-layer > .nodedc-switch { text-align:left; }
.observation-empty { display:grid; place-content:center; height:100%; text-align:center; }
.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; }
@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } }
.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; }
/* Transform the live panel as one item; reveal it across nested split boundaries. */
.observation-panel-drag { position:relative; height:100%; min-height:0; }
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
.observation-split:has(.observation-panel-drag.is-dragging),
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
@container (max-width:340px) {
.observation-panel__header { flex-wrap:wrap; }
.observation-panel__title { min-width:80px; }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
}
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
@import "../../../components/observation/observation.css";
@@ -1,14 +1,37 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, StatusBadge, ToastStack } from "@nodedc/ui-react";
import { viewedAiRun } from "../../core/simulation/viewedAiRun";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, InspectorSelectField, ResourceList, ResourceRow, StatusBadge, ToastStack } from "@nodedc/ui-react";
import { SimulationSourceImport } from "../../components/simulation/SimulationSourceImport";
import { AiWorldImport } from "../../components/simulation/AiWorldImport";
import { AiWorldStream } from "../../components/simulation/AiWorldStream";
import { AiWorldSetup } from "../../components/simulation/AiWorldSetup";
import { AiRunView } from "../../components/simulation/AiRunView";
import { AiRunActions } from "../../components/simulation/AiRunActions";
import { AiCompositionFields } from "../../components/simulation/AiCompositionFields";
import { fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules, type AiSelection } from "../../core/simulation/aiPolygon";
import { AiRunReport } from "../../components/simulation/AiRunReport";
import { AiConfiguration } from "../../components/simulation/AiConfiguration";
import { AiSessionSection } from "../../components/simulation/AiSessionSection";
import { AiTaskSelect } from "../../components/simulation/AiTaskSelect";
import { AiPlanSaveWindow } from "../../components/simulation/AiPlanSaveWindow";
import { planMatchesDraft } from "../../core/simulation/planDraft";
import type { AiPlan, AiWaypoint } from "../../core/simulation/aiPolygon";
import { aiPlanName, updateAiPlan, removeAiRun, fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules } from "../../core/simulation/aiPolygon";
import { useAiSelection } from "../../core/simulation/useAiSelection";
import { useRoverSettings } from "../../core/simulation/useRoverSettings";
import { RoverSettingsWindow } from "../../components/simulation/RoverSettingsWindow";
import { currentSelection } from "../../core/simulation/runConfiguration";
import { saveLocalPlan } from "../../core/simulation/aiEditor";
import type { LocalDraft } from "../../components/simulation/AiLocalPlanner";
const LocalManualScene = lazy(() => import("../../components/simulation/LocalManualScene").then((m) => ({ default: m.LocalManualScene })));
const AiLocalPlanner = lazy(() => import("../../components/simulation/AiLocalPlanner").then((m) => ({ default: m.AiLocalPlanner })));
const EMPTY_POINTS:AiWaypoint[]=[];
export function AiPolygonWorkspace() {
const [mode,setMode] = useState<"manual"|"inference">("inference");
const [manual,setManual] = useState(false);
const [importChoice,setImportChoice] = useState(false);
const [planning, setPlanning] = useState(false);
const [draft, setDraft] = useState<LocalDraft | null>(null);
const [catalog, setCatalog] = useState<AiCatalog | null>(null);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [runId, setRunId] = useState<string | null>(null);
@@ -16,14 +39,49 @@ export function AiPolygonWorkspace() {
const [error, setError] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [roverSettingsOpen,setRoverSettingsOpen] = useState(false);
const [actionsHost, setActionsHost] = useState<HTMLDivElement | null>(null);
const [modules, setModules] = useState<AiModules | null>(null);
const [selection, setSelection] = useState<AiSelection | undefined>();
const [robotId, setRobotId] = useState<string | null>(null);
const [planId, setPlanId] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [saveOpen, setSaveOpen] = useState(false);
const [launchAfterSave,setLaunchAfterSave] = useState(false);
const [editorPlan,setEditorPlan] = useState<AiPlan|null>(null);
const [planName, setPlanName] = useState("");
const [removing,setRemoving] = useState<string|null>(null);
const [removed,setRemoved] = useState<{kind:"plan"|"run";id:string;name:string}[]>([]);
const planUpdated = (value:AiPlan) => {
setCatalog(prior=>prior?{...prior,plans:value.removed ? prior.plans.filter(p=>p.plan_id!==value.plan_id)
: prior.plans.map(p=>p.plan_id===value.plan_id?value:p)}:prior);
if(value.removed){
setRemoved(prior=>[...prior,{kind:"plan",id:value.plan_id,name:aiPlanName(value)}]);
if(plan?.plan_id===value.plan_id)setPlanId("");
}
};
const removeRun = async (value:AiRun) => {
setRemoving(value.run_id);
try {
await removeAiRun(value.run_id,true);
setCatalog(prior=>prior?{...prior,runs:prior.runs.filter(r=>r.run_id!==value.run_id)}:prior);
setRemoved(prior=>[...prior,{kind:"run",id:value.run_id,name:`Прогон ${new Date(value.created_at??"").toLocaleString("ru-RU")}`}]);
} catch(caught) { setError(caught instanceof Error?caught.message:"Не удалось удалить прогон."); }
finally {setRemoving(null);}
};
const undoRemove = async () => {
const item=removed.at(-1);if(!item)return;
setRemoving(item.id);
try {
if(item.kind==="plan")await updateAiPlan(item.id,{removed:false});else await removeAiRun(item.id,false);
await load();setRemoved(prior=>prior.filter(p=>p.id!==item.id));
} catch(caught) {setError(caught instanceof Error?caught.message:"Не удалось восстановить запись.");}
finally {setRemoving(null);}
};
const fast = useRef(false);
const load = useCallback(async () => { const result = await fetchAiCatalog(); setCatalog(result); }, []);
useEffect(() => {
let active = true;
void fetchAiModules().then((value) => { if (active) { setModules(value); setSelection(value.selection); } })
void fetchAiModules().then((value) => { if (active) setModules(value); })
.catch((caught: Error) => { if (active) setError(caught.message); });
return () => { active = false; };
}, []);
@@ -39,15 +97,17 @@ export function AiPolygonWorkspace() {
void poll(); return () => { active = false; clearTimeout(timer); };
}, []);
const selected = catalog?.worlds.find((world) => world.world_id === selectedId);
const activeRun = catalog?.runtime.active_run;
useEffect(() => {
if (activeRun?.world.world_id === selectedId) setRunId(activeRun.run_id);
}, [activeRun?.run_id, activeRun?.world.world_id, selectedId]);
const run = selected ? catalog?.runtime.active_run?.world.world_id === selected.world_id
? catalog.runtime.active_run : catalog?.runs.find((item) => item.run_id === runId && item.world.world_id === selected.world_id)
: undefined;
// Catalog observation does not acquire NVIDIA's single video slot. Only Start
// or an explicit Open may attach this browser to a running simulation.
const run = selected && mode === "inference" ? viewedAiRun(catalog,selected.world_id,runId) : undefined;
const shownFailure=useRef<string|null>(null);
useEffect(()=>{
if(run?.state==='failed'&&shownFailure.current!==run.run_id){
shownFailure.current=run.run_id;setError(run.message??'Не удалось запустить симуляцию.');
}
},[run?.run_id,run?.state,run?.message]);
const acceptRun = (value: AiRun) => {
setSettingsOpen(false);
setSettingsOpen(false);setPlanning(false);setDraft(null);
setRunId(value.run_id); fast.current = !["completed", "stopped", "failed"].includes(value.state);
setCatalog((prior) => prior ? { ...prior, runs: [value, ...prior.runs.filter((r) => r.run_id !== value.run_id)],
runtime: { ...prior.runtime, active_run: fast.current ? value : null } } : prior);
@@ -59,21 +119,81 @@ export function AiPolygonWorkspace() {
const openWorld = (world: AiWorld) => {
if (world.status === "uploading") setImporting({ source: world, resume: world });
else {
setSelectedId(world.world_id); setRunId(null); setSettingsOpen(!world.settings.prepared);
setSelectedId(world.world_id); setRunId(catalog?.runtime.active_run?.world.world_id===world.world_id?catalog.runtime.active_run.run_id:null); setPlanId(null);setEditorPlan(null);setSettingsOpen(!world.settings.prepared);
}
};
const returnToLocations = () => { setSelectedId(null); setRunId(null); };
const returnToLocations = () => { setManual(false); setPlanning(false); setDraft(null); setSelectedId(null); setRunId(null); };
const running = !!run && !["completed", "stopped", "failed"].includes(run.state);
const robot = catalog?.robots?.find((item) => item.robot_id === robotId) ?? catalog?.robots?.[0];
const [selection, setSelection] = useAiSelection(selectedId, robot?.robot_id ?? null, modules);
const plans = (catalog?.plans ?? []).filter((p) => p.world_id === selectedId
&& p.robot_id === robot?.robot_id && p.robot_sha256 === robot?.sha256);
const previousPlan = (catalog?.plans ?? []).find((p) => p.world_id === selectedId && p.robot_id === robot?.robot_id);
const plan = planId === null ? plans[0] : plans.find((p) => p.plan_id === planId);
const [roverSettings,setRoverSettings] = useRoverSettings(robot,
plan?.settings?.max_speed_mps ?? selected?.settings.max_speed_mps ?? .15);
const start = (purpose: "planning" | "evaluation", task=plan) => {
if (!selected || !robot) return;
if (purpose === "planning") { setEditorPlan(plan??(planId===null?previousPlan:null)??null);setSettingsOpen(false); setDraft(null); setPlanning(true); return; }
setStarting(true);
void fetchAiModules().then((fresh) => {
setModules(fresh);
const composition = currentSelection(selection ?? fresh.selection, fresh);
setSelection(composition);
return startAiRun(selected, robot, composition, purpose, task, roverSettings);
}).then(acceptRun).catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false));
};
const save = () => {
if (!draft || !robot) return;
setSaving(true);
void saveLocalPlan(draft.cache, robot, draft.points, planName, draft.id, draft.sequence).then(async (saved) => {
setPlanId(saved.plan_id);setSaveOpen(false);
setCatalog(prior=>prior?{...prior,plans:[saved,...prior.plans.filter(p=>p.plan_id!==saved.plan_id)]}:prior);
if(launchAfterSave)start("evaluation",saved);
}).catch((caught: Error) => setError(caught.message)).finally(() => setSaving(false));
};
const openSave = (launch=false) => {
setLaunchAfterSave(launch);setPlanName(plan?aiPlanName(plan):`${selected?.name} · маршрут`);setSaveOpen(true);
};
const launchDraft = () => {
if(!draft||!robot)return;
if(planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points))start("evaluation",plan);
else openSave(true);
};
const connection = <StatusBadge tone={catalog?.runtime.available ? "success" : "neutral"}>
{catalog?.runtime.available ? "Симулятор подключён" : "Симулятор не подключён"}
</StatusBadge>;
const sceneActions = selected && catalog ? <>
<Button onClick={() => setSettingsOpen(!settingsOpen)}>Старт и масштаб</Button>
{!run || ["completed", "stopped", "failed"].includes(run.state) ? <Button variant="primary"
icon={<Icon name="play" />} loading={starting}
disabled={!catalog.runtime.available || !selected.settings.prepared || !!catalog.runtime.active_run}
onClick={() => { setStarting(true); void startAiRun(selected, selection).then(acceptRun)
.catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false)); }}>Открыть симуляцию</Button> : null}
{run ? <AiRunActions run={run} onChange={acceptRun} /> : null}
{!planning&&!manual&&!running&&!starting?<><div className="ai-polygon__robot-select"><InspectorSelectField label="Режим" value={mode}
options={[{value:"inference",label:"Inference"},{value:"manual",label:"Ручное управление"}]}
disabled={running || planning || manual || starting}
onChange={(value)=>{setMode(value);setRunId(null);setSettingsOpen(false);}} /></div>
<div className="ai-polygon__rover-row"><div className="ai-polygon__robot-select"><InspectorSelectField label="Ровер"
value={running ? run.robot?.robot_id ?? "" : robot?.robot_id ?? ""}
options={(catalog.robots ?? []).map((item) => ({ value: item.robot_id, label: item.name }))}
disabled={planning || manual || starting || running} onChange={(id)=>{setRobotId(id);setPlanId(null);}} /></div>
<IconButton label="Настройки ровера" disabled={!robot || !roverSettings || starting}
onClick={()=>setRoverSettingsOpen(true)}><Icon name="settings"/></IconButton>
</div>
{roverSettings?<p>{roverSettings.max_speed_mps} м/с · {roverSettings.base_mass_kg+roverSettings.payload_mass_kg} кг с грузом</p>:null}</>:null}
{mode==="inference"&&!running&&!starting?<AiTaskSelect inspector={!planning} plans={plans} value={plan?.plan_id??""}
disabled={running||starting||saving} onUpdated={planUpdated}
onChange={(id)=>{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null}
<div className="ai-polygon__actions">{mode === "manual" ? <Button variant="primary" icon={<Icon name={manual ? "stop" : "play"} />}
disabled={!robot || !selected.settings.prepared}
onClick={()=>{setSettingsOpen(false);setManual(!manual);}}>{manual ? "Завершить" : "Старт"}</Button> : planning ? <>
<Button disabled={starting || saving || !draft || draft.points.length < 2}
onClick={()=>openSave()}>Сохранить задание</Button>
<Button variant="primary" icon={<Icon name="play"/>} loading={starting}
disabled={saving || !draft || draft.points.length<2 || selected.inference_ready===false || !catalog.runtime.available || !!catalog.runtime.active_run}
onClick={launchDraft}>Запустить симуляцию</Button>
</> : !running ? <>
<Button loading={starting} disabled={!robot || !selected.settings.prepared}
onClick={() => start("planning")}>Подготовить маршрут</Button>
<Button variant="primary" icon={<Icon name="play" />} loading={starting}
disabled={!robot || !plan || selected.inference_ready === false || !catalog.runtime.available || !!catalog.runtime.active_run}
onClick={() => start("evaluation")}>Запустить симуляцию</Button>
</> : <AiRunActions run={run!} onChange={acceptRun} />}</div>
</> : null;
return <div className="ai-polygon">
<header className="ai-polygon__head">
@@ -84,34 +204,74 @@ export function AiPolygonWorkspace() {
<h2>{selected?.name ?? "Доступные локации"}</h2>
</div>
<div className="ai-polygon__actions" ref={setActionsHost}>
{selected ? !run ? sceneActions : null : <>{connection}
<Button icon={<Icon name="upload" />} onClick={() => setImporting({ source: null })}>Импорт локации</Button></>}
{selected ? null : <>{connection}
<Button icon={<Icon name="upload" />} onClick={() => setImportChoice(true)}>Импорт локации</Button></>}
</div>
</header>
<LoadingRegion className="ai-polygon__content" loading={!catalog && !error} label="Загрузка локаций">
<LoadingRegion className={`ai-polygon__content${manual||planning?" ai-polygon__content--local":""}`} loading={!catalog && !error} label="Загрузка локаций">
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Не удалось выполнить действие", description: error }]} onDismiss={() => setError(null)} /> : null}
{removed.length?<GlassSurface padding="sm" className="ai-polygon__row">
<span>Удалено из списка: {removed.at(-1)?.name}</span>
<Button disabled={removing!==null} onClick={()=>void undoRemove()}>Отменить удаление</Button>
</GlassSurface>:null}
{catalog ? !selected ? <section aria-label="Доступные локации" className="ai-polygon__section">
{catalog.worlds.map((world) => <GlassSurface key={world.world_id} padding="md" className="ai-polygon__row">
<div><strong>{world.name}</strong><p>{world.author} · {world.license}</p></div>
{catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
{catalog.runtime.active_run.state === "running" && catalog.runtime.active_run.telemetry?.ai_ready
? "AI запущен" : catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
</StatusBadge> : null}
<Button onClick={() => openWorld(world)}>{world.status === "uploading" ? "Продолжить импорт" : "Открыть"}</Button>
</GlassSurface>)}
<ResourceList>{catalog.worlds.map((world) => <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
status={catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
{catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
</StatusBadge> : undefined}
actions={<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
onClick={() => openWorld(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>}/>
</li>)}</ResourceList>
</section> : <section className="ai-polygon__section" aria-label={`Симуляция ${selected.name}`}>
<LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
{run ? <AiWorldStream world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
{!running && !planning && !manual ? <AiSessionSection key={`${selected.world_id}:configuration`}
scope={`${selected.world_id}:configuration`} title="Конфигурация">
<div className="ai-polygon__configuration-columns">
<section className="ai-polygon__configuration-column" aria-label="Базовые настройки">
<h3>Базовые настройки</h3>
<div className="ai-polygon__configuration-fields">
<InspectorSelectField label="Локация" value={selected.world_id}
options={catalog.worlds.filter(w=>w.status!=="uploading").map(w=>({value:w.world_id,label:w.name}))}
disabled={starting} onChange={id=>{const world=catalog.worlds.find(w=>w.world_id===id);if(world)openWorld(world);}} />
{sceneActions}
</div>
{mode === "inference" && !running && !planning ? <div className="ai-polygon__facts">
{plan ? <p>{plan.points.length} точек · {plan.length_m.toFixed(1)} м · задание сохранено</p>
: <p>{previousPlan && !plans.length && planId===null ? "Сохранённый маршрут использует другую версию ровера. Откройте «Подготовить маршрут» и сохраните задание для выбранного ровера." : "Для запуска выберите задание или сохраните маршрут минимум из двух точек: старт и финиш."}</p>}
</div> : null}
</section>
{mode==='inference'&&modules&&selection?<AiConfiguration key={selected.world_id} modules={modules}
selection={selection} disabled={starting||!!catalog.runtime.active_run} onChange={setSelection}/>:null}
</div>
</AiSessionSection> : null}
{mode === "inference" && !planning && !running && catalog.runtime.active_run ? <div className="ai-polygon__facts"><p>Выполняется симуляция «{catalog.runtime.active_run.world.name}».</p>
{catalog.runtime.active_run.world.world_id===selected.world_id?<Button onClick={()=>acceptRun(catalog.runtime.active_run!)}>Открыть текущую симуляцию</Button>:null}</div> : null}
{manual && robot ? <Suspense fallback={<LoadingRegion loading label="Открываем ручное управление" />}>
<LocalManualScene key={selected.world_id} world={selected} robot={robot} settings={roverSettings} actionsHost={actionsHost} headerActions={sceneActions} />
</Suspense> : planning ? <Suspense fallback={<LoadingRegion loading label="Открываем редактор" />}>
<AiLocalPlanner key={selected.world_id} world={selected} initialPoints={editorPlan?.points ?? EMPTY_POINTS}
busy={starting || saving} onDraft={setDraft} actionsHost={actionsHost} headerActions={sceneActions} />
</Suspense> : <LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
{mode === "inference" && running && run ? <AiWorldStream key={run.run_id} world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
actionsHost={actionsHost} headerActions={sceneActions}
controls={<AiRunView run={run} connection={connection} />} /> : <div className="ai-polygon__telemetry-row">{connection}</div>}
</LoadingRegion>
controls={<AiRunView run={run} />} /> : mode === "inference" ? <div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">{connection}{selected.inference_ready===false?<p>{selected.inference_message}</p>:null}</div> : null}
</LoadingRegion>}
{mode === "inference" && !planning ? <AiRunReport key={selected.world_id} worldId={selected.world_id} modules={modules} onRemove={removeRun} removing={removing} runs={catalog.runs.filter((item) => item.world.world_id === selected.world_id)} /> : null}
{settingsOpen ? <AiWorldSetup key={selected.world_id} world={selected}
disabled={!!catalog.runtime.active_run} onSaved={acceptWorld} /> : null}
{settingsOpen && modules && selection ? <AiCompositionFields modules={modules}
selection={activeRun?.world.world_id === selectedId ? activeRun.request?.composition ?? selection : selection}
disabled={!!catalog.runtime.active_run} onChange={setSelection} /> : null}
</section> : null}
</LoadingRegion>
{roverSettingsOpen && robot && roverSettings && !running && !manual && !planning && !starting
? <RoverSettingsWindow key={robot.sha256} robot={robot} value={roverSettings} manual={mode==="manual"}
onClose={()=>setRoverSettingsOpen(false)} onApply={value=>{
setRoverSettingsOpen(false);
try {setRoverSettings(value);} catch {setError("Настройки применены, но не сохранены в браузере. После перезагрузки их нужно задать снова.");}
}}/> : null}
{saveOpen?<AiPlanSaveWindow name={planName} onName={setPlanName} busy={saving}
launch={launchAfterSave} onClose={()=>setSaveOpen(false)} onSave={save}/>:null}
<SimulationSourceImport open={importChoice} onClose={()=>setImportChoice(false)}
onPly={()=>setImporting({source:null})} onReady={(id)=>{void load();setSelectedId(id);}} />
{importing ? <AiWorldImport source={importing.source} resume={importing.resume}
onClose={() => setImporting(null)} onImported={acceptWorld} /> : null}
</div>;
@@ -1,428 +1,6 @@
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type DragEvent,
} from "react";
import {
ActivityIndicator,
Button,
ConfirmationModal,
GlassSurface,
Icon,
StatusBadge,
Select,
} from "@nodedc/ui-react";
import { SimulationCatalog } from "../../components/simulation/SimulationCatalog";
import { AiPolygonWorkspace } from "./AiPolygonWorkspace";
import { SimulationProjectWindow } from "../../components/simulation/SimulationProjectWindow";
import { SimulationViewport } from "../../components/simulation/SimulationViewport";
import {
createSimulationProject,
deleteSimulationProject,
fetchSimulationProjects,
retrySimulationProject,
uploadSimulationProjectSource,
type SimulationProject,
type SimulationProjectStatus,
type SimulationUploadProgress,
} from "../../core/simulation/projects";
import {
archiveProjectName,
archivesFromDrop,
hasDroppedFiles,
} from "../../core/simulation/sourceFiles";
const BUILD_STATUSES = new Set<SimulationProjectStatus>(["queued", "processing", "importing"]);
interface BrowserUpload {
project: SimulationProject;
file: File;
}
/** One location library; execution mode is selected inside the location. */
export function SimulationWorkspace() {
const [profile, setProfile] = useState<"lcc" | "ai">(() => {
try { return localStorage.getItem("missioncore.simulation-profile") === "ai" ? "ai" : "lcc"; }
catch { return "lcc"; }
});
return <div className="simulation-profiles" data-simulation-profile={profile}>
<Select label="Профиль симуляции" value={profile} options={[
{ value: "lcc", label: "LCC Gaussian Mirror" }, { value: "ai", label: "AI-полигон" },
]} onChange={(value) => { setProfile(value);
try { localStorage.setItem("missioncore.simulation-profile", value); } catch { /* Private browsing. */ }
}} />
{profile === "lcc" ? <LccGaussianWorkspace /> : <AiPolygonWorkspace />}
</div>;
}
function LccGaussianWorkspace() {
const [projects, setProjects] = useState<SimulationProject[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [windowOpen, setWindowOpen] = useState(false);
const [editing, setEditing] = useState<SimulationProject | null>(null);
const [deleting, setDeleting] = useState<SimulationProject | null>(null);
const [retryingId, setRetryingId] = useState<string | null>(null);
const [pendingUploads, setPendingUploads] = useState<BrowserUpload[]>([]);
const [uploadProgress, setUploadProgress] = useState<Map<string, SimulationUploadProgress>>(
() => new Map(),
);
const [queueError, setQueueError] = useState<string | null>(null);
const [dropping, setDropping] = useState(false);
const activeUploadRef = useRef<{ projectId: string; controller: AbortController } | null>(null);
const intakeChainRef = useRef<Promise<void>>(Promise.resolve());
const dragDepthRef = useRef(0);
const load = useCallback(async (signal?: AbortSignal) => {
try {
const next = await fetchSimulationProjects(signal);
setProjects(next);
setError(null);
} catch (caught) {
if (signal?.aborted) return;
setError(caught instanceof Error ? caught.message : "Каталог симуляций недоступен.");
} finally {
if (!signal?.aborted) setLoading(false);
}
}, []);
useEffect(() => {
const controller = new AbortController();
void load(controller.signal);
return () => controller.abort();
}, [load]);
useEffect(() => {
if (!projects.some((project) => BUILD_STATUSES.has(project.status))) return;
const timer = window.setInterval(() => void load(), 2_000);
return () => window.clearInterval(timer);
}, [load, projects]);
useEffect(() => {
const next = pendingUploads[0];
if (!next || activeUploadRef.current) return;
const controller = new AbortController();
activeUploadRef.current = { projectId: next.project.projectId, controller };
void uploadSimulationProjectSource(
next.project,
[{ file: next.file, logicalPath: next.file.name }],
(progress) => {
setUploadProgress((current) => {
const updated = new Map(current);
updated.set(next.project.projectId, progress);
return updated;
});
setProjects((current) => current.map((project) => (
project.projectId === next.project.projectId
? {
...project,
source: { ...project.source, uploadedByteLength: progress.uploadedBytes },
}
: project
)));
},
controller.signal,
).then((queued) => {
setProjects((current) => current.map((project) => (
project.projectId === queued.projectId ? queued : project
)));
setQueueError(null);
}).catch((caught) => {
if (controller.signal.aborted) return;
setQueueError(caught instanceof Error
? `${next.file.name}: ${caught.message}`
: `${next.file.name}: загрузка остановлена.`);
}).finally(() => {
setPendingUploads((current) => current.filter(
(item) => item.project.projectId !== next.project.projectId,
));
setUploadProgress((current) => {
const updated = new Map(current);
updated.delete(next.project.projectId);
return updated;
});
activeUploadRef.current = null;
});
}, [pendingUploads]);
useEffect(() => () => activeUploadRef.current?.controller.abort(), []);
const selected = useMemo(
() => projects.find((project) => project.projectId === selectedId) ?? null,
[projects, selectedId],
);
const openCreate = () => {
setEditing(null);
setWindowOpen(true);
};
const openEdit = (project: SimulationProject) => {
setEditing(project);
setWindowOpen(true);
};
const acceptSaved = (project: SimulationProject) => {
const wasEditing = editing !== null;
setProjects((current) => [project, ...current.filter((item) => item.projectId !== project.projectId)]);
if (!wasEditing) setSelectedId(project.projectId);
setWindowOpen(false);
setEditing(null);
};
const acceptViewerProject = useCallback((project: SimulationProject) => {
setProjects((current) => current.map((item) => (
item.projectId === project.projectId ? project : item
)));
}, []);
const confirmDelete = async () => {
if (!deleting) return;
const pending = pendingUploads.find((item) => item.project.projectId === deleting.projectId);
if (activeUploadRef.current?.projectId === deleting.projectId) {
activeUploadRef.current.controller.abort();
}
setPendingUploads((current) => current.filter(
(item) => item.project.projectId !== deleting.projectId,
));
try {
await deleteSimulationProject(deleting.projectId);
setProjects((current) => current.filter((project) => project.projectId !== deleting.projectId));
setUploadProgress((current) => {
const updated = new Map(current);
updated.delete(deleting.projectId);
return updated;
});
if (selectedId === deleting.projectId) setSelectedId(null);
setDeleting(null);
} catch (caught) {
if (pending) setPendingUploads((current) => [pending, ...current]);
const message = caught instanceof Error ? caught.message : "Не удалось удалить проект.";
setQueueError(message);
throw caught;
}
};
const enqueueDroppedArchives = useCallback((files: File[]) => {
intakeChainRef.current = intakeChainRef.current.then(async () => {
for (const file of files) {
try {
const project = await createSimulationProject(
archiveProjectName(file.name),
"outdoor",
[{ file, logicalPath: file.name }],
);
setProjects((current) => [
project,
...current.filter((item) => item.projectId !== project.projectId),
]);
setPendingUploads((current) => [...current, { project, file }]);
} catch (caught) {
setQueueError(caught instanceof Error
? `${file.name}: ${caught.message}`
: `${file.name}: не удалось создать проект.`);
}
}
});
}, []);
const handleDrop = async (transfer: DataTransfer) => {
dragDepthRef.current = 0;
setDropping(false);
setQueueError(null);
try {
enqueueDroppedArchives(await archivesFromDrop(transfer));
} catch (caught) {
setQueueError(caught instanceof Error ? caught.message : "Архивы не приняты.");
}
};
const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
if (!hasDroppedFiles(event.dataTransfer)) return;
event.preventDefault();
dragDepthRef.current += 1;
setDropping(true);
};
const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
if (!hasDroppedFiles(event.dataTransfer)) return;
event.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) setDropping(false);
};
const retry = async (project: SimulationProject) => {
setRetryingId(project.projectId);
setError(null);
try {
const queued = await retrySimulationProject(project.projectId);
setProjects((current) => current.map((item) => (
item.projectId === queued.projectId ? queued : item
)));
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Не удалось повторить сборку.");
} finally {
setRetryingId(null);
}
};
if (selected) {
return (
<div className="simulation-workspace simulation-workspace--scene">
<header className="simulation-workspace__scene-head">
<Button
size="compact"
variant="ghost"
icon={<Icon name="chevron-left" size={16} />}
onClick={() => setSelectedId(null)}
>
Все проекты
</Button>
<div>
<span className="section-eyebrow">LAB / SIMULATION RUNTIME</span>
<h2>{selected.name}</h2>
</div>
<StatusBadge tone={statusPresentation(selected.status).tone}>
{statusPresentation(selected.status).label}
</StatusBadge>
</header>
{selected.status === "ready" && selected.worldManifest ? (
<SimulationViewport
project={selected}
onProjectChange={acceptViewerProject}
/>
) : (
<GlassSurface className="simulation-workspace__processing" padding="lg">
{selected.status === "failed" ? <Icon name="alert" size={20} /> : <ActivityIndicator label="Сборка мира" />}
<div className="simulation-workspace__processing-copy">
<strong>{selected.status === "failed" ? "Сборка остановлена" : "Worker 006 собирает мир"}</strong>
<p>{error ?? selected.error ?? processingMessage(selected)}</p>
</div>
<div className="simulation-workspace__processing-actions">
<StatusBadge tone={selected.status === "failed" ? "warning" : "accent"}>
{providerStateLabel(selected.provider.state, selected.status)}
</StatusBadge>
{selected.status === "failed" ? (
<Button
size="compact"
variant="secondary"
disabled={retryingId === selected.projectId}
icon={retryingId === selected.projectId
? <ActivityIndicator size="compact" />
: <Icon name="refresh" size={14} />}
onClick={() => void retry(selected)}
>
Повторить сборку
</Button>
) : null}
</div>
</GlassSurface>
)}
</div>
);
}
return (
<div
className="simulation-workspace"
onDragEnter={handleDragEnter}
onDragOver={(event) => {
if (!hasDroppedFiles(event.dataTransfer)) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
}}
onDragLeave={handleDragLeave}
onDrop={(event) => {
if (!hasDroppedFiles(event.dataTransfer)) return;
event.preventDefault();
void handleDrop(event.dataTransfer);
}}
>
<header className="simulation-workspace__head">
<div>
<span className="section-eyebrow">ТЕСТОВЫЙ КОНТУР / СИМУЛЯЦИИ</span>
<h2>Gaussian-миры</h2>
<p>Каталог исходников, сборок Worker 006 и полнофункциональных интерактивных сцен.</p>
</div>
<Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={openCreate}>
Новый проект
</Button>
</header>
<SimulationCatalog
projects={projects}
uploadProgress={uploadProgress}
loading={loading}
loadError={error}
queueError={queueError}
dropping={dropping}
onCreate={openCreate}
onRetryLoad={() => void load()}
onSelect={(project) => setSelectedId(project.projectId)}
onEdit={openEdit}
onDelete={setDeleting}
/>
<SimulationProjectWindow
open={windowOpen}
project={editing}
onClose={() => { if (!windowOpen) return; setWindowOpen(false); setEditing(null); }}
onSaved={acceptSaved}
/>
<ConfirmationModal
open={deleting !== null}
title="Удалить проект симуляции?"
description={(
<p>
Проект <strong>{deleting?.name}</strong>, локальные производные артефакты и job на Worker 006 будут удалены.
</p>
)}
confirmLabel="Удалить проект"
pendingLabel="Удаляем…"
danger
onClose={() => setDeleting(null)}
onConfirm={confirmDelete}
/>
</div>
);
}
function statusPresentation(status: SimulationProjectStatus): {
label: string;
tone: "success" | "accent" | "warning" | "neutral";
} {
if (status === "ready") return { label: "Визуал готов", tone: "success" };
if (status === "failed") return { label: "Ошибка", tone: "warning" };
if (status === "uploading") return { label: "Загрузка", tone: "neutral" };
if (status === "importing") return { label: "Импорт", tone: "accent" };
return { label: "Сборка", tone: "accent" };
}
function processingMessage(project: SimulationProject): string {
const progress = project.provider.progress;
const completed = progress?.completed_steps;
const total = progress?.total_steps;
if (typeof completed === "number" && typeof total === "number") {
return `Этап ${completed.toLocaleString("ru-RU")} из ${total.toLocaleString("ru-RU")}. Каталог обновляется автоматически.`;
}
return "Исходник подтверждён; локация и её LOD-уровни собираются в переносимом контейнере.";
}
function providerStateLabel(
state: string | null,
projectStatus: SimulationProjectStatus,
): string {
if (state === "queued") return "Ожидание";
if (state === "verifying_source") return "Проверка исходника";
if (state === "inspecting") return "Анализ локации";
if (state === "building_preview") return "Подготовка локации";
if (state === "building_streamed_sog") return "Сборка LOD";
if (state === "building_collision") return "Сборка коллизий";
if (state === "ready") return "Визуал готов";
if (state === "failed") return "Ошибка";
return statusPresentation(projectStatus).label;
return <AiPolygonWorkspace />;
}