Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4d4ea4cf8 | ||
|
|
c4622332e6 | ||
|
|
8c520ba32e | ||
|
|
a14158e483 | ||
|
|
31b74e4571 | ||
|
|
2e85d95c71 | ||
|
|
012286e972 | ||
|
|
7f87b5aa4d | ||
|
|
9a2ea5fc2e | ||
|
|
021b9f427f | ||
|
|
1f1d4a2807 | ||
|
|
bc915c01e1 | ||
|
|
6a89f809a4 | ||
|
|
140b6002e0 | ||
|
|
117e937906 | ||
|
|
8bf6571ce2 | ||
|
|
15a60e7e31 | ||
|
|
d0e5f90952 |
@@ -5,6 +5,41 @@ real device plugin investigates an owner-controlled XGRIDS/LixelKity K1 as a
|
||||
black-box sensor. Preserve the device, the host, the working LAN, raw evidence,
|
||||
and the boundary between Mission Core and vendor-specific integration code.
|
||||
|
||||
## Single working directory — owner requirement, 2026-10-08
|
||||
|
||||
The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50),
|
||||
in the owner rules dated 2026-10-08. The main [MISSIONCOR-1 architecture plan](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-1)
|
||||
links to that record for monorepo, storage, resource and live-only telemetry rules.
|
||||
|
||||
- Keep exactly one Mission Core checkout on the operator Mac:
|
||||
`NODEDC/NODEDC_MISSION_CORE`. Use commits and branches in that repository.
|
||||
Do not create sibling clones, worktrees, baseline copies, or task-specific
|
||||
Mission Core directories without a new explicit owner request.
|
||||
- The canonical service on port 8000 and its LaunchAgent use this checkout.
|
||||
Keep its existing runtime data under `.runtime/mission-core`; never merge
|
||||
retired worktree application states into that live data directory.
|
||||
- Keep private rover/CAD working materials under `private/engineering`,
|
||||
local engineering reports under `outputs`, and simulation qualification
|
||||
evidence under `.runtime/simulation-qualifications`. These are local data,
|
||||
not source files to add to normal Git. Preserve unique evidence when moving
|
||||
or retiring a workspace, and verify equality before removing duplicate files.
|
||||
- Bound generated build storage. Retain the two most recent intermediate Linux
|
||||
build-input packages per active build line; preserve separately designated
|
||||
qualified releases and required rollback artifacts. Do not accumulate a new
|
||||
full package after every iteration without retiring superseded intermediates.
|
||||
- Check disk space before large builds or captures. Keep task scratch work
|
||||
under `.runtime` and clean generated scratch at completion; do not scatter
|
||||
temporary project folders through the parent repository directory.
|
||||
- Other repositories, platform worktrees, infrastructure, DOC, workspace bridge,
|
||||
Site/SEO, BIM Viewer, Device Core, Design Guideline, and Gaussian Pipeline are
|
||||
separate ownership boundaries. Mission Core cleanup must not alter them.
|
||||
- Operator telemetry is live-only: bounded latest values in RAM, expiry and a
|
||||
daily reset. Do not reintroduce a local time-series database or persistent raw
|
||||
monitoring history on the Mac. Diagnostic logs must rotate. Future historical
|
||||
monitoring requires an explicitly provisioned separate service; simulation
|
||||
evidence and recordings have a separate lifecycle and must not be deleted as
|
||||
part of telemetry cleanup.
|
||||
|
||||
## Non-negotiable safety boundaries
|
||||
|
||||
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
|
||||
|
||||
@@ -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
|
||||
@@ -632,3 +638,22 @@ Real captures, projects, router metadata, serials, credentials, maps, images,
|
||||
and logs under `.runtime/`, canonical evidence roots and legacy `sessions/` are
|
||||
ignored by normal Git. Redacted manifests and SHA-256 inventories are committed;
|
||||
encrypted/replicated artifact storage remains a deployment decision.
|
||||
|
||||
## Local working directory
|
||||
|
||||
The operator installation uses one checkout, `NODEDC_MISSION_CORE`, including
|
||||
the service on `http://127.0.0.1:8000`. Work on source through commits and branches
|
||||
in this checkout; do not create sibling Mission Core worktrees or project copies.
|
||||
|
||||
- `.runtime/mission-core`: existing application data and location registry.
|
||||
- `.runtime/simulation-qualifications`: preserved simulation runs and evidence.
|
||||
- `private/engineering`: private DCD-006, camera-mount and K1 modelling materials.
|
||||
- `outputs`: local engineering reports and retained task outputs.
|
||||
- `.runtime/archived-app-state`: retired worktree data, separate from live state.
|
||||
|
||||
The 2026-10-08 consolidation preserved the operator sources in
|
||||
`archive/operator-before-consolidation-20261008` and the separate unfinished
|
||||
simulation sources in `work/simulation-before-consolidation-20261008`.
|
||||
These are source-preservation branches, not additional accepted deployments.
|
||||
The local move, hash-verification and cleanup receipts are retained under
|
||||
`.runtime/consolidation-20261008`. No remote branches were changed.
|
||||
|
||||
Generated
+11
-1
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,174 @@
|
||||
{
|
||||
"schema_version": "missioncore.rover-motion/v1",
|
||||
"source_scene": "DCD-006_rover_v020.blend",
|
||||
"source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79",
|
||||
"source_saved": false,
|
||||
"visual_sha256": "4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e",
|
||||
"forward_axis": "+X",
|
||||
"up_axis": "Y",
|
||||
"track_centres_m": {
|
||||
"L": 0.3425,
|
||||
"R": -0.3425
|
||||
},
|
||||
"track_width_m": 0.685,
|
||||
"shift_m": [
|
||||
-0.05350000038743019,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"length_m": 2.222,
|
||||
"pitch_m": 0.0505,
|
||||
"phase_m": 0.03069696662739778,
|
||||
"segments": [
|
||||
[
|
||||
"arc",
|
||||
0,
|
||||
0.060539054924808725,
|
||||
[
|
||||
-0.16593354688111153,
|
||||
0.32184557191629776,
|
||||
0.0655,
|
||||
2.3390854961098873
|
||||
]
|
||||
],
|
||||
[
|
||||
"line",
|
||||
0.060539054924808725,
|
||||
0.5760464371429339,
|
||||
[
|
||||
-0.15575880346026824,
|
||||
0.3865504758751169,
|
||||
0.9878611291422765,
|
||||
-0.1553395942113481,
|
||||
0.15533959421134813,
|
||||
0.9878611291422766
|
||||
]
|
||||
],
|
||||
[
|
||||
"arc",
|
||||
0.6365854920677426,
|
||||
0.15172294911931034,
|
||||
[
|
||||
0.40182697,
|
||||
0.22413776,
|
||||
0.07382606110411796,
|
||||
1.4148251155784564
|
||||
]
|
||||
],
|
||||
[
|
||||
"line",
|
||||
0.7883084411870529,
|
||||
0.1629407568053742,
|
||||
[
|
||||
0.46102862009488454,
|
||||
0.18003048254840684,
|
||||
-0.5974486081464921,
|
||||
-0.8019072020027126,
|
||||
0.8019072020027126,
|
||||
-0.5974486081464921
|
||||
]
|
||||
],
|
||||
[
|
||||
"arc",
|
||||
0.9512491979924271,
|
||||
0.06094648310379254,
|
||||
[
|
||||
0.31115497,
|
||||
0.0885,
|
||||
0.0655,
|
||||
-0.6403156687217281
|
||||
]
|
||||
],
|
||||
[
|
||||
"line",
|
||||
1.0121956810962196,
|
||||
0.7185584980197575,
|
||||
[
|
||||
0.31115497,
|
||||
0.022999999999999993,
|
||||
-1.0,
|
||||
0.0,
|
||||
-0.0,
|
||||
-1.0
|
||||
]
|
||||
],
|
||||
[
|
||||
"arc",
|
||||
1.730754179115977,
|
||||
0.15545137821999958,
|
||||
[
|
||||
-0.40740352801975754,
|
||||
0.0885,
|
||||
0.0655,
|
||||
-1.5707963267948966
|
||||
]
|
||||
],
|
||||
[
|
||||
"line",
|
||||
1.8862055573359766,
|
||||
0.33579444266402353,
|
||||
[
|
||||
-0.45291987081346463,
|
||||
0.1356010885085021,
|
||||
0.719100587916063,
|
||||
0.6949059968504895,
|
||||
-0.6949059968504895,
|
||||
0.719100587916063
|
||||
]
|
||||
]
|
||||
],
|
||||
"link_count": 44,
|
||||
"wheels": [
|
||||
{
|
||||
"node": "R_SPIN_rear_lower",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "R_SPIN_middle_lower",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "R_SPIN_rear_upper",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "R_SPIN_front_lower",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "R_SPIN_DRIVE",
|
||||
"radius_m": 0.07233592163526643
|
||||
},
|
||||
{
|
||||
"node": "L_SPIN_rear_lower",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "L_SPIN_middle_lower",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "L_SPIN_rear_upper",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "L_SPIN_front_lower",
|
||||
"radius_m": 0.0625
|
||||
},
|
||||
{
|
||||
"node": "L_SPIN_DRIVE",
|
||||
"radius_m": 0.07233592163526643
|
||||
}
|
||||
],
|
||||
"dimensions_m": [
|
||||
1.1630001068115234,
|
||||
0.9049999713897705,
|
||||
0.7378441095352173
|
||||
],
|
||||
"minimum_m": [
|
||||
-0.5814999938011169,
|
||||
-0.45249998569488525,
|
||||
-0.003844098187983036
|
||||
],
|
||||
"method": "44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; no track contact dynamics"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<!doctype html>
|
||||
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Worker video</title></head>
|
||||
<body><video id="worker-video" autoplay muted playsinline></video><audio id="worker-audio" muted></audio>
|
||||
<script type="module" src="/src/components/simulation/streamFrame.ts"></script></body></html>
|
||||
@@ -265,6 +265,8 @@ LaboratoryMetricEvidenceSceneHandle,
|
||||
showCurrentIncrement: boolean;
|
||||
showLocalSurface: boolean;
|
||||
showRollingMap: boolean;
|
||||
showReferenceGeometry?: boolean;
|
||||
showRenderStats?: boolean;
|
||||
showLowStep?: boolean;
|
||||
pointSemanticClassIds?: readonly (number | null)[];
|
||||
semanticClasses?: readonly RecordedEvidenceSemanticClass[];
|
||||
@@ -287,6 +289,8 @@ LaboratoryMetricEvidenceSceneHandle,
|
||||
showLocalSurface,
|
||||
showRollingMap,
|
||||
showLowStep = true,
|
||||
showReferenceGeometry = true,
|
||||
showRenderStats = true,
|
||||
pointSemanticClassIds,
|
||||
semanticClasses,
|
||||
semanticPalette,
|
||||
@@ -746,6 +750,7 @@ LaboratoryMetricEvidenceSceneHandle,
|
||||
if (!host || !content) return;
|
||||
clearGroup(content);
|
||||
|
||||
if (!showReferenceGeometry) { requestRenderRef.current(); return; }
|
||||
const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM;
|
||||
const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2;
|
||||
const corridorMesh = new THREE.Mesh(
|
||||
@@ -806,6 +811,7 @@ LaboratoryMetricEvidenceSceneHandle,
|
||||
content.add(grid);
|
||||
requestRenderRef.current();
|
||||
}, [
|
||||
showReferenceGeometry,
|
||||
corridor.forwardLengthM,
|
||||
corridor.halfWidthM,
|
||||
corridor.rearMarginM,
|
||||
@@ -912,7 +918,7 @@ LaboratoryMetricEvidenceSceneHandle,
|
||||
{renderError ? <p>{renderError}</p> : null}
|
||||
</div>
|
||||
<div className="laboratory-metric-evidence-scene__legend">
|
||||
{renderStats ? (
|
||||
{showRenderStats && renderStats ? (
|
||||
<span
|
||||
data-decision="performance"
|
||||
title="CPU-время отправки последнего WebGL render pass; это не GPU timer. В покое сцена не перерисовывается."
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import {useLayoutEffect,useRef,type ReactNode} from 'react';
|
||||
import {DockLayout,type DockTree} from '@nodedc/ui-react';
|
||||
import {observationTree,type ObservationLayout} from '../../core/fleet/observationLayout';
|
||||
|
||||
export function ObservationMount({element,className='observation-mount'}:{element:HTMLElement;className?:string}){
|
||||
const ref=useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
|
||||
return <div ref={ref} className={className}/>;
|
||||
}
|
||||
export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,children}:{
|
||||
ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void;
|
||||
labels:Record<string,string>;focusedId?:string|null;children:ReactNode;
|
||||
}){
|
||||
return <DockLayout tree={observationTree(layout,ids)} onTreeChange={onTreeChange}
|
||||
focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id}))}
|
||||
renderPanel={id=><ObservationMount element={mounts.get(id)!}/>}>{children}</DockLayout>;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
|
||||
export function ObservationLayoutSaveWindow({onClose,onSave,initialName='',onRemove}:{onClose:()=>void;onSave:(name:string)=>boolean;initialName?:string;onRemove?:()=>boolean}) {
|
||||
const [name,setName]=useState(initialName);
|
||||
const save=()=>{if(name.trim()&&onSave(name))onClose();};
|
||||
return <Window open title={onRemove?'Редактировать раскладку':'Сохранить расположение'} size="sm" onClose={onClose}
|
||||
footer={<WindowFooterActions>
|
||||
{onRemove&&<Button icon={<Icon name="trash"/>} onClick={()=>{if(onRemove())onClose();}}>Удалить раскладку</Button>}
|
||||
<Button variant="primary" disabled={!name.trim()} onClick={save}>{onRemove?'Сохранить имя':'Сохранить'}</Button>
|
||||
</WindowFooterActions>}>
|
||||
<TextField label="Название раскладки" value={name} maxLength={120} onChange={event=>setName(event.target.value)}
|
||||
onKeyDown={event=>{if(event.key==='Enter'&&!event.nativeEvent.isComposing){event.preventDefault();save();}}}
|
||||
description={onRemove?undefined:'Сохраняются выбранные камеры, слои и расположение окон. Недоступные устройства появятся при подключении.'}/>
|
||||
</Window>;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import {useLayoutEffect,useRef,type ReactNode} from 'react';
|
||||
|
||||
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
|
||||
export function ObservationPanelHeader({children}:{children:ReactNode}) {
|
||||
const ref=useRef<HTMLElement>(null);
|
||||
useLayoutEffect(()=>{
|
||||
const header=ref.current!;
|
||||
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
|
||||
measure();const observer=new ResizeObserver(measure);observer.observe(header);
|
||||
return()=>observer.disconnect();
|
||||
},[]);
|
||||
return <header ref={ref} className="observation-panel__header">{children}</header>;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
|
||||
.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
|
||||
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
|
||||
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
|
||||
.observation-toolbar h2, .observation-panel h3 { margin:0; }
|
||||
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
|
||||
.observation-actions { flex-shrink:0; }
|
||||
.observation-deck { flex:1; min-height:0; min-width:0; }
|
||||
.observation-layout { position:relative; height:100%; min-height:0; min-width:0; }
|
||||
.observation-layout__slot { height:100%; min-height:0; }
|
||||
.observation-layout__panel { position:absolute; min-height:0; min-width:0; }
|
||||
.observation-layout__panel:has(.is-dragging) { z-index:var(--nodedc-layer-panel); }
|
||||
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
|
||||
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
|
||||
.observation-panel__surface > .observation-mount { flex:1; }
|
||||
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
|
||||
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
|
||||
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
|
||||
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
|
||||
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
|
||||
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
|
||||
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
|
||||
.observation-header-slot:has(> div:empty) { display:none; }
|
||||
.observation-layer-select { min-width:0; max-width:120px; }
|
||||
.observation-layer-select button { max-width:100%; }
|
||||
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
|
||||
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
|
||||
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
|
||||
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
|
||||
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
|
||||
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
|
||||
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
|
||||
.observation-layer > * { min-width:0; width:100%; }
|
||||
.observation-layer > .nodedc-switch { text-align:left; }
|
||||
.observation-empty { display:grid; place-content:center; height:100%; text-align:center; }
|
||||
.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; }
|
||||
@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } }
|
||||
|
||||
.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; }
|
||||
|
||||
/* Transform the live panel as one item; reveal it across nested split boundaries. */
|
||||
.observation-panel-drag { position:relative; height:100%; min-height:0; }
|
||||
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
|
||||
.observation-split:has(.observation-panel-drag.is-dragging),
|
||||
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
|
||||
@container (max-width:340px) {
|
||||
.observation-panel__header { flex-wrap:wrap; }
|
||||
.observation-panel__title { min-width:80px; }
|
||||
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
|
||||
}
|
||||
|
||||
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FieldFrame, Select } from "@nodedc/ui-react";
|
||||
import { InspectorSelectField } from "@nodedc/ui-react";
|
||||
import type { AiModules, AiSelection } from "../../core/simulation/aiPolygon";
|
||||
|
||||
const labels = { segmentation: "Поверхность", detection: "Объекты", geometry: "Рельеф",
|
||||
@@ -8,10 +8,13 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
|
||||
modules: AiModules; selection: AiSelection; disabled: boolean; onChange: (value: AiSelection) => void;
|
||||
}) {
|
||||
return <section className="ai-polygon__section" aria-label="Композиция AI">
|
||||
<h3>Модули AI</h3>
|
||||
{selection.selections.some(s=>s.module_id==="simulation-waypoint-mission")?<>
|
||||
<InspectorSelectField label="Профиль движения" disabled={disabled} value={String(selection.selections.find(s=>s.module_id==="simulation-waypoint-mission")?.parameters.environment??"park")}
|
||||
options={[{value:"natural",label:"Природа · пересечённая местность"},{value:"park",label:"Парк · дорожки"},{value:"urban",label:"Город · тротуары"}]}
|
||||
onChange={environment=>onChange({...selection,selections:selection.selections.map(s=>s.module_id==="simulation-waypoint-mission"?{...s,parameters:{...s.parameters,environment}}:s)})}/>
|
||||
</>:null}
|
||||
{modules.catalog.groups.filter(({ modules: options }) => options.length > 0).map(({ group, modules: options }) =>
|
||||
<FieldFrame key={group} label={labels[group]}>
|
||||
<Select label={`Модуль: ${labels[group]}`} disabled={disabled}
|
||||
<InspectorSelectField key={group} label={labels[group]} disabled={disabled}
|
||||
value={selection.selections.find((row) => row.group === group)?.module_id ?? ""}
|
||||
options={options.map((module) => ({ value: module.moduleId, label: module.label }))}
|
||||
onChange={(value) => {
|
||||
@@ -20,7 +23,6 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
|
||||
onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), {
|
||||
group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults,
|
||||
}] });
|
||||
}} />
|
||||
</FieldFrame>)}
|
||||
}} />)}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Button,Icon,InspectorSelectField,ToastStack} from '@nodedc/ui-react';
|
||||
import type {AiModules,AiSelection} from '../../core/simulation/aiPolygon';
|
||||
import {createAiProfile,fetchAiProfiles,sameAiIntent,updateAiProfile,type AiProfile} from '../../core/simulation/aiProfiles';
|
||||
import {currentSelection} from '../../core/simulation/runConfiguration';
|
||||
import {AiCompositionFields} from './AiCompositionFields';
|
||||
import {AiProfileWindow} from './AiProfileWindow';
|
||||
|
||||
export function AiConfiguration({modules,selection,disabled,onChange}: {
|
||||
modules:AiModules;selection:AiSelection;disabled:boolean;onChange:(selection:AiSelection)=>void;
|
||||
}) {
|
||||
const [profiles,setProfiles]=useState<AiProfile[]>([]);
|
||||
const [picked,setPicked]=useState<string|null>(null);
|
||||
const [modal,setModal]=useState<'save'|AiProfile|null>(null);
|
||||
const [busy,setBusy]=useState(false);
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
useEffect(()=>{let active=true;void fetchAiProfiles().then(rows=>{if(active)setProfiles(rows);})
|
||||
.catch(e=>{if(active)setError(e.message);});return()=>{active=false;};},[]);
|
||||
const current=picked===null?profiles.find(p=>sameAiIntent(p.composition,selection)):profiles.find(p=>p.profile_id===picked);
|
||||
const changed=!!current&&!sameAiIntent(current.composition,selection);
|
||||
const accept=(value:AiProfile)=>setProfiles(rows=>value.removed?rows.filter(p=>p.profile_id!==value.profile_id)
|
||||
:[...rows.filter(p=>p.profile_id!==value.profile_id),value].sort((a,b)=>a.name.localeCompare(b.name)));
|
||||
const save=async(name:string,removed=false)=>{
|
||||
if(!modal||busy)return;setBusy(true);setError(null);
|
||||
try {
|
||||
const editing=modal==='save'?null:modal;
|
||||
const composition=editing?undefined:currentSelection(selection,modules);
|
||||
const value=editing?await updateAiProfile(editing,{name,removed})
|
||||
:current&&name===current.name?await updateAiProfile(current,{composition})
|
||||
:await createAiProfile(name,composition!);
|
||||
accept(value);setModal(null);
|
||||
if(!editing){setPicked(value.profile_id);onChange(value.composition);}
|
||||
if(removed&&picked===value.profile_id)setPicked(null);
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');
|
||||
void fetchAiProfiles().then(setProfiles).catch(()=>undefined);
|
||||
}finally{setBusy(false);}
|
||||
};
|
||||
return <section className="ai-polygon__configuration-column" aria-label="Конфигурация AI">
|
||||
<h3>Конфигурация AI</h3>
|
||||
<div className="ai-polygon__profile-row">
|
||||
<InspectorSelectField label="Профиль AI" value={current?.profile_id??''} disabled={disabled||busy}
|
||||
options={[{value:'',label:'Своя конфигурация'},...profiles.map(p=>({value:p.profile_id,
|
||||
label:p.name+(changed&&p===current?' · изменён':''),
|
||||
action:{label:`Редактировать профиль «${p.name}»`,icon:<Icon name="edit"/>,disabled:disabled||busy,
|
||||
onAction:()=>{setError(null);setModal(p);}}}))]}
|
||||
onChange={id=>{if(!id){setPicked('');return;}const value=profiles.find(p=>p.profile_id===id);if(!value)return;
|
||||
try{onChange(currentSelection(value.composition,modules));setPicked(id);setError(null);}
|
||||
catch(e){setError(e instanceof Error?e.message:'Профиль недоступен.');}}}/>
|
||||
<Button icon={<Icon name="save"/>} disabled={disabled||busy} onClick={()=>{setError(null);setModal('save');}}>Сохранить профиль</Button>
|
||||
</div>
|
||||
<AiCompositionFields modules={modules} selection={selection} disabled={disabled||busy} onChange={onChange}/>
|
||||
{modal&&<AiProfileWindow key={modal==='save'?'save':modal.profile_id} editing={modal!=='save'} busy={busy}
|
||||
initialName={modal==='save'?current?.name??'':modal.name} onClose={()=>setModal(null)} onSave={name=>void save(name)}
|
||||
onRemove={modal==='save'?undefined:()=>void save(modal.name,true)}/>}
|
||||
<ToastStack items={error?[{id:'ai-profile',tone:'error',title:'Профиль AI не сохранён',description:error}]:[]}
|
||||
onDismiss={()=>setError(null)}/>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
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[] = [];
|
||||
private route: number[][] = [];
|
||||
clip = Infinity;
|
||||
height: [number, number] = [0, 1];
|
||||
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
|
||||
private onProject: (markers: EditorMarker[]) => void,
|
||||
private onRouteProject: (points: ScreenPoint[]) => void = () => undefined) {
|
||||
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.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
|
||||
this.onProject(this.points.map((p) => {
|
||||
const [x,y,z] = toEditor(p.position);
|
||||
return { id:p.id, base:this.project(x,y,z), top:this.project(x,y+this.preferences.waypoint.height,z),
|
||||
x:this.project(x+this.annotations.axisLength,y,z), y:this.project(x,y+this.annotations.axisLength,z), z:this.project(x,y,z+this.annotations.axisLength) };
|
||||
}));
|
||||
}
|
||||
});
|
||||
app.start(); this.home();
|
||||
}
|
||||
async load() {
|
||||
const scene = localScene(this.cache);
|
||||
await this.terrain.load(scene.collision.meshUrl!, this.abort.signal, scene.transforms.worldFromCollision);
|
||||
if (this.disposed) return;
|
||||
this.height = [this.terrain.bounds.min.y, this.terrain.bounds.max.y];
|
||||
if (this.height[1] <= this.height[0]) this.height = [this.height[0]-.5,this.height[1]+.5];
|
||||
const asset = new Asset("Route editor", "gsplat", { url: scene.visual.streamedSogUrl! });
|
||||
this.asset = asset;
|
||||
await new Promise<void>((resolve,reject) => {
|
||||
asset.once("error", (e: string) => reject(new Error(e)));
|
||||
asset.ready(() => resolve()); this.app.assets.add(asset); this.app.assets.load(asset);
|
||||
});
|
||||
if (this.disposed) { asset.unload(); return; }
|
||||
this.scan.addComponent("gsplat", { asset, unified: true });
|
||||
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
|
||||
uniform float editorClip;
|
||||
void modifySplatCenter(inout vec3 center) {}
|
||||
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
|
||||
void modifySplatColor(vec3 center, inout vec4 color) {
|
||||
// Unified work-buffer modifiers receive the calibrated world center.
|
||||
if (center.y > editorClip) color.a = 0.0;
|
||||
}` });
|
||||
this.setPreferences(this.preferences);
|
||||
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
|
||||
this.setClip(Infinity); this.dirty = true;
|
||||
}
|
||||
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
|
||||
top() {this.controls.top((this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor));this.syncCamera();this.dirty=true;}
|
||||
setPoints(points: AiWaypoint[]) { this.points = points; this.annotations.set(points,this.selected,this.preferences);this.dirty = true; }
|
||||
setSelected(id: string|null) {this.selected=id;this.annotations.set(this.points,id,this.preferences);this.dirty=true;}
|
||||
setPreferences(preferences: PlannerPreferences) {
|
||||
this.controls.navigation=preferences.navigation;
|
||||
this.preferences=preferences;this.annotations.set(this.points,this.selected,preferences);
|
||||
const profile=QUALITY_PROFILES[preferences.quality];
|
||||
this.app.scene.gsplat.splatBudget=profile.splatBudget;
|
||||
this.app.graphicsDevice.maxPixelRatio=Math.min(window.devicePixelRatio||1,profile.pixelRatio);
|
||||
if(this.scan.gsplat) {
|
||||
Object.assign(this.scan.gsplat,{lodBaseDistance:profile.lodBaseDistance,lodMultiplier:profile.lodMultiplier,lodRangeMin:profile.lodRangeMin,lodRangeMax:profile.lodRangeMax});
|
||||
}
|
||||
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
|
||||
}
|
||||
setClip(height: number) {
|
||||
this.clip = height;
|
||||
if (this.scan.gsplat) {
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
|
||||
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
|
||||
}
|
||||
this.dirty = true;
|
||||
}
|
||||
setNavigation(enabled: boolean) {
|
||||
this.controls.setNavigation(enabled);
|
||||
}
|
||||
setAddMode(add: boolean) { this.controls.setAddMode(add); }
|
||||
private syncCamera() {
|
||||
const { position:p, quaternion:q } = this.controls.camera;
|
||||
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
|
||||
}
|
||||
home() {
|
||||
const first = this.points[0]?.position ?? [...this.cache.world.settings.spawn_xy, this.cache.world.settings.ground_z];
|
||||
this.controls.home(toEditor(first)); this.syncCamera(); this.dirty = true;
|
||||
}
|
||||
pick(x: number,y: number) {
|
||||
const width = this.canvas.clientWidth, height = this.canvas.clientHeight;
|
||||
const from = this.camera.camera!.screenToWorld(x*width,y*height,.05);
|
||||
const to = this.camera.camera!.screenToWorld(x*width,y*height,2000);
|
||||
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip);
|
||||
return hit ? toMission(hit.toArray()) : null;
|
||||
}
|
||||
pickWaypoint(x:number,y:number) {
|
||||
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
|
||||
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
|
||||
const direction=[to.x-from.x,to.y-from.y,to.z-from.z];
|
||||
let nearest=Infinity, id:string|null=null;
|
||||
for(const point of this.points) {
|
||||
const t=waypointHit([from.x,from.y,from.z],direction,toEditor(point.position),this.preferences.waypoint.diameter/2,this.preferences.waypoint.height);
|
||||
if(t!==null && t<nearest){nearest=t;id=point.id;}
|
||||
}
|
||||
return id;
|
||||
}
|
||||
move(point: AiWaypoint, x: number, y: number, axis: WaypointAxis) {
|
||||
const p = toEditor(point.position);
|
||||
const from = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
|
||||
const to = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
|
||||
const hit = dragWaypoint([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],p,axis);
|
||||
if (!hit) return null;
|
||||
if (axis !== "xz") return toMission(hit);
|
||||
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip);
|
||||
return ground ? toMission(ground.toArray()) : null;
|
||||
}
|
||||
private project(x:number,y:number,z:number): ScreenPoint {
|
||||
const point = this.camera.camera!.worldToScreen(new Vec3(x,y,z));
|
||||
return point.z > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
|
||||
}
|
||||
dispose() {
|
||||
this.disposed = true;
|
||||
this.controls.dispose();
|
||||
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
|
||||
this.annotations.dispose();
|
||||
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { lazy, Suspense, useEffect, useState } from "react";
|
||||
import { LoadingRegion } from "@nodedc/ui-react";
|
||||
import { polygonRequest } from "../../core/simulation/aiPolygon";
|
||||
const SpatialPreview=lazy(()=>import("./AiSpatialPreview").then(m=>({default:m.AiSpatialPreview})));
|
||||
export interface InferencePreview {
|
||||
frame_id:number;simulation_time_ns:number;received_at:string;environment:"park"|"natural"|"urban";
|
||||
layers:({id:string;label:string;ports?:string[];legend?:{class_id:number;label:string;color:string}[]} & (
|
||||
{kind?:"image";jpeg:string} | {kind:"points3d";points:[number,number,number][];source_count:number;frame:string}
|
||||
))[];
|
||||
}
|
||||
export function useInferencePreview(runId:string|undefined,active:boolean) {
|
||||
const [preview,setPreview]=useState<InferencePreview|null>(null);
|
||||
useEffect(()=>{
|
||||
setPreview(null);if(!runId || !active)return;
|
||||
const abort=new AbortController();let timer=0;
|
||||
const poll=async()=>{
|
||||
try {
|
||||
if(document.visibilityState==="visible") {
|
||||
const value=await polygonRequest<InferencePreview|null>(`/runs/${runId}/inference-preview`,{signal:abort.signal});
|
||||
if(!abort.signal.aborted)setPreview(value);
|
||||
}
|
||||
} catch { /* Main status owns connection errors; retain the dated last frame. */ }
|
||||
if(!abort.signal.aborted)timer=window.setTimeout(()=>void poll(),500);
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[runId,active]);
|
||||
return preview;
|
||||
}
|
||||
export function AiInferencePreview({preview,layer}:{preview:InferencePreview;layer:string}) {
|
||||
const selected=preview.layers.find(p=>p.id===layer);
|
||||
if(!selected)return null;
|
||||
return <div className="ai-inference-preview" aria-label={`Результат AI: ${selected.label}`}>
|
||||
{selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}>
|
||||
<SpatialPreview points={selected.points} label={selected.label}/>
|
||||
</Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>}
|
||||
<div className="ai-inference-preview__caption">
|
||||
Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
|
||||
{selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null}
|
||||
{selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null}
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { PreparedRoute } from "../../core/simulation/routePreparation";
|
||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
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, preparedRoute=null }: {
|
||||
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
|
||||
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
|
||||
}) {
|
||||
const markerSvg=useRef<SVGSVGElement>(null);
|
||||
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
|
||||
const viewport = useRef<HTMLDivElement>(null), loadedPoints = useRef(initialPoints);
|
||||
const [preferences] = usePlannerPreferences();
|
||||
const runtime = useRef<AiEditorRuntime | null>(null);
|
||||
const { expanded, toggle } = useSimulationFullscreen(host);
|
||||
const [ready, setReady] = useState(false), [retry,setRetry] = useState(0);
|
||||
const { cache,error,setError } = useLocalScene(world,retry);
|
||||
const [editing,edit] = useReducer(editWaypoints,initialPoints,waypointEditing);
|
||||
const {points,selected,sequence} = editing;
|
||||
const press=useRef<{id:number;x:number;y:number}|null>(null);
|
||||
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
|
||||
const [viewMode,setViewMode]=useState<"3d"|"top">("3d");
|
||||
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
||||
const [mode,setMode] = useState<"view" | "add">("view");
|
||||
const [clip,setClip] = useState(Infinity);
|
||||
const draftId = useRef(crypto.randomUUID().replaceAll("-",""));
|
||||
const drag = useRef<{ point: AiWaypoint; axis: WaypointAxis; offset: number[] } | null>(null);
|
||||
const callback = useRef(onDraft); callback.current = onDraft;
|
||||
useEffect(() => {
|
||||
if (cache?.status !== "ready" || !canvas.current) return;
|
||||
let active = true;
|
||||
setReady(false); setError(null); setClip(Infinity);
|
||||
let view: AiEditorRuntime;
|
||||
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
|
||||
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?.setRoute(preparedRoute?.preview_xyz??[]);
|
||||
if(preparedRoute && ready){runtime.current?.top();setViewMode("top");}
|
||||
},[preparedRoute?.sha256,ready]);
|
||||
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
|
||||
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
|
||||
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
|
||||
useEffect(()=>{
|
||||
if(loadedPoints.current === initialPoints) return;
|
||||
loadedPoints.current=initialPoints;
|
||||
edit({type:"load",points:initialPoints});
|
||||
},[initialPoints]);
|
||||
const add = (x:number,y:number) => {
|
||||
if (points.length >= 33) { setError("В задании может быть до 33 точек."); return; }
|
||||
const position = runtime.current?.pick(x,y);
|
||||
if (!position) { setError("Под курсором нет доступной поверхности. Измените ракурс или срез."); return; }
|
||||
const point = { id:crypto.randomUUID().replaceAll("-","").slice(0,16),position };
|
||||
edit({type:"replace",points:[...points,point],selected:point.id});
|
||||
};
|
||||
const position = (e: { clientX:number;clientY:number }) => {
|
||||
const rect = canvas.current!.getBoundingClientRect();
|
||||
return [(e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height];
|
||||
};
|
||||
const progress = cache ? Object.values(cache.files) : [];
|
||||
const bytes = progress.reduce((n,f)=>n+f.uploaded_bytes,0), total = progress.reduce((n,f)=>n+f.byte_length,0);
|
||||
const message = cache?.status === "uploading" ? `Копируем сцену на диск · ${Math.round(bytes/Math.max(1,total)*100)}%`
|
||||
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
|
||||
return <div className="ai-polygon__stage" ref={host}>
|
||||
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
|
||||
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
|
||||
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
|
||||
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p></div>
|
||||
<div className="ai-polygon__viewer">
|
||||
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
|
||||
onKeyDown={(e)=>{
|
||||
const editable=!!(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"],.nodedc-workspace-window');
|
||||
const action=waypointShortcut(e,editable);
|
||||
if(!busy && ready && !drag.current && action){e.preventDefault();edit({type:action});setError(null);}
|
||||
}}>
|
||||
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning>
|
||||
{ready?<div className="ai-local-editor__tools nodedc-scene-controls" inert={busy}>
|
||||
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
|
||||
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
|
||||
}}><Icon name="trash"/></IconButton>:null}
|
||||
{preparedRoute?<SegmentedControl label="Ракурс маршрута" value={viewMode}
|
||||
items={[{value:"3d",label:"3D"},{value:"top",label:"Вид сверху"}]}
|
||||
onChange={v=>{setViewMode(v);if(v==="top")runtime.current?.top();else runtime.current?.home();}}/>:null}
|
||||
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
|
||||
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
|
||||
</div>:null}
|
||||
</SimulationViewTools>
|
||||
<div className="ai-local-editor__surface"
|
||||
onPointerDownCapture={(e)=>{
|
||||
if(e.target!==canvas.current || e.button!==0 || busy || !ready)return;
|
||||
const id=runtime.current?.pickWaypoint(...position(e) as [number,number]);
|
||||
if(!id)return;
|
||||
e.preventDefault();e.stopPropagation();press.current=null;
|
||||
canvas.current?.focus({preventScroll:true});edit({type:"select",id});
|
||||
const base=markers.find(m=>m.id===id)?.base;
|
||||
if(!base)return;
|
||||
edit({type:"begin"});
|
||||
drag.current={point:points.find(p=>p.id===id)!,axis:"xz",offset:base.map((v,i)=>v-position(e)[i])};
|
||||
runtime.current?.setNavigation(false);markerSvg.current!.setPointerCapture(e.pointerId);
|
||||
}}
|
||||
onPointerDown={(e)=>{if(e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
|
||||
onPointerCancel={()=>{press.current=null;}}
|
||||
onPointerUp={(e)=>{
|
||||
const start=press.current;press.current=null;
|
||||
if(!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
|
||||
if(mode==="add")add(...position(e) as [number,number]);else edit({type:"select",id:null});
|
||||
}}><canvas ref={canvas} aria-label="Локальная Gaussian-сцена для маршрута" />
|
||||
<svg ref={markerSvg} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
|
||||
onPointerMove={(e)=>{
|
||||
if (!drag.current) return;
|
||||
const d=drag.current, [x,y]=position(e);
|
||||
const moved=runtime.current?.move(d.point,x+d.offset[0],y+d.offset[1],d.axis);
|
||||
if(moved)edit({type:"move",points:points.map(p=>p.id===d.point.id?{...p,position:moved}:p)});
|
||||
}}
|
||||
onPointerUp={(e)=>{
|
||||
drag.current=null;edit({type:"commit"});
|
||||
runtime.current?.setNavigation(!busy);if(e.currentTarget.hasPointerCapture(e.pointerId))e.currentTarget.releasePointerCapture(e.pointerId); }}
|
||||
onPointerCancel={()=>{edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}}>
|
||||
{preparedRoute?<path className="ai-route__line" d={routeProjection.map((p,i)=>p?`${i&&routeProjection[i-1]?"L":"M"}${p[0]*1280},${p[1]*720}`:"").join(" ")} />:null}
|
||||
{!preparedRoute?<path className="ai-route__line" d={markers.map((m,i)=>m.base?`${i&&markers[i-1].base?"L":"M"}${m.base[0]*1280},${m.base[1]*720}`:"").join(" ")} />:null}
|
||||
{markers.map((m,i)=>m.base&&m.top ? <g key={m.id} data-waypoint="true" className={`ai-route__marker ${selected===m.id?"is-selected":""}`}
|
||||
onPointerDown={(e)=>{
|
||||
if (busy || e.button !== 0) return;
|
||||
e.preventDefault();e.stopPropagation();edit({type:"select",id:m.id});edit({type:"begin"});
|
||||
drag.current={point:points.find((p)=>p.id===m.id)!,axis:"xz",offset:m.base!.map((v,i)=>v-position(e)[i])};
|
||||
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
|
||||
}}>
|
||||
|
||||
|
||||
<text textAnchor={m.top[0]>.85?"end":"start"} x={m.top[0]*1280+(m.top[0]>.85?-10:10)} y={m.top[1]*720}>{i===0?"Старт":i===markers.length-1?`Финиш · ${i}`:i}</text>
|
||||
{selected===m.id ? (["x","y","z"] as const).map((axis)=>m[axis] ? <g key={axis} className="ai-local-editor__axis-hit" onPointerDown={(e)=>{
|
||||
if (busy || e.button !== 0) return;
|
||||
e.preventDefault();e.stopPropagation();edit({type:"begin"});drag.current={point:points.find((p)=>p.id===m.id)!,axis,offset:m.base!.map((v,i)=>v-position(e)[i])};
|
||||
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
|
||||
}}><line x1={m.base![0]*1280} y1={m.base![1]*720} x2={m[axis]![0]*1280} y2={m[axis]![1]*720}/>
|
||||
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
|
||||
</g>:null)}
|
||||
</svg></div>
|
||||
{!ready && !error ? <div className="ai-polygon__preview-error"><LoadingRegion loading label={message} /></div>:null}
|
||||
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
|
||||
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={Number.isFinite(clip)?clip:runtime.current!.height[1]}
|
||||
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
|
||||
onChange={(v)=>{const next=v>=runtime.current!.height[1]?Infinity:v;setClip(next);runtime.current!.setClip(next);}}/></div>
|
||||
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
|
||||
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
|
||||
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}: {
|
||||
error:string|null;name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
|
||||
onClose:()=>void;onSave:()=>void;
|
||||
}) {
|
||||
return <Window open title={launch?"Сохранить задание и запустить":"Сохранить задание"}
|
||||
size="sm" onClose={()=>{if(!busy)onClose();}}
|
||||
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
|
||||
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
|
||||
<div className="ai-polygon__form">
|
||||
{error?<p role="alert">{error}</p>:null}
|
||||
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
|
||||
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
|
||||
export function AiProfileWindow({initialName='',editing=false,busy,onClose,onSave,onRemove}: {
|
||||
initialName?:string;editing?:boolean;busy:boolean;onClose:()=>void;
|
||||
onSave:(name:string)=>void;onRemove?:()=>void;
|
||||
}) {
|
||||
const [name,setName]=useState(initialName);
|
||||
return <Window open size="sm" title={editing?'Редактировать профиль AI':'Сохранить профиль AI'}
|
||||
onClose={()=>{if(!busy)onClose();}} footer={<WindowFooterActions>
|
||||
{onRemove&&<Button icon={<Icon name="trash"/>} disabled={busy} onClick={onRemove}>Удалить профиль</Button>}
|
||||
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={()=>onSave(name.trim())}>
|
||||
{editing?'Сохранить имя':'Сохранить профиль'}</Button>
|
||||
</WindowFooterActions>}>
|
||||
<TextField label="Название профиля" maxLength={120} value={name} disabled={busy}
|
||||
onChange={e=>setName(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!busy&&name.trim())onSave(name.trim());}}/>
|
||||
</Window>;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { useEffect, useRef, useState, type PointerEvent } from "react";
|
||||
import { Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
|
||||
import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import { useAiPlanningControls } from "./useAiPlanningControls";
|
||||
|
||||
const xy = (p: NonNullable<ScreenPoint>) => `${p[0] * 1280},${p[1] * 720}`;
|
||||
function path(points: ScreenPoint[]) {
|
||||
let drawing = false;
|
||||
return points.map((p) => {
|
||||
if (!p) { drawing = false; return ""; }
|
||||
const command = `${drawing ? "L" : "M"}${xy(p)}`; drawing = true; return command;
|
||||
}).join(" ");
|
||||
}
|
||||
type Drag = { start: [number, number]; last: [number, number]; at: number;
|
||||
action: "orbit" | "pan" | "move"; point_id?: string; axis?: "x" | "y" | "xy";
|
||||
base?: NonNullable<ScreenPoint>; moved: boolean };
|
||||
|
||||
/** Screen-space annotations only. All geometry/projection and terrain picking belong to Worker. */
|
||||
export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: { run: AiRun; onChange: (run: AiRun) => void; videoReady: boolean; visible?: boolean }) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const svg = useRef<SVGSVGElement>(null);
|
||||
const drag = useRef<Drag | null>(null);
|
||||
const [size, setSize] = useState({ width: 0, height: 0 });
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [mode, setMode] = useState<"view" | "add">("view");
|
||||
const [clip, setClip] = useState<number | null>(null);
|
||||
const editing = run.request?.purpose === "planning";
|
||||
const data = run.telemetry?.route_overlay;
|
||||
const draft = run.telemetry?.planning;
|
||||
const cameraReady = videoReady && editing && !!draft && run.control !== "stop";
|
||||
const { send, busy, error, keyDown, stopKeys } = useAiPlanningControls(run, onChange, cameraReady);
|
||||
const pending = busy || (run.planning_sequence ?? 0) > (draft?.sequence ?? 0);
|
||||
const ready = cameraReady && !pending && !draft?.camera_moving;
|
||||
const low = draft?.height_min, high = draft?.height_max;
|
||||
useEffect(() => { if (!pending) setClip(draft?.clip_height ?? null); }, [pending, draft?.clip_height]);
|
||||
useEffect(() => {
|
||||
if (!host.current) return;
|
||||
const resize = new ResizeObserver(([entry]) => {
|
||||
const width = (editing ? Math.min : Math.max)(entry.contentRect.width, entry.contentRect.height * 16 / 9);
|
||||
setSize({ width, height: width * 9 / 16 });
|
||||
});
|
||||
resize.observe(host.current); return () => resize.disconnect();
|
||||
}, []);
|
||||
const controls = useRef({ send, cameraReady }); controls.current = { send, cameraReady };
|
||||
useEffect(() => {
|
||||
const element = host.current;
|
||||
const wheel = (event: WheelEvent) => {
|
||||
if (!(event.target instanceof Element) || !event.target.closest(".ai-route__canvas")) return;
|
||||
if (!controls.current.cameraReady) return;
|
||||
event.preventDefault();
|
||||
const pixels = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 720 : 1);
|
||||
controls.current.send({ action: "zoom", amount: Math.max(-3, Math.min(3, pixels * .006)) });
|
||||
};
|
||||
element?.addEventListener("wheel", wheel, { passive: false });
|
||||
return () => element?.removeEventListener("wheel", wheel);
|
||||
}, []);
|
||||
const position = (event: { clientX: number; clientY: number }): [number, number] => {
|
||||
const rect = svg.current!.getBoundingClientRect();
|
||||
return [(event.clientX - rect.left) / rect.width, (event.clientY - rect.top) / rect.height];
|
||||
};
|
||||
const start = (event: PointerEvent<SVGElement>, point?: string, axis?: Drag["axis"]) => {
|
||||
if (!cameraReady || (point && !ready)) return;
|
||||
event.stopPropagation(); event.preventDefault();
|
||||
svg.current?.focus({ preventScroll: true });
|
||||
const marker = data?.markers.find((m) => m.id === point);
|
||||
if (point) setSelected(point);
|
||||
const p = position(event);
|
||||
drag.current = { start: p, last: p, at: performance.now(), moved: false,
|
||||
action: point ? "move" : event.shiftKey || event.button === 1 ? "pan" : "orbit",
|
||||
point_id: point, axis, base: marker?.base ?? undefined };
|
||||
svg.current?.setPointerCapture(event.pointerId);
|
||||
};
|
||||
const move = (event: PointerEvent<SVGSVGElement>) => {
|
||||
const d = drag.current; if (!d) return;
|
||||
const p = position(event);
|
||||
d.moved ||= Math.hypot(p[0] - d.start[0], p[1] - d.start[1]) > .005;
|
||||
if (d.action !== "move" && d.moved && performance.now() - d.at > 100) {
|
||||
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
|
||||
d.last = p; d.at = performance.now();
|
||||
}
|
||||
};
|
||||
const end = (event: PointerEvent<SVGSVGElement>) => {
|
||||
const d = drag.current; drag.current = null; if (!d) return;
|
||||
const p = position(event);
|
||||
if (d.action === "move" && d.moved && d.base) {
|
||||
send({ action: "move", point_id: d.point_id, axis: d.axis ?? "xy",
|
||||
x: Math.max(0, Math.min(1, d.base[0] + p[0] - d.start[0])),
|
||||
y: Math.max(0, Math.min(1, d.base[1] + p[1] - d.start[1])) });
|
||||
} else if (!d.moved && !d.point_id && mode === "add" && ready) send({ action: "add", x: p[0], y: p[1] });
|
||||
else if (d.moved && d.action !== "move") {
|
||||
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
|
||||
}
|
||||
if (svg.current?.hasPointerCapture(event.pointerId)) svg.current.releasePointerCapture(event.pointerId);
|
||||
};
|
||||
return <div className="ai-route" ref={host} hidden={!videoReady}>
|
||||
{data && visible ? <svg ref={svg} viewBox="0 0 1280 720" style={size}
|
||||
className={`ai-route__canvas ${editing ? "ai-route__canvas--editing" : ""}`}
|
||||
tabIndex={editing ? 0 : undefined} onKeyDown={keyDown} onBlur={stopKeys}
|
||||
aria-label="Маршрут и точки задания" onContextMenu={(e) => e.preventDefault()}
|
||||
onPointerDown={(e) => start(e)} onPointerMove={move} onPointerUp={end}
|
||||
onPointerCancel={() => { drag.current = null; }}>
|
||||
<path className="ai-route__line" d={path(data.markers.map((m) => m.base))} />
|
||||
<path className="ai-route__trace" d={path(data.trace)} />
|
||||
{data.markers.map((m, i) => m.base && m.top ? <g key={m.id}
|
||||
className={`ai-route__marker ${selected === m.id ? "is-selected" : ""} ${!editing && i === data.active_index ? "is-active" : ""}`}
|
||||
onPointerDown={(e) => start(e, m.id, "xy")}>
|
||||
<line className="ai-route__beam" x1={m.base[0]*1280} y1={m.base[1]*720} x2={m.top[0]*1280} y2={m.top[1]*720} />
|
||||
<circle cx={m.base[0]*1280} cy={m.base[1]*720} r="8" />
|
||||
<text x={m.top[0]*1280+10} y={m.top[1]*720}>{i === 0 ? "Старт" : i === data.markers.length-1 ? `Финиш · ${i}` : i}</text>
|
||||
{editing && selected === m.id ? (["x", "y"] as const).map((axis) => {
|
||||
const p = axis === "x" ? m.x_axis : m.y_axis;
|
||||
return p ? <g key={axis} className="ai-route__axis" onPointerDown={(e) => start(e, m.id, axis)}>
|
||||
<line x1={m.base![0]*1280} y1={m.base![1]*720} x2={p[0]*1280} y2={p[1]*720} />
|
||||
<circle cx={p[0]*1280} cy={p[1]*720} r="12" />
|
||||
</g> : null;
|
||||
}) : null}
|
||||
</g> : null)}
|
||||
</svg> : null}
|
||||
{editing && low != null && high != null && high > low ? <div className="ai-route__height">
|
||||
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={clip ?? high}
|
||||
min={low} max={high} step="any" disabled={!cameraReady}
|
||||
formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`}
|
||||
formatLimit={(value) => value.toFixed(1).replace('.', ',')}
|
||||
onChange={(value) => {
|
||||
const height = value >= high - Math.max(1, high-low)*1e-9 ? null : value;
|
||||
setClip(height); send({ action: "clip", amount: value, enabled: height != null });
|
||||
}} />
|
||||
</div> : null}
|
||||
{editing ? <div className="ai-route__tools">
|
||||
<SegmentedControl label="Инструмент маршрута" size="dense" value={mode} onChange={setMode}
|
||||
items={[{ value: "view", label: "Обзор" }, { value: "add", label: "Точка по клику" }]} />
|
||||
<Button disabled={!ready} onClick={() => send({ action: "add", x: .5, y: .5 })}>Добавить waypoint</Button>
|
||||
<Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button>
|
||||
<Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
|
||||
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
|
||||
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p>
|
||||
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null}
|
||||
</div> : null}
|
||||
</div>;
|
||||
}
|
||||
@@ -14,12 +14,12 @@ export function AiRunActions({ run, onChange }: { run: AiRun; onChange: (run: Ai
|
||||
};
|
||||
return <>
|
||||
{!terminal ? <>
|
||||
<Button disabled={!!busy || pending || ["starting", "stopping", "disconnected"].includes(run.state)}
|
||||
{run.state !== "stopping" && run.state !== "starting" ? <Button disabled={!!busy || pending || ["starting", "stopping", "disconnected"].includes(run.state)}
|
||||
variant={run.state === "ready" ? "primary" : "secondary"}
|
||||
loading={busy === "pause" || busy === "play"}
|
||||
onClick={() => command(run.state === "running" ? "pause" : "play")}>
|
||||
{run.state === "starting" ? "Подготовка…" : run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
|
||||
</Button>
|
||||
{run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
|
||||
</Button> : null}
|
||||
<Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"}
|
||||
icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button>
|
||||
</> : null}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
|
||||
import type { AiModules, AiRun } from "../../core/simulation/aiPolygon";
|
||||
|
||||
import { AiSessionSection, useSessionLayout } from "./AiSessionSection";
|
||||
|
||||
const outcomes = {
|
||||
"goal-reached": "Маршрут пройден", "time-limit": "Лимит времени",
|
||||
"operator-stop": "Остановлен оператором", stuck: "Проезд не найден",
|
||||
unstable: "Опасный наклон", error: "Ошибка выполнения", "not-evaluated": "Результат не определён",
|
||||
};
|
||||
const reasons: Record<string, string> = {
|
||||
"stale-camera": "Устарел кадр камеры", "stale-command": "Устарело решение",
|
||||
"inference-error": "Ошибка inference", "no-road": "Не найдена поверхность для движения",
|
||||
obstacle: "Препятствие", waiting: "Ожидание пути", uncertain: "Недостаточно данных",
|
||||
paused: "Пауза оператора", "goal-reached": "Достижение цели", stuck: "Нет проезда",
|
||||
unstable: "Опасный наклон", unknown: "Причина не записана",
|
||||
};
|
||||
const measured = (value: number | null, unit: string, digits = 1) =>
|
||||
value === null ? "Нет измерения" : `${value.toFixed(digits)} ${unit}`;
|
||||
|
||||
export function AiRunReport({ runs, modules, onRemove, removing, worldId }: { worldId:string; runs: AiRun[]; modules: AiModules|null;
|
||||
onRemove:(run:AiRun)=>void; removing:string|null }) {
|
||||
const [open,setOpen] = useSessionLayout(`${worldId}:runs`, []);
|
||||
const names = new Map(modules?.catalog.groups.flatMap(g=>g.modules.map(m=>[m.moduleId,m.label] as const)) ?? []);
|
||||
const available = runs.filter((run) => run.request?.purpose !== "planning");
|
||||
return <AiSessionSection scope={`${worldId}:results`} title="Результаты сессии">
|
||||
{available.length ? <Inspector variant="panel" openSections={open} onOpenSectionsChange={setOpen} className="ai-polygon__history" sections={available.map((run)=>({
|
||||
id:run.run_id, icon:<Icon name="activity"/>,
|
||||
label:`${run.created_at || run.report?.generated_at ? new Date(run.created_at ?? run.report!.generated_at).toLocaleString("ru-RU") : "Время не записано"} · ${run.robot?.name ?? "Ровер не записан"} · ${run.plan_display_name ?? run.plan?.name ?? "Без задания"}`,
|
||||
description:`${run.report ? outcomes[run.report.mission_outcome] : run.message ?? "Прогон выполняется"} · ${(run.request?.composition?.selections ?? []).map(s=>names.get(s.module_id) ?? s.module_id).join(" · ") || "AI не запускался"}`,
|
||||
content:<GlassSurface padding="md"><RunDetails run={run}/></GlassSurface>,
|
||||
action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`,
|
||||
icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
|
||||
onAction:()=>onRemove(run)},
|
||||
}))}/> : <p>В этой локации ещё нет прогонов.</p>}
|
||||
</AiSessionSection>;
|
||||
}
|
||||
function RunDetails({run}:{run:AiRun}) {
|
||||
if(!run.report)return <p>{run.message ?? "Отчёт появится после завершения прогона."}</p>;
|
||||
const report=run.report;
|
||||
return <div className="ai-polygon__form ai-polygon__report">
|
||||
<StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}>
|
||||
{outcomes[report.mission_outcome]}
|
||||
</StatusBadge>
|
||||
<dl>
|
||||
{run.state==='failed'&&run.message?<div><dt>Причина остановки</dt><dd>{run.message}</dd></div>:null}
|
||||
<div><dt>Задание</dt><dd>{run.plan_display_name ?? run.plan?.name ?? "Без сохранённого задания"}</dd></div>
|
||||
<div><dt>Ровер</dt><dd>{run.robot?.name ?? "Не записан"}</dd></div>
|
||||
{run.rover_configuration?<div><dt>Масса / груз</dt><dd>{run.rover_configuration.total_mass_kg} / {run.rover_configuration.settings.payload_mass_kg} кг</dd></div>:null}
|
||||
{report.speed?<><div><dt>Скорость · заданная / пиковая</dt><dd>{measured(report.speed.requested_max_mps,"м/с",3)} / {measured(report.speed.measured_max_mps,"м/с",3)}</dd></div>
|
||||
<div><dt>Максимальное превышение / длительность</dt><dd>{measured(report.speed.maximum_excess_mps,"м/с",4)} / {measured(report.speed.seconds_above_requested,"с",2)}</dd></div></>:null}
|
||||
<div><dt>Цели после стартовой точки</dt><dd>{report.waypoints_reached === null ? "Нет измерения" : `${report.waypoints_reached} / ${report.waypoint_count}`}</dd></div>
|
||||
<div><dt>Пройдено</dt><dd>{measured(report.distance_m, "м", 2)}</dd></div>
|
||||
<div><dt>Время мира</dt><dd>{measured(report.simulation_seconds, "с")}</dd></div>
|
||||
<div><dt>До конечной цели</dt><dd>{measured(report.goal_error_m, "м", 2)}</dd></div>
|
||||
<div><dt>Решения AI / ошибки</dt><dd>{report.inference_count} / {report.inference_errors}</dd></div>
|
||||
<div><dt>Задержка AI · медиана / P95</dt><dd>{measured(report.inference_ms_p50, "мс", 0)} / {measured(report.inference_ms_p95, "мс", 0)}</dd></div>
|
||||
<div><dt>Столкновения</dt><dd>{report.collision_count === null ? "Учёт ещё не подключён" : report.collision_count}</dd></div>
|
||||
</dl>
|
||||
<h3>Остановки после начала движения</h3>
|
||||
{report.stops.length ? <dl>{report.stops.map((stop) => <div key={stop.reason}>
|
||||
<dt>{reasons[stop.reason] ?? stop.reason}</dt><dd>{stop.events} · {stop.seconds.toFixed(1)} с</dd>
|
||||
</div>)}</dl> : <p>Переходов от движения к нулевой команде не записано.</p>}
|
||||
<p>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</p>
|
||||
<dl className="ai-polygon__report-identities">
|
||||
<div><dt>Прогон</dt><dd>{report.run_id}</dd></div>
|
||||
<div><dt>Профиль ровера</dt><dd>{report.robot_sha256 ?? "Не записан"}</dd></div>
|
||||
<div><dt>Композиция AI</dt><dd>{report.composition_sha256 ?? "Не запускалась"}</dd></div>
|
||||
<div><dt>SHA-256 отчёта</dt><dd>{report.report_sha256}</dd></div>
|
||||
<div><dt>SHA-256 архива</dt><dd>{report.manifest_sha256}</dd></div>
|
||||
</dl>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { StatusBadge } from "@nodedc/ui-react";
|
||||
import { type AiRun } from "../../core/simulation/aiPolygon";
|
||||
|
||||
@@ -16,37 +15,42 @@ const REASONS: Record<string, string> = {
|
||||
"goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон",
|
||||
waiting: "Ожидаем возможность движения",
|
||||
};
|
||||
export function AiRunView({ run, connection }: { run: AiRun; connection: ReactNode }) {
|
||||
export function AiRunView({ run }: { run: AiRun }) {
|
||||
const terminal = ["completed", "stopped", "failed"].includes(run.state);
|
||||
const telemetry = run.telemetry;
|
||||
const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0);
|
||||
const preparingModels = run.state === "running" && run.phase === "models";
|
||||
const reason = telemetry?.stop_reason === "unstable" ? "Остановка: опасный наклон"
|
||||
const missionStopped = ["stuck", "goal-reached", "unstable"].includes(telemetry?.decision?.reason ?? "");
|
||||
const reason = missionStopped ? REASONS[telemetry!.decision!.reason] : telemetry?.stop_reason === "unstable" ? "Остановка: опасный наклон"
|
||||
: telemetry?.stop_reason === "stale-camera" || telemetry?.stop_reason === "stale-command"
|
||||
? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error"
|
||||
? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01
|
||||
? "Ровер не движется" : REASONS[telemetry?.decision?.reason ?? ""];
|
||||
const showTelemetry = telemetry && !terminal && !["stopping", "disconnected"].includes(run.state);
|
||||
const live = showTelemetry && run.state === "running";
|
||||
const metrics = [
|
||||
["Скорость", showTelemetry ? `${Math.abs(telemetry.speed_mps).toFixed(2)} м/с` : "—"],
|
||||
["Пройдено", (terminal?run.report?.distance_m:telemetry?.distance_m) != null ? `${(terminal?run.report!.distance_m:telemetry!.distance_m)!.toFixed(1)} м` : "—"],
|
||||
["Время мира", showTelemetry ? `${(telemetry.simulation_time_ns / 1e9).toFixed(1)} с` : "—"],
|
||||
["Симуляция", live ? `${telemetry.rtf.toFixed(2)}×` : "—"],
|
||||
["Камера", live ? `${telemetry.sensor_fps.toFixed(1)} FPS` : "—"],
|
||||
["AI", live ? `${telemetry.ai_hz.toFixed(1)} решений/с` : "—"],
|
||||
["Inference", live && telemetry.inference_ms !== null ? `${telemetry.inference_ms.toFixed(0)} мс` : "—"],
|
||||
["Возраст кадра", live && telemetry.frame_age_ms !== null ? `${telemetry.frame_age_ms.toFixed(0)} мс` : "—"],
|
||||
];
|
||||
return <section className="ai-polygon__run" aria-label="Управление симуляцией">
|
||||
<div className="ai-polygon__telemetry-row">
|
||||
<div className="ai-polygon__facts">
|
||||
{run.state !== "ready" && run.state !== "running" || preparingModels || pending ? <StatusBadge tone={run.state === "failed" || run.state === "disconnected" ? "warning" : "neutral"}>
|
||||
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : STATES[run.state]}
|
||||
</StatusBadge> : null}
|
||||
{telemetry && !terminal && run.state !== "stopping" && run.state !== "disconnected" ? <div className="ai-polygon__facts">
|
||||
{run.state === "running" && !preparingModels && reason ? <strong>{reason}</strong> : null}
|
||||
<span>Скорость: {Math.abs(telemetry.speed_mps).toFixed(2)} м/с</span>
|
||||
<span>Время мира: {(telemetry.simulation_time_ns / 1e9).toFixed(1)} с</span>
|
||||
{run.state === "running" ? <>
|
||||
<span>Симуляция: {telemetry.rtf.toFixed(2)}×</span>
|
||||
<span>Камера: {telemetry.sensor_fps.toFixed(1)} FPS</span>
|
||||
<span>AI: {telemetry.ai_hz.toFixed(1)} решений/с</span>
|
||||
{telemetry.inference_ms !== null ? <span>Inference: {telemetry.inference_ms.toFixed(0)} мс</span> : null}
|
||||
{telemetry.frame_age_ms !== null ? <span>Возраст кадра: {telemetry.frame_age_ms.toFixed(0)} мс</span> : null}
|
||||
</> : null}
|
||||
</div> : null}
|
||||
</div>
|
||||
{connection}
|
||||
</div>
|
||||
<dl className="ai-polygon__run-metrics">
|
||||
<div className="ai-polygon__run-metric ai-polygon__run-metric--status">
|
||||
<dt>Состояние</dt><dd>
|
||||
<StatusBadge tone={run.state === "failed" || run.state === "disconnected" || (run.state === "running" && telemetry?.decision?.reason === "stuck") ? "warning" : run.state === "running" && !preparingModels && !pending ? "success" : "neutral"}>
|
||||
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : run.state === "running" && reason ? reason : STATES[run.state]}
|
||||
</StatusBadge>
|
||||
</dd>
|
||||
</div>
|
||||
{metrics.map(([label, value]) => <div className="ai-polygon__run-metric" key={label}>
|
||||
<dt>{label}</dt><dd>{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
{run.state === "failed" && run.message ? <p>{run.message}</p> : null}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { GlassSurface, Icon, Inspector } from "@nodedc/ui-react";
|
||||
|
||||
/** Layout belongs to the operator and location, not a particular live run. */
|
||||
export function useSessionLayout(scope: string, initial: string[]) {
|
||||
const key = `nodedc.simulation.layout.v1:${scope}`;
|
||||
const [open, setOpen] = useState<string[]>(() => {
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
|
||||
if (Array.isArray(value) && value.every(id => typeof id === "string")) return value;
|
||||
} catch { /* Private browsing or older invalid preferences use the default. */ }
|
||||
return initial;
|
||||
});
|
||||
return [open, (ids: string[]) => {
|
||||
setOpen(ids);
|
||||
try { localStorage.setItem(key, JSON.stringify(ids)); } catch { /* This session still works. */ }
|
||||
}] as const;
|
||||
}
|
||||
|
||||
export function AiSessionSection({ scope, title, children, initiallyOpen = true }: {
|
||||
scope: string; title: string; children: ReactNode; initiallyOpen?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useSessionLayout(scope, initiallyOpen ? ["body"] : []);
|
||||
return <Inspector variant="panel" openSections={open} onOpenSectionsChange={setOpen}
|
||||
sections={[{ id: "body", label: title, icon: <Icon name={scope.endsWith("results") ? "activity" : "settings"} />,
|
||||
content: <GlassSurface padding="md" className="ai-polygon__section">{children}</GlassSurface> }]} />;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { LaboratoryMetricEvidenceScene, type LaboratoryMetricPoint3 } from "../laboratory/LaboratoryMetricEvidenceScene";
|
||||
|
||||
const EMPTY: [] = [];
|
||||
// View framing only; no fabricated rig or corridor is drawn on sensor evidence.
|
||||
const FRAMING = { forwardLengthM: 8, rearMarginM: 0, halfWidthM: 0 };
|
||||
const NO_RIG = { lengthM: 0, widthM: 0, nominalSensorHeightM: 0 };
|
||||
export function AiSpatialPreview({ points, label }: { points: LaboratoryMetricPoint3[]; label:string }) {
|
||||
return <LaboratoryMetricEvidenceScene pointCloudBodyXyzM={points} localSurfaceBodyXyzM={EMPTY}
|
||||
obstacles={EMPTY} rig={NO_RIG} corridor={FRAMING} occupiedVoxelSizeM={0.1} mode="3d" label={label}
|
||||
showCurrentIncrement showLocalSurface={false} showRollingMap={false} showReferenceGeometry={false} showRenderStats={false}/>;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useState } from "react";
|
||||
import { Button, Icon, InspectorSelectField, Select, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { aiPlanName, updateAiPlan, type AiPlan } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiTaskSelect({plans,value,disabled,onChange,onUpdated,inspector=false}: {
|
||||
inspector?:boolean;plans:AiPlan[];value:string;disabled:boolean;onChange:(id:string)=>void;onUpdated:(plan:AiPlan)=>void;
|
||||
}) {
|
||||
const TaskSelect = inspector ? InspectorSelectField : Select;
|
||||
const [editing,setEditing]=useState<AiPlan|null>(null);
|
||||
const [name,setName]=useState("");
|
||||
const [busy,setBusy]=useState(false);
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
const save=(removed=false)=>{
|
||||
if(!editing||busy)return;
|
||||
setBusy(true);
|
||||
void updateAiPlan(editing.plan_id,removed?{removed:true}:{display_name:name.trim()})
|
||||
.then(plan=>{onUpdated(plan);setEditing(null);})
|
||||
.catch((caught:Error)=>setError(caught.message)).finally(()=>setBusy(false));
|
||||
};
|
||||
return <>
|
||||
<div className="ai-polygon__plan-select"><TaskSelect label="Задание" value={value} disabled={disabled}
|
||||
onChange={onChange} options={[
|
||||
{value:"",label:"Новое задание"},
|
||||
...plans.map(plan=>({value:plan.plan_id,label:aiPlanName(plan),
|
||||
description:`${plan.points.length} точек · ${plan.length_m.toFixed(1)} м`,
|
||||
action:{label:`Редактировать задание «${aiPlanName(plan)}»`,icon:<Icon name="edit"/>,
|
||||
onAction:()=>{setName(aiPlanName(plan));setEditing(plan);setError(null);}},
|
||||
})),
|
||||
]}/></div>
|
||||
<Window open={!!editing} title="Редактировать задание" size="sm" onClose={()=>{if(!busy)setEditing(null);}}
|
||||
footer={<WindowFooterActions>
|
||||
<Button icon={<Icon name="trash"/>} disabled={busy} onClick={()=>save(true)}>Удалить задание</Button>
|
||||
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={()=>save()}>Сохранить имя</Button>
|
||||
</WindowFooterActions>}>
|
||||
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
</Window>
|
||||
{error?<ToastStack items={[{id:"task-edit",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
</>;
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
import { useState } from "react";
|
||||
import { Button, TextField, TextAreaField, ToastStack } from "@nodedc/ui-react";
|
||||
import { Button, TextField, ToastStack } from "@nodedc/ui-react";
|
||||
import { configureAiWorld, type AiWorld, type AiWorldSettings } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiWorldSetup({ world, disabled, onSaved }: {
|
||||
world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<AiWorldSettings>(world.settings);
|
||||
const [route, setRoute] = useState((world.settings.route_xy ?? []).map((p) => p.join(" ")).join("\n"));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const field = (label: string, value: number, change: (value: number) => void) =>
|
||||
@@ -26,16 +25,9 @@ export function AiWorldSetup({ world, disabled, onSaved }: {
|
||||
{field("Направление, °", draft.heading_degrees, (v) => setDraft({ ...draft, heading_degrees: v }))}
|
||||
{field("Высота камеры, м", draft.camera_height_m, (v) => setDraft({ ...draft, camera_height_m: v }))}
|
||||
{field("Скорость до, м/с", draft.max_speed_mps, (v) => setDraft({ ...draft, max_speed_mps: v }))}
|
||||
<TextAreaField label="Точки маршрута, X Y в метрах" rows={3} value={route}
|
||||
hint="Каждая точка — с новой строки. Пустое поле: движение по видимой тропе."
|
||||
disabled={disabled || busy} onChange={(e) => setRoute(e.target.value)} />
|
||||
<Button disabled={disabled} loading={busy} onClick={() => {
|
||||
const points = route.trim() ? route.trim().split(/\n+/).map((line) => line.trim().split(/\s+/).map(Number)) : [];
|
||||
if (points.length > 32 || points.some((p) => p.length !== 2 || p.some((v) => !Number.isFinite(v)))) {
|
||||
setError("Укажите не более 32 точек: два числа X Y в каждой строке."); return;
|
||||
}
|
||||
setBusy(true); setError(null);
|
||||
void configureAiWorld(world, { ...draft, route_xy: points as [number, number][], prepared: true }).then(onSaved)
|
||||
void configureAiWorld(world, { ...draft, prepared: true }).then(onSaved)
|
||||
.catch((caught: Error) => setError(caught.message)).finally(() => setBusy(false));
|
||||
}}>Сохранить старт и масштаб</Button>
|
||||
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Настройки не сохранены", description: error }]} onDismiss={() => setError(null)} /> : null}
|
||||
|
||||
@@ -1,88 +1,38 @@
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||
import { useCallback, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, Icon, IconButton, LoadingRegion, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
|
||||
import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import { WorkerVideo, type WorkerVideoState } from "./WorkerVideo";
|
||||
import { AiRouteOverlay } from "./AiRouteOverlay";
|
||||
import { useInferencePreview } from "./AiInferencePreview";
|
||||
import { SimulationObservationDeck } from "./SimulationObservationDeck";
|
||||
import { useObserverInput } from "./useObserverInput";
|
||||
import { useSimulationFullscreen } from "./useSimulationFullscreen";
|
||||
|
||||
// NVIDIA has process-global browser listeners. Serialize replacement/cleanup,
|
||||
// including React StrictMode, without letting an old viewer terminate a new one.
|
||||
let streamLifecycle: Promise<unknown> = Promise.resolve();
|
||||
|
||||
/** Decode the actual Worker stream. This component never loads a world or creates a 3D engine. */
|
||||
export function AiWorldStream({ world, run, onBack, onChange, controls, headerActions, actionsHost }: {
|
||||
world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode;
|
||||
headerActions?: ReactNode; actionsHost?: HTMLElement | null;
|
||||
}) {
|
||||
const frame = useRef<HTMLDivElement>(null);
|
||||
const video = useRef<HTMLVideoElement>(null);
|
||||
const id = useId().replaceAll(":", "");
|
||||
const frame = useRef<HTMLDivElement>(null), surface=useRef<HTMLDivElement>(null);
|
||||
const { expanded, toggle } = useSimulationFullscreen(frame);
|
||||
const [state, setState] = useState<"connecting" | "live" | "failed" | "stalled">("connecting");
|
||||
const [state, setState] = useState<WorkerVideoState>("connecting");
|
||||
const [fps, setFps] = useState<number | null>(null);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [cameraError, setCameraError] = useState(false);
|
||||
const [routeVisible, setRouteVisible] = useState(true);
|
||||
const endpoint = run?.worker?.stream;
|
||||
const terminal = !run || ["completed", "stopped", "failed"].includes(run.state);
|
||||
const connectable = !terminal && !!run?.telemetry?.stream_ready && !!endpoint;
|
||||
const endpointKey = JSON.stringify(endpoint);
|
||||
useEffect(() => {
|
||||
if (!connectable || !endpoint || !video.current) return;
|
||||
let disposed = false;
|
||||
let stream: import("@nvidia/ov-web-rtc").AppStreamer | undefined;
|
||||
let settle!: () => void;
|
||||
const settled = new Promise<void>((resolve) => { settle = resolve; });
|
||||
let callback = 0;
|
||||
let lastFrame = performance.now();
|
||||
let frames = 0;
|
||||
let measuredAt = performance.now();
|
||||
let connected = false;
|
||||
setState("connecting"); setFps(null);
|
||||
const element = video.current;
|
||||
const received = () => {
|
||||
if (disposed) return;
|
||||
lastFrame = performance.now(); frames += 1; connected = true; setState("live");
|
||||
callback = element.requestVideoFrameCallback(received);
|
||||
};
|
||||
callback = element.requestVideoFrameCallback(received);
|
||||
const timer = setInterval(() => {
|
||||
const now = performance.now();
|
||||
setFps(frames * 1000 / (now - measuredAt));
|
||||
frames = 0; measuredAt = now;
|
||||
if (connected && now - lastFrame > 3000) setState("stalled");
|
||||
}, 1000);
|
||||
const setup = streamLifecycle.catch(() => undefined).then(async () => {
|
||||
const sdk = await import("@nvidia/ov-web-rtc");
|
||||
if (disposed) { settle(); return; }
|
||||
stream = new sdk.AppStreamer();
|
||||
await stream.connect({ streamSource: sdk.StreamType.DIRECT, logLevel: sdk.LogLevel.WARN,
|
||||
streamConfig: { signalingServer: endpoint.server, signalingPort: endpoint.signaling_port,
|
||||
signalingPath: "/", mediaServer: endpoint.server, mediaPort: endpoint.media_port,
|
||||
width: endpoint.width, height: endpoint.height, fps: endpoint.fps,
|
||||
videoElementId: `polygon-video-${id}`, audioElementId: `polygon-audio-${id}`,
|
||||
autoLaunch: true, mic: false, enableAV1Support: false, fitStreamResolution: false,
|
||||
maxReconnects: 1, reconnectDelay: 2000, connectivityTimeout: 5000,
|
||||
onStart: (event) => {
|
||||
if (event.status === sdk.EventStatus.SUCCESS || event.status === sdk.EventStatus.ERROR
|
||||
|| event.status === sdk.EventStatus.CANCELED) settle();
|
||||
if (!disposed && event.status === sdk.EventStatus.ERROR) setState("failed");
|
||||
},
|
||||
onStop: () => { settle(); if (!disposed) setState("stalled"); },
|
||||
} });
|
||||
if (stream.streamStatus !== sdk.StreamStatus.STARTING) settle();
|
||||
}).catch(() => { settle(); if (!disposed) setState("failed"); });
|
||||
streamLifecycle = setup;
|
||||
return () => {
|
||||
disposed = true; clearInterval(timer); element.cancelVideoFrameCallback(callback);
|
||||
// connect() resolves with IN_PROGRESS; terminate() during STARTING does
|
||||
// not dispose the SDK. Await its final callback before admitting a new owner.
|
||||
streamLifecycle = setup.then(async () => {
|
||||
await settled;
|
||||
await stream?.terminate(false);
|
||||
}).catch(() => undefined);
|
||||
};
|
||||
// A telemetry refresh must never reconnect or reload the stream.
|
||||
}, [connectable, endpointKey, run?.run_id, id, revision]);
|
||||
const mode = run?.camera ?? "follow";
|
||||
const cameraOptions: { value: AiCamera; label: string; disabled: boolean }[] = [
|
||||
{ value: "follow", label: "От третьего лица", disabled: terminal },
|
||||
{ value: "overview", label: "Свободный обзор", disabled: terminal },
|
||||
{ value: "camera", label: "От первого лица", disabled: terminal },
|
||||
];
|
||||
const preview=useInferencePreview(run?.run_id,!terminal);
|
||||
const inputError=useCallback(()=>setCameraError(true),[]);
|
||||
useObserverInput(surface,run?.run_id,mode,connectable&&state==="live",inputError);
|
||||
const changeCamera = (camera: AiCamera) => {
|
||||
if (!run) return;
|
||||
setCameraError(false);
|
||||
@@ -99,35 +49,33 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
|
||||
</div> : null}
|
||||
{controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null}
|
||||
<div className="ai-polygon__viewer">
|
||||
<div className="ai-polygon__viewer-toolbar">
|
||||
<SegmentedControl<AiCamera> label="Вид симуляции" size="dense" value={mode} onChange={changeCamera}
|
||||
items={[{ value: "follow", label: "За ровером", disabled: terminal },
|
||||
{ value: "overview", label: "Обзор", disabled: terminal }, { value: "camera", label: "Камера AI", disabled: terminal }]} />
|
||||
<div className="ai-polygon__actions">
|
||||
{connectable ? <StatusBadge tone={state === "live" ? "success" : "warning"}>
|
||||
{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : "Ожидаем видео"}
|
||||
</StatusBadge> : null}
|
||||
<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}>
|
||||
<Icon name={expanded ? "minimize" : "expand"} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
<SimulationObservationDeck preview={preview}
|
||||
toolbar={<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}><Icon name={expanded ? "minimize" : "expand"} /></IconButton>}
|
||||
videoActions={<Dropdown placement="bottom-end" width={280} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><IconButton ref={setTriggerRef} label="Настройки вида симуляции" aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}><Icon name="settings"/></IconButton>}>
|
||||
<div className="ai-polygon__layer-options">
|
||||
{run?.request?.purpose === "planning" ? <StatusBadge tone="neutral">Планирование маршрута</StatusBadge> : <Select<AiCamera> label="Вид симуляции" value={mode} onChange={changeCamera} options={cameraOptions} disabled={terminal} />}
|
||||
{run?.telemetry?.route_overlay && run.request?.purpose !== "planning" ? <Checker label="Показывать маршрут" checked={routeVisible} onChange={setRouteVisible}/> : null}
|
||||
</div>
|
||||
</Dropdown>}
|
||||
video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
|
||||
<div className="ai-polygon__stream-picture">
|
||||
{connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
|
||||
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
|
||||
<div className="ai-polygon__viewport">
|
||||
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
|
||||
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
|
||||
<div className="ai-polygon__video" inert>
|
||||
<video ref={video} id={`polygon-video-${id}`} autoPlay muted playsInline tabIndex={-1}
|
||||
aria-label={`Видео симуляции ${world.name} с Worker`} />
|
||||
<audio id={`polygon-audio-${id}`} muted />
|
||||
{connectable&&endpoint&&state!=="failed"?<WorkerVideo key={`${run?.run_id}:${revision}`} endpoint={endpoint}
|
||||
onState={(status,value)=>{setState(status);setFps(value);}}/>:null}
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
{!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null}
|
||||
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div>
|
||||
: connectable && (state === "failed" || state === "stalled") ? <div className="ai-polygon__preview-error" role="status">
|
||||
<p>Видеопоток прерван. Состояние симуляции показано выше.</p>
|
||||
<Button onClick={() => setRevision((value) => value + 1)}>Подключить видео</Button>
|
||||
: connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
|
||||
<p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
|
||||
<Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
|
||||
</div> : null}
|
||||
</div>
|
||||
</div>}/>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { DEFAULT_PLANNER_PREFERENCES, panSensitivity } from "../../core/simulation/plannerPreferences";
|
||||
import { zoomDisplacement } from "../../core/simulation/editorZoom";
|
||||
import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/editorNavigation";
|
||||
import { PerspectiveCamera, Vector3 } from "three";
|
||||
|
||||
const KEYS = new Set(["KeyW","KeyA","KeyS","KeyD","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","KeyQ","KeyE","ShiftLeft","ShiftRight"]);
|
||||
/** Input/math only: PlayCanvas remains the sole renderer. */
|
||||
export class EditorCamera {
|
||||
readonly camera = new PerspectiveCamera(60, 1, .05, 3000);
|
||||
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
|
||||
get rotationCenter(){return this.gesture&&!this.gesture.pan?this.gesture.anchor:null;}
|
||||
private keys = new Set<string>();
|
||||
private enabled=true;
|
||||
private topPoints:number[][]|null=null;
|
||||
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;
|
||||
this.topPoints=null;
|
||||
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;
|
||||
this.topPoints=null;
|
||||
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();if(this.topPoints)this.top(this.topPoints);}
|
||||
home(point:number[]){
|
||||
this.topPoints=null;
|
||||
const target=new Vector3(...point);
|
||||
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
|
||||
}
|
||||
top(points:number[][]){
|
||||
if(!points.length)return;
|
||||
this.topPoints=points;
|
||||
const low=[0,1,2].map(i=>Math.min(...points.map(p=>p[i])));
|
||||
const high=[0,1,2].map(i=>Math.max(...points.map(p=>p[i])));
|
||||
const target=new Vector3(...low.map((v,i)=>(v+high[i])/2));
|
||||
const span=Math.max((high[0]-low[0])/this.camera.aspect,high[2]-low[2],10);
|
||||
const distance=span/(2*Math.tan(Math.PI/6))*1.15+high[1]-low[1];
|
||||
this.camera.position.copy(target).add(new Vector3(0,distance,0));
|
||||
this.camera.up.set(0,0,-1);this.camera.lookAt(target);this.camera.up.set(0,1,0);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;
|
||||
this.topPoints=null;
|
||||
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
|
||||
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
|
||||
this.delta.copy(this.forward).multiplyScalar(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown"))
|
||||
.addScaledVector(this.right,pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft"));
|
||||
this.delta.y+=pressed("KeyE")-pressed("KeyQ");
|
||||
this.delta.normalize().multiplyScalar(Math.min(.1,Math.max(0,dt))*(pressed("ShiftLeft","ShiftRight")?16:4));
|
||||
this.camera.position.add(this.delta);this.camera.updateMatrixWorld();
|
||||
}
|
||||
dispose(){
|
||||
this.clear();this.surface.removeEventListener("wheel",this.zoom);
|
||||
this.surface.removeEventListener("pointerdown",this.pointerDown);this.surface.removeEventListener("pointermove",this.pointerMove);
|
||||
this.surface.removeEventListener("pointerup",this.pointerEnd);this.surface.removeEventListener("pointercancel",this.pointerEnd);
|
||||
this.surface.removeEventListener("lostpointercapture",this.pointerEnd);
|
||||
window.removeEventListener("keydown",this.keyDown);window.removeEventListener("keyup",this.keyUp);
|
||||
window.removeEventListener("blur",this.clear);this.canvas.removeEventListener("blur",this.clear);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Mesh, Matrix4, Ray, Vector3 } from "three";
|
||||
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
|
||||
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
|
||||
import { MeshBVH } from "three-mesh-bvh";
|
||||
import { GenerateMeshBVHWorker } from "three-mesh-bvh/worker";
|
||||
|
||||
/** CPU picking only: no Three renderer, physical stepping, or AI in the editor. */
|
||||
export class EditorTerrain {
|
||||
private draco = new DRACOLoader().setDecoderPath({
|
||||
js: "/vendor/playcanvas/draco/1.5.7/draco_wasm_wrapper_gltf.js",
|
||||
wasm: "/vendor/playcanvas/draco/1.5.7/draco_decoder_gltf.wasm",
|
||||
}).setWorkerLimit(1);
|
||||
private builder: GenerateMeshBVHWorker | null = new GenerateMeshBVHWorker();
|
||||
private trees: MeshBVH[] = [];
|
||||
private geometries: BufferGeometry[] = [];
|
||||
private disposed = false;
|
||||
bounds = new Box3();
|
||||
async load(url: string, signal: AbortSignal, transform?: number[]) {
|
||||
const response = await fetch(url, { signal });
|
||||
if (!response.ok) throw new Error("Не удалось открыть поверхность локации.");
|
||||
const gltf = await new GLTFLoader().setDRACOLoader(this.draco).parseAsync(await response.arrayBuffer(), "");
|
||||
if (this.disposed || signal.aborted) {
|
||||
gltf.scene.traverse((object) => { if (object instanceof Mesh) object.geometry.dispose(); });
|
||||
throw new DOMException("Aborted", "AbortError");
|
||||
}
|
||||
if (transform) gltf.scene.applyMatrix4(new Matrix4().fromArray(transform));
|
||||
gltf.scene.updateMatrixWorld(true);
|
||||
gltf.scene.traverse((object) => {
|
||||
if (!(object instanceof Mesh)) return;
|
||||
const input = object.geometry;
|
||||
const geometry = new BufferGeometry();
|
||||
const position = input.getAttribute("position");
|
||||
const xyz = new Float32Array(position.count * 3);
|
||||
const p = new Vector3();
|
||||
for (let i = 0; i < position.count; i++) {
|
||||
p.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
|
||||
xyz[i*3] = p.x; xyz[i*3+1] = p.y; xyz[i*3+2] = p.z;
|
||||
}
|
||||
geometry.setAttribute("position", new BufferAttribute(xyz, 3));
|
||||
geometry.setIndex(input.index!.clone());
|
||||
geometry.computeBoundingBox(); this.bounds.union(geometry.boundingBox!);
|
||||
this.geometries.push(geometry); input.dispose();
|
||||
});
|
||||
for (const geometry of this.geometries) {
|
||||
if (this.disposed || signal.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
this.trees.push(await this.builder!.generate(geometry, { maxLeafTris: 10 }));
|
||||
}
|
||||
this.builder?.dispose(); this.builder = null;
|
||||
}
|
||||
pick(origin: number[], direction: number[], clip = Infinity) {
|
||||
const ray = new Ray(new Vector3(...origin), new Vector3(...direction).normalize());
|
||||
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
|
||||
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
|
||||
.sort((a, b) => a.distance - b.distance)[0]?.point ?? null;
|
||||
}
|
||||
ground(x: number, z: number, near: number, clip = Infinity) {
|
||||
const ray = new Ray(new Vector3(x, this.bounds.max.y + 1, z), new Vector3(0, -1, 0));
|
||||
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
|
||||
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
|
||||
.sort((a, b) => Math.abs(a.point.y - near) - Math.abs(b.point.y - near))[0]?.point ?? null;
|
||||
}
|
||||
dispose() { this.disposed = true; this.draco.dispose(); this.builder?.dispose(); this.builder = null; this.geometries.forEach((g) => g.dispose()); this.trees = []; }
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { SimulationViewTools } from "./SimulationViewTools";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
|
||||
import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import type { RoverSettings } from "../../core/simulation/roverSettings";
|
||||
import { toEditor } from "../../core/simulation/aiEditor";
|
||||
import { PlayCanvasRuntime } from "./PlayCanvasRuntime";
|
||||
import { localScene } from "./localScene";
|
||||
import { useLocalScene } from "./useLocalScene";
|
||||
import { useSimulationFullscreen } from "./useSimulationFullscreen";
|
||||
|
||||
export function LocalManualScene({world,robot,settings,actionsHost,headerActions}: {
|
||||
world:AiWorld; robot:AiRobot; settings?:RoverSettings; actionsHost:HTMLElement|null; headerActions:React.ReactNode;
|
||||
}) {
|
||||
const [preferences]=usePlannerPreferences();
|
||||
const host=useRef<HTMLDivElement>(null), canvas=useRef<HTMLCanvasElement>(null);
|
||||
const viewport=useRef<HTMLDivElement>(null);
|
||||
const runtime=useRef<PlayCanvasRuntime|null>(null);
|
||||
const [retry,setRetry]=useState(0), [ready,setReady]=useState(false), [speed,setSpeed]=useState(0);
|
||||
const {cache,error,setError}=useLocalScene(world,retry);
|
||||
const {expanded,toggle}=useSimulationFullscreen(host);
|
||||
useEffect(()=>{
|
||||
if(cache?.status!=="ready"||!canvas.current)return;
|
||||
let active=true;
|
||||
const view=new PlayCanvasRuntime(); runtime.current=view; setReady(false);
|
||||
void (async()=>{
|
||||
await view.mount(canvas.current!); if(!active)return;
|
||||
view.setQuality(preferences.quality);
|
||||
await view.loadWorld(localScene(cache)); if(!active)return;
|
||||
const configured = settings ? {...robot,physics:{...robot.physics,mass_kg:settings.base_mass_kg+settings.payload_mass_kg}} : robot;
|
||||
await view.setRobot(configured,toEditor([...world.settings.spawn_xy,world.settings.ground_z]),90+world.settings.heading_degrees,settings?.max_speed_mps);
|
||||
if(!active)return;
|
||||
await view.setControlMode("ugv"); if(active)setReady(true);
|
||||
})().catch((e:Error)=>{if(active)setError(e.message);});
|
||||
const timer=setInterval(()=>{if(active)setSpeed(view.speed);},250);
|
||||
return ()=>{active=false;clearInterval(timer);view.dispose();runtime.current=null;};
|
||||
},[cache?.key,cache?.status,robot.sha256,retry]);
|
||||
useEffect(()=>{runtime.current?.setQuality(preferences.quality);},[preferences.quality,ready]);
|
||||
return <div className="ai-polygon__stage" ref={host}>
|
||||
{expanded?<div className="ai-polygon__actions">{headerActions}</div>:actionsHost?createPortal(headerActions,actionsHost):null}
|
||||
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
|
||||
<StatusBadge tone={ready?"success":"neutral"}>{ready?"Ручное управление · локально":"Подготовка сцены"}</StatusBadge></div>
|
||||
<div className="ai-polygon__viewer">
|
||||
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}>
|
||||
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport}/>
|
||||
<canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} />
|
||||
{ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null}
|
||||
{!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null}
|
||||
{error?<div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Application, BLEND_NORMAL, Color, Entity, Layer, StandardMaterial, Vec3 } from "playcanvas";
|
||||
import { toEditor } from "../../core/simulation/aiEditor";
|
||||
import type { AiWaypoint } from "../../core/simulation/aiPolygon";
|
||||
import { axisWorldLength, DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
|
||||
/** Operator-only geometry: never exported into the Worker scene or inference camera. */
|
||||
export class PlannerMarkers {
|
||||
private centroid:Entity|null=null;
|
||||
private layer = new Layer({name:"Planner annotations", clearDepthBuffer:true});
|
||||
private root = new Entity("Route annotations");
|
||||
private materials: StandardMaterial[] = [];
|
||||
private beams: { entity: Entity; material: StandardMaterial; index: number }[] = [];
|
||||
private pivot = new Entity("Waypoint pivot");
|
||||
private arrows: {shaft: Entity; cone: Entity; axis: "x"|"y"|"z"}[] = [];
|
||||
private points: AiWaypoint[] = [];
|
||||
private preferences = DEFAULT_PLANNER_PREFERENCES;
|
||||
private selected: string|null = null;
|
||||
private elapsed = 0;
|
||||
axisLength = 1;
|
||||
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {
|
||||
app.scene.layers.push(this.layer);
|
||||
camera.camera!.layers=[...camera.camera!.layers,this.layer.id];
|
||||
app.root.addChild(this.root); this.root.addChild(this.pivot);
|
||||
const light = new Entity("Annotation light");
|
||||
light.addComponent("light", {type:"directional",color:new Color(1,1,1),intensity:1,layers:[this.layer.id]});
|
||||
light.setEulerAngles(35,25,0);this.root.addChild(light);
|
||||
app.scene.ambientLight = new Color(.45,.45,.45);
|
||||
}
|
||||
private material(color: string, opacity: number) {
|
||||
const m = new StandardMaterial(); m.diffuse.fromString(color);m.emissive.copy(m.diffuse).mulScalar(.12);
|
||||
m.opacity=opacity;m.blendType=BLEND_NORMAL;m.depthWrite=false;m.update();this.materials.push(m);return m;
|
||||
}
|
||||
private shape(name: string, type: "cylinder"|"cone"|"sphere", material: StandardMaterial, parent: Entity) {
|
||||
const entity=new Entity(name);entity.addComponent("render",{type,material,layers:[this.layer.id],castShadows:false,receiveShadows:false});parent.addChild(entity);return entity;
|
||||
}
|
||||
set(points: AiWaypoint[], selected: string|null, preferences: PlannerPreferences) {
|
||||
if(this.centroid && this.selected===selected && this.preferences===preferences && points.length===this.points.length && points.every((v,i)=>v.id===this.points[i].id)) {
|
||||
this.points=points;
|
||||
this.beams.forEach(({entity},i)=>{const [x,y,z]=toEditor(points[i].position);entity.setPosition(x,y+preferences.waypoint.height/2,z);});
|
||||
return;
|
||||
}
|
||||
this.points=points;this.selected=selected;this.preferences=preferences;
|
||||
this.centroid?.destroy();this.centroid=null;
|
||||
this.beams.forEach(({entity})=>entity.destroy());this.beams=[];
|
||||
this.arrows.forEach(({shaft,cone})=>{shaft.destroy();cone.destroy();});this.arrows=[];
|
||||
this.materials.forEach(m=>m.destroy());this.materials=[];
|
||||
const w=preferences.waypoint,p=preferences.pivot,n=preferences.navigation;
|
||||
this.centroid=this.shape("Rotation centre","sphere",this.material(n.centroidColor,n.centroidOpacity),this.root);
|
||||
this.centroid.enabled=false;
|
||||
for(const [index,point] of points.entries()) {
|
||||
const [x,y,z]=toEditor(point.position),material=this.material(w.color,w.opacity);
|
||||
material.emissive.fromString(w.emissionColor);material.emissiveIntensity=w.emission;material.update();
|
||||
const entity=this.shape(point.id,"cylinder",material,this.root);
|
||||
entity.setPosition(x,y+w.height/2,z);entity.setLocalScale(w.diameter,w.height,w.diameter);
|
||||
this.beams.push({entity,material,index});
|
||||
}
|
||||
this.pivot.enabled=!!points.find(point=>point.id===selected);
|
||||
if(this.pivot.enabled) for(const axis of ["x","y","z"] as const) {
|
||||
const material=this.material(p[axis],p.opacity);
|
||||
// Gizmo remains visible when its origin is inside the selected beam.
|
||||
material.depthTest=false;material.update();
|
||||
this.arrows.push({axis,shaft:this.shape(`${axis} shaft`,"cylinder",material,this.pivot),cone:this.shape(`${axis} cone`,"cone",material,this.pivot)});
|
||||
}
|
||||
}
|
||||
setRotationCenter(point:{x:number;y:number;z:number}|null) {
|
||||
if(!this.centroid)return false;
|
||||
const changed=this.centroid.enabled!==!!point;
|
||||
this.centroid.enabled=!!point;
|
||||
if(point)this.centroid.setPosition(point.x,point.y,point.z);
|
||||
return changed;
|
||||
}
|
||||
update(dt: number) {
|
||||
this.elapsed+=dt;
|
||||
if(this.centroid?.enabled) {
|
||||
const depth=this.centroid.getPosition().clone().sub(this.camera.getPosition()).dot(this.camera.forward);
|
||||
const size=axisWorldLength(depth,this.canvas.clientHeight,this.preferences.navigation.centroidPixels);
|
||||
this.centroid.setLocalScale(size,size,size);
|
||||
}
|
||||
const w=this.preferences.waypoint,p=this.preferences.pivot;
|
||||
const motion=window.matchMedia("(prefers-reduced-motion: reduce)").matches?0:w.frequency;
|
||||
this.beams.forEach(({material,index})=>{material.opacity=w.opacity*(motion? .8+.2*Math.cos(this.elapsed*motion*Math.PI*2-index*.3):1);material.update();});
|
||||
const point=this.points.find(v=>v.id===this.selected);
|
||||
if(point) {
|
||||
const position=new Vec3(...toEditor(point.position));this.pivot.setPosition(position);
|
||||
const depth=position.clone().sub(this.camera.getPosition()).dot(this.camera.forward);
|
||||
this.pivot.enabled=depth>0;
|
||||
this.axisLength=axisWorldLength(depth,this.canvas.clientHeight,p.pixels);
|
||||
const unit=this.axisLength/p.pixels,tip=p.cone*unit,stem=this.axisLength-tip;
|
||||
for(const {axis,shaft,cone} of this.arrows) {
|
||||
const v=axis==="x"?new Vec3(1,0,0):axis==="y"?new Vec3(0,1,0):new Vec3(0,0,1);
|
||||
shaft.setLocalPosition(v.clone().mulScalar(stem/2));cone.setLocalPosition(v.clone().mulScalar(stem+tip/2));
|
||||
for(const shape of [shaft,cone])shape.setLocalEulerAngles(axis==="z"?90:0,0,axis==="x"?-90:0);
|
||||
shaft.setLocalScale(p.diameter*unit,stem,p.diameter*unit);cone.setLocalScale(tip*.7,tip,tip*.7);
|
||||
}
|
||||
}
|
||||
return this.beams.length>0 && motion>0;
|
||||
}
|
||||
dispose() {this.app.scene.layers.remove(this.layer);this.root.destroy();this.materials.forEach(m=>m.destroy());}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
|
||||
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<HTMLDivElement|null>; onClose: () => void }) {
|
||||
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation">("pivot");
|
||||
const [saved,update] = usePlannerPreferences();
|
||||
const [value,setValue] = useState(saved);
|
||||
const [rect,setRect] = useState(()=>{
|
||||
const bounds=boundsRef.current?.getBoundingClientRect();
|
||||
const y=(boundsRef.current?.querySelector(".ai-simulation__view-tools")?.getBoundingClientRect().height??48)+24;
|
||||
return {x:96,y,width:400,height:Math.max(230,Math.min(490,(bounds?.height??600)-y-12))};
|
||||
});
|
||||
const [maximized,setMaximized] = useState(false);
|
||||
const editing = useRef(false), pending = useRef<PlannerPreferences|null>(null);
|
||||
const [error,setError] = useState<string|null>(null);
|
||||
const commit = () => {
|
||||
editing.current=false;
|
||||
const next=pending.current; pending.current=null;
|
||||
if(!next)return;
|
||||
try { update(next);setError(null); }
|
||||
catch { setError("Не удалось сохранить настройки в этом браузере."); }
|
||||
};
|
||||
const commitRef=useRef(commit);commitRef.current=commit;
|
||||
useEffect(()=>{if(!editing.current)setValue(saved);},[saved]);
|
||||
useEffect(()=>{
|
||||
const release=()=>commitRef.current();
|
||||
const escape=(e:KeyboardEvent)=>{
|
||||
if(e.key!=="Escape" || e.defaultPrevented || document.querySelector(".nodedc-dropdown-surface"))return;
|
||||
e.preventDefault();release();onClose();
|
||||
};
|
||||
window.addEventListener("pointerup",release);window.addEventListener("pointercancel",release);
|
||||
window.addEventListener("keyup",release);window.addEventListener("blur",release);
|
||||
window.addEventListener("keydown",escape);
|
||||
return ()=>{
|
||||
window.removeEventListener("pointerup",release);window.removeEventListener("pointercancel",release);
|
||||
window.removeEventListener("keyup",release);window.removeEventListener("blur",release);
|
||||
window.removeEventListener("keydown",escape);
|
||||
};
|
||||
},[onClose]);
|
||||
const set = (group: "pivot"|"waypoint"|"navigation", key: string, next: string|number) => {
|
||||
const base=pending.current??value;
|
||||
const changed={...base,[group]:{...base[group],[key]:next}};
|
||||
pending.current=changed;setValue(changed);
|
||||
if(!editing.current)commit();
|
||||
};
|
||||
const range = (group: "pivot"|"waypoint"|"navigation", key: string, label: string, min: number, max: number, step: number, unit: string) =>
|
||||
<RangeControl key={key} label={label} min={min} max={max} step={step}
|
||||
value={Number(value[group][key as keyof typeof value[typeof group]])} onChange={(v)=>set(group,key,v)}
|
||||
formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
|
||||
return <WorkspaceWindow boundsRef={boundsRef} rect={rect} onRectChange={setRect}
|
||||
resizeIndicator={false}
|
||||
maximized={maximized} onMaximizedChange={setMaximized} minWidth={320} minHeight={230}
|
||||
zIndex={100} title="Настройки планировщика" closeLabel="Закрыть настройки планировщика"
|
||||
onClose={()=>{commit();onClose();}}>
|
||||
<div className="ai-polygon__form" onPointerDownCapture={(e)=>{
|
||||
if((e.target as Element).closest('input[type="range"], [role="slider"]'))editing.current=true;
|
||||
}} onKeyDownCapture={(e)=>{
|
||||
if((e.target as Element).matches('input[type="range"], [role="slider"]') && ["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(e.key))editing.current=true;
|
||||
}}>
|
||||
<Select label="Раздел настроек планировщика" value={section} onChange={setSection}
|
||||
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"}]}/>
|
||||
{section === "pivot" ? <>
|
||||
{range("pivot","pixels","Размер осей",50,220,5,"px")}
|
||||
{range("pivot","diameter","Диаметр стержня",2,16,1,"px")}
|
||||
{range("pivot","cone","Размер конусов",10,40,1,"px")}
|
||||
{range("pivot","opacity","Непрозрачность",.15,1,.05,"")}
|
||||
{(["x","y","z"] as const).map((axis)=><ControlRow key={axis} label={`Цвет ${axis.toUpperCase()}`}><ColorField label={`Цвет ${axis.toUpperCase()}`} value={value.pivot[axis]} onChange={(v)=>set("pivot",axis,v)}/></ControlRow>)}
|
||||
</> : section === "waypoint" ? <>
|
||||
{range("waypoint","diameter","Диаметр",.05,3,.05,"м")}
|
||||
{range("waypoint","height","Высота",.2,50,.1,"м")}
|
||||
<ControlRow label="Цвет waypoint"><ColorField label="Цвет waypoint" value={value.waypoint.color} onChange={(v)=>set("waypoint","color",v)}/></ControlRow>
|
||||
{range("waypoint","opacity","Непрозрачность",.1,1,.05,"")}
|
||||
{range("waypoint","frequency","Пульсация",0,3,.1,"Гц")}
|
||||
<strong>Свечение</strong>
|
||||
{range("waypoint","emission","Сила эмиссии",0,5,.1,"")}
|
||||
<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow>
|
||||
</> : <>
|
||||
<strong>Сдвиг камеры</strong>
|
||||
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p>
|
||||
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
|
||||
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")}
|
||||
{range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")}
|
||||
{range("navigation","farPan","Чувствительность вдали",.1,5,.1,"×")}
|
||||
<strong>Зум</strong>
|
||||
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
|
||||
<strong>Центр вращения</strong>
|
||||
<p>Шарик появляется в точке нажатия на время вращения.</p>
|
||||
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
|
||||
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
|
||||
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
|
||||
</>}
|
||||
{error?<ToastStack items={[{id:"preferences",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
</div>
|
||||
</WorkspaceWindow>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
|
||||
import {
|
||||
Application,
|
||||
Asset,
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
type ModelComponent,
|
||||
type ScriptType,
|
||||
} from "playcanvas";
|
||||
import type { AiRobot } from "../../core/simulation/aiPolygon";
|
||||
import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs";
|
||||
|
||||
import {
|
||||
@@ -76,24 +78,10 @@ const HOME_POSITION = new Vec3(0, 1, 0);
|
||||
const HOME_FOCUS = new Vec3(1, 1, 0);
|
||||
const DRACO_DECODER_ROOT = "/vendor/playcanvas/draco/1.5.7";
|
||||
|
||||
const QUALITY_PROFILES: Record<SimulationQuality, {
|
||||
lodBaseDistance: number;
|
||||
lodMultiplier: number;
|
||||
lodRangeMin: number;
|
||||
lodRangeMax: number;
|
||||
pixelRatio: number;
|
||||
splatBudget: number;
|
||||
targetFps: number;
|
||||
}> = {
|
||||
low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 350_000, targetFps: 30 },
|
||||
medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 700_000, targetFps: 45 },
|
||||
high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 1_200_000, targetFps: 60 },
|
||||
ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 2_500_000, targetFps: 60 },
|
||||
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60 },
|
||||
};
|
||||
|
||||
export class PlayCanvasRuntime implements SimulationRuntime {
|
||||
private app: Application | null = null;
|
||||
private robotAsset: Asset | null = null;
|
||||
private canvas: HTMLCanvasElement | null = null;
|
||||
private camera: Entity | null = null;
|
||||
private cameraController: CameraController | null = null;
|
||||
@@ -155,7 +143,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
|
||||
antialias: true,
|
||||
alpha: false,
|
||||
preserveDrawingBuffer: false,
|
||||
powerPreference: "high-performance",
|
||||
powerPreference: "default",
|
||||
},
|
||||
});
|
||||
this.app = app;
|
||||
@@ -306,6 +294,27 @@ export class PlayCanvasRuntime implements SimulationRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
async setRobot(robot: AiRobot, ground: number[], headingDegrees: number, maxSpeedMps = .5): Promise<void> {
|
||||
const app = this.requiredApp();
|
||||
const publicRoot = "apps/control-station/public/";
|
||||
if (!robot.visual.source.startsWith(publicRoot)) throw new Error("Модель ровера недоступна.");
|
||||
const asset = new Asset(robot.name,"container",{ url: "/"+robot.visual.source.slice(publicRoot.length) });
|
||||
this.robotAsset = asset; app.assets.add(asset);
|
||||
await new Promise<void>((resolve,reject) => {
|
||||
asset.ready(()=>resolve()); asset.once("error",()=>reject(new Error("Модель ровера не загрузилась.")));
|
||||
app.assets.load(asset);
|
||||
});
|
||||
if (this.disposed) { asset.unload(); return; }
|
||||
const resource = asset.resource as ContainerResource;
|
||||
this.setUgvPreset({ presetName: robot.name, massKg: robot.physics.mass_kg,
|
||||
dimensionsMeters: { length:robot.physics.length_m, width:robot.physics.width_m,
|
||||
height:robot.physics.height_m, groundClearance: .15 },
|
||||
maxSpeedMetersPerSecond: maxSpeedMps, maxTurnRateDegrees: 45, invertSteering: false });
|
||||
this.ugvController!.setRobot(()=>resource.instantiateRenderEntity(),new Vec3(...ground),headingDegrees,robot.visual.motion);
|
||||
}
|
||||
|
||||
get speed(): number { return this.ugvController?.speed ?? 0; }
|
||||
|
||||
setQuality(quality: SimulationQuality): void {
|
||||
this.quality = quality;
|
||||
this.applyQuality();
|
||||
@@ -380,6 +389,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
|
||||
this.unloadWorld();
|
||||
this.ugvController?.dispose();
|
||||
this.ugvController = null;
|
||||
this.robotAsset?.unload(); this.robotAsset = null;
|
||||
if (this.app) {
|
||||
this.app.autoRender = false;
|
||||
this.app.renderNextFrame = false;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useState } from "react";
|
||||
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import type { AiRobot } from "../../core/simulation/aiPolygon";
|
||||
import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings";
|
||||
|
||||
export function RoverSettingsWindow({robot,value,manual,onApply,onClose}:{
|
||||
robot:AiRobot; value:RoverSettings; manual:boolean;
|
||||
onApply:(value:RoverSettings)=>void; onClose:()=>void;
|
||||
}) {
|
||||
const [draft,setDraft] = useState(value);
|
||||
const field = (key:Exclude<keyof RoverSettings,"schema_version">, label:string, min:number, max:number|undefined, step:number) =>
|
||||
<TextField label={label} type="number" min={min} max={max} step={step}
|
||||
value={Number.isFinite(draft[key])?draft[key]:""}
|
||||
onChange={e=>setDraft({...draft,[key]:e.target.value===""?NaN:Number(e.target.value)})}/>;
|
||||
const valid=validRoverSettings(draft,robot);
|
||||
return <Window open title={`Настройки ровера · ${robot.name}`} onClose={onClose}
|
||||
footer={<WindowFooterActions>
|
||||
<Button onClick={()=>setDraft(current=>({...defaultRoverSettings(robot,value.max_speed_mps),max_speed_mps:current.max_speed_mps}))}>Сбросить массу и нагрузку</Button>
|
||||
<Button variant="primary" disabled={!valid} onClick={()=>onApply(draft)}>Применить</Button>
|
||||
</WindowFooterActions>}>
|
||||
<div className="ai-polygon__form ai-polygon__report">
|
||||
{field("max_speed_mps","Скорость до, м/с",.05,undefined,.01)}
|
||||
{field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)}
|
||||
{field("payload_mass_kg","Дополнительный груз, кг",0,500,1)}
|
||||
{field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)}
|
||||
<p>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</p>
|
||||
<p>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</p>
|
||||
{manual?<p>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</p>:null}
|
||||
<p>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</p>
|
||||
{!valid?<p role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</p>:null}
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Entity } from "playcanvas";
|
||||
import { beltPose, type RoverMotion } from "../../core/simulation/roverMotion";
|
||||
|
||||
export class RoverTrackMotion {
|
||||
private distance = { L:0, R:0 };
|
||||
private links: { node:Entity; side:"L"|"R"; index:number }[] = [];
|
||||
private wheels: { node:Entity; side:"L"|"R"; radius:number; angle:number }[] = [];
|
||||
constructor(root: Entity, private motion: RoverMotion) {
|
||||
const requireNode = (name: string) => {
|
||||
const node = root.findByName(name) as Entity | null;
|
||||
if (!node) throw new Error(`В модели отсутствует узел анимации ${name}`);
|
||||
return node;
|
||||
};
|
||||
for (const side of ["L","R"] as const) {
|
||||
for (let index=0;index<motion.link_count;index++) {
|
||||
this.links.push({node:requireNode(`${side}_BELT_${String(index).padStart(2,"0")}`),side,index});
|
||||
}
|
||||
}
|
||||
this.wheels = motion.wheels.map(w => ({node:requireNode(w.node),side:w.node[0] as "L"|"R",radius:w.radius_m,angle:0}));
|
||||
}
|
||||
update(dt: number, forwardSpeed: number, yawRate: number) {
|
||||
// Local controller uses +Z forward, +Y up: positive yaw turns right.
|
||||
const speed={L:forwardSpeed+yawRate*this.motion.track_width_m/2,R:forwardSpeed-yawRate*this.motion.track_width_m/2};
|
||||
const step=Math.min(.1,Math.max(0,dt));
|
||||
for (const side of ["L","R"] as const) this.distance[side]=(this.distance[side]+speed[side]*step)%this.motion.length_m;
|
||||
for (const w of this.wheels) {
|
||||
w.angle=(w.angle-speed[w.side]*step/w.radius)%(2*Math.PI);
|
||||
w.node.setLocalEulerAngles(0,0,w.angle*180/Math.PI);
|
||||
}
|
||||
for (const link of this.links) {
|
||||
const pose=beltPose(this.motion,this.distance[link.side],link.side,link.index);
|
||||
link.node.setLocalPosition(pose.position[0],pose.position[1],pose.position[2]);
|
||||
link.node.setLocalEulerAngles(0,0,pose.angle*180/Math.PI);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import {useEffect,useRef,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
|
||||
import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout';
|
||||
import {useObservationPresets} from '../../core/fleet/useObservationPresets';
|
||||
import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets';
|
||||
import {ObservationLayoutSaveWindow} from '../observation/ObservationLayoutSaveWindow';
|
||||
import {ObservationDeck} from '../observation/ObservationDeck';
|
||||
import {ObservationPanelHeader} from '../observation/ObservationPanelHeader';
|
||||
import {AiInferencePreview,type InferencePreview} from './AiInferencePreview';
|
||||
import '../observation/observation.css';
|
||||
|
||||
const storageKey='missioncore.simulation.observation.v1';
|
||||
export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{video:ReactNode;videoActions:ReactNode;toolbar:ReactNode;preview:null|InferencePreview}){
|
||||
const presets=useObservationPresets('missioncore.simulation.observation-presets.v1',storageKey);
|
||||
const {layout,setLayout}=presets;
|
||||
const [saving,setSaving]=useState(false);
|
||||
const [editing,setEditing]=useState<string|null>(null);
|
||||
const edited=presets.presets.find(p=>p.id===editing);
|
||||
const [full,setFull]=useState<string|null>(null);
|
||||
const mounts=useRef(new Map<string,HTMLElement>());
|
||||
const sources=[{id:'video',label:'Симуляция'},...(preview?.layers??[])];
|
||||
for(const source of sources)if(!mounts.current.has(source.id)){const element=document.createElement('div');element.className='observation-panel-mount';mounts.current.set(source.id,element);}
|
||||
const ids=orderedObservationIDs(layout,sources.map(source=>source.id));
|
||||
const visible=ids.filter(id=>!layout.hidden.includes(id)&&(id==='video'||layout.catalogVisible?.includes(id)));
|
||||
const effectiveFull=full&&visible.includes(full)?full:null;
|
||||
const show=(id:string,checked:boolean)=>setLayout(value=>({...value,catalogVisible:checked?[...new Set([...(value.catalogVisible??[]),id])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:checked?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key==='Escape'&&effectiveFull&&!document.querySelector('[role=dialog],[role=listbox]')){setFull(null);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull]);
|
||||
return <div className="ai-polygon__observation">
|
||||
<div className="ai-polygon__observation-toolbar">
|
||||
{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}
|
||||
<Dropdown placement="bottom-end" width={340} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><Button ref={setTriggerRef} icon={<Icon name="layers"/>} aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Камеры и слои</Button>}>
|
||||
{({close})=><div className="ai-polygon__layer-options" role="group" aria-label="Камеры и слои">
|
||||
<Select label="Расположение окон" value={presets.selected} options={[...observationArrangements,...presets.presets.map(p=>({value:p.id,label:p.name,action:{label:`Редактировать раскладку «${p.name}»`,icon:<Icon name="edit"/>,onAction:()=>{close();presets.clearError();setEditing(p.id);}}}))]} onChange={value=>{presets.select(value);setFull(null);}}/>
|
||||
{ids.map(id=>{const source=sources.find(item=>item.id===id)!;return <Checker key={id} label={source.label} checked={visible.includes(id)} onChange={checked=>show(id,checked)}/>;})}
|
||||
<Button onClick={()=>{const known=[...new Set([...ids,...(layout.catalogVisible??[])])].filter(id=>!layout.hidden.includes(id)&&(id==='video'||layout.catalogVisible?.includes(id)));const tree=observationTree(layout,known);if(tree)setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)));close();setSaving(true);}}>Сохранить расположение</Button>
|
||||
</div>}
|
||||
</Dropdown>
|
||||
{toolbar}
|
||||
</div>
|
||||
<div className="observation-deck">{visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.id,source.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
|
||||
{sources.filter(source=>visible.includes(source.id)).map(source=>createPortal(
|
||||
<div className="observation-panel"><GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
|
||||
<ObservationPanelHeader><DockHandle id={source.id} label={source.label}/><div className="observation-panel__title"><h3 title={source.label}>{source.label}</h3></div><div className="observation-actions">
|
||||
{source.id==='video'&&videoActions}
|
||||
<IconButton label={`${effectiveFull===source.id?'Восстановить':'Развернуть'} · ${source.label}`} onClick={()=>setFull(value=>value===source.id?null:source.id)}><Icon name={effectiveFull===source.id?'minimize':'expand'}/></IconButton>
|
||||
<IconButton label={`Скрыть · ${source.label}`} onClick={()=>show(source.id,false)}><Icon name="close"/></IconButton>
|
||||
</div></ObservationPanelHeader>
|
||||
<div className="observation-mount">{source.id==='video'?video:preview&&<AiInferencePreview preview={preview} layer={source.id}/>}</div>
|
||||
</GlassSurface></div>,mounts.current.get(source.id)!,source.id))}
|
||||
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
|
||||
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
|
||||
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
|
||||
<ToastStack items={presets.error?[{id:"layout-save",tone:"error",title:"Раскладка не сохранена",description:presets.error}]:[]} onDismiss={presets.clearError}/>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
|
||||
import { SimulationProjectWindow } from "./SimulationProjectWindow";
|
||||
|
||||
/** Reuses the existing resumable Gaussian Pipeline admission workflow. */
|
||||
export function SimulationSourceImport({open,onClose,onPly,onReady}: {
|
||||
open:boolean; onClose:()=>void; onPly:()=>void; onReady:(worldId:string)=>void;
|
||||
}) {
|
||||
const [archive,setArchive]=useState(false), [project,setProject]=useState<SimulationProject|null>(null);
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
const [pending,setPending]=useState<SimulationProject[]>([]);
|
||||
useEffect(()=>{
|
||||
if(!open)return;
|
||||
const abort=new AbortController();setError(null);
|
||||
void fetchSimulationProjects(abort.signal).then(rows=>{
|
||||
if(!abort.signal.aborted)setPending(rows.filter(p=>p.status!=='ready'));
|
||||
}).catch(e=>{if(!abort.signal.aborted)setError(e.message);});
|
||||
return()=>abort.abort();
|
||||
},[open]);
|
||||
useEffect(()=>{
|
||||
if(!project||project.status==='ready'||project.status==='failed')return;
|
||||
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||
const poll=async()=>{
|
||||
try {
|
||||
const projects=await fetchSimulationProjects(abort.signal);
|
||||
const next=projects.find(p=>p.projectId===project.projectId);
|
||||
if(abort.signal.aborted)return;
|
||||
if(next?.status==='ready'){setProject(null);onReady(next.projectId.replace('sim-','aiworld-'));return;}
|
||||
if(next){setProject(next);if(next.status==='failed')return;}
|
||||
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
|
||||
if(!abort.signal.aborted)timer=setTimeout(()=>void poll(),2000);
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[project?.projectId,project?.status]);
|
||||
return <>
|
||||
<Window open={open} title="Импорт локации" onClose={onClose}><div className="ai-polygon__actions">
|
||||
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
|
||||
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
|
||||
</div>
|
||||
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><p>{p.name}</p>
|
||||
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
{error?<p role="alert">{error}</p>:null}
|
||||
</Window>
|
||||
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
|
||||
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
|
||||
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
|
||||
<p>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</p>
|
||||
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
|
||||
</LoadingRegion>
|
||||
</Window>:null}
|
||||
</>;
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
} from "playcanvas";
|
||||
import { MeshoptSimplifier } from "meshoptimizer/simplifier";
|
||||
import type { SimulationUgvPreset } from "../../core/simulation/projects";
|
||||
import type { RoverMotion } from "../../core/simulation/roverMotion";
|
||||
import { RoverTrackMotion } from "./RoverTrackMotion";
|
||||
|
||||
const AMMO_MODULE_ROOT = "/vendor/playcanvas/ammo/2026-08-25";
|
||||
const UGV_SPAWN_POSITION = new Vec3(0, 1.15, 0);
|
||||
@@ -230,6 +232,12 @@ export class SimulationUgvController {
|
||||
private orbitIdleSeconds = 0;
|
||||
private cameraOrbitInitialized = false;
|
||||
private active = false;
|
||||
private disposed = false;
|
||||
private spawnGround = new Vec3(0,0,0);
|
||||
private spawnRotation = UGV_SPAWN_ROTATION.clone();
|
||||
private visualFactory: (() => Entity) | null = null;
|
||||
private motion: RoverMotion | undefined;
|
||||
private trackMotion: RoverTrackMotion | null = null;
|
||||
private vehicleEntity: Entity | null = null;
|
||||
private vehicle: NativeRaycastVehicle | null = null;
|
||||
private vehicleRaycaster: NativeObject | null = null;
|
||||
@@ -251,6 +259,16 @@ export class SimulationUgvController {
|
||||
this.settings = cloneUgvPreset(initialSettings);
|
||||
}
|
||||
|
||||
setRobot(visualFactory: () => Entity, ground: Vec3, headingDegrees: number, motion?: RoverMotion): void {
|
||||
if (this.active) throw new Error("Сначала остановите ручное управление.");
|
||||
this.visualFactory = visualFactory;
|
||||
this.motion = motion;
|
||||
this.spawnGround.copy(ground);
|
||||
this.spawnRotation.set(0,headingDegrees,0);
|
||||
}
|
||||
|
||||
get speed(): number { return (this.vehicle?.getCurrentSpeedKmHour() ?? 0) / 3.6; }
|
||||
|
||||
get enabled(): boolean {
|
||||
return this.active;
|
||||
}
|
||||
@@ -269,9 +287,11 @@ export class SimulationUgvController {
|
||||
async enable(collisionWorld: Entity): Promise<void> {
|
||||
if (this.active) return;
|
||||
await nextAnimationFrame();
|
||||
if (this.disposed) return;
|
||||
try {
|
||||
await this.createStaticCollisionBodies(collisionWorld);
|
||||
await nextAnimationFrame();
|
||||
if (this.disposed) { this.disable(); return; }
|
||||
this.spawnPosition.copy(this.findSafeSpawnPosition());
|
||||
this.createVehicle();
|
||||
this.attachInput();
|
||||
@@ -302,6 +322,7 @@ export class SimulationUgvController {
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.disable();
|
||||
}
|
||||
|
||||
@@ -309,7 +330,7 @@ export class SimulationUgvController {
|
||||
const vehicleEntity = this.vehicleEntity as (Entity & NativeRigidBodyAccess) | null;
|
||||
const rigidbody = vehicleEntity?.rigidbody;
|
||||
if (!vehicleEntity || !rigidbody) return;
|
||||
rigidbody.teleport(this.spawnPosition, UGV_SPAWN_ROTATION);
|
||||
rigidbody.teleport(this.spawnPosition, this.spawnRotation);
|
||||
rigidbody.linearVelocity = ZERO;
|
||||
rigidbody.angularVelocity = ZERO;
|
||||
this.vehicle?.resetSuspension();
|
||||
@@ -455,6 +476,11 @@ export class SimulationUgvController {
|
||||
}
|
||||
|
||||
body?.setActivationState(DISABLE_DEACTIVATION);
|
||||
if (rigidbody && this.trackMotion) {
|
||||
const forward = this.vehicleEntity.getRotation().transformVector(new Vec3(0,0,1));
|
||||
const up = this.vehicleEntity.up;
|
||||
this.trackMotion.update(deltaSeconds,rigidbody.linearVelocity.dot(forward),rigidbody.angularVelocity.dot(up));
|
||||
}
|
||||
if (this.vehicleEntity.getPosition().y < -8) this.reset();
|
||||
this.updateCamera(deltaSeconds);
|
||||
}
|
||||
@@ -593,6 +619,7 @@ export class SimulationUgvController {
|
||||
|
||||
const rootInverse = collisionWorld.getWorldTransform().clone().invert();
|
||||
for (let index = 0; index < meshInstances.length; index += 1) {
|
||||
if (this.disposed) return;
|
||||
const meshInstance = meshInstances[index];
|
||||
const physicsMesh = createPhysicsProxyMesh(
|
||||
this.app,
|
||||
@@ -707,6 +734,15 @@ export class SimulationUgvController {
|
||||
});
|
||||
}
|
||||
|
||||
if (this.visualFactory) {
|
||||
// Keep the physical contact proxy; the operator sees only the selected CAD model.
|
||||
for (const render of vehicle.findComponents("render")) (render as { enabled: boolean }).enabled = false;
|
||||
const visual = this.visualFactory();
|
||||
visual.setLocalEulerAngles(0,-90,0); // glTF +X forward -> controller +Z forward
|
||||
visual.setLocalPosition(0,-dimensions.originHeight,0);
|
||||
vehicle.addChild(visual);
|
||||
this.trackMotion = this.motion ? new RoverTrackMotion(visual,this.motion) : null;
|
||||
}
|
||||
vehicle.setLocalPosition(this.spawnPosition);
|
||||
this.app.root.addChild(vehicle);
|
||||
|
||||
@@ -827,12 +863,12 @@ export class SimulationUgvController {
|
||||
const heights: number[] = [];
|
||||
let suitable = true;
|
||||
for (const [sampleX, sampleZ] of footprint) {
|
||||
const x = UGV_SPAWN_POSITION.x + offsetX + sampleX;
|
||||
const z = UGV_SPAWN_POSITION.z + offsetZ + sampleZ;
|
||||
from.set(x, 8, z);
|
||||
to.set(x, -8, z);
|
||||
const x = this.spawnGround.x + offsetX + sampleX;
|
||||
const z = this.spawnGround.z + offsetZ + sampleZ;
|
||||
from.set(x, this.spawnGround.y + 3, z);
|
||||
to.set(x, this.spawnGround.y - 3, z);
|
||||
const hit = physics.raycastFirst(from, to);
|
||||
if (!hit || hit.normal.y < 0.72 || Math.abs(hit.point.y) > 2.5) {
|
||||
if (!hit || hit.normal.y < 0.72 || Math.abs(hit.point.y - this.spawnGround.y) > 2.5) {
|
||||
suitable = false;
|
||||
break;
|
||||
}
|
||||
@@ -843,8 +879,8 @@ export class SimulationUgvController {
|
||||
const maximum = Math.max(...heights);
|
||||
if (maximum - minimum > 0.32) continue;
|
||||
|
||||
const x = UGV_SPAWN_POSITION.x + offsetX;
|
||||
const z = UGV_SPAWN_POSITION.z + offsetZ;
|
||||
const x = this.spawnGround.x + offsetX;
|
||||
const z = this.spawnGround.z + offsetZ;
|
||||
const ground = heights.reduce((sum, height) => sum + height, 0) / heights.length;
|
||||
const clearanceHeight = ground + dimensions.originHeight;
|
||||
const origin = new Vec3(x, clearanceHeight, z);
|
||||
@@ -855,10 +891,11 @@ export class SimulationUgvController {
|
||||
if (!blocked) return new Vec3(x, ground + dimensions.originHeight, z);
|
||||
}
|
||||
|
||||
return UGV_SPAWN_POSITION.clone();
|
||||
throw new Error("В месте старта нет опоры для ровера. Выберите другую точку старта.");
|
||||
}
|
||||
|
||||
private destroyVehicle(): void {
|
||||
this.trackMotion = null;
|
||||
if (this.vehicle && this.dynamicsWorld) {
|
||||
runCleanup("remove vehicle action", () => this.dynamicsWorld?.removeAction(this.vehicle as NativeObject));
|
||||
}
|
||||
@@ -890,6 +927,7 @@ export class SimulationUgvController {
|
||||
window.addEventListener("keydown", this.onKeyDown, true);
|
||||
window.addEventListener("keyup", this.onKeyUp, true);
|
||||
window.addEventListener("blur", this.onWindowBlur);
|
||||
this.canvas.addEventListener("blur", this.onWindowBlur);
|
||||
this.canvas.addEventListener("pointerdown", this.onOrbitPointerDown);
|
||||
this.canvas.addEventListener("pointermove", this.onOrbitPointerMove);
|
||||
this.canvas.addEventListener("pointerup", this.onOrbitPointerUp);
|
||||
@@ -901,6 +939,7 @@ export class SimulationUgvController {
|
||||
window.removeEventListener("keydown", this.onKeyDown, true);
|
||||
window.removeEventListener("keyup", this.onKeyUp, true);
|
||||
window.removeEventListener("blur", this.onWindowBlur);
|
||||
this.canvas.removeEventListener("blur", this.onWindowBlur);
|
||||
this.canvas.removeEventListener("pointerdown", this.onOrbitPointerDown);
|
||||
this.canvas.removeEventListener("pointermove", this.onOrbitPointerMove);
|
||||
this.canvas.removeEventListener("pointerup", this.onOrbitPointerUp);
|
||||
@@ -965,7 +1004,7 @@ export class SimulationUgvController {
|
||||
}
|
||||
|
||||
private onKeyDown = (event: KeyboardEvent): void => {
|
||||
if (!this.active || isTextEntry(event.target)) return;
|
||||
if (!this.active || document.activeElement !== this.canvas || isTextEntry(event.target)) return;
|
||||
if (!UGV_KEYS.has(event.code)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useState, type ReactNode, type RefObject } from "react";
|
||||
import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { PlannerSettings } from "./PlannerSettings";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
|
||||
export function SimulationViewTools({expanded,toggle,planning=false,boundsRef,children}: {expanded:boolean;toggle:()=>void;planning?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
|
||||
const [prefs,update]=usePlannerPreferences();
|
||||
const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
return <>
|
||||
<div className="ai-simulation__view-tools nodedc-scene-controls">
|
||||
{children}
|
||||
<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
|
||||
options={[{value:"low",label:"Низкое"},{value:"medium",label:"Среднее"},{value:"high",label:"Высокое"},{value:"ultra",label:"Ультра"},{value:"maximum",label:"Максимум"}]}
|
||||
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>
|
||||
<IconButton label="Помощь по управлению" onClick={()=>setHelp(true)}><Icon name="info"/></IconButton>
|
||||
{planning?<IconButton label="Настройки планировщика" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
|
||||
<IconButton label={expanded?"Свернуть просмотр":"Развернуть просмотр"} onClick={toggle}><Icon name={expanded?"minimize":"expand"}/></IconButton>
|
||||
</div>
|
||||
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
|
||||
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
|
||||
<div className="ai-polygon__form">{planning?<>
|
||||
<p>ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.</p>
|
||||
<p>Прокрутка — зум к курсору, в том числе в режиме добавления точек.</p>
|
||||
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
|
||||
<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>
|
||||
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
|
||||
</Window>
|
||||
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
|
||||
import { streamRecovery } from "../../core/simulation/streamRecovery";
|
||||
export type WorkerVideoState="connecting"|"live"|"failed";
|
||||
export function WorkerVideo({endpoint,onState}:{endpoint:AiStreamEndpoint;onState:(state:WorkerVideoState,fps:number|null)=>void}){
|
||||
const frame=useRef<HTMLIFrameElement>(null),callback=useRef(onState);callback.current=onState;
|
||||
const [attempt,setAttempt]=useState(0);
|
||||
useEffect(()=>{
|
||||
const started=performance.now();let lastFrame:number|null=null,failedAt:number|null=null,finished=false;
|
||||
callback.current("connecting",null);
|
||||
const receive=(e:MessageEvent)=>{
|
||||
if(finished||e.origin!==location.origin||e.source!==frame.current?.contentWindow||e.data?.type!=="missioncore-worker-video")return;
|
||||
if(e.data.state==="live"&&Number.isFinite(e.data.fps)){
|
||||
lastFrame=performance.now();failedAt=null;callback.current("live",e.data.fps);
|
||||
}else if(e.data.state==="failed")failedAt??=performance.now();
|
||||
};
|
||||
const timer=setInterval(()=>{
|
||||
const action=streamRecovery(performance.now(),started,lastFrame,failedAt,attempt);
|
||||
if(finished||action==="wait")return;
|
||||
finished=true;
|
||||
if(action==="retry")setAttempt(n=>n+1);else callback.current("failed",null);
|
||||
},500);
|
||||
window.addEventListener("message",receive);
|
||||
return ()=>{finished=true;clearInterval(timer);window.removeEventListener("message",receive);};
|
||||
},[attempt]);
|
||||
return <iframe key={attempt} ref={frame} className="ai-polygon__video-frame" title="Видеопоток Worker"
|
||||
src="/simulation-stream.html" allow="autoplay" tabIndex={-1}
|
||||
onLoad={()=>frame.current?.contentWindow?.postMessage({type:"missioncore-worker-connect",endpoint},location.origin)}/>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Mat4, Quat, Vec3 } from "playcanvas";
|
||||
import { editorAssetUrl, type EditorCache } from "../../core/simulation/aiEditor";
|
||||
import type { SimulationWorldManifest } from "../../core/simulation/projects";
|
||||
|
||||
/** Both local modes consume the same disk-backed assets and metric transforms. */
|
||||
export function localScene(cache: EditorCache): SimulationWorldManifest {
|
||||
const saved = cache.local_scene;
|
||||
const matrix = (r: number[]) => new Mat4().setFromEulerAngles(r[0],r[1],r[2]);
|
||||
const visual = saved ? matrix(saved.visual_rotation) : new Mat4().mul2(
|
||||
matrix([-90,0,0]), new Mat4().setTRS(new Vec3(),
|
||||
new Quat().setFromEulerAngles(...cache.world.settings.rotation_degrees),
|
||||
new Vec3().set(cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit)));
|
||||
return {
|
||||
schemaVersion: "missioncore.simulation-world-manifest/v1", projectId: cache.world.world_id,
|
||||
visual: { previewSogUrl: null, streamedSogUrl: saved?.visual_url ?? editorAssetUrl(cache.key,"scene.sog") },
|
||||
collision: { meshUrl: saved?.collision_url ?? editorAssetUrl(cache.key,"collision.glb"), available: true },
|
||||
transforms: { worldFromVisual: Array.from(visual.data),
|
||||
worldFromCollision: Array.from((saved ? matrix(saved.collision_rotation) : new Mat4()).data) },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #000; }
|
||||
body { display: grid; place-items: center; }
|
||||
/* Round the decoded picture itself, including when the viewport letterboxes. */
|
||||
video { display: block; width: 100%; height: 100%; object-fit: cover; }
|
||||
audio { display: none; }
|
||||
@@ -0,0 +1,54 @@
|
||||
import { AppStreamer, StreamType, LogLevel, EventStatus } from "@nvidia/ov-web-rtc";
|
||||
import { StreamDiagnostics } from "../../core/simulation/streamDiagnostics";
|
||||
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
|
||||
import "@nodedc/tokens/tokens.css";
|
||||
import "./streamFrame.css";
|
||||
|
||||
// A dedicated document owns NVIDIA's window-global handlers and peer connection.
|
||||
// Removing this iframe releases them even if the SDK is stuck in STARTING.
|
||||
const video=document.getElementById("worker-video") as HTMLVideoElement;
|
||||
const fitVideo=(width:number,height:number)=>{
|
||||
if(!(width>0&&height>0))return;
|
||||
video.style.setProperty("--stream-width-for-height",`${100*width/height}vh`);
|
||||
video.style.setProperty("--stream-height-for-width",`${100*height/width}vw`);
|
||||
};
|
||||
video.addEventListener("loadedmetadata",()=>fitVideo(video.videoWidth,video.videoHeight));
|
||||
let started=false;
|
||||
const report=(state:string,fps=0)=>window.parent.postMessage({type:"missioncore-worker-video",state,fps},location.origin);
|
||||
window.addEventListener("message",(e:MessageEvent)=>{
|
||||
if(started || e.source!==window.parent || e.origin!==location.origin || e.data?.type!=="missioncore-worker-connect")return;
|
||||
started=true;
|
||||
const endpoint=e.data.endpoint as AiStreamEndpoint;
|
||||
fitVideo(endpoint.width,endpoint.height);
|
||||
const diagnostics=new StreamDiagnostics();
|
||||
let frames=0,measuredAt=performance.now(),decoded=0;
|
||||
const frame:VideoFrameRequestCallback=(now,metadata)=>{
|
||||
frames++;diagnostics.observeFrame(now,metadata);video.requestVideoFrameCallback(frame);
|
||||
};
|
||||
video.requestVideoFrameCallback(frame);
|
||||
const timer=setInterval(()=>{
|
||||
const now=performance.now();
|
||||
// Presentation callbacks can be throttled independently of decoding in a
|
||||
// background view. Prefer decoded, non-dropped video frames for telemetry.
|
||||
const quality=video.getVideoPlaybackQuality?.();
|
||||
const total=quality?quality.totalVideoFrames-quality.droppedVideoFrames:decoded+frames;
|
||||
const count=Math.max(0,total-decoded);
|
||||
const fps=count*1000/(now-measuredAt);
|
||||
video.dataset.streamDiagnostics=JSON.stringify(diagnostics.snapshot(now,fps));
|
||||
if(count>0)report("live",fps);
|
||||
decoded=total;frames=0;measuredAt=now;
|
||||
},1000);
|
||||
const stream=new AppStreamer();
|
||||
void stream.connect({streamSource:StreamType.DIRECT,logLevel:LogLevel.WARN,streamConfig:{
|
||||
signalingServer:endpoint.server,signalingPort:endpoint.signaling_port,signalingPath:"/",
|
||||
mediaServer:endpoint.server,mediaPort:endpoint.media_port,
|
||||
width:endpoint.width,height:endpoint.height,fps:endpoint.fps,
|
||||
videoElementId:"worker-video",audioElementId:"worker-audio",
|
||||
autoLaunch:true,mic:false,enableAV1Support:false,fitStreamResolution:false,
|
||||
maxReconnects:0,connectivityTimeout:5000,
|
||||
onStart:event=>{if(event.status===EventStatus.ERROR||event.status===EventStatus.CANCELED)report("failed");},
|
||||
onStop:()=>report("failed"),
|
||||
onStreamStats:event=>diagnostics.observeNative(performance.now(),event.data?.stats),
|
||||
}}).catch(()=>report("failed"));
|
||||
window.addEventListener("pagehide",()=>{clearInterval(timer);delete video.dataset.streamDiagnostics;void stream.terminate(false).catch(()=>undefined);},{once:true});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { sendAiPlanningCommand, type AiPlanningCommand, type AiRun } from "../../core/simulation/aiPolygon";
|
||||
|
||||
const motion = new Set(["orbit", "pan", "zoom", "fly"]);
|
||||
const keys = new Set(["KeyW", "KeyA", "KeyS", "KeyD", "KeyQ", "KeyE", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ShiftLeft", "ShiftRight"]);
|
||||
const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value));
|
||||
|
||||
/** Bounded operator intents only; Worker integrates and renders the camera. */
|
||||
export function useAiPlanningControls(run: AiRun, onChange: (run: AiRun) => void, enabled: boolean) {
|
||||
const current = useRef({ run, onChange, enabled }); current.current = { run, onChange, enabled };
|
||||
const queue = useRef<AiPlanningCommand[]>([]);
|
||||
const sending = useRef(false);
|
||||
const alive = useRef(true);
|
||||
const held = useRef(new Set<string>());
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const flush = async () => {
|
||||
if (sending.current || !alive.current) return;
|
||||
sending.current = true;
|
||||
try {
|
||||
while (queue.current.length && alive.current && current.current.enabled) {
|
||||
const run = current.current.run;
|
||||
if ((run.planning_sequence ?? 0) - (run.telemetry?.planning?.sequence ?? 0) >= 4) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
continue;
|
||||
}
|
||||
const command = queue.current.shift()!;
|
||||
const updated = await sendAiPlanningCommand(current.current.run, command);
|
||||
if (alive.current) current.current.onChange(updated);
|
||||
}
|
||||
} catch (caught) {
|
||||
queue.current = []; held.current.clear();
|
||||
if (alive.current) setError(caught instanceof Error ? caught.message : "Не удалось изменить обзор.");
|
||||
} finally {
|
||||
sending.current = false;
|
||||
if (alive.current) setBusy(false);
|
||||
}
|
||||
};
|
||||
const send = (command: AiPlanningCommand) => {
|
||||
if (!current.current.enabled) return;
|
||||
// Do not accumulate motion while Worker is behind; subsequent key ticks retry.
|
||||
const pending = (current.current.run.planning_sequence ?? 0) - (current.current.run.telemetry?.planning?.sequence ?? 0);
|
||||
if (motion.has(command.action) && pending >= 4) return;
|
||||
const previous = queue.current.at(-1);
|
||||
if (command.action === "clip" && previous?.action === "clip") queue.current.pop();
|
||||
else if (motion.has(command.action) && previous?.action === command.action) {
|
||||
queue.current.pop();
|
||||
command = { ...command, x: clamp((previous.x ?? 0) + (command.x ?? 0), 1),
|
||||
y: clamp((previous.y ?? 0) + (command.y ?? 0), 1),
|
||||
amount: clamp((previous.amount ?? 0) + (command.amount ?? 0), 3) };
|
||||
}
|
||||
if (queue.current.length >= 8) return;
|
||||
queue.current.push(command); setBusy(true); setError(null); void flush();
|
||||
};
|
||||
const sender = useRef(send); sender.current = send;
|
||||
const stopKeys = () => {
|
||||
held.current.clear();
|
||||
queue.current = queue.current.filter((command) => command.action !== "fly");
|
||||
};
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
const release = (event: globalThis.KeyboardEvent) => held.current.delete(event.code);
|
||||
const hide = () => { if (document.hidden) stopKeys(); };
|
||||
window.addEventListener("keyup", release); window.addEventListener("blur", stopKeys);
|
||||
document.addEventListener("visibilitychange", hide);
|
||||
let last = performance.now();
|
||||
const timer = setInterval(() => {
|
||||
const now = performance.now(), dt = Math.min(.12, (now-last)/1000); last = now;
|
||||
const h = held.current;
|
||||
if (!current.current.enabled || document.hidden || !h.size) return;
|
||||
const pressed = (...codes: string[]) => Number(codes.some((code) => h.has(code)));
|
||||
const x = pressed("KeyD", "ArrowRight")-pressed("KeyA", "ArrowLeft");
|
||||
const y = pressed("KeyW", "ArrowUp")-pressed("KeyS", "ArrowDown");
|
||||
const z = pressed("KeyE")-pressed("KeyQ");
|
||||
const length = Math.hypot(x, y, z); if (!length) return;
|
||||
const distance = dt * (pressed("ShiftLeft", "ShiftRight") ? 8 : 2.5) / length;
|
||||
sender.current({ action: "fly", x: x*distance, y: y*distance, amount: z*distance });
|
||||
}, 100);
|
||||
return () => {
|
||||
alive.current = false; clearInterval(timer); stopKeys(); queue.current = [];
|
||||
window.removeEventListener("keyup", release); window.removeEventListener("blur", stopKeys);
|
||||
document.removeEventListener("visibilitychange", hide);
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => { if (!enabled) { stopKeys(); queue.current = []; } }, [enabled]);
|
||||
const keyDown = (event: KeyboardEvent<SVGSVGElement>) => {
|
||||
if (keys.has(event.code)) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (!held.current.has(event.code) && !event.code.startsWith("Shift")) {
|
||||
const x = Number(["KeyD", "ArrowRight"].includes(event.code))-Number(["KeyA", "ArrowLeft"].includes(event.code));
|
||||
const y = Number(["KeyW", "ArrowUp"].includes(event.code))-Number(["KeyS", "ArrowDown"].includes(event.code));
|
||||
send({ action: "fly", x: x*.1, y: y*.1, amount: (Number(event.code === "KeyE")-Number(event.code === "KeyQ"))*.1 });
|
||||
}
|
||||
held.current.add(event.code);
|
||||
}
|
||||
else if (event.code === "Home") { event.preventDefault(); send({ action: "home" }); }
|
||||
};
|
||||
return { send, busy, error, keyDown, stopKeys };
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchEditor, prepareEditor, type EditorCache } from "../../core/simulation/aiEditor";
|
||||
import type { AiWorld } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function useLocalScene(world: AiWorld, retry: number) {
|
||||
const [cache,setCache] = useState<EditorCache | null>(null);
|
||||
const [error,setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
const abort = new AbortController(); let timer: ReturnType<typeof setTimeout>;
|
||||
const poll = async (key?: string) => {
|
||||
try {
|
||||
const value = key ? await fetchEditor(key,abort.signal) : await prepareEditor(world,abort.signal);
|
||||
if (abort.signal.aborted) return;
|
||||
setCache(value);
|
||||
if (value.status === "failed") setError(value.error);
|
||||
else if (value.status !== "ready") timer = setTimeout(() => void poll(value.key),1000);
|
||||
} catch (e) { if (!abort.signal.aborted) setError((e as Error).message); }
|
||||
};
|
||||
setCache(null); setError(null); void poll();
|
||||
return () => { abort.abort(); clearTimeout(timer); };
|
||||
}, [world.world_id,retry]);
|
||||
return { cache,error,setError };
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useEffect, type RefObject } from "react";
|
||||
import { polygonRequest, type AiCamera } from "../../core/simulation/aiPolygon";
|
||||
|
||||
/** Bounded, coalesced operator input. Never forwards device/drive commands. */
|
||||
export function useObserverInput(surface:RefObject<HTMLDivElement|null>,runId:string|undefined,mode:AiCamera,enabled:boolean,onError:()=>void) {
|
||||
useEffect(()=>{
|
||||
const element=surface.current;if(!element || !runId || !enabled)return;
|
||||
const input={session:crypto.randomUUID().replaceAll("-",""),sequence:0,orbit:[0,0],move:[0,0,0],zoom:0};
|
||||
let gesture:{id:number;x:number;y:number;pan:boolean}|null=null, dirty=false, sending=false, closed=false;
|
||||
const keys=new Set<string>();
|
||||
const allowed=new Set(["KeyW","KeyS","KeyA","KeyD","KeyQ","KeyE","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","ShiftLeft","ShiftRight"]);
|
||||
const clamp=(v:number)=>Math.max(-9999,Math.min(9999,v));
|
||||
const down=(e:PointerEvent)=>{
|
||||
if((e.target as Element).closest('button,[role="button"],[role="slider"],.nodedc-select-anchor') || ![0,1,2].includes(e.button))return;
|
||||
e.preventDefault();element.focus({preventScroll:true});
|
||||
gesture={id:e.pointerId,x:e.clientX,y:e.clientY,pan:e.button!==0};element.setPointerCapture(e.pointerId);
|
||||
};
|
||||
const move=(e:PointerEvent)=>{
|
||||
if(!gesture || gesture.id!==e.pointerId)return;
|
||||
const dx=e.clientX-gesture.x,dy=e.clientY-gesture.y;gesture.x=e.clientX;gesture.y=e.clientY;
|
||||
if(gesture.pan){input.move[0]=clamp(input.move[0]-dx*.02);input.move[2]=clamp(input.move[2]+dy*.02);}
|
||||
else{input.orbit[0]=clamp(input.orbit[0]-dx*.005);input.orbit[1]=clamp(input.orbit[1]-dy*.005);}
|
||||
dirty=true;
|
||||
};
|
||||
const end=()=>{gesture=null;};
|
||||
const wheel=(e:WheelEvent)=>{
|
||||
if((e.target as Element).closest('button,.nodedc-select-anchor'))return;
|
||||
e.preventDefault();input.zoom=clamp(input.zoom+e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?element.clientHeight:1)*.0015);dirty=true;
|
||||
};
|
||||
const keyDown=(e:KeyboardEvent)=>{if(document.activeElement!==element || e.ctrlKey || e.metaKey || e.altKey || !allowed.has(e.code))return;e.preventDefault();keys.add(e.code);};
|
||||
const keyUp=(e:KeyboardEvent)=>keys.delete(e.code);
|
||||
const clear=()=>{keys.clear();end();};
|
||||
const context=(e:Event)=>e.preventDefault();
|
||||
element.addEventListener("pointerdown",down);element.addEventListener("pointermove",move);element.addEventListener("pointerup",end);element.addEventListener("pointercancel",end);
|
||||
element.addEventListener("wheel",wheel,{passive:false});element.addEventListener("contextmenu",context);element.addEventListener("blur",clear);
|
||||
window.addEventListener("keydown",keyDown);window.addEventListener("keyup",keyUp);window.addEventListener("blur",clear);
|
||||
let last=performance.now();
|
||||
const tick=window.setInterval(()=>{
|
||||
const now=performance.now(),dt=Math.min(.15,(now-last)/1000);last=now;
|
||||
if(mode==="overview" && keys.size && document.visibilityState==="visible") {
|
||||
const pressed=(...codes:string[])=>Number(codes.some(k=>keys.has(k)));
|
||||
const speed=dt*(pressed("ShiftLeft","ShiftRight")?16:4);
|
||||
input.move[0]=clamp(input.move[0]+speed*(pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft")));
|
||||
input.move[1]=clamp(input.move[1]+speed*(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown")));
|
||||
input.move[2]=clamp(input.move[2]+speed*(pressed("KeyE")-pressed("KeyQ")));dirty=true;
|
||||
}
|
||||
if(!dirty || sending)return;
|
||||
dirty=false;sending=true;input.sequence++;
|
||||
void polygonRequest(`/runs/${runId}/view`,{method:"PUT",body:JSON.stringify({camera:mode,navigation:input})})
|
||||
.catch(()=>{if(!closed){dirty=true;onError();}}).finally(()=>{sending=false;});
|
||||
},100);
|
||||
return ()=>{
|
||||
closed=true;clearInterval(tick);clear();
|
||||
element.removeEventListener("pointerdown",down);element.removeEventListener("pointermove",move);element.removeEventListener("pointerup",end);element.removeEventListener("pointercancel",end);
|
||||
element.removeEventListener("wheel",wheel);element.removeEventListener("contextmenu",context);element.removeEventListener("blur",clear);
|
||||
window.removeEventListener("keydown",keyDown);window.removeEventListener("keyup",keyUp);window.removeEventListener("blur",clear);
|
||||
};
|
||||
},[surface,runId,mode,enabled,onError]);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { DEFAULT_PLANNER_PREFERENCES, normalizePlannerPreferences, PLANNER_PREFERENCES_KEY, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
const listeners = new Set<() => void>();
|
||||
let current = DEFAULT_PLANNER_PREFERENCES;
|
||||
try { current = normalizePlannerPreferences(JSON.parse(localStorage.getItem(PLANNER_PREFERENCES_KEY) ?? "null")); } catch { /* Defaults remain usable if storage is unavailable. */ }
|
||||
window.addEventListener("storage", (event) => {
|
||||
if (event.key !== PLANNER_PREFERENCES_KEY) return;
|
||||
try { current = normalizePlannerPreferences(JSON.parse(event.newValue ?? "null")); } catch { return; }
|
||||
listeners.forEach((notify) => notify());
|
||||
});
|
||||
export function usePlannerPreferences() {
|
||||
const value = useSyncExternalStore((notify) => { listeners.add(notify); return () => { listeners.delete(notify); }; }, () => current);
|
||||
const update = (next: PlannerPreferences) => {
|
||||
const valid = normalizePlannerPreferences(next);
|
||||
// Persist before accepting, so a quota/privacy failure is visible to the caller.
|
||||
localStorage.setItem(PLANNER_PREFERENCES_KEY, JSON.stringify(valid));
|
||||
current = valid; listeners.forEach((notify) => notify());
|
||||
};
|
||||
return [value, update] as const;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>)
|
||||
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
|
||||
const escape = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return;
|
||||
if (view.current.querySelector('[role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void document.exitFullscreen().catch(() => undefined);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {decodeDockTree, reconcileDockTree, moveDockPanel, dockIds, type DockTree, type DockMove} from "@nodedc/ui-core";
|
||||
export interface ObservationLayout {
|
||||
version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
|
||||
tree?:DockTree; version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
|
||||
catalogVisible?:string[]; splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
|
||||
}
|
||||
export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'});
|
||||
@@ -8,6 +9,7 @@ export function decodeObservationLayout(value:unknown):ObservationLayout {
|
||||
const source=record(value),result=emptyObservationLayout();if(source.version!==1)return result;
|
||||
const ids=(value:unknown)=>Array.isArray(value)?[...new Set(value.filter((v):v is string=>typeof v==='string'&&v.length<512))].slice(0,128):[];
|
||||
if(source.catalogVisible!==undefined)result.catalogVisible=ids(source.catalogVisible);
|
||||
const tree=decodeDockTree(source.tree);if(tree)result.tree=tree;
|
||||
result.order=ids(source.order);result.hidden=ids(source.hidden);
|
||||
result.layers=Object.fromEntries(Object.entries(record(source.layers)).filter(([k,v])=>k.length<512&&typeof v==='string'&&v.length<128).slice(0,128)) as Record<string,string>;
|
||||
result.splits=Object.fromEntries(Object.entries(record(source.splits)).filter(([k,v])=>k.length<4096&&typeof v==='number'&&Number.isFinite(v)).slice(0,256).map(([k,v])=>[k,Math.min(80,Math.max(20,v as number))]));
|
||||
@@ -20,5 +22,30 @@ export function orderedObservationIDs(layout:ObservationLayout,available:string[
|
||||
export function moveObservation(layout:ObservationLayout,available:string[],from:string,to:string):ObservationLayout {
|
||||
const order=orderedObservationIDs(layout,available);const source=order.indexOf(from),target=order.indexOf(to);
|
||||
if(source<0||target<0||source===target)return layout;
|
||||
if(layout.tree){const tree=moveDockPanel(layout.tree,{activeId:from,overId:to,position:"center"});if(tree)return withObservationTree(layout,tree);}
|
||||
order.splice(source,1);order.splice(target,0,from);return {...layout,order};
|
||||
}
|
||||
|
||||
/** Retain legacy defaults until the first edit; afterwards tree geometry owns placement. */
|
||||
export function observationTree(layout:ObservationLayout,ids:string[]):DockTree|null {
|
||||
if(layout.tree)return reconcileDockTree(layout.tree,ids);
|
||||
const build=(keys:string[],depth=0):DockTree|null=>{
|
||||
if(!keys.length)return null;
|
||||
if(keys.length===1)return {id:keys[0]};
|
||||
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&keys.some(id=>!['map','rover','telemetry'].includes(id));
|
||||
const cameraCount=keys.filter(id=>!['map','rover','telemetry'].includes(id)).length;
|
||||
const mid=defaultColumns&&cameraCount<keys.length?cameraCount:layout.arrangement==='auto'&&keys[0]==='map'&&keys.includes('rover')?1:Math.ceil(keys.length/2);
|
||||
const axis=layout.arrangement==='rows'?'y':layout.arrangement==='columns'?'x':depth%2?'y':'x';
|
||||
return {axis,ratio:layout.splits[JSON.stringify(keys)]??50,first:build(keys.slice(0,mid),depth+1)!,second:build(keys.slice(mid),depth+1)!};
|
||||
};
|
||||
return build(ids);
|
||||
}
|
||||
export function dockObservation(layout:ObservationLayout,ids:string[],move:DockMove):ObservationLayout {
|
||||
const tree=moveDockPanel(observationTree(layout,ids),move);
|
||||
return tree?withObservationTree(layout,tree):layout;
|
||||
}
|
||||
|
||||
export function withObservationTree(layout:ObservationLayout,tree:DockTree):ObservationLayout {
|
||||
const visible=dockIds(tree);
|
||||
return {...layout,tree,order:[...visible,...layout.order.filter(id=>!visible.includes(id))]};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import {dockIds, type DockTree} from '@nodedc/ui-core';
|
||||
import {decodeObservationLayout, type ObservationLayout} from './observationLayout';
|
||||
|
||||
export const observationArrangements = [
|
||||
{value:'auto',label:'Автоматически'}, {value:'columns',label:'В ряд'},
|
||||
{value:'rows',label:'Друг под другом'},
|
||||
] as const;
|
||||
export interface ObservationPreset {id:string;name:string;layout:ObservationLayout}
|
||||
export interface ObservationPresets {version:1;selected:string;layout:ObservationLayout;presets:ObservationPreset[]}
|
||||
const clone = (layout:unknown):ObservationLayout => JSON.parse(JSON.stringify(decodeObservationLayout(layout)));
|
||||
export function decodeObservationPresets(value:unknown, legacy?:unknown):ObservationPresets {
|
||||
const source = value && typeof value === 'object' ? value as Partial<ObservationPresets> : {};
|
||||
const presets:ObservationPreset[] = [];
|
||||
if(source.version === 1 && Array.isArray(source.presets)) for(const item of source.presets.slice(0,128)) {
|
||||
if(!item || typeof item.id!=='string' || !item.id.startsWith('saved:') || item.id.length>128
|
||||
|| typeof item.name!=='string' || !item.name.trim() || item.name.length>120
|
||||
|| presets.some(p=>p.id===item.id || p.name===item.name.trim())) continue;
|
||||
presets.push({id:item.id,name:item.name.trim(),layout:clone(item.layout)});
|
||||
}
|
||||
const layout=decodeObservationLayout(source.version===1 ? source.layout : legacy);
|
||||
const selected=source.selected;
|
||||
return {version:1,presets,layout,selected:typeof selected==='string' &&
|
||||
(presets.some(p=>p.id===selected) || observationArrangements.some(p=>p.value===selected))
|
||||
? selected : layout.arrangement};
|
||||
}
|
||||
export function selectObservationPreset(state:ObservationPresets,id:string):ObservationPresets {
|
||||
const preset=state.presets.find(p=>p.id===id);
|
||||
if(preset)return {...state,selected:id,layout:clone(preset.layout)};
|
||||
const arrangement=observationArrangements.find(p=>p.value===id)?.value;
|
||||
return arrangement ? {...state,selected:id,layout:{...state.layout,arrangement,tree:undefined,order:[],splits:{}}} : state;
|
||||
}
|
||||
export function saveObservationPreset(state:ObservationPresets,name:string,id:string):ObservationPresets {
|
||||
name=name.trim();
|
||||
if(!name || name.length>120)throw new Error('Укажите название раскладки.');
|
||||
if(state.presets.some(p=>p.name.toLocaleLowerCase()===name.toLocaleLowerCase()) ||
|
||||
observationArrangements.some(p=>p.label.toLocaleLowerCase()===name.toLocaleLowerCase()))
|
||||
throw new Error('Раскладка с таким названием уже существует.');
|
||||
if(state.presets.length>=128)throw new Error('Достигнут предел сохранённых раскладок.');
|
||||
if(!id.startsWith('saved:') || state.presets.some(p=>p.id===id))throw new Error('Не удалось создать раскладку.');
|
||||
return {...state,selected:id,presets:[...state.presets,{id,name,layout:clone(state.layout)}]};
|
||||
}
|
||||
export function renameObservationPreset(state:ObservationPresets,id:string,name:string):ObservationPresets {
|
||||
const preset=state.presets.find(p=>p.id===id);
|
||||
if(!preset)throw new Error('Раскладка не найдена.');
|
||||
const validated=saveObservationPreset({...state,presets:state.presets.filter(p=>p.id!==id)},name,id);
|
||||
return {...state,presets:state.presets.map(p=>p.id===id?{...p,name:validated.presets.at(-1)!.name}:p)};
|
||||
}
|
||||
export function removeObservationPreset(state:ObservationPresets,id:string):ObservationPresets {
|
||||
return {...state,presets:state.presets.filter(p=>p.id!==id),
|
||||
selected:state.selected===id?state.layout.arrangement:state.selected};
|
||||
}
|
||||
|
||||
/** Reattach dormant branches after editing the visible projection. Availability
|
||||
* never deletes a device or its split; returning devices recover their anchors. */
|
||||
export function retainDormantObservationTree(previous:DockTree|undefined,next:DockTree):DockTree {
|
||||
if(!previous)return next;
|
||||
const present=new Set(dockIds(next));
|
||||
const insert=(tree:DockTree,anchor:string,branch:DockTree,split:Exclude<DockTree,{id:string}>,first:boolean):DockTree=>{
|
||||
if('id' in tree)return tree.id===anchor ? {...split,first:first?branch:tree,second:first?tree:branch} : tree;
|
||||
return {...tree,first:insert(tree.first,anchor,branch,split,first),second:insert(tree.second,anchor,branch,split,first)};
|
||||
};
|
||||
const restore=(old:DockTree)=>{
|
||||
if('id' in old)return;
|
||||
const first=dockIds(old.first).find(id=>present.has(id));
|
||||
const second=dockIds(old.second).find(id=>present.has(id));
|
||||
if(!first && second)next=insert(next,second,old.first,old,true);
|
||||
else if(first && !second)next=insert(next,first,old.second,old,false);
|
||||
else if(first && second){restore(old.first);restore(old.second);}
|
||||
};
|
||||
restore(previous);return next;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {useEffect,useState,type SetStateAction} from 'react';
|
||||
import {type ObservationLayout} from './observationLayout';
|
||||
import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets';
|
||||
|
||||
export function useObservationPresets(storageKey:string,legacyKey:string) {
|
||||
const [state,setState]=useState(()=>{
|
||||
const read=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}};
|
||||
return decodeObservationPresets(read(storageKey),read(legacyKey));
|
||||
});
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
useEffect(()=>{
|
||||
try{localStorage.setItem(storageKey,JSON.stringify(state));}
|
||||
catch{setError('Браузер не сохранил раскладку. Проверьте доступное место и разрешение на хранение данных.');}
|
||||
},[state,storageKey]);
|
||||
const setLayout=(update:SetStateAction<ObservationLayout>)=>setState(current=>({...current,
|
||||
layout:typeof update==='function'?update(current.layout):update}));
|
||||
const commit=(update:()=>ObservationPresets)=>{
|
||||
try{
|
||||
const next=update();
|
||||
localStorage.setItem(storageKey,JSON.stringify(next));setState(next);setError(null);return true;
|
||||
}catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;}
|
||||
};
|
||||
return {...state,setLayout,save:(name:string)=>commit(()=>saveObservationPreset(state,name,`saved:${crypto.randomUUID()}`)),
|
||||
rename:(id:string,name:string)=>commit(()=>renameObservationPreset(state,id,name)),
|
||||
remove:(id:string)=>commit(()=>removeObservationPreset(state,id)),
|
||||
select:(id:string)=>setState(current=>selectObservationPreset(current,id)),
|
||||
error,clearError:()=>setError(null)};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint, type AiWorld } from "./aiPolygon";
|
||||
export interface EditorCache {
|
||||
local_scene?: { visual_url: string; collision_url: string; visual_rotation: number[]; collision_rotation: number[] };
|
||||
key: string; world: AiWorld; status: "queued" | "preparing" | "uploading" | "ready" | "failed";
|
||||
error: string | null;
|
||||
files: Record<string, { sha256: string; byte_length: number; uploaded_bytes: number }>;
|
||||
}
|
||||
export const prepareEditor = (world: AiWorld, signal?: AbortSignal) => polygonRequest<EditorCache>(
|
||||
`/worlds/${world.world_id}/editor-cache`, { method: "POST", signal });
|
||||
export const fetchEditor = (key: string, signal?: AbortSignal) => polygonRequest<EditorCache>(`/editor-cache/${key}`, { signal });
|
||||
export const editorAssetUrl = (key: string, name: string) => `/api/v1/ai-polygon/editor-cache/${key}/${name}`;
|
||||
export const saveLocalPlan = (cache: EditorCache, robot: AiRobot, points: AiWaypoint[], name: string,
|
||||
draftId: string, sequence: number, routePreparationKey?:string|null) => polygonRequest<AiPlan>("/plans", { method: "POST", body: JSON.stringify({
|
||||
cache_key: cache.key, robot_id: robot.robot_id, robot_sha256: robot.sha256,
|
||||
draft_id: draftId, sequence, points, name, route_preparation_key:routePreparationKey??null,
|
||||
}) });
|
||||
export { toEditor, toMission } from "./aiEditorCoordinates";
|
||||
@@ -0,0 +1,3 @@
|
||||
/** Isaac uses Z up; the glTF/PlayCanvas editor uses Y up. This preserves handedness. */
|
||||
export const toEditor = ([x, y, z]: number[]): [number, number, number] => [x, z, -y];
|
||||
export const toMission = ([x, y, z]: number[]): [number, number, number] => [x, -z, y];
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { PreparedRoute } from "./routePreparation";
|
||||
import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition";
|
||||
import type { RoverMotion } from "./roverMotion";
|
||||
import type { RoverSettings } from "./roverSettings";
|
||||
|
||||
const API = "/api/v1/ai-polygon";
|
||||
|
||||
@@ -28,14 +31,29 @@ export interface AiSource {
|
||||
description?: string;
|
||||
}
|
||||
export interface AiWorld extends AiSource {
|
||||
local_scene?: { project_id: string };
|
||||
inference_ready?: boolean; inference_message?: string;
|
||||
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
|
||||
status: "uploading" | "available"; sha256: string | null; splat_count: number | null;
|
||||
settings: AiWorldSettings;
|
||||
}
|
||||
export interface AiRobot {
|
||||
robot_id: string; name: string; revision: string; sha256: string;
|
||||
visual: { dimensions_m: [number, number, number]; source: string; sha256: string; motion?: RoverMotion };
|
||||
physics: { mass_kg: number; length_m: number; width_m: number; height_m: number };
|
||||
control?: { max_side_speed_mps: number };
|
||||
}
|
||||
export interface AiRun {
|
||||
run_id: string;
|
||||
created_at?: string;
|
||||
world: AiWorld;
|
||||
request?: { composition?: AiSelection };
|
||||
robot?: AiRobot | null;
|
||||
report?: AiRunReport | null;
|
||||
request?: { composition?: AiSelection; purpose?: "planning" | "evaluation"; rover_settings?: RoverSettings | null };
|
||||
rover_configuration?: { sha256:string; total_mass_kg:number; effective_robot_sha256:string; settings:RoverSettings } | null;
|
||||
plan?: AiPlan | null;
|
||||
plan_display_name?: string | null;
|
||||
planning_sequence?: number;
|
||||
state: "starting" | "ready" | "running" | "paused" | "stopping" | "completed" | "stopped" | "failed" | "disconnected";
|
||||
clock?: "lockstep" | "realtime";
|
||||
control?: "play" | "pause" | "stop";
|
||||
@@ -57,20 +75,57 @@ export interface AiRun {
|
||||
road_fraction: number; obstacle_count: number };
|
||||
};
|
||||
}
|
||||
export interface AiRunReport {
|
||||
run_id: string; generated_at: string;
|
||||
mission_outcome: "goal-reached" | "time-limit" | "operator-stop" | "stuck" | "unstable" | "error" | "not-evaluated";
|
||||
distance_m: number | null; simulation_seconds: number | null; goal_error_m: number | null;
|
||||
waypoint_count: number; waypoints_reached: number | null;
|
||||
inference_count: number; inference_errors: number;
|
||||
inference_ms_p50: number | null; inference_ms_p95: number | null;
|
||||
stops: { reason: string; events: number; seconds: number }[];
|
||||
collision_count: number | null;
|
||||
robot_sha256: string | null; composition_sha256: string | null;
|
||||
report_sha256: string; manifest_sha256: string; evidence_files: number; evidence_bytes: number;
|
||||
speed?: {requested_max_mps:number; measured_max_mps:number|null; maximum_excess_mps:number|null; seconds_above_requested:number|null} | null;
|
||||
}
|
||||
export type AiCamera = "follow" | "overview" | "camera";
|
||||
export interface AiStreamEndpoint {
|
||||
server: string; signaling_port: number; media_port: number; width: number; height: number; fps: number;
|
||||
}
|
||||
export interface AiTelemetry {
|
||||
distance_m?: number | null;
|
||||
sequence: number; control_sequence: number; simulation_time_ns: number;
|
||||
rtf: number; render_fps: number; sensor_fps: number; ai_hz: number;
|
||||
inference_ms: number | null; frame_age_ms: number | null; command_age_ms: number | null;
|
||||
speed_mps: number; applied_speed_mps: number; stop_reason: string;
|
||||
ai_ready: boolean; stream_ready: boolean; camera: AiCamera;
|
||||
decision: NonNullable<AiRun["last_sample"]>["decision"] | null;
|
||||
planning?: AiPlanningState | null;
|
||||
route_overlay?: AiRouteOverlay | null;
|
||||
}
|
||||
export interface AiWaypoint { id: string; position: [number, number, number] }
|
||||
export type ScreenPoint = [number, number] | null;
|
||||
export interface AiRouteOverlay {
|
||||
markers: (AiWaypoint & { index: number; base: ScreenPoint; top: ScreenPoint;
|
||||
x_axis: ScreenPoint; y_axis: ScreenPoint })[];
|
||||
trace: ScreenPoint[]; active_index: number; view_revision: number;
|
||||
}
|
||||
export interface AiPlanningState { sequence: number; view_revision: number; points: AiWaypoint[];
|
||||
error: string | null; can_undo: boolean; clip_height: number | null;
|
||||
height_min?: number | null; height_max?: number | null; camera_moving?: boolean }
|
||||
export interface AiPlan { prepared_route?:PreparedRoute; route_preparation_key?:string; plan_id: string; name: string; sha256: string; world_id: string;
|
||||
settings?: Pick<AiWorldSettings, "max_speed_mps">;
|
||||
display_name?: string; removed?: boolean;
|
||||
editor_cache_key?: string;
|
||||
robot_id: string; robot_sha256: string; points: AiWaypoint[]; length_m: number; created_at: string }
|
||||
export interface AiPlanningCommand {
|
||||
action: "orbit" | "pan" | "zoom" | "fly" | "home" | "add" | "move" | "delete" | "clear" | "clip" | "undo";
|
||||
point_id?: string; x?: number; y?: number; amount?: number; enabled?: boolean; axis?: "x" | "y" | "xy";
|
||||
}
|
||||
export interface AiCatalog {
|
||||
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
|
||||
robots: AiRobot[];
|
||||
plans: AiPlan[];
|
||||
runtime: { available: boolean; active_run: AiRun | null };
|
||||
}
|
||||
|
||||
@@ -87,13 +142,29 @@ export async function polygonRequest<T>(path: string, init: RequestInit = {}): P
|
||||
}
|
||||
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
|
||||
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog");
|
||||
export const aiPlanName = (plan: AiPlan) => plan.display_name ?? plan.name;
|
||||
export const updateAiPlan = (id:string, changes:{display_name?:string;removed?:boolean}) =>
|
||||
polygonRequest<AiPlan>(`/plans/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
|
||||
export const removeAiRun = (id:string, removed:boolean) =>
|
||||
polygonRequest<AiRun>(`/runs/${id}`, {method:"PATCH",body:JSON.stringify({removed})});
|
||||
export const configureAiWorld = (world: AiWorld, settings: AiWorldSettings) =>
|
||||
polygonRequest<AiWorld>(`/worlds/${world.world_id}/settings`, {
|
||||
method: "PUT", body: JSON.stringify(settings),
|
||||
});
|
||||
export const startAiRun = (world: AiWorld, composition?: AiSelection) => polygonRequest<AiRun>("/runs", {
|
||||
export const startAiRun = (world: AiWorld, robot: AiRobot, composition?: AiSelection,
|
||||
purpose: "planning" | "evaluation" = "evaluation", plan?: AiPlan, roverSettings?: RoverSettings) => polygonRequest<AiRun>("/runs", {
|
||||
method: "POST", headers: { "Idempotency-Key": crypto.randomUUID() },
|
||||
body: JSON.stringify({ world_id: world.world_id, clock: "realtime", start_paused: true, duration_seconds: 1800, composition }),
|
||||
body: JSON.stringify({ world_id: world.world_id, robot_id: robot.robot_id, robot_sha256: robot.sha256,
|
||||
clock: "realtime", start_paused: purpose === "planning",
|
||||
composition, purpose, plan_id: plan?.plan_id, rover_settings:roverSettings }),
|
||||
});
|
||||
export const sendAiPlanningCommand = (run: AiRun, command: AiPlanningCommand) =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/planning`, { method: "PUT", body: JSON.stringify({
|
||||
...command, request_id: crypto.randomUUID().replaceAll("-", ""),
|
||||
view_revision: run.telemetry?.planning?.view_revision ?? 0,
|
||||
}) });
|
||||
export const saveAiPlan = (run: AiRun, name: string) => polygonRequest<AiPlan>(`/runs/${run.run_id}/plan`, {
|
||||
method: "POST", body: JSON.stringify({ name, sequence: run.telemetry?.planning?.sequence ?? 0 }),
|
||||
});
|
||||
export const setAiCamera = (run: AiRun, camera: AiCamera) =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/view`, { method: "PUT", body: JSON.stringify({ camera }) });
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import {polygonRequest,type AiSelection} from './aiPolygon';
|
||||
|
||||
export interface AiProfile {
|
||||
profile_id:string; name:string; composition:AiSelection; revision:number; removed:boolean;
|
||||
}
|
||||
export const fetchAiProfiles=()=>polygonRequest<AiProfile[]>('/ai-profiles');
|
||||
export const createAiProfile=(name:string,composition:AiSelection)=>polygonRequest<AiProfile>('/ai-profiles',
|
||||
{method:'POST',body:JSON.stringify({name,composition})});
|
||||
export const updateAiProfile=(profile:AiProfile,changes:{name?:string;composition?:AiSelection;removed?:boolean})=>
|
||||
polygonRequest<AiProfile>(`/ai-profiles/${profile.profile_id}`,
|
||||
{method:'PATCH',body:JSON.stringify({expected_revision:profile.revision,...changes})});
|
||||
|
||||
/** Saved intent survives installed module revisions; admission rebinds SHA-256. */
|
||||
export function sameAiIntent(a:AiSelection,b:AiSelection):boolean {
|
||||
const stable=(value:unknown):unknown=>Array.isArray(value)?value.map(stable):value&&typeof value==='object'
|
||||
?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>[k,stable(v)])):value;
|
||||
const intent=(value:AiSelection)=>value.selections.map(({group,module_id,parameters})=>({group,module_id,parameters}))
|
||||
.sort((a,b)=>a.group.localeCompare(b.group));
|
||||
return JSON.stringify(stable(intent(a)))===JSON.stringify(stable(intent(b)));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { PerspectiveCamera, Quaternion, Vector3 } from "three";
|
||||
const UP = new Vector3(0,1,0);
|
||||
/** Depth along the optical axis gives a metric screen-space pan at any zoom. */
|
||||
export function navigationDepth(camera: PerspectiveCamera, anchor: Vector3) {
|
||||
return Math.max(.1, anchor.clone().sub(camera.position).dot(camera.getWorldDirection(new Vector3())));
|
||||
}
|
||||
export function panCamera(camera: PerspectiveCamera, depth: number, dx: number, dy: number, height: number) {
|
||||
const scale=2*depth*Math.tan(camera.fov*Math.PI/360)/Math.max(1,height);
|
||||
camera.position.add(new Vector3(-dx*scale,dy*scale,0).applyQuaternion(camera.quaternion));
|
||||
camera.updateMatrixWorld();
|
||||
}
|
||||
/** Rotate the complete camera pose about the picked point: no lookAt snap.
|
||||
* The picked point keeps its screen coordinates, including off-centre clicks. */
|
||||
export function orbitCamera(camera: PerspectiveCamera, anchor: Vector3, dx: number, dy: number, height: number) {
|
||||
const factor=2*Math.PI/Math.max(1,height);
|
||||
const yaw=new Quaternion().setFromAxisAngle(UP,-dx*factor);
|
||||
const forward=camera.getWorldDirection(new Vector3());
|
||||
const elevation=Math.asin(Math.max(-1,Math.min(1,forward.y)));
|
||||
const pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,elevation-dy*factor))-elevation;
|
||||
const right=new Vector3(1,0,0).applyQuaternion(camera.quaternion).applyQuaternion(yaw);
|
||||
const rotation=new Quaternion().setFromAxisAngle(right,pitch).multiply(yaw);
|
||||
camera.position.sub(anchor).applyQuaternion(rotation).add(anchor);
|
||||
camera.quaternion.premultiply(rotation);
|
||||
camera.updateMatrixWorld();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/** Exponential dolly in metres, independent of OrbitControls' target radius. */
|
||||
export function zoomDisplacement(depth: number, wheelPixels: number): number {
|
||||
return depth * (1 - Math.exp(Math.max(-.8, Math.min(.8,wheelPixels*.002))));
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export type GaussianQuality = "low" | "medium" | "high" | "ultra" | "maximum";
|
||||
// PlayCanvas: zero disables count-budget enforcement; quality uses LOD distances only.
|
||||
export const QUALITY_PROFILES: Record<GaussianQuality, {
|
||||
lodBaseDistance: number;
|
||||
lodMultiplier: number;
|
||||
lodRangeMin: number;
|
||||
lodRangeMax: number;
|
||||
pixelRatio: number;
|
||||
splatBudget: number;
|
||||
targetFps: number;
|
||||
}> = {
|
||||
low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 0, targetFps: 30 },
|
||||
medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 0, targetFps: 45 },
|
||||
high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 0, targetFps: 60 },
|
||||
ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 0, targetFps: 60 },
|
||||
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 0, targetFps: 60 },
|
||||
};
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { AiPlan, AiWaypoint } from "./aiPolygon";
|
||||
|
||||
/** A launch may reuse a saved task only when it represents this exact draft. */
|
||||
export function planMatchesDraft(plan:AiPlan|undefined, cacheKey:string, robotSha:string, points:AiWaypoint[]) {
|
||||
return !!plan && plan.editor_cache_key===cacheKey && plan.robot_sha256===robotSha
|
||||
&& plan.points.length===points.length && plan.points.every((point,i)=>point.id===points[i].id
|
||||
&& point.position.every((value,axis)=>value===points[i].position[axis]));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { GaussianQuality } from "./gaussianQuality";
|
||||
|
||||
export interface PlannerPreferences {
|
||||
quality: GaussianQuality;
|
||||
navigation: { nearDistance:number; farDistance:number; nearPan:number; farPan:number; zoom:number; centroidPixels:number; centroidColor:string; centroidOpacity:number };
|
||||
pivot: { pixels: number; diameter: number; cone: number; opacity: number; x: string; y: string; z: string };
|
||||
waypoint: { diameter: number; height: number; color: string; opacity: number; frequency: number; emission: number; emissionColor: string };
|
||||
}
|
||||
export const PLANNER_PREFERENCES_KEY = "missioncore.simulation-view/v1";
|
||||
export const DEFAULT_PLANNER_PREFERENCES: PlannerPreferences = {
|
||||
quality: "medium",
|
||||
navigation: { nearDistance:3, farDistance:100, nearPan:1, farPan:1, zoom:1, centroidPixels:14, centroidColor:"#edf0eb", centroidOpacity:.8 },
|
||||
pivot: { pixels: 105, diameter: 5, cone: 22, opacity: 1, x: "#e85b54", y: "#83ca61", z: "#6499ed" },
|
||||
waypoint: { diameter: .35, height: 4.5, color: "#edf0eb", opacity: .65, frequency: .5, emission: 1.5, emissionColor: "#edf0eb" },
|
||||
};
|
||||
/** Persisted operator preferences are untrusted input; old/invalid fields get defaults. */
|
||||
export function normalizePlannerPreferences(value: unknown): PlannerPreferences {
|
||||
const v = value && typeof value === "object" ? value as Partial<PlannerPreferences> : {};
|
||||
const p: Partial<PlannerPreferences["pivot"]> = v.pivot ?? {}, w: Partial<PlannerPreferences["waypoint"]> = v.waypoint ?? {}, d = DEFAULT_PLANNER_PREFERENCES;
|
||||
const n = (x: unknown, fallback: number, min: number, max: number) => typeof x === "number" && Number.isFinite(x) ? Math.max(min, Math.min(max,x)) : fallback;
|
||||
const color = (x: unknown, fallback: string) => typeof x === "string" && /^#[0-9a-f]{6}$/i.test(x) ? x : fallback;
|
||||
const nav:Partial<PlannerPreferences["navigation"]>=v.navigation??{}, dn=d.navigation;
|
||||
const nearDistance=n(nav.nearDistance,dn.nearDistance,.5,50);
|
||||
return {
|
||||
navigation: {nearDistance,farDistance:Math.max(nearDistance+1,n(nav.farDistance,dn.farDistance,2,500)),
|
||||
nearPan:n(nav.nearPan,dn.nearPan,.1,5),farPan:n(nav.farPan,dn.farPan,.1,5),zoom:n(nav.zoom,dn.zoom,.1,3),
|
||||
centroidPixels:n(nav.centroidPixels,dn.centroidPixels,6,64),centroidColor:color(nav.centroidColor,dn.centroidColor),centroidOpacity:n(nav.centroidOpacity,dn.centroidOpacity,.1,1)},
|
||||
quality: ["low","medium","high","ultra","maximum"].includes(v.quality ?? "") ? v.quality! : d.quality,
|
||||
pivot: { pixels:n(p.pixels,d.pivot.pixels,50,220), diameter:n(p.diameter,d.pivot.diameter,2,16), cone:n(p.cone,d.pivot.cone,10,40), opacity:n(p.opacity,d.pivot.opacity,.15,1),
|
||||
x:color(p.x,d.pivot.x), y:color(p.y,d.pivot.y), z:color(p.z,d.pivot.z) },
|
||||
waypoint: { diameter:n(w.diameter,d.waypoint.diameter,.05,3), height:n(w.height,d.waypoint.height,.2,50), color:color(w.color,d.waypoint.color), opacity:n(w.opacity,d.waypoint.opacity,.1,1), frequency:n(w.frequency,d.waypoint.frequency,0,3), emission:n(w.emission,d.waypoint.emission,0,5), emissionColor:color(w.emissionColor,d.waypoint.emissionColor) },
|
||||
};
|
||||
}
|
||||
export function axisWorldLength(depth: number, height: number, pixels: number) {
|
||||
return Math.max(.01, depth) * 2 * Math.tan(Math.PI / 6) * pixels / Math.max(1,height);
|
||||
}
|
||||
|
||||
export function panSensitivity(distance:number,navigation:PlannerPreferences["navigation"]) {
|
||||
const t=Math.max(0,Math.min(1,(distance-navigation.nearDistance)/(navigation.farDistance-navigation.nearDistance)));
|
||||
const smooth=t*t*(3-2*t);
|
||||
return navigation.nearPan+(navigation.farPan-navigation.nearPan)*smooth;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint } from "./aiPolygon";
|
||||
import type { EditorCache } from "./aiEditor";
|
||||
|
||||
export interface PreparedRoute {
|
||||
sha256:string; preview_xyz:number[][]; length_m:number;
|
||||
identity:{world_sha256:string;robot_sha256:string;points:AiWaypoint[]};
|
||||
}
|
||||
export interface RoutePreparation {
|
||||
key:string;status:"queued"|"preparing"|"ready"|"failed";error:string|null;result:PreparedRoute|null;
|
||||
}
|
||||
export function routeMatches(route:PreparedRoute|null|undefined, cache:EditorCache|null,
|
||||
robot:AiRobot|undefined, points:AiWaypoint[]) {
|
||||
return !!route && !!cache && !!robot && route.identity.world_sha256===cache.world.sha256
|
||||
&& route.identity.robot_sha256===robot.sha256 && JSON.stringify(route.identity.points)===JSON.stringify(points);
|
||||
}
|
||||
export function useRoutePreparation(cache:EditorCache|null, robot:AiRobot|undefined,
|
||||
points:AiWaypoint[], plan:AiPlan|undefined, onError:(message:string)=>void) {
|
||||
const [job,setJob]=useState<RoutePreparation|null>(null);
|
||||
const [submitting,setSubmitting]=useState(false);
|
||||
const generation=useRef(0);
|
||||
const signature=JSON.stringify([cache?.key,robot?.sha256,points]);
|
||||
const current=useRef(signature);current.current=signature;
|
||||
const error=useRef(onError);error.current=onError;
|
||||
useEffect(()=>{generation.current++;setJob(null);setSubmitting(false);},[signature]);
|
||||
useEffect(()=>{
|
||||
if(!job || !["queued","preparing"].includes(job.status))return;
|
||||
const key=job.key,stamp=generation.current;
|
||||
let active=true,timer:ReturnType<typeof setTimeout>;
|
||||
const controller=new AbortController();
|
||||
const poll=async()=>{
|
||||
try {
|
||||
const next=await polygonRequest<RoutePreparation>(`/route-preparations/${key}`,{signal:controller.signal});
|
||||
if(active && generation.current===stamp){
|
||||
setJob(next);
|
||||
if(next.status==="failed")error.current(next.error??"Маршрут не построен.");
|
||||
else if(next.status!=="ready")timer=setTimeout(()=>void poll(),1000);
|
||||
}
|
||||
} catch(caught) {
|
||||
if(active){error.current((caught as Error).message);setJob(null);}
|
||||
}
|
||||
};
|
||||
timer=setTimeout(()=>void poll(),500);
|
||||
return()=>{active=false;clearTimeout(timer);controller.abort();};
|
||||
},[job?.key,job?.status]);
|
||||
const generated=routeMatches(job?.result,cache,robot,points)?job?.result:null;
|
||||
const saved=routeMatches(plan?.prepared_route,cache,robot,points)?plan?.prepared_route:null;
|
||||
const route=generated??saved??null;
|
||||
const key=generated?job!.key:saved?plan?.route_preparation_key:null;
|
||||
const prepare=async()=>{
|
||||
if(!cache||!robot||points.length<2)return;
|
||||
const stamp=generation.current,snapshot=signature;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const next=await polygonRequest<RoutePreparation>("/route-preparations",{method:"POST",body:JSON.stringify({
|
||||
cache_key:cache.key,robot_id:robot.robot_id,robot_sha256:robot.sha256,points,
|
||||
})});
|
||||
if(stamp===generation.current && current.current===snapshot)setJob(next);
|
||||
} catch(caught) {if(stamp===generation.current)error.current((caught as Error).message);}
|
||||
finally {if(stamp===generation.current)setSubmitting(false);}
|
||||
};
|
||||
return {route,key:key??null,prepare,busy:submitting||!!job&&["queued","preparing"].includes(job.status)};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export interface RoverMotion {
|
||||
schema_version: "missioncore.rover-motion/v1";
|
||||
length_m: number; pitch_m: number; phase_m: number; link_count: number;
|
||||
track_width_m: number; track_centres_m: { L: number; R: number }; shift_m: number[];
|
||||
segments: ["arc" | "line", number, number, number[]][];
|
||||
wheels: { node: string; radius_m: number }[];
|
||||
}
|
||||
export function beltPose(motion: RoverMotion, distance: number, side: "L" | "R", index: number) {
|
||||
const s = ((distance + motion.phase_m + index*motion.pitch_m) % motion.length_m + motion.length_m) % motion.length_m;
|
||||
const segment = motion.segments.find(([, start, length]) => s <= start+length+1e-10)!;
|
||||
const [kind,start,,d] = segment, t = s-start;
|
||||
let x: number, z: number, angle: number;
|
||||
if (kind === "arc") {
|
||||
const [cx,cz,r,a] = d, q = a-t/r;
|
||||
x=cx+r*Math.cos(q); z=cz+r*Math.sin(q); angle=q-Math.PI/2;
|
||||
} else {
|
||||
x=d[0]+d[2]*t; z=d[1]+d[3]*t; angle=Math.atan2(d[3],d[2]);
|
||||
}
|
||||
return { position:[x+motion.shift_m[0],z+motion.shift_m[2],-motion.track_centres_m[side]-motion.shift_m[1]], angle };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { AiRobot } from "./aiPolygon";
|
||||
|
||||
export interface RoverSettings {
|
||||
schema_version: "missioncore.rover-settings/v2";
|
||||
max_speed_mps: number;
|
||||
base_mass_kg: number;
|
||||
payload_mass_kg: number;
|
||||
payload_height_m: number;
|
||||
}
|
||||
export const roverSettingsKey = (robot: AiRobot) => `nodedc.simulation.rover.v1:${robot.robot_id}:${robot.sha256}`;
|
||||
export function defaultRoverSettings(robot: AiRobot, speed: number): RoverSettings {
|
||||
return { schema_version: "missioncore.rover-settings/v2",
|
||||
max_speed_mps: Math.max(.05, Number.isFinite(speed) ? speed : .3),
|
||||
base_mass_kg: robot.physics.mass_kg, payload_mass_kg: 0,
|
||||
payload_height_m: Math.round((robot.physics.height_m + .1) * 100) / 100 };
|
||||
}
|
||||
export function validRoverSettings(value: RoverSettings, _robot: AiRobot): boolean {
|
||||
const within = (v:number, min:number, max:number) => Number.isFinite(v) && v>=min && v<=max;
|
||||
return value.schema_version === "missioncore.rover-settings/v2"
|
||||
&& within(value.max_speed_mps, .05, Infinity)
|
||||
&& within(value.base_mass_kg,10,1000) && within(value.payload_mass_kg,0,500)
|
||||
&& within(value.payload_height_m,.1,3);
|
||||
}
|
||||
export function parseRoverSettings(raw: string | null, robot: AiRobot): RoverSettings | undefined {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
if (value?.schema_version === "missioncore.rover-settings/v1") value.schema_version = "missioncore.rover-settings/v2";
|
||||
if (!value || !validRoverSettings(value,robot)
|
||||
|| Object.keys(value).sort().join() !== "base_mass_kg,max_speed_mps,payload_height_m,payload_mass_kg,schema_version") return;
|
||||
return value;
|
||||
} catch { return; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { AiModules, AiSelection } from "./aiPolygon";
|
||||
|
||||
const SCHEMA = "missioncore.observatory-ai-composition/v1";
|
||||
const GROUPS = new Set(["segmentation", "detection", "geometry", "range", "motion", "policy"]);
|
||||
|
||||
/** Stored intent is untrusted. Worker admission still owns executable contracts. */
|
||||
export function parseSavedSelection(raw: string | null): AiSelection | undefined {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
if (value?.schema_version !== SCHEMA || !Array.isArray(value.selections)
|
||||
|| !value.selections.length || value.selections.length > GROUPS.size) return;
|
||||
const groups = new Set<string>();
|
||||
for (const row of value.selections) {
|
||||
if (!row || !GROUPS.has(row.group) || groups.has(row.group)
|
||||
|| typeof row.module_id !== "string" || !/^[a-z0-9][a-z0-9-]{0,127}$/.test(row.module_id)
|
||||
|| typeof row.module_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.module_sha256)
|
||||
|| !row.parameters || typeof row.parameters !== "object" || Array.isArray(row.parameters)) return;
|
||||
groups.add(row.group);
|
||||
}
|
||||
return value as AiSelection;
|
||||
} catch { return; }
|
||||
}
|
||||
|
||||
/** Rebind every chosen provider, including alternatives absent from defaults. */
|
||||
export function currentSelection(selection: AiSelection, installed: AiModules): AiSelection {
|
||||
return { ...selection, selections: selection.selections.map(row => {
|
||||
const module = installed.catalog.groups.find(group => group.group === row.group)
|
||||
?.modules.find(candidate => candidate.moduleId === row.module_id);
|
||||
if (!module) throw new Error("Выбранный AI-модуль больше недоступен. Проверьте конфигурацию AI.");
|
||||
return { ...row, module_sha256: module.moduleSha256,
|
||||
parameters: { ...module.defaults, ...row.parameters } };
|
||||
}) };
|
||||
}
|
||||
|
||||
export const selectionStorageKey = (world: string, robot: string) =>
|
||||
`nodedc.simulation.composition.v1:${world}:${robot}`;
|
||||
@@ -0,0 +1,46 @@
|
||||
/** One expiring diagnostic sample; never a recording or a control input. */
|
||||
export interface StreamFrameTiming {
|
||||
expectedDisplayTime: number;
|
||||
captureTime?: number;
|
||||
receiveTime?: number;
|
||||
processingDuration?: number;
|
||||
}
|
||||
const finite = (value: unknown): number | null =>
|
||||
typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
|
||||
const elapsed = (later: number, earlier: number | undefined) => {
|
||||
if (earlier === undefined || finite(earlier) === null) return null;
|
||||
const value = later - earlier;
|
||||
return value >= 0 && value <= 60_000 ? value : null;
|
||||
};
|
||||
export class StreamDiagnostics {
|
||||
private native: { at: number; values: Record<string, number | string | null> } | null = null;
|
||||
private frame: { at: number; values: Record<string, number | null> } | null = null;
|
||||
observeNative(now: number, input: unknown) {
|
||||
if (!input || typeof input !== "object") return;
|
||||
const value = input as Record<string, unknown>;
|
||||
const fields = {fps: "fps", round_trip_ms: "rtd", decode_ms: "avgDecodeTime",
|
||||
bitrate_mbps: "currentBitrate", available_mbps: "totalBandwidth", bandwidth_percent: "utilizedBandwidth",
|
||||
frame_loss_total: "frameLoss", packet_loss_total: "packetLoss",
|
||||
width: "streamingResolutionWidth", height: "streamingResolutionHeight"};
|
||||
this.native = { at: now, values: Object.fromEntries(Object.entries(fields)
|
||||
.map(([key, source]) => [key, finite(value[source])])) };
|
||||
this.native.values.codec = typeof value.codec === "string" && /^[a-z0-9._-]{1,32}$/i.test(value.codec) ? value.codec : null;
|
||||
}
|
||||
observeFrame(now: number, value: StreamFrameTiming) {
|
||||
// WebRTC captureTime is the browser's RTCP-based remote clock estimate.
|
||||
// Never subtract a Worker monotonic clock from performance.now().
|
||||
this.frame = { at: now, values: {
|
||||
estimated_capture_to_present_ms: elapsed(value.expectedDisplayTime, value.captureTime),
|
||||
receive_to_present_ms: elapsed(value.expectedDisplayTime, value.receiveTime),
|
||||
frame_decode_ms: finite(value.processingDuration) === null ? null : value.processingDuration! * 1000,
|
||||
}};
|
||||
}
|
||||
snapshot(now: number, decodedFps: number) {
|
||||
const fresh = <T extends {at:number}>(sample:T|null) =>
|
||||
sample && now >= sample.at && now-sample.at <= 3000 ? sample : null;
|
||||
const native=fresh(this.native), frame=fresh(this.frame);
|
||||
return {schema_version:"missioncore.stream-diagnostics/v1", sampled_at_ms:now,
|
||||
decoded_fps:finite(decodedFps), native:native ? {...native.values, age_ms:now-native.at} : null,
|
||||
presentation:frame ? {...frame.values, age_ms:now-frame.at} : null};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** A bounded first-frame/stall watchdog, independent of SDK callbacks. */
|
||||
export function streamRecovery(now:number,started:number,lastFrame:number|null,failedAt:number|null,attempt:number) {
|
||||
const expired=failedAt!==null ? now-failedAt>=2000 : lastFrame===null ? now-started>=20000 : now-lastFrame>=10000;
|
||||
return !expired?"wait":attempt<2?"retry":"failed";
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import type { AiModules, AiSelection } from "./aiPolygon";
|
||||
import { parseSavedSelection, selectionStorageKey } from "./runConfiguration";
|
||||
|
||||
/** Location/robot intent survives reload; changing location never carries it over. */
|
||||
export function useAiSelection(world: string | null, robot: string | null, modules: AiModules | null) {
|
||||
const scope = world && robot ? selectionStorageKey(world, robot) : null;
|
||||
const [draft, setDraft] = useState<{ scope: string | null; value: AiSelection } | null>(null);
|
||||
const saved = useMemo(() => {
|
||||
try { return scope ? parseSavedSelection(localStorage.getItem(scope)) : undefined; }
|
||||
catch { return undefined; }
|
||||
}, [scope]);
|
||||
const selection = draft?.scope === scope ? draft.value : saved ?? modules?.selection;
|
||||
const setSelection = (value: AiSelection) => {
|
||||
setDraft({ scope, value });
|
||||
try { if (scope) localStorage.setItem(scope, JSON.stringify(value)); }
|
||||
catch { /* In-memory intent remains usable if browser storage is unavailable. */ }
|
||||
};
|
||||
return [selection, setSelection] as const;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import type { AiRobot } from "./aiPolygon";
|
||||
import { defaultRoverSettings, parseRoverSettings, roverSettingsKey, type RoverSettings } from "./roverSettings";
|
||||
|
||||
export function useRoverSettings(robot: AiRobot | undefined, speed: number) {
|
||||
const scope = robot ? roverSettingsKey(robot) : null;
|
||||
const [draft,setDraft] = useState<{scope:string;value:RoverSettings}|null>(null);
|
||||
const saved = useMemo(()=>{
|
||||
try { return robot && scope ? parseRoverSettings(localStorage.getItem(scope),robot) : undefined; }
|
||||
catch { return undefined; }
|
||||
},[scope]);
|
||||
const value = draft?.scope===scope ? draft.value : saved ?? (robot ? defaultRoverSettings(robot,speed) : undefined);
|
||||
const update = (next:RoverSettings) => {
|
||||
if(!scope)return;
|
||||
setDraft({scope,value:next});
|
||||
// Keep usable in-memory intent, but let the caller report persistence failure.
|
||||
localStorage.setItem(scope,JSON.stringify(next));
|
||||
};
|
||||
return [value,update] as const;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { AiCatalog, AiRun } from "./aiPolygon";
|
||||
/** Read-only catalog refreshes never claim a browser's video session. */
|
||||
export function viewedAiRun(catalog:AiCatalog|null,worldId:string,runId:string|null):AiRun|undefined {
|
||||
if(!catalog||!runId)return undefined;
|
||||
const active=catalog.runtime.active_run;
|
||||
if(active?.run_id===runId&&active.world.world_id===worldId)return active;
|
||||
return catalog.runs.find(r=>r.run_id===runId&&r.world.world_id===worldId);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export type WaypointAxis = "x" | "y" | "z" | "xz";
|
||||
/** Closest point on the selected axis to the screen ray. Null at a parallel view. */
|
||||
export function dragWaypoint(origin: number[], direction: number[], point: number[], axis: WaypointAxis): number[] | null {
|
||||
const norm = Math.hypot(...direction);
|
||||
if (norm < 1e-9) return null;
|
||||
const d = direction.map(v => v / norm);
|
||||
if (axis === "xz") {
|
||||
if (Math.abs(d[1]) < 1e-5) return null;
|
||||
const t = (point[1] - origin[1]) / d[1];
|
||||
return t < 0 ? null : origin.map((v,i) => v + t*d[i]);
|
||||
}
|
||||
const index = {x:0,y:1,z:2}[axis], denominator = 1-d[index]**2;
|
||||
if (denominator < 1e-5) return null;
|
||||
const v = point.map((p,i) => p-origin[i]);
|
||||
const distance = (d[index]*v.reduce((sum,p,i) => sum+p*d[i],0)-v[index])/denominator;
|
||||
return point.map((p,i) => p+(i===index?distance:0));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { AiWaypoint } from "./aiPolygon";
|
||||
interface Snapshot { points: AiWaypoint[]; selected: string|null }
|
||||
export interface WaypointEditing extends Snapshot { history:Snapshot[]; gesture:Snapshot|null; sequence:number }
|
||||
export type WaypointEdit = {type:"select";id:string|null}|{type:"replace"|"move"|"load";points:AiWaypoint[];selected?:string|null}
|
||||
|{type:"delete"|"undo"|"begin"|"commit"|"cancel"};
|
||||
export function waypointEditing(points:AiWaypoint[]):WaypointEditing {return {points,selected:null,history:[],gesture:null,sequence:0};}
|
||||
const snapshot=(s:WaypointEditing):Snapshot=>({points:s.points,selected:s.selected});
|
||||
const same=(a:AiWaypoint[],b:AiWaypoint[])=>a.length===b.length&&a.every((p,i)=>p.id===b[i].id&&p.position.every((v,j)=>v===b[i].position[j]));
|
||||
export function editWaypoints(s:WaypointEditing,a:WaypointEdit):WaypointEditing {
|
||||
const commit=(prior:Snapshot,points:AiWaypoint[],selected:string|null):WaypointEditing=>({
|
||||
points,selected,gesture:null,history:[...s.history.slice(-49),prior],sequence:s.sequence+1,
|
||||
});
|
||||
switch(a.type){
|
||||
case "select":return {...s,selected:a.id};
|
||||
case "load":return {...waypointEditing(a.points),sequence:s.sequence+1};
|
||||
case "replace":return same(s.points,a.points)?s:commit(snapshot(s),a.points,a.selected??null);
|
||||
case "delete":return s.gesture||!s.points.some(p=>p.id===s.selected)?s:commit(snapshot(s),s.points.filter(p=>p.id!==s.selected),null);
|
||||
case "begin":return {...s,gesture:snapshot(s)};
|
||||
case "move":return s.gesture?{...s,points:a.points}:s;
|
||||
case "cancel":return s.gesture?{...s,...s.gesture,gesture:null}:s;
|
||||
case "commit":return !s.gesture?s:same(s.gesture.points,s.points)?{...s,gesture:null}:commit(s.gesture,s.points,s.selected);
|
||||
case "undo":{
|
||||
if(s.gesture)return {...s,...s.gesture,gesture:null};
|
||||
const prior=s.history.at(-1);return prior?{...s,...prior,history:s.history.slice(0,-1),sequence:s.sequence+1}:s;
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Keyboard shortcuts are local to the scene; native text undo remains native. */
|
||||
export function waypointShortcut(e:{key:string;code:string;ctrlKey:boolean;metaKey:boolean;altKey:boolean;shiftKey:boolean},editable:boolean):"undo"|"delete"|null {
|
||||
if(editable||e.altKey)return null;
|
||||
if((e.ctrlKey||e.metaKey)&&!e.shiftKey&&e.code==="KeyZ")return "undo";
|
||||
if(!e.ctrlKey&&!e.metaKey&&(e.key==="Delete"||e.key==="Backspace"))return "delete";
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Exact closed vertical cylinder, including caps. Ray need not be normalized. */
|
||||
export function waypointHit(origin:number[], direction:number[], base:number[], radius:number, height:number):number|null {
|
||||
const [ox,oy,oz]=origin.map((v,i)=>v-base[i]), [dx,dy,dz]=direction;
|
||||
const candidates:number[]=[];
|
||||
const a=dx*dx+dz*dz,b=2*(ox*dx+oz*dz),c=ox*ox+oz*oz-radius*radius;
|
||||
if(a>1e-14) {
|
||||
const discriminant=b*b-4*a*c;
|
||||
if(discriminant>=0)for(const t of [(-b-Math.sqrt(discriminant))/(2*a),(-b+Math.sqrt(discriminant))/(2*a)])
|
||||
if(t>=0 && oy+t*dy>=0 && oy+t*dy<=height)candidates.push(t);
|
||||
}
|
||||
if(Math.abs(dy)>1e-14)for(const y of [0,height]) {
|
||||
const t=(y-oy)/dy;
|
||||
if(t>=0 && (ox+t*dx)**2+(oz+t*dz)**2<=radius*radius)candidates.push(t);
|
||||
}
|
||||
return candidates.length?Math.min(...candidates):null;
|
||||
}
|
||||
@@ -1,12 +1,21 @@
|
||||
.simulation-profiles { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-height: 0; }
|
||||
.simulation-profiles > .nodedc-select-anchor { justify-self: start; }
|
||||
.ai-polygon { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; min-width: 0; min-height: 0; overflow: hidden; }
|
||||
.ai-polygon { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-width: 0; min-height: 0; overflow: hidden; }
|
||||
.ai-polygon__content { min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: 1rem; }
|
||||
.ai-polygon__head, .ai-polygon__row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
|
||||
.ai-polygon__actions, .ai-polygon__facts { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
|
||||
.ai-polygon__robot-select { width: 12rem; flex: 0 0 12rem; }
|
||||
.ai-polygon__report { font-size: var(--nodedc-font-size-sm); }
|
||||
.ai-polygon__report dl { margin: 0; display: grid; gap: .5rem; }
|
||||
.ai-polygon__report dl > div { display: flex; justify-content: space-between; gap: 1rem; }
|
||||
.ai-polygon__report dt, .ai-polygon__report p { color: var(--nodedc-text-muted); }
|
||||
.ai-polygon__report dd { margin: 0; text-align: right; }
|
||||
.ai-polygon__report h3 { margin: .5rem 0 0; font-size: var(--nodedc-font-size-md); }
|
||||
.ai-polygon__report-identities dd { overflow-wrap: anywhere; max-width: 65%; }
|
||||
.ai-polygon__telemetry-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
|
||||
.ai-polygon__telemetry-row > .ai-polygon__facts { flex: 1; min-width: 0; }
|
||||
.ai-polygon__telemetry-row > :last-child { flex-shrink: 0; }
|
||||
.ai-polygon__telemetry-row--local { justify-content: flex-start; flex-wrap: wrap; }
|
||||
.ai-polygon__section, .ai-polygon__run, .ai-polygon__form { display: grid; gap: .75rem; }
|
||||
.ai-polygon h2, .ai-polygon h3, .ai-polygon p { margin: 0; }
|
||||
.ai-polygon h2 { font-size: var(--nodedc-font-size-title); }
|
||||
@@ -17,9 +26,12 @@
|
||||
|
||||
.ai-polygon__title { display: flex; align-items: center; gap: 1rem; }
|
||||
.ai-polygon__stage { display: flex; flex-direction: column; gap: .75rem; min-width: 0; }
|
||||
.ai-polygon__content--local { display: flex; flex-direction: column; gap: .75rem; overflow: hidden; padding-bottom: 0; }
|
||||
.ai-polygon__content--local > .ai-polygon__section,
|
||||
.ai-polygon__content--local .ai-polygon__stage { display: flex; flex-direction: column; flex: 1; min-height: 0; }
|
||||
.ai-polygon__content--local .ai-polygon__viewer { flex: 1; height: auto; min-height: 0; }
|
||||
.ai-polygon__viewer { display: flex; flex-direction: column; min-height: 24rem; height: min(65vh, 48rem); overflow: hidden; border-radius: var(--nodedc-radius-panel); background: var(--nodedc-canvas); }
|
||||
.ai-polygon__viewer-toolbar { display: flex; justify-content: space-between; align-items: flex-start; padding: .5rem; gap: .5rem; }
|
||||
.ai-polygon__viewport { flex: 1; position: relative; min-height: 0; overflow: hidden; }
|
||||
.ai-polygon__viewport { flex: 1; position: relative; min-height: 0; overflow: hidden; border-radius: inherit; }
|
||||
.ai-polygon__viewport[hidden] { display: none; }
|
||||
.ai-polygon__viewport .nodedc-loading-region { height: 100%; }
|
||||
.ai-polygon__video { width: 100%; height: 100%; pointer-events: none; }
|
||||
@@ -27,3 +39,135 @@
|
||||
.ai-polygon__preview-error { position: absolute; inset: 0; display: grid; place-content: center; gap: .75rem; background: var(--nodedc-canvas); }
|
||||
.ai-polygon__stage:fullscreen { height: 100%; box-sizing: border-box; padding: .75rem; overflow: auto; background: var(--nodedc-canvas); }
|
||||
.ai-polygon__stage:fullscreen .ai-polygon__viewer { flex: 1; height: auto; min-height: 12rem; }
|
||||
|
||||
.ai-polygon__plan-select { width: 16rem; flex: 0 0 16rem; }
|
||||
@media (max-width: 1600px) {
|
||||
.ai-polygon__robot-select { width: 8rem; flex-basis: 8rem; }
|
||||
.ai-polygon__plan-select { width: 10rem; flex-basis: 10rem; }
|
||||
}
|
||||
.ai-route { position: absolute; inset: 0; pointer-events: none; }
|
||||
.ai-route__canvas { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); overflow: hidden; }
|
||||
.ai-route__canvas--editing { pointer-events: auto; touch-action: none; cursor: grab; }
|
||||
.ai-route__tools { position: absolute; bottom: .75rem; left: .75rem; right: 5rem; display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; pointer-events: auto; }
|
||||
.ai-route__tools p { flex-basis: 100%; padding: .25rem .5rem; background: var(--nodedc-canvas-soft); border-radius: var(--nodedc-radius-control); }
|
||||
.ai-route__height { position: absolute; top: 44px; right: 12px; bottom: 12px; width: 58px; display: flex; flex-direction: column; align-items: center; gap: 6px; pointer-events: auto; color: var(--nodedc-text-muted); font-size: var(--nodedc-font-size-xs); }
|
||||
.ai-route__height > .nodedc-range-scale { flex: 1; min-height: 0; }
|
||||
.ai-route__line { fill: none; stroke: var(--nodedc-text-primary); stroke-width: 3; stroke-dasharray: 8 5; opacity: .8; pointer-events: none; }
|
||||
.ai-route__trace { fill: none; stroke: rgb(var(--nodedc-success-rgb)); stroke-width: 4; pointer-events: none; }
|
||||
.ai-route__marker { fill: var(--nodedc-text-primary); stroke: var(--nodedc-canvas); stroke-width: 2; cursor: pointer; }
|
||||
.ai-route__beam { stroke: var(--nodedc-text-primary); stroke-width: 7; animation: ai-route-pulse 2s ease-in-out infinite; }
|
||||
.ai-route__marker text { font: 600 16px var(--nodedc-font-family); paint-order: stroke; stroke-width: 3; }
|
||||
.ai-route__marker.is-selected, .ai-route__marker.is-active { fill: rgb(var(--nodedc-accent-rgb)); }
|
||||
.ai-route__marker.is-selected .ai-route__beam, .ai-route__marker.is-active .ai-route__beam { stroke: rgb(var(--nodedc-accent-rgb)); }
|
||||
.ai-route__axis { stroke: rgb(var(--nodedc-accent-rgb)); stroke-width: 5; cursor: move; }
|
||||
.ai-route__axis path { fill: rgb(var(--nodedc-accent-rgb)); stroke-width: 2; }
|
||||
.ai-route__axis text { stroke: none; fill: var(--nodedc-text-primary); font-size: 16px; }
|
||||
@keyframes ai-route-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .4; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ai-route__beam { animation: none; } }
|
||||
.ai-local-editor__surface { position: absolute; inset: 0; touch-action: none; }
|
||||
.ai-local-editor > canvas, .ai-local-editor__surface > canvas { display: block; width: 100%; height: 100%; touch-action: none; }
|
||||
.ai-local-editor__markers { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
|
||||
.ai-local-editor__markers .ai-route__marker { pointer-events: auto; touch-action: none; }
|
||||
|
||||
.ai-local-editor__markers .ai-route__beam { stroke-width: 21; }
|
||||
|
||||
/* View controls float above the render target; there is no separate header strip. */
|
||||
.ai-simulation__view-tools { max-width: calc(100% - 6rem); flex-wrap: wrap; justify-content: flex-end; position: absolute; z-index: 3; top: .5rem; right: .5rem; display: flex; align-items: center; gap: .5rem; }
|
||||
.ai-simulation__view-tools > .nodedc-select-anchor { width: 10rem; }
|
||||
.ai-simulation__speed { position: absolute; left: .75rem; bottom: .75rem; pointer-events: none; font-size: var(--nodedc-font-size-sm); }
|
||||
/* Equal visible padding on all three sides; owner requested twice the radius-centred inset. */
|
||||
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: var(--ai-clip-inset); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
|
||||
.ai-local-editor__tools { display: flex; align-items: center; gap: .5rem; }
|
||||
.ai-local-editor .ai-route__tools { left: 5.5rem; right: .75rem; }
|
||||
/* The renderer has no perimeter; canonical controls retain their focus indicators. */
|
||||
.ai-local-editor canvas { outline: none; }
|
||||
.ai-local-editor__hit, .ai-local-editor__axis-hit line { stroke: transparent; stroke-width: 28; pointer-events: stroke; }
|
||||
.ai-local-editor__axis-hit { cursor: move; }
|
||||
.ai-local-editor__axis-hit text { stroke: none; fill: var(--nodedc-text-primary); pointer-events: none; }
|
||||
.ai-polygon__history { width: 100%; }
|
||||
|
||||
.ai-polygon__stream-bounds { container-type: size; }
|
||||
/* Video and its projected route use the same cover transform, with one outer clip. */
|
||||
.ai-polygon__stream-picture { position: absolute; inset: 0; border-radius: var(--nodedc-radius-panel); overflow: hidden; }
|
||||
.ai-polygon__stream-tools { position: absolute; z-index: 3; top: 1.5rem; left: 1.5rem; right: 1.5rem; display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; pointer-events: none; }
|
||||
.ai-polygon__stream-fps { flex-shrink: 0; }
|
||||
.ai-polygon__stream-actions { margin-left: auto; display: flex; align-items: center; gap: .5rem; pointer-events: auto; }
|
||||
|
||||
.ai-polygon__video-frame { display: block; width: 100%; height: 100%; border: 0; pointer-events: none; }
|
||||
|
||||
.ai-polygon__stream-bounds { outline: none; touch-action: none; }
|
||||
.ai-polygon__stream-actions { flex-wrap: wrap; justify-content: flex-end; max-width: 100%; }
|
||||
.ai-polygon__camera-select { display: none; width: 13rem; max-width: 100%; }
|
||||
@container (max-width: 45rem) {
|
||||
.ai-polygon__camera-tabs { display: none; }
|
||||
.ai-polygon__camera-select { display: block; }
|
||||
}
|
||||
.ai-polygon__inference-tools { position: absolute; z-index: 3; bottom: 1.5rem; right: 1.5rem; left: 1.5rem; display: flex; justify-content: flex-end; flex-wrap: wrap; gap: .5rem; pointer-events: none; }
|
||||
.ai-polygon__inference-tools > * { pointer-events: auto; }
|
||||
.ai-polygon__layer-options { display: grid; gap: .5rem; }
|
||||
.ai-inference-preview { flex: 1; min-width: 0; position: relative; overflow: hidden; border-radius: var(--nodedc-radius-panel); background: var(--nodedc-canvas); }
|
||||
.ai-inference-preview > img { display: block; width: 100%; height: 100%; object-fit: contain; }
|
||||
.ai-inference-preview__tools { position: absolute; top: 1.5rem; left: 1.5rem; right: 1.5rem; display: flex; align-items: center; justify-content: space-between; gap: .5rem; }
|
||||
.ai-inference-preview__caption { position: absolute; bottom: 1.5rem; left: 1.5rem; right: 1.5rem; display: grid; gap: .5rem; font-size: var(--nodedc-font-size-sm); }
|
||||
|
||||
.ai-inference-preview__legend { display: flex; flex-wrap: wrap; gap: .35rem .75rem; }
|
||||
.ai-inference-preview__legend > span { display: inline-flex; align-items: center; gap: .3rem; }
|
||||
.ai-inference-preview__legend i { width: .65rem; height: .65rem; border-radius: 50%; }
|
||||
.ai-inference-preview__caption { background: var(--nodedc-surface-overlay, #272729); padding: .75rem; border-radius: 1rem; }
|
||||
|
||||
.ai-polygon__configuration-columns { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:var(--nodedc-space-6); align-items:start; }
|
||||
.ai-polygon__configuration-column { display:grid; gap:var(--nodedc-space-4); min-width:0; }
|
||||
.ai-polygon__configuration-fields { display: grid; gap: 1rem; width: 100%; }
|
||||
.ai-polygon__profile-row { display:flex; align-items:flex-end; gap:var(--nodedc-space-2); flex-wrap:wrap; }
|
||||
.ai-polygon__profile-row > :first-child { flex:1; min-width:12rem; }
|
||||
@media (max-width: 800px) { .ai-polygon__configuration-columns { grid-template-columns:minmax(0,1fr); } }
|
||||
.ai-polygon__rover-row { display: flex; align-items: flex-end; gap: .5rem; min-width: 0; }
|
||||
.ai-polygon__rover-row > .ai-polygon__robot-select { flex: 1; width: auto; min-width: 0; }
|
||||
/* Stable grid cells keep the one Worker video connection mounted as panes change. */
|
||||
.ai-polygon__viewports { flex: 1; min-height: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-auto-rows: minmax(18rem, 1fr); gap: .75rem; overflow: auto; }
|
||||
.ai-polygon__viewports[data-panes="1"] { grid-template-columns: minmax(0, 1fr); }
|
||||
.ai-polygon__viewports > * { min-width: 0; min-height: 0; }
|
||||
.ai-inference-preview:fullscreen { width: 100%; height: 100%; }
|
||||
.ai-inference-preview__tools { z-index: 2; pointer-events: none; }
|
||||
.ai-inference-preview__tools > * { pointer-events: auto; }
|
||||
.ai-inference-preview__caption { pointer-events: none; }
|
||||
.ai-polygon__viewer:has(> .ai-polygon__viewports) { background: transparent; }
|
||||
@media (max-width: 800px) {
|
||||
.ai-polygon__viewports { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
.ai-polygon__configuration-fields > .ai-polygon__robot-select,
|
||||
.ai-polygon__configuration-fields > .ai-polygon__plan-select { width: 100%; }
|
||||
.ai-polygon__observation { display:flex; flex-direction:column; flex:1; min-width:0; min-height:0; gap:var(--nodedc-space-2); }
|
||||
.ai-polygon__observation-toolbar { display:flex; justify-content:flex-end; gap:var(--nodedc-space-2); }
|
||||
.ai-polygon__observation .ai-polygon__viewport, .ai-polygon__observation .ai-inference-preview { height:100%; min-height:0; }
|
||||
.ai-polygon__observation .ai-polygon__stream-fps { position:absolute; bottom:var(--nodedc-space-3); left:var(--nodedc-space-3); z-index:2; }
|
||||
.ai-polygon__observation .observation-panel__header { z-index:4; }
|
||||
.ai-polygon__viewer:has(> .ai-polygon__observation) { background:transparent; }
|
||||
|
||||
/* Fixed telemetry slots keep changing status and digit counts independent. */
|
||||
.ai-polygon__run { container-type: inline-size; }
|
||||
.ai-polygon__run-metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(9, minmax(0, 1fr));
|
||||
gap: .75rem;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
padding: .5rem .25rem;
|
||||
box-sizing: border-box;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
}
|
||||
.ai-polygon__run-metric { min-width: 0; text-align: center; }
|
||||
.ai-polygon__run-metric dt { margin-bottom: .25rem; color: var(--nodedc-text-muted); }
|
||||
.ai-polygon__run-metric dd {
|
||||
margin: 0;
|
||||
min-height: 2.5em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.ai-polygon__run-metric--status dd { display: flex; justify-content: center; }
|
||||
@container (max-width: 64rem) {
|
||||
.ai-polygon__run-metrics { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
}
|
||||
@container (max-width: 32rem) {
|
||||
.ai-polygon__run-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {useEffect,useLayoutEffect,useMemo,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,DragDropRoot,DraggableItem,DropZone,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,Window} from '@nodedc/ui-react';
|
||||
import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,Window} from '@nodedc/ui-react';
|
||||
import {useDevicePluginHost} from '../../../core/device-plugins/DevicePluginHost';
|
||||
import {createFleetSensorTransport} from '../../../core/fleet/sensorTransport';
|
||||
import {decodeObservationLayout,emptyObservationLayout,moveObservation,orderedObservationIDs} from '../../../core/fleet/observationLayout';
|
||||
import {decodeObservationLayout,emptyObservationLayout,moveObservation,withObservationTree,orderedObservationIDs} from '../../../core/fleet/observationLayout';
|
||||
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
|
||||
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
|
||||
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
|
||||
@@ -45,21 +45,19 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
|
||||
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
|
||||
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
|
||||
useEffect(()=>{try{localStorage.setItem(storageKey,JSON.stringify(layout));}catch{/* The workspace remains usable without browser storage. */}},[storageKey,layout]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
|
||||
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,catalogVisible:show?[...new Set([...(value.catalogVisible??[]),...(sources.find(source=>source.key===id)?.catalog?[id]:[])])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
|
||||
const layerFor=(key:string,view:SensorObservationView)=>view.layers?.find(layer=>layer.value===layout.layers[key])?.value??view.layers?.[0]?.value??view.id;
|
||||
const navigationActions=<><IconButton label="Конфигуратор" onClick={configure}><Icon name="sliders"/></IconButton><IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton></>;
|
||||
return <>{headerToolsHost&&!expanded&&createPortal(navigationActions,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
|
||||
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&navigationActions}<Button onClick={()=>{setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
|
||||
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
|
||||
<DragDropRoot onDragEnd={({activeId,overId})=>{if(overId)setLayout(value=>moveObservation(value,ids,activeId,overId));}}>
|
||||
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={effectiveFull?[effectiveFull]:visible} mounts={mounts.current} layout={layout} onSplit={(key,value)=>setLayout(current=>({...current,splits:{...current.splits,[key]:value}}))}/>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>{setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
|
||||
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,tree))}>
|
||||
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
|
||||
<DropZone id={source.key} className="observation-panel">
|
||||
<DraggableItem id={source.key} className="observation-panel-drag">{({handle})=>
|
||||
<div className="observation-panel">
|
||||
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
|
||||
<ObservationPanelHeader>
|
||||
{handle}
|
||||
<DockHandle id={source.key} label={source.view.label}/>
|
||||
<div className="observation-panel__title"><h3 title={source.view.label}>{source.view.label}</h3><ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
|
||||
<div className="observation-actions">
|
||||
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
|
||||
@@ -71,9 +69,8 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
|
||||
</ObservationPanelHeader>
|
||||
<ObservationMount element={media.current.get(source.key)!}/>
|
||||
</GlassSurface>
|
||||
}</DraggableItem>
|
||||
</DropZone>,mounts.current.get(source.key)!,source.key))}
|
||||
</DragDropRoot>
|
||||
</div>,mounts.current.get(source.key)!,source.key))}
|
||||
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
|
||||
{groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} enabled={enabled&&inventory?.fresh!==false&&device.online} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
|
||||
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить в конфигураторе</Button></div></div>,media.current.get(source.key)!,source.key))}
|
||||
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
|
||||
@@ -81,9 +78,9 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
|
||||
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible}/>,media.current.get('rover')!,'rover-session')}
|
||||
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state}/>,media.current.get('telemetry')!,'telemetry-session')}
|
||||
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
|
||||
<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement}))}/>
|
||||
<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement,tree:undefined,splits:{}}))}/>
|
||||
{ids.map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.catalog?`${source.view.label} · Источник не подключён`:source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
|
||||
<Button onClick={()=>{setLayout(emptyObservationLayout());setFull(null);}}>Восстановить расположение</Button>
|
||||
<Button onClick={()=>{setLayout(current=>({...current,tree:undefined,order:[],splits:{},arrangement:'auto'}));setFull(null);}}>Восстановить расположение</Button>
|
||||
</div></Window>
|
||||
</section>,portal)}</>;
|
||||
}
|
||||
|
||||
@@ -1,18 +1 @@
|
||||
import {useLayoutEffect,useRef} from 'react';
|
||||
import {SplitPane} from '@nodedc/ui-react';
|
||||
import type {ObservationLayout} from '../../../core/fleet/observationLayout';
|
||||
|
||||
/** Moving a mount preserves media elements, peer lifetimes and native renderer state. */
|
||||
export function ObservationMount({element,className='observation-mount'}:{element:HTMLElement;className?:string}){
|
||||
const ref=useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
|
||||
return <div ref={ref} className={className}/>;
|
||||
}
|
||||
export function ObservationDeck({ids,mounts,layout,onSplit,depth=0}:{ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onSplit:(key:string,value:number)=>void;depth?:number}){
|
||||
if(!ids.length)return null;
|
||||
if(ids.length===1)return <ObservationMount element={mounts.get(ids[0])!}/>;
|
||||
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&ids.some(id=>!['map','rover','telemetry'].includes(id));
|
||||
const cameraCount=ids.filter(id=>!['map','rover','telemetry'].includes(id)).length;
|
||||
const mid=defaultColumns&&cameraCount<ids.length?cameraCount:layout.arrangement==='auto'&&ids[0]==='map'&&ids.includes('rover')?1:Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical';
|
||||
return <SplitPane separatorAppearance="invisible" className="observation-split" orientation={orientation} primarySize={layout.splits[key]??50} onPrimarySizeChange={value=>onSplit(key,value)} separatorLabel="Изменить размеры окон" primary={<ObservationDeck ids={ids.slice(0,mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>} secondary={<ObservationDeck ids={ids.slice(mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>}/>;
|
||||
}
|
||||
export {ObservationDeck,ObservationMount} from "../../../components/observation/ObservationDeck";
|
||||
|
||||
@@ -1,13 +1 @@
|
||||
import {useLayoutEffect,useRef,type ReactNode} from 'react';
|
||||
|
||||
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
|
||||
export function ObservationPanelHeader({children}:{children:ReactNode}) {
|
||||
const ref=useRef<HTMLElement>(null);
|
||||
useLayoutEffect(()=>{
|
||||
const header=ref.current!;
|
||||
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
|
||||
measure();const observer=new ResizeObserver(measure);observer.observe(header);
|
||||
return()=>observer.disconnect();
|
||||
},[]);
|
||||
return <header ref={ref} className="observation-panel__header">{children}</header>;
|
||||
}
|
||||
export {ObservationPanelHeader} from "../../../components/observation/ObservationPanelHeader";
|
||||
|
||||
@@ -1,50 +1 @@
|
||||
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
|
||||
.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
|
||||
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
|
||||
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
|
||||
.observation-toolbar h2, .observation-panel h3 { margin:0; }
|
||||
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
|
||||
.observation-actions { flex-shrink:0; }
|
||||
.observation-deck { flex:1; min-height:0; min-width:0; }
|
||||
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
|
||||
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
|
||||
.observation-panel__surface > .observation-mount { flex:1; }
|
||||
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
|
||||
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
|
||||
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
|
||||
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
|
||||
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
|
||||
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
|
||||
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
|
||||
.observation-header-slot:has(> div:empty) { display:none; }
|
||||
.observation-layer-select { min-width:0; max-width:120px; }
|
||||
.observation-layer-select button { max-width:100%; }
|
||||
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
|
||||
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
|
||||
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
|
||||
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
|
||||
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
|
||||
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
|
||||
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
|
||||
.observation-layer > * { min-width:0; width:100%; }
|
||||
.observation-layer > .nodedc-switch { text-align:left; }
|
||||
.observation-empty { display:grid; place-content:center; height:100%; text-align:center; }
|
||||
.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; }
|
||||
@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } }
|
||||
|
||||
.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; }
|
||||
|
||||
/* Transform the live panel as one item; reveal it across nested split boundaries. */
|
||||
.observation-panel-drag { position:relative; height:100%; min-height:0; }
|
||||
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
|
||||
.observation-split:has(.observation-panel-drag.is-dragging),
|
||||
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
|
||||
@container (max-width:340px) {
|
||||
.observation-panel__header { flex-wrap:wrap; }
|
||||
.observation-panel__title { min-width:80px; }
|
||||
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
|
||||
}
|
||||
|
||||
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
|
||||
@import "../../../components/observation/observation.css";
|
||||
|
||||
@@ -1,14 +1,38 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, StatusBadge, ToastStack } from "@nodedc/ui-react";
|
||||
import { useRoutePreparation } from "../../core/simulation/routePreparation";
|
||||
import { viewedAiRun } from "../../core/simulation/viewedAiRun";
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, InspectorSelectField, ResourceList, ResourceRow, StatusBadge, ToastStack } from "@nodedc/ui-react";
|
||||
import { SimulationSourceImport } from "../../components/simulation/SimulationSourceImport";
|
||||
import { AiWorldImport } from "../../components/simulation/AiWorldImport";
|
||||
import { AiWorldStream } from "../../components/simulation/AiWorldStream";
|
||||
import { AiWorldSetup } from "../../components/simulation/AiWorldSetup";
|
||||
import { AiRunView } from "../../components/simulation/AiRunView";
|
||||
import { AiRunActions } from "../../components/simulation/AiRunActions";
|
||||
import { AiCompositionFields } from "../../components/simulation/AiCompositionFields";
|
||||
import { fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules, type AiSelection } from "../../core/simulation/aiPolygon";
|
||||
import { AiRunReport } from "../../components/simulation/AiRunReport";
|
||||
import { AiConfiguration } from "../../components/simulation/AiConfiguration";
|
||||
import { AiSessionSection } from "../../components/simulation/AiSessionSection";
|
||||
import { AiTaskSelect } from "../../components/simulation/AiTaskSelect";
|
||||
import { AiPlanSaveWindow } from "../../components/simulation/AiPlanSaveWindow";
|
||||
import { planMatchesDraft } from "../../core/simulation/planDraft";
|
||||
import type { AiPlan, AiWaypoint } from "../../core/simulation/aiPolygon";
|
||||
import { aiPlanName, updateAiPlan, removeAiRun, fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules } from "../../core/simulation/aiPolygon";
|
||||
import { useAiSelection } from "../../core/simulation/useAiSelection";
|
||||
import { useRoverSettings } from "../../core/simulation/useRoverSettings";
|
||||
import { RoverSettingsWindow } from "../../components/simulation/RoverSettingsWindow";
|
||||
import { currentSelection } from "../../core/simulation/runConfiguration";
|
||||
|
||||
import { saveLocalPlan } from "../../core/simulation/aiEditor";
|
||||
import type { LocalDraft } from "../../components/simulation/AiLocalPlanner";
|
||||
const LocalManualScene = lazy(() => import("../../components/simulation/LocalManualScene").then((m) => ({ default: m.LocalManualScene })));
|
||||
const AiLocalPlanner = lazy(() => import("../../components/simulation/AiLocalPlanner").then((m) => ({ default: m.AiLocalPlanner })));
|
||||
const EMPTY_POINTS:AiWaypoint[]=[];
|
||||
|
||||
export function AiPolygonWorkspace() {
|
||||
const [mode,setMode] = useState<"manual"|"inference">("inference");
|
||||
const [manual,setManual] = useState(false);
|
||||
const [importChoice,setImportChoice] = useState(false);
|
||||
const [planning, setPlanning] = useState(false);
|
||||
const [draft, setDraft] = useState<LocalDraft | null>(null);
|
||||
const [catalog, setCatalog] = useState<AiCatalog | null>(null);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [runId, setRunId] = useState<string | null>(null);
|
||||
@@ -16,14 +40,50 @@ export function AiPolygonWorkspace() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [roverSettingsOpen,setRoverSettingsOpen] = useState(false);
|
||||
const [actionsHost, setActionsHost] = useState<HTMLDivElement | null>(null);
|
||||
const [modules, setModules] = useState<AiModules | null>(null);
|
||||
const [selection, setSelection] = useState<AiSelection | undefined>();
|
||||
const [robotId, setRobotId] = useState<string | null>(null);
|
||||
const [planId, setPlanId] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError,setSaveError] = useState<string|null>(null);
|
||||
const [saveOpen, setSaveOpen] = useState(false);
|
||||
const [launchAfterSave,setLaunchAfterSave] = useState(false);
|
||||
const [editorPlan,setEditorPlan] = useState<AiPlan|null>(null);
|
||||
const [planName, setPlanName] = useState("");
|
||||
const [removing,setRemoving] = useState<string|null>(null);
|
||||
const [removed,setRemoved] = useState<{kind:"plan"|"run";id:string;name:string}[]>([]);
|
||||
const planUpdated = (value:AiPlan) => {
|
||||
setCatalog(prior=>prior?{...prior,plans:value.removed ? prior.plans.filter(p=>p.plan_id!==value.plan_id)
|
||||
: prior.plans.map(p=>p.plan_id===value.plan_id?value:p)}:prior);
|
||||
if(value.removed){
|
||||
setRemoved(prior=>[...prior,{kind:"plan",id:value.plan_id,name:aiPlanName(value)}]);
|
||||
if(plan?.plan_id===value.plan_id)setPlanId("");
|
||||
}
|
||||
};
|
||||
const removeRun = async (value:AiRun) => {
|
||||
setRemoving(value.run_id);
|
||||
try {
|
||||
await removeAiRun(value.run_id,true);
|
||||
setCatalog(prior=>prior?{...prior,runs:prior.runs.filter(r=>r.run_id!==value.run_id)}:prior);
|
||||
setRemoved(prior=>[...prior,{kind:"run",id:value.run_id,name:`Прогон ${new Date(value.created_at??"").toLocaleString("ru-RU")}`}]);
|
||||
} catch(caught) { setError(caught instanceof Error?caught.message:"Не удалось удалить прогон."); }
|
||||
finally {setRemoving(null);}
|
||||
};
|
||||
const undoRemove = async () => {
|
||||
const item=removed.at(-1);if(!item)return;
|
||||
setRemoving(item.id);
|
||||
try {
|
||||
if(item.kind==="plan")await updateAiPlan(item.id,{removed:false});else await removeAiRun(item.id,false);
|
||||
await load();setRemoved(prior=>prior.filter(p=>p.id!==item.id));
|
||||
} catch(caught) {setError(caught instanceof Error?caught.message:"Не удалось восстановить запись.");}
|
||||
finally {setRemoving(null);}
|
||||
};
|
||||
const fast = useRef(false);
|
||||
const load = useCallback(async () => { const result = await fetchAiCatalog(); setCatalog(result); }, []);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void fetchAiModules().then((value) => { if (active) { setModules(value); setSelection(value.selection); } })
|
||||
void fetchAiModules().then((value) => { if (active) setModules(value); })
|
||||
.catch((caught: Error) => { if (active) setError(caught.message); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
@@ -39,15 +99,17 @@ export function AiPolygonWorkspace() {
|
||||
void poll(); return () => { active = false; clearTimeout(timer); };
|
||||
}, []);
|
||||
const selected = catalog?.worlds.find((world) => world.world_id === selectedId);
|
||||
const activeRun = catalog?.runtime.active_run;
|
||||
useEffect(() => {
|
||||
if (activeRun?.world.world_id === selectedId) setRunId(activeRun.run_id);
|
||||
}, [activeRun?.run_id, activeRun?.world.world_id, selectedId]);
|
||||
const run = selected ? catalog?.runtime.active_run?.world.world_id === selected.world_id
|
||||
? catalog.runtime.active_run : catalog?.runs.find((item) => item.run_id === runId && item.world.world_id === selected.world_id)
|
||||
: undefined;
|
||||
// Catalog observation does not acquire NVIDIA's single video slot. Only Start
|
||||
// or an explicit Open may attach this browser to a running simulation.
|
||||
const run = selected && mode === "inference" ? viewedAiRun(catalog,selected.world_id,runId) : undefined;
|
||||
const shownFailure=useRef<string|null>(null);
|
||||
useEffect(()=>{
|
||||
if(run?.state==='failed'&&shownFailure.current!==run.run_id){
|
||||
shownFailure.current=run.run_id;setError(run.message??'Не удалось запустить симуляцию.');
|
||||
}
|
||||
},[run?.run_id,run?.state,run?.message]);
|
||||
const acceptRun = (value: AiRun) => {
|
||||
setSettingsOpen(false);
|
||||
setSettingsOpen(false);setPlanning(false);setDraft(null);
|
||||
setRunId(value.run_id); fast.current = !["completed", "stopped", "failed"].includes(value.state);
|
||||
setCatalog((prior) => prior ? { ...prior, runs: [value, ...prior.runs.filter((r) => r.run_id !== value.run_id)],
|
||||
runtime: { ...prior.runtime, active_run: fast.current ? value : null } } : prior);
|
||||
@@ -59,21 +121,87 @@ export function AiPolygonWorkspace() {
|
||||
const openWorld = (world: AiWorld) => {
|
||||
if (world.status === "uploading") setImporting({ source: world, resume: world });
|
||||
else {
|
||||
setSelectedId(world.world_id); setRunId(null); setSettingsOpen(!world.settings.prepared);
|
||||
setSelectedId(world.world_id); setRunId(catalog?.runtime.active_run?.world.world_id===world.world_id?catalog.runtime.active_run.run_id:null); setPlanId(null);setEditorPlan(null);setSettingsOpen(!world.settings.prepared);
|
||||
}
|
||||
};
|
||||
const returnToLocations = () => { setSelectedId(null); setRunId(null); };
|
||||
const returnToLocations = () => { setManual(false); setPlanning(false); setDraft(null); setSelectedId(null); setRunId(null); };
|
||||
const running = !!run && !["completed", "stopped", "failed"].includes(run.state);
|
||||
const robot = catalog?.robots?.find((item) => item.robot_id === robotId) ?? catalog?.robots?.[0];
|
||||
const [selection, setSelection] = useAiSelection(selectedId, robot?.robot_id ?? null, modules);
|
||||
const plans = (catalog?.plans ?? []).filter((p) => p.world_id === selectedId
|
||||
&& p.robot_id === robot?.robot_id && p.robot_sha256 === robot?.sha256);
|
||||
const previousPlan = (catalog?.plans ?? []).find((p) => p.world_id === selectedId && p.robot_id === robot?.robot_id);
|
||||
const plan = planId === null ? plans[0] : plans.find((p) => p.plan_id === planId);
|
||||
const [roverSettings,setRoverSettings] = useRoverSettings(robot,
|
||||
plan?.settings?.max_speed_mps ?? selected?.settings.max_speed_mps ?? .15);
|
||||
const routeRequired=!!selected?.local_scene;
|
||||
const preparation=useRoutePreparation(draft?.cache??null,robot,draft?.points??EMPTY_POINTS,plan,setError);
|
||||
const start = (purpose: "planning" | "evaluation", task=plan) => {
|
||||
if (!selected || !robot) return;
|
||||
if (purpose === "planning") { setEditorPlan(plan??(planId===null?previousPlan:null)??null);setSettingsOpen(false); setDraft(null); setPlanning(true); return; }
|
||||
setStarting(true);
|
||||
void fetchAiModules().then((fresh) => {
|
||||
setModules(fresh);
|
||||
const composition = currentSelection(selection ?? fresh.selection, fresh);
|
||||
setSelection(composition);
|
||||
return startAiRun(selected, robot, composition, purpose, task, roverSettings);
|
||||
}).then(acceptRun).catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false));
|
||||
};
|
||||
const save = () => {
|
||||
if (!draft || !robot) return;
|
||||
setSaving(true);setSaveError(null);
|
||||
void saveLocalPlan(draft.cache, robot, draft.points, planName, draft.id, draft.sequence, preparation.key).then(async (saved) => {
|
||||
setPlanId(saved.plan_id);setSaveOpen(false);
|
||||
setCatalog(prior=>prior?{...prior,plans:[saved,...prior.plans.filter(p=>p.plan_id!==saved.plan_id)]}:prior);
|
||||
if(launchAfterSave)start("evaluation",saved);
|
||||
}).catch((caught: Error) => setSaveError(caught.message)).finally(() => setSaving(false));
|
||||
};
|
||||
const openSave = (launch=false) => {
|
||||
setSaveError(null);setLaunchAfterSave(launch);setPlanName(plan?aiPlanName(plan):`${selected?.name} · маршрут`);setSaveOpen(true);
|
||||
};
|
||||
const launchDraft = () => {
|
||||
if(!draft||!robot)return;
|
||||
if(routeRequired && (!preparation.route || !preparation.key))return;
|
||||
if(planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points) && (!routeRequired || plan?.prepared_route?.sha256===preparation.route?.sha256))start("evaluation",plan);
|
||||
else openSave(true);
|
||||
};
|
||||
const connection = <StatusBadge tone={catalog?.runtime.available ? "success" : "neutral"}>
|
||||
{catalog?.runtime.available ? "Симулятор подключён" : "Симулятор не подключён"}
|
||||
</StatusBadge>;
|
||||
const sceneActions = selected && catalog ? <>
|
||||
<Button onClick={() => setSettingsOpen(!settingsOpen)}>Старт и масштаб</Button>
|
||||
{!run || ["completed", "stopped", "failed"].includes(run.state) ? <Button variant="primary"
|
||||
icon={<Icon name="play" />} loading={starting}
|
||||
disabled={!catalog.runtime.available || !selected.settings.prepared || !!catalog.runtime.active_run}
|
||||
onClick={() => { setStarting(true); void startAiRun(selected, selection).then(acceptRun)
|
||||
.catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false)); }}>Открыть симуляцию</Button> : null}
|
||||
{run ? <AiRunActions run={run} onChange={acceptRun} /> : null}
|
||||
{!planning&&!manual&&!running&&!starting?<><div className="ai-polygon__robot-select"><InspectorSelectField label="Режим" value={mode}
|
||||
options={[{value:"inference",label:"Inference"},{value:"manual",label:"Ручное управление"}]}
|
||||
disabled={running || planning || manual || starting}
|
||||
onChange={(value)=>{setMode(value);setRunId(null);setSettingsOpen(false);}} /></div>
|
||||
<div className="ai-polygon__rover-row"><div className="ai-polygon__robot-select"><InspectorSelectField label="Ровер"
|
||||
value={running ? run.robot?.robot_id ?? "" : robot?.robot_id ?? ""}
|
||||
options={(catalog.robots ?? []).map((item) => ({ value: item.robot_id, label: item.name }))}
|
||||
disabled={planning || manual || starting || running} onChange={(id)=>{setRobotId(id);setPlanId(null);}} /></div>
|
||||
<IconButton label="Настройки ровера" disabled={!robot || !roverSettings || starting}
|
||||
onClick={()=>setRoverSettingsOpen(true)}><Icon name="settings"/></IconButton>
|
||||
</div>
|
||||
{roverSettings?<p>{roverSettings.max_speed_mps} м/с · {roverSettings.base_mass_kg+roverSettings.payload_mass_kg} кг с грузом</p>:null}</>:null}
|
||||
{mode==="inference"&&!running&&!starting?<AiTaskSelect inspector={!planning} plans={plans} value={plan?.plan_id??""}
|
||||
disabled={running||starting||saving||preparation.busy} onUpdated={planUpdated}
|
||||
onChange={(id)=>{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null}
|
||||
<div className="ai-polygon__actions">{mode === "manual" ? <Button variant="primary" icon={<Icon name={manual ? "stop" : "play"} />}
|
||||
disabled={!robot || !selected.settings.prepared}
|
||||
onClick={()=>{setSettingsOpen(false);setManual(!manual);}}>{manual ? "Завершить" : "Старт"}</Button> : planning ? <>
|
||||
<Button disabled={starting || saving || preparation.busy || (routeRequired && !preparation.route) || !draft || draft.points.length < 2}
|
||||
onClick={()=>openSave()}>Сохранить задание</Button>
|
||||
{!routeRequired || preparation.route ? <Button variant="primary" icon={<Icon name="play"/>} loading={starting}
|
||||
disabled={saving || !draft || selected.inference_ready===false || !catalog.runtime.available || !!catalog.runtime.active_run}
|
||||
onClick={launchDraft}>Запустить симуляцию</Button> : <Button variant="primary" icon={<Icon name="plan"/>}
|
||||
loading={preparation.busy} disabled={saving || starting || !draft || draft.points.length<2 || !catalog.runtime.available}
|
||||
onClick={()=>void preparation.prepare()}>Спланировать маршрут</Button>}
|
||||
{preparation.busy?<p role="status">Рассчитываем маршрут по сцене</p>:null}
|
||||
</> : !running ? <>
|
||||
<Button loading={starting} disabled={!robot || !selected.settings.prepared}
|
||||
onClick={() => start("planning")}>Подготовить маршрут</Button>
|
||||
<Button variant="primary" icon={<Icon name="play" />} loading={starting}
|
||||
disabled={!robot || !plan || (routeRequired && !plan.prepared_route) || selected.inference_ready === false || !catalog.runtime.available || !!catalog.runtime.active_run}
|
||||
onClick={() => start("evaluation")}>Запустить симуляцию</Button>
|
||||
</> : <AiRunActions run={run!} onChange={acceptRun} />}</div>
|
||||
</> : null;
|
||||
return <div className="ai-polygon">
|
||||
<header className="ai-polygon__head">
|
||||
@@ -84,34 +212,74 @@ export function AiPolygonWorkspace() {
|
||||
<h2>{selected?.name ?? "Доступные локации"}</h2>
|
||||
</div>
|
||||
<div className="ai-polygon__actions" ref={setActionsHost}>
|
||||
{selected ? !run ? sceneActions : null : <>{connection}
|
||||
<Button icon={<Icon name="upload" />} onClick={() => setImporting({ source: null })}>Импорт локации</Button></>}
|
||||
{selected ? null : <>{connection}
|
||||
<Button icon={<Icon name="upload" />} onClick={() => setImportChoice(true)}>Импорт локации</Button></>}
|
||||
</div>
|
||||
</header>
|
||||
<LoadingRegion className="ai-polygon__content" loading={!catalog && !error} label="Загрузка локаций">
|
||||
<LoadingRegion className={`ai-polygon__content${manual||planning?" ai-polygon__content--local":""}`} loading={!catalog && !error} label="Загрузка локаций">
|
||||
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Не удалось выполнить действие", description: error }]} onDismiss={() => setError(null)} /> : null}
|
||||
{removed.length?<GlassSurface padding="sm" className="ai-polygon__row">
|
||||
<span>Удалено из списка: {removed.at(-1)?.name}</span>
|
||||
<Button disabled={removing!==null} onClick={()=>void undoRemove()}>Отменить удаление</Button>
|
||||
</GlassSurface>:null}
|
||||
{catalog ? !selected ? <section aria-label="Доступные локации" className="ai-polygon__section">
|
||||
{catalog.worlds.map((world) => <GlassSurface key={world.world_id} padding="md" className="ai-polygon__row">
|
||||
<div><strong>{world.name}</strong><p>{world.author} · {world.license}</p></div>
|
||||
{catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
|
||||
{catalog.runtime.active_run.state === "running" && catalog.runtime.active_run.telemetry?.ai_ready
|
||||
? "AI запущен" : catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
|
||||
</StatusBadge> : null}
|
||||
<Button onClick={() => openWorld(world)}>{world.status === "uploading" ? "Продолжить импорт" : "Открыть"}</Button>
|
||||
</GlassSurface>)}
|
||||
<ResourceList>{catalog.worlds.map((world) => <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
|
||||
status={catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
|
||||
{catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
|
||||
</StatusBadge> : undefined}
|
||||
actions={<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
|
||||
onClick={() => openWorld(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>}/>
|
||||
</li>)}</ResourceList>
|
||||
</section> : <section className="ai-polygon__section" aria-label={`Симуляция ${selected.name}`}>
|
||||
<LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
|
||||
{run ? <AiWorldStream world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
|
||||
{!running && !planning && !manual ? <AiSessionSection key={`${selected.world_id}:configuration`}
|
||||
scope={`${selected.world_id}:configuration`} title="Конфигурация">
|
||||
<div className="ai-polygon__configuration-columns">
|
||||
<section className="ai-polygon__configuration-column" aria-label="Базовые настройки">
|
||||
<h3>Базовые настройки</h3>
|
||||
<div className="ai-polygon__configuration-fields">
|
||||
<InspectorSelectField label="Локация" value={selected.world_id}
|
||||
options={catalog.worlds.filter(w=>w.status!=="uploading").map(w=>({value:w.world_id,label:w.name}))}
|
||||
disabled={starting} onChange={id=>{const world=catalog.worlds.find(w=>w.world_id===id);if(world)openWorld(world);}} />
|
||||
{sceneActions}
|
||||
</div>
|
||||
{mode === "inference" && !running && !planning ? <div className="ai-polygon__facts">
|
||||
{plan ? <p>{plan.points.length} точек · {plan.length_m.toFixed(1)} м · задание сохранено</p>
|
||||
: <p>{previousPlan && !plans.length && planId===null ? "Сохранённый маршрут использует другую версию ровера. Откройте «Подготовить маршрут» и сохраните задание для выбранного ровера." : "Для запуска выберите задание или сохраните маршрут минимум из двух точек: старт и финиш."}</p>}
|
||||
</div> : null}
|
||||
</section>
|
||||
{mode==='inference'&&modules&&selection?<AiConfiguration key={selected.world_id} modules={modules}
|
||||
selection={selection} disabled={starting||!!catalog.runtime.active_run} onChange={setSelection}/>:null}
|
||||
</div>
|
||||
</AiSessionSection> : null}
|
||||
{mode === "inference" && !planning && !running && catalog.runtime.active_run ? <div className="ai-polygon__facts"><p>Выполняется симуляция «{catalog.runtime.active_run.world.name}».</p>
|
||||
{catalog.runtime.active_run.world.world_id===selected.world_id?<Button onClick={()=>acceptRun(catalog.runtime.active_run!)}>Открыть текущую симуляцию</Button>:null}</div> : null}
|
||||
{manual && robot ? <Suspense fallback={<LoadingRegion loading label="Открываем ручное управление" />}>
|
||||
<LocalManualScene key={selected.world_id} world={selected} robot={robot} settings={roverSettings} actionsHost={actionsHost} headerActions={sceneActions} />
|
||||
</Suspense> : planning ? <Suspense fallback={<LoadingRegion loading label="Открываем редактор" />}>
|
||||
<AiLocalPlanner key={selected.world_id} world={selected} initialPoints={editorPlan?.points ?? EMPTY_POINTS}
|
||||
busy={starting || saving || preparation.busy} preparedRoute={preparation.route} onDraft={setDraft} actionsHost={actionsHost} headerActions={sceneActions} />
|
||||
</Suspense> : <LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
|
||||
{mode === "inference" && running && run ? <AiWorldStream key={run.run_id} world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
|
||||
actionsHost={actionsHost} headerActions={sceneActions}
|
||||
controls={<AiRunView run={run} connection={connection} />} /> : <div className="ai-polygon__telemetry-row">{connection}</div>}
|
||||
</LoadingRegion>
|
||||
controls={<AiRunView run={run} />} /> : mode === "inference" ? <div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">{connection}{selected.inference_ready===false?<p>{selected.inference_message}</p>:null}</div> : null}
|
||||
</LoadingRegion>}
|
||||
{mode === "inference" && !planning ? <AiRunReport key={selected.world_id} worldId={selected.world_id} modules={modules} onRemove={removeRun} removing={removing} runs={catalog.runs.filter((item) => item.world.world_id === selected.world_id)} /> : null}
|
||||
{settingsOpen ? <AiWorldSetup key={selected.world_id} world={selected}
|
||||
disabled={!!catalog.runtime.active_run} onSaved={acceptWorld} /> : null}
|
||||
{settingsOpen && modules && selection ? <AiCompositionFields modules={modules}
|
||||
selection={activeRun?.world.world_id === selectedId ? activeRun.request?.composition ?? selection : selection}
|
||||
disabled={!!catalog.runtime.active_run} onChange={setSelection} /> : null}
|
||||
|
||||
</section> : null}
|
||||
</LoadingRegion>
|
||||
{roverSettingsOpen && robot && roverSettings && !running && !manual && !planning && !starting
|
||||
? <RoverSettingsWindow key={robot.sha256} robot={robot} value={roverSettings} manual={mode==="manual"}
|
||||
onClose={()=>setRoverSettingsOpen(false)} onApply={value=>{
|
||||
setRoverSettingsOpen(false);
|
||||
try {setRoverSettings(value);} catch {setError("Настройки применены, но не сохранены в браузере. После перезагрузки их нужно задать снова.");}
|
||||
}}/> : null}
|
||||
{saveOpen?<AiPlanSaveWindow error={saveError} name={planName} onName={setPlanName} busy={saving}
|
||||
launch={launchAfterSave} onClose={()=>setSaveOpen(false)} onSave={save}/>:null}
|
||||
<SimulationSourceImport open={importChoice} onClose={()=>setImportChoice(false)}
|
||||
onPly={()=>setImporting({source:null})} onReady={(id)=>{void load();setSelectedId(id);}} />
|
||||
{importing ? <AiWorldImport source={importing.source} resume={importing.resume}
|
||||
onClose={() => setImporting(null)} onImported={acceptWorld} /> : null}
|
||||
</div>;
|
||||
|
||||
@@ -1,428 +1,6 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type DragEvent,
|
||||
} from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
ConfirmationModal,
|
||||
GlassSurface,
|
||||
Icon,
|
||||
StatusBadge,
|
||||
Select,
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import { SimulationCatalog } from "../../components/simulation/SimulationCatalog";
|
||||
import { AiPolygonWorkspace } from "./AiPolygonWorkspace";
|
||||
import { SimulationProjectWindow } from "../../components/simulation/SimulationProjectWindow";
|
||||
import { SimulationViewport } from "../../components/simulation/SimulationViewport";
|
||||
import {
|
||||
createSimulationProject,
|
||||
deleteSimulationProject,
|
||||
fetchSimulationProjects,
|
||||
retrySimulationProject,
|
||||
uploadSimulationProjectSource,
|
||||
type SimulationProject,
|
||||
type SimulationProjectStatus,
|
||||
type SimulationUploadProgress,
|
||||
} from "../../core/simulation/projects";
|
||||
import {
|
||||
archiveProjectName,
|
||||
archivesFromDrop,
|
||||
hasDroppedFiles,
|
||||
} from "../../core/simulation/sourceFiles";
|
||||
|
||||
const BUILD_STATUSES = new Set<SimulationProjectStatus>(["queued", "processing", "importing"]);
|
||||
|
||||
interface BrowserUpload {
|
||||
project: SimulationProject;
|
||||
file: File;
|
||||
}
|
||||
|
||||
/** One location library; execution mode is selected inside the location. */
|
||||
export function SimulationWorkspace() {
|
||||
const [profile, setProfile] = useState<"lcc" | "ai">(() => {
|
||||
try { return localStorage.getItem("missioncore.simulation-profile") === "ai" ? "ai" : "lcc"; }
|
||||
catch { return "lcc"; }
|
||||
});
|
||||
return <div className="simulation-profiles" data-simulation-profile={profile}>
|
||||
<Select label="Профиль симуляции" value={profile} options={[
|
||||
{ value: "lcc", label: "LCC Gaussian Mirror" }, { value: "ai", label: "AI-полигон" },
|
||||
]} onChange={(value) => { setProfile(value);
|
||||
try { localStorage.setItem("missioncore.simulation-profile", value); } catch { /* Private browsing. */ }
|
||||
}} />
|
||||
{profile === "lcc" ? <LccGaussianWorkspace /> : <AiPolygonWorkspace />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function LccGaussianWorkspace() {
|
||||
const [projects, setProjects] = useState<SimulationProject[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [windowOpen, setWindowOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<SimulationProject | null>(null);
|
||||
const [deleting, setDeleting] = useState<SimulationProject | null>(null);
|
||||
const [retryingId, setRetryingId] = useState<string | null>(null);
|
||||
const [pendingUploads, setPendingUploads] = useState<BrowserUpload[]>([]);
|
||||
const [uploadProgress, setUploadProgress] = useState<Map<string, SimulationUploadProgress>>(
|
||||
() => new Map(),
|
||||
);
|
||||
const [queueError, setQueueError] = useState<string | null>(null);
|
||||
const [dropping, setDropping] = useState(false);
|
||||
const activeUploadRef = useRef<{ projectId: string; controller: AbortController } | null>(null);
|
||||
const intakeChainRef = useRef<Promise<void>>(Promise.resolve());
|
||||
const dragDepthRef = useRef(0);
|
||||
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
try {
|
||||
const next = await fetchSimulationProjects(signal);
|
||||
setProjects(next);
|
||||
setError(null);
|
||||
} catch (caught) {
|
||||
if (signal?.aborted) return;
|
||||
setError(caught instanceof Error ? caught.message : "Каталог симуляций недоступен.");
|
||||
} finally {
|
||||
if (!signal?.aborted) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void load(controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!projects.some((project) => BUILD_STATUSES.has(project.status))) return;
|
||||
const timer = window.setInterval(() => void load(), 2_000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [load, projects]);
|
||||
|
||||
useEffect(() => {
|
||||
const next = pendingUploads[0];
|
||||
if (!next || activeUploadRef.current) return;
|
||||
const controller = new AbortController();
|
||||
activeUploadRef.current = { projectId: next.project.projectId, controller };
|
||||
void uploadSimulationProjectSource(
|
||||
next.project,
|
||||
[{ file: next.file, logicalPath: next.file.name }],
|
||||
(progress) => {
|
||||
setUploadProgress((current) => {
|
||||
const updated = new Map(current);
|
||||
updated.set(next.project.projectId, progress);
|
||||
return updated;
|
||||
});
|
||||
setProjects((current) => current.map((project) => (
|
||||
project.projectId === next.project.projectId
|
||||
? {
|
||||
...project,
|
||||
source: { ...project.source, uploadedByteLength: progress.uploadedBytes },
|
||||
}
|
||||
: project
|
||||
)));
|
||||
},
|
||||
controller.signal,
|
||||
).then((queued) => {
|
||||
setProjects((current) => current.map((project) => (
|
||||
project.projectId === queued.projectId ? queued : project
|
||||
)));
|
||||
setQueueError(null);
|
||||
}).catch((caught) => {
|
||||
if (controller.signal.aborted) return;
|
||||
setQueueError(caught instanceof Error
|
||||
? `${next.file.name}: ${caught.message}`
|
||||
: `${next.file.name}: загрузка остановлена.`);
|
||||
}).finally(() => {
|
||||
setPendingUploads((current) => current.filter(
|
||||
(item) => item.project.projectId !== next.project.projectId,
|
||||
));
|
||||
setUploadProgress((current) => {
|
||||
const updated = new Map(current);
|
||||
updated.delete(next.project.projectId);
|
||||
return updated;
|
||||
});
|
||||
activeUploadRef.current = null;
|
||||
});
|
||||
}, [pendingUploads]);
|
||||
|
||||
useEffect(() => () => activeUploadRef.current?.controller.abort(), []);
|
||||
|
||||
const selected = useMemo(
|
||||
() => projects.find((project) => project.projectId === selectedId) ?? null,
|
||||
[projects, selectedId],
|
||||
);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setWindowOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (project: SimulationProject) => {
|
||||
setEditing(project);
|
||||
setWindowOpen(true);
|
||||
};
|
||||
|
||||
const acceptSaved = (project: SimulationProject) => {
|
||||
const wasEditing = editing !== null;
|
||||
setProjects((current) => [project, ...current.filter((item) => item.projectId !== project.projectId)]);
|
||||
if (!wasEditing) setSelectedId(project.projectId);
|
||||
setWindowOpen(false);
|
||||
setEditing(null);
|
||||
};
|
||||
|
||||
const acceptViewerProject = useCallback((project: SimulationProject) => {
|
||||
setProjects((current) => current.map((item) => (
|
||||
item.projectId === project.projectId ? project : item
|
||||
)));
|
||||
}, []);
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!deleting) return;
|
||||
const pending = pendingUploads.find((item) => item.project.projectId === deleting.projectId);
|
||||
if (activeUploadRef.current?.projectId === deleting.projectId) {
|
||||
activeUploadRef.current.controller.abort();
|
||||
}
|
||||
setPendingUploads((current) => current.filter(
|
||||
(item) => item.project.projectId !== deleting.projectId,
|
||||
));
|
||||
try {
|
||||
await deleteSimulationProject(deleting.projectId);
|
||||
setProjects((current) => current.filter((project) => project.projectId !== deleting.projectId));
|
||||
setUploadProgress((current) => {
|
||||
const updated = new Map(current);
|
||||
updated.delete(deleting.projectId);
|
||||
return updated;
|
||||
});
|
||||
if (selectedId === deleting.projectId) setSelectedId(null);
|
||||
setDeleting(null);
|
||||
} catch (caught) {
|
||||
if (pending) setPendingUploads((current) => [pending, ...current]);
|
||||
const message = caught instanceof Error ? caught.message : "Не удалось удалить проект.";
|
||||
setQueueError(message);
|
||||
throw caught;
|
||||
}
|
||||
};
|
||||
|
||||
const enqueueDroppedArchives = useCallback((files: File[]) => {
|
||||
intakeChainRef.current = intakeChainRef.current.then(async () => {
|
||||
for (const file of files) {
|
||||
try {
|
||||
const project = await createSimulationProject(
|
||||
archiveProjectName(file.name),
|
||||
"outdoor",
|
||||
[{ file, logicalPath: file.name }],
|
||||
);
|
||||
setProjects((current) => [
|
||||
project,
|
||||
...current.filter((item) => item.projectId !== project.projectId),
|
||||
]);
|
||||
setPendingUploads((current) => [...current, { project, file }]);
|
||||
} catch (caught) {
|
||||
setQueueError(caught instanceof Error
|
||||
? `${file.name}: ${caught.message}`
|
||||
: `${file.name}: не удалось создать проект.`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleDrop = async (transfer: DataTransfer) => {
|
||||
dragDepthRef.current = 0;
|
||||
setDropping(false);
|
||||
setQueueError(null);
|
||||
try {
|
||||
enqueueDroppedArchives(await archivesFromDrop(transfer));
|
||||
} catch (caught) {
|
||||
setQueueError(caught instanceof Error ? caught.message : "Архивы не приняты.");
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
dragDepthRef.current += 1;
|
||||
setDropping(true);
|
||||
};
|
||||
|
||||
const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
|
||||
if (dragDepthRef.current === 0) setDropping(false);
|
||||
};
|
||||
|
||||
const retry = async (project: SimulationProject) => {
|
||||
setRetryingId(project.projectId);
|
||||
setError(null);
|
||||
try {
|
||||
const queued = await retrySimulationProject(project.projectId);
|
||||
setProjects((current) => current.map((item) => (
|
||||
item.projectId === queued.projectId ? queued : item
|
||||
)));
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "Не удалось повторить сборку.");
|
||||
} finally {
|
||||
setRetryingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (selected) {
|
||||
return (
|
||||
<div className="simulation-workspace simulation-workspace--scene">
|
||||
<header className="simulation-workspace__scene-head">
|
||||
<Button
|
||||
size="compact"
|
||||
variant="ghost"
|
||||
icon={<Icon name="chevron-left" size={16} />}
|
||||
onClick={() => setSelectedId(null)}
|
||||
>
|
||||
Все проекты
|
||||
</Button>
|
||||
<div>
|
||||
<span className="section-eyebrow">LAB / SIMULATION RUNTIME</span>
|
||||
<h2>{selected.name}</h2>
|
||||
</div>
|
||||
<StatusBadge tone={statusPresentation(selected.status).tone}>
|
||||
{statusPresentation(selected.status).label}
|
||||
</StatusBadge>
|
||||
</header>
|
||||
{selected.status === "ready" && selected.worldManifest ? (
|
||||
<SimulationViewport
|
||||
project={selected}
|
||||
onProjectChange={acceptViewerProject}
|
||||
/>
|
||||
) : (
|
||||
<GlassSurface className="simulation-workspace__processing" padding="lg">
|
||||
{selected.status === "failed" ? <Icon name="alert" size={20} /> : <ActivityIndicator label="Сборка мира" />}
|
||||
<div className="simulation-workspace__processing-copy">
|
||||
<strong>{selected.status === "failed" ? "Сборка остановлена" : "Worker 006 собирает мир"}</strong>
|
||||
<p>{error ?? selected.error ?? processingMessage(selected)}</p>
|
||||
</div>
|
||||
<div className="simulation-workspace__processing-actions">
|
||||
<StatusBadge tone={selected.status === "failed" ? "warning" : "accent"}>
|
||||
{providerStateLabel(selected.provider.state, selected.status)}
|
||||
</StatusBadge>
|
||||
{selected.status === "failed" ? (
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={retryingId === selected.projectId}
|
||||
icon={retryingId === selected.projectId
|
||||
? <ActivityIndicator size="compact" />
|
||||
: <Icon name="refresh" size={14} />}
|
||||
onClick={() => void retry(selected)}
|
||||
>
|
||||
Повторить сборку
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</GlassSurface>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="simulation-workspace"
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={(event) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
}}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={(event) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
void handleDrop(event.dataTransfer);
|
||||
}}
|
||||
>
|
||||
<header className="simulation-workspace__head">
|
||||
<div>
|
||||
<span className="section-eyebrow">ТЕСТОВЫЙ КОНТУР / СИМУЛЯЦИИ</span>
|
||||
<h2>Gaussian-миры</h2>
|
||||
<p>Каталог исходников, сборок Worker 006 и полнофункциональных интерактивных сцен.</p>
|
||||
</div>
|
||||
<Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={openCreate}>
|
||||
Новый проект
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<SimulationCatalog
|
||||
projects={projects}
|
||||
uploadProgress={uploadProgress}
|
||||
loading={loading}
|
||||
loadError={error}
|
||||
queueError={queueError}
|
||||
dropping={dropping}
|
||||
onCreate={openCreate}
|
||||
onRetryLoad={() => void load()}
|
||||
onSelect={(project) => setSelectedId(project.projectId)}
|
||||
onEdit={openEdit}
|
||||
onDelete={setDeleting}
|
||||
/>
|
||||
|
||||
<SimulationProjectWindow
|
||||
open={windowOpen}
|
||||
project={editing}
|
||||
onClose={() => { if (!windowOpen) return; setWindowOpen(false); setEditing(null); }}
|
||||
onSaved={acceptSaved}
|
||||
/>
|
||||
<ConfirmationModal
|
||||
open={deleting !== null}
|
||||
title="Удалить проект симуляции?"
|
||||
description={(
|
||||
<p>
|
||||
Проект <strong>{deleting?.name}</strong>, локальные производные артефакты и job на Worker 006 будут удалены.
|
||||
</p>
|
||||
)}
|
||||
confirmLabel="Удалить проект"
|
||||
pendingLabel="Удаляем…"
|
||||
danger
|
||||
onClose={() => setDeleting(null)}
|
||||
onConfirm={confirmDelete}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function statusPresentation(status: SimulationProjectStatus): {
|
||||
label: string;
|
||||
tone: "success" | "accent" | "warning" | "neutral";
|
||||
} {
|
||||
if (status === "ready") return { label: "Визуал готов", tone: "success" };
|
||||
if (status === "failed") return { label: "Ошибка", tone: "warning" };
|
||||
if (status === "uploading") return { label: "Загрузка", tone: "neutral" };
|
||||
if (status === "importing") return { label: "Импорт", tone: "accent" };
|
||||
return { label: "Сборка", tone: "accent" };
|
||||
}
|
||||
|
||||
function processingMessage(project: SimulationProject): string {
|
||||
const progress = project.provider.progress;
|
||||
const completed = progress?.completed_steps;
|
||||
const total = progress?.total_steps;
|
||||
if (typeof completed === "number" && typeof total === "number") {
|
||||
return `Этап ${completed.toLocaleString("ru-RU")} из ${total.toLocaleString("ru-RU")}. Каталог обновляется автоматически.`;
|
||||
}
|
||||
return "Исходник подтверждён; локация и её LOD-уровни собираются в переносимом контейнере.";
|
||||
}
|
||||
|
||||
function providerStateLabel(
|
||||
state: string | null,
|
||||
projectStatus: SimulationProjectStatus,
|
||||
): string {
|
||||
if (state === "queued") return "Ожидание";
|
||||
if (state === "verifying_source") return "Проверка исходника";
|
||||
if (state === "inspecting") return "Анализ локации";
|
||||
if (state === "building_preview") return "Подготовка локации";
|
||||
if (state === "building_streamed_sog") return "Сборка LOD";
|
||||
if (state === "building_collision") return "Сборка коллизий";
|
||||
if (state === "ready") return "Визуал готов";
|
||||
if (state === "failed") return "Ошибка";
|
||||
return statusPresentation(projectStatus).label;
|
||||
return <AiPolygonWorkspace />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import ts from 'typescript';
|
||||
import { Mat4, Vec3 } from 'playcanvas';
|
||||
const source=readFileSync(new URL('../src/core/simulation/aiEditorCoordinates.ts',import.meta.url),'utf8');
|
||||
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {toEditor,toMission}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
test('editor glTF surface and Isaac mission coordinates roundtrip without reflection',()=>{
|
||||
const p=[-134.744,38.807,1.527];
|
||||
assert.deepEqual(toMission(toEditor(p)),p);
|
||||
assert.deepEqual(toEditor([0,0,1]),[0,1,-0]);
|
||||
const a=new Vec3(...toEditor([1,0,0])), b=new Vec3(...toEditor([0,1,0]));
|
||||
assert.ok(new Vec3().cross(a,b).equals(new Vec3(...toEditor([0,0,1]))));
|
||||
});
|
||||
test('Riverside raw Gaussian rotation agrees with paired glTF collider',()=>{
|
||||
const raw=new Vec3(-134.744,1.527,-38.807);
|
||||
const native=new Mat4().setFromEulerAngles(90,0,0).transformPoint(raw);
|
||||
const editor=new Mat4().setFromEulerAngles(-90,0,0).transformPoint(native);
|
||||
assert.ok(editor.distance(raw)<1e-5);
|
||||
const expected=toMission([raw.x,raw.y,raw.z]);
|
||||
assert.ok(Math.hypot(native.x-expected[0],native.y-expected[1],native.z-expected[2])<1e-5);
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
import {PerspectiveCamera,Vector3} from 'three';
|
||||
async function source(name){
|
||||
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText.replace('from "three"',`from "${import.meta.resolve('three')}"`);
|
||||
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
}
|
||||
const {panCamera,orbitCamera,navigationDepth}=await source('editorNavigation');
|
||||
const {editWaypoints,waypointEditing,waypointShortcut}=await source('waypointEditing');
|
||||
const {streamRecovery}=await source('streamRecovery');
|
||||
const {panSensitivity,normalizePlannerPreferences}=await source('plannerPreferences');
|
||||
test('pan follows the same pixel displacement at 2, 20 and 500 metre distances',()=>{
|
||||
for(const distance of [2,20,500]){
|
||||
const camera=new PerspectiveCamera(60,1.5,.05,3000);camera.position.set(0,0,distance);camera.updateMatrixWorld();
|
||||
const anchor=new Vector3();const depth=navigationDepth(camera,anchor);
|
||||
panCamera(camera,depth,120,-80,720);
|
||||
const pixel=anchor.project(camera);
|
||||
assert.ok(Math.abs(pixel.x*1080/2-120)<1e-8);
|
||||
assert.ok(Math.abs(-pixel.y*720/2+80)<1e-8);
|
||||
}
|
||||
});
|
||||
test('off-centre orbit pivot stays under cursor without jump, roll or radius drift',()=>{
|
||||
const camera=new PerspectiveCamera(60,1.5,.05,3000);camera.position.set(0,5,10);camera.lookAt(0,0,0);camera.updateMatrixWorld();
|
||||
const anchor=new Vector3(2,0,1),screen=anchor.clone().project(camera),radius=camera.position.distanceTo(anchor);
|
||||
for(let i=0;i<20;i++){
|
||||
orbitCamera(camera,anchor,8,3,720);
|
||||
assert.ok(anchor.clone().project(camera).distanceTo(screen)<1e-10);
|
||||
assert.ok(Math.abs(camera.position.distanceTo(anchor)-radius)<1e-10);
|
||||
assert.ok(Math.abs(new Vector3(1,0,0).applyQuaternion(camera.quaternion).y)<1e-10);
|
||||
}
|
||||
});
|
||||
const points=[{id:'a',position:[0,0,0]},{id:'b',position:[2,0,0]}];
|
||||
test('selection never alters route; delete/undo restores order, coordinates and selection',()=>{
|
||||
let s=waypointEditing(points);s=editWaypoints(s,{type:'select',id:'a'});s=editWaypoints(s,{type:'select',id:null});
|
||||
assert.equal(s.history.length,0);assert.equal(s.sequence,0);
|
||||
s=editWaypoints(s,{type:'select',id:'a'});s=editWaypoints(s,{type:'delete'});
|
||||
assert.deepEqual(s.points,[points[1]]);assert.equal(s.selected,null);
|
||||
s=editWaypoints(s,{type:'undo'});assert.deepEqual(s.points,points);assert.equal(s.selected,'a');assert.equal(s.sequence,2);
|
||||
});
|
||||
test('drag creates one undo entry, click none, canceled drag restores coordinates',()=>{
|
||||
let s=editWaypoints(waypointEditing(points),{type:'select',id:'b'});
|
||||
s=editWaypoints(s,{type:'begin'});s=editWaypoints(s,{type:'commit'});assert.equal(s.history.length,0);
|
||||
s=editWaypoints(s,{type:'begin'});
|
||||
for(let i=0;i<20;i++)s=editWaypoints(s,{type:'move',points:[points[0],{id:'b',position:[3+i,0,0]}]});
|
||||
s=editWaypoints(s,{type:'commit'});assert.equal(s.history.length,1);
|
||||
s=editWaypoints(s,{type:'undo'});assert.deepEqual(s.points,points);
|
||||
s=editWaypoints(s,{type:'begin'});s=editWaypoints(s,{type:'move',points:[]});s=editWaypoints(s,{type:'cancel'});assert.deepEqual(s.points,points);
|
||||
});
|
||||
test('new task isolates history and shortcuts preserve native text editing',()=>{
|
||||
let s=waypointEditing(points);s=editWaypoints(s,{type:'replace',points:[]});s=editWaypoints(s,{type:'load',points});
|
||||
assert.equal(s.history.length,0);
|
||||
const e={key:'z',code:'KeyZ',ctrlKey:false,metaKey:false,shiftKey:false,altKey:false};
|
||||
assert.equal(waypointShortcut({...e,ctrlKey:true},false),'undo');assert.equal(waypointShortcut({...e,metaKey:true},false),'undo');
|
||||
assert.equal(waypointShortcut({...e,metaKey:true},true),null);
|
||||
assert.equal(waypointShortcut({...e,key:'Delete',code:'Delete'},false),'delete');
|
||||
assert.equal(waypointShortcut({...e,key:'Backspace',code:'Backspace'},false),'delete');
|
||||
assert.equal(waypointShortcut({...e,key:'Delete',code:'Delete',ctrlKey:true},false),null);
|
||||
});
|
||||
test('navigation preferences migrate, maintain ordered distances and interpolate smoothly',()=>{
|
||||
const p=normalizePlannerPreferences({waypoint:{height:50},navigation:{nearDistance:3,farDistance:100,nearPan:.5,farPan:2}});
|
||||
assert.equal(p.waypoint.height,50);assert.equal(p.navigation.zoom,1);
|
||||
assert.equal(panSensitivity(1,p.navigation),.5);assert.equal(panSensitivity(200,p.navigation),2);
|
||||
assert.equal(panSensitivity(51.5,p.navigation),1.25);
|
||||
const bad=normalizePlannerPreferences({navigation:{nearDistance:50,farDistance:2,zoom:NaN}});
|
||||
assert.equal(bad.navigation.farDistance,51);assert.equal(bad.navigation.zoom,1);
|
||||
assert.deepEqual(normalizePlannerPreferences(JSON.parse(JSON.stringify(p))),p);
|
||||
});
|
||||
test('video watchdog bounds first-frame wait, stall recovery and retry count',()=>{
|
||||
assert.equal(streamRecovery(19999,0,null,null,0),'wait');assert.equal(streamRecovery(20000,0,null,null,0),'retry');
|
||||
assert.equal(streamRecovery(20000,0,null,null,2),'failed');assert.equal(streamRecovery(20000,0,15000,null,0),'wait');
|
||||
assert.equal(streamRecovery(25000,0,15000,null,1),'retry');assert.equal(streamRecovery(5000,0,null,3000,2),'failed');
|
||||
});
|
||||
|
||||
const {viewedAiRun}=await source('viewedAiRun');
|
||||
test('catalog discovery of a run cannot claim an idle or historical viewer',()=>{
|
||||
const old={run_id:'old',world:{world_id:'forest'}},live={run_id:'new',world:{world_id:'forest'}};
|
||||
const catalog={runtime:{active_run:live},runs:[old,live]};
|
||||
assert.equal(viewedAiRun(catalog,'forest',null),undefined);
|
||||
assert.equal(viewedAiRun(catalog,'forest','old'),old);
|
||||
assert.equal(viewedAiRun(catalog,'forest','new'),live);
|
||||
assert.equal(viewedAiRun(catalog,'bamboo','new'),undefined);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import ts from 'typescript';
|
||||
const code=ts.transpileModule(readFileSync(new URL('../src/core/simulation/planDraft.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {planMatchesDraft}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
const points=[{id:'start',position:[0,0,0]},{id:'finish',position:[3,1,0]}];
|
||||
const plan={editor_cache_key:'scene-v1',robot_sha256:'rover-v1',points};
|
||||
test('editor launch reuses only the exact ordered saved route, including elevation',()=>{
|
||||
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',structuredClone(points)),true);
|
||||
const moved=structuredClone(points);moved[1].position[2]=.2;
|
||||
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',moved),false);
|
||||
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',[...points].reverse()),false);
|
||||
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v1',points.slice(1)),false);
|
||||
});
|
||||
test('changed scene or rover requires a fresh task even when coordinates match',()=>{
|
||||
assert.equal(planMatchesDraft(plan,'scene-v2','rover-v1',points),false);
|
||||
assert.equal(planMatchesDraft(plan,'scene-v1','rover-v2',points),false);
|
||||
assert.equal(planMatchesDraft(undefined,'scene-v1','rover-v1',points),false);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import ts from 'typescript';
|
||||
async function source(name) {
|
||||
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
}
|
||||
const {normalizePlannerPreferences,DEFAULT_PLANNER_PREFERENCES,axisWorldLength}=await source('plannerPreferences');
|
||||
const {zoomDisplacement}=await source('editorZoom');
|
||||
test('preferences survive round trip, validate old/corrupt storage and clamp physical dimensions',()=>{
|
||||
const value={...DEFAULT_PLANNER_PREFERENCES,waypoint:{...DEFAULT_PLANNER_PREFERENCES.waypoint,diameter:.8,height:3,color:'#00aaff',opacity:.5,frequency:0}};
|
||||
assert.deepEqual(normalizePlannerPreferences(JSON.parse(JSON.stringify(value))),value);
|
||||
assert.deepEqual(normalizePlannerPreferences(null),DEFAULT_PLANNER_PREFERENCES);
|
||||
const invalid=normalizePlannerPreferences({pivot:{x:'url(x)',opacity:99},waypoint:{height:-9,diameter:NaN}});
|
||||
assert.equal(invalid.pivot.x,DEFAULT_PLANNER_PREFERENCES.pivot.x);
|
||||
assert.equal(invalid.pivot.opacity,1);assert.equal(invalid.waypoint.height,.2);assert.equal(invalid.waypoint.diameter,.35);
|
||||
});
|
||||
test('perspective projection preserves gizmo pixels at different depths and viewport heights',()=>{
|
||||
for(const depth of [1,10,500])for(const height of [500,900,1600]) {
|
||||
const projected=axisWorldLength(depth,height,105)/(2*depth*Math.tan(Math.PI/6))*height;
|
||||
assert.ok(Math.abs(projected-105)<1e-8);
|
||||
}
|
||||
});
|
||||
test('far zoom takes proportional steps and equal reverse wheel deltas return to original distance',()=>{
|
||||
for(const depth of [2,20,200,2000]) {
|
||||
const next=depth-zoomDisplacement(depth,80);
|
||||
assert.ok(next>depth);
|
||||
const restored=next-zoomDisplacement(next,-80);
|
||||
assert.ok(Math.abs(restored-depth)<1e-8);
|
||||
assert.ok(zoomDisplacement(depth,-80)>depth*.1);
|
||||
}
|
||||
});
|
||||
const {waypointHit}=await source('waypointHit');
|
||||
test('waypoint picks complete sides, caps and a camera inside the beam at any physical size',()=>{
|
||||
for(const radius of [.025,.5,1.5])for(const height of [.2,5,50]) {
|
||||
assert.notEqual(waypointHit([radius*.9,height*.9,5],[0,0,-1],[0,0,0],radius,height),null);
|
||||
assert.notEqual(waypointHit([radius*.9,height+1,0],[0,-1,0],[0,0,0],radius,height),null);
|
||||
assert.notEqual(waypointHit([0,height/2,0],[0,0,1],[0,0,0],radius,height),null);
|
||||
assert.equal(waypointHit([radius*1.1,height/2,5],[0,0,-1],[0,0,0],radius,height),null);
|
||||
}
|
||||
});
|
||||
test('world-size centroid preference migrates to independent pixel size; emission is bounded',()=>{
|
||||
const prefs=normalizePlannerPreferences({navigation:{centroidDiameter:5},waypoint:{emission:20,emissionColor:'invalid'}});
|
||||
assert.equal(prefs.navigation.centroidPixels,14);
|
||||
assert.equal(prefs.waypoint.emission,5);
|
||||
for(const depth of [1,30,300]) {
|
||||
const pixels=axisWorldLength(depth,720,prefs.navigation.centroidPixels)/(2*depth*Math.tan(Math.PI/6))*720;
|
||||
assert.ok(Math.abs(pixels-14)<1e-8);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {readFileSync} from "node:fs";
|
||||
import {test} from "node:test";
|
||||
import ts from "typescript";
|
||||
const code=ts.transpileModule(readFileSync(new URL("../src/core/simulation/roverSettings.ts",import.meta.url),"utf8"),
|
||||
{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {defaultRoverSettings,validRoverSettings,parseRoverSettings,roverSettingsKey}=
|
||||
await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
|
||||
const robot={robot_id:"dcd006",sha256:"a".repeat(64),physics:{mass_kg:100,height_m:.734},control:{max_side_speed_mps:.3}};
|
||||
test("speed and payload persist per robot revision, with finite physical bounds",()=>{
|
||||
const initial=defaultRoverSettings(robot,.15);
|
||||
const loaded={...initial,max_speed_mps:.2,payload_mass_kg:30,payload_height_m:.9};
|
||||
assert.equal(initial.base_mass_kg,100);
|
||||
assert.equal(initial.payload_height_m,.83);
|
||||
assert.equal(validRoverSettings(loaded,robot),true);
|
||||
assert.deepEqual(parseRoverSettings(JSON.stringify(loaded),robot),loaded);
|
||||
assert.notEqual(roverSettingsKey(robot),roverSettingsKey({...robot,sha256:"b".repeat(64)}));
|
||||
assert.equal(validRoverSettings({...loaded,max_speed_mps:.4},robot),true);
|
||||
for(const patch of [{max_speed_mps:.01},{max_speed_mps:Infinity},{max_speed_mps:NaN},{base_mass_kg:0},{payload_mass_kg:-1},
|
||||
{payload_height_m:Infinity},{max_speed_mps:"0.2"}]) {
|
||||
assert.equal(validRoverSettings({...loaded,...patch},robot),false);
|
||||
assert.equal(parseRoverSettings(JSON.stringify({...loaded,...patch}),robot),undefined);
|
||||
}
|
||||
assert.equal(parseRoverSettings(JSON.stringify({...loaded,unknown:1}),robot),undefined);
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import ts from 'typescript';
|
||||
async function source(name) {
|
||||
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
}
|
||||
const {dragWaypoint}=await source('waypointDrag'),{beltPose}=await source('roverMotion');
|
||||
const motion=JSON.parse(readFileSync(new URL('../public/rover-scene/dcd006-v020-motion.json',import.meta.url)));
|
||||
const near=(a,b)=>assert.ok(Math.abs(a-b)<1e-7,`${a} != ${b}`);
|
||||
test('axis pivot only moves the selected coordinate, including elevation',()=>{
|
||||
const p=[3,4,5],o=[8,12,16];
|
||||
for(const [axis,index] of [['x',0],['y',1],['z',2]]) {
|
||||
const target=[...p];target[index]+=2;
|
||||
const result=dragWaypoint(o,target.map((v,i)=>v-o[i]),p,axis);
|
||||
result.forEach((v,i)=>near(v,target[i]));
|
||||
dragWaypoint(o,p.map((v,i)=>v-o[i]),p,axis).forEach((v,i)=>near(v,p[i]));
|
||||
}
|
||||
assert.equal(dragWaypoint([0,0,0],[1,0,0],p,'x'),null);
|
||||
});
|
||||
test('belt loops without a seam and reverse travel returns to the same position',()=>{
|
||||
for(const side of ['L','R'])for(let i=0;i<44;i++) {
|
||||
const a=beltPose(motion,-.8,side,i), b=beltPose(motion,motion.length_m-.8,side,i);
|
||||
a.position.forEach((v,j)=>near(v,b.position[j]));near(Math.sin(a.angle),Math.sin(b.angle));
|
||||
}
|
||||
});
|
||||
test('belt travels backward at ground contact, forward on the upper run, both sides aligned',()=>{
|
||||
for(const [,start,length,d] of motion.segments.filter(s=>s[0]==='line')) {
|
||||
const s=start+length/2-motion.phase_m;
|
||||
const a=beltPose(motion,s,'L',0), b=beltPose(motion,s+.0001,'L',0);
|
||||
near((b.position[0]-a.position[0])/.0001,d[2]);
|
||||
near((b.position[1]-a.position[1])/.0001,d[3]);
|
||||
const right=beltPose(motion,s,'R',0);near(a.position[0],right.position[0]);near(a.position[1],right.position[1]);
|
||||
near(right.position[2]-a.position[2],motion.track_width_m);
|
||||
}
|
||||
});
|
||||
|
||||
test('local animated rig follows motion and freezes at zero input', async()=>{
|
||||
const {Entity}=await import('playcanvas');
|
||||
const mathCode=ts.transpileModule(readFileSync(new URL('../src/core/simulation/roverMotion.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const mathUrl=`data:text/javascript;base64,${Buffer.from(mathCode).toString('base64')}`;
|
||||
let code=ts.transpileModule(readFileSync(new URL('../src/components/simulation/RoverTrackMotion.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
code=code.replace('"../../core/simulation/roverMotion"',JSON.stringify(mathUrl));
|
||||
const {RoverTrackMotion}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
const root=new Entity();
|
||||
for(const side of ['L','R'])for(let i=0;i<44;i++)root.addChild(new Entity(`${side}_BELT_${String(i).padStart(2,'0')}`));
|
||||
for(const w of motion.wheels)root.addChild(new Entity(w.node));
|
||||
const rig=new RoverTrackMotion(root,motion);rig.update(.1,.3,0);
|
||||
const expected=beltPose(motion,.03,'L',0), node=root.findByName('L_BELT_00');
|
||||
const p=node.getLocalPosition();[p.x,p.y,p.z].forEach((v,i)=>near(v,expected.position[i]));
|
||||
const before=node.getLocalRotation().clone();rig.update(.1,0,0);assert.ok(node.getLocalRotation().equals(before));
|
||||
rig.update(.1,-.3,0);const atOrigin=beltPose(motion,0,'L',0), reset=node.getLocalPosition();
|
||||
[reset.x,reset.y,reset.z].forEach((v,i)=>near(v,atOrigin.position[i]));
|
||||
root.destroy();
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import ts from 'typescript';
|
||||
|
||||
const source=ts.transpileModule(readFileSync(new URL('../src/core/simulation/runConfiguration.ts',import.meta.url),'utf8'),
|
||||
{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {parseSavedSelection,currentSelection,selectionStorageKey}=
|
||||
await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
|
||||
const selection={schema_version:'missioncore.observatory-ai-composition/v1',selections:[
|
||||
{group:'segmentation',module_id:'outdoor-provider',module_sha256:'a'.repeat(64),parameters:{}},
|
||||
{group:'policy',module_id:'mission',module_sha256:'b'.repeat(64),parameters:{environment:'park'}},
|
||||
]};
|
||||
const installed={selection:{...selection,selections:[]},catalog:{groups:[
|
||||
{group:'segmentation',modules:[{moduleId:'outdoor-provider',moduleSha256:'c'.repeat(64),defaults:{}}]},
|
||||
{group:'policy',modules:[{moduleId:'mission',moduleSha256:'d'.repeat(64),defaults:{environment:'natural'}}]},
|
||||
]}};
|
||||
|
||||
test('stored per-location intent survives JSON; malformed, duplicate or foreign groups are rejected',()=>{
|
||||
assert.deepEqual(parseSavedSelection(JSON.stringify(selection)),selection);
|
||||
for(const value of [null,'broken',JSON.stringify({...selection,selections:[...selection.selections,selection.selections[0]]}),
|
||||
JSON.stringify({...selection,selections:[{...selection.selections[0],group:'source'}]}),
|
||||
JSON.stringify({...selection,selections:[{...selection.selections[0],parameters:[]} ]})]) {
|
||||
assert.equal(parseSavedSelection(value),undefined);
|
||||
}
|
||||
assert.notEqual(selectionStorageKey('riverside','tracked'),selectionStorageKey('forest','tracked'));
|
||||
assert.notEqual(selectionStorageKey('riverside','tracked'),selectionStorageKey('riverside','wheeled'));
|
||||
});
|
||||
test('alternative provider is rebound from full registry and park permissions survive an update',()=>{
|
||||
const fresh=currentSelection(selection,installed);
|
||||
assert.equal(fresh.selections[0].module_sha256,'c'.repeat(64));
|
||||
assert.equal(fresh.selections[1].parameters.environment,'park');
|
||||
assert.equal(selection.selections[0].module_sha256,'a'.repeat(64));
|
||||
assert.throws(()=>currentSelection(selection,{...installed,catalog:{groups:[]}}),/недоступен/);
|
||||
});
|
||||
test('continuous simulation admission does not send a distance-based duration ceiling',()=>{
|
||||
const api=readFileSync(new URL('../src/core/simulation/aiPolygon.ts',import.meta.url),'utf8');
|
||||
const start=api.slice(api.indexOf('export const startAiRun'),api.indexOf('export const sendAiPlanningCommand'));
|
||||
assert.doesNotMatch(start,/duration_seconds|runDurationSeconds/);
|
||||
assert.match(start,/clock: "realtime"/);
|
||||
});
|
||||
@@ -20,18 +20,20 @@ test("simulation is a dedicated Polygon workspace with a bounded feature slice",
|
||||
assert.match(productModel, /id: "simulations"[\s\S]*root: "polygon"[\s\S]*kind: "simulations"/);
|
||||
assert.match(workspaceHub, /case "simulations":[\s\S]*<SimulationWorkspace \/>/);
|
||||
assert.match(catalog, /simulation-catalog__table/);
|
||||
assert.match(workspace, /archivesFromDrop/);
|
||||
assert.match(workspace, /uploadSimulationProjectSource/);
|
||||
|
||||
|
||||
assert.match(catalog, /colSpan=\{3\}/);
|
||||
assert.match(catalog, /Ожидает обработки/);
|
||||
assert.match(catalog, /Прогресс \$\{roundedPercent\}% \|/);
|
||||
assert.match(catalog, /Осталось примерно \$\{minutes\} мин/);
|
||||
assert.match(catalog, /simulation-catalog__progress-track/);
|
||||
assert.doesNotMatch(catalog, /disabled=\{ACTIVE_STATUSES\.has/);
|
||||
assert.match(workspace, /<SimulationViewport[\s\S]*project=\{selected\}/);
|
||||
assert.match(workspace, /<ConfirmationModal/);
|
||||
assert.match(workspace, /if \(state === "building_streamed_sog"\) return "Сборка LOD"/);
|
||||
assert.doesNotMatch(workspace, /\{selected\.provider\.state \?\? selected\.status\}/);
|
||||
|
||||
|
||||
|
||||
|
||||
assert.match(workspace, /<AiPolygonWorkspace \/>/);
|
||||
assert.doesNotMatch(workspace, /simulation-profile|LccGaussianWorkspace/);
|
||||
assert.match(styles, /styles\/simulation\.css/);
|
||||
});
|
||||
|
||||
@@ -69,12 +71,12 @@ test("browser upload remains same-origin, resumable and token-free", async () =>
|
||||
test("failed simulation can restart from its retained Mission Core source", async () => {
|
||||
const [core, workspace] = await Promise.all([
|
||||
read("core/simulation/projects.ts"),
|
||||
read("workspaces/simulation/SimulationWorkspace.tsx"),
|
||||
read("components/simulation/SimulationSourceImport.tsx"),
|
||||
]);
|
||||
|
||||
assert.match(core, /retrySimulationProject/);
|
||||
assert.match(core, /\$\{API_ROOT\}\/\$\{encodeURIComponent\(projectId\)\}\/build/);
|
||||
assert.match(workspace, /Повторить сборку/);
|
||||
assert.match(workspace, /Повторить подготовку/);
|
||||
});
|
||||
|
||||
test("PlayCanvas owns the realtime scene graph without an iframe or React entity tree", async () => {
|
||||
@@ -97,7 +99,7 @@ test("PlayCanvas owns the realtime scene graph without an iframe or React entity
|
||||
assert.match(runtime, /camera\.script\?\.create\(CameraControls/);
|
||||
assert.match(runtime, /const HOME_POSITION = new Vec3\(0, 1, 0\)/);
|
||||
assert.match(runtime, /const HOME_FOCUS = new Vec3\(1, 1, 0\)/);
|
||||
assert.match(runtime, /maximum: \{[^}]*lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60/);
|
||||
assert.match(await read("core/simulation/gaussianQuality.ts"), /maximum: \{[^}]*lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 0, targetFps: 60/);
|
||||
assert.match(runtime, /app\.scene\.gsplat\.splatBudget = profile\.splatBudget/);
|
||||
assert.match(runtime, /app\.autoRender = false/);
|
||||
assert.match(runtime, /app\.systems\.gsplat\?\.on\("frame:request", this\.requestGsplatFrame\)/);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
const code=ts.transpileModule(readFileSync(new URL('../src/core/simulation/streamDiagnostics.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {StreamDiagnostics}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
test('network round trip, decode and estimated presentation delay retain separate units',()=>{
|
||||
const d=new StreamDiagnostics();d.observeNative(100,{fps:8,rtd:42,avgDecodeTime:3,currentBitrate:9,codec:'H264'});
|
||||
d.observeFrame(105,{expectedDisplayTime:106,captureTime:40,receiveTime:96,processingDuration:.003});
|
||||
const s=d.snapshot(110,7.8);assert.equal(s.native.round_trip_ms,42);assert.equal(s.native.decode_ms,3);
|
||||
assert.equal(s.presentation.estimated_capture_to_present_ms,66);assert.equal(s.presentation.receive_to_present_ms,10);
|
||||
assert.equal(s.presentation.frame_decode_ms,3);assert.equal(s.decoded_fps,7.8);
|
||||
});
|
||||
test('missing remote clock estimates and invalid SDK fields remain unknown, not zero latency',()=>{
|
||||
const d=new StreamDiagnostics();d.observeNative(0,{rtd:NaN,avgDecodeTime:-1,fps:0,codec:'secret://endpoint',extra:'ignored'});
|
||||
d.observeFrame(1,{expectedDisplayTime:2});const s=d.snapshot(2,0);
|
||||
assert.equal(s.native.fps,0);assert.equal(s.native.round_trip_ms,null);assert.equal(s.native.decode_ms,null);
|
||||
assert.equal(s.native.codec,null);assert.equal(s.native.extra,undefined);assert.equal(s.presentation.estimated_capture_to_present_ms,null);
|
||||
});
|
||||
test('stalled native and presentation samples expire independently after three seconds',()=>{
|
||||
const d=new StreamDiagnostics();d.observeNative(0,{fps:8});d.observeFrame(2500,{expectedDisplayTime:2501});
|
||||
assert.equal(d.snapshot(3001,0).native,null);assert.ok(d.snapshot(3001,0).presentation);
|
||||
assert.equal(d.snapshot(5501,0).presentation,null);
|
||||
});
|
||||
test('invalid clock order cannot become a claimed end-to-end measurement',()=>{
|
||||
const d=new StreamDiagnostics();d.observeFrame(100,{expectedDisplayTime:100,captureTime:110,receiveTime:-1});
|
||||
assert.equal(d.snapshot(100,8).presentation.estimated_capture_to_present_ms,null);
|
||||
assert.equal(d.snapshot(100,8).presentation.receive_to_present_ms,null);
|
||||
});
|
||||
@@ -95,6 +95,7 @@ export default defineConfig(({ mode }) => {
|
||||
rollupOptions: {
|
||||
input: {
|
||||
app: fileURLToPath(new URL("./index.html", import.meta.url)),
|
||||
simulationStream: fileURLToPath(new URL("./simulation-stream.html", import.meta.url)),
|
||||
rerun: fileURLToPath(new URL("./rerun-runtime.html", import.meta.url)),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
MISSIONCORE_MQTT_BIND_ADDRESS=127.0.0.1
|
||||
MISSIONCORE_MQTT_PORT=1883
|
||||
MISSIONCORE_TELEMETRY_QUERY_PORT=18030
|
||||
MISSIONCORE_DB_NAME=missioncore_telemetry
|
||||
MISSIONCORE_DB_USER=missioncore_ingest
|
||||
MISSIONCORE_DB_PASSWORD=replace-with-a-random-local-secret
|
||||
MISSIONCORE_DB_INGEST_PASSWORD=replace-with-a-separate-ingest-secret
|
||||
MISSIONCORE_MQTT_INGEST_USER=missioncore-ingest
|
||||
MISSIONCORE_MQTT_INGEST_PASSWORD=replace-with-a-random-local-secret
|
||||
|
||||
@@ -2,54 +2,45 @@
|
||||
|
||||
Portable local-only telemetry infrastructure for compute contours.
|
||||
|
||||
One Docker Compose project, `ndc-mission-core-telemetry`, owns three long-running
|
||||
containers and one bounded bootstrap job:
|
||||
The operator contour is **live-only**. One Compose project,
|
||||
`ndc-mission-core-telemetry`, owns two services: the authenticated Mosquitto broker
|
||||
and the normalizer/query adapter. There is no local telemetry database, named data
|
||||
volume, raw metric archive, or SQL retention job.
|
||||
|
||||
- `ndc-mission-core-mqtt-broker` — Eclipse Mosquitto `2.1.2-alpine`;
|
||||
- `ndc-mission-core-telemetry-timescaledb` — TimescaleDB HA OSS
|
||||
`pg16.14-ts2.28.2-all-oss`;
|
||||
- `ndc-mission-core-telemetry-bootstrap` — one-shot database role/bootstrap job;
|
||||
- `ndc-mission-core-telemetry-normalizer` — Mission Core telemetry normalizer.
|
||||
Each new sample replaces the previous value for the same contour, agent,
|
||||
measurement and series. The existing `/v1/contours/.../agents/.../latest` response
|
||||
contract is preserved. Split Telegraf fields at the same timestamp are merged;
|
||||
out-of-order older samples cannot replace newer state.
|
||||
|
||||
The Telegraf configuration templates cover Windows and Linux, but the agent runs as a
|
||||
host service rather than inside this Compose project. This preserves access to native
|
||||
Windows performance counters, Docker Desktop and NVIDIA telemetry.
|
||||
The cache lives only in RAM. Values expire after five minutes (the Core UI asks
|
||||
for at most 30-second-old values). Limits are 512 series per agent, 20,000 total,
|
||||
and 16 MiB of accounted entries including a fixed overhead allowance, within the
|
||||
256 MiB container memory ceiling. Oldest entries are evicted on capacity pressure;
|
||||
health exposes capacity, eviction and stale-input counters. This is bounded local
|
||||
monitoring, not a claim of acceptance for hundreds of workers.
|
||||
|
||||
The normalizer exposes a read-only normalized telemetry adapter on
|
||||
`127.0.0.1:18030`. Mission Core reads this adapter; the browser never receives MQTT or
|
||||
Timescale credentials, and Timescale is not published on a host port.
|
||||
The normalizer uses a separate `missioncore_normalizer` database role with only
|
||||
`SELECT`, `INSERT`, `UPDATE`, and bounded retention `DELETE` on the telemetry
|
||||
hypertable. Raw telemetry older than 30 days is removed in batches of at most
|
||||
1000 rows per minute, on a separate connection/thread (2s statement / 250ms lock
|
||||
deadline). Retention never runs inside the MQTT callback. This stays compatible
|
||||
with the Apache-licensed Timescale image without
|
||||
depending on the Timescale License retention scheduler.
|
||||
A background sweep clears the entire cache at the UTC date boundary, including
|
||||
when no messages arrive; restart also starts empty. Routine HTTP polls and message
|
||||
payloads are not logged. Both services rotate their diagnostic Docker logs at
|
||||
5 MiB × 2 files per service. MQTT persistence/retained messages are disabled,
|
||||
offline sessions are not replayed, and queues are bounded. Authentication, agent
|
||||
ACLs, loopback query access and the existing Worker connection are unchanged.
|
||||
|
||||
The 1 GiB database container explicitly sets 128 MiB shared buffers and 64 MiB
|
||||
maintenance memory. The HA image's automatic tuning sees the Docker VM instead
|
||||
of this container limit; do not inherit its multi-GiB defaults.
|
||||
`/health` reports `storage_ready` and `storage.backend=memory`; it no longer claims
|
||||
a database is reachable. Startup reconciliation uses that contract and can start
|
||||
only broker + normalizer. Long-term monitoring, if requested later, belongs to a
|
||||
separate explicitly provisioned service with time/size retention budgets.
|
||||
|
||||
For a memory-constrained local repair, `compose.source.yaml` mounts the reviewed
|
||||
normalizer source read-only into the **existing** image. Set
|
||||
`MISSIONCORE_NORMALIZER_SOURCE` to the absolute `normalizer.py` path, pass both
|
||||
Compose files and the existing private `--env-file` / `--project-directory`, and
|
||||
use `up -d --no-deps --no-build normalizer`. This is an explicit local source
|
||||
override, not a rebuilt portable image. Normal restart/reboot retains the mount.
|
||||
For migration from the retired SQL deployment: qualify the live adapter first,
|
||||
then remove only the exact Mission Core Timescale/bootstrap containers and the
|
||||
`ndc-mission-core-telemetry-timescale-data` volume, with owner authorization for
|
||||
history deletion. The old `ndc-mission-core-mqtt-data` volume is also obsolete.
|
||||
Do not use global Docker pruning or remove the Docker disk image. Simulation
|
||||
recordings, evidence, local application databases and Worker artifacts are separate
|
||||
and are not part of this migration.
|
||||
|
||||
The stack is one deployment contour, not one multi-process container. Keeping broker,
|
||||
normalizer and database in separate containers preserves independent health checks,
|
||||
least-privilege boundaries and rollback while Compose provides one operator lifecycle:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose up -d
|
||||
docker compose down
|
||||
```
|
||||
|
||||
All NODE.DC-owned Docker objects use the lowercase `ndc-` namespace. Docker names are
|
||||
case-sensitive identifiers, so the product prefix is normalized to lowercase while the
|
||||
product name remains NODE.DC in operator-facing copy.
|
||||
The optional `compose.source.yaml` provides a read-only source override for a
|
||||
bounded local repair; normal releases use the built normalizer image.
|
||||
|
||||
This directory does not contain credentials. Copy `.env.example` to `.env`, generate
|
||||
unique passwords and build the ACL/password files before starting the stack.
|
||||
@@ -101,10 +92,7 @@ network: ndc-mission-core-telemetry
|
||||
containers:
|
||||
ndc-mission-core-mqtt-broker
|
||||
ndc-mission-core-telemetry-normalizer
|
||||
ndc-mission-core-telemetry-timescaledb
|
||||
volumes:
|
||||
ndc-mission-core-mqtt-data
|
||||
ndc-mission-core-telemetry-timescale-data
|
||||
volumes: none (volatile tmpfs only)
|
||||
```
|
||||
|
||||
`prepare.py` passes passwords to `mosquitto_passwd` through stdin. Secrets are not placed
|
||||
|
||||
@@ -10,6 +10,11 @@ services:
|
||||
image: eclipse-mosquitto:2.1.2-alpine
|
||||
container_name: ndc-mission-core-mqtt-broker
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: local
|
||||
options:
|
||||
max-size: "5m"
|
||||
max-file: "2"
|
||||
read_only: true
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
@@ -33,9 +38,10 @@ services:
|
||||
- ./mosquitto/mosquitto.conf:/mosquitto/config/mosquitto.conf:ro
|
||||
- ./runtime/mosquitto/passwords:/mosquitto/config/passwords:ro
|
||||
- ./runtime/mosquitto/acl:/mosquitto/config/acl:ro
|
||||
- broker-data:/mosquitto/data
|
||||
tmpfs:
|
||||
- /tmp:size=16m,noexec,nosuid
|
||||
- /mosquitto/data:size=1m,noexec,nosuid
|
||||
- /mosquitto/log:size=1m,noexec,nosuid
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
@@ -47,67 +53,18 @@ services:
|
||||
timeout: 4s
|
||||
retries: 6
|
||||
|
||||
timescale:
|
||||
image: timescale/timescaledb-ha:pg16.14-ts2.28.2-all-oss
|
||||
# The HA image auto-tunes for the Docker VM, not this 1 GiB container.
|
||||
command: ["postgres", "-c", "shared_buffers=128MB", "-c", "work_mem=4MB", "-c", "maintenance_work_mem=64MB", "-c", "effective_cache_size=512MB", "-c", "max_parallel_workers_per_gather=0", "-c", "max_connections=32"]
|
||||
container_name: ndc-mission-core-telemetry-timescaledb
|
||||
restart: unless-stopped
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 1024m
|
||||
pids_limit: 256
|
||||
labels:
|
||||
<<: *ndc-labels
|
||||
com.nodedc.role: telemetry-database
|
||||
environment:
|
||||
POSTGRES_DB: "${MISSIONCORE_DB_NAME}"
|
||||
POSTGRES_USER: "${MISSIONCORE_DB_USER}"
|
||||
POSTGRES_PASSWORD: "${MISSIONCORE_DB_PASSWORD}"
|
||||
volumes:
|
||||
- timescale-data:/home/postgres/pgdata/data
|
||||
- ./timescale/001_telemetry.sql:/docker-entrypoint-initdb.d/001_telemetry.sql:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${MISSIONCORE_DB_USER} -d ${MISSIONCORE_DB_NAME}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
database-bootstrap:
|
||||
image: timescale/timescaledb-ha:pg16.14-ts2.28.2-all-oss
|
||||
container_name: ndc-mission-core-telemetry-bootstrap
|
||||
restart: "no"
|
||||
read_only: true
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
mem_limit: 128m
|
||||
pids_limit: 64
|
||||
labels:
|
||||
<<: *ndc-labels
|
||||
com.nodedc.role: telemetry-database-bootstrap
|
||||
depends_on:
|
||||
timescale:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
MISSIONCORE_DB_NAME: "${MISSIONCORE_DB_NAME}"
|
||||
MISSIONCORE_DB_ADMIN_USER: "${MISSIONCORE_DB_USER}"
|
||||
MISSIONCORE_DB_ADMIN_PASSWORD: "${MISSIONCORE_DB_PASSWORD}"
|
||||
MISSIONCORE_DB_INGEST_PASSWORD: "${MISSIONCORE_DB_INGEST_PASSWORD}"
|
||||
volumes:
|
||||
- ./timescale/002_roles_and_retention.sh:/bootstrap.sh:ro
|
||||
tmpfs:
|
||||
- /tmp:size=16m,noexec,nosuid
|
||||
entrypoint: ["/bin/sh", "/bootstrap.sh"]
|
||||
|
||||
normalizer:
|
||||
image: nodedc/mission-core-telemetry-normalizer:local
|
||||
image: ndc-mission-core-telemetry-normalizer:live-v1
|
||||
container_name: ndc-mission-core-telemetry-normalizer
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: deploy/telemetry-plane/normalizer/Dockerfile
|
||||
context: ./normalizer
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: local
|
||||
options:
|
||||
max-size: "5m"
|
||||
max-file: "2"
|
||||
read_only: true
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
@@ -121,10 +78,6 @@ services:
|
||||
depends_on:
|
||||
broker:
|
||||
condition: service_healthy
|
||||
timescale:
|
||||
condition: service_healthy
|
||||
database-bootstrap:
|
||||
condition: service_completed_successfully
|
||||
ports:
|
||||
- "127.0.0.1:${MISSIONCORE_TELEMETRY_QUERY_PORT:-18030}:18030"
|
||||
environment:
|
||||
@@ -132,8 +85,6 @@ services:
|
||||
MISSIONCORE_MQTT_PORT: "1883"
|
||||
MISSIONCORE_MQTT_USERNAME: "${MISSIONCORE_MQTT_INGEST_USER}"
|
||||
MISSIONCORE_MQTT_PASSWORD: "${MISSIONCORE_MQTT_INGEST_PASSWORD}"
|
||||
MISSIONCORE_DATABASE_DSN: >-
|
||||
postgresql://missioncore_normalizer:${MISSIONCORE_DB_INGEST_PASSWORD}@timescale:5432/${MISSIONCORE_DB_NAME}
|
||||
MISSIONCORE_QUERY_HOST: "0.0.0.0"
|
||||
MISSIONCORE_QUERY_PORT: "18030"
|
||||
tmpfs:
|
||||
@@ -150,18 +101,6 @@ services:
|
||||
timeout: 4s
|
||||
retries: 6
|
||||
|
||||
volumes:
|
||||
broker-data:
|
||||
name: ndc-mission-core-mqtt-data
|
||||
labels:
|
||||
<<: *ndc-labels
|
||||
com.nodedc.role: mqtt-storage
|
||||
timescale-data:
|
||||
name: ndc-mission-core-telemetry-timescale-data
|
||||
labels:
|
||||
<<: *ndc-labels
|
||||
com.nodedc.role: telemetry-storage
|
||||
|
||||
networks:
|
||||
default:
|
||||
name: ndc-mission-core-telemetry
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
persistence true
|
||||
persistence_location /mosquitto/data/
|
||||
# Live telemetry only: never write MQTT messages/session history to disk.
|
||||
persistence false
|
||||
retain_available false
|
||||
# Health probe waits 3s; without retained messages SYS must publish within that.
|
||||
sys_interval 1
|
||||
max_queued_messages 200
|
||||
max_queued_bytes 1048576
|
||||
message_size_limit 1048576
|
||||
persistent_client_expiration 1d
|
||||
|
||||
listener 1883 0.0.0.0
|
||||
allow_anonymous false
|
||||
@@ -7,5 +14,5 @@ password_file /mosquitto/config/passwords
|
||||
acl_file /mosquitto/config/acl
|
||||
|
||||
log_dest stdout
|
||||
connection_messages true
|
||||
connection_messages false
|
||||
log_timestamp true
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
RUN pip install --no-cache-dir "paho-mqtt>=2.1,<3" "psycopg[binary]>=3.2,<4"
|
||||
COPY deploy/telemetry-plane/normalizer/normalizer.py /app/normalizer.py
|
||||
RUN pip install --no-cache-dir "paho-mqtt==2.1.0"
|
||||
COPY normalizer.py /app/normalizer.py
|
||||
|
||||
USER 65532:65532
|
||||
ENTRYPOINT ["python", "/app/normalizer.py"]
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from datetime import UTC, datetime
|
||||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
@@ -31,8 +31,10 @@ SAFE_IDENTIFIER: Final = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")
|
||||
MAX_PAYLOAD_BYTES: Final = 1024 * 1024
|
||||
MAX_TAGS: Final = 256
|
||||
MAX_SERIES_KEY_BYTES: Final = 4096
|
||||
RETENTION_INTERVAL_SECONDS: Final = 60
|
||||
RETENTION_BATCH_ROWS: Final = 1000
|
||||
LATEST_TTL_SECONDS: Final = 300
|
||||
MAX_LATEST_SAMPLES: Final = 20_000
|
||||
MAX_AGENT_SAMPLES: Final = 512
|
||||
MAX_CACHE_BYTES: Final = 16 * 1024 * 1024
|
||||
ALLOWED_TELEMETRY_TAGS: Final = frozenset(
|
||||
{
|
||||
"agent_id",
|
||||
@@ -133,9 +135,7 @@ def _sanitize_tags(document: dict[str, Any]) -> dict[str, Any]:
|
||||
if len(tags) > MAX_TAGS:
|
||||
raise ValueError("telemetry payload contains too many tags")
|
||||
sanitized = {
|
||||
str(name): str(value)
|
||||
for name, value in tags.items()
|
||||
if name in ALLOWED_TELEMETRY_TAGS
|
||||
str(name): str(value) for name, value in tags.items() if name in ALLOWED_TELEMETRY_TAGS
|
||||
}
|
||||
return {**document, "tags": sanitized}
|
||||
|
||||
@@ -197,11 +197,7 @@ def _normalize(topic: str, payload: bytes) -> tuple[object, ...]:
|
||||
node_id = document.get("node_id") or _tag_text(document, "node_id")
|
||||
if not node_id:
|
||||
node_id = _tag_text(document, "host")
|
||||
if (
|
||||
not isinstance(node_id, str)
|
||||
or not node_id.strip()
|
||||
or len(node_id.strip()) > 128
|
||||
):
|
||||
if not isinstance(node_id, str) or not node_id.strip() or len(node_id.strip()) > 128:
|
||||
raise ValueError("node_id is required")
|
||||
observed_at = _timestamp(observed_value)
|
||||
return (
|
||||
@@ -222,27 +218,163 @@ def _normalize(topic: str, payload: bytes) -> tuple[object, ...]:
|
||||
)
|
||||
|
||||
|
||||
class TelemetryQueryServer(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
class LatestTelemetry:
|
||||
"""Bounded volatile latest-value cache; never a time-series archive."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_address: tuple[str, int],
|
||||
dsn: str,
|
||||
runtime_health: TelemetryRuntimeHealth,
|
||||
*,
|
||||
clock=None,
|
||||
ttl_seconds=LATEST_TTL_SECONDS,
|
||||
max_samples=MAX_LATEST_SAMPLES,
|
||||
max_agent_samples=MAX_AGENT_SAMPLES,
|
||||
max_bytes=MAX_CACHE_BYTES,
|
||||
) -> None:
|
||||
super().__init__(server_address, TelemetryQueryHandler)
|
||||
self.dsn = dsn
|
||||
self.runtime_health = runtime_health
|
||||
self._clock = clock or (lambda: datetime.now(UTC))
|
||||
self._ttl = ttl_seconds
|
||||
self._max_samples = max_samples
|
||||
self._max_agent_samples = max_agent_samples
|
||||
self._max_bytes = max_bytes
|
||||
self._lock = threading.Lock()
|
||||
self._entries: OrderedDict = OrderedDict()
|
||||
self._agents: dict = {}
|
||||
self._bytes = 0
|
||||
self._day = self._clock().date()
|
||||
self._next_sweep = 0.0
|
||||
self._evictions = 0
|
||||
self._rejected = 0
|
||||
self._daily_resets = 0
|
||||
|
||||
def _remove(self, key) -> None:
|
||||
row, _ingested, size = self._entries.pop(key)
|
||||
agent = key[:2]
|
||||
self._agents[agent].pop(key)
|
||||
if not self._agents[agent]:
|
||||
del self._agents[agent]
|
||||
self._bytes -= size
|
||||
|
||||
def _maintain(self, now: datetime) -> None:
|
||||
if now.date() != self._day:
|
||||
self._entries.clear()
|
||||
self._agents.clear()
|
||||
self._bytes = 0
|
||||
self._day = now.date()
|
||||
self._daily_resets += 1
|
||||
self._next_sweep = 0.0
|
||||
if now.timestamp() >= self._next_sweep:
|
||||
cutoff = now.timestamp() - self._ttl
|
||||
for key, (row, _ingested, _size) in list(self._entries.items()):
|
||||
if row[0].timestamp() < cutoff:
|
||||
self._remove(key)
|
||||
self._next_sweep = now.timestamp() + 5
|
||||
|
||||
def maintenance(self) -> None:
|
||||
with self._lock:
|
||||
self._maintain(self._clock())
|
||||
|
||||
def put(self, row: tuple) -> bool:
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
self._maintain(now)
|
||||
age = (now - row[0]).total_seconds()
|
||||
if age > self._ttl or age < -30:
|
||||
self._rejected += 1
|
||||
return False
|
||||
key = (row[1], row[2], row[4], row[5], row[6])
|
||||
agent = key[:2]
|
||||
previous = self._entries.get(key)
|
||||
if previous:
|
||||
old = previous[0]
|
||||
if old[0] > row[0]:
|
||||
return False
|
||||
if old[0] == row[0] and old[7] == row[7] == TELEGRAF_SCHEMA:
|
||||
# Telegraf can split fields of a single timestamp across messages.
|
||||
previous_payload = json.loads(old[13])
|
||||
payload = json.loads(row[13])
|
||||
payload["fields"] = {
|
||||
**previous_payload.get("fields", {}),
|
||||
**payload.get("fields", {}),
|
||||
}
|
||||
row = (
|
||||
*row[:13],
|
||||
json.dumps(payload, separators=(",", ":"), ensure_ascii=False),
|
||||
)
|
||||
# Count retained strings as UTF-8, plus a conservative fixed entry charge.
|
||||
# Both entry count and container RSS also have independent hard limits.
|
||||
size = sum(len(str(value).encode("utf-8")) for value in row) + 512
|
||||
if size > self._max_bytes:
|
||||
self._rejected += 1
|
||||
return False
|
||||
if previous:
|
||||
self._remove(key)
|
||||
while len(self._agents.get(agent, {})) >= self._max_agent_samples:
|
||||
self._remove(next(iter(self._agents[agent])))
|
||||
self._evictions += 1
|
||||
while self._entries and (
|
||||
len(self._entries) >= self._max_samples or self._bytes + size > self._max_bytes
|
||||
):
|
||||
self._remove(next(iter(self._entries)))
|
||||
self._evictions += 1
|
||||
self._entries[key] = (row, now, size)
|
||||
self._agents.setdefault(agent, OrderedDict())[key] = None
|
||||
self._bytes += size
|
||||
return True
|
||||
|
||||
def latest(self, contour_id: str, agent_id: str, max_age_seconds: int) -> list:
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
self._maintain(now)
|
||||
entries = [self._entries[key] for key in self._agents.get((contour_id, agent_id), {})]
|
||||
samples = []
|
||||
for row, ingested, _size in entries:
|
||||
if (now - row[0]).total_seconds() > min(max_age_seconds, self._ttl):
|
||||
continue
|
||||
samples.append(
|
||||
{
|
||||
"observed_at_utc": row[0].isoformat().replace("+00:00", "Z"),
|
||||
"ingested_at_utc": ingested.isoformat().replace("+00:00", "Z"),
|
||||
"node_id": row[3],
|
||||
"kind": row[4],
|
||||
"measurement": row[5],
|
||||
"series_key": row[6],
|
||||
"source_schema": row[7],
|
||||
"lab_id": row[9],
|
||||
"run_id": row[10],
|
||||
"request_id": row[11],
|
||||
"frame_index": row[12],
|
||||
"payload": json.loads(row[13]),
|
||||
}
|
||||
)
|
||||
return sorted(
|
||||
samples,
|
||||
key=lambda sample: (sample["kind"], sample["measurement"], sample["series_key"]),
|
||||
)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
with self._lock:
|
||||
self._maintain(self._clock())
|
||||
return {
|
||||
"backend": "memory",
|
||||
"persistent_history": False,
|
||||
"samples": len(self._entries),
|
||||
"agents": len(self._agents),
|
||||
"accounted_bytes": self._bytes,
|
||||
"max_bytes": self._max_bytes,
|
||||
"max_samples": self._max_samples,
|
||||
"max_agent_samples": self._max_agent_samples,
|
||||
"ttl_seconds": self._ttl,
|
||||
"daily_reset_timezone": "UTC",
|
||||
"reset_day": self._day.isoformat(),
|
||||
"daily_resets": self._daily_resets,
|
||||
"evictions": self._evictions,
|
||||
"rejected_samples": self._rejected,
|
||||
}
|
||||
|
||||
|
||||
class TelemetryRuntimeHealth:
|
||||
"""Thread-safe health of the actual MQTT-to-database ingestion path."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._mqtt_connected = False
|
||||
self._database_connected = False
|
||||
self._last_ingested_at_utc: str | None = None
|
||||
self._last_error: str | None = None
|
||||
|
||||
@@ -251,341 +383,145 @@ class TelemetryRuntimeHealth:
|
||||
self._mqtt_connected = connected
|
||||
self._last_error = error
|
||||
|
||||
def set_database(self, connected: bool, error: str | None = None) -> None:
|
||||
with self._lock:
|
||||
self._database_connected = connected
|
||||
self._last_error = error
|
||||
|
||||
def mark_ingested(self) -> None:
|
||||
with self._lock:
|
||||
self._database_connected = True
|
||||
self._last_ingested_at_utc = (
|
||||
datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
)
|
||||
self._last_ingested_at_utc = datetime.now(UTC).isoformat().replace("+00:00", "Z")
|
||||
self._last_error = None
|
||||
|
||||
def snapshot(self) -> dict[str, object]:
|
||||
with self._lock:
|
||||
return {
|
||||
"mqtt_connected": self._mqtt_connected,
|
||||
"database_connected": self._database_connected,
|
||||
"last_ingested_at_utc": self._last_ingested_at_utc,
|
||||
"last_error": self._last_error,
|
||||
}
|
||||
|
||||
|
||||
class TelemetryQueryServer(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(self, server_address, cache, runtime_health) -> None:
|
||||
super().__init__(server_address, TelemetryQueryHandler)
|
||||
self.cache = cache
|
||||
self.runtime_health = runtime_health
|
||||
|
||||
|
||||
class TelemetryQueryHandler(BaseHTTPRequestHandler):
|
||||
server: TelemetryQueryServer
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802 - stdlib HTTP handler contract
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == "/health":
|
||||
self._health()
|
||||
runtime = self.server.runtime_health.snapshot()
|
||||
ok = runtime["mqtt_connected"] is True
|
||||
self._json(
|
||||
HTTPStatus.OK if ok else HTTPStatus.SERVICE_UNAVAILABLE,
|
||||
{
|
||||
"ok": ok,
|
||||
"schema_version": QUERY_SCHEMA,
|
||||
"storage_ready": True,
|
||||
"storage": self.server.cache.snapshot(),
|
||||
**runtime,
|
||||
},
|
||||
)
|
||||
return
|
||||
match = re.fullmatch(
|
||||
r"/v1/contours/(?P<contour>[-a-z0-9]+)/agents/"
|
||||
r"(?P<agent>[-a-z0-9]+)/latest",
|
||||
r"/v1/contours/(?P<contour>[-a-z0-9]+)/agents/(?P<agent>[-a-z0-9]+)/latest",
|
||||
parsed.path,
|
||||
)
|
||||
if match is None:
|
||||
self._json(HTTPStatus.NOT_FOUND, {"detail": "not found"})
|
||||
return
|
||||
query = parse_qs(parsed.query)
|
||||
try:
|
||||
max_age_seconds = int(query.get("max_age_seconds", ["120"])[0])
|
||||
max_age_seconds = int(parse_qs(parsed.query).get("max_age_seconds", ["120"])[0])
|
||||
except ValueError:
|
||||
self._json(HTTPStatus.BAD_REQUEST, {"detail": "invalid max_age_seconds"})
|
||||
return
|
||||
max_age_seconds = 0
|
||||
if not 1 <= max_age_seconds <= 86_400:
|
||||
self._json(HTTPStatus.BAD_REQUEST, {"detail": "invalid max_age_seconds"})
|
||||
return
|
||||
self._latest(
|
||||
match.group("contour"),
|
||||
match.group("agent"),
|
||||
max_age_seconds=max_age_seconds,
|
||||
)
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
print(f"telemetry query: {format % args}", flush=True)
|
||||
|
||||
def _health(self) -> None:
|
||||
import psycopg # type: ignore[import-not-found]
|
||||
|
||||
database_reachable = False
|
||||
try:
|
||||
with (
|
||||
psycopg.connect(self.server.dsn) as connection,
|
||||
connection.cursor() as cursor,
|
||||
):
|
||||
cursor.execute("SELECT 1")
|
||||
cursor.fetchone()
|
||||
database_reachable = True
|
||||
except psycopg.Error:
|
||||
database_reachable = False
|
||||
runtime = self.server.runtime_health.snapshot()
|
||||
ok = (
|
||||
database_reachable
|
||||
and runtime["mqtt_connected"] is True
|
||||
and runtime["database_connected"] is True
|
||||
)
|
||||
self._json(
|
||||
HTTPStatus.OK if ok else HTTPStatus.SERVICE_UNAVAILABLE,
|
||||
{
|
||||
"ok": ok,
|
||||
"schema_version": QUERY_SCHEMA,
|
||||
"database_reachable": database_reachable,
|
||||
**runtime,
|
||||
},
|
||||
)
|
||||
|
||||
def _latest(
|
||||
self,
|
||||
contour_id: str,
|
||||
agent_id: str,
|
||||
*,
|
||||
max_age_seconds: int,
|
||||
) -> None:
|
||||
import psycopg # type: ignore[import-not-found]
|
||||
|
||||
if (
|
||||
SAFE_IDENTIFIER.fullmatch(contour_id) is None
|
||||
or SAFE_IDENTIFIER.fullmatch(agent_id) is None
|
||||
):
|
||||
contour, agent = match.group("contour"), match.group("agent")
|
||||
if SAFE_IDENTIFIER.fullmatch(contour) is None or SAFE_IDENTIFIER.fullmatch(agent) is None:
|
||||
self._json(HTTPStatus.BAD_REQUEST, {"detail": "invalid identifier"})
|
||||
return
|
||||
try:
|
||||
with (
|
||||
psycopg.connect(self.server.dsn) as connection,
|
||||
connection.cursor() as cursor,
|
||||
):
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT DISTINCT ON (kind, measurement, series_key)
|
||||
observed_at, ingested_at, node_id, kind, measurement,
|
||||
series_key, source_schema, lab_id, run_id, request_id,
|
||||
frame_index, payload
|
||||
FROM contour_telemetry_samples
|
||||
WHERE contour_id = %s
|
||||
AND agent_id = %s
|
||||
AND observed_at >= NOW() - (%s * INTERVAL '1 second')
|
||||
ORDER BY kind, measurement, series_key, observed_at DESC
|
||||
""",
|
||||
(contour_id, agent_id, max_age_seconds),
|
||||
)
|
||||
rows = cursor.fetchall()
|
||||
except psycopg.Error:
|
||||
self._json(
|
||||
HTTPStatus.SERVICE_UNAVAILABLE,
|
||||
{"detail": "telemetry database unavailable"},
|
||||
)
|
||||
return
|
||||
samples = [
|
||||
{
|
||||
"observed_at_utc": row[0].astimezone(UTC).isoformat().replace("+00:00", "Z"),
|
||||
"ingested_at_utc": row[1].astimezone(UTC).isoformat().replace("+00:00", "Z"),
|
||||
"node_id": row[2],
|
||||
"kind": row[3],
|
||||
"measurement": row[4],
|
||||
"series_key": row[5],
|
||||
"source_schema": row[6],
|
||||
"lab_id": row[7],
|
||||
"run_id": row[8],
|
||||
"request_id": row[9],
|
||||
"frame_index": row[10],
|
||||
"payload": row[11],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
self._json(
|
||||
HTTPStatus.OK,
|
||||
{
|
||||
"schema_version": QUERY_SCHEMA,
|
||||
"contour_id": contour_id,
|
||||
"agent_id": agent_id,
|
||||
"samples": samples,
|
||||
"contour_id": contour,
|
||||
"agent_id": agent,
|
||||
"samples": self.server.cache.latest(contour, agent, max_age_seconds),
|
||||
},
|
||||
)
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
# Polls/health checks must not become another on-disk telemetry history.
|
||||
pass
|
||||
|
||||
def _json(self, status: HTTPStatus, document: dict[str, object]) -> None:
|
||||
body = json.dumps(
|
||||
document,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
body = json.dumps(document, ensure_ascii=False, separators=(",", ":")).encode()
|
||||
self.send_response(status.value)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
def _start_query_server(
|
||||
dsn: str,
|
||||
runtime_health: TelemetryRuntimeHealth,
|
||||
) -> ThreadingHTTPServer:
|
||||
def _start_query_server(cache, runtime_health) -> ThreadingHTTPServer:
|
||||
host = os.environ.get("MISSIONCORE_QUERY_HOST", "0.0.0.0")
|
||||
port = int(os.environ.get("MISSIONCORE_QUERY_PORT", "18030"))
|
||||
server = TelemetryQueryServer((host, port), dsn, runtime_health)
|
||||
thread = threading.Thread(
|
||||
target=server.serve_forever,
|
||||
name="telemetry-query",
|
||||
daemon=True,
|
||||
)
|
||||
thread.start()
|
||||
server = TelemetryQueryServer((host, port), cache, runtime_health)
|
||||
threading.Thread(target=server.serve_forever, name="telemetry-query", daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
def _retention_batch(connection: Any) -> int:
|
||||
"""Preserve the existing 30-day policy without an unbounded startup DELETE."""
|
||||
with connection.transaction(), connection.cursor() as cursor:
|
||||
cursor.execute("SET LOCAL statement_timeout = '2s'")
|
||||
cursor.execute("SET LOCAL lock_timeout = '250ms'")
|
||||
cursor.execute(
|
||||
"""
|
||||
WITH expired AS (
|
||||
SELECT tableoid, ctid FROM contour_telemetry_samples
|
||||
WHERE observed_at < CURRENT_TIMESTAMP - INTERVAL '30 days'
|
||||
ORDER BY observed_at LIMIT %s
|
||||
)
|
||||
DELETE FROM contour_telemetry_samples AS samples USING expired
|
||||
WHERE samples.tableoid = expired.tableoid AND samples.ctid = expired.ctid
|
||||
""",
|
||||
(RETENTION_BATCH_ROWS,),
|
||||
)
|
||||
return cursor.rowcount
|
||||
|
||||
|
||||
def _retention_loop(dsn: str) -> None:
|
||||
import psycopg # type: ignore[import-not-found]
|
||||
|
||||
def _maintenance_loop(cache: LatestTelemetry) -> None:
|
||||
while True:
|
||||
# Neither a retention timeout nor database recovery blocks MQTT I/O.
|
||||
time.sleep(RETENTION_INTERVAL_SECONDS)
|
||||
try:
|
||||
with psycopg.connect(dsn, connect_timeout=3) as connection:
|
||||
_retention_batch(connection)
|
||||
except psycopg.Error:
|
||||
print("telemetry retention deferred", flush=True)
|
||||
time.sleep(1)
|
||||
cache.maintenance()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import paho.mqtt.client as mqtt
|
||||
import psycopg # type: ignore[import-not-found]
|
||||
from paho.mqtt import MQTTException
|
||||
from paho.mqtt.enums import CallbackAPIVersion
|
||||
|
||||
dsn = _required("MISSIONCORE_DATABASE_DSN")
|
||||
host = _required("MISSIONCORE_MQTT_HOST")
|
||||
port = int(os.environ.get("MISSIONCORE_MQTT_PORT", "1883"))
|
||||
username = _required("MISSIONCORE_MQTT_USERNAME")
|
||||
password = _required("MISSIONCORE_MQTT_PASSWORD")
|
||||
cache = LatestTelemetry()
|
||||
runtime_health = TelemetryRuntimeHealth()
|
||||
connection = psycopg.connect(dsn, autocommit=True)
|
||||
threading.Thread(
|
||||
target=_retention_loop, args=(dsn,), name="telemetry-retention", daemon=True
|
||||
target=_maintenance_loop, args=(cache,), name="telemetry-expiry", daemon=True
|
||||
).start()
|
||||
runtime_health.set_database(True)
|
||||
_start_query_server(dsn, runtime_health)
|
||||
_start_query_server(cache, runtime_health)
|
||||
# No offline replay queue: this receiver serves current state, not history.
|
||||
client = mqtt.Client(
|
||||
callback_api_version=CallbackAPIVersion.VERSION2,
|
||||
client_id="ndc-mission-core-telemetry-normalizer",
|
||||
clean_session=False,
|
||||
clean_session=True,
|
||||
)
|
||||
client.username_pw_set(username, password)
|
||||
|
||||
def on_connect(
|
||||
connected_client: Any,
|
||||
_userdata: object,
|
||||
_flags: Any,
|
||||
reason_code: Any,
|
||||
_properties: Any,
|
||||
) -> None:
|
||||
def on_connect(connected_client, _userdata, _flags, reason_code, _properties):
|
||||
if reason_code.is_failure:
|
||||
runtime_health.set_mqtt(False, f"MQTT connection rejected: {reason_code}")
|
||||
raise RuntimeError(f"MQTT connection rejected: {reason_code}")
|
||||
runtime_health.set_mqtt(False, "MQTT connection rejected")
|
||||
return
|
||||
connected_client.subscribe(TOPIC, qos=1)
|
||||
runtime_health.set_mqtt(True)
|
||||
|
||||
def on_disconnect(
|
||||
_connected_client: Any,
|
||||
_userdata: object,
|
||||
_disconnect_flags: Any,
|
||||
reason_code: Any,
|
||||
_properties: Any,
|
||||
) -> None:
|
||||
runtime_health.set_mqtt(False, f"MQTT disconnected: {reason_code}")
|
||||
def on_disconnect(_client, _userdata, _flags, reason_code, _properties):
|
||||
runtime_health.set_mqtt(False, "MQTT disconnected")
|
||||
|
||||
def on_message(_client: Any, _userdata: object, message: Any) -> None:
|
||||
nonlocal connection
|
||||
def on_message(_client, _userdata, message):
|
||||
try:
|
||||
row = _normalize(message.topic, message.payload)
|
||||
except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
print(f"telemetry sample rejected: {exc}", flush=True)
|
||||
return
|
||||
for attempt in range(2):
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO contour_telemetry_samples (
|
||||
observed_at, contour_id, agent_id, node_id, kind, measurement,
|
||||
series_key, source_schema, source_topic, lab_id, run_id,
|
||||
request_id, frame_index, payload
|
||||
)
|
||||
VALUES (
|
||||
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
|
||||
%s::jsonb
|
||||
)
|
||||
ON CONFLICT (
|
||||
observed_at, contour_id, agent_id, kind, measurement, series_key
|
||||
)
|
||||
DO UPDATE SET
|
||||
ingested_at = NOW(),
|
||||
node_id = EXCLUDED.node_id,
|
||||
series_key = EXCLUDED.series_key,
|
||||
source_schema = EXCLUDED.source_schema,
|
||||
source_topic = EXCLUDED.source_topic,
|
||||
lab_id = EXCLUDED.lab_id,
|
||||
run_id = EXCLUDED.run_id,
|
||||
request_id = EXCLUDED.request_id,
|
||||
frame_index = EXCLUDED.frame_index,
|
||||
payload = CASE
|
||||
WHEN contour_telemetry_samples.source_schema = %s
|
||||
AND EXCLUDED.source_schema = %s
|
||||
THEN EXCLUDED.payload || jsonb_build_object(
|
||||
'fields',
|
||||
COALESCE(
|
||||
contour_telemetry_samples.payload -> 'fields',
|
||||
'{}'::jsonb
|
||||
) || COALESCE(
|
||||
EXCLUDED.payload -> 'fields',
|
||||
'{}'::jsonb
|
||||
)
|
||||
)
|
||||
ELSE EXCLUDED.payload
|
||||
END
|
||||
""",
|
||||
(*row, TELEGRAF_SCHEMA, TELEGRAF_SCHEMA),
|
||||
)
|
||||
if cache.put(row):
|
||||
runtime_health.mark_ingested()
|
||||
return
|
||||
except psycopg.Error as exc:
|
||||
runtime_health.set_database(False, f"database ingestion failed: {exc}")
|
||||
with contextlib.suppress(psycopg.Error):
|
||||
connection.close()
|
||||
if attempt == 0:
|
||||
try:
|
||||
connection = psycopg.connect(dsn, autocommit=True)
|
||||
runtime_health.set_database(True)
|
||||
except psycopg.Error as reconnect_error:
|
||||
runtime_health.set_database(
|
||||
False,
|
||||
f"database reconnect failed: {reconnect_error}",
|
||||
)
|
||||
break
|
||||
else:
|
||||
break
|
||||
print("telemetry sample rejected: database unavailable", flush=True)
|
||||
except (ValueError, UnicodeDecodeError, TypeError, OverflowError):
|
||||
# Never log rejected payloads or emit an unbounded line per bad sample.
|
||||
return
|
||||
|
||||
client.on_connect = on_connect
|
||||
client.on_disconnect = on_disconnect
|
||||
@@ -594,9 +530,8 @@ def main() -> None:
|
||||
try:
|
||||
client.connect(host, port, keepalive=30)
|
||||
client.loop_forever(retry_first_connection=True)
|
||||
except (OSError, MQTTException, psycopg.Error) as exc:
|
||||
runtime_health.set_mqtt(False, f"MQTT reconnecting: {exc}")
|
||||
print(f"telemetry normalizer reconnecting: {exc}", flush=True)
|
||||
except (OSError, MQTTException):
|
||||
runtime_health.set_mqtt(False, "MQTT reconnecting")
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
|
||||
@@ -24,9 +24,7 @@ PLACEHOLDER: Final = "replace-with-"
|
||||
AGENT_REGISTRY_SCHEMA: Final = "missioncore.telemetry-agent-credential-registry/v1"
|
||||
AGENT_PAYLOAD_SCHEMA: Final = "missioncore.telemetry-agent-provisioning-payload/v1"
|
||||
AGENT_BUNDLE_SCHEMA: Final = "missioncore.telemetry-agent-bundle/v1"
|
||||
SAFE_IDENTIFIER: Final = re.compile(
|
||||
r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$"
|
||||
)
|
||||
SAFE_IDENTIFIER: Final = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")
|
||||
SAFE_INTERVAL: Final = re.compile(r"^[1-9][0-9]{0,2}s$")
|
||||
WINDOWS_BUNDLE_FILES: Final = (
|
||||
"Install-NdcMissionCoreTelemetryRecovery.ps1",
|
||||
@@ -62,10 +60,6 @@ def _initialize_environment(bind_address: str, *, overwrite: bool = False) -> No
|
||||
"MISSIONCORE_MQTT_BIND_ADDRESS": normalized_bind_address,
|
||||
"MISSIONCORE_MQTT_PORT": "1883",
|
||||
"MISSIONCORE_TELEMETRY_QUERY_PORT": "18030",
|
||||
"MISSIONCORE_DB_NAME": "missioncore_telemetry",
|
||||
"MISSIONCORE_DB_USER": "missioncore_ingest",
|
||||
"MISSIONCORE_DB_PASSWORD": secrets.token_urlsafe(36),
|
||||
"MISSIONCORE_DB_INGEST_PASSWORD": secrets.token_urlsafe(36),
|
||||
"MISSIONCORE_MQTT_INGEST_USER": "missioncore-ingest",
|
||||
"MISSIONCORE_MQTT_INGEST_PASSWORD": secrets.token_urlsafe(36),
|
||||
}
|
||||
@@ -91,17 +85,6 @@ def _environment() -> dict[str, str]:
|
||||
|
||||
def _migrate_environment() -> None:
|
||||
values = _environment()
|
||||
additions: dict[str, str] = {}
|
||||
if "MISSIONCORE_DB_INGEST_PASSWORD" not in values:
|
||||
additions["MISSIONCORE_DB_INGEST_PASSWORD"] = secrets.token_urlsafe(36)
|
||||
if additions:
|
||||
with ENV_PATH.open("a", encoding="utf-8", newline="\n") as stream:
|
||||
for name, value in additions.items():
|
||||
stream.write(f"{name}={value}\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(ENV_PATH, 0o600)
|
||||
values.update(additions)
|
||||
_migrate_legacy_worker(values)
|
||||
|
||||
|
||||
@@ -301,12 +284,12 @@ def _private_mqtt_host(value: str) -> None:
|
||||
try:
|
||||
address = ipaddress.ip_address(value)
|
||||
except ValueError:
|
||||
if not value.endswith(".local") or len(value) > 253 or any(
|
||||
SAFE_IDENTIFIER.fullmatch(label) is None for label in value[:-6].split(".")
|
||||
if (
|
||||
not value.endswith(".local")
|
||||
or len(value) > 253
|
||||
or any(SAFE_IDENTIFIER.fullmatch(label) is None for label in value[:-6].split("."))
|
||||
):
|
||||
raise RuntimeError(
|
||||
"MQTT host must be a private IP or stable .local hostname"
|
||||
) from None
|
||||
raise RuntimeError("MQTT host must be a private IP or stable .local hostname") from None
|
||||
else:
|
||||
if not address.is_private or address.is_unspecified or address.is_multicast:
|
||||
raise RuntimeError("MQTT host must be a private IP or stable .local hostname")
|
||||
@@ -391,7 +374,6 @@ def _prepare_plane() -> None:
|
||||
agents = _read_agent_registry()
|
||||
ingest_user = _required(values, "MISSIONCORE_MQTT_INGEST_USER")
|
||||
ingest_password = _required(values, "MISSIONCORE_MQTT_INGEST_PASSWORD")
|
||||
_required(values, "MISSIONCORE_DB_PASSWORD")
|
||||
RUNTIME.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
password_path = RUNTIME / "passwords"
|
||||
_prepare_password_entries(password_path, ingest_user, ingest_password, agents)
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
CREATE EXTENSION IF NOT EXISTS timescaledb;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS contour_telemetry_samples (
|
||||
observed_at TIMESTAMPTZ NOT NULL,
|
||||
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
contour_id TEXT NOT NULL,
|
||||
agent_id TEXT NOT NULL,
|
||||
node_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
measurement TEXT NOT NULL,
|
||||
series_key TEXT NOT NULL DEFAULT '',
|
||||
source_schema TEXT NOT NULL,
|
||||
source_topic TEXT NOT NULL,
|
||||
lab_id TEXT,
|
||||
run_id TEXT,
|
||||
request_id TEXT,
|
||||
frame_index BIGINT,
|
||||
payload JSONB NOT NULL,
|
||||
PRIMARY KEY (
|
||||
observed_at,
|
||||
contour_id,
|
||||
agent_id,
|
||||
kind,
|
||||
measurement,
|
||||
series_key
|
||||
)
|
||||
);
|
||||
|
||||
SELECT create_hypertable(
|
||||
'contour_telemetry_samples',
|
||||
by_range('observed_at'),
|
||||
if_not_exists => TRUE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS contour_telemetry_latest_idx
|
||||
ON contour_telemetry_samples (
|
||||
contour_id,
|
||||
agent_id,
|
||||
kind,
|
||||
measurement,
|
||||
series_key,
|
||||
observed_at DESC
|
||||
);
|
||||
@@ -1,31 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
export PGPASSWORD="${MISSIONCORE_DB_ADMIN_PASSWORD}"
|
||||
|
||||
psql \
|
||||
--host timescale \
|
||||
--username "${MISSIONCORE_DB_ADMIN_USER}" \
|
||||
--dbname "${MISSIONCORE_DB_NAME}" \
|
||||
--set ON_ERROR_STOP=1 \
|
||||
--set database_name="${MISSIONCORE_DB_NAME}" \
|
||||
--set ingest_password="${MISSIONCORE_DB_INGEST_PASSWORD}" <<'SQL'
|
||||
DO $roles$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_roles WHERE rolname = 'missioncore_normalizer'
|
||||
) THEN
|
||||
CREATE ROLE missioncore_normalizer LOGIN;
|
||||
END IF;
|
||||
END
|
||||
$roles$;
|
||||
|
||||
ALTER ROLE missioncore_normalizer PASSWORD :'ingest_password';
|
||||
GRANT CONNECT ON DATABASE :"database_name" TO missioncore_normalizer;
|
||||
GRANT USAGE ON SCHEMA public TO missioncore_normalizer;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON contour_telemetry_samples
|
||||
TO missioncore_normalizer;
|
||||
|
||||
DELETE FROM contour_telemetry_samples
|
||||
WHERE observed_at < CURRENT_TIMESTAMP - INTERVAL '30 days';
|
||||
SQL
|
||||
@@ -1,8 +1,54 @@
|
||||
# Mission Core Polygon: product definition and system requirements
|
||||
|
||||
Status: canonical working SRS, 2026-07-25.
|
||||
> Актуальная композиция от 02.10.2026: единый каталог, режим и ровер; ручной заезд локально, AI на Worker. См. [SIMULATION_WORKFLOW.md](SIMULATION_WORKFLOW.md). Описание прежнего разделения профилей ниже — история решений.
|
||||
|
||||
Ops source of truth:
|
||||
> Уточнение владельца 02.10.2026: интерактивное планирование маршрута теперь
|
||||
> локальное, с дисковым кэшем Gaussian-preview и collider. Физика, сенсоры,
|
||||
> inference и рендер выполняемого прогона остаются на Worker. Это заменяет
|
||||
> прежнее требование удалённого редактора; см. `AI_POLYGON_ROUTE_PLANNING.md`.
|
||||
|
||||
|
||||
Status: general qualification principles with a historical 2026-07-25
|
||||
Gazebo/PX4 implementation snapshot. Current-profile reconciliation: 2026-10-02.
|
||||
|
||||
## Current applicability — 2026-10-02
|
||||
|
||||
The active owner-directed development is **AI-полигон**: native Isaac 6.1 on
|
||||
Worker006, Gaussian appearance with separately checked collision geometry,
|
||||
a selected DCD-006 v020 visual model (1.163×0.905×0.734 m) with a provisional
|
||||
four-wheel differential contact proxy, and the shared AI composition. Worker owns
|
||||
physics, sensor rendering, inference, control and raw journals; the operator
|
||||
Mac receives video/compact telemetry and sends lifecycle commands. Physical
|
||||
VESC/ASVD work and the LCC Gaussian Mirror profile remain separate.
|
||||
|
||||
The current working purpose, evidence boundary, experiment protocol and next
|
||||
gates are in [AI Polygon workflow](AI_POLYGON_WORKFLOW.md), with read-only live
|
||||
verification in [the 2 October audit](audits/2026-10-02-simulation-state-review.md).
|
||||
[MISSIONCOR-83](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-83) owns current
|
||||
implementation/evaluation; MISSIONCOR-39 retains general architecture ownership.
|
||||
|
||||
The selected robot ID/profile hash is immutable per run. The native Worker
|
||||
verifies the shared PlayCanvas GLB and converts it to metre-scale Z-up USD;
|
||||
this does not constitute calibrated track mechanics or animated track links.
|
||||
New normally closed runs seal a Worker-local report and artifact SHA index;
|
||||
Core stores the compact report, and the operator reads it in the simulation
|
||||
workspace. Missing collision measurements remain null. Goal completion and
|
||||
duration expiry are distinct report outcomes.
|
||||
|
||||
Sections below preserve the July profile's architecture, evidence and proposed
|
||||
S0–S6 sequence. Gazebo/PX4/Ackermann, Linux-only placement, Nav2 and Unreal
|
||||
selection are **not prerequisites or current implementation claims** for the
|
||||
September Isaac profile. That profile uses its own `/api/v1/ai-polygon` contracts;
|
||||
integration into the earlier generic provider/qualification-report contracts
|
||||
has not been established. Historical gates cannot be inherited across profiles.
|
||||
|
||||
Source identity, declared clocks/frames, virtual-only authority, preserved
|
||||
failures and evidence-bound comparisons remain applicable. The next useful
|
||||
AI-profile gate is repeatable, reported navigation on a bounded scenario set.
|
||||
Two recorded completions of the same approximately 11 m paved task do not
|
||||
establish off-road autonomy. Proposed workflow gates are not completed features.
|
||||
|
||||
Historical July profile's Ops records:
|
||||
|
||||
- [MISSIONCOR-38](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-38) is the
|
||||
product epic and original simulation-branch scope.
|
||||
@@ -13,7 +59,8 @@ Ops source of truth:
|
||||
- [MISSIONCOR-41](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-41) is the
|
||||
active S1 lifecycle/authority implementation and qualification gate.
|
||||
|
||||
This document, ADR 0015, ADR 0016 and ADR 0017 are the repository truth. A material change
|
||||
This document's applicability section, the linked AI workflow, ADR 0015,
|
||||
ADR 0016 and ADR 0017 define the scoped repository truth. A material change
|
||||
to run kinds, authority, clocks, frames, source-of-record, provider boundaries,
|
||||
component placement or phase gates must update the ADR/SRS and MISSIONCOR-39
|
||||
together.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user