Compare commits

...
10 Commits
342 changed files with 20366 additions and 1130 deletions
+1
View File
@@ -12,3 +12,4 @@
apps/control-station/vendor/rerun-web-viewer-0.34.1/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
apps/control-station/public/rover-scene/*.glb filter=lfs diff=lfs merge=lfs -text
apps/control-station/public/battery-scene/*.glb filter=lfs diff=lfs merge=lfs -text
Binary file not shown.
@@ -0,0 +1,119 @@
{
"source": "Cattle_Battery_Enclosure_R04.blend",
"source_sha256": "ec802dfbc2866ab474ce5f809ea9289f2402ec791c0abccb22826620af78a42b",
"model": "catl-r04.glb",
"sha256": "1f4ac32560ac1906abd92e7c3be35f852ce166ead700f5e27c3b3ce2bdcc7dd3",
"bytes": 39541516,
"groups": 63,
"cell_bodies": 13,
"objects": [
"bms/Cable / red silicone",
"bms/Cable / graphite silicone",
"bms/Mount / G10 dielectric",
"bms/Nickel plated copper / busbars",
"bms/Sense / warm yellow",
"bms/labels/electronics",
"bms/Connector / ivory polymer",
"bms/BMS / green PCB",
"bms/Aluminium / satin",
"bms/Lid / insulating black",
"bms/Mount / adhesive film",
"bms/Steel / fasteners",
"bms/cells/C01",
"bms/Cell / wrapped lower edge",
"bms/labels/cells",
"bms/cell-display/C01",
"bms/cells/C02",
"bms/cell-display/C02",
"bms/cells/C03",
"bms/cell-display/C03",
"bms/cells/C04",
"bms/cell-display/C04",
"bms/cells/C05",
"bms/cell-display/C05",
"bms/cells/C06",
"bms/cell-display/C06",
"bms/cells/C07",
"bms/cell-display/C07",
"bms/cells/C08",
"bms/cell-display/C08",
"bms/cells/C09",
"bms/cell-display/C09",
"bms/cells/C10",
"bms/cell-display/C10",
"bms/cells/C11",
"bms/cell-display/C11",
"bms/cells/C12",
"bms/cell-display/C12",
"bms/cells/C13",
"bms/cell-display/C13",
"bms/CASE | bead-blasted graphite/CASE | base tray",
"bms/CASE | bead-blasted graphite/CASE | front endplate",
"bms/CASE | bead-blasted graphite/CASE | rear endplate",
"bms/glass/CASE | removable solid top",
"bms/glass/CASE | slotted side -1",
"bms/glass/CASE | slotted side 1",
"bms/R04 | elastomer seal",
"bms/R04 | graphite moulded polymer",
"bms/labels/enclosure",
"bms/R04 | smoked polycarbonate",
"bms/R04 | display protective polycarbonate",
"bms/DISPLAY | black glass",
"bms/CASE | recessed black",
"bms/CASE | darker frame",
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return",
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return.001",
"bms/CASE | bead-blasted graphite/HANDLE | integral web underside",
"bms/CASE | dielectric liner",
"bms/CASE | dielectric liner/left",
"bms/CASE | dielectric liner/right",
"bms/Connector / gold plated contacts",
"bms/XT90-S / anti spark green insert",
"bms/XT90-S / yellow PA housing"
],
"materials": [
"bms/Cable / red silicone",
"bms/Cable / graphite silicone",
"bms/Mount / G10 dielectric",
"bms/Nickel plated copper / busbars",
"bms/Sense / warm yellow",
"bms/labels",
"bms/Connector / ivory polymer",
"bms/BMS / green PCB",
"bms/Aluminium / satin",
"bms/Lid / insulating black",
"bms/Mount / adhesive film",
"bms/Steel / fasteners",
"bms/cells",
"bms/Cell / wrapped lower edge",
"bms/cell-display/C01",
"bms/cell-display/C02",
"bms/cell-display/C03",
"bms/cell-display/C04",
"bms/cell-display/C05",
"bms/cell-display/C06",
"bms/cell-display/C07",
"bms/cell-display/C08",
"bms/cell-display/C09",
"bms/cell-display/C10",
"bms/cell-display/C11",
"bms/cell-display/C12",
"bms/cell-display/C13",
"bms/CASE | bead-blasted graphite",
"bms/glass",
"bms/R04 | elastomer seal",
"bms/R04 | graphite moulded polymer",
"bms/R04 | smoked polycarbonate",
"bms/R04 | display protective polycarbonate",
"bms/DISPLAY | black glass",
"bms/CASE | recessed black",
"bms/CASE | darker frame",
"bms/CASE | dielectric liner",
"bms/Connector / gold plated contacts",
"bms/XT90-S / anti spark green insert",
"bms/XT90-S / yellow PA housing"
],
"cell_displays": 13,
"uv": "cube_projection; original cell display faces use planar X/Z UV",
"source_modified": false
}
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -32,6 +32,26 @@ const additions = {
},
};
// Preserve the exact previous patch as an audited upgrade path.
for (const [name, addition] of Object.entries(additions)) {
addition.previousCode = addition.code;
if (name === "index.d.ts") {
addition.code += " set_height_slice(lower: number | null, upper: number | null): boolean;\n get_height_bounds(): {min: number; max: number} | null;\n";
} else {
const typed = name === "index.ts";
addition.code += ` set_height_slice(lower${typed ? ": number | null" : ""}, upper${typed ? ": number | null" : ""})${typed ? ": boolean" : ""} {
if (!this.#handle) throw new Error("Rerun viewer is stopped");
const off = lower === null && upper === null;
return this.#handle.nodedc_height_slice(off ? undefined : (lower ?? -3e38), off ? undefined : (upper ?? 3e38));
}
get_height_bounds()${typed ? ": {min: number; max: number} | null" : ""} {
if (!this.#handle) throw new Error("Rerun viewer is stopped");
return JSON.parse(this.#handle.nodedc_height_bounds() ?? "null");
}
`;
}
}
// Validate the complete set before changing any installed file. A package
// upgrade, corrupt artifact or independently modified wrapper fails closed.
const writes = [];
@@ -39,9 +59,9 @@ for (const [name, identity] of Object.entries(manifest.files)) {
const current = readFileSync(resolve(packageRoot, name));
let output;
if (additions[name]) {
const { marker, code } = additions[name];
const { marker, code, previousCode } = additions[name];
const source = current.toString("utf8");
const original = source.includes(code) ? source.replace(code, "") : source;
const original = source.includes(code) ? source.replace(code, "") : source.replace(previousCode, "");
if (sha(original) !== identity.upstreamSha256 || original.split(marker).length !== 2) {
throw new Error(`Unexpected upstream wrapper: ${name}`);
}
@@ -49,7 +69,7 @@ for (const [name, identity] of Object.entries(manifest.files)) {
} else {
output = readFileSync(resolve(vendorRoot, identity.artifact));
if (sha(output) !== identity.sha256) throw new Error(`Corrupt navigation artifact: ${name}`);
if (![identity.upstreamSha256, identity.sha256].includes(sha(current))) {
if (![identity.upstreamSha256, identity.previousArtifactSha256, identity.sha256].includes(sha(current))) {
throw new Error(`Unexpected installed runtime: ${name}`);
}
}
+1
View File
@@ -786,6 +786,7 @@ export default function App() {
content={activeDefinition ? (
<ApplicationPanel
key={activeDefinition.id}
allowFullscreen={activeDefinition.kind === "vehicles"}
eyebrow={activeDefinition.eyebrow}
title={
activeDefinition.kind === "vehicles"
@@ -2,8 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { createIsolatedRerunHost } from "./rerun/isolatedRerunHost";
import { keepRecordedBlueprintSession } from "../core/observation/recordedBlueprintLifecycle";
import {
RECORDED_RERUN_ORBITAL_EYE,
RECORDED_RERUN_PLAN_EYE,
selectRecordedRerunCameraEye,
type RecordedRerunCameraEye,
} from "./rerun/recordedRerunCameraJournal";
@@ -148,10 +147,7 @@ export interface RerunViewportProps {
interface RerunBlueprintChannel {
endpointUrl: string;
cameraContract?: string | null;
appliedFollowTrajectory?: boolean | null;
pendingFollowCameraEye?: RecordedRerunCameraEye | null;
getCameraEye?: () => RecordedRerunCameraEye | null;
getCurrentTimeNs?: () => number | null;
channel: {
readonly ready: boolean;
send_rrd: (rrdBytes: Uint8Array) => void;
@@ -1649,16 +1645,9 @@ function RerunViewportInstance({
blueprintChannel = {
endpointUrl: recordedBlueprintUrl,
cameraContract: null,
appliedFollowTrajectory: null,
pendingFollowCameraEye: null,
getCameraEye: () => "get_camera_eye" in viewer
? viewer.get_camera_eye()
: null,
getCurrentTimeNs: () => {
const currentIdentity = recordedIdentityRef.current;
if (!currentIdentity) return null;
return viewer.get_current_time(currentIdentity.recordingId, "session_time");
},
channel,
};
blueprintChannelRef.current = blueprintChannel;
@@ -2114,29 +2103,7 @@ function RerunViewportInstance({
);
const cameraContractChanged = active.cameraContract !== cameraContract;
const abort = new AbortController();
const previousFollow = active.appliedFollowTrajectory ?? false;
const enablingFollow = recordedFollowTrajectory && !previousFollow;
const disablingFollow = !recordedFollowTrajectory && previousFollow;
const transitionEye = (enablingFollow || disablingFollow)
? active.getCameraEye?.()
: null;
if (enablingFollow && transitionEye) {
active.pendingFollowCameraEye = transitionEye;
} else if (disablingFollow) {
active.pendingFollowCameraEye = null;
}
const pendingFollowEye = recordedFollowTrajectory
? active.pendingFollowCameraEye ?? null
: null;
const requestBlueprint = async (
cameraEye?: RecordedRerunCameraEye,
eyeRelativeToTracking = false,
reactivateUpdates = false,
) => {
const currentTimeNs = active.getCurrentTimeNs?.();
if (eyeRelativeToTracking && currentTimeNs == null) {
throw new Error("Recorded tracking cursor is unavailable");
}
const requestBlueprint = async (cameraEye?: RecordedRerunCameraEye) => {
return fetchRecordedBlueprintRrd(recordedBlueprintUrl,
{...sceneSettings, showPoints: sceneSettings.showPoints && !pointDisplay.hidePoints}, identity, {
displayPointBank: pointDisplay.bank,
@@ -2152,12 +2119,11 @@ function RerunViewportInstance({
unifiedCameraShare: recordedUnifiedCameraShare,
planView: recordedPlanView,
cameraEye,
eyeRelativeToTracking,
// Only following-eye transitions need a pose at the cursor. Supplying
// time for display-only updates makes the API scan the entire archive
// for camera bounds, although neither the camera nor its pose changed.
currentTimeNs: eyeRelativeToTracking ? currentTimeNs : undefined,
reactivateUpdates,
// The native controller owns continuous tracking and its world eye.
// Reinterpreting this as a rig-relative eye snaps an off-centre view
// back onto the rig. It also needlessly scans the recording for a pose.
eyeRelativeToTracking: false,
reactivateUpdates: true,
});
};
const canApply = () => (
@@ -2175,43 +2141,14 @@ function RerunViewportInstance({
return true;
};
void (async () => {
const firstEye = disablingFollow
? transitionEye ?? undefined
: !enablingFollow && (cameraContractChanged || pendingFollowEye)
? pendingFollowEye ?? (recordedPlanView ? RECORDED_RERUN_PLAN_EYE : RECORDED_RERUN_ORBITAL_EYE)
: !enablingFollow ? active.getCameraEye?.() ?? undefined : undefined;
const firstEyeIsTrackingRelative = Boolean(firstEye) && (
disablingFollow || recordedFollowTrajectory
// Reactivating a blueprint replaces the edited native store. Carry its
// actual eye through follow/layer/display changes in one update; only
// explicit reset and plan/3D changes select a startup preset.
const cameraEye = selectRecordedRerunCameraEye(
cameraContractChanged, recordedPlanView, active.getCameraEye?.() ?? null,
);
const firstPayload = await requestBlueprint(
firstEye,
firstEyeIsTrackingRelative,
// Upstream copies incoming blueprints into an active store. Every
// settings update must activate it; merely appending rows is invisible.
// Activation copies the incoming blueprint store, not the operator's
// edited store. Preserve its actual native eye on display-only updates;
// omitting the eye resurrects the embedded startup camera.
true,
);
if (!applyPayload(firstPayload)) return;
active.cameraContract = cameraContract;
active.appliedFollowTrajectory = recordedFollowTrajectory;
if (!enablingFollow || !transitionEye) {
if (pendingFollowEye && firstEye === pendingFollowEye) {
active.pendingFollowCameraEye = null;
}
return;
}
// Rerun 0.36.3 intentionally fits a newly tracked transform to its
// bounding box. Apply the operator's relative eye on the next native
// frame, after tracking is established, to retain direction and zoom.
await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
if (!canApply()) return;
const stabilizedPayload = await requestBlueprint(transitionEye, true, true);
if (!applyPayload(stabilizedPayload)) return;
active.pendingFollowCameraEye = null;
const payload = await requestBlueprint(cameraEye);
if (applyPayload(payload)) active.cameraContract = cameraContract;
})().catch((error: unknown) => {
// The recording remains usable with its embedded default blueprint.
// A later settings change retries through the same small channel.
@@ -0,0 +1,31 @@
import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Description,FeatureSettingsWindow,Icon,IconButton,RangeControl,SettingsCard} from '@nodedc/ui-react';
import {parseBatteryAppearance,type BatteryAppearance} from '../../core/batteryScene/appearance';
import type {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
type Section='markings'|'panels';
export function BatteryAppearanceSettings({open,onClose,profile}:{open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
const [section,setSection]=useState<Section>('markings'),input=useRef<HTMLInputElement>(null);
const {value,update}=profile,p=value.panels,m=value.markings;
const panel=(patch:Partial<BatteryAppearance['panels']>)=>update({...value,panels:{...p,...patch}});
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Интерфейс батареи',subtitle:'Локальный профиль',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Плашки показаний',icon:'settings'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
footer={<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
{section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
<ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow>
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
</SettingsCard>:<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
{range('Размер подписей, px',p.labelSize,10,20,labelSize=>panel({labelSize}))}
{range('Размер значений, px',p.valueSize,12,30,valueSize=>panel({valueSize}))}
<ControlRow label="Цвет текста"><ColorField label="Цвет текста" value={p.textColor} onChange={textColor=>panel({textColor})}/></ControlRow>
<ControlRow label="Цвет стекла"><ColorField label="Цвет стекла" value={p.glass.tintHex} onChange={tintHex=>glass({tintHex})}/></ControlRow>
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
</SettingsCard>}
<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>
</FeatureSettingsWindow>;
}
@@ -0,0 +1,35 @@
import {useEffect,useRef} from 'react';
import * as pc from 'playcanvas';
import type {PlayCanvasViewerProps} from '../rover/playcanvas/PlayCanvasViewer';
import type {CellMarkingAppearance} from '../../core/batteryScene/appearance';
import {cellDisplayIndex,drawCellDisplay} from '../../core/batteryScene/cellDisplay';
type Api=Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0];
/** GPU textures on the thirteen original Blender faces. Opaque geometry owns occlusion. */
export function BatteryCellLabels({api,values,ready,appearance}:{api:Api|null;values:readonly number[];ready:boolean;appearance:CellMarkingAppearance}){
const latest=useRef({values,appearance});latest.current={values,appearance};
useEffect(()=>{
if(!api||!ready)return;
const displays=(api.modelRoot.findComponents('render') as pc.RenderComponent[]).flatMap(component=>component.meshInstances).flatMap(mesh=>{
const index=cellDisplayIndex(mesh.node.name);if(index===null)return [];
const canvas=document.createElement('canvas');canvas.width=canvas.height=256;const ctx=canvas.getContext('2d');if(!ctx)return [];
const texture=new pc.Texture(api.app.graphicsDevice,{name:mesh.node.name,format:pc.PIXELFORMAT_SRGBA8,mipmaps:true,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});
const original=mesh.material,material=new pc.StandardMaterial();material.name=mesh.node.name;
material.diffuse.set(0,0,0);material.emissive.set(1,1,1);material.emissiveMap=texture;material.opacityMap=texture;material.opacityMapChannel='a';
material.useLighting=false;material.useFog=false;material.blendType=pc.BLEND_NORMAL;material.depthTest=true;material.depthWrite=false;material.cull=pc.CULLFACE_BACK;material.update();
return [{mesh,index,canvas,ctx,texture,material,original,signature:''}];
});
const update=()=>{for(const display of displays){
const {values,appearance}=latest.current,value=values[display.index],signature=JSON.stringify([Number.isFinite(value)?value:null,appearance.color,appearance.size]);
if(display.signature!==signature){drawCellDisplay(display.ctx,display.index,value,appearance);display.texture.setSource(display.canvas);display.texture.upload();display.signature=signature;}
// These material slots carry live readings; their appearance is owned by battery settings.
display.mesh.material=display.material;
}};
update();api.app.on('prerender',update);
let disposed=false;
const dispose=()=>{if(disposed)return;disposed=true;api.app.off('prerender',update);api.app.off('destroy',dispose);for(const display of displays){if(display.mesh.material===display.material)display.mesh.material=display.original;display.material.destroy();display.texture.destroy();}};
// Viewer cleanup precedes sibling effect cleanup. Release GPU resources before the device.
api.app.on('destroy',dispose);
return dispose;
},[api,ready]);
return null;
}
@@ -0,0 +1,20 @@
import type {CellMarkingAppearance} from '../../core/batteryScene/appearance';
import {BatteryCellLabels} from './BatteryCellLabels';
import type {PlayCanvasViewerProps} from '../rover/playcanvas/PlayCanvasViewer';
import {useMemo,useState} from 'react';
import {Description} from '@nodedc/ui-react';
import {SceneEditor} from '../rover/editor/RoverScene';
import {useSceneDocument} from '../../core/roverScene/useSceneDocument';
import {batterySceneProfile,defaultBatteryScene} from '../../core/batteryScene/profile';
export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){
const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]);
const scene=useSceneDocument(deviceId,profile);
const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading');
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R04">
<SceneEditor scene={scene} defaults={defaultBatteryScene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v5" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
<BatteryCellLabels api={api} ready={phase==='ready'} values={cellVoltages} appearance={markingAppearance}/>
{phase!=='ready'&&<div className="bms-scene-status"><Description role="status">{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}</Description></div>}
</div>;
}
@@ -0,0 +1,22 @@
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
import {useEffect,useState,type ReactNode} from 'react';
import {createPortal} from 'react-dom';
import {EditorWorkspace,Icon,IconButton,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
import {batteryViewHeight,batteryViewHeightKey,minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back}:{deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
const full=useApplicationPanelFullscreen(),[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
const profile=useBatteryAppearance(deviceId,settings);
const [height,setHeight]=useState(()=>{try{return batteryViewHeight(localStorage.getItem(batteryViewHeightKey(deviceId)),window.innerHeight);}catch{return batteryViewHeight(null,window.innerHeight);}});
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{
if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return;
event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back();
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
const commitHeight=(value:number)=>{try{localStorage.setItem(batteryViewHeightKey(deviceId),JSON.stringify({height:value}));setError('');}catch{setError('Не удалось сохранить высоту окна на этом компьютере.');}};
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>;
}
@@ -0,0 +1,11 @@
import {Fragment,useEffect,useState} from 'react';
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
</SettingsCard>;
}
@@ -0,0 +1,15 @@
import {useRef} from 'react';
import {Button,Description,Icon,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {useNetBirdBackups} from '../../core/fleet/useNetBirdBackups';
export function NetBirdBackups(){
const {items,loading,busy,error,upload}=useNetBirdBackups();const input=useRef<HTMLInputElement>(null);
return <SettingsCard title="Резервные копии сети" description="Полная копия базы NetBird, ключей и зарегистрированных устройств хранится в этом Mission Core отдельно от VPS. Она содержит секреты сети." actions={<StatusBadge tone={items.length?'success':'warning'}>{loading?'Проверяем хранилище':items.length?`Сохранено: ${items.length}`:'Копий пока нет'}</StatusBadge>}>
<Description>После изменения устройств или настроек сети сохраните свежую копию. Автоматическое получение копий пока не настроено.</Description>
<input ref={input} type="file" accept=".zip,application/zip" hidden aria-label="Полная резервная копия NetBird" disabled={busy} onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(file)void upload(file);}}/>
<Button icon={<Icon name="upload"/>} loading={busy} disabled={busy||loading} onClick={()=>input.current?.click()}>Сохранить копию в Mission Core</Button>
{error&&<StatusBadge tone="danger">{error}</StatusBadge>}
{items.map(item=><SettingsCard key={item.id} title={item.domain} description={`Сохранена ${new Date(item.stored_at).toLocaleString('ru-RU')} · ${(item.bytes/1024/1024).toFixed(1)} МиБ · Контрольные суммы проверены`}>
<Button icon={<Icon name="download"/>} onClick={()=>{const link=document.createElement('a');link.href=`/api/v1/fleet/netbird/backups/${item.id}/download`;link.download='mission-core-netbird-backup.zip';link.click();}}>Скачать для восстановления</Button>
</SettingsCard>)}
</SettingsCard>;
}
@@ -0,0 +1,36 @@
import {useEffect,useState} from 'react';
import {Button,Description,Icon,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
import {InstallerCard} from './InstallerCard';
import {NetBirdBackups} from './NetBirdBackups';
import {useNetBird,type NetBirdState} from '../../core/fleet/useNetBird';
const labels:Record<NetBirdState,string>={missing_client:'Клиент не установлен',unsupported_client:'Требуется другая версия клиента',unavailable:'Клиент недоступен',disconnected:'Не подключён',connecting:'Подключение',connected:'Подключён',other_network:'Клиент подключён к другой сети',address_conflict:'Проверьте адресацию сервера'};
export function NetBirdConnection(){
const network=useNetBird();const {status,clients,error,busy,clientError}=network;
const [server,setServer]=useState(''),[edited,setEdited]=useState(false),[installer,setInstaller]=useState('macos');
useEffect(()=>{if(!edited&&status?.server_url)setServer(status.server_url);},[status?.server_url,edited]);
const selected=clients.find(item=>item.id===installer);
const state=status?.pending==='installing'?'Устанавливаем клиент':status?.pending==='cancelling'?'Отменяем подключение':status?.pending==='authentication'?'Требуется вход':status?.pending==='verifying'?'Проверяем соединение':status?.pending?'Подключаемся':status?labels[status.state]:'Получаем состояние';
return <>
<InstallerCard kind="vps-netbird"/>
<NetBirdBackups/>
<SettingsCard title="Этот компьютер" description="NetBird соединяет компьютеры через ваш сервер. Вход выполняется в браузере; подключение поддерживает системный клиент." actions={<StatusBadge tone={busy?'warning':status?.state==='connected'?'success':'neutral'}>{state}</StatusBadge>}>
<TextField label="Адрес сервера NetBird" placeholder="https://netbird.example.com" value={server} maxLength={300} disabled={busy} onChange={event=>{setEdited(true);setServer(event.target.value);}} hint="Адрес выдаёт установщик VPS или администратор вашей сети."/>
{status?.state==='connected'&&<Description>Адрес этого компьютера: {status.address}</Description>}
{status?.can_install&&['missing_client','unsupported_client'].includes(status.state)&&<Button disabled={busy||!clients.find(item=>item.id==='macos')?.available} onClick={()=>void network.action('install')}>Установить клиент на этот Mac</Button>}
<Button variant="primary" disabled={busy||!server.trim()||!status||['missing_client','unsupported_client','unavailable','other_network'].includes(status.state)} onClick={()=>void network.action('connect',server)}>{status?.state==='connected'?'Проверить подключение':'Подключить этот компьютер'}</Button>
{status?.pending&&status.pending!=='installing'&&<Button disabled={network.requestBusy||status.pending==='cancelling'} onClick={()=>void network.action('cancel')}>Прекратить ожидание</Button>}
{status?.auth_url&&<Button onClick={()=>window.open(status.auth_url,'_blank','noopener,noreferrer')}>Войти на сервере</Button>}
{status?.pending==='installing'&&<Description>Подтвердите системный запрос macOS. Пароль администратора вводится только в системном окне.</Description>}
{(error||status?.error)&&<StatusBadge tone="danger">{error||status?.error}</StatusBadge>}
</SettingsCard>
<SettingsCard title="Клиенты для других компьютеров" description={`Официальные установщики NetBird${status?.client_version?' '+status.client_version:''}. Файлы хранятся в этом Mission Core и проверяются перед скачиванием.`}>
{clientError&&<StatusBadge tone="danger">{clientError}</StatusBadge>}
<Select label="Операционная система" value={installer} options={clients.map(item=>({value:item.id,label:item.label}))} onChange={setInstaller}/>
<Button icon={<Icon name="download"/>} disabled={!selected?.available} onClick={()=>{if(selected){const link=document.createElement('a');link.href=selected.download_url;link.download=selected.filename;link.click();}}}>Скачать клиент</Button>
<Description>Установите клиент, укажите этот же адрес сервера в его настройках и выполните вход. Mission Core на другом компьютере для подключения к сети не требуется.</Description>
{installer.startsWith('linux')&&<Description>Пакет «интерфейс» устанавливается вместе с основным клиентом той же версии. Для устройства без экрана используйте ключ подключения из панели NetBird.</Description>}
{selected&&!selected.available&&<Description>Этот установщик пока отсутствует в локальном каталоге.</Description>}
</SettingsCard>
</>;
}
@@ -0,0 +1,9 @@
import {Button,Window,WindowFooterActions} from '@nodedc/ui-react';
import {NetBirdConnection} from './NetBirdConnection';
export function OperatorNetworkWindow({onClose}:{onClose:()=>void}){
return <Window open title="Сеть операторского компьютера" subtitle="NetBird · WireGuard" size="lg" onClose={onClose}
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button></WindowFooterActions>}>
<NetBirdConnection/>
</Window>;
}
@@ -1,5 +1,7 @@
.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-center--expanded { position:fixed; inset:0; z-index:calc(var(--nodedc-layer-overlay) - 1); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
/* Inline fallback for browsers without state-preserving DOM moves. */
.nodedc-application-panel:has(.observation-center--expanded) { transform:none; overflow:visible; }
.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; }
@@ -13,6 +15,7 @@
.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--flow > .observation-mount { height:0; flex:1 1 0; }
.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; }
@@ -29,8 +32,10 @@
.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-source__notice--centered { inset:var(--observation-overlay-header-space, 0px) 0 0; margin:0; padding:var(--nodedc-space-4); display:grid; place-content:center; font-size:var(--nodedc-font-size-sm); pointer-events:none; }
/* Notices use the full viewport, independent of its overlaid header. */
.observation-source__notice { position:absolute; inset:0; box-sizing:border-box; margin:0; padding:var(--nodedc-space-4); display:flex; flex-direction:column; align-items:center; justify-content:center; gap:var(--nodedc-space-3); text-align:center; font-family:inherit; font-size:var(--nodedc-font-size-sm); font-weight:400; line-height:1.4; color:var(--nodedc-text-muted); pointer-events:none; }
.observation-source__notice > p { margin:0; }
.observation-source__notice > button, .observation-source__notice > a { pointer-events:auto; }
.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); }
@@ -7,18 +7,58 @@ export function createIsolatedRerunHost(host: HTMLElement) {
let frame: HTMLIFrameElement | null = host.ownerDocument.createElement("iframe");
frame.title = "Синхронизированная запись";
frame.className = "rerun-viewport__runtime";
frame.src = "/rerun-runtime.html";
frame.loading = "eager";
let navigation: number | undefined;
let disposed = false;
let releaseFacade: (() => void) | null = null;
let releaseInput: (() => void) | null = null;
let frameWindow: RerunFrameWindow | null = null;
let rejectReady: ((reason: Error) => void) | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
const bootstrapAbort = new AbortController();
let markup: string | null = null;
let fetching = false;
const scheduleNavigation = () => {
if (disposed || navigation !== undefined) return;
const window = host.ownerDocument.defaultView;
const navigate = () => {
navigation = undefined;
if (disposed) return;
// Observation portals may exist before the asynchronous dock is mounted.
// Start the isolated realm only once its host belongs to the document.
if (host.isConnected === false) {
scheduleNavigation();
return;
}
frame!.src = "/rerun-runtime.html";
if (markup === null) {
if (fetching) return;
fetching = true;
// Fetch only the bundled, same-origin document. Inline it into the
// isolated realm so startup does not depend on a deferred iframe
// document navigation inside a dock/portal. Its assets use root URLs.
void fetch("/rerun-runtime.html", {signal: bootstrapAbort.signal, credentials: "same-origin", redirect: "error"})
.then(response => { if (!response.ok) throw new Error("Recorded viewer host failed to load"); return response.text(); })
.then(value => { if (!disposed) { markup = value; scheduleNavigation(); } })
.catch(() => { if (!disposed) { rejectReady?.(new Error("Recorded viewer host failed to load")); dispose(); } });
return;
}
frame!.srcdoc = markup;
if (frame!.parentNode !== host) host.append(frame!);
};
// A background operator tab may suspend animation frames completely.
// Bootstrap must progress independently of painting or focus.
if (window?.setTimeout) navigation = window.setTimeout(navigate, 50);
else navigate();
};
const dispose = () => {
if (disposed) return;
disposed = true;
if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation);
clearTimeout(timer);
bootstrapAbort.abort();
delete host.dataset.rerunCamera;
frame!.onload = null;
frame!.onerror = null;
releaseInput?.();
@@ -32,6 +72,7 @@ export function createIsolatedRerunHost(host: HTMLElement) {
frameWindow = null;
frame!.remove();
frame = null;
markup = null;
rejectReady?.(new Error("Recorded viewer was disposed"));
rejectReady = null;
}
@@ -39,21 +80,38 @@ export function createIsolatedRerunHost(host: HTMLElement) {
const ready = new Promise<{ viewer: RecordedRerunViewer; mount: HTMLElement }>((resolve, reject) => {
rejectReady = reject;
frame!.onload = () => {
const handleLoad = () => {
if (disposed) return;
try {
frameWindow = frame!.contentWindow as RerunFrameWindow | null;
const api = frameWindow?.missionCoreRerun;
if (!api && frame!.contentDocument?.URL === "about:blank") {
return;
}
if (!api || api.version !== 2) throw new Error("Recorded viewer host is unavailable");
const owner = createRecordedRerunFacade((request, bytes) => {
const current = frameWindow?.missionCoreRerun;
if (!current) throw new Error("Recorded viewer was disposed");
return current.invoke(request, bytes);
const response = current.invoke(request, bytes);
// Bounded, read-only evidence of the rendered eye at the existing
// playback poll. No extra timer, transport, history or camera writes.
if (JSON.parse(request).method === "get_current_time") {
try {
const eye = JSON.parse(current.invoke('{"method":"get-camera-eye"}'));
host.dataset.rerunCamera = JSON.stringify({
timeNs: JSON.parse(response).result ?? null, eye: eye.result ?? null,
});
} catch { delete host.dataset.rerunCamera; }
}
return response;
});
releaseFacade = owner.dispose;
api.connect(owner.notify);
releaseInput = relayIsolatedRerunInput(host, frameWindow, frame);
clearTimeout(timer);
bootstrapAbort.abort();
if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation);
navigation = undefined;
rejectReady = null;
frame!.onload = null;
frame!.onerror = null;
@@ -63,15 +121,21 @@ export function createIsolatedRerunHost(host: HTMLElement) {
dispose();
}
};
frame!.onerror = () => {
const handleError = () => {
reject(new Error("Recorded viewer host failed to load"));
dispose();
};
const bind = (element: HTMLIFrameElement) => {
element.onload = () => { if (frame === element) handleLoad(); };
element.onerror = () => { if (frame === element) handleError(); };
};
bind(frame!);
timer = setTimeout(() => {
reject(new Error("Recorded viewer host timed out"));
dispose();
}, 30_000);
});
host.append(frame);
scheduleNavigation();
return { ready, dispose };
}
@@ -26,3 +26,14 @@ export function readNativeRerunCameraEye(value: unknown): RecordedRerunCameraEye
};
return { position: vector("position"), lookTarget: vector("lookTarget"), eyeUp: vector("eyeUp") };
}
/** Select an eye for blueprint replacement, never implement camera motion. */
export function selectRecordedRerunCameraEye(
cameraContractChanged: boolean,
planView: boolean,
currentEye: RecordedRerunCameraEye | null,
): RecordedRerunCameraEye | undefined {
return cameraContractChanged
? (planView ? RECORDED_RERUN_PLAN_EYE : RECORDED_RERUN_ORBITAL_EYE)
: currentEye ?? undefined;
}
@@ -12,6 +12,8 @@ export type RecordedRerunViewer = Pick<WebViewer,
> & {
open_channel: (name?: string) => Channel;
get_camera_eye: () => RecordedRerunCameraEye | null;
set_height_slice: (lower:number|null,upper:number|null)=>boolean;
get_height_bounds: ()=>{min:number;max:number}|null;
};
/** Parent-owned values only. No SDK Promise or foreign prototype escapes. */
@@ -88,6 +90,8 @@ export function createRecordedRerunFacade(invoke: RerunInvoke | null) {
set_current_time: (...args) => command("set_current_time", args),
set_playing: (...args) => command("set_playing", args),
get_camera_eye: () => command("get-camera-eye"),
set_height_slice: (lower,upper) => command("set-height-slice",[lower,upper]),
get_height_bounds: () => command("get-height-bounds"),
};
return { facade, dispose, notify };
}
@@ -80,6 +80,13 @@ export function createRecordedRerunOwner(create: () => WebViewer, mount: HTMLEle
case "get-camera-eye": result = readNativeRerunCameraEye(
(required() as WebViewer & { get_camera_eye?(): unknown }).get_camera_eye?.(),
); break;
case "set-height-slice": {
const [lower,upper]=args;
if ([lower,upper].some(v=>v!==null&&(typeof v!=="number"||!Number.isFinite(v))) ||
(lower!==null&&upper!==null&&lower>upper)) throw new Error("Invalid height slice");
result=(required() as WebViewer & {set_height_slice?(lower:number|null,upper:number|null):boolean}).set_height_slice?.(lower,upper)??false;
} break;
case "get-height-bounds": result=(required() as WebViewer & {get_height_bounds?():{min:number;max:number}|null}).get_height_bounds?.()??null; break;
case "open": required().open(args[0]); break;
case "close": required().close(args[0]); break;
case "override_panel_state": required().override_panel_state(args[0], args[1]); break;
@@ -1,6 +1,7 @@
import {roverModelID} from '../../core/roverScene/model';
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {Button,EditorWorkspace,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {roverDevEvent} from '../../core/fleet/roverDevEvents';
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
@@ -11,7 +12,7 @@ import './rover.css';
const Scene=lazy(()=>import('./editor/RoverScene'));
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление вкл',driving:'Управление вкл',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выкл',fault:'Управление остановлено'};
export function RoverView({vehicleID,controller:c,header,active,observation}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
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 [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
@@ -29,7 +30,7 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
},[open,active]);
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]);
useEffect(()=>{if(persistableRoverSettings(settings))try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
useEffect(()=>{if(!active)stop();},[active,stop]);
useEffect(()=>{if(!active){stop();setEditing(false);}},[active,stop]);
useEffect(()=>{
if(!c.ready||!active||open||editing||!stage.current)return;
const scope=stage.current.closest<HTMLElement>('.observation-center')??stage.current;
@@ -45,8 +46,9 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
const speedValid=duty?settings.throttlePercent>=1&&settings.throttlePercent<=100:settings.maxErpm>=300&&settings.maxErpm<=3000;
const observing=observation??roverObservationStatus(c.state,c.connection);
const availability=observing.label??(c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null);
const tone=preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral';
const status=c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение');
const inputBlocked=c.ready&&!active;
const tone=inputBlocked||preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral';
const status=inputBlocked?'Управление приостановлено':c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение');
const running=c.armed||c.pending||c.recovering;
return <>
{createPortal(<><IconButton label={running?"Остановить управление":"Включить управление"} aria-pressed={running||open} onClick={running?stop:showSettings}><Icon name={running?'stop':'play'}/></IconButton><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)}
@@ -54,7 +56,8 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
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'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
<EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
@@ -69,10 +72,11 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
</div>
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
</div>}
</EditorWorkspace>
</div>
<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="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:'dcd006-v020',label:'DCD-006 · полный ровер v020'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
@@ -0,0 +1,14 @@
import {ColorField,ControlRow,Description,RangeControl,Switch} from '@nodedc/ui-react';
import type {ChargeGradient} from '../../../core/roverScene/chargeGradient';
export function ChargeGradientInspector({value,onChange}:{value:ChargeGradient;onChange:(value:ChargeGradient)=>void}){
const patch=(change:Partial<ChargeGradient>)=>onChange({...value,...change});
return <div className="rover-scene-fields">
<Switch label="Градиент по заряду" checked={value.enabled} onChange={enabled=>patch({enabled})}/>
<Description>Две пары цветов: при 0% и при 100%. Между ними — плавный переход по общему заряду батареи.</Description>
{(['lowA','lowB','highA','highB'] as const).map((key,i)=><ControlRow key={key} label={['0% · цвет A','0% · цвет B','100% · цвет A','100% · цвет B'][i]}><ColorField label={['0% · цвет A','0% · цвет B','100% · цвет A','100% · цвет B'][i]} value={value[key]} onChange={color=>patch({[key]:color})}/></ControlRow>)}
<RangeControl label="Сила свечения градиента" value={value.intensity} min={0} max={10} step={.05} exactValueBounds={{min:0,max:10}} onChange={intensity=>patch({intensity})}/>
<RangeControl label="Скорость переливания" value={value.speed} min={0} max={3} step={.01} exactValueBounds={{min:0,max:3}} onChange={speed=>patch({speed})}/>
<RangeControl label="Масштаб рисунка" value={value.scale} min={1} max={50} step={.1} exactValueBounds={{min:1,max:50}} onChange={scale=>patch({scale})}/>
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
</div>;
}
@@ -1,3 +1,4 @@
import {ChargeGradientInspector} from './ChargeGradientInspector';
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';
@@ -5,8 +6,9 @@ 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>},
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={material.chargeGradient?['charge']:['surface']} sections={[
...(material.chargeGradient?[{id:'charge',label:'Градиент заряда',content:<ChargeGradientInspector value={material.chargeGradient} onChange={chargeGradient=>onChange({chargeGradient})}/>}]:[]),
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields">{!material.chargeGradient?.enabled&&<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></>;
@@ -0,0 +1,23 @@
import {useLayoutEffect,useRef,type CSSProperties} from 'react';
import {Button,DraggableItem,Icon,IconButton} from '@nodedc/ui-react';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {materialTileSizes,type EditorWindowRect} from '../../../core/roverScene/editorLayout';
export function MaterialTile({material}:{material:MaterialSpec}){return <span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':material.color,'--material-gloss':1-material.roughness,...(material.chargeGradient?.enabled?{background:`linear-gradient(135deg,${material.chargeGradient.highA},${material.chargeGradient.highB})`}:{})} as CSSProperties}/><span>{material.name}</span></span>;}
type Props={materials:Record<string,MaterialSpec>;selected:string|null;revealVersion:number;pick:(id:string)=>void;add:()=>void;rect?:EditorWindowRect;tileSize:number};
export function MaterialPalette({materials,selected,pick,add,revealVersion,rect,tileSize}:Props){
const grid=useRef<HTMLDivElement>(null);
useLayoutEffect(()=>{
const content=grid.current,parent=content?.closest('.nodedc-window__body'),target=content?.querySelector<HTMLElement>('[aria-pressed="true"]');
if(!parent||!target)return;
const p=parent.getBoundingClientRect(),t=target.getBoundingClientRect();
if(t.top<p.top)parent.scrollTop+=t.top-p.top;else if(t.bottom>p.bottom)parent.scrollTop+=t.bottom-p.bottom;
},[selected,revealVersion,tileSize,rect?.width,rect?.height]);
return <div ref={grid} className="rover-material-palette__items" style={{'--material-tile-width':`${tileSize}px`,'--material-swatch-size':`${38*tileSize/materialTileSizes.default}px`,'--material-tile-font':`${Math.max(10,12*tileSize/materialTileSizes.default)}px`} as CSSProperties}>
{Object.entries(materials).map(([id,m])=><DraggableItem id={id} data={{materialId:id}} key={id} className="scene-material-drag">{({activator})=><Button {...activator.attributes} {...activator.listeners} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><MaterialTile material={m}/></Button>}</DraggableItem>)}
<Button aria-label="Добавить материал" title="Добавить материал" onClick={add}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button>
</div>;
}
export function MaterialPaletteActions({tileSize,onTileSize}:{tileSize:number;onTileSize:(size:number)=>void}){return <>
<IconButton label="Уменьшить плитки материалов" disabled={tileSize<=materialTileSizes.min} onClick={()=>onTileSize(Math.max(materialTileSizes.min,tileSize-materialTileSizes.step))}><Icon name="minus"/></IconButton>
<IconButton label="Увеличить плитки материалов" disabled={tileSize>=materialTileSizes.max} onClick={()=>onTileSize(Math.min(materialTileSizes.max,tileSize+materialTileSizes.step))}><Icon name="plus"/></IconButton>
</>;}
@@ -1,38 +1,73 @@
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 {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout';
import {roverModelURL} from '../../../core/roverScene/model';
import {useCallback,useEffect,useRef,useState} from 'react';
import {Description,DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
import {createMaterial,changeField,defaultScene,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {assignObjectMaterial,findSceneObject,objectTargets,type SceneObject} from '../../../core/roverScene/sceneObjects';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
import PlayCanvasViewer from '../playcanvas/PlayCanvasViewer';
import PlayCanvasViewer,{type PlayCanvasViewerProps} from '../playcanvas/PlayCanvasViewer';
import type {ScenePicker,ScenePick} from '../playcanvas/useSceneMaterials';
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
import {MaterialInspector} from './MaterialInspector';
import {MaterialPalette,MaterialPaletteActions,MaterialTile} from './MaterialPalette';
import {SceneObjectTree} from './SceneObjectTree';
import {useSceneUndo} from './useSceneUndo';
import type {ChargeState} from '../playcanvas/chargeMaterial';
import {useObjectSelection} from './useObjectSelection';
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}}}));};
export default function RoverScene({vehicleID,...props}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
const scene=useSceneDocument(vehicleID);return <SceneEditor {...props} scene={scene}/>;
}
export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,defaults=defaultScene,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;defaults?:typeof defaultScene;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
useSceneUndo(scene,editing);
const layout=scene.document.editorLayout;
const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default;
const [palette,setPalette]=useState(true),[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 [objectsOpen,setObjectsOpen]=useState(true),[root,setRoot]=useState<SceneObject|null>(null),[selectedObject,setSelectedObject]=useState<string|null>(null);
const [selectionVersion,setSelectionVersion]=useState(0);
const [modelPhase,setModelPhase]=useState<'loading'|'ready'|'error'>('loading');
const [sceneApi,setSceneApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const picker=useRef<ScenePicker|null>(null);
const pickerReady=useCallback((value:ScenePicker|null)=>{picker.current=value;},[]);
const sceneGraph=useCallback((value:SceneObject|null)=>{setRoot(value);},[]);
const sceneReady=useCallback((api:Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0])=>{setSceneApi(api);onSceneReady?.(api);},[onSceneReady]);
const modelState=useCallback((value:'loading'|'ready'|'error')=>{setModelPhase(value);onModelState(value);},[onModelState]);
const pick=useCallback((id:string)=>{setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
const objectPick=useCallback((hit:ScenePick|null)=>{setSelectionVersion(v=>v+1);if(!hit){setSelectedObject(null);setSelected(null);setMaterialOpen(false);return;}setSelectedObject(hit.objectId);setPalette(true);pick(hit.materialId);},[pick]);
const selectObject=(id:string)=>{setSelectionVersion(v=>v+1);setSelectedObject(id);const item=findSceneObject(root,id),source=item?.materialIds?.[0];const material=scene.document.objectAssignments?.[id]??(source?(scene.document.assignments[source]??source):null);if(material){setPalette(true);pick(material);}};
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=maxSceneMaterials){scene.setError(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{if(Object.entries(patch).every(([key,value])=>scene.document.materials[id]?.[key as keyof MaterialSpec]===value))return;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 node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
const material=selected?scene.document.materials[selected]:null;
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>
const tools:EditorDockTool[]=[
{id:'objects',title:'Объекты сцены',label:'Объекты сцены',open:objectsOpen,onClose:()=>setObjectsOpen(false),className:'scene-object-window',initialRect:{left:16,top:16,width:380,height:600},content:<SceneObjectTree revealVersion={selectionVersion} root={root} selected={selectedObject} visibility={scene.document.objectVisibility} legacyVisibility={scene.document.objects} onSelect={selectObject} onVisibility={(id,value)=>scene.update(doc=>({...doc,objectVisibility:{...doc.objectVisibility,[id]:value}}))}/>},
{id:'palette',title:'Материалы сцены',label:'Материалы сцены',open:palette,onClose:()=>setPalette(false),className:'rover-material-palette',initialRect:{left:400,top:420,width:640,height:340},minimumSize:{width:280,height:180},
actions:<MaterialPaletteActions tileSize={tileSize} onTileSize={size=>scene.update(doc=>({...doc,editorLayout:{windows:{},...doc.editorLayout,materialTileSize:size}}))}/>,content:<MaterialPalette tileSize={tileSize} revealVersion={selectionVersion} materials={scene.document.materials} selected={selected} pick={pick} add={addMaterial}/>},
{id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),footer:<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaults().postFx}))}/>,content:<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
{id:'material',title:material?.name||'Материал',label:'Материал',activationKey:`${selectionVersion}:${selected}`,subtitle:node?`Назначить: ${node.name}`:'Выберите объект в дереве',open:materialOpen&&!!material,onClose:()=>setMaterialOpen(false),
actions:<IconButton label="Назначить материал выбранному объекту" disabled={!selected||!targets.length} onClick={()=>selected&&scene.update(doc=>assignObjectMaterial(doc,targets,selected))}><Icon name="chevron-right"/></IconButton>,
content:material&&selected?<><Description>{node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'}</Description><MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaults().materials[selected]??createMaterial(defaults(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/></>:null}
];
return <DragDropRoot renderOverlay={({data})=>{const m=scene.document.materials[String(data?.materialId)];return m?<GlassSurface padding="sm"><MaterialTile material={m}/></GlassSurface>:null;}} onDragEnd={({activeData,pointer})=>{
const id=String(activeData?.materialId??'');if(!editing||!pointer||!Object.hasOwn(scene.document.materials,id))return;
// Reject palettes/inspectors and empty sky. Only an actual visible model hit assigns.
if(!(document.elementFromPoint(pointer.x,pointer.y) instanceof HTMLCanvasElement))return;
const hit=picker.current?.pick(pointer.x,pointer.y);if(!hit)return;
setSelectedObject(hit.objectId);setSelected(id);scene.update(doc=>assignObjectMaterial(doc,[hit.objectId],id));
}}>
<EditorDockLayout value={docking} enabled={editing} tools={tools} onChange={next=>scene.update(doc=>({...doc,editorLayout:{windows:{},materialTileSize:materialTileSizes.default,...doc.editorLayout,docking:next}}))} primary={<>
<DropZone id="scene-model" className="rover-scene-drop"><LoadingRegion className="rover-view__scene" loading={!scene.ready} label="Загрузка настроек сцены">
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
</LoadingRegion></DropZone>
{editing&&<>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><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-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></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('')}/>
</>;
</DragDropRoot>;
}
@@ -0,0 +1,11 @@
import {useEffect,useMemo,useState} from 'react';
import {Tree,TextField,type TreeNode} from '@nodedc/ui-react';
import {findSceneObject,type SceneObject} from '../../../core/roverScene/sceneObjects';
const label=(name:string)=>({'ModelRoot':'Сцена','Model':'Модель','bms/labels/cells':'Надписи ячеек','bms/labels/enclosure':'Надписи корпуса','bms/labels/electronics':'Маркировка электроники'}[name]??name.replace(/^bms\/cell-display\/C(\d+)$/,'Маркировка ячейки $1').replace(/^bms\//,''));
export function SceneObjectTree({root,selected,visibility,legacyVisibility,onSelect,onVisibility,revealVersion}:{root:SceneObject|null;selected:string|null;revealVersion:number;visibility?:Record<string,boolean>;legacyVisibility?:Record<string,boolean>;onSelect:(id:string)=>void;onVisibility:(id:string,value:boolean)=>void}){
const [query,setQuery]=useState('');
useEffect(()=>{const node=findSceneObject(root,selected);if(node&&query&&!label(node.name).toLocaleLowerCase().includes(query.toLocaleLowerCase()))setQuery('');},[selected,revealVersion]);
const convert=(node:SceneObject):TreeNode=>({id:node.id,label:label(node.name),visible:visibility?.[node.id]??legacyVisibility?.[node.name]??node.enabled,children:node.children.map(convert)});
const nodes=useMemo(()=>root?[convert(root)]:[],[root,visibility,legacyVisibility]);
return <div className="scene-object-outliner"><TextField label="Найти объект" value={query} onChange={e=>setQuery(e.target.value)}/><Tree label="Дерево объектов сцены" nodes={nodes} revealKey={revealVersion} selected={selected} onSelect={onSelect} onVisibilityChange={onVisibility} query={query}/></div>;
}
@@ -2,16 +2,28 @@
.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);}
.rover-material-palette .nodedc-window__body {overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;}
.rover-material-palette__items {display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,var(--material-tile-width)),1fr));gap:var(--nodedc-space-2);align-content:start;}
.rover-material-palette__items .nodedc-button {width:100%;height:100%;min-width:0;padding:var(--nodedc-space-2);}
.rover-material-tile {display:grid;justify-items:center;align-content:center;gap:var(--nodedc-space-1);width:100%;min-width:0;white-space:normal;overflow-wrap:anywhere;font-size:var(--material-tile-font,var(--nodedc-font-size-xs));}
.rover-material-tile>span:last-child {display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;min-height:2.4em;line-height:1.2;}
/* 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-material-swatch {display:block;width:var(--material-swatch-size,38px);height:var(--material-swatch-size,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}}
@container(max-width:460px){.rover-scene-save{top:calc(var(--observation-overlay-header-space, 0px) + 4.5rem)}}
.rover-scene-drop{position:absolute;inset:0}
.rover-scene-drop>.rover-view__scene{position:absolute;inset:0}
.scene-object-children{margin-left:var(--nodedc-space-3)}
.scene-material-drag{display:flex;align-items:center;gap:var(--nodedc-space-1)}
.scene-object-outliner{height:100%;min-height:0;display:flex;flex-direction:column;gap:var(--nodedc-space-3)}
.scene-object-outliner .nodedc-tree{flex:1;min-height:0}
.scene-object-window .nodedc-window__body{overflow:hidden}
.scene-material-drag>.nodedc-button{touch-action:none;cursor:grab}
.scene-material-drag.is-dragging>.nodedc-button{cursor:grabbing}
.bms-editor-content{position:absolute;inset:0;height:100%;}
@@ -0,0 +1,15 @@
import {useEffect} from 'react';
import * as pc from 'playcanvas';
import {sceneObjectId} from '../playcanvas/sceneTree';
/** Renderer evidence, including an occluded part selected through the tree. */
export function useObjectSelection(api:{app:pc.Application;modelRoot:pc.Entity}|null,ids:readonly string[],enabled:boolean){
const key=ids.join('\n');
useEffect(()=>{
if(!api||!enabled||!key)return;
const selected=new Set(key.split('\n'));
const meshes=(api.modelRoot.findComponents('render') as pc.RenderComponent[]).flatMap(component=>component.meshInstances).filter(mesh=>selected.has(sceneObjectId(mesh.node)));
const color=new pc.Color(1,1,1,.8);
const draw=()=>{for(const mesh of meshes)api.app.drawWireAlignedBox(mesh.aabb.getMin(),mesh.aabb.getMax(),color,false);};
api.app.on('update',draw);return()=>{api.app.off('update',draw);};
},[api,key,enabled]);
}
@@ -0,0 +1,18 @@
import {useEffect} from 'react';
import {historyCommand} from '../../../core/roverScene/sceneHistory';
import type {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
export function useSceneUndo(scene:ReturnType<typeof useSceneDocument>,active:boolean){
const {undo,redo,beginGesture,endGesture}=scene;
useEffect(()=>{
if(!active)return;
const keydown=(event:KeyboardEvent)=>{
const command=historyCommand(event);
if(command){event.preventDefault();event.stopImmediatePropagation();if(command==='undo')undo();else redo();return;}
if(!event.repeat&&event.key.startsWith('Arrow')&&(event.target as HTMLElement)?.closest?.('[role=slider],input[type=range]'))beginGesture();
};
const keyup=(event:KeyboardEvent)=>{if(event.key.startsWith('Arrow'))endGesture();};
window.addEventListener('keydown',keydown,true);window.addEventListener('keyup',keyup,true);
window.addEventListener('pointerdown',beginGesture,true);window.addEventListener('pointerup',endGesture);window.addEventListener('pointercancel',endGesture);window.addEventListener('blur',endGesture);
return()=>{endGesture();window.removeEventListener('keydown',keydown,true);window.removeEventListener('keyup',keyup,true);window.removeEventListener('pointerdown',beginGesture,true);window.removeEventListener('pointerup',endGesture);window.removeEventListener('pointercancel',endGesture);window.removeEventListener('blur',endGesture);};
},[active,undo,redo,beginGesture,endGesture]);
}
@@ -16,8 +16,10 @@
"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"
"Responsive scene framing and palette space without drive authority",
"Approved v022 CAM R09 / K1 C22 assembly; original chassis material groups retained, authored equipment colors and 16 mounting frames exported",
"Owner finish: CAM MOLLE and K1 base/holder/cap match matte black frame; Insta360 X4 body uses dark polymer; previous v022 stored palettes migrate once"
],
"inspector_source_sha256": "8f1df16bd8c12fb1b8481480690ff4ed0e6b2645cb3fba527888c0f9acb59192",
"model_revision": "dcd006-v020-materials-v2"
"model_revision": "dcd006-v022-materials-v2"
}
@@ -1,3 +1,5 @@
import {viewportFov,type CameraState} from '../../../core/roverScene/cameraState'
export type {CameraState} from '../../../core/roverScene/cameraState'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import * as pc from 'playcanvas'
import { buildSceneTree } from './sceneTree'
@@ -14,6 +16,7 @@ const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
export type PlayCanvasViewerProps = SceneMaterialsProps & {
modelUrl: string | null
minFitDistance?: number
postFx?: Partial<PostFxSettings> | null
viewportSize?: { width: number; height: number }
onSceneReady?: (api: { app: pc.Application; camera: pc.Entity; modelRoot: pc.Entity }) => void
@@ -31,13 +34,6 @@ export type PlayCanvasViewerProps = SceneMaterialsProps & {
muteLogs?: boolean
}
export type CameraState = {
pivot: { x: number; y: number; z: number }
distance: number
azimuthDeg: number
elevationDeg: number
}
// ------------------------------------------------------------
// Fallback texture handler
class SimpleTextureHandler {
@@ -583,6 +579,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
cameraEntity.setPosition(x, y, z)
cameraEntity.lookAt(pivot)
if (autoRotate && dt > 0) emitChange(false)
}
const onMouseDown = (e: MouseEvent) => {
@@ -615,6 +612,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
}
const onMouseUp = () => {
if (!dragging && !panning) return
dragging = false
panning = false
idleTime = 0
@@ -622,9 +620,14 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
}
const onWheel = (e: WheelEvent) => {
// Own wheel/pinch only on the canvas: never zoom the page and camera together.
e.preventDefault();e.stopPropagation();
idleTime = 0
const dir = Math.sign(e.deltaY)
if (dir) targetDistance *= 1 + dir * zoomStrength
if (dir) {
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?canvas.clientHeight:1);
targetDistance *= Math.exp(Math.max(-.35,Math.min(.35,delta*(e.ctrlKey ? .012 : zoomStrength/40))));
}
updateCamera(0)
emitChange(false)
if (wheelCommitTimer) window.clearTimeout(wheelCommitTimer)
@@ -639,7 +642,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
canvas.addEventListener('mousedown', onMouseDown)
window.addEventListener('mousemove', onMouseMove)
window.addEventListener('mouseup', onMouseUp)
canvas.addEventListener('wheel', onWheel, { passive: true })
canvas.addEventListener('wheel', onWheel, { passive: false })
canvas.addEventListener('contextmenu', onContextMenu)
app.on('update', updateCamera as any)
@@ -877,8 +880,9 @@ function applyPostFx(
}
export default function PlayCanvasViewer({
minFitDistance = 1.8,
modelUrl,
materials, assignments, editing, onMaterialPick, onTextureState,
materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState,
postFx,
viewportSize,
onSceneReady,
@@ -916,7 +920,8 @@ export default function PlayCanvasViewer({
const gridMaterialRef = useRef<pc.ShaderMaterial | null>(null)
const sceneMapRef = useRef<Map<string, pc.Entity>>(new Map())
const loadTokenRef = useRef(0)
const cameraStateRef = useRef<CameraState | null>(null)
const referenceHeightRef = useRef(cameraState?.referenceHeight ?? 0)
const cameraStateRef = useRef<CameraState | null>(cameraState ?? null)
const onCameraChangeRef = useRef<PlayCanvasViewerProps['onCameraChange']>(null)
const logWarn = useCallback((...args: any[]) => { if (!muteLogs) console.warn(...args) }, [muteLogs])
const logError = useCallback((...args: any[]) => { if (!muteLogs) console.error(...args) }, [muteLogs])
@@ -925,7 +930,7 @@ export default function PlayCanvasViewer({
const [skyboxVersion, setSkyboxVersion] = useState(0)
const [modelVersion, setModelVersion] = useState(0)
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,editing,onMaterialPick,onTextureState})
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState})
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
@@ -957,14 +962,10 @@ export default function PlayCanvasViewer({
// PlayCanvas writes fixed pixel CSS sizes; the hosted pane remains fluid.
canvas.style.width = '100%'
canvas.style.height = '100%'
const model = inst.root.findByName('Model') as pc.Entity | null
const bounds = model ? computeAabb(model) : null
const orbit = (inst as any).__orbit as OrbitController | undefined
if (bounds && orbit) {
const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * w / h)
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
}
// Hold focal length in CSS pixels. Resize changes the crop, never orbit state.
if (!referenceHeightRef.current) referenceHeightRef.current = h
const camera = cameraEntityRef.current?.camera
if (camera) camera.fov = viewportFov(h, referenceHeightRef.current)
}, [])
useEffect(() => {
@@ -1082,7 +1083,7 @@ export default function PlayCanvasViewer({
inertiaFactor: cameraInertiaFactor ?? undefined,
inertiaTime: cameraInertiaTime ?? undefined,
onChange: (state, commit) => {
onCameraChangeRef.current?.(state, commit)
onCameraChangeRef.current?.({...state,referenceHeight:referenceHeightRef.current || canvas.clientHeight}, commit)
},
})
@@ -1481,6 +1482,7 @@ export default function PlayCanvasViewer({
if (!modelRoot) return
let cancelled = false
const request = new AbortController()
const loadGlb = async (url: string) => {
const loadToken = ++loadTokenRef.current
@@ -1493,7 +1495,11 @@ export default function PlayCanvasViewer({
ensureTextureHandler(app)
asset = new pc.Asset('model', 'container', { url })
const response = await fetch(url, { signal: AbortSignal.any([request.signal, AbortSignal.timeout(30000)]) })
if (!response.ok) throw new Error(`Model request failed: ${response.status}`)
const contents = await response.arrayBuffer()
if (cancelled) return
asset = new pc.Asset('model', 'container', { url, contents })
app.assets.add(asset)
const loadedAsset = asset
@@ -1535,7 +1541,8 @@ export default function PlayCanvasViewer({
const cam = cameraEntityRef.current?.camera
const vertical = (cam?.fov ?? 28) * Math.PI / 360
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)) * 0.88))
orbit.setDistance(Math.max(minFitDistance, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
onCameraChangeRef.current?.({...orbit.getState(),referenceHeight:referenceHeightRef.current},true)
}
if (exposeSceneGraph || onSceneGraph) {
@@ -1564,6 +1571,7 @@ export default function PlayCanvasViewer({
return () => {
cancelled = true
request.abort()
}
}, [resolvedUrl, exposeSceneGraph, onSceneGraph])
@@ -1573,7 +1581,9 @@ export default function PlayCanvasViewer({
if (!app) return
const orbit = (app as any).__orbit as OrbitController | undefined
if (!orbit) return
if (cameraState.referenceHeight) referenceHeightRef.current = cameraState.referenceHeight
orbit.setState(cameraState)
resizeCanvas()
}, [appReady, cameraState])
useEffect(() => {
@@ -1622,12 +1632,15 @@ export default function PlayCanvasViewer({
const modelEntity = (modelRoot as any).findByName?.('Model') as pc.Entity | null
const aabb = computeAabb(modelEntity || modelRoot)
if (!aabb) return
referenceHeightRef.current = canvasRef.current?.clientHeight || referenceHeightRef.current
resizeCanvas()
orbit.setState({
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
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),
distance: Math.max(minFitDistance,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,
elevationDeg: 10,
})
onCameraChangeRef.current?.({...orbit.getState(),referenceHeight:referenceHeightRef.current},true)
}, [appReady, cameraResetToken, modelVersion])
useEffect(() => {
@@ -0,0 +1,34 @@
import * as pc from 'playcanvas';
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
export type ChargeState={soc:number|null;fresh:boolean};
const emission=`
uniform vec3 chargeColorA;
uniform vec3 chargeColorB;
uniform float chargeTime;
uniform float chargeScale;
uniform float chargeIntensity;
uniform float chargeSaturation;
void getEmission() {
vec3 p=vPositionW*chargeScale;
float wave=sin(p.x*0.77+sin(p.y*0.91+chargeTime)*1.2+chargeTime*0.43);
wave+=sin(p.z*0.71-p.y*0.48+sin(p.x*0.57-chargeTime*0.61));
float blend=smoothstep(-1.6,1.6,wave);
vec3 color=mix(chargeColorA,chargeColorB,blend);
color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation);
dEmission=color*chargeIntensity;
}`;
export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){
const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL);
if(gradient?.enabled){chunks.set('emissivePS',emission);material.emissive.set(1,1,1);material.emissiveIntensity=1;material.diffuse.set(.02,.02,.02);}
else chunks.delete('emissivePS');
}
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number){
const known=state?.soc!==null&&state?.soc!==undefined;
const colors=known?chargePair(gradient,state!.soc):[[.12,.14,.16],[.18,.20,.22]];
material.setParameter('chargeColorA',colors[0].map(value=>value**2.2));
material.setParameter('chargeColorB',colors[1].map(value=>value**2.2));
material.setParameter('chargeTime',time*gradient.speed);
material.setParameter('chargeScale',gradient.scale);
material.setParameter('chargeIntensity',gradient.intensity*(known?1:.2));
material.setParameter('chargeSaturation',known?1:0);
}
@@ -1,20 +1,28 @@
import type * as pc from 'playcanvas'
import type {SceneObject} from '../../../core/roverScene/sceneObjects'
export type SceneTreeNode = {
id: string
name: string
enabled: boolean
children: SceneTreeNode[]
export type SceneTreeNode = SceneObject
/** Names and duplicate sibling ordinals survive reload; runtime GUIDs do not. */
export function sceneObjectId(node:pc.GraphNode):string{
const path:string[]=[];let current:pc.GraphNode|null=node;
while(current&&current.name!=='ModelRoot'){
const siblings=current.parent?.children.filter(child=>child.name===current!.name)??[];
path.unshift(encodeURIComponent(current.name||'Entity')+(siblings.length>1?`~${siblings.indexOf(current)}`:''));current=current.parent;
}
return 'object/'+(path.join('/')||'root');
}
export function buildSceneTree(root: pc.GraphNode, map: Map<string, pc.Entity>): SceneTreeNode {
const id = String((root as any).getGuid?.() ?? (root as any)._guid ?? root.name)
const id = sceneObjectId(root)
const children = (root.children || []).map((c) => buildSceneTree(c, map))
map.set(id, root as pc.Entity)
return {
id,
name: root.name || 'Entity',
enabled: root.enabled !== false,
renderable: !!(root as pc.Entity).render?.meshInstances.length,
materialIds: [...new Set((root as pc.Entity).render?.meshInstances.map(mi=>mi.material?.name).filter((name):name is string=>!!name)??[])],
children,
}
}
@@ -1,12 +1,18 @@
import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas';
import {configureChargeMaterial,updateChargeMaterial,type ChargeState} from './chargeMaterial';
import {sceneObjectId} from './sceneTree';
export type ScenePick={objectId:string;materialId:string};
export type ScenePicker={pick:(x:number,y:number)=>ScenePick|null};
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};
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;onPickerReady?:(picker:ScenePicker|null)=>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};
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState}:SceneMaterialsProps){
const latest=useRef({materials,onObjectPick,onTextureState,chargeState});latest.current={materials,onObjectPick,onTextureState,chargeState};
const animated=useRef(new Map<string,pc.StandardMaterial>());
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
const generation=useRef(0);
const originalVisibility=useRef(new WeakMap<pc.GraphNode,boolean>());
const originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>());
const customMaterials=useRef(new Map<string,pc.StandardMaterial>());
useEffect(()=>{
@@ -23,7 +29,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
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;
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(objectAssignments?.[sceneObjectId(mi.node)]??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)=>{
@@ -32,7 +38,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update();
};
const used=new Set<string>();
const used=new Set<string>();animated.current.clear();
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;
@@ -58,26 +64,39 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
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');});
}
}
configureChargeMaterial(m,spec.chargeGradient);
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0);}
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]);
},[materials,assignments,objectAssignments,modelVersion,appRef,onTextureState]);
useEffect(()=>{
const app=appRef.current;if(!app||!modelVersion)return;
let time=0;const motion=window.matchMedia('(prefers-reduced-motion: reduce)');
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient?.enabled)updateChargeMaterial(material,gradient,live.chargeState,time);}};
app.on('update',update);return()=>{app.off('update',update);};
},[appRef,modelVersion]);
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 root=appRef.current?.root.findByName('ModelRoot');if(!root||!modelVersion)return;
const visit=(node:pc.GraphNode)=>{if(!originalVisibility.current.has(node))originalVisibility.current.set(node,node.enabled);node.enabled=objectVisibility?.[sceneObjectId(node)]??legacyObjectVisibility?.[node.name]??originalVisibility.current.get(node)!;for(const child of node.children)visit(child);};visit(root);
},[objectVisibility,legacyObjectVisibility,modelVersion,appRef]);
useEffect(()=>{
const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current;
if(!editing||!app||!canvas||!camera?.camera||!modelVersion)return;
if(!editing||!app||!canvas||!camera?.camera||!modelVersion){onPickerReady?.(null);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);}
const pick=(x:number,y:number):ScenePick|null=>{
const rect=canvas.getBoundingClientRect();if(x<rect.left||x>=rect.right||y<rect.top||y>=rect.bottom)return null;
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(Math.floor(x-rect.left),Math.floor(y-rect.top)).find((mi):mi is pc.MeshInstance=>mi instanceof pc.MeshInstance&&originalGroups.current.has(mi));
return hit?{objectId:sceneObjectId(hit.node),materialId:hit.material.name}:null;
};
onPickerReady?.({pick});
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 hit=pick(e.clientX,e.clientY);latest.current.onObjectPick?.(hit);};
canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up);
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);picker.destroy();};
},[editing,modelVersion,appRef,cameraRef,canvasRef]);
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);onPickerReady?.(null);picker.destroy();};
},[editing,modelVersion,appRef,cameraRef,canvasRef,onPickerReady]);
}
@@ -1,6 +1,7 @@
.rover-view { position:relative; height:100%; min-height:200px; overflow:hidden; container-type:inline-size; }
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
.rover-view .rover-view__scene { position:absolute; inset:0; }
.nodedc-editor-workspace__body>.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__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; transform:scale(.8); transform-origin:bottom right; }
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
@@ -13,7 +13,7 @@ import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiE
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
import { localScene } from "./localScene";
import { EditorTerrain } from "./EditorTerrain";
import { EditorCamera } from "./EditorCamera";
import { EditorCamera, type NavigationOwner } from "./EditorCamera";
import { EditorSurfacePicker } from "./EditorSurfacePicker";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
@@ -240,8 +240,8 @@ export class AiEditorRuntime {
}
this.dirty = true;
}
setNavigation(enabled: boolean) {
this.controls.setNavigation(enabled);
setNavigation(enabled: boolean, owner: NavigationOwner = "planner") {
this.controls.setNavigation(enabled, owner);
}
setSemanticSelection(active:boolean) {this.controls.semanticSelection=active;}
setAddMode(add: boolean) { this.controls.setAddMode(add); }
@@ -5,6 +5,8 @@ import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/e
import { PerspectiveCamera, Vector3 } from "three";
import {cameraRay,isOrthographic,switchProjection,type EditorProjection,type ProjectionCamera} from "../../core/simulation/editorProjection";
export type NavigationOwner = "planner" | "semantic";
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 {
@@ -14,7 +16,8 @@ export class EditorCamera {
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
get rotationCenter(){return this.gesture&&!this.gesture.pan&&!this.gesture.pending?this.gesture.anchor:null;}
private keys = new Set<string>();
private enabled=true;
private navigationBlocks=new Set<NavigationOwner>();
private get enabled(){return this.navigationBlocks.size===0;}
private topPoints:number[][]|null=null;
private addMode=false;
semanticSelection=false;
@@ -153,7 +156,10 @@ export class EditorCamera {
}
setAddMode(add:boolean){this.cancelGesture();this.addMode=add;}
invalidateSurface(){this.cancelGesture();this.lastAnchor=null;}
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
setNavigation(enabled:boolean,owner:NavigationOwner="planner"){
if(enabled)this.navigationBlocks.delete(owner);else this.navigationBlocks.add(owner);
if(!this.enabled)this.clear();
}
update(dt:number){
if(!this.enabled||!this.keys.size)return;
this.cancelGesture();
@@ -15,7 +15,7 @@ export function PlannerCameraTools({runtime,viewport,disabled}:{runtime:AiEditor
return <>
<Dropdown placement="bottom-end" width={220} trigger={({toggle,setTriggerRef,open})=><IconButton ref={setTriggerRef}
label={`Проекция: ${projection==="orthographic"?"ортографическая":"перспективная"}`} title="Выбрать проекцию" disabled={disabled} aria-expanded={open} onClick={toggle}><Icon name={projection}/></IconButton>}>
{({close})=><div className="semantic-tools__menu">{([['orthographic','Ортографическая'],['perspective','Перспективная']] as const).map(([mode,label])=><Button key={mode} width="full" variant={projection===mode?"primary":"secondary"} tone="neutral" aria-pressed={projection===mode} onClick={()=>{updateLayout({projection:mode});close();}}>{label}</Button>)}</div>}
{({close})=><div className="semantic-tools__menu">{([['orthographic','Ортографическая'],['perspective','Перспективная']] as const).map(([mode,label])=><Button key={mode} width="full" variant={projection===mode?"primary":"secondary"} tone="neutral" aria-pressed={projection===mode} onClick={()=>{updateLayout({projection:mode});close();}}>{label}</Button>)}<Button width="full" onClick={()=>{runtime.top();close();}}>Показать сцену целиком</Button></div>}
</Dropdown>
{createPortal(<div className="ai-local-editor__cube"><NavigationCube quaternion={quaternion} {...preferences.cube} disabled={disabled} onSelect={direction=>runtime.view(direction)}/></div>,viewport)}
</>;
@@ -11,7 +11,8 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
const {runtime,viewport,map,original,layers,selected}=props;
const [,redraw]=useState(0);
const {hover,ghostMap,marquee,brush}=useSemanticGestures(props);
useEffect(()=>{runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime]);
useEffect(()=>{if(!props.editing&&!original)return;runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime,props.editing,original]);
if(!props.editing&&!original)return null;
const rect=viewport.querySelector("canvas")?.getBoundingClientRect();if(!rect)return null;
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*rect.width,q[1]*rect.height]:null;};
const line=(path:number[][])=>{const p=path.map(project);return p.map((v,i)=>v?`${i&&p[i-1]?"L":"M"}${v[0]},${v[1]}`:"").join(" ");};
@@ -20,7 +21,7 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
const point=semanticAnchor(props),g=point?runtime.semanticGizmo(point):null,base=point?project(point):null;
const featureColor=(id:string)=>`rgb(${(URBAN_COLORS[id]??URBAN_COLORS.road_boundary).join(",")})`;
const color=featureColor(chosen[0]?.properties.class??layers.at(-1)??"road_boundary");
const visible=map.features.filter(f=>layers.includes(f.properties.class as typeof layers[number])&&f.properties.review_status!=="rejected");
const visible=map.features.filter(f=>(chosen.includes(f)||highlight.includes(f))&&layers.includes(f.properties.class as typeof layers[number])&&f.properties.review_status!=="rejected");
const node=selected&&!selected.object&&chosen[0]&&!isRigidMarking(chosen[0])?knots(chosen[0],selected.path)[selected.index]:null;
const handleScale=node?curveControlScale(knots(chosen[0],selected!.path),selected!.index,chosen[0].geometry.type==="Polygon",project):1;
return createPortal(<svg className="ai-local-editor__markers" width="100%" height="100%" aria-label="Редактор контуров">
@@ -1,10 +1,11 @@
import {useSimulationLayout} from "./useSimulationLayout";
import {useSemanticDocument} from "./useSemanticDocument";
import {useEffect,useRef,useState} from "react";
import {createPortal} from "react-dom";
import {Button,Icon,IconButton,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
import {Button,FieldFrame,Icon,IconButton,Select,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
import {URBAN_LABELS,availableUrbanClasses,visibleUrbanMap,type UrbanMap,type UrbanClassId} from "../../core/simulation/urbanMap";
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticDraft,semanticOperation,semanticRequest,undoSemantic,
type SemanticDraft,type SemanticOperation,type SemanticRevision,type Vertex} from "../../core/simulation/semanticEdits";
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticOperation,undoSemantic,
type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import type {AiEditorRuntime} from "./AiEditorRuntime";
import {SemanticEditOverlay,type SemanticChoice} from "./SemanticEditOverlay";
import {SemanticTools} from "./SemanticTools";
@@ -14,12 +15,11 @@ import {duplicateIndex,type SemanticAxis} from "../../core/simulation/semanticVe
export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,source,headerHost}:{
headerHost:HTMLElement|null;worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;active:boolean;busy:boolean;source:UrbanMap;
}) {
const [revision,setRevision]=useState<SemanticRevision|null>(null);
const [draft,setDraft]=useState<SemanticDraft|null>(null);
const [error,setError]=useState<string|null>(null),[saving,setSaving]=useState(false);
const [loading,setLoading]=useState(true);
const [editing,setEditing]=useState(true);
const [error,setError]=useState<string|null>(null);
const [confirmDiscard,setConfirmDiscard]=useState(false);
const [layout,updateLayout]=useSimulationLayout();
const document=useSemanticDocument(worldId,worldSha,active,source,layout.semanticVersion,setError);
const {revision,draft,setDraft,saving,loading,editing,setEditing,save}=document;
const visible=layout.visible,setVisible=(v:typeof visible|((prior:typeof visible)=>typeof visible))=>updateLayout({visible:typeof v==="function"?v(visible):v});
const [selection,setSelection]=useState<Vertex[]>([]),[wholeContour,setWholeContour]=useState(false);
const selectVertices=(vertices:Vertex[],whole=false)=>{setSelection(vertices);setWholeContour(whole);};
@@ -32,28 +32,18 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
const [tool,setTool]=useState<SemanticTool>("select");
const [template,setTemplate]=useState<string|null>(null);
const [preview,setPreview]=useState<SemanticOperation|null>(null);
const attempt=useRef<{key:string;signature:string}|null>(null);
const current=useRef({draft,revision});current.current={draft,revision};
const accept=(value:SemanticRevision)=>{
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
throw new Error("Правки относятся к другой сцене.");
setRevision(value);setDraft(semanticDraft(value.edited));attempt.current=null;setSelected(null);
};
useEffect(()=>{
if(!active||revision)return;
const abort=new AbortController();
setLoading(true);setError(null);
void semanticRequest(worldId,undefined,abort.signal).then(accept)
.catch(e=>{if(!abort.signal.aborted)setError(e.message);})
.finally(()=>{if(!abort.signal.aborted)setLoading(false);});
return()=>abort.abort();
},[active,worldId,worldSha,revision]);
useEffect(()=>{if(active){setEditing(true);}},[active]);
setSelected(null);setPreview(null);setTool("select");setTemplate(null);
if(!revision)return;
const available=availableUrbanClasses(revision.edited);
if(layers.length&&available.length&&!layers.some(layer=>available.includes(layer)))setLayers(available);
if(revision.revision)updateLayout({semanticVersion:"manual"});
},[revision]);
useEffect(()=>{runtime.setSemanticSelection(active&&editing);viewport.dataset.semanticEditing=String(active&&editing);
return()=>{runtime.setSemanticSelection(false);delete viewport.dataset.semanticEditing;};},[runtime,viewport,active,editing]);
const operate=(op:SemanticOperation)=>{
if(busy||saving)return;
if(busy||saving||loading||!editing||!document.canEdit||!current.current.draft)return;
try{const prior=current.current.draft!,next=commitSemantic(prior,op);setDraft(next);setError(null);
if(op.kind==="duplicate_vertex"&&next!==prior)setSelected({feature_id:op.feature_id,path:op.path,index:duplicateIndex(op.index,prior.map.features.find(f=>f.id===op.feature_id)!.geometry.type==="Polygon",op.side)});
if(op.kind==="duplicate_marking"&&next!==prior)setSelected({feature_id:op.new_feature_id,path:0,index:0,object:true});
@@ -79,7 +69,7 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
if(!active)return;
runtime.setAddMode(false);
const keyboard=(e:KeyboardEvent)=>{
if(!editing||busy||saving||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||document.querySelector('[data-dropdown-lineage]'))return;
if(!editing||busy||saving||loading||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||window.document.querySelector('[data-dropdown-lineage]'))return;
if((e.metaKey||e.ctrlKey)&&e.code==="KeyZ"){
e.preventDefault();e.stopImmediatePropagation();setPreview(null);
setDraft(s=>s?(e.shiftKey?redoSemantic(s):undoSemantic(s)):s);setSelected(null);
@@ -91,24 +81,14 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
e.preventDefault();e.stopImmediatePropagation();removeSelected();
}
};
document.addEventListener("keydown",keyboard,true);
return()=>document.removeEventListener("keydown",keyboard,true);
},[active,editing,busy,saving,preview,selection,layers,viewport,runtime,display]);
window.document.addEventListener("keydown",keyboard,true);
return()=>window.document.removeEventListener("keydown",keyboard,true);
},[active,editing,busy,saving,loading,preview,selection,layers,viewport,runtime,display]);
useEffect(()=>{
if(!draft?.operations.length)return;
const warn=(e:BeforeUnloadEvent)=>{e.preventDefault();};
window.addEventListener("beforeunload",warn);return()=>window.removeEventListener("beforeunload",warn);
},[draft?.operations.length]);
const save=async()=>{
const s=current.current;if(!s.draft?.operations.length||!s.revision||saving)return;
const body={expected_revision:s.revision.revision,model_sha256:s.revision.model_sha256,operations:s.draft.operations};
const signature=JSON.stringify(body);
if(attempt.current?.signature!==signature)attempt.current={signature,key:crypto.randomUUID()};
setSaving(true);setError(null);
try{accept(await semanticRequest(worldId,{...body,request_id:attempt.current.key}));}
catch(e){setError((e as Error).message);}
finally{setSaving(false);}
};
if(!active)return null;
const classes=availableUrbanClasses(display);
if(!classes.includes("road_marking"))classes.push("road_marking");
@@ -119,29 +99,36 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
const undo=()=>{setDraft(s=>s?undoSemantic(s):s);setSelected(null);};
const redo=()=>{setDraft(s=>s?redoSemantic(s):s);setSelected(null);};
const controls=<>
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing}
onClick={()=>{setEditing(v=>!v);setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
{document.options.length?<FieldFrame label="Версия разметки" labelPlacement="below" className="ai-polygon__semantic-version-field"><Select label="Версия разметки" value={document.selected} options={document.options.map(option=>({...option,label:option.value===document.selected&&document.dirty?`${option.label} · несохранённые правки`:option.label}))}
disabled={loading||saving||document.dirty} onChange={v=>{document.select(v);updateLayout({semanticVersion:v.startsWith("manual:")?"manual":v as "raw"|"algorithmic"});}}/></FieldFrame>:null}
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={document.selected==="raw"?"Сырая разметка доступна только для просмотра":editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing} disabled={!document.canEdit||busy}
onClick={()=>{document.toggleEditing();setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
{draft?.operations.length?<IconButton label="Сохранить правки" title="Сохранить правки" loading={saving} onClick={()=>void save()}><Icon name="save"/></IconButton>:null}
{document.dirty?<Button disabled={saving} onClick={()=>setConfirmDiscard(true)}>Отменить правки</Button>:null}
</>;
return <>
{headerHost?createPortal(controls,headerHost):null}
{!revision?<Button loading={loading} onClick={()=>{setLoading(true);setError(null);void semanticRequest(worldId).then(accept).catch(e=>setError(e.message)).finally(()=>setLoading(false));}}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
{revision?<SemanticTools viewport={viewport} editing={editing&&visible.user&&layers.length>0&&!busy&&!saving} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
{loading||!revision?<Button loading={loading} onClick={document.refresh}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
{revision?<SemanticTools viewport={viewport} editing={editing&&document.canEdit&&visible.user&&layers.length>0&&!busy} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
area={layers.some(id=>["pedestrian_area","sidewalk"].includes(id))} template={template} setTemplate={id=>{setTemplate(id);setSelected(null);setTool("select");}}
selection={selection} map={display} operate={operate} remove={removeSelected} undo={undo} redo={redo} canUndo={!!draft?.operations.length} canRedo={!!draft?.future.length}
axis={axis} setAxis={setAxis} visible={visible} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
axis={axis} setAxis={setAxis} visible={visible} compareAvailable={document.selected.startsWith("manual:")||document.dirty} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
{createPortal(<div className="ai-local-editor__legend nodedc-scene-controls">
{classes.length?<SegmentedControl label="Видимые и редактируемые слои" selectionMode="multiple" value={layers} onChange={v=>{setLayers(v);setSelection(s=>s.filter(x=>v.includes(display.features.find(f=>f.id===x.feature_id)?.properties.class as UrbanClassId)));chooseTool("select");}}
items={classes.map(id=>({value:id,label:URBAN_LABELS[id]}))}/>:null}
</div>,viewport)}
<SemanticEditOverlay runtime={runtime} viewport={viewport} map={visibleUrbanMap(overlay,visible.user?layers:[])}
original={visible.model&&revision?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
editing={editing&&visible.user&&layers.length>0} blocked={busy||saving} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
original={visible.model&&revision&&(document.selected.startsWith("manual:")||document.dirty)?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
editing={editing&&document.canEdit&&visible.user&&layers.length>0} blocked={busy||saving||loading} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
axis={axis} areaMode={areaMode} onSelect={setSelected} onSelection={selectVertices} onChoose={setChoices} onOperation={operate} onPreview={setPreview} onError={setError}
onExit={()=>{setEditing(false);setSelected(null);chooseTool("select");}}/>
<Window open={choices.length>0} onClose={()=>setChoices([])} title="Выберите контур">
{choices.map(({vertex,selection,wholeContour,operation},index)=><Button key={vertex.feature_id} onClick={()=>{selectVertices(selection,wholeContour);if(operation)operate(operation);setChoices([]);}}>{URBAN_LABELS[display.features.find(f=>f.id===vertex.feature_id)?.properties.class as UrbanClassId]} · {index+1}</Button>)}
</Window>
<Window open={confirmDiscard} onClose={()=>setConfirmDiscard(false)} title="Отменить несохранённые правки?">
<Button onClick={()=>setConfirmDiscard(false)}>Продолжить редактирование</Button>
<Button variant="danger" onClick={()=>{document.discard();setSelected(null);setConfirmDiscard(false);}}>Отменить правки</Button>
</Window>
<ToastStack items={error?[{id:"semantic",tone:"error",title:"Не удалось выполнить действие",description:error}]:[]} onDismiss={()=>setError(null)}/>
</>;
}
@@ -7,7 +7,7 @@ import type {SemanticTool} from "./semanticEditorTypes";
import {usePlannerPreferences} from "./usePlannerPreferences";
export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:SemanticTool;setTool:(v:SemanticTool)=>void;marking:boolean;contours:boolean;area:boolean;template:string|null;setTemplate:(v:string)=>void;
selection:Vertex[];map:UrbanMap;operate:(op:SemanticOperation)=>void;remove:()=>void;undo:()=>void;redo:()=>void;canUndo:boolean;canRedo:boolean;axis:SemanticAxis;setAxis:(v:SemanticAxis)=>void;
visible:{model:boolean;user:boolean};setVisible:(v:{model:boolean;user:boolean})=>void;areaMode:"union"|"difference";setAreaMode:(m:"union"|"difference")=>void;onError:(s:string)=>void}) {
visible:{model:boolean;user:boolean};compareAvailable:boolean;setVisible:(v:{model:boolean;user:boolean})=>void;areaMode:"union"|"difference";setAreaMode:(m:"union"|"difference")=>void;onError:(s:string)=>void}) {
const [prefs,update]=usePlannerPreferences();
const items:ToolbarItem[]=[{id:"hold",label:prefs.toolbar.autoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!prefs.toolbar.autoHide,onSelect:()=>{try{update({...prefs,toolbar:{...prefs.toolbar,autoHide:!prefs.toolbar.autoHide}});}catch{p.onError("Не удалось сохранить закрепление тулбара.");}}}];
const editableMarking=p.selection.some(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);});
@@ -39,8 +39,8 @@ export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:Seman
if(p.canRedo)items.push({id:"redo",label:"Повторить",shortcut:"Control+Shift+Z Meta+Shift+Z",icon:"redo",onSelect:p.redo});
}
items.push({id:"visibility",label:"Видимость разметки",icon:"eye",onSelect:()=>{},menu:menu(<>
<Checker label="Алгоритмическая разметка" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>
<Checker label="Ручная разметка" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
<Checker label="Показывать разметку" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
{p.compareAvailable?<Checker label="Сравнить с исходной алгоритмической" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>:null}
</>)}, {id:"quality",label:"Качество Gaussian-сцены",icon:"sliders",onSelect:()=>{},menu:close=>menu(([["low","Низкое"],["medium","Среднее"],["high","Высокое"],["ultra","Ультра"],["maximum","Максимум"]] as const).map(([quality,label])=><Button key={quality} width="full" variant={prefs.quality===quality?"primary":"secondary"} tone="neutral" aria-pressed={prefs.quality===quality} onClick={()=>{try{update({...prefs,quality});close();}catch{p.onError("Не удалось сохранить качество.");}}}>{label}</Button>))});
if(p.editing&&p.marking)items.push({id:"marking",label:"Добавить элемент разметки",icon:"plus",active:!!p.template,onSelect:()=>{},menu:close=>menu(MARKING_TEMPLATES.templates.filter(t=>!(t as {hidden?:boolean}).hidden).map(t=><Button key={t.id} width="full" onClick={()=>{p.setTemplate(t.id);close();}}>{t.label}</Button>))});
return createPortal(<Toolbar container={p.viewport} {...prefs.toolbar} label="Инструменты семантики" items={items}/>,p.viewport);
@@ -0,0 +1,14 @@
import {useEffect,useMemo,useSyncExternalStore} from "react";
import {getSemanticSession,hasUnsavedSemanticSessions} from "../../core/simulation/semanticDocument";
// Protection belongs to all retained scenes, not only the mounted editor.
window.addEventListener("beforeunload",event=>{if(hasUnsavedSemanticSessions())event.preventDefault();});
export function useSemanticDocument(worldId:string,worldSha:string,active:boolean,source:object,preferred:string,onError:(error:string|null)=>void) {
const session=useMemo(()=>getSemanticSession(worldId,worldSha,preferred),[worldId,worldSha]);
const state=useSyncExternalStore(session.subscribe,session.snapshot);
useEffect(()=>{if(active)void session.open();else session.setEditing(false);},[session,active,source]);
useEffect(()=>{onError(state.error);},[state.error,onError]);
return {...state,options:session.options(),dirty:session.dirty,canEdit:session.canEdit,
select:session.select,setDraft:session.setDraft,setEditing:session.setEditing,
toggleEditing:session.toggleEditing,save:session.save,discard:session.discard,refresh:()=>void session.open()};
}
@@ -33,7 +33,7 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
const d=drag;drag=null;latest.current.onPreview(null);
if(d){if(!cancel&&d.op)latest.current.onOperation(d.op);release(d.id);}
if(box){const id=box.id;box=null;release(id);}setMarquee(null);
runtime.setNavigation(!latest.current.blocked);
runtime.setNavigation(!latest.current.blocked,"semantic");
};
const commitShape=(points:number[][])=>{
try{const p=latest.current,f=p.map.features.find(f=>f.id===p.selected?.feature_id&&["pedestrian_area","sidewalk"].includes(f.properties.class));
@@ -52,7 +52,7 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
duplicate:duplicate?{feature_id:selected.feature_id,path:selected.path,index:selected.index}:undefined,
copy:copy?{feature_id:selected.feature_id,new_feature_id:`user-${crypto.randomUUID()}`}:undefined};
if(handle){const nodes=knots(f,selected.path);drag.handleScale=curveControlScale(nodes,selected.index,f.geometry.type==="Polygon",project);drag.handleStart=nodes[selected.index][handle];}
runtime.setNavigation(false);viewport.setPointerCapture(e.pointerId);
runtime.setNavigation(false,"semantic");viewport.setPointerCapture(e.pointerId);
};
const down=(e:PointerEvent)=>{
const p=latest.current;if(!p.editing||p.blocked)return;
@@ -160,11 +160,13 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
}else if(e.key==="Enter"&&shape.length>=3){stop(e);commitShape(shape);}
};
const leave=()=>{if(!drag&&!box){generation++;pending=null;setGhost(null);setHover(null);}};
// Loading owns a temporary semantic lock; completion must restore input without blur.
runtime.setNavigation(!props.blocked,"semantic");
viewport.addEventListener("pointerdown",down,true);viewport.addEventListener("pointermove",move,true);viewport.addEventListener("pointerup",up,true);
viewport.addEventListener("pointercancel",cancel,true);viewport.addEventListener("pointerleave",leave);document.addEventListener("keydown",key,true);
window.addEventListener("blur",cancel);
return()=>{disposed=true;cancel();viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
},[props.runtime,props.viewport,props.editing,props.tool,props.template,props.layers]);
return()=>{disposed=true;cancel();runtime.setNavigation(true,"semantic");viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
},[props.runtime,props.viewport,props.editing,props.blocked,props.tool,props.template,props.layers]);
const ghostMap=ghost?semanticOperation({...props.map,features:[]},ghost):null;
return {hover,ghostMap,marquee,brush};
}
@@ -1,4 +1,11 @@
import {usbCanSensorUi} from '../../../../plugins/usb-can/frontend/src/plugin';
import {createElement} from 'react';
import {jkBmsSensorUi} from '../../../../plugins/jk-bms/frontend/src/plugin';
import {BmsDetail} from '../../../../plugins/jk-bms/frontend/src/BmsDetail';
import type {BatteryState} from '../../../../plugins/jk-bms/frontend/src/model';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {BatteryScene} from '../components/battery/BatteryScene';
import {BatteryWorkspace} from '../components/battery/BatteryWorkspace';
import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin';
import type { DeviceUiPlugin } from "../core/device-plugins/contracts";
import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin";
@@ -12,4 +19,6 @@ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([
// Node-executed camera controls use the existing sensor contribution contract;
// they do not register a desktop capture/AI runtime or a new product workspace.
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi,usbCanSensorUi]);
const CoreBmsDetail=(props:SensorDetailProps)=>createElement(BatteryWorkspace,{key:props.device.id,deviceId:props.device.id,title:`Аккумулятор / ${props.device.name}`,headerActionsTarget:props.headerActionsTarget,back:props.back,children:controls=>createElement(BmsDetail,{...props,presentation:'page',editing:controls.editing,panelAppearance:controls.appearance.panels,renderViewport:controls.renderViewport,renderScene:(state:BatteryState)=>createElement(BatteryScene,{editing:controls.editing,markingAppearance:controls.appearance.markings,deviceId:props.device.id,seedKey:props.sceneSeedKey,soc:state.sample?.soc_percent??null,fresh:state.fresh,cellVoltages:state.sample?.cell_voltages_v})})});
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi,usbCanSensorUi,{...jkBmsSensorUi,detailPresentation:'workspace' as const,Detail:CoreBmsDetail}]);
@@ -0,0 +1,14 @@
import {defaultGlassMaterial,type GlassMaterialSettings} from '@nodedc/ui-core';
export type CellMarkingAppearance={color:string;size:number};
export type BatteryPanelAppearance={height:number;radius:number;labelSize:number;valueSize:number;textColor:string;glass:GlassMaterialSettings};
export type BatteryAppearance={schema:'missioncore.battery-ui/v1';markings:CellMarkingAppearance;panels:BatteryPanelAppearance};
export const batteryAppearanceKey=(id:string)=>`missioncore.battery-ui/v1:${id}`;
export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},panels:{height:76,radius:24,labelSize:12,valueSize:18,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};}
const object=(v:unknown):Record<string,unknown>=>v!==null&&typeof v==='object'?v as Record<string,unknown>:{};
const number=(v:unknown,fallback:number,min:number,max:number)=>typeof v==='number'&&Number.isFinite(v)?Math.min(max,Math.max(min,v)):fallback;
const color=(v:unknown,fallback:string)=>typeof v==='string'&&/^#[0-9a-f]{6}$/i.test(v)?v.toLowerCase():fallback;
export function parseBatteryAppearance(raw:unknown):BatteryAppearance{
const source=object(raw);if(source.schema!=='missioncore.battery-ui/v1')throw new Error('Это не профиль интерфейса батареи.');
const d=defaultBatteryAppearance(),m=object(source.markings),p=object(source.panels),g=object(p.glass);
return {schema:d.schema,markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,18,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}};
}
@@ -0,0 +1,12 @@
import type {CellMarkingAppearance} from './appearance';
export function cellDisplayIndex(name:string){const match=/^bms\/cell-display\/C(0[1-9]|1[0-3])$/.exec(name);return match?Number(match[1])-1:null;}
export function cellDisplayText(index:number,value:number|undefined){return {number:String(index+1).padStart(2,'0'),voltage:Number.isFinite(value)?`${value!.toLocaleString('ru-RU',{minimumFractionDigits:3,maximumFractionDigits:3})} В`:'— В'};}
/** One fixed composition on each existing 27 × 29 mm label face. No camera projection. */
export function drawCellDisplay(ctx:CanvasRenderingContext2D,index:number,value:number|undefined,appearance:CellMarkingAppearance){
const text=cellDisplayText(index,value),size=appearance.size/100;
ctx.clearRect(0,0,256,256);ctx.save();ctx.translate(128,128);ctx.scale(size,size);
ctx.fillStyle=appearance.color;ctx.textAlign='center';ctx.textBaseline='middle';
ctx.font='600 76px sans-serif';ctx.fillText(text.number,0,-36);
ctx.font='500 40px sans-serif';ctx.fillText(text.voltage,0,46);
ctx.restore();
}
@@ -0,0 +1,34 @@
import {defaultChargeGradient} from '../roverScene/chargeGradient';
import r04 from './r04.json';
import {defaultScene,parseScene,type SceneDocument} from '../roverScene/sceneDocument';
import {readScene} from '../roverScene/sceneStorage';
import type {SceneDocumentProfile} from '../roverScene/useSceneDocument';
export function defaultBatteryScene():SceneDocument {
return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1',
materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}};
}
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{
const request=indexedDB.open('missioncore-battery-scenes',1);
request.onupgradeneeded=()=>request.result.createObjectStore('scenes');
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
request.onblocked=()=>reject(new Error('Хранилище батареи занято другим окном.'));
});}
async function save(id:string,document:SceneDocument){const db=await database();try{await new Promise<void>((resolve,reject)=>{
const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,id);
tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);
});}finally{db.close();}}
export function batterySceneProfile(seedKey?:string):SceneDocumentProfile {
return {defaults:defaultBatteryScene,write:save,filename:'battery-r04-scene.json',read:async id=>{
const db=await database();let raw:unknown;try{raw=await new Promise((resolve,reject)=>{
const request=db.transaction('scenes').objectStore('scenes').get(id);
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
});}finally{db.close();}
if(raw)return parseScene(raw,defaultBatteryScene);
const seed=seedKey?await readScene(seedKey):null;
const doc=defaultBatteryScene();
if(seed){doc.postFx=structuredClone(seed.postFx);doc.cameraAutoRotate=seed.cameraAutoRotate;doc.cameraZoomStrength=seed.cameraZoomStrength;}
// Copy once. Subsequent rover edits and battery edits have separate owners.
await save(id,doc);return doc;
}};
}
@@ -0,0 +1,501 @@
{
"materials": {
"bms/Cable / red silicone": {
"name": "Cable / red silicone",
"color": "#ac1922",
"metalness": 0,
"roughness": 0.47999998927116394,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Cable / graphite silicone": {
"name": "Cable / graphite silicone",
"color": "#22252a",
"metalness": 0.05000000074505806,
"roughness": 0.3700000047683716,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Mount / G10 dielectric": {
"name": "Mount / G10 dielectric",
"color": "#3e8572",
"metalness": 0,
"roughness": 0.5199999809265137,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Nickel plated copper / busbars": {
"name": "Nickel plated copper / busbars",
"color": "#c4ccd2",
"metalness": 0.8299999833106995,
"roughness": 0.27000001072883606,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Sense / warm yellow": {
"name": "Sense / warm yellow",
"color": "#f6c629",
"metalness": 0.05000000074505806,
"roughness": 0.3199999928474426,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/labels": {
"name": "Надписи",
"color": "#e5eee8",
"metalness": 0,
"roughness": 0.9,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#ffffff",
"emissiveIntensity": 0.08,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Connector / ivory polymer": {
"name": "Connector / ivory polymer",
"color": "#e4e2d2",
"metalness": 0.05000000074505806,
"roughness": 0.4000000059604645,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/BMS / green PCB": {
"name": "BMS / green PCB",
"color": "#266c50",
"metalness": 0.15000000596046448,
"roughness": 0.4000000059604645,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Aluminium / satin": {
"name": "Aluminium / satin",
"color": "#cdd6dd",
"metalness": 0.800000011920929,
"roughness": 0.3100000023841858,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Lid / insulating black": {
"name": "Lid / insulating black",
"color": "#15191e",
"metalness": 0,
"roughness": 0.6499999761581421,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Mount / adhesive film": {
"name": "Mount / adhesive film",
"color": "#6f756f",
"metalness": 0,
"roughness": 0.6200000047683716,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Steel / fasteners": {
"name": "Steel / fasteners",
"color": "#bdc4ca",
"metalness": 0.8799999952316284,
"roughness": 0.23000000417232513,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/cells": {
"name": "Ячейки · общий SOC",
"color": "#487b80",
"metalness": 0,
"roughness": 0.68,
"opacity": 0.82,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#ffffff",
"emissiveIntensity": 0.65,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Cell / wrapped lower edge": {
"name": "Cell / wrapped lower edge",
"color": "#223894",
"metalness": 0.20000000298023224,
"roughness": 0.3100000023841858,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/CASE | bead-blasted graphite": {
"name": "CASE | bead-blasted graphite",
"color": "#464a4f",
"metalness": 0.3199999928474426,
"roughness": 0.5199999809265137,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/glass": {
"name": "Прозрачная часть корпуса",
"color": "#7898a1",
"metalness": 0.05,
"roughness": 0.42,
"opacity": 0.12,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/R04 | elastomer seal": {
"name": "R04 | elastomer seal",
"color": "#121517",
"metalness": 0,
"roughness": 0.699999988079071,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/R04 | graphite moulded polymer": {
"name": "R04 | graphite moulded polymer",
"color": "#222930",
"metalness": 0,
"roughness": 0.36000001430511475,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/R04 | smoked polycarbonate": {
"name": "R04 | smoked polycarbonate",
"color": "#98aab5",
"metalness": 0,
"roughness": 0.15000000596046448,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/R04 | display protective polycarbonate": {
"name": "R04 | display protective polycarbonate",
"color": "#eef7fa",
"metalness": 0,
"roughness": 0.11999999731779099,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/DISPLAY | black glass": {
"name": "DISPLAY | black glass",
"color": "#121f23",
"metalness": 0.18000000715255737,
"roughness": 0.2199999988079071,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/CASE | recessed black": {
"name": "CASE | recessed black",
"color": "#1e2227",
"metalness": 0.11999999731779099,
"roughness": 0.5,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/CASE | darker frame": {
"name": "CASE | darker frame",
"color": "#41464c",
"metalness": 0.6499999761581421,
"roughness": 0.3199999928474426,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/CASE | dielectric liner": {
"name": "CASE | dielectric liner",
"color": "#313437",
"metalness": 0,
"roughness": 0.6499999761581421,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/Connector / gold plated contacts": {
"name": "Connector / gold plated contacts",
"color": "#d6a44a",
"metalness": 0.8500000238418579,
"roughness": 0.25,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/XT90-S / anti spark green insert": {
"name": "XT90-S / anti spark green insert",
"color": "#30a455",
"metalness": 0,
"roughness": 0.4300000071525574,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
},
"bms/XT90-S / yellow PA housing": {
"name": "XT90-S / yellow PA housing",
"color": "#f9bd22",
"metalness": 0,
"roughness": 0.3799999952316284,
"opacity": 1,
"reflectivity": 1,
"clearCoat": 0,
"clearCoatRoughness": 0.3,
"emissive": "#000000",
"emissiveIntensity": 0,
"normalStrength": 1,
"doubleSided": true,
"tiling": 1,
"textures": {}
}
},
"objects": {
"bms/Cable / red silicone": true,
"bms/Cable / graphite silicone": true,
"bms/Mount / G10 dielectric": true,
"bms/Nickel plated copper / busbars": true,
"bms/Sense / warm yellow": true,
"bms/labels/electronics": true,
"bms/Connector / ivory polymer": true,
"bms/BMS / green PCB": true,
"bms/Aluminium / satin": true,
"bms/Lid / insulating black": true,
"bms/Mount / adhesive film": true,
"bms/Steel / fasteners": true,
"bms/cells/C01": true,
"bms/Cell / wrapped lower edge": true,
"bms/labels/cells": true,
"bms/cell-display/C01": true,
"bms/cells/C02": true,
"bms/cell-display/C02": true,
"bms/cells/C03": true,
"bms/cell-display/C03": true,
"bms/cells/C04": true,
"bms/cell-display/C04": true,
"bms/cells/C05": true,
"bms/cell-display/C05": true,
"bms/cells/C06": true,
"bms/cell-display/C06": true,
"bms/cells/C07": true,
"bms/cell-display/C07": true,
"bms/cells/C08": true,
"bms/cell-display/C08": true,
"bms/cells/C09": true,
"bms/cell-display/C09": true,
"bms/cells/C10": true,
"bms/cell-display/C10": true,
"bms/cells/C11": true,
"bms/cell-display/C11": true,
"bms/cells/C12": true,
"bms/cell-display/C12": true,
"bms/cells/C13": true,
"bms/cell-display/C13": true,
"bms/CASE | bead-blasted graphite/CASE | base tray": true,
"bms/CASE | bead-blasted graphite/CASE | front endplate": true,
"bms/CASE | bead-blasted graphite/CASE | rear endplate": true,
"bms/glass/CASE | removable solid top": true,
"bms/glass/CASE | slotted side -1": true,
"bms/glass/CASE | slotted side 1": true,
"bms/R04 | elastomer seal": true,
"bms/R04 | graphite moulded polymer": true,
"bms/labels/enclosure": true,
"bms/R04 | smoked polycarbonate": true,
"bms/R04 | display protective polycarbonate": true,
"bms/DISPLAY | black glass": true,
"bms/CASE | recessed black": true,
"bms/CASE | darker frame": true,
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return": true,
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return.001": true,
"bms/CASE | bead-blasted graphite/HANDLE | integral web underside": true,
"bms/CASE | dielectric liner": true,
"bms/CASE | dielectric liner/left": true,
"bms/CASE | dielectric liner/right": true,
"bms/Connector / gold plated contacts": true,
"bms/XT90-S / anti spark green insert": true,
"bms/XT90-S / yellow PA housing": true
}
}
@@ -0,0 +1,21 @@
import {useCallback,useEffect,useState} from 'react';
import {SceneHistory,historyCommand} from '../roverScene/sceneHistory';
import {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance,type BatteryAppearance} from './appearance';
export function useBatteryAppearance(id:string,active:boolean){
const [error,setError]=useState('');
const [history]=useState(()=>{let profile=defaultBatteryAppearance();try{const raw=localStorage.getItem(batteryAppearanceKey(id));if(raw)profile=parseBatteryAppearance(JSON.parse(raw));}catch{/* Keep the usable default if the local profile is unavailable. */}return new SceneHistory(profile);});
const [value,setValue]=useState(history.present);
const publish=useCallback(()=>{setValue(history.present);try{localStorage.setItem(batteryAppearanceKey(id),JSON.stringify(history.present));setError('');}catch{setError('Не удалось сохранить настройки батареи на этом компьютере.');}},[history,id]);
const update=useCallback((next:BatteryAppearance)=>{if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]);
const undo=useCallback(()=>{if(history.undo())publish();},[history,publish]);
const redo=useCallback(()=>{if(history.redo())publish();},[history,publish]);
useEffect(()=>{
if(!active)return;
const begin=()=>history.begin(),end=()=>history.end();
const key=(e:KeyboardEvent)=>{const command=historyCommand(e);if(command){e.preventDefault();e.stopImmediatePropagation();if(command==='undo')undo();else redo();}else if(!e.repeat&&e.key.startsWith('Arrow')&&(e.target as HTMLElement)?.closest?.('[role=slider],input[type=range]'))begin();};
const up=(e:KeyboardEvent)=>{if(e.key.startsWith('Arrow'))end();};
window.addEventListener('keydown',key,true);window.addEventListener('keyup',up,true);window.addEventListener('pointerdown',begin,true);window.addEventListener('pointerup',end);window.addEventListener('pointercancel',end);window.addEventListener('blur',end);
return()=>{end();window.removeEventListener('keydown',key,true);window.removeEventListener('keyup',up,true);window.removeEventListener('pointerdown',begin,true);window.removeEventListener('pointerup',end);window.removeEventListener('pointercancel',end);window.removeEventListener('blur',end);};
},[active,history,undo,redo]);
return {value,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError};
}
@@ -0,0 +1,7 @@
/** Local view geometry is independent of imported scene/material JSON. */
export const minBatteryViewHeight=360,maxBatteryViewHeight=2160;
export const batteryViewHeightKey=(id:string)=>`missioncore.battery-view/v1:${encodeURIComponent(id)}`;
export function batteryViewHeight(raw:string|null,viewportHeight:number):number{
const fallback=Math.max(minBatteryViewHeight,Math.min(900,Math.round(viewportHeight-300)));
try{const value=JSON.parse(raw??'null');return typeof value?.height==='number'&&Number.isFinite(value.height)?Math.max(minBatteryViewHeight,Math.min(maxBatteryViewHeight,Math.round(value.height))):fallback;}catch{return fallback;}
}
@@ -0,0 +1,52 @@
import type {BoardHost,BoardNetworkInterface,Vehicle} from './useFleet';
type NetworkFacts={ssid:string;signal:number|null;addresses:string[]|null};
export interface RememberedNetwork {
name:string; kind:'wifi'|'ethernet'; hardware:BoardNetworkInterface['hardware'];
state:string; stateAt:string; facts:NetworkFacts; observed:boolean; seenAt:number;
}
export interface BoardNetworkMemory {
scope:string; input:BoardHost|null; sampledAt:string; readable:boolean; entries:RememberedNetwork[];
}
export const boardNetworkScope=(v:Vehicle)=>`${v.id}\0${v.node_id}`;
const physical=(n:BoardNetworkInterface)=>n.kind==='wifi'||n.kind==='ethernet';
const compare=(a:BoardNetworkInterface,b:BoardNetworkInterface)=>Number(a.kind!=='wifi')-Number(b.kind!=='wifi')||a.name.localeCompare(b.name);
const reportedStates=new Set(['connected','disconnected','unavailable','connecting','disconnecting','failed']);
const sameFacts=(a:NetworkFacts,b:NetworkFacts)=>a.ssid===b.ssid&&a.signal===b.signal&&JSON.stringify(a.addresses)===JSON.stringify(b.addresses);
function factsFrom(n:BoardNetworkInterface,previous?:NetworkFacts):NetworkFacts {
const ssid=n.connection?.ssid??previous?.ssid??'',sameNetwork=ssid===previous?.ssid;
const signal=n.connection?.signal_percent;
return {ssid,signal:typeof signal==='number'&&Number.isInteger(signal)&&signal>=0&&signal<=100?signal:sameNetwork?previous?.signal??null:null,
addresses:n.addresses_readable===false?previous?.addresses??null:[...n.addresses].sort()};
}
// The snapshot's observation time is separate from the adapter's reported state.
// Only a readable inventory may confirm removal; missing/unknown observations
// cannot erase a known state. Keep current interfaces plus 64 absent rows in RAM.
export function rememberBoardNetworks(previous:BoardNetworkMemory|null,vehicle:Vehicle):BoardNetworkMemory {
const scope=boardNetworkScope(vehicle),host=vehicle.host;
const old=previous?.scope===scope?previous:null;
const sampledAt=host?.collected_at||old?.sampledAt||'';
const at=Date.parse(sampledAt),before=Date.parse(old?.sampledAt??'');
if(old&&Number.isFinite(at)&&Number.isFinite(before)&&at<before)return {...old,input:host};
const readable=!!host&&host.networks_readable!==false;
const current=new Map((readable?host.networks:[]).filter(physical).sort(compare).map(n=>[n.name,n]));
const reportedNames=new Set(host?.networks.map(n=>n.name)??[]);
const prior=new Map(old?.entries.map(e=>[e.name,e])??[]);
const names=[...prior.keys(),...Array.from(current.keys()).filter(name=>!prior.has(name))];
const entries=names.map(name=>{
const existing=prior.get(name),next=current.get(name);
if(!next)return readable&&!reportedNames.has(name)?{...existing!,observed:false}:existing!;
const stamp=next.connection?.collected_at??'',connectionAt=Date.parse(stamp),previousAt=Date.parse(existing?.stateAt??'');
const reported=!!next.connection&&reportedStates.has(next.connection.state)&&Number.isFinite(connectionAt)&&(!Number.isFinite(previousAt)||connectionAt>=previousAt);
const state=reported?next.connection!.state:existing?.observed?existing.state:'unknown';
let facts=!existing||(reported&&state==='connected')?factsFrom(next,existing?.facts):existing.facts;
// Equal packets reuse facts, so timestamps alone never repaint adapter cards.
if(existing&&sameFacts(facts,existing.facts))facts=existing.facts;
const hardware={...existing?.hardware,...Object.fromEntries(Object.entries(next.hardware??{}).filter(([,value])=>!!value))};
return {name,kind:next.kind as 'wifi'|'ethernet',hardware,state,stateAt:reported?stamp:existing?.stateAt??'',facts,
observed:true,seenAt:Number.isFinite(at)?at:existing?.seenAt??0};
});
const retained=new Set(entries.filter(e=>!e.observed).sort((a,b)=>b.seenAt-a.seenAt).slice(0,64).map(e=>e.name));
return {scope,input:host,sampledAt,readable,entries:entries.filter(e=>e.observed||retained.has(e.name))};
}
@@ -0,0 +1,23 @@
import type {Vehicle} from './useFleet';
import {rememberBoardNetworks,type BoardNetworkMemory} from './boardNetworkMemory';
const states=new Map(Object.entries({connected:'Подключён',disconnected:'Не подключён',unavailable:'Недоступен',connecting:'Подключается',disconnecting:'Отключается',failed:'Ошибка подключения',unknown:'Нет сведений'}));
const buses=new Map(Object.entries({usb:'USB',pci:'PCI',sdio:'SDIO',platform:'Платформенный',virtio:'Virtio'}));
export function boardNetworkStatus(vehicle:Vehicle,available:boolean,memory=rememberBoardNetworks(null,vehicle)) {
// Board liveness is not an adapter state and inventory age is not a disconnect.
const live=available&&vehicle.connectivity==='online';
const baseTitle=(n:RememberedNetwork)=>[n.kind==='wifi'?'Wi-Fi':'Ethernet',buses.get(n.hardware?.bus??'')].filter(Boolean).join(' · ');
const totals=new Map<string,number>(),indices=new Map<string,number>();
for(const n of memory.entries){const base=baseTitle(n);totals.set(base,(totals.get(base)??0)+1);}
const links=memory.entries.map(n=>{
const base=baseTitle(n),index=(indices.get(base)??0)+1;indices.set(base,index);
const title=(totals.get(base)??0)>1?`${base} · Адаптер ${index}`:base;
const state=n.observed?n.state:'absent';
return {name:n.name,kind:n.kind,title,model:n.hardware?.model??'',vendor:n.hardware?.vendor??'',state,
status:state==='absent'?'Не обнаружен':states.get(state)??'Нет сведений',...n.facts};
});
return {links,readable:memory.readable,live,collectedAt:memory.sampledAt};
}
type RememberedNetwork=BoardNetworkMemory['entries'][number];
export type BoardNetworkStatusValue=ReturnType<typeof boardNetworkStatus>;
@@ -0,0 +1,18 @@
import {type DockTree,dockIds} from '@nodedc/ui-core';
import type {ObservationLayout} from './observationLayout';
/** Transfer chosen catalog slots once; never overwrite an existing device layout. */
export function bindObservationLayout(layout:ObservationLayout,bindings:readonly {from:string;to:string}[]):ObservationLayout{
const known=new Set([...layout.order,...layout.hidden,...Object.keys(layout.layers),...(layout.tree?dockIds(layout.tree):[])]);
const map=new Map(bindings.filter(({from,to})=>(known.has(from)||layout.catalogVisible?.includes(from))&&!known.has(to)).map(({from,to})=>[from,to]));
if(!map.size)return layout;
const key=(id:string)=>map.get(id)??id;
const tree=(value:DockTree):DockTree=>'id'in value?{id:key(value.id)}:{...value,first:tree(value.first),second:tree(value.second)};
const splits=Object.fromEntries(Object.entries(layout.splits).map(([name,ratio])=>{
try{const ids:unknown=JSON.parse(name);if(Array.isArray(ids)&&ids.every(id=>typeof id==='string'))return [JSON.stringify(ids.map(key)),ratio];}catch{/* Preserve unrelated legacy split keys. */}
return [name,ratio];
}));
return {...layout,tree:layout.tree?tree(layout.tree):undefined,order:layout.order.map(key),hidden:layout.hidden.map(key),
layers:Object.fromEntries(Object.entries(layout.layers).map(([id,value])=>[key(id),value])),splits,
catalogVisible:layout.catalogVisible?.filter(id=>!map.has(id))};
}
@@ -1,3 +1,4 @@
import {readSceneSettings,type SceneSettings} from '../../sceneSettings';
import {dockIds, type DockTree} from '@nodedc/ui-core';
import {decodeObservationLayout, type ObservationLayout} from './observationLayout';
@@ -6,7 +7,7 @@ export const observationArrangements = [
{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[]}
export interface ObservationPresets {version:1;selected:string;layout:ObservationLayout;presets:ObservationPreset[];scenes?:Record<string,SceneSettings>}
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> : {};
@@ -19,7 +20,10 @@ export function decodeObservationPresets(value:unknown, legacy?:unknown):Observa
}
const layout=decodeObservationLayout(source.version===1 ? source.layout : legacy);
const selected=source.selected;
return {version:1,presets,layout,selected:typeof selected==='string' &&
const scenes:Record<string,SceneSettings>={};
if(source.version===1 && source.scenes && typeof source.scenes==='object')
for(const [key,value] of Object.entries(source.scenes).slice(0,128)){const profile=readSceneSettings(value);if(key.length<=512&&profile)scenes[key]=profile;}
return {version:1,presets,layout,...(Object.keys(scenes).length?{scenes}:{}),selected:typeof selected==='string' &&
(presets.some(p=>p.id===selected) || observationArrangements.some(p=>p.value===selected))
? selected : layout.arrangement};
}
@@ -1,3 +1,4 @@
import {roverModelID} from '../roverScene/model';
export type RoverMode='arcade'|'tank';
export type Demand={left:number;right:number};
export const keysFor=(mode:RoverMode)=>mode==='arcade'?['KeyW','KeyA','KeyS','KeyD']:['KeyQ','KeyE','KeyA','KeyD'];
@@ -20,7 +21,7 @@ export function roverSettings(value:unknown):typeof defaultRoverSettings {
// ERPM has no trustworthy conversion to throttle. Migrate at 10%, never
// reinterpret an old saved number as a percentage or full throttle.
throttlePercent:v.version!==1&&typeof v.throttlePercent==='number'&&Number.isFinite(v.throttlePercent)?Math.max(1,Math.min(100,v.throttlePercent)):10,
model:v.model==='dcd006-v020'?v.model:'',
model:v.model==='dcd006-v020'||v.model===roverModelID?roverModelID:'',
}:{} )};
}
@@ -1,10 +1,10 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {fleetRequest} from './useFleet';
export type NetworkProvider='tailscale'|'wireguard';
export type NetworkProvider='tailscale'|'wireguard'|'netbird';
export interface SharedNetworkProfile {id:string;name:string;endpoint:string;state:string;boards:number}
export interface BoardNetworkView {
profiles:SharedNetworkProfile[];available:boolean;
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string}|null;
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string;netbird_endpoint?:string;netbird?:{state:string;address:string;server_url:string}}|null;
operation:{id:string;state:string;error?:string}|null;
}
export function useBoardNetwork(vehicleId:string){
@@ -31,5 +31,5 @@ export function useBoardNetwork(vehicleId:string){
await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'PUT',{provider,profile_id:provider==='wireguard'?profileId:null,expected_revision:value.node.revision});await refresh();
}catch(e){setError(e instanceof Error?e.message:'Подключение не применено.');}finally{setBusy(false);}};
return {value,provider,setProvider,profileId,setProfileId,error,busy,applying,dirty,importing,save,
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:profileId))};
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:provider==='netbird'?value.node?.netbird_endpoint:profileId))};
}
@@ -0,0 +1,15 @@
import {useState} from 'react';
import type {Vehicle} from './useFleet';
import {boardNetworkScope,rememberBoardNetworks} from './boardNetworkMemory';
import {boardNetworkStatus} from './boardNetworkStatus';
export function useBoardNetworkStatus(vehicle:Vehicle,available:boolean) {
const [memory,setMemory]=useState(()=>rememberBoardNetworks(null,vehicle));
// Adjust before rendering children. There is deliberately no clock/expiry
// timer: only a received observation can change an adapter's reported state.
if(memory.scope!==boardNetworkScope(vehicle)||memory.input!==vehicle.host){
const next=rememberBoardNetworks(memory,vehicle);setMemory(next);
return boardNetworkStatus(vehicle,available,next);
}
return boardNetworkStatus(vehicle,available,memory);
}
@@ -1,15 +1,22 @@
import { useCallback, useEffect, useState } from "react";
export interface BoardNetworkInterface {
name: string; up: boolean; addresses: string[]; addresses_readable?: boolean;
kind?: 'wifi'|'ethernet'|'virtual'|'unknown';
hardware?: {bus?:string;vendor?:string;model?:string};
connection?: {state:string;ssid?:string;signal_percent?:number;collected_at:string};
}
export interface BoardHost {
hostname: string; os: string; architecture: string; cpus: number;
memory_kib: number | null; collected_at: string;
networks: { name: string; up: boolean; addresses: string[] }[];
networks: BoardNetworkInterface[]; networks_readable?: boolean;
usb: { port: string; product: string }[];
}
export interface Vehicle {
id: string; node_id: string; name: string; platform: string;
enrollment: "pending" | "paired" | "revoked" | "failed";
connectivity: "online" | "offline"; last_seen: number | null;
inventory_fresh?: boolean;
host: BoardHost | null; notice: string; revision: number;
}
export interface FleetPreview {
@@ -0,0 +1,40 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {fleetRequest} from './useFleet';
export type NetBirdState='missing_client'|'unsupported_client'|'unavailable'|'disconnected'|'connecting'|'connected'|'other_network'|'address_conflict';
export interface NetBirdStatus {state:NetBirdState;server_url:string;address:string;client_version:string;pending:string;auth_url:string;error:string;can_install:boolean}
export interface NetBirdInstaller {id:string;label:string;filename:string;available:boolean;download_url:string;bytes:number}
export function useNetBird(){
const [status,setStatus]=useState<NetBirdStatus|null>(null),[clients,setClients]=useState<NetBirdInstaller[]>([]);
const [statusError,setStatusError]=useState(''),[actionError,setActionError]=useState(''),[clientError,setClientError]=useState('');
const [requestBusy,setRequestBusy]=useState(false);
const operation=useRef(false),generation=useRef(0),mounted=useRef(false);
useEffect(()=>{
mounted.current=true;let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
const poll=async()=>{
const epoch=generation.current;
try{
const value=await fleetRequest<NetBirdStatus>('/netbird','GET',undefined,20000,controller.signal);
if(active&&epoch===generation.current&&!operation.current){setStatus(value);setStatusError('');}
}catch{
if(active&&epoch===generation.current&&!operation.current){setStatusError('Состояние клиента недоступно.');setStatus(null);}
}finally{if(active)timer=setTimeout(poll,3000);}
};
void poll();
void fleetRequest<{items:NetBirdInstaller[]}>('/netbird/clients','GET',undefined,30000,controller.signal)
.then(value=>{if(active){setClients(value.items);setClientError('');}})
.catch(()=>{if(active)setClientError('Установщики недоступны. Повторите открытие настроек.');});
return()=>{active=false;mounted.current=false;controller.abort();clearTimeout(timer);};
},[]);
const action=useCallback(async(kind:'connect'|'install'|'cancel',server_url?:string)=>{
if(operation.current)return;
operation.current=true;generation.current+=1;setRequestBusy(true);setActionError('');
try{
const next=await fleetRequest<NetBirdStatus>(`/netbird/${kind}`,'POST',kind==='connect'?{server_url}:undefined,30000);
if(mounted.current){setStatus(next);setStatusError('');}
}catch(e){if(mounted.current)setActionError(e instanceof Error?e.message:'Операция не завершена.');}
finally{operation.current=false;generation.current+=1;if(mounted.current)setRequestBusy(false);}
},[]);
return {status,clients,clientError,error:actionError||statusError,
requestBusy,busy:requestBusy||Boolean(status?.pending),action};
}
@@ -0,0 +1,21 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {fleetRequest} from './useFleet';
export interface NetworkBackup {id:string;domain:string;server_url:string;bytes:number;stored_at:string;verification:'checksums_verified'}
export function useNetBirdBackups(){
const [items,setItems]=useState<NetworkBackup[]>([]),[loading,setLoading]=useState(true),[busy,setBusy]=useState(false),[error,setError]=useState('');
const mounted=useRef(false),operation=useRef(false);
const refresh=useCallback(async()=>{const result=await fleetRequest<{items:NetworkBackup[]}>('/netbird/backups');if(mounted.current)setItems(result.items);},[]);
useEffect(()=>{mounted.current=true;void refresh().catch(()=>{if(mounted.current)setError('Не удалось прочитать резервные копии.');}).finally(()=>{if(mounted.current)setLoading(false);});return()=>{mounted.current=false;};},[refresh]);
const upload=useCallback(async(file:File)=>{
if(operation.current)return;
operation.current=true;setBusy(true);setError('');
try{
if(file.size>256*1024*1024)throw Error('Резервная копия превышает 256 МиБ.');
const response=await fetch('/api/v1/fleet/netbird/backups',{method:'POST',body:file,headers:{'Content-Type':'application/zip'},signal:AbortSignal.timeout(120000)});
if(!response.ok){let detail='Не удалось сохранить копию.';try{const data=await response.json() as {detail?:string};detail=data.detail||detail;}catch{/* retain public error */}throw Error(detail);}
await refresh();
}catch(e){if(mounted.current)setError(e instanceof Error?e.message:'Не удалось сохранить копию.');}
finally{operation.current=false;if(mounted.current)setBusy(false);}
},[refresh]);
return {items,loading,busy,error,upload};
}
@@ -1,3 +1,4 @@
import type {SceneSettings} from '../../sceneSettings';
import {useEffect,useRef,useState,type SetStateAction} from 'react';
import type {CameraPresentation} from '../../../../../packages/sensor-ui/src/observation';
import type {ObservationLayout} from './observationLayout';
@@ -132,6 +133,7 @@ export function useVehicleObservation(vehicleID:string) {
try{localStorage.removeItem(draftKey+':recovery');}catch{}
};
return {...document.layouts,recovery:!!recovery,restore,ready,pending,cameras:document.cameras,setLayout,
setScene:(id:string,value:SceneSettings)=>changeLayouts(current=>({...current,scenes:{...current.scenes,[id]:value}})),
setCamera:(id:string,value:CameraPresentation)=>update(current=>({...current,cameras:{...current.cameras,[id]:value}})),
select:(id:string)=>changeLayouts(current=>selectObservationPreset(current,id)),
save:(name:string)=>changeLayouts(current=>saveObservationPreset(current,name,`saved:${crypto.randomUUID()}`)),
+1 -6
View File
@@ -1,6 +1 @@
/** View-only bounds. Each full-range endpoint disables its own clipping plane. */
export function heightSlice([lower, upper]: readonly [number, number], [min, max]: readonly [number, number]) {
const tolerance = Math.max(1, max - min) * 1e-9;
return { floor: lower <= min + tolerance ? null : lower,
ceiling: upper >= max - tolerance ? null : upper };
}
export {heightSlice} from "../../../../packages/spatial-ui/src/heightSlice";
@@ -0,0 +1,16 @@
/** Reparenting with append/remove destroys iframe browsing contexts. */
export function observationPortal(portal: HTMLElement, inline: HTMLElement, overlay: HTMLElement) {
inline.append(portal);
return {
setExpanded(expanded: boolean) {
const target = (expanded ? overlay : inline) as HTMLElement & {
moveBefore?: (node: Node, before: Node | null) => void;
};
if (portal.parentElement === target) return;
// Atomic moves preserve the running renderer, its canvas and history.
// Older hosts stay inline; the expanded CSS escapes its containing panel.
if (typeof target.moveBefore === 'function') target.moveBefore(portal, null);
},
dispose() { portal.remove(); },
};
}
@@ -35,7 +35,9 @@ export function decodeSessionDisplay(value: unknown, sessionId: string): SceneSe
|| ['showPoints','showTrajectory','showGrid','showLabels','showCameraFrustums'].some(key => typeof s[key as keyof SceneSettings] !== 'boolean')) {
throw new Error('Некорректные настройки отображения');
}
return {...s, accumulationMaxSeconds: Math.max(s.accumulationSeconds, s.accumulationMaxSeconds!)};
// Older recording profiles do not own the optional live-view navigation
// fields. Restore their neutral defaults when reading that wire format.
return {...defaultSceneSettings, ...s, accumulationMaxSeconds: Math.max(s.accumulationSeconds, s.accumulationMaxSeconds!)};
}
export async function loadSessionDisplay(sessionId: string, signal?: AbortSignal): Promise<SceneSettings> {
@@ -0,0 +1,12 @@
import {useEffect,useState} from 'react';
import {defaultSceneSettings,type SceneSettings} from '../../sceneSettings';
import {fetchObservationWorkspaceLayoutProfile} from './workspaceLayout';
/** Initial profile only; a board's persisted pane settings always take precedence. */
export function useSpatialDefaults(){
const [settings,setSettings]=useState<SceneSettings|null>(null);
useEffect(()=>{let active=true;
void fetchObservationWorkspaceLayoutProfile().then(profile=>{if(active)setSettings({...defaultSceneSettings,...profile?.sceneSettings});}).catch(()=>{if(active)setSettings({...defaultSceneSettings});});
return()=>{active=false;};
},[]);
return settings;
}
@@ -0,0 +1,9 @@
/** Local scene metadata. Height anchors projection so resizing crops without refitting. */
export type CameraState={pivot:{x:number;y:number;z:number};distance:number;azimuthDeg:number;elevationDeg:number;referenceHeight?:number};
export function parseCameraState(value:unknown):CameraState|undefined{
const v=value as CameraState;
if(!v||!v.pivot||![v.pivot.x,v.pivot.y,v.pivot.z,v.distance,v.azimuthDeg,v.elevationDeg].every(n=>typeof n==='number'&&Number.isFinite(n)))return;
if(v.distance<.05||v.distance>500||Math.max(...Object.values(v.pivot).map(Math.abs))>100000||Math.abs(v.azimuthDeg)>1e9||v.elevationDeg<5||v.elevationDeg>90)return;
return {pivot:{x:v.pivot.x,y:v.pivot.y,z:v.pivot.z},distance:v.distance,azimuthDeg:v.azimuthDeg,elevationDeg:v.elevationDeg,...(Number.isFinite(v.referenceHeight)&&v.referenceHeight!>=1&&v.referenceHeight!<=10000?{referenceHeight:v.referenceHeight}:{})};
}
export function viewportFov(height:number,referenceHeight:number){return 2*Math.atan(Math.max(1,height)/Math.max(1,referenceHeight)*Math.tan(14*Math.PI/180))*180/Math.PI;}
@@ -0,0 +1,17 @@
export type ChargeGradient={enabled:boolean;lowA:string;lowB:string;highA:string;highB:string;speed:number;scale:number;intensity:number};
export const defaultChargeGradient=():ChargeGradient=>({enabled:true,lowA:'#ef2815',lowB:'#ff9b23',highA:'#20db62',highB:'#6cffe0',speed:.45,scale:12,intensity:2.5});
export function parseChargeGradient(raw:unknown):ChargeGradient{
const result=defaultChargeGradient(),value=raw as Partial<ChargeGradient>|undefined;
if(!value)return result;
if(typeof value.enabled==='boolean')result.enabled=value.enabled;
for(const key of ['lowA','lowB','highA','highB'] as const)if(typeof value[key]==='string'&&/^#[0-9a-f]{6}$/i.test(value[key]))result[key]=value[key];
for(const [key,min,max] of [['speed',0,3],['scale',1,50],['intensity',0,10]] as const)if(typeof value[key]==='number'&&Number.isFinite(value[key]))result[key]=Math.max(min,Math.min(max,value[key]));
return result;
}
/** Interpolate each end of the gradient; no individual-cell SOC is inferred. */
export function chargePair(spec:ChargeGradient,soc:number|null):[number[],number[]]{
const t=Number.isFinite(soc)?Math.max(0,Math.min(100,soc!))/100:0;
const rgb=(hex:string)=>[1,3,5].map(i=>parseInt(hex.slice(i,i+2),16)/255);
const mix=(a:string,b:string)=>rgb(a).map((v,i)=>v+(rgb(b)[i]-v)*t);
return [mix(spec.lowA,spec.highA),mix(spec.lowB,spec.highB)];
}
@@ -0,0 +1,25 @@
import {decodeEditorDock,type EditorDockState} from '@nodedc/ui-core';
/** Scene-owned layout; ui-core supplies only framework-neutral split contracts. */
export type EditorWindowRect = {left:number;top:number;width:number;height:number};
export const editorWindowIds = ['objects','environment','material','palette'] as const;
export type EditorWindowId = typeof editorWindowIds[number];
export type SceneEditorLayout = {windows:Partial<Record<EditorWindowId,EditorWindowRect>>;materialTileSize:number;docking?:EditorDockState};
export const materialTileSizes = {min:84,max:224,step:20,default:144};
export function parseEditorLayout(raw:unknown):SceneEditorLayout|undefined {
if(!raw||typeof raw!=='object')return undefined;
const value=raw as Partial<SceneEditorLayout>,windows:SceneEditorLayout['windows']={};
for(const id of editorWindowIds){
const rect=value.windows?.[id];
if(!rect||!['left','top','width','height'].every(k=>typeof rect[k as keyof EditorWindowRect]==='number'&&Number.isFinite(rect[k as keyof EditorWindowRect])))continue;
if(rect.width<=0||rect.height<=0)continue;
windows[id]={left:Math.max(-16384,Math.min(16384,rect.left)),top:Math.max(-16384,Math.min(16384,rect.top)),width:Math.min(16384,rect.width),height:Math.min(16384,rect.height)};
}
const size=value.materialTileSize;
const docking=decodeEditorDock(value.docking,'viewport',editorWindowIds);
return {windows,materialTileSize:typeof size==='number'&&Number.isFinite(size)?Math.max(materialTileSizes.min,Math.min(materialTileSizes.max,size)):materialTileSizes.default,...(docking?{docking}:{})};
}
export function editorDockLayout(layout:SceneEditorLayout|undefined):EditorDockState {
if(layout?.docking)return layout.docking;
if(layout&&Object.keys(layout.windows).length)return {tree:{id:'viewport'},floating:{...layout.windows}};
return {tree:{axis:'y',ratio:74,first:{axis:'x',ratio:24,first:{id:'objects'},second:{id:'viewport'}},second:{id:'palette'}},floating:{}};
}
@@ -0,0 +1,219 @@
{
"equipment-0493091ab933": {
"name": "V2 · holder",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-0908c23514b2": {
"name": "R02 | мягкая прокладка",
"color": "#2c3538",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-11906634ee6a": {
"name": "K1 v02 optical panel",
"color": "#50565b",
"metalness": 0.5600000023841858,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-13e890e68f3f": {
"name": "R01 | X4 габаритный макет",
"color": "#24292d",
"metalness": 0,
"roughness": 0.44,
"finish": "polymer"
},
"equipment-1bbe3dad55fc": {
"name": "K1 recessed dark",
"color": "#10181b",
"metalness": 0.10000000149011612,
"roughness": 0.5,
"finish": ""
},
"equipment-1d261a8554d2": {
"name": "Graphite",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-1e00b025ef0c": {
"name": "R02 | крепёж",
"color": "#bfc8ce",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-1f5d576357b7": {
"name": "V2 · gold",
"color": "#d3ad61",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-2161878cdab8": {
"name": "V2 · dark",
"color": "#42484d",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-2383eeb9eaa4": {
"name": "K1 v02 optical pupil",
"color": "#070d14",
"metalness": 0.18000000715255737,
"roughness": 0.0949999988079071,
"finish": ""
},
"equipment-29bcad9db811": {
"name": "K1 v02 black anodized lens barrel",
"color": "#292c2e",
"metalness": 0.6200000047683716,
"roughness": 0.27000001072883606,
"finish": ""
},
"equipment-2ab952389fe9": {
"name": "V2 · base",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-34aa5bfe76d8": {
"name": "R01 | оптика",
"color": "#212c34",
"metalness": 0.44999998807907104,
"roughness": 0.15000000596046448,
"finish": ""
},
"equipment-475e36b7333a": {
"name": "K1 v02 optical coating",
"color": "#182227",
"metalness": 0.4000000059604645,
"roughness": 0.10499999672174454,
"finish": ""
},
"equipment-688e0cbe9c28": {
"name": "K1 v02 satin optical mounts",
"color": "#5b5f5f",
"metalness": 0.6200000047683716,
"roughness": 0.36000001430511475,
"finish": ""
},
"equipment-69e526e4be1d": {
"name": "V2 · cap",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-7b915b2b1e72": {
"name": "C15 · латунная вставка M3 8x4.6",
"color": "#ddaf59",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-7f03a1b05fab": {
"name": "K1 optical glass visual",
"color": "#0a1d24",
"metalness": 0.3499999940395355,
"roughness": 0.12999999523162842,
"finish": ""
},
"equipment-8ad4cd1cb790": {
"name": "K1 graphite alloy",
"color": "#555b61",
"metalness": 0.550000011920929,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-9b5cc39ebcbc": {
"name": "K1 marking",
"color": "#b5b8bc",
"metalness": 0.30000001192092896,
"roughness": 0.5,
"finish": ""
},
"equipment-a7a15ac46f69": {
"name": "K1 machined aluminium",
"color": "#aaafb5",
"metalness": 0.800000011920929,
"roughness": 0.2800000011920929,
"finish": ""
},
"equipment-a7b17ba2a0ea": {
"name": "COMMS stainless",
"color": "#aab5b8",
"metalness": 0.800000011920929,
"roughness": 0.23000000417232513,
"finish": ""
},
"equipment-aa837fc3ef7e": {
"name": "K1 v02 internal optical reflection",
"color": "#353f3d",
"metalness": 0.699999988079071,
"roughness": 0.1599999964237213,
"finish": ""
},
"equipment-ae3f1afea9c8": {
"name": "COMMS gasket",
"color": "#212423",
"metalness": 0.0,
"roughness": 0.800000011920929,
"finish": ""
},
"equipment-c080c558e87a": {
"name": "V2 · power",
"color": "#e1a659",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-c97348106414": {
"name": "COMMS black ASA",
"color": "#232728",
"metalness": 0.0,
"roughness": 0.30000001192092896,
"finish": ""
},
"equipment-dd82990a7ae2": {
"name": "C15 · винт M3",
"color": "#afb8bc",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-e1968fb48dc3": {
"name": "V2 · steel",
"color": "#b3babf",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-e5d7e970a6a9": {
"name": "K1 rubber",
"color": "#1b1e21",
"metalness": 0.0,
"roughness": 0.6600000262260437,
"finish": ""
},
"equipment-e9d38b515cd1": {
"name": "C17 · крепёж основания M4x16",
"color": "#b3b8bd",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-ffdf234220cd": {
"name": "K1 v02 charging contact gold",
"color": "#d7a252",
"metalness": 0.800000011920929,
"roughness": 0.25,
"finish": ""
}
}
@@ -0,0 +1,5 @@
export const roverModelID='dcd006-v022';
export const roverModelRevision='dcd006-v022-materials-v2';
export const roverModelURL='/rover-scene/dcd006-v022.glb?materials-v2';
export const legacyRoverModelRevision='dcd006-v020-materials-v2';
export const previousRoverModelRevision='dcd006-v022-assembly-v1';
@@ -1,5 +1,11 @@
import {parseEditorLayout,type SceneEditorLayout} from './editorLayout';
import {parseCameraState,type CameraState} from './cameraState';
import {parseChargeGradient,type ChargeGradient} from './chargeGradient';
import equipmentMaterials from './equipmentMaterials.json';
import {roverModelRevision,legacyRoverModelRevision,previousRoverModelRevision} from './model';
import {mergePostFxDefaults,type PostFxSettings} from './postFx';
import donorFields from './environmentFields.json';
import {validObjectId} from './sceneObjects';
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'},
@@ -9,12 +15,15 @@ export const environmentFields:SceneField[]=[...donorFields,
];
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>};
export type MaterialSpec={chargeGradient?:ChargeGradient;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'|'missioncore.battery-scene/v1';model:string;environmentVersion:2;camera?:CameraState;editorLayout?:SceneEditorLayout;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;objects?:Record<string,boolean>};
// Reserve the added equipment slots without consuming the legacy custom-material budget.
export const maxSceneMaterials=128+Object.keys(equipmentMaterials).length;
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:{
return {schema:'missioncore.rover-scene/v1',model:roverModelRevision,environmentVersion:2,postFx,cameraZoomStrength:.04,cameraAutoRotate:false,assignments:{},materials:{
...Object.fromEntries(Object.entries(equipmentMaterials).map(([key,m])=>['rover/'+key,material(m.name,m.color,m.metalness,m.roughness)])),
'rover/body':material('Корпус и подвеска','#2c2f31',.12,.53),
'rover/rubber':material('Резина гусениц и катков','#202328',0,.72),
'rover/track-steel':material('Нержавеющие проставки','#c4c8cd',1,.17),
@@ -27,12 +36,12 @@ export function defaultScene():SceneDocument{
}};
}
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;
if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id)||Object.keys(doc.materials).length>=maxSceneMaterials)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;
if((!Object.hasOwn(doc.materials,group)||group.startsWith('custom/'))||!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);}
@@ -56,6 +65,7 @@ export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDoc
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);
}
if(value===old)return doc;
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];}
@@ -65,11 +75,14 @@ export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDoc
}
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();
export function parseScene(raw:unknown,defaults:()=>SceneDocument=defaultScene):SceneDocument{
const base=defaults(),r=raw as SceneDocument;const models=base.schema==='missioncore.rover-scene/v1'?[roverModelRevision,legacyRoverModelRevision,previousRoverModelRevision]:[base.model];if(!r||r.schema!==base.schema||!models.includes(r.model))throw new Error('Файл сцены не подходит к этой модели.');
let doc=base;
const layout=parseEditorLayout(r.editorLayout);if(layout)doc.editorLayout=layout;
const camera=parseCameraState(r.camera);if(camera)doc.camera=camera;
if(doc.objects)for(const id of Object.keys(doc.objects)){const legacy=Object.keys(r.objects??{}).filter(key=>id===key||id.startsWith(key+'/')).sort((a,b)=>b.length-a.length)[0];if(legacy&&typeof r.objects?.[legacy]==='boolean')doc.objects[id]=r.objects[legacy];}
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 материалов.');
if(Object.keys(r.materials??{}).length>maxSceneMaterials)throw new Error(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);
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;
@@ -77,9 +90,27 @@ export function parseScene(raw:unknown):SceneDocument{
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;
if(m.chargeGradient)base.chargeGradient=parseChargeGradient(m.chargeGradient);
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);
for(const key of ['objectAssignments','objectVisibility'] as const){
const entries=Object.entries(r[key]??{});if(entries.length>4096)throw new Error('Слишком много объектов в файле сцены.');
const values=entries.filter(([id,value])=>validObjectId(id)&&(key==='objectAssignments'?typeof value==='string'&&Object.hasOwn(doc.materials,value):typeof value==='boolean'));
if(values.length)(doc as any)[key]=Object.fromEntries(values);
}
if(base.schema==='missioncore.battery-scene/v1'){
for(const parent of ['bms/labels','bms/CASE | dielectric liner']){
const oldId='object/Model/'+encodeURIComponent(parent);
for(const name of Object.keys(doc.objects??{}).filter(name=>name.startsWith(parent+'/'))){const id='object/Model/'+encodeURIComponent(name);for(const key of ['objectAssignments','objectVisibility'] as const){const values=doc[key];if(values&&values[oldId]!==undefined&&values[id]===undefined)(values as Record<string,unknown>)[id]=values[oldId];}}
}
}
if(base.schema==='missioncore.rover-scene/v1'&&r.model!==roverModelRevision)for(const [key,spec] of Object.entries(equipmentMaterials)){
if(!spec.finish)continue;
const group='rover/'+key,finish=doc.materials['rover/'+spec.finish];
doc.materials[group]={...doc.materials[group],color:finish.color,metalness:finish.metalness,roughness:finish.roughness};
delete doc.assignments[group];
}
if(textureBytes(doc)>28_000_000)throw new Error('Суммарный объём текстур превышает 20 МБ.');
return doc;
}
@@ -0,0 +1,27 @@
/** Session history retains shared immutable document values, not cloned snapshots. */
export class SceneHistory<T> {
private past:T[]=[];
private future:T[]=[];
private grouping=false;
private recorded=false;
constructor(public present:T){}
get canUndo(){return this.past.length>0;}
get canRedo(){return this.future.length>0;}
begin(){this.grouping=true;this.recorded=false;}
end(){this.grouping=false;this.recorded=false;}
reset(value:T){this.present=value;this.past=[];this.future=[];this.end();}
update(value:T){
if(value===this.present)return false;
if(!this.grouping||!this.recorded)this.past.push(this.present);
this.recorded=true;this.future=[];this.present=value;return true;
}
undo(){this.end();if(!this.canUndo)return false;this.future.push(this.present);this.present=this.past.pop()!;return true;}
redo(){this.end();if(!this.canRedo)return false;this.past.push(this.present);this.present=this.future.pop()!;return true;}
}
export function historyCommand(event:{code:string;key:string;ctrlKey:boolean;metaKey:boolean;shiftKey:boolean;altKey:boolean}):'undo'|'redo'|null{
if(!(event.ctrlKey||event.metaKey)||event.altKey)return null;
const key=event.key.toLowerCase();
if(event.code==='KeyZ'||key==='z'||key==='я')return event.shiftKey?'redo':'undo';
if(event.code==='KeyY'||key==='y'||key==='н')return 'redo';
return null;
}
@@ -15,7 +15,8 @@ function withdrawnEnvironment(){
}
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());
const environmentChanged=(raw as Partial<SceneDocument>).environmentVersion!==2;
const updated=environmentChanged||(raw as Partial<SceneDocument>).model!==doc.model;
const restoredEnvironment=environmentChanged&&JSON.stringify(doc.postFx)===JSON.stringify(withdrawnEnvironment());
return {document:restoredEnvironment?{...doc,postFx:defaultScene().postFx}:doc,updated,restoredEnvironment};
}
@@ -0,0 +1,15 @@
import type {SceneDocument} from './sceneDocument';
export type SceneObject={id:string;name:string;enabled:boolean;renderable:boolean;materialIds?:string[];children:SceneObject[]};
export const validObjectId=(id:string)=>id.startsWith('object/')&&id.length<=2048&&!/[\u0000-\u001f]/.test(id);
export function objectTargets(node:SceneObject):string[]{return [...(node.renderable?[node.id]:[]),...node.children.flatMap(objectTargets)];}
export function findSceneObject(node:SceneObject|null,id:string|null):SceneObject|undefined{
if(!node||!id)return;return node.id===id?node:node.children.map(child=>findSceneObject(child,id)).find(Boolean);
}
export function assignObjectMaterial(doc:SceneDocument,ids:readonly string[],material:string):SceneDocument{
if(!Object.hasOwn(doc.materials,material)||!ids.length||ids.some(id=>!validObjectId(id)))return doc;
if(ids.every(id=>doc.objectAssignments?.[id]===material))return doc;
const objectAssignments={...doc.objectAssignments};for(const id of ids)objectAssignments[id]=material;
if(Object.keys(objectAssignments).length>4096)return doc;
return {...doc,objectAssignments};
}
@@ -1,5 +1,6 @@
import type {SceneDocument} from './sceneDocument';
import {loadStoredScene} from './sceneMigration';
// Retain the original storage slot so upgrades preserve operator materials and environment.
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>{
@@ -1,22 +1,32 @@
import type {CameraState} from './cameraState';
import {useCallback,useEffect,useRef,useState} from 'react';
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
import {SceneHistory} from './sceneHistory';
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 enqueue=(vehicle:string,doc:SceneDocument,write=saveScene)=>{const next=writes.catch(()=>{}).then(()=>write(vehicle,doc));writes=next;return next;};
export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:typeof saveScene;filename:string};
export function useSceneDocument(vehicle:string,profile?:SceneDocumentProfile){
const defaults=profile?.defaults??defaultScene,read=profile?.read??readScene,write=profile?.write??saveScene;
const [document,setDocument]=useState(defaults),[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');},[]);
const latest=useRef({document,revision,vehicle,write});latest.current={document,revision,vehicle,write};
const pendingCamera=useRef<CameraState|null>(null);
const savedRevision=useRef(0),history=useRef(new SceneHistory(document));
const publish=useCallback(()=>{setDocument(history.current.present);setRevision(v=>v+1);setSaveState('saving');},[]);
const undo=useCallback(()=>{pendingCamera.current=null;if(history.current.undo())publish();},[publish]);
const redo=useCallback(()=>{pendingCamera.current=null;if(history.current.redo())publish();},[publish]);
const beginGesture=useCallback(()=>history.current.begin(),[]),endGesture=useCallback(()=>history.current.end(),[]);
useEffect(()=>{let cancelled=false;read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle,profile]);
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(history.current.update(fn(history.current.present)))publish();},[publish]);
const recordCamera=useCallback((camera:CameraState,commit=false)=>{pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]);
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);
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).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};
},[ready,revision,vehicle,document,write]);
useEffect(()=>()=>{const v=latest.current;if(pendingCamera.current||v.revision>savedRevision.current)void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).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()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=profile?.filename??'rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return {document,recordCamera,ready,saveState,error,setError,update,undo,redo,canUndo:history.current.canUndo,canRedo:history.current.canRedo,beginGesture,endGesture,importDocument,exportDocument};
}
@@ -0,0 +1,90 @@
import {semanticDraft,semanticRequest,type SemanticDraft,type SemanticRevision} from "./semanticEdits";
import {checkSemanticWorld,chooseVersion,manualKey,semanticVersions,versionOptions,versionQuery,type SemanticVersions} from "./semanticVersions";
interface DocumentState {
revision:SemanticRevision|null;draft:SemanticDraft|null;versions:SemanticVersions|null;
selected:string;editing:boolean;saving:boolean;loading:boolean;error:string|null;
}
export interface SemanticDocumentApi {
versions:typeof semanticVersions;request:typeof semanticRequest;uuid:()=>string;
}
const api:SemanticDocumentApi={versions:semanticVersions,request:semanticRequest,uuid:()=>crypto.randomUUID()};
/** One session owns the draft AND its pending save across scene mounts. */
export class SemanticDocumentSession {
private value:DocumentState;
private listeners=new Set<()=>void>();
private generation=0;
private abort:AbortController|null=null;
private branch:string|null=null;
private attempt:{key:string;signature:string}|null=null;
constructor(readonly worldId:string,readonly worldSha:string,preferred:string,private transport=api){
this.value={revision:null,draft:null,versions:null,selected:preferred,editing:false,saving:false,loading:false,error:null};
}
snapshot=()=>this.value;
subscribe=(listener:()=>void)=>{this.listeners.add(listener);return()=>{this.listeners.delete(listener);};};
private update(patch:Partial<DocumentState>){this.value={...this.value,...patch};this.listeners.forEach(listener=>listener());}
get dirty(){return !!this.value.draft?.operations.length;}
get protected(){return this.dirty||this.value.saving;}
get canEdit(){return this.value.selected!=="raw"&&!this.value.loading&&!this.value.saving&&!!this.value.revision;}
async open(preferred=this.value.selected){
if(this.protected)return;
this.abort?.abort();const abort=this.abort=new AbortController(),id=++this.generation;
this.update({loading:true,editing:false,error:null});
try {
const versions=await this.transport.versions(this.worldId,abort.signal);
const selected=chooseVersion(preferred,versions);
const revision=await this.transport.request(this.worldId,undefined,abort.signal,versionQuery(selected,versions));
checkSemanticWorld(revision,this.worldSha);
if(abort.signal.aborted||id!==this.generation)return;
this.branch=null;this.attempt=null;
// Commit the identity, label and geometry together. A failed GET retains
// the previous view, and a late response cannot overwrite a newer view.
this.update({versions,selected,revision,draft:semanticDraft(revision.edited),loading:false});
} catch(error){if(!abort.signal.aborted&&id===this.generation)this.update({error:(error as Error).message,loading:false});}
}
select=(selected:string)=>{if(!this.protected&&!this.value.loading)void this.open(selected);};
setEditing=(next:boolean)=>{if(!next){this.update({editing:false});return;}if(!this.canEdit)return;
if(this.value.selected==="algorithmic"&&!this.branch)this.branch=this.transport.uuid();
this.update({editing:true});};
toggleEditing=()=>this.setEditing(!this.value.editing);
setDraft=(value:SemanticDraft|null|((prior:SemanticDraft|null)=>SemanticDraft|null))=>{
if(!this.canEdit||!this.value.editing)return;
this.update({draft:typeof value==="function"?value(this.value.draft):value});
};
discard=()=>{if(this.value.saving||!this.value.revision)return;this.branch=null;this.attempt=null;
this.update({draft:semanticDraft(this.value.revision.edited),editing:false});};
save=async()=>{
const {draft,revision,selected,versions}=this.value;
if(!draft?.operations.length||!revision||!versions||this.value.saving||selected==="raw")return;
const branch=selected==="algorithmic"?this.branch:revision.branch_id;
if(selected==="algorithmic"&&!branch){this.update({error:"Не удалось создать ручную версию."});return;}
const body={expected_revision:revision.revision,model_sha256:revision.model_sha256,operations:draft.operations,
...(branch?{branch_id:branch}:{})};
const signature=JSON.stringify(body);
if(this.attempt?.signature!==signature)this.attempt={signature,key:this.transport.uuid()};
this.update({saving:true,error:null});
try {
const saved=await this.transport.request(this.worldId,{...body,request_id:this.attempt.key});
checkSemanticWorld(saved,this.worldSha);
if(!saved.revision||saved.model_sha256!==revision.model_sha256||(saved.branch_id??null)!==(branch??null))
throw new Error("Ответ сохранения относится к другой версии. Черновик сохранён в этом окне.");
const row={branch_id:saved.branch_id??null,revision:saved.revision,model_sha256:saved.model_sha256,
created_at:saved.history.at(-1)!.created_at};
this.branch=null;this.attempt=null;
this.update({revision:saved,draft:semanticDraft(saved.edited),selected:manualKey(saved.branch_id??null),editing:false,
versions:{...versions,manual:[row,...versions.manual.filter(v=>v.branch_id!==row.branch_id)]}});
} catch(error){this.update({error:(error as Error).message});}
finally{this.update({saving:false});}
};
options=()=>this.value.versions?versionOptions(this.value.versions):[];
}
const sessions=new Map<string,SemanticDocumentSession>();
export function getSemanticSession(worldId:string,worldSha:string,preferred:string) {
for(const [key,session] of sessions)if(key!==worldSha&&!session.protected&&!session.snapshot().loading)sessions.delete(key);
let session=sessions.get(worldSha);
if(!session){session=new SemanticDocumentSession(worldId,worldSha,preferred);sessions.set(worldSha,session);}
return session;
}
export const hasUnsavedSemanticSessions=()=>[...sessions.values()].some(session=>session.protected);
@@ -68,7 +68,7 @@ function objectOperation(map:UrbanMap,op:Exclude<SemanticOperation,VertexOperati
}
export interface SemanticRevision {
schema_version:"missioncore.semantic-editor/v1";
revision:string|null;model_sha256:string;latest_model_sha256:string;
branch_id?:string|null;revision:string|null;model_sha256:string;latest_model_sha256:string|null;
model:UrbanMap;edited:UrbanMap;
history:{revision:string;created_at:string;actions:number}[];
learning:{state:string;dataset_ready:boolean};
@@ -138,8 +138,9 @@ export function segmentHit(p:number[],a:number[],b:number[]) {
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
return {t,distance:Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy)};
}
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal):Promise<SemanticRevision> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits`,{
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal,query?:Record<string,string>):Promise<SemanticRevision> {
const search=query?`?${new URLSearchParams(query)}`:"";
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits${search}`,{
method:body?"POST":"GET",cache:"no-store",signal,
...(body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}:{}),
});
@@ -149,6 +150,7 @@ export async function semanticRequest(worldId:string,body?:object,signal?:AbortS
}
const result=await response.json() as SemanticRevision;
if(result.schema_version!=="missioncore.semantic-editor/v1")throw new Error("Неизвестная версия редактора.");
if(query?.source==="raw"&&(result as SemanticRevision&{read_only?:boolean}).read_only===true)result.edited=result.model;
return result;
}
@@ -0,0 +1,37 @@
import type {SemanticRevision} from "./semanticEdits";
export interface SemanticVersions {
raw_sha256:string|null; algorithmic_sha256:string|null;
manual:{branch_id:string|null;revision:string;model_sha256:string;created_at:string}[];
}
export const manualKey=(branch:string|null)=>`manual:${branch??"legacy"}`;
export function versionOptions(versions:SemanticVersions):{value:string;label:string;disabled?:boolean}[] {
return [
{value:"raw",label:"Сырая алгоритмическая",disabled:!versions.raw_sha256},
{value:"algorithmic",label:"Алгоритмическая",disabled:!versions.algorithmic_sha256},
...versions.manual.map((row,i)=>({value:manualKey(row.branch_id),
label:versions.manual.length===1?"Ручная":`Ручная · ${new Date(row.created_at).toLocaleString("ru-RU")}${i===0?" · последняя":""}`})),
];
}
export function versionQuery(key:string,versions:SemanticVersions):Record<string,string> {
if(key==="raw"||key==="algorithmic")return {source:key,
model_sha256:(key==="raw"?versions.raw_sha256:versions.algorithmic_sha256)??""};
const branch=versions.manual.find(row=>manualKey(row.branch_id)===key);
if(!branch)throw new Error("Ручная версия не найдена.");
return {source:"manual",...(branch.branch_id?{branch_id:branch.branch_id}:{})};
}
export function chooseVersion(preferred:string,versions:SemanticVersions):string {
if(preferred==="manual"&&versions.manual.length)return manualKey(versions.manual[0].branch_id);
const options=versionOptions(versions);
if(options.some(row=>row.value===preferred&&!row.disabled))return preferred;
return versions.algorithmic_sha256?"algorithmic":versions.manual.length?manualKey(versions.manual[0].branch_id):"raw";
}
export async function semanticVersions(worldId:string,signal?:AbortSignal):Promise<SemanticVersions> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-versions`,{cache:"no-store",signal});
if(!response.ok)throw new Error("Не удалось получить версии разметки.");
return response.json();
}
export function checkSemanticWorld(value:SemanticRevision,worldSha:string) {
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
throw new Error("Правки относятся к другой сцене.");
}
@@ -3,18 +3,20 @@ import type {EditorProjection} from "./editorProjection";
import type {SemanticAxis} from "./semanticVector";
export interface SimulationLayout {
mode:"view"|"semantic"|"planning"; projection:EditorProjection;
semanticVersion:"raw"|"algorithmic"|"manual";
sceneLayers:{gaussian:boolean;collision:boolean}; infrastructure:boolean; memory:boolean;
layers:UrbanClassId[]; urbanLayers:UrbanClassId[];
visible:{model:boolean;user:boolean}; axis:SemanticAxis; areaMode:"union"|"difference";
}
const classes:UrbanClassId[]=["road_boundary","pedestrian_boundary","building_facade","curb","curb_cut","sidewalk","pedestrian_area","carriageway","service_lane","bike_lane","parking","crosswalk_area","crosswalk_marking","road_marking"];
export const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",sceneLayers:{gaussian:true,collision:false},infrastructure:false,memory:false,layers:["road_boundary"],urbanLayers:classes,visible:{model:false,user:true},axis:"xy",areaMode:"union"};
export const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",semanticVersion:"algorithmic",sceneLayers:{gaussian:true,collision:false},infrastructure:false,memory:false,layers:["road_boundary"],urbanLayers:classes,visible:{model:false,user:true},axis:"xy",areaMode:"union"};
export function normalizeSimulationLayout(raw:unknown):SimulationLayout {
const v=(raw&&typeof raw==="object"?raw:{}) as Partial<SimulationLayout>,d=DEFAULT_SIMULATION_LAYOUT;
const pick=<T extends string>(x:unknown,values:readonly T[],fallback:T):T=>values.includes(x as T)?x as T:fallback;
const bool=(x:unknown,f:boolean)=>typeof x==="boolean"?x:f;
const layers=(x:unknown,f:UrbanClassId[])=>Array.isArray(x)?Array.from(new Set(x.filter((k):k is UrbanClassId=>classes.includes(k)))):f;
return {mode:pick(v.mode,["view","semantic","planning"],d.mode),projection:pick(v.projection,["perspective","orthographic"],d.projection),
semanticVersion:pick(v.semanticVersion,["raw","algorithmic","manual"],d.semanticVersion),
sceneLayers:{gaussian:bool(v.sceneLayers?.gaussian,true),collision:bool(v.sceneLayers?.collision,false)},infrastructure:bool(v.infrastructure,false),memory:bool(v.memory,false),
layers:layers(v.layers,d.layers),urbanLayers:layers(v.urbanLayers,d.urbanLayers),visible:{model:bool(v.visible?.model,false),user:bool(v.visible?.user,true)},
axis:pick(v.axis,["x","y","z","xy","xz","yz"],d.axis),areaMode:pick(v.areaMode,["union","difference"],d.areaMode)};
@@ -196,5 +196,6 @@
.semantic-tools__menu { display: flex; flex-direction: column; gap: .25rem; }
.ai-polygon__semantic-actions { display: contents; }
.ai-polygon__semantic-version-field { width: 18rem; min-width: 0; max-width: 100%; }
.ai-local-editor__cube { position: absolute; top: 8px; left: 4px; z-index: 5; }
@@ -1,6 +1,8 @@
import {useState} from 'react';
import {useBoardNetwork} from '../../core/fleet/useBoardNetwork';
import {useBoardNetworkStatus} from '../../core/fleet/useBoardNetworkStatus';
import {BoardNetworkSettings} from './BoardNetworkSettings';
import {BoardNetworkStatus} from './BoardNetworkStatus';
import {Button,Icon,IconButton,ResourceRow,StatusBadge,FeatureSettingsWindow,WindowFooterActions} from '@nodedc/ui-react';
import type {Vehicle} from '../../core/fleet/useFleet';
@@ -14,11 +16,12 @@ export function BoardComputerRow({vehicle,enabled,showingSavedDevices,onSettings
export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicle:Vehicle;enabled:boolean;onClose:()=>void;onRevoke:()=>void}){
const [section,setSection]=useState('binding');
const network=useBoardNetwork(vehicle.id);
const interfaces=useBoardNetworkStatus(vehicle,enabled);
return <FeatureSettingsWindow open title="Бортовой компьютер" subtitle={vehicle.host?.hostname||'Mission Core Node'}
identity={{title:vehicle.host?.hostname||'Mission Core Node',subtitle:vehicle.node_id,avatarLabel:'БК'}}
sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'},{id:'interfaces',label:'Сеть',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button>{section==='network'&&<Button variant="primary" disabled={!network.canSave} onClick={()=>void network.save()}>{network.applying?'Применяем…':'Сохранить'}</Button>}</WindowFooterActions>}>
{section==='network'?<BoardNetworkSettings network={network}/>:
{section==='network'?<BoardNetworkSettings network={network}/>:section==='interfaces'?<BoardNetworkStatus status={interfaces}/>:
<div className="fleet-form"><StatusBadge tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'}>{boardStatus(vehicle,enabled)}</StatusBadge>
{vehicle.notice&&<p role="status">{vehicle.notice}</p>}
<dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{vehicle.node_id}</dd></div><div><dt>Последняя связь</dt><dd>{vehicle.last_seen?new Date(vehicle.last_seen*1000).toLocaleString('ru-RU'):'Соединение ещё не получено'}</dd></div>
@@ -8,11 +8,11 @@ export function BoardNetworkSettings({network}:{network:ReturnType<typeof useBoa
const current=value?.node;
const selected=value?.profiles.find(p=>p.id===profileId);
const progress=value?.operation?.state;
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='netbird'?'NetBird подключён':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
return <div className="fleet-form">
<SettingsCard title="Связь с Core" description="Профиль связи этого бортового компьютера с Mission Core. Вычислительный Worker сохраняет своё подключение." actions={<StatusBadge tone={applying?'warning':value?.available?'success':'neutral'}>{label}</StatusBadge>}>
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:<>
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'netbird',label:'NetBird · WireGuard'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:provider==='netbird'?<p>{current?.netbird_endpoint?`Борт подключён к ${current.netbird?.server_url}. Новый канал будет проверен перед сохранением.`:'Подключите Core и борт к одному серверу NetBird. На борту: Система → Частная сеть.'}</p>:<>
<Select label="Общий профиль VPS" value={profileId} options={[{value:'',label:'Выберите профиль'},...(value?.profiles??[]).filter(p=>p.state==='ready').map(p=>({value:p.id,label:p.name,description:`Подключено бортов: ${p.boards} · ${p.endpoint}`}))]} onChange={network.setProfileId} disabled={busy||applying}/>
{selected&&<StatusBadge tone={selected.state==='ready'?'success':'warning'}>{selected.state==='ready'?`VPS подключён · Подключено бортов: ${selected.boards}`:'Подключение VPS не завершено'}</StatusBadge>}
<p>Один профиль используется всем парком. У каждого борта будет отдельное защищённое подключение.</p>
@@ -0,0 +1,27 @@
import {memo} from 'react';
import {Description,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {BoardNetworkStatusValue} from '../../core/fleet/boardNetworkStatus';
const NetworkCard=memo(function NetworkCard(link:BoardNetworkStatusValue['links'][number]) {
return <SettingsCard title={link.title}
actions={<StatusBadge tone={link.state==='connected'?'success':link.state==='connecting'?'warning':'neutral'}>{link.status}</StatusBadge>}>
<dl className="fleet-facts">
<div><dt>Модель</dt><dd>{link.model||'Нет сведений'}</dd></div>
<div><dt>Производитель</dt><dd>{link.vendor||'Нет сведений'}</dd></div>
<div><dt>Интерфейс</dt><dd>{link.name}</dd></div>
{link.kind==='wifi'&&<div><dt>Последняя сеть</dt><dd>{link.ssid||'Нет сведений'}</dd></div>}
{link.kind==='wifi'&&<div><dt>Последний сигнал</dt><dd>{link.signal!==null?`${link.signal}%`:'Нет сведений'}</dd></div>}
<div><dt>Последний IP-адрес</dt><dd>{link.addresses?.length?link.addresses.join(', '):'Нет сведений'}</dd></div>
</dl>
</SettingsCard>;
});
export function BoardNetworkStatus({status}:{status:BoardNetworkStatusValue}) {
const {links,readable,live,collectedAt}=status;
return <div className="fleet-form">
<Description>Состояние Wi-Fi и Ethernet по последним полученным данным борта. Карточки обновляются при изменении сведений. Изменение сети здесь недоступно.</Description>
<StatusBadge tone={live?'success':'neutral'}>{live?'Связь с бортом установлена':'Связь с бортом не подтверждена'}</StatusBadge>
<Description>Данные борта на {collectedAt&&Number.isFinite(Date.parse(collectedAt))?new Date(collectedAt).toLocaleString('ru-RU'):'ещё не получен'}.</Description>
{!links.length?<SettingsCard title={readable?'Нет сведений о Wi-Fi и Ethernet':'Сведения о сети недоступны'} description="Борт пока не передал данные физических подключений."/>:
links.map(link=><NetworkCard key={link.name} {...link}/>)}
</div>;
}
@@ -0,0 +1,22 @@
import {useMemo,useState} from 'react';
import {createPortal} from 'react-dom';
import {Description,Icon,IconButton,LoadingRegion,SettingsCard,ToastStack} from '@nodedc/ui-react';
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
import {createFleetSensorTransport} from '../../core/fleet/sensorTransport';
import type {Vehicle} from '../../core/fleet/useFleet';
import {sensorContribution} from '../../../../../packages/sensor-ui/src/extensions';
import {useObservationInventory} from './observation/useObservationInventory';
/** Equipment details own a full workspace, alongside observation and monitoring. */
export function VehicleDeviceView({vehicle,deviceID,enabled,back,headerToolsHost,titlePrefix,headerTitleHost}:{vehicle:Vehicle;deviceID:string;enabled:boolean;back:()=>void;headerToolsHost?:HTMLElement|null;titlePrefix:string;headerTitleHost?:HTMLElement|null}){
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicle.id),[vehicle.id]);
const {inventory,refresh}=useObservationInventory(transport);
const [error,setError]=useState('');
const device=inventory?.items.find(item=>item.id===deviceID),contribution=device?sensorContribution(registry.sensorContributions,device):undefined;
const Detail=contribution?.Detail;
const navigation=<IconButton label="Вернуться к оборудованию аппарата" onClick={back}><Icon name="chevron-left"/></IconButton>;
return <>{headerTitleHost&&createPortal(`${titlePrefix}${device?` / ${device.name}`:""}`,headerTitleHost)}{headerToolsHost?createPortal(navigation,headerToolsHost):navigation}
{!inventory?<LoadingRegion loading label="Получение устройства"/>:device&&Detail?<Detail key={device.id} headerActionsTarget={headerToolsHost} device={device} enabled={enabled&&inventory.fresh!==false} transport={transport} sceneSeedKey={vehicle.id} back={back} refresh={async()=>{await refresh();}} failure={value=>setError(value instanceof Error?value.message:String(value??''))}/>:<SettingsCard title="Устройство недоступно"><Description>Вернитесь к оборудованию и обновите список устройств.</Description></SettingsCard>}
<ToastStack items={error?[{id:'equipment-detail',tone:'error',title:'Просмотр устройства',description:error}]:[]} onDismiss={()=>setError('')}/>
</>;
}
@@ -5,13 +5,13 @@ import {boardStatus} from './BoardComputer';
import {platformLabel} from './NodeInvitationForm';
import {VehicleSensors} from './VehicleSensors';
export function VehicleFleetRow({vehicle,available,expanded,onToggle,onObserve,onAddComputer,onBoardSettings,onMonitor,onUpdated}:{vehicle:Vehicle;available:boolean;expanded:boolean;onToggle:()=>void;onObserve:()=>void;onAddComputer:()=>void;onBoardSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
export function VehicleFleetRow({vehicle,available,expanded,onToggle,onObserve,onAddComputer,onBoardSettings,onMonitor,onUpdated,onDeviceView}:{vehicle:Vehicle;available:boolean;expanded:boolean;onToggle:()=>void;onObserve:()=>void;onAddComputer:()=>void;onBoardSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void;onDeviceView?:(id:string)=>void}){
const [settingsOpen,setSettingsOpen]=useState(false);
const [equipmentActionsTarget,setEquipmentActionsTarget]=useState<HTMLSpanElement|null>(null);
const branchID=useId();
const enabled=available&&vehicle.enrollment==='paired'&&vehicle.connectivity==='online';
const label=available?boardStatus(vehicle):'Нет свежих данных';
const sensors={vehicle,enabled,onAddComputer,onSettings:onBoardSettings,onMonitor,onUpdated};
const sensors={vehicle,enabled,onAddComputer,onSettings:onBoardSettings,onMonitor,onUpdated,onDeviceView};
return <li>
<ResourceRow icon={<Icon name="apps"/>} title={vehicle.name} description={platformLabel(vehicle.platform)} metadata={label} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'} aria-label={label} title={label}/>} actions={<>
{expanded&&!settingsOpen&&<span ref={setEquipmentActionsTarget} className="fleet-equipment-actions"/>}
@@ -7,11 +7,11 @@ import {createFleetSensorTransport} from '../../core/fleet/sensorTransport';
import type {Vehicle} from '../../core/fleet/useFleet';
import {VehicleEquipment} from './VehicleEquipment';
import {VehicleIdentitySettings} from './VehicleIdentitySettings';
export function VehicleSensors({vehicle,enabled,mode='equipment',equipmentActionsTarget,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;mode?:'equipment'|'settings';equipmentActionsTarget?:HTMLElement|null;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
export function VehicleSensors({vehicle,enabled,mode='equipment',equipmentActionsTarget,onAddComputer,onSettings,onMonitor,onUpdated,onDeviceView}:{vehicle:Vehicle;enabled:boolean;mode?:'equipment'|'settings';equipmentActionsTarget?:HTMLElement|null;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void;onDeviceView?:(id:string)=>void}){
const vehicleID=vehicle.id;
const {registry}=useDevicePluginHost();
const sensorContributions=registry.sensorContributions;
const layout=useMemo(()=>boardLayout(vehicleID),[vehicleID]);
const transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={`${vehicleID}:${vehicle.node_id}`} transport={transport} enabled={enabled} previewEnabled={vehicle.enrollment==='paired'} readOfflineInventory detailActionsTarget={equipmentActionsTarget} renderBoard={content=>mode==='settings'?<div className="sensor-content"><VehicleIdentitySettings vehicle={vehicle} onUpdated={onUpdated}/>{content.settings}</div>:<VehicleEquipment vehicle={vehicle} enabled={enabled} layout={layout} content={content} actionsTarget={equipmentActionsTarget} onAddComputer={onAddComputer} onSettings={onSettings} onMonitor={onMonitor}/>}/>;
return <SensorWorkspace onOpenDetail={onDeviceView?device=>onDeviceView(device.id):undefined} sceneSeedKey={vehicleID} contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={`${vehicleID}:${vehicle.node_id}`} transport={transport} enabled={enabled} previewEnabled={vehicle.enrollment==='paired'} readOfflineInventory detailActionsTarget={equipmentActionsTarget} renderBoard={content=>mode==='settings'?<div className="sensor-content"><VehicleIdentitySettings vehicle={vehicle} onUpdated={onUpdated}/>{content.settings}</div>:<VehicleEquipment vehicle={vehicle} enabled={enabled} layout={layout} content={content} actionsTarget={equipmentActionsTarget} onAddComputer={onAddComputer} onSettings={onSettings} onMonitor={onMonitor}/>}/>;
}
@@ -6,15 +6,18 @@ import {BoardObservationCenter} from './observation/BoardObservationCenter';
import {BoardMonitorView} from './BoardMonitorView';
import {BoardComputerSettings} from './BoardComputer';
import {NodeInvitationForm,platformLabel} from './NodeInvitationForm';
import {VehicleDeviceView} from './VehicleDeviceView';
import {VehicleFleetRow} from './VehicleFleetRow';
import {OperatorNetworkWindow} from '../../components/network/OperatorNetworkWindow';
import './fleet.css';
export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerToolsHost?:HTMLElement|null;headerTitleHost?:HTMLElement|null}){
const fleet=useFleet();
const [view,setView]=useState<{vehicleID:string;mode:'observation'|'monitor'}|null>(null);
const [view,setView]=useState<{vehicleID:string;mode:'observation'|'monitor'|'device';deviceID?:string}|null>(null);
const [expanded,setExpanded]=useState<string[]>([]);
const [adding,setAdding]=useState<Vehicle|null|undefined>();
const [boardSettings,setBoardSettings]=useState<string|null>(null);
const [operatorNetwork,setOperatorNetwork]=useState(false);
const [revoking,setRevoking]=useState<Vehicle|null>(null),[error,setError]=useState('');
const detail=fleet.items?.find(item=>item.id===view?.vehicleID);
const settingsVehicle=fleet.items?.find(item=>item.id===boardSettings);
@@ -22,15 +25,17 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools
const refresh=()=>{void fleet.refresh().catch(()=>setError('Не удалось обновить аппарат. Повторите получение сведений.'));};
const showEquipment=(id:string)=>{setExpanded(current=>current.includes(id)?current:[...current,id]);setView(null);};
const complete=(item:Vehicle)=>{setAdding(undefined);showEquipment(item.id);refresh();};
const addButton=<IconButton label="Добавить аппарат" onClick={()=>setAdding(null)}><Icon name="plus"/></IconButton>;
const addButton=<><IconButton label="Сеть операторского компьютера" onClick={()=>setOperatorNetwork(true)}><Icon name="network"/></IconButton><IconButton label="Добавить аппарат" onClick={()=>setAdding(null)}><Icon name="plus"/></IconButton></>;
const headerAdd=!detail&&(headerToolsHost?createPortal(addButton,headerToolsHost):addButton);
const titleSuffix=detail?` — ${detail.name} / ${platformLabel(detail.platform)}`:'';
const content=detail&&view?.mode==='observation'?<BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={enabled(detail)} paired={detail.enrollment==='paired'} back={()=>setView(null)} configure={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost}/>
const content=detail&&view?.mode==='device'&&view.deviceID?<VehicleDeviceView vehicle={detail} deviceID={view.deviceID} enabled={enabled(detail)} back={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost} titlePrefix={titleSuffix} headerTitleHost={headerTitleHost}/>
:detail&&view?.mode==='observation'?<BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={enabled(detail)} paired={detail.enrollment==='paired'} back={()=>setView(null)} configure={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost}/>
:detail&&view?.mode==='monitor'?<BoardMonitorView vehicle={detail.id} name={detail.name} back={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost}/>
:<div className="fleet-workspace">
{!fleet.items?<LoadingRegion loading={!fleet.error} label="Получение аппаратов"/>:fleet.items.length===0?<SettingsCard title="Аппаратов пока нет" description="Создайте аппарат и подключите его бортовой компьютер по приглашению Mission Core Node."/>:<ResourceList aria-label="Аппараты">{fleet.items.map(item=><VehicleFleetRow key={item.id} vehicle={item} available={!fleet.error} expanded={expanded.includes(item.id)} onToggle={()=>setExpanded(current=>current.includes(item.id)?current.filter(id=>id!==item.id):[...current,item.id])} onObserve={()=>setView({vehicleID:item.id,mode:'observation'})} onAddComputer={()=>setAdding(item)} onBoardSettings={()=>setBoardSettings(item.id)} onMonitor={()=>setView({vehicleID:item.id,mode:'monitor'})} onUpdated={fleet.acceptVehicle}/>)}</ResourceList>}
{!fleet.items?<LoadingRegion loading={!fleet.error} label="Получение аппаратов"/>:fleet.items.length===0?<SettingsCard title="Аппаратов пока нет" description="Создайте аппарат и подключите его бортовой компьютер по приглашению Mission Core Node."/>:<ResourceList aria-label="Аппараты">{fleet.items.map(item=><VehicleFleetRow key={item.id} vehicle={item} available={!fleet.error} expanded={expanded.includes(item.id)} onToggle={()=>setExpanded(current=>current.includes(item.id)?current.filter(id=>id!==item.id):[...current,item.id])} onDeviceView={deviceID=>setView({vehicleID:item.id,mode:'device',deviceID})} onObserve={()=>setView({vehicleID:item.id,mode:'observation'})} onAddComputer={()=>setAdding(item)} onBoardSettings={()=>setBoardSettings(item.id)} onMonitor={()=>setView({vehicleID:item.id,mode:'monitor'})} onUpdated={fleet.acceptVehicle}/>)}</ResourceList>}
</div>;
return <>{headerTitleHost&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{content}
return <>{headerTitleHost&&view?.mode!=='device'&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{content}
{operatorNetwork&&<OperatorNetworkWindow onClose={()=>setOperatorNetwork(false)}/>}
{adding!==undefined&&<NodeInvitationForm key={adding?.id??'new'} vehicle={adding??undefined} onClose={()=>setAdding(undefined)} onComplete={complete} renderWindow={({content,actions,busy})=><Window open title={adding?'Подключить бортовой компьютер':'Добавить аппарат'} subtitle={adding?adding.name:'Создать аппарат и подключить БК по приглашению Node'} size="md" closeOnBackdrop={false} closeOnEscape={!busy} onClose={()=>{if(!busy)setAdding(undefined);}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}>{content}</Window>}/>}
{settingsVehicle&&<BoardComputerSettings vehicle={settingsVehicle} enabled={enabled(settingsVehicle)} onClose={()=>setBoardSettings(null)} onRevoke={()=>{setBoardSettings(null);setRevoking(settingsVehicle);}}/>}
<ConfirmationModal open={revoking!==null} title="Отозвать привязку БК?" description={`Аппарат «${revoking?.name??''}» останется в реестре. БК потеряет доступ к Core и получит отзыв при следующем соединении.`} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={()=>setRevoking(null)} onConfirm={async()=>{if(!revoking)return;try{await fleetRequest(`/${encodeURIComponent(revoking.id)}`,'DELETE');await fleet.refresh();setRevoking(null);}catch(e){setError(e instanceof Error?e.message:'Не удалось отозвать привязку.');throw e;}}}/>
@@ -1,11 +1 @@
import {Fragment,useEffect,useState} from 'react';
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
</SettingsCard>;
}
export {InstallerCard} from '../../../components/network/InstallerCard';
@@ -4,6 +4,8 @@ import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,Stat
import {useDevicePluginHost} from '../../../core/device-plugins/DevicePluginHost';
import {createFleetSensorTransport} from '../../../core/fleet/sensorTransport';
import {moveObservation,withObservationTree,orderedObservationIDs,observationTree} from '../../../core/fleet/observationLayout';
import {bindObservationLayout} from '../../../core/fleet/observationBinding';
import {useSpatialDefaults} from '../../../core/observation/useSpatialDefaults';
import {useVehicleObservation} from '../../../core/fleet/useVehicleObservation';
import {observationArrangements,retainDormantObservationTree} from '../../../core/fleet/observationPresets';
import {ObservationLayoutSaveWindow} from '../../../components/observation/ObservationLayoutSaveWindow';
@@ -11,8 +13,9 @@ import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHo
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
import {unboundObservationViews} from '../../../../../../packages/sensor-ui/src/observationCatalog';
import {sensorContribution} from '../../../../../../packages/sensor-ui/src/extensions';
import {sensorContribution,wirelessContributions} from '../../../../../../packages/sensor-ui/src/extensions';
import {ObservationDeviceSettings} from './ObservationDeviceSettings';
import {ObservationConnectionWindow} from './ObservationConnectionWindow';
import {ObservationPanelHeader} from './ObservationPanelHeader';
import {ObservationDeck,ObservationMount} from './ObservationDeck';
import {ObservationMap} from './ObservationMap';
@@ -25,28 +28,42 @@ import {RoverLogs} from '../../../components/rover/RoverLogs';
import {useRoverDiagnostics} from '../../../core/fleet/useRoverDiagnostics';
import {useRoverControl} from '../../../core/fleet/useRoverControl';
import {roverObservationStatus} from '../../../core/fleet/roverObservation';
import {observationPortal} from '../../../core/observation/observationPortal';
export function BoardObservationCenter({vehicleID,name,enabled,paired,back,configure,headerToolsHost}:{vehicleID:string;name:string;enabled:boolean;paired:boolean;back:()=>void;configure:()=>void;headerToolsHost?:HTMLElement|null}){
const diagnostics=useRoverDiagnostics(vehicleID);
const [devOpen,setDevOpen]=useState(false);
const [primaryCamera,setPrimaryCamera]=useState<string|null>(null),primaryRef=useRef<string|null>(null);
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
const inventory=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
const {inventory,refresh}=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
const {layout,setLayout}=presets;
const spatialDefaults=useSpatialDefaults();
const [saving,setSaving]=useState(false),[editing,setEditing]=useState<string|null>(null);
const edited=presets.presets.find(p=>p.id===editing);
const [settingsView,setSettingsView]=useState('points');
const [settingsDevice,setSettingsDevice]=useState<string|null>(null);
const [connectingKind,setConnectingKind]=useState<string|null>(null);
const wireless=wirelessContributions(registry.sensorContributions);
const connect=(kind:string)=>{setSettingsDevice(null);setConnectingKind(kind);};
const reconnect=(kind:string|undefined)=>kind&&transport.enrollment&&wireless.some(item=>item.kind===kind)?()=>connect(kind):undefined;
const [layersOpen,setLayersOpen]=useState(false);
const [full,setFull]=useState<string|null>(null),[expanded,setExpanded]=useState(false);
const frame=useRef<HTMLDivElement>(null),[portal]=useState(()=>document.createElement('div'));
useLayoutEffect(()=>{(expanded?document.body:frame.current!).append(portal);return()=>portal.remove();},[expanded,portal]);
const portalOwner=useRef<ReturnType<typeof observationPortal>|null>(null);
useLayoutEffect(()=>{const owner=observationPortal(portal,frame.current!,document.body);portalOwner.current=owner;return()=>{portalOwner.current=null;owner.dispose();};},[portal]);
useLayoutEffect(()=>{portalOwner.current?.setExpanded(expanded);},[expanded]);
const mounts=useRef(new Map<string,HTMLElement>()),media=useRef(new Map<string,HTMLElement>()),headers=useRef(new Map<string,ObservationHeaderTargets>());
const groups=(inventory?.items??[]).flatMap(device=>{
const contribution=sensorContribution(registry.sensorContributions,device)?.observation;
const views=contribution?.views(device)??cameraObservationViews(device);
return views.length?[{device,views,independentMediaLiveness:contribution?contribution.independentMediaLiveness===true:true,Session:contribution?.Session??CameraObservation}]:[];
});
const sources:{key:string;deviceID?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
const sceneKeys=groups.flatMap(group=>group.views.filter(view=>view.scene).map(view=>observationKey(group.device.id,view.id)));
useEffect(()=>{if(presets.ready&&spatialDefaults)for(const key of sceneKeys)if(!presets.scenes?.[key])presets.setScene(key,spatialDefaults);},[presets.ready,spatialDefaults,JSON.stringify(sceneKeys)]);
const bindings=groups.filter(group=>groups.filter(other=>other.device.kind===group.device.kind).length===1).flatMap(group=>group.views.map(view=>({from:JSON.stringify(['catalog',group.device.kind,view.id]),to:observationKey(group.device.id,view.id)})));
const bindingKey=JSON.stringify(bindings);
useEffect(()=>{if(!presets.ready)return;setLayout(value=>bindObservationLayout(value,bindings));setFull(value=>bindings.find(item=>item.from===value)?.to??value);},[bindingKey,presets.ready,layout]);
const sources:{key:string;deviceID?:string;kind?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,kind:group.device.kind,view})));
sources.push(...unboundObservationViews(inventory?.items??[],registry.sensorContributions));
sources.push({key:'map',view:{id:'map',label:'Карта'}},{key:'rover',view:{id:'rover',label:'3D View аппарата'}},{key:'telemetry',view:{id:'telemetry',label:'Телеметрия'}});
if(diagnostics.state.id)sources.push({key:'rover-logs',view:{id:'rover-logs',label:'Логи управления'}});
@@ -60,7 +77,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
// own this subscription; the rover transport enforces its own freshness.
const rover=useRoverControl(vehicleID,paired&&(visible.includes('rover')||visible.includes('telemetry')));
const roverObservation=roverObservationStatus(rover.state,rover.connection);
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice&&!devOpen;
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice&&!connectingKind&&!devOpen;
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
@@ -73,7 +90,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
<div className="observation-deck">{!inventory||!presets.ready?<LoadingRegion loading={!presets.error} label="Получение визуальных источников"/>:visible.length?<ObservationDeck minimumSizes={{telemetry:roverTelemetryMinimum(rover.state)}} ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
<div className="observation-panel">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className={`observation-panel__surface observation-panel__surface--${source.view.header==='flow'?'flow':'overlay'}`}>
<ObservationPanelHeader>
<DockHandle id={source.key} label={source.view.label}/>
<div className="observation-panel__title">{source.key!=='rover'&&<h3 title={source.view.label}>{source.view.label}</h3>}<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
@@ -81,7 +98,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.actionsTarget}/>
{source.deviceID&&cameras.some(group=>group.device.id===source.deviceID)&&<IconButton label={`${primaryRef.current===source.deviceID?'Основной видеопоток':'Сделать основным видеопотоком'} · ${source.view.label}`} aria-pressed={primaryRef.current===source.deviceID} onClick={()=>setPrimaryCamera(source.deviceID!)}><Icon name="eye"/></IconButton>}
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>setSettingsDevice(source.deviceID!)}><Icon name="settings"/></IconButton>}
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>{setSettingsView(source.view.id==='plan'?'plan':'points');setSettingsDevice(source.deviceID!);}}><Icon name="settings"/></IconButton>}
<IconButton label={`${effectiveFull===source.key?'Восстановить':'Развернуть'} · ${source.view.label}`} onClick={()=>setFull(value=>value===source.key?null:source.key)}><Icon name={effectiveFull===source.key?'minimize':'expand'}/></IconButton>
<IconButton label={`Скрыть · ${source.view.label}`} onClick={()=>setVisible(source.key,false)}><Icon name="close"/></IconButton>
</div>
@@ -90,11 +107,12 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
</GlassSurface>
</div>,mounts.current.get(source.key)!,source.key))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
{groups.map(({device,views,Session,independentMediaLiveness})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={(independentMediaLiveness?paired:enabled&&inventory?.fresh!==false)&&device.online} fresh={enabled&&inventory?.fresh!==false} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить оборудование</Button></div></div>,media.current.get(source.key)!,source.key))}
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
{presets.ready&&groups.map(({device,views,Session,independentMediaLiveness})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} configure={view=>{setSettingsView(view==='plan'?'plan':'points');setSettingsDevice(device.id);}} sceneProfiles={Object.fromEntries(views.map(view=>[view.id,presets.scenes?.[observationKey(device.id,view.id)]]).filter(([,value])=>value))} onSceneChange={presets.ready?(view,value)=>presets.setScene(observationKey(device.id,view),value):undefined} reconnect={reconnect(device.kind)} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={(independentMediaLiveness?paired:enabled&&inventory?.fresh!==false)&&device.online} fresh={enabled&&inventory?.fresh!==false} createRerunHost={createIsolatedRerunHost} views={views.filter(view=>visible.includes(observationKey(device.id,view.id))).map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={reconnect(source.kind)??configure}>Подключить оборудование</Button></div></div>,media.current.get(source.key)!,source.key))}
{connectingKind&&<ObservationConnectionWindow key={`${vehicleID}:${connectingKind}`} kind={connectingKind} transport={transport} contributions={registry.sensorContributions} enabled={enabled} refresh={refresh} close={()=>setConnectingKind(null)} configure={setSettingsDevice}/>}
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id+settingsView} sceneProfile={{view:settingsView,settings:presets.scenes?.[observationKey(configuredDevice.id,settingsView)],save:value=>presets.setScene(observationKey(configuredDevice.id,settingsView),value)}} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false} close={()=>setSettingsDevice(null)} configure={configure} refresh={async()=>{await refresh();}} reconnect={reconnect(configuredDevice.kind)}/>}
{visible.includes('map')&&createPortal(<ObservationMap vehicleID={vehicleID} header={headers.current.get('map')!}/>,media.current.get('map')!,'map-session')}
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible} observation={roverObservation}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} name={name} controller={rover} header={headers.current.get('rover')!} active={drivingVisible} observation={roverObservation}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('rover-logs')&&createPortal(<RoverLogs capture={diagnostics} header={headers.current.get('rover-logs')!}/>,media.current.get('rover-logs')!,'rover-logs-session')}
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state} observation={roverObservation}/>,media.current.get('telemetry')!,'telemetry-session')}
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
@@ -0,0 +1,25 @@
import {useEffect,useRef} from 'react';
import {WirelessEnrollmentWindow} from '../../../../../../packages/sensor-ui/src/WirelessEnrollmentWindow';
import {enrolledDevice,type SensorInventory,type SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
import type {SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
/** One enrollment owner for every view of the selected device kind. */
export function ObservationConnectionWindow({kind,transport,contributions,enabled,refresh,close,configure}:{
kind:string;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;
refresh:()=>Promise<SensorInventory|null>;close:()=>void;configure:(deviceID:string)=>void;
}){
const current=useRef({active:true,enabled});
current.current.enabled=enabled;
useEffect(()=>{current.current.active=true;return()=>{current.current.active=false;};},[]);
async function complete(sessionID:string,signal?:AbortSignal){
if(!current.current.enabled)throw new Error('БК недоступен. Обновите состояние устройства.');
const inventory=await refresh();
if(signal?.aborted||!current.current.active)return;
const device=inventory&&enrolledDevice(inventory,sessionID);
if(!current.current.enabled||!device||device.kind!==kind)throw new Error('Связь с устройством пока не подтверждена. Проверьте его состояние.');
close();configure(device.id);
}
if(!transport.enrollment)return null;
return <WirelessEnrollmentWindow initialKind={kind} contributions={contributions.filter(item=>item.kind===kind)} transport={transport.enrollment}
enabled={enabled} onClose={close} onChange={()=>{void refresh();}} onComplete={complete}/>;
}
@@ -1,17 +1,18 @@
import {useState} from 'react';
import {Button,ToastStack,Window} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../../../packages/sensor-ui/src/extensions';
import {SensorDetail} from '../../../../../../packages/sensor-ui/src/SensorDetail';
import {sensorContribution,type SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
import type {Sensor,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure}:{device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void}) {
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure,refresh,reconnect,sceneProfile}:{sceneProfile?:SensorDetailProps['sceneProfile'];device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void;refresh:()=>Promise<void>;reconnect?:()=>void}) {
const [error,setError]=useState('');
const contribution=sensorContribution(contributions,device);
const Detail=contribution?.Detail??SensorDetail;
const content=<Detail key={device.snapshot.context.session_id} device={device} transport={transport} enabled={enabled} back={close} refresh={async()=>{await transport.inventory();}} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>;
const content=<Detail key={device.snapshot.context.session_id} device={device} transport={transport} enabled={enabled} previewEnabled={false} sceneProfile={sceneProfile} back={close} backLabel="Вернуться к наблюдению" refresh={refresh} reconnect={reconnect} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>;
if(contribution?.detailPresentation==='modal')return <>{content}<ToastStack items={error?[{id:'device-settings-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="end" draggable closeOnBackdrop={false} lockBodyScroll={false} trapFocus={false} onClose={close}>
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="center" closeOnBackdrop={false} onClose={close}>
{!enabled&&<p>Нет связи с устройством. Настройки оборудования будут доступны после подключения.</p>}
{!device.prepared&&<Button onClick={configure}>Открыть оборудование аппарата</Button>}
{error&&<p role="alert">{error}</p>}
@@ -1,17 +1,23 @@
import {useEffect,useState} from 'react';
import {useCallback,useEffect,useRef,useState} from 'react';
import type {SensorInventory,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
export function useObservationInventory(transport:SensorTransport){
const [inventory,setInventory]=useState<SensorInventory|null>(null);
const reader=useRef<(()=>Promise<SensorInventory|null>)|null>(null);
const refresh=useCallback(async()=>await reader.current?.()??null,[]);
useEffect(()=>{
let active=true,running=false,revision=0,last=0;
const receive=(value:SensorInventory)=>{if(active){revision++;last=Date.now();setInventory(value);}};
let active=true,running=false,revision=0,last=0,latest:SensorInventory|null=null;
const lifetime=new AbortController();
setInventory(null);
const receive=(value:SensorInventory)=>{if(active){revision++;last=Date.now();latest=value;setInventory(value);}};
// A lost SSE connection is not evidence that a working camera stopped.
// Retain the last inventory for one bounded heartbeat window and verify via HTTP.
const unavailable=()=>{if(active&&Date.now()-last>15000)setInventory(value=>value?{...value,fresh:false}:value);};
const poll=async()=>{if(running||Date.now()-last<4000)return;running=true;const before=revision;try{const value=await transport.inventory();if(before===revision)receive(value);}catch{if(before===revision)unavailable();}finally{running=false;}};
const read=async()=>{const before=revision;try{const value=await transport.inventory(lifetime.signal);if(!active)return null;if(before===revision)receive(value);return latest;}catch{if(before===revision)unavailable();return null;}};
reader.current=read;
const poll=async()=>{if(running||Date.now()-last<4000)return;running=true;try{await read();}finally{running=false;}};
void poll();const unsubscribe=transport.subscribe?.(receive,()=>{unavailable();void poll();});const timer=setInterval(()=>{unavailable();void poll();},5000);
return()=>{active=false;clearInterval(timer);unsubscribe?.();};
return()=>{active=false;lifetime.abort();if(reader.current===read)reader.current=null;clearInterval(timer);unsubscribe?.();};
},[transport]);
return inventory;
return {inventory,refresh};
}
@@ -0,0 +1,100 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const load=async path=>{const result=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));};
const {defaultBatteryScene}=await load('../src/core/batteryScene/profile.ts');
const {defaultScene,parseScene,changeField,assignMaterial,createMaterial}=await load('../src/core/roverScene/sceneDocument.ts');
test('battery JSON is isolated from rover JSON and preserves all editor settings',()=>{
const rover=defaultScene();let battery=defaultBatteryScene();
assert.deepEqual(battery.postFx,rover.postFx);
battery=changeField(battery,'postFx.lighting.exposure',1.7);
battery=createMaterial(battery,'custom/synthetic');
battery=assignMaterial(battery,'bms/labels','custom/synthetic');
battery.materials['bms/glass'].opacity=.25;
battery.objects[Object.keys(battery.objects)[0]]=false;
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(battery)),defaultBatteryScene),battery);
assert.throws(()=>parseScene(battery));assert.throws(()=>parseScene(rover,defaultBatteryScene));
assert.notEqual(defaultBatteryScene().materials['bms/glass'].opacity,.25);
assert.equal(rover.postFx.lighting.exposure,defaultScene().postFx.lighting.exposure);
});
const {batteryState}=await load('../../../plugins/jk-bms/frontend/src/model.ts');
test('stale and absent samples cannot turn into current or zero battery readings',()=>{
const now=Date.parse('2026-11-03T10:00:00Z'),device={online:true,bms_status:{state:'streaming',fresh:true,compatible:true,sample_at:new Date(now).toISOString(),sample:{soc_percent:80}}};
assert.equal(batteryState(device,true,now).fresh,true);
assert.equal(batteryState(device,false,now).fresh,false);
assert.equal(batteryState(device,true,now+13000).fresh,false);
assert.equal(batteryState(device,true,now+300001).sample.soc_percent,80);
assert.equal(batteryState(device,true,Date.parse('2026-11-04T00:00:00Z')).sample,null);
assert.equal(batteryState({online:false},true,now).sample,null);
});
const {batteryViewHeight,batteryViewHeightKey}=await load('../src/core/batteryScene/viewHeight.ts');
test('view height round trips independently per battery and rejects corrupt geometry',()=>{
const store=new Map();store.set(batteryViewHeightKey('device/a'),JSON.stringify({height:721}));
assert.equal(batteryViewHeight(store.get(batteryViewHeightKey('device/a')),1024),721);
assert.equal(batteryViewHeight(store.get(batteryViewHeightKey('device/b'))??null,1024),724);
for(const raw of ['broken','null','{"height":"800"}','{"height":null}'])assert.equal(batteryViewHeight(raw,900),600);
assert.equal(batteryViewHeight('{"height":-100}',900),360);
assert.equal(batteryViewHeight('{"height":100000}',900),2160);
});
const {updateChargeMaterial}=await load('../src/components/rover/playcanvas/chargeMaterial.ts');
test('temporary disconnect holds the exact last colour and emission; expired telemetry is unknown',()=>{
const gradient=defaultBatteryScene().materials['bms/cells'].chargeGradient;
const values=state=>{const result={};updateChargeMaterial({setParameter:(key,value)=>result[key]=value},gradient,state,3.5);return result;};
const live=values({soc:82,fresh:true});
assert.deepEqual(values({soc:82,fresh:false}),live);
const expired=values({soc:null,fresh:false});
assert.equal(expired.chargeSaturation,0);assert.notDeepEqual(expired.chargeColorA,live.chargeColorA);
assert.notDeepEqual(values({soc:52,fresh:true}).chargeColorA,live.chargeColorA);
});
const {viewportFov,parseCameraState}=await load('../src/core/roverScene/cameraState.ts');
test('saved camera JSON round trips and resizes preserve focal pixels without changing pose',()=>{
const camera={pivot:{x:.1,y:.2,z:-.3},distance:1.2,azimuthDeg:-135,elevationDeg:42,referenceHeight:789};
const doc={...defaultBatteryScene(),camera};
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(doc)),defaultBatteryScene).camera,camera);
const focal=h=>h/(2*Math.tan(viewportFov(h,camera.referenceHeight)*Math.PI/360));
assert.ok(Math.abs(focal(360)-focal(789))<1e-9);assert.ok(Math.abs(focal(1700)-focal(789))<1e-9);
assert.equal(parseCameraState({...camera,distance:NaN}),undefined);
assert.equal(parseCameraState({...camera,pivot:{x:Infinity,y:0,z:0}}),undefined);
assert.equal(parseCameraState({...camera,distance:-1}),undefined);
});
test('split dielectric side backers inherit existing assignment/visibility without replacing explicit child edits',()=>{
const id=name=>'object/Model/'+encodeURIComponent('bms/CASE | dielectric liner'+name);
const doc=defaultBatteryScene();
doc.objectAssignments={[id('')]:'bms/glass',[id('/right')]:'bms/cells'};
doc.objectVisibility={[id('')]:false,[id('/right')]:true};
const next=parseScene(doc,defaultBatteryScene);
assert.equal(next.objectAssignments[id('/left')],'bms/glass');assert.equal(next.objectAssignments[id('/right')],'bms/cells');
assert.equal(next.objectVisibility[id('/left')],false);assert.equal(next.objectVisibility[id('/right')],true);
assert.equal(Object.keys(next.objects).length,63);
});
const {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance}=await load('../src/core/batteryScene/appearance.ts');
const {cellDisplayIndex,cellDisplayText}=await load('../src/core/batteryScene/cellDisplay.ts');
test('battery appearance is isolated, round trips, rejects foreign JSON and bounds imported controls',()=>{
const a=defaultBatteryAppearance(),b=defaultBatteryAppearance();a.panels.glass.tintHex='#cc3300';a.markings.size=150;
assert.deepEqual(parseBatteryAppearance(JSON.parse(JSON.stringify(a))),a);
assert.equal(b.panels.glass.tintHex,'#0b0b0e');assert.equal(b.panels.height,76);
assert.notEqual(batteryAppearanceKey('a'),batteryAppearanceKey('b'));
assert.throws(()=>parseBatteryAppearance(defaultBatteryScene()));
const bounded=parseBatteryAppearance({...a,markings:{size:500,color:'invalid'},panels:{height:-1,radius:Infinity,glass:{tintOpacity:1000,blur:-5}}});
assert.equal(bounded.markings.size,160);assert.equal(bounded.markings.color,'#ffffff');assert.equal(bounded.panels.height,56);assert.equal(bounded.panels.radius,24);assert.equal(bounded.panels.glass.tintOpacity,100);assert.equal(bounded.panels.glass.blur,0);
});
test('each label receives only its own measured voltage, with unknown never shown as zero',()=>{
for(let i=0;i<13;i++)assert.equal(cellDisplayIndex(`bms/cell-display/C${String(i+1).padStart(2,'0')}`),i);
for(const bad of ['bms/cells/C01','bms/cell-display/C00','bms/cell-display/C14'])assert.equal(cellDisplayIndex(bad),null);
assert.deepEqual(cellDisplayText(12,3.456),{number:'13',voltage:'3,456 В'});
for(const value of [undefined,NaN,Infinity])assert.equal(cellDisplayText(0,value).voltage,'— В');
});
import {readFileSync} from 'node:fs';
test('R04 exports thirteen original front faces with independent materials and planar UVs',()=>{
const glb=readFileSync(new URL('../public/battery-scene/catl-r04.glb',import.meta.url));
const gltf=JSON.parse(glb.subarray(20,20+glb.readUInt32LE(12)).toString());
const displays=gltf.meshes.filter(m=>cellDisplayIndex(m.name)!==null);assert.equal(displays.length,13);
const ids=new Set();for(const mesh of displays){const p=mesh.primitives[0],a=gltf.accessors[p.attributes.POSITION],uv=gltf.accessors[p.attributes.TEXCOORD_0];
assert.equal(gltf.materials[p.material].name,mesh.name);ids.add(p.material);assert.equal(uv.count,4);
const x=(cellDisplayIndex(mesh.name)-6)*.036;
assert.ok(Math.abs((a.min[0]+a.max[0])/2-x)<1e-6);assert.ok(Math.abs((a.min[1]+a.max[1])/2-.063)<1e-6);
assert.ok(Math.abs(a.min[2]-.08664)<1e-6);assert.equal(a.min[2],a.max[2]);
}assert.equal(ids.size,13);
});
@@ -0,0 +1,142 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,project,View,remember;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({boardNetworkStatus:project}=await server.ssrLoadModule('/src/core/fleet/boardNetworkStatus.ts'));
({rememberBoardNetworks:remember}=await server.ssrLoadModule('/src/core/fleet/boardNetworkMemory.ts'));
({BoardNetworkStatus:View}=await server.ssrLoadModule('/src/workspaces/fleet/BoardNetworkStatus.tsx'));
});
after(async()=>{await server?.close();});
const fixture=(now=Date.now())=>({connectivity:'online',inventory_fresh:true,host:{networks_readable:true,collected_at:new Date(now).toISOString(),networks:[
{name:'usb-radio',kind:'wifi',addresses:['192.0.2.4/24'],connection:{state:'connected',ssid:'Test <network>',signal_percent:0,collected_at:new Date(now).toISOString()}},
{name:'cable',kind:'ethernet',addresses:[],connection:{state:'unavailable',collected_at:new Date(now).toISOString()}},
{name:'tunnel',kind:'virtual',addresses:['10.0.0.1/32'],connection:{state:'connected',collected_at:new Date(now).toISOString()}},
]}});
test('physical connections retain SSID, zero signal and cable state without VPN interfaces',()=>{
const p=project(fixture(100000),true);
assert.equal(p.links.length,2);assert.equal(p.links[0].ssid,'Test <network>');
assert.equal(p.links[0].signal,0);assert.equal(p.links[0].state,'connected');
assert.equal(p.links[1].status,'Недоступен');assert.deepEqual(p.links[1].addresses,[]);
});
test('inventory age and transport availability never rewrite a received adapter state',()=>{
const v=fixture(100000),memory=remember(null,v),first=project(v,true,memory);
for(const [input,available] of [[v,false],[{...v,inventory_fresh:false},true],[{...v,connectivity:'offline'},true],[fixture(0),true]]){
const status=project(input,available,memory);assert.deepEqual(status.links,first.links);
}
assert.equal(project({...v,inventory_fresh:false},true,memory).live,true);
assert.equal(project(v,false,memory).live,false);
assert.equal(project({...v,connectivity:'offline'},true,memory).live,false);
});
test('missing metadata does not infer Wi-Fi or connection from interface name or IP',()=>{
const v=fixture();v.host.networks=[{name:'wlan0',up:true,addresses:['192.0.2.1']}];
assert.deepEqual(project(v,true).links,[]);
v.host.networks[0].kind='wifi';assert.equal(project(v,true).links[0].status,'Нет сведений');
v.host.networks_readable=false;assert.equal(project(v,true).readable,false);
});
test('invalid signal and failed address reads remain unknown',()=>{
const v=fixture();v.host.networks[0].connection.signal_percent=101;v.host.networks[0].addresses_readable=false;
assert.equal(project(v,true).links[0].signal,null);assert.equal(project(v,true).links[0].addresses,null);
});
test('network section displays escaped real facts and exposes no mutation controls',()=>{
const html=renderToStaticMarkup(createElement(View,{status:project(fixture(),true)}));
assert.match(html,/Test &lt;network&gt;/);assert.match(html,/0%/);assert.match(html,/192\.0\.2\.4/);assert.match(html,/Ethernet/);
assert.doesNotMatch(html,/<button|<input|<select|tunnel|Сохранить/);
const stale=renderToStaticMarkup(createElement(View,{status:project(fixture(0),true)}));
assert.doesNotMatch(stale,/Данные устарели/);assert.match(stale,/по последним полученным данным/);
});
test('hardware labels use reported bus and model, never interface-name guesses',()=>{
const v=fixture();v.host.networks[0].hardware={bus:'usb',vendor:'Example vendor',model:'Radio <X>'};
v.host.networks[1].hardware={bus:'pci',model:'Ethernet model'};
const links=project(v,true).links;
assert.equal(links[0].title,'Wi-Fi · USB');assert.equal(links[0].model,'Radio <X>');
assert.equal(links[1].title,'Ethernet · PCI');
const html=renderToStaticMarkup(createElement(View,{status:project(v,true)}));
assert.match(html,/Radio &lt;X&gt;/);assert.match(html,/Example vendor/);assert.match(html,/Интерфейс/);
delete v.host.networks[0].hardware;v.host.networks[0].name='wlx-looks-like-usb';
assert.equal(project(v,true).links[0].title,'Wi-Fi');assert.equal(project(v,true).links[0].model,'');
});
test('multiple adapters keep their numbering across inventory order and connection changes',()=>{
const v=fixture();const a=v.host.networks[0];a.hardware={bus:'usb'};a.name='radio-b';
const b={...a,name:'radio-a',connection:{...a.connection,state:'disconnected'}};
v.host.networks.push(b);
const names=()=>Object.fromEntries(project(v,true).links.map(x=>[x.name,x.title]));
const expected={'radio-a':'Wi-Fi · USB · Адаптер 1','radio-b':'Wi-Fi · USB · Адаптер 2',cable:'Ethernet'};
assert.deepEqual(names(),expected);
v.host.networks.reverse();a.connection.state='disconnected';b.connection.state='connected';assert.deepEqual(names(),expected);
v.host.networks=v.host.networks.filter(n=>n.name!=='radio-a');
assert.equal(project(v,true).links.find(n=>n.name==='radio-b').title,'Wi-Fi · USB');
});
test('explicit negative response changes status and keeps last association facts and card structure',()=>{
const now=100000,v=fixture(now);let memory=remember(null,v);
const first=project(v,true,memory),names=first.links.map(x=>x.name);
const fields=status=>renderToStaticMarkup(createElement(View,{status})).match(/<dt>[^<]*<\/dt>/g);
const disconnected=structuredClone(v);disconnected.host.collected_at=new Date(now+1000).toISOString();
Object.assign(disconnected.host.networks[0],{addresses:[],connection:{state:'disconnected',collected_at:disconnected.host.collected_at}});
memory=remember(memory,disconnected);const negative=project(disconnected,true,memory);
assert.equal(negative.links[0].status,'Не подключён');assert.equal(negative.links[0].state,'disconnected');
for(const key of ['ssid','signal','addresses'])assert.deepEqual(negative.links[0][key],first.links[0][key]);
assert.deepEqual(fields(negative),fields(first));assert.deepEqual(negative.links.map(x=>x.name),names);
});
test('failed reads and omitted or unknown connection metadata retain the last reported state',()=>{
const v=fixture(100000),initial=remember(null,v),first=project(v,true,initial);
for(const host of [null,{...v.host,networks_readable:false,networks:[]},
{...v.host,networks:v.host.networks.map(n=>({...n,connection:undefined}))},
{...v.host,networks:v.host.networks.map(n=>({...n,kind:'unknown',connection:undefined}))},
{...v.host,networks:v.host.networks.map(n=>({...n,connection:{...n.connection,state:'unknown'}}))}]){
const missing={...v,host},memory=remember(initial,missing),status=project(missing,true,memory);
assert.deepEqual(status.links,first.links);
assert.deepEqual(project(v,true,remember(memory,v)).links,first.links);
}
});
test('a complete inventory confirms removal; reappearance without a state does not revive old connected status',()=>{
const v=fixture(100000),initial=remember(null,v),absent={...v,host:{...v.host,networks:[]}};
const removed=remember(initial,absent);assert.equal(project(absent,true,removed).links[0].status,'Не обнаружен');
const reappeared=structuredClone(v);delete reappeared.host.networks[0].connection;
const memory=remember(removed,reappeared);assert.equal(project(reappeared,true,memory).links[0].status,'Нет сведений');
assert.equal(project(v,true,remember(memory,v)).links[0].state,'connected');
});
test('new adapters append without renumbering known cards when a report omits one',()=>{
const v=fixture(100000);v.host.networks[0].hardware={bus:'usb',model:'Known radio'};v.host.networks[0].name='radio-b';
let memory=remember(null,v);const added=structuredClone(v);added.host.networks.unshift({...v.host.networks[0],name:'radio-a'});
memory=remember(memory,added);let status=project(added,true,memory);
assert.deepEqual(status.links.map(x=>x.name),['radio-b','cable','radio-a']);assert.equal(status.links[0].title,'Wi-Fi · USB · Адаптер 1');
const partial=structuredClone(v);partial.host.networks[0].hardware={bus:'usb'};partial.host.networks[0].connection=undefined;
memory=remember(memory,partial);status=project(partial,true,memory);
assert.deepEqual(status.links.map(x=>x.name),['radio-b','cable','radio-a']);assert.equal(status.links[0].title,'Wi-Fi · USB · Адаптер 1');assert.equal(status.links[0].model,'Known radio');
assert.equal(status.links[2].title,'Wi-Fi · USB · Адаптер 2');assert.equal(status.links[2].status,'Не обнаружен');
});
test('remembered facts never leak to another board and older packets cannot replace accepted state even after read failure',()=>{
const v={...fixture(100000),id:'vehicle-a',node_id:'board-a'},memory=remember(null,v);
for(const other of [{...v,id:'vehicle-b',host:null},{...v,node_id:'board-b',host:null}])assert.deepEqual(remember(memory,other).entries,[]);
const older=structuredClone(v);older.host.collected_at=new Date(99000).toISOString();older.host.networks=[];
const ignored=remember(remember(memory,{...v,host:null}),older);
assert.equal(ignored.input,older.host);assert.deepEqual(ignored.entries,memory.entries);
assert.equal(project(older,true,ignored).links[0].state,'connected');
});
test('timestamps and inventory order alone do not change adapter card props',()=>{
let v=fixture(100000),memory=remember(null,v);const first=project(v,true,memory);
for(const time of [121000,150000,86400000]){
const next=fixture(time);next.host.networks.reverse();
memory=remember(memory,next);const status=project(next,true,memory);
assert.deepEqual(status.links,first.links);
assert.equal(status.links[0].addresses,first.links[0].addresses);
assert.equal(status.collectedAt,next.host.collected_at);
}
});
test('actual network, signal and address changes update facts; an older embedded observation cannot undo them',()=>{
const v=fixture(100000);let memory=remember(null,v);const next=fixture(110000);
Object.assign(next.host.networks[0].connection,{ssid:'Another network',signal_percent:65});next.host.networks[0].addresses=['198.51.100.2/24'];
memory=remember(memory,next);const row=project(next,true,memory).links[0];
assert.equal(row.ssid,'Another network');assert.equal(row.signal,65);assert.deepEqual(row.addresses,['198.51.100.2/24']);
const late=fixture(120000);late.host.networks[0].connection={state:'disconnected',collected_at:new Date(100000).toISOString()};
assert.deepEqual(project(late,true,remember(memory,late)).links[0],row);
});
test('absent-row memory is bounded without limiting the current physical interface list',()=>{
const v=fixture(100000);v.host.networks=Array.from({length:70},(_,i)=>({...v.host.networks[0],name:`radio-${i}`}));
const current=remember(null,v);assert.equal(current.entries.length,70);
const absent=remember(current,{...v,host:{...v.host,networks:[]}});assert.equal(absent.entries.length,64);
});
@@ -1,12 +1,13 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,layout,source,fanout,catalog;
let server,layout,source,fanout,catalog,binding;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
layout=await server.ssrLoadModule('/src/core/fleet/observationLayout.ts');
source=await server.ssrLoadModule('../../packages/sensor-ui/src/observation.ts');
catalog=await server.ssrLoadModule('../../packages/sensor-ui/src/observationCatalog.ts');
binding=await server.ssrLoadModule('/src/core/fleet/observationBinding.ts');
({observationRerun:fanout}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/observationRerun.ts'));
});
after(async()=>{await server?.close();});
@@ -29,21 +30,38 @@ test('camera observation exposes only advertised layers with one viewport and RG
assert.equal(views.length,1);assert.deepEqual(views[0].layers.map(v=>v.value),['color','depth','points']);
assert.deepEqual(source.cameraObservationViews({name:'unknown',layers:[]}),[]);
});
test('two Rerun views share bytes, apply independent blueprints once and dispose both hosts',async()=>{
const fetchBefore=globalThis.fetch;globalThis.fetch=async url=>new Response(Uint8Array.of(String(url).includes('plan')?2:1));
const sent=[[],[]],closed=[],started=[];let count=0;
const factory=mount=>{const index=count++;return {ready:Promise.resolve({mount,viewer:{start:async()=>started.push(index),open_channel:name=>({ready:true,send_rrd:bytes=>sent[index].push([name,[...bytes]]),close:()=>{}}),get_active_recording_id:()=> 'recording-1',override_panel_state:()=>{},set_active_timeline:()=>{}}}),dispose:()=>closed.push(index)};};
try{
const host=fanout(factory,{current:{id:'top'}})({id:'3d'});const {viewer,mount}=await host.ready;
await viewer.start(null,mount,{});const channel=viewer.open_channel('rrd');channel.send_rrd(Uint8Array.of(9,8));
assert.deepEqual(sent[0],[['rrd',[9,8]]]);assert.deepEqual(sent[1],[['rrd',[9,8]]]);
viewer.get_active_recording_id();viewer.get_active_recording_id();
assert.deepEqual(sent[0].at(-1),['observation-perspective',[1]]);assert.deepEqual(sent[1].at(-1),['observation-plan',[2]]);
assert.equal(sent[0].length,2);assert.deepEqual(started,[0,1]);host.dispose();assert.deepEqual(closed,[0,1]);
}finally{globalThis.fetch=fetchBefore;}
test('each native pane uses canonical settings, preserves its eye and releases its blueprint owner',async()=>{
const sent=[],calls=[],slices=[];let disposed=0,started=false;
const eye={position:[1,2,3],lookTarget:[0,0,0],eyeUp:[0,0,1]};
const settings={pointSize:2.5,accumulationSeconds:45,colorMode:'distance',palette:'viridis',customColor:'#f7f8f4',showPoints:true,showTrajectory:true,showGrid:false};
const state={view:'plan',settings,device:{id:'k1',snapshot:{context:{session_id:'session'}}},transport:{submit:async command=>{calls.push(command);return {state:'complete',result:{rrd:btoa(String.fromCharCode(1,2,3))}};}}};
const factory=mount=>({ready:Promise.resolve({mount,viewer:{get ready(){return started;},start:async()=>{started=true;},open_channel:()=>({ready:true,send_rrd:bytes=>sent.push([...bytes]),close:()=>{}}),set_height_slice:(lo,hi)=>{slices.push([lo,hi]);return true;},get_camera_eye:()=>eye,get_active_recording_id:()=> 'recording-1'}}),dispose:()=>disposed++});
const host=fanout(factory,()=>state)({id:'plan',dataset:{}}),{viewer,mount}=await host.ready;
assert.equal(viewer.ready,false);
await viewer.start(null,mount,{});
assert.equal(viewer.ready,true,'native readiness remains a live getter after wrapping');
assert.equal(viewer.get_active_recording_id(),null,'hide native defaults until the canonical profile is applied');
await new Promise(resolve=>setImmediate(resolve));
assert.deepEqual(sent,[[1,2,3]]);assert.equal(calls[0].action_id,'details');
assert.equal(calls[0].parameters.preview_blueprint.view,'plan');
assert.equal(calls[0].parameters.preview_blueprint.settings.accumulation_seconds,45);
viewer.get_active_recording_id();assert.equal(calls.length,1);
state.settings={...settings,pointSize:5};viewer.get_active_recording_id();
await new Promise(resolve=>setImmediate(resolve));
assert.deepEqual(calls[1].parameters.preview_blueprint.eye,eye);
assert.equal(calls[1].parameters.preview_blueprint.owner,calls[0].parameters.preview_blueprint.owner);
state.settings={...state.settings,heightFloor:-1,heightCeiling:3};viewer.get_active_recording_id();
await new Promise(resolve=>setImmediate(resolve));
assert.equal(calls.length,2,'height slice must remain local and never wait on the board');
assert.deepEqual(slices.at(-1),[-1,3]);
state.settings={...state.settings,followTrajectory:true};viewer.get_active_recording_id();
await new Promise(resolve=>setImmediate(resolve));
assert.equal(calls[2].parameters.preview_blueprint.follow_trajectory,true);
assert.deepEqual(calls[2].parameters.preview_blueprint.eye,eye);
host.dispose();await new Promise(resolve=>setImmediate(resolve));
assert.equal(disposed,1);assert.equal(calls.at(-1).parameters.preview_blueprint.release,true);
});
test('known offline D455 remains selectable; connected capabilities override the catalog',()=>{
const offline={name:'RealSense D455',model:'RealSense D455',online:false,layers:[]};
assert.deepEqual(source.cameraObservationViews(offline)[0].layers.map(v=>v.value),['color','depth','infrared1','infrared2','points','motion']);
@@ -54,9 +72,38 @@ test('unbound catalog views have no device authority; connected instances replac
const plugin={kind:'k1',observation:{catalog:{label:'K1',views:[{id:'points',label:'Points'},{id:'camera',label:'Camera'}]}}};
const entries=catalog.unboundObservationViews([],[plugin]);
assert.equal(entries.length,2);assert.notEqual(entries[0].key,entries[1].key);
assert.equal(entries[0].kind,'k1');
assert.equal(entries[0].deviceID,undefined);assert.equal(entries[0].device,undefined);
assert.deepEqual(catalog.unboundObservationViews([{id:'one',kind:'k1'}],[plugin]),[]);
assert.deepEqual(catalog.unboundObservationViews([],[plugin,plugin]),[]);
const persisted=layout.decodeObservationLayout({...layout.emptyObservationLayout(),catalogVisible:[entries[0].key,entries[0].key,null]});
assert.deepEqual(persisted.catalogVisible,[entries[0].key]);
});
test('enrollment replaces catalog slots in place and retains hidden windows and split geometry',()=>{
const from=['points','plan','camera'].map(id=>JSON.stringify(['catalog','k1',id]));
const to=['points','plan','camera'].map(id=>source.observationKey('k1-exact',id));
const pairs=from.map((id,i)=>({from:id,to:to[i]}));
const original={...layout.emptyObservationLayout(),order:['rover',...from],hidden:[from[2]],catalogVisible:from,
layers:{[from[0]]:'points'},splits:{[JSON.stringify(from)]:38},tree:{axis:'x',ratio:31,first:{id:from[0]},second:{axis:'y',ratio:66,first:{id:from[1]},second:{id:'rover'}}}};
const value=binding.bindObservationLayout(original,pairs);
assert.deepEqual(value.order,['rover',...to]);assert.deepEqual(value.hidden,[to[2]]);assert.deepEqual(value.catalogVisible,[]);
assert.equal(value.tree.ratio,31);assert.equal(value.tree.first.id,to[0]);assert.equal(value.tree.second.first.id,to[1]);assert.equal(value.tree.second.ratio,66);
assert.deepEqual(value.layers,{[to[0]]:'points'});assert.equal(value.splits[JSON.stringify(to)],38);
assert.equal(binding.bindObservationLayout(value,pairs),value);
const saved={...original,order:[...original.order,to[0]]};
assert.equal(binding.bindObservationLayout(saved,pairs).tree.first.id,from[0],'never overwrite an existing physical-device layout');
});
test('whole-view docking survives observation persistence with camera identities and hidden sources',()=>{
const ids=['map','rover',source.observationKey('x4-1','left'),source.observationKey('x4-1','right'),'telemetry'];
const camera=ids[2],original={...layout.emptyObservationLayout(),hidden:['offline'],order:[...ids,'offline'],layers:{[camera]:'color'}};
for(const position of ['left','right','top','bottom']){
const changed=layout.dockObservation(original,ids,{activeId:camera,overId:camera,position,scope:'workspace'});
const restored=layout.decodeObservationLayout(JSON.parse(JSON.stringify(changed)));
assert.deepEqual(restored.tree,changed.tree);assert.deepEqual(restored.hidden,['offline']);
assert.deepEqual(restored.layers,{[camera]:'color'});
assert.deepEqual(position==='left'||position==='top'?restored.tree.first:restored.tree.second,{id:camera});
assert.deepEqual([...restored.order].sort(),[...ids,'offline'].sort());
}
});
@@ -144,3 +144,15 @@ test('camera snapshot restores exact pose, orthographic scale and orbit anchor a
assert.deepEqual(next.c.snapshot(),old);next.c.dispose();
}
});
test('navigation blockers are independent and only their owners can release them',()=>{
const f=fixture();f.c.setProjection('orthographic');
const wheel=()=>f.event('wheel',{deltaX:0,deltaY:-120,deltaMode:0});
const span=()=>f.c.camera.top;
try{
const initial=span();f.c.setNavigation(false);f.c.setNavigation(false,'semantic');
f.c.setNavigation(true);wheel();assert.equal(span(),initial,'planner release must not clear semantic lock');
f.c.setNavigation(false);f.c.setNavigation(true,'semantic');wheel();assert.equal(span(),initial,'semantic release must not clear planner lock');
f.c.setNavigation(true);wheel();assert.ok(span()<initial,'input resumes immediately without blur');
}finally{f.c.dispose();}
});
@@ -4,10 +4,11 @@ import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,Detail,presentation,enrolledDevice;
let server,Detail,presentation,enrolledDevice,ObservationAction;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({K1Detail:Detail}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Detail.tsx'));
({K1ObservationAction:ObservationAction}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1ObservationAction.tsx'));
presentation=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/presentation.ts');
({enrolledDevice}=await server.ssrLoadModule('../../packages/sensor-ui/src/contracts.ts'));
});
@@ -88,3 +89,47 @@ test('completed scan with healthy control remains connected and permits a named
assert.doesNotMatch(markup,/Проверить состояние K1|Подключить устройство|Устройство остановлено/);
assert.equal(presentation.k1Status(stopped,false).tone,'neutral');
});
test('observation Play only opens configuration; active acquisition offers its existing controls',()=>{
let opened=0;
const action=ObservationAction({device,fresh:true,configure:()=>opened++});
assert.equal(action.props.label,'Начать сканирование K1');assert.equal(action.props.children.props.name,'play');
action.props.onClick();assert.equal(opened,1);
assert.equal(ObservationAction({device,fresh:false,configure:()=>opened++}),null);
const active={...device,snapshot:{...device.snapshot,acquisition:'streaming'}};
let stopped=0;const stop=ObservationAction({device:{...active,control:{...active.control,can_stop:true}},fresh:true,stop:()=>stopped++});
assert.equal(stop.props.label,'Остановить сканирование K1');stop.props.onClick();assert.equal(stopped,1);assert.equal(opened,1);
});
test('observation configuration preserves START fields and STOP without a duplicate media viewer',()=>{
for(const acquisition of ['idle','starting','streaming','stopping']){
const value={...device,snapshot:{...device.snapshot,acquisition}};
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,backLabel:'Вернуться к наблюдению',transport:{},back:()=>{},refresh:async()=>{},failure:()=>{},createRerunHost:()=>assert.fail('must not allocate another viewer')}));
assert.match(markup,/Вернуться к наблюдению/);assert.doesNotMatch(markup,/rerun-viewport__canvas|Открыть пространственную сцену/);
if(acquisition==='idle')assert.match(markup,/Название проекта/);
if(acquisition==='streaming')assert.match(markup,/Остановить устройство/);
}
});
test('observation gear contains only acquisition controls, including before START',()=>{
for(const acquisition of ['idle','streaming']){
const value={...device,snapshot:{...device.snapshot,acquisition}};
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,sceneProfile:{view:'plan',save:()=>{}},transport:{},back:()=>{},refresh:async()=>{},failure:()=>{}}));
assert.doesNotMatch(markup,/Размер точки|Атрибут цвета|Палитра|rerun-viewport__canvas/);
if(acquisition==='idle')assert.match(markup,/Название проекта/);
else assert.match(markup,/Остановить устройство/);
}
});
test('K1 storage shows used percentage and expires independently of a fresh inventory',()=>{
const now=Date.now(),observed_at=new Date(now-1000).toISOString();
const almostFull={...device,storage_status:{used_percent:98.99,observed_at}};
assert.equal(presentation.k1StorageStatus(almostFull,true,now+18000).tone,'warning');
const status=presentation.k1StorageStatus(almostFull,true,now);
assert.equal(status.tone,'warning');assert.match(status.label,/занято 99 %.*мало свободного места/);
assert.match(render(almostFull),/Хранилище K1: занято 99 %/);
for(const [value,fresh,at] of [[almostFull,false,now],[{...almostFull,online:false},true,now],[almostFull,true,now+20000],[{...device,storage_status:null},true,now]]){
const unavailable=presentation.k1StorageStatus(value,fresh,at);
assert.equal(unavailable.tone,'neutral');assert.match(unavailable.label,/нет свежих данных/);assert.doesNotMatch(unavailable.label,/99/);
}
assert.equal(presentation.k1StorageStatus({...device,storage_status:{used_percent:0,observed_at}},true,now).tone,'neutral');
});
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,Observation;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',plugins:[{
name:'inline-observation-portals-for-ssr',enforce:'pre',
transform(code,id){
if(id.endsWith('/K1Observation.tsx')||id.endsWith('/ObservationHeader.tsx'))
return code.replace("import {createPortal} from 'react-dom';","import {cloneElement as portalChild} from 'react'; const createPortal=(child: any,_target: unknown,key?: string)=>child&&key?portalChild(child,{key}):child;");
},
}]});
({K1Observation:Observation}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Observation.tsx'));
});
after(async()=>{await server?.close();});
const render=(acquisition,enabled)=>renderToStaticMarkup(createElement(Observation,{
device:{id:'synthetic-k1',name:'K1',online:enabled,verified:enabled,
control:{can_stop:true,acquisition_id:'same-acquisition'},
snapshot:{acquisition,context:{session_id:'same-session'}}},
transport:{},enabled,fresh:enabled,views:[{id:'points',target:{},statusTarget:{},actionsTarget:{}}],
createRerunHost:()=>assert.fail('server rendering must not allocate a viewer'),
}));
test('an ongoing acquisition retains the spatial surface during a link gap while STOP is disabled',()=>{
const online=render('streaming',true),offline=render('streaming',false);
for(const markup of [online,offline]){
assert.match(markup,/rerun-viewport__canvas/);
assert.match(markup,/Окно накопления облака точек/);
assert.match(markup,/Позиция воспроизведения/);
assert.match(markup,/ЭФИР/);
assert.doesNotMatch(markup,/буфер не включён/);
assert.match(markup,/Следовать за K1/);
assert.doesNotMatch(markup,/data-viewer-controls/);
assert.match(markup,/data-pulse="true"/);
}
const stop=offline.match(/<button\b[^>]*aria-label="Остановить сканирование K1"[^>]*>/)?.[0];
assert.ok(stop);assert.match(stop,/disabled=""/);
assert.doesNotMatch(offline,/Инициировать запуск/);
});
test('completed or never-started acquisitions do not retain an active spatial surface',()=>{
for(const acquisition of ['idle','failed'])
assert.doesNotMatch(render(acquisition,false),/rerun-viewport__canvas/);
});

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