Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import {decodeDockTree, reconcileDockTree, moveDockPanel, dockIds, type DockTree, type DockMove} from "@nodedc/ui-core";
|
||||
export interface ObservationLayout {
|
||||
version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
|
||||
tree?:DockTree; version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
|
||||
catalogVisible?:string[]; splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
|
||||
}
|
||||
export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'});
|
||||
@@ -8,6 +9,7 @@ export function decodeObservationLayout(value:unknown):ObservationLayout {
|
||||
const source=record(value),result=emptyObservationLayout();if(source.version!==1)return result;
|
||||
const ids=(value:unknown)=>Array.isArray(value)?[...new Set(value.filter((v):v is string=>typeof v==='string'&&v.length<512))].slice(0,128):[];
|
||||
if(source.catalogVisible!==undefined)result.catalogVisible=ids(source.catalogVisible);
|
||||
const tree=decodeDockTree(source.tree);if(tree)result.tree=tree;
|
||||
result.order=ids(source.order);result.hidden=ids(source.hidden);
|
||||
result.layers=Object.fromEntries(Object.entries(record(source.layers)).filter(([k,v])=>k.length<512&&typeof v==='string'&&v.length<128).slice(0,128)) as Record<string,string>;
|
||||
result.splits=Object.fromEntries(Object.entries(record(source.splits)).filter(([k,v])=>k.length<4096&&typeof v==='number'&&Number.isFinite(v)).slice(0,256).map(([k,v])=>[k,Math.min(80,Math.max(20,v as number))]));
|
||||
@@ -20,5 +22,30 @@ export function orderedObservationIDs(layout:ObservationLayout,available:string[
|
||||
export function moveObservation(layout:ObservationLayout,available:string[],from:string,to:string):ObservationLayout {
|
||||
const order=orderedObservationIDs(layout,available);const source=order.indexOf(from),target=order.indexOf(to);
|
||||
if(source<0||target<0||source===target)return layout;
|
||||
if(layout.tree){const tree=moveDockPanel(layout.tree,{activeId:from,overId:to,position:"center"});if(tree)return withObservationTree(layout,tree);}
|
||||
order.splice(source,1);order.splice(target,0,from);return {...layout,order};
|
||||
}
|
||||
|
||||
/** Retain legacy defaults until the first edit; afterwards tree geometry owns placement. */
|
||||
export function observationTree(layout:ObservationLayout,ids:string[]):DockTree|null {
|
||||
if(layout.tree)return reconcileDockTree(layout.tree,ids);
|
||||
const build=(keys:string[],depth=0):DockTree|null=>{
|
||||
if(!keys.length)return null;
|
||||
if(keys.length===1)return {id:keys[0]};
|
||||
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&keys.some(id=>!['map','rover','telemetry'].includes(id));
|
||||
const cameraCount=keys.filter(id=>!['map','rover','telemetry'].includes(id)).length;
|
||||
const mid=defaultColumns&&cameraCount<keys.length?cameraCount:layout.arrangement==='auto'&&keys[0]==='map'&&keys.includes('rover')?1:Math.ceil(keys.length/2);
|
||||
const axis=layout.arrangement==='rows'?'y':layout.arrangement==='columns'?'x':depth%2?'y':'x';
|
||||
return {axis,ratio:layout.splits[JSON.stringify(keys)]??50,first:build(keys.slice(0,mid),depth+1)!,second:build(keys.slice(mid),depth+1)!};
|
||||
};
|
||||
return build(ids);
|
||||
}
|
||||
export function dockObservation(layout:ObservationLayout,ids:string[],move:DockMove):ObservationLayout {
|
||||
const tree=moveDockPanel(observationTree(layout,ids),move);
|
||||
return tree?withObservationTree(layout,tree):layout;
|
||||
}
|
||||
|
||||
export function withObservationTree(layout:ObservationLayout,tree:DockTree):ObservationLayout {
|
||||
const visible=dockIds(tree);
|
||||
return {...layout,tree,order:[...visible,...layout.order.filter(id=>!visible.includes(id))]};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import {dockIds, type DockTree} from '@nodedc/ui-core';
|
||||
import {decodeObservationLayout, type ObservationLayout} from './observationLayout';
|
||||
|
||||
export const observationArrangements = [
|
||||
{value:'auto',label:'Автоматически'}, {value:'columns',label:'В ряд'},
|
||||
{value:'rows',label:'Друг под другом'},
|
||||
] as const;
|
||||
export interface ObservationPreset {id:string;name:string;layout:ObservationLayout}
|
||||
export interface ObservationPresets {version:1;selected:string;layout:ObservationLayout;presets:ObservationPreset[]}
|
||||
const clone = (layout:unknown):ObservationLayout => JSON.parse(JSON.stringify(decodeObservationLayout(layout)));
|
||||
export function decodeObservationPresets(value:unknown, legacy?:unknown):ObservationPresets {
|
||||
const source = value && typeof value === 'object' ? value as Partial<ObservationPresets> : {};
|
||||
const presets:ObservationPreset[] = [];
|
||||
if(source.version === 1 && Array.isArray(source.presets)) for(const item of source.presets.slice(0,128)) {
|
||||
if(!item || typeof item.id!=='string' || !item.id.startsWith('saved:') || item.id.length>128
|
||||
|| typeof item.name!=='string' || !item.name.trim() || item.name.length>120
|
||||
|| presets.some(p=>p.id===item.id || p.name===item.name.trim())) continue;
|
||||
presets.push({id:item.id,name:item.name.trim(),layout:clone(item.layout)});
|
||||
}
|
||||
const layout=decodeObservationLayout(source.version===1 ? source.layout : legacy);
|
||||
const selected=source.selected;
|
||||
return {version:1,presets,layout,selected:typeof selected==='string' &&
|
||||
(presets.some(p=>p.id===selected) || observationArrangements.some(p=>p.value===selected))
|
||||
? selected : layout.arrangement};
|
||||
}
|
||||
export function selectObservationPreset(state:ObservationPresets,id:string):ObservationPresets {
|
||||
const preset=state.presets.find(p=>p.id===id);
|
||||
if(preset)return {...state,selected:id,layout:clone(preset.layout)};
|
||||
const arrangement=observationArrangements.find(p=>p.value===id)?.value;
|
||||
return arrangement ? {...state,selected:id,layout:{...state.layout,arrangement,tree:undefined,order:[],splits:{}}} : state;
|
||||
}
|
||||
export function saveObservationPreset(state:ObservationPresets,name:string,id:string):ObservationPresets {
|
||||
name=name.trim();
|
||||
if(!name || name.length>120)throw new Error('Укажите название раскладки.');
|
||||
if(state.presets.some(p=>p.name.toLocaleLowerCase()===name.toLocaleLowerCase()) ||
|
||||
observationArrangements.some(p=>p.label.toLocaleLowerCase()===name.toLocaleLowerCase()))
|
||||
throw new Error('Раскладка с таким названием уже существует.');
|
||||
if(state.presets.length>=128)throw new Error('Достигнут предел сохранённых раскладок.');
|
||||
if(!id.startsWith('saved:') || state.presets.some(p=>p.id===id))throw new Error('Не удалось создать раскладку.');
|
||||
return {...state,selected:id,presets:[...state.presets,{id,name,layout:clone(state.layout)}]};
|
||||
}
|
||||
export function renameObservationPreset(state:ObservationPresets,id:string,name:string):ObservationPresets {
|
||||
const preset=state.presets.find(p=>p.id===id);
|
||||
if(!preset)throw new Error('Раскладка не найдена.');
|
||||
const validated=saveObservationPreset({...state,presets:state.presets.filter(p=>p.id!==id)},name,id);
|
||||
return {...state,presets:state.presets.map(p=>p.id===id?{...p,name:validated.presets.at(-1)!.name}:p)};
|
||||
}
|
||||
export function removeObservationPreset(state:ObservationPresets,id:string):ObservationPresets {
|
||||
return {...state,presets:state.presets.filter(p=>p.id!==id),
|
||||
selected:state.selected===id?state.layout.arrangement:state.selected};
|
||||
}
|
||||
|
||||
/** Reattach dormant branches after editing the visible projection. Availability
|
||||
* never deletes a device or its split; returning devices recover their anchors. */
|
||||
export function retainDormantObservationTree(previous:DockTree|undefined,next:DockTree):DockTree {
|
||||
if(!previous)return next;
|
||||
const present=new Set(dockIds(next));
|
||||
const insert=(tree:DockTree,anchor:string,branch:DockTree,split:Exclude<DockTree,{id:string}>,first:boolean):DockTree=>{
|
||||
if('id' in tree)return tree.id===anchor ? {...split,first:first?branch:tree,second:first?tree:branch} : tree;
|
||||
return {...tree,first:insert(tree.first,anchor,branch,split,first),second:insert(tree.second,anchor,branch,split,first)};
|
||||
};
|
||||
const restore=(old:DockTree)=>{
|
||||
if('id' in old)return;
|
||||
const first=dockIds(old.first).find(id=>present.has(id));
|
||||
const second=dockIds(old.second).find(id=>present.has(id));
|
||||
if(!first && second)next=insert(next,second,old.first,old,true);
|
||||
else if(first && !second)next=insert(next,first,old.second,old,false);
|
||||
else if(first && second){restore(old.first);restore(old.second);}
|
||||
};
|
||||
restore(previous);return next;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {useEffect,useState,type SetStateAction} from 'react';
|
||||
import {type ObservationLayout} from './observationLayout';
|
||||
import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets';
|
||||
|
||||
export function useObservationPresets(storageKey:string,legacyKey:string) {
|
||||
const [state,setState]=useState(()=>{
|
||||
const read=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}};
|
||||
return decodeObservationPresets(read(storageKey),read(legacyKey));
|
||||
});
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
useEffect(()=>{
|
||||
try{localStorage.setItem(storageKey,JSON.stringify(state));}
|
||||
catch{setError('Браузер не сохранил раскладку. Проверьте доступное место и разрешение на хранение данных.');}
|
||||
},[state,storageKey]);
|
||||
const setLayout=(update:SetStateAction<ObservationLayout>)=>setState(current=>({...current,
|
||||
layout:typeof update==='function'?update(current.layout):update}));
|
||||
const commit=(update:()=>ObservationPresets)=>{
|
||||
try{
|
||||
const next=update();
|
||||
localStorage.setItem(storageKey,JSON.stringify(next));setState(next);setError(null);return true;
|
||||
}catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;}
|
||||
};
|
||||
return {...state,setLayout,save:(name:string)=>commit(()=>saveObservationPreset(state,name,`saved:${crypto.randomUUID()}`)),
|
||||
rename:(id:string,name:string)=>commit(()=>renameObservationPreset(state,id,name)),
|
||||
remove:(id:string)=>commit(()=>removeObservationPreset(state,id)),
|
||||
select:(id:string)=>setState(current=>selectObservationPreset(current,id)),
|
||||
error,clearError:()=>setError(null)};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint, type AiWorld } from "./aiPolygon";
|
||||
export interface EditorCache {
|
||||
local_scene?: { visual_url: string; collision_url: string; visual_rotation: number[]; collision_rotation: number[] };
|
||||
key: string; world: AiWorld; status: "queued" | "preparing" | "uploading" | "ready" | "failed";
|
||||
error: string | null;
|
||||
files: Record<string, { sha256: string; byte_length: number; uploaded_bytes: number }>;
|
||||
}
|
||||
export const prepareEditor = (world: AiWorld, signal?: AbortSignal) => polygonRequest<EditorCache>(
|
||||
`/worlds/${world.world_id}/editor-cache`, { method: "POST", signal });
|
||||
export const fetchEditor = (key: string, signal?: AbortSignal) => polygonRequest<EditorCache>(`/editor-cache/${key}`, { signal });
|
||||
export const editorAssetUrl = (key: string, name: string) => `/api/v1/ai-polygon/editor-cache/${key}/${name}`;
|
||||
export const saveLocalPlan = (cache: EditorCache, robot: AiRobot, points: AiWaypoint[], name: string,
|
||||
draftId: string, sequence: number) => polygonRequest<AiPlan>("/plans", { method: "POST", body: JSON.stringify({
|
||||
cache_key: cache.key, robot_id: robot.robot_id, robot_sha256: robot.sha256,
|
||||
draft_id: draftId, sequence, points, name,
|
||||
}) });
|
||||
export { toEditor, toMission } from "./aiEditorCoordinates";
|
||||
@@ -0,0 +1,3 @@
|
||||
/** Isaac uses Z up; the glTF/PlayCanvas editor uses Y up. This preserves handedness. */
|
||||
export const toEditor = ([x, y, z]: number[]): [number, number, number] => [x, z, -y];
|
||||
export const toMission = ([x, y, z]: number[]): [number, number, number] => [x, -z, y];
|
||||
@@ -1,4 +1,6 @@
|
||||
import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition";
|
||||
import type { RoverMotion } from "./roverMotion";
|
||||
import type { RoverSettings } from "./roverSettings";
|
||||
|
||||
const API = "/api/v1/ai-polygon";
|
||||
|
||||
@@ -28,14 +30,29 @@ export interface AiSource {
|
||||
description?: string;
|
||||
}
|
||||
export interface AiWorld extends AiSource {
|
||||
local_scene?: { project_id: string };
|
||||
inference_ready?: boolean; inference_message?: string;
|
||||
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
|
||||
status: "uploading" | "available"; sha256: string | null; splat_count: number | null;
|
||||
settings: AiWorldSettings;
|
||||
}
|
||||
export interface AiRobot {
|
||||
robot_id: string; name: string; revision: string; sha256: string;
|
||||
visual: { dimensions_m: [number, number, number]; source: string; sha256: string; motion?: RoverMotion };
|
||||
physics: { mass_kg: number; length_m: number; width_m: number; height_m: number };
|
||||
control?: { max_side_speed_mps: number };
|
||||
}
|
||||
export interface AiRun {
|
||||
run_id: string;
|
||||
created_at?: string;
|
||||
world: AiWorld;
|
||||
request?: { composition?: AiSelection };
|
||||
robot?: AiRobot | null;
|
||||
report?: AiRunReport | null;
|
||||
request?: { composition?: AiSelection; purpose?: "planning" | "evaluation"; rover_settings?: RoverSettings | null };
|
||||
rover_configuration?: { sha256:string; total_mass_kg:number; effective_robot_sha256:string; settings:RoverSettings } | null;
|
||||
plan?: AiPlan | null;
|
||||
plan_display_name?: string | null;
|
||||
planning_sequence?: number;
|
||||
state: "starting" | "ready" | "running" | "paused" | "stopping" | "completed" | "stopped" | "failed" | "disconnected";
|
||||
clock?: "lockstep" | "realtime";
|
||||
control?: "play" | "pause" | "stop";
|
||||
@@ -57,20 +74,57 @@ export interface AiRun {
|
||||
road_fraction: number; obstacle_count: number };
|
||||
};
|
||||
}
|
||||
export interface AiRunReport {
|
||||
run_id: string; generated_at: string;
|
||||
mission_outcome: "goal-reached" | "time-limit" | "operator-stop" | "stuck" | "unstable" | "error" | "not-evaluated";
|
||||
distance_m: number | null; simulation_seconds: number | null; goal_error_m: number | null;
|
||||
waypoint_count: number; waypoints_reached: number | null;
|
||||
inference_count: number; inference_errors: number;
|
||||
inference_ms_p50: number | null; inference_ms_p95: number | null;
|
||||
stops: { reason: string; events: number; seconds: number }[];
|
||||
collision_count: number | null;
|
||||
robot_sha256: string | null; composition_sha256: string | null;
|
||||
report_sha256: string; manifest_sha256: string; evidence_files: number; evidence_bytes: number;
|
||||
speed?: {requested_max_mps:number; measured_max_mps:number|null; maximum_excess_mps:number|null; seconds_above_requested:number|null} | null;
|
||||
}
|
||||
export type AiCamera = "follow" | "overview" | "camera";
|
||||
export interface AiStreamEndpoint {
|
||||
server: string; signaling_port: number; media_port: number; width: number; height: number; fps: number;
|
||||
}
|
||||
export interface AiTelemetry {
|
||||
distance_m?: number | null;
|
||||
sequence: number; control_sequence: number; simulation_time_ns: number;
|
||||
rtf: number; render_fps: number; sensor_fps: number; ai_hz: number;
|
||||
inference_ms: number | null; frame_age_ms: number | null; command_age_ms: number | null;
|
||||
speed_mps: number; applied_speed_mps: number; stop_reason: string;
|
||||
ai_ready: boolean; stream_ready: boolean; camera: AiCamera;
|
||||
decision: NonNullable<AiRun["last_sample"]>["decision"] | null;
|
||||
planning?: AiPlanningState | null;
|
||||
route_overlay?: AiRouteOverlay | null;
|
||||
}
|
||||
export interface AiWaypoint { id: string; position: [number, number, number] }
|
||||
export type ScreenPoint = [number, number] | null;
|
||||
export interface AiRouteOverlay {
|
||||
markers: (AiWaypoint & { index: number; base: ScreenPoint; top: ScreenPoint;
|
||||
x_axis: ScreenPoint; y_axis: ScreenPoint })[];
|
||||
trace: ScreenPoint[]; active_index: number; view_revision: number;
|
||||
}
|
||||
export interface AiPlanningState { sequence: number; view_revision: number; points: AiWaypoint[];
|
||||
error: string | null; can_undo: boolean; clip_height: number | null;
|
||||
height_min?: number | null; height_max?: number | null; camera_moving?: boolean }
|
||||
export interface AiPlan { plan_id: string; name: string; sha256: string; world_id: string;
|
||||
settings?: Pick<AiWorldSettings, "max_speed_mps">;
|
||||
display_name?: string; removed?: boolean;
|
||||
editor_cache_key?: string;
|
||||
robot_id: string; robot_sha256: string; points: AiWaypoint[]; length_m: number; created_at: string }
|
||||
export interface AiPlanningCommand {
|
||||
action: "orbit" | "pan" | "zoom" | "fly" | "home" | "add" | "move" | "delete" | "clear" | "clip" | "undo";
|
||||
point_id?: string; x?: number; y?: number; amount?: number; enabled?: boolean; axis?: "x" | "y" | "xy";
|
||||
}
|
||||
export interface AiCatalog {
|
||||
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
|
||||
robots: AiRobot[];
|
||||
plans: AiPlan[];
|
||||
runtime: { available: boolean; active_run: AiRun | null };
|
||||
}
|
||||
|
||||
@@ -87,13 +141,29 @@ export async function polygonRequest<T>(path: string, init: RequestInit = {}): P
|
||||
}
|
||||
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
|
||||
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog");
|
||||
export const aiPlanName = (plan: AiPlan) => plan.display_name ?? plan.name;
|
||||
export const updateAiPlan = (id:string, changes:{display_name?:string;removed?:boolean}) =>
|
||||
polygonRequest<AiPlan>(`/plans/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
|
||||
export const removeAiRun = (id:string, removed:boolean) =>
|
||||
polygonRequest<AiRun>(`/runs/${id}`, {method:"PATCH",body:JSON.stringify({removed})});
|
||||
export const configureAiWorld = (world: AiWorld, settings: AiWorldSettings) =>
|
||||
polygonRequest<AiWorld>(`/worlds/${world.world_id}/settings`, {
|
||||
method: "PUT", body: JSON.stringify(settings),
|
||||
});
|
||||
export const startAiRun = (world: AiWorld, composition?: AiSelection) => polygonRequest<AiRun>("/runs", {
|
||||
export const startAiRun = (world: AiWorld, robot: AiRobot, composition?: AiSelection,
|
||||
purpose: "planning" | "evaluation" = "evaluation", plan?: AiPlan, roverSettings?: RoverSettings) => polygonRequest<AiRun>("/runs", {
|
||||
method: "POST", headers: { "Idempotency-Key": crypto.randomUUID() },
|
||||
body: JSON.stringify({ world_id: world.world_id, clock: "realtime", start_paused: true, duration_seconds: 1800, composition }),
|
||||
body: JSON.stringify({ world_id: world.world_id, robot_id: robot.robot_id, robot_sha256: robot.sha256,
|
||||
clock: "realtime", start_paused: purpose === "planning",
|
||||
composition, purpose, plan_id: plan?.plan_id, rover_settings:roverSettings }),
|
||||
});
|
||||
export const sendAiPlanningCommand = (run: AiRun, command: AiPlanningCommand) =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/planning`, { method: "PUT", body: JSON.stringify({
|
||||
...command, request_id: crypto.randomUUID().replaceAll("-", ""),
|
||||
view_revision: run.telemetry?.planning?.view_revision ?? 0,
|
||||
}) });
|
||||
export const saveAiPlan = (run: AiRun, name: string) => polygonRequest<AiPlan>(`/runs/${run.run_id}/plan`, {
|
||||
method: "POST", body: JSON.stringify({ name, sequence: run.telemetry?.planning?.sequence ?? 0 }),
|
||||
});
|
||||
export const setAiCamera = (run: AiRun, camera: AiCamera) =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/view`, { method: "PUT", body: JSON.stringify({ camera }) });
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import {polygonRequest,type AiSelection} from './aiPolygon';
|
||||
|
||||
export interface AiProfile {
|
||||
profile_id:string; name:string; composition:AiSelection; revision:number; removed:boolean;
|
||||
}
|
||||
export const fetchAiProfiles=()=>polygonRequest<AiProfile[]>('/ai-profiles');
|
||||
export const createAiProfile=(name:string,composition:AiSelection)=>polygonRequest<AiProfile>('/ai-profiles',
|
||||
{method:'POST',body:JSON.stringify({name,composition})});
|
||||
export const updateAiProfile=(profile:AiProfile,changes:{name?:string;composition?:AiSelection;removed?:boolean})=>
|
||||
polygonRequest<AiProfile>(`/ai-profiles/${profile.profile_id}`,
|
||||
{method:'PATCH',body:JSON.stringify({expected_revision:profile.revision,...changes})});
|
||||
|
||||
/** Saved intent survives installed module revisions; admission rebinds SHA-256. */
|
||||
export function sameAiIntent(a:AiSelection,b:AiSelection):boolean {
|
||||
const stable=(value:unknown):unknown=>Array.isArray(value)?value.map(stable):value&&typeof value==='object'
|
||||
?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>[k,stable(v)])):value;
|
||||
const intent=(value:AiSelection)=>value.selections.map(({group,module_id,parameters})=>({group,module_id,parameters}))
|
||||
.sort((a,b)=>a.group.localeCompare(b.group));
|
||||
return JSON.stringify(stable(intent(a)))===JSON.stringify(stable(intent(b)));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { PerspectiveCamera, Quaternion, Vector3 } from "three";
|
||||
const UP = new Vector3(0,1,0);
|
||||
/** Depth along the optical axis gives a metric screen-space pan at any zoom. */
|
||||
export function navigationDepth(camera: PerspectiveCamera, anchor: Vector3) {
|
||||
return Math.max(.1, anchor.clone().sub(camera.position).dot(camera.getWorldDirection(new Vector3())));
|
||||
}
|
||||
export function panCamera(camera: PerspectiveCamera, depth: number, dx: number, dy: number, height: number) {
|
||||
const scale=2*depth*Math.tan(camera.fov*Math.PI/360)/Math.max(1,height);
|
||||
camera.position.add(new Vector3(-dx*scale,dy*scale,0).applyQuaternion(camera.quaternion));
|
||||
camera.updateMatrixWorld();
|
||||
}
|
||||
/** Rotate the complete camera pose about the picked point: no lookAt snap.
|
||||
* The picked point keeps its screen coordinates, including off-centre clicks. */
|
||||
export function orbitCamera(camera: PerspectiveCamera, anchor: Vector3, dx: number, dy: number, height: number) {
|
||||
const factor=2*Math.PI/Math.max(1,height);
|
||||
const yaw=new Quaternion().setFromAxisAngle(UP,-dx*factor);
|
||||
const forward=camera.getWorldDirection(new Vector3());
|
||||
const elevation=Math.asin(Math.max(-1,Math.min(1,forward.y)));
|
||||
const pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,elevation-dy*factor))-elevation;
|
||||
const right=new Vector3(1,0,0).applyQuaternion(camera.quaternion).applyQuaternion(yaw);
|
||||
const rotation=new Quaternion().setFromAxisAngle(right,pitch).multiply(yaw);
|
||||
camera.position.sub(anchor).applyQuaternion(rotation).add(anchor);
|
||||
camera.quaternion.premultiply(rotation);
|
||||
camera.updateMatrixWorld();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/** Exponential dolly in metres, independent of OrbitControls' target radius. */
|
||||
export function zoomDisplacement(depth: number, wheelPixels: number): number {
|
||||
return depth * (1 - Math.exp(Math.max(-.8, Math.min(.8,wheelPixels*.002))));
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export type GaussianQuality = "low" | "medium" | "high" | "ultra" | "maximum";
|
||||
// PlayCanvas: zero disables count-budget enforcement; quality uses LOD distances only.
|
||||
export const QUALITY_PROFILES: Record<GaussianQuality, {
|
||||
lodBaseDistance: number;
|
||||
lodMultiplier: number;
|
||||
lodRangeMin: number;
|
||||
lodRangeMax: number;
|
||||
pixelRatio: number;
|
||||
splatBudget: number;
|
||||
targetFps: number;
|
||||
}> = {
|
||||
low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 0, targetFps: 30 },
|
||||
medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 0, targetFps: 45 },
|
||||
high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 0, targetFps: 60 },
|
||||
ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 0, targetFps: 60 },
|
||||
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 0, targetFps: 60 },
|
||||
};
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { AiPlan, AiWaypoint } from "./aiPolygon";
|
||||
|
||||
/** A launch may reuse a saved task only when it represents this exact draft. */
|
||||
export function planMatchesDraft(plan:AiPlan|undefined, cacheKey:string, robotSha:string, points:AiWaypoint[]) {
|
||||
return !!plan && plan.editor_cache_key===cacheKey && plan.robot_sha256===robotSha
|
||||
&& plan.points.length===points.length && plan.points.every((point,i)=>point.id===points[i].id
|
||||
&& point.position.every((value,axis)=>value===points[i].position[axis]));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { GaussianQuality } from "./gaussianQuality";
|
||||
|
||||
export interface PlannerPreferences {
|
||||
quality: GaussianQuality;
|
||||
navigation: { nearDistance:number; farDistance:number; nearPan:number; farPan:number; zoom:number; centroidPixels:number; centroidColor:string; centroidOpacity:number };
|
||||
pivot: { pixels: number; diameter: number; cone: number; opacity: number; x: string; y: string; z: string };
|
||||
waypoint: { diameter: number; height: number; color: string; opacity: number; frequency: number; emission: number; emissionColor: string };
|
||||
}
|
||||
export const PLANNER_PREFERENCES_KEY = "missioncore.simulation-view/v1";
|
||||
export const DEFAULT_PLANNER_PREFERENCES: PlannerPreferences = {
|
||||
quality: "medium",
|
||||
navigation: { nearDistance:3, farDistance:100, nearPan:1, farPan:1, zoom:1, centroidPixels:14, centroidColor:"#edf0eb", centroidOpacity:.8 },
|
||||
pivot: { pixels: 105, diameter: 5, cone: 22, opacity: 1, x: "#e85b54", y: "#83ca61", z: "#6499ed" },
|
||||
waypoint: { diameter: .35, height: 4.5, color: "#edf0eb", opacity: .65, frequency: .5, emission: 1.5, emissionColor: "#edf0eb" },
|
||||
};
|
||||
/** Persisted operator preferences are untrusted input; old/invalid fields get defaults. */
|
||||
export function normalizePlannerPreferences(value: unknown): PlannerPreferences {
|
||||
const v = value && typeof value === "object" ? value as Partial<PlannerPreferences> : {};
|
||||
const p: Partial<PlannerPreferences["pivot"]> = v.pivot ?? {}, w: Partial<PlannerPreferences["waypoint"]> = v.waypoint ?? {}, d = DEFAULT_PLANNER_PREFERENCES;
|
||||
const n = (x: unknown, fallback: number, min: number, max: number) => typeof x === "number" && Number.isFinite(x) ? Math.max(min, Math.min(max,x)) : fallback;
|
||||
const color = (x: unknown, fallback: string) => typeof x === "string" && /^#[0-9a-f]{6}$/i.test(x) ? x : fallback;
|
||||
const nav:Partial<PlannerPreferences["navigation"]>=v.navigation??{}, dn=d.navigation;
|
||||
const nearDistance=n(nav.nearDistance,dn.nearDistance,.5,50);
|
||||
return {
|
||||
navigation: {nearDistance,farDistance:Math.max(nearDistance+1,n(nav.farDistance,dn.farDistance,2,500)),
|
||||
nearPan:n(nav.nearPan,dn.nearPan,.1,5),farPan:n(nav.farPan,dn.farPan,.1,5),zoom:n(nav.zoom,dn.zoom,.1,3),
|
||||
centroidPixels:n(nav.centroidPixels,dn.centroidPixels,6,64),centroidColor:color(nav.centroidColor,dn.centroidColor),centroidOpacity:n(nav.centroidOpacity,dn.centroidOpacity,.1,1)},
|
||||
quality: ["low","medium","high","ultra","maximum"].includes(v.quality ?? "") ? v.quality! : d.quality,
|
||||
pivot: { pixels:n(p.pixels,d.pivot.pixels,50,220), diameter:n(p.diameter,d.pivot.diameter,2,16), cone:n(p.cone,d.pivot.cone,10,40), opacity:n(p.opacity,d.pivot.opacity,.15,1),
|
||||
x:color(p.x,d.pivot.x), y:color(p.y,d.pivot.y), z:color(p.z,d.pivot.z) },
|
||||
waypoint: { diameter:n(w.diameter,d.waypoint.diameter,.05,3), height:n(w.height,d.waypoint.height,.2,50), color:color(w.color,d.waypoint.color), opacity:n(w.opacity,d.waypoint.opacity,.1,1), frequency:n(w.frequency,d.waypoint.frequency,0,3), emission:n(w.emission,d.waypoint.emission,0,5), emissionColor:color(w.emissionColor,d.waypoint.emissionColor) },
|
||||
};
|
||||
}
|
||||
export function axisWorldLength(depth: number, height: number, pixels: number) {
|
||||
return Math.max(.01, depth) * 2 * Math.tan(Math.PI / 6) * pixels / Math.max(1,height);
|
||||
}
|
||||
|
||||
export function panSensitivity(distance:number,navigation:PlannerPreferences["navigation"]) {
|
||||
const t=Math.max(0,Math.min(1,(distance-navigation.nearDistance)/(navigation.farDistance-navigation.nearDistance)));
|
||||
const smooth=t*t*(3-2*t);
|
||||
return navigation.nearPan+(navigation.farPan-navigation.nearPan)*smooth;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export interface RoverMotion {
|
||||
schema_version: "missioncore.rover-motion/v1";
|
||||
length_m: number; pitch_m: number; phase_m: number; link_count: number;
|
||||
track_width_m: number; track_centres_m: { L: number; R: number }; shift_m: number[];
|
||||
segments: ["arc" | "line", number, number, number[]][];
|
||||
wheels: { node: string; radius_m: number }[];
|
||||
}
|
||||
export function beltPose(motion: RoverMotion, distance: number, side: "L" | "R", index: number) {
|
||||
const s = ((distance + motion.phase_m + index*motion.pitch_m) % motion.length_m + motion.length_m) % motion.length_m;
|
||||
const segment = motion.segments.find(([, start, length]) => s <= start+length+1e-10)!;
|
||||
const [kind,start,,d] = segment, t = s-start;
|
||||
let x: number, z: number, angle: number;
|
||||
if (kind === "arc") {
|
||||
const [cx,cz,r,a] = d, q = a-t/r;
|
||||
x=cx+r*Math.cos(q); z=cz+r*Math.sin(q); angle=q-Math.PI/2;
|
||||
} else {
|
||||
x=d[0]+d[2]*t; z=d[1]+d[3]*t; angle=Math.atan2(d[3],d[2]);
|
||||
}
|
||||
return { position:[x+motion.shift_m[0],z+motion.shift_m[2],-motion.track_centres_m[side]-motion.shift_m[1]], angle };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { AiRobot } from "./aiPolygon";
|
||||
|
||||
export interface RoverSettings {
|
||||
schema_version: "missioncore.rover-settings/v2";
|
||||
max_speed_mps: number;
|
||||
base_mass_kg: number;
|
||||
payload_mass_kg: number;
|
||||
payload_height_m: number;
|
||||
}
|
||||
export const roverSettingsKey = (robot: AiRobot) => `nodedc.simulation.rover.v1:${robot.robot_id}:${robot.sha256}`;
|
||||
export function defaultRoverSettings(robot: AiRobot, speed: number): RoverSettings {
|
||||
return { schema_version: "missioncore.rover-settings/v2",
|
||||
max_speed_mps: Math.max(.05, Number.isFinite(speed) ? speed : .3),
|
||||
base_mass_kg: robot.physics.mass_kg, payload_mass_kg: 0,
|
||||
payload_height_m: Math.round((robot.physics.height_m + .1) * 100) / 100 };
|
||||
}
|
||||
export function validRoverSettings(value: RoverSettings, _robot: AiRobot): boolean {
|
||||
const within = (v:number, min:number, max:number) => Number.isFinite(v) && v>=min && v<=max;
|
||||
return value.schema_version === "missioncore.rover-settings/v2"
|
||||
&& within(value.max_speed_mps, .05, Infinity)
|
||||
&& within(value.base_mass_kg,10,1000) && within(value.payload_mass_kg,0,500)
|
||||
&& within(value.payload_height_m,.1,3);
|
||||
}
|
||||
export function parseRoverSettings(raw: string | null, robot: AiRobot): RoverSettings | undefined {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
if (value?.schema_version === "missioncore.rover-settings/v1") value.schema_version = "missioncore.rover-settings/v2";
|
||||
if (!value || !validRoverSettings(value,robot)
|
||||
|| Object.keys(value).sort().join() !== "base_mass_kg,max_speed_mps,payload_height_m,payload_mass_kg,schema_version") return;
|
||||
return value;
|
||||
} catch { return; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { AiModules, AiSelection } from "./aiPolygon";
|
||||
|
||||
const SCHEMA = "missioncore.observatory-ai-composition/v1";
|
||||
const GROUPS = new Set(["segmentation", "detection", "geometry", "range", "motion", "policy"]);
|
||||
|
||||
/** Stored intent is untrusted. Worker admission still owns executable contracts. */
|
||||
export function parseSavedSelection(raw: string | null): AiSelection | undefined {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
if (value?.schema_version !== SCHEMA || !Array.isArray(value.selections)
|
||||
|| !value.selections.length || value.selections.length > GROUPS.size) return;
|
||||
const groups = new Set<string>();
|
||||
for (const row of value.selections) {
|
||||
if (!row || !GROUPS.has(row.group) || groups.has(row.group)
|
||||
|| typeof row.module_id !== "string" || !/^[a-z0-9][a-z0-9-]{0,127}$/.test(row.module_id)
|
||||
|| typeof row.module_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.module_sha256)
|
||||
|| !row.parameters || typeof row.parameters !== "object" || Array.isArray(row.parameters)) return;
|
||||
groups.add(row.group);
|
||||
}
|
||||
return value as AiSelection;
|
||||
} catch { return; }
|
||||
}
|
||||
|
||||
/** Rebind every chosen provider, including alternatives absent from defaults. */
|
||||
export function currentSelection(selection: AiSelection, installed: AiModules): AiSelection {
|
||||
return { ...selection, selections: selection.selections.map(row => {
|
||||
const module = installed.catalog.groups.find(group => group.group === row.group)
|
||||
?.modules.find(candidate => candidate.moduleId === row.module_id);
|
||||
if (!module) throw new Error("Выбранный AI-модуль больше недоступен. Проверьте конфигурацию AI.");
|
||||
return { ...row, module_sha256: module.moduleSha256,
|
||||
parameters: { ...module.defaults, ...row.parameters } };
|
||||
}) };
|
||||
}
|
||||
|
||||
export const selectionStorageKey = (world: string, robot: string) =>
|
||||
`nodedc.simulation.composition.v1:${world}:${robot}`;
|
||||
@@ -0,0 +1,5 @@
|
||||
/** A bounded first-frame/stall watchdog, independent of SDK callbacks. */
|
||||
export function streamRecovery(now:number,started:number,lastFrame:number|null,failedAt:number|null,attempt:number) {
|
||||
const expired=failedAt!==null ? now-failedAt>=2000 : lastFrame===null ? now-started>=20000 : now-lastFrame>=10000;
|
||||
return !expired?"wait":attempt<2?"retry":"failed";
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import type { AiModules, AiSelection } from "./aiPolygon";
|
||||
import { parseSavedSelection, selectionStorageKey } from "./runConfiguration";
|
||||
|
||||
/** Location/robot intent survives reload; changing location never carries it over. */
|
||||
export function useAiSelection(world: string | null, robot: string | null, modules: AiModules | null) {
|
||||
const scope = world && robot ? selectionStorageKey(world, robot) : null;
|
||||
const [draft, setDraft] = useState<{ scope: string | null; value: AiSelection } | null>(null);
|
||||
const saved = useMemo(() => {
|
||||
try { return scope ? parseSavedSelection(localStorage.getItem(scope)) : undefined; }
|
||||
catch { return undefined; }
|
||||
}, [scope]);
|
||||
const selection = draft?.scope === scope ? draft.value : saved ?? modules?.selection;
|
||||
const setSelection = (value: AiSelection) => {
|
||||
setDraft({ scope, value });
|
||||
try { if (scope) localStorage.setItem(scope, JSON.stringify(value)); }
|
||||
catch { /* In-memory intent remains usable if browser storage is unavailable. */ }
|
||||
};
|
||||
return [selection, setSelection] as const;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import type { AiRobot } from "./aiPolygon";
|
||||
import { defaultRoverSettings, parseRoverSettings, roverSettingsKey, type RoverSettings } from "./roverSettings";
|
||||
|
||||
export function useRoverSettings(robot: AiRobot | undefined, speed: number) {
|
||||
const scope = robot ? roverSettingsKey(robot) : null;
|
||||
const [draft,setDraft] = useState<{scope:string;value:RoverSettings}|null>(null);
|
||||
const saved = useMemo(()=>{
|
||||
try { return robot && scope ? parseRoverSettings(localStorage.getItem(scope),robot) : undefined; }
|
||||
catch { return undefined; }
|
||||
},[scope]);
|
||||
const value = draft?.scope===scope ? draft.value : saved ?? (robot ? defaultRoverSettings(robot,speed) : undefined);
|
||||
const update = (next:RoverSettings) => {
|
||||
if(!scope)return;
|
||||
setDraft({scope,value:next});
|
||||
// Keep usable in-memory intent, but let the caller report persistence failure.
|
||||
localStorage.setItem(scope,JSON.stringify(next));
|
||||
};
|
||||
return [value,update] as const;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { AiCatalog, AiRun } from "./aiPolygon";
|
||||
/** Read-only catalog refreshes never claim a browser's video session. */
|
||||
export function viewedAiRun(catalog:AiCatalog|null,worldId:string,runId:string|null):AiRun|undefined {
|
||||
if(!catalog||!runId)return undefined;
|
||||
const active=catalog.runtime.active_run;
|
||||
if(active?.run_id===runId&&active.world.world_id===worldId)return active;
|
||||
return catalog.runs.find(r=>r.run_id===runId&&r.world.world_id===worldId);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export type WaypointAxis = "x" | "y" | "z" | "xz";
|
||||
/** Closest point on the selected axis to the screen ray. Null at a parallel view. */
|
||||
export function dragWaypoint(origin: number[], direction: number[], point: number[], axis: WaypointAxis): number[] | null {
|
||||
const norm = Math.hypot(...direction);
|
||||
if (norm < 1e-9) return null;
|
||||
const d = direction.map(v => v / norm);
|
||||
if (axis === "xz") {
|
||||
if (Math.abs(d[1]) < 1e-5) return null;
|
||||
const t = (point[1] - origin[1]) / d[1];
|
||||
return t < 0 ? null : origin.map((v,i) => v + t*d[i]);
|
||||
}
|
||||
const index = {x:0,y:1,z:2}[axis], denominator = 1-d[index]**2;
|
||||
if (denominator < 1e-5) return null;
|
||||
const v = point.map((p,i) => p-origin[i]);
|
||||
const distance = (d[index]*v.reduce((sum,p,i) => sum+p*d[i],0)-v[index])/denominator;
|
||||
return point.map((p,i) => p+(i===index?distance:0));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { AiWaypoint } from "./aiPolygon";
|
||||
interface Snapshot { points: AiWaypoint[]; selected: string|null }
|
||||
export interface WaypointEditing extends Snapshot { history:Snapshot[]; gesture:Snapshot|null; sequence:number }
|
||||
export type WaypointEdit = {type:"select";id:string|null}|{type:"replace"|"move"|"load";points:AiWaypoint[];selected?:string|null}
|
||||
|{type:"delete"|"undo"|"begin"|"commit"|"cancel"};
|
||||
export function waypointEditing(points:AiWaypoint[]):WaypointEditing {return {points,selected:null,history:[],gesture:null,sequence:0};}
|
||||
const snapshot=(s:WaypointEditing):Snapshot=>({points:s.points,selected:s.selected});
|
||||
const same=(a:AiWaypoint[],b:AiWaypoint[])=>a.length===b.length&&a.every((p,i)=>p.id===b[i].id&&p.position.every((v,j)=>v===b[i].position[j]));
|
||||
export function editWaypoints(s:WaypointEditing,a:WaypointEdit):WaypointEditing {
|
||||
const commit=(prior:Snapshot,points:AiWaypoint[],selected:string|null):WaypointEditing=>({
|
||||
points,selected,gesture:null,history:[...s.history.slice(-49),prior],sequence:s.sequence+1,
|
||||
});
|
||||
switch(a.type){
|
||||
case "select":return {...s,selected:a.id};
|
||||
case "load":return {...waypointEditing(a.points),sequence:s.sequence+1};
|
||||
case "replace":return same(s.points,a.points)?s:commit(snapshot(s),a.points,a.selected??null);
|
||||
case "delete":return s.gesture||!s.points.some(p=>p.id===s.selected)?s:commit(snapshot(s),s.points.filter(p=>p.id!==s.selected),null);
|
||||
case "begin":return {...s,gesture:snapshot(s)};
|
||||
case "move":return s.gesture?{...s,points:a.points}:s;
|
||||
case "cancel":return s.gesture?{...s,...s.gesture,gesture:null}:s;
|
||||
case "commit":return !s.gesture?s:same(s.gesture.points,s.points)?{...s,gesture:null}:commit(s.gesture,s.points,s.selected);
|
||||
case "undo":{
|
||||
if(s.gesture)return {...s,...s.gesture,gesture:null};
|
||||
const prior=s.history.at(-1);return prior?{...s,...prior,history:s.history.slice(0,-1),sequence:s.sequence+1}:s;
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Keyboard shortcuts are local to the scene; native text undo remains native. */
|
||||
export function waypointShortcut(e:{key:string;code:string;ctrlKey:boolean;metaKey:boolean;altKey:boolean;shiftKey:boolean},editable:boolean):"undo"|"delete"|null {
|
||||
if(editable||e.altKey)return null;
|
||||
if((e.ctrlKey||e.metaKey)&&!e.shiftKey&&e.code==="KeyZ")return "undo";
|
||||
if(!e.ctrlKey&&!e.metaKey&&(e.key==="Delete"||e.key==="Backspace"))return "delete";
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Exact closed vertical cylinder, including caps. Ray need not be normalized. */
|
||||
export function waypointHit(origin:number[], direction:number[], base:number[], radius:number, height:number):number|null {
|
||||
const [ox,oy,oz]=origin.map((v,i)=>v-base[i]), [dx,dy,dz]=direction;
|
||||
const candidates:number[]=[];
|
||||
const a=dx*dx+dz*dz,b=2*(ox*dx+oz*dz),c=ox*ox+oz*oz-radius*radius;
|
||||
if(a>1e-14) {
|
||||
const discriminant=b*b-4*a*c;
|
||||
if(discriminant>=0)for(const t of [(-b-Math.sqrt(discriminant))/(2*a),(-b+Math.sqrt(discriminant))/(2*a)])
|
||||
if(t>=0 && oy+t*dy>=0 && oy+t*dy<=height)candidates.push(t);
|
||||
}
|
||||
if(Math.abs(dy)>1e-14)for(const y of [0,height]) {
|
||||
const t=(y-oy)/dy;
|
||||
if(t>=0 && (ox+t*dx)**2+(oz+t*dz)**2<=radius*radius)candidates.push(t);
|
||||
}
|
||||
return candidates.length?Math.min(...candidates):null;
|
||||
}
|
||||
Reference in New Issue
Block a user