Compare commits

..
Author SHA1 Message Date
DCCONSTRUCTIONS 4a8fffb418 feat(bim): integrate selection sync and flight speed rail 2026-11-15 15:40:33 +03:00
DCCONSTRUCTIONS 6911da71d8 Integrate BIM material labels and canvas context menu fix 2026-11-15 15:10:05 +03:00
DCCONSTRUCTIONS 87c0c7960a Integrate BIM shared coordinates and layer placement tools 2026-11-15 14:44:48 +03:00
DCCONSTRUCTIONS b96bea1599 Integrate BIM 0.2.16 background checks and grouped glass panels 2026-11-15 13:45:17 +03:00
DCCONSTRUCTIONS 136be019af fix(bim): integrate surface picking and stable hierarchy viewer 2026-11-15 12:49:31 +03:00
DCCONSTRUCTIONS e8e450e93a fix(bim): integrate consistent keyboard navigation speed 2026-11-15 12:09:13 +03:00
DCCONSTRUCTIONS 28cb2e49a4 feat(bim): integrate surface pivot navigation and transparent dock resizing 2026-11-15 11:57:14 +03:00
DCCONSTRUCTIONS c6280525ba fix(bim): install keyboard-only viewport navigation 2026-11-15 11:14:36 +03:00
DCCONSTRUCTIONS 4002ae4c96 feat(bim): install source preflight and layout-independent viewport flight 2026-11-15 10:53:57 +03:00
DCCONSTRUCTIONS 71705ea862 Integrate BIM project uniqueness and shared content lifecycle 2026-11-15 10:29:45 +03:00
DCCONSTRUCTIONS 91a18c580a fix(bim): align upload bar and status in catalog and layers 2026-11-15 09:57:52 +03:00
DCCONSTRUCTIONS 8e37ef6968 feat(bim): integrate acknowledged upload pause and converter progress 2026-11-15 09:50:23 +03:00
DCCONSTRUCTIONS 1a0b5b0bd7 fix(bim): integrate whole-surface intake and background uploads 2026-11-15 09:07:23 +03:00
DCCONSTRUCTIONS d88ea2de93 feat(bim): integrate Worker point clouds and format downloads 2026-11-15 01:29:41 +03:00
DCCONSTRUCTIONS c785f1173f docs(bim): record lifecycle audit and multiuser readiness limits 2026-11-15 00:13:46 +03:00
DCCONSTRUCTIONS 1c092ff0e3 feat(bim): integrate portable viewport settings and shared screen picker 2026-11-15 00:01:32 +03:00
DCCONSTRUCTIONS f6e0bab559 Integrate BIM selection, cube settings and shared viewport refinements 2026-11-14 23:16:52 +03:00
DCCONSTRUCTIONS e8920f56a2 Integrate dockable BIM viewer, IFC hierarchy and scene tools 2026-11-14 22:16:11 +03:00
DCCONSTRUCTIONS 9937eb66d8 Integrate BIM entry hierarchy, durable retirement and viewport glass 2026-11-14 20:44:00 +03:00
DCCONSTRUCTIONS cd27a5e483 feat(bim): integrate portable IFC viewer, project map and prepared layers 2026-11-14 18:49:43 +03:00
DCCONSTRUCTIONS a49fb00b8e feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements
Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
2026-11-11 23:53:46 +03:00
DCCONSTRUCTIONS 58ac9fe3d2 Assemble complete modular LAB recordings on Worker before readiness 2026-11-10 04:44:02 +03:00
DCCONSTRUCTIONS 800518ea80 Record cold-cache LAB playback acceptance and remaining producer integration 2026-11-10 03:23:43 +03:00
DCCONSTRUCTIONS 1317f78672 Restore complete LAB recordings from verified Worker publications 2026-11-10 03:23:20 +03:00
DCCONSTRUCTIONS a724a9796a docs(worker): qualify Wi-Fi result transfer and explicit range recovery 2026-11-10 02:29:07 +03:00
DCCONSTRUCTIONS 4d0306f353 docs(worker): record LTE telemetry acceptance and local LAB reuse 2026-11-10 02:07:12 +03:00
DCCONSTRUCTIONS 40872d3534 fix(system): keep network configuration in worker settings 2026-11-10 02:06:41 +03:00
DCCONSTRUCTIONS 1472926112 docs: record Ops reconciliation and remaining network acceptance plan 2026-11-10 01:17:10 +03:00
DCCONSTRUCTIONS e8025bc99f feat(system): add worker and VPS catalogs with guarded local removal 2026-11-10 01:11:24 +03:00
DCCONSTRUCTIONS ad5a929e06 feat(worker): supervise VPN connections and recover batched telemetry 2026-11-10 01:10:37 +03:00
DCCONSTRUCTIONS fe5900ff3b refactor(lab): move execution to Worker and manage replay and transfer lifecycles 2026-11-10 01:09:39 +03:00
DCCONSTRUCTIONS cd34b6ce1a fix(scene): persist editor and battery profiles in Core 2026-11-10 01:08:00 +03:00
DCCONSTRUCTIONS 7595bea07c fix(simulation): isolate semantics and correct clipping and orthographic LOD 2026-11-10 01:05:59 +03:00
DCCONSTRUCTIONS ab5766df6a Bound semantic worker storage and add verified evidence closeout 2026-11-07 18:53:56 +03:00
DCCONSTRUCTIONS 43148a8769 Bound semantic map publication and define experiment storage closeout 2026-11-07 17:31:06 +03:00
DCCONSTRUCTIONS 09c13a5c68 Retain imported originals on Worker before retiring Core staging 2026-11-07 16:45:17 +03:00
DCCONSTRUCTIONS b0332fa377 docs: preserve useful experiment history in Ops 2026-11-04 19:22:04 +03:00
DCCONSTRUCTIONS d5f35e4a74 feat(battery): support compact charge indicators and header offset 2026-11-04 18:18:33 +03:00
DCCONSTRUCTIONS 14e6426cd5 feat(scene-editor): duplicate independent materials with named copies 2026-11-04 18:18:33 +03:00
DCCONSTRUCTIONS f228b20c2b feat(battery): configure observatory indicator geometry and space design controls 2026-11-04 17:46:06 +03:00
DCCONSTRUCTIONS 55e1ab8d1c feat(scene-editor): share environment profiles and separate SOC material surfaces 2026-11-04 17:46:05 +03:00
DCCONSTRUCTIONS 5f8ed0d94c feat(battery-ui): integrate observatory detail, appearance controls and compact BMS hierarchy 2026-11-04 17:14:56 +03:00
DCCONSTRUCTIONS c9d79456ef feat(battery): add welded R05 frame and correct CATL enclosure labels 2026-11-04 17:14:56 +03:00
DCCONSTRUCTIONS 42213001ba feat(bms): add read-only diagnostics and guarded operating switch commands 2026-11-04 17:14:54 +03:00
DCCONSTRUCTIONS ab8e977f11 feat(node): add confirmed board shutdown with expiring commands 2026-11-04 15:52:46 +03:00
DCCONSTRUCTIONS f76928b606 feat(bms): collapse connection details and separate telemetry tiles 2026-11-04 15:48:01 +03:00
DCCONSTRUCTIONS df743a9f6c build(node): package NetBird and JK BMS with pinned shared UI sources 2026-11-04 00:43:00 +03:00
DCCONSTRUCTIONS f3d0c25ccd feat(bms): discover JK batteries and integrate read-only telemetry scenes 2026-11-04 00:43:00 +03:00
DCCONSTRUCTIONS 2f0a066dde feat(playcanvas): share dockable scene tools and persistent model editing 2026-11-04 00:42:59 +03:00
DCCONSTRUCTIONS 038337783f feat(k1): add USB networking, device management and acquisition recovery 2026-11-04 00:42:57 +03:00
DCCONSTRUCTIONS 14c3c7c2b6 feat(observatory): persist scene profiles and stable device view bindings 2026-11-04 00:42:56 +03:00
DCCONSTRUCTIONS b7b5ac9cf0 feat(semantics): version scene edits and refine paint geometry 2026-11-04 00:42:55 +03:00
DCCONSTRUCTIONS 7a3c3c00b3 feat(rerun): retain live playback and recover isolated viewer resources 2026-11-04 00:42:54 +03:00
DCCONSTRUCTIONS 669ada973f feat(node): expose fresh network interface and hardware status 2026-11-04 00:42:26 +03:00
DCCONSTRUCTIONS 2c0a10b687 feat(network): integrate NetBird clients, profiles and private backups 2026-11-04 00:42:25 +03:00
DCCONSTRUCTIONS 1e77b198cb fix(transport): recover rover feedback and retained WireGuard routes 2026-11-04 00:42:24 +03:00
810 changed files with 49526 additions and 5271 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
+96 -6
View File
@@ -5,6 +5,17 @@ real device plugin investigates an owner-controlled XGRIDS/LixelKity K1 as a
black-box sensor. Preserve the device, the host, the working LAN, raw evidence,
and the boundary between Mission Core and vendor-specific integration code.
- Owner clarification (2026-11-08): LAB trash means permanent deletion of that
LAB's admitted files on Core and Worker, followed by removal from history.
Do not replace it with catalog-only hiding or leave unreachable result bytes.
Source recordings and files shared by retained LABs are separate owners.
Worker acknowledgement is mandatory; on failure keep a retryable history row.
Local-copy expiry/delete is a separate action that preserves history and Worker
results. Pin protects against expiry, not explicit full-LAB deletion.
A LAB module/registered component, its model, benchmark and shared inputs are
not disposable run output. Missing UI history alone is never evidence of junk;
establish ownership and dependencies before retiring an old experiment.
## Single working directory — owner requirement, 2026-10-08
The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50),
@@ -75,6 +86,55 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
retain the immutable algorithm result and human provenance separately.
See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates.
## LAB placement — owner clarification, 2026-11-08
All supported laboratory execution, raw inputs, intermediate arrays and heavy
working directories belong to the portable Worker runtime. The operator Core is
a viewport: retain ready visual products, semantic maps/manual edits and bounded
metadata, never a silent local compute fallback. See
`docs/LAB_AND_INSTALLER_STORAGE.md` and `deploy/laboratory/README.md`.
Canonical Ops policy: [MISSIONCOR-97 — Storage rules](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-97).
Read its current rules before a new LAB/AI data producer or storage migration;
keep current implementation distinct from the dated distributed-storage research.
A LAB viewing result means a full playable recording with synchronized
segmentation/camera frames, 3D cuboids and timeline where the experiment provides
those layers. Catalog JSON, a screenshot or a textual report does not establish
playback acceptance. Preserve the current UI; do not add neural/narrative reports
or redesign LAB as part of storage migration. Later owner clarification on
8 November explicitly adds global Storage settings (configurable local LAB-copy
retention), offline pins, actual local availability and removal of local copies.
Run history must remain discoverable independently of replay compatibility or
local cache presence. These are requirements, not features already implemented
by the storage audit; see `outputs/storage-fresh-audit-20261108/REPORT.md`.
Verify real playback before retiring local working data; preserve accepted
recordings, Gaussians, semantic edits and original captures.
The configurable LAB-copy TTL (default 30 days) applies exclusively to unpinned
local viewing copies in Mission Core, never to Worker experiments or their models.
Integrated/experimental model assets, installed executor packages/images, runtime
environments and experimental configurations are retained until a separate owner
decision consolidates the pipeline, even under `cache` or `derived`. Do not apply
LAB-copy TTL or absence-from-UI cleanup to them. A disposable transport package
means job input/output transfer bytes, not an executor/model distribution. Before retiring an intermediate
copy, verify publication/retry readers, shared owners and restoration of its exact
identity. See the 8 November intermediate-store rules in
`docs/STORAGE_RETENTION.md` and `outputs/intermediate-storage-review-20261108/REPORT.md`.
Portable source/result transfer uses shared physical-disk reservations (2 GiB
free reserve), not fixed 8/4 GiB directory ceilings or model-count limits.
Source copies registered by admitted producers retire only after durable queue
consumers finish and exact originals remain available. HTTP reader locks span the
whole response. Preserve unknown paths, changed originals, shared filesystem
owners and pending publication/reconciliation. Source retirement is not a TTL.
Result closeout retains manifest/receipt for archive-backed retries; do not
readmit retired compute definitions merely to retire historical copies.
Use an explicit target allowlist for one-time historical cleanup and verify
unselected files; unknown old copies are not automatically adopted by a scan.
These rules do not change installed model/executor assets or viewing-copy TTL.
See the 9 November transfer lifecycle section of `docs/STORAGE_RETENTION.md`.
## Non-negotiable safety boundaries
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
@@ -280,12 +340,21 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
- The compact summary must explain the decision question, immutable source,
tested method/models/algorithms, experimental mode, principal result,
limitations, and retained authority. It is not the engineering report.
- Owner reporting rule (2026-10-09): Ops contains concise, verified delivered
results only: what works, the implementation used, and its accepted scope.
Keep intermediate experiments, failed attempts, architecture proposals,
detailed logs and future plans in local engineering evidence, not Ops.
Consolidate superseded intermediate blocks instead of appending a run diary.
Never present a partial experiment as a completed product result.
- Owner reporting rule (2026-10-09), clarified 2026-11-04: keep current Ops
summaries concise and evidence-backed: what works, implementation and accepted
scope. Replace or remove obsolete assertions about the current state.
Preserve decision-relevant dated experiments: capability/limit findings, tested
alternatives and consequential failures that explain a decision or prevent
repeating a dead end. Keep the method/conditions, outcome, limitation, decision
and evidence reference separate from current state. Age alone does not make
useful evidence disposable. Do not retain every attempt, intermediate UI edit,
routine check or duplicate metric merely for history; consolidate nonessential
detail and keep traces local. A local backup alone does not preserve important
experiment findings in Ops. Annotate disproved interpretations without erasing
their observations; never invent why an untested option was rejected.
Raw logs/media, credentials and secret fields remain in private evidence;
proposals remain explicitly unverified. Never present a partial experiment as
a completed product result. Follow the ops-context skill for card updates.
- Spatial evidence uses 3D by default. Image-space reprojection may be offered
as a 2D diagnostic mode inside the same reusable viewer. Primary evidence
viewers must provide the canonical expand/restore action.
@@ -326,3 +395,24 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
unchanged searches or model variants under a new name.
- Worker access/power/runtime authority comes from the owner's current session
instructions, never from the card or an old experiment's training allowance.
## Scene profile persistence — owner requirement, 2026-11-09
- Rover/battery materials, imported textures, scene/environment profiles, camera
pose, editor-window layout and battery UI/view settings are durable Core JSON
configuration. Use `data_dir/scene-profiles/.../meta.json`; never make browser
IndexedDB/localStorage their sole authority. Do not classify these files or
their recovery copies as cache or task scratch.
- Legacy browser records may be read once only when the Core document is absent.
A failed read must not save defaults over user settings. Preserve source data
during migration/recovery; use atomic replacement, previous-version backup and
revision checks so a stale tab cannot silently replace a newer profile.
- Recover actual settings from retained JSON/records before considering manual
reconstruction. Distinguish a proven storage defect from an unproven deletion
trigger, and state the timestamp/fidelity limit of any recovered source.
## Enforced compact typography
Operational values/section headings use md (13 px), explanatory/status/error copy uses Description/sm (12 px). Only canonical window/page title roles use title (18 px). Do not add browser-default paragraphs, local larger sizes, font shorthand or inline fontSize. Typography checks are mandatory build gates; never extend the frozen compact legacy baseline or generalize scene/display exceptions to satisfy a feature. Run the typography contract tests and verify computed sizes in centered/floating and narrow windows. See Design Guideline docs/OPERATIONAL_TYPOGRAPHY.md.
+11
View File
@@ -10,6 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
@@ -882,6 +883,16 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nodedc/bim-viewer": {
"version": "0.2.22",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"integrity": "sha512-Nl2PffhxaiSAdFZpHR5O2oYqxih/csC3fvIUl7EDnWWlDG7j1xKHtLo65suM9EaeAjx1GMUQsjTmF/I7VeI6Ow==",
"peerDependencies": {
"@nodedc/ui-react": "0.7.0",
"react": ">=19 <20",
"react-dom": ">=19 <20"
}
},
"node_modules/@nodedc/map-cesium-react": {
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"link": true
+4 -2
View File
@@ -6,14 +6,16 @@
"scripts": {
"dev": "vite",
"postinstall": "node scripts/install-rerun-navigation.mjs",
"prebuild": "node scripts/install-rerun-navigation.mjs",
"prebuild": "npm run check:typography && node scripts/install-rerun-navigation.mjs",
"build": "tsc -b && vite build",
"preview": "vite preview",
"test:unit": "node --test --test-concurrency=1 test/*.test.mjs",
"typecheck": "tsc -b --pretty false"
"typecheck": "tsc -b --pretty false",
"check:typography": "node --test test/operationalTypography.test.mjs"
},
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
Binary file not shown.
@@ -0,0 +1,132 @@
{
"source": "CATL_Battery_Enclosure_R05.blend",
"source_sha256": "8a3da0abaeeabc3a006dec51e2ae5a1af8af56b3b1361772279d7766084faea3",
"model": "catl-r04.glb",
"sha256": "7a01c35d7b8fac13e841053841e372170715c7b79b865f8719ab137b24d5cd20",
"bytes": 39916192,
"groups": 75,
"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/FRAME | welded graphite steel/FRAME | bottom cross front",
"bms/FRAME | welded graphite steel/FRAME | bottom cross rear",
"bms/FRAME | welded graphite steel/FRAME | bottom longitudinal left",
"bms/FRAME | welded graphite steel/FRAME | bottom longitudinal right",
"bms/FRAME | welded graphite steel/FRAME | post front left",
"bms/FRAME | welded graphite steel/FRAME | post front right",
"bms/FRAME | welded graphite steel/FRAME | post rear left",
"bms/FRAME | welded graphite steel/FRAME | post rear right",
"bms/FRAME | welded graphite steel/FRAME | top cross front",
"bms/FRAME | welded graphite steel/FRAME | top cross rear",
"bms/FRAME | welded graphite steel/FRAME | top longitudinal left",
"bms/FRAME | welded graphite steel/FRAME | top longitudinal right",
"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/FRAME | welded graphite steel",
"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}`);
}
}
+13 -12
View File
@@ -1,7 +1,7 @@
import {SceneDisplayControls} from "../../../packages/spatial-ui/src/SceneDisplayControls";
import {SceneLayerControls} from "../../../packages/spatial-ui/src/SceneLayerControls";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
import { Description,
AdminNavigationPanel,
AppHeader,
ApplicationPanel,
@@ -9,7 +9,6 @@ import {
Button,
ControlRow,
HeaderNavigation,
HeaderProfile,
Icon,
Inspector,
StatusBadge,
@@ -59,6 +58,7 @@ import {
type ObservationWorkspaceLayoutProfile,
} from "./core/observation/workspaceLayout";
import {
capabilityStatusLabel,
rootById,
roots,
workspaceById,
@@ -444,7 +444,7 @@ export default function App() {
workspace.openNavigation();
if (rootId === "system") {
workspace.openView(
activeDefinition?.root === "system" ? activeDefinition.id : "modules",
activeDefinition?.id === "vps" ? "vps" : "workers",
);
} else {
workspace.closeView();
@@ -666,7 +666,7 @@ export default function App() {
connectionScenarioResetting: runtime.pendingAction === "mode",
saveWorkspaceLayout,
workspaceLayoutSaving: workspaceLayoutProfile.state === "saving",
systemUtilityActions: computeContourSettings.utilityActions,
systemUtilityActions: [...computeContourSettings.utilityActions, {label: "К списку воркеров", icon: "chevron-left", onClick: () => openNavigationView("workers")}],
sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) },
});
@@ -687,7 +687,6 @@ export default function App() {
/>
}
right={
<HeaderProfile>
<UserProfileMenu
displayName="DC"
subtitle="Mission Core"
@@ -707,7 +706,6 @@ export default function App() {
},
]}
/>
</HeaderProfile>
}
/>
);
@@ -738,8 +736,8 @@ export default function App() {
navigation={currentRoot && activeRoot === "system" ? (
<SystemNavigationPanel
title={currentRoot.title}
onAdd={computeContourSettings.openCreate}
onNavigateRoot={() => openNavigationView("modules")}
activeId={activeDefinition?.id ?? "workers"}
onNavigate={openNavigationView}
onClose={workspace.closeNavigation}
/>
) : currentRoot ? (
@@ -786,9 +784,10 @@ export default function App() {
content={activeDefinition ? (
<ApplicationPanel
key={activeDefinition.id}
allowFullscreen={activeDefinition.kind === "vehicles"}
eyebrow={activeDefinition.eyebrow}
title={
activeDefinition.kind === "vehicles"
(activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects")
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
: activeDefinition.kind === "recordings"
&& replayPresented
@@ -835,7 +834,7 @@ export default function App() {
/>
) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
) : activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control
@@ -843,13 +842,15 @@ export default function App() {
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
) : activeDefinition.kind === "contour-health" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "workers" || activeDefinition.kind === "vps" ? (
<div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.root === "system" ? (
<SystemWorkspaceSelector
value={activeDefinition.id}
onChange={openNavigationView}
/>
) : (
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
<StatusBadge tone={activeDefinition.status === "active" ? "success" : "warning"}>{capabilityStatusLabel[activeDefinition.status ?? "contract"]}</StatusBadge>
)
}
utilityActions={contentActions}
@@ -1107,7 +1108,7 @@ export default function App() {
<i className="api-dot" data-status={effectiveSourceUrl ? "online" : "checking"} aria-hidden="true" />
{effectiveSourceUrl ? "Источник назначен" : "Источник не назначен"}
</span>
<p>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</p>
<Description>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</Description>
</div>
<SceneLayerControls sceneSettings={sceneSettings} pending={runtime.pendingAction === "viewer"} applyScenePatch={applyScenePatch}/>
</Window>
@@ -1,5 +1,6 @@
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
import { useLabStorageSettings } from "./storage/LabStorageSettings";
import { roots, workspaces, workspacesForRoot } from "../productModel";
interface Props {
@@ -16,7 +17,8 @@ const surfaces = environmentSurfaceIds.map(id => ({
actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id),
}));
export function EnvironmentSettingsWindow(props: Props) {
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet"
const storage = useLabStorageSettings(props.open);
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage]}
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
onUpload={(id, itemId, file) => {
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
@@ -1,4 +1,4 @@
import { LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react";
import { Description, LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react";
import type { BackendStatus, RuntimePhase } from "../core/runtime/contracts";
import type { EnvironmentPage } from "../core/environment/environmentSettings";
@@ -35,7 +35,7 @@ export function LandingStage({
<span className="section-eyebrow">ИСТОЧНИК</span>
<StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge>
</div>
<p>{message || "Выберите архитектурный блок в верхней навигации."}</p>
<Description>{message || "Выберите архитектурный блок в верхней навигации."}</Description>
</>}
footer={<>
<span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
@@ -1,4 +1,4 @@
import { GlassSurface } from "@nodedc/ui-react";
import { Description, GlassSurface } from "@nodedc/ui-react";
export interface MetricCardProps {
eyebrow: string;
@@ -16,7 +16,7 @@ export function MetricCard({ eyebrow, value, unit, detail, featured = false }: M
<strong>{value}</strong>
{unit ? <span>{unit}</span> : null}
</div>
<p>{detail}</p>
<Description>{detail}</Description>
</GlassSurface>
);
}
@@ -1,5 +1,5 @@
import { useState } from "react";
import { ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
import { Description, ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
import {
type ObservationSessionReplayLaunch,
@@ -279,16 +279,16 @@ export function ObservationSessionSelect({
description={deleteTarget ? <>
<strong>{deleteTarget.label}</strong>
{deleteTarget.lab ? (
<p>
<Description>
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
лабораторный результат останутся неизменными.
</p>
</Description>
) : (
<p>
<Description>
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
видеоматериалы будут удалены с этого сервера без возможности восстановления.
</p>
</Description>
)}
{sessions.error && sessions.deletingSessionId === null ? (
<p className="observation-session-delete-error" role="alert">{sessions.error}</p>
@@ -346,11 +346,11 @@ export function ObservationSessionArchive({
{labsOnly ? "ВОСПРОИЗВОДИМЫЕ ЛАБОРАТОРНЫЕ ЗАПИСИ" : "АРХИВ НАБЛЮДЕНИЯ"}
</span>
<h2>{labsOnly ? "Записанные лабораторные работы" : "Сохранённые сессии"}</h2>
<p>
<Description>
{labsOnly
? "Каждая запись связана с LAB-конфигурацией и открывается как самостоятельный визуальный результат."
: "Выберите запись: сцена и синхронные каналы откроются ниже, не меняя эфир наблюдения."}
</p>
</Description>
</div>
<button
type="button"
@@ -457,16 +457,16 @@ export function ObservationSessionArchive({
description={deleteTarget ? <>
<strong>{deleteTarget.label}</strong>
{deleteTarget.lab ? (
<p>
<Description>
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
лабораторный результат останутся неизменными.
</p>
</Description>
) : (
<p>
<Description>
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
видеоматериалы будут удалены с этого сервера без возможности восстановления.
</p>
</Description>
)}
</> : null}
confirmLabel="Удалить сессию"
@@ -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.
@@ -2263,7 +2200,7 @@ function RerunViewportInstance({
/>
) : null}
{presentationStatus === "loading" ? (
<div className="rerun-viewport__notice" role="status">
<div data-glass-context="scene" className="rerun-viewport__notice nodedc-viewport-surface" role="status">
<span className="busy-indicator" aria-hidden="true" />
<div>
<strong>
@@ -2280,7 +2217,7 @@ function RerunViewportInstance({
</div>
) : null}
{presentationStatus === "error" ? (
<div className="rerun-viewport__notice rerun-viewport__notice--error" role="alert">
<div data-glass-context="scene" className="rerun-viewport__notice rerun-viewport__notice--error nodedc-viewport-surface" role="alert">
<div>
<strong>Источник не открыт</strong>
<span>Проверьте локальный поток Rerun или повторите подключение.</span>
@@ -0,0 +1,23 @@
import {BatteryDesignSettings} from './BatteryDesignSettings';
import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Description,FeatureSettingsWindow,Icon,IconButton,RangeControl,SettingsCard} from '@nodedc/ui-react';
import {parseBatteryAppearance} from '../../core/batteryScene/appearance';
import type {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
import {BmsSettings} from '../../../../../plugins/jk-bms/frontend/src/BmsSettings';
type Section='markings'|'panels'|'diagnostics'|'protection'|'control';
export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?:SensorDetailProps;open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
const [section,setSection]=useState<Section>('markings'),input=useRef<HTMLInputElement>(null);
const {value,update}=profile,m=value.markings;
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:section==='markings'||section==='panels'?'Профиль Mission Core':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={(section==='markings'||section==='panels')&&<><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={(section==='markings'||section==='panels')&&<><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:'Не удалось прочитать профиль.');}}}/></>}>
{sensor&&section!=='markings'&&section!=='panels'?<BmsSettings {...sensor} section={section} open={open}/>: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>:<BatteryDesignSettings value={value} update={update}/>}
{(section==='markings'||section==='panels')&&<Description>Сохраняется в Mission Core для этой батареи. 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,2 @@
.battery-design-settings{display:grid;gap:var(--nodedc-space-4);min-width:0}
.battery-indicator-previews{display:flex;flex-wrap:wrap;align-items:center;gap:var(--nodedc-space-3)}
@@ -0,0 +1,40 @@
import {BatteryIndicator} from './BatteryIndicator';
import './BatteryDesignSettings.css';
import {useState} from 'react';
import {ColorField,ControlRow,Description,RangeControl,Select,SettingsCard} from '@nodedc/ui-react';
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;update:(value:BatteryAppearance)=>void}){
const [target,setTarget]=useState<'panels'|'indicator'>('panels');
const p=value.panels,i=value.indicator;
const panel=(patch:Partial<typeof p>)=>update({...value,panels:{...p,...patch}});
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
const indicator=(patch:Partial<typeof i>)=>update({...value,indicator:{...i,...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 color=(label:string,value:string,onChange:(v:string)=>void)=><ControlRow label={label}><ColorField label={label} value={value} onChange={onChange}/></ControlRow>;
return <div className="battery-design-settings"><Select label="Элемент дизайна" value={target} onChange={setTarget} options={[{value:'panels',label:'Плашки показаний'},{value:'indicator',label:'Индикатор в обсерватории'}]}/>
{target==='panels'?<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}))}
{color('Цвет текста',p.textColor,textColor=>panel({textColor}))}
{color('Цвет стекла',p.glass.tintHex,tintHex=>glass({tintHex}))}
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
</SettingsCard>:<SettingsCard title="Индикатор в обсерватории" description="Размеры, цвет заливки и диапазоны уровня заряда для этой батареи.">
{range('Ширина индикатора, px',i.width,32,320,width=>indicator({width}))}
{range('Высота индикатора, px',i.height,12,96,height=>indicator({height}))}
{range('Радиус углов индикатора, px',i.radius,0,48,radius=>indicator({radius}))}
{range('Отступ от кнопок шапки влево, px',i.offset,0,320,offset=>indicator({offset}))}
<Select label="Режим цвета индикатора" value={i.mode} onChange={mode=>indicator({mode})} options={[{value:'ranges',label:'По уровню заряда'},{value:'mono',label:'Один цвет'}]}/>
{i.mode==='mono'?color('Цвет индикатора',i.color,color=>indicator({color})):<>
{range('Низкий заряд ниже, %',i.lowUntil,0,99,lowUntil=>indicator({lowUntil,middleUntil:Math.max(i.middleUntil,lowUntil+1)}))}
{color('Низкий заряд',i.lowColor,lowColor=>indicator({lowColor}))}
{range('Средний заряд ниже, %',i.middleUntil,i.lowUntil+1,100,middleUntil=>indicator({middleUntil}))}
{color('Средний заряд',i.middleColor,middleColor=>indicator({middleColor}))}
{color('Высокий заряд',i.highColor,highColor=>indicator({highColor}))}
</>}
<Description>Чёрный или белый текст выбирается автоматически по цвету заливки. Предпросмотр:</Description>
<div className="battery-indicator-previews">{[10,25,80].map(soc=><BatteryIndicator key={soc} appearance={i} soc={soc} label="Предпросмотр заряда" valueText={`${soc}%`} disabled/>)}</div>
</SettingsCard>}</div>;
}
@@ -0,0 +1,6 @@
import {LevelButton,type LevelButtonProps} from '@nodedc/ui-react';
import {batteryIndicatorColor,type BatteryIndicatorAppearance} from '../../core/batteryScene/appearance';
type Props=Omit<LevelButtonProps,'value'|'fillColor'>&{appearance:BatteryIndicatorAppearance;soc:number|null};
export function BatteryIndicator({appearance,soc,style,...props}:Props){
return <LevelButton {...props} value={soc===null?null:soc/100} fillColor={batteryIndicatorColor(appearance,soc)} geometry={{width:appearance.width,height:appearance.height,radius:appearance.radius}} style={style}/>;
}
@@ -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} 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-модель батареи R05">
<SceneEditor scene={scene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v6-r05" 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,24 @@
import {useBatteryView} from '../../core/batteryScene/useBatteryView';
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
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,LoadingRegion,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
import {minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back,sensor,fullscreenControl}:{sensor?:SensorDetailProps;fullscreenControl?:{fullscreen:boolean;setFullscreen:(value:boolean)=>void};deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
const profile=useBatteryAppearance(deviceId,settings);
const view=useBatteryView(deviceId);const {height,setHeight,commitHeight}=view;
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 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}<LoadingRegion loading={!profile.ready||!view.ready} label="Загрузка настроек батареи">{profile.ready&&view.ready&&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>})}</LoadingRegion><BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error||view.error)?[{id:'battery-view-save',title:error||profile.error||view.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');view.setError('');}}/></>;
}
@@ -6,7 +6,6 @@ import {
useState,
} from "react";
import {
ActivityIndicator,
Button,
Checker,
ControlRow,
@@ -35,7 +34,9 @@ import {
import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay";
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
import { laboratoryResultRerunProfile } from "../../core/observation/viewerProfile";
import { resolveObservationSessionReplay } from "../../core/observation/useObservationSessions";
import { prepareLabReplay, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
import { LabReplayProgress } from "./LabReplayProgress";
import { announceLabStorageChange } from "../../core/storage/localLabStorage";
import type { AIViewerLayer } from "../../core/observatory/aiComposition";
import {
fetchLabViewProfile,
@@ -216,6 +217,7 @@ export function CanonicalResultRerunReplay({
const [viewerStatus, setViewerStatus] = useState<RerunViewportStatus>("idle");
const [launch, setLaunch] = useState<CanonicalReplayLaunch | null>(null);
const [launchError, setLaunchError] = useState<string | null>(null);
const [preparationProgress, setPreparationProgress] = useState<Progress>({ phase: "checking", fraction: null });
const sceneDraftRef = useRef(sceneDraft);
const previousSplitViewRef = useRef(splitView);
const trackedLaunchSha256Ref = useRef<string | null>(null);
@@ -275,15 +277,10 @@ export function CanonicalResultRerunReplay({
setPlayback(null);
setPlaybackController(null);
setViewerStatus("idle");
void resolveObservationSessionReplay(sessionId, {
signal: controller.signal,
maximumWaitMs: 30 * 60 * 1000,
onUpdate: () => undefined,
}).then(async (value) => ({
base: value,
replay: await resolveReplay(resultId, value, { signal: controller.signal }),
})).then((value) => {
if (!controller.signal.aborted) setLaunch(value);
void prepareLabReplay(resultId, sessionId, resolveReplay, {
signal: controller.signal, onProgress: setPreparationProgress,
}).then((value) => {
if (!controller.signal.aborted) { setLaunch(value); announceLabStorageChange(); }
}).catch((caught: unknown) => {
if (!controller.signal.aborted) {
setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна.");
@@ -465,7 +462,9 @@ export function CanonicalResultRerunReplay({
emptyMessage="Слои результата недоступны."
deckOverlays={presentationState === "loading" ? (
<div className="canonical-vegetation-rerun-replay__loading">
<ActivityIndicator label="Загружаем синхронизированную запись" />
<LabReplayProgress progress={launch
? { phase: "opening", fraction: playback?.bufferProgress ?? null }
: preparationProgress} />
</div>
) : undefined}
transport={transport}
@@ -0,0 +1,10 @@
import { Description, ProgressBar } from "@nodedc/ui-react";
import { labReplayProgressView, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
export function LabReplayProgress({ progress }: { progress: Progress }) {
const view = labReplayProgressView(progress);
return <div className="lab-replay-progress" aria-busy="true">
<Description role="status" aria-live="polite">{view.text}</Description>
<ProgressBar label={view.label} value={view.value} valueText={view.text} />
</div>;
}
@@ -1,3 +1,4 @@
import { Description } from '@nodedc/ui-react';
import {
forwardRef,
type CSSProperties,
@@ -915,7 +916,7 @@ LaboratoryMetricEvidenceSceneHandle,
return (
<div className="laboratory-metric-evidence-scene">
<div ref={hostRef} className="laboratory-metric-evidence-scene__viewport">
{renderError ? <p>{renderError}</p> : null}
{renderError ? <Description>{renderError}</Description> : null}
</div>
<div className="laboratory-metric-evidence-scene__legend">
{showRenderStats && renderStats ? (
@@ -1,5 +1,5 @@
import { useId, useState, type ReactNode } from "react";
import { Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react";
import { Description, Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react";
export interface LaboratoryOption<T extends string> {
id: T;
@@ -91,7 +91,7 @@ export function LaboratorySelector<T extends string>({
<div>
<span className="section-eyebrow">{eyebrow}</span>
<h2>{title}</h2>
<p>{description}</p>
<Description>{description}</Description>
</div>
<div className="laboratory-selector__control">
<span>{label}</span>
@@ -1,4 +1,4 @@
import { GlassSurface } from "@nodedc/ui-react";
import { Description, GlassSurface } from "@nodedc/ui-react";
import { CanonicalResultRerunReplay } from "./CanonicalResultRerunReplay";
import { resolveCanonicalLabReplay } from "../../core/laboratory/canonicalLabReplay";
import type { ObservatoryPortableResultReview } from "../../core/observatory/recordedRun";
@@ -38,7 +38,7 @@ export function PortableResultReplay({
&& (moduleId === "rf-detr" || moduleId === "object-distance");
if (!tgs && !semantics && !objects) return (
<GlassSurface className="observatory-replay-state" padding="lg">
<p role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</p>
<Description role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</Description>
</GlassSurface>
);
return <CanonicalResultRerunReplay key={review.resultId} resultId={review.resultId}
@@ -1,20 +1,20 @@
import { Button, LoadingRegion, Window } from "@nodedc/ui-react";
import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
import type { RouteCheck } from "../../core/missions/planner";
export function MissionCheckWindow({ open, onClose, busy, error, report, run }: {
open: boolean; onClose: () => void; busy: boolean; error: string | null; report: RouteCheck | null; run: () => void;
}) {
return <Window open={open} title="Проверка маршрута" size="md" onClose={onClose}><div className="mission-planner__check">
<p>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</p>
<Description>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</Description>
<LoadingRegion loading={busy} label="Проверка исходных данных">
{error && <p role="alert">{error}</p>}
{error && <Description role="alert">{error}</Description>}
{report && <><dl>
<div><dt>Исходная запись</dt><dd>{report.source_verified ? "Контрольные суммы совпадают" : "Недоступна"}</dd></div>
<div><dt>Версия черновика</dt><dd>{report.revision}</dd></div>
<div><dt>Длина маршрута</dt><dd>{report.length_m.toFixed(2)} м</dd></div>
<div><dt>Положения сканера</dt><dd>{report.pose_count.toLocaleString("ru-RU")}</dd></div>
<div><dt>Максимальный шаг</dt><dd>{report.max_step_m.toFixed(2)} м</dd></div></dl>
{report.warnings.map(w => <p key={w}>{w}</p>)}
<p>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</p></>}
{report.warnings.map(w => <Description key={w}>{w}</Description>)}
<Description>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</Description></>}
<Button disabled={busy} onClick={run}>{report ? "Повторить проверку" : "Начать проверку"}</Button>
</LoadingRegion>
</div></Window>;
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from "react";
import { RangeControl } from "@nodedc/ui-react";
import { Description, RangeControl } from "@nodedc/ui-react";
import { routeLength, type PlanningPose, type PlanningSource } from "../../core/missions/planner";
/** Equal-axis plan projection; the moving marker is an archive pose, not localization. */
export function MissionRoutePreview({ source, poses }: { source: PlanningSource; poses: PlanningPose[] }) {
@@ -22,8 +22,8 @@ export function MissionRoutePreview({ source, poses }: { source: PlanningSource;
<polyline points={projection.selected} className="mission-route-preview__selected" fill="none" />
<circle cx={x} cy={y} r="6" className="mission-route-preview__cursor" />
<path d="M40 450h100" className="mission-route-preview__selected" /><text x="40" y="438">{(100 / projection.scale).toFixed(1)} м</text>
</svg><p>Путь: {routeLength(poses).toFixed(2)} м · {poses.length.toLocaleString("ru-RU")} положений · X/Y, масштаб осей одинаковый</p>
</svg><Description>Путь: {routeLength(poses).toFixed(2)} м · {poses.length.toLocaleString("ru-RU")} положений · X/Y, масштаб осей одинаковый</Description>
<RangeControl label="Положение на маршруте" value={Math.min(cursor, poses.length - 1) + 1} min={1} max={poses.length} step={1} formatValue={n => `${n} / ${poses.length}`} onChange={n => setCursor(n - 1)} />
<p>Кадр {point.index + 1} · X {point.position[0].toFixed(2)} · Y {point.position[1].toFixed(2)} · Z {point.position[2].toFixed(2)} м</p>
<Description>Кадр {point.index + 1} · X {point.position[0].toFixed(2)} · Y {point.position[1].toFixed(2)} · Z {point.position[2].toFixed(2)} м</Description>
</div>;
}
@@ -1,5 +1,5 @@
import type {ReactNode} from 'react';
import {Button, StatusBadge} from '@nodedc/ui-react';
import { Description,Button, StatusBadge} from '@nodedc/ui-react';
import {planningAwaitsCapture, usePlanningTest} from '../../core/missions/PlanningTestContext';
/** Composition-level handoff; never sends a device or acquisition command. */
@@ -12,9 +12,9 @@ export function PlanningCaptureGuard({enabled, onResume, children}: {
if (!enabled || !planningAwaitsCapture(planning.test)) return <>{children}</>;
return <div className="mission-planner__check">
<StatusBadge tone="warning">Исследование ожидает новую запись</StatusBadge>
<p>{planning.test!.draft.name}</p>
<p>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</p>
{planning.error && <p role="alert">{planning.error}</p>}
<Description>{planning.test!.draft.name}</Description>
<Description>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</Description>
{planning.error && <Description role="alert">{planning.error}</Description>}
<div className="mission-planner__actions">
<Button loading={planning.busy} onClick={() => void planning.finish()}>Завершить исследование</Button>
<Button disabled={planning.busy} onClick={onResume}>Вернуться к исследованию</Button>
@@ -1,5 +1,5 @@
import {useEffect,useState,type ReactNode} from 'react';
import {Button,LoadingRegion,StatusBadge,Window} from '@nodedc/ui-react';
import { Description,Button,LoadingRegion,StatusBadge,Window} from '@nodedc/ui-react';
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
import {planningTestTerminal,usePlanningTest} from '../../core/missions/PlanningTestContext';
@@ -15,17 +15,17 @@ export function PlanningConnectionWindow({children}:{children:ReactNode}){
if(!p.test)return <>{children}</>;
const t=p.test, terminal=planningTestTerminal(t);
const details=<><StatusBadge tone="neutral">Профиль · Планирование</StatusBadge>
<p>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</p>
<p>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</p></>;
<Description>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</Description>
<Description>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</Description></>;
return <div className="mission-planner__check">
{details}<p>{t.message}</p>{p.error&&<p role="alert">{p.error}</p>}
{details}<Description>{t.message}</Description>{p.error&&<Description role="alert">{p.error}</Description>}
<div className="mission-planner__actions"><Button onClick={()=>setOpen(true)}>Подключение сканера</Button>
{t.state==='running'&&t.planning_phase==='lost'&&!t.tracking_established&&<Button loading={p.busy} onClick={()=>void p.retryInitialization()}>Переинициализировать</Button>}
{!terminal&&<Button loading={p.busy} onClick={()=>void p.finish()}>Завершить исследование</Button>}</div>
<Window open={open} title="Подключение сканера · Планирование" size="lg" className="planning-connection" onClose={()=>setOpen(false)}>
<div className="mission-planner__check">{details}
{t.state==='preparing'?<LoadingRegion loading label="Подготовка эталонного участка" />
: terminal?<p>{t.message}</p>:children}
: terminal?<Description>{t.message}</Description>:children}
</div>
</Window>
</div>;
@@ -1,11 +1,11 @@
import { Inspector, Icon, StatusBadge } from '@nodedc/ui-react';
import { Description, Inspector, Icon, StatusBadge } from '@nodedc/ui-react';
import { planningProjectStatus, type PlanningProjectDetail } from '../../core/missions/planningProjects';
export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail}) {
const r=p.result;
return <Inspector variant="panel" defaultOpen={['sources','result']} sections={[
{id:'sources',label:'Проект',icon:<Icon name="file"/>,content:<div className="inspector-control-stack">
<p>{p.name}</p><small>{new Date(p.created_at_utc).toLocaleString('ru-RU')}</small>
<Description>{p.name}</Description><small>{new Date(p.created_at_utc).toLocaleString('ru-RU')}</small>
<dl><div><dt>Эталон</dt><dd>{p.reference_label}</dd></div><div><dt>Повторный проход</dt><dd>{p.query_label??'—'}</dd></div>
<div><dt>Участок эталона</dt><dd>{p.draft.route.length_m.toFixed(2)} м</dd></div></dl>
</div>},
@@ -15,7 +15,7 @@ export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail
<div><dt>Расхождение поверхностей</dt><dd>{r.inlier_rmse_m==null?'—':`${r.inlier_rmse_m.toFixed(3)} м`}</dd></div>
{r.correction_m!=null&&<div><dt>Уточнение привязки</dt><dd>{r.correction_m.toFixed(2)} м · {r.correction_deg.toFixed(1)}°</dd></div>}
{r.registration_seconds!=null&&<div><dt>Расчёт</dt><dd>{r.registration_seconds.toFixed(2)} с</dd></div>}
</dl><small>Совпадение поверхностей не является измеренной точностью положения.</small></>:<p>{p.message?`Сохранённое сообщение: ${p.message}`:'Расчёт совмещения ещё не выполнен.'}</p>}
</dl><small>Совпадение поверхностей не является измеренной точностью положения.</small></>:<Description>{p.message?`Сохранённое сообщение: ${p.message}`:'Расчёт совмещения ещё не выполнен.'}</Description>}
{p.evidence_relation==='same_recording'&&<small>Оба участка из одной записи: внутренняя проверка общей карты.</small>}
{p.scene_note&&p.scene_url&&<small>{p.scene_note}</small>}
{r?.reasons.map(reason=><small key={reason}>{reason}</small>)}
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { ConfirmationModal, Icon, Select, ToastStack } from '@nodedc/ui-react';
import { Description, ConfirmationModal, Icon, Select, ToastStack } from '@nodedc/ui-react';
import { planningProjectDeletable, planningProjectStatus, type PlanningProject } from '../../core/missions/planningProjects';
export function PlanningProjectSelect({items, value, disabled, onChange, onRemove}: {
@@ -29,8 +29,8 @@ export function PlanningProjectSelect({items, value, disabled, onChange, onRemov
<ConfirmationModal open={target !== null} title="Удалить совмещённый маршрут?"
description={target ? <>
<strong>{target.name}</strong>
<p>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</p>
<p>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</p>
<Description>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</Description>
<Description>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</Description>
</> : null}
confirmLabel="Удалить маршрут" pendingLabel="Удаление…" danger
onClose={() => { if (!busy) setTarget(null); }}
@@ -1,4 +1,4 @@
import { Button, Icon, Inspector, InspectorSelectField, TextField } from '@nodedc/ui-react';
import { Description, Button, Icon, Inspector, InspectorSelectField, TextField } from '@nodedc/ui-react';
import { routeLength, canStartPlanningRoute } from '../../core/missions/planner';
import type { useMissionPlanner } from '../../core/missions/useMissionPlanner';
@@ -24,7 +24,7 @@ export function PlanningProjectSettings({p,onStart,starting}:{
<div className="inspector-control-stack">
{p.source&&!routeReady&&<small>В записи недостаточно перемещения для привязки. Выберите другой эталон.</small>}
<Button variant="primary" loading={starting} disabled={disabled||!p.ready||!routeReady} onClick={onStart}><Icon name="play"/>Начать новый проход</Button>
{p.error&&<p role="alert">{p.error}</p>}
{p.error&&<Description role="alert">{p.error}</Description>}
</div>
</>;
}
@@ -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,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'}){
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((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <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>;
}
@@ -0,0 +1,47 @@
import {useEffect,useRef,useState} from 'react';
import {Description,Icon} from '@nodedc/ui-react';
import type {SpeedMeasurement} from '../../../../../packages/router-ui/src/contracts';
import {speedFraction,speedPoint,speedTrack,speedValues} from './speedGauge';
import './routerSpeedGauge.css';
function useMarker(target:number){
const [position,setPosition]=useState(target),last=useRef(target);
useEffect(()=>{
if(window.matchMedia('(prefers-reduced-motion: reduce)').matches){last.current=target;setPosition(target);return;}
const start=performance.now(),from=last.current;let frame=0;
function animate(now:number){const t=Math.min(1,(now-start)/650),next=from+(target-from)*(1-Math.pow(1-t,3));last.current=next;setPosition(next);if(t<1)frame=requestAnimationFrame(animate);}
frame=requestAnimationFrame(animate);return()=>cancelAnimationFrame(frame);
},[target]);
return position;
}
const format=(n:number|null)=>n===null?'—':new Intl.NumberFormat('ru-RU',{maximumFractionDigits:1}).format(n/1e6);
export function RouterSpeedGauge({measurement,waiting,fresh}:{measurement?:SpeedMeasurement;waiting:boolean;fresh:boolean}){
const {down,up}=speedValues(measurement),phase=measurement?.phase;
const running=phase==='download'||phase==='upload';
const [clock,setClock]=useState(Date.now());
useEffect(()=>{if(!running)return;const timer=setInterval(()=>setClock(Date.now()),1000);return()=>clearInterval(timer);},[running]);
const stale=running&&(!fresh||!!measurement?.sampled_at&&clock-measurement.sampled_at>6000);
const ceiling=Math.max(down??0,up??0)>1e9?1e10:1e9;
const active=phase==='upload'?up:down;
const marker=speedPoint(useMarker(speedFraction(active??0,ceiling)));
const secondary=speedPoint(speedFraction(up??0,ceiling));
const state=waiting?'Подготовка замера':stale?'Ожидаем данные борта':phase==='latency'?'Проверяем задержку':phase==='download'?'Измеряем приём':phase==='upload'?'Измеряем передачу':phase==='complete'?'Замер завершён':phase==='cancelled'?'Замер остановлен':phase==='error'?'Замер не завершён':'Готов к замеру';
const caption=phase==='download'||phase==='upload'?'Текущая средняя · Мбит/с':'Мбит/с';
return <div className="router-speed-visual"><div className="router-speed-state"><Description role="status">{state}</Description></div><figure className="router-speed-gauge" aria-label={`Скорость соединения. ${state}. Приём ${format(down)}, передача ${format(up)} Мбит/с.`}>
<svg viewBox="0 0 720 280" aria-hidden="true" className={stale?'router-speed-instrument is-stale':'router-speed-instrument'}>
<path d={speedTrack} className="router-speed-track"/>
{Array.from({length:121},(_,i)=>{const p=speedPoint(i/120),lit=active!==null&&i/120<=speedFraction(active,ceiling);return <line key={i} x1={p.x} y1={p.y} x2={p.x+p.nx*12} y2={p.y+p.ny*12} className={lit?'router-speed-tick is-lit':'router-speed-tick'}/>;})}
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <line key={n} x1={p.x} y1={p.y} x2={p.x+p.nx*22} y2={p.y+p.ny*22} className="router-speed-major"/>;})}
{active!==null&&<g className="router-speed-marker"><circle cx={marker.x} cy={marker.y} r="11" className="router-speed-halo"/><circle cx={marker.x} cy={marker.y} r="4"/></g>}
{phase==='complete'&&up!==null&&<circle cx={secondary.x} cy={secondary.y} r="5" className="router-speed-upload-marker"/>}
</svg>
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <span key={n} className="router-speed-scale" style={{left:`${(p.x-p.nx*22)/720*100}%`,top:`${(p.y-p.ny*22)/280*100}%`}}>{n*(ceiling/1e9)}</span>;})}
<figcaption className="router-speed-center">
<div className="router-speed-readings">
<div data-active={phase==='download'}><span><Icon name="download"/> Приём</span><strong>{format(down)}</strong></div>
<div data-active={phase==='upload'}><span><Icon name="upload"/> Передача</span><strong>{format(up)}</strong></div>
</div>
<Description>{caption}</Description>
</figcaption>
</figure></div>;
}
@@ -0,0 +1,20 @@
.router-speed-visual{margin:8px 0}.router-speed-state{text-align:center}
.router-speed-gauge{position:relative;width:100%;max-width:600px;aspect-ratio:18/7;margin:0 auto;isolation:isolate;color:var(--nodedc-text-primary)}
.router-speed-instrument{display:block;width:100%;height:100%;overflow:visible}
.router-speed-track{fill:none;stroke:currentColor;stroke-width:1;opacity:.06}
.router-speed-tick{stroke:currentColor;stroke-width:1.4;stroke-linecap:round;opacity:.18;transition:opacity 450ms ease}
.router-speed-tick.is-lit{opacity:.8}
.router-speed-major{stroke:currentColor;stroke-width:1.5;stroke-linecap:round;opacity:.5}
.router-speed-marker{fill:currentColor}
.router-speed-halo{opacity:.1}
.router-speed-upload-marker{fill:none;stroke:var(--nodedc-text-muted);stroke-width:2}
.router-speed-instrument.is-stale{opacity:.45}
.router-speed-scale{position:absolute;transform:translate(-50%,-50%);font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-muted);font-variant-numeric:tabular-nums}
.router-speed-center{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:52%;display:grid;gap:12px;text-align:center}
.router-speed-readings{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.router-speed-readings>div{display:grid;gap:8px}
.router-speed-readings span{display:flex;align-items:center;justify-content:center;gap:6px;color:var(--nodedc-text-muted);font-size:var(--nodedc-font-size-sm)}
.router-speed-readings strong{font-size:var(--nodedc-font-size-md);font-weight:600;font-variant-numeric:tabular-nums}
.router-speed-readings [data-active=true] span{color:var(--nodedc-text-primary)}
@media(max-width:600px){.router-speed-gauge{margin:8px auto}.router-speed-center{gap:6px;width:58%}.router-speed-readings{gap:8px}.router-speed-readings>div{gap:4px}.router-speed-scale{font-size:var(--nodedc-font-size-xs)}}
@media(prefers-reduced-motion:reduce){.router-speed-tick{transition:none}}
@@ -0,0 +1,21 @@
/** Geometry of the router speed instrument. Values stay measured, only the marker interpolates. */
export function speedFraction(bps:number,ceiling=1e9){
return Math.log1p(Math.max(0,Math.min(ceiling,bps))/(ceiling/100))/Math.log(101);
}
export function speedPoint(fraction:number){
const radius=95,left=142,right=578,top=45,bottom=235,tail=143,straight=right-left;
let d=Math.max(0,Math.min(1,fraction))*(tail*2+Math.PI*radius*2+straight);
if(d<=tail)return{x:285-d,y:bottom,nx:0,ny:1};d-=tail;
if(d<=Math.PI*radius){const a=Math.PI/2+d/radius;return{x:left+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
if(d<=straight)return{x:left+d,y:top,nx:0,ny:-1};d-=straight;
if(d<=Math.PI*radius){const a=-Math.PI/2+d/radius;return{x:right+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
return{x:right-d,y:bottom,nx:0,ny:1};
}
export const speedTrack='M285 235 H142 A95 95 0 0 1 142 45 H578 A95 95 0 0 1 578 235 H435';
export function speedValues(m:{phase:string;current_bps?:number;sampled_at?:number;download_bps:number;upload_bps:number}|undefined){
if(!m)return{down:null,up:null};
if(m.phase==='complete')return{down:m.download_bps,up:m.upload_bps};
if(m.phase==='download')return{down:m.sampled_at?m.current_bps??null:null,up:null};
if(m.phase==='upload')return{down:m.download_bps,up:m.sampled_at?m.current_bps??null:null};
return{down:null,up:null};
}
@@ -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); }
@@ -0,0 +1,29 @@
import { useState } from "react";
import { Description, ConfirmationModal, Icon, IconButton } from "@nodedc/ui-react";
import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs";
import { deleteFailedRunProjection } from "../../core/observatory/failedRunHistory";
export function FailedRunActions({ job, onDeleted }: {
job: ObservatoryRecordedJob;
onDeleted: () => void;
}) {
const [open, setOpen] = useState(false);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
return <>
<IconButton label="Удалить ошибочную попытку" onClick={() => { setError(null); setOpen(true); }}>
<Icon name="trash" size={16} />
</IconButton>
<ConfirmationModal open={open} title="Удалить ошибочную попытку?"
description={<><Description>Попытка и её рабочие файлы будут удалены с этого устройства и Worker. Исходная запись сохранится.</Description>
{error ? <Description role="alert">{error}</Description> : null}</>}
confirmLabel="Удалить попытку" pendingLabel="Удаляем…" danger
onClose={() => { if (!pending) setOpen(false); }}
onConfirm={async () => {
setPending(true); setError(null);
try { await deleteFailedRunProjection(job); setOpen(false); onDeleted(); }
catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось удалить попытку."); }
finally { setPending(false); }
}} />
</>;
}
@@ -0,0 +1,71 @@
import { useEffect, useRef, useState } from "react";
import { ConfirmationModal, Icon, IconButton, ToastStack, type ToastItem } from "@nodedc/ui-react";
import { announceLabStorageChange, pinLabCopy, prepareLocalLabCopy, removeLabCopy,
type LocalLabCopy } from "../../core/storage/localLabStorage";
import { formatLocalLabSize } from "../../core/storage/localLabPresentation";
import type { LabReplayProgress } from "../../core/laboratory/prepareLabReplay";
export type LabCopyProgress = LabReplayProgress;
export function LabCopyActions({ id, sourceId, composition = false, copy, available, storageError, onProgress }: {
id: string; sourceId: string; composition?: boolean; copy?: LocalLabCopy;
available: boolean; storageError: string | null;
onProgress?: (value: LabReplayProgress | null) => void;
}) {
const [busy, setBusy] = useState<"download" | "pin" | "remove" | null>(null);
const [toasts, setToasts] = useState<ToastItem[]>([]);
const [confirm, setConfirm] = useState(false);
const request = useRef<AbortController | null>(null);
const progressCallback = useRef(onProgress);
progressCallback.current = onProgress;
useEffect(() => () => { request.current?.abort(); progressCallback.current?.(null); }, []);
const status = storageError ?? (!available ? "Проверяем локальную копию"
: copy?.local ? `На этом устройстве · ${formatLocalLabSize(copy, true)}`
: "Загрузить запись на это устройство");
async function perform(kind: "download" | "pin" | "remove", action: (signal: AbortSignal) => Promise<unknown>) {
if (request.current) return;
const controller = new AbortController(); request.current = controller;
setBusy(kind); setToasts([]);
try {
await action(controller.signal);
if (!controller.signal.aborted) setConfirm(false);
} catch (reason) {
if (!controller.signal.aborted) setToasts([{ id: "lab-copy-error", tone: "error",
title: "Не удалось изменить локальную копию",
description: reason instanceof Error ? reason.message : "Повторите действие." }]);
} finally {
announceLabStorageChange();
progressCallback.current?.(null);
request.current = null;
if (!controller.signal.aborted) setBusy(null);
}
}
const prepare = (signal: AbortSignal) => prepareLocalLabCopy(id, sourceId, composition,
{ signal, onProgress: (value) => progressCallback.current?.(value) });
const unavailable = !available || !!storageError;
return <>
<IconButton label={status} loading={busy === "download"}
disabled={!!busy || unavailable || !!copy?.local}
onClick={() => void perform("download", prepare)}>
<Icon name={copy?.local ? "database" : "download"} size={16} />
</IconButton>
<IconButton label={copy?.pinned ? "Открепить локальную запись" : "Оставить полную запись на этом устройстве"}
aria-pressed={copy?.pinned ?? false} loading={busy === "pin"} disabled={!!busy || unavailable}
onClick={() => void perform("pin", async (signal) => {
if (!copy?.local && !copy?.pinned) await prepare(signal);
signal.throwIfAborted();
await pinLabCopy(id, !copy?.pinned);
})}>
<Icon name="pin" size={16} />
</IconButton>
{copy?.local ? <IconButton label="Удалить только локальную копию" loading={busy === "remove"}
disabled={!!busy || copy.pinned || unavailable} onClick={() => setConfirm(true)}>
<Icon name="minus" size={16} />
</IconButton> : null}
<ToastStack items={toasts} onDismiss={(key) => setToasts((items) => items.filter((item) => item.id !== key))} />
<ConfirmationModal open={confirm} title="Удалить локальную копию?"
description="Результат и история запуска останутся. Копию можно вернуть кнопкой загрузки или открытием просмотра."
confirmLabel="Удалить копию" cancelLabel="Отмена" onClose={() => { if (!busy) setConfirm(false); }}
onConfirm={() => perform("remove", () => removeLabCopy(id))} />
</>;
}
@@ -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,5 +1,5 @@
import {createPortal} from 'react-dom';
import {Button,StatusBadge} from '@nodedc/ui-react';
import { Description,Button,StatusBadge} from '@nodedc/ui-react';
import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import './roverLogs.css';
@@ -11,11 +11,11 @@ export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:Obse
<div className="rover-logs">
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{capture.state.local_capture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal()}>Сохранить с компьютера</Button>}</div>
<p>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</p>
{storage?.file&&<p title={storage.file}>{storage.file}</p>}
{failed&&<p role="alert">Файл может быть неполным: {failed}</p>}
<p>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</p>
{capture.state.local_capture?.id&&<p>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</p>}
<Description>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</Description>
{storage?.file&&<Description title={storage.file}>{storage.file}</Description>}
{failed&&<Description role="alert">Файл может быть неполным: {failed}</Description>}
<Description>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</Description>
{capture.state.local_capture?.id&&<Description>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</Description>}
<div className="rover-logs__entries" role="log" aria-live="off" aria-label="События DEV-сессии">
{[...capture.rows].reverse().map(item=>{const row=item.record??item;return <pre key={item.record_sequence}>{JSON.stringify(row,null,2)}</pre>;})}
</div>
@@ -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 { Description,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,10 +56,11 @@ 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>}
</LoadingRegion>:<div className="rover-view__empty"><Description>Выберите модель аппарата.</Description><Button onClick={showSettings}>Настройки вида</Button></div>}
{c.ready&&!editing&&<div className="rover-view__controls">
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
@@ -69,15 +72,16 @@ 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)}))}/>
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
<Description>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</Description>
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button>
</div></Window>
@@ -0,0 +1,16 @@
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})}/>
<RangeControl label="Контраст градиента" value={value.contrast} min={.1} max={4} step={.01} exactValueBounds={{min:.1,max:4}} onChange={contrast=>patch({contrast})}/>
<RangeControl label="Насыщенность градиента" value={value.saturation} min={0} max={2} step={.01} exactValueBounds={{min:0,max:2}} onChange={saturation=>patch({saturation})}/>
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
</div>;
}
@@ -0,0 +1,10 @@
import {useState} from 'react';
import {Button,Description,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function DuplicateMaterialDialog({initialName,onDuplicate,onClose}:{initialName:string;onDuplicate:(name:string)=>void;onClose:()=>void}){
const [name,setName]=useState(initialName),[error,setError]=useState('');
const save=()=>{try{onDuplicate(name);onClose();}catch(e){setError(e instanceof Error?e.message:'Не удалось создать копию материала.');}};
return <Window open title="Дублировать материал" size="sm" onClose={onClose} footer={<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button variant="primary" tone="neutral" disabled={!name.trim()} onClick={save}>Создать дубликат</Button></WindowFooterActions>}>
<TextField label="Название дубликата" autoFocus maxLength={120} value={name} onChange={e=>{setName(e.target.value);setError('');}} onKeyDown={e=>{if(e.key==='Enter'&&!e.nativeEvent.isComposing&&name.trim()){e.preventDefault();save();}}}/>
{error&&<Description role="alert">{error}</Description>}
</Window>;
}
@@ -1,11 +1,13 @@
import {EnvironmentProfiles} from './EnvironmentProfiles';
import type {ReactNode} from 'react';
import {LutField} from './LutField';
import {useRef} from 'react';
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
export function EnvironmentInspector({document,onChange,onResetCamera,onError,update,sceneFiles}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;sceneFiles:ReactNode;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
const groups=[...new Set(environmentFields.map(f=>f.group))];
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>;
return <Inspector defaultOpen={['profiles']} sections={[{id:'profiles',label:'Профили',content:<><EnvironmentProfiles document={document} update={update} onError={onError}/><Inspector sections={[{id:'scene-json',label:'Вся сцена · JSON',content:sceneFiles}]}/></>},...groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))]}/>;
}
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
@@ -17,7 +19,7 @@ function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
}
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){
export function SceneFileActions({onImport,onExport}:{onImport:(file:File)=>void;onExport:()=>void}){
const input=useRef<HTMLInputElement>(null);
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт всей сцены</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт всей сцены</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
}
@@ -0,0 +1,33 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Description,InspectorSelectField,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
import {applyEnvironment,builtinEnvironment,environmentMatches,parseEnvironmentProfile,sceneEnvironment,type EnvironmentProfile,type StoredEnvironmentProfile} from '../../../core/roverScene/environmentProfiles';
import {readEnvironmentProfiles,saveEnvironmentProfile,watchEnvironmentProfiles} from '../../../core/roverScene/environmentProfileStorage';
import type {SceneDocument} from '../../../core/roverScene/sceneDocument';
export function EnvironmentProfiles({document:doc,update,onError}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;onError:(message:string)=>void}){
const [profiles,setProfiles]=useState<StoredEnvironmentProfile[]>([]),[ready,setReady]=useState(false),[pending,setPending]=useState(false),[draft,setDraft]=useState<EnvironmentProfile|null>(null),[name,setName]=useState('');
const input=useRef<HTMLInputElement>(null),mounted=useRef(true);
useEffect(()=>{mounted.current=true;let generation=0;const refresh=()=>{const current=++generation;readEnvironmentProfiles().then(value=>{if(mounted.current&&current===generation){setProfiles(value);setReady(true);}}).catch(e=>{if(mounted.current&&current===generation)onError(e instanceof Error?e.message:'Не удалось прочитать профили.');});};refresh();const stop=watchEnvironmentProfiles(refresh);return()=>{mounted.current=false;stop();};},[onError]);
const builtin=builtinEnvironment(),all=[builtin,...profiles],id=doc.environmentProfileId??(environmentMatches(doc,builtin.environment)?builtin.id:'current'),selected=all.find(p=>p.id===id);
const dirty=!selected||!environmentMatches(doc,selected.environment);
const current=():EnvironmentProfile=>({schema:'missioncore.environment-profile/v1',name:selected?.name??'Мой профиль',environment:sceneEnvironment(doc)});
const begin=(value=current())=>{setDraft(value);setName(value.name==='NodeDC'?'Мой профиль':value.name);};
const save=async(copy:boolean)=>{
const source=copy?draft:current();if(!source||(!copy&&!selected))return;setPending(true);
try{const saved=await saveEnvironmentProfile({...source,name:copy?name:source.name,id:copy?`env/${crypto.randomUUID()}`:selected!.id,revision:0},copy?null:selected!.revision);
if(mounted.current){setProfiles(previous=>[...previous.filter(p=>p.id!==saved.id),saved]);if(copy){update(d=>applyEnvironment(d,saved));setDraft(null);}else update(d=>d.environmentProfileId===saved.id?d:{...d,environmentProfileId:saved.id});}
}catch(e){onError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{if(mounted.current)setPending(false);}
};
const exportJson=()=>{const value=current(),url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=globalThis.document.createElement('a');a.href=url;a.download='environment-profile.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return <div className="rover-scene-fields">
<InspectorSelectField label="Профиль окружения" value={id} disabled={!ready||pending} options={[...(!selected?[{value:id,label:'Текущие настройки · без сохранённого профиля'}]:[]),...all.map(p=>({value:p.id,label:p.name}))]} onChange={value=>{const profile=all.find(p=>p.id===value);if(profile)update(d=>applyEnvironment(d,profile));}}/>
<Description>{dirty?'Есть изменения относительно профиля. Настройки сцены сохраняются автоматически.':'Настройки совпадают с профилем.'}</Description>
<div className="rover-scene-actions"><Button size="compact" disabled={!ready||!selected||selected.id===builtin.id||pending||!dirty} loading={pending&&!draft} onClick={()=>void save(false)}>Пересохранить профиль</Button><Button size="compact" disabled={!ready||pending} onClick={()=>begin()}>Сохранить как…</Button></div>
<div className="rover-scene-actions"><Button size="compact" onClick={exportJson}>Экспорт JSON</Button><Button size="compact" disabled={!ready||pending} onClick={()=>input.current?.click()}>Импорт JSON</Button></div>
<Description>Библиотека общая для сцен в Mission Core. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
<input ref={input} type="file" hidden accept=".json,application/json" onChange={async e=>{const f=e.currentTarget.files?.[0];e.currentTarget.value='';if(!f)return;try{if(f.size>2_000_000)throw new Error('Профиль больше 2 МБ.');const value=parseEnvironmentProfile(JSON.parse(await f.text()));if(mounted.current)begin(value);}catch(error){onError(error instanceof Error?error.message:'Не удалось импортировать профиль.');}}}/>
<Window open={!!draft} onClose={()=>{if(!pending)setDraft(null);}} title="Сохранить профиль окружения" size="sm" footer={<WindowFooterActions><Button disabled={pending} onClick={()=>setDraft(null)}>Отмена</Button><Button variant="primary" loading={pending} disabled={!name.trim()} onClick={()=>void save(true)}>Сохранить</Button></WindowFooterActions>}>
<TextField label="Название профиля" value={name} maxLength={80} disabled={pending} onChange={e=>setName(e.target.value)}/>
<Description>Профиль будет доступен для батареи, ровера и других сцен.</Description>
</Window>
</div>;
}
@@ -1,17 +1,20 @@
import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
]}/><Button onClick={onReset}>Исходный материал</Button></>;
}
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
import {useState} from 'react';
import {DuplicateMaterialDialog} from './DuplicateMaterialDialog';
import {Description,Inspector,InspectorSelectField,TextField,Button} from '@nodedc/ui-react';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {ChargeGradientInspector} from './ChargeGradientInspector';
import {MaterialSurfaceInspector} from './MaterialSurfaceInspector';
export type MaterialPreview='auto'|'active'|'inactive';
export function MaterialInspector({material,onChange,onDuplicate,copyName,selectionDescription,onError,preview='auto',onPreview}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onDuplicate:(name:string)=>void;copyName:string;selectionDescription:string;onError:(message:string)=>void;preview?:MaterialPreview;onPreview?:(value:MaterialPreview)=>void}){
const gradient=material.chargeGradient,[duplicate,setDuplicate]=useState(false);
const header=<><Description>{selectionDescription}</Description><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><Description>Изменения применяются ко всем деталям с этим материалом.</Description>
{gradient&&<InspectorSelectField label="Предпросмотр материала" value={preview} options={[{value:'auto',label:'По данным BMS'},{value:'active',label:'Активный · градиент'},{value:'inactive',label:'Неактивный · без данных'}]} onChange={v=>onPreview?.(v as MaterialPreview)}/>}
{gradient&&preview==='active'&&<Description>Предпросмотр градиента: текущий заряд, а при отсутствии показаний — 50%.</Description>}</>;
const footer=<Button variant="primary" tone="neutral" onClick={()=>setDuplicate(true)}>Дублировать материал</Button>;
return <>{gradient?
<Inspector header={header} footer={footer} defaultOpen={['active']} sections={[
{id:'active',label:'Активный материал · градиент',content:<><ChargeGradientInspector value={gradient} onChange={chargeGradient=>onChange({chargeGradient})}/><MaterialSurfaceInspector material={material} onChange={onChange} onError={onError}/></>},
{id:'inactive',label:'Неактивный материал · без данных',content:<><Description>Самостоятельный материал, когда сохранённого заряда нет. Свои поверхность, текстуры и свечение.</Description><MaterialSurfaceInspector material={gradient.inactive} onChange={patch=>onChange({chargeGradient:{...gradient,inactive:{...gradient.inactive,...patch}}})} onError={onError}/></>}
]}/>:<MaterialSurfaceInspector header={header} footer={footer} material={material} onChange={onChange} onError={onError}/>}
{duplicate&&<DuplicateMaterialDialog initialName={copyName} onDuplicate={onDuplicate} onClose={()=>setDuplicate(false)}/>}</>;
}
@@ -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>
</>;}
@@ -0,0 +1,18 @@
import {useRef,useState,type ReactNode} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSurface} from '../../../core/roverScene/materialSurface';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialSurfaceInspector({material,onChange,onError,header,footer}:{header?:ReactNode;footer?:ReactNode;material:MaterialSurface;onChange:(patch:Partial<MaterialSurface>)=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSurface,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 <Inspector header={header} footer={footer} defaultOpen={['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
]}/>;
}
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSurface['textures'][TextureSlot];onChange:(value:MaterialSurface['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
}
@@ -1,38 +1,75 @@
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 {duplicateMaterial,materialCopyName} from '../../../core/roverScene/materialActions';
import {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout';
import {roverModelURL} from '../../../core/roverScene/model';
import {useCallback,useEffect,useRef,useState} from 'react';
import {DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
import {createMaterial,changeField,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 {MaterialInspector,type MaterialPreview} 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,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;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 [materialPreview,setMaterialPreview]=useState<MaterialPreview>('auto');
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)=>{setMaterialPreview('auto');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 saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
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 saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено в Mission Core';
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),content:<EnvironmentInspector update={scene.update} sceneFiles={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument}/>} 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?<MaterialInspector key={selected} selectionDescription={node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'} copyName={materialCopyName(scene.document,selected)} onDuplicate={name=>{const id=`custom/${crypto.randomUUID()}`,next=duplicateMaterial(scene.document,selected,id,name);scene.update(()=>next);setPalette(true);setSelectionVersion(v=>v+1);pick(id);}} preview={materialPreview} onPreview={setMaterialPreview} material={material} onChange={patch=>patchMaterial(selected,patch)} 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} materialPreview={editing&&materialOpen&&selected&&materialPreview!=='auto'?{id:selected,mode:materialPreview}:undefined} 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"><div 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></div></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, materialPreview,
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,materialPreview})
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,58 @@
import * as pc from 'playcanvas';
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
import type {MaterialSurface} from '../../../core/roverScene/materialSurface';
import {applyMaterialSurface} from './materialSurface';
const surfaces=new WeakMap<pc.StandardMaterial,{surface:MaterialSurface;gradient:ChargeGradient}>();
export type ChargeState={soc:number|null;fresh:boolean};
export type ChargePreview={id:string;mode:'active'|'inactive'};
export function previewChargeState(state:ChargeState|undefined,preview?:ChargePreview):ChargeState|undefined{
return preview?.mode==='inactive'?{soc:null,fresh:false}:preview?.mode==='active'?{soc:Number.isFinite(state?.soc)?state!.soc:50,fresh:true}:state;
}
export function chargeSurface(spec:MaterialSpec,state:ChargeState|undefined):MaterialSurface{return spec.chargeGradient&&!Number.isFinite(state?.soc)?spec.chargeGradient.inactive:spec;}
const emission=`
uniform vec3 chargeColorA;
uniform vec3 chargeColorB;
uniform float chargeTime;
uniform float chargeScale;
uniform float chargeIntensity;
uniform float chargeSaturation;
uniform float chargeContrast;
uniform vec3 material_emissive;
uniform float material_emissiveIntensity;
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=clamp((smoothstep(-1.6,1.6,wave)-0.5)*chargeContrast+0.5,0.0,1.0);
vec3 color=mix(chargeColorA,chargeColorB,blend);
color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation);
vec3 baseEmission=material_emissive*material_emissiveIntensity;
#ifdef STD_EMISSIVE_TEXTURE
baseEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
#endif
#ifdef STD_EMISSIVE_VERTEX
baseEmission *= saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL});
#endif
dEmission=baseEmission+max(color,vec3(0.0))*chargeIntensity;
}`;
export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){
const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL);
if(gradient)chunks.set('emissivePS',emission);else chunks.delete('emissivePS');
surfaces.delete(material);
}
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec,bindTextures?:(surface:MaterialSurface)=>void){
const known=typeof state?.soc==='number'&&Number.isFinite(state.soc),surface=known?spec:gradient.inactive;
const applied=surfaces.get(material);
if(!applied||applied.surface!==surface||applied.gradient!==gradient){
applyMaterialSurface(material,surface);bindTextures?.(surface);material.update();surfaces.set(material,{surface,gradient});
}
const colors=known?chargePair(gradient,state!.soc):[[0,0,0],[0,0,0]];
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',known&&gradient.enabled?gradient.intensity:0);
material.setParameter('chargeSaturation',gradient.saturation);
material.setParameter('chargeContrast',gradient.contrast);
}
@@ -0,0 +1,13 @@
import * as pc from 'playcanvas';
import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
export const surfaceMaps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
export function applyMaterialSurface(m:pc.StandardMaterial,spec:MaterialSurface){
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
m.depthWrite=m.blendType===pc.BLEND_NONE;
}
@@ -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,20 @@
import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas';
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;editing?:boolean;onMaterialPick?:(id:string,group:string)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,editing,onMaterialPick,onTextureState}:SceneMaterialsProps){
const latest=useRef({materials,onMaterialPick,onTextureState});latest.current={materials,onMaterialPick,onTextureState};
import {configureChargeMaterial,updateChargeMaterial,chargeSurface,previewChargeState,type ChargePreview,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} from '../../../core/roverScene/sceneDocument';
import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
import {applyMaterialSurface,surfaceMaps as maps} from './materialSurface';
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;materialPreview?:ChargePreview;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
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,materialPreview}:SceneMaterialsProps){
const latest=useRef({materials,onObjectPick,onTextureState,chargeState,materialPreview});latest.current={materials,onObjectPick,onTextureState,chargeState,materialPreview};
const bindings=useRef(new Map<string,(surface:MaterialSurface)=>void>());
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,61 +31,70 @@ 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)=>{
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSurface)=>{
(m as any)[maps[slot]]=texture;
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update();
};
const used=new Set<string>();
const used=new Set<string>();animated.current.clear();bindings.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;
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
// Specular factor is independent from the donor's global IBL multiplier.
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
m.depthWrite=m.blendType===pc.BLEND_NONE;
const state=()=>previewChargeState(latest.current.chargeState,latest.current.materialPreview?.id===id?latest.current.materialPreview:undefined);
const selectedSurface=()=>chargeSurface(spec,state());
const bind=(surface:MaterialSurface)=>{for(const slot of Object.keys(maps) as TextureSlot[]){const data=surface.textures[slot]?.data;applyTexture(m,slot,data?textures.current.get(`${slot==='diffuse'||slot==='emissive'}:${data}`)?.texture??null:null,surface);}};
bindings.current.set(id,bind);
for(const surface of [spec,...(spec.chargeGradient?[spec.chargeGradient.inactive]:[])]){
for(const slot of Object.keys(maps) as TextureSlot[]){
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;}
const data=surface.textures[slot]?.data;if(!data)continue;
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
let item=textures.current.get(key);
if(!item){
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:surface.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
item={promise};textures.current.set(key,item);const cached=item;
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
}
if(item.texture)applyTexture(m,slot,item.texture,spec);
else{
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
if(!item.texture){
pending++;item.promise.then(tex=>{if(generation.current===current&&selectedSurface()===surface)applyTexture(m,slot,tex,surface);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
}
}
}
configureChargeMaterial(m,spec.chargeGradient);
if(spec.chargeGradient){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,state(),0,spec,bind);}else{applyMaterialSurface(m,spec);bind(spec);}
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)updateChargeMaterial(material,gradient,previewChargeState(live.chargeState,live.materialPreview?.id===id?live.materialPreview:undefined),time,live.materials![id],bindings.current.get(id));}};
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); }
@@ -1,6 +1,6 @@
.nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);}
.rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);}
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
.rover-logs__entries {flex:1;min-height:0;overflow:auto;}
.rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);}
@@ -1,19 +1,20 @@
import type {SceneView} from "../../core/simulation/simulationLayout";
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
import { sceneClipBounds } from "../../core/simulation/sceneClip";
import { heightSlice } from "../../core/heightSlice";
import { sceneClipBounds, sceneClipRange } from "../../core/simulation/sceneClip";
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
import { EditorCollisionLayer } from "./EditorCollisionLayer";
import { waypointHit } from "../../core/simulation/waypointHit";
import { PlannerMarkers } from "./PlannerMarkers";
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import { QUALITY_PROFILES, orthographicLodFov } from "../../core/simulation/gaussianQuality";
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { Application, Asset, BoundingBox, Color, Entity, FILLMODE_NONE, Mat4, Quat, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
import { localScene } from "./localScene";
import { EditorTerrain } from "./EditorTerrain";
import { EditorCamera } from "./EditorCamera";
import { EditorCamera, type NavigationOwner } from "./EditorCamera";
import { EditorSurfacePicker } from "./EditorSurfacePicker";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
@@ -37,6 +38,7 @@ export class AiEditorRuntime {
private semanticProject: (()=>void)|null = null;
private visualBounds:number[][]=[];
private urbanVisible=false;
private semanticMode=false;
private experienceLayer: EditorUrbanMapLayer | null = null;
private experiencePoints: number[][] = [];
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
@@ -130,11 +132,14 @@ export class AiEditorRuntime {
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
uniform float editorClip;
uniform float editorFloor;
uniform float editorClipEnabled;
uniform float editorFloorEnabled;
void modifySplatCenter(inout vec3 center) {}
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
void modifySplatColor(vec3 center, inout vec4 color) {
// Unified work-buffer modifiers receive the calibrated world center.
if (center.y > editorClip || center.y < editorFloor) color.a = 0.0;
if ((editorClipEnabled > 0.5 && center.y > editorClip) ||
(editorFloorEnabled > 0.5 && center.y < editorFloor)) color.a = 0.0;
}` });
this.setPreferences(this.preferences);
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
@@ -151,10 +156,10 @@ export class AiEditorRuntime {
setUrbanMap(document: UrbanMap) {
this.urbanBounds=urbanExtent(document);
this.urbanLayer?.dispose();
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.urbanVisible);this.dirty=true;
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.semanticMode&&this.urbanVisible);this.dirty=true;
}
snapshotView():SceneView{return {...this.controls.snapshot(),clip:[Number.isFinite(this.clipFloor)?this.clipFloor:null,Number.isFinite(this.clip)?this.clip:null]};}
restoreView(view:SceneView){this.setClip(view.clip[1]??Infinity,view.clip[0]??-Infinity);this.controls.restore(view);this.syncCamera();this.dirty=true;}
restoreView(view:SceneView){const [floor,ceiling]=sceneClipRange(view.clip,this.height);this.setClip(ceiling,floor);this.controls.restore(view);this.syncCamera();this.dirty=true;}
watchCamera(callback:((q:[number,number,number,number])=>void)|null) {this.cameraProject=callback;this.dirty=true;}
setProjection(mode:EditorProjection){this.surfacePicker.invalidate();this.controls.setProjection(mode);this.syncCamera();this.dirty=true;}
view(direction:number[]){this.surfacePicker.invalidate();this.controls.view(direction);this.syncCamera();this.dirty=true;}
@@ -202,7 +207,8 @@ export class AiEditorRuntime {
return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null;
}
setUrbanClasses(selected:readonly UrbanClassId[]) {this.urbanLayer?.setClasses(selected);this.dirty=true;}
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(visible);this.dirty=true; }
setSemanticMode(active: boolean) { this.semanticMode=active;this.urbanLayer?.setVisible(active&&this.urbanVisible);this.dirty=true; }
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(this.semanticMode&&visible);this.dirty=true; }
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
@@ -229,26 +235,33 @@ export class AiEditorRuntime {
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
}
setClip(height: number, floor = -Infinity) {
const slice=heightSlice(sceneClipRange([floor,height],this.height),this.height);
height=slice.ceiling??Infinity;floor=slice.floor??-Infinity;
this.surfacePicker.invalidate();this.controls.invalidateSurface();
this.clip = height; this.clipFloor = floor;
this.collisionLayer?.setClip(height,floor);
this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor);
if (this.scan.gsplat) {
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : -1e9);
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 0);
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : 0);
this.scan.gsplat.setParameter("editorClipEnabled", Number.isFinite(height) ? 1 : 0);
this.scan.gsplat.setParameter("editorFloorEnabled", Number.isFinite(floor) ? 1 : 0);
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
}
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); }
private syncCamera() {
const c=this.controls.camera;
this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE;
if(isOrthographic(c))this.camera.camera!.orthoHeight=c.top;
if(isOrthographic(c)){
this.camera.camera!.orthoHeight=screenSpan(c,1)/2;
this.camera.camera!.fov=orthographicLodFov(screenSpan(c,1)/2,this.controls.focusDepth);
}else this.camera.camera!.fov=c.fov;
const { position:p, quaternion:q } = c;
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
}
@@ -23,7 +23,7 @@ export function AiInferencePreview({preview,layer}:{preview:InferencePreview;lay
{selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}>
<SpatialPreview points={selected.points} label={selected.label}/>
</Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>}
<div className="ai-inference-preview__caption">
<div data-glass-context="scene" className="ai-inference-preview__caption nodedc-viewport-surface">
Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
{selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null}
{selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null}
@@ -1,11 +1,11 @@
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
import {PlannerCameraTools} from "./PlannerCameraTools";
import { heightSlice } from "../../core/heightSlice";
import { sceneClipRange, sceneClipLabel } from "../../core/simulation/sceneClip";
import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
import { PlannerLegend } from "./PlannerLegend";
import { SemanticEditor } from "./SemanticEditor";
import { PlannerExperience } from "./PlannerExperience";
import { loadUrbanMap, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
import { loadUrbanMap, type UrbanMap } from "../../core/simulation/urbanMap";
import type { PreparedRoute } from "../../core/simulation/routePreparation";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
@@ -13,7 +13,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
import { Description, Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
import { type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
@@ -23,11 +23,11 @@ import { useSimulationFullscreen } from "./useSimulationFullscreen";
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
export type LocationMode = "view" | "semantic" | "planning";
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, busy=false, preparedRoute=null }: {
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, onBack, busy=false, preparedRoute=null }: {
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
actionsHost: HTMLElement | null; headerActions: React.ReactNode;
routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void;
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void; onBack:()=>void;
}) {
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
const markerSvg=useRef<SVGSVGElement>(null);
@@ -46,10 +46,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers});
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
const semantic=sceneMode==="semantic", planning=sceneMode==="planning";
const urbanVisible=layout.infrastructure,setUrbanVisible=(infrastructure:boolean)=>updateLayout({infrastructure});
const urbanClasses=layout.urbanLayers,setUrbanClasses=(urbanLayers:UrbanClassId[])=>updateLayout({urbanLayers});
const [memoryVisible,setMemoryVisible]=useState(false);
const [urbanError,setUrbanError]=useState<string|null>(null);
const [markers, setMarkers] = useState<EditorMarker[]>([]);
const [mode,setMode] = useState<"view" | "add">("view");
const [clip,setClip] = useState<[number,number]|null>(null);
@@ -62,7 +59,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const sceneKey=cache.world.sha256!,remember=()=>{if(loaded&&runtime.current)writeSceneView(sceneKey,runtime.current.snapshotView());};
const timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember);
const abort=new AbortController();
setUrbanMap(null);setUrbanError(null);
setUrbanMap(null);
setReady(false); setError(null); setClip(null);
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
@@ -71,12 +68,12 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
void view.load().then(() => { if (active) {
const remembered=readSceneView(sceneKey),settings=getSimulationLayout();
if(remembered){view.restoreView(remembered);setClip([remembered.clip[0]??view.height[0],remembered.clip[1]??view.height[1]]);}
if(remembered){view.restoreView(remembered);setClip(sceneClipRange(view.snapshotView().clip,view.height));}
view.setProjection(settings.projection);view.setSceneLayers(settings.sceneLayers);
loaded=true;setReady(true);
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{
if(active && map){view.setUrbanMap(map);setUrbanMap(map);}
}).catch((e:Error)=>{if(active)setUrbanError(e.message);});
}).catch((e:Error)=>{if(active)setError(e.message);});
} }).catch((e: Error) => { if (active) setError(e.message); });
return () => { remember();clearInterval(timer);window.removeEventListener("pagehide",remember);active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
}, [cache?.key,cache?.status,retry]);
@@ -85,8 +82,8 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
}, [points,cache,ready,sequence,planning]);
useEffect(()=>{
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);}
},[semantic,urbanMap,urbanVisible,urbanClasses]);
runtime.current?.setSemanticMode(semantic);
},[semantic,ready]);
useEffect(()=>{
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
@@ -95,8 +92,6 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
setMode("view");press.current=null;runtime.current?.setAddMode(false);
if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}
},[sceneMode,ready]);
// SemanticEditor owns both the edited map and its layer mask in semantic mode.
useEffect(()=>{if(!semantic)runtime.current?.setUrbanClasses(urbanClasses);},[semantic,urbanClasses,urbanMap,ready]);
useEffect(()=>{if(ready)try{runtime.current?.setSceneLayers(sceneLayers);}catch(e){setError((e as Error).message);}},[sceneLayers,ready]);
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
@@ -123,12 +118,20 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"};
const infrastructure=semantic?<InfrastructureAnalysis worldId={world.world_id} worldSha={world.sha256!} busy={busy} hasMap={!!urbanMap}
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setUrbanError(null);}}/>:null;
const header=<>{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setError(null);}}/>:null;
const header=<div className="ai-polygon__scene-actions">
<div className="ai-polygon__context-actions">
{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}
</div>
<div className="ai-polygon__mode-actions">
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
</FieldFrame>{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}</>;
</FieldFrame>
<IconButton label="Назад к локациям" disabled={busy} onClick={onBack}><Icon name="chevron-left"/></IconButton>
</div>
</div>;
return <div className="ai-polygon__stage" ref={host}>
{expanded ? <>
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
@@ -137,8 +140,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
</>}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge>
{planning?<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>:null}
{!semantic && urbanVisible && urbanMap ? <p>Инфраструктура · {urbanMap.coverage.kind === "objects-only" ? `${urbanMap.schema_version === "missioncore.urban-map/v3" ? "по скану" : urbanMap.analysis?.scope === "whole-scene" ? `обследовано ${urbanMap.analysis.tiles_total} участков · данные в ${urbanMap.analysis.tiles_mapped}` : "участок"} · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
{planning?<Description>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</Description>:null}
</div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
@@ -158,13 +160,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
}}><Icon name="trash"/></IconButton>:null}
</div>
<SegmentedGroup label="Слои сцены" className="ai-local-editor__layers">
{!semantic&&urbanMap?<SegmentedButton title={urbanError??"Карта дорожной инфраструктуры"}
active={urbanVisible} aria-pressed={urbanVisible}
onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}>Инфраструктура</SegmentedButton>:null}
{(["gaussian","collision"] as const).map(key=><SegmentedButton key={key} active={sceneLayers[key]} aria-pressed={sceneLayers[key]}
onClick={()=>{try {const next={...sceneLayers,[key]:!sceneLayers[key]};runtime.current?.setSceneLayers(next);setSceneLayers(next);setError(null);}
catch(e){setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}>{key==="gaussian"?"Gaussian":"Коллизии"}</SegmentedButton>)}
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
{sceneMode!=="view" && runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
runtime={runtime.current} viewport={viewport.current} onVisibilityChange={setMemoryVisible}/> : null}
</SegmentedGroup>
{urbanMap&&urbanMap.schema_version!=="missioncore.urban-map/v1"&&runtime.current&&viewport.current?<SemanticEditor key={world.sha256} worldId={world.world_id} worldSha={world.sha256!}
@@ -223,15 +222,15 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
</g>:null)}
</svg></div>
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
selected={urbanClasses} onChange={setUrbanClasses} disabled={busy}/>:null}
{planning?<PlannerLegend map={null} memory={memoryVisible}
selected={[]} onChange={()=>undefined} disabled={busy}/>:null}
{!ready && !error ? <LoadingRegion className="ai-local-editor__loading" loading label={message} />:null}
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={clip??runtime.current!.height}
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></div>
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
formatValue={(v)=>sceneClipLabel(v,runtime.current!.height)} formatLimit={(v)=>sceneClipLabel(v,runtime.current!.height)}
onChange={(v)=>{const view=runtime.current!;view.setClip(v[1],v[0]);setClip(sceneClipRange(view.snapshotView().clip,view.height));}}/></div>
{error?<div className="ai-route__tools"><Description role="alert">{error}</Description></div>:null}</>:null}
{error && !ready ? <div className="ai-polygon__preview-error"><Description role="alert">{error}</Description><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
</div>
</div>
</div>;
@@ -1,6 +1,6 @@
import { useState } from "react";
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
import { Description, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
@@ -61,7 +61,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
</WindowFooterActions>}>
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
onChange={event => setName(event.target.value)}/>
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null}
{editing?.world_id === activeWorldId ? <Description>Удаление станет доступно после завершения симуляции.</Description> : null}
</Window>
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
@@ -1,4 +1,4 @@
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import { Description, Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}: {
error:string|null;name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
@@ -9,9 +9,9 @@ export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}:
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
<div className="ai-polygon__form">
{error?<p role="alert">{error}</p>:null}
{error?<Description role="alert">{error}</Description>:null}
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
<Description>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</Description>
</div>
</Window>;
}
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState, type PointerEvent } from "react";
import { Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { Description, Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon";
import { useAiPlanningControls } from "./useAiPlanningControls";
@@ -133,8 +133,8 @@ export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: {
<Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button>
<Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p>
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null}
<Description>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</Description>
{error || draft?.error ? <Description role="alert">{error ?? draft?.error}</Description> : null}
</div> : null}
</div>;
}
@@ -1,4 +1,4 @@
import { Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
import { Description, Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
import type { AiModules, AiRun } from "../../core/simulation/aiPolygon";
import { AiSessionSection, useSessionLayout } from "./AiSessionSection";
@@ -32,11 +32,11 @@ export function AiRunReport({ runs, modules, onRemove, removing, worldId }: { wo
action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`,
icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
onAction:()=>onRemove(run)},
}))}/> : <p>В этой локации ещё нет прогонов.</p>}
}))}/> : <Description>В этой локации ещё нет прогонов.</Description>}
</AiSessionSection>;
}
function RunDetails({run}:{run:AiRun}) {
if(!run.report)return <p>{run.message ?? "Отчёт появится после завершения прогона."}</p>;
if(!run.report)return <Description>{run.message ?? "Отчёт появится после завершения прогона."}</Description>;
const report=run.report;
return <div className="ai-polygon__form ai-polygon__report">
<StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}>
@@ -60,8 +60,8 @@ function RunDetails({run}:{run:AiRun}) {
<h3>Остановки после начала движения</h3>
{report.stops.length ? <dl>{report.stops.map((stop) => <div key={stop.reason}>
<dt>{reasons[stop.reason] ?? stop.reason}</dt><dd>{stop.events} · {stop.seconds.toFixed(1)} с</dd>
</div>)}</dl> : <p>Переходов от движения к нулевой команде не записано.</p>}
<p>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</p>
</div>)}</dl> : <Description>Переходов от движения к нулевой команде не записано.</Description>}
<Description>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</Description>
<dl className="ai-polygon__report-identities">
<div><dt>Прогон</dt><dd>{report.run_id}</dd></div>
<div><dt>Профиль ровера</dt><dd>{report.robot_sha256 ?? "Не записан"}</dd></div>
@@ -1,4 +1,4 @@
import { StatusBadge } from "@nodedc/ui-react";
import { Description, StatusBadge } from "@nodedc/ui-react";
import { type AiRun } from "../../core/simulation/aiPolygon";
const STATES: Record<AiRun["state"], string> = {
@@ -51,6 +51,6 @@ export function AiRunView({ run }: { run: AiRun }) {
<dt>{label}</dt><dd>{value}</dd>
</div>)}
</dl>
{run.state === "failed" && run.message ? <p>{run.message}</p> : null}
{run.state === "failed" && run.message ? <Description>{run.message}</Description> : null}
</section>;
}
@@ -1,6 +1,6 @@
import { useCallback, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
import { Description, Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon";
import { WorkerVideo, type WorkerVideoState } from "./WorkerVideo";
import { AiRouteOverlay } from "./AiRouteOverlay";
@@ -60,7 +60,7 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
<div className="ai-polygon__stream-picture">
{connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
{cameraError ? <Description role="alert">Не удалось переключить камеру.</Description> : null}
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
<div className="ai-polygon__video" inert>
@@ -69,9 +69,9 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
</div>
</LoadingRegion>
{!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null}
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div>
{terminal ? <div className="ai-polygon__preview-error"><Description>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</Description></div>
: connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
<p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
<Description>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</Description>
<Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
</div> : null}
</div>
@@ -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;
@@ -24,6 +27,7 @@ export class EditorCamera {
private right = new Vector3();
private delta = new Vector3();
sceneCenter = new Vector3();
get focusDepth(){return navigationDepth(this.camera,this.lastAnchor??this.sceneCenter);}
pick: ((x:number,y:number)=>number[]|null)|null = null;
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
@@ -153,7 +157,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();
@@ -2,7 +2,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
import { Description, Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon";
import type { RoverSettings } from "../../core/simulation/roverSettings";
import { toEditor } from "../../core/simulation/aiEditor";
@@ -48,7 +48,7 @@ export function LocalManualScene({world,robot,settings,actionsHost,headerActions
<canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} />
{ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null}
{!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null}
{error?<div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
{error?<div className="ai-polygon__preview-error"><Description role="alert">{error}</Description><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
</div>
</div>
</div>;
@@ -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)}
</>;
@@ -1,6 +1,6 @@
import {useSimulationLayout} from "./useSimulationLayout";
import { useEffect, useState } from "react";
import { Checker, Dropdown, SegmentedButton } from "@nodedc/ui-react";
import { Description, Checker, Dropdown, SegmentedButton } from "@nodedc/ui-react";
import { createPortal } from "react-dom";
import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
@@ -33,13 +33,13 @@ export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilit
aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
<div className="ai-polygon__layer-options">
<strong>Память локации</strong>
<p>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</p>
{error?<p role="alert">{error}</p>:memory?<>
<p>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</p>
<Description>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</Description>
{error?<Description role="alert">{error}</Description>:memory?<>
<Description>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</Description>
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>}
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p>
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p>
</>:<Description>Сохранённых проездов пока нет. Память появится после движения ровера.</Description>}
<Description>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</Description>
<Description>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</Description>
</div>
</Dropdown>
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import { Description, ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
import {PlannerCubeSettings} from "./PlannerCubeSettings";
import {PlannerToolbarSettings} from "./PlannerToolbarSettings";
@@ -79,7 +79,7 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow>
</> : <>
<strong>Сдвиг камеры</strong>
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p>
<Description>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</Description>
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")}
{range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")}
@@ -87,7 +87,7 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
<strong>Зум</strong>
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
<strong>Центр вращения</strong>
<p>Шарик появляется в точке нажатия на время вращения.</p>
<Description>Шарик появляется в точке нажатия на время вращения.</Description>
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
@@ -1,5 +1,5 @@
import { useState } from "react";
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import { Description, Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import type { AiRobot } from "../../core/simulation/aiPolygon";
import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings";
@@ -23,11 +23,11 @@ export function RoverSettingsWindow({robot,value,manual,onApply,onClose}:{
{field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)}
{field("payload_mass_kg","Дополнительный груз, кг",0,500,1)}
{field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)}
<p>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</p>
<p>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</p>
{manual?<p>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</p>:null}
<p>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</p>
{!valid?<p role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</p>:null}
<Description>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</Description>
<Description>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</Description>
{manual?<Description>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</Description>:null}
<Description>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</Description>
{!valid?<Description role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</Description>:null}
</div>
</Window>;
}
@@ -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);
@@ -1,4 +1,4 @@
import {
import { Description,
ActivityIndicator,
Button,
Icon,
@@ -85,7 +85,7 @@ export function SimulationCatalog({
<div className="simulation-catalog__empty">
<span><Icon name="globe" size={20} /></span>
<strong>Перетащите архивы в это окно</strong>
<p>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</p>
<Description>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</Description>
<Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={onCreate}>
Новый проект
</Button>
@@ -1,6 +1,6 @@
import {useEffect,useRef,useState,type ReactNode} from 'react';
import {createPortal} from 'react-dom';
import {Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
import { Description,Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout';
import {useObservationPresets} from '../../core/fleet/useObservationPresets';
import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets';
@@ -48,7 +48,7 @@ export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{
</div></ObservationPanelHeader>
<div className="observation-mount">{source.id==='video'?video:preview&&<AiInferencePreview preview={preview} layer={source.id}/>}</div>
</GlassSurface></div>,mounts.current.get(source.id)!,source.id))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
</ObservationDeck>:<div className="observation-empty"><Description>Все окна скрыты.</Description><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
<ToastStack items={presets.error?[{id:"layout-save",tone:"error",title:"Раскладка не сохранена",description:presets.error}]:[]} onDismiss={presets.clearError}/>
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import { Button, LoadingRegion, Window } from "@nodedc/ui-react";
import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
import { SimulationProjectWindow } from "./SimulationProjectWindow";
@@ -38,14 +38,14 @@ export function SimulationSourceImport({open,onClose,onPly,onReady}: {
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
</div>
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><p>{p.name}</p>
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><Description>{p.name}</Description>
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
{error?<p role="alert">{error}</p>:null}
{error?<Description role="alert">{error}</Description>:null}
</Window>
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
<p>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</p>
<Description>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</Description>
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
</LoadingRegion>
</Window>:null}
@@ -1,4 +1,4 @@
import {
import { Description,
Button,
Icon,
RangeControl,
@@ -44,12 +44,12 @@ export function SimulationUgvSettingsPanel({
<strong>Физика UGV</strong>
<span>Дифференциальный привод</span>
</div>
<p>
<Description>
A/D без W/S разворачивают UGV вокруг собственного центра. Скорость и
динамика применяются сразу. Мышь вращает камеру вокруг машины, колесо
меняет дистанцию; после паузы камера плавно возвращается назад. Ползунок
работает в штатном диапазоне, точное значение можно ввести вручную.
</p>
</Description>
<TextField
label="Название пресета"
value={value.presetName}
@@ -1,5 +1,5 @@
import { useState, type ReactNode, type RefObject } from "react";
import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { Description, Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { PlannerSettings } from "./PlannerSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
@@ -22,12 +22,12 @@ export function SimulationViewTools({expanded,toggle,semantic=false,planning=fal
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
<div className="ai-polygon__form">{planning?<>
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p>
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null}
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null}
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
<Description>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</Description>
<Description>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</Description>
<Description>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</Description>
{semantic?<Description>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</Description>:null}
{routeEditing?<Description>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</Description>:null}
</>:<><Description>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</Description><Description>Мышь — обзор.</Description></>}</div>
</Window>
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</>;
@@ -1,5 +1,5 @@
import { useEffect, useId, useRef, useState } from "react";
import {
import { Description,
ActivityIndicator,
Button,
GlassMaterialSurface,
@@ -237,7 +237,7 @@ export function SimulationViewport({
data-control-mode={controlMode}
aria-label={`Сцена ${project.name}`}
>
<header className="simulation-viewport__toolbar">
<header data-glass-context="scene" className="simulation-viewport__toolbar nodedc-viewport-surface">
<div>
<StatusBadge tone={state === "failed" || collisionState === "failed" ? "warning" : state === "ready" && collisionState !== "loading" ? "success" : "accent"}>
{controlState === "loading"
@@ -341,7 +341,7 @@ export function SimulationViewport({
role="dialog"
aria-label="Настройки сцены"
>
<div className="simulation-viewport__settings-head">
<div data-glass-context="scene" className="simulation-viewport__settings-head nodedc-viewport-surface">
<div>
<strong>Настройки сцены</strong>
<span>Локация, камера и UGV</span>
@@ -356,9 +356,9 @@ export function SimulationViewport({
<strong>Система координат</strong>
<span>Мир сцены · Y вверх</span>
</div>
<p>
<Description>
Коррекция слоёв не меняет координаты камеры, навигации и будущей физики.
</p>
</Description>
<div className="simulation-viewport__settings-rotations">
<LayerRotationFields
label="Гауссовый слой"
@@ -450,10 +450,10 @@ export function SimulationViewport({
<div className="simulation-viewport__stage">
<canvas ref={canvasRef} aria-label={`Сцена ${project.name}`} />
{state !== "ready" ? (
<div className="simulation-viewport__state" role={state === "failed" ? "alert" : "status"}>
<div data-glass-context="scene" className="simulation-viewport__state nodedc-viewport-surface" role={state === "failed" ? "alert" : "status"}>
{state === "failed" ? null : <ActivityIndicator label="Загрузка локации" />}
<strong>{state === "failed" ? "Локация не открылась" : "Загружаем локацию"}</strong>
<p>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</p>
<Description>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</Description>
</div>
) : null}
</div>
@@ -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};
}
@@ -0,0 +1,32 @@
import { useEffect, useState } from "react";
import { Description, Button, SettingsCard, TextField, WindowFooterActions } from "@nodedc/ui-react";
import { announceLabStorageChange, saveLabRetention, useLocalLabStorage } from "../../core/storage/localLabStorage";
export function useLabStorageSettings(open: boolean) {
const { data, error: loadError, refresh } = useLocalLabStorage(open);
const [days, setDays] = useState("30");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
useEffect(() => { if (data) setDays(String(data.retention_days)); }, [data?.retention_days]);
const number = Number(days);
const valid = Number.isInteger(number) && number >= 1 && number <= 365;
const content = <SettingsCard eyebrow="ХРАНИЛИЩЕ" title="Локальные записи лабораторий"
description="Срок хранения готовых записей просмотра после последнего открытия. Закреплённые записи остаются на этом устройстве до снятия булавки.">
<TextField label="Срок временного хранения, дней" type="number" min={1} max={365}
value={days} disabled={busy || !data} onChange={event => { setDays(event.target.value); setSaved(false); }} />
<Description>После снятия булавки срок начинается заново. История запусков и результаты на Worker сохраняются.</Description>
<Description>Правило применяется к учтённым записям просмотра AI Inference. Исходные записи, Gaussian-сцены и разметка сохраняются отдельно.</Description>
{loadError || error ? <Description role="alert">{error ?? loadError}</Description> : saved ? <Description role="status">Настройки сохранены.</Description> : null}
</SettingsCard>;
const footer = <WindowFooterActions>
<Button variant="secondary" disabled={busy || !data || days === String(data.retention_days)}
onClick={() => { setDays(String(data!.retention_days)); setError(null); }}>Сбросить изменения</Button>
<Button variant="primary" tone="neutral" disabled={busy || !data || !valid || days === String(data.retention_days)}
onClick={() => { setBusy(true); setError(null); void saveLabRetention(number).then(async () => {
await refresh(); setSaved(true); announceLabStorageChange();
}).catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось сохранить срок хранения."))
.finally(() => setBusy(false)); }}>{busy ? "Сохраняем…" : "Сохранить"}</Button>
</WindowFooterActions>;
return { id: "storage", label: "Хранилище", icon: "database" as const, content, footer };
}
@@ -1,579 +0,0 @@
import { useEffect, useMemo, useState } from "react";
import {
Button,
FeatureSettingsWindow,
FieldFrame,
Icon,
Select,
SettingsCard,
StatusBadge,
TextField,
WindowFooterActions,
} from "@nodedc/ui-react";
import {
applyComputeContourNetwork,
fetchComputeContourAgentInstall,
fetchComputeContourNetwork,
type ComputeContour,
type ComputeContourAgentInstall,
type ComputeContourDraft,
type ComputeContourNetworkStatus,
type ComputeContourPlatform,
} from "../../core/system/computeContours";
import {
DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
parseTelemetryPollIntervalDraft,
resolveTelemetryPollIntervalDraft,
} from "../../core/system/telemetryPollInterval";
interface ComputeContourSettingsWindowProps {
open: boolean;
contour: ComputeContour | null;
mode: "create" | "edit";
onClose: () => void;
onCreate: (draft: ComputeContourDraft) => Promise<ComputeContour>;
onUpdate: (
contour: ComputeContour,
draft: ComputeContourDraft,
) => Promise<ComputeContour>;
}
const platformOptions = [
{ value: "windows", label: "Windows", description: "Worker с Windows service" },
{ value: "linux", label: "Linux", description: "Worker с systemd service" },
{ value: "unknown", label: "Не определено", description: "Платформа будет уточнена" },
] satisfies Array<{
value: ComputeContourPlatform;
label: string;
description: string;
}>;
function emptyDraft(): ComputeContourDraft {
return {
display_name: "",
expected_node_id: "",
platform: "unknown",
telemetry_mode: "agent-mqtt",
address: "",
ssh_port: 22,
mqtt_host: "127.0.0.1",
mqtt_port: 1883,
mqtt_bind_address: "127.0.0.1",
telemetry_poll_interval_seconds: DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
mqtt_publish_interval_seconds: 2,
};
}
function draftFromContour(contour: ComputeContour | null): ComputeContourDraft {
if (!contour) return emptyDraft();
return {
display_name: contour.display_name,
expected_node_id: contour.expected_node_id,
platform: contour.platform,
telemetry_mode: contour.telemetry_mode,
address: contour.address,
ssh_port: contour.ssh_port,
mqtt_host: contour.mqtt_host,
mqtt_port: contour.mqtt_port,
mqtt_bind_address: contour.mqtt_bind_address,
telemetry_poll_interval_seconds: contour.telemetry_poll_interval_seconds,
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
};
}
export function ComputeContourSettingsWindow({
open,
contour,
mode,
onClose,
onCreate,
onUpdate,
}: ComputeContourSettingsWindowProps) {
const [draft, setDraft] = useState<ComputeContourDraft>(() => draftFromContour(contour));
const [telemetryPollIntervalDraft, setTelemetryPollIntervalDraft] = useState(
() => String(draftFromContour(contour).telemetry_poll_interval_seconds),
);
const [mqttPublishIntervalDraft, setMqttPublishIntervalDraft] = useState(
() => String(draftFromContour(contour).mqtt_publish_interval_seconds),
);
const [activeSection, setActiveSection] = useState<"connection" | "agent">("connection");
const [install, setInstall] = useState<ComputeContourAgentInstall | null>(null);
const [network, setNetwork] = useState<ComputeContourNetworkStatus | null>(null);
const [networkAction, setNetworkAction] = useState<
"refresh" | "broker" | "worker" | null
>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
const nextDraft = draftFromContour(mode === "edit" ? contour : null);
setDraft(nextDraft);
setTelemetryPollIntervalDraft(String(nextDraft.telemetry_poll_interval_seconds));
setMqttPublishIntervalDraft(String(nextDraft.mqtt_publish_interval_seconds));
setActiveSection("connection");
setInstall(null);
setNetwork(null);
setNetworkAction(null);
setError(null);
}, [contour, mode, open]);
useEffect(() => {
if (!open || mode !== "edit" || !contour) return;
const controller = new AbortController();
setNetworkAction("refresh");
void fetchComputeContourNetwork(contour.contour_id, controller.signal)
.then((document) => {
if (!controller.signal.aborted) setNetwork(document);
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
}
})
.finally(() => {
if (!controller.signal.aborted) setNetworkAction(null);
});
return () => controller.abort();
}, [contour, mode, open]);
useEffect(() => {
if (!open || mode !== "edit" || !contour) return;
const controller = new AbortController();
void fetchComputeContourAgentInstall(contour.contour_id, controller.signal)
.then((document) => {
if (!controller.signal.aborted) setInstall(document);
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setError(reason instanceof Error ? reason.message : "Инструкция агента недоступна.");
}
});
return () => controller.abort();
}, [contour, mode, open]);
const telemetryPollIntervalSeconds = useMemo(
() => parseTelemetryPollIntervalDraft(telemetryPollIntervalDraft),
[telemetryPollIntervalDraft],
);
const mqttPublishIntervalSeconds = useMemo(
() => parseTelemetryPollIntervalDraft(mqttPublishIntervalDraft),
[mqttPublishIntervalDraft],
);
const valid = useMemo(() => (
Boolean(draft.display_name.trim())
&& Boolean(draft.expected_node_id.trim())
&& Boolean(draft.mqtt_host.trim())
&& Boolean(draft.mqtt_bind_address.trim())
&& Number.isInteger(draft.ssh_port)
&& draft.ssh_port > 0
&& Number.isInteger(draft.mqtt_port)
&& draft.mqtt_port > 0
&& telemetryPollIntervalSeconds !== null
&& mqttPublishIntervalSeconds !== null
), [draft, mqttPublishIntervalSeconds, telemetryPollIntervalSeconds]);
const networkProfileDirty = Boolean(
contour
&& (
draft.mqtt_host !== contour.mqtt_host
|| draft.mqtt_port !== contour.mqtt_port
|| draft.mqtt_bind_address !== contour.mqtt_bind_address
|| draft.mqtt_publish_interval_seconds !== contour.mqtt_publish_interval_seconds
),
);
const commitTelemetryPollInterval = () => {
const resolution = resolveTelemetryPollIntervalDraft(
telemetryPollIntervalDraft,
draft.telemetry_poll_interval_seconds,
);
setTelemetryPollIntervalDraft(resolution.draft);
if (!resolution.accepted) return;
setDraft((current) => (
current.telemetry_poll_interval_seconds === resolution.seconds
? current
: {
...current,
telemetry_poll_interval_seconds: resolution.seconds,
}
));
};
const commitMqttPublishInterval = () => {
const resolution = resolveTelemetryPollIntervalDraft(
mqttPublishIntervalDraft,
draft.mqtt_publish_interval_seconds,
);
setMqttPublishIntervalDraft(resolution.draft);
if (!resolution.accepted) return;
setDraft((current) => (
current.mqtt_publish_interval_seconds === resolution.seconds
? current
: {
...current,
mqtt_publish_interval_seconds: resolution.seconds,
}
));
};
const save = async () => {
if (
!valid
|| busy
|| telemetryPollIntervalSeconds === null
|| mqttPublishIntervalSeconds === null
) return;
const committedDraft = {
...draft,
telemetry_poll_interval_seconds: telemetryPollIntervalSeconds,
mqtt_publish_interval_seconds: mqttPublishIntervalSeconds,
};
setBusy(true);
setError(null);
try {
if (mode === "edit" && contour) {
await onUpdate(contour, committedDraft);
} else {
await onCreate(committedDraft);
}
onClose();
} catch (reason) {
setError(reason instanceof Error ? reason.message : "Контур не сохранён.");
} finally {
setBusy(false);
}
};
const refreshNetwork = async () => {
if (!contour || networkAction) return;
setNetworkAction("refresh");
setError(null);
try {
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
} catch (reason) {
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
} finally {
setNetworkAction(null);
}
};
const applyNetwork = async (target: "broker" | "worker") => {
if (!contour || networkAction || networkProfileDirty) return;
setNetworkAction(target);
setError(null);
try {
await applyComputeContourNetwork(contour.contour_id, target);
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "Сетевой профиль не применён.",
);
} finally {
setNetworkAction(null);
}
};
return (
<FeatureSettingsWindow
open={open}
title={mode === "create" ? "Добавить вычислительный контур" : "Настройки контура"}
subtitle="Локальная переносимая конфигурация"
identity={{
title: contour?.display_name ?? "Новый контур",
subtitle: contour?.expected_node_id ?? "Node ID не назначен",
avatarLabel: contour?.display_name.slice(0, 2).toUpperCase() ?? "WC",
}}
sections={[
{
id: "connection",
label: "Подключение",
group: "ВЫЧИСЛИТЕЛЬНЫЙ КОНТУР",
icon: "network",
},
{
id: "agent",
label: "Агент",
group: "ТЕЛЕМЕТРИЯ",
icon: "activity",
disabled: mode === "create",
},
]}
activeSection={activeSection}
onSectionChange={setActiveSection}
onClose={onClose}
footer={(
<WindowFooterActions>
<Button variant="secondary" onClick={onClose}>Отмена</Button>
<Button variant="primary" disabled={!valid || busy} onClick={() => void save()}>
{busy ? "Сохраняем…" : mode === "create" ? "Добавить контур" : "Сохранить"}
</Button>
</WindowFooterActions>
)}
>
<div className="compute-contour-settings">
{activeSection === "connection" ? (
<>
<SettingsCard
eyebrow="КОНТУР"
title="Идентичность и локальная сеть"
description="Node ID проверяется независимо от IP-адреса. Адрес можно менять при переносе комплекта в другую локальную сеть."
>
<div className="compute-contour-settings__form">
<TextField
label="Название"
value={draft.display_name}
placeholder="Worker 006"
onChange={(event) => setDraft((current) => ({
...current,
display_name: event.currentTarget.value,
}))}
/>
<TextField
label="Ожидаемый Node ID"
value={draft.expected_node_id}
placeholder="DESKTOP-OPJ8J04"
onChange={(event) => setDraft((current) => ({
...current,
expected_node_id: event.currentTarget.value,
}))}
/>
<FieldFrame label="Операционная система">
<Select
label="Операционная система"
value={draft.platform}
options={platformOptions}
variant="split"
menuWidth="anchor"
onChange={(platform) => setDraft((current) => ({ ...current, platform }))}
/>
</FieldFrame>
<TextField
label="Адрес узла"
hint="IP или hostname в текущей LAN"
value={draft.address}
onChange={(event) => setDraft((current) => ({
...current,
address: event.currentTarget.value,
}))}
/>
<TextField
label="MQTT broker"
hint="Стабильный hostname рекомендуется вместо выдаваемого DHCP IP"
value={draft.mqtt_host}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_host: event.currentTarget.value,
}))}
/>
<TextField
label="MQTT port"
type="number"
min={1}
max={65535}
value={String(draft.mqtt_port)}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_port: Number(event.currentTarget.value),
}))}
/>
<TextField
label="Публикация broker"
hint="IP текущего Mac в разрешённой LAN · 0.0.0.0 запрещён"
value={draft.mqtt_bind_address}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_bind_address: event.currentTarget.value,
}))}
/>
<TextField
label="Обновление интерфейса"
hint="1–60 с"
type="text"
inputMode="numeric"
autoComplete="off"
aria-invalid={telemetryPollIntervalSeconds === null}
value={telemetryPollIntervalDraft}
onChange={(event) => setTelemetryPollIntervalDraft(event.currentTarget.value)}
onBlur={commitTelemetryPollInterval}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
commitTelemetryPollInterval();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setTelemetryPollIntervalDraft(
String(draft.telemetry_poll_interval_seconds),
);
}
}}
/>
<TextField
label="Интервал MQTT агента"
hint="1–60 с · применяется конфигурацией агента"
type="text"
inputMode="numeric"
autoComplete="off"
aria-invalid={mqttPublishIntervalSeconds === null}
value={mqttPublishIntervalDraft}
onChange={(event) => setMqttPublishIntervalDraft(event.currentTarget.value)}
onBlur={commitMqttPublishInterval}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
commitMqttPublishInterval();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setMqttPublishIntervalDraft(
String(draft.mqtt_publish_interval_seconds),
);
}
}}
/>
{draft.telemetry_mode === "legacy-ssh" ? (
<TextField
label="SSH port"
type="number"
min={1}
max={65535}
value={String(draft.ssh_port)}
onChange={(event) => setDraft((current) => ({
...current,
ssh_port: Number(event.currentTarget.value),
}))}
/>
) : null}
</div>
</SettingsCard>
<SettingsCard
eyebrow="СЕТЕВОЙ ПРОФИЛЬ"
title="MQTT · Mac ↔ Worker"
description="Mesh-точки одной LAN не закрепляются по отдельности. Профиль хранит стабильное имя Mac и адрес публикации broker в текущей сети."
actions={(
<StatusBadge tone={network?.broker.ready ? "success" : "warning"}>
{network?.broker.ready ? "Broker доступен" : "Нужна проверка"}
</StatusBadge>
)}
>
<div className="compute-contour-settings__network">
<dl>
<div>
<dt>Endpoint Worker</dt>
<dd>{network
? `${network.broker.configured_host}:${network.broker.configured_port}`
: "—"}</dd>
</div>
<div>
<dt>Текущий IP</dt>
<dd>{network?.broker.resolved_addresses.join(", ") || "—"}</dd>
</div>
<div>
<dt>Публикация Mac</dt>
<dd>{network?.broker.bind_address ?? "—"}</dd>
</div>
<div>
<dt>{contour?.display_name ?? "Worker"}</dt>
<dd>{network?.worker.reachable
? `${network.worker.mqtt_host ?? "—"}:${network.worker.mqtt_port ?? "—"}`
: "Недоступен"}</dd>
</div>
</dl>
<div className="compute-contour-settings__network-statuses">
<StatusBadge tone={network?.broker.bind_reachable ? "success" : "danger"}>
{network?.broker.bind_reachable
? "Listener Mac доступен"
: "Listener Mac недоступен"}
</StatusBadge>
<StatusBadge tone={network?.worker.broker_reachable ? "success" : "danger"}>
{network?.worker.broker_reachable
? "Worker видит broker"
: "Worker не видит broker"}
</StatusBadge>
<StatusBadge tone={network?.worker.matches_profile ? "success" : "warning"}>
{network?.worker.matches_profile
? "Профиль синхронизирован"
: "Профиль отличается"}
</StatusBadge>
</div>
<div className="compute-contour-settings__network-actions">
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction)}
icon={<Icon name="refresh" size={14} />}
onClick={() => void refreshNetwork()}
>
{networkAction === "refresh" ? "Проверяем…" : "Проверить"}
</Button>
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction) || networkProfileDirty}
onClick={() => void applyNetwork("broker")}
>
{networkAction === "broker" ? "Применяем…" : "Применить на Mac"}
</Button>
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction) || networkProfileDirty}
onClick={() => void applyNetwork("worker")}
>
{networkAction === "worker" ? "Применяем…" : "Применить на Worker"}
</Button>
</div>
{networkProfileDirty ? (
<p>Сначала сохраните изменённый сетевой профиль, затем примените его.</p>
) : null}
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
</div>
</SettingsCard>
</>
) : null}
{activeSection === "agent" ? (
<SettingsCard
eyebrow="АГЕНТ"
title="Telegraf · универсальный сборщик"
description="Hardware и runtime собирает готовый агент. Mission Core нормализует только контур, LAB/run и стадии обработки."
actions={(
<StatusBadge tone={install?.ready ? "success" : "warning"}>
{install?.ready ? "Готов к установке" : "Нужен scoped MQTT credential"}
</StatusBadge>
)}
>
{install ? (
<div className="compute-contour-settings__install">
<dl>
<div><dt>Шаблон</dt><dd>{install.agent.configuration_template}</dd></div>
<div><dt>Секрет</dt><dd>интерактивный ввод · не хранится в UI</dd></div>
</dl>
<code>{install.command}</code>
<Button
size="compact"
variant="secondary"
icon={<Icon name="copy" size={14} />}
onClick={() => void navigator.clipboard.writeText(install.command)}
>
Копировать команду
</Button>
{install.blocked_reason ? <p>{install.blocked_reason}</p> : null}
</div>
) : (
<p className="compute-contour-settings__empty">
Сохраните контур, чтобы получить платформенную инструкцию установки.
</p>
)}
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
</SettingsCard>
) : null}
</div>
</FeatureSettingsWindow>
);
}
@@ -0,0 +1,38 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Description,Icon,Select,SettingsCard,TextAreaField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {InstallerCard} from '../network/InstallerCard';
import {serverRequest,useServers,type Server} from '../../core/system/servers';
import {vpsRequest} from '../../core/fleet/vps';
export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSaved}:{server?:Server;fixedKind?:'librespeed';onClose:()=>void;onSaved:()=>void}) {
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
const serviceName=kind==='librespeed'?'LibreSpeed':'WireGuard';
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
async function connect(){if(!server)return;setBusy(true);setError('');try{
await serverRequest(`/${server.id}/services`,'POST',{kind,document:document.trim(),expected_revision:server.revision,network_interface:network||null});
setDocument('');onSaved();
}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить службу.');}finally{setBusy(false);}}
return <><Window open title="Добавить службу" subtitle={server?`${server.name} · ${server.address}`:'Выберите зарегистрированный VPS'} size="lg" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
footer={<WindowFooterActions><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!server||!document.trim()} onClick={()=>void connect()}>Подключить службу</Button></WindowFooterActions>}>
<div className="system-catalog-form">
{!initialServer&&<Select label="VPS" value={serverId} disabled={busy} options={[{value:'',label:'Выберите VPS'},...(catalog.items??[]).map(s=>({value:s.id,label:`${s.name} · ${s.address}`}))]} onChange={id=>{setServerId(id);setDocument('');setFilename('');}}/>}
{!initialServer&&catalog.items?.length===0&&<Description>Сначала добавьте VPS в разделе «Система → VPS».</Description>}
{catalog.error&&!initialServer&&<Description>{catalog.error}</Description>}
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
{kind!=='arnavi'?<>
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
{filename&&<Description>{filename}</Description>}
<Description>Файл на VPS: {kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
</SettingsCard>
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
</div>
</Window><ToastStack items={error?[{id:'server-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1,33 @@
import {useState} from 'react';
import {Button, Description, Icon, IconButton, LoadingRegion, SettingsCard, TextField, ToastStack, Window, WindowFooterActions} from '@nodedc/ui-react';
import {serverRequest,type Server,type ServerRemovalPlan} from '../../core/system/servers';
export function ServerSettings({server,onClose,onSaved,onRemoved}:{server?:Server;onClose:()=>void;onSaved:(server:Server)=>void;onRemoved?:()=>void}) {
const [name,setName]=useState(server?.name??''),[address,setAddress]=useState(server?.address??'');
const [busy,setBusy]=useState(false),[error,setError]=useState('');
const [removing,setRemoving]=useState(false),[plan,setPlan]=useState<ServerRemovalPlan|null>(null);
async function prepareRemoval(){if(!server)return;setRemoving(true);setPlan(null);setBusy(true);setError('');try{
setPlan(await serverRequest<ServerRemovalPlan>(`/${server.id}/removal`,'POST',{expected_revision:server.revision}));
}catch(e){setError(e instanceof Error?e.message:'Не удалось проверить подключения VPS.');}finally{setBusy(false);}}
async function remove(){if(!server||!plan||plan.blocked.length)return;setBusy(true);setError('');try{
await serverRequest(`/${server.id}`,'DELETE',{expected_revision:server.revision,confirmation:plan.confirmation});
onRemoved?.();
}catch(e){setPlan(null);setError(e instanceof Error?e.message:'Удаление не завершено. Повторите проверку.');}finally{setBusy(false);}}
async function save(){setBusy(true);setError('');try{
const item=await serverRequest<Server>(server?`/${server.id}`:'',server?'PUT':'POST',{name:name.trim(),address:address.trim(),...(server?{expected_revision:server.revision}:{})});
onSaved(item);
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить VPS.');}finally{setBusy(false);}}
return <><Window open title={removing?'Удалить VPS?':server?'Настройки VPS':'Добавить VPS'} subtitle={server?.name}
size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
headerActionsPlacement="before-close" headerActions={server&&!removing&&<IconButton label="Удалить VPS" disabled={busy} onClick={()=>void prepareRemoval()}><Icon name="trash"/></IconButton>}
footer={<WindowFooterActions>{removing?<><Button disabled={busy} onClick={()=>{setRemoving(false);setPlan(null);setError('');}}>Отменить</Button>{plan?<Button loading={busy} disabled={busy||!!plan.blocked.length} onClick={()=>void remove()}>Удалить</Button>:<Button loading={busy} disabled={busy} onClick={()=>void prepareRemoval()}>Повторить проверку</Button>}</>:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||!address.trim()} onClick={()=>void save()}>{server?'Сохранить':'Добавить VPS'}</Button></>}</WindowFooterActions>}>
{removing?<LoadingRegion loading={busy&&!plan} label="Проверка подключений"><SettingsCard title={`Удалить «${server?.name}» из Mission Core?`} description="Это действие нельзя отменить.">
<Description>Будут удалены карточка VPS, сохранённые подключения его служб и локальные туннели WireGuard. Для повторного подключения понадобятся новые приглашения.</Description>
<Description>Сам VPS, установленные на нём службы и данные останутся на сервере.</Description>
{plan&&<><Description>Подключения служб: {plan.services.join(', ')||'нет'}. Связанные подключения аппаратов: {plan.vehicle_connections}; воркеров: {plan.worker_connections}.</Description>{plan.blocked.map(message=><Description key={message}>{message}</Description>)}</>}
</SettingsCard></LoadingRegion>:<div className="system-catalog-form">
<TextField label="Название" placeholder="Например, Макхост · сеть парка" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
<TextField label="Адрес сервера" hint={server?.services.length?'Адрес используется подключёнными службами.':'Публичный IP-адрес или DNS-имя, без протокола и порта.'} value={address} maxLength={253} disabled={busy||!!server?.services.length} onChange={e=>setAddress(e.target.value)}/>
</div>}
</Window><ToastStack items={error?[{id:'server-save',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}

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