Compare commits

..
Author SHA1 Message Date
DCCONSTRUCTIONS 140b6002e0 Restore observed recovery through native Nav2 2026-10-08 11:11:12 +03:00
DCCONSTRUCTIONS 117e937906 Link project rules to the canonical Ops architecture record 2026-10-08 11:04:30 +03:00
DCCONSTRUCTIONS 8bf6571ce2 Keep operator telemetry live-only with bounded volatile state 2026-10-08 10:54:35 +03:00
DCCONSTRUCTIONS 15a60e7e31 chore: consolidate Mission Core workspace and bound local build storage 2026-10-08 10:22:16 +03:00
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00
DCCONSTRUCTIONS 97614742bb Accept qualified ARNavi VPS 0.2.5 v1 compatibility contract 2026-10-01 14:38:42 +03:00
DCCONSTRUCTIONS a78fdeae66 Accept qualified ARNavi VPS 0.2.4 client contract 2026-10-01 09:13:14 +03:00
DCCONSTRUCTIONS b17ff5554e Preserve ARNavi full settings support through VPS 0.2.3 2026-10-01 01:07:13 +03:00
DCCONSTRUCTIONS 43b63e8eb9 Accept shared B2 VPS 0.2.1 for equipment settings and commands 2026-09-30 22:43:12 +03:00
DCCONSTRUCTIONS df36e92500 Accept ARNavi VPS 0.2.0 through the existing client contract 2026-09-30 15:34:24 +03:00
DCCONSTRUCTIONS 6dd652f71e Keep B2 client fixes and move VPS implementation to its standalone repository 2026-09-29 12:41:21 +03:00
DCCONSTRUCTIONS 03d44d0fb1 docs(handoff): record ARNavi cards, source revisions and closeout checks 2026-09-28 18:52:10 +03:00
DCCONSTRUCTIONS 21f46ac38a docs(arnavi): consolidate server and tracker handoff with qualification evidence 2026-09-28 18:44:50 +03:00
DCCONSTRUCTIONS 67ae1f4d77 feat(map): show independent tracker positions and recover unavailable layers 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS 031e01a99b feat(ui): add tracker provisioning, SIM policies, command history and firmware archive 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS f3a7592d90 feat(fleet): integrate independent trackers, VPS pairing and recoverable commands 2026-09-28 18:44:12 +03:00
DCCONSTRUCTIONS d684eb7e05 feat(vps): ship durable ARNavi host with reproducible install and recovery 2026-09-28 18:43:39 +03:00
DCCONSTRUCTIONS b6efae3272 feat(arnavi): add qualified B2 protocols, USB provisioning and SIM evidence 2026-09-28 18:43:32 +03:00
DCCONSTRUCTIONS fb33a6d45c fix(ui): label connectivity checks as Проверка состояния 2026-09-25 23:26:51 +03:00
DCCONSTRUCTIONS 0fb117fe7b docs: record worker recovery acceptance and deployment boundaries 2026-09-25 23:25:02 +03:00
DCCONSTRUCTIONS e2cf3078b6 fix(ui): unify connectivity labels and move contour refresh to header 2026-09-25 23:24:45 +03:00
DCCONSTRUCTIONS f3640026cf fix(telemetry): recover worker agent and Tailscale transport automatically 2026-09-25 23:24:27 +03:00
DCCONSTRUCTIONS bd5873ef34 fix(fleet): derive contour status from registered nodes and remove obsolete tabs 2026-09-25 22:28:42 +03:00
DCCONSTRUCTIONS aecae4a986 feat(fleet): edit apparatus name independently of onboard availability 2026-09-25 22:28:22 +03:00
DCCONSTRUCTIONS ee7576b7b4 refactor(fleet-ui): consolidate apparatus header and computer status 2026-09-25 21:58:57 +03:00
DCCONSTRUCTIONS e2b0d839eb feat(fleet-ui): organize apparatus equipment beneath its computer 2026-09-25 21:38:25 +03:00
DCCONSTRUCTIONS d2ec9e95b1 feat(fleet): replace onboard computer without replacing apparatus 2026-09-25 21:38:13 +03:00
DCCONSTRUCTIONS 8283f9ba85 feat(observation): expose offline sources with transparent viewport headers 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS db3b1d7b67 fix(navigation): return repeated section selections to their entry view 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS a993eda6b8 feat(rover): add live scene and material editing with environment migration 2026-09-25 19:13:52 +03:00
603 changed files with 155827 additions and 3424 deletions
+35
View File
@@ -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, black-box sensor. Preserve the device, the host, the working LAN, raw evidence,
and the boundary between Mission Core and vendor-specific integration code. 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 ## Non-negotiable safety boundaries
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE - Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
+30
View File
@@ -1,5 +1,10 @@
# NODEDC MISSION CORE # NODEDC MISSION CORE
ARNavi B2 VPS server development moved to
[NODEDC_MISSION_CORE_ARNAVI-VPS](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS).
Mission Core retains its B2 client and existing pairing; see the
[repository boundary](docs/arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning, NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning,
recording, and integration platform for NODEDC autonomous systems. This recording, and integration platform for NODEDC autonomous systems. This
repository is the canonical early-stage monorepo: it contains the Mission Core repository is the canonical early-stage monorepo: it contains the Mission Core
@@ -202,6 +207,12 @@ See [the Dataset Gateway plan](docs/14_LIDAR_DATASET_GATEWAY.md),
## Simulation Polygon ## 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 Mission Core now has a parallel Polygon product branch for reproducible
autonomy qualification. Mission Core owns scenarios, qualification-run autonomy qualification. Mission Core owns scenarios, qualification-run
lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4 lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4
@@ -627,3 +638,22 @@ Real captures, projects, router metadata, serials, credentials, maps, images,
and logs under `.runtime/`, canonical evidence roots and legacy `sessions/` are and logs under `.runtime/`, canonical evidence roots and legacy `sessions/` are
ignored by normal Git. Redacted manifests and SHA-256 inventories are committed; ignored by normal Git. Redacted manifests and SHA-256 inventories are committed;
encrypted/replicated artifact storage remains a deployment decision. 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.
+11 -1
View File
@@ -21,7 +21,8 @@
"playcanvas": "2.21.4", "playcanvas": "2.21.4",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"three": "0.185.1" "three": "0.185.1",
"three-mesh-bvh": "0.9.15"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
@@ -1893,6 +1894,15 @@
"integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==", "integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
"license": "MIT" "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": { "node_modules/tinyglobby": {
"version": "0.2.17", "version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+2 -1
View File
@@ -25,7 +25,8 @@
"playcanvas": "2.21.4", "playcanvas": "2.21.4",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"three": "0.185.1" "three": "0.185.1",
"three-mesh-bvh": "0.9.15"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
@@ -0,0 +1,174 @@
{
"schema_version": "missioncore.rover-motion/v1",
"source_scene": "DCD-006_rover_v020.blend",
"source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79",
"source_saved": false,
"visual_sha256": "4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e",
"forward_axis": "+X",
"up_axis": "Y",
"track_centres_m": {
"L": 0.3425,
"R": -0.3425
},
"track_width_m": 0.685,
"shift_m": [
-0.05350000038743019,
0.0,
0.0
],
"length_m": 2.222,
"pitch_m": 0.0505,
"phase_m": 0.03069696662739778,
"segments": [
[
"arc",
0,
0.060539054924808725,
[
-0.16593354688111153,
0.32184557191629776,
0.0655,
2.3390854961098873
]
],
[
"line",
0.060539054924808725,
0.5760464371429339,
[
-0.15575880346026824,
0.3865504758751169,
0.9878611291422765,
-0.1553395942113481,
0.15533959421134813,
0.9878611291422766
]
],
[
"arc",
0.6365854920677426,
0.15172294911931034,
[
0.40182697,
0.22413776,
0.07382606110411796,
1.4148251155784564
]
],
[
"line",
0.7883084411870529,
0.1629407568053742,
[
0.46102862009488454,
0.18003048254840684,
-0.5974486081464921,
-0.8019072020027126,
0.8019072020027126,
-0.5974486081464921
]
],
[
"arc",
0.9512491979924271,
0.06094648310379254,
[
0.31115497,
0.0885,
0.0655,
-0.6403156687217281
]
],
[
"line",
1.0121956810962196,
0.7185584980197575,
[
0.31115497,
0.022999999999999993,
-1.0,
0.0,
-0.0,
-1.0
]
],
[
"arc",
1.730754179115977,
0.15545137821999958,
[
-0.40740352801975754,
0.0885,
0.0655,
-1.5707963267948966
]
],
[
"line",
1.8862055573359766,
0.33579444266402353,
[
-0.45291987081346463,
0.1356010885085021,
0.719100587916063,
0.6949059968504895,
-0.6949059968504895,
0.719100587916063
]
]
],
"link_count": 44,
"wheels": [
{
"node": "R_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "R_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_DRIVE",
"radius_m": 0.07233592163526643
},
{
"node": "L_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "L_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_DRIVE",
"radius_m": 0.07233592163526643
}
],
"dimensions_m": [
1.1630001068115234,
0.9049999713897705,
0.7378441095352173
],
"minimum_m": [
-0.5814999938011169,
-0.45249998569488525,
-0.003844098187983036
],
"method": "44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; no track contact dynamics"
}
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -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>
+26 -10
View File
@@ -152,6 +152,7 @@ export default function App() {
contentExpanded: true, contentExpanded: true,
}); });
const [navigationRevision, setNavigationRevision] = useState(0);
const [activeRoot, setActiveRoot] = useState<RootId | null>( const [activeRoot, setActiveRoot] = useState<RootId | null>(
polygonDatasetRoute.active ? "data" : null, polygonDatasetRoute.active ? "data" : null,
); );
@@ -159,6 +160,7 @@ export default function App() {
const [launchProfile, setLaunchProfile] = useState<WorkspaceLaunchProfile>('direct'); const [launchProfile, setLaunchProfile] = useState<WorkspaceLaunchProfile>('direct');
const [sourceUrl, setSourceUrl] = useState(""); const [sourceUrl, setSourceUrl] = useState("");
const [workspaceHeaderToolsHost, setWorkspaceHeaderToolsHost] = useState<HTMLDivElement | null>(null); const [workspaceHeaderToolsHost, setWorkspaceHeaderToolsHost] = useState<HTMLDivElement | null>(null);
const [workspaceHeaderTitleHost, setWorkspaceHeaderTitleHost] = useState<HTMLSpanElement | null>(null);
const [recordedReplay, setRecordedReplay] = useState<ObservationSessionReplayLaunch | null>(null); const [recordedReplay, setRecordedReplay] = useState<ObservationSessionReplayLaunch | null>(null);
const [recordedReplayLabel, setRecordedReplayLabel] = useState<string | null>(null); const [recordedReplayLabel, setRecordedReplayLabel] = useState<string | null>(null);
const [replayTransitioning, setReplayTransitioning] = useState(false); const [replayTransitioning, setReplayTransitioning] = useState(false);
@@ -457,6 +459,17 @@ export default function App() {
workspace.openView(viewId); workspace.openView(viewId);
}; };
// Explicit menu navigation always returns to that workspace's entry screen.
const openNavigationView = (viewId: string) => {
if (!workspaceById(viewId)) return;
setNavigationRevision(value => value + 1);
sessionOverview.close();
setSourceWindowOpen(false);
setDisplayWindowOpen(false);
setLayerInspectorOpen(false);
openView(viewId);
};
const openSource = () => { const openSource = () => {
if (!sceneWorkspaceActive) return; if (!sceneWorkspaceActive) return;
setSourceDraft(sourceUrl); setSourceDraft(sourceUrl);
@@ -645,11 +658,8 @@ export default function App() {
return () => window.clearTimeout(timer); return () => window.clearTimeout(timer);
}, [layoutSaveNotice]); }, [layoutSaveNotice]);
const [fleetCreateRequest, setFleetCreateRequest] = useState(0);
const sessionOverview = useSessionOverviewMode(activeDefinition?.kind === "recordings"); const sessionOverview = useSessionOverviewMode(activeDefinition?.kind === "recordings");
const onAddVehicle = useCallback(() => setFleetCreateRequest(value => value + 1), []);
const contentActions = useApplicationPanelActions({ const contentActions = useApplicationPanelActions({
onAddVehicle,
definition: activeDefinition, definition: activeDefinition,
refreshRuntime: runtime.refresh, refreshRuntime: runtime.refresh,
resetConnectionScenario: runtime.resetConnectionScenario, resetConnectionScenario: runtime.resetConnectionScenario,
@@ -729,6 +739,7 @@ export default function App() {
<SystemNavigationPanel <SystemNavigationPanel
title={currentRoot.title} title={currentRoot.title}
onAdd={computeContourSettings.openCreate} onAdd={computeContourSettings.openCreate}
onNavigateRoot={() => openNavigationView("modules")}
onClose={workspace.closeNavigation} onClose={workspace.closeNavigation}
/> />
) : currentRoot ? ( ) : currentRoot ? (
@@ -755,7 +766,7 @@ export default function App() {
icon: <Icon name={item.icon} />, icon: <Icon name={item.icon} />,
}))} }))}
activeId={workspace.activeView ?? undefined} activeId={workspace.activeView ?? undefined}
onItemChange={openView} onItemChange={openNavigationView}
footer={ footer={
<> <>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true"> <span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
@@ -765,7 +776,8 @@ export default function App() {
{rootWorkspaces.length}{" "} {rootWorkspaces.length}{" "}
{rootWorkspaces.length === 1 {rootWorkspaces.length === 1
? "рабочая поверхность" ? "рабочая поверхность"
: "рабочих поверхностей"} : rootWorkspaces.length >= 2 && rootWorkspaces.length <= 4
? "рабочие поверхности" : "рабочих поверхностей"}
</span> </span>
</> </>
} }
@@ -776,7 +788,9 @@ export default function App() {
key={activeDefinition.id} key={activeDefinition.id}
eyebrow={activeDefinition.eyebrow} eyebrow={activeDefinition.eyebrow}
title={ title={
activeDefinition.kind === "recordings" activeDefinition.kind === "vehicles"
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
: activeDefinition.kind === "recordings"
&& replayPresented && replayPresented
&& recordedReplayLabel && recordedReplayLabel
? `${activeDefinition.title}: ${recordedReplayLabel}` ? `${activeDefinition.title}: ${recordedReplayLabel}`
@@ -822,16 +836,18 @@ export default function App() {
/> />
) : activeDefinition.kind === "missions" ? ( ) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} /> <div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" ? <div ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? ( ) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
<StatusBadge tone="neutral">Offline evaluation</StatusBadge> <StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? ( ) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control laboratoryAnnotation.control
) : activeDefinition.kind === "observatory" ? ( ) : activeDefinition.kind === "observatory" ? (
<StatusBadge tone="neutral">Только наблюдение</StatusBadge> <StatusBadge tone="neutral">Только наблюдение</StatusBadge>
) : activeDefinition.kind === "contour-health" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.root === "system" ? ( ) : activeDefinition.root === "system" ? (
<SystemWorkspaceSelector <SystemWorkspaceSelector
value={activeDefinition.id} value={activeDefinition.id}
onChange={openView} onChange={openNavigationView}
/> />
) : ( ) : (
<StatusBadge tone="warning">Интерфейс готов</StatusBadge> <StatusBadge tone="warning">Интерфейс готов</StatusBadge>
@@ -840,7 +856,7 @@ export default function App() {
utilityActions={contentActions} utilityActions={contentActions}
onClose={workspace.closeView} onClose={workspace.closeView}
> >
<PlanningCaptureGuard <PlanningCaptureGuard key={`${activeDefinition.id}:${navigationRevision}`}
enabled={launchProfile === 'direct' && (activeDefinition.kind === 'device' || activeDefinition.kind === 'spatial')} enabled={launchProfile === 'direct' && (activeDefinition.kind === 'device' || activeDefinition.kind === 'spatial')}
onResume={() => openView('local-device', 'planning')} onResume={() => openView('local-device', 'planning')}
> >
@@ -860,8 +876,8 @@ export default function App() {
<WorkspaceRenderer <WorkspaceRenderer
launchProfile={launchProfile} launchProfile={launchProfile}
definition={activeDefinition} definition={activeDefinition}
fleetCreateRequest={fleetCreateRequest}
headerToolsHost={workspaceHeaderToolsHost} headerToolsHost={workspaceHeaderToolsHost}
headerTitleHost={workspaceHeaderTitleHost}
state={activeRuntimeState} state={activeRuntimeState}
backendStatus={runtime.backendStatus} backendStatus={runtime.backendStatus}
sourceUrl={effectiveSourceUrl} sourceUrl={effectiveSourceUrl}
@@ -0,0 +1,8 @@
import {createPortal} from 'react-dom';
import {Icon,IconButton} from '@nodedc/ui-react';
/** A nested workspace returns through the shared panel header. */
export function WorkspaceBackButton({label,onClick,host}:{label:string;onClick:()=>void;host?:HTMLElement|null}) {
const button=<IconButton label={label} onClick={onClick}><Icon name="chevron-left"/></IconButton>;
return host?createPortal(button,host):button;
}
@@ -265,6 +265,8 @@ LaboratoryMetricEvidenceSceneHandle,
showCurrentIncrement: boolean; showCurrentIncrement: boolean;
showLocalSurface: boolean; showLocalSurface: boolean;
showRollingMap: boolean; showRollingMap: boolean;
showReferenceGeometry?: boolean;
showRenderStats?: boolean;
showLowStep?: boolean; showLowStep?: boolean;
pointSemanticClassIds?: readonly (number | null)[]; pointSemanticClassIds?: readonly (number | null)[];
semanticClasses?: readonly RecordedEvidenceSemanticClass[]; semanticClasses?: readonly RecordedEvidenceSemanticClass[];
@@ -287,6 +289,8 @@ LaboratoryMetricEvidenceSceneHandle,
showLocalSurface, showLocalSurface,
showRollingMap, showRollingMap,
showLowStep = true, showLowStep = true,
showReferenceGeometry = true,
showRenderStats = true,
pointSemanticClassIds, pointSemanticClassIds,
semanticClasses, semanticClasses,
semanticPalette, semanticPalette,
@@ -746,6 +750,7 @@ LaboratoryMetricEvidenceSceneHandle,
if (!host || !content) return; if (!host || !content) return;
clearGroup(content); clearGroup(content);
if (!showReferenceGeometry) { requestRenderRef.current(); return; }
const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM; const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM;
const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2; const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2;
const corridorMesh = new THREE.Mesh( const corridorMesh = new THREE.Mesh(
@@ -806,6 +811,7 @@ LaboratoryMetricEvidenceSceneHandle,
content.add(grid); content.add(grid);
requestRenderRef.current(); requestRenderRef.current();
}, [ }, [
showReferenceGeometry,
corridor.forwardLengthM, corridor.forwardLengthM,
corridor.halfWidthM, corridor.halfWidthM,
corridor.rearMarginM, corridor.rearMarginM,
@@ -912,7 +918,7 @@ LaboratoryMetricEvidenceSceneHandle,
{renderError ? <p>{renderError}</p> : null} {renderError ? <p>{renderError}</p> : null}
</div> </div>
<div className="laboratory-metric-evidence-scene__legend"> <div className="laboratory-metric-evidence-scene__legend">
{renderStats ? ( {showRenderStats && renderStats ? (
<span <span
data-decision="performance" data-decision="performance"
title="CPU-время отправки последнего WebGL render pass; это не GPU timer. В покое сцена не перерисовывается." 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)); }
@@ -6,40 +6,41 @@ import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
import type {RoverController} from '../../core/fleet/useRoverControl'; import type {RoverController} from '../../core/fleet/useRoverControl';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation'; import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import './rover.css'; import './rover.css';
const Scene=lazy(()=>import('./playcanvas/PlayCanvasViewer')); const Scene=lazy(()=>import('./editor/RoverScene'));
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'}; const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'};
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
const storage=`missioncore.rover-view.v1:${vehicleID}`; const storage=`missioncore.rover-view.v1:${vehicleID}`;
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}}); const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set()); const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
const [editing,setEditing]=useState(false);
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading'); const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null); const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]); const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]);
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]); useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
useEffect(()=>{if(!active)stop();},[active,stop]); useEffect(()=>{if(!active)stop();},[active,stop]);
useEffect(()=>{ useEffect(()=>{
if(!c.ready||!active||open||!stage.current)return; if(!c.ready||!active||open||editing||!stage.current)return;
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop}); const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
input.current=binding;c.setInputGuard(binding.valid); input.current=binding;c.setInputGuard(binding.valid);
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;}; return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
},[c.ready,active,open,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]); },[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
const showSettings=()=>{stop();setOpen(true);}; const showSettings=()=>{setEditing(false);stop();setOpen(true);};
const preparing=c.pending||(c.armed&&!c.ready); const preparing=c.pending||(c.armed&&!c.ready);
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null; const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null;
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral'; const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение'); const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
return <> return <>
{createPortal(<IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton>,header.actionsTarget)} {createPortal(<><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)} {createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером" <div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}> onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера"> {settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера">
<Suspense fallback={null}><Scene modelUrl="/rover-scene/dcd006-v020.glb" cameraAutoRotate={false} onModelState={setModelState}/></Suspense> <Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>} {modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>} </LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
<div className="rover-view__status"><StatusBadge tone={tone}>{status}</StatusBadge></div> <div className="rover-view__status"><StatusBadge tone={editing?'neutral':tone}>{editing?'Редактирование сцены':status}</StatusBadge></div>
{c.ready&&<div className="rover-view__controls"> {c.ready&&!editing&&<div className="rover-view__controls">
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}> <div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)} {keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
disabled={!c.ready||!active} pressed={held.has(code)} disabled={!c.ready||!active} pressed={held.has(code)}
@@ -50,9 +51,9 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
</div> </div>
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span> <span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
</div>} </div>}
<div className="rover-view__authority"> {!editing&&<div className="rover-view__authority">
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>} {c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
</div> </div>}
</div> </div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings"> <Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/> <Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
@@ -0,0 +1,23 @@
import {LutField} from './LutField';
import {useRef} from 'react';
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
const groups=[...new Set(environmentFields.map(f=>f.group))];
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>;
}
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
if(f.type==='action')return <Button onClick={onResetCamera}>Сбросить камеру</Button>;
if(f.type==='toggle')return <Switch label={f.label} checked={!!value} disabled={disabled} onChange={onChange}/>;
if(f.type==='color')return <ControlRow label={f.label}><ColorField label={f.label} value={String(value)} disabled={disabled} onChange={onChange}/></ControlRow>;
if(f.type==='select')return <InspectorSelectField label={f.label} value={String(value)} options={f.options??[]} disabled={disabled} onChange={onChange}/>;
if(f.type==='doubleSlider'){const range=value as number[];return <>{['Начало тумана, м','Конец тумана, м'].map((label,i)=><RangeControl key={i} label={label} min={f.min??0} max={f.max??100} step={f.step??1} exactValueBounds={{min:f.min,max:f.max}} value={range[i]} disabled={disabled} onChange={v=>onChange(i?[range[0],v]:[v,range[1]])}/>)}</>;}
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
}
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){
const input=useRef<HTMLInputElement>(null);
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
}
@@ -0,0 +1,7 @@
import {useRef,useState} from 'react';
import {Button,Icon,IconButton} from '@nodedc/ui-react';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
export function LutField({value,onChange,onError}:{value:string|null|undefined;onChange:(value:string|null)=>void;onError:(error:string)=>void}){
const input=useRef<HTMLInputElement>(null),[loading,setLoading]=useState(false);
return <div className="rover-scene-fields"><p className="rover-scene-note">PNG 256 × 16 · горизонтальная таблица 16³</p><div className="rover-scene-actions"><Button loading={loading} onClick={()=>input.current?.click()}>{value?'Заменить LUT':'Загрузить LUT'}</Button>{value&&<IconButton label="Удалить LUT" onClick={()=>onChange(null)}><Icon name="trash"/></IconButton>}</div><input hidden ref={input} type="file" accept="image/png" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setLoading(true);try{const bitmap=await createImageBitmap(file);const valid=bitmap.width===256&&bitmap.height===16;bitmap.close();if(!valid||file.type!=='image/png')throw new Error('Нужна PNG-таблица LUT размером 256 × 16.');onChange((await textureFromFile(file)).data);}catch(error){onError(error instanceof Error?error.message:'Не удалось прочитать LUT.');}finally{setLoading(false);}}}/></div>;
}
@@ -0,0 +1,17 @@
import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
]}/><Button onClick={onReset}>Исходный материал</Button></>;
}
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
}
@@ -0,0 +1,38 @@
import {useCallback,useEffect,useState,type CSSProperties} from 'react';
import {Button,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,Window} from '@nodedc/ui-react';
import {assignMaterial,createMaterial,changeField,defaultScene,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
import PlayCanvasViewer from '../playcanvas/PlayCanvasViewer';
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
import {MaterialInspector} from './MaterialInspector';
import './sceneEditor.css';
export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
const scene=useSceneDocument(vehicleID),[palette,setPalette]=useState(false),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
const [selectedGroup,setSelectedGroup]=useState<string|null>(null);
const pick=useCallback((id:string,group?:string)=>{setSelected(id);if(group)setSelectedGroup(group);setMaterialOpen(true);},[]);
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=128){scene.setError('В сцене может быть не больше 128 материалов.');return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{const next={...scene.document,materials:{...scene.document.materials,[id]:{...scene.document.materials[id],...patch}}};if(textureBytes(next)>28_000_000){scene.setError('Суммарный объём текстур превышает 20 МБ. Удалите ненужную текстуру.');return;}scene.update(doc=>({...doc,materials:{...doc.materials,[id]:{...doc.materials[id],...patch}}}));};
useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]);
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
const material=selected?scene.document.materials[selected]:null;
return <>
<LoadingRegion className="rover-view__scene" style={{bottom:editing&&palette?150:0}} loading={!scene.ready} label="Загрузка настроек сцены">
{scene.ready&&<PlayCanvasViewer modelUrl="/rover-scene/dcd006-v020.glb?materials-v2" postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} materials={scene.document.materials} assignments={scene.document.assignments} editing={editing} onMaterialPick={pick} onModelState={onModelState} onTextureState={setTextureState}/>}
</LoadingRegion>
{editing&&<>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
{palette&&<GlassSurface className="rover-material-palette"><div className="rover-material-palette__header"><span>Материалы · выберите в палитре или на модели</span><IconButton label="Скрыть палитру материалов" onClick={()=>setPalette(false)}><Icon name="close"/></IconButton></div><div className="rover-material-palette__items">{Object.entries(scene.document.materials).map(([id,m])=><Button key={id} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':m.color,'--material-gloss':1-m.roughness} as CSSProperties}/><span>{m.name}</span></span></Button>)}<Button aria-label="Добавить материал" title="Добавить материал" onClick={addMaterial}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button></div></GlassSurface>}
</>}
<Window open={editing&&environment} title="Окружение сцены" placement="end" draggable onClose={()=>setEnvironment(false)} footer={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaultScene().postFx}))}/>}>
<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>
</Window>
<Window open={editing&&materialOpen&&!!material} title={material?.name||'Материал'} subtitle="Материал сцены" placement="end" draggable style={{position:'fixed',left:'var(--nodedc-space-4)',top:'6rem',right:'auto'}} onClose={()=>setMaterialOpen(false)}>
{material&&selected&&<>
{selectedGroup?<div className="rover-scene-fields"><p className="rover-scene-note">Выбранная группа: {defaultScene().materials[selectedGroup]?.name}</p><Button disabled={(scene.document.assignments[selectedGroup]??selectedGroup)===selected} onClick={()=>scene.update(doc=>assignMaterial(doc,selectedGroup,selected))}>Назначить выбранной группе</Button></div>:<p className="rover-scene-note">Нажмите на деталь в сцене, затем выберите материал в палитре, чтобы назначить его группе.</p>}
<MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaultScene().materials[selected]??createMaterial(defaultScene(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/>
</>}
</Window>
<ToastStack items={scene.error?[{id:'rover-scene-error',tone:'error',title:'Настройки сцены',description:scene.error}]:[]} onDismiss={()=>scene.setError('')}/>
</>;
}
@@ -0,0 +1,17 @@
.rover-scene-tools {position:absolute;right:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3));}
.rover-scene-tools__surface,.rover-scene-actions {display:flex;align-items:center;gap:var(--nodedc-space-2);flex-wrap:wrap;}
.rover-scene-tools__surface {padding:var(--nodedc-space-1);}
.rover-scene-save {position:absolute;left:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + 3rem);pointer-events:none;}
.rover-material-palette {position:absolute;bottom:var(--nodedc-space-3);left:var(--nodedc-space-3);right:var(--nodedc-space-3);padding:var(--nodedc-space-2);}
.rover-material-palette__header {display:flex;align-items:center;justify-content:space-between;gap:var(--nodedc-space-2);font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);}
.rover-material-palette__items {display:flex;gap:var(--nodedc-space-2);overflow:auto;}
.rover-material-palette__items > * {flex:0 0 auto;}
.rover-material-tile {display:grid;justify-items:center;gap:var(--nodedc-space-1);width:100px;white-space:normal;font-size:var(--nodedc-font-size-xs);}
/* Domain material thumbnail: a swatch, not a replacement control. */
.rover-material-swatch {display:block;width:38px;height:38px;border-radius:50%;background:radial-gradient(ellipse at 35% 25%,#ffffffb0,transparent 45%),radial-gradient(ellipse at 60% 75%,transparent,var(--material-color) 70%),var(--material-color);box-shadow:inset -5px -5px 12px #0008;}
.rover-scene-fields {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-scene-note {font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);}
.rover-scene-texture__row {display:flex;gap:var(--nodedc-space-2);align-items:center;min-width:0;}
.rover-scene-texture__row img {width:36px;height:36px;object-fit:cover;}
.rover-scene-texture__row .nodedc-button {min-width:0;overflow:hidden;}
@container(max-width:460px){.rover-scene-save{top:calc(var(--observation-overlay-header-space, 0px) + 4.5rem)}.rover-material-tile{width:82px}.rover-material-palette__header>span{max-width:210px}}
@@ -11,6 +11,13 @@
"No fallback to a different vehicle", "No fallback to a different vehicle",
"Removed unused node-editor type helper; rendering settings unchanged", "Removed unused node-editor type helper; rendering settings unchanged",
"Observe the host pane on resize; preserve responsive canvas CSS sizing", "Observe the host pane on resize; preserve responsive canvas CSS sizing",
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect" "Frame the complete rover using the donor 28-degree FOV and current viewport aspect",
] "Scene editing uses canonical modeless Design Guideline inspectors; all 109 donor camera/post-FX fields retained as a versioned field catalog",
"Original NodeDC environment preset restored by owner request; editor reset changes environment only",
"Semantic material groups, UV texture editing, GPU surface picking and bounded texture disposal",
"Live grid step/diameter and ambient fill added; wireframe application and LUT loading corrected",
"Responsive scene framing and palette space without drive authority"
],
"inspector_source_sha256": "8f1df16bd8c12fb1b8481480690ff4ed0e6b2645cb3fba527888c0f9acb59192",
"model_revision": "dcd006-v020-materials-v2"
} }
@@ -3,13 +3,16 @@ import * as pc from 'playcanvas'
import { buildSceneTree } from './sceneTree' import { buildSceneTree } from './sceneTree'
import { mergePostFxDefaults, type PostFxSettings } from './playcanvasPostFx' import { mergePostFxDefaults, type PostFxSettings } from './playcanvasPostFx'
import {useLutTexture} from './useLutTexture'
import {useSceneMaterials,type SceneMaterialsProps} from './useSceneMaterials'
const DEFAULT_MODEL_URL = '' const DEFAULT_MODEL_URL = ''
const PIXELFORMAT_RGBA8 = (pc as any).PIXELFORMAT_RGBA8 ?? 7 const PIXELFORMAT_RGBA8 = (pc as any).PIXELFORMAT_RGBA8 ?? 7
const PIXELFORMAT_111110F = (pc as any).PIXELFORMAT_111110F ?? 18 const PIXELFORMAT_111110F = (pc as any).PIXELFORMAT_111110F ?? 18
const PIXELFORMAT_RGBA16F = (pc as any).PIXELFORMAT_RGBA16F ?? 12 const PIXELFORMAT_RGBA16F = (pc as any).PIXELFORMAT_RGBA16F ?? 12
const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14 const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
export type PlayCanvasViewerProps = { export type PlayCanvasViewerProps = SceneMaterialsProps & {
modelUrl: string | null modelUrl: string | null
postFx?: Partial<PostFxSettings> | null postFx?: Partial<PostFxSettings> | null
viewportSize?: { width: number; height: number } viewportSize?: { width: number; height: number }
@@ -390,16 +393,9 @@ function toColor(value: ColorInput, fallback?: pc.Color): pc.Color {
} }
function setWireframeForScene(app: pc.Application, enabled: boolean) { function setWireframeForScene(app: pc.Application, enabled: boolean) {
const renders = app.root.findComponents('render') as any[] const root = app.root.findByName('ModelRoot') as pc.Entity | null
for (const r of renders) { for (const mi of collectMeshInstances(root)) {
const meshInstances = r?.meshInstances ?? [] mi.renderStyle = enabled ? pc.RENDERSTYLE_WIREFRAME : pc.RENDERSTYLE_SOLID
for (const mi of meshInstances) {
const mat = mi.material as any
if (mat && 'wireframe' in mat) {
mat.wireframe = enabled
mat.update?.()
}
}
} }
} }
@@ -805,7 +801,7 @@ function applyPostFx(
} }
frame.rendering.renderTargetScale = fx.rendering.renderTargetScale frame.rendering.renderTargetScale = fx.rendering.renderTargetScale
frame.rendering.samples = Number.isFinite(overrides?.samples) ? Number(overrides?.samples) : fx.rendering.samples frame.rendering.samples = Number.isFinite(overrides?.samples) ? Number(overrides?.samples) : fx.rendering.samples
frame.rendering.sceneColorMap = true frame.rendering.sceneColorMap = !!fx.rendering.sceneColorMap
frame.rendering.sceneDepthMap = !!fx.rendering.sceneDepthMap frame.rendering.sceneDepthMap = !!fx.rendering.sceneDepthMap
frame.rendering.toneMapping = fx.rendering.toneMapping frame.rendering.toneMapping = fx.rendering.toneMapping
frame.rendering.sharpness = fx.rendering.sharpness frame.rendering.sharpness = fx.rendering.sharpness
@@ -882,6 +878,7 @@ function applyPostFx(
export default function PlayCanvasViewer({ export default function PlayCanvasViewer({
modelUrl, modelUrl,
materials, assignments, editing, onMaterialPick, onTextureState,
postFx, postFx,
viewportSize, viewportSize,
onSceneReady, onSceneReady,
@@ -928,7 +925,11 @@ export default function PlayCanvasViewer({
const [skyboxVersion, setSkyboxVersion] = useState(0) const [skyboxVersion, setSkyboxVersion] = useState(0)
const [modelVersion, setModelVersion] = useState(0) const [modelVersion, setModelVersion] = useState(0)
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,editing,onMaterialPick,onTextureState})
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx]) const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
useLutTexture(appRef,cameraFrameRef,lutTextureRef,fx.lut.textureUrl,appReady,lutError)
useEffect(() => { useEffect(() => {
cameraStateRef.current = cameraState ?? null cameraStateRef.current = cameraState ?? null
@@ -962,7 +963,7 @@ export default function PlayCanvasViewer({
if (bounds && orbit) { if (bounds && orbit) {
const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360 const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * w / h) const horizontal = Math.atan(Math.tan(vertical) * w / h)
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1)) orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
} }
}, []) }, [])
@@ -1112,6 +1113,8 @@ export default function PlayCanvasViewer({
`, `,
fragmentGLSL: ` fragmentGLSL: `
uniform vec2 uHalfExtents; uniform vec2 uHalfExtents;
uniform float uGridStep;
uniform float uGridRadius;
uniform vec3 uColorX; uniform vec3 uColorX;
uniform vec3 uColorZ; uniform vec3 uColorZ;
uniform vec3 uColorMain; uniform vec3 uColorMain;
@@ -1182,7 +1185,9 @@ export default function PlayCanvasViewer({
void main(void) { void main(void) {
vec2 uv = uv0; vec2 uv = uv0;
vec2 pos = (uv * 2.0 - 1.0) * uHalfExtents; vec2 worldPos = (uv * 2.0 - 1.0) * uHalfExtents;
if (length(worldPos) > uGridRadius) discard;
vec2 pos = worldPos / uGridStep;
vec2 ddx = dFdx(pos); vec2 ddx = dFdx(pos);
vec2 ddy = dFdy(pos); vec2 ddy = dFdy(pos);
@@ -1262,7 +1267,7 @@ export default function PlayCanvasViewer({
float fadeEnd = max(0.0, uFadeEnd); float fadeEnd = max(0.0, uFadeEnd);
float fade = 1.0; float fade = 1.0;
if (fadeEnd > fadeStart && fadeEnd > 0.0) { if (fadeEnd > fadeStart && fadeEnd > 0.0) {
float d = length(pos); float d = length(worldPos);
fade = 1.0 - smoothstep(fadeStart, fadeEnd, d); fade = 1.0 - smoothstep(fadeStart, fadeEnd, d);
} }
outAlpha *= fade; outAlpha *= fade;
@@ -1312,6 +1317,8 @@ export default function PlayCanvasViewer({
gridMaterial.setParameter('uFadeStart', 0) gridMaterial.setParameter('uFadeStart', 0)
gridMaterial.setParameter('uFadeEnd', 0) gridMaterial.setParameter('uFadeEnd', 0)
gridMaterial.setParameter('uResolution', 2) gridMaterial.setParameter('uResolution', 2)
gridMaterial.setParameter('uGridStep', fx.grid.step)
gridMaterial.setParameter('uGridRadius', fx.grid.diameter / 2)
const gridHalfExtents = new pc.Vec2(500, 500) const gridHalfExtents = new pc.Vec2(500, 500)
gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y]) gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y])
gridMaterial.update() gridMaterial.update()
@@ -1528,7 +1535,7 @@ export default function PlayCanvasViewer({
const cam = cameraEntityRef.current?.camera const cam = cameraEntityRef.current?.camera
const vertical = (cam?.fov ?? 28) * Math.PI / 360 const vertical = (cam?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1)) const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1))
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1)) orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
} }
if (exposeSceneGraph || onSceneGraph) { if (exposeSceneGraph || onSceneGraph) {
@@ -1617,7 +1624,7 @@ export default function PlayCanvasViewer({
if (!aabb) return if (!aabb) return
orbit.setState({ orbit.setState({
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z }, pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
distance: Math.max(1.8, aabb.halfExtents.length() * 2.5), distance: Math.max(1.8,aabb.halfExtents.length() / Math.sin(Math.min(14*Math.PI/180,Math.atan(Math.tan(14*Math.PI/180)*(cameraEntityRef.current?.camera?.aspectRatio??1))))*.88),
azimuthDeg: 45, azimuthDeg: 45,
elevationDeg: 10, elevationDeg: 10,
}) })
@@ -1638,6 +1645,9 @@ export default function PlayCanvasViewer({
const gridVisible = !!fx.grid.enabled || !!fx.grid.dotsEnabled || !!fx.grid.crossEnabled const gridVisible = !!fx.grid.enabled || !!fx.grid.dotsEnabled || !!fx.grid.crossEnabled
grid.enabled = gridVisible grid.enabled = gridVisible
grid.setLocalScale(fx.grid.diameter,1,fx.grid.diameter)
mat.setParameter('uGridStep',fx.grid.step)
mat.setParameter('uGridRadius',fx.grid.diameter/2)
const cX = toColor(fx.grid.colorX) const cX = toColor(fx.grid.colorX)
const cZ = toColor(fx.grid.colorZ) const cZ = toColor(fx.grid.colorZ)
const cMain = toColor(fx.grid.colorMain) const cMain = toColor(fx.grid.colorMain)
@@ -1661,6 +1671,7 @@ export default function PlayCanvasViewer({
mat.setParameter('uFadeEnd', Math.max(0, Number(fx.grid.fadeEnd) || 0)) mat.setParameter('uFadeEnd', Math.max(0, Number(fx.grid.fadeEnd) || 0))
mat.update() mat.update()
}, [ }, [
fx.grid.step,fx.grid.diameter,
fx.grid.enabled, fx.grid.enabled,
fx.grid.colorX, fx.grid.colorX,
fx.grid.colorZ, fx.grid.colorZ,
@@ -1690,7 +1701,7 @@ export default function PlayCanvasViewer({
const app = appRef.current const app = appRef.current
if (!app) return if (!app) return
setWireframeForScene(app, fx.rendering.wireframe) setWireframeForScene(app, fx.rendering.wireframe)
}, [fx.rendering.wireframe]) }, [fx.rendering.wireframe,modelVersion])
useEffect(() => { useEffect(() => {
const frame: any = cameraFrameRef.current const frame: any = cameraFrameRef.current
@@ -1703,9 +1714,10 @@ export default function PlayCanvasViewer({
const app = appRef.current const app = appRef.current
if (!app) return if (!app) return
if (fx.lighting) { if (fx.lighting) {
app.scene.ambientLight = new pc.Color(fx.lighting.ambientIntensity,fx.lighting.ambientIntensity,fx.lighting.ambientIntensity)
app.scene.exposure = fx.lighting.exposure app.scene.exposure = fx.lighting.exposure
} }
}, [fx.lighting?.exposure]) }, [fx.lighting?.exposure,fx.lighting.ambientIntensity])
useEffect(() => { useEffect(() => {
const app = appRef.current const app = appRef.current
@@ -1924,6 +1936,8 @@ export default function PlayCanvasViewer({
envAtlasVersion, envAtlasVersion,
skyboxVersion, skyboxVersion,
modelVersion, modelVersion,
materials,
assignments,
fx.envAtlas.enabled, fx.envAtlas.enabled,
fx.envAtlas.background, fx.envAtlas.background,
fx.envAtlas.reflection, fx.envAtlas.reflection,
@@ -1,393 +1,2 @@
// Shared serializable contract; donor defaults remain available.
export type PostFxSettings = { export * from '../../../core/roverScene/postFx';
lighting: {
exposure: number
skyBoxIntensity: number
}
envAtlas: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
brightness: number
contrast: number
saturation: number
toneMapping: number
mip: number
rotation: number
}
skybox: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
mip: number
rotation: number
colorA: string
colorB: string
}
rendering: {
backgroundColor: string
wireframe: boolean
renderFormat: number
renderFormatFallback0: number
renderFormatFallback1: number
stencil: boolean
renderTargetScale: number
samples: number
sharpness: number
toneMapping: number
sceneColorMap: boolean
sceneDepthMap: boolean
fog: 'none' | 'linear' | 'exp' | 'exp2'
fogColor: string
fogRange: [number, number]
fogDensity: number
fogStart: number
fogEnd: number
}
grid: {
enabled: boolean
colorX: string
colorZ: string
colorMain: string
alphaX: number
alphaZ: number
alphaMain: number
dotsEnabled: boolean
dotsColor: string
dotsAlpha: number
dotsDiameter: number
crossEnabled: boolean
crossColor: string
crossAlpha: number
crossLength: number
crossWidth: number
fadeStart: number
fadeEnd: number
}
ssao: {
type: 'none' | 'lighting' | 'combine'
blurEnabled: boolean
intensity: number
radius: number
samples: number
power: number
minAngle: number
scale: number
}
bloom: {
enabled: boolean
intensity: number
lastMipLevel: number
}
chromaticAberration: {
enabled: boolean
intensity: number
}
taa: {
enabled: boolean
jitter: number
}
grading: {
enabled: boolean
brightness: number
contrast: number
saturation: number
tint: string
}
lut: {
intensity: number
textureUrl?: string | null
}
vignette: {
enabled: boolean
intensity: number
inner: number
outer: number
curvature: number
color: string
}
directionalLight: {
enabled: boolean
color: string
intensity: number
azimuth: number
elevation: number
castShadows: boolean
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
shadowCatcher: {
enabled: boolean
size: number
yOffset: number
lightIntensity: number
lightColor: string
lightAzimuth: number
lightElevation: number
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
}
export const DEFAULT_POSTFX: PostFxSettings = {
lighting: {
exposure: 1.21,
skyBoxIntensity: 0.86,
},
envAtlas: {
enabled: true,
background: false,
reflection: true,
intensity: 0.76,
reflectionIntensity: 0.6,
brightness: 1.65,
contrast: 1,
saturation: 1,
toneMapping: 0,
mip: 1,
rotation: 247,
},
skybox: {
enabled: false,
background: false,
reflection: true,
intensity: 0.62,
reflectionIntensity: 1,
mip: 0,
rotation: 0,
colorA: '#c5bfbf',
colorB: '#c7bcbc',
},
rendering: {
backgroundColor: '#111113',
wireframe: false,
renderFormat: 18,
renderFormatFallback0: 12,
renderFormatFallback1: 14,
stencil: false,
renderTargetScale: 1,
samples: 4,
sharpness: 0,
toneMapping: 4,
sceneColorMap: false,
sceneDepthMap: false,
fog: 'exp',
fogColor: '#dcc2ff',
fogRange: [0, 100],
fogDensity: 0.008,
fogStart: 0,
fogEnd: 100,
},
grid: {
enabled: true,
colorX: '#ffffff',
colorZ: '#ffffff',
colorMain: '#7a3cff',
alphaX: 0.18,
alphaZ: 0.18,
alphaMain: 0.6,
dotsEnabled: false,
dotsColor: '#ffffff',
dotsAlpha: 0.5,
dotsDiameter: 0.06,
crossEnabled: false,
crossColor: '#ffffff',
crossAlpha: 0.5,
crossLength: 0.5,
crossWidth: 0.06,
fadeStart: 0,
fadeEnd: 0,
},
ssao: {
type: 'none',
blurEnabled: true,
intensity: 0.5,
radius: 30,
samples: 12,
power: 6,
minAngle: 10,
scale: 1,
},
bloom: {
enabled: true,
intensity: 0.03,
lastMipLevel: 4,
},
chromaticAberration: {
enabled: true,
intensity: 30,
},
taa: {
enabled: false,
jitter: 1,
},
grading: {
enabled: true,
brightness: 0.837,
contrast: 1.1,
saturation: 1.126,
tint: '#ffffff',
},
lut: {
intensity: 1,
textureUrl: null,
},
vignette: {
enabled: true,
intensity: 1,
inner: 0.25,
outer: 1.52,
curvature: 0.78,
color: '#000000',
},
directionalLight: {
enabled: true,
color: '#ffffff',
intensity: 0.4,
azimuth: 0,
elevation: 0,
castShadows: false,
shadowIntensity: 0.5,
shadowDistance: 16,
shadowResolution: 1024,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
shadowCatcher: {
enabled: true,
size: 9,
yOffset: 0.001,
lightIntensity: 0.3,
lightColor: '#ffffff',
lightAzimuth: 20,
lightElevation: 60,
shadowIntensity: 0.29,
shadowDistance: 16,
shadowResolution: 2048,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
}
function isObject(value: any): value is Record<string, any> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
const merge = (target: any, source: any) => {
if (!isObject(source)) return
for (const [key, value] of Object.entries(source)) {
if (isObject(value)) {
if (!isObject(target[key])) target[key] = {}
merge(target[key], value)
} else {
target[key] = value
}
}
}
merge(out, raw)
const legacy: any = raw as any
if (legacy?.hdrLight) {
const src = legacy.hdrLight
const env = legacy?.envAtlas ?? {}
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
}
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
if (typeof legacy.hdrReflection.enabled === 'boolean') {
out.envAtlas.reflection = legacy.hdrReflection.enabled
}
}
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
}
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
out.envAtlas.brightness = 1
}
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
out.envAtlas.contrast = 1
}
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
out.envAtlas.saturation = 1
}
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
out.envAtlas.toneMapping = 0
}
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
out.skybox.reflectionIntensity = out.skybox.intensity
}
if (out.grid && typeof out.grid.enabled !== 'boolean') {
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
}
if (out.grid && typeof out.grid.colorX !== 'string') {
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
}
if (out.grid && typeof out.grid.colorZ !== 'string') {
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
}
if (out.grid && typeof out.grid.colorMain !== 'string') {
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
}
if (out.grid && typeof out.grid.alphaX !== 'number') {
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
}
if (out.grid && typeof out.grid.alphaZ !== 'number') {
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
}
if (out.grid && typeof out.grid.alphaMain !== 'number') {
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
}
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
}
if (out.grid && typeof out.grid.dotsColor !== 'string') {
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
}
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
}
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
}
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
}
if (out.grid && typeof out.grid.crossColor !== 'string') {
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
}
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
}
if (out.grid && typeof out.grid.crossLength !== 'number') {
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
}
if (out.grid && typeof out.grid.crossWidth !== 'number') {
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
}
return out as PostFxSettings
}
@@ -0,0 +1,17 @@
import {useEffect,type RefObject} from 'react';
import * as pc from 'playcanvas';
export function useLutTexture(appRef:RefObject<pc.Application|null>,frameRef:RefObject<any>,textureRef:RefObject<pc.Texture|null>,url:string|null|undefined,ready:boolean,onError?:()=>void){
useEffect(()=>{
const app=appRef.current;let cancelled=false;
const clear=()=>{if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=null;frameRef.current.update?.();}textureRef.current?.destroy();textureRef.current=null;};
clear();if(!app||!ready||!url)return;
const img=new Image();img.onload=()=>{
if(cancelled)return;
if(img.width!==256||img.height!==16){onError?.();return;}
const texture=new pc.Texture(app.graphicsDevice,{name:'Rover color LUT',format:pc.PIXELFORMAT_SRGBA8,mipmaps:false,minFilter:pc.FILTER_LINEAR,magFilter:pc.FILTER_LINEAR,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});
texture.setSource(img);textureRef.current=texture;
if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=texture;frameRef.current.update?.();}
};img.onerror=()=>{if(!cancelled)onError?.();};img.src=url;
return()=>{cancelled=true;clear();};
},[appRef,frameRef,textureRef,url,ready,onError]);
}
@@ -0,0 +1,83 @@
import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas';
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;editing?:boolean;onMaterialPick?:(id:string,group:string)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,editing,onMaterialPick,onTextureState}:SceneMaterialsProps){
const latest=useRef({materials,onMaterialPick,onTextureState});latest.current={materials,onMaterialPick,onTextureState};
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
const generation=useRef(0);
const originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>());
const customMaterials=useRef(new Map<string,pc.StandardMaterial>());
useEffect(()=>{
const app=appRef.current;if(!app||!modelVersion||!materials)return;
const current=++generation.current;let pending=0,failed=false;
const map=new Map<string,pc.StandardMaterial>();
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
if(!(mi.material instanceof pc.StandardMaterial))continue;
if(!originalGroups.current.has(mi))originalGroups.current.set(mi,{id:mi.material.name,material:mi.material});
const source=originalGroups.current.get(mi)!;map.set(source.id,source.material);
}
for(const id of Object.keys(materials))if(id.startsWith('custom/')){
if(!customMaterials.current.has(id)){const m=new pc.StandardMaterial();m.name=id;customMaterials.current.set(id,m);}
map.set(id,customMaterials.current.get(id)!);
}
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(assignments?.[source.id]??source.id)??source.material;
}
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{
(m as any)[maps[slot]]=texture;
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update();
};
const used=new Set<string>();
for(const [id,spec] of Object.entries(materials)){
const m=map.get(id);if(!m)continue;
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
// Specular factor is independent from the donor's global IBL multiplier.
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
m.depthWrite=m.blendType===pc.BLEND_NONE;
for(const slot of Object.keys(maps) as TextureSlot[]){
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;}
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
let item=textures.current.get(key);
if(!item){
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
item={promise};textures.current.set(key,item);const cached=item;
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
}
if(item.texture)applyTexture(m,slot,item.texture,spec);
else{
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
}
}
m.update();
}
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
onTextureState?.(pending?'loading':'ready');
return()=>{generation.current++;};
},[materials,assignments,modelVersion,appRef,onTextureState]);
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
useEffect(()=>{
const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current;
if(!editing||!app||!canvas||!camera?.camera||!modelVersion)return;
const picker=new pc.Picker(app,1,1);let start:{x:number;y:number}|null=null;
const down=(e:PointerEvent)=>{start=e.button===0?{x:e.clientX,y:e.clientY}:null;};
const up=(e:PointerEvent)=>{
const p=start;start=null;if(!p||Math.hypot(p.x-e.clientX,p.y-e.clientY)>4)return;
const rect=canvas.getBoundingClientRect();picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height)));
picker.prepare(camera.camera!,app.scene);
const hit=picker.getSelection(e.clientX-rect.left,e.clientY-rect.top).find(mi=>!!latest.current.materials?.[mi.material.name]);
if(hit instanceof pc.MeshInstance){const source=originalGroups.current.get(hit);if(source)latest.current.onMaterialPick?.(hit.material.name,source.id);}
};
canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up);
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);picker.destroy();};
},[editing,modelVersion,appRef,cameraRef,canvasRef]);
}
@@ -2,7 +2,7 @@
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; } .rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
.rover-view .rover-view__scene { position:absolute; inset:0; } .rover-view .rover-view__scene { position:absolute; inset:0; }
.rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); } .rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
.rover-view__status { position:absolute; top:var(--nodedc-space-3); left:var(--nodedc-space-3); } .rover-view__status { position:absolute; top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); left:var(--nodedc-space-3); }
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; } .rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); } .rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); } .rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
@@ -10,7 +10,7 @@
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; } .rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); } .rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
@container (max-width: 380px) { @container (max-width: 380px) {
.rover-view__authority { top:48px; bottom:auto; } .rover-view:has(.rover-view__controls) .rover-view__authority { top:calc(var(--observation-overlay-header-space, 0px) + 48px); bottom:auto; }
} }
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); } .rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); } .rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
@@ -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"; import type { AiModules, AiSelection } from "../../core/simulation/aiPolygon";
const labels = { segmentation: "Поверхность", detection: "Объекты", geometry: "Рельеф", 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; modules: AiModules; selection: AiSelection; disabled: boolean; onChange: (value: AiSelection) => void;
}) { }) {
return <section className="ai-polygon__section" aria-label="Композиция AI"> 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 }) => {modules.catalog.groups.filter(({ modules: options }) => options.length > 0).map(({ group, modules: options }) =>
<FieldFrame key={group} label={labels[group]}> <InspectorSelectField key={group} label={labels[group]} disabled={disabled}
<Select label={`Модуль: ${labels[group]}`} disabled={disabled}
value={selection.selections.find((row) => row.group === group)?.module_id ?? ""} value={selection.selections.find((row) => row.group === group)?.module_id ?? ""}
options={options.map((module) => ({ value: module.moduleId, label: module.label }))} options={options.map((module) => ({ value: module.moduleId, label: module.label }))}
onChange={(value) => { onChange={(value) => {
@@ -20,7 +23,6 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), { onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), {
group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults, group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults,
}] }); }] });
}} /> }} />)}
</FieldFrame>)}
</section>; </section>;
} }
@@ -0,0 +1,58 @@
import {useEffect,useState} from 'react';
import {Button,Icon,InspectorSelectField,ToastStack} from '@nodedc/ui-react';
import type {AiModules,AiSelection} from '../../core/simulation/aiPolygon';
import {createAiProfile,fetchAiProfiles,sameAiIntent,updateAiProfile,type AiProfile} from '../../core/simulation/aiProfiles';
import {currentSelection} from '../../core/simulation/runConfiguration';
import {AiCompositionFields} from './AiCompositionFields';
import {AiProfileWindow} from './AiProfileWindow';
export function AiConfiguration({modules,selection,disabled,onChange}: {
modules:AiModules;selection:AiSelection;disabled:boolean;onChange:(selection:AiSelection)=>void;
}) {
const [profiles,setProfiles]=useState<AiProfile[]>([]);
const [picked,setPicked]=useState<string|null>(null);
const [modal,setModal]=useState<'save'|AiProfile|null>(null);
const [busy,setBusy]=useState(false);
const [error,setError]=useState<string|null>(null);
useEffect(()=>{let active=true;void fetchAiProfiles().then(rows=>{if(active)setProfiles(rows);})
.catch(e=>{if(active)setError(e.message);});return()=>{active=false;};},[]);
const current=picked===null?profiles.find(p=>sameAiIntent(p.composition,selection)):profiles.find(p=>p.profile_id===picked);
const changed=!!current&&!sameAiIntent(current.composition,selection);
const accept=(value:AiProfile)=>setProfiles(rows=>value.removed?rows.filter(p=>p.profile_id!==value.profile_id)
:[...rows.filter(p=>p.profile_id!==value.profile_id),value].sort((a,b)=>a.name.localeCompare(b.name)));
const save=async(name:string,removed=false)=>{
if(!modal||busy)return;setBusy(true);setError(null);
try {
const editing=modal==='save'?null:modal;
const composition=editing?undefined:currentSelection(selection,modules);
const value=editing?await updateAiProfile(editing,{name,removed})
:current&&name===current.name?await updateAiProfile(current,{composition})
:await createAiProfile(name,composition!);
accept(value);setModal(null);
if(!editing){setPicked(value.profile_id);onChange(value.composition);}
if(removed&&picked===value.profile_id)setPicked(null);
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');
void fetchAiProfiles().then(setProfiles).catch(()=>undefined);
}finally{setBusy(false);}
};
return <section className="ai-polygon__configuration-column" aria-label="Конфигурация AI">
<h3>Конфигурация AI</h3>
<div className="ai-polygon__profile-row">
<InspectorSelectField label="Профиль AI" value={current?.profile_id??''} disabled={disabled||busy}
options={[{value:'',label:'Своя конфигурация'},...profiles.map(p=>({value:p.profile_id,
label:p.name+(changed&&p===current?' · изменён':''),
action:{label:`Редактировать профиль «${p.name}»`,icon:<Icon name="edit"/>,disabled:disabled||busy,
onAction:()=>{setError(null);setModal(p);}}}))]}
onChange={id=>{if(!id){setPicked('');return;}const value=profiles.find(p=>p.profile_id===id);if(!value)return;
try{onChange(currentSelection(value.composition,modules));setPicked(id);setError(null);}
catch(e){setError(e instanceof Error?e.message:'Профиль недоступен.');}}}/>
<Button icon={<Icon name="save"/>} disabled={disabled||busy} onClick={()=>{setError(null);setModal('save');}}>Сохранить профиль</Button>
</div>
<AiCompositionFields modules={modules} selection={selection} disabled={disabled||busy} onChange={onChange}/>
{modal&&<AiProfileWindow key={modal==='save'?'save':modal.profile_id} editing={modal!=='save'} busy={busy}
initialName={modal==='save'?current?.name??'':modal.name} onClose={()=>setModal(null)} onSave={name=>void save(name)}
onRemove={modal==='save'?undefined:()=>void save(modal.name,true)}/>}
<ToastStack items={error?[{id:'ai-profile',tone:'error',title:'Профиль AI не сохранён',description:error}]:[]}
onDismiss={()=>setError(null)}/>
</section>;
}
@@ -0,0 +1,175 @@
import { waypointHit } from "../../core/simulation/waypointHit";
import { PlannerMarkers } from "./PlannerMarkers";
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { Application, Asset, Color, Entity, FILLMODE_NONE, Mat4, Quat, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
import { localScene } from "./localScene";
import { EditorTerrain } from "./EditorTerrain";
import { EditorCamera } from "./EditorCamera";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
export interface EditorMarker { id: string; base: ScreenPoint; top: ScreenPoint; x: ScreenPoint; y: ScreenPoint; z: ScreenPoint }
/** Local planning view. Lifecycle deliberately excludes Ammo, Isaac and inference. */
export class AiEditorRuntime {
private app: Application;
private camera: Entity;
private scan: Entity;
private asset: Asset | null = null;
private controls: EditorCamera;
private annotations: PlannerMarkers;
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private terrain = new EditorTerrain();
private resize: ResizeObserver;
private abort = new AbortController();
private disposed = false;
private dirty = true;
private previous = "";
private points: AiWaypoint[] = [];
clip = Infinity;
height: [number, number] = [0, 1];
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
private onProject: (markers: EditorMarker[]) => void) {
canvas.tabIndex = 0;
this.app = new Application(canvas, { graphicsDeviceOptions: { antialias: false, alpha: false,
preserveDrawingBuffer: false, powerPreference: "default" } });
const app = this.app;
this.camera = new Entity("Editor camera", app);
this.scan = new Entity("Editor Gaussian proxy", app);
app.autoRender = false; app.graphicsDevice.maxPixelRatio = 1;
app.setCanvasFillMode(FILLMODE_NONE, 1, 1); app.setCanvasResolution(RESOLUTION_AUTO);
this.camera.addComponent("camera", { nearClip: .05, farClip: 3000, fov: 60, clearColor: new Color(.025,.03,.04) });
this.controls = new EditorCamera(canvas.parentElement!, canvas);
app.root.addChild(this.camera);
app.root.addChild(this.scan);
this.annotations = new PlannerMarkers(app,this.camera,canvas);
this.controls.pick = (x,y) => { const p=this.pick(x,y);return p?toEditor(p):null; };
const transform = new Mat4().set(localScene(cache).transforms.worldFromVisual);
this.scan.setPosition(transform.getTranslation());
this.scan.setRotation(new Quat().setFromMat4(transform));
this.scan.setLocalScale(transform.getScale());
app.scene.gsplat.splatBudget = 0;
this.resize = new ResizeObserver(() => {
const rect = canvas.parentElement!.getBoundingClientRect();
app.resizeCanvas(Math.max(1,rect.width), Math.max(1,rect.height));
this.controls.resize(Math.max(1,rect.width), Math.max(1,rect.height)); this.dirty = true;
});
this.resize.observe(canvas.parentElement!);
app.systems.gsplat?.on("frame:request", () => { app.renderNextFrame = true; });
app.on("update", (dt: number) => {
this.controls.update(dt); this.syncCamera();
if (this.annotations.setRotationCenter(this.controls.rotationCenter)) app.renderNextFrame = true;
if (this.annotations.update(dt)) app.renderNextFrame = true;
const matrix = this.camera.getWorldTransform().data.join(",");
if (matrix !== this.previous || this.dirty) {
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
this.onProject(this.points.map((p) => {
const [x,y,z] = toEditor(p.position);
return { id:p.id, base:this.project(x,y,z), top:this.project(x,y+this.preferences.waypoint.height,z),
x:this.project(x+this.annotations.axisLength,y,z), y:this.project(x,y+this.annotations.axisLength,z), z:this.project(x,y,z+this.annotations.axisLength) };
}));
}
});
app.start(); this.home();
}
async load() {
const scene = localScene(this.cache);
await this.terrain.load(scene.collision.meshUrl!, this.abort.signal, scene.transforms.worldFromCollision);
if (this.disposed) return;
this.height = [this.terrain.bounds.min.y, this.terrain.bounds.max.y];
if (this.height[1] <= this.height[0]) this.height = [this.height[0]-.5,this.height[1]+.5];
const asset = new Asset("Route editor", "gsplat", { url: scene.visual.streamedSogUrl! });
this.asset = asset;
await new Promise<void>((resolve,reject) => {
asset.once("error", (e: string) => reject(new Error(e)));
asset.ready(() => resolve()); this.app.assets.add(asset); this.app.assets.load(asset);
});
if (this.disposed) { asset.unload(); return; }
this.scan.addComponent("gsplat", { asset, unified: true });
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
uniform float editorClip;
void modifySplatCenter(inout vec3 center) {}
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
void modifySplatColor(vec3 center, inout vec4 color) {
// Unified work-buffer modifiers receive the calibrated world center.
if (center.y > editorClip) color.a = 0.0;
}` });
this.setPreferences(this.preferences);
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
this.setClip(Infinity); this.dirty = true;
}
setPoints(points: AiWaypoint[]) { this.points = points; this.annotations.set(points,this.selected,this.preferences);this.dirty = true; }
setSelected(id: string|null) {this.selected=id;this.annotations.set(this.points,id,this.preferences);this.dirty=true;}
setPreferences(preferences: PlannerPreferences) {
this.controls.navigation=preferences.navigation;
this.preferences=preferences;this.annotations.set(this.points,this.selected,preferences);
const profile=QUALITY_PROFILES[preferences.quality];
this.app.scene.gsplat.splatBudget=profile.splatBudget;
this.app.graphicsDevice.maxPixelRatio=Math.min(window.devicePixelRatio||1,profile.pixelRatio);
if(this.scan.gsplat) {
Object.assign(this.scan.gsplat,{lodBaseDistance:profile.lodBaseDistance,lodMultiplier:profile.lodMultiplier,lodRangeMin:profile.lodRangeMin,lodRangeMax:profile.lodRangeMax});
}
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
}
setClip(height: number) {
this.clip = height;
if (this.scan.gsplat) {
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
}
this.dirty = true;
}
setNavigation(enabled: boolean) {
this.controls.setNavigation(enabled);
}
setAddMode(add: boolean) { this.controls.setAddMode(add); }
private syncCamera() {
const { position:p, quaternion:q } = this.controls.camera;
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
}
home() {
const first = this.points[0]?.position ?? [...this.cache.world.settings.spawn_xy, this.cache.world.settings.ground_z];
this.controls.home(toEditor(first)); this.syncCamera(); this.dirty = true;
}
pick(x: number,y: number) {
const width = this.canvas.clientWidth, height = this.canvas.clientHeight;
const from = this.camera.camera!.screenToWorld(x*width,y*height,.05);
const to = this.camera.camera!.screenToWorld(x*width,y*height,2000);
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip);
return hit ? toMission(hit.toArray()) : null;
}
pickWaypoint(x:number,y:number) {
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const direction=[to.x-from.x,to.y-from.y,to.z-from.z];
let nearest=Infinity, id:string|null=null;
for(const point of this.points) {
const t=waypointHit([from.x,from.y,from.z],direction,toEditor(point.position),this.preferences.waypoint.diameter/2,this.preferences.waypoint.height);
if(t!==null && t<nearest){nearest=t;id=point.id;}
}
return id;
}
move(point: AiWaypoint, x: number, y: number, axis: WaypointAxis) {
const p = toEditor(point.position);
const from = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const hit = dragWaypoint([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],p,axis);
if (!hit) return null;
if (axis !== "xz") return toMission(hit);
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip);
return ground ? toMission(ground.toArray()) : null;
}
private project(x:number,y:number,z:number): ScreenPoint {
const point = this.camera.camera!.worldToScreen(new Vec3(x,y,z));
return point.z > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
}
dispose() {
this.disposed = true;
this.controls.dispose();
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
this.annotations.dispose();
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
}
}
@@ -0,0 +1,42 @@
import { lazy, Suspense, useEffect, useState } from "react";
import { LoadingRegion } from "@nodedc/ui-react";
import { polygonRequest } from "../../core/simulation/aiPolygon";
const SpatialPreview=lazy(()=>import("./AiSpatialPreview").then(m=>({default:m.AiSpatialPreview})));
export interface InferencePreview {
frame_id:number;simulation_time_ns:number;received_at:string;environment:"park"|"natural"|"urban";
layers:({id:string;label:string;ports?:string[];legend?:{class_id:number;label:string;color:string}[]} & (
{kind?:"image";jpeg:string} | {kind:"points3d";points:[number,number,number][];source_count:number;frame:string}
))[];
}
export function useInferencePreview(runId:string|undefined,active:boolean) {
const [preview,setPreview]=useState<InferencePreview|null>(null);
useEffect(()=>{
setPreview(null);if(!runId || !active)return;
const abort=new AbortController();let timer=0;
const poll=async()=>{
try {
if(document.visibilityState==="visible") {
const value=await polygonRequest<InferencePreview|null>(`/runs/${runId}/inference-preview`,{signal:abort.signal});
if(!abort.signal.aborted)setPreview(value);
}
} catch { /* Main status owns connection errors; retain the dated last frame. */ }
if(!abort.signal.aborted)timer=window.setTimeout(()=>void poll(),500);
};
void poll();return()=>{abort.abort();clearTimeout(timer);};
},[runId,active]);
return preview;
}
export function AiInferencePreview({preview,layer}:{preview:InferencePreview;layer:string}) {
const selected=preview.layers.find(p=>p.id===layer);
if(!selected)return null;
return <div className="ai-inference-preview" aria-label={`Результат AI: ${selected.label}`}>
{selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}>
<SpatialPreview points={selected.points} label={selected.label}/>
</Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>}
<div className="ai-inference-preview__caption">
Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
{selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null}
{selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null}
</div>
</div>;
}
@@ -0,0 +1,156 @@
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, Icon, IconButton, LoadingRegion, RangeControl, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
import { type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
import type { WaypointAxis } from "../../core/simulation/waypointDrag";
import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, busy=false }: {
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean;
}) {
const markerSvg=useRef<SVGSVGElement>(null);
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
const viewport = useRef<HTMLDivElement>(null), loadedPoints = useRef(initialPoints);
const [preferences] = usePlannerPreferences();
const runtime = useRef<AiEditorRuntime | null>(null);
const { expanded, toggle } = useSimulationFullscreen(host);
const [ready, setReady] = useState(false), [retry,setRetry] = useState(0);
const { cache,error,setError } = useLocalScene(world,retry);
const [editing,edit] = useReducer(editWaypoints,initialPoints,waypointEditing);
const {points,selected,sequence} = editing;
const press=useRef<{id:number;x:number;y:number}|null>(null);
const [markers, setMarkers] = useState<EditorMarker[]>([]);
const [mode,setMode] = useState<"view" | "add">("view");
const [clip,setClip] = useState(Infinity);
const draftId = useRef(crypto.randomUUID().replaceAll("-",""));
const drag = useRef<{ point: AiWaypoint; axis: WaypointAxis; offset: number[] } | null>(null);
const callback = useRef(onDraft); callback.current = onDraft;
useEffect(() => {
if (cache?.status !== "ready" || !canvas.current) return;
let active = true;
setReady(false); setError(null); setClip(Infinity);
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers); }
catch (e) { setError((e as Error).message); return; }
runtime.current = view;
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
void view.load().then(() => { if (active) setReady(true); }).catch((e: Error) => { if (active) setError(e.message); });
return () => { active=false; runtime.current=null; view.dispose(); callback.current(null); };
}, [cache?.key,cache?.status,retry]);
useEffect(() => {
runtime.current?.setPoints(points);
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
}, [points,cache,ready,sequence]);
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
useEffect(()=>{
if(loadedPoints.current === initialPoints) return;
loadedPoints.current=initialPoints;
edit({type:"load",points:initialPoints});
},[initialPoints]);
const add = (x:number,y:number) => {
if (points.length >= 33) { setError("В задании может быть до 33 точек."); return; }
const position = runtime.current?.pick(x,y);
if (!position) { setError("Под курсором нет доступной поверхности. Измените ракурс или срез."); return; }
const point = { id:crypto.randomUUID().replaceAll("-","").slice(0,16),position };
edit({type:"replace",points:[...points,point],selected:point.id});
};
const position = (e: { clientX:number;clientY:number }) => {
const rect = canvas.current!.getBoundingClientRect();
return [(e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height];
};
const progress = cache ? Object.values(cache.files) : [];
const bytes = progress.reduce((n,f)=>n+f.uploaded_bytes,0), total = progress.reduce((n,f)=>n+f.byte_length,0);
const message = cache?.status === "uploading" ? `Копируем сцену на диск · ${Math.round(bytes/Math.max(1,total)*100)}%`
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
return <div className="ai-polygon__stage" ref={host}>
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
<p>{points.length} точек · первая — старт, последняя — финиш</p></div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
onKeyDown={(e)=>{
const editable=!!(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"],.nodedc-workspace-window');
const action=waypointShortcut(e,editable);
if(!busy && ready && !drag.current && action){e.preventDefault();edit({type:action});setError(null);}
}}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning>
{ready?<div className="ai-local-editor__tools nodedc-scene-controls" inert={busy}>
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
}}><Icon name="trash"/></IconButton>:null}
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
</div>:null}
</SimulationViewTools>
<div className="ai-local-editor__surface"
onPointerDownCapture={(e)=>{
if(e.target!==canvas.current || e.button!==0 || busy || !ready)return;
const id=runtime.current?.pickWaypoint(...position(e) as [number,number]);
if(!id)return;
e.preventDefault();e.stopPropagation();press.current=null;
canvas.current?.focus({preventScroll:true});edit({type:"select",id});
const base=markers.find(m=>m.id===id)?.base;
if(!base)return;
edit({type:"begin"});
drag.current={point:points.find(p=>p.id===id)!,axis:"xz",offset:base.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);markerSvg.current!.setPointerCapture(e.pointerId);
}}
onPointerDown={(e)=>{if(e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
onPointerCancel={()=>{press.current=null;}}
onPointerUp={(e)=>{
const start=press.current;press.current=null;
if(!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
if(mode==="add")add(...position(e) as [number,number]);else edit({type:"select",id:null});
}}><canvas ref={canvas} aria-label="Локальная Gaussian-сцена для маршрута" />
<svg ref={markerSvg} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
onPointerMove={(e)=>{
if (!drag.current) return;
const d=drag.current, [x,y]=position(e);
const moved=runtime.current?.move(d.point,x+d.offset[0],y+d.offset[1],d.axis);
if(moved)edit({type:"move",points:points.map(p=>p.id===d.point.id?{...p,position:moved}:p)});
}}
onPointerUp={(e)=>{
drag.current=null;edit({type:"commit"});
runtime.current?.setNavigation(!busy);if(e.currentTarget.hasPointerCapture(e.pointerId))e.currentTarget.releasePointerCapture(e.pointerId); }}
onPointerCancel={()=>{edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}}>
<path className="ai-route__line" d={markers.map((m,i)=>m.base?`${i&&markers[i-1].base?"L":"M"}${m.base[0]*1280},${m.base[1]*720}`:"").join(" ")} />
{markers.map((m,i)=>m.base&&m.top ? <g key={m.id} data-waypoint="true" className={`ai-route__marker ${selected===m.id?"is-selected":""}`}
onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
e.preventDefault();e.stopPropagation();edit({type:"select",id:m.id});edit({type:"begin"});
drag.current={point:points.find((p)=>p.id===m.id)!,axis:"xz",offset:m.base!.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
}}>
<text x={m.top[0]*1280+10} y={m.top[1]*720}>{i===0?"Старт":i===markers.length-1?`Финиш · ${i}`:i}</text>
{selected===m.id ? (["x","y","z"] as const).map((axis)=>m[axis] ? <g key={axis} className="ai-local-editor__axis-hit" onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
e.preventDefault();e.stopPropagation();edit({type:"begin"});drag.current={point:points.find((p)=>p.id===m.id)!,axis,offset:m.base!.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
}}><line x1={m.base![0]*1280} y1={m.base![1]*720} x2={m[axis]![0]*1280} y2={m[axis]![1]*720}/>
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
</g>:null)}
</svg></div>
{!ready && !error ? <div className="ai-polygon__preview-error"><LoadingRegion loading label={message} /></div>:null}
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={Number.isFinite(clip)?clip:runtime.current!.height[1]}
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
onChange={(v)=>{const next=v>=runtime.current!.height[1]?Infinity:v;setClip(next);runtime.current!.setClip(next);}}/></div>
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
</div>
</div>
</div>;
}
@@ -0,0 +1,16 @@
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave}: {
name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
onClose:()=>void;onSave:()=>void;
}) {
return <Window open title={launch?"Сохранить задание и запустить":"Сохранить задание"}
size="sm" onClose={()=>{if(!busy)onClose();}}
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
<div className="ai-polygon__form">
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
</div>
</Window>;
}
@@ -0,0 +1,18 @@
import {useState} from 'react';
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function AiProfileWindow({initialName='',editing=false,busy,onClose,onSave,onRemove}: {
initialName?:string;editing?:boolean;busy:boolean;onClose:()=>void;
onSave:(name:string)=>void;onRemove?:()=>void;
}) {
const [name,setName]=useState(initialName);
return <Window open size="sm" title={editing?'Редактировать профиль AI':'Сохранить профиль AI'}
onClose={()=>{if(!busy)onClose();}} footer={<WindowFooterActions>
{onRemove&&<Button icon={<Icon name="trash"/>} disabled={busy} onClick={onRemove}>Удалить профиль</Button>}
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={()=>onSave(name.trim())}>
{editing?'Сохранить имя':'Сохранить профиль'}</Button>
</WindowFooterActions>}>
<TextField label="Название профиля" maxLength={120} value={name} disabled={busy}
onChange={e=>setName(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!busy&&name.trim())onSave(name.trim());}}/>
</Window>;
}
@@ -0,0 +1,140 @@
import { useEffect, useRef, useState, type PointerEvent } from "react";
import { Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon";
import { useAiPlanningControls } from "./useAiPlanningControls";
const xy = (p: NonNullable<ScreenPoint>) => `${p[0] * 1280},${p[1] * 720}`;
function path(points: ScreenPoint[]) {
let drawing = false;
return points.map((p) => {
if (!p) { drawing = false; return ""; }
const command = `${drawing ? "L" : "M"}${xy(p)}`; drawing = true; return command;
}).join(" ");
}
type Drag = { start: [number, number]; last: [number, number]; at: number;
action: "orbit" | "pan" | "move"; point_id?: string; axis?: "x" | "y" | "xy";
base?: NonNullable<ScreenPoint>; moved: boolean };
/** Screen-space annotations only. All geometry/projection and terrain picking belong to Worker. */
export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: { run: AiRun; onChange: (run: AiRun) => void; videoReady: boolean; visible?: boolean }) {
const host = useRef<HTMLDivElement>(null);
const svg = useRef<SVGSVGElement>(null);
const drag = useRef<Drag | null>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const [selected, setSelected] = useState<string | null>(null);
const [mode, setMode] = useState<"view" | "add">("view");
const [clip, setClip] = useState<number | null>(null);
const editing = run.request?.purpose === "planning";
const data = run.telemetry?.route_overlay;
const draft = run.telemetry?.planning;
const cameraReady = videoReady && editing && !!draft && run.control !== "stop";
const { send, busy, error, keyDown, stopKeys } = useAiPlanningControls(run, onChange, cameraReady);
const pending = busy || (run.planning_sequence ?? 0) > (draft?.sequence ?? 0);
const ready = cameraReady && !pending && !draft?.camera_moving;
const low = draft?.height_min, high = draft?.height_max;
useEffect(() => { if (!pending) setClip(draft?.clip_height ?? null); }, [pending, draft?.clip_height]);
useEffect(() => {
if (!host.current) return;
const resize = new ResizeObserver(([entry]) => {
const width = (editing ? Math.min : Math.max)(entry.contentRect.width, entry.contentRect.height * 16 / 9);
setSize({ width, height: width * 9 / 16 });
});
resize.observe(host.current); return () => resize.disconnect();
}, []);
const controls = useRef({ send, cameraReady }); controls.current = { send, cameraReady };
useEffect(() => {
const element = host.current;
const wheel = (event: WheelEvent) => {
if (!(event.target instanceof Element) || !event.target.closest(".ai-route__canvas")) return;
if (!controls.current.cameraReady) return;
event.preventDefault();
const pixels = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 720 : 1);
controls.current.send({ action: "zoom", amount: Math.max(-3, Math.min(3, pixels * .006)) });
};
element?.addEventListener("wheel", wheel, { passive: false });
return () => element?.removeEventListener("wheel", wheel);
}, []);
const position = (event: { clientX: number; clientY: number }): [number, number] => {
const rect = svg.current!.getBoundingClientRect();
return [(event.clientX - rect.left) / rect.width, (event.clientY - rect.top) / rect.height];
};
const start = (event: PointerEvent<SVGElement>, point?: string, axis?: Drag["axis"]) => {
if (!cameraReady || (point && !ready)) return;
event.stopPropagation(); event.preventDefault();
svg.current?.focus({ preventScroll: true });
const marker = data?.markers.find((m) => m.id === point);
if (point) setSelected(point);
const p = position(event);
drag.current = { start: p, last: p, at: performance.now(), moved: false,
action: point ? "move" : event.shiftKey || event.button === 1 ? "pan" : "orbit",
point_id: point, axis, base: marker?.base ?? undefined };
svg.current?.setPointerCapture(event.pointerId);
};
const move = (event: PointerEvent<SVGSVGElement>) => {
const d = drag.current; if (!d) return;
const p = position(event);
d.moved ||= Math.hypot(p[0] - d.start[0], p[1] - d.start[1]) > .005;
if (d.action !== "move" && d.moved && performance.now() - d.at > 100) {
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
d.last = p; d.at = performance.now();
}
};
const end = (event: PointerEvent<SVGSVGElement>) => {
const d = drag.current; drag.current = null; if (!d) return;
const p = position(event);
if (d.action === "move" && d.moved && d.base) {
send({ action: "move", point_id: d.point_id, axis: d.axis ?? "xy",
x: Math.max(0, Math.min(1, d.base[0] + p[0] - d.start[0])),
y: Math.max(0, Math.min(1, d.base[1] + p[1] - d.start[1])) });
} else if (!d.moved && !d.point_id && mode === "add" && ready) send({ action: "add", x: p[0], y: p[1] });
else if (d.moved && d.action !== "move") {
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
}
if (svg.current?.hasPointerCapture(event.pointerId)) svg.current.releasePointerCapture(event.pointerId);
};
return <div className="ai-route" ref={host} hidden={!videoReady}>
{data && visible ? <svg ref={svg} viewBox="0 0 1280 720" style={size}
className={`ai-route__canvas ${editing ? "ai-route__canvas--editing" : ""}`}
tabIndex={editing ? 0 : undefined} onKeyDown={keyDown} onBlur={stopKeys}
aria-label="Маршрут и точки задания" onContextMenu={(e) => e.preventDefault()}
onPointerDown={(e) => start(e)} onPointerMove={move} onPointerUp={end}
onPointerCancel={() => { drag.current = null; }}>
<path className="ai-route__line" d={path(data.markers.map((m) => m.base))} />
<path className="ai-route__trace" d={path(data.trace)} />
{data.markers.map((m, i) => m.base && m.top ? <g key={m.id}
className={`ai-route__marker ${selected === m.id ? "is-selected" : ""} ${!editing && i === data.active_index ? "is-active" : ""}`}
onPointerDown={(e) => start(e, m.id, "xy")}>
<line className="ai-route__beam" x1={m.base[0]*1280} y1={m.base[1]*720} x2={m.top[0]*1280} y2={m.top[1]*720} />
<circle cx={m.base[0]*1280} cy={m.base[1]*720} r="8" />
<text x={m.top[0]*1280+10} y={m.top[1]*720}>{i === 0 ? "Старт" : i === data.markers.length-1 ? `Финиш · ${i}` : i}</text>
{editing && selected === m.id ? (["x", "y"] as const).map((axis) => {
const p = axis === "x" ? m.x_axis : m.y_axis;
return p ? <g key={axis} className="ai-route__axis" onPointerDown={(e) => start(e, m.id, axis)}>
<line x1={m.base![0]*1280} y1={m.base![1]*720} x2={p[0]*1280} y2={p[1]*720} />
<circle cx={p[0]*1280} cy={p[1]*720} r="12" />
</g> : null;
}) : null}
</g> : null)}
</svg> : null}
{editing && low != null && high != null && high > low ? <div className="ai-route__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={clip ?? high}
min={low} max={high} step="any" disabled={!cameraReady}
formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`}
formatLimit={(value) => value.toFixed(1).replace('.', ',')}
onChange={(value) => {
const height = value >= high - Math.max(1, high-low)*1e-9 ? null : value;
setClip(height); send({ action: "clip", amount: value, enabled: height != null });
}} />
</div> : null}
{editing ? <div className="ai-route__tools">
<SegmentedControl label="Инструмент маршрута" size="dense" value={mode} onChange={setMode}
items={[{ value: "view", label: "Обзор" }, { value: "add", label: "Точка по клику" }]} />
<Button disabled={!ready} onClick={() => send({ action: "add", x: .5, y: .5 })}>Добавить waypoint</Button>
<Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button>
<Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p>
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null}
</div> : null}
</div>;
}
@@ -14,12 +14,12 @@ export function AiRunActions({ run, onChange }: { run: AiRun; onChange: (run: Ai
}; };
return <> return <>
{!terminal ? <> {!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"} variant={run.state === "ready" ? "primary" : "secondary"}
loading={busy === "pause" || busy === "play"} loading={busy === "pause" || busy === "play"}
onClick={() => command(run.state === "running" ? "pause" : "play")}> onClick={() => command(run.state === "running" ? "pause" : "play")}>
{run.state === "starting" ? "Подготовка…" : run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"} {run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
</Button> </Button> : null}
<Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"} <Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"}
icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button> icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button>
</> : null} </> : 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 { StatusBadge } from "@nodedc/ui-react";
import { type AiRun } from "../../core/simulation/aiPolygon"; import { type AiRun } from "../../core/simulation/aiPolygon";
@@ -16,37 +15,42 @@ const REASONS: Record<string, string> = {
"goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон", "goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон",
waiting: "Ожидаем возможность движения", 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 terminal = ["completed", "stopped", "failed"].includes(run.state);
const telemetry = run.telemetry; const telemetry = run.telemetry;
const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0); const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0);
const preparingModels = run.state === "running" && run.phase === "models"; 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" : telemetry?.stop_reason === "stale-camera" || telemetry?.stop_reason === "stale-command"
? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error" ? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error"
? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01 ? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01
? "Ровер не движется" : REASONS[telemetry?.decision?.reason ?? ""]; ? "Ровер не движется" : 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="Управление симуляцией"> return <section className="ai-polygon__run" aria-label="Управление симуляцией">
<div className="ai-polygon__telemetry-row"> <dl className="ai-polygon__run-metrics">
<div className="ai-polygon__facts"> <div className="ai-polygon__run-metric ai-polygon__run-metric--status">
{run.state !== "ready" && run.state !== "running" || preparingModels || pending ? <StatusBadge tone={run.state === "failed" || run.state === "disconnected" ? "warning" : "neutral"}> <dt>Состояние</dt><dd>
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : STATES[run.state]} <StatusBadge tone={run.state === "failed" || run.state === "disconnected" || (run.state === "running" && telemetry?.decision?.reason === "stuck") ? "warning" : run.state === "running" && !preparingModels && !pending ? "success" : "neutral"}>
</StatusBadge> : null} {preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : run.state === "running" && reason ? reason : STATES[run.state]}
{telemetry && !terminal && run.state !== "stopping" && run.state !== "disconnected" ? <div className="ai-polygon__facts"> </StatusBadge>
{run.state === "running" && !preparingModels && reason ? <strong>{reason}</strong> : null} </dd>
<span>Скорость: {Math.abs(telemetry.speed_mps).toFixed(2)} м/с</span> </div>
<span>Время мира: {(telemetry.simulation_time_ns / 1e9).toFixed(1)} с</span> {metrics.map(([label, value]) => <div className="ai-polygon__run-metric" key={label}>
{run.state === "running" ? <> <dt>{label}</dt><dd>{value}</dd>
<span>Симуляция: {telemetry.rtf.toFixed(2)}×</span> </div>)}
<span>Камера: {telemetry.sensor_fps.toFixed(1)} FPS</span> </dl>
<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>
{run.state === "failed" && run.message ? <p>{run.message}</p> : null} {run.state === "failed" && run.message ? <p>{run.message}</p> : null}
</section>; </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 { 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"; import { configureAiWorld, type AiWorld, type AiWorldSettings } from "../../core/simulation/aiPolygon";
export function AiWorldSetup({ world, disabled, onSaved }: { export function AiWorldSetup({ world, disabled, onSaved }: {
world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void; world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void;
}) { }) {
const [draft, setDraft] = useState<AiWorldSettings>(world.settings); 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 [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const field = (label: string, value: number, change: (value: number) => void) => 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.heading_degrees, (v) => setDraft({ ...draft, heading_degrees: v }))}
{field("Высота камеры, м", draft.camera_height_m, (v) => setDraft({ ...draft, camera_height_m: 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 }))} {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={() => { <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); 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)); .catch((caught: Error) => setError(caught.message)).finally(() => setBusy(false));
}}>Сохранить старт и масштаб</Button> }}>Сохранить старт и масштаб</Button>
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Настройки не сохранены", description: error }]} onDismiss={() => setError(null)} /> : null} {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 { 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 { 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"; 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. */ /** 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 }: { export function AiWorldStream({ world, run, onBack, onChange, controls, headerActions, actionsHost }: {
world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode; world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode;
headerActions?: ReactNode; actionsHost?: HTMLElement | null; headerActions?: ReactNode; actionsHost?: HTMLElement | null;
}) { }) {
const frame = useRef<HTMLDivElement>(null); const frame = useRef<HTMLDivElement>(null), surface=useRef<HTMLDivElement>(null);
const video = useRef<HTMLVideoElement>(null);
const id = useId().replaceAll(":", "");
const { expanded, toggle } = useSimulationFullscreen(frame); 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 [fps, setFps] = useState<number | null>(null);
const [revision, setRevision] = useState(0); const [revision, setRevision] = useState(0);
const [cameraError, setCameraError] = useState(false); const [cameraError, setCameraError] = useState(false);
const [routeVisible, setRouteVisible] = useState(true);
const endpoint = run?.worker?.stream; const endpoint = run?.worker?.stream;
const terminal = !run || ["completed", "stopped", "failed"].includes(run.state); const terminal = !run || ["completed", "stopped", "failed"].includes(run.state);
const connectable = !terminal && !!run?.telemetry?.stream_ready && !!endpoint; 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 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) => { const changeCamera = (camera: AiCamera) => {
if (!run) return; if (!run) return;
setCameraError(false); setCameraError(false);
@@ -99,35 +49,33 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
</div> : null} </div> : null}
{controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null} {controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null}
<div className="ai-polygon__viewer"> <div className="ai-polygon__viewer">
<div className="ai-polygon__viewer-toolbar"> <SimulationObservationDeck preview={preview}
<SegmentedControl<AiCamera> label="Вид симуляции" size="dense" value={mode} onChange={changeCamera} toolbar={<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}><Icon name={expanded ? "minimize" : "expand"} /></IconButton>}
items={[{ value: "follow", label: "За ровером", disabled: terminal }, 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>}>
{ value: "overview", label: "Обзор", disabled: terminal }, { value: "camera", label: "Камера AI", disabled: terminal }]} /> <div className="ai-polygon__layer-options">
<div className="ai-polygon__actions"> {run?.request?.purpose === "planning" ? <StatusBadge tone="neutral">Планирование маршрута</StatusBadge> : <Select<AiCamera> label="Вид симуляции" value={mode} onChange={changeCamera} options={cameraOptions} disabled={terminal} />}
{connectable ? <StatusBadge tone={state === "live" ? "success" : "warning"}> {run?.telemetry?.route_overlay && run.request?.purpose !== "planning" ? <Checker label="Показывать маршрут" checked={routeVisible} onChange={setRouteVisible}/> : null}
{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : "Ожидаем видео"} </div>
</StatusBadge> : null} </Dropdown>}
<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}> video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
<Icon name={expanded ? "minimize" : "expand"} /> <div className="ai-polygon__stream-picture">
</IconButton> {connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
</div>
</div>
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null} {cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
<div className="ai-polygon__viewport">
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")} <LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}> label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
<div className="ai-polygon__video" inert> <div className="ai-polygon__video" inert>
<video ref={video} id={`polygon-video-${id}`} autoPlay muted playsInline tabIndex={-1} {connectable&&endpoint&&state!=="failed"?<WorkerVideo key={`${run?.run_id}:${revision}`} endpoint={endpoint}
aria-label={`Видео симуляции ${world.name} с Worker`} /> onState={(status,value)=>{setState(status);setFps(value);}}/>:null}
<audio id={`polygon-audio-${id}`} muted />
</div> </div>
</LoadingRegion> </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> {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"> : connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
<p>Видеопоток прерван. Состояние симуляции показано выше.</p> <p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
<Button onClick={() => setRevision((value) => value + 1)}>Подключить видео</Button> <Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
</div> : null} </div> : null}
</div> </div>
</div>}/>
</div> </div>
</div>; </div>;
} }
@@ -0,0 +1,100 @@
import { DEFAULT_PLANNER_PREFERENCES, panSensitivity } from "../../core/simulation/plannerPreferences";
import { zoomDisplacement } from "../../core/simulation/editorZoom";
import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/editorNavigation";
import { PerspectiveCamera, Vector3 } from "three";
const KEYS = new Set(["KeyW","KeyA","KeyS","KeyD","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","KeyQ","KeyE","ShiftLeft","ShiftRight"]);
/** Input/math only: PlayCanvas remains the sole renderer. */
export class EditorCamera {
readonly camera = new PerspectiveCamera(60, 1, .05, 3000);
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
get rotationCenter(){return this.gesture&&!this.gesture.pan?this.gesture.anchor:null;}
private keys = new Set<string>();
private enabled=true;
private addMode=false;
private gesture: {id:number;x:number;y:number;anchor:Vector3;depth:number;distance:number;pan:boolean}|null=null;
private forward = new Vector3();
private right = new Vector3();
private delta = new Vector3();
sceneCenter = new Vector3();
pick: ((x:number,y:number)=>number[]|null)|null = null;
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
surface.addEventListener("wheel",this.zoom,{passive:false});
surface.addEventListener("pointerdown",this.pointerDown);
surface.addEventListener("pointermove",this.pointerMove);
surface.addEventListener("pointerup",this.pointerEnd);
surface.addEventListener("pointercancel",this.pointerEnd);
surface.addEventListener("lostpointercapture",this.pointerEnd);
window.addEventListener("keydown",this.keyDown);
window.addEventListener("keyup",this.keyUp);
window.addEventListener("blur",this.clear);
canvas.addEventListener("blur",this.clear);
}
private anchor(x:number,y:number) {
const hit=this.pick?.(x,y);
if(hit)return new Vector3(...hit);
// Empty sky has no surface; retain useful scale relative to the scene.
return this.camera.getWorldDirection(new Vector3())
.multiplyScalar(Math.max(2,this.camera.position.distanceTo(this.sceneCenter))).add(this.camera.position);
}
private pointerDown=(e:PointerEvent)=>{
this.canvas.focus({preventScroll:true});
if(!this.enabled || (e.target as Element).closest("[data-waypoint]") || ![0,1,2].includes(e.button))return;
if(e.button===0 && this.addMode)return;
const rect=this.canvas.getBoundingClientRect();
const anchor=this.anchor((e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height);
this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0};
this.surface.setPointerCapture(e.pointerId);
};
private pointerMove=(e:PointerEvent)=>{
const g=this.gesture;if(!g||g.id!==e.pointerId||!this.enabled)return;
const dx=e.clientX-g.x,dy=e.clientY-g.y;g.x=e.clientX;g.y=e.clientY;
if(g.pan)panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
};
private pointerEnd=(e:PointerEvent)=>{
if(this.gesture?.id!==e.pointerId)return;
this.gesture=null;
if(this.surface.hasPointerCapture(e.pointerId))this.surface.releasePointerCapture(e.pointerId);
};
private zoom=(e:WheelEvent)=>{
if(!this.enabled)return;
e.preventDefault();this.canvas.focus({preventScroll:true});
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const ray=new Vector3(x*2-1,1-y*2,.5).unproject(this.camera).sub(this.camera.position).normalize();
const depth=this.camera.position.distanceTo(this.anchor(x,y));
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?rect.height:1);
this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));this.camera.updateMatrixWorld();
};
private keyDown=(e:KeyboardEvent)=>{
if(document.activeElement!==this.canvas || e.ctrlKey || e.metaKey || e.altKey || !KEYS.has(e.code))return;
e.preventDefault();this.keys.add(e.code);
};
private keyUp=(e:KeyboardEvent)=>{this.keys.delete(e.code);};
private clear=()=>{this.keys.clear();this.gesture=null;};
resize(width:number,height:number){this.camera.aspect=width/height;this.camera.updateProjectionMatrix();}
home(point:number[]){
const target=new Vector3(...point);
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.addMode=add;}
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
update(dt:number){
if(!this.enabled||!this.keys.size)return;
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
this.delta.copy(this.forward).multiplyScalar(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown"))
.addScaledVector(this.right,pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft"));
this.delta.y+=pressed("KeyE")-pressed("KeyQ");
this.delta.normalize().multiplyScalar(Math.min(.1,Math.max(0,dt))*(pressed("ShiftLeft","ShiftRight")?16:4));
this.camera.position.add(this.delta);this.camera.updateMatrixWorld();
}
dispose(){
this.clear();this.surface.removeEventListener("wheel",this.zoom);
this.surface.removeEventListener("pointerdown",this.pointerDown);this.surface.removeEventListener("pointermove",this.pointerMove);
this.surface.removeEventListener("pointerup",this.pointerEnd);this.surface.removeEventListener("pointercancel",this.pointerEnd);
this.surface.removeEventListener("lostpointercapture",this.pointerEnd);
window.removeEventListener("keydown",this.keyDown);window.removeEventListener("keyup",this.keyUp);
window.removeEventListener("blur",this.clear);this.canvas.removeEventListener("blur",this.clear);
}
}
@@ -0,0 +1,63 @@
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Mesh, Matrix4, Ray, Vector3 } from "three";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { MeshBVH } from "three-mesh-bvh";
import { GenerateMeshBVHWorker } from "three-mesh-bvh/worker";
/** CPU picking only: no Three renderer, physical stepping, or AI in the editor. */
export class EditorTerrain {
private draco = new DRACOLoader().setDecoderPath({
js: "/vendor/playcanvas/draco/1.5.7/draco_wasm_wrapper_gltf.js",
wasm: "/vendor/playcanvas/draco/1.5.7/draco_decoder_gltf.wasm",
}).setWorkerLimit(1);
private builder: GenerateMeshBVHWorker | null = new GenerateMeshBVHWorker();
private trees: MeshBVH[] = [];
private geometries: BufferGeometry[] = [];
private disposed = false;
bounds = new Box3();
async load(url: string, signal: AbortSignal, transform?: number[]) {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error("Не удалось открыть поверхность локации.");
const gltf = await new GLTFLoader().setDRACOLoader(this.draco).parseAsync(await response.arrayBuffer(), "");
if (this.disposed || signal.aborted) {
gltf.scene.traverse((object) => { if (object instanceof Mesh) object.geometry.dispose(); });
throw new DOMException("Aborted", "AbortError");
}
if (transform) gltf.scene.applyMatrix4(new Matrix4().fromArray(transform));
gltf.scene.updateMatrixWorld(true);
gltf.scene.traverse((object) => {
if (!(object instanceof Mesh)) return;
const input = object.geometry;
const geometry = new BufferGeometry();
const position = input.getAttribute("position");
const xyz = new Float32Array(position.count * 3);
const p = new Vector3();
for (let i = 0; i < position.count; i++) {
p.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
xyz[i*3] = p.x; xyz[i*3+1] = p.y; xyz[i*3+2] = p.z;
}
geometry.setAttribute("position", new BufferAttribute(xyz, 3));
geometry.setIndex(input.index!.clone());
geometry.computeBoundingBox(); this.bounds.union(geometry.boundingBox!);
this.geometries.push(geometry); input.dispose();
});
for (const geometry of this.geometries) {
if (this.disposed || signal.aborted) throw new DOMException("Aborted", "AbortError");
this.trees.push(await this.builder!.generate(geometry, { maxLeafTris: 10 }));
}
this.builder?.dispose(); this.builder = null;
}
pick(origin: number[], direction: number[], clip = Infinity) {
const ray = new Ray(new Vector3(...origin), new Vector3(...direction).normalize());
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.sort((a, b) => a.distance - b.distance)[0]?.point ?? null;
}
ground(x: number, z: number, near: number, clip = Infinity) {
const ray = new Ray(new Vector3(x, this.bounds.max.y + 1, z), new Vector3(0, -1, 0));
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.sort((a, b) => Math.abs(a.point.y - near) - Math.abs(b.point.y - near))[0]?.point ?? null;
}
dispose() { this.disposed = true; this.draco.dispose(); this.builder?.dispose(); this.builder = null; this.geometries.forEach((g) => g.dispose()); this.trees = []; }
}
@@ -0,0 +1,55 @@
import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon";
import type { RoverSettings } from "../../core/simulation/roverSettings";
import { toEditor } from "../../core/simulation/aiEditor";
import { PlayCanvasRuntime } from "./PlayCanvasRuntime";
import { localScene } from "./localScene";
import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export function LocalManualScene({world,robot,settings,actionsHost,headerActions}: {
world:AiWorld; robot:AiRobot; settings?:RoverSettings; actionsHost:HTMLElement|null; headerActions:React.ReactNode;
}) {
const [preferences]=usePlannerPreferences();
const host=useRef<HTMLDivElement>(null), canvas=useRef<HTMLCanvasElement>(null);
const viewport=useRef<HTMLDivElement>(null);
const runtime=useRef<PlayCanvasRuntime|null>(null);
const [retry,setRetry]=useState(0), [ready,setReady]=useState(false), [speed,setSpeed]=useState(0);
const {cache,error,setError}=useLocalScene(world,retry);
const {expanded,toggle}=useSimulationFullscreen(host);
useEffect(()=>{
if(cache?.status!=="ready"||!canvas.current)return;
let active=true;
const view=new PlayCanvasRuntime(); runtime.current=view; setReady(false);
void (async()=>{
await view.mount(canvas.current!); if(!active)return;
view.setQuality(preferences.quality);
await view.loadWorld(localScene(cache)); if(!active)return;
const configured = settings ? {...robot,physics:{...robot.physics,mass_kg:settings.base_mass_kg+settings.payload_mass_kg}} : robot;
await view.setRobot(configured,toEditor([...world.settings.spawn_xy,world.settings.ground_z]),90+world.settings.heading_degrees,settings?.max_speed_mps);
if(!active)return;
await view.setControlMode("ugv"); if(active)setReady(true);
})().catch((e:Error)=>{if(active)setError(e.message);});
const timer=setInterval(()=>{if(active)setSpeed(view.speed);},250);
return ()=>{active=false;clearInterval(timer);view.dispose();runtime.current=null;};
},[cache?.key,cache?.status,robot.sha256,retry]);
useEffect(()=>{runtime.current?.setQuality(preferences.quality);},[preferences.quality,ready]);
return <div className="ai-polygon__stage" ref={host}>
{expanded?<div className="ai-polygon__actions">{headerActions}</div>:actionsHost?createPortal(headerActions,actionsHost):null}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready?"success":"neutral"}>{ready?"Ручное управление · локально":"Подготовка сцены"}</StatusBadge></div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport}/>
<canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} />
{ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null}
{!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null}
{error?<div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
</div>
</div>
</div>;
}
@@ -0,0 +1,99 @@
import { Application, BLEND_NORMAL, Color, Entity, Layer, StandardMaterial, Vec3 } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import type { AiWaypoint } from "../../core/simulation/aiPolygon";
import { axisWorldLength, DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
/** Operator-only geometry: never exported into the Worker scene or inference camera. */
export class PlannerMarkers {
private centroid:Entity|null=null;
private layer = new Layer({name:"Planner annotations", clearDepthBuffer:true});
private root = new Entity("Route annotations");
private materials: StandardMaterial[] = [];
private beams: { entity: Entity; material: StandardMaterial; index: number }[] = [];
private pivot = new Entity("Waypoint pivot");
private arrows: {shaft: Entity; cone: Entity; axis: "x"|"y"|"z"}[] = [];
private points: AiWaypoint[] = [];
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private elapsed = 0;
axisLength = 1;
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {
app.scene.layers.push(this.layer);
camera.camera!.layers=[...camera.camera!.layers,this.layer.id];
app.root.addChild(this.root); this.root.addChild(this.pivot);
const light = new Entity("Annotation light");
light.addComponent("light", {type:"directional",color:new Color(1,1,1),intensity:1,layers:[this.layer.id]});
light.setEulerAngles(35,25,0);this.root.addChild(light);
app.scene.ambientLight = new Color(.45,.45,.45);
}
private material(color: string, opacity: number) {
const m = new StandardMaterial(); m.diffuse.fromString(color);m.emissive.copy(m.diffuse).mulScalar(.12);
m.opacity=opacity;m.blendType=BLEND_NORMAL;m.depthWrite=false;m.update();this.materials.push(m);return m;
}
private shape(name: string, type: "cylinder"|"cone"|"sphere", material: StandardMaterial, parent: Entity) {
const entity=new Entity(name);entity.addComponent("render",{type,material,layers:[this.layer.id],castShadows:false,receiveShadows:false});parent.addChild(entity);return entity;
}
set(points: AiWaypoint[], selected: string|null, preferences: PlannerPreferences) {
if(this.centroid && this.selected===selected && this.preferences===preferences && points.length===this.points.length && points.every((v,i)=>v.id===this.points[i].id)) {
this.points=points;
this.beams.forEach(({entity},i)=>{const [x,y,z]=toEditor(points[i].position);entity.setPosition(x,y+preferences.waypoint.height/2,z);});
return;
}
this.points=points;this.selected=selected;this.preferences=preferences;
this.centroid?.destroy();this.centroid=null;
this.beams.forEach(({entity})=>entity.destroy());this.beams=[];
this.arrows.forEach(({shaft,cone})=>{shaft.destroy();cone.destroy();});this.arrows=[];
this.materials.forEach(m=>m.destroy());this.materials=[];
const w=preferences.waypoint,p=preferences.pivot,n=preferences.navigation;
this.centroid=this.shape("Rotation centre","sphere",this.material(n.centroidColor,n.centroidOpacity),this.root);
this.centroid.enabled=false;
for(const [index,point] of points.entries()) {
const [x,y,z]=toEditor(point.position),material=this.material(w.color,w.opacity);
material.emissive.fromString(w.emissionColor);material.emissiveIntensity=w.emission;material.update();
const entity=this.shape(point.id,"cylinder",material,this.root);
entity.setPosition(x,y+w.height/2,z);entity.setLocalScale(w.diameter,w.height,w.diameter);
this.beams.push({entity,material,index});
}
this.pivot.enabled=!!points.find(point=>point.id===selected);
if(this.pivot.enabled) for(const axis of ["x","y","z"] as const) {
const material=this.material(p[axis],p.opacity);
// Gizmo remains visible when its origin is inside the selected beam.
material.depthTest=false;material.update();
this.arrows.push({axis,shaft:this.shape(`${axis} shaft`,"cylinder",material,this.pivot),cone:this.shape(`${axis} cone`,"cone",material,this.pivot)});
}
}
setRotationCenter(point:{x:number;y:number;z:number}|null) {
if(!this.centroid)return false;
const changed=this.centroid.enabled!==!!point;
this.centroid.enabled=!!point;
if(point)this.centroid.setPosition(point.x,point.y,point.z);
return changed;
}
update(dt: number) {
this.elapsed+=dt;
if(this.centroid?.enabled) {
const depth=this.centroid.getPosition().clone().sub(this.camera.getPosition()).dot(this.camera.forward);
const size=axisWorldLength(depth,this.canvas.clientHeight,this.preferences.navigation.centroidPixels);
this.centroid.setLocalScale(size,size,size);
}
const w=this.preferences.waypoint,p=this.preferences.pivot;
const motion=window.matchMedia("(prefers-reduced-motion: reduce)").matches?0:w.frequency;
this.beams.forEach(({material,index})=>{material.opacity=w.opacity*(motion? .8+.2*Math.cos(this.elapsed*motion*Math.PI*2-index*.3):1);material.update();});
const point=this.points.find(v=>v.id===this.selected);
if(point) {
const position=new Vec3(...toEditor(point.position));this.pivot.setPosition(position);
const depth=position.clone().sub(this.camera.getPosition()).dot(this.camera.forward);
this.pivot.enabled=depth>0;
this.axisLength=axisWorldLength(depth,this.canvas.clientHeight,p.pixels);
const unit=this.axisLength/p.pixels,tip=p.cone*unit,stem=this.axisLength-tip;
for(const {axis,shaft,cone} of this.arrows) {
const v=axis==="x"?new Vec3(1,0,0):axis==="y"?new Vec3(0,1,0):new Vec3(0,0,1);
shaft.setLocalPosition(v.clone().mulScalar(stem/2));cone.setLocalPosition(v.clone().mulScalar(stem+tip/2));
for(const shape of [shaft,cone])shape.setLocalEulerAngles(axis==="z"?90:0,0,axis==="x"?-90:0);
shaft.setLocalScale(p.diameter*unit,stem,p.diameter*unit);cone.setLocalScale(tip*.7,tip,tip*.7);
}
}
return this.beams.length>0 && motion>0;
}
dispose() {this.app.scene.layers.remove(this.layer);this.root.destroy();this.materials.forEach(m=>m.destroy());}
}
@@ -0,0 +1,96 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<HTMLDivElement|null>; onClose: () => void }) {
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation">("pivot");
const [saved,update] = usePlannerPreferences();
const [value,setValue] = useState(saved);
const [rect,setRect] = useState(()=>{
const bounds=boundsRef.current?.getBoundingClientRect();
const y=(boundsRef.current?.querySelector(".ai-simulation__view-tools")?.getBoundingClientRect().height??48)+24;
return {x:96,y,width:400,height:Math.max(230,Math.min(490,(bounds?.height??600)-y-12))};
});
const [maximized,setMaximized] = useState(false);
const editing = useRef(false), pending = useRef<PlannerPreferences|null>(null);
const [error,setError] = useState<string|null>(null);
const commit = () => {
editing.current=false;
const next=pending.current; pending.current=null;
if(!next)return;
try { update(next);setError(null); }
catch { setError("Не удалось сохранить настройки в этом браузере."); }
};
const commitRef=useRef(commit);commitRef.current=commit;
useEffect(()=>{if(!editing.current)setValue(saved);},[saved]);
useEffect(()=>{
const release=()=>commitRef.current();
const escape=(e:KeyboardEvent)=>{
if(e.key!=="Escape" || e.defaultPrevented || document.querySelector(".nodedc-dropdown-surface"))return;
e.preventDefault();release();onClose();
};
window.addEventListener("pointerup",release);window.addEventListener("pointercancel",release);
window.addEventListener("keyup",release);window.addEventListener("blur",release);
window.addEventListener("keydown",escape);
return ()=>{
window.removeEventListener("pointerup",release);window.removeEventListener("pointercancel",release);
window.removeEventListener("keyup",release);window.removeEventListener("blur",release);
window.removeEventListener("keydown",escape);
};
},[onClose]);
const set = (group: "pivot"|"waypoint"|"navigation", key: string, next: string|number) => {
const base=pending.current??value;
const changed={...base,[group]:{...base[group],[key]:next}};
pending.current=changed;setValue(changed);
if(!editing.current)commit();
};
const range = (group: "pivot"|"waypoint"|"navigation", key: string, label: string, min: number, max: number, step: number, unit: string) =>
<RangeControl key={key} label={label} min={min} max={max} step={step}
value={Number(value[group][key as keyof typeof value[typeof group]])} onChange={(v)=>set(group,key,v)}
formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
return <WorkspaceWindow boundsRef={boundsRef} rect={rect} onRectChange={setRect}
resizeIndicator={false}
maximized={maximized} onMaximizedChange={setMaximized} minWidth={320} minHeight={230}
zIndex={100} title="Настройки планировщика" closeLabel="Закрыть настройки планировщика"
onClose={()=>{commit();onClose();}}>
<div className="ai-polygon__form" onPointerDownCapture={(e)=>{
if((e.target as Element).closest('input[type="range"], [role="slider"]'))editing.current=true;
}} onKeyDownCapture={(e)=>{
if((e.target as Element).matches('input[type="range"], [role="slider"]') && ["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(e.key))editing.current=true;
}}>
<Select label="Раздел настроек планировщика" value={section} onChange={setSection}
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"}]}/>
{section === "pivot" ? <>
{range("pivot","pixels","Размер осей",50,220,5,"px")}
{range("pivot","diameter","Диаметр стержня",2,16,1,"px")}
{range("pivot","cone","Размер конусов",10,40,1,"px")}
{range("pivot","opacity","Непрозрачность",.15,1,.05,"")}
{(["x","y","z"] as const).map((axis)=><ControlRow key={axis} label={`Цвет ${axis.toUpperCase()}`}><ColorField label={`Цвет ${axis.toUpperCase()}`} value={value.pivot[axis]} onChange={(v)=>set("pivot",axis,v)}/></ControlRow>)}
</> : section === "waypoint" ? <>
{range("waypoint","diameter","Диаметр",.05,3,.05,"м")}
{range("waypoint","height","Высота",.2,50,.1,"м")}
<ControlRow label="Цвет waypoint"><ColorField label="Цвет waypoint" value={value.waypoint.color} onChange={(v)=>set("waypoint","color",v)}/></ControlRow>
{range("waypoint","opacity","Непрозрачность",.1,1,.05,"")}
{range("waypoint","frequency","Пульсация",0,3,.1,"Гц")}
<strong>Свечение</strong>
{range("waypoint","emission","Сила эмиссии",0,5,.1,"")}
<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow>
</> : <>
<strong>Сдвиг камеры</strong>
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p>
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")}
{range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")}
{range("navigation","farPan","Чувствительность вдали",.1,5,.1,"×")}
<strong>Зум</strong>
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
<strong>Центр вращения</strong>
<p>Шарик появляется в точке нажатия на время вращения.</p>
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
</>}
{error?<ToastStack items={[{id:"preferences",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</div>
</WorkspaceWindow>;
}
@@ -1,3 +1,4 @@
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import { import {
Application, Application,
Asset, Asset,
@@ -18,6 +19,7 @@ import {
type ModelComponent, type ModelComponent,
type ScriptType, type ScriptType,
} from "playcanvas"; } from "playcanvas";
import type { AiRobot } from "../../core/simulation/aiPolygon";
import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs"; import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs";
import { import {
@@ -76,24 +78,10 @@ const HOME_POSITION = new Vec3(0, 1, 0);
const HOME_FOCUS = new Vec3(1, 1, 0); const HOME_FOCUS = new Vec3(1, 1, 0);
const DRACO_DECODER_ROOT = "/vendor/playcanvas/draco/1.5.7"; 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 { export class PlayCanvasRuntime implements SimulationRuntime {
private app: Application | null = null; private app: Application | null = null;
private robotAsset: Asset | null = null;
private canvas: HTMLCanvasElement | null = null; private canvas: HTMLCanvasElement | null = null;
private camera: Entity | null = null; private camera: Entity | null = null;
private cameraController: CameraController | null = null; private cameraController: CameraController | null = null;
@@ -155,7 +143,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
antialias: true, antialias: true,
alpha: false, alpha: false,
preserveDrawingBuffer: false, preserveDrawingBuffer: false,
powerPreference: "high-performance", powerPreference: "default",
}, },
}); });
this.app = app; 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 { setQuality(quality: SimulationQuality): void {
this.quality = quality; this.quality = quality;
this.applyQuality(); this.applyQuality();
@@ -380,6 +389,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
this.unloadWorld(); this.unloadWorld();
this.ugvController?.dispose(); this.ugvController?.dispose();
this.ugvController = null; this.ugvController = null;
this.robotAsset?.unload(); this.robotAsset = null;
if (this.app) { if (this.app) {
this.app.autoRender = false; this.app.autoRender = false;
this.app.renderNextFrame = 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"; } from "playcanvas";
import { MeshoptSimplifier } from "meshoptimizer/simplifier"; import { MeshoptSimplifier } from "meshoptimizer/simplifier";
import type { SimulationUgvPreset } from "../../core/simulation/projects"; 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 AMMO_MODULE_ROOT = "/vendor/playcanvas/ammo/2026-08-25";
const UGV_SPAWN_POSITION = new Vec3(0, 1.15, 0); const UGV_SPAWN_POSITION = new Vec3(0, 1.15, 0);
@@ -230,6 +232,12 @@ export class SimulationUgvController {
private orbitIdleSeconds = 0; private orbitIdleSeconds = 0;
private cameraOrbitInitialized = false; private cameraOrbitInitialized = false;
private active = 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 vehicleEntity: Entity | null = null;
private vehicle: NativeRaycastVehicle | null = null; private vehicle: NativeRaycastVehicle | null = null;
private vehicleRaycaster: NativeObject | null = null; private vehicleRaycaster: NativeObject | null = null;
@@ -251,6 +259,16 @@ export class SimulationUgvController {
this.settings = cloneUgvPreset(initialSettings); 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 { get enabled(): boolean {
return this.active; return this.active;
} }
@@ -269,9 +287,11 @@ export class SimulationUgvController {
async enable(collisionWorld: Entity): Promise<void> { async enable(collisionWorld: Entity): Promise<void> {
if (this.active) return; if (this.active) return;
await nextAnimationFrame(); await nextAnimationFrame();
if (this.disposed) return;
try { try {
await this.createStaticCollisionBodies(collisionWorld); await this.createStaticCollisionBodies(collisionWorld);
await nextAnimationFrame(); await nextAnimationFrame();
if (this.disposed) { this.disable(); return; }
this.spawnPosition.copy(this.findSafeSpawnPosition()); this.spawnPosition.copy(this.findSafeSpawnPosition());
this.createVehicle(); this.createVehicle();
this.attachInput(); this.attachInput();
@@ -302,6 +322,7 @@ export class SimulationUgvController {
} }
dispose(): void { dispose(): void {
this.disposed = true;
this.disable(); this.disable();
} }
@@ -309,7 +330,7 @@ export class SimulationUgvController {
const vehicleEntity = this.vehicleEntity as (Entity & NativeRigidBodyAccess) | null; const vehicleEntity = this.vehicleEntity as (Entity & NativeRigidBodyAccess) | null;
const rigidbody = vehicleEntity?.rigidbody; const rigidbody = vehicleEntity?.rigidbody;
if (!vehicleEntity || !rigidbody) return; if (!vehicleEntity || !rigidbody) return;
rigidbody.teleport(this.spawnPosition, UGV_SPAWN_ROTATION); rigidbody.teleport(this.spawnPosition, this.spawnRotation);
rigidbody.linearVelocity = ZERO; rigidbody.linearVelocity = ZERO;
rigidbody.angularVelocity = ZERO; rigidbody.angularVelocity = ZERO;
this.vehicle?.resetSuspension(); this.vehicle?.resetSuspension();
@@ -455,6 +476,11 @@ export class SimulationUgvController {
} }
body?.setActivationState(DISABLE_DEACTIVATION); 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(); if (this.vehicleEntity.getPosition().y < -8) this.reset();
this.updateCamera(deltaSeconds); this.updateCamera(deltaSeconds);
} }
@@ -593,6 +619,7 @@ export class SimulationUgvController {
const rootInverse = collisionWorld.getWorldTransform().clone().invert(); const rootInverse = collisionWorld.getWorldTransform().clone().invert();
for (let index = 0; index < meshInstances.length; index += 1) { for (let index = 0; index < meshInstances.length; index += 1) {
if (this.disposed) return;
const meshInstance = meshInstances[index]; const meshInstance = meshInstances[index];
const physicsMesh = createPhysicsProxyMesh( const physicsMesh = createPhysicsProxyMesh(
this.app, 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); vehicle.setLocalPosition(this.spawnPosition);
this.app.root.addChild(vehicle); this.app.root.addChild(vehicle);
@@ -827,12 +863,12 @@ export class SimulationUgvController {
const heights: number[] = []; const heights: number[] = [];
let suitable = true; let suitable = true;
for (const [sampleX, sampleZ] of footprint) { for (const [sampleX, sampleZ] of footprint) {
const x = UGV_SPAWN_POSITION.x + offsetX + sampleX; const x = this.spawnGround.x + offsetX + sampleX;
const z = UGV_SPAWN_POSITION.z + offsetZ + sampleZ; const z = this.spawnGround.z + offsetZ + sampleZ;
from.set(x, 8, z); from.set(x, this.spawnGround.y + 3, z);
to.set(x, -8, z); to.set(x, this.spawnGround.y - 3, z);
const hit = physics.raycastFirst(from, to); 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; suitable = false;
break; break;
} }
@@ -843,8 +879,8 @@ export class SimulationUgvController {
const maximum = Math.max(...heights); const maximum = Math.max(...heights);
if (maximum - minimum > 0.32) continue; if (maximum - minimum > 0.32) continue;
const x = UGV_SPAWN_POSITION.x + offsetX; const x = this.spawnGround.x + offsetX;
const z = UGV_SPAWN_POSITION.z + offsetZ; const z = this.spawnGround.z + offsetZ;
const ground = heights.reduce((sum, height) => sum + height, 0) / heights.length; const ground = heights.reduce((sum, height) => sum + height, 0) / heights.length;
const clearanceHeight = ground + dimensions.originHeight; const clearanceHeight = ground + dimensions.originHeight;
const origin = new Vec3(x, clearanceHeight, z); const origin = new Vec3(x, clearanceHeight, z);
@@ -855,10 +891,11 @@ export class SimulationUgvController {
if (!blocked) return new Vec3(x, ground + dimensions.originHeight, z); if (!blocked) return new Vec3(x, ground + dimensions.originHeight, z);
} }
return UGV_SPAWN_POSITION.clone(); throw new Error("В месте старта нет опоры для ровера. Выберите другую точку старта.");
} }
private destroyVehicle(): void { private destroyVehicle(): void {
this.trackMotion = null;
if (this.vehicle && this.dynamicsWorld) { if (this.vehicle && this.dynamicsWorld) {
runCleanup("remove vehicle action", () => this.dynamicsWorld?.removeAction(this.vehicle as NativeObject)); 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("keydown", this.onKeyDown, true);
window.addEventListener("keyup", this.onKeyUp, true); window.addEventListener("keyup", this.onKeyUp, true);
window.addEventListener("blur", this.onWindowBlur); window.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("pointerdown", this.onOrbitPointerDown); this.canvas.addEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.addEventListener("pointermove", this.onOrbitPointerMove); this.canvas.addEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.addEventListener("pointerup", this.onOrbitPointerUp); this.canvas.addEventListener("pointerup", this.onOrbitPointerUp);
@@ -901,6 +939,7 @@ export class SimulationUgvController {
window.removeEventListener("keydown", this.onKeyDown, true); window.removeEventListener("keydown", this.onKeyDown, true);
window.removeEventListener("keyup", this.onKeyUp, true); window.removeEventListener("keyup", this.onKeyUp, true);
window.removeEventListener("blur", this.onWindowBlur); window.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("pointerdown", this.onOrbitPointerDown); this.canvas.removeEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.removeEventListener("pointermove", this.onOrbitPointerMove); this.canvas.removeEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.removeEventListener("pointerup", this.onOrbitPointerUp); this.canvas.removeEventListener("pointerup", this.onOrbitPointerUp);
@@ -965,7 +1004,7 @@ export class SimulationUgvController {
} }
private onKeyDown = (event: KeyboardEvent): void => { 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; if (!UGV_KEYS.has(event.code)) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
@@ -0,0 +1,30 @@
import { useState, type ReactNode, type RefObject } from "react";
import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { PlannerSettings } from "./PlannerSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function SimulationViewTools({expanded,toggle,planning=false,boundsRef,children}: {expanded:boolean;toggle:()=>void;planning?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
const [prefs,update]=usePlannerPreferences();
const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState<string|null>(null);
return <>
<div className="ai-simulation__view-tools nodedc-scene-controls">
{children}
<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
options={[{value:"low",label:"Низкое"},{value:"medium",label:"Среднее"},{value:"high",label:"Высокое"},{value:"ultra",label:"Ультра"},{value:"maximum",label:"Максимум"}]}
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>
<IconButton label="Помощь по управлению" onClick={()=>setHelp(true)}><Icon name="info"/></IconButton>
{planning?<IconButton label="Настройки планировщика" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
<IconButton label={expanded?"Свернуть просмотр":"Развернуть просмотр"} onClick={toggle}><Icon name={expanded?"minimize":"expand"}/></IconButton>
</div>
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
<div className="ai-polygon__form">{planning?<>
<p>ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>Прокрутка — зум к курсору, в том числе в режиме добавления точек.</p>
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
</Window>
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</>;
}
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from "react";
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
import { streamRecovery } from "../../core/simulation/streamRecovery";
export type WorkerVideoState="connecting"|"live"|"failed";
export function WorkerVideo({endpoint,onState}:{endpoint:AiStreamEndpoint;onState:(state:WorkerVideoState,fps:number|null)=>void}){
const frame=useRef<HTMLIFrameElement>(null),callback=useRef(onState);callback.current=onState;
const [attempt,setAttempt]=useState(0);
useEffect(()=>{
const started=performance.now();let lastFrame:number|null=null,failedAt:number|null=null,finished=false;
callback.current("connecting",null);
const receive=(e:MessageEvent)=>{
if(finished||e.origin!==location.origin||e.source!==frame.current?.contentWindow||e.data?.type!=="missioncore-worker-video")return;
if(e.data.state==="live"&&Number.isFinite(e.data.fps)){
lastFrame=performance.now();failedAt=null;callback.current("live",e.data.fps);
}else if(e.data.state==="failed")failedAt??=performance.now();
};
const timer=setInterval(()=>{
const action=streamRecovery(performance.now(),started,lastFrame,failedAt,attempt);
if(finished||action==="wait")return;
finished=true;
if(action==="retry")setAttempt(n=>n+1);else callback.current("failed",null);
},500);
window.addEventListener("message",receive);
return ()=>{finished=true;clearInterval(timer);window.removeEventListener("message",receive);};
},[attempt]);
return <iframe key={attempt} ref={frame} className="ai-polygon__video-frame" title="Видеопоток Worker"
src="/simulation-stream.html" allow="autoplay" tabIndex={-1}
onLoad={()=>frame.current?.contentWindow?.postMessage({type:"missioncore-worker-connect",endpoint},location.origin)}/>;
}
@@ -0,0 +1,20 @@
import { Mat4, Quat, Vec3 } from "playcanvas";
import { editorAssetUrl, type EditorCache } from "../../core/simulation/aiEditor";
import type { SimulationWorldManifest } from "../../core/simulation/projects";
/** Both local modes consume the same disk-backed assets and metric transforms. */
export function localScene(cache: EditorCache): SimulationWorldManifest {
const saved = cache.local_scene;
const matrix = (r: number[]) => new Mat4().setFromEulerAngles(r[0],r[1],r[2]);
const visual = saved ? matrix(saved.visual_rotation) : new Mat4().mul2(
matrix([-90,0,0]), new Mat4().setTRS(new Vec3(),
new Quat().setFromEulerAngles(...cache.world.settings.rotation_degrees),
new Vec3().set(cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit)));
return {
schemaVersion: "missioncore.simulation-world-manifest/v1", projectId: cache.world.world_id,
visual: { previewSogUrl: null, streamedSogUrl: saved?.visual_url ?? editorAssetUrl(cache.key,"scene.sog") },
collision: { meshUrl: saved?.collision_url ?? editorAssetUrl(cache.key,"collision.glb"), available: true },
transforms: { worldFromVisual: Array.from(visual.data),
worldFromCollision: Array.from((saved ? matrix(saved.collision_rotation) : new Mat4()).data) },
};
}
@@ -0,0 +1,5 @@
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #000; }
body { display: grid; place-items: center; }
/* Round the decoded picture itself, including when the viewport letterboxes. */
video { display: block; width: 100%; height: 100%; object-fit: cover; }
audio { display: none; }
@@ -0,0 +1,47 @@
import { AppStreamer, StreamType, LogLevel, EventStatus } from "@nvidia/ov-web-rtc";
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
import "@nodedc/tokens/tokens.css";
import "./streamFrame.css";
// A dedicated document owns NVIDIA's window-global handlers and peer connection.
// Removing this iframe releases them even if the SDK is stuck in STARTING.
const video=document.getElementById("worker-video") as HTMLVideoElement;
const fitVideo=(width:number,height:number)=>{
if(!(width>0&&height>0))return;
video.style.setProperty("--stream-width-for-height",`${100*width/height}vh`);
video.style.setProperty("--stream-height-for-width",`${100*height/width}vw`);
};
video.addEventListener("loadedmetadata",()=>fitVideo(video.videoWidth,video.videoHeight));
let started=false;
const report=(state:string,fps=0)=>window.parent.postMessage({type:"missioncore-worker-video",state,fps},location.origin);
window.addEventListener("message",(e:MessageEvent)=>{
if(started || e.source!==window.parent || e.origin!==location.origin || e.data?.type!=="missioncore-worker-connect")return;
started=true;
const endpoint=e.data.endpoint as AiStreamEndpoint;
fitVideo(endpoint.width,endpoint.height);
let frames=0,measuredAt=performance.now(),decoded=0;
const frame=()=>{frames++;video.requestVideoFrameCallback(frame);};
video.requestVideoFrameCallback(frame);
setInterval(()=>{
const now=performance.now();
// Presentation callbacks can be throttled independently of decoding in a
// background view. Prefer decoded, non-dropped video frames for telemetry.
const quality=video.getVideoPlaybackQuality?.();
const total=quality?quality.totalVideoFrames-quality.droppedVideoFrames:decoded+frames;
const count=Math.max(0,total-decoded);
if(count>0)report("live",count*1000/(now-measuredAt));
decoded=total;frames=0;measuredAt=now;
},1000);
const stream=new AppStreamer();
void stream.connect({streamSource:StreamType.DIRECT,logLevel:LogLevel.WARN,streamConfig:{
signalingServer:endpoint.server,signalingPort:endpoint.signaling_port,signalingPath:"/",
mediaServer:endpoint.server,mediaPort:endpoint.media_port,
width:endpoint.width,height:endpoint.height,fps:endpoint.fps,
videoElementId:"worker-video",audioElementId:"worker-audio",
autoLaunch:true,mic:false,enableAV1Support:false,fitStreamResolution:false,
maxReconnects:0,connectivityTimeout:5000,
onStart:event=>{if(event.status===EventStatus.ERROR||event.status===EventStatus.CANCELED)report("failed");},
onStop:()=>report("failed"),
}}).catch(()=>report("failed"));
window.addEventListener("pagehide",()=>{void stream.terminate(false).catch(()=>undefined);},{once:true});
});
@@ -0,0 +1,99 @@
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { sendAiPlanningCommand, type AiPlanningCommand, type AiRun } from "../../core/simulation/aiPolygon";
const motion = new Set(["orbit", "pan", "zoom", "fly"]);
const keys = new Set(["KeyW", "KeyA", "KeyS", "KeyD", "KeyQ", "KeyE", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ShiftLeft", "ShiftRight"]);
const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value));
/** Bounded operator intents only; Worker integrates and renders the camera. */
export function useAiPlanningControls(run: AiRun, onChange: (run: AiRun) => void, enabled: boolean) {
const current = useRef({ run, onChange, enabled }); current.current = { run, onChange, enabled };
const queue = useRef<AiPlanningCommand[]>([]);
const sending = useRef(false);
const alive = useRef(true);
const held = useRef(new Set<string>());
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const flush = async () => {
if (sending.current || !alive.current) return;
sending.current = true;
try {
while (queue.current.length && alive.current && current.current.enabled) {
const run = current.current.run;
if ((run.planning_sequence ?? 0) - (run.telemetry?.planning?.sequence ?? 0) >= 4) {
await new Promise((resolve) => setTimeout(resolve, 100));
continue;
}
const command = queue.current.shift()!;
const updated = await sendAiPlanningCommand(current.current.run, command);
if (alive.current) current.current.onChange(updated);
}
} catch (caught) {
queue.current = []; held.current.clear();
if (alive.current) setError(caught instanceof Error ? caught.message : "Не удалось изменить обзор.");
} finally {
sending.current = false;
if (alive.current) setBusy(false);
}
};
const send = (command: AiPlanningCommand) => {
if (!current.current.enabled) return;
// Do not accumulate motion while Worker is behind; subsequent key ticks retry.
const pending = (current.current.run.planning_sequence ?? 0) - (current.current.run.telemetry?.planning?.sequence ?? 0);
if (motion.has(command.action) && pending >= 4) return;
const previous = queue.current.at(-1);
if (command.action === "clip" && previous?.action === "clip") queue.current.pop();
else if (motion.has(command.action) && previous?.action === command.action) {
queue.current.pop();
command = { ...command, x: clamp((previous.x ?? 0) + (command.x ?? 0), 1),
y: clamp((previous.y ?? 0) + (command.y ?? 0), 1),
amount: clamp((previous.amount ?? 0) + (command.amount ?? 0), 3) };
}
if (queue.current.length >= 8) return;
queue.current.push(command); setBusy(true); setError(null); void flush();
};
const sender = useRef(send); sender.current = send;
const stopKeys = () => {
held.current.clear();
queue.current = queue.current.filter((command) => command.action !== "fly");
};
useEffect(() => {
alive.current = true;
const release = (event: globalThis.KeyboardEvent) => held.current.delete(event.code);
const hide = () => { if (document.hidden) stopKeys(); };
window.addEventListener("keyup", release); window.addEventListener("blur", stopKeys);
document.addEventListener("visibilitychange", hide);
let last = performance.now();
const timer = setInterval(() => {
const now = performance.now(), dt = Math.min(.12, (now-last)/1000); last = now;
const h = held.current;
if (!current.current.enabled || document.hidden || !h.size) return;
const pressed = (...codes: string[]) => Number(codes.some((code) => h.has(code)));
const x = pressed("KeyD", "ArrowRight")-pressed("KeyA", "ArrowLeft");
const y = pressed("KeyW", "ArrowUp")-pressed("KeyS", "ArrowDown");
const z = pressed("KeyE")-pressed("KeyQ");
const length = Math.hypot(x, y, z); if (!length) return;
const distance = dt * (pressed("ShiftLeft", "ShiftRight") ? 8 : 2.5) / length;
sender.current({ action: "fly", x: x*distance, y: y*distance, amount: z*distance });
}, 100);
return () => {
alive.current = false; clearInterval(timer); stopKeys(); queue.current = [];
window.removeEventListener("keyup", release); window.removeEventListener("blur", stopKeys);
document.removeEventListener("visibilitychange", hide);
};
}, []);
useEffect(() => { if (!enabled) { stopKeys(); queue.current = []; } }, [enabled]);
const keyDown = (event: KeyboardEvent<SVGSVGElement>) => {
if (keys.has(event.code)) {
event.preventDefault(); event.stopPropagation();
if (!held.current.has(event.code) && !event.code.startsWith("Shift")) {
const x = Number(["KeyD", "ArrowRight"].includes(event.code))-Number(["KeyA", "ArrowLeft"].includes(event.code));
const y = Number(["KeyW", "ArrowUp"].includes(event.code))-Number(["KeyS", "ArrowDown"].includes(event.code));
send({ action: "fly", x: x*.1, y: y*.1, amount: (Number(event.code === "KeyE")-Number(event.code === "KeyQ"))*.1 });
}
held.current.add(event.code);
}
else if (event.code === "Home") { event.preventDefault(); send({ action: "home" }); }
};
return { send, busy, error, keyDown, stopKeys };
}
@@ -0,0 +1,23 @@
import { useEffect, useState } from "react";
import { fetchEditor, prepareEditor, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWorld } from "../../core/simulation/aiPolygon";
export function useLocalScene(world: AiWorld, retry: number) {
const [cache,setCache] = useState<EditorCache | null>(null);
const [error,setError] = useState<string | null>(null);
useEffect(() => {
const abort = new AbortController(); let timer: ReturnType<typeof setTimeout>;
const poll = async (key?: string) => {
try {
const value = key ? await fetchEditor(key,abort.signal) : await prepareEditor(world,abort.signal);
if (abort.signal.aborted) return;
setCache(value);
if (value.status === "failed") setError(value.error);
else if (value.status !== "ready") timer = setTimeout(() => void poll(value.key),1000);
} catch (e) { if (!abort.signal.aborted) setError((e as Error).message); }
};
setCache(null); setError(null); void poll();
return () => { abort.abort(); clearTimeout(timer); };
}, [world.world_id,retry]);
return { cache,error,setError };
}
@@ -0,0 +1,59 @@
import { useEffect, type RefObject } from "react";
import { polygonRequest, type AiCamera } from "../../core/simulation/aiPolygon";
/** Bounded, coalesced operator input. Never forwards device/drive commands. */
export function useObserverInput(surface:RefObject<HTMLDivElement|null>,runId:string|undefined,mode:AiCamera,enabled:boolean,onError:()=>void) {
useEffect(()=>{
const element=surface.current;if(!element || !runId || !enabled)return;
const input={session:crypto.randomUUID().replaceAll("-",""),sequence:0,orbit:[0,0],move:[0,0,0],zoom:0};
let gesture:{id:number;x:number;y:number;pan:boolean}|null=null, dirty=false, sending=false, closed=false;
const keys=new Set<string>();
const allowed=new Set(["KeyW","KeyS","KeyA","KeyD","KeyQ","KeyE","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","ShiftLeft","ShiftRight"]);
const clamp=(v:number)=>Math.max(-9999,Math.min(9999,v));
const down=(e:PointerEvent)=>{
if((e.target as Element).closest('button,[role="button"],[role="slider"],.nodedc-select-anchor') || ![0,1,2].includes(e.button))return;
e.preventDefault();element.focus({preventScroll:true});
gesture={id:e.pointerId,x:e.clientX,y:e.clientY,pan:e.button!==0};element.setPointerCapture(e.pointerId);
};
const move=(e:PointerEvent)=>{
if(!gesture || gesture.id!==e.pointerId)return;
const dx=e.clientX-gesture.x,dy=e.clientY-gesture.y;gesture.x=e.clientX;gesture.y=e.clientY;
if(gesture.pan){input.move[0]=clamp(input.move[0]-dx*.02);input.move[2]=clamp(input.move[2]+dy*.02);}
else{input.orbit[0]=clamp(input.orbit[0]-dx*.005);input.orbit[1]=clamp(input.orbit[1]-dy*.005);}
dirty=true;
};
const end=()=>{gesture=null;};
const wheel=(e:WheelEvent)=>{
if((e.target as Element).closest('button,.nodedc-select-anchor'))return;
e.preventDefault();input.zoom=clamp(input.zoom+e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?element.clientHeight:1)*.0015);dirty=true;
};
const keyDown=(e:KeyboardEvent)=>{if(document.activeElement!==element || e.ctrlKey || e.metaKey || e.altKey || !allowed.has(e.code))return;e.preventDefault();keys.add(e.code);};
const keyUp=(e:KeyboardEvent)=>keys.delete(e.code);
const clear=()=>{keys.clear();end();};
const context=(e:Event)=>e.preventDefault();
element.addEventListener("pointerdown",down);element.addEventListener("pointermove",move);element.addEventListener("pointerup",end);element.addEventListener("pointercancel",end);
element.addEventListener("wheel",wheel,{passive:false});element.addEventListener("contextmenu",context);element.addEventListener("blur",clear);
window.addEventListener("keydown",keyDown);window.addEventListener("keyup",keyUp);window.addEventListener("blur",clear);
let last=performance.now();
const tick=window.setInterval(()=>{
const now=performance.now(),dt=Math.min(.15,(now-last)/1000);last=now;
if(mode==="overview" && keys.size && document.visibilityState==="visible") {
const pressed=(...codes:string[])=>Number(codes.some(k=>keys.has(k)));
const speed=dt*(pressed("ShiftLeft","ShiftRight")?16:4);
input.move[0]=clamp(input.move[0]+speed*(pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft")));
input.move[1]=clamp(input.move[1]+speed*(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown")));
input.move[2]=clamp(input.move[2]+speed*(pressed("KeyE")-pressed("KeyQ")));dirty=true;
}
if(!dirty || sending)return;
dirty=false;sending=true;input.sequence++;
void polygonRequest(`/runs/${runId}/view`,{method:"PUT",body:JSON.stringify({camera:mode,navigation:input})})
.catch(()=>{if(!closed){dirty=true;onError();}}).finally(()=>{sending=false;});
},100);
return ()=>{
closed=true;clearInterval(tick);clear();
element.removeEventListener("pointerdown",down);element.removeEventListener("pointermove",move);element.removeEventListener("pointerup",end);element.removeEventListener("pointercancel",end);
element.removeEventListener("wheel",wheel);element.removeEventListener("contextmenu",context);element.removeEventListener("blur",clear);
window.removeEventListener("keydown",keyDown);window.removeEventListener("keyup",keyUp);window.removeEventListener("blur",clear);
};
},[surface,runId,mode,enabled,onError]);
}
@@ -0,0 +1,20 @@
import { useSyncExternalStore } from "react";
import { DEFAULT_PLANNER_PREFERENCES, normalizePlannerPreferences, PLANNER_PREFERENCES_KEY, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
const listeners = new Set<() => void>();
let current = DEFAULT_PLANNER_PREFERENCES;
try { current = normalizePlannerPreferences(JSON.parse(localStorage.getItem(PLANNER_PREFERENCES_KEY) ?? "null")); } catch { /* Defaults remain usable if storage is unavailable. */ }
window.addEventListener("storage", (event) => {
if (event.key !== PLANNER_PREFERENCES_KEY) return;
try { current = normalizePlannerPreferences(JSON.parse(event.newValue ?? "null")); } catch { return; }
listeners.forEach((notify) => notify());
});
export function usePlannerPreferences() {
const value = useSyncExternalStore((notify) => { listeners.add(notify); return () => { listeners.delete(notify); }; }, () => current);
const update = (next: PlannerPreferences) => {
const valid = normalizePlannerPreferences(next);
// Persist before accepting, so a quota/privacy failure is visible to the caller.
localStorage.setItem(PLANNER_PREFERENCES_KEY, JSON.stringify(valid));
current = valid; listeners.forEach((notify) => notify());
};
return [value, update] as const;
}
@@ -6,6 +6,7 @@ export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>)
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current); const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
const escape = (event: KeyboardEvent) => { const escape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return; 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.preventDefault();
event.stopPropagation(); event.stopPropagation();
void document.exitFullscreen().catch(() => undefined); void document.exitFullscreen().catch(() => undefined);
@@ -9,12 +9,14 @@ import { useComputeContours } from "../../core/system/ComputeContourContext";
interface SystemNavigationPanelProps { interface SystemNavigationPanelProps {
title: string; title: string;
onAdd: () => void; onAdd: () => void;
onNavigateRoot: () => void;
onClose: () => void; onClose: () => void;
} }
export function SystemNavigationPanel({ export function SystemNavigationPanel({
title, title,
onAdd, onAdd,
onNavigateRoot,
onClose, onClose,
}: SystemNavigationPanelProps) { }: SystemNavigationPanelProps) {
const { contours, selectedContour, selectContour } = useComputeContours(); const { contours, selectedContour, selectContour } = useComputeContours();
@@ -40,7 +42,7 @@ export function SystemNavigationPanel({
description: contour.expected_node_id, description: contour.expected_node_id,
icon: <Icon name="apps" />, icon: <Icon name="apps" />,
active: selectedContour?.contour_id === contour.contour_id, active: selectedContour?.contour_id === contour.contour_id,
onSelect: () => selectContour(contour.contour_id), onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
}))} }))}
items={[]} items={[]}
onItemChange={() => undefined} onItemChange={() => undefined}
@@ -5,7 +5,6 @@ import type { WorkspaceDefinition } from "../productModel";
interface ApplicationPanelActionsOptions { interface ApplicationPanelActionsOptions {
definition: WorkspaceDefinition | null; definition: WorkspaceDefinition | null;
onAddVehicle?: () => void;
refreshRuntime: () => void; refreshRuntime: () => void;
resetConnectionScenario?: () => Promise<boolean>; resetConnectionScenario?: () => Promise<boolean>;
connectionScenarioResetting: boolean; connectionScenarioResetting: boolean;
@@ -45,7 +44,6 @@ export function deviceRuntimeUtilityAction({
export function useApplicationPanelActions({ export function useApplicationPanelActions({
definition, definition,
onAddVehicle,
refreshRuntime, refreshRuntime,
resetConnectionScenario, resetConnectionScenario,
connectionScenarioResetting, connectionScenarioResetting,
@@ -56,7 +54,6 @@ export function useApplicationPanelActions({
}: ApplicationPanelActionsOptions): ApplicationPanelUtilityAction[] { }: ApplicationPanelActionsOptions): ApplicationPanelUtilityAction[] {
return useMemo(() => { return useMemo(() => {
const actions: ApplicationPanelUtilityAction[] = []; const actions: ApplicationPanelUtilityAction[] = [];
if (definition?.kind === "vehicles" && onAddVehicle) actions.push({ label: "Добавить аппарат", icon: "plus", onClick: onAddVehicle });
if (definition?.kind === "device") { if (definition?.kind === "device") {
actions.push(deviceRuntimeUtilityAction({ actions.push(deviceRuntimeUtilityAction({
refreshRuntime, refreshRuntime,
@@ -81,7 +78,6 @@ export function useApplicationPanelActions({
return actions; return actions;
}, [ }, [
definition, definition,
onAddVehicle,
refreshRuntime, refreshRuntime,
resetConnectionScenario, resetConnectionScenario,
connectionScenarioResetting, connectionScenarioResetting,
@@ -0,0 +1,62 @@
import type {CellularNetwork,CellularStamp,TrackerTelemetry} from './vps';
export function cellularFresh(value:CellularStamp|undefined,now=Date.now()/1000){
return !!value&&now-value.measured_at>=0&&now-value.measured_at<90;
}
// Public INTERNAL TAG table examples. A serving network never selects an APN.
const networks:Record<string,string>={'250:1':'МТС','250:2':'МегаФон','250:99':'Билайн'};
export function cellularCardOperator(telemetry:TrackerTelemetry|undefined,slot:string){
const card=telemetry?.sim_identity?.slots[slot];
const home=card?.binding_current?card.known_card?.home_network:undefined;
return home?({'25001':'МТС','25002':'МегаФон','25099':'Билайн'} as Record<string,string>)[home]:undefined;
}
export function cellularOperator(value:CellularNetwork|undefined){
return value?.mcc==null?undefined:networks[`${value.mcc}:${value.mnc}`];
}
/** Losing freshness does not prove card removal; retain explicitly labelled history. */
export function cellularSimOptions(telemetry:TrackerTelemetry|undefined,now=Date.now()/1000){
const status=telemetry?.cellular?.status;
if(!status||status.measured_at>now)return [];
const current=!!telemetry?.online&&cellularFresh(status,now);
return (['1','2'] as const).filter(slot=>[1,2,3,5,6].includes(status!.sim_states[slot])).map(slot=>{
const network=telemetry?.cellular?.networks[slot];
const registered=[1,5].includes(status!.sim_states[slot]);
const knownNetwork=network&&network.measured_at<=now&&(current?cellularFresh(network,now):network.measured_at<=status.measured_at);
const operator=cellularCardOperator(telemetry,slot)??(registered&&knownNetwork?cellularOperator(network):undefined);
return {value:slot,label:`SIM ${slot} (${operator??'оператор не определён'})${current?'':' · последние данные'}`};
});
}
export function cellularSimCurrent(telemetry:TrackerTelemetry|undefined,slot:number,now=Date.now()/1000){
return !!telemetry?.online&&cellularFresh(telemetry.cellular?.status,now)&&[1,2,3,5,6].includes(telemetry.cellular!.status!.sim_states[String(slot)]);
}
export function cellularNetworkLabel(value:CellularNetwork|undefined){
if(!value||value.mcc===null)return 'Оператор не определён';
const code=`${String(value.mcc).padStart(3,'0')}-${String(value.mnc).padStart(2,'0')}`;
const name=cellularOperator(value);
return name?`${name} · ${code}`:`Оператор не определён · код ${code}`;
}
export function cellularSlotDescription(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const view=cellularSlotView(telemetry,slot,now);
if(view.absent)return 'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.';
const operator=cellularCardOperator(telemetry,slot);
if(operator)return operator;
if(view.current&&view.network?.mcc==null)return view.internet?'Интернет подключён. B2 ещё не передал код сети оператора.':'B2 ещё не передал код сети оператора.';
return cellularNetworkLabel(view.network);
}
export function cellularSlotView(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const status=telemetry?.cellular?.status;
const current=!!telemetry?.online&&cellularFresh(status,now);
const absent=current&&status?.sim_states[slot]===0;
// A fresh removal invalidates the old serving-network reading for this slot.
const network=absent?undefined:telemetry?.cellular?.networks[slot];
const selected=current&&!absent&&status?.active_sim===Number(slot);
const internet=selected&&status?.gsm_state===4;
const role=!current?'Последнее полученное состояние':absent?'SIM не обнаружена':internet?'Используется для интернета':selected?'Выбрана модемом':'Не выбрана для интернета';
return {current,absent,network,internet,role};
}
export function cellularSimLabel(value:number|undefined){
return ({0:'SIM не обнаружена',1:'Регистрация в домашней сети',2:'Поиск сети',3:'Регистрация отклонена',5:'Регистрация в роуминге',6:'Ошибка PIN'} as Record<number,string>)[value??-1]??'Нет сведений';
}
export function cellularModemLabel(value:number|undefined){
return ({0:'Модем выключен',1:'Модем включён',2:'Модем отвечает',3:'Подключение GPRS',4:'GPRS подключён'} as Record<number,string>)[value??-1]??'Нет сведений о модеме';
}
@@ -0,0 +1,29 @@
import type {EquipmentCommand,EquipmentNetworkOperation,IndependentDevice} from './equipment';
export interface CommandPreset {id:string;label:string;command:EquipmentCommand;wire:string;encoding:string;queue_seconds:number;confirmation:string;firmware:string;unavailable:string}
export interface CommandEvent {state:string;attempt?:number;stage?:string;observed_at:number;occurred_at?:number;historical:boolean}
export interface CommandEntry extends Omit<EquipmentNetworkOperation,'scope'> {sequence?:number;delivered_at?:number;delivery_seconds?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial<CommandPreset>;firmware?:string;queue_deadline?:number;finished_at?:number;updated_at?:number;reason?:string;events:CommandEvent[]}
export interface CommandRuntime {items:CommandEntry[];tracked_items:CommandEntry[];next_before:number|null;counts:Record<string,number>;catalog:CommandPreset[];device:IndependentDevice;capacity:number|null;durable_kinds?:string[]}
export const commandPending=(state:string)=>['waiting','submitting','queued','dispatched'].includes(state);
export const commandTracked=(entry:CommandEntry)=>commandPending(entry.state)||entry.reconcile_pending===true;
export const commandStatus=(state:string)=>({delivered:'Доставлено',accepted:'Принято B2',stopped:'Повторы остановлены',attempt_started:'Начата попытка',waiting:'В очереди Core',submitting:'Передача на VPS',queued:'В очереди VPS',dispatched:'Отправлено B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',reconnected:'Связь после перезапуска подтверждена',expired:'Срок истёк',unconfirmed:'Результат не подтверждён',uncertain:'Результат неизвестен',cancelled:'Отменено до отправки',rejected:'Отклонено',observed:'Прочитано',verified:'Настройки проверены',sim_selected:'SIM подключена',not_applied:'Не применено'} as Record<string,string>)[state]??'Неизвестный статус';
export const commandTone=(state:string):'success'|'warning'|'neutral'=>['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
export const commandDate=(value?:number)=>value===undefined?'—':new Date(value*1000).toLocaleString('ru-RU');
export const commandDuration=(value?:number)=>value===undefined?'—':`${value.toFixed(3)} с`;
export function mergeCommands(current:CommandEntry[],incoming:CommandEntry[]):CommandEntry[]{
const values=new Map(current.map(item=>[item.id,item]));for(const item of incoming){const old=values.get(item.id);if(!old||(item.updated_at??0)>=(old.updated_at??0))values.set(item.id,item);}
return [...values.values()].sort((a,b)=>(b.sequence??0)-(a.sequence??0));
}
export function commandReason(value:CommandEntry):string{
if(value.reason==='pulse_result_unknown')return 'Импульс был отправлен, но доставка не подтверждена. Автоматический повтор может вызвать второй импульс. Проверьте результат перед повторной отправкой.';
if(value.state==='expired'&&value.vps_created_at&&!value.dispatched_at)return 'VPS не дождался готового соединения с B2 до истечения срока. Команда трекеру не отправлена.';
return ({settings_changed:'Настройки изменились после запроса повтора. Команда не отправлена.',queue_deadline:'Время ожидания в Core истекло; передача на VPS не начиналась.',device_changed:'После постановки в очередь изменилось устройство или его привязка.',host_changed:'Изменилась привязка VPS.',operator_cancelled:'Оператор отменил команду до передачи на VPS.',historical_result_missing:'Окончательный результат этой старой операции не сохранился.'} as Record<string,string>)[value.reason??'']??'';
}
export function commandReceipt(value:CommandEntry):string{
if(value.delivered_at!==undefined)return 'Доставка команды подтверждена. Это не подтверждение переключения контактов выхода.';
if(value.device_code===undefined&&value.description?.encoding?.includes('FC'))return 'Текстовый ответ B2 не содержит идентификатора команды. Исполнение по такому ответу подтвердить нельзя.';
if(value.device_code===undefined)return 'Ответ трекера не получен';
return ({0:value.kind==='restart'?'B2 принял команду перезапуска':'B2 подтвердил команду без ошибки',1:'B2 не распознал команду',2:'Недостаточно аргументов',3:'Слишком много аргументов',4:'Некорректное значение аргумента',5:'B2 сообщил об ошибке выполнения',6:'B2 принял команду; требуется время на выполнение',7:'Очередь команд B2 заполнена',8:'Подключённое устройство недоступно',9:'Подключённое устройство не ответило'} as Record<number,string>)[value.device_code]??'Неизвестный ответ B2';
}
export const commandEntryStatus=(value:CommandEntry)=>value.durable&&commandPending(value.state)&&value.stop_requested?'Остановка повторов':value.durable&&commandPending(value.state)&&value.runtime_phase&&value.runtime_phase!=='executing'?({'waiting-link':'Ожидает связи с B2','retry-wait':'Ожидает следующей попытки','checking-result':'Проверка состояния B2',reconciling:'Уточнение результата у VPS'} as Record<string,string>)[value.runtime_phase]??commandStatus(value.state):value.state==='dispatched'&&value.device_accepted_at!==undefined?commandStatus('device_accepted'):commandStatus(value.state);
@@ -0,0 +1,105 @@
/** Independent equipment is owned by Fleet, never by a vehicle's Node transport. */
export interface EquipmentPolicy {
schema_version:1;
endpoint:{host:string;port:number;slot:number}|null;
connectivity:{strategy:'preserve'|'manual'|'operator'|'sim'|'both'|'native';apn1:string;apn2:string;apn?:string|null;preset_id?:string|null;sim_slot?:number;activate?:boolean;automatic?:boolean};
parameters:Record<string,number>;
}
export interface EquipmentField {key:string;label:string;group:string;min:number;max:number}
export interface ConnectivityPreset {id:string;label:string;apn:string}
export interface EquipmentModel {id:string;label:string;fields:EquipmentField[];profile_schema:number;connectivity_presets?:ConnectivityPreset[];usb_write_firmware?:string[]}
export interface EquipmentProfile {id:string;name:string;model_id:string;settings:EquipmentPolicy;created_at:number}
export interface EquipmentObservation {
output_modes?:Record<string,number>;configuration_read_at?:number;configuration_transport?:'vps';
supported_profile_fields?:string[];read_at:number;model:string;device_id:string;imei_suffix:string;firmware:string;
sim1_iccid_reported_suffix:string|null;sim1_iccid_reported_length:number;
sim2_iccid_reported_suffix:string|null;sim2_iccid_reported_length:number;
configuration:{record_count:number;apn1:string;apn2:string;servers:{slot:number;host:string;port:number;protocol_code:number}[]};
provisioned:false;
}
export interface EquipmentCandidate {id:string;model_id:string;observed:EquipmentObservation;settings:EquipmentPolicy;expires_at:number}
export type EquipmentCommand = {kind:'request-position'}|{kind:'restart'}|{kind:'pulse-output';pin:number;seconds:number}|{kind:'set-output';pin:number;enabled:boolean};
export interface EquipmentNetworkOperation {reason?:string;id:string;durable?:boolean;runtime_phase?:string;attempt_count?:number;next_attempt_at?:number;attempt_expires_at?:number;stop_requested?:boolean;reconcile_pending?:boolean;read_only?:boolean;state:string;stage?:string;scope:'server1'|'configuration'|'sim-selection'|'command';sim_policy?:'both';sim_slot?:number;active_sim?:number;command?:EquipmentCommand;kind?:EquipmentCommand['kind']|'read-settings'|'configure-server1'|'read-configuration'|'configure-all'|'select-sim';unchanged?:boolean;record_count?:number;configuration_sha256?:string;created_at?:number;expires_at?:number;dispatched_at?:number;queue_seconds?:number;roundtrip_seconds?:number;device_code?:number;device_accepted_at?:number;reconnected_at?:number;reconnect_seconds?:number;telemetry_measured_at?:number;verified_at?:number;server1?:{host:string;port:number}}
export interface IndependentDevice {network_operation?:EquipmentNetworkOperation;network_server1?:{host:string;port:number};id:string;name:string;model_id:string;vehicle_id:string;revision:number;observed:EquipmentObservation;settings:EquipmentPolicy;profile_id:string|null;policy_state:'saved'|'applied'|'unchanged'|'uncertain'|'rolled_back'|'not_applied'|'not_started';updated_at:number}
export async function equipmentRequest<T>(path:string,method='GET',body?:unknown):Promise<T>{
const response=await fetch(`/api/v1/fleet/equipment${path}`,{method,credentials:'same-origin',cache:'no-store',headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(path.endsWith('/apply')?120000:45000)});
if(!response.ok){const value=await response.json().catch(()=>({}));throw new Error(typeof value.detail==='string'?value.detail:'Не удалось выполнить действие с оборудованием.');}
return response.json();
}
export const emptyEquipmentPolicy=():EquipmentPolicy=>({schema_version:1,endpoint:null,connectivity:{strategy:'preserve',apn1:'',apn2:''},parameters:{}});
/** Compare settings by value, including server defaults; JSON key order is not an edit. */
export function equipmentPolicyEqual(a:EquipmentPolicy,b:EquipmentPolicy):boolean{
const canonical=(p:EquipmentPolicy)=>{
const c=p.connectivity;
return JSON.stringify([p.schema_version,p.endpoint?[p.endpoint.host,p.endpoint.port,p.endpoint.slot]:null,[c.strategy,c.apn1,c.apn2,c.apn??null,c.preset_id??null,c.sim_slot??1,c.activate??false,c.automatic??false],Object.entries(p.parameters).sort(([x],[y])=>x.localeCompare(y))]);
};
return canonical(a)===canonical(b);
}
/** A saved SIM target does not itself request another modem restart. */
export function simSelectionIntent(draft:EquipmentPolicy,saved:EquipmentPolicy,selected:boolean):boolean{
return (['both','native'].includes(draft.connectivity.strategy)||draft.connectivity.strategy==='sim'&&draft.connectivity.activate===true)&&(selected||!equipmentPolicyEqual({...draft,endpoint:null,parameters:{}},{...saved,endpoint:null,parameters:{}}));
}
/** Selecting a SIM requests exclusive data service; keep its current APN unless edited. */
export function selectInternetSim(policy:EquipmentPolicy,slot:number):EquipmentPolicy{
if(![1,2].includes(slot))return policy;
const current=policy.connectivity;
const apn=current.strategy==='sim'&&current.sim_slot===slot?current.apn??null:null;
return {...policy,connectivity:{strategy:'sim',sim_slot:slot,activate:true,automatic:apn===null,apn,apn1:'',apn2:'',preset_id:null}};
}
export function allowBothInternetSims(policy:EquipmentPolicy,withoutApn=false):EquipmentPolicy{
return {...policy,connectivity:{strategy:withoutApn?'native':'both',apn1:'',apn2:''}};
}
export function equipmentApplyMessage(state:IndependentDevice['policy_state']):string{
return {saved:'Настройки сохранены в Mission Core.',applied:'Настройки записаны в трекер и проверены чтением.',unchanged:'Настройки трекера уже совпадают с сохранёнными.',uncertain:'Результат записи не подтверждён. Прочитайте настройки повторно перед следующим действием.',rolled_back:'Проверка записи не прошла. Предыдущие настройки восстановлены.',not_applied:'Трекер сохранил прежние настройки. Изменения не применены.',not_started:'Запись не началась. Прочитайте устройство повторно и проверьте настройки.'}[state];
}
export function policyError(policy:EquipmentPolicy,fields:EquipmentField[]):string{
if(policy.endpoint&&(!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/i.test(policy.endpoint.host)||!Number.isInteger(policy.endpoint.port)||policy.endpoint.port<1||policy.endpoint.port>65535))return 'Укажите DNS/IP и порт от 1 до 65535.';
if(policy.connectivity.strategy==='sim'&&(![1,2].includes(policy.connectivity.sim_slot??1)||!/^([A-Za-z0-9.-]{0,29})$/.test(policy.connectivity.apn??'')))return 'Проверьте APN выбранной SIM.';
if(policy.connectivity.strategy==='manual'&&!policy.connectivity.apn1.trim())return 'Укажите APN основной SIM.';
if(policy.connectivity.strategy==='operator'&&(!policy.connectivity.preset_id||![1,2].includes(policy.connectivity.sim_slot??1)))return 'Выберите настройки оператора и SIM.';
for(const [key,value]of Object.entries(policy.parameters)){const field=fields.find(f=>f.key===key);if(!field||!Number.isInteger(value)||value<field.min||value>field.max)return `Проверьте значение: ${field?.label??key}.`;}
for(const [a,b]of [['243','244'],['245','246']])if(policy.parameters[a]!==undefined&&policy.parameters[b]!==undefined&&policy.parameters[a]>policy.parameters[b])return 'Минимальное значение превышает максимальное.';
return '';
}
/** A local deadline ends the spinner, not the VPS operation or the write interlock. */
export function networkOperationProgress(operation?:EquipmentNetworkOperation,now=Date.now()/1000){
const pending=!!operation&&['submitting','queued','dispatched'].includes(operation.state);
const deadline=operation?.durable?undefined:operation?.expires_at??(operation?.created_at!==undefined?operation.created_at+240:undefined);
const overdue=pending&&deadline!==undefined&&now>=deadline;
const remaining=pending&&deadline!==undefined?Math.max(0,Math.ceil(deadline-now)):undefined;
return {pending,overdue,waiting:pending&&!overdue,remaining};
}
export function configurationWriteNotStarted(operation?:EquipmentNetworkOperation):boolean{
return !!operation&&['configuration','sim-selection'].includes(operation.scope)&&!operation.read_only&&operation.stage==='preflight'&&['unconfirmed','expired'].includes(operation.state);
}
export function networkOperationMessage(operation?:EquipmentNetworkOperation):string{
if(operation?.reason==='sim_card_changed')return 'Карта в выбранном слоте изменилась. Выберите SIM заново и сохраните настройки.';
if(!operation)return 'Сохранение профиля и подтверждение трекером отображаются отдельно.';
if(operation.durable){
if(operation.stop_requested&&['submitting','queued','dispatched'].includes(operation.state))return 'Останавливаем дальнейшие повторы. Уже отправленная попытка может завершиться.';
if(operation.state==='stopped')return 'Дальнейшие попытки остановлены. История отправок сохранена.';
if(operation.state==='accepted')return 'B2 подтвердил приём команды перезапуска. Возвращение на связь пока не подтверждено; повторного перезапуска не будет.';
if(['submitting','queued','dispatched'].includes(operation.state))return ({reconciling:'Уточняем сохранённый результат у VPS. Задание остаётся в очереди.', 'waiting-identity':'Ожидаем подтверждение карты в выбранном слоте. Настройки пока не отправляются.', 'waiting-link':'Задание сохранено. Ожидаем свежую связь с B2.', 'retry-wait':'Ответ предыдущей попытки не подтверждён. Задание ожидает следующую попытку.', 'checking-result':'Читаем фактические настройки B2 перед решением о повторной записи.', executing:operation.stage==='preflight'?'Читаем текущую конфигурацию B2…':operation.stage==='write'?'Передаём настройки B2…':operation.stage==='verify'?'Проверяем настройки повторным чтением…':operation.stage==='restart'?'Настройки проверены. Ожидаем свежую связь после перезапуска B2…':'Ожидаем результат текущей попытки от B2.'} as Record<string,string>)[operation.runtime_phase??'']??'Задание сохранено. Передаём его на VPS…';
}
if(operation.scope==='command'&&operation.command?.kind==='restart'){
if(operation.state==='dispatched')return 'Команда перезапуска отправлена. Ожидаем свежие данные по новому соединению.';
if(operation.state==='reconnected')return 'После команды перезапуска трекер прислал свежие данные по новому соединению.';
if(operation.state==='unconfirmed')return 'Команда отправлена, но возвращение трекера на связь не подтверждено. Автоматического повторения не будет.';
}
if(operation.scope==='command')return ({submitting:'Передача команды на VPS…',queued:'VPS ожидает соединение с трекером…',dispatched:'Команда отправлена трекеру. Ожидаем ответ.',device_confirmed:'Трекер подтвердил приём команды.',device_rejected:'Трекер отклонил команду.',expired:'Срок отправки истёк. Команда не отправлена.',unconfirmed:'Команда отправлена, но её выполнение не подтверждено отдельным ответом.',uncertain:'Результат команды неизвестен. Автоматического повторения не будет.'} as Record<string,string>)[operation.state]??'Статус команды недоступен.';
if(configurationWriteNotStarted(operation))return 'Трекер не прислал конфигурацию до истечения срока ожидания. Запись настроек не началась. Прочитайте настройки через VPS перед новой попыткой.';
if(operation.scope==='sim-selection'){
if(operation.sim_policy==='both'){
if(operation.state==='sim_selected')return `Обе SIM разрешены. Связь через SIM ${operation.active_sim} подтверждена свежими данными B2.`;
if(operation.stage==='restart')return ['queued','dispatched'].includes(operation.state)?'Обе SIM разрешены. Перезапускаем B2 и ждём восстановления интернета…':'Настройки записаны, но возвращение B2 на связь пока не подтверждено.';
}
if(operation.state==='sim_selected')return `SIM ${operation.active_sim} подключена к интернету. Получены свежие данные B2 через VPS.`;
if(operation.stage==='restart')return ['queued','dispatched'].includes(operation.state)?`Настройки проверены. Перезапускаем B2 и ждём интернет через SIM ${operation.sim_slot}…`:`Настройки записаны, но интернет через SIM ${operation.sim_slot} не подтверждён. Повторного перезапуска не будет.`;
}
if(['configuration','sim-selection'].includes(operation.scope))return ({submitting:'Передача запроса на VPS…',queued:'Ожидание следующего шага обмена с трекером…',dispatched:operation.stage==='preflight'?'Чтение полной конфигурации трекера…':operation.stage==='write'?'Передача настроек трекеру…':'Повторное чтение и проверка записи…',observed:`Конфигурация прочитана с трекера: ${operation.record_count??'—'} параметров.`,verified:operation.unchanged?'Настройки B2 уже совпадают с сохранённым профилем.':'Настройки записаны в B2 и подтверждены повторным чтением.',rejected:'Запись отменена: конфигурация трекера изменилась либо затронут резервный канал связи. Прочитайте настройки повторно.',not_applied:'Трекер сохранил прежние настройки.',expired:'Срок операции истёк. Начните с повторного чтения.',uncertain:'Результат записи не подтверждён. Автоматического повтора не будет.',unconfirmed:operation.stage==='preflight'?'Выгрузка настроек не получена. Прочитайте устройство повторно.':'Завершение записи не подтверждено. Прочитайте настройки B2 повторно.'} as Record<string,string>)[operation.state]??'Статус операции недоступен.';
if(operation.state==='observed')return `Сервер 1 прочитан с трекера: ${operation.server1?.host}:${operation.server1?.port}.`;
if(operation.state==='verified')return `Сервер 1 подтверждён трекером: ${operation.server1?.host}:${operation.server1?.port}. Проверено ${new Date((operation.verified_at??0)*1000).toLocaleString('ru-RU')}.`;
return ({submitting:'Отправка запроса на VPS…',queued:'Ожидание связи с трекером…',dispatched:operation.stage==='preflight'?'Чтение текущих настроек трекера…':operation.stage==='write'?'Запись адреса сервера…':'Проверка адреса сервера повторным чтением…',rejected:'Запись отменена: текущие настройки трекера отличаются от ожидаемых.',not_applied:'Трекер сохранил прежний адрес сервера.',expired:'Трекер не вышел на связь. Запись не началась.',uncertain:'Результат записи не подтверждён. Повторная запись автоматически не выполняется.',unconfirmed:'Ответ не получен. Результат записи не подтверждён.'} as Record<string,string>)[operation.state]??'Статус операции недоступен.';
}
@@ -0,0 +1,27 @@
export interface FirmwareImage {
id:string;model_id:string;filename:string;bytes:number;sha256:string;added_at:number;
version:string|null;source_url:string|null;source:'manufacturer'|'user';installable:false;
}
export interface FirmwareCatalog {items:FirmwareImage[];update_available:false}
const root='/api/v1/fleet/equipment/firmware';
async function response(url:string,init:RequestInit={}){
const value=await fetch(url,{...init,credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(30000)});
if(!value.ok){const error=await value.json().catch(()=>({}));throw new Error(typeof error.detail==='string'?error.detail:'Архив прошивок недоступен. Повторите действие.');}
return value;
}
export async function readFirmware(model:string):Promise<FirmwareCatalog>{
return (await response(`${root}/${encodeURIComponent(model)}`)).json();
}
export async function uploadFirmware(model:string,file:File):Promise<FirmwareImage>{
if(!/\.dfw$/i.test(file.name)||file.size===0||file.size>4*1024*1024)throw new Error('Выберите непустой файл .dfw размером до 4 МБ.');
return (await response(`${root}/${encodeURIComponent(model)}?filename=${encodeURIComponent(file.name)}`,{method:'POST',headers:{'Content-Type':'application/octet-stream'},body:file})).json();
}
export async function downloadFirmware(image:FirmwareImage):Promise<void>{
const value=await response(`${root}/${encodeURIComponent(image.model_id)}/${image.id}/download`);
const data=await value.arrayBuffer();
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data)),b=>b.toString(16).padStart(2,'0')).join('');
if(digest!==image.sha256||data.byteLength!==image.bytes)throw new Error('Контрольная сумма файла не совпала. Скачивание отменено.');
const url=URL.createObjectURL(new Blob([data],{type:'application/octet-stream'}));
const anchor=document.createElement('a');anchor.href=url;anchor.download=image.filename;
document.body.append(anchor);anchor.click();anchor.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
@@ -1,12 +1,15 @@
import {decodeDockTree, reconcileDockTree, moveDockPanel, dockIds, type DockTree, type DockMove} from "@nodedc/ui-core";
export interface ObservationLayout { 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>;
splits:Record<string,number>; arrangement:'auto'|'columns'|'rows'; catalogVisible?:string[]; splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
} }
export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'}); export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'});
const record=(value:unknown):Record<string,unknown>=>value!==null&&typeof value==='object'&&!Array.isArray(value)?value as Record<string,unknown>:{}; const record=(value:unknown):Record<string,unknown>=>value!==null&&typeof value==='object'&&!Array.isArray(value)?value as Record<string,unknown>:{};
export function decodeObservationLayout(value:unknown):ObservationLayout { export function decodeObservationLayout(value:unknown):ObservationLayout {
const source=record(value),result=emptyObservationLayout();if(source.version!==1)return result; 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):[]; 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.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.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))])); 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))]));
@@ -19,5 +22,30 @@ export function orderedObservationIDs(layout:ObservationLayout,available:string[
export function moveObservation(layout:ObservationLayout,available:string[],from:string,to:string):ObservationLayout { 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); const order=orderedObservationIDs(layout,available);const source=order.indexOf(from),target=order.indexOf(to);
if(source<0||target<0||source===target)return layout; 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}; 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,17 @@
import {useEffect,useState} from 'react';
import {equipmentRequest} from './equipment';
import {commandPending,type CommandEntry} from './commandRuntime';
export interface CommandAttempt {id:string;number:number;phase:string;state:string;observed_at:number;dispatched_at?:number;received_at?:number;device_accepted_at?:number;device_code?:number;roundtrip_seconds?:number}
interface Page {items:CommandAttempt[];next_before:number|null}
export function useCommandAttempts(identifier:string,entry:CommandEntry){
const [page,setPage]=useState<Page>({items:[],next_before:null}),[error,setError]=useState(''),[working,setWorking]=useState(false),[retry,setRetry]=useState(0);
const path=`/instances/${identifier}/commands/${entry.id}/attempts`;
useEffect(()=>{
if(!entry.durable)return;
let active=true;let timer:ReturnType<typeof setTimeout>;
async function read(){try{const value=await equipmentRequest<Page>(path);if(active){setPage(old=>({items:[...new Map([...old.items,...value.items].map(item=>[item.number,item])).values()].sort((a,b)=>b.number-a.number),next_before:old.items.length>20?old.next_before:value.next_before}));setError('');}}catch(e){if(active)setError(e instanceof Error?e.message:'История попыток недоступна.');}finally{if(active&&commandPending(entry.state))timer=setTimeout(()=>void read(),3000);}}
void read();return()=>{active=false;clearTimeout(timer);};
},[path,entry.durable,entry.state,retry]);
async function more(){if(page.next_before===null||working)return;setWorking(true);try{const value=await equipmentRequest<Page>(`${path}?before=${page.next_before}`);setPage(old=>({items:[...new Map([...old.items,...value.items].map(item=>[item.number,item])).values()].sort((a,b)=>b.number-a.number),next_before:value.next_before}));setError('');}catch(e){setError(e instanceof Error?e.message:'История попыток недоступна.');}finally{setWorking(false);}}
return {...page,error,working,more,refresh:()=>setRetry(n=>n+1)};
}
@@ -0,0 +1,31 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {equipmentRequest} from './equipment';
import {commandTracked,mergeCommands,type CommandEntry,type CommandRuntime} from './commandRuntime';
type Intent={request_id:string;preset_id?:string;repeat_of?:string};
export function useCommandRuntime(identifier:string){
const path=`/instances/${identifier}/commands`,key=`missioncore.command-intent.${identifier}`;
const [data,setData]=useState<CommandRuntime|null>(null),[items,setItems]=useState<CommandEntry[]>([]),[before,setBefore]=useState<number|null>(null),[error,setError]=useState(''),[activity,setActivity]=useState('');
const alive=useRef(true),sending=useRef(false),first=useRef(true);
const tracked=useRef<string[]>([]);
const [intent,setIntent]=useState<Intent|null>(()=>{try{const v=JSON.parse(localStorage.getItem(key)??'null');return v&&/^[a-f0-9]{32}$/.test(v.request_id)&&(typeof v.preset_id==='string'||typeof v.repeat_of==='string')?v:null;}catch{return null;}});
const accept=useCallback((value:CommandRuntime)=>{if(!alive.current)return;tracked.current=value.tracked_items.filter(commandTracked).map(item=>item.id).slice(0,32);setData(value);setItems(old=>mergeCommands(old,[...value.items,...value.tracked_items]));if(first.current){first.current=false;setBefore(value.next_before);}setError('');},[]);
const refresh=useCallback(async()=>{const query=new URLSearchParams();for(const id of tracked.current)query.append('tracked',id);accept(await equipmentRequest<CommandRuntime>(`${path}?${query}`));},[path,accept]);
useEffect(()=>{alive.current=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{await refresh();}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Журнал временно недоступен.');}finally{if(alive.current)timer=setTimeout(()=>void poll(),2000);}}void poll();return()=>{alive.current=false;clearTimeout(timer);};},[refresh]);
useEffect(()=>{if(intent&&items.some(item=>item.id===intent.request_id)){localStorage.removeItem(key);setIntent(null);}},[items,intent,key]);
async function send(preset:string,repeatOf?:string){
if(sending.current)return;sending.current=true;setActivity(repeatOf?`repeat:${repeatOf}`:'send');setError('');
const request=intent??{request_id:crypto.randomUUID().replaceAll('-',''),...(repeatOf?{repeat_of:repeatOf}:{preset_id:preset})};
try{
// Persist the request ID before HTTP. A lost reply/reopened window reuses it.
localStorage.setItem(key,JSON.stringify(request));setIntent(request);
const response=await fetch(`/api/v1/fleet/equipment${path}${request.repeat_of?`/${request.repeat_of}/repeat`:''}`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify(request.repeat_of?{request_id:request.request_id}:request),signal:AbortSignal.timeout(15000)});
if(!response.ok){const value=await response.json().catch(()=>({}));if(response.status>=400&&response.status<500){localStorage.removeItem(key);if(alive.current)setIntent(null);}throw new Error(value.detail??'Ответ на отправку не получен. Уточните её с тем же ID.');}
localStorage.removeItem(key);if(alive.current)setIntent(null);await refresh();
}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Ответ не получен. Уточните отправку с тем же ID.');}
finally{sending.current=false;if(alive.current)setActivity('');}
}
async function cancel(id:string){setActivity(id);try{await equipmentRequest(`${path}/${id}/cancel`,'POST');await refresh();}catch(e){setError(e instanceof Error?e.message:'Отмена не подтверждена.');}finally{if(alive.current)setActivity('');}}
async function more(){if(before===null)return;setActivity('more');try{const value=await equipmentRequest<CommandRuntime>(`${path}?before=${before}`);if(alive.current){setItems(old=>mergeCommands(old,value.items));setBefore(value.next_before);}}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать историю.');}finally{if(alive.current)setActivity('');}}
return {data,items,before,error,setError,working:!!activity,activity,intent,send,repeat:(id:string)=>send('',id),cancel,more,refresh};
}
@@ -57,5 +57,8 @@ export function useFleet() {
events.onerror = unavailable; events.onerror = unavailable;
return () => { active = false; events.close(); if (fallback) clearInterval(fallback); }; return () => { active = false; events.close(); if (fallback) clearInterval(fallback); };
}, []); }, []);
return { items, error, refresh }; const acceptVehicle = useCallback((vehicle: Vehicle) => {
setItems(current => current?.map(item => item.id === vehicle.id ? vehicle : item) ?? null);
}, []);
return { items, error, refresh, acceptVehicle };
} }
@@ -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,26 @@
import {useEffect,useState} from 'react';
export interface VPSHost {id:string;name:string;endpoint:string;network_interface?:string|null;vehicle_ids:string[];revision:number;state:'pending'|'paired';last_sync_at:number|null;status:{version:string;tracker:{host:string;port:number};pending_packages:number;devices:number;capabilities:string[]}|null}
export interface TrackerPosition {instance_id:string;host_id:string;latitude:number;longitude:number;measured_at:number;received_at:number;source:'gnss'|'lbs'|'wifi';satellites:number|null;course:number;speed_kmh:number}
export interface TrackerOutputs {pins:Record<string,boolean>;host_id:string;measured_at:number;received_at:number}
export interface CellularStamp {measured_at:number;received_at:number}
export interface CellularStatus extends CellularStamp {gsm_state:number;active_sim:1|2;sim_states:Record<string,number>}
export interface CellularNetwork extends CellularStamp {mcc:number|null;mnc:number;signal:number|null}
export interface TrackerCellular {host_id:string;status?:CellularStatus;networks:Record<string,CellularNetwork>}
export interface InternetAccess {state:'ready'|'waiting_identity'|'unknown_card'|'unsupported_operator';source?:'verified_card'|'carrier_candidate';apn?:string;home_network?:string;card_ref?:string}
export interface TrackerTelemetry {instance_id:string;name:string;vehicle_id:string;position:TrackerPosition|null;last_packet_at:number|null;online:boolean;position_fresh:boolean;outputs?:TrackerOutputs|null;outputs_fresh?:boolean;cellular?:TrackerCellular|null;internet_access?:Record<string,InternetAccess>|null;sim_identity?:{slots:Record<string,{binding_current?:boolean;known_card?:{home_network:string;card_ref:string}|null}>}|null}
export async function vpsRequest<T>(path='',method='GET',body?:unknown):Promise<T>{
const response=await fetch(`/api/v1/fleet/vps-hosts${path}`,{method,cache:'no-store',credentials:'same-origin',headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(45000)});
if(!response.ok){const data=await response.json().catch(()=>({}));throw new Error(typeof data.detail==='string'?data.detail:'VPS недоступен. Повторите действие.');}
return response.json();
}
export function hostOnline(host:VPSHost){return !!host.last_sync_at&&Date.now()/1000-host.last_sync_at<30;}
export function telemetryLabel(item:TrackerTelemetry|undefined){return item?.online?'Передаёт данные на VPS':item?.last_packet_at?`Последний пакет: ${new Date(item.last_packet_at*1000).toLocaleString('ru-RU')}`:'Ожидание первого пакета на VPS';}
export function useTrackerTelemetry(vehicleID:string){
const [items,setItems]=useState<TrackerTelemetry[]>([]),[unavailable,setUnavailable]=useState(false);
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;setItems([]);
async function poll(){try{const value=await vpsRequest<{items:TrackerTelemetry[]}>(`/telemetry?vehicle_id=${encodeURIComponent(vehicleID)}`);if(active){setItems(value.items);setUnavailable(false);}}catch{if(active)setUnavailable(true);}finally{if(active)timer=setTimeout(()=>void poll(),5000);}}
void poll();return()=>{active=false;clearTimeout(timer);};
},[vehicleID]);
return {items,unavailable};
}
@@ -0,0 +1,21 @@
import {useEffect,useRef} from 'react';
/** Recover the existing renderer only after its own gateway is reachable again. */
export function useMapRecovery(unavailable:boolean,retry:()=>void){
const callback=useRef(retry);callback.current=retry;
useEffect(()=>{
if(!unavailable)return;
let active=true;let timer:ReturnType<typeof setTimeout>;
const abort=new AbortController();
async function check(){
try{
const response=await fetch('/api/v1/map/gateway/health',{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(10000)])});
const value=response.ok?await response.json():null;
if(active&&value?.ok===true){callback.current();return;}
}catch{/* Retain the unavailable state; no public-provider fallback. */}
if(active)timer=setTimeout(()=>void check(),30000);
}
timer=setTimeout(()=>void check(),30000);
return()=>{active=false;abort.abort();clearTimeout(timer);};
},[unavailable]);
}
@@ -37,5 +37,5 @@ export function useSessionOverviewMode(enabled: boolean) {
window.addEventListener("keydown", close, true); window.addEventListener("keydown", close, true);
return () => window.removeEventListener("keydown", close, true); return () => window.removeEventListener("keydown", close, true);
}, [open]); }, [open]);
return { open: enabled && open, toggle: useCallback(() => setOpen(v => !v), []) }; return { open: enabled && open, close: useCallback(() => setOpen(false), []), toggle: useCallback(() => setOpen(v => !v), []) };
} }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,399 @@
export type PostFxSettings = {
lighting: {
ambientIntensity: number
exposure: number
skyBoxIntensity: number
}
envAtlas: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
brightness: number
contrast: number
saturation: number
toneMapping: number
mip: number
rotation: number
}
skybox: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
mip: number
rotation: number
colorA: string
colorB: string
}
rendering: {
backgroundColor: string
wireframe: boolean
renderFormat: number
renderFormatFallback0: number
renderFormatFallback1: number
stencil: boolean
renderTargetScale: number
samples: number
sharpness: number
toneMapping: number
sceneColorMap: boolean
sceneDepthMap: boolean
fog: 'none' | 'linear' | 'exp' | 'exp2'
fogColor: string
fogRange: [number, number]
fogDensity: number
fogStart: number
fogEnd: number
}
grid: {
step: number
diameter: number
enabled: boolean
colorX: string
colorZ: string
colorMain: string
alphaX: number
alphaZ: number
alphaMain: number
dotsEnabled: boolean
dotsColor: string
dotsAlpha: number
dotsDiameter: number
crossEnabled: boolean
crossColor: string
crossAlpha: number
crossLength: number
crossWidth: number
fadeStart: number
fadeEnd: number
}
ssao: {
type: 'none' | 'lighting' | 'combine'
blurEnabled: boolean
intensity: number
radius: number
samples: number
power: number
minAngle: number
scale: number
}
bloom: {
enabled: boolean
intensity: number
lastMipLevel: number
}
chromaticAberration: {
enabled: boolean
intensity: number
}
taa: {
enabled: boolean
jitter: number
}
grading: {
enabled: boolean
brightness: number
contrast: number
saturation: number
tint: string
}
lut: {
intensity: number
textureUrl?: string | null
}
vignette: {
enabled: boolean
intensity: number
inner: number
outer: number
curvature: number
color: string
}
directionalLight: {
enabled: boolean
color: string
intensity: number
azimuth: number
elevation: number
castShadows: boolean
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
shadowCatcher: {
enabled: boolean
size: number
yOffset: number
lightIntensity: number
lightColor: string
lightAzimuth: number
lightElevation: number
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
}
export const DEFAULT_POSTFX: PostFxSettings = {
lighting: {
ambientIntensity: 0,
exposure: 1.21,
skyBoxIntensity: 0.86,
},
envAtlas: {
enabled: true,
background: false,
reflection: true,
intensity: 0.76,
reflectionIntensity: 0.6,
brightness: 1.65,
contrast: 1,
saturation: 1,
toneMapping: 0,
mip: 1,
rotation: 247,
},
skybox: {
enabled: false,
background: false,
reflection: true,
intensity: 0.62,
reflectionIntensity: 1,
mip: 0,
rotation: 0,
colorA: '#c5bfbf',
colorB: '#c7bcbc',
},
rendering: {
backgroundColor: '#111113',
wireframe: false,
renderFormat: 18,
renderFormatFallback0: 12,
renderFormatFallback1: 14,
stencil: false,
renderTargetScale: 1,
samples: 4,
sharpness: 0,
toneMapping: 4,
sceneColorMap: false,
sceneDepthMap: false,
fog: 'exp',
fogColor: '#dcc2ff',
fogRange: [0, 100],
fogDensity: 0.008,
fogStart: 0,
fogEnd: 100,
},
grid: {
step: 1,
diameter: 1000,
enabled: true,
colorX: '#ffffff',
colorZ: '#ffffff',
colorMain: '#7a3cff',
alphaX: 0.18,
alphaZ: 0.18,
alphaMain: 0.6,
dotsEnabled: false,
dotsColor: '#ffffff',
dotsAlpha: 0.5,
dotsDiameter: 0.06,
crossEnabled: false,
crossColor: '#ffffff',
crossAlpha: 0.5,
crossLength: 0.5,
crossWidth: 0.06,
fadeStart: 0,
fadeEnd: 0,
},
ssao: {
type: 'none',
blurEnabled: true,
intensity: 0.5,
radius: 30,
samples: 12,
power: 6,
minAngle: 10,
scale: 1,
},
bloom: {
enabled: true,
intensity: 0.03,
lastMipLevel: 4,
},
chromaticAberration: {
enabled: true,
intensity: 30,
},
taa: {
enabled: false,
jitter: 1,
},
grading: {
enabled: true,
brightness: 0.837,
contrast: 1.1,
saturation: 1.126,
tint: '#ffffff',
},
lut: {
intensity: 1,
textureUrl: null,
},
vignette: {
enabled: true,
intensity: 1,
inner: 0.25,
outer: 1.52,
curvature: 0.78,
color: '#000000',
},
directionalLight: {
enabled: true,
color: '#ffffff',
intensity: 0.4,
azimuth: 0,
elevation: 0,
castShadows: false,
shadowIntensity: 0.5,
shadowDistance: 16,
shadowResolution: 1024,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
shadowCatcher: {
enabled: true,
size: 9,
yOffset: 0.001,
lightIntensity: 0.3,
lightColor: '#ffffff',
lightAzimuth: 20,
lightElevation: 60,
shadowIntensity: 0.29,
shadowDistance: 16,
shadowResolution: 2048,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
}
function isObject(value: any): value is Record<string, any> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
const merge = (target: any, source: any) => {
if (!isObject(source)) return
for (const [key, value] of Object.entries(source)) {
if (isObject(value)) {
if (!isObject(target[key])) target[key] = {}
merge(target[key], value)
} else {
target[key] = value
}
}
}
merge(out, raw)
const legacy: any = raw as any
if (legacy?.hdrLight) {
const src = legacy.hdrLight
const env = legacy?.envAtlas ?? {}
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
}
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
if (typeof legacy.hdrReflection.enabled === 'boolean') {
out.envAtlas.reflection = legacy.hdrReflection.enabled
}
}
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
}
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
out.envAtlas.brightness = 1
}
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
out.envAtlas.contrast = 1
}
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
out.envAtlas.saturation = 1
}
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
out.envAtlas.toneMapping = 0
}
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
out.skybox.reflectionIntensity = out.skybox.intensity
}
if (out.grid && typeof out.grid.enabled !== 'boolean') {
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
}
if (out.grid && typeof out.grid.colorX !== 'string') {
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
}
if (out.grid && typeof out.grid.colorZ !== 'string') {
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
}
if (out.grid && typeof out.grid.colorMain !== 'string') {
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
}
if (out.grid && typeof out.grid.alphaX !== 'number') {
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
}
if (out.grid && typeof out.grid.alphaZ !== 'number') {
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
}
if (out.grid && typeof out.grid.alphaMain !== 'number') {
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
}
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
}
if (out.grid && typeof out.grid.dotsColor !== 'string') {
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
}
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
}
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
}
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
}
if (out.grid && typeof out.grid.crossColor !== 'string') {
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
}
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
}
if (out.grid && typeof out.grid.crossLength !== 'number') {
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
}
if (out.grid && typeof out.grid.crossWidth !== 'number') {
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
}
return out as PostFxSettings
}
@@ -0,0 +1,85 @@
import {mergePostFxDefaults,type PostFxSettings} from './postFx';
import donorFields from './environmentFields.json';
export type SceneField={key:string;type:string;label:string;group:string;default?:unknown;min?:number;max?:number;step?:number;options?:{label:string;value:string}[];disabledIf?:string};
export const environmentFields:SceneField[]=[...donorFields,
{key:'postFx.lut.textureUrl',type:'texture',label:'Таблица LUT',group:'PostProcess/LUT'},
{key:'postFx.lighting.ambientIntensity',type:'sliderNumber',label:'Заполняющий свет',group:'PostProcess/Lighting',min:0,max:1,step:.01},
{key:'postFx.grid.step',type:'sliderNumber',label:'Шаг основной сетки, м',group:'PostProcess/Grid',min:.01,max:10,step:.01},
{key:'postFx.grid.diameter',type:'sliderNumber',label:'Диаметр сетки, м',group:'PostProcess/Grid',min:1,max:1000,step:1},
];
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const;
export type TextureSlot=typeof textureSlots[number];
export type MaterialSpec={name:string;color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
export type SceneDocument={schema:'missioncore.rover-scene/v1';model:'dcd006-v020-materials-v2';environmentVersion:2;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>};
const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
export function defaultScene():SceneDocument{
const postFx=mergePostFxDefaults();
return {schema:'missioncore.rover-scene/v1',model:'dcd006-v020-materials-v2',environmentVersion:2,postFx,cameraZoomStrength:.04,cameraAutoRotate:false,assignments:{},materials:{
'rover/body':material('Корпус и подвеска','#2c2f31',.12,.53),
'rover/rubber':material('Резина гусениц и катков','#202328',0,.72),
'rover/track-steel':material('Нержавеющие проставки','#c4c8cd',1,.17),
'rover/box':material('Бортовой ящик','#34373a',.08,.4),
'rover/molle':material('MOLLE панель','#52575b',.3,.44),
'rover/motor':material('Алюминий моторов','#95999c',.68,.38),
'rover/hardware':material('Чёрный крепёж','#24272b',.45,.38),
'rover/polymer':material('Пластик и кожухи','#24292d',0,.44),
'rover/drive':material('Ведущие звёзды','#81652f',0,.46),
}};
}
export function createMaterial(doc:SceneDocument,id:string):SceneDocument{
if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id)||Object.keys(doc.materials).length>=128)return doc;
const used=new Set(Object.values(doc.materials).map(m=>m.name));let n=1;while(used.has(`Материал ${n}`))n++;
return {...doc,materials:{...doc.materials,[id]:material(`Материал ${n}`,'#808080',0,.5)}};
}
export function assignMaterial(doc:SceneDocument,group:string,id:string):SceneDocument{
if(!Object.hasOwn(defaultScene().materials,group)||!Object.hasOwn(doc.materials,id))return doc;
return {...doc,assignments:{...doc.assignments,[group]:id}};
}
export function fieldValue(doc:SceneDocument,key:string):unknown{return key.split('.').reduce<unknown>((v,k)=>v&&typeof v==='object'?(v as Record<string,unknown>)[k]:undefined,doc);}
export function fieldDisabled(doc:SceneDocument,f:SceneField):boolean{
const rule=f.disabledIf;if(!rule)return false;
if(rule.startsWith('!'))return !fieldValue(doc,rule.slice(1));
const atlas=doc.postFx.envAtlas.enabled,sky=doc.postFx.skybox.enabled;
return ({ssaoDisabled:doc.postFx.ssao.type==='none',fogDisabled:doc.postFx.rendering.fog==='none',envAtlasBlocked:sky,skyboxBlocked:atlas,envAtlasFieldsDisabled:sky||!atlas,skyboxFieldsDisabled:atlas||!sky,gridDotsDisabled:!doc.postFx.grid.dotsEnabled,gridCrossDisabled:!doc.postFx.grid.crossEnabled} as Record<string,boolean>)[rule]??false;
}
export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDocument{
const f=environmentFields.find(x=>x.key===key);if(!f||f.type==='action')return doc;
if(f.type==='texture'&&value!==null&&(typeof value!=='string'||value.length>1_000_000||!/^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(value)))return doc;
const old=fieldValue(doc,key);
if(typeof old==='number'){
value=Number(value);if(!Number.isFinite(value))return doc;
if(f.min!==undefined)value=Math.max(f.min,value as number);if(f.max!==undefined)value=Math.min(f.max,value as number);
}else if(typeof old==='boolean'){if(typeof value!=='boolean')return doc;}
else if(f.type==='color'){if(typeof value!=='string'||!/^#[0-9a-f]{6}$/i.test(value))return doc;}
if(f.options&&!f.options.some(o=>o.value===String(value)))return doc;
if(f.type==='doubleSlider'){
if(!Array.isArray(value)||value.length!==2||!value.every(Number.isFinite))return doc;
value=[Math.max(0,Math.min(100,value[0])),Math.max(0,Math.min(100,value[1]))].sort((a,b)=>a-b);
}
const result={...doc,postFx:structuredClone(doc.postFx)};const parts=key.split('.');const tail=parts.pop()!;
const target=parts.reduce((v,k)=>v[k],result as any);target[tail]=value;
if(key==='postFx.rendering.fogRange'){[result.postFx.rendering.fogStart,result.postFx.rendering.fogEnd]=value as [number,number];}
if(key==='postFx.envAtlas.enabled'&&value)result.postFx.skybox.enabled=false;
if(key==='postFx.skybox.enabled'&&value)result.postFx.envAtlas.enabled=false;
return result;
}
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]};
export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+Object.values(m.textures).reduce((n,t)=>n+(t?.data.length??0),0),0);}
export function parseScene(raw:unknown):SceneDocument{
const r=raw as SceneDocument;if(!r||r.schema!=='missioncore.rover-scene/v1'||r.model!=='dcd006-v020-materials-v2')throw new Error('Файл сцены не подходит к этой модели.');
let doc=defaultScene();
for(const f of environmentFields){const v=fieldValue(r,f.key);if(v!==undefined)doc=changeField(doc,f.key,v);}
if(Object.keys(r.materials??{}).length>128)throw new Error('В сцене может быть не больше 128 материалов.');
for(const id of Object.keys(r.materials??{}))if(id.startsWith('custom/'))doc=createMaterial(doc,id);
for(const [id,base] of Object.entries(doc.materials)){
const m=r.materials?.[id];if(!m)continue;
if(typeof m.name==='string')base.name=m.name.trim().slice(0,120)||base.name;
for(const key of ['color','emissive'] as const)if(/^#[0-9a-f]{6}$/i.test(m[key]))base[key]=m[key];
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSpec];if(typeof v==='number'&&Number.isFinite(v))(base as any)[key]=Math.max(lo,Math.min(hi,v));}
if(typeof m.doubleSided==='boolean')base.doubleSided=m.doubleSided;
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');base.textures[slot]={name:t.name.slice(0,200),data:t.data};}
}
for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id);
if(textureBytes(doc)>28_000_000)throw new Error('Суммарный объём текстур превышает 20 МБ.');
return doc;
}
@@ -0,0 +1,21 @@
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
// Fingerprint of the first editor's withdrawn neutral preset. Match the entire
// environment: independently edited environments must never be reset on load.
function withdrawnEnvironment(){
const fx=defaultScene().postFx;
Object.assign(fx.lighting,{exposure:1.1,skyBoxIntensity:1,ambientIntensity:.22});
Object.assign(fx.envAtlas,{reflectionIntensity:1,brightness:1.2});
Object.assign(fx.rendering,{backgroundColor:'#202227',fog:'none',toneMapping:4});
Object.assign(fx.grid,{colorMain:'#747982',colorX:'#93969c',colorZ:'#93969c',alphaMain:.25,alphaX:.35,alphaZ:.35,fadeStart:2,fadeEnd:5,step:.5,diameter:12});
fx.chromaticAberration.enabled=false;fx.vignette.enabled=false;fx.grading.enabled=false;fx.bloom.enabled=false;
Object.assign(fx.directionalLight,{intensity:1.8,azimuth:135,elevation:45});
Object.assign(fx.shadowCatcher,{size:4,lightIntensity:.5,shadowIntensity:.25});
return fx;
}
export function loadStoredScene(raw:unknown):{document:SceneDocument;updated:boolean;restoredEnvironment:boolean}{
const doc=parseScene(raw);
const updated=(raw as Partial<SceneDocument>).environmentVersion!==2;
const restoredEnvironment=updated&&JSON.stringify(doc.postFx)===JSON.stringify(withdrawnEnvironment());
return {document:restoredEnvironment?{...doc,postFx:defaultScene().postFx}:doc,updated,restoredEnvironment};
}
@@ -0,0 +1,23 @@
import type {SceneDocument} from './sceneDocument';
import {loadStoredScene} from './sceneMigration';
const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`;
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});}
export async function readScene(vehicle:string):Promise<SceneDocument|null>{
const db=await database();try{
const raw=await new Promise<unknown>((resolve,reject)=>{const r=db.transaction('scenes').objectStore('scenes').get(key(vehicle));r.onerror=()=>reject(r.error);r.onsuccess=()=>resolve(r.result);});
if(!raw)return null;
const result=loadStoredScene(raw);
if(result.updated)await new Promise<void>((resolve,reject)=>{
const tx=db.transaction('scenes','readwrite'),store=tx.objectStore('scenes');
if(result.restoredEnvironment)store.put(raw,`${key(vehicle)}:before-environment-v2`);
store.put(result.document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);
});
return result.document;
}finally{db.close();}
}
export async function saveScene(vehicle:string,document:SceneDocument):Promise<void>{const db=await database();try{await new Promise<void>((resolve,reject)=>{const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);});}finally{db.close();}}
export async function textureFromFile(file:File):Promise<{name:string;data:string}>{
if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8_000_000)throw new Error('Выберите PNG, JPEG или WebP до 8 МБ.');
const bitmap=await createImageBitmap(file);try{if(bitmap.width>4096||bitmap.height>4096)throw new Error('Максимальный размер текстуры — 4096 × 4096.');}finally{bitmap.close();}
return new Promise((resolve,reject)=>{const r=new FileReader();r.onerror=()=>reject(r.error);r.onload=()=>resolve({name:file.name,data:String(r.result)});r.readAsDataURL(file);});
}
@@ -0,0 +1,22 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
import {readScene,saveScene} from './sceneStorage';
let writes=Promise.resolve();
const enqueue=(vehicle:string,doc:SceneDocument)=>{const next=writes.catch(()=>{}).then(()=>saveScene(vehicle,doc));writes=next;return next;};
export function useSceneDocument(vehicle:string){
const [document,setDocument]=useState(defaultScene),[ready,setReady]=useState(false),[revision,setRevision]=useState(0);
const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState('');
const latest=useRef({document,revision,vehicle});latest.current={document,revision,vehicle};
const savedRevision=useRef(0);
useEffect(()=>{let cancelled=false;readScene(vehicle).then(value=>{if(!cancelled){setDocument(value??defaultScene());setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle]);
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{setDocument(d=>fn(d));setRevision(v=>v+1);setSaveState('saving');},[]);
useEffect(()=>{
if(!ready||revision===0)return;
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
return()=>{cancelled=true;clearTimeout(timer);};
},[ready,revision,vehicle,document]);
useEffect(()=>()=>{const v=latest.current;if(v.revision>savedRevision.current)void enqueue(v.vehicle,v.document).catch(()=>{});},[]);
const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()));update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download='rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return {document,ready,saveState,error,setError,update,importDocument,exportDocument};
}
@@ -0,0 +1,17 @@
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint, type AiWorld } from "./aiPolygon";
export interface EditorCache {
local_scene?: { visual_url: string; collision_url: string; visual_rotation: number[]; collision_rotation: number[] };
key: string; world: AiWorld; status: "queued" | "preparing" | "uploading" | "ready" | "failed";
error: string | null;
files: Record<string, { sha256: string; byte_length: number; uploaded_bytes: number }>;
}
export const prepareEditor = (world: AiWorld, signal?: AbortSignal) => polygonRequest<EditorCache>(
`/worlds/${world.world_id}/editor-cache`, { method: "POST", signal });
export const fetchEditor = (key: string, signal?: AbortSignal) => polygonRequest<EditorCache>(`/editor-cache/${key}`, { signal });
export const editorAssetUrl = (key: string, name: string) => `/api/v1/ai-polygon/editor-cache/${key}/${name}`;
export const saveLocalPlan = (cache: EditorCache, robot: AiRobot, points: AiWaypoint[], name: string,
draftId: string, sequence: number) => polygonRequest<AiPlan>("/plans", { method: "POST", body: JSON.stringify({
cache_key: cache.key, robot_id: robot.robot_id, robot_sha256: robot.sha256,
draft_id: draftId, sequence, points, name,
}) });
export { toEditor, toMission } from "./aiEditorCoordinates";
@@ -0,0 +1,3 @@
/** Isaac uses Z up; the glTF/PlayCanvas editor uses Y up. This preserves handedness. */
export const toEditor = ([x, y, z]: number[]): [number, number, number] => [x, z, -y];
export const toMission = ([x, y, z]: number[]): [number, number, number] => [x, -z, y];
@@ -1,4 +1,6 @@
import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition"; import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition";
import type { RoverMotion } from "./roverMotion";
import type { RoverSettings } from "./roverSettings";
const API = "/api/v1/ai-polygon"; const API = "/api/v1/ai-polygon";
@@ -28,14 +30,29 @@ export interface AiSource {
description?: string; description?: string;
} }
export interface AiWorld extends AiSource { 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; world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
status: "uploading" | "available"; sha256: string | null; splat_count: number | null; status: "uploading" | "available"; sha256: string | null; splat_count: number | null;
settings: AiWorldSettings; 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 { export interface AiRun {
run_id: string; run_id: string;
created_at?: string;
world: AiWorld; 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"; state: "starting" | "ready" | "running" | "paused" | "stopping" | "completed" | "stopped" | "failed" | "disconnected";
clock?: "lockstep" | "realtime"; clock?: "lockstep" | "realtime";
control?: "play" | "pause" | "stop"; control?: "play" | "pause" | "stop";
@@ -57,20 +74,57 @@ export interface AiRun {
road_fraction: number; obstacle_count: number }; 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 type AiCamera = "follow" | "overview" | "camera";
export interface AiStreamEndpoint { export interface AiStreamEndpoint {
server: string; signaling_port: number; media_port: number; width: number; height: number; fps: number; server: string; signaling_port: number; media_port: number; width: number; height: number; fps: number;
} }
export interface AiTelemetry { export interface AiTelemetry {
distance_m?: number | null;
sequence: number; control_sequence: number; simulation_time_ns: number; sequence: number; control_sequence: number; simulation_time_ns: number;
rtf: number; render_fps: number; sensor_fps: number; ai_hz: 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; inference_ms: number | null; frame_age_ms: number | null; command_age_ms: number | null;
speed_mps: number; applied_speed_mps: number; stop_reason: string; speed_mps: number; applied_speed_mps: number; stop_reason: string;
ai_ready: boolean; stream_ready: boolean; camera: AiCamera; ai_ready: boolean; stream_ready: boolean; camera: AiCamera;
decision: NonNullable<AiRun["last_sample"]>["decision"] | null; decision: NonNullable<AiRun["last_sample"]>["decision"] | null;
planning?: AiPlanningState | null;
route_overlay?: AiRouteOverlay | null;
}
export interface AiWaypoint { id: string; position: [number, number, number] }
export type ScreenPoint = [number, number] | null;
export interface AiRouteOverlay {
markers: (AiWaypoint & { index: number; base: ScreenPoint; top: ScreenPoint;
x_axis: ScreenPoint; y_axis: ScreenPoint })[];
trace: ScreenPoint[]; active_index: number; view_revision: number;
}
export interface AiPlanningState { sequence: number; view_revision: number; points: AiWaypoint[];
error: string | null; can_undo: boolean; clip_height: number | null;
height_min?: number | null; height_max?: number | null; camera_moving?: boolean }
export interface AiPlan { plan_id: string; name: string; sha256: string; world_id: string;
settings?: Pick<AiWorldSettings, "max_speed_mps">;
display_name?: string; removed?: boolean;
editor_cache_key?: string;
robot_id: string; robot_sha256: string; points: AiWaypoint[]; length_m: number; created_at: string }
export interface AiPlanningCommand {
action: "orbit" | "pan" | "zoom" | "fly" | "home" | "add" | "move" | "delete" | "clear" | "clip" | "undo";
point_id?: string; x?: number; y?: number; amount?: number; enabled?: boolean; axis?: "x" | "y" | "xy";
} }
export interface AiCatalog { export interface AiCatalog {
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[]; sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
robots: AiRobot[];
plans: AiPlan[];
runtime: { available: boolean; active_run: AiRun | null }; runtime: { available: boolean; active_run: AiRun | null };
} }
@@ -87,13 +141,29 @@ export async function polygonRequest<T>(path: string, init: RequestInit = {}): P
} }
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`; export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog"); 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) => export const configureAiWorld = (world: AiWorld, settings: AiWorldSettings) =>
polygonRequest<AiWorld>(`/worlds/${world.world_id}/settings`, { polygonRequest<AiWorld>(`/worlds/${world.world_id}/settings`, {
method: "PUT", body: JSON.stringify(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() }, 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) => export const setAiCamera = (run: AiRun, camera: AiCamera) =>
polygonRequest<AiRun>(`/runs/${run.run_id}/view`, { method: "PUT", body: JSON.stringify({ camera }) }); polygonRequest<AiRun>(`/runs/${run.run_id}/view`, { method: "PUT", body: JSON.stringify({ camera }) });
@@ -0,0 +1,20 @@
import {polygonRequest,type AiSelection} from './aiPolygon';
export interface AiProfile {
profile_id:string; name:string; composition:AiSelection; revision:number; removed:boolean;
}
export const fetchAiProfiles=()=>polygonRequest<AiProfile[]>('/ai-profiles');
export const createAiProfile=(name:string,composition:AiSelection)=>polygonRequest<AiProfile>('/ai-profiles',
{method:'POST',body:JSON.stringify({name,composition})});
export const updateAiProfile=(profile:AiProfile,changes:{name?:string;composition?:AiSelection;removed?:boolean})=>
polygonRequest<AiProfile>(`/ai-profiles/${profile.profile_id}`,
{method:'PATCH',body:JSON.stringify({expected_revision:profile.revision,...changes})});
/** Saved intent survives installed module revisions; admission rebinds SHA-256. */
export function sameAiIntent(a:AiSelection,b:AiSelection):boolean {
const stable=(value:unknown):unknown=>Array.isArray(value)?value.map(stable):value&&typeof value==='object'
?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>[k,stable(v)])):value;
const intent=(value:AiSelection)=>value.selections.map(({group,module_id,parameters})=>({group,module_id,parameters}))
.sort((a,b)=>a.group.localeCompare(b.group));
return JSON.stringify(stable(intent(a)))===JSON.stringify(stable(intent(b)));
}
@@ -0,0 +1,25 @@
import { PerspectiveCamera, Quaternion, Vector3 } from "three";
const UP = new Vector3(0,1,0);
/** Depth along the optical axis gives a metric screen-space pan at any zoom. */
export function navigationDepth(camera: PerspectiveCamera, anchor: Vector3) {
return Math.max(.1, anchor.clone().sub(camera.position).dot(camera.getWorldDirection(new Vector3())));
}
export function panCamera(camera: PerspectiveCamera, depth: number, dx: number, dy: number, height: number) {
const scale=2*depth*Math.tan(camera.fov*Math.PI/360)/Math.max(1,height);
camera.position.add(new Vector3(-dx*scale,dy*scale,0).applyQuaternion(camera.quaternion));
camera.updateMatrixWorld();
}
/** Rotate the complete camera pose about the picked point: no lookAt snap.
* The picked point keeps its screen coordinates, including off-centre clicks. */
export function orbitCamera(camera: PerspectiveCamera, anchor: Vector3, dx: number, dy: number, height: number) {
const factor=2*Math.PI/Math.max(1,height);
const yaw=new Quaternion().setFromAxisAngle(UP,-dx*factor);
const forward=camera.getWorldDirection(new Vector3());
const elevation=Math.asin(Math.max(-1,Math.min(1,forward.y)));
const pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,elevation-dy*factor))-elevation;
const right=new Vector3(1,0,0).applyQuaternion(camera.quaternion).applyQuaternion(yaw);
const rotation=new Quaternion().setFromAxisAngle(right,pitch).multiply(yaw);
camera.position.sub(anchor).applyQuaternion(rotation).add(anchor);
camera.quaternion.premultiply(rotation);
camera.updateMatrixWorld();
}
@@ -0,0 +1,4 @@
/** Exponential dolly in metres, independent of OrbitControls' target radius. */
export function zoomDisplacement(depth: number, wheelPixels: number): number {
return depth * (1 - Math.exp(Math.max(-.8, Math.min(.8,wheelPixels*.002))));
}
@@ -0,0 +1,18 @@
export type GaussianQuality = "low" | "medium" | "high" | "ultra" | "maximum";
// PlayCanvas: zero disables count-budget enforcement; quality uses LOD distances only.
export const QUALITY_PROFILES: Record<GaussianQuality, {
lodBaseDistance: number;
lodMultiplier: number;
lodRangeMin: number;
lodRangeMax: number;
pixelRatio: number;
splatBudget: number;
targetFps: number;
}> = {
low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 0, targetFps: 30 },
medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 0, targetFps: 45 },
high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 0, targetFps: 60 },
ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 0, targetFps: 60 },
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 0, targetFps: 60 },
};
@@ -0,0 +1,8 @@
import type { AiPlan, AiWaypoint } from "./aiPolygon";
/** A launch may reuse a saved task only when it represents this exact draft. */
export function planMatchesDraft(plan:AiPlan|undefined, cacheKey:string, robotSha:string, points:AiWaypoint[]) {
return !!plan && plan.editor_cache_key===cacheKey && plan.robot_sha256===robotSha
&& plan.points.length===points.length && plan.points.every((point,i)=>point.id===points[i].id
&& point.position.every((value,axis)=>value===points[i].position[axis]));
}
@@ -0,0 +1,42 @@
import type { GaussianQuality } from "./gaussianQuality";
export interface PlannerPreferences {
quality: GaussianQuality;
navigation: { nearDistance:number; farDistance:number; nearPan:number; farPan:number; zoom:number; centroidPixels:number; centroidColor:string; centroidOpacity:number };
pivot: { pixels: number; diameter: number; cone: number; opacity: number; x: string; y: string; z: string };
waypoint: { diameter: number; height: number; color: string; opacity: number; frequency: number; emission: number; emissionColor: string };
}
export const PLANNER_PREFERENCES_KEY = "missioncore.simulation-view/v1";
export const DEFAULT_PLANNER_PREFERENCES: PlannerPreferences = {
quality: "medium",
navigation: { nearDistance:3, farDistance:100, nearPan:1, farPan:1, zoom:1, centroidPixels:14, centroidColor:"#edf0eb", centroidOpacity:.8 },
pivot: { pixels: 105, diameter: 5, cone: 22, opacity: 1, x: "#e85b54", y: "#83ca61", z: "#6499ed" },
waypoint: { diameter: .35, height: 4.5, color: "#edf0eb", opacity: .65, frequency: .5, emission: 1.5, emissionColor: "#edf0eb" },
};
/** Persisted operator preferences are untrusted input; old/invalid fields get defaults. */
export function normalizePlannerPreferences(value: unknown): PlannerPreferences {
const v = value && typeof value === "object" ? value as Partial<PlannerPreferences> : {};
const p: Partial<PlannerPreferences["pivot"]> = v.pivot ?? {}, w: Partial<PlannerPreferences["waypoint"]> = v.waypoint ?? {}, d = DEFAULT_PLANNER_PREFERENCES;
const n = (x: unknown, fallback: number, min: number, max: number) => typeof x === "number" && Number.isFinite(x) ? Math.max(min, Math.min(max,x)) : fallback;
const color = (x: unknown, fallback: string) => typeof x === "string" && /^#[0-9a-f]{6}$/i.test(x) ? x : fallback;
const nav:Partial<PlannerPreferences["navigation"]>=v.navigation??{}, dn=d.navigation;
const nearDistance=n(nav.nearDistance,dn.nearDistance,.5,50);
return {
navigation: {nearDistance,farDistance:Math.max(nearDistance+1,n(nav.farDistance,dn.farDistance,2,500)),
nearPan:n(nav.nearPan,dn.nearPan,.1,5),farPan:n(nav.farPan,dn.farPan,.1,5),zoom:n(nav.zoom,dn.zoom,.1,3),
centroidPixels:n(nav.centroidPixels,dn.centroidPixels,6,64),centroidColor:color(nav.centroidColor,dn.centroidColor),centroidOpacity:n(nav.centroidOpacity,dn.centroidOpacity,.1,1)},
quality: ["low","medium","high","ultra","maximum"].includes(v.quality ?? "") ? v.quality! : d.quality,
pivot: { pixels:n(p.pixels,d.pivot.pixels,50,220), diameter:n(p.diameter,d.pivot.diameter,2,16), cone:n(p.cone,d.pivot.cone,10,40), opacity:n(p.opacity,d.pivot.opacity,.15,1),
x:color(p.x,d.pivot.x), y:color(p.y,d.pivot.y), z:color(p.z,d.pivot.z) },
waypoint: { diameter:n(w.diameter,d.waypoint.diameter,.05,3), height:n(w.height,d.waypoint.height,.2,50), color:color(w.color,d.waypoint.color), opacity:n(w.opacity,d.waypoint.opacity,.1,1), frequency:n(w.frequency,d.waypoint.frequency,0,3), emission:n(w.emission,d.waypoint.emission,0,5), emissionColor:color(w.emissionColor,d.waypoint.emissionColor) },
};
}
export function axisWorldLength(depth: number, height: number, pixels: number) {
return Math.max(.01, depth) * 2 * Math.tan(Math.PI / 6) * pixels / Math.max(1,height);
}
export function panSensitivity(distance:number,navigation:PlannerPreferences["navigation"]) {
const t=Math.max(0,Math.min(1,(distance-navigation.nearDistance)/(navigation.farDistance-navigation.nearDistance)));
const smooth=t*t*(3-2*t);
return navigation.nearPan+(navigation.farPan-navigation.nearPan)*smooth;
}
@@ -0,0 +1,20 @@
export interface RoverMotion {
schema_version: "missioncore.rover-motion/v1";
length_m: number; pitch_m: number; phase_m: number; link_count: number;
track_width_m: number; track_centres_m: { L: number; R: number }; shift_m: number[];
segments: ["arc" | "line", number, number, number[]][];
wheels: { node: string; radius_m: number }[];
}
export function beltPose(motion: RoverMotion, distance: number, side: "L" | "R", index: number) {
const s = ((distance + motion.phase_m + index*motion.pitch_m) % motion.length_m + motion.length_m) % motion.length_m;
const segment = motion.segments.find(([, start, length]) => s <= start+length+1e-10)!;
const [kind,start,,d] = segment, t = s-start;
let x: number, z: number, angle: number;
if (kind === "arc") {
const [cx,cz,r,a] = d, q = a-t/r;
x=cx+r*Math.cos(q); z=cz+r*Math.sin(q); angle=q-Math.PI/2;
} else {
x=d[0]+d[2]*t; z=d[1]+d[3]*t; angle=Math.atan2(d[3],d[2]);
}
return { position:[x+motion.shift_m[0],z+motion.shift_m[2],-motion.track_centres_m[side]-motion.shift_m[1]], angle };
}
@@ -0,0 +1,32 @@
import type { AiRobot } from "./aiPolygon";
export interface RoverSettings {
schema_version: "missioncore.rover-settings/v2";
max_speed_mps: number;
base_mass_kg: number;
payload_mass_kg: number;
payload_height_m: number;
}
export const roverSettingsKey = (robot: AiRobot) => `nodedc.simulation.rover.v1:${robot.robot_id}:${robot.sha256}`;
export function defaultRoverSettings(robot: AiRobot, speed: number): RoverSettings {
return { schema_version: "missioncore.rover-settings/v2",
max_speed_mps: Math.max(.05, Number.isFinite(speed) ? speed : .3),
base_mass_kg: robot.physics.mass_kg, payload_mass_kg: 0,
payload_height_m: Math.round((robot.physics.height_m + .1) * 100) / 100 };
}
export function validRoverSettings(value: RoverSettings, _robot: AiRobot): boolean {
const within = (v:number, min:number, max:number) => Number.isFinite(v) && v>=min && v<=max;
return value.schema_version === "missioncore.rover-settings/v2"
&& within(value.max_speed_mps, .05, Infinity)
&& within(value.base_mass_kg,10,1000) && within(value.payload_mass_kg,0,500)
&& within(value.payload_height_m,.1,3);
}
export function parseRoverSettings(raw: string | null, robot: AiRobot): RoverSettings | undefined {
try {
const value = JSON.parse(raw ?? "null");
if (value?.schema_version === "missioncore.rover-settings/v1") value.schema_version = "missioncore.rover-settings/v2";
if (!value || !validRoverSettings(value,robot)
|| Object.keys(value).sort().join() !== "base_mass_kg,max_speed_mps,payload_height_m,payload_mass_kg,schema_version") return;
return value;
} catch { return; }
}
@@ -0,0 +1,36 @@
import type { AiModules, AiSelection } from "./aiPolygon";
const SCHEMA = "missioncore.observatory-ai-composition/v1";
const GROUPS = new Set(["segmentation", "detection", "geometry", "range", "motion", "policy"]);
/** Stored intent is untrusted. Worker admission still owns executable contracts. */
export function parseSavedSelection(raw: string | null): AiSelection | undefined {
try {
const value = JSON.parse(raw ?? "null");
if (value?.schema_version !== SCHEMA || !Array.isArray(value.selections)
|| !value.selections.length || value.selections.length > GROUPS.size) return;
const groups = new Set<string>();
for (const row of value.selections) {
if (!row || !GROUPS.has(row.group) || groups.has(row.group)
|| typeof row.module_id !== "string" || !/^[a-z0-9][a-z0-9-]{0,127}$/.test(row.module_id)
|| typeof row.module_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.module_sha256)
|| !row.parameters || typeof row.parameters !== "object" || Array.isArray(row.parameters)) return;
groups.add(row.group);
}
return value as AiSelection;
} catch { return; }
}
/** Rebind every chosen provider, including alternatives absent from defaults. */
export function currentSelection(selection: AiSelection, installed: AiModules): AiSelection {
return { ...selection, selections: selection.selections.map(row => {
const module = installed.catalog.groups.find(group => group.group === row.group)
?.modules.find(candidate => candidate.moduleId === row.module_id);
if (!module) throw new Error("Выбранный AI-модуль больше недоступен. Проверьте конфигурацию AI.");
return { ...row, module_sha256: module.moduleSha256,
parameters: { ...module.defaults, ...row.parameters } };
}) };
}
export const selectionStorageKey = (world: string, robot: string) =>
`nodedc.simulation.composition.v1:${world}:${robot}`;
@@ -0,0 +1,5 @@
/** A bounded first-frame/stall watchdog, independent of SDK callbacks. */
export function streamRecovery(now:number,started:number,lastFrame:number|null,failedAt:number|null,attempt:number) {
const expired=failedAt!==null ? now-failedAt>=2000 : lastFrame===null ? now-started>=20000 : now-lastFrame>=10000;
return !expired?"wait":attempt<2?"retry":"failed";
}
@@ -0,0 +1,20 @@
import { useMemo, useState } from "react";
import type { AiModules, AiSelection } from "./aiPolygon";
import { parseSavedSelection, selectionStorageKey } from "./runConfiguration";
/** Location/robot intent survives reload; changing location never carries it over. */
export function useAiSelection(world: string | null, robot: string | null, modules: AiModules | null) {
const scope = world && robot ? selectionStorageKey(world, robot) : null;
const [draft, setDraft] = useState<{ scope: string | null; value: AiSelection } | null>(null);
const saved = useMemo(() => {
try { return scope ? parseSavedSelection(localStorage.getItem(scope)) : undefined; }
catch { return undefined; }
}, [scope]);
const selection = draft?.scope === scope ? draft.value : saved ?? modules?.selection;
const setSelection = (value: AiSelection) => {
setDraft({ scope, value });
try { if (scope) localStorage.setItem(scope, JSON.stringify(value)); }
catch { /* In-memory intent remains usable if browser storage is unavailable. */ }
};
return [selection, setSelection] as const;
}

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