diff --git a/README.md b/README.md
index 636b5a11..d4240f4e 100644
--- a/README.md
+++ b/README.md
@@ -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
diff --git a/apps/control-station/package-lock.json b/apps/control-station/package-lock.json
index 454cfc4f..eac33007 100644
--- a/apps/control-station/package-lock.json
+++ b/apps/control-station/package-lock.json
@@ -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",
diff --git a/apps/control-station/package.json b/apps/control-station/package.json
index 233a0f67..e4963858 100644
--- a/apps/control-station/package.json
+++ b/apps/control-station/package.json
@@ -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",
diff --git a/apps/control-station/public/rover-scene/dcd006-v020-motion.glb b/apps/control-station/public/rover-scene/dcd006-v020-motion.glb
new file mode 100644
index 00000000..08ceb003
--- /dev/null
+++ b/apps/control-station/public/rover-scene/dcd006-v020-motion.glb
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e
+size 53447724
diff --git a/apps/control-station/public/rover-scene/dcd006-v020-motion.json b/apps/control-station/public/rover-scene/dcd006-v020-motion.json
new file mode 100644
index 00000000..2a95ada9
--- /dev/null
+++ b/apps/control-station/public/rover-scene/dcd006-v020-motion.json
@@ -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"
+}
diff --git a/apps/control-station/simulation-stream.html b/apps/control-station/simulation-stream.html
new file mode 100644
index 00000000..33652857
--- /dev/null
+++ b/apps/control-station/simulation-stream.html
@@ -0,0 +1,4 @@
+
+
Worker video
+
+
diff --git a/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx b/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx
index a4bb6bd1..cd9eb57c 100644
--- a/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx
+++ b/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx
@@ -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 ? {renderError}
: null}
- {renderStats ? (
+ {showRenderStats && renderStats ? (
(null);
+ useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
+ return ;
+}
+export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,children}:{
+ ids:string[];mounts:Map
;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void;
+ labels:Record;focusedId?:string|null;children:ReactNode;
+}){
+ return ({id,label:labels[id]??id}))}
+ renderPanel={id=>}>{children} ;
+}
diff --git a/apps/control-station/src/components/observation/ObservationLayoutSaveWindow.tsx b/apps/control-station/src/components/observation/ObservationLayoutSaveWindow.tsx
new file mode 100644
index 00000000..a6a7a20b
--- /dev/null
+++ b/apps/control-station/src/components/observation/ObservationLayoutSaveWindow.tsx
@@ -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
+ {onRemove&& } onClick={()=>{if(onRemove())onClose();}}>Удалить раскладку}
+ {onRemove?'Сохранить имя':'Сохранить'}
+ }>
+ setName(event.target.value)}
+ onKeyDown={event=>{if(event.key==='Enter'&&!event.nativeEvent.isComposing){event.preventDefault();save();}}}
+ description={onRemove?undefined:'Сохраняются выбранные камеры, слои и расположение окон. Недоступные устройства появятся при подключении.'}/>
+ ;
+}
diff --git a/apps/control-station/src/components/observation/ObservationPanelHeader.tsx b/apps/control-station/src/components/observation/ObservationPanelHeader.tsx
new file mode 100644
index 00000000..356dd74d
--- /dev/null
+++ b/apps/control-station/src/components/observation/ObservationPanelHeader.tsx
@@ -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(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 ;
+}
diff --git a/apps/control-station/src/components/observation/observation.css b/apps/control-station/src/components/observation/observation.css
new file mode 100644
index 00000000..98ebb763
--- /dev/null
+++ b/apps/control-station/src/components/observation/observation.css
@@ -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)); }
diff --git a/apps/control-station/src/components/simulation/AiCompositionFields.tsx b/apps/control-station/src/components/simulation/AiCompositionFields.tsx
index bd8e9fc1..14fe20d3 100644
--- a/apps/control-station/src/components/simulation/AiCompositionFields.tsx
+++ b/apps/control-station/src/components/simulation/AiCompositionFields.tsx
@@ -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
- Модули AI
+ {selection.selections.some(s=>s.module_id==="simulation-waypoint-mission")?<>
+ 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 }) =>
-
- 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,
}] });
- }} />
- )}
+ }} />)}
;
}
diff --git a/apps/control-station/src/components/simulation/AiConfiguration.tsx b/apps/control-station/src/components/simulation/AiConfiguration.tsx
new file mode 100644
index 00000000..059475c3
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiConfiguration.tsx
@@ -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([]);
+ const [picked,setPicked]=useState(null);
+ const [modal,setModal]=useState<'save'|AiProfile|null>(null);
+ const [busy,setBusy]=useState(false);
+ const [error,setError]=useState(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
+ Конфигурация AI
+
+ ({value:p.profile_id,
+ label:p.name+(changed&&p===current?' · изменён':''),
+ action:{label:`Редактировать профиль «${p.name}»`,icon: ,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:'Профиль недоступен.');}}}/>
+ } disabled={disabled||busy} onClick={()=>{setError(null);setModal('save');}}>Сохранить профиль
+
+
+ {modal&&setModal(null)} onSave={name=>void save(name)}
+ onRemove={modal==='save'?undefined:()=>void save(modal.name,true)}/>}
+ setError(null)}/>
+ ;
+}
diff --git a/apps/control-station/src/components/simulation/AiEditorRuntime.ts b/apps/control-station/src/components/simulation/AiEditorRuntime.ts
new file mode 100644
index 00000000..2b54ddc7
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiEditorRuntime.ts
@@ -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((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 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;
+ }
+}
diff --git a/apps/control-station/src/components/simulation/AiInferencePreview.tsx b/apps/control-station/src/components/simulation/AiInferencePreview.tsx
new file mode 100644
index 00000000..b0e92e5e
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiInferencePreview.tsx
@@ -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(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(`/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
+ {selected.kind==="points3d"?
}>
+
+ : }
+
+ Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
+ {selected.legend?.length?{selected.legend.map(c=>{c.label} )} :null}
+ {selected.kind==="points3d"?{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры :null}
+
+ ;
+}
diff --git a/apps/control-station/src/components/simulation/AiLocalPlanner.tsx b/apps/control-station/src/components/simulation/AiLocalPlanner.tsx
new file mode 100644
index 00000000..8812a57f
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiLocalPlanner.tsx
@@ -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(null);
+ const host = useRef(null), canvas = useRef(null);
+ const viewport = useRef(null), loadedPoints = useRef(initialPoints);
+ const [preferences] = usePlannerPreferences();
+ const runtime = useRef(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([]);
+ 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
+ {expanded ?
{headerActions}
: actionsHost ? createPortal(headerActions,actionsHost) : null}
+
+
{ready ? "Планирование на этом компьютере" : message}
+
{points.length} точек · первая — старт, последняя — финиш
+
+
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);}
+ }}>
+
+ {ready?
+ {points.some(p=>p.id===selected)?{
+ edit({type:"delete"});canvas.current?.focus({preventScroll:true});
+ }}> :null}
+ {setMode(v);runtime.current?.setAddMode(v==="add");}}
+ items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
+
:null}
+
+
{
+ 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});
+ }}>
+
{
+ 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);}}>
+ 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 ? {
+ 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);
+ }}>
+
+
+ {i===0?"Старт":i===markers.length-1?`Финиш · ${i}`:i}
+ {selected===m.id ? (["x","y","z"] as const).map((axis)=>m[axis] ? {
+ 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);
+ }}>
+ {axis.toUpperCase()} :null):null}
+ :null)}
+
+ {!ready && !error ?
:null}
+ {ready ? <>
`${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);}}/>
+ {error?
:null}>:null}
+ {error && !ready ?
{error}
setRetry(retry+1)}>Повторить загрузку :null}
+
+
+
;
+}
diff --git a/apps/control-station/src/components/simulation/AiPlanSaveWindow.tsx b/apps/control-station/src/components/simulation/AiPlanSaveWindow.tsx
new file mode 100644
index 00000000..fb7e5059
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiPlanSaveWindow.tsx
@@ -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 {if(!busy)onClose();}}
+ footer={{launch?"Сохранить и запустить":"Сохранить"} }>
+
+
onName(e.target.value)}/>
+ Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.
+
+ ;
+}
diff --git a/apps/control-station/src/components/simulation/AiProfileWindow.tsx b/apps/control-station/src/components/simulation/AiProfileWindow.tsx
new file mode 100644
index 00000000..cf79527c
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiProfileWindow.tsx
@@ -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 {if(!busy)onClose();}} footer={
+ {onRemove&& } disabled={busy} onClick={onRemove}>Удалить профиль}
+ onSave(name.trim())}>
+ {editing?'Сохранить имя':'Сохранить профиль'}
+ }>
+ setName(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!busy&&name.trim())onSave(name.trim());}}/>
+ ;
+}
diff --git a/apps/control-station/src/components/simulation/AiRouteOverlay.tsx b/apps/control-station/src/components/simulation/AiRouteOverlay.tsx
new file mode 100644
index 00000000..53abdc63
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiRouteOverlay.tsx
@@ -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) => `${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; 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(null);
+ const svg = useRef(null);
+ const drag = useRef(null);
+ const [size, setSize] = useState({ width: 0, height: 0 });
+ const [selected, setSelected] = useState(null);
+ const [mode, setMode] = useState<"view" | "add">("view");
+ const [clip, setClip] = useState(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, 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) => {
+ 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) => {
+ 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
+ {data && visible ?
e.preventDefault()}
+ onPointerDown={(e) => start(e)} onPointerMove={move} onPointerUp={end}
+ onPointerCancel={() => { drag.current = null; }}>
+ m.base))} />
+
+ {data.markers.map((m, i) => m.base && m.top ? start(e, m.id, "xy")}>
+
+
+ {i === 0 ? "Старт" : i === data.markers.length-1 ? `Финиш · ${i}` : i}
+ {editing && selected === m.id ? (["x", "y"] as const).map((axis) => {
+ const p = axis === "x" ? m.x_axis : m.y_axis;
+ return p ? start(e, m.id, axis)}>
+
+
+ : null;
+ }) : null}
+ : null)}
+ : null}
+ {editing && low != null && high != null && high > low ?
+ `${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 });
+ }} />
+
: null}
+ {editing ?
+
+
send({ action: "add", x: .5, y: .5 })}>Добавить waypoint
+
m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку
+
send({ action: "undo" })}>Отменить
+
send({ action: "home" })}>К началу маршрута
+
Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее
+ {error || draft?.error ?
{error ?? draft?.error}
: null}
+
: null}
+
;
+}
diff --git a/apps/control-station/src/components/simulation/AiRunActions.tsx b/apps/control-station/src/components/simulation/AiRunActions.tsx
index cb9cb652..03381aca 100644
--- a/apps/control-station/src/components/simulation/AiRunActions.tsx
+++ b/apps/control-station/src/components/simulation/AiRunActions.tsx
@@ -14,12 +14,12 @@ export function AiRunActions({ run, onChange }: { run: AiRun; onChange: (run: Ai
};
return <>
{!terminal ? <>
- command(run.state === "running" ? "pause" : "play")}>
- {run.state === "starting" ? "Подготовка…" : run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
-
+ {run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
+ : null}
} onClick={() => command("stop")}>Завершить симуляцию
> : null}
diff --git a/apps/control-station/src/components/simulation/AiRunReport.tsx b/apps/control-station/src/components/simulation/AiRunReport.tsx
new file mode 100644
index 00000000..6a0cd64a
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiRunReport.tsx
@@ -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 = {
+ "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
+ {available.length ? ({
+ id:run.run_id, icon: ,
+ 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: ,
+ action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`,
+ icon: ,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
+ onAction:()=>onRemove(run)},
+ }))}/> : В этой локации ещё нет прогонов.
}
+ ;
+}
+function RunDetails({run}:{run:AiRun}) {
+ if(!run.report)return {run.message ?? "Отчёт появится после завершения прогона."}
;
+ const report=run.report;
+ return
+
+ {outcomes[report.mission_outcome]}
+
+
+ {run.state==='failed'&&run.message?
Причина остановки {run.message} :null}
+
Задание {run.plan_display_name ?? run.plan?.name ?? "Без сохранённого задания"}
+
Ровер {run.robot?.name ?? "Не записан"}
+ {run.rover_configuration?
Масса / груз {run.rover_configuration.total_mass_kg} / {run.rover_configuration.settings.payload_mass_kg} кг :null}
+ {report.speed?<>
Скорость · заданная / пиковая {measured(report.speed.requested_max_mps,"м/с",3)} / {measured(report.speed.measured_max_mps,"м/с",3)}
+
Максимальное превышение / длительность {measured(report.speed.maximum_excess_mps,"м/с",4)} / {measured(report.speed.seconds_above_requested,"с",2)} >:null}
+
Цели после стартовой точки {report.waypoints_reached === null ? "Нет измерения" : `${report.waypoints_reached} / ${report.waypoint_count}`}
+
Пройдено {measured(report.distance_m, "м", 2)}
+
Время мира {measured(report.simulation_seconds, "с")}
+
До конечной цели {measured(report.goal_error_m, "м", 2)}
+
Решения AI / ошибки {report.inference_count} / {report.inference_errors}
+
Задержка AI · медиана / P95 {measured(report.inference_ms_p50, "мс", 0)} / {measured(report.inference_ms_p95, "мс", 0)}
+
Столкновения {report.collision_count === null ? "Учёт ещё не подключён" : report.collision_count}
+
+
Остановки после начала движения
+ {report.stops.length ?
{report.stops.map((stop) =>
+
{reasons[stop.reason] ?? stop.reason} {stop.events} · {stop.seconds.toFixed(1)} с
+ )} :
Переходов от движения к нулевой команде не записано.
}
+
Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.
+
+
Прогон {report.run_id}
+
Профиль ровера {report.robot_sha256 ?? "Не записан"}
+
Композиция AI {report.composition_sha256 ?? "Не запускалась"}
+
SHA-256 отчёта {report.report_sha256}
+
SHA-256 архива {report.manifest_sha256}
+
+
;
+}
diff --git a/apps/control-station/src/components/simulation/AiRunView.tsx b/apps/control-station/src/components/simulation/AiRunView.tsx
index 53465f53..1c7ce771 100644
--- a/apps/control-station/src/components/simulation/AiRunView.tsx
+++ b/apps/control-station/src/components/simulation/AiRunView.tsx
@@ -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 = {
"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
-
-
- {run.state !== "ready" && run.state !== "running" || preparingModels || pending ?
- {preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : STATES[run.state]}
- : null}
- {telemetry && !terminal && run.state !== "stopping" && run.state !== "disconnected" ?
- {run.state === "running" && !preparingModels && reason ? {reason} : null}
- Скорость: {Math.abs(telemetry.speed_mps).toFixed(2)} м/с
- Время мира: {(telemetry.simulation_time_ns / 1e9).toFixed(1)} с
- {run.state === "running" ? <>
- Симуляция: {telemetry.rtf.toFixed(2)}×
- Камера: {telemetry.sensor_fps.toFixed(1)} FPS
- AI: {telemetry.ai_hz.toFixed(1)} решений/с
- {telemetry.inference_ms !== null ? Inference: {telemetry.inference_ms.toFixed(0)} мс : null}
- {telemetry.frame_age_ms !== null ? Возраст кадра: {telemetry.frame_age_ms.toFixed(0)} мс : null}
- > : null}
-
: null}
-
- {connection}
-
+
+
+
Состояние
+
+ {preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : run.state === "running" && reason ? reason : STATES[run.state]}
+
+
+
+ {metrics.map(([label, value]) =>
+
{label} {value}
+ )}
+
{run.state === "failed" && run.message ? {run.message}
: null}
;
}
diff --git a/apps/control-station/src/components/simulation/AiSessionSection.tsx b/apps/control-station/src/components/simulation/AiSessionSection.tsx
new file mode 100644
index 00000000..c19ecf63
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiSessionSection.tsx
@@ -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(() => {
+ 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 ,
+ content: {children} }]} />;
+}
diff --git a/apps/control-station/src/components/simulation/AiSpatialPreview.tsx b/apps/control-station/src/components/simulation/AiSpatialPreview.tsx
new file mode 100644
index 00000000..92d44e59
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiSpatialPreview.tsx
@@ -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 ;
+}
diff --git a/apps/control-station/src/components/simulation/AiTaskSelect.tsx b/apps/control-station/src/components/simulation/AiTaskSelect.tsx
new file mode 100644
index 00000000..4342188a
--- /dev/null
+++ b/apps/control-station/src/components/simulation/AiTaskSelect.tsx
@@ -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(null);
+ const [name,setName]=useState("");
+ const [busy,setBusy]=useState(false);
+ const [error,setError]=useState(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 <>
+ ({value:plan.plan_id,label:aiPlanName(plan),
+ description:`${plan.points.length} точек · ${plan.length_m.toFixed(1)} м`,
+ action:{label:`Редактировать задание «${aiPlanName(plan)}»`,icon: ,
+ onAction:()=>{setName(aiPlanName(plan));setEditing(plan);setError(null);}},
+ })),
+ ]}/>
+ {if(!busy)setEditing(null);}}
+ footer={
+ } disabled={busy} onClick={()=>save(true)}>Удалить задание
+ save()}>Сохранить имя
+ }>
+ setName(e.target.value)}/>
+
+ {error?setError(null)}/>:null}
+ >;
+}
diff --git a/apps/control-station/src/components/simulation/AiWorldSetup.tsx b/apps/control-station/src/components/simulation/AiWorldSetup.tsx
index f6353541..7dee8b7c 100644
--- a/apps/control-station/src/components/simulation/AiWorldSetup.tsx
+++ b/apps/control-station/src/components/simulation/AiWorldSetup.tsx
@@ -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(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(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 }))}
- setRoute(e.target.value)} />
{
- 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));
}}>Сохранить старт и масштаб
{error ? setError(null)} /> : null}
diff --git a/apps/control-station/src/components/simulation/AiWorldStream.tsx b/apps/control-station/src/components/simulation/AiWorldStream.tsx
index ad00c9b8..ea40cb55 100644
--- a/apps/control-station/src/components/simulation/AiWorldStream.tsx
+++ b/apps/control-station/src/components/simulation/AiWorldStream.tsx
@@ -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 = 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(null);
- const video = useRef(null);
- const id = useId().replaceAll(":", "");
+ const frame = useRef(null), surface=useRef(null);
const { expanded, toggle } = useSimulationFullscreen(frame);
- const [state, setState] = useState<"connecting" | "live" | "failed" | "stalled">("connecting");
+ const [state, setState] = useState("connecting");
const [fps, setFps] = useState(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((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
: null}
{controls ? {controls}
: null}
-
-
label="Вид симуляции" size="dense" value={mode} onChange={changeCamera}
- items={[{ value: "follow", label: "За ровером", disabled: terminal },
- { value: "overview", label: "Обзор", disabled: terminal }, { value: "camera", label: "Камера AI", disabled: terminal }]} />
-
- {connectable ?
- {state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : "Ожидаем видео"}
- : null}
-
-
-
-
-
+
}
+ videoActions={ }>
+
+ {run?.request?.purpose === "planning" ? Планирование маршрута : label="Вид симуляции" value={mode} onChange={changeCamera} options={cameraOptions} disabled={terminal} />}
+ {run?.telemetry?.route_overlay && run.request?.purpose !== "planning" ? : null}
+
+ }
+ video={
+
+ {connectable ?
{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"} : null}
{cameraError ?
Не удалось переключить камеру.
: null}
-
-
-
+ {connectable&&endpoint&&state!=="failed"?
{setState(status);setFps(value);}}/>:null}
+ {!terminal && run && run.telemetry?.route_overlay ?
: null}
{terminal ?
{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}
- : connectable && (state === "failed" || state === "stalled") ?
-
Видеопоток прерван. Состояние симуляции показано выше.
-
setRevision((value) => value + 1)}>Подключить видео
+ : connectable && state === "failed" ?
+
Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.
+
{setState("connecting");setRevision((value) => value + 1);}}>Подключить видео
: null}
+
}/>
;
}
diff --git a/apps/control-station/src/components/simulation/EditorCamera.ts b/apps/control-station/src/components/simulation/EditorCamera.ts
new file mode 100644
index 00000000..88d2058d
--- /dev/null
+++ b/apps/control-station/src/components/simulation/EditorCamera.ts
@@ -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();
+ 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);
+ }
+}
diff --git a/apps/control-station/src/components/simulation/EditorTerrain.ts b/apps/control-station/src/components/simulation/EditorTerrain.ts
new file mode 100644
index 00000000..5de9a0f3
--- /dev/null
+++ b/apps/control-station/src/components/simulation/EditorTerrain.ts
@@ -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 = []; }
+}
diff --git a/apps/control-station/src/components/simulation/LocalManualScene.tsx b/apps/control-station/src/components/simulation/LocalManualScene.tsx
new file mode 100644
index 00000000..83a1895d
--- /dev/null
+++ b/apps/control-station/src/components/simulation/LocalManualScene.tsx
@@ -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(null), canvas=useRef(null);
+ const viewport=useRef(null);
+ const runtime=useRef(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
+ {expanded?
{headerActions}
:actionsHost?createPortal(headerActions,actionsHost):null}
+
+ {ready?"Ручное управление · локально":"Подготовка сцены"}
+
+
e.preventDefault()}>
+
+
+ {ready?Скорость: {Math.abs(speed).toFixed(2)} м/с
:null}
+ {!ready&&!error?
:null}
+ {error?{error}
{setError(null);setRetry(retry+1);}}>Повторить :null}
+
+
+
;
+}
diff --git a/apps/control-station/src/components/simulation/PlannerMarkers.ts b/apps/control-station/src/components/simulation/PlannerMarkers.ts
new file mode 100644
index 00000000..8bbf6d0e
--- /dev/null
+++ b/apps/control-station/src/components/simulation/PlannerMarkers.ts
@@ -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());}
+}
diff --git a/apps/control-station/src/components/simulation/PlannerSettings.tsx b/apps/control-station/src/components/simulation/PlannerSettings.tsx
new file mode 100644
index 00000000..25c1c9f9
--- /dev/null
+++ b/apps/control-station/src/components/simulation/PlannerSettings.tsx
@@ -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; 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(null);
+ const [error,setError] = useState(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) =>
+ set(group,key,v)}
+ formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
+ return {commit();onClose();}}>
+ {
+ 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;
+ }}>
+
+ {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)=>set("pivot",axis,v)}/> )}
+ > : section === "waypoint" ? <>
+ {range("waypoint","diameter","Диаметр",.05,3,.05,"м")}
+ {range("waypoint","height","Высота",.2,50,.1,"м")}
+ set("waypoint","color",v)}/>
+ {range("waypoint","opacity","Непрозрачность",.1,1,.05,"")}
+ {range("waypoint","frequency","Пульсация",0,3,.1,"Гц")}
+ Свечение
+ {range("waypoint","emission","Сила эмиссии",0,5,.1,"")}
+ set("waypoint","emissionColor",v)}/>
+ > : <>
+ Сдвиг камеры
+ Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.
+ {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,"×")}
+ Зум
+ {range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
+ Центр вращения
+ Шарик появляется в точке нажатия на время вращения.
+ {range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
+ set("navigation","centroidColor",v)}/>
+ {range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
+ >}
+ {error?setError(null)}/>:null}
+
+ ;
+}
diff --git a/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts b/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts
index 52f1bb3b..d9e68e46 100644
--- a/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts
+++ b/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts
@@ -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 = {
- 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 {
+ 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((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;
diff --git a/apps/control-station/src/components/simulation/RoverSettingsWindow.tsx b/apps/control-station/src/components/simulation/RoverSettingsWindow.tsx
new file mode 100644
index 00000000..67e23a2e
--- /dev/null
+++ b/apps/control-station/src/components/simulation/RoverSettingsWindow.tsx
@@ -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, label:string, min:number, max:number|undefined, step:number) =>
+ setDraft({...draft,[key]:e.target.value===""?NaN:Number(e.target.value)})}/>;
+ const valid=validRoverSettings(draft,robot);
+ return
+ setDraft(current=>({...defaultRoverSettings(robot,value.max_speed_mps),max_speed_mps:current.max_speed_mps}))}>Сбросить массу и нагрузку
+ onApply(draft)}>Применить
+ }>
+
+ {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)}
+
Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.
+
Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.
+ {manual?
В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.
:null}
+
Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.
+ {!valid?
Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.
:null}
+
+ ;
+}
diff --git a/apps/control-station/src/components/simulation/RoverTrackMotion.ts b/apps/control-station/src/components/simulation/RoverTrackMotion.ts
new file mode 100644
index 00000000..d31b4667
--- /dev/null
+++ b/apps/control-station/src/components/simulation/RoverTrackMotion.ts
@@ -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 ({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);
+ }
+ }
+}
diff --git a/apps/control-station/src/components/simulation/SimulationObservationDeck.tsx b/apps/control-station/src/components/simulation/SimulationObservationDeck.tsx
new file mode 100644
index 00000000..609293fc
--- /dev/null
+++ b/apps/control-station/src/components/simulation/SimulationObservationDeck.tsx
@@ -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(null);
+ const edited=presets.presets.find(p=>p.id===editing);
+ const [full,setFull]=useState(null);
+ const mounts=useRef(new Map());
+ 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
+
+ {effectiveFull&&
setFull(null)}>Все окна }
+
} aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Камеры и слои}>
+ {({close})=>
+ ({value:p.id,label:p.name,action:{label:`Редактировать раскладку «${p.name}»`,icon: ,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 show(id,checked)}/>;})}
+ {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);}}>Сохранить расположение
+
}
+
+ {toolbar}
+
+
{visible.length?
[source.id,source.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
+ {sources.filter(source=>visible.includes(source.id)).map(source=>createPortal(
+
+
{source.label}
+ {source.id==='video'&&videoActions}
+ setFull(value=>value===source.id?null:source.id)}>
+ show(source.id,false)}>
+
+ {source.id==='video'?video:preview&&
}
+ ,mounts.current.get(source.id)!,source.id))}
+ :
Все окна скрыты.
show('video',true)}>Показать симуляцию }
+ {saving&&
setSaving(false)} onSave={presets.save}/>}
+ {edited&&setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
+
+ ;
+}
diff --git a/apps/control-station/src/components/simulation/SimulationSourceImport.tsx b/apps/control-station/src/components/simulation/SimulationSourceImport.tsx
new file mode 100644
index 00000000..07116b6c
--- /dev/null
+++ b/apps/control-station/src/components/simulation/SimulationSourceImport.tsx
@@ -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(null);
+ const [error,setError]=useState(null);
+ const [pending,setPending]=useState([]);
+ 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;
+ 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 <>
+
+ {onClose();onPly();}}>Gaussian PLY
+ {onClose();setArchive(true);}}>Архив или папка LCC
+
+ {pending.map(p=>{p.name}
+
{onClose();setError(null);setProject(p);}}>Подготовка локации )}
+ {error?{error}
:null}
+
+ setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
+ {project?setProject(null)}>
+
+ {error??project.error??'Локация появится в общей библиотеке после подготовки.'}
+ {project.status==='failed'?void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку :null}
+
+ :null}
+ >;
+}
diff --git a/apps/control-station/src/components/simulation/SimulationUgvController.ts b/apps/control-station/src/components/simulation/SimulationUgvController.ts
index d3b5553c..5478b14d 100644
--- a/apps/control-station/src/components/simulation/SimulationUgvController.ts
+++ b/apps/control-station/src/components/simulation/SimulationUgvController.ts
@@ -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 {
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();
diff --git a/apps/control-station/src/components/simulation/SimulationViewTools.tsx b/apps/control-station/src/components/simulation/SimulationViewTools.tsx
new file mode 100644
index 00000000..6224e6b9
--- /dev/null
+++ b/apps/control-station/src/components/simulation/SimulationViewTools.tsx
@@ -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;children?:ReactNode}) {
+ const [prefs,update]=usePlannerPreferences();
+ const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState(null);
+ return <>
+
+ {children}
+ {try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>
+ setHelp(true)}>
+ {planning?setSettings(true)}> :null}
+
+
+ {settings?setSettings(false)}/>:null}
+ setHelp(false)} title="Управление сценой">
+ {planning?<>
+
ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.
+
Прокрутка — зум к курсору, в том числе в режиме добавления точек.
+
WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.
+
Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.
+ >:<>
WASD / стрелки — движение. Пробел — тормоз. R — к старту.
Мышь — обзор.
>}
+
+ {error?setError(null)}/>:null}
+ >;
+}
diff --git a/apps/control-station/src/components/simulation/WorkerVideo.tsx b/apps/control-station/src/components/simulation/WorkerVideo.tsx
new file mode 100644
index 00000000..f3d59722
--- /dev/null
+++ b/apps/control-station/src/components/simulation/WorkerVideo.tsx
@@ -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(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