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
+6
View File
@@ -207,6 +207,12 @@ See [the Dataset Gateway plan](docs/14_LIDAR_DATASET_GATEWAY.md),
## Simulation Polygon
Current AI Polygon purpose, architecture, measured status and experiment plan:
[AI Polygon workflow](docs/AI_POLYGON_WORKFLOW.md), reconciled 2026-10-02.
It uses Isaac and shared AI modules entirely on Worker006, with operator video
on the Mac. The Gazebo/PX4 S0/S1 account below is a historical profile with its
own evidence; it must not be read as the current AI Polygon implementation.
Mission Core now has a parallel Polygon product branch for reproducible
autonomy qualification. Mission Core owns scenarios, qualification-run
lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4
+11 -1
View File
@@ -21,7 +21,8 @@
"playcanvas": "2.21.4",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1"
"three": "0.185.1",
"three-mesh-bvh": "0.9.15"
},
"devDependencies": {
"@types/node": "^24.0.0",
@@ -1893,6 +1894,15 @@
"integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
"license": "MIT"
},
"node_modules/three-mesh-bvh": {
"version": "0.9.15",
"resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.15.tgz",
"integrity": "sha512-9xdEDkCzFoT8VPFH9DznwFSdbaIEjMvM106Iqq7TJurrIheUKDcdW4prfJTCxryih4XS/UxWs0H3K4MLMRFyOQ==",
"license": "MIT",
"peerDependencies": {
"three": ">= 0.159.0"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+2 -1
View File
@@ -25,7 +25,8 @@
"playcanvas": "2.21.4",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1"
"three": "0.185.1",
"three-mesh-bvh": "0.9.15"
},
"devDependencies": {
"@types/node": "^24.0.0",
@@ -0,0 +1,174 @@
{
"schema_version": "missioncore.rover-motion/v1",
"source_scene": "DCD-006_rover_v020.blend",
"source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79",
"source_saved": false,
"visual_sha256": "4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e",
"forward_axis": "+X",
"up_axis": "Y",
"track_centres_m": {
"L": 0.3425,
"R": -0.3425
},
"track_width_m": 0.685,
"shift_m": [
-0.05350000038743019,
0.0,
0.0
],
"length_m": 2.222,
"pitch_m": 0.0505,
"phase_m": 0.03069696662739778,
"segments": [
[
"arc",
0,
0.060539054924808725,
[
-0.16593354688111153,
0.32184557191629776,
0.0655,
2.3390854961098873
]
],
[
"line",
0.060539054924808725,
0.5760464371429339,
[
-0.15575880346026824,
0.3865504758751169,
0.9878611291422765,
-0.1553395942113481,
0.15533959421134813,
0.9878611291422766
]
],
[
"arc",
0.6365854920677426,
0.15172294911931034,
[
0.40182697,
0.22413776,
0.07382606110411796,
1.4148251155784564
]
],
[
"line",
0.7883084411870529,
0.1629407568053742,
[
0.46102862009488454,
0.18003048254840684,
-0.5974486081464921,
-0.8019072020027126,
0.8019072020027126,
-0.5974486081464921
]
],
[
"arc",
0.9512491979924271,
0.06094648310379254,
[
0.31115497,
0.0885,
0.0655,
-0.6403156687217281
]
],
[
"line",
1.0121956810962196,
0.7185584980197575,
[
0.31115497,
0.022999999999999993,
-1.0,
0.0,
-0.0,
-1.0
]
],
[
"arc",
1.730754179115977,
0.15545137821999958,
[
-0.40740352801975754,
0.0885,
0.0655,
-1.5707963267948966
]
],
[
"line",
1.8862055573359766,
0.33579444266402353,
[
-0.45291987081346463,
0.1356010885085021,
0.719100587916063,
0.6949059968504895,
-0.6949059968504895,
0.719100587916063
]
]
],
"link_count": 44,
"wheels": [
{
"node": "R_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "R_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_DRIVE",
"radius_m": 0.07233592163526643
},
{
"node": "L_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "L_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_DRIVE",
"radius_m": 0.07233592163526643
}
],
"dimensions_m": [
1.1630001068115234,
0.9049999713897705,
0.7378441095352173
],
"minimum_m": [
-0.5814999938011169,
-0.45249998569488525,
-0.003844098187983036
],
"method": "44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; no track contact dynamics"
}
@@ -0,0 +1,4 @@
<!doctype html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Worker video</title></head>
<body><video id="worker-video" autoplay muted playsinline></video><audio id="worker-audio" muted></audio>
<script type="module" src="/src/components/simulation/streamFrame.ts"></script></body></html>
@@ -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 />;
}
@@ -0,0 +1,23 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import ts from 'typescript';
import { Mat4, Vec3 } from 'playcanvas';
const source=readFileSync(new URL('../src/core/simulation/aiEditorCoordinates.ts',import.meta.url),'utf8');
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {toEditor,toMission}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
test('editor glTF surface and Isaac mission coordinates roundtrip without reflection',()=>{
const p=[-134.744,38.807,1.527];
assert.deepEqual(toMission(toEditor(p)),p);
assert.deepEqual(toEditor([0,0,1]),[0,1,-0]);
const a=new Vec3(...toEditor([1,0,0])), b=new Vec3(...toEditor([0,1,0]));
assert.ok(new Vec3().cross(a,b).equals(new Vec3(...toEditor([0,0,1]))));
});
test('Riverside raw Gaussian rotation agrees with paired glTF collider',()=>{
const raw=new Vec3(-134.744,1.527,-38.807);
const native=new Mat4().setFromEulerAngles(90,0,0).transformPoint(raw);
const editor=new Mat4().setFromEulerAngles(-90,0,0).transformPoint(native);
assert.ok(editor.distance(raw)<1e-5);
const expected=toMission([raw.x,raw.y,raw.z]);
assert.ok(Math.hypot(native.x-expected[0],native.y-expected[1],native.z-expected[2])<1e-5);
});
@@ -0,0 +1,84 @@
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {test} from 'node:test';
import ts from 'typescript';
import {PerspectiveCamera,Vector3} from 'three';
async function source(name){
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText.replace('from "three"',`from "${import.meta.resolve('three')}"`);
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
}
const {panCamera,orbitCamera,navigationDepth}=await source('editorNavigation');
const {editWaypoints,waypointEditing,waypointShortcut}=await source('waypointEditing');
const {streamRecovery}=await source('streamRecovery');
const {panSensitivity,normalizePlannerPreferences}=await source('plannerPreferences');
test('pan follows the same pixel displacement at 2, 20 and 500 metre distances',()=>{
for(const distance of [2,20,500]){
const camera=new PerspectiveCamera(60,1.5,.05,3000);camera.position.set(0,0,distance);camera.updateMatrixWorld();
const anchor=new Vector3();const depth=navigationDepth(camera,anchor);
panCamera(camera,depth,120,-80,720);
const pixel=anchor.project(camera);
assert.ok(Math.abs(pixel.x*1080/2-120)<1e-8);
assert.ok(Math.abs(-pixel.y*720/2+80)<1e-8);
}
});
test('off-centre orbit pivot stays under cursor without jump, roll or radius drift',()=>{
const camera=new PerspectiveCamera(60,1.5,.05,3000);camera.position.set(0,5,10);camera.lookAt(0,0,0);camera.updateMatrixWorld();
const anchor=new Vector3(2,0,1),screen=anchor.clone().project(camera),radius=camera.position.distanceTo(anchor);
for(let i=0;i<20;i++){
orbitCamera(camera,anchor,8,3,720);
assert.ok(anchor.clone().project(camera).distanceTo(screen)<1e-10);
assert.ok(Math.abs(camera.position.distanceTo(anchor)-radius)<1e-10);
assert.ok(Math.abs(new Vector3(1,0,0).applyQuaternion(camera.quaternion).y)<1e-10);
}
});
const points=[{id:'a',position:[0,0,0]},{id:'b',position:[2,0,0]}];
test('selection never alters route; delete/undo restores order, coordinates and selection',()=>{
let s=waypointEditing(points);s=editWaypoints(s,{type:'select',id:'a'});s=editWaypoints(s,{type:'select',id:null});
assert.equal(s.history.length,0);assert.equal(s.sequence,0);
s=editWaypoints(s,{type:'select',id:'a'});s=editWaypoints(s,{type:'delete'});
assert.deepEqual(s.points,[points[1]]);assert.equal(s.selected,null);
s=editWaypoints(s,{type:'undo'});assert.deepEqual(s.points,points);assert.equal(s.selected,'a');assert.equal(s.sequence,2);
});
test('drag creates one undo entry, click none, canceled drag restores coordinates',()=>{
let s=editWaypoints(waypointEditing(points),{type:'select',id:'b'});
s=editWaypoints(s,{type:'begin'});s=editWaypoints(s,{type:'commit'});assert.equal(s.history.length,0);
s=editWaypoints(s,{type:'begin'});
for(let i=0;i<20;i++)s=editWaypoints(s,{type:'move',points:[points[0],{id:'b',position:[3+i,0,0]}]});
s=editWaypoints(s,{type:'commit'});assert.equal(s.history.length,1);
s=editWaypoints(s,{type:'undo'});assert.deepEqual(s.points,points);
s=editWaypoints(s,{type:'begin'});s=editWaypoints(s,{type:'move',points:[]});s=editWaypoints(s,{type:'cancel'});assert.deepEqual(s.points,points);
});
test('new task isolates history and shortcuts preserve native text editing',()=>{
let s=waypointEditing(points);s=editWaypoints(s,{type:'replace',points:[]});s=editWaypoints(s,{type:'load',points});
assert.equal(s.history.length,0);
const e={key:'z',code:'KeyZ',ctrlKey:false,metaKey:false,shiftKey:false,altKey:false};
assert.equal(waypointShortcut({...e,ctrlKey:true},false),'undo');assert.equal(waypointShortcut({...e,metaKey:true},false),'undo');
assert.equal(waypointShortcut({...e,metaKey:true},true),null);
assert.equal(waypointShortcut({...e,key:'Delete',code:'Delete'},false),'delete');
assert.equal(waypointShortcut({...e,key:'Backspace',code:'Backspace'},false),'delete');
assert.equal(waypointShortcut({...e,key:'Delete',code:'Delete',ctrlKey:true},false),null);
});
test('navigation preferences migrate, maintain ordered distances and interpolate smoothly',()=>{
const p=normalizePlannerPreferences({waypoint:{height:50},navigation:{nearDistance:3,farDistance:100,nearPan:.5,farPan:2}});
assert.equal(p.waypoint.height,50);assert.equal(p.navigation.zoom,1);
assert.equal(panSensitivity(1,p.navigation),.5);assert.equal(panSensitivity(200,p.navigation),2);
assert.equal(panSensitivity(51.5,p.navigation),1.25);
const bad=normalizePlannerPreferences({navigation:{nearDistance:50,farDistance:2,zoom:NaN}});
assert.equal(bad.navigation.farDistance,51);assert.equal(bad.navigation.zoom,1);
assert.deepEqual(normalizePlannerPreferences(JSON.parse(JSON.stringify(p))),p);
});
test('video watchdog bounds first-frame wait, stall recovery and retry count',()=>{
assert.equal(streamRecovery(19999,0,null,null,0),'wait');assert.equal(streamRecovery(20000,0,null,null,0),'retry');
assert.equal(streamRecovery(20000,0,null,null,2),'failed');assert.equal(streamRecovery(20000,0,15000,null,0),'wait');
assert.equal(streamRecovery(25000,0,15000,null,1),'retry');assert.equal(streamRecovery(5000,0,null,3000,2),'failed');
});
const {viewedAiRun}=await source('viewedAiRun');
test('catalog discovery of a run cannot claim an idle or historical viewer',()=>{
const old={run_id:'old',world:{world_id:'forest'}},live={run_id:'new',world:{world_id:'forest'}};
const catalog={runtime:{active_run:live},runs:[old,live]};
assert.equal(viewedAiRun(catalog,'forest',null),undefined);
assert.equal(viewedAiRun(catalog,'forest','old'),old);
assert.equal(viewedAiRun(catalog,'forest','new'),live);
assert.equal(viewedAiRun(catalog,'bamboo','new'),undefined);
});
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import ts from 'typescript';
const code=ts.transpileModule(readFileSync(new URL('../src/core/simulation/planDraft.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {planMatchesDraft}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const points=[{id:'start',position:[0,0,0]},{id:'finish',position:[3,1,0]}];
const plan={editor_cache_key:'scene-v1',robot_sha256:'rover-v1',points};
test('editor launch reuses only the exact ordered saved route, including elevation',()=>{
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',structuredClone(points)),true);
const moved=structuredClone(points);moved[1].position[2]=.2;
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',moved),false);
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',[...points].reverse()),false);
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',points.slice(1)),false);
});
test('changed scene or rover requires a fresh task even when coordinates match',()=>{
assert.equal(planMatchesDraft(plan,'scene-v2','rover-v1',points),false);
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v2',points),false);
assert.equal(planMatchesDraft(undefined,'scene-v1','rover-v1',points),false);
});
@@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import ts from 'typescript';
async function source(name) {
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
}
const {normalizePlannerPreferences,DEFAULT_PLANNER_PREFERENCES,axisWorldLength}=await source('plannerPreferences');
const {zoomDisplacement}=await source('editorZoom');
test('preferences survive round trip, validate old/corrupt storage and clamp physical dimensions',()=>{
const value={...DEFAULT_PLANNER_PREFERENCES,waypoint:{...DEFAULT_PLANNER_PREFERENCES.waypoint,diameter:.8,height:3,color:'#00aaff',opacity:.5,frequency:0}};
assert.deepEqual(normalizePlannerPreferences(JSON.parse(JSON.stringify(value))),value);
assert.deepEqual(normalizePlannerPreferences(null),DEFAULT_PLANNER_PREFERENCES);
const invalid=normalizePlannerPreferences({pivot:{x:'url(x)',opacity:99},waypoint:{height:-9,diameter:NaN}});
assert.equal(invalid.pivot.x,DEFAULT_PLANNER_PREFERENCES.pivot.x);
assert.equal(invalid.pivot.opacity,1);assert.equal(invalid.waypoint.height,.2);assert.equal(invalid.waypoint.diameter,.35);
});
test('perspective projection preserves gizmo pixels at different depths and viewport heights',()=>{
for(const depth of [1,10,500])for(const height of [500,900,1600]) {
const projected=axisWorldLength(depth,height,105)/(2*depth*Math.tan(Math.PI/6))*height;
assert.ok(Math.abs(projected-105)<1e-8);
}
});
test('far zoom takes proportional steps and equal reverse wheel deltas return to original distance',()=>{
for(const depth of [2,20,200,2000]) {
const next=depth-zoomDisplacement(depth,80);
assert.ok(next>depth);
const restored=next-zoomDisplacement(next,-80);
assert.ok(Math.abs(restored-depth)<1e-8);
assert.ok(zoomDisplacement(depth,-80)>depth*.1);
}
});
const {waypointHit}=await source('waypointHit');
test('waypoint picks complete sides, caps and a camera inside the beam at any physical size',()=>{
for(const radius of [.025,.5,1.5])for(const height of [.2,5,50]) {
assert.notEqual(waypointHit([radius*.9,height*.9,5],[0,0,-1],[0,0,0],radius,height),null);
assert.notEqual(waypointHit([radius*.9,height+1,0],[0,-1,0],[0,0,0],radius,height),null);
assert.notEqual(waypointHit([0,height/2,0],[0,0,1],[0,0,0],radius,height),null);
assert.equal(waypointHit([radius*1.1,height/2,5],[0,0,-1],[0,0,0],radius,height),null);
}
});
test('world-size centroid preference migrates to independent pixel size; emission is bounded',()=>{
const prefs=normalizePlannerPreferences({navigation:{centroidDiameter:5},waypoint:{emission:20,emissionColor:'invalid'}});
assert.equal(prefs.navigation.centroidPixels,14);
assert.equal(prefs.waypoint.emission,5);
for(const depth of [1,30,300]) {
const pixels=axisWorldLength(depth,720,prefs.navigation.centroidPixels)/(2*depth*Math.tan(Math.PI/6))*720;
assert.ok(Math.abs(pixels-14)<1e-8);
}
});
@@ -0,0 +1,24 @@
import assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import ts from "typescript";
const code=ts.transpileModule(readFileSync(new URL("../src/core/simulation/roverSettings.ts",import.meta.url),"utf8"),
{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {defaultRoverSettings,validRoverSettings,parseRoverSettings,roverSettingsKey}=
await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
const robot={robot_id:"dcd006",sha256:"a".repeat(64),physics:{mass_kg:100,height_m:.734},control:{max_side_speed_mps:.3}};
test("speed and payload persist per robot revision, with finite physical bounds",()=>{
const initial=defaultRoverSettings(robot,.15);
const loaded={...initial,max_speed_mps:.2,payload_mass_kg:30,payload_height_m:.9};
assert.equal(initial.base_mass_kg,100);
assert.equal(initial.payload_height_m,.83);
assert.equal(validRoverSettings(loaded,robot),true);
assert.deepEqual(parseRoverSettings(JSON.stringify(loaded),robot),loaded);
assert.notEqual(roverSettingsKey(robot),roverSettingsKey({...robot,sha256:"b".repeat(64)}));
for(const patch of [{max_speed_mps:.4},{max_speed_mps:NaN},{base_mass_kg:0},{payload_mass_kg:-1},
{payload_height_m:Infinity},{max_speed_mps:"0.2"}]) {
assert.equal(validRoverSettings({...loaded,...patch},robot),false);
assert.equal(parseRoverSettings(JSON.stringify({...loaded,...patch}),robot),undefined);
}
assert.equal(parseRoverSettings(JSON.stringify({...loaded,unknown:1}),robot),undefined);
});
@@ -0,0 +1,56 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import ts from 'typescript';
async function source(name) {
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
}
const {dragWaypoint}=await source('waypointDrag'),{beltPose}=await source('roverMotion');
const motion=JSON.parse(readFileSync(new URL('../public/rover-scene/dcd006-v020-motion.json',import.meta.url)));
const near=(a,b)=>assert.ok(Math.abs(a-b)<1e-7,`${a} != ${b}`);
test('axis pivot only moves the selected coordinate, including elevation',()=>{
const p=[3,4,5],o=[8,12,16];
for(const [axis,index] of [['x',0],['y',1],['z',2]]) {
const target=[...p];target[index]+=2;
const result=dragWaypoint(o,target.map((v,i)=>v-o[i]),p,axis);
result.forEach((v,i)=>near(v,target[i]));
dragWaypoint(o,p.map((v,i)=>v-o[i]),p,axis).forEach((v,i)=>near(v,p[i]));
}
assert.equal(dragWaypoint([0,0,0],[1,0,0],p,'x'),null);
});
test('belt loops without a seam and reverse travel returns to the same position',()=>{
for(const side of ['L','R'])for(let i=0;i<44;i++) {
const a=beltPose(motion,-.8,side,i), b=beltPose(motion,motion.length_m-.8,side,i);
a.position.forEach((v,j)=>near(v,b.position[j]));near(Math.sin(a.angle),Math.sin(b.angle));
}
});
test('belt travels backward at ground contact, forward on the upper run, both sides aligned',()=>{
for(const [,start,length,d] of motion.segments.filter(s=>s[0]==='line')) {
const s=start+length/2-motion.phase_m;
const a=beltPose(motion,s,'L',0), b=beltPose(motion,s+.0001,'L',0);
near((b.position[0]-a.position[0])/.0001,d[2]);
near((b.position[1]-a.position[1])/.0001,d[3]);
const right=beltPose(motion,s,'R',0);near(a.position[0],right.position[0]);near(a.position[1],right.position[1]);
near(right.position[2]-a.position[2],motion.track_width_m);
}
});
test('local animated rig follows motion and freezes at zero input', async()=>{
const {Entity}=await import('playcanvas');
const mathCode=ts.transpileModule(readFileSync(new URL('../src/core/simulation/roverMotion.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const mathUrl=`data:text/javascript;base64,${Buffer.from(mathCode).toString('base64')}`;
let code=ts.transpileModule(readFileSync(new URL('../src/components/simulation/RoverTrackMotion.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
code=code.replace('"../../core/simulation/roverMotion"',JSON.stringify(mathUrl));
const {RoverTrackMotion}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const root=new Entity();
for(const side of ['L','R'])for(let i=0;i<44;i++)root.addChild(new Entity(`${side}_BELT_${String(i).padStart(2,'0')}`));
for(const w of motion.wheels)root.addChild(new Entity(w.node));
const rig=new RoverTrackMotion(root,motion);rig.update(.1,.3,0);
const expected=beltPose(motion,.03,'L',0), node=root.findByName('L_BELT_00');
const p=node.getLocalPosition();[p.x,p.y,p.z].forEach((v,i)=>near(v,expected.position[i]));
const before=node.getLocalRotation().clone();rig.update(.1,0,0);assert.ok(node.getLocalRotation().equals(before));
rig.update(.1,-.3,0);const atOrigin=beltPose(motion,0,'L',0), reset=node.getLocalPosition();
[reset.x,reset.y,reset.z].forEach((v,i)=>near(v,atOrigin.position[i]));
root.destroy();
});
@@ -0,0 +1,43 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import ts from 'typescript';
const source=ts.transpileModule(readFileSync(new URL('../src/core/simulation/runConfiguration.ts',import.meta.url),'utf8'),
{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {parseSavedSelection,currentSelection,runDurationSeconds,selectionStorageKey}=
await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
const selection={schema_version:'missioncore.observatory-ai-composition/v1',selections:[
{group:'segmentation',module_id:'outdoor-provider',module_sha256:'a'.repeat(64),parameters:{}},
{group:'policy',module_id:'mission',module_sha256:'b'.repeat(64),parameters:{environment:'park'}},
]};
const installed={selection:{...selection,selections:[]},catalog:{groups:[
{group:'segmentation',modules:[{moduleId:'outdoor-provider',moduleSha256:'c'.repeat(64),defaults:{}}]},
{group:'policy',modules:[{moduleId:'mission',moduleSha256:'d'.repeat(64),defaults:{environment:'natural'}}]},
]}};
test('stored per-location intent survives JSON; malformed, duplicate or foreign groups are rejected',()=>{
assert.deepEqual(parseSavedSelection(JSON.stringify(selection)),selection);
for(const value of [null,'broken',JSON.stringify({...selection,selections:[...selection.selections,selection.selections[0]]}),
JSON.stringify({...selection,selections:[{...selection.selections[0],group:'source'}]}),
JSON.stringify({...selection,selections:[{...selection.selections[0],parameters:[]} ]})]) {
assert.equal(parseSavedSelection(value),undefined);
}
assert.notEqual(selectionStorageKey('riverside','tracked'),selectionStorageKey('forest','tracked'));
assert.notEqual(selectionStorageKey('riverside','tracked'),selectionStorageKey('riverside','wheeled'));
});
test('alternative provider is rebound from full registry and park permissions survive an update',()=>{
const fresh=currentSelection(selection,installed);
assert.equal(fresh.selections[0].module_sha256,'c'.repeat(64));
assert.equal(fresh.selections[1].parameters.environment,'park');
assert.equal(selection.selections[0].module_sha256,'a'.repeat(64));
assert.throws(()=>currentSelection(selection,{...installed,catalog:{groups:[]}}),/недоступен/);
});
test('310 m at 0.15 m/s is not cut off by the old 30-minute ceiling; budgets stay bounded',()=>{
assert.ok(runDurationSeconds(310.34,.15)>310.34/.15+120);
assert.ok(runDurationSeconds(310.34,.15)>1800);
assert.equal(runDurationSeconds(3.4,.15),1800);
assert.equal(runDurationSeconds(100000,.01),7200);
for(const speed of [0,-1,NaN,Infinity])assert.equal(runDurationSeconds(310,speed),1800);
for(const length of [undefined,NaN,-1,Infinity])assert.equal(runDurationSeconds(length,.15),1800);
});
@@ -20,18 +20,20 @@ test("simulation is a dedicated Polygon workspace with a bounded feature slice",
assert.match(productModel, /id: "simulations"[\s\S]*root: "polygon"[\s\S]*kind: "simulations"/);
assert.match(workspaceHub, /case "simulations":[\s\S]*<SimulationWorkspace \/>/);
assert.match(catalog, /simulation-catalog__table/);
assert.match(workspace, /archivesFromDrop/);
assert.match(workspace, /uploadSimulationProjectSource/);
assert.match(catalog, /colSpan=\{3\}/);
assert.match(catalog, /Ожидает обработки/);
assert.match(catalog, /Прогресс \$\{roundedPercent\}% \|/);
assert.match(catalog, /Осталось примерно \$\{minutes\} мин/);
assert.match(catalog, /simulation-catalog__progress-track/);
assert.doesNotMatch(catalog, /disabled=\{ACTIVE_STATUSES\.has/);
assert.match(workspace, /<SimulationViewport[\s\S]*project=\{selected\}/);
assert.match(workspace, /<ConfirmationModal/);
assert.match(workspace, /if \(state === "building_streamed_sog"\) return "Сборка LOD"/);
assert.doesNotMatch(workspace, /\{selected\.provider\.state \?\? selected\.status\}/);
assert.match(workspace, /<AiPolygonWorkspace \/>/);
assert.doesNotMatch(workspace, /simulation-profile|LccGaussianWorkspace/);
assert.match(styles, /styles\/simulation\.css/);
});
@@ -69,12 +71,12 @@ test("browser upload remains same-origin, resumable and token-free", async () =>
test("failed simulation can restart from its retained Mission Core source", async () => {
const [core, workspace] = await Promise.all([
read("core/simulation/projects.ts"),
read("workspaces/simulation/SimulationWorkspace.tsx"),
read("components/simulation/SimulationSourceImport.tsx"),
]);
assert.match(core, /retrySimulationProject/);
assert.match(core, /\$\{API_ROOT\}\/\$\{encodeURIComponent\(projectId\)\}\/build/);
assert.match(workspace, /Повторить сборку/);
assert.match(workspace, /Повторить подготовку/);
});
test("PlayCanvas owns the realtime scene graph without an iframe or React entity tree", async () => {
@@ -97,7 +99,7 @@ test("PlayCanvas owns the realtime scene graph without an iframe or React entity
assert.match(runtime, /camera\.script\?\.create\(CameraControls/);
assert.match(runtime, /const HOME_POSITION = new Vec3\(0, 1, 0\)/);
assert.match(runtime, /const HOME_FOCUS = new Vec3\(1, 1, 0\)/);
assert.match(runtime, /maximum: \{[^}]*lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60/);
assert.match(await read("core/simulation/gaussianQuality.ts"), /maximum: \{[^}]*lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60/);
assert.match(runtime, /app\.scene\.gsplat\.splatBudget = profile\.splatBudget/);
assert.match(runtime, /app\.autoRender = false/);
assert.match(runtime, /app\.systems\.gsplat\?\.on\("frame:request", this\.requestGsplatFrame\)/);
+1
View File
@@ -95,6 +95,7 @@ export default defineConfig(({ mode }) => {
rollupOptions: {
input: {
app: fileURLToPath(new URL("./index.html", import.meta.url)),
simulationStream: fileURLToPath(new URL("./simulation-stream.html", import.meta.url)),
rerun: fileURLToPath(new URL("./rerun-runtime.html", import.meta.url)),
},
},
+50 -3
View File
@@ -1,8 +1,54 @@
# Mission Core Polygon: product definition and system requirements
Status: canonical working SRS, 2026-07-25.
> Актуальная композиция от 02.10.2026: единый каталог, режим и ровер; ручной заезд локально, AI на Worker. См. [SIMULATION_WORKFLOW.md](SIMULATION_WORKFLOW.md). Описание прежнего разделения профилей ниже — история решений.
Ops source of truth:
> Уточнение владельца 02.10.2026: интерактивное планирование маршрута теперь
> локальное, с дисковым кэшем Gaussian-preview и collider. Физика, сенсоры,
> inference и рендер выполняемого прогона остаются на Worker. Это заменяет
> прежнее требование удалённого редактора; см. `AI_POLYGON_ROUTE_PLANNING.md`.
Status: general qualification principles with a historical 2026-07-25
Gazebo/PX4 implementation snapshot. Current-profile reconciliation: 2026-10-02.
## Current applicability — 2026-10-02
The active owner-directed development is **AI-полигон**: native Isaac 6.1 on
Worker006, Gaussian appearance with separately checked collision geometry,
a selected DCD-006 v020 visual model (1.163×0.905×0.734 m) with a provisional
four-wheel differential contact proxy, and the shared AI composition. Worker owns
physics, sensor rendering, inference, control and raw journals; the operator
Mac receives video/compact telemetry and sends lifecycle commands. Physical
VESC/ASVD work and the LCC Gaussian Mirror profile remain separate.
The current working purpose, evidence boundary, experiment protocol and next
gates are in [AI Polygon workflow](AI_POLYGON_WORKFLOW.md), with read-only live
verification in [the 2 October audit](audits/2026-10-02-simulation-state-review.md).
[MISSIONCOR-83](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-83) owns current
implementation/evaluation; MISSIONCOR-39 retains general architecture ownership.
The selected robot ID/profile hash is immutable per run. The native Worker
verifies the shared PlayCanvas GLB and converts it to metre-scale Z-up USD;
this does not constitute calibrated track mechanics or animated track links.
New normally closed runs seal a Worker-local report and artifact SHA index;
Core stores the compact report, and the operator reads it in the simulation
workspace. Missing collision measurements remain null. Goal completion and
duration expiry are distinct report outcomes.
Sections below preserve the July profile's architecture, evidence and proposed
S0–S6 sequence. Gazebo/PX4/Ackermann, Linux-only placement, Nav2 and Unreal
selection are **not prerequisites or current implementation claims** for the
September Isaac profile. That profile uses its own `/api/v1/ai-polygon` contracts;
integration into the earlier generic provider/qualification-report contracts
has not been established. Historical gates cannot be inherited across profiles.
Source identity, declared clocks/frames, virtual-only authority, preserved
failures and evidence-bound comparisons remain applicable. The next useful
AI-profile gate is repeatable, reported navigation on a bounded scenario set.
Two recorded completions of the same approximately 11 m paved task do not
establish off-road autonomy. Proposed workflow gates are not completed features.
Historical July profile's Ops records:
- [MISSIONCOR-38](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-38) is the
product epic and original simulation-branch scope.
@@ -13,7 +59,8 @@ Ops source of truth:
- [MISSIONCOR-41](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-41) is the
active S1 lifecycle/authority implementation and qualification gate.
This document, ADR 0015, ADR 0016 and ADR 0017 are the repository truth. A material change
This document's applicability section, the linked AI workflow, ADR 0015,
ADR 0016 and ADR 0017 define the scoped repository truth. A material change
to run kinds, authority, clocks, frames, source-of-record, provider boundaries,
component placement or phase gates must update the ADR/SRS and MISSIONCOR-39
together.
+14
View File
@@ -1,8 +1,22 @@
# Simulation Worlds — product-surface brief
> Актуальная композиция от 02.10.2026: единый каталог, режим и ровер; ручной заезд локально, AI на Worker. См. [SIMULATION_WORKFLOW.md](SIMULATION_WORKFLOW.md). Описание прежнего разделения профилей ниже — история решений.
> Уточнение владельца 02.10.2026: интерактивное планирование маршрута теперь
> локальное, с дисковым кэшем Gaussian-preview и collider. Физика, сенсоры,
> inference и рендер выполняемого прогона остаются на Worker. Это заменяет
> прежнее требование удалённого редактора; см. `AI_POLYGON_ROUTE_PLANNING.md`.
Status: accepted for the first working vertical slice on 2026-08-26; visual/physical stage boundary
revised on 2026-08-27.
Scope clarification, 2026-10-02: this brief describes the **LCC Gaussian Mirror**
ingestion/viewing profile. Its browser PlayCanvas runtime is not the active
AI Polygon execution architecture. The latter renders and computes on Worker006
and delivers video to the operator; see [AI Polygon workflow](AI_POLYGON_WORKFLOW.md).
Visual readiness here does not qualify terrain or autonomous navigation there.
## Job story
When an operator has a computed XGRIDS export, they need to create a named simulation project from
+70
View File
@@ -0,0 +1,70 @@
# AI-полигон: локальное планирование и задание на Worker
Решение владельца от 02.10.2026: интерактивное планирование выполняется на
операторском компьютере. Удалённый редактор оказался непригоден по задержке
управления, несмотря на достаточную частоту видеопотока. Предыдущая реализация
и её измерения остаются историей в дневном аудите; они не доказывают удобство
редактирования.
## Граница выполнения
- Mission Core хранит на диске локальную копию Gaussian-сцены для редактора и
точную collision-поверхность. В режиме планирования PlayCanvas отображает сцену.
Здесь нет физического шага, inference, симуляции сенсоров или управления VESC.
- Worker переиспользует проверенный исходный SOG либо один раз конвертирует
PLY штатным SplatTransform 3.4.0. Для Forest сохранён исходный архив, повторное
квантование не выполняется.
Количество гауссов и SH-полосы сохраняются: decimation и filter-harmonics
не применяются. Квантование атрибутов SOG не является lossless. Передача идёт
по существующему аутентифицированному каналу Worker → Core. Нет нового сервера,
публичного порта или файлового обмена на каждый поворот камеры.
- Поворот, полёт, zoom, высотный срез, установка и перенос точек выполняются
локально. Picking использует точный collider и BVH, собираемый в Web Worker.
- Сохранение задания передаёт только точки и идентичности. План неизменяем;
редактирование создаёт следующую ревизию. Первая точка задаёт старт, направление
второй — начальный курс, последняя — финиш. Допускается 2–33 точки.
- При запуске локальный редактор уничтожается. Worker получает задание, проверяет
collider, размещение ровера и запускает прежние Isaac/AI-композицию/сенсоры.
Mac декодирует видео и рисует телеметрию и маршрут поверх него.
- Маршрутная разметка не входит в изображение камеры AI. Собственные LCC-проекты
теперь входят в общую библиотеку; [актуальная развилка режимов](SIMULATION_WORKFLOW.md)
включает отдельное локальное ручное управление.
## Управление
ЛКМ — orbit, ПКМ — свободный взгляд, Shift + ЛКМ / средняя кнопка — сдвиг.
Колесо — zoom, WASD / стрелки — полёт, Q/E — вниз/вверх, Shift — быстрее.
Камера не привязана к земле. Кнопка возврата восстанавливает обзор старта.
«Добавить waypoint» ставит точку под центром вида. Режим «Точка по клику»
добавляет её под курсором. Выбранную точку можно перетащить по поверхности или
горизонтальным осям X/Z; высота получается пересечением с collider, а не ручным
вводом. Удаление и отмена локальны. Наличие поверхности не доказывает проходимость.
Справа переиспользован канонический вертикальный `RangeControl` из просмотра
облаков. Диапазон — высоты поверхности. Верхняя отметка выключает срез, включая
Gaussian-выбросы. Срез влияет только на обзор и picking редактора.
## Кэш и воспроизводимость
Путь: `<data_dir>/ai-polygon/editor-cache/<key>/`. Ключ содержит версию формата,
world/source/collider identity и настройки калибровки. Текущая версия кэша — 2;
версия 1 с уменьшением плотности не используется новым редактором. `manifest.json` фиксирует
SHA-256 и размеры preview/collider. Промежуточные `.part` не выдаются браузеру;
после проверки полноты и SHA-256 файлы атомарно публикуются. Передача продолжается
с принятого смещения, есть ограничение объёма и свободного места. Повторное
открытие готовой копии не требует доступного Worker.
SOG-кэш используется редактором и локальным ручным режимом. Worker использует
исходные гауссы или LOD0 области задания из готового SOG. Метрическая поверхность не упрощается. Координаты задания — Isaac Z-up,
локального вида — glTF Y-up; преобразование `[x,y,z] → [x,z,-y]` сохраняет
ориентацию. План хранит отдельный хеш поверхности редактора, проверяемый Worker
перед запуском физики.
Старые удалённые planning API оставлены для совместимости; продуктовая кнопка
использует локальный редактор и не создаёт simulation run. Первичная подготовка
на Worker использует существующий арбитраж GPU под владельцем `aicache-<key>`;
он освобождается после закрытия процесса подготовки. Уже готовый локальный кэш
не требует Worker или GPU lease.
Проверка реализации: [локальный редактор и SOG, 02.10](audits/2026-10-02-local-route-editor.md).
+222
View File
@@ -0,0 +1,222 @@
# AI-полигон: цель, рабочая схема и план
> Актуальная единая библиотека и развилка ручного/AI-режима описаны в
> [SIMULATION_WORKFLOW.md](SIMULATION_WORKFLOW.md).
> Уточнение владельца 02.10.2026: интерактивное планирование маршрута теперь
> локальное, с дисковым SOG-кэшем полной плотности и collider. Физика, сенсоры,
> inference и рендер выполняемого прогона остаются на Worker. Это заменяет
> прежнее требование удалённого редактора; см. `AI_POLYGON_ROUTE_PLANNING.md`.
Актуализировано 03.10.2026. Камеры, слои inference и профили движения:
[проверка 03.10](audits/2026-10-03-observer-cameras-and-inference.md).
Продолжение: [сравнение поверхностей и задержек](audits/2026-10-03-surface-sequence-and-latency.md).
GOOSE на исходном длинном задании прошёл 92 м вместо 6,2 м у ADE, затем
остановился из-за запаздывающих решений. Полное прохождение остаётся открытым.
Это рабочая точка входа для текущего AI-полигона.
Проверенные факты отделены от предложенного следующего этапа. Источники:
[сверка состояния](audits/2026-10-02-simulation-state-review.md),
[R34](audits/2026-09-23-ai-polygon-continuous-motion.md),
[runbook Worker](runbooks/AI_POLYGON_WORKER_006.md),
[MISSIONCOR-83](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-83).
Общая архитектурная карточка —
[MISSIONCOR-39](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-39).
## Зачем он нужен
Цель — проверять, выполняет ли выбранная композиция восприятия, планирования
и управления задачу движения в заданных условиях. Каждое изменение должно
отвечать на конкретный вопрос: лучше ли ровер держит маршрут, отличает проезд
от препятствия, останавливается при опасности и продолжает движение, когда
причина остановки исчезла. Результат — сохранённый эксперимент с вердиктом,
метриками и объяснением отказов.
Сейчас мы собираем и испытываем готовые модели и алгоритмы. Заезд сам по себе
не обучает нейросеть. Польза — раннее обнаружение ошибок, сравнение композиций
на одинаковых заданиях и накопление регрессий до появления подходящего
бортового вычислителя. Производительность RTX 4090 не определяет будущую
производительность бортового устройства.
## Какие контуры различаем
| Контур | Назначение и статус |
| --- | --- |
| AI-полигон | Действующая разработка: Worker006, Isaac, Gaussian, физика и общая AI-композиция; выбираемый DCD-006 v020 с исходной CAD-моделью 1,163×0,905×0,734 м и временной физической моделью контакта |
| Собственные LCC-сканы | В общей библиотеке: локальные ручное управление и планирование; подготовленное задание исполняется на Worker. Визуальная готовность не доказывает навигацию |
| AI Inference / recorded replay | Проверка моделей на записанных данных; новые команды не меняют записанное будущее, поэтому это не доказательство замкнутого движения |
| Июльский Gazebo/PX4 Polygon | Историческая линия со своей ограниченной приёмкой; её S0/S1 и планы Nav2/Unreal не являются текущим состоянием Isaac |
| Физическое управление VESC/ASVD | Отдельная работа; в AI-полигоне нет доступа к приводам настоящих аппаратов |
Для выполняемого AI-прогона все тяжёлые вычисления остаются на Worker. Локальное
планирование — отдельный режим с SOG-кэшем. Ограничение Worker
не переопределяет устройство отдельного исторического LCC-viewer.
## Где что работает
```mermaid
flowchart LR
O["Mission Core на Mac: задание и управление"] -->|"Start / Pause / Stop"| W
subgraph W["Worker 006"]
P["Isaac: мир и физика"] --> S["RGB, виртуальный LiDAR, поза"]
S --> A["Общая композиция AI"]
A --> C["Проверка команды и привод 60 Гц"]
C --> P
P --> J["Локальные журналы"]
A --> J
end
W -->|"Готовое видео и компактная телеметрия"| O
```
Выбираемая композиция: DDRNet GOOSE или SegFormer B2 оценивает поверхности, RF-DETR ищет
объекты, WaypointMission ведёт задание по точкам, CMU выбирает локальный путь
и скорость/поворот. Модули подключены через общий
`ModuleRegistry/ModuleSpec/CompositionSpec`; DDRNet и прежние профили сохранены.
Новая модель должна подключаться туда же и сравниваться с зафиксированной
базовой композицией.
Выбор сохраняется отдельно для локации и ровера. Для проверяемой Riverside
выбран GOOSE; это не глобальная замена остальных профилей. При старте состав
сверяется со всеми установленными модулями, а снимок задания определяет скорость
и длительность: запас `1,5 × длина / скорость + 120 с`, в пределах 30–120 минут.
Время — ограничение эксперимента, а не обещание достижения цели.
Маршрут задаёт цель. Положение машины меняет физика по командам контроллера;
машина не перемещается по заранее записанной анимации. Последнее свежее решение
исполняется между кадрами; физика/привод 60 Гц не обязаны ждать каждого inference.
При превышении возраста кадра 800 мс или команды 500 мс движение прекращается.
AI около 4–5 решений/с и операторское видео порядка 15–28 FPS в дневных
проверках 02.10 — разные измерения; это наблюдения, не гарантированная частота.
Gaussian задаёт внешний вид, collision mesh — опору и препятствия. Навигация
получает наблюдаемые лучи, а не полный меш. **Однако поза сейчас берётся прямо
из симулятора:** локализация, SLAM, дрейф одометрии и соответствие виртуального
LiDAR будущим реальным датчикам ещё не проверены. Это явно упрощённый профиль.
Navmesh датасета используется при подготовке задания, не как скрытая карта
проезда для runtime AI.
## Что сделано и что доказано
| Область | Реализовано / подтверждено | Открытая граница |
| --- | --- | --- |
| Размещение | Рендер, физика, inference и полный архив на Worker; Mac получает поток | Coordinator восстановлен; ожидание Docker добавлено. Холодный вход в Windows после выключения ещё нужно повторно проверить |
| Композиция | Реальные модели, локальный планировщик, маршрут и общий конструктор | Нет автоматической сравнительной приёмки разных композиций |
| Привод | 60 Гц, нарастание команды до 0,2 м/с², свежесть, пауза/продолжение | Пять визуально обусловленных остановок R34 остаются; реальная электромеханика не откалибрована |
| Маршрут | Два записанных завершения одного задания Riverside Path: 6 точек, исходный маршрут 11,03 м | Нет серии повторов на разных дорогах, поворотах и препятствиях |
| Рельеф | Отдельные проверки плоскости, ступеней 5/10 см и уклонов до 25° на лабораторном шасси | Это не приёмка грунтовки, подвески, сцепления, травы или настоящего ровера |
| Локации | Forest, Bamboo и Riverside присутствуют в каталоге | Forest/Bamboo не приняты для автономного прохождения; прежняя оценка Forest отозвана после обнаружения переворота |
| Журналы | Версии композиции, кадры/маски/дальности, решения, движение, исходы сохраняются | Новые прогоны автоматически получают report.json и evidence-manifest.json; оператор видит «Результаты прогонов». Сравнение серий и резервная копия ещё не реализованы |
| Люди/животные | Детектор есть в композиции | Динамические сценарии, остановка и возобновление перед ними не квалифицированы |
Утренняя операционная проверка 02.10 выявила нехватку свободного места в Core:
около 1,30 GB при резерве 2,15 GB; API отвечает, но health сообщает
`operational=false`. Перед дневными испытаниями запас места восстановлен, Core и Worker запущены.
Утренняя неисправность сохранена в датированном аудите; она не описывает
готовность после дневного обновления.
R34: 86,2 с времени мира, ошибка финиша 0,344 м при допуске миссии 0,4 м;
медиана inference 125 мс, p95 219 мс. Более поздний заезд 23.09 по тому же
заданию: 92,57 с, ошибка 0,355 м, также шесть точек. Это ограниченное
подтверждение работоспособности всей цепочки. Радиус benchmark 0,2 м,
вся локация, длинная грунтовая дорога и безопасная автономия не приняты.
## Как должен выглядеть один полезный эксперимент
Это следующий рабочий протокол; его автоматизация ещё не реализована целиком.
1. Сформулировать вопрос до запуска. Например: «Снижает ли временная устойчивость
оценки поверхности число необоснованных остановок, сохраняя реакцию на препятствие?»
2. Зафиксировать сценарий: мир и collider с хешами, масштаб/оси, старт, маршрут,
профиль ровера/сенсоров, скорость, акторы, ограничения времени, ожидаемый исход.
Сохранить runtime, composition hash, параметры и управляемые seed, где доступны.
3. Задать метрики и критерии до просмотра результата. Для свободного маршрута
ожидается достижение цели; для непроходимого участка успешный исход — остановка
перед опасностью. Отсутствующий счётчик столкновений означает «не измерено».
4. Запустить неизменённую базовую композицию, затем кандидат с одним изменением.
Минимальный первый план — по 5 повторов на каждом выбранном сценарии;
это инженерная проверка повторяемости, не статистическая гарантия надёжности.
5. Считать отчёт на Worker из журналов. Сопоставить успех задания, время, ошибку
финиша, причины/длительность остановок, вмешательства, столкновения/зазор,
скорость и ускорения, возраст наблюдений, задержки моделей, RTF и видеочастоту.
Паузы оператора учитывать отдельно. Изменение команды и измеренное ускорение
тела — разные величины; гладкая команда сама по себе не доказывает гладкую езду.
6. Принять или отклонить кандидата с причиной. Сохранить неудачи и добавить
регрессию для найденного дефекта. Итоговый вывод ограничить проверенными условиями.
`completed` в текущем API — терминальный статус исполнения. Он возникает и
при истечении длительности. Поэтому отчёт обязан отдельно фиксировать достижение
цели, ожидаемую безопасную остановку, timeout, ошибку и ручное завершение.
Нельзя считать все `completed` успешной навигацией.
Набор используемых для настройки маршрутов отделяется от контрольных маршрутов,
на которых принимается кандидат. Одно красивое прохождение и улучшение на
знакомом участке не закрывают переносимость на новую местность.
## Где фиксируем
| Место | Что там является истиной | Что ещё нужно |
| --- | --- | --- |
| Worker: `D:\NDC_MISSIONCORE\runtime\simulation\state\<run_id>` | Полные решения, sensor artifacts, физическое движение, композиция, итог | report.json и evidence-manifest.json закрываются автоматически; проверяемый экспорт/резервная копия ещё нужны |
| Core: `<data_dir>/ai-polygon/{worlds,runs}` | Каталог, снимок настроек при старте, lifecycle, последний компактный snapshot | Компактный report и хеши сохранены в run; UI показывает последние 30 прогонов каталога. Общий поиск/сравнение серий ещё нужны |
| Репозиторий | Контракты, сценарии без приватных данных, код, тесты, runbook и датированные аудиты | Генератор run_report.py и контракт SimulationReport реализованы; измерение контактов и метрики ускорений ещё нужны |
| Ops: MISSIONCOR-83 | Текущий результат, план, критерии, открытые проблемы и ссылки | После каждого эксперимента — краткий факт/решение/следующий шаг, а не только технический лог |
| Ops: MISSIONCOR-39 | Общие архитектурные границы и связь профилей | Синхронизировать при изменении размещения, authority или контрактов |
Сырые кадры и журналы не коммитятся. Уже закрытые receipts не переписываются.
Для новых закрытых прогонов индекс включает файлы и их SHA-256; отчёт
не перезаписывается. Исторические прогоны автоматически не пересчитываются.
Наличие индекса не означает проверенную резервную копию. Новый MLflow/отдельный конструктор
для этого этапа не нужен: сначала завершаем существующую модель run/report.
## Уточнение владельца: сначала видимое задание
После дневных испытаний 02.10 приоритет изменён: сначала визуальное
локальное планирование и явная сохранённая задача, затем доводка движения.
Сценарий и контракты — [планирование маршрута](AI_POLYGON_ROUTE_PLANNING.md).
Редактор, сохранённые задания и слой маршрута реализованы; приёмка —
[дневной аудит](audits/2026-10-02-route-planner-and-rover.md).
Дальнейшие изменения навигации проверяются на явно выбранной версии задания.
Дневной baseline DCD-006 не прошёл прежний маршрут: 3/6 точек, затем stuck.
Исторический успех другого профиля не переносится на новую геометрию ровера.
## План квалификации после визуального планирования
| Порядок | Работа | Проверяемый выход и польза |
| --- | --- | --- |
| 1 · реализовано, холодный вход ещё проверить | Запас места восстановлен, coordinator ожидает Docker; AI ждёт готовности моделей | Core operational, после входа в Windows Worker сам регистрируется, холодный Start/Stop повторяется, прежние модели и Docker-конфигурации сохранены |
| 2 · реализовано | Автоматический отчёт и закрытие evidence для нового нормально завершённого run | Каждый прогон имеет явный mission outcome, метрики, причины остановок, версии и проверяемые ссылки; результат понятен без SSH |
| 3 | Повторить Riverside, устранить необоснованные остановки | Предложенная первая цель: 5/5 достижений при ошибке ≤0,4 м, ≤180 с simulation time без пауз, без stale-stop в штатном движении и без необъяснённых остановок на размеченном свободном участке; все защитные сценарии сохраняются |
| 4 | Компактная серия природных ситуаций | Поворот тропы, проходимый камень, непроходимая ступень, перекрытие, отсутствие опоры/край, выход человека/животного, потеря/задержка данных; у каждого ожидаемый исход и полный учёт контактов |
| 5 | Один пригодный грунтовый мир и контрольные маршруты | Gaussian и независимая физическая геометрия согласованы по масштабу/осям; твёрдые препятствия отделены от мягкой растительности; улучшение повторяется на отложенных участках |
| 6 | Приблизить сенсоры и динамику к будущему аппарату | Добавлены заявленные шум/задержка/ошибка позы, профиль сенсоров и измеренная динамика; затем отдельные replay/shadow/аппаратные проверки |
Шаги 2–5 используют готовые Isaac/CMU/модели и текущую композицию. Новые модели
подключаются при установленной причине ошибки восприятия. Полная замена движка,
генерация множества миров и обучение новых сетей не являются обязательными
условиями первого полезного результата.
При проверке травы сначала определить физический смысл: допустимая мягкая
растительность не должна случайно становиться стеной из Gaussian mesh. Опасные
ветки/стволы/камни и неизвестная опора остаются препятствиями. Если физический
слой скана не позволяет это различить, сцена остаётся визуальной до подготовки
и проверки collision-профиля.
## Опора на готовые подходы
Раздельные частоты планирования и сглаживания команд используются, например,
в [Nav2 Velocity Smoother](https://ros-navigation.github.io/mkdocs.nav2.org/rolling/configuration_and_development/configuration_guide/core_servers/configuring_velocity_smoother/).
Отдельная проверка близких препятствий описана в
[Nav2 Collision Monitor](https://ros-navigation.github.io/mkdocs.nav2.org/rolling/configuration_and_development/configuration_guide/core_servers/collision_monitor/configuring_collision_monitor_node/).
Это ориентиры устройства контура, не утверждение, что эти пакеты установлены
в нашем CMU-профиле. [Isaac benchmarks](https://docs.isaacsim.omniverse.nvidia.com/latest/reference_material/benchmarks.html)
также разделяют RTF и показатели рендера. Конкретные критерии выше — наш
предложенный протокол следующего этапа, не внешняя сертификация.
Обновление 03.10, после сравнения поверхностей: GOOSE на исходном задании
прошёл 91,99 м, затем остановился из-за запаздывающих решений. Ускорен расчёт
соседств рельефа без изменения порогов. Два последующих заезда на отдельном
участке прошли прежнее место остановки, но не достигли допуска финиша:
ошибка 0,545 и 0,810 м при допуске 0,4 м. Исправлен конфликт разрешения заднего
хода между миссией и CMU. Этот участок и весь маршрут всё ещё не приняты.
Данные, версии и следующий проверяемый шаг — в
[аудите последовательности и задержек](audits/2026-10-03-surface-sequence-and-latency.md).
+204
View File
@@ -0,0 +1,204 @@
# Симуляции: единые локации и два режима
Решение владельца 02.10.2026 заменяет разделение UI на AI-полигон и LCC Gaussian
Mirror. Точка входа — LAB → Симуляции → доступная локация. В шапке сначала
выбирается режим, затем ровер. Исторические аудиты сохраняют факты своих версий.
| Режим | Действия | Место исполнения | Что проверяет |
| --- | --- | --- | --- |
| Ручное управление | Выбрать DCD-006 → Старт → WASD / стрелки, Space — тормоз, R — возврат | Локальные SOG, PlayCanvas и существующий Ammo-контроллер | Обзор локации, масштаб, контакт с поверхностью и ручное управление |
| Inference | Выбрать DCD-006 → Подготовить маршрут → сохранить задание → запустить симуляцию | Редактор локальный; физика, камеры, AI, рендер и журнал на Worker 006 | Выполнение неизменяемого задания выбранной композицией AI |
В ручном режиме нет кнопок маршрута и AI, подключения видеопотока, GPU-резервации
Worker или отчёта автономного испытания. Переключение режима и ровера блокируется
до закрытия текущего редактора/заезда. Потеря фокуса снимает ручные команды.
Полноэкранный режим возвращается штатной кнопкой или Escape.
## Один источник локации
Каталог объединяет PLY-локации Forest, Bamboo, Riverside и готовые проекты
Gaussian Pipeline. Старые project ID, оригиналы, артефакты и калибровки сохранены.
`ProjectWorlds` — read-through адаптер, не вторая база сканов. В проекте сохраняются
независимые визуальная и collision-калибровки. Их изменение меняет идентичность
мира и требует нового задания.
Импорт архива/папки LCC использует существующие uploader, Gaussian Pipeline и
его статусы. Импорт Gaussian PLY сохраняет существующий контракт. Готовый
streamed SOG собственных проектов читается прямо с диска Core. Повторная
реконструкция и копирование в отдельный редакторский кэш не выполняются.
Для PLY-локаций редактор и ручной режим совместно используют проверенный SOG-кэш.
Источники и условия лицензий остаются в метаданных, а не в шапке сцены.
Общий `localScene` задаёт URL визуального слоя, collision mesh и преобразования
для обоих локальных режимов. Редактор использует BVH для выбора земли, без физики.
Физический proxy ручного режима получает тот же collider и профиль DCD-006.
Штатный Draco 1.5.7 декодирует сжатую геометрию, не меняя её топологию.
## Worker и большие SOG
Worker объявляет capability `project-sog`. Старый Worker не допускает запуск
такого задания. Для существующих проектов он переиспользует артефакты локального
Gaussian Pipeline с проверкой SHA-256; при их отсутствии получает проверенные
артефакты Core по действующему закрытому каналу.
SplatTransform 3.4.0 адаптирует LOD0 области задания в формат текущего Isaac
Gaussian renderer. Область ограничена точками маршрута плюс 12 метров с каждой
стороны. Это явное пространственное ограничение, не уменьшение плотности внутри
области. Лимит — 8 миллионов гауссов; превышение останавливает подготовку.
Receipt сохраняет границы, исходный хеш, число гауссов и версию конвертера.
Collider не обрезается и не восстанавливается заново. Сжатый collider декодируется
без упрощения; исходный хеш и хеш декодированного результата фиксируются раздельно.
Координаты локального renderer — Y-up; задания и Isaac — Z-up. Переход локальный
→ задание: `[x,y,z] → [x,-z,y]`. Калибровка применяется ровно один раз. Разметка
маршрута и срез принадлежат операторскому виду и не попадают в камеру AI.
## Границы результата
В обоих режимах показан выбранный DCD-006 из канонической CAD-модели. Ручная
физика пока использует существующий raycast vehicle proxy со скрытыми колёсами,
а не полноценную модель гусеничной ленты. Масса и контакт не квалифицированы
по реальному аппарату. Ручной проезд не доказывает автономную проходимость.
Цель AI-режима, состав модулей, журналирование и ограничения квалификации описаны
в [AI workflow](AI_POLYGON_WORKFLOW.md). Docker-профили моделей остаются общими.
Статусы конкретных проверок — в [аудите объединения](audits/2026-10-02-unified-simulation.md).
## Камера, waypoint и подвижная модель · 02.10.2026
В локальном редакторе ПКМ/клик двумя пальцами с перемещением панорамирует сцену.
Прокрутка масштабирует к курсору и доступна в обоих режимах инструмента.
ЛКМ вращает камеру вокруг точки на поверхности, в которой начато нажатие;
WASD/стрелки перемещают камеру, Q/E меняют высоту. `EditorCamera` использует
только математику Three; единственный локальный renderer — PlayCanvas.
Слайд учитывает расстояние до поверхности. В разделе «Навигация» настроек
задаются ближний/дальний пороги, чувствительность на них, скорость зума и вид
сферы центра вращения. Сфера видна только во время вращения.
Маршрутный инструмент — «Обзор» или «Waypoint по клику». Отдельное добавление
в центр вида убрано. Основание waypoint увеличено втрое, луч — с 1,5 до 4,5 м.
Стрелки X/Y/Z позволяют переместить точку по выбранной оси; Y меняет высоту
по новому указанию владельца. Перетаскивание основания по X/Z ищет поверхность.
Добавление кликом также привязано к collider; произвольная высота точки не
означает разрешение роверу летать: физика продолжает следовать грунту.
Высота визуального луча настраивается до 50 м. Delete/Backspace удаляет выбранную
точку, Ctrl/Cmd+Z отменяет добавление, удаление или перенос с восстановлением
выделения. В «Обзоре» клик по пустой сцене снимает выделение; в режиме добавления
клик по существующей точке выбирает её. Переключатель инструмента и корзина
расположены справа сверху, вертикальный срез — слева.
Визуальная модель dcd006-v020-motion.glb получена из исходного CAD через
`tools/rover-scene/export_motion.py`. Сохранены 10 вращающихся сборок на родных
осях и по 44 повторяющихся шага протектора/скоб на каждом борту. Непрерывная
основа ленты сохраняет исходную кривизну. Шеврон в нижней ветви направлен
к +X, передней ведущей звезде. Исходный .blend не перезаписывается.
Отдельное Blender-превью — outputs/rover-motion/DCD-006_v020_motion.blend.
Локальная анимация зависит от фактической продольной скорости и поворота корпуса,
Worker-анимация — от измеренных скоростей левых/правых физических колёс proxy.
Математика и траектория общие, адаптеры PlayCanvas/USD независимы. Звезда
проходит девять шагов ленты за оборот; катки вращаются по своему радиусу.
Это визуальная кинематика с жёсткими элементами протектора, не расчёт изгиба
резины, натяжения, сцепления гусениц или токов VESC.
На Worker звенья представлены стандартным [USD PointInstancer](https://openusd.org/release/api/class_usd_geom_point_instancer.html).
Фаза накапливается по шагам физики; атрибуты визуальных экземпляров обновляются
пакетом один раз на кадр вне PhysX callback. Метрики стоимости и положения
анимации записываются в поле track_motion журнала motion.jsonl.
## Настройки и запуск · 02.10.2026, вечер
Все локальные локации используют `missioncore.simulation-view/v1`: качество
Gaussian-сцены, физические размеры/цвет/непрозрачность/пульсацию waypoint и
размеры/цвета X/Y/Z пивота. Настройки сохраняются в браузере этой операторской,
не в задании или профиле робота. Восстановление проверяет диапазоны и формат.
Качество разделяет один набор профилей между прежним viewer, локальным ручным
режимом и планировщиком. Оно не меняет сенсорную камеру Worker.
Разметка планировщика — отдельный PlayCanvas Layer поверх скана, с объёмными
цилиндрами и конусами. Оси масштабируются по глубине камеры, сохраняя экранный
размер; waypoint сохраняют размеры в метрах. SVG оставлен только для подписей,
линии маршрута. Выбор waypoint проверяет весь объём цилиндра, включая боковую
поверхность и торцы, независимо от его высоты и диаметра. Ни одна из этих сущностей не передаётся
в inference. Зум использует глубину collider под курсором, с резервным расстоянием
до центра локации, а не деградирующее расстояние до orbit target.
Старое задание другой версии ровера остаётся источником точек в редакторе, но
не допускается к исполнению без пересохранения. Запуск автоматически включает
AI выбранной композиции. Конфигурация AI доступна возле выбора задания.
После подтверждённого завершения видеосеанс демонтируется, а в локации остаются
кнопки нового запуска и единый accordion прогонов: дата/время, ровер, задание,
композиция и детали отчёта. `stopping` не считается свободным Worker: Core ждёт
`resources_released=true`, отправляемое после закрытия дочернего процесса и
остановки принадлежащего прогону model stack. Старые отчёты сохраняются.
Видео открывается только при запуске из текущего окна либо явном открытии
активной симуляции. Обновление каталога в другой вкладке не захватывает поток.
NVIDIA-клиент живёт в отдельном документе: выход освобождает соединение даже
во время подключения. После 20 с без первого кадра или 10 с без новых кадров
клиент пересоздаётся, не более двух автоматических попыток; затем доступен
ручной повтор. Это восстановление просмотра не перезапускает исполнение задания.
FPS слева над видео относится к декодируемому операторскому потоку; частоты
сенсорной камеры и решений AI остаются отдельными показателями телеметрии.
## Именованные задания и история — 02.10.2026
В шапке локации: режим → ровер → задание. Выбор задания открывает его маршрут
в локальном редакторе. «Сохранить задание» запрашивает имя; «Запустить симуляцию»
использует текущий маршрут, при изменениях сначала предлагает его сохранить.
Карандаш в строке выпадашки открывает переименование и удаление. Корзина прогона
находится слева от стрелки раскрытия. Удаление убирает запись из списка, доступна
отмена; исходные доказательства сохраняются. Активный прогон удалить нельзя.
Настройки планировщика — локальное перемещаемое окно без затемнения; скрытый
угол сохраняет изменение размера. Проверки: audits/2026-10-02-simulation-task-library.md.
## Наблюдение и профили движения — 03.10.2026
Настройки waypoint дополнены цветом свечения и силой эмиссии 0–5. Это яркость
самого материала, без отдельного bloom-ореола. Настройка применяется после
отпускания контрола, сохраняется вместе с остальными предпочтениями операторской.
Сфера центра вращения имеет экранный диаметр 6–64 px, одинаковый на любом зуме.
Физические размеры waypoint по-прежнему задаются в метрах.
Операторский вид Worker имеет три режима: «От третьего лица», «От первого лица»,
«Свободный обзор». ЛКМ вращает, ПКМ перемещает, колесо приближает/отдаляет;
WASD/стрелки и Q/E перемещают свободную камеру. Положение свободной камеры не
следует за машиной. В первом и третьем лице можно оглядываться независимо от
направления ровера. Камера сенсора AI при этом не меняется. Накопленные команды
камеры передаются с идентификатором сессии и последовательностью, применяются
однократно и сглаживаются на частоте рендера.
Кнопки справа снизу открывают отдельный viewport с результатами реальной
композиции: сегментация с легендой классов, допустимое покрытие и детекция.
Все слои одного preview имеют общие frame ID, время мира и composition hash.
Worker передаёт ограниченные JPEG-превью до 2 раз в секунду; видео остаётся
отдельным потоком. Пустая детекция означает отсутствие найденных объектов,
а не отсутствие запуска модели. Открытие/закрытие слоя не пересоздаёт видеосеанс.
FPS операторского видео находится сверху слева, камеры и маршрут — сверху справа.
В узком viewport три режима камеры переходят в штатную выпадашку.
Профиль выбирается в «Конфигурации AI» и входит в параметры и hash общей
композиции. «Природа» сохраняет исходные кандидаты проезда модели; «Парк»
разрешает дорожные покрытия и грунтовые тропы, исключает газон; «Город» ограничен
пешеходными покрытиями. Это правила классов модели, не распознавание назначения
каждого участка: ADE-класс earth может означать и грунтовую тропу, и голую землю.
Неуверенный пиксель разрешённого класса не записывается как физическое препятствие,
но не может сам дать визуальную цель. Семантические запреты добавляются к
наблюдаемой карте CMU после геометрической обработки и не отменяют её препятствий.
Финиш маршрута и доступность видео не доказывают соблюдение всех правил парков
или города; приёмка конкретных сценариев фиксируется отдельно.
Реализация, фактические проверки и ограничения этой версии:
[аудит наблюдения и профилей](audits/2026-10-03-observer-cameras-and-inference.md).
## Session presentation and current road-stop evidence (2026-10-03)
Location configuration and session results are collapsible with per-location
operator layout persistence. AI output views toggle independently; their available
set comes from executed composition ports. Current views include segmentation,
profile-permitted surface, detection and observed LiDAR returns. See
[session layout and road-stop audit](audits/2026-10-03-session-layout-and-road-stop.md)
for deployment, visual acceptance and the reproduced 310 m mission failure.
The long mission is not qualified: incorrect/low-confidence surface labels leave
no full-width local support after approximately six metres.
@@ -1,5 +1,13 @@
# ADR 0016: Distributed web product, edge runtime and worker topology
> Уточнение 02.10.2026: локальный ручной режим и локальное планирование входят в единую библиотеку локаций; AI-исполнение остаётся на Worker. См. [актуальный канон](../SIMULATION_WORKFLOW.md).
> Уточнение владельца 02.10.2026: интерактивное планирование маршрута теперь
> локальное, с дисковым кэшем Gaussian-preview и collider. Физика, сенсоры,
> inference и рендер выполняемого прогона остаются на Worker. Это заменяет
> прежнее требование удалённого редактора; см. `AI_POLYGON_ROUTE_PLANNING.md`.
## Status
Accepted for architecture on 2026-07-24. It defines placement and packaging,
@@ -9,6 +17,14 @@ physical command authority remain separate gates.
## Context
Profile clarification, 2026-10-02: the active AI Polygon runs native Isaac and
its model containers on the Windows Worker006. Its browser receives video and
compact state; it does not render the Gaussian world. The Linux/WSL Gazebo
details below describe the historical profile, not a mandatory operating system
for every simulator. Current run/evidence ownership and bounded acceptance:
[AI Polygon workflow](../AI_POLYGON_WORKFLOW.md). Onboard runtime and physical
actuator authority remain independently owned.
Mission Core has a React Control Station, a Python control plane, native
simulation providers and future onboard components. Treating all of them as one
application creates two misleading alternatives:
@@ -1,5 +1,13 @@
# ADR 0017: Provider-neutral simulation and Unreal evaluation
> Уточнение 02.10.2026: локальный ручной режим и локальное планирование входят в единую библиотеку локаций; AI-исполнение остаётся на Worker. См. [актуальный канон](../SIMULATION_WORKFLOW.md).
> Уточнение владельца 02.10.2026: интерактивное планирование маршрута теперь
> локальное, с дисковым кэшем Gaussian-preview и collider. Физика, сенсоры,
> inference и рендер выполняемого прогона остаются на Worker. Это заменяет
> прежнее требование удалённого редактора; см. `AI_POLYGON_ROUTE_PLANNING.md`.
## Status
Accepted for architecture on 2026-07-25. The provider contract is implemented
@@ -9,6 +17,16 @@ CARLA and Project AirSim is accepted by this decision.
## Context
Current applicability, reconciled 2026-10-02: the active AI Polygon uses native
Isaac on Worker006 and its own AI-polygon run/worker contracts, not the July
Gazebo/PX4 stack. See [current SRS scope](../12_SIMULATION_POLYGON_PRODUCT_AND_SRS.md)
and [AI workflow](../AI_POLYGON_WORKFLOW.md). Provider replacement, separate visual
and physical geometry, and virtual-only authority remain architectural boundaries.
The generic provider-profile migration and full qualification-report convergence
are not proven by the AI implementation. The Gazebo regression and Unreal
evaluation below are historical profile-specific decisions; Unreal evaluation
does not block the current Isaac work. Do not transfer their acceptance claims.
The first Polygon vertical proved that Mission Core can own a virtual Ackermann
run, display canonical ENU/FLU state in React, persist evidence and deliver
bounded virtual-only rover commands through PX4. That proof used one concrete
@@ -176,4 +194,3 @@ Defer until U0 selects a direction:
- [CARLA documentation](https://carla.readthedocs.io/)
- [Project AirSim documentation](https://iamaisim.github.io/ProjectAirSim/)
- [ASAM OpenDRIVE](https://www.asam.net/standards/detail/opendrive/)
@@ -0,0 +1,129 @@
# 02.10.2026 — локальный редактор маршрута, SOG и выполнение на Worker
## Решение и граница
По уточнению владельца интерактивное планирование перенесено на операторский
Mac. Редактор хранит полную Gaussian-сцену в дисковом SOG-кэше, отображает её
PlayCanvas и использует точный collider только для picking/BVH. Физики,
синтетических сенсоров, inference и команд настоящему устройству здесь нет.
Выполняемый прогон, его рендер и журнал остаются на Worker 006. Это заменяет
утреннее решение о редакторе через удалённый видеопоток; прежний аудит остаётся
историческим свидетельством, а не утверждением об удобстве такого управления.
## Реализация
- `AiLocalPlanner`, `AiEditorRuntime`, `EditorTerrain`: локальные orbit/fly,
WASD/стрелки/Q/E, zoom, канонический вертикальный RangeControl, waypoint по
клику/центру, горизонтальные оси, привязка к поверхности, удаление и undo.
Слой разметки не входит в изображение камеры AI.
- Сохраняется неизменяемое задание с world/robot SHA, точками, идентичностью
локального черновика и collider. Сохранение не создаёт фиктивный simulation run.
Worker сверяет collider редактора перед запуском физики.
- `editor_cache.py`, `ai_polygon_api.py`: дисковый cache v2, возобновляемые
512 KiB chunks, ограничения размера, SHA-256, атомарная публикация только
полного кэша, инвалидирование при изменении source/настроек/поверхности.
- Подготовка выполняется через существующий приватный Worker API. Временное
владение GPU `aicache-<key>` использует общий арбитраж, сохраняется при
переподключении и освобождается только после закрытия Windows Job. Сам
редактор готового кэша не нуждается в Worker или GPU reservation.
- Уже установленные SplatTransform 3.4.0 и PlayCanvas используются повторно.
Никаких новых системных пакетов, портов или изменений Docker-профилей.
## SOG: проверенная плотность
Проверка Core-кэша: 2026-10-02T14:02:56Z. Размеры — bytes, не MiB.
| Локация | Исходный PLY | SOG | Gaussian count до/после | SH bands |
| --- | ---: | ---: | ---: | ---: |
| Forest Scan | 505617082 | 31462568 | 2142439 / 2142439 | 3 |
| Bamboo Trail | 325861955 | 68749892 | 5818957 / 5818957 | 0 |
| Riverside Path | 142307349 | 23533415 | 2092749 / 2092749 | 0 |
Forest использует исходный SOG/WebP-архив, сохранённый 21.09. Его source manifest
`55b9fab459b98ac81126dc5df460f3e6b6f3b31108cfa053c094e33cae09f478`
связан с импортированным PLY в versioned `editor-sources.json`. Проверяется
каждый хеш, упаковка ZIP сохраняет исходные bytes без повторного квантования.
Bamboo и Riverside сконвертированы из полного PLY штатным конвертером.
Decimation и удаление SH не применяются. SOG квантирует атрибуты: сохранённое
количество гауссов не означает математически lossless-кодирование.
SHA-256 SOG:
- Forest: `1ab360abb70d34604445d03fed5d90320dcd1ebb43b13932f5622c757753c454`.
- Bamboo: `6c495ea75fcc72d02aff8ec5067563c8c993613d63a154cec39fee39223e021b`.
- Riverside: `25cec6d69d6d698c83abf72142a29b1d4fa3f2b4c615b515a1a12a86baac271b`.
Промежуточный 600k compressed-PLY вариант отвергнут: он уменьшал плотность.
Windows GPU-путь SplatTransform для Forest завершался native failure; пробный
Vulkan-адаптер также не прошёл и удалён из итоговой реализации. Повторное
CPU-кодирование исходного Forest оказалось ненужным благодаря сохранённому SOG.
Для новых SH-насыщенных импортов без исходного архива штатный CPU fallback
ограничен одним часом; ускоренное GPU-кодирование на этом Windows не принято.
## Визуальная проверка
В единственной вкладке IAB на canonical `127.0.0.1:8000` открыты все три SOG.
На Riverside проверены orbit, высотный срез, добавление в центре, перенос точки,
удаление, undo, сохранение и выход; на Forest — orbit/zoom, клавиатурный полёт,
добавление на грунтовку по клику и Escape из fullscreen. После открытий и выходов
новых console errors нет. Исправлены найденные ошибки инициализации Application,
повторного dispose BVH worker и начального pose CameraControls: первый жест больше
не прерывает незавершённый animated reset.
Дисковый кэш всех трёх локаций готов. Редактирование не породило ни одного
planning run. На проверке готового кэша GPU reservations = 0. Локальный FPS
численно не квалифицирован; рендер запрашивается при изменении вида/разметки,
а не постоянно в неподвижном редакторе.
## Проверка полного цикла
UI сохранил `aiplan-557556da24654cdf8f38e14a1e10255c`, источник
`operator-local-viewport`, source_run_id = null. Это Riverside, DCD-006 v020,
две точки, длина задания 3.395846955 м, радиус прибытия 0.4 м.
Plan SHA `2011bd09d45d18f6dd5f1e67172ea790e5f8656b4f284975f4ecbec2e4ffc40c`.
Этот план запущен через UI на Worker:
`airun-3f847907fb024f178badecceab461201`, итог **goal-reached**,
23.800001 с simulation time, фактический путь 3.045622 м, ошибка до цели
0.360462 м. 110 AI decisions, 0 inference errors, median 125 ms / P95 203 ms.
Единственная зафиксированная остановка после начала движения — достижение цели.
Наблюдаемое видео: около 28 FPS на паузе и 18 FPS после движения, не гарантия.
Collision count не подключён; нулевое значение не выдумывается.
Worker автоматически завершил эпизод и сохранил 456 evidence files / 14487980
bytes. Report SHA `74a871a83c67be3235aa687367f76b566353f880a85437345b9fb8814c6ecae8`,
evidence manifest SHA `2cab5456160037bfb0f5d0610b6ed148a5113c9039df285b9cbb8682e13ce1e2`.
Отчёт подтверждён в интерфейсе «Результаты прогонов».
## Артефакт и проверки
Worker release `03abe7cf43f3720b`, 652 verified files, установлен штатным
`Install-RealtimeWorker.ps1` в 2026-10-02T13:58:24Z. Archive SHA
`ee4504639bfc3fd7eaf021de6314e6543ca4404300c9a1fece7821deadd8dbb4`.
Исходные модели, inference-композиции, восемь существующих контейнеров и LCC
сохранены. Private receipts/cache manifests/logs:
`outputs/ai-polygon-2026-10-02/local-editor-release/`.
126 focused Python tests passed (AI protocol, planning, realtime, cache,
navigation, spawn, reports, shared GPU queue). Девять cache tests включают
возобновление, checksum/path boundaries, локальное сохранение при отсутствии
Worker, stale calibration, reservation ownership, сохранение density/SH и
byte-exact переиспользование оригинального архива. Ruff и diff checks passed.
Frontend: полный прежний unit pass 1019, два новых coordinate checks; TypeScript
и production build прошли. Предупреждения: существующие большие Vite chunks и
Starlette/httpx deprecation, без новых failures.
## Граница приёмки и следующий шаг
Принят локальный редактор и короткий end-to-end цикл его задания на Worker.
Не приняты полное прохождение Forest/Bamboo, динамические люди/животные,
реальная локализация, физическая точность гусениц и управление настоящими VESC.
Collision proxy Forest/Bamboo ограничен ранее подготовленной областью; видимый
Gaussian вне collider не допускается как точка задания. Для длинных маршрутов
понадобится отдельная квалификация покрытия поверхности и проходимости.
Автоматическое вытеснение старых cache revisions пока отсутствует; проверка
свободного места и максимальный размер передачи действуют.
Следующий эксперимент: вручную задать осмысленный маршрут, затем сравнивать
композиции на одном неизменяемом задании, сохраняя outcome, остановки, ошибки,
возраст кадров и evidence. Успешный короткий заезд не равен общей автономности.
@@ -0,0 +1,84 @@
# Planner settings, zoom and simulation launch — 2026-10-02
Owner request: shared planner appearance, volumetric editable markers, stable
cursor zoom, Gaussian quality selector, overlay controls, explicit launch and
release, per-location accordion history. Input screenshots: 19:32:25,
19:32:55, 19:34:14 and 19:41:56 (operator local time).
## Implementation
- `core/simulation/plannerPreferences.ts`: versioned, bounded preferences for
pivot screen dimensions and axis colors, waypoint world dimensions, opacity,
pulse frequency and quality. `usePlannerPreferences` persists in this browser
and shares changes across locations/tabs. It does not alter robot or plan SHA.
- `PlannerSettings` uses canonical FeatureSettingsWindow, RangeControl,
ColorField and ControlRow. `SimulationViewTools` supplies quality/help/settings/
fullscreen over the actual image, without a separate black strip.
- `PlannerMarkers`: PlayCanvas cylinder/cone geometry in a dedicated annotation
Layer, with perspective-correct world scaling for constant-size pivot axes.
Gaussian unified rendering hid default-layer transparent markers; the explicit
later layer resolved this, verified by screenshots. SVG retains only labels,
route connection and invisible pick targets. The white center circle is gone.
- `EditorCamera`: wheel translation follows the cursor ray, scaled from the
collider hit depth, falling back to scene-center distance. Orbit target radius
no longer controls zoom speed. RMB pan and add-mode zoom are retained.
- `gaussianQuality.ts`: one existing five-level profile table consumed by both
PlayCanvas runtimes. Preferences affect operator rendering, not Worker sensors.
- `AiPolygonWorkspace`: mode/rover/prepare/launch; no Start and Scale button.
Existing calibration still serves unprepared imports. Composition selector
remains accessible through Configuration AI. Launch starts inference directly.
- `AiRunReport`: one canonical Inspector panel accordion per location, including
date/time, robot, task, requested composition, outcome and recorded details.
Terminal video mounts are removed after acknowledged Worker finish.
- Design Guideline `Window` and `Dropdown`: native fullscreen-aware portal root;
same existing controls, no local copies. Registry, docs and catalog updated.
## Diagnosed launch blocker
Worker was available and had no active reservation. Riverside's saved plan used
robot SHA 15b75ea2093c8cac3f3208f4cca100d3735178a37cf5ac804827f3806baee66b;
the current animated profile is f57e9f6131ff1afc4cb8a1b4e5abfbe01c58d7e35f8a225e4f839108974f2984.
The previous UI silently excluded the plan. It now explains the mismatch and
loads the historical points into the editor for explicit resaving. No immutable
plan was rewritten. The screenshots also showed a one-point unsavable draft;
the UI continues to require two points and explains the requirement.
## Qualification
- Frontend architecture 4 checks, full unit suite 1028/1028, TypeScript and
production build pass. Existing large-chunk warnings remain.
- Backend lifecycle/planning/report checks: 18 passed.
- Design Guideline ui-react build, registry, floating/select/range checks: 13
passed. Fullscreen settings/menu and nested Escape verified in Mission Core.
- Browser: Riverside old points restored; 3D beam selected; X pivot dragged and
undo restored points; far out/in zoom; zoom in waypoint mode; settings saved
and retained after reload; high quality retained when entering pokrovka manual
mode; restored medium after QA. No canvas outline in either viewport, controls
overlay scene. Physical trackpad held gestures are not synthesized by the tool.
- New plan aiplan-bf877a6dce3a4928af8c453099ef1dfc preserves the two Riverside
points for current DCD-006. Browser-issued run airun-c5294f4ef5f74bbea733b4979e79e9ed
reached the goal: 3.077 m, 24.433 s simulated, goal error .343 m, 112 decisions,
zero inference errors. A captured live snapshot had RTF .988 and render 15.60 FPS.
- Immediate next run airun-3a8e1affadb44b9ebb4468797b61e043 accepted. Operator
stop during preparation reached stopped and active_run=null. It produced an
operator-stop report, with no AI decisions, as expected.
- Existing Worker cleanup protocol already waits for the episode child, model
startup ownership and stack.stop(), then sends resources_released=true and
retries until Core accepts. Core releases the exact reservation only on that
receipt. No forced lease deletion, hand patch or Docker profile change.
## Limits and evidence
This is a short launch/editor regression, not qualification of long outdoor
routes, reliable physical collision counts or real tracked traction. Collision
count is still null in the report; no zero-collision claim is made. Operator
preferences belong to this browser; remote observer route overlay remains its
existing telemetry visualization. The three-dimensional annotation layer is
only the local planner and never enters AI frames.
Raw catalog snapshots, tests and final receipt manifest:
`outputs/ai-polygon-2026-10-02/planner-ui-evidence/` (local ignored artifacts).
Worker package remains 6746d47f225891b6. Eight pre-existing Docker model/pipeline
containers were preserved. Canonical Core remains on port 8000.
Final UI regression run airun-42ff41d3dad24079a4f9d2fd2fde87c1 also reached its goal: 3.074 m, 23.683 s, 107 decisions, 0 errors. The terminal video mount disappeared and the report accordion opened in-browser.
@@ -0,0 +1,134 @@
# AI-полигон · DCD-006 и явное задание · 02.10.2026
Дневной инкремент после утренней read-only сверки. Не изменяет исторические
результаты 23.09. Исходный код изменён локально; commit/push не выполнялись.
## Результат и границы
В AI-полигоне появились выбор DCD-006, удалённое визуальное планирование,
неизменяемое именованное задание и отчёт нового прогона. Worker исполняет
Isaac, физику, Gaussian, все модели общей композиции и хранит полный архив.
Mac декодирует WebRTC и рисует компактный 2D SVG-слой по проекциям Worker.
VESC/ASVD и LCC не входят в этот инкремент.
Это приёмка редактора и связи plan → run → report, а не природной автономии.
Динамические акторы, калиброванная физика гусениц, SLAM/шум одометрии,
счётчик контактов и серия 5/5 остаются открытыми.
## Версия и профиль
Worker release `4c8f9ace48ca8952`, 649 файлов;
bundle SHA-256 `43355c6614b7e983d211f0a91eb40b1e9f00b6e7e38bbb29d294e8591a35f49e`.
Проверены manifest identity и SHA каждого файла; установка через штатный
`Install-RealtimeWorker.ps1`. Предыдущие версии сохранены для отката.
Контейнерные профили и веса других контуров не заменялись.
DCD-006 v020 использует тот же GLB, что PlayCanvas Rover006:
`3b9aa6f828c7a4ca1c5581b84299164fcddc9ecb37f56ec1f5341ce6df0f0cfa`.
Габариты 1,163×0,905×0,734 м, 9 PBR-мешей; анимации гусениц нет.
Профиль `15b75ea2093c8cac3f3208f4cca100d3735178a37cf5ac804827f3806baee66b`.
Физика — временные четыре скрытых колесных контакта, условные 24 кг.
Камера размещена перед габаритом; её калибровка сохранена в профиле.
Это лабораторная модель, не квалифицированный цифровой двойник привода.
## Реализация
- `plans.py`, `runs.py`, contracts/API: неизменяемые задания с SHA мира,
collider, профиля ровера, метрами/осями, порядком точек и исходной позой.
Сохранение ждёт подтверждения всех команд Worker. Новая версия не меняет
существующий план или настройки каталога. Новый UI требует plan_id;
инженерный API без plan_id сохраняет совместимость.
- `terrain_picker.py`: готовый NVIDIA Warp BVH над подготовленным collider
на GPU Worker. PhysX query при остановленной физике не находил поверхность;
Warp независимо от physics clock возвращает действительное попадание.
- `route_view.py`: свободная камера, terrain picking, оси/Undo и проекция
точек. Добавление по клику/центру, перенос по двум горизонтальным осям,
привязка высоты к поверхности, удаление. Не более 33 точек со стартом.
Устаревшая ревизия камеры отклоняется. Очередь ограничена, команды дедуплицируются.
- `AiRouteOverlay`, `useAiPlanningControls`: только UI/SVG и ограниченные
команды. Мышь меняет взгляд, Shift + мышь сдвигает обзор, колесо двигает
вдоль взгляда, WASD/стрелки дают свободный полёт, Q/E — вниз/вверх,
Shift ускоряет, Home возвращает исходную камеру. Worker сглаживает позу;
команды задают конечные смещения, поэтому потеря key-up не оставляет скорость.
- Вертикальный `RangeControl` взят из `SessionOverviewScene` сравнения облаков
с теми же orientation, limitSide, форматированием и размещением. Ручное поле
высоты удалено. Шкала Riverside −3,075…22,35 м по подготовленной геометрии.
Gaussian extent содержал выбросы −3777…3964 м и не пригоден для этой шкалы.
Верхний конец выключает срез полностью, в том числе для выбросов.
- Срез реализован RTX Section Plane в preview; простой USD Camera clipping
оказался неэффективен и удалён. На живом видео высота 1,8 м срезает верхнюю
растительность, верхняя отметка возвращает изображение. Новый evaluation
явно выключает Section Plane. Исходники сцены/collider не меняются.
- Маркеры, оси, маршрут и фактический след отсутствуют в USD и RGB render
product; AI их не видит. Отдельного аннотированного sensor input нет.
- `run_report.py`: после остановки native/model процессов закрывает неизменяемые
report и evidence manifest на Worker. Core получает метрики и идентичности;
report проверяет plan ID/SHA. Неизмеренные столкновения остаются null.
## Живая проверка редактора
`airun-288ec91f71d7409aa2273b16311294b2`: добавление по клику/центру,
выделение, перенос по оси X, удаление/Undo, сохранение задания. Физическое
время 0, inference 0. Единственный видео-клиент работает; второй открытый
просмотр мешал получить offer. Пользователь закрыл вторую вкладку, после
переподключения получено 28 FPS. В сообщении ошибки теперь объяснено
ограничение одного клиента NVIDIA.
`airun-31337385392f466c94110e3340b260a6`: повторное открытие сохранённого
задания, вращение камеры мышью и действующий Section Plane. Выявлен и
исправлен непригодный диапазон шкалы по Gaussian extent.
`airun-b8870648e01d42e498a9d473750578c1`, финальная версия: команды W, E,
ArrowRight, zoom, Home, срез и перенос финиша по X подтверждены Worker,
planning error=null. Рендер около 28 FPS; physics_steps=0,
inference_count=0. Проверены обычное окно и fullscreen; сохранение из
fullscreen открывает видимое каноническое окно, затем завершает preview.
Два разных задания сохранены без ввода XYZ:
| Задание | Точки / длина | Идентичность |
| --- | --- | --- |
| Riverside · проверка планировщика | 2 / 3,164 м | `aiplan-bbf4e3c8199147b090d5a5cb3f438fa6`; SHA `6fc5db8887e59b59590ecd32afb2de9ea60bb8c12904e3fa4f08bed8461f1aea` |
| Riverside · короткое задание DCD-006 | 2 / 3,396 м | `aiplan-7b6ba389010b4e35923b521994ae5032`; SHA `328be134b8b29988662f19c79a8e28a64480dade97ff8b089cba7431e506b827` |
Первый план не изменился после сохранения второго. На playback план и след
можно скрыть; аннотации не включены в inference. Предпросмотр не переносит
физическое тело при каждом редактировании стартового маркера: сохранённая
новая поза применяется при создании следующего прогона и проверяется placement gate.
## Навигационная граница
Контрольный run `airun-5fc78e787b754cf599de0d5d699e8e92` по второму
визуально созданному заданию завершился **goal-reached**. Физическое время
23,6167 с, фактический путь3,0565 м, ошибка финиша0,35497 м при допуске0,4 м;
одна цель после старта достигнута. 110 inference, 0 ошибок,
median125/p95219 мс. В отчёте только конечная остановка1,95с, промежуточных
no-road/stale-stop нет. Это один короткий прямой маршрут, не серия5/5.
Plan SHA `328be134b8b29988662f19c79a8e28a64480dade97ff8b089cba7431e506b827`;
composition SHA `891904a1e31c9fc0ec21d6b80bc00de7b05c642f49c8fd714bb71a1c132c0a6c`;
report SHA `3027736fb7c3ab20be8a4cc5f559e0d394f3412a7b4c34ef581ce846479958e7`;
manifest SHA `a89abad1051bf8f4194ae2ca3a82f0c1a1a73faceebe67ab2d3ed8f64122063a`.
456 файлов /14 211 048 bytes на Worker. UI «Результаты прогонов» показывает
имя задания, исход «Маршрут пройден»,1/1целей,метрики и отсутствие учёта
столкновений. После завершения active_run=null.
Дневной baseline с CAD-габаритом `airun-c2e2366811f3442d8e016966d0bce811`
остановился stuck после 3/6 целей: 88,633 с мира, 7,593 м, 412 AI-вызовов,
0 inference errors, median125/p95234 мс. Три no-road остановки суммарно34,55с;
две stale остановки суммарно0,0667с. Пять успешных повторов не получены.
Report SHA `967b46282554a0a2dbb1e5ebe8f1310a3b187d0dce1332dfdcd750d7e01f8068`;
manifest SHA `3902a34ea662c7688382b68984508da6034e0845efe629573afdcdddcf692b38`.
Исторический успешный заезд старого шасси не квалифицирует новый CAD-профиль.
## Проверки кода
65 focused Python tests: planning/realtime/reports/navigation/spawn/API.
Проверены immutable hash, mismatch world/robot, ack/save/stop, границы DTO,
проекция и обратный луч, terrain height/оси/Undo, stale view, свободный полёт,
затухание камеры и нулевая/отрицательная плоскость. Ruff и diff-check чистые.
Frontend: architecture4, полный unit1019, TypeScript и production build.
Остаётся прежнее предупреждение Vite о больших chunks; новых ошибок сборки нет.
Core8000 сохраняет единственный durable процесс. Полные сырые данные и кадры
остаются на Worker; этот аудит содержит только идентичности и результаты.
@@ -0,0 +1,101 @@
# Simulation editor navigation and video lifecycle — 2026-10-02
Owner request: metric navigation at near/far zoom, orbit around the pressed
surface point, editable navigation preferences, reversible waypoint editing,
compact viewport controls and recovery from missing Worker video.
## Implementation
- `EditorCamera` uses Three camera/vector math only; PlayCanvas remains the sole
local renderer. Pan scales by optical surface depth and viewport height, with
a configurable smooth interpolation between near/far sensitivity and distance
thresholds (defaults 3 m / 100 m, both sensitivity 1×). Wheel speed is configurable.
- `editorNavigation.ts` rotates camera position AND orientation rigidly around
the picked point. Off-centre picks stay at the same screen coordinate instead
of snapping the camera toward a new look-at target. Empty sky falls back to a
forward point at scene distance. A local sphere marks the pivot only during
the orbit gesture; diameter, color and opacity are configurable.
- `waypointEditing.ts` owns bounded undo snapshots, selection, drag transactions
and draft revision. Delete/Backspace deletes the selected point; Ctrl/Cmd+Z
restores coordinates, order and selection. Text fields/settings retain native
keyboard behavior. A drag adds one history entry; selection/canceled drag adds
none. Opening another task isolates history.
- Empty scene click clears selection in Overview. Add mode selects existing
markers or places a new surface point. Wheel and right-drag navigation remain
available. Waypoint height accepts up to 50 m; old settings migrate normally.
- Planner tool modes use the standard segmented size at the top right, with
selected-point trash on their left. Clip scale is on the left. No Undo/Home
buttons remain. The modeless settings window opens below the tool row within
viewport bounds. Scene-control segmented backgrounds are corrected in the
canonical Design Guideline, including its living catalog example.
- Planning hides the inactive mode/rover selectors. A running simulation hides
mode/rover/task selectors and the duplicate Preparation button. One simulation
state badge stays at the left above the viewport; camera modes sit at the top
right beside expand.
- The NVIDIA SDK now lives in a dedicated same-origin `simulation-stream.html`
iframe. Removing the document releases its peer connection and global handlers
even if SDK 6.7 remains in STARTING. The former module-global promise queue
waited for an unbounded `settled` callback and could block every later viewer.
The former first-frame wait also had no watchdog until a first frame arrived.
Recovery now bounds first-frame wait to 20 s, stall to 10 s and automatic
replacements to two; exhausted recovery releases the frame and offers retry.
Message origin/source are checked. Telemetry updates do not reconnect video.
This changes browser video ownership only, not Worker execution or inference.
## Validation
- Architecture checks: 4 passed. Frontend full unit suite: 1038 passed.
- Typecheck and production build passed; existing large-bundle advisory remains.
- Design Guideline registry and catalog typecheck passed; 6 density/range checks
passed. No deployment or Worker model/profile changes were required.
- Browser verified waypoint selection, empty click deselection, Delete, Cmd+Z,
Ctrl+Z, selecting an existing point in Add mode without duplication, adding a
point and undoing it, orbit movement and zoom in Add mode. Height 50 m and
committed navigation sensitivity round-trip through the settings UI passed;
test changes were restored to their prior values.
- The first reproduction using the previous client received 15 FPS while moving
and 28 FPS paused. Run `airun-60e99c16a7b64d36b68a17b4cc5656a5` was explicitly
stopped after inspection. The user's earlier missing-video root cause cannot
be assigned conclusively from its screenshot or server log alone.
## Final browser acceptance
- The run viewer now requires an explicitly selected run ID. A background tab
displaying the location must not automatically attach when catalog polling
sees a newly started run. `viewedAiRun.ts` and its focused test enforce this
boundary; explicit Open still attaches to an existing active run.
- Run `airun-81212dcfe1f94e60bb57e5597084604d` proved repeated leave/reopen and
reload/reopen of the same Worker process with the isolated video client.
Video returned without manual retry and showed 24–28 FPS paused. The existing
wall-clock run limit eventually ended this paused run during extended UI QA;
that termination is not evidence of a video reconnect failure.
- Final run `airun-1914081b601549519c837fe68c5eb5b9` proved a fresh launch from the
unchanged saved 5-point route. Moving telemetry showed 0.14 m/s, sensor 4.3 FPS,
AI 5.3 decisions/s and operator video 4 FPS at one sample. These are different
clocks; this work does not qualify real-time throughput under inference load.
- Planner normal 1280×720 and native fullscreen 2048×1280 checks passed: scale on
the left, opaque standard toolbar on the right, trash only with selection,
modeless navigation settings below the toolbar without obscuring the scale.
Escape restores the normal view. Original waypoint coordinates and navigation
preferences were preserved after testing.
- Follow-up owner adjustment doubles the radius-centred clip-rail inset from
12.8 to 25.6 px, equally on the left, top and bottom. Endpoint labels remain
inward; only the domain layout changes, not the RangeControl primitive.
- Stream FPS is on the left. Camera modes, route visibility and fullscreen are
aligned on the right at the canonical 46 px control height. Hiding the route
removes the annotation layer; showing it restores the same overlay.
- The fitted picture, route overlay and toolbar share one viewport. It uses the
canonical 22 px panel radius and an 8 px inset mask to exclude the encoded
stream edge; controls sit 16 px inside that visible edge. This only clips the
operator display and preserves projection coordinates and sensor pixels.
- Evidence: `outputs/ai-polygon-2026-10-02/editor-navigation-evidence/` in the
NODEDC workspace contains `planner-navigation.jpg`, `planner-tools.jpg` and
`video-fullscreen.jpg`. Build/typecheck passed after final layout edits.
No complete route, collision envelope, actuator behavior or autonomous safety
qualification is claimed by this UI/video acceptance. Worker profiles, model
composition, Docker configuration and physical devices were not modified.
Final cleanup: the fresh run was stopped via the product; catalog reports
`active_run=null`, `available=true`. Canonical Core PID 26337 remains on :8000;
no listener on :8765. No temporary test/build processes were left running.
@@ -0,0 +1,105 @@
# AI-полигон: сверка состояния 02.10.2026
Запрос: восстановить понимание цели, реализации, ограничений, плана и места
фиксации результатов. Выполнен read-only обзор кода, Ops, Core8000 и Worker006.
Новые симуляции, модели, контейнеры и службы не запускались; runtime не менялся.
Рабочая схема и следующий план: [AI_POLYGON_WORKFLOW](../AI_POLYGON_WORKFLOW.md).
## Текущее состояние и источники
- HEAD при начале: `9761474`; рабочее дерево чистое. Simulation runtime сохранён
в `f01bd39` от 25.09, эксперименты — `dad11b4`; более поздних изменений этих
runtime-путей в просмотренной истории нет.
- MISSIONCOR-83 уже содержит перенос результатов 23.09 и Git-closeout 25.09.
Ранние блоки с названиями «текущий» всё ещё указывают старые releases и планы.
MISSIONCOR-39 и SRS описывают в основном июльский Gazebo/PX4 контур.
- Core8000 отвечает на каталог: 3 локации (Forest, Bamboo, Riverside),
`runtime.available=false`, `active_run=null`. `world.status=available` —
состояние каталога/импорта, не приёмка автономного проезда.
- Финальный `/api/health` около 07:30 UTC возвращает `operational=false`:
recording cache сообщает `capacity-pressure`, свободно 1 299 984 384 bytes
при резерве 2 147 483 648. Процесс/API доступны, но Core сейчас не готов
к операциям по своей health-проверке. Это отдельная от Worker preflight
проблема ёмкости; пользовательские записи и кэши не удалялись.
- Worker006 доступен через существующий SSH alias. Проверка около
`2026-10-02T07:12:48Z`: Scheduled Task `ndc-ai-polygon-worker` в `Ready`,
последний result=1, запуск 10:07:25 местного времени Worker; active marker
отсутствует, native Kit процессов 0.
- Installation receipt по-прежнему указывает `22c28daad98da60b`, 597 файлов,
установлено 23.09 в 08:30:06 UTC. Это чтение receipt, не повторный hash-check
каждого установленного файла и не доказательство текущей готовности.
- Журнал 02.10: coordinator завершился в `ModelStack.preflight()` на
`docker image inspect` DDRNet-image. При следующем read-only обращении Docker
29.5.3 и этот exact image уже доступны. Причина исходного отказа не установлена:
readiness race при старте машины — гипотеза, stderr первоначального inspect
в журнале отсутствует. Старый `service-status.json` не является живым heartbeat.
Восстановление/повторный запуск остаётся работой следующего этапа.
## Сохранённая приёмка и найденный поздний заезд
R34 и его ограничения остаются в
[аудите 23.09](2026-09-23-ai-polygon-continuous-motion.md). SHA-256 receipt
`state/continuous-motion-evidence-20260923.json` повторно совпал:
`5c1d0bb5f081cb74d440c43cdaf4d41a8e82e488a5050834a9e727827752007b`.
Все 3961 файла receipt заново не проверялись.
Более поздний run `airun-9bc4154d8d4c427896078e89d3e573bf` создан
23.09 в 08:50:43 UTC. Он отсутствует в указанном receipt. На Worker прочитаны
его `run.json`, результаты, motion/physics/decision journals и composition;
сводка пересчитана 02.10 в 07:15:45 UTC (Worker monotonic 636.546):
| Показатель | Результат |
| --- | --- |
| Мир/миссия | Тот же Riverside Path / 6 точек episode97 |
| Итог модели и Worker | `goal-reached`, `completed`, 0 recovery |
| Последнее время мира | 92,5667 с |
| Смещение старт–финиш | 10,5801 м; не полная длина физической траектории |
| Ошибка до конечной точки | 0,354959 м при допуске миссии 0,4 м |
| Решения | 400 записей; 0 решений `inference-error` |
| Максимальный наблюдённый наклон | 4,6469° по компактному motion journal |
| AI / render | Медианы 4,5714 Hz / 17,1171 FPS по running+ai_ready snapshots |
Это второй сохранённый результат на одном задании, не новый эксперимент
02.10 и не серия независимой приёмки. Контакты, пропуски препятствий и полная
классификация остановок этого позднего заезда здесь не оценивались.
400 journal records и 399 в последнем Core snapshot относятся к разным срезам
завершения и не подменяются друг другом.
Хеши прочитанных файлов позднего run:
| Файл | SHA-256 |
| --- | --- |
| run.json | `dfa882565793948a43b038aca1a15a5c240000899d98f17116f2f03aba57e7fe` |
| result.json / worker-result.json | `472c266be27174a41a9c9306be1a6db90fb27c2590abf54993a06a528b0c80ed` |
| motion.jsonl | `a49d475fb59dcd2382e97fbd7ca43011dc0c91329856ad838c1fa72ee224e719` |
| physics-motion.jsonl | `bd801b17e0a931b23618d9ad8a2e952b381a217405ac615c6f9eacd0e2142b60` |
| camera/decisions.jsonl | `b4dd44215ad91dcba23041d4e8a14038d8428eef29cb666dd406d4f0c2f67b44` |
| composition.json | `282f6ec2282abd51e2a9f81b395252f103c710c7535fe0d4fee053933b7166a2` |
Private derived summary: `outputs/ai-polygon-2026-10-02/recorded-run-review.json`.
Этот компактный индекс не заменяет полного закрытия артефактов позднего run;
старый receipt оставлен неизменённым.
## Выводы по коду
`RunStore` сохраняет снимок мира/композиции и последний realtime snapshot.
Полный realtime archive остаётся на Worker; `/runs/{id}/decisions` на Core
не экспортирует этот remote archive. `completed` также используется по
истечении duration в `run_realtime.py`: для навигационной приёмки требуется
отдельный mission outcome, одного lifecycle state недостаточно.
В `navigation_client.py` вход `source.pose` — поза из симулятора. CMU получает
наблюдаемые range points, но метрическая локализация идеализирована. Настоящий
SLAM/одометрия, sensor parity, распределение шума и sim-to-real не приняты.
Общая композиция сохраняется. Автоматического сравнения версий, полной
сценарной оценки столкновений и единого пользовательского отчёта пока нет.
Обновлены рабочая схема, ссылки/границы SRS и ADR, LCC brief и противоречивые
формулировки runbook. Исторические измерения сохраняются; планы не превращены
в отметки о выполнении. Код и UI не изменялись, повторный тестовый прогон
продукта не требовался; проверяются Markdown links и `git diff --check`.
MISSIONCOR-83 и MISSIONCOR-39 обновлены и прочитаны обратно: 33 и 38 блоков.
Прежние тела исторических блоков/checkers сохранены, кроме явно уточнённой роли
общей архитектурной карточки; состояния карточек не менялись. Новые документы
оставлены в рабочем дереве, commit/push не выполнялись.
@@ -0,0 +1,66 @@
# Simulation tasks and local planner controls — 2026-10-02
## Accepted workflow
The operator chooses a location, mode, rover and named task in the header.
Selecting a task opens its points in the local editor. New task starts an empty
route; changing tasks in an open editor preserves the prior points in Undo.
Save opens a name dialog and keeps the editor open. Launch uses the exact saved
route if it matches the draft, scene cache and robot; otherwise it first asks to
save the current route. Simulation/inference/rendering remain on Worker 006.
A task row has the shared Select action for editing its name or removing it.
A run row uses the shared Inspector action left of a down/up disclosure chevron.
Removal is a server-persisted list change with an immediate Undo action. Immutable
plan files, run evidence and Worker journals are retained. Running/unreleased
runs cannot be removed. Removed tasks cannot start new runs. Labels are separate
metadata; each new run snapshots the current label without changing plan SHA.
## UI composition
- Mode → rover → task → save/launch; compact widths at smaller viewports.
- Save dialog only asks for the task name; task selection lives in the header.
- Planner preferences use a bounded 400 px WorkspaceWindow, without modal
dimming. It can move, resize and maximize within the viewport. The corner
indicator is hidden while pointer and keyboard resizing remain functional.
- Pivot/Waypoint is a dropdown within that window. Range gestures commit into
shared browser preferences and the scene on release; exact fields commit on
Enter/blur. Preferences still apply across this browser's locations.
- Local status sits on the left above the viewport; manual speed is bottom-left
inside it. The local viewport fits the remaining workspace height, including
compact windows, so bottom controls do not fall below the visible scene. Quality and buttons use the shared opaque scene-control material.
- Shared DG registry, component documentation and catalog examples were updated.
## Acceptance
- Frontend architecture 4 checks and exact draft identity 2 checks passed.
- Frontend typecheck, 1030/1030 unit tests and production build passed, sequentially.
Existing large-chunk Vite warnings remain.
- Backend 29 tests passed across library, planning, realtime lifecycle and cache.
Tests cover rename/remove/restore across restart, immutable file preservation,
rejected active-run removal, removed task launch, path safety, request validation
and label snapshots. Focused Ruff checks passed.
- DG packages build, catalog typecheck, registry and 12 focused density/select/
floating checks passed.
- Browser: task rename/delete/Undo, run delete/Undo, task selection into editor,
save-name modal in native fullscreen, modeless settings, hidden resize indicator
and keyboard resize (468→458 px), opaque controls, nested dropdown Escape and
panel chevron (180° when expanded) verified. Final manual QA at 1280×720:
viewport ends at y=684, speed ends at y=672, entirely within the visible area.
- Browser-issued run airun-ae498618e9ad4d8683f5cdfb167a903e launched directly from
the editor using aiplan-b5d71c781b694f1ebf11643112f560df. It reached its goal:
3.048 m, 24.233 s simulated, goal error 0.368 m, 110 decisions, zero inference
errors. Median/P95 inference 125/204 ms. One no-road stop lasted 0.233 s.
Worker confirmed release; active_run=null and Worker available afterward.
- Core is the durable launchd service on 127.0.0.1:8000; no backend on 8765.
Worker package and Docker composition were not changed in this UI increment.
## Limits
The short run verifies task selection/launch/reporting, not long-route outdoor
navigation or tracked traction. Collision count remains unmeasured. The browser
video counter briefly reported 0 FPS; this pass does not qualify streaming cadence.
The worker telemetry and completed report are the launch evidence.
Local evidence: outputs/ai-polygon-2026-10-02/task-library-evidence/ (ignored),
including the final catalog, screenshot and test/build logs.
@@ -0,0 +1,84 @@
# Единая библиотека и развилка режимов · 02.10.2026
## Решение и реализация
По указанию владельца после открытия локации выбираются режим и ровер.
Ручное управление использует локальный SOG и существующий PlayCanvas/Ammo
контроллер с выбранной моделью DCD-006. Inference использует локальный редактор
и сохранённое задание, затем Isaac и общую AI-композицию на Worker 006.
См. [текущий канон](../SIMULATION_WORKFLOW.md).
Все шесть подготовленных локаций доступны в одном каталоге. Убрана развилка
AI-полигон/LCC Mirror. Собственные проекты остаются в `SimulationProjectStore`;
адаптер `ProjectWorlds` переиспользует их артефакты и сохранённые калибровки.
Профили моделей, Docker-службы и физические устройства не мигрировались.
`localScene` и `useLocalScene` общие для редактора и ручного режима.
`LocalManualScene` владеет локальным lifecycle, `AiLocalPlanner` — только редактором.
План и запуск сохраняют прежние immutable identity/Worker reservation контракты.
Выполнение собственного SOG допускается только на Worker с capability `project-sog`
и с сохранённым заданием. Большие проекты адаптируются штатным SplatTransform
в LOD0 области маршрута; исходный collider сохраняется, Draco декодируется без
упрощения. Подготовка ограничена временем, размером и свободным местом.
## Исправленные дефекты
- Воспроизведено падение выбора waypoint: React updater обращался к очищенному
`drag.current.previous`. Состояние завершённого drag теперь захватывается до
очистки ссылки; простой выбор не создаёт undo и новую ревизию маршрута.
- В собственном скане collider оказался Draco GLB. Подключён уже поставляемый
официальный Draco 1.5.7 в локальный picker и версионный Worker decoder.
- Unified PlayCanvas modifier получает world center. Повторное преобразование
высоты ломало срез повёрнутого скана; теперь сравнивается world Y.
- Два подготовительных запуска прервались из-за RemoteDisconnected при heartbeat.
Подготовительный poll ограничен 1 Гц, только этот идемпотентный опрос имеет
до трёх попыток при транспортной ошибке. Мутации запуска не повторяются.
- Общая сцена снова занимает высоту родителя; заголовок отделён от скролла контента.
## Проверки
Frontend: 1021 unit test, включая архитектурные ограничения, прошёл; typecheck
и production build прошли. Backend: 51 профильная проверка прошла; после
добавления capability/task admission проверки — ещё 13 целевых тестов, включая
три теста общей библиотеки. `git diff --check` и Ruff выбранных Python-файлов прошли.
Browser: шесть локаций, порядок режим/ровер, отсутствие кнопок маршрута и AI
в ручной ветке, локальный DCD на Riverside, Forest, Bamboo и собственном скане, fullscreen/выход.
В собственном скане проверены orbit, точки по клику, выбор, перенос, сохранение
и повторное открытие задания. Высотный срез визуально скрывает здания, оставляя
поверхность. Целый интерфейс больше не падает при выборе точки.
## Контрольное выполнение на Worker
Версионный пакет `6dbe040bea734bab`, 658 проверенных файлов,
SHA-256 `c89981345a5e49208980ef0340fb01d869fd6498839056b759b82703b46a8426`.
Установлен штатным `Install-RealtimeWorker.ps1`; rollback — прежний `03abe7cf43f3720b`.
Промежуточный `db51b92582dee23f` сохранён как история транспортного отказа.
Run `airun-0786e7551a1046aa894393cd62347ef6`, план
`aiplan-fbc2591c766f4209ba7fbb9182f1e255`, DCD-006 v020.
Две точки, длина задания 3,323 м на собственном городском скане.
Конвертер: 490 355 гауссов, 3 SH-полосы, 5,704 с, peak CPU memory 757 MB.
Декодированный collider: 52 467 вершин, 101 704 треугольника.
Видеопоток Worker показал ту же поверхность, модель и точки, что локальный редактор.
Итог: **goal-reached**, 14,117 с мира; путь 3,060 м; ошибка финиша 0,270 м
при допуске 0,4 м. 66 решений, 0 ошибок inference, p50 110 мс, p95 203 мс.
В журнале остановок только завершение цели. Счётчик столкновений не измерен.
Композиция `891904a1e31c9fc0ec21d6b80bc00de7b05c642f49c8fd714bb71a1c132c0a6c`.
Отчёт, подготовительный лог и evidence manifest сохранены вне Git в
`outputs/ai-polygon-2026-10-02/unified-simulation-evidence/` и на Worker.
## Граница приёмки
Короткое задание подтверждает интеграцию собственного SOG, локального плана,
Worker-физики и реальной AI-композиции. Это не приёмка всей карты, всех шести
локаций, динамических препятствий или полевого аппарата. Локальная ручная физика
пока использует прежний vehicle proxy; гусеничный контакт и масса не откалиброваны.
Следующий этап — серия повторяемых заданий с поворотами и препятствиями и отдельная
квалификация контакта. Исторические проверки Riverside остаются независимыми.
Финальная проверка: Worker service Running, active/editor-active отсутствуют,
во время локальной Bamboo-сцены active run = null и GPU reservations = 0.
Сохранены все 8 исходных Docker-служб. После финальных UI-правок повторно
прошли 10 архитектурных/симуляционных frontend-тестов и production build.

Some files were not shown because too many files have changed in this diff Show More