Compare commits

..
Author SHA1 Message Date
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
DCCONSTRUCTIONS f4cdf3744a feat(ui): integrate fleet equipment and expanded workspace layouts
Compose expanded workspaces and fleet equipment through shared product controls. Integrate device surfaces and preserve the documented UI grammar.
2026-10-29 09:10:02 +03:00
DCCONSTRUCTIONS 755a124bd8 build(node): ship qualified installers with CAN maintenance and rollback
Publish qualified Node and device bundles through versioned installers. Coordinate CAN maintenance, dependency closure, retained rollback and packaging provenance.
2026-10-29 09:10:02 +03:00
DCCONSTRUCTIONS fa8bde584f feat(video): recover camera previews and reduce encoding and playout cost
Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS e06ff9a214 feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS bec20d63e2 feat(monitor): keep operator telemetry live and retire local replicas
Keep operator monitoring in bounded live snapshots and provide scoped replica retirement. Update the board dashboard and retirement regressions.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS 7878937691 feat(viewer): unify spatial clipping, planning and observation surfaces
Share spatial clipping and height slices across live planning and recorded observations. Refine scene navigation, report serialization and viewer presentation.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS f48411f8fe feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00
DCCONSTRUCTIONS 69dc566665 feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
2026-10-29 09:10:00 +03:00
DCCONSTRUCTIONS 5d56237124 feat(routers): add observed router inventory and scoped controls
Separate router discovery, evidence and authorized control from device runtime. Add Node/Core contracts and reusable operator surfaces.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 8b210258ca feat(usb-can): add isolated adapter runtime and confirmed CAN transactions
Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS f32c7b400b feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 115476d2e6 feat(sdk): add bounded media admission, diagnostics and H264 recovery
Introduce deadline-bound admission and common diagnostics for constrained links. Add H264 packetization, recovery and the measured two-thread veryfast encoder path.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 70ef3f9f1c chore(storage): bound build retention, caches and test resources
Track build ownership, qualified pins and bounded cache/log lifecycles. Move Vite fixtures to a job-owned server helper and preserve private outputs outside Git.
2026-10-29 09:09:58 +03:00
DCCONSTRUCTIONS 55f64f195b Add vector infrastructure maps and persistent location experience 2026-10-10 14:35:50 +03:00
DCCONSTRUCTIONS e095a43f00 Restore collision layers in local route planner 2026-10-10 11:33:47 +03:00
DCCONSTRUCTIONS ac980912e0 Plan translation before choosing motion toward a local goal 2026-10-10 08:29:26 +03:00
DCCONSTRUCTIONS fe495fa302 Include SOG converter bootstrap chunk in cold project packages 2026-10-10 07:40:45 +03:00
DCCONSTRUCTIONS 670e8047b3 Advance passed advisory route joints from observed body progress 2026-10-10 06:48:19 +03:00
DCCONSTRUCTIONS 621023380a Keep detector planning reserve out of native body collision map 2026-10-10 06:13:32 +03:00
DCCONSTRUCTIONS 3657998f9d Measure advisory route progress beyond approximate joints 2026-10-10 05:38:35 +03:00
DCCONSTRUCTIONS b071c6131b Retain measured local intent support across range resampling 2026-10-10 05:17:03 +03:00
DCCONSTRUCTIONS 3735f21fc2 Prevent accumulated range sampling drift in observed passages 2026-10-10 05:02:18 +03:00
DCCONSTRUCTIONS 5a68240511 Batch exact ground support queries in the control loop 2026-10-10 04:57:32 +03:00
DCCONSTRUCTIONS d8c79a1134 Carry captured sensor range envelopes into navigation observations 2026-10-10 04:18:27 +03:00
DCCONSTRUCTIONS e1fa0f8e2d Admit observed crossing areas before the unknown-road planning boundary 2026-10-10 04:00:55 +03:00
DCCONSTRUCTIONS 18e6a0e971 Version urban lidar horizon and retain measured crossing exits 2026-10-10 03:50:39 +03:00
DCCONSTRUCTIONS 857bd1fc7b Keep live guarded path when a same-leg extension is rejected 2026-10-10 03:38:04 +03:00
DCCONSTRUCTIONS 6b656a8a57 Advance observed passage intent without repeated lateral retargeting 2026-10-10 03:07:54 +03:00
DCCONSTRUCTIONS f12f5e86c9 Keep through-travel heading at lateral local goals 2026-10-10 02:48:25 +03:00
DCCONSTRUCTIONS e3d116d5b0 Select urban passage intent from measured world geometry 2026-10-10 02:12:18 +03:00
DCCONSTRUCTIONS 7ee42c44f0 Retain observed passage intent through range crop changes 2026-10-10 01:42:04 +03:00
DCCONSTRUCTIONS d0f6c80ee2 Reconstruct crossing permission from observed approach geometry 2026-10-10 01:19:52 +03:00
DCCONSTRUCTIONS 04b940e8e1 Preserve native command ownership for a moving direction hint 2026-10-10 00:46:23 +03:00
DCCONSTRUCTIONS 41fa11e6c8 Keep advisory route joints directional and preserve observed clearance 2026-10-10 00:29:41 +03:00
DCCONSTRUCTIONS daabdb9450 Keep passage clearance tied to observed spatial geometry 2026-10-10 00:12:01 +03:00
DCCONSTRUCTIONS 8bd2a9967a Choose local passage centres before route guidance 2026-10-09 23:40:19 +03:00
DCCONSTRUCTIONS e61aa6da5f Admit observed crossing ground between zebra markings 2026-10-09 23:01:29 +03:00
DCCONSTRUCTIONS 60d660f447 Allow bounded physics catch-up beyond sensor acquisition overhead 2026-10-09 22:45:15 +03:00
DCCONSTRUCTIONS be5cc98d5c Include selected source LOD in Worker scene package 2026-10-09 22:28:06 +03:00
DCCONSTRUCTIONS 37d6f90456 Select complete source LOD explicitly and reject renderer allocation failures 2026-10-09 22:24:46 +03:00
DCCONSTRUCTIONS 16865574d0 Align Nav2 with physics time and preserve complete simulation scenes 2026-10-09 22:15:20 +03:00
DCCONSTRUCTIONS 3376b1a9e6 Keep local reroutes bound to original edges within simplified guidance 2026-10-09 20:43:44 +03:00
DCCONSTRUCTIONS b2faab8ada Preserve admitted command ownership across route path refinements 2026-10-09 20:37:04 +03:00
DCCONSTRUCTIONS 286e1fbf33 Keep local navigation on its path across goal refinements 2026-10-09 20:02:11 +03:00
DCCONSTRUCTIONS 4e84aad33f Complete local XY goals without artificial terminal rotations 2026-10-09 19:08:57 +03:00
DCCONSTRUCTIONS 70e47fc83b Allow observed detours to join advisory route segments 2026-10-09 18:43:54 +03:00
DCCONSTRUCTIONS b4dab01f2a Persist rover observation configuration and calibrate Insta360 panorama 2026-10-09 18:17:54 +03:00
DCCONSTRUCTIONS c43b097a3a Bound corridor ranking work and retire aborted local actions 2026-10-09 14:36:52 +03:00
DCCONSTRUCTIONS 25e8fb7e43 Look beyond short local goals and stabilize observed surface intent 2026-10-09 14:16:53 +03:00
DCCONSTRUCTIONS 35c1b88cd7 Keep clearance refresh bounded and preserve rear recovery observation 2026-10-09 13:29:20 +03:00
DCCONSTRUCTIONS ade3c19d2a Guide local goals around observed obstacles and finish native recovery 2026-10-09 13:06:04 +03:00
DCCONSTRUCTIONS 51406fc90c Separate Nav2 body collision from ground search costs 2026-10-09 12:22:26 +03:00
DCCONSTRUCTIONS 39dd3bb551 Separate forbidden ground from body collision and retain capture phase 2026-10-09 11:39:34 +03:00
DCCONSTRUCTIONS f449caa6e0 Publish fresh front perception before supplementary neural views 2026-10-09 10:56:08 +03:00
DCCONSTRUCTIONS 4153c122a3 perf(simulation): copy native ray hits without NumPy protocol probing 2026-10-09 10:21:22 +03:00
DCCONSTRUCTIONS 0fb9636683 fix(simulation): include native experience in runtime identity 2026-10-09 10:11:59 +03:00
DCCONSTRUCTIONS 5e2e0aa4d7 perf(simulation): push current previews and streamline native sensor startup 2026-10-09 10:09:59 +03:00
DCCONSTRUCTIONS c4d4ea4cf8 Measure Worker video delivery separately from simulation cadence 2026-10-09 09:33:52 +03:00
DCCONSTRUCTIONS c4622332e6 Reconsider transient native planner rejections after bounded backoff 2026-10-09 08:40:52 +03:00
DCCONSTRUCTIONS 8c520ba32e Bound urban route clearance preference and expose Nav2 costmap diagnostics 2026-10-09 07:48:20 +03:00
DCCONSTRUCTIONS a14158e483 Bind Nav2 route transitions to current observed body support
Return a separate positive-surface body receipt before reaching a guide vertex. Keep mission arrival and command admission independent, reject stale transaction reuse, and include the bridge helper in module identity. Validate the actual Nav2 plan entry with observed, unknown and obstructed support.
2026-10-08 23:54:38 +03:00
DCCONSTRUCTIONS 31b74e4571 Add prepared urban route guidance to Gaussian simulation planning
Introduce a content-bound scene route provider, advisory runtime graph and plan-preview-launch workflow. Preserve live sensing authority and retire blocked intermediate goals without discarding final-arrival evidence. Bound native visual context losslessly and provide verified cache relocation. Full Maroseyka route qualification remains open.
2026-10-08 23:42:26 +03:00
DCCONSTRUCTIONS 2e85d95c71 Prevent goal oscillation and unintended differential drive arcs 2026-10-08 21:14:12 +03:00
DCCONSTRUCTIONS 012286e972 Align native planning clearance and admit observed tracked pivots 2026-10-08 21:14:12 +03:00
DCCONSTRUCTIONS 7f87b5aa4d Optimize range clearing with equivalent early pixel rejection 2026-10-08 21:14:11 +03:00
DCCONSTRUCTIONS 9a2ea5fc2e perf(simulation): cache SAM3 text and retain exact perception evidence 2026-10-08 18:29:32 +03:00
DCCONSTRUCTIONS 021b9f427f fix(simulation): retire rejected Nav2 intermediate goals 2026-10-08 15:29:41 +03:00
DCCONSTRUCTIONS 1f1d4a2807 perf(simulation): reuse support surface within an observation 2026-10-08 15:14:14 +03:00
DCCONSTRUCTIONS bc915c01e1 fix(simulation): consume Nav2 local action completion 2026-10-08 14:00:54 +03:00
DCCONSTRUCTIONS 6a89f809a4 fix(simulation): bound Nav2 heading discretization by rover geometry
Use pinned Smac Hybrid with a geometry-derived angular grid so rectangular starts are not rejected by coarse lattice headings. Keep the full padded footprint, unknown-space veto, TTLs, and native controller/behavior ownership.

Validated on the same archived costmap, five native pass/block scenarios, HTTP/PCL/Nav2 lifecycle and rear-obstacle checks, and 12 CPU tests. Original-route live check moved 20.13 m before its fixed wall budget; the 30 m integration criterion and full-route acceptance remain open.
2026-10-08 13:07:24 +03:00
DCCONSTRUCTIONS 140b6002e0 Restore observed recovery through native Nav2 2026-10-08 11:11:12 +03:00
DCCONSTRUCTIONS 117e937906 Link project rules to the canonical Ops architecture record 2026-10-08 11:04:30 +03:00
DCCONSTRUCTIONS 8bf6571ce2 Keep operator telemetry live-only with bounded volatile state 2026-10-08 10:54:35 +03:00
DCCONSTRUCTIONS 15a60e7e31 chore: consolidate Mission Core workspace and bound local build storage 2026-10-08 10:22:16 +03:00
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00
2291 changed files with 315018 additions and 5437 deletions
+8 -20
View File
@@ -193,7 +193,7 @@ The compact summary must cover:
- retained authority. - retained authority.
Keep manifests, long hashes, implementation files, validation logs, regressions, Keep manifests, long hashes, implementation files, validation logs, regressions,
rejected approaches, and next-stage planning in the Mission Core Ops report. rejected approaches, and next-stage planning in local engineering evidence.
Do not expose roadmap steps, next-gate checklists, internal reason taxonomies, Do not expose roadmap steps, next-gate checklists, internal reason taxonomies,
debug controls, placeholder blocks, or implementation scaffolding in product debug controls, placeholder blocks, or implementation scaffolding in product
@@ -214,26 +214,14 @@ UI.
- Keep renderer colors semantic and token-derived. Never use them to invent - Keep renderer colors semantic and token-derived. Never use them to invent
control states or persistent colored outlines. control states or persistent colored outlines.
## Ops report boundary ## Ops result boundary — owner revision, 2026-10-09
When the task includes reporting a completed LAB or architecture milestone, use Use the direct `nodedc-ops-agent` tools only for concise verified delivered
the direct `nodedc-ops-agent` tools and write titled structured blocks in this results: what works, what implementation is used, and the accepted scope.
order: Keep intermediate measurements, failed attempts, architecture proposals,
hypotheses and next-stage plans in local engineering evidence, not Ops.
1. Objective and architecture stage. Consolidate superseded intermediate blocks instead of appending a run diary.
2. Decision question and hypothesis. Do not turn a partial experiment into a completed-product claim.
3. Immutable source evidence and bounds.
4. Method, preprocessing, models, algorithms, tools, and identities.
5. Worker/runtime topology and resource policy.
6. Experimental implementation.
7. Validation and reproduced evidence.
8. Results.
9. Regressions, rejected approaches, and limitations.
10. Decision.
11. Next stage and forbidden authority.
12. Acceptance checker.
Do not turn the product UI into a duplicate Ops report.
## Validation ## Validation
+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.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/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/rover-scene/*.glb filter=lfs diff=lfs merge=lfs -text
apps/control-station/public/battery-scene/*.glb filter=lfs diff=lfs merge=lfs -text
+3
View File
@@ -56,3 +56,6 @@ node_modules
# Private experiment evidence and generated build archives. # Private experiment evidence and generated build archives.
/outputs/ /outputs/
# Packaged WireGuard binaries are published artifacts, not source.
/apps/wireguard-client/build/
+114 -6
View File
@@ -5,6 +5,76 @@ real device plugin investigates an owner-controlled XGRIDS/LixelKity K1 as a
black-box sensor. Preserve the device, the host, the working LAN, raw evidence, black-box sensor. Preserve the device, the host, the working LAN, raw evidence,
and the boundary between Mission Core and vendor-specific integration code. and the boundary between Mission Core and vendor-specific integration code.
## Single working directory — owner requirement, 2026-10-08
The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50),
in the owner rules dated 2026-10-08. The main [MISSIONCOR-1 architecture plan](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-1)
links to that record for monorepo, storage, resource and live-only telemetry rules.
- Keep exactly one Mission Core checkout on the operator Mac:
`NODEDC/NODEDC_MISSION_CORE`. Use commits and branches in that repository.
Do not create sibling clones, worktrees, baseline copies, or task-specific
Mission Core directories without a new explicit owner request.
- The canonical service on port 8000 and its LaunchAgent use this checkout.
Keep its existing runtime data under `.runtime/mission-core`; never merge
retired worktree application states into that live data directory.
- Keep private rover/CAD working materials under `private/engineering`,
local engineering reports under `outputs`, and simulation qualification
evidence under `.runtime/simulation-qualifications`. These are local data,
not source files to add to normal Git. Preserve unique evidence when moving
or retiring a workspace, and verify equality before removing duplicate files.
- Bound generated build storage. Retain the two most recent intermediate Linux
build-input packages per active build line; preserve separately designated
qualified releases and required rollback artifacts. Do not accumulate a new
full package after every iteration without retiring superseded intermediates.
- Build storage lifecycle is implemented by `scripts/packaging/build_retention.py`;
follow `docs/STORAGE_RETENTION.md`. New input generators return a persistent
active owner handle. After the remote job/transfer/qualification is confirmed
terminal, close only your own hold with `finish` (pin qualified/rollback
outcomes), review its plan and apply it as part of build completion. Never
expire active holds by age or declare unknown legacy inputs disposable.
- Run local Python validation through `scripts/check_python.py pytest|ruff|mypy`
(pass the usual file/selection arguments). It owns temporary caches, disables
persistent pytest/Ruff cache output, and cleans its own scratch after child
processes end. Never sweep another active job's cache or unknown crash residue.
- Runtime cache publication quotas and bounded service journals are defined in
`docs/STORAGE_RETENTION.md`. Existing replay/overlay data remains protected;
a full quota refuses a new copy rather than deleting recovery material.
- Check disk space before large builds or captures. Keep task scratch work
under `.runtime` and clean generated scratch at completion; do not scatter
temporary project folders through the parent repository directory.
- Owner amendment, 2026-10-19: completed simulation/urban-infrastructure
engineering experiments must not retain unlimited raw frames, render arrays
and step-by-step traces by default. At closeout preserve a compact textual
report, exact inputs/configuration/source identities, result/limitations and
regression evidence; archive text with verified hashes, then retire the
explicitly inventoried disposable derived files after all owners stop.
Use one content-addressed text copy for duplicates. Keep only the limited
visual evidence needed by the final report. Do not leave a complete new
media export after every iteration or require the owner to clean it manually.
This is a closeout obligation for engineering-owned scratch, not permission
to TTL-delete application runs, scans, accepted maps, working code, offline
dependencies, installers, qualified releases or pinned rollback. Unknown or
active ownership blocks removal; retain a deletion receipt and link the
archive from the report/Ops. See the amendment in docs/STORAGE_RETENTION.md.
- Other repositories, platform worktrees, infrastructure, DOC, workspace bridge,
Site/SEO, BIM Viewer, Device Core, Design Guideline, and Gaussian Pipeline are
separate ownership boundaries. Mission Core cleanup must not alter them.
- Operator telemetry is live-only: bounded latest values in RAM, expiry and a
daily reset. Do not reintroduce a local time-series database or persistent raw
monitoring history on the Mac. Diagnostic logs must rotate. Future historical
monitoring requires an explicitly provisioned separate service; simulation
evidence and recordings have a separate lifecycle and must not be deleted as
part of telemetry cleanup.
- Owner amendment, 2026-10-20: new semantic-learning images, observations,
datasets, checkpoints and heavy experiments belong to a separate portable
persistent store on Worker 006, outside the source checkout and container
writable layer. Never accumulate them on the operator Mac or add a local
fallback. Core may keep viewer scenes, semantic results and bounded edit
metadata. Saving an edit is not dataset preparation or training acceptance;
retain the immutable algorithm result and human provenance separately.
See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates.
## Non-negotiable safety boundaries ## Non-negotiable safety boundaries
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE - Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
@@ -173,7 +243,7 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
canonical Design Guideline exports. canonical Design Guideline exports.
- Product UI must not expose implementation steps, roadmap gates, internal - Product UI must not expose implementation steps, roadmap gates, internal
reason taxonomies, debug controls, placeholder status blocks, or temporary reason taxonomies, debug controls, placeholder status blocks, or temporary
experiment scaffolding. Keep these in Ops, engineering reports, or developer experiment scaffolding. Keep these in local engineering reports or developer
tooling. tooling.
- Extend one reusable application pattern instead of adding per-LAB layouts. - Extend one reusable application pattern instead of adding per-LAB layouts.
A new LAB supplies data and renderer configuration; it does not invent a new A new LAB supplies data and renderer configuration; it does not invent a new
@@ -210,11 +280,49 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
- The compact summary must explain the decision question, immutable source, - The compact summary must explain the decision question, immutable source,
tested method/models/algorithms, experimental mode, principal result, tested method/models/algorithms, experimental mode, principal result,
limitations, and retained authority. It is not the engineering report. limitations, and retained authority. It is not the engineering report.
- The complete engineering report belongs in the Mission Core Ops card as - Owner reporting rule (2026-10-09): Ops contains concise, verified delivered
titled structured blocks: objective and architecture stage, source evidence, results only: what works, the implementation used, and its accepted scope.
method/models/algorithms, worker/runtime, implementation, validation, Keep intermediate experiments, failed attempts, architecture proposals,
results, regressions and limitations, decision, next stage, and acceptance detailed logs and future plans in local engineering evidence, not Ops.
checker. Consolidate superseded intermediate blocks instead of appending a run diary.
Never present a partial experiment as a completed product result.
- Spatial evidence uses 3D by default. Image-space reprojection may be offered - Spatial evidence uses 3D by default. Image-space reprojection may be offered
as a 2D diagnostic mode inside the same reusable viewer. Primary evidence as a 2D diagnostic mode inside the same reusable viewer. Primary evidence
viewers must provide the canonical expand/restore action. viewers must provide the canonical expand/restore action.
## Urban semantic agent contract — owner requirement, 2026-10-26
- Product foundation: read `docs/SCENE_SEMANTICS_PRODUCT_CONCEPT.md`. Each scan is
a standalone local scene, including unnamed/unmapped locations. Raw recorded
sensor points support localization; Gaussian observations support the current
semantic research. Never substitute Gaussian-derived geometry for raw points.
- No GPS/address/public-map prerequisite and no automatic cross-scan geographic
matching, overlap search, registration or merging. Those require a separate
explicit owner request. Named train/evaluation source lists do not authorize
geographic investigation. Preserve source lineage and evaluation honesty.
- Crosswalks are functionally important; the target includes all observed road
markings for scene context, interface/product value and difficult-task
validation. Do not reduce the scope to demo-only markings or crosswalks only.
- For automated infrastructure annotation, dataset preparation and learning,
begin with live Ops MISSIONCOR-93 (agent contract) and MISSIONCOR-88 (product),
then `docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md`. Reuse the current hypothesis
register and existing experiments; a new chat does not reset the investigation.
- The owner explicitly requests MISSIONCOR-93 to hold current architecture,
rules, bounded next steps and portable handoff. This is the scoped exception
to the earlier delivered-results-only Ops rule. Keep raw logs/media in local
engineering evidence; update the current card blocks after meaningful changes.
- Root owns the useful outcome, real dispatch, integration and final decision.
Use one reusable critic and an optional bounded research scout, at most two
active helpers and no nested delegation. Send compact briefs, not full history.
- New annotation cycles use the v2 objective/dispatch contract. Approved partial
annotations are distinct from completing the enclosing product work package.
Handle introduced critical regressions within the session or revert/isolate
the change. Do not declare success merely because a ledger or test completed.
- Choose reusable pipelines against actual inputs/outputs and accumulated
evidence before narrow tuning. Every closed hypothesis states tested scope,
supporting artifacts and a substantive condition for reopening. Do not repeat
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.
+25
View File
@@ -207,6 +207,12 @@ See [the Dataset Gateway plan](docs/14_LIDAR_DATASET_GATEWAY.md),
## Simulation Polygon ## Simulation Polygon
Current AI Polygon purpose, architecture, measured status and experiment plan:
[AI Polygon workflow](docs/AI_POLYGON_WORKFLOW.md), reconciled 2026-10-02.
It uses Isaac and shared AI modules entirely on Worker006, with operator video
on the Mac. The Gazebo/PX4 S0/S1 account below is a historical profile with its
own evidence; it must not be read as the current AI Polygon implementation.
Mission Core now has a parallel Polygon product branch for reproducible Mission Core now has a parallel Polygon product branch for reproducible
autonomy qualification. Mission Core owns scenarios, qualification-run autonomy qualification. Mission Core owns scenarios, qualification-run
lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4 lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4
@@ -632,3 +638,22 @@ Real captures, projects, router metadata, serials, credentials, maps, images,
and logs under `.runtime/`, canonical evidence roots and legacy `sessions/` are and logs under `.runtime/`, canonical evidence roots and legacy `sessions/` are
ignored by normal Git. Redacted manifests and SHA-256 inventories are committed; ignored by normal Git. Redacted manifests and SHA-256 inventories are committed;
encrypted/replicated artifact storage remains a deployment decision. encrypted/replicated artifact storage remains a deployment decision.
## Local working directory
The operator installation uses one checkout, `NODEDC_MISSION_CORE`, including
the service on `http://127.0.0.1:8000`. Work on source through commits and branches
in this checkout; do not create sibling Mission Core worktrees or project copies.
- `.runtime/mission-core`: existing application data and location registry.
- `.runtime/simulation-qualifications`: preserved simulation runs and evidence.
- `private/engineering`: private DCD-006, camera-mount and K1 modelling materials.
- `outputs`: local engineering reports and retained task outputs.
- `.runtime/archived-app-state`: retired worktree data, separate from live state.
The 2026-10-08 consolidation preserved the operator sources in
`archive/operator-before-consolidation-20261008` and the separate unfinished
simulation sources in `work/simulation-before-consolidation-20261008`.
These are source-preservation branches, not additional accepted deployments.
The local move, hash-verification and cleanup receipts are retained under
`.runtime/consolidation-20261008`. No remote branches were changed.
+37 -1
View File
@@ -19,9 +19,11 @@
"@rerun-io/web-viewer": "0.36.3", "@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1", "meshoptimizer": "1.1.1",
"playcanvas": "2.21.4", "playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"three": "0.185.1" "three": "0.185.1",
"three-mesh-bvh": "0.9.15"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
@@ -1756,6 +1758,16 @@
"node": ">=18.3.0" "node": ">=18.3.0"
} }
}, },
"node_modules/polygon-clipping": {
"version": "0.15.7",
"resolved": "https://registry.npmjs.org/polygon-clipping/-/polygon-clipping-0.15.7.tgz",
"integrity": "sha512-nhfdr83ECBg6xtqOAJab1tbksbBAOMUltN60bU+llHVOL0e5Onm1WpAXXWXVB39L8AJFssoIhEVuy/S90MmotA==",
"license": "MIT",
"dependencies": {
"robust-predicates": "^3.0.2",
"splaytree": "^3.1.0"
}
},
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.19", "version": "8.5.19",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",
@@ -1816,6 +1828,12 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/rollup": { "node_modules/rollup": {
"version": "4.62.2", "version": "4.62.2",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
@@ -1887,12 +1905,30 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/splaytree": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/splaytree/-/splaytree-3.2.3.tgz",
"integrity": "sha512-7OXrNWzy6CK+r7Ch9OLPBDTKfB6XlWHjX4P0RU5B3IgFuWPeYN0XtRtlexGRjgbQxpfaUve6jTAwBGWuGntz/w==",
"license": "MIT",
"engines": {
"node": ">=18.20 || >=20"
}
},
"node_modules/three": { "node_modules/three": {
"version": "0.185.1", "version": "0.185.1",
"resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz", "resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
"integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==", "integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/three-mesh-bvh": {
"version": "0.9.15",
"resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.15.tgz",
"integrity": "sha512-9xdEDkCzFoT8VPFH9DznwFSdbaIEjMvM106Iqq7TJurrIheUKDcdW4prfJTCxryih4XS/UxWs0H3K4MLMRFyOQ==",
"license": "MIT",
"peerDependencies": {
"three": ">= 0.159.0"
}
},
"node_modules/tinyglobby": { "node_modules/tinyglobby": {
"version": "0.2.17", "version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+4 -2
View File
@@ -9,7 +9,7 @@
"prebuild": "node scripts/install-rerun-navigation.mjs", "prebuild": "node scripts/install-rerun-navigation.mjs",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"preview": "vite preview", "preview": "vite preview",
"test:unit": "node --test test/*.test.mjs", "test:unit": "node --test --test-concurrency=1 test/*.test.mjs",
"typecheck": "tsc -b --pretty false" "typecheck": "tsc -b --pretty false"
}, },
"dependencies": { "dependencies": {
@@ -23,9 +23,11 @@
"@rerun-io/web-viewer": "0.36.3", "@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1", "meshoptimizer": "1.1.1",
"playcanvas": "2.21.4", "playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"three": "0.185.1" "three": "0.185.1",
"three-mesh-bvh": "0.9.15"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
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
}
@@ -0,0 +1,174 @@
{
"schema_version": "missioncore.rover-motion/v1",
"source_scene": "DCD-006_rover_v020.blend",
"source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79",
"source_saved": false,
"visual_sha256": "4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e",
"forward_axis": "+X",
"up_axis": "Y",
"track_centres_m": {
"L": 0.3425,
"R": -0.3425
},
"track_width_m": 0.685,
"shift_m": [
-0.05350000038743019,
0.0,
0.0
],
"length_m": 2.222,
"pitch_m": 0.0505,
"phase_m": 0.03069696662739778,
"segments": [
[
"arc",
0,
0.060539054924808725,
[
-0.16593354688111153,
0.32184557191629776,
0.0655,
2.3390854961098873
]
],
[
"line",
0.060539054924808725,
0.5760464371429339,
[
-0.15575880346026824,
0.3865504758751169,
0.9878611291422765,
-0.1553395942113481,
0.15533959421134813,
0.9878611291422766
]
],
[
"arc",
0.6365854920677426,
0.15172294911931034,
[
0.40182697,
0.22413776,
0.07382606110411796,
1.4148251155784564
]
],
[
"line",
0.7883084411870529,
0.1629407568053742,
[
0.46102862009488454,
0.18003048254840684,
-0.5974486081464921,
-0.8019072020027126,
0.8019072020027126,
-0.5974486081464921
]
],
[
"arc",
0.9512491979924271,
0.06094648310379254,
[
0.31115497,
0.0885,
0.0655,
-0.6403156687217281
]
],
[
"line",
1.0121956810962196,
0.7185584980197575,
[
0.31115497,
0.022999999999999993,
-1.0,
0.0,
-0.0,
-1.0
]
],
[
"arc",
1.730754179115977,
0.15545137821999958,
[
-0.40740352801975754,
0.0885,
0.0655,
-1.5707963267948966
]
],
[
"line",
1.8862055573359766,
0.33579444266402353,
[
-0.45291987081346463,
0.1356010885085021,
0.719100587916063,
0.6949059968504895,
-0.6949059968504895,
0.719100587916063
]
]
],
"link_count": 44,
"wheels": [
{
"node": "R_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "R_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_DRIVE",
"radius_m": 0.07233592163526643
},
{
"node": "L_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "L_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_DRIVE",
"radius_m": 0.07233592163526643
}
],
"dimensions_m": [
1.1630001068115234,
0.9049999713897705,
0.7378441095352173
],
"minimum_m": [
-0.5814999938011169,
-0.45249998569488525,
-0.003844098187983036
],
"method": "44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; no track contact dynamics"
}
Binary file not shown.
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
# Panorama optical conventions
`frontend/src/panoramaCalibration.ts` adapts calibration layouts and projection
conventions from [GyroView](https://github.com/bubo-squared/GyroView), revision
`ae5c22b155ab4ec9c28d141e61340ca2d6f94994`. This is not Insta360 Media SDK.
Legacy radius angles, polynomial normalization and lens-pose signs are
open-source interpretations; they require qualification on the actual live camera.
No GyroView application, recording parser or dependency tree is included.
MIT License
Copyright (c) 2026 Bubo²
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -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 // Validate the complete set before changing any installed file. A package
// upgrade, corrupt artifact or independently modified wrapper fails closed. // upgrade, corrupt artifact or independently modified wrapper fails closed.
const writes = []; const writes = [];
@@ -39,9 +59,9 @@ for (const [name, identity] of Object.entries(manifest.files)) {
const current = readFileSync(resolve(packageRoot, name)); const current = readFileSync(resolve(packageRoot, name));
let output; let output;
if (additions[name]) { if (additions[name]) {
const { marker, code } = additions[name]; const { marker, code, previousCode } = additions[name];
const source = current.toString("utf8"); 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) { if (sha(original) !== identity.upstreamSha256 || original.split(marker).length !== 2) {
throw new Error(`Unexpected upstream wrapper: ${name}`); throw new Error(`Unexpected upstream wrapper: ${name}`);
} }
@@ -49,7 +69,7 @@ for (const [name, identity] of Object.entries(manifest.files)) {
} else { } else {
output = readFileSync(resolve(vendorRoot, identity.artifact)); output = readFileSync(resolve(vendorRoot, identity.artifact));
if (sha(output) !== identity.sha256) throw new Error(`Corrupt navigation artifact: ${name}`); 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}`); throw new Error(`Unexpected installed runtime: ${name}`);
} }
} }
@@ -0,0 +1,4 @@
<!doctype html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Worker video</title></head>
<body><video id="worker-video" autoplay muted playsinline></video><audio id="worker-audio" muted></audio>
<script type="module" src="/src/components/simulation/streamFrame.ts"></script></body></html>
+5 -5
View File
@@ -722,9 +722,9 @@ export default function App() {
workspace.navigationOpen && activeRoot !== null workspace.navigationOpen && activeRoot !== null
} }
contentOpen={workspace.contentOpen && activeDefinition !== null} contentOpen={workspace.contentOpen && activeDefinition !== null}
contentExpanded={workspace.contentExpanded} contentExpanded
header={header} header={header}
stage={ stage={activeDefinition ? null :
<LandingStage <LandingStage
root={currentRoot} root={currentRoot}
backendStatus={runtime.backendStatus} backendStatus={runtime.backendStatus}
@@ -786,6 +786,7 @@ export default function App() {
content={activeDefinition ? ( content={activeDefinition ? (
<ApplicationPanel <ApplicationPanel
key={activeDefinition.id} key={activeDefinition.id}
allowFullscreen={activeDefinition.kind === "vehicles"}
eyebrow={activeDefinition.eyebrow} eyebrow={activeDefinition.eyebrow}
title={ title={
activeDefinition.kind === "vehicles" activeDefinition.kind === "vehicles"
@@ -797,8 +798,7 @@ export default function App() {
: activeDefinition.title : activeDefinition.title
} }
description={activeDefinition.description} description={activeDefinition.description}
expanded={workspace.contentExpanded} expanded
onExpandedChange={workspace.setContentExpanded}
headerTools={ headerTools={
activeDefinition.kind === "device" ? ( activeDefinition.kind === "device" ? (
<StatusBadge tone={phaseTone(runtime.state?.phase)}> <StatusBadge tone={phaseTone(runtime.state?.phase)}>
@@ -836,7 +836,7 @@ export default function App() {
/> />
) : activeDefinition.kind === "missions" ? ( ) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} /> <div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? ( ) : activeDefinition.kind === "vehicles" ? <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> <StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? ( ) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control laboratoryAnnotation.control
@@ -2,8 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { createIsolatedRerunHost } from "./rerun/isolatedRerunHost"; import { createIsolatedRerunHost } from "./rerun/isolatedRerunHost";
import { keepRecordedBlueprintSession } from "../core/observation/recordedBlueprintLifecycle"; import { keepRecordedBlueprintSession } from "../core/observation/recordedBlueprintLifecycle";
import { import {
RECORDED_RERUN_ORBITAL_EYE, selectRecordedRerunCameraEye,
RECORDED_RERUN_PLAN_EYE,
type RecordedRerunCameraEye, type RecordedRerunCameraEye,
} from "./rerun/recordedRerunCameraJournal"; } from "./rerun/recordedRerunCameraJournal";
@@ -148,10 +147,7 @@ export interface RerunViewportProps {
interface RerunBlueprintChannel { interface RerunBlueprintChannel {
endpointUrl: string; endpointUrl: string;
cameraContract?: string | null; cameraContract?: string | null;
appliedFollowTrajectory?: boolean | null;
pendingFollowCameraEye?: RecordedRerunCameraEye | null;
getCameraEye?: () => RecordedRerunCameraEye | null; getCameraEye?: () => RecordedRerunCameraEye | null;
getCurrentTimeNs?: () => number | null;
channel: { channel: {
readonly ready: boolean; readonly ready: boolean;
send_rrd: (rrdBytes: Uint8Array) => void; send_rrd: (rrdBytes: Uint8Array) => void;
@@ -1649,16 +1645,9 @@ function RerunViewportInstance({
blueprintChannel = { blueprintChannel = {
endpointUrl: recordedBlueprintUrl, endpointUrl: recordedBlueprintUrl,
cameraContract: null, cameraContract: null,
appliedFollowTrajectory: null,
pendingFollowCameraEye: null,
getCameraEye: () => "get_camera_eye" in viewer getCameraEye: () => "get_camera_eye" in viewer
? viewer.get_camera_eye() ? viewer.get_camera_eye()
: null, : null,
getCurrentTimeNs: () => {
const currentIdentity = recordedIdentityRef.current;
if (!currentIdentity) return null;
return viewer.get_current_time(currentIdentity.recordingId, "session_time");
},
channel, channel,
}; };
blueprintChannelRef.current = blueprintChannel; blueprintChannelRef.current = blueprintChannel;
@@ -2114,29 +2103,7 @@ function RerunViewportInstance({
); );
const cameraContractChanged = active.cameraContract !== cameraContract; const cameraContractChanged = active.cameraContract !== cameraContract;
const abort = new AbortController(); const abort = new AbortController();
const previousFollow = active.appliedFollowTrajectory ?? false; const requestBlueprint = async (cameraEye?: RecordedRerunCameraEye) => {
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");
}
return fetchRecordedBlueprintRrd(recordedBlueprintUrl, return fetchRecordedBlueprintRrd(recordedBlueprintUrl,
{...sceneSettings, showPoints: sceneSettings.showPoints && !pointDisplay.hidePoints}, identity, { {...sceneSettings, showPoints: sceneSettings.showPoints && !pointDisplay.hidePoints}, identity, {
displayPointBank: pointDisplay.bank, displayPointBank: pointDisplay.bank,
@@ -2152,12 +2119,11 @@ function RerunViewportInstance({
unifiedCameraShare: recordedUnifiedCameraShare, unifiedCameraShare: recordedUnifiedCameraShare,
planView: recordedPlanView, planView: recordedPlanView,
cameraEye, cameraEye,
eyeRelativeToTracking, // The native controller owns continuous tracking and its world eye.
// Only following-eye transitions need a pose at the cursor. Supplying // Reinterpreting this as a rig-relative eye snaps an off-centre view
// time for display-only updates makes the API scan the entire archive // back onto the rig. It also needlessly scans the recording for a pose.
// for camera bounds, although neither the camera nor its pose changed. eyeRelativeToTracking: false,
currentTimeNs: eyeRelativeToTracking ? currentTimeNs : undefined, reactivateUpdates: true,
reactivateUpdates,
}); });
}; };
const canApply = () => ( const canApply = () => (
@@ -2175,43 +2141,14 @@ function RerunViewportInstance({
return true; return true;
}; };
void (async () => { void (async () => {
const firstEye = disablingFollow // Reactivating a blueprint replaces the edited native store. Carry its
? transitionEye ?? undefined // actual eye through follow/layer/display changes in one update; only
: !enablingFollow && (cameraContractChanged || pendingFollowEye) // explicit reset and plan/3D changes select a startup preset.
? pendingFollowEye ?? (recordedPlanView ? RECORDED_RERUN_PLAN_EYE : RECORDED_RERUN_ORBITAL_EYE) const cameraEye = selectRecordedRerunCameraEye(
: !enablingFollow ? active.getCameraEye?.() ?? undefined : undefined; cameraContractChanged, recordedPlanView, active.getCameraEye?.() ?? null,
const firstEyeIsTrackingRelative = Boolean(firstEye) && (
disablingFollow || recordedFollowTrajectory
); );
const firstPayload = await requestBlueprint( const payload = await requestBlueprint(cameraEye);
firstEye, if (applyPayload(payload)) active.cameraContract = cameraContract;
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;
})().catch((error: unknown) => { })().catch((error: unknown) => {
// The recording remains usable with its embedded default blueprint. // The recording remains usable with its embedded default blueprint.
// A later settings change retries through the same small channel. // A later settings change retries through the same small channel.
@@ -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'?'Локальный профиль':'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>Сохраняется на этом компьютере для этой батареи. 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,34 @@
import {useState} from 'react';
import {ColorField,ControlRow,Description,LevelButton,RangeControl,Select,SettingsCard} from '@nodedc/ui-react';
import {batteryIndicatorColor,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 <><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="Цвет заливки и диапазоны уровня заряда для этой батареи.">
<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="observation-actions">{[10,25,80].map(soc=><LevelButton key={soc} label="Предпросмотр заряда" value={soc/100} valueText={`${soc}%`} fillColor={batteryIndicatorColor(i,soc)} disabled/>)}</div>
</SettingsCard>}</>;
}
@@ -0,0 +1,20 @@
import type {CellMarkingAppearance} from '../../core/batteryScene/appearance';
import {BatteryCellLabels} from './BatteryCellLabels';
import type {PlayCanvasViewerProps} from '../rover/playcanvas/PlayCanvasViewer';
import {useMemo,useState} from 'react';
import {Description} from '@nodedc/ui-react';
import {SceneEditor} from '../rover/editor/RoverScene';
import {useSceneDocument} from '../../core/roverScene/useSceneDocument';
import {batterySceneProfile,defaultBatteryScene} from '../../core/batteryScene/profile';
export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){
const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]);
const scene=useSceneDocument(deviceId,profile);
const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading');
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R05">
<SceneEditor scene={scene} defaults={defaultBatteryScene} 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,23 @@
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,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
import {batteryViewHeight,batteryViewHeightKey,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 [height,setHeight]=useState(()=>{try{return batteryViewHeight(localStorage.getItem(batteryViewHeightKey(deviceId)),window.innerHeight);}catch{return batteryViewHeight(null,window.innerHeight);}});
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{
if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return;
event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back();
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
const commitHeight=(value:number)=>{try{localStorage.setItem(batteryViewHeightKey(deviceId),JSON.stringify({height:value}));setError('');}catch{setError('Не удалось сохранить высоту окна на этом компьютере.');}};
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>;
}
@@ -171,7 +171,7 @@ export function CanonicalRecordedLabReplay<
> >
{splitView || paneToolbarsAlwaysVisible ? ( {splitView || paneToolbarsAlwaysVisible ? (
<div <div
className="m4-replay-threat-visual__pane-toolbar" className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="media" data-pane-toolbar="media"
data-multi-semantic={mediaMultiLayer ? "true" : undefined} data-multi-semantic={mediaMultiLayer ? "true" : undefined}
> >
@@ -190,7 +190,7 @@ export function CanonicalRecordedLabReplay<
> >
{splitView || paneToolbarsAlwaysVisible ? ( {splitView || paneToolbarsAlwaysVisible ? (
<div <div
className="m4-replay-threat-visual__pane-toolbar" className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="spatial" data-pane-toolbar="spatial"
> >
{spatialLeadingControl} {spatialLeadingControl}
@@ -83,7 +83,7 @@ export function LaboratoryEvidenceViewer<
}, [expanded, onExpandedChange]); }, [expanded, onExpandedChange]);
const controls = ( const controls = (
<div className="laboratory-evidence-viewer__controls"> <div className="laboratory-evidence-viewer__controls nodedc-viewport-controls">
{actions} {actions}
{modeControlsVisible && secondaryMode ? ( {modeControlsVisible && secondaryMode ? (
<SegmentedControl <SegmentedControl
@@ -137,7 +137,7 @@ export function LaboratoryEvidenceViewer<
{children} {children}
</div> </div>
{transport ? ( {transport ? (
<div className="laboratory-evidence-viewer__transport"> <div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport} {transport}
</div> </div>
) : null} ) : null}
@@ -149,7 +149,7 @@ export function LaboratoryEvidenceViewer<
</div> </div>
{overlay} {overlay}
{transport ? ( {transport ? (
<div className="laboratory-evidence-viewer__transport"> <div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport} {transport}
</div> </div>
) : null} ) : null}
@@ -265,6 +265,8 @@ LaboratoryMetricEvidenceSceneHandle,
showCurrentIncrement: boolean; showCurrentIncrement: boolean;
showLocalSurface: boolean; showLocalSurface: boolean;
showRollingMap: boolean; showRollingMap: boolean;
showReferenceGeometry?: boolean;
showRenderStats?: boolean;
showLowStep?: boolean; showLowStep?: boolean;
pointSemanticClassIds?: readonly (number | null)[]; pointSemanticClassIds?: readonly (number | null)[];
semanticClasses?: readonly RecordedEvidenceSemanticClass[]; semanticClasses?: readonly RecordedEvidenceSemanticClass[];
@@ -287,6 +289,8 @@ LaboratoryMetricEvidenceSceneHandle,
showLocalSurface, showLocalSurface,
showRollingMap, showRollingMap,
showLowStep = true, showLowStep = true,
showReferenceGeometry = true,
showRenderStats = true,
pointSemanticClassIds, pointSemanticClassIds,
semanticClasses, semanticClasses,
semanticPalette, semanticPalette,
@@ -746,6 +750,7 @@ LaboratoryMetricEvidenceSceneHandle,
if (!host || !content) return; if (!host || !content) return;
clearGroup(content); clearGroup(content);
if (!showReferenceGeometry) { requestRenderRef.current(); return; }
const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM; const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM;
const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2; const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2;
const corridorMesh = new THREE.Mesh( const corridorMesh = new THREE.Mesh(
@@ -806,6 +811,7 @@ LaboratoryMetricEvidenceSceneHandle,
content.add(grid); content.add(grid);
requestRenderRef.current(); requestRenderRef.current();
}, [ }, [
showReferenceGeometry,
corridor.forwardLengthM, corridor.forwardLengthM,
corridor.halfWidthM, corridor.halfWidthM,
corridor.rearMarginM, corridor.rearMarginM,
@@ -912,7 +918,7 @@ LaboratoryMetricEvidenceSceneHandle,
{renderError ? <p>{renderError}</p> : null} {renderError ? <p>{renderError}</p> : null}
</div> </div>
<div className="laboratory-metric-evidence-scene__legend"> <div className="laboratory-metric-evidence-scene__legend">
{renderStats ? ( {showRenderStats && renderStats ? (
<span <span
data-decision="performance" data-decision="performance"
title="CPU-время отправки последнего WebGL render pass; это не GPU timer. В покое сцена не перерисовывается." title="CPU-время отправки последнего WebGL render pass; это не GPU timer. В покое сцена не перерисовывается."
@@ -101,7 +101,7 @@ export function LaboratoryReviewWorkspaceFrame({
keepFocusInside(event, event.currentTarget); keepFocusInside(event, event.currentTarget);
}} }}
> >
<header className="laboratory-review-workspace__toolbar">{toolbar}</header> <header className="laboratory-review-workspace__toolbar nodedc-viewport-controls">{toolbar}</header>
<div className="laboratory-review-workspace__stage">{stage}</div> <div className="laboratory-review-workspace__stage">{stage}</div>
{inspector ? <footer className="laboratory-review-workspace__inspector">{inspector}</footer> : null} {inspector ? <footer className="laboratory-review-workspace__inspector">{inspector}</footer> : null}
{overlays} {overlays}
@@ -1,3 +1,4 @@
import {heightSlice} from "../../core/heightSlice";
import {useEffect,useRef,useState} from 'react'; import {useEffect,useRef,useState} from 'react';
import {Button,LoadingRegion,RangeControl} from '@nodedc/ui-react'; import {Button,LoadingRegion,RangeControl} from '@nodedc/ui-react';
import {createIsolatedRerunHost} from '../rerun/isolatedRerunHost'; import {createIsolatedRerunHost} from '../rerun/isolatedRerunHost';
@@ -26,16 +27,20 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
const optionsRef=useRef(options);optionsRef.current=options; const optionsRef=useRef(options);optionsRef.current=options;
const stateRef=useRef({active,revision});stateRef.current={active,revision}; const stateRef=useRef({active,revision});stateRef.current={active,revision};
const ceilingRef=useRef<number|null>(null); const ceilingRef=useRef<number|null>(null);
const floorRef=useRef<number|null>(null);
const boundsRef=useRef<{min:number;max:number}|null>(null); const boundsRef=useRef<{min:number;max:number}|null>(null);
const host=useRef<HTMLDivElement>(null); const host=useRef<HTMLDivElement>(null);
const [state,setState]=useState('loading'),[retry,setRetry]=useState(0); const [state,setState]=useState('loading'),[retry,setRetry]=useState(0);
const [bounds,setBounds]=useState<{min:number;max:number}|null>(null); const [bounds,setBounds]=useState<{min:number;max:number}|null>(null);
const [ceiling,setCeiling]=useState<number|null>(null); const [ceiling,setCeiling]=useState<number|null>(null);
const [floor,setFloor]=useState<number|null>(null);
useEffect(()=>{
ceilingRef.current=null;floorRef.current=null;setCeiling(null);setFloor(null);
},[runId]);
useEffect(()=>{ useEffect(()=>{
ceilingRef.current=null;
const next=heightBounds&&Number.isFinite(heightBounds.min)&&Number.isFinite(heightBounds.max)&&heightBounds.max>heightBounds.min?heightBounds:null; const next=heightBounds&&Number.isFinite(heightBounds.min)&&Number.isFinite(heightBounds.max)&&heightBounds.max>heightBounds.min?heightBounds:null;
boundsRef.current=next; boundsRef.current=next;
setBounds(next);setCeiling(null); setBounds(next);
},[runId,heightBounds?.min,heightBounds?.max]); },[runId,heightBounds?.min,heightBounds?.max]);
useEffect(()=>{ useEffect(()=>{
if(!host.current)return; if(!host.current)return;
@@ -54,6 +59,7 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
stopStream=startPlanningSceneStream({ stopStream=startPlanningSceneStream({
url:`${plannerBase}/live-tests/${runId}/scene-delta.rrd`, url:`${plannerBase}/live-tests/${runId}/scene-delta.rrd`,
snapshot:()=>({...stateRef.current,options:{...optionsRef.current, snapshot:()=>({...stateRef.current,options:{...optionsRef.current,
...(floorRef.current===null?{}:{floor_m:floorRef.current}),
...(ceilingRef.current===null?{}:{ceiling_m:ceilingRef.current})}}), ...(ceilingRef.current===null?{}:{ceiling_m:ceilingRef.current})}}),
apply:async(bytes,delivery)=>{ apply:async(bytes,delivery)=>{
if(disposed)return; if(disposed)return;
@@ -62,9 +68,6 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
const previous=boundsRef.current; const previous=boundsRef.current;
if(!previous||previous.min!==next.min||previous.max!==next.max){ if(!previous||previous.min!==next.min||previous.max!==next.max){
boundsRef.current=next;setBounds(next); boundsRef.current=next;setBounds(next);
if(ceilingRef.current!==null&&(ceilingRef.current<next.min||ceilingRef.current>next.max)){
ceilingRef.current=null;setCeiling(null);
}
} }
} }
sceneAvailable=true; sceneAvailable=true;
@@ -89,15 +92,15 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
return()=>{disposed=true;stopStream?.();reporter.dispose();clearTimeout(timeout);runtime.dispose();}; return()=>{disposed=true;stopStream?.();reporter.dispose();clearTimeout(timeout);runtime.dispose();};
},[runId,retry]); },[runId,retry]);
const sourceBounds=bounds??heightBounds; const sourceBounds=bounds??heightBounds;
const rangeBounds=sourceBounds?{min:Math.min(sourceBounds.min,0),max:CLIP_CEILING_M}:null; const rangeBounds=sourceBounds?{min:Math.min(sourceBounds.min,0,floor??Infinity),max:Math.max(CLIP_CEILING_M,sourceBounds.max,ceiling??-Infinity)}:null;
return <LoadingRegion loading={state==='loading'} label="Загрузка эталона и нового прохода" className="planning-live__scene"> return <LoadingRegion loading={state==='loading'} label="Загрузка эталона и нового прохода" className="planning-live__scene">
<div ref={host} className="session-overview__runtime rerun-single-view-content" style={{visibility:state==='ready'?'visible':'hidden'}} /> <div ref={host} className="session-overview__runtime rerun-single-view-content" style={{visibility:state==='ready'?'visible':'hidden'}} />
{rangeBounds&&state==='ready'&&<div className="session-overview__height"> {rangeBounds&&state==='ready'&&<div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={ceiling??rangeBounds.max} min={rangeBounds.min} max={rangeBounds.max} step="any" <RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor??rangeBounds.min,ceiling??rangeBounds.max]} min={rangeBounds.min} max={rangeBounds.max} step="any"
formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')} formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')}
onChange={value=>{ onChange={value=>{
const next=value>=rangeBounds.max-Math.max(1,rangeBounds.max-rangeBounds.min)*1e-9?null:value; const next=heightSlice(value,[rangeBounds.min,rangeBounds.max]);
ceilingRef.current=next;setCeiling(next); floorRef.current=next.floor;setFloor(next.floor);ceilingRef.current=next.ceiling;setCeiling(next.ceiling);
}}/> }}/>
</div>} </div>}
{state==='error'&&<div className="session-overview__empty"><span>Обновление сцены недоступно.</span><Button onClick={()=>setRetry(v=>v+1)}>Повторить подключение сцены</Button></div>} {state==='error'&&<div className="session-overview__empty"><span>Обновление сцены недоступно.</span><Button onClick={()=>setRetry(v=>v+1)}>Повторить подключение сцены</Button></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}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
</SettingsCard>;
}
@@ -0,0 +1,15 @@
import {useRef} from 'react';
import {Button,Description,Icon,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {useNetBirdBackups} from '../../core/fleet/useNetBirdBackups';
export function NetBirdBackups(){
const {items,loading,busy,error,upload}=useNetBirdBackups();const input=useRef<HTMLInputElement>(null);
return <SettingsCard title="Резервные копии сети" description="Полная копия базы NetBird, ключей и зарегистрированных устройств хранится в этом Mission Core отдельно от VPS. Она содержит секреты сети." actions={<StatusBadge tone={items.length?'success':'warning'}>{loading?'Проверяем хранилище':items.length?`Сохранено: ${items.length}`:'Копий пока нет'}</StatusBadge>}>
<Description>После изменения устройств или настроек сети сохраните свежую копию. Автоматическое получение копий пока не настроено.</Description>
<input ref={input} type="file" accept=".zip,application/zip" hidden aria-label="Полная резервная копия NetBird" disabled={busy} onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(file)void upload(file);}}/>
<Button icon={<Icon name="upload"/>} loading={busy} disabled={busy||loading} onClick={()=>input.current?.click()}>Сохранить копию в Mission Core</Button>
{error&&<StatusBadge tone="danger">{error}</StatusBadge>}
{items.map(item=><SettingsCard key={item.id} title={item.domain} description={`Сохранена ${new Date(item.stored_at).toLocaleString('ru-RU')} · ${(item.bytes/1024/1024).toFixed(1)} МиБ · Контрольные суммы проверены`}>
<Button icon={<Icon name="download"/>} onClick={()=>{const link=document.createElement('a');link.href=`/api/v1/fleet/netbird/backups/${item.id}/download`;link.download='mission-core-netbird-backup.zip';link.click();}}>Скачать для восстановления</Button>
</SettingsCard>)}
</SettingsCard>;
}
@@ -0,0 +1,36 @@
import {useEffect,useState} from 'react';
import {Button,Description,Icon,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
import {InstallerCard} from './InstallerCard';
import {NetBirdBackups} from './NetBirdBackups';
import {useNetBird,type NetBirdState} from '../../core/fleet/useNetBird';
const labels:Record<NetBirdState,string>={missing_client:'Клиент не установлен',unsupported_client:'Требуется другая версия клиента',unavailable:'Клиент недоступен',disconnected:'Не подключён',connecting:'Подключение',connected:'Подключён',other_network:'Клиент подключён к другой сети',address_conflict:'Проверьте адресацию сервера'};
export function NetBirdConnection(){
const network=useNetBird();const {status,clients,error,busy,clientError}=network;
const [server,setServer]=useState(''),[edited,setEdited]=useState(false),[installer,setInstaller]=useState('macos');
useEffect(()=>{if(!edited&&status?.server_url)setServer(status.server_url);},[status?.server_url,edited]);
const selected=clients.find(item=>item.id===installer);
const state=status?.pending==='installing'?'Устанавливаем клиент':status?.pending==='cancelling'?'Отменяем подключение':status?.pending==='authentication'?'Требуется вход':status?.pending==='verifying'?'Проверяем соединение':status?.pending?'Подключаемся':status?labels[status.state]:'Получаем состояние';
return <>
<InstallerCard kind="vps-netbird"/>
<NetBirdBackups/>
<SettingsCard title="Этот компьютер" description="NetBird соединяет компьютеры через ваш сервер. Вход выполняется в браузере; подключение поддерживает системный клиент." actions={<StatusBadge tone={busy?'warning':status?.state==='connected'?'success':'neutral'}>{state}</StatusBadge>}>
<TextField label="Адрес сервера NetBird" placeholder="https://netbird.example.com" value={server} maxLength={300} disabled={busy} onChange={event=>{setEdited(true);setServer(event.target.value);}} hint="Адрес выдаёт установщик VPS или администратор вашей сети."/>
{status?.state==='connected'&&<Description>Адрес этого компьютера: {status.address}</Description>}
{status?.can_install&&['missing_client','unsupported_client'].includes(status.state)&&<Button disabled={busy||!clients.find(item=>item.id==='macos')?.available} onClick={()=>void network.action('install')}>Установить клиент на этот Mac</Button>}
<Button variant="primary" disabled={busy||!server.trim()||!status||['missing_client','unsupported_client','unavailable','other_network'].includes(status.state)} onClick={()=>void network.action('connect',server)}>{status?.state==='connected'?'Проверить подключение':'Подключить этот компьютер'}</Button>
{status?.pending&&status.pending!=='installing'&&<Button disabled={network.requestBusy||status.pending==='cancelling'} onClick={()=>void network.action('cancel')}>Прекратить ожидание</Button>}
{status?.auth_url&&<Button onClick={()=>window.open(status.auth_url,'_blank','noopener,noreferrer')}>Войти на сервере</Button>}
{status?.pending==='installing'&&<Description>Подтвердите системный запрос macOS. Пароль администратора вводится только в системном окне.</Description>}
{(error||status?.error)&&<StatusBadge tone="danger">{error||status?.error}</StatusBadge>}
</SettingsCard>
<SettingsCard title="Клиенты для других компьютеров" description={`Официальные установщики NetBird${status?.client_version?' '+status.client_version:''}. Файлы хранятся в этом Mission Core и проверяются перед скачиванием.`}>
{clientError&&<StatusBadge tone="danger">{clientError}</StatusBadge>}
<Select label="Операционная система" value={installer} options={clients.map(item=>({value:item.id,label:item.label}))} onChange={setInstaller}/>
<Button icon={<Icon name="download"/>} disabled={!selected?.available} onClick={()=>{if(selected){const link=document.createElement('a');link.href=selected.download_url;link.download=selected.filename;link.click();}}}>Скачать клиент</Button>
<Description>Установите клиент, укажите этот же адрес сервера в его настройках и выполните вход. Mission Core на другом компьютере для подключения к сети не требуется.</Description>
{installer.startsWith('linux')&&<Description>Пакет «интерфейс» устанавливается вместе с основным клиентом той же версии. Для устройства без экрана используйте ключ подключения из панели NetBird.</Description>}
{selected&&!selected.available&&<Description>Этот установщик пока отсутствует в локальном каталоге.</Description>}
</SettingsCard>
</>;
}
@@ -0,0 +1,9 @@
import {Button,Window,WindowFooterActions} from '@nodedc/ui-react';
import {NetBirdConnection} from './NetBirdConnection';
export function OperatorNetworkWindow({onClose}:{onClose:()=>void}){
return <Window open title="Сеть операторского компьютера" subtitle="NetBird · WireGuard" size="lg" onClose={onClose}
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button></WindowFooterActions>}>
<NetBirdConnection/>
</Window>;
}
@@ -0,0 +1,17 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
import {DockLayout,type DockTree} from '@nodedc/ui-react';
import {observationTree,type ObservationLayout} from '../../core/fleet/observationLayout';
export function ObservationMount({element,className='observation-mount'}:{element:HTMLElement;className?:string}){
const ref=useRef<HTMLDivElement>(null);
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
return <div ref={ref} className={className}/>;
}
export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,minimumSizes,children}:{
ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void;
minimumSizes?:Record<string,{width:number;height:number}>; labels:Record<string,string>;focusedId?:string|null;children:ReactNode;
}){
return <DockLayout tree={observationTree(layout,ids)} onTreeChange={onTreeChange}
focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id,minimumSize:minimumSizes?.[id],preferredSize:!layout.tree&&!Object.keys(layout.splits).length?minimumSizes?.[id]:undefined}))}
renderPanel={id=><ObservationMount element={mounts.get(id)!}/>}>{children}</DockLayout>;
}
@@ -0,0 +1,16 @@
import {useState} from 'react';
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function ObservationLayoutSaveWindow({onClose,onSave,initialName='',onRemove}:{onClose:()=>void;onSave:(name:string)=>boolean;initialName?:string;onRemove?:()=>boolean}) {
const [name,setName]=useState(initialName);
const save=()=>{if(name.trim()&&onSave(name))onClose();};
return <Window open title={onRemove?'Редактировать раскладку':'Сохранить расположение'} size="sm" onClose={onClose}
footer={<WindowFooterActions>
{onRemove&&<Button icon={<Icon name="trash"/>} onClick={()=>{if(onRemove())onClose();}}>Удалить раскладку</Button>}
<Button variant="primary" disabled={!name.trim()} onClick={save}>{onRemove?'Сохранить имя':'Сохранить'}</Button>
</WindowFooterActions>}>
<TextField label="Название раскладки" value={name} maxLength={120} onChange={event=>setName(event.target.value)}
onKeyDown={event=>{if(event.key==='Enter'&&!event.nativeEvent.isComposing){event.preventDefault();save();}}}
description={onRemove?undefined:'Сохраняются выбранные камеры, слои и расположение окон. Недоступные устройства появятся при подключении.'}/>
</Window>;
}
@@ -0,0 +1,13 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
export function ObservationPanelHeader({children}:{children:ReactNode}) {
const ref=useRef<HTMLElement>(null);
useLayoutEffect(()=>{
const header=ref.current!;
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
measure();const observer=new ResizeObserver(measure);observer.observe(header);
return()=>observer.disconnect();
},[]);
return <header ref={ref} className="observation-panel__header nodedc-viewport-controls">{children}</header>;
}
@@ -1,3 +1,4 @@
import { heightSlice } from "../../core/heightSlice";
import { type ReactNode, useEffect, useRef, useState } from "react"; import { type ReactNode, useEffect, useRef, useState } from "react";
import { Button, LoadingRegion, RangeControl, SegmentedControl } from "@nodedc/ui-react"; import { Button, LoadingRegion, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost"; import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost";
@@ -11,6 +12,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const [retry, setRetry] = useState(0); const [retry, setRetry] = useState(0);
const [metadata, setMetadata] = useState<OverviewSpatialMetadata | null>(null); const [metadata, setMetadata] = useState<OverviewSpatialMetadata | null>(null);
const [ceiling, setCeiling] = useState<number | null>(null); const [ceiling, setCeiling] = useState<number | null>(null);
const [floor, setFloor] = useState<number | null>(null);
const [mode, setMode] = useState<OverviewViewMode>("3d"); const [mode, setMode] = useState<OverviewViewMode>("3d");
const [viewError, setViewError] = useState<string | null>(null); const [viewError, setViewError] = useState<string | null>(null);
const [visiblePoints, setVisiblePoints] = useState<number | null>(null); const [visiblePoints, setVisiblePoints] = useState<number | null>(null);
@@ -26,7 +28,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const abort = new AbortController(); const abort = new AbortController();
appliedMode.current = null; appliedMode.current = null;
setState("loading"); setState("loading");
setMetadata(null); setCeiling(null); setMode("3d"); setVisiblePoints(null); setViewError(null); setMetadata(null); setCeiling(null); setFloor(null); setMode("3d"); setVisiblePoints(null); setViewError(null);
setRepresentation("original"); setAppliedRepresentation("original"); setUpdating(false); setRepresentation("original"); setAppliedRepresentation("original"); setUpdating(false);
void fetchOverviewSpatial(sourceUrl, abort.signal).then(data => { void fetchOverviewSpatial(sourceUrl, abort.signal).then(data => {
if (disposed) return; if (disposed) return;
@@ -56,7 +58,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const timer = setTimeout(() => { const timer = setTimeout(() => {
const aspect = Math.max(.1, Math.min(20, (host.current?.clientWidth ?? 1) / Math.max(1, (host.current?.clientHeight ?? 1) - 28))); const aspect = Math.max(.1, Math.min(20, (host.current?.clientWidth ?? 1) / Math.max(1, (host.current?.clientHeight ?? 1) - 28)));
void updateOverviewSpatial(sourceUrl, ceiling, appliedMode.current === mode ? null : mode, aspect, abort.signal, void updateOverviewSpatial(sourceUrl, ceiling, appliedMode.current === mode ? null : mode, aspect, abort.signal,
comparison?.generation ?? null, comparison ? representation : "original").then(result => { comparison?.generation ?? null, comparison ? representation : "original", floor).then(result => {
if (abort.signal.aborted || !controller.current) return; if (abort.signal.aborted || !controller.current) return;
controller.current.channel.send_rrd(result.bytes); controller.current.channel.send_rrd(result.bytes);
appliedMode.current = mode; appliedMode.current = mode;
@@ -65,12 +67,12 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
}).catch(() => { if (!abort.signal.aborted) { setUpdating(false); setViewError("Не удалось обновить вид облака. Показан предыдущий вид."); } }); }).catch(() => { if (!abort.signal.aborted) { setUpdating(false); setViewError("Не удалось обновить вид облака. Показан предыдущий вид."); } });
}, 180); }, 180);
return () => { abort.abort(); clearTimeout(timer); }; return () => { abort.abort(); clearTimeout(timer); };
}, [state, metadata, sourceUrl, ceiling, mode, retry, comparison, representation]); }, [state, metadata, sourceUrl, ceiling, floor, mode, retry, comparison, representation]);
const low = comparison?.height_min_m ?? metadata?.height_min_m; const low = comparison?.height_min_m ?? metadata?.height_min_m;
const high = comparison?.height_max_m ?? metadata?.height_max_m; const high = comparison?.height_max_m ?? metadata?.height_max_m;
return <> return <>
<div className={`session-overview__scene-head ${hideTitle?"session-overview__scene-head--end":""}`}>{!hideTitle&&<h2>Облако и траектория</h2>} <div className={`session-overview__scene-head nodedc-viewport-controls ${hideTitle?"session-overview__scene-head--end":""}`}>{!hideTitle&&<h2>Облако и траектория</h2>}
{compareVersions && comparison && <SegmentedControl label="Версия облака" value={representation} onChange={setRepresentation} {compareVersions && comparison && <SegmentedControl label="Версия облака" value={representation} onChange={setRepresentation}
items={[{ value: "original", label: "Исходное", disabled: state !== "ready" }, { value: "corrected", label: "Исправленное", disabled: state !== "ready" }]} />} items={[{ value: "original", label: "Исходное", disabled: state !== "ready" }, { value: "corrected", label: "Исправленное", disabled: state !== "ready" }]} />}
<SegmentedControl label="Вид облака" value={mode} onChange={setMode} <SegmentedControl label="Вид облака" value={mode} onChange={setMode}
@@ -80,15 +82,15 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
<LoadingRegion loading={state === "loading" || (state === "ready" && !!metadata && visiblePoints === null && !viewError)} label="Загрузка облака" className="session-overview__scene"> <LoadingRegion loading={state === "loading" || (state === "ready" && !!metadata && visiblePoints === null && !viewError)} label="Загрузка облака" className="session-overview__scene">
<div ref={host} className={`session-overview__runtime ${hideTitle?"rerun-single-view-content":""}`} style={{ visibility: state === "ready" && metadata && visiblePoints !== null ? "visible" : "hidden" }} /> <div ref={host} className={`session-overview__runtime ${hideTitle?"rerun-single-view-content":""}`} style={{ visibility: state === "ready" && metadata && visiblePoints !== null ? "visible" : "hidden" }} />
{low != null && high != null && high > low && state === "ready" && <div className="session-overview__height"> {low != null && high != null && high > low && state === "ready" && <div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={ceiling ?? high} min={low} max={high} step="any" <RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor ?? low, ceiling ?? high]} min={low} max={high} step="any"
formatValue={value => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={value => value.toFixed(1).replace('.', ',')} formatValue={value => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={value => value.toFixed(1).replace('.', ',')}
onChange={value => setCeiling(value >= high - Math.max(1, high - low) * 1e-9 ? null : value)} /> onChange={value => { const next = heightSlice(value, [low, high]); setFloor(next.floor); setCeiling(next.ceiling); }} />
</div>} </div>}
{state === "error" && <div className="session-overview__empty"><span>Не удалось открыть облако.</span><Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>} {state === "error" && <div className="session-overview__empty"><span>Не удалось открыть облако.</span><Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
</LoadingRegion> </LoadingRegion>
<span className="session-overview__note" role="status" aria-busy={updating}> <span className="session-overview__note" role="status" aria-busy={updating}>
{updating ? "Обновление · " : comparison ? `${appliedRepresentation === "corrected" ? "Исправленное" : "Исходное"} · ` : ""} {updating ? "Обновление · " : comparison ? `${appliedRepresentation === "corrected" ? "Исправленное" : "Исходное"} · ` : ""}
{ceiling == null ? "Без среза" : `Высота ≤ ${ceiling.toFixed(1)} м`} · {visiblePoints?.toLocaleString("ru-RU") ?? "—"} точек {floor == null && ceiling == null ? "Без среза" : `${floor == null ? "" : `${floor.toFixed(1)} м ≤ `}Высота${ceiling == null ? "" : ` ≤ ${ceiling.toFixed(1)} м`}`} · {visiblePoints?.toLocaleString("ru-RU") ?? "—"} точек
{comparison && <><br />Выборка для просмотра. Исходная запись сохранена отдельно.</>} {comparison && <><br />Выборка для просмотра. Исходная запись сохранена отдельно.</>}
</span> </span>
{viewError && <div className="session-overview__note" role="alert">{viewError}<Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>} {viewError && <div className="session-overview__note" role="alert">{viewError}<Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
@@ -0,0 +1,62 @@
.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: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; }
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
.observation-actions { flex-shrink:0; }
.observation-deck { flex:1; min-height:0; min-width:0; }
.observation-layout { position:relative; height:100%; min-height:0; min-width:0; }
.observation-layout__slot { height:100%; min-height:0; }
.observation-layout__panel { position:absolute; min-height:0; min-width:0; }
.observation-layout__panel:has(.is-dragging) { z-index:var(--nodedc-layer-panel); }
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
.observation-panel__surface > .observation-mount { flex:1; }
.observation-panel__surface--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; }
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
.observation-header-slot:has(> div:empty) { display:none; }
.observation-panel__title .observation-header-slot, .observation-panel__title .observation-header-slot > div { min-width:0; max-width:100%; flex-shrink:1; }
.observation-layer-select { min-width:0; max-width:120px; }
.observation-layer-select button { max-width:100%; }
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
/* 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); }
.observation-layer > * { min-width:0; width:100%; }
.observation-layer > .nodedc-switch { text-align:left; }
.observation-empty { display:grid; place-content:center; height:100%; text-align:center; }
.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; }
@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } }
.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; }
/* Transform the live panel as one item; reveal it across nested split boundaries. */
.observation-panel-drag { position:relative; height:100%; min-height:0; }
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
.observation-split:has(.observation-panel-drag.is-dragging),
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
@container (max-width:420px) {
.observation-panel__header { flex-wrap:wrap; }
.observation-panel__title { min-width:80px; }
.observation-panel__title:has(.rover-view__title) { min-width:min(160px, 100%); }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; gap:var(--nodedc-space-1); }
}
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
@@ -7,18 +7,58 @@ export function createIsolatedRerunHost(host: HTMLElement) {
let frame: HTMLIFrameElement | null = host.ownerDocument.createElement("iframe"); let frame: HTMLIFrameElement | null = host.ownerDocument.createElement("iframe");
frame.title = "Синхронизированная запись"; frame.title = "Синхронизированная запись";
frame.className = "rerun-viewport__runtime"; frame.className = "rerun-viewport__runtime";
frame.src = "/rerun-runtime.html"; frame.loading = "eager";
let navigation: number | undefined;
let disposed = false; let disposed = false;
let releaseFacade: (() => void) | null = null; let releaseFacade: (() => void) | null = null;
let releaseInput: (() => void) | null = null; let releaseInput: (() => void) | null = null;
let frameWindow: RerunFrameWindow | null = null; let frameWindow: RerunFrameWindow | null = null;
let rejectReady: ((reason: Error) => void) | null = null; let rejectReady: ((reason: Error) => void) | null = null;
let timer: ReturnType<typeof setTimeout> | undefined; 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 = () => { const dispose = () => {
if (disposed) return; if (disposed) return;
disposed = true; disposed = true;
if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation);
clearTimeout(timer); clearTimeout(timer);
bootstrapAbort.abort();
delete host.dataset.rerunCamera;
frame!.onload = null; frame!.onload = null;
frame!.onerror = null; frame!.onerror = null;
releaseInput?.(); releaseInput?.();
@@ -32,6 +72,7 @@ export function createIsolatedRerunHost(host: HTMLElement) {
frameWindow = null; frameWindow = null;
frame!.remove(); frame!.remove();
frame = null; frame = null;
markup = null;
rejectReady?.(new Error("Recorded viewer was disposed")); rejectReady?.(new Error("Recorded viewer was disposed"));
rejectReady = null; rejectReady = null;
} }
@@ -39,21 +80,38 @@ export function createIsolatedRerunHost(host: HTMLElement) {
const ready = new Promise<{ viewer: RecordedRerunViewer; mount: HTMLElement }>((resolve, reject) => { const ready = new Promise<{ viewer: RecordedRerunViewer; mount: HTMLElement }>((resolve, reject) => {
rejectReady = reject; rejectReady = reject;
frame!.onload = () => { const handleLoad = () => {
if (disposed) return; if (disposed) return;
try { try {
frameWindow = frame!.contentWindow as RerunFrameWindow | null; frameWindow = frame!.contentWindow as RerunFrameWindow | null;
const api = frameWindow?.missionCoreRerun; 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"); if (!api || api.version !== 2) throw new Error("Recorded viewer host is unavailable");
const owner = createRecordedRerunFacade((request, bytes) => { const owner = createRecordedRerunFacade((request, bytes) => {
const current = frameWindow?.missionCoreRerun; const current = frameWindow?.missionCoreRerun;
if (!current) throw new Error("Recorded viewer was disposed"); 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; releaseFacade = owner.dispose;
api.connect(owner.notify); api.connect(owner.notify);
releaseInput = relayIsolatedRerunInput(host, frameWindow, frame); releaseInput = relayIsolatedRerunInput(host, frameWindow, frame);
clearTimeout(timer); clearTimeout(timer);
bootstrapAbort.abort();
if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation);
navigation = undefined;
rejectReady = null; rejectReady = null;
frame!.onload = null; frame!.onload = null;
frame!.onerror = null; frame!.onerror = null;
@@ -63,15 +121,21 @@ export function createIsolatedRerunHost(host: HTMLElement) {
dispose(); dispose();
} }
}; };
frame!.onerror = () => { const handleError = () => {
reject(new Error("Recorded viewer host failed to load")); reject(new Error("Recorded viewer host failed to load"));
dispose(); dispose();
}; };
const bind = (element: HTMLIFrameElement) => {
element.onload = () => { if (frame === element) handleLoad(); };
element.onerror = () => { if (frame === element) handleError(); };
};
bind(frame!);
timer = setTimeout(() => { timer = setTimeout(() => {
reject(new Error("Recorded viewer host timed out")); reject(new Error("Recorded viewer host timed out"));
dispose(); dispose();
}, 30_000); }, 30_000);
}); });
host.append(frame); scheduleNavigation();
return { ready, dispose }; return { ready, dispose };
} }
@@ -26,3 +26,14 @@ export function readNativeRerunCameraEye(value: unknown): RecordedRerunCameraEye
}; };
return { position: vector("position"), lookTarget: vector("lookTarget"), eyeUp: vector("eyeUp") }; 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; open_channel: (name?: string) => Channel;
get_camera_eye: () => RecordedRerunCameraEye | null; 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. */ /** 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_current_time: (...args) => command("set_current_time", args),
set_playing: (...args) => command("set_playing", args), set_playing: (...args) => command("set_playing", args),
get_camera_eye: () => command("get-camera-eye"), 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 }; return { facade, dispose, notify };
} }
@@ -80,6 +80,13 @@ export function createRecordedRerunOwner(create: () => WebViewer, mount: HTMLEle
case "get-camera-eye": result = readNativeRerunCameraEye( case "get-camera-eye": result = readNativeRerunCameraEye(
(required() as WebViewer & { get_camera_eye?(): unknown }).get_camera_eye?.(), (required() as WebViewer & { get_camera_eye?(): unknown }).get_camera_eye?.(),
); break; ); 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 "open": required().open(args[0]); break;
case "close": required().close(args[0]); break; case "close": required().close(args[0]); break;
case "override_panel_state": required().override_panel_state(args[0], args[1]); break; case "override_panel_state": required().override_panel_state(args[0], args[1]); break;
@@ -0,0 +1,32 @@
import {useState} from 'react';
import {Button,Description,Select,SettingsCard,Switch,Window,WindowFooterActions} from '@nodedc/ui-react';
import {localDevOptions,type DevOptions,type RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
import './roverLogs.css';
export function RoverDevWindow({capture,close,started}:{capture:RoverDiagnostics;close:()=>void;started:()=>void}){
const [options,setOptions]=useState<DevOptions>({...localDevOptions});
const [local,setLocal]=useState({enabled:true,preview:true});
const set=(key:keyof DevOptions,value:boolean|number)=>setOptions(current=>({...current,[key]:value}));
const rates=[8,16,32,64].map(value=>({value:String(value),label:`${value} кбит/с`}));
const begin=async()=>{if(await capture.toggle(options,local)){started();close();}};
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
<div className="rover-dev-options">
<Description>Запись сохраняется на борту. После завершения её можно скачать в окне логов. Закрытие окна не останавливает запись.</Description>
<SettingsCard title="Что записывать" description="Переходы управления, остановки и ошибки записываются всегда.">
<Switch label="Подробные замеры моторов" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
<Switch label="Сетевые события и распределение полосы" checked={options.network} onChange={value=>set('network',value)}/>
</SettingsCard>
<SettingsCard title="Замеры на компьютере" description="Задержки команд и события браузера сохраняются отдельно от записи борта. Эти замеры не передаются на борт.">
<Switch label="Записать замеры Core и браузера" checked={local.enabled} onChange={enabled=>setLocal(current=>({...current,enabled}))}/>
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер хранится в памяти до перезапуска Core: не более 15 минут и последних 6000 событий. После остановки сохраните его отдельной кнопкой в окне логов.</Description></>}
</SettingsCard>
<SettingsCard title="Передача во время записи" description={!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
<Switch label="Показывать события онлайн" checked={options.live} onChange={value=>set('live',value)}/>
{options.live&&<Select label="Лимит live-событий" value={String(options.live_kbps)} options={rates} onChange={value=>set('live_kbps',Number(value))}/>}
<Switch label="Добавлять события Core и браузера" checked={options.core_trace} onChange={value=>set('core_trace',value)}/>
{options.core_trace&&<><Description>Эти события передаются с компьютера оператора на борт. При нехватке полосы пропуски отмечаются в записи.</Description><Select label="Лимит событий на борт" value={String(options.core_kbps)} options={rates} onChange={value=>set('core_kbps',Number(value))}/></>}
</SettingsCard>
{!capture.state.options_supported&&<Description>Борт ещё не подтвердил доступность настроек записи. Запуск станет доступен после подключения совместимого борта.</Description>}
</div>
</Window>;
}
@@ -0,0 +1,24 @@
import {createPortal} from 'react-dom';
import {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';
export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:ObservationHeaderTargets}){
const storage=capture.state.node?.storage,failed=storage?.error||capture.state.node?.transport_error;
const status=failed?'Ошибка записи':capture.state.closing?'Завершение записи':storage?.closed?'Запись завершена':capture.state.node?.active?'Запись на борт':'Ожидание борта';
return <>
{createPortal(<StatusBadge variant="indicator" tone={failed?'danger':capture.state.node?.active?'success':'warning'} aria-label={status} title={status}/>,header.statusTarget)}
<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>}
<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>
</div>
</>;
}
@@ -1,7 +1,9 @@
import {ComparisonTable,Description,StatusBadge} from '@nodedc/ui-react';
import type {RoverState} from '../../core/fleet/useRoverControl'; import type {RoverState} from '../../core/fleet/useRoverControl';
import type {RoverObservationStatus} from '../../core/fleet/roverObservation';
import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model'; import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model';
const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—'; const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—';
export function RoverTelemetry({state}:{state:RoverState}){ export function roverTelemetryTable(state:RoverState){
const devices=state.snapshot.devices??[],profile=state.snapshot.profile; const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
const positions=drivePositions(profile?.layout??null); const positions=drivePositions(profile?.layout??null);
const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({ const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({
@@ -9,17 +11,19 @@ export function RoverTelemetry({state}:{state:RoverState}){
reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid), reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid),
})); }));
const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))]; const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))];
return <div className="rover-telemetry"> const fresh=(d:typeof readings[number])=>state.fresh&&!!d.reading&&Number.isFinite(d.reading.age_ms)&&d.reading.age_ms>=0&&d.reading.age_ms<1000;
{!state.fresh?<p>Нет свежих показаний VESC.</p>:!readings.length?<p>Получение показаний VESC…</p>:readings.map(d=>{ const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const;
const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined; return {
return <section key={d.uuid}><strong>{d.label}</strong><span>VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''}</span> columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
<dl><div><dt>Ток мотора</dt><dd>{number(v?.motor_current_a)} А</dd></div> rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')},
<div><dt>Ток батареи</dt><dd>{number(v?.input_current_a)} А</dd></div> {id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')},
<div><dt>Напряжение</dt><dd>{number(v?.input_voltage_v)} В</dd></div> ...metrics.map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
<div><dt>Обороты, ERPM</dt><dd>{number(v?.erpm,0)}</dd></div> {id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}],
<div><dt>Контроллер</dt><dd>{number(v?.mos_temperature_c)} °C</dd></div> };
<div><dt>Ошибка VESC</dt><dd>{v?v.fault_code===0?'Нет':String(v.fault_code):'—'}</dd></div></dl>
</section>;
})}
</div>;
} }
export function RoverTelemetry({state,observation}:{state:RoverState;observation?:RoverObservationStatus}){
const table=roverTelemetryTable(state);
return <div className="rover-telemetry">{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
}
export function roverTelemetryMinimum(state:RoverState){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:280};}
@@ -1,45 +1,66 @@
import {roverModelID} from '../../core/roverScene/model';
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react'; import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom'; import {createPortal} from 'react-dom';
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react'; import {Button,EditorWorkspace,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput'; import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {roverDevEvent} from '../../core/fleet/roverDevEvents';
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput'; import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
import type {RoverController} from '../../core/fleet/useRoverControl'; import type {RoverController} from '../../core/fleet/useRoverControl';
import {roverObservationStatus,type RoverObservationStatus} from '../../core/fleet/roverObservation';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation'; import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import './rover.css'; import './rover.css';
const Scene=lazy(()=>import('./editor/RoverScene')); const Scene=lazy(()=>import('./editor/RoverScene'));
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'}; const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление вкл',driving:'Управление вкл',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выкл',fault:'Управление остановлено'};
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){ export function RoverView({vehicleID,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 storage=`missioncore.rover-view.v1:${vehicleID}`;
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}}); const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set()); const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
const [editing,setEditing]=useState(false); const [editing,setEditing]=useState(false);
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading'); const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null); const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]); const focusAfterArm=useRef(false);
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]); useEffect(()=>{
useEffect(()=>{if(!active)stop();},[active,stop]); if(open||!focusAfterArm.current)return;
focusAfterArm.current=false;
// Window restores its opener on close. Transfer input after that cleanup,
// once only, without taking focus back from another window or dialog.
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!document.querySelector('[role=dialog],[role=listbox]'))stage.current?.focus({preventScroll:true});});
return()=>cancelAnimationFrame(frame);
},[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();setEditing(false);}},[active,stop]);
useEffect(()=>{ useEffect(()=>{
if(!c.ready||!active||open||editing||!stage.current)return; if(!c.ready||!active||open||editing||!stage.current)return;
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop}); const scope=stage.current.closest<HTMLElement>('.observation-center')??stage.current;
const binding=bindRoverHoldInput(scope,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop,trace:(event,data)=>roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,event,data)});
input.current=binding;c.setInputGuard(binding.valid); input.current=binding;c.setInputGuard(binding.valid);
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;}; return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
},[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]); },[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
const showSettings=()=>{setEditing(false);stop();setOpen(true);}; const showSettings=()=>{setEditing(false);stop();setOpen(true);};
const preparing=c.pending||(c.armed&&!c.ready); const preparing=c.recovering||c.pending||(c.armed&&!c.ready);
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null; const duty=c.controlMode!=='rpm';
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral'; const limits=(c.state.snapshot.devices??[]).filter(d=>d.slot&&d.current_limits);
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение'); const currentDescription=limits.length?limits.map(d=>`${d.label}: до ${d.current_limits!.motor_a.toLocaleString('ru-RU',{maximumFractionDigits:2})} А`).join('; ')+'. Выбранный предел ограничивает тягу; настройки VESC сохраняются.':'Предел тяги. Каждый мотор также ограничен своей конфигурацией VESC.';
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 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 <> return <>
{createPortal(<><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)} {createPortal(<><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)}
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)} {createPortal(<><StatusBadge variant="indicator" tone={editing?'neutral':tone} pulse={!editing&&(preparing||observing.pulse)} aria-label={editing?'Редактирование сцены':status}/><h3 className="rover-view__title" title={status}>{editing?'Редактирование сцены':status}</h3></>,header.statusTarget)}
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером" <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();}}> onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера"> <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> <Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>} {modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>} </LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
<div className="rover-view__status"><StatusBadge tone={editing?'neutral':tone}>{editing?'Редактирование сцены':status}</StatusBadge></div>
{c.ready&&!editing&&<div className="rover-view__controls"> {c.ready&&!editing&&<div className="rover-view__controls">
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}> <div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)} {keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
@@ -51,20 +72,18 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
</div> </div>
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span> <span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
</div>} </div>}
{!editing&&<div className="rover-view__authority"> </EditorWorkspace>
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
</div>}
</div> </div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings"> <Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/> <Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
<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}))}/>
<TextField label="Предел тока каждого мотора, А" type="number" min={.5} max={30} step={.5} value={settings.currentA} onChange={e=>setSettings(v=>({...v,currentA:Number(e.target.value)}))}/> {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={settings.maxErpm} onChange={e=>setSettings(v=>({...v,maxErpm:Number(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)}))}/>}
<Switch label="Моторы остановлены, движение можно начинать" checked={confirmed} onChange={setConfirmed}/> <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&&<StatusBadge tone="warning">{availability}</StatusBadge>} {(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
<p>Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. Команда с пульта прекращает удалённое управление.</p> <p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
<Button variant="primary" tone="neutral" disabled={!confirmed||!c.canArm||!(settings.currentA>=.5&&settings.currentA<=30&&settings.maxErpm>=300&&settings.maxErpm<=3000)} loading={c.pending} <Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
onClick={async()=>{const acquired=await c.arm(settings.currentA,settings.maxErpm);if(acquired){setOpen(false);if(document.hasFocus())stage.current?.focus();}}}>Включить управление</Button> 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> </div></Window>
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/> <ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
</>; </>;
@@ -0,0 +1,17 @@
import {ColorField,ControlRow,Description,RangeControl,Switch} from '@nodedc/ui-react';
import type {ChargeGradient} from '../../../core/roverScene/chargeGradient';
export function ChargeGradientInspector({value,onChange}:{value:ChargeGradient;onChange:(value:ChargeGradient)=>void}){
const patch=(change:Partial<ChargeGradient>)=>onChange({...value,...change});
return <div className="rover-scene-fields">
<Switch label="Градиент по заряду" checked={value.enabled} onChange={enabled=>patch({enabled})}/>
<Description>Две пары цветов: при 0% и при 100%. Между ними — плавный переход по общему заряду батареи.</Description>
{(['lowA','lowB','highA','highB'] as const).map((key,i)=><ControlRow key={key} label={['0% · цвет A','0% · цвет B','100% · цвет A','100% · цвет B'][i]}><ColorField label={['0% · цвет A','0% · цвет B','100% · цвет A','100% · цвет B'][i]} value={value[key]} onChange={color=>patch({[key]:color})}/></ControlRow>)}
<RangeControl label="Сила свечения градиента" value={value.intensity} min={0} max={10} step={.05} exactValueBounds={{min:0,max:10}} onChange={intensity=>patch({intensity})}/>
<RangeControl label="Скорость переливания" value={value.speed} min={0} max={3} step={.01} exactValueBounds={{min:0,max:3}} onChange={speed=>patch({speed})}/>
<RangeControl label="Масштаб рисунка" value={value.scale} min={1} max={50} step={.1} exactValueBounds={{min:1,max:50}} onChange={scale=>patch({scale})}/>
<Description>Материал без данных · используется, когда сохранённого заряда нет. Без свечения.</Description>
<ControlRow label="Цвет без данных"><ColorField label="Цвет без данных" value={value.fallbackColor} onChange={fallbackColor=>patch({fallbackColor})}/></ControlRow>
{([['fallbackMetalness','Металличность без данных'],['fallbackRoughness','Шероховатость без данных'],['fallbackReflectivity','Отражение без данных'],['fallbackOpacity','Непрозрачность без данных']] as const).map(([key,label])=><RangeControl key={key} label={label} value={value[key]} min={0} max={1} step={.01} exactValueBounds={{min:0,max:1}} onChange={v=>patch({[key]:v})}/>)}
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
</div>;
}
@@ -1,3 +1,4 @@
import {ChargeGradientInspector} from './ChargeGradientInspector';
import {useRef,useState} from 'react'; import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-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 {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
@@ -5,8 +6,9 @@ import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'}; 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}){ 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})}/>; 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={[ return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={material.chargeGradient?['charge']:['surface']} sections={[
{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>}, ...(material.chargeGradient?[{id:'charge',label:'Градиент заряда',content:<ChargeGradientInspector value={material.chargeGradient} onChange={chargeGradient=>onChange({chargeGradient})}/>}]:[]),
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields">{!material.chargeGradient?.enabled&&<ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>}{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>}, {id:'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>}, {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></>; ]}/><Button onClick={onReset}>Исходный материал</Button></>;
@@ -0,0 +1,23 @@
import {useLayoutEffect,useRef,type CSSProperties} from 'react';
import {Button,DraggableItem,Icon,IconButton} from '@nodedc/ui-react';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {materialTileSizes,type EditorWindowRect} from '../../../core/roverScene/editorLayout';
export function MaterialTile({material}:{material:MaterialSpec}){return <span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':material.color,'--material-gloss':1-material.roughness,...(material.chargeGradient?.enabled?{background:`linear-gradient(135deg,${material.chargeGradient.highA},${material.chargeGradient.highB})`}:{})} as CSSProperties}/><span>{material.name}</span></span>;}
type Props={materials:Record<string,MaterialSpec>;selected:string|null;revealVersion:number;pick:(id:string)=>void;add:()=>void;rect?:EditorWindowRect;tileSize:number};
export function MaterialPalette({materials,selected,pick,add,revealVersion,rect,tileSize}:Props){
const grid=useRef<HTMLDivElement>(null);
useLayoutEffect(()=>{
const content=grid.current,parent=content?.closest('.nodedc-window__body'),target=content?.querySelector<HTMLElement>('[aria-pressed="true"]');
if(!parent||!target)return;
const p=parent.getBoundingClientRect(),t=target.getBoundingClientRect();
if(t.top<p.top)parent.scrollTop+=t.top-p.top;else if(t.bottom>p.bottom)parent.scrollTop+=t.bottom-p.bottom;
},[selected,revealVersion,tileSize,rect?.width,rect?.height]);
return <div ref={grid} className="rover-material-palette__items" style={{'--material-tile-width':`${tileSize}px`,'--material-swatch-size':`${38*tileSize/materialTileSizes.default}px`,'--material-tile-font':`${Math.max(10,12*tileSize/materialTileSizes.default)}px`} as CSSProperties}>
{Object.entries(materials).map(([id,m])=><DraggableItem id={id} data={{materialId:id}} key={id} className="scene-material-drag">{({activator})=><Button {...activator.attributes} {...activator.listeners} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><MaterialTile material={m}/></Button>}</DraggableItem>)}
<Button aria-label="Добавить материал" title="Добавить материал" onClick={add}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button>
</div>;
}
export function MaterialPaletteActions({tileSize,onTileSize}:{tileSize:number;onTileSize:(size:number)=>void}){return <>
<IconButton label="Уменьшить плитки материалов" disabled={tileSize<=materialTileSizes.min} onClick={()=>onTileSize(Math.max(materialTileSizes.min,tileSize-materialTileSizes.step))}><Icon name="minus"/></IconButton>
<IconButton label="Увеличить плитки материалов" disabled={tileSize>=materialTileSizes.max} onClick={()=>onTileSize(Math.min(materialTileSizes.max,tileSize+materialTileSizes.step))}><Icon name="plus"/></IconButton>
</>;}
@@ -1,38 +1,73 @@
import {useCallback,useEffect,useState,type CSSProperties} from 'react'; import {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout';
import {Button,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,Window} from '@nodedc/ui-react'; import {roverModelURL} from '../../../core/roverScene/model';
import {assignMaterial,createMaterial,changeField,defaultScene,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument'; import {useCallback,useEffect,useRef,useState} from 'react';
import {Description,DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
import {createMaterial,changeField,defaultScene,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {assignObjectMaterial,findSceneObject,objectTargets,type SceneObject} from '../../../core/roverScene/sceneObjects';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument'; import {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 {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
import {MaterialInspector} from './MaterialInspector'; import {MaterialInspector} from './MaterialInspector';
import {MaterialPalette,MaterialPaletteActions,MaterialTile} from './MaterialPalette';
import {SceneObjectTree} from './SceneObjectTree';
import {useSceneUndo} from './useSceneUndo';
import type {ChargeState} from '../playcanvas/chargeMaterial';
import {useObjectSelection} from './useObjectSelection';
import './sceneEditor.css'; import './sceneEditor.css';
export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){ export default function RoverScene({vehicleID,...props}:{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 scene=useSceneDocument(vehicleID);return <SceneEditor {...props} scene={scene}/>;
const [selectedGroup,setSelectedGroup]=useState<string|null>(null); }
const pick=useCallback((id:string,group?:string)=>{setSelected(id);if(group)setSelectedGroup(group);setMaterialOpen(true);},[]); export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,defaults=defaultScene,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;defaults?:typeof defaultScene;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
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);}; useSceneUndo(scene,editing);
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}}}));}; const layout=scene.document.editorLayout;
const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default;
const [palette,setPalette]=useState(true),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
const [objectsOpen,setObjectsOpen]=useState(true),[root,setRoot]=useState<SceneObject|null>(null),[selectedObject,setSelectedObject]=useState<string|null>(null);
const [selectionVersion,setSelectionVersion]=useState(0);
const [modelPhase,setModelPhase]=useState<'loading'|'ready'|'error'>('loading');
const [sceneApi,setSceneApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const picker=useRef<ScenePicker|null>(null);
const pickerReady=useCallback((value:ScenePicker|null)=>{picker.current=value;},[]);
const sceneGraph=useCallback((value:SceneObject|null)=>{setRoot(value);},[]);
const sceneReady=useCallback((api:Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0])=>{setSceneApi(api);onSceneReady?.(api);},[onSceneReady]);
const modelState=useCallback((value:'loading'|'ready'|'error')=>{setModelPhase(value);onModelState(value);},[onModelState]);
const pick=useCallback((id:string)=>{setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
const objectPick=useCallback((hit:ScenePick|null)=>{setSelectionVersion(v=>v+1);if(!hit){setSelectedObject(null);setSelected(null);setMaterialOpen(false);return;}setSelectedObject(hit.objectId);setPalette(true);pick(hit.materialId);},[pick]);
const selectObject=(id:string)=>{setSelectionVersion(v=>v+1);setSelectedObject(id);const item=findSceneObject(root,id),source=item?.materialIds?.[0];const material=scene.document.objectAssignments?.[id]??(source?(scene.document.assignments[source]??source):null);if(material){setPalette(true);pick(material);}};
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=maxSceneMaterials){scene.setError(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{if(Object.entries(patch).every(([key,value])=>scene.document.materials[id]?.[key as keyof MaterialSpec]===value))return;const next={...scene.document,materials:{...scene.document.materials,[id]:{...scene.document.materials[id],...patch}}};if(textureBytes(next)>28_000_000){scene.setError('Суммарный объём текстур превышает 20 МБ. Удалите ненужную текстуру.');return;}scene.update(doc=>({...doc,materials:{...doc.materials,[id]:{...doc.materials[id],...patch}}}));};
useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]); useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]);
const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
const material=selected?scene.document.materials[selected]:null;
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере'; const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
const material=selected?scene.document.materials[selected]:null; const tools:EditorDockTool[]=[
return <> {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}}))}/>},
<LoadingRegion className="rover-view__scene" style={{bottom:editing&&palette?150:0}} loading={!scene.ready} label="Загрузка настроек сцены"> {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},
{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}/>} 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}/>},
</LoadingRegion> {id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),footer:<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaults().postFx}))}/>,content:<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
{id:'material',title:material?.name||'Материал',label:'Материал',activationKey:`${selectionVersion}:${selected}`,subtitle:node?`Назначить: ${node.name}`:'Выберите объект в дереве',open:materialOpen&&!!material,onClose:()=>setMaterialOpen(false),
actions:<IconButton label="Назначить материал выбранному объекту" disabled={!selected||!targets.length} onClick={()=>selected&&scene.update(doc=>assignObjectMaterial(doc,targets,selected))}><Icon name="chevron-right"/></IconButton>,
content:material&&selected?<><Description>{node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'}</Description><MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaults().materials[selected]??createMaterial(defaults(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/></>:null}
];
return <DragDropRoot renderOverlay={({data})=>{const m=scene.document.materials[String(data?.materialId)];return m?<GlassSurface padding="sm"><MaterialTile material={m}/></GlassSurface>:null;}} onDragEnd={({activeData,pointer})=>{
const id=String(activeData?.materialId??'');if(!editing||!pointer||!Object.hasOwn(scene.document.materials,id))return;
// Reject palettes/inspectors and empty sky. Only an actual visible model hit assigns.
if(!(document.elementFromPoint(pointer.x,pointer.y) instanceof HTMLCanvasElement))return;
const hit=picker.current?.pick(pointer.x,pointer.y);if(!hit)return;
setSelectedObject(hit.objectId);setSelected(id);scene.update(doc=>assignObjectMaterial(doc,[hit.objectId],id));
}}>
<EditorDockLayout value={docking} enabled={editing} tools={tools} onChange={next=>scene.update(doc=>({...doc,editorLayout:{windows:{},materialTileSize:materialTileSizes.default,...doc.editorLayout,docking:next}}))} primary={<>
<DropZone id="scene-model" className="rover-scene-drop"><LoadingRegion className="rover-view__scene" loading={!scene.ready} label="Загрузка настроек сцены">
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
</LoadingRegion></DropZone>
{editing&&<> {editing&&<>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div> <div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></IconButton></GlassSurface></div>
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div> <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('')}/> <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,.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-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-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 .nodedc-window__body {overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;}
.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: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 {display:flex;gap:var(--nodedc-space-2);overflow:auto;} .rover-material-palette__items .nodedc-button {width:100%;height:100%;min-width:0;padding:var(--nodedc-space-2);}
.rover-material-palette__items > * {flex:0 0 auto;} .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 {display:grid;justify-items:center;gap:var(--nodedc-space-1);width:100px;white-space:normal;font-size: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. */ /* 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-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-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 {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 img {width:36px;height:36px;object-fit:cover;}
.rover-scene-texture__row .nodedc-button {min-width:0;overflow:hidden;} .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", "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", "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", "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", "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 React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import * as pc from 'playcanvas' import * as pc from 'playcanvas'
import { buildSceneTree } from './sceneTree' import { buildSceneTree } from './sceneTree'
@@ -14,6 +16,7 @@ const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
export type PlayCanvasViewerProps = SceneMaterialsProps & { export type PlayCanvasViewerProps = SceneMaterialsProps & {
modelUrl: string | null modelUrl: string | null
minFitDistance?: number
postFx?: Partial<PostFxSettings> | null postFx?: Partial<PostFxSettings> | null
viewportSize?: { width: number; height: number } viewportSize?: { width: number; height: number }
onSceneReady?: (api: { app: pc.Application; camera: pc.Entity; modelRoot: pc.Entity }) => void onSceneReady?: (api: { app: pc.Application; camera: pc.Entity; modelRoot: pc.Entity }) => void
@@ -31,13 +34,6 @@ export type PlayCanvasViewerProps = SceneMaterialsProps & {
muteLogs?: boolean muteLogs?: boolean
} }
export type CameraState = {
pivot: { x: number; y: number; z: number }
distance: number
azimuthDeg: number
elevationDeg: number
}
// ------------------------------------------------------------ // ------------------------------------------------------------
// Fallback texture handler // Fallback texture handler
class SimpleTextureHandler { class SimpleTextureHandler {
@@ -583,6 +579,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
cameraEntity.setPosition(x, y, z) cameraEntity.setPosition(x, y, z)
cameraEntity.lookAt(pivot) cameraEntity.lookAt(pivot)
if (autoRotate && dt > 0) emitChange(false)
} }
const onMouseDown = (e: MouseEvent) => { const onMouseDown = (e: MouseEvent) => {
@@ -615,6 +612,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
} }
const onMouseUp = () => { const onMouseUp = () => {
if (!dragging && !panning) return
dragging = false dragging = false
panning = false panning = false
idleTime = 0 idleTime = 0
@@ -622,9 +620,14 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
} }
const onWheel = (e: WheelEvent) => { const onWheel = (e: WheelEvent) => {
// Own wheel/pinch only on the canvas: never zoom the page and camera together.
e.preventDefault();e.stopPropagation();
idleTime = 0 idleTime = 0
const dir = Math.sign(e.deltaY) 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) updateCamera(0)
emitChange(false) emitChange(false)
if (wheelCommitTimer) window.clearTimeout(wheelCommitTimer) if (wheelCommitTimer) window.clearTimeout(wheelCommitTimer)
@@ -639,7 +642,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
canvas.addEventListener('mousedown', onMouseDown) canvas.addEventListener('mousedown', onMouseDown)
window.addEventListener('mousemove', onMouseMove) window.addEventListener('mousemove', onMouseMove)
window.addEventListener('mouseup', onMouseUp) window.addEventListener('mouseup', onMouseUp)
canvas.addEventListener('wheel', onWheel, { passive: true }) canvas.addEventListener('wheel', onWheel, { passive: false })
canvas.addEventListener('contextmenu', onContextMenu) canvas.addEventListener('contextmenu', onContextMenu)
app.on('update', updateCamera as any) app.on('update', updateCamera as any)
@@ -877,8 +880,9 @@ function applyPostFx(
} }
export default function PlayCanvasViewer({ export default function PlayCanvasViewer({
minFitDistance = 1.8,
modelUrl, modelUrl,
materials, assignments, editing, onMaterialPick, onTextureState, materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState,
postFx, postFx,
viewportSize, viewportSize,
onSceneReady, onSceneReady,
@@ -916,7 +920,8 @@ export default function PlayCanvasViewer({
const gridMaterialRef = useRef<pc.ShaderMaterial | null>(null) const gridMaterialRef = useRef<pc.ShaderMaterial | null>(null)
const sceneMapRef = useRef<Map<string, pc.Entity>>(new Map()) const sceneMapRef = useRef<Map<string, pc.Entity>>(new Map())
const loadTokenRef = useRef(0) 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 onCameraChangeRef = useRef<PlayCanvasViewerProps['onCameraChange']>(null)
const logWarn = useCallback((...args: any[]) => { if (!muteLogs) console.warn(...args) }, [muteLogs]) const logWarn = useCallback((...args: any[]) => { if (!muteLogs) console.warn(...args) }, [muteLogs])
const logError = useCallback((...args: any[]) => { if (!muteLogs) console.error(...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 [skyboxVersion, setSkyboxVersion] = useState(0)
const [modelVersion, setModelVersion] = useState(0) const [modelVersion, setModelVersion] = useState(0)
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,editing,onMaterialPick,onTextureState}) useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState})
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx]) const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState]) 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. // PlayCanvas writes fixed pixel CSS sizes; the hosted pane remains fluid.
canvas.style.width = '100%' canvas.style.width = '100%'
canvas.style.height = '100%' canvas.style.height = '100%'
const model = inst.root.findByName('Model') as pc.Entity | null // Hold focal length in CSS pixels. Resize changes the crop, never orbit state.
const bounds = model ? computeAabb(model) : null if (!referenceHeightRef.current) referenceHeightRef.current = h
const orbit = (inst as any).__orbit as OrbitController | undefined const camera = cameraEntityRef.current?.camera
if (bounds && orbit) { if (camera) camera.fov = viewportFov(h, referenceHeightRef.current)
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))
}
}, []) }, [])
useEffect(() => { useEffect(() => {
@@ -1082,7 +1083,7 @@ export default function PlayCanvasViewer({
inertiaFactor: cameraInertiaFactor ?? undefined, inertiaFactor: cameraInertiaFactor ?? undefined,
inertiaTime: cameraInertiaTime ?? undefined, inertiaTime: cameraInertiaTime ?? undefined,
onChange: (state, commit) => { 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 if (!modelRoot) return
let cancelled = false let cancelled = false
const request = new AbortController()
const loadGlb = async (url: string) => { const loadGlb = async (url: string) => {
const loadToken = ++loadTokenRef.current const loadToken = ++loadTokenRef.current
@@ -1493,7 +1495,11 @@ export default function PlayCanvasViewer({
ensureTextureHandler(app) 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) app.assets.add(asset)
const loadedAsset = asset const loadedAsset = asset
@@ -1535,7 +1541,8 @@ export default function PlayCanvasViewer({
const cam = cameraEntityRef.current?.camera const cam = cameraEntityRef.current?.camera
const vertical = (cam?.fov ?? 28) * Math.PI / 360 const vertical = (cam?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1)) const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1))
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 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) { if (exposeSceneGraph || onSceneGraph) {
@@ -1564,6 +1571,7 @@ export default function PlayCanvasViewer({
return () => { return () => {
cancelled = true cancelled = true
request.abort()
} }
}, [resolvedUrl, exposeSceneGraph, onSceneGraph]) }, [resolvedUrl, exposeSceneGraph, onSceneGraph])
@@ -1573,7 +1581,9 @@ export default function PlayCanvasViewer({
if (!app) return if (!app) return
const orbit = (app as any).__orbit as OrbitController | undefined const orbit = (app as any).__orbit as OrbitController | undefined
if (!orbit) return if (!orbit) return
if (cameraState.referenceHeight) referenceHeightRef.current = cameraState.referenceHeight
orbit.setState(cameraState) orbit.setState(cameraState)
resizeCanvas()
}, [appReady, cameraState]) }, [appReady, cameraState])
useEffect(() => { useEffect(() => {
@@ -1622,12 +1632,15 @@ export default function PlayCanvasViewer({
const modelEntity = (modelRoot as any).findByName?.('Model') as pc.Entity | null const modelEntity = (modelRoot as any).findByName?.('Model') as pc.Entity | null
const aabb = computeAabb(modelEntity || modelRoot) const aabb = computeAabb(modelEntity || modelRoot)
if (!aabb) return if (!aabb) return
referenceHeightRef.current = canvasRef.current?.clientHeight || referenceHeightRef.current
resizeCanvas()
orbit.setState({ orbit.setState({
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z }, pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
distance: Math.max(1.8,aabb.halfExtents.length() / 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, azimuthDeg: 45,
elevationDeg: 10, elevationDeg: 10,
}) })
onCameraChangeRef.current?.({...orbit.getState(),referenceHeight:referenceHeightRef.current},true)
}, [appReady, cameraResetToken, modelVersion]) }, [appReady, cameraResetToken, modelVersion])
useEffect(() => { useEffect(() => {
@@ -0,0 +1,47 @@
import * as pc from 'playcanvas';
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
const surfaces=new WeakMap<pc.StandardMaterial,{known:boolean;spec:MaterialSpec;gradient:ChargeGradient}>();
export type ChargeState={soc:number|null;fresh:boolean};
const emission=`
uniform vec3 chargeColorA;
uniform vec3 chargeColorB;
uniform float chargeTime;
uniform float chargeScale;
uniform float chargeIntensity;
uniform float chargeSaturation;
void getEmission() {
vec3 p=vPositionW*chargeScale;
float wave=sin(p.x*0.77+sin(p.y*0.91+chargeTime)*1.2+chargeTime*0.43);
wave+=sin(p.z*0.71-p.y*0.48+sin(p.x*0.57-chargeTime*0.61));
float blend=smoothstep(-1.6,1.6,wave);
vec3 color=mix(chargeColorA,chargeColorB,blend);
color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation);
dEmission=color*chargeIntensity;
}`;
export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){
const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL);
if(gradient?.enabled){chunks.set('emissivePS',emission);material.emissive.set(1,1,1);material.emissiveIntensity=1;material.diffuse.set(.02,.02,.02);}
else chunks.delete('emissivePS');
}
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec){
const known=typeof state?.soc==='number'&&Number.isFinite(state.soc);
const applied=surfaces.get(material);
if(!applied||applied.known!==known||applied.spec!==spec||applied.gradient!==gradient){
if(known)material.diffuse.set(.02,.02,.02);else material.diffuse.fromString(gradient.fallbackColor);
material.metalness=known?spec.metalness:gradient.fallbackMetalness;
material.gloss=known?spec.roughness:gradient.fallbackRoughness;
material.specularityFactor=known?spec.reflectivity:gradient.fallbackReflectivity;
material.opacity=known?spec.opacity:gradient.fallbackOpacity;
material.blendType=material.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
material.depthWrite=material.blendType===pc.BLEND_NONE;
material.update();surfaces.set(material,{known,spec,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.intensity:0);
material.setParameter('chargeSaturation',known?1:0);
}
@@ -1,20 +1,28 @@
import type * as pc from 'playcanvas' import type * as pc from 'playcanvas'
import type {SceneObject} from '../../../core/roverScene/sceneObjects'
export type SceneTreeNode = { export type SceneTreeNode = SceneObject
id: string
name: string /** Names and duplicate sibling ordinals survive reload; runtime GUIDs do not. */
enabled: boolean export function sceneObjectId(node:pc.GraphNode):string{
children: SceneTreeNode[] 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 { 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)) const children = (root.children || []).map((c) => buildSceneTree(c, map))
map.set(id, root as pc.Entity) map.set(id, root as pc.Entity)
return { return {
id, id,
name: root.name || 'Entity', name: root.name || 'Entity',
enabled: root.enabled !== false, 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, children,
} }
} }
@@ -1,12 +1,18 @@
import {useEffect,useRef,type RefObject} from 'react'; import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas'; import * as pc from 'playcanvas';
import {configureChargeMaterial,updateChargeMaterial,type ChargeState} from './chargeMaterial';
import {sceneObjectId} from './sceneTree';
export type ScenePick={objectId:string;materialId:string};
export type ScenePicker={pick:(x:number,y:number)=>ScenePick|null};
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument'; import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;editing?:boolean;onMaterialPick?:(id:string,group:string)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void}; export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'}; 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){ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState}:SceneMaterialsProps){
const latest=useRef({materials,onMaterialPick,onTextureState});latest.current={materials,onMaterialPick,onTextureState}; const latest=useRef({materials,onObjectPick,onTextureState,chargeState});latest.current={materials,onObjectPick,onTextureState,chargeState};
const animated=useRef(new Map<string,pc.StandardMaterial>());
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>()); const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
const generation=useRef(0); 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 originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>());
const customMaterials=useRef(new Map<string,pc.StandardMaterial>()); const customMaterials=useRef(new Map<string,pc.StandardMaterial>());
useEffect(()=>{ useEffect(()=>{
@@ -23,7 +29,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
map.set(id,customMaterials.current.get(id)!); 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){ 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);} 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:MaterialSpec)=>{
@@ -32,7 +38,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r'; if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update(); m.update();
}; };
const used=new Set<string>(); const used=new Set<string>();animated.current.clear();
for(const [id,spec] of Object.entries(materials)){ for(const [id,spec] of Object.entries(materials)){
const m=map.get(id);if(!m)continue; const m=map.get(id);if(!m)continue;
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness; m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
@@ -58,26 +64,39 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');}); pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
} }
} }
configureChargeMaterial(m,spec.chargeGradient);
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0,spec);}
m.update(); m.update();
} }
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);} for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
onTextureState?.(pending?'loading':'ready'); onTextureState?.(pending?'loading':'ready');
return()=>{generation.current++;}; return()=>{generation.current++;};
},[materials,assignments,modelVersion,appRef,onTextureState]); },[materials,assignments,objectAssignments,modelVersion,appRef,onTextureState]);
useEffect(()=>{
const app=appRef.current;if(!app||!modelVersion)return;
let time=0;const motion=window.matchMedia('(prefers-reduced-motion: reduce)');
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient?.enabled)updateChargeMaterial(material,gradient,live.chargeState,time,live.materials![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(()=>()=>{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(()=>{ useEffect(()=>{
const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current; 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 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 pick=(x:number,y:number):ScenePick|null=>{
const up=(e:PointerEvent)=>{ const rect=canvas.getBoundingClientRect();if(x<rect.left||x>=rect.right||y<rect.top||y>=rect.bottom)return null;
const p=start;start=null;if(!p||Math.hypot(p.x-e.clientX,p.y-e.clientY)>4)return; picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height)));picker.prepare(camera.camera!,app.scene);
const rect=canvas.getBoundingClientRect();picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height))); 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));
picker.prepare(camera.camera!,app.scene); return hit?{objectId:sceneObjectId(hit.node),materialId:hit.material.name}:null;
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);}
}; };
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); canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up);
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);picker.destroy();}; return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);onPickerReady?.(null);picker.destroy();};
},[editing,modelVersion,appRef,cameraRef,canvasRef]); },[editing,modelVersion,appRef,cameraRef,canvasRef,onPickerReady]);
} }
@@ -1,20 +1,13 @@
.rover-view { position:relative; height:100%; min-height:200px; overflow:hidden; container-type:inline-size; } .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:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
.rover-view .rover-view__scene { position:absolute; inset:0; } .rover-view .rover-view__scene { position:absolute; inset:0; }
.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__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
.rover-view__status { position:absolute; top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); left:var(--nodedc-space-3); } .rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; transform:scale(.8); transform-origin:bottom right; }
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); } .rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); } .rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
.rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; } .rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; }
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; } .rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
@container (max-width: 380px) {
.rover-view:has(.rover-view__controls) .rover-view__authority { top:calc(var(--observation-overlay-header-space, 0px) + 48px); bottom:auto; }
}
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); } .rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); } .rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
.rover-telemetry { height:100%; overflow:auto; padding:var(--nodedc-space-3); display:flex; flex-wrap:wrap; align-content:start; gap:var(--nodedc-space-4); font-size:var(--nodedc-font-size-sm); } .rover-telemetry {height:100%; min-height:0; min-width:0; overflow:hidden; padding:var(--nodedc-space-3);}.rover-telemetry > .nodedc-comparison-table {max-height:100%;}
.rover-telemetry section { flex:1; min-width:170px; }.rover-telemetry section > span { display:block; color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-xs); margin-top:var(--nodedc-space-1); }
.rover-telemetry dl { display:grid; gap:var(--nodedc-space-1); margin-bottom:0; }.rover-telemetry dl > div { display:flex; justify-content:space-between; gap:var(--nodedc-space-3); }
.rover-telemetry dt { color:var(--nodedc-text-secondary); }.rover-telemetry dd { margin:0; font-variant-numeric:tabular-nums; }
@@ -0,0 +1,10 @@
.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__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);}
.rover-dev-options {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-dev-options .nodedc-settings-card__body {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-logs__actions {display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);}
@@ -1,4 +1,4 @@
import { FieldFrame, Select } from "@nodedc/ui-react"; import { InspectorSelectField } from "@nodedc/ui-react";
import type { AiModules, AiSelection } from "../../core/simulation/aiPolygon"; import type { AiModules, AiSelection } from "../../core/simulation/aiPolygon";
const labels = { segmentation: "Поверхность", detection: "Объекты", geometry: "Рельеф", const labels = { segmentation: "Поверхность", detection: "Объекты", geometry: "Рельеф",
@@ -8,10 +8,13 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
modules: AiModules; selection: AiSelection; disabled: boolean; onChange: (value: AiSelection) => void; modules: AiModules; selection: AiSelection; disabled: boolean; onChange: (value: AiSelection) => void;
}) { }) {
return <section className="ai-polygon__section" aria-label="Композиция AI"> return <section className="ai-polygon__section" aria-label="Композиция AI">
<h3>Модули AI</h3> {selection.selections.some(s=>s.module_id==="simulation-waypoint-mission")?<>
<InspectorSelectField label="Профиль движения" disabled={disabled} value={String(selection.selections.find(s=>s.module_id==="simulation-waypoint-mission")?.parameters.environment??"park")}
options={[{value:"natural",label:"Природа · пересечённая местность"},{value:"park",label:"Парк · дорожки"},{value:"urban",label:"Город · тротуары"}]}
onChange={environment=>onChange({...selection,selections:selection.selections.map(s=>s.module_id==="simulation-waypoint-mission"?{...s,parameters:{...s.parameters,environment}}:s)})}/>
</>:null}
{modules.catalog.groups.filter(({ modules: options }) => options.length > 0).map(({ group, modules: options }) => {modules.catalog.groups.filter(({ modules: options }) => options.length > 0).map(({ group, modules: options }) =>
<FieldFrame key={group} label={labels[group]}> <InspectorSelectField key={group} label={labels[group]} disabled={disabled}
<Select label={`Модуль: ${labels[group]}`} disabled={disabled}
value={selection.selections.find((row) => row.group === group)?.module_id ?? ""} value={selection.selections.find((row) => row.group === group)?.module_id ?? ""}
options={options.map((module) => ({ value: module.moduleId, label: module.label }))} options={options.map((module) => ({ value: module.moduleId, label: module.label }))}
onChange={(value) => { onChange={(value) => {
@@ -20,7 +23,6 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), { onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), {
group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults, group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults,
}] }); }] });
}} /> }} />)}
</FieldFrame>)}
</section>; </section>;
} }
@@ -0,0 +1,58 @@
import {useEffect,useState} from 'react';
import {Button,Icon,InspectorSelectField,ToastStack} from '@nodedc/ui-react';
import type {AiModules,AiSelection} from '../../core/simulation/aiPolygon';
import {createAiProfile,fetchAiProfiles,sameAiIntent,updateAiProfile,type AiProfile} from '../../core/simulation/aiProfiles';
import {currentSelection} from '../../core/simulation/runConfiguration';
import {AiCompositionFields} from './AiCompositionFields';
import {AiProfileWindow} from './AiProfileWindow';
export function AiConfiguration({modules,selection,disabled,onChange}: {
modules:AiModules;selection:AiSelection;disabled:boolean;onChange:(selection:AiSelection)=>void;
}) {
const [profiles,setProfiles]=useState<AiProfile[]>([]);
const [picked,setPicked]=useState<string|null>(null);
const [modal,setModal]=useState<'save'|AiProfile|null>(null);
const [busy,setBusy]=useState(false);
const [error,setError]=useState<string|null>(null);
useEffect(()=>{let active=true;void fetchAiProfiles().then(rows=>{if(active)setProfiles(rows);})
.catch(e=>{if(active)setError(e.message);});return()=>{active=false;};},[]);
const current=picked===null?profiles.find(p=>sameAiIntent(p.composition,selection)):profiles.find(p=>p.profile_id===picked);
const changed=!!current&&!sameAiIntent(current.composition,selection);
const accept=(value:AiProfile)=>setProfiles(rows=>value.removed?rows.filter(p=>p.profile_id!==value.profile_id)
:[...rows.filter(p=>p.profile_id!==value.profile_id),value].sort((a,b)=>a.name.localeCompare(b.name)));
const save=async(name:string,removed=false)=>{
if(!modal||busy)return;setBusy(true);setError(null);
try {
const editing=modal==='save'?null:modal;
const composition=editing?undefined:currentSelection(selection,modules);
const value=editing?await updateAiProfile(editing,{name,removed})
:current&&name===current.name?await updateAiProfile(current,{composition})
:await createAiProfile(name,composition!);
accept(value);setModal(null);
if(!editing){setPicked(value.profile_id);onChange(value.composition);}
if(removed&&picked===value.profile_id)setPicked(null);
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');
void fetchAiProfiles().then(setProfiles).catch(()=>undefined);
}finally{setBusy(false);}
};
return <section className="ai-polygon__configuration-column" aria-label="Конфигурация AI">
<h3>Конфигурация AI</h3>
<div className="ai-polygon__profile-row">
<InspectorSelectField label="Профиль AI" value={current?.profile_id??''} disabled={disabled||busy}
options={[{value:'',label:'Своя конфигурация'},...profiles.map(p=>({value:p.profile_id,
label:p.name+(changed&&p===current?' · изменён':''),
action:{label:`Редактировать профиль «${p.name}»`,icon:<Icon name="edit"/>,disabled:disabled||busy,
onAction:()=>{setError(null);setModal(p);}}}))]}
onChange={id=>{if(!id){setPicked('');return;}const value=profiles.find(p=>p.profile_id===id);if(!value)return;
try{onChange(currentSelection(value.composition,modules));setPicked(id);setError(null);}
catch(e){setError(e instanceof Error?e.message:'Профиль недоступен.');}}}/>
<Button icon={<Icon name="save"/>} disabled={disabled||busy} onClick={()=>{setError(null);setModal('save');}}>Сохранить профиль</Button>
</div>
<AiCompositionFields modules={modules} selection={selection} disabled={disabled||busy} onChange={onChange}/>
{modal&&<AiProfileWindow key={modal==='save'?'save':modal.profile_id} editing={modal!=='save'} busy={busy}
initialName={modal==='save'?current?.name??'':modal.name} onClose={()=>setModal(null)} onSave={name=>void save(name)}
onRemove={modal==='save'?undefined:()=>void save(modal.name,true)}/>}
<ToastStack items={error?[{id:'ai-profile',tone:'error',title:'Профиль AI не сохранён',description:error}]:[]}
onDismiss={()=>setError(null)}/>
</section>;
}
@@ -0,0 +1,301 @@
import type {SceneView} from "../../core/simulation/simulationLayout";
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
import { sceneClipBounds } 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 { 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, type NavigationOwner } from "./EditorCamera";
import { EditorSurfacePicker } from "./EditorSurfacePicker";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
export interface EditorMarker { id: string; base: ScreenPoint; top: ScreenPoint; x: ScreenPoint; y: ScreenPoint; z: ScreenPoint }
/** Local planning view. Lifecycle deliberately excludes Ammo, Isaac and inference. */
export class AiEditorRuntime {
private app: Application;
private camera: Entity;
private scan: Entity;
private asset: Asset | null = null;
private controls: EditorCamera;
private surfacePicker: EditorSurfacePicker;
private collisionVisible = false;
private annotations: PlannerMarkers;
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private terrain = new EditorTerrain();
private urbanLayer: EditorUrbanMapLayer | null = null;
private urbanBounds:number[][]=[];
private cameraProject: ((q:[number,number,number,number])=>void)|null=null;
private semanticProject: (()=>void)|null = null;
private visualBounds:number[][]=[];
private urbanVisible=false;
private experienceLayer: EditorUrbanMapLayer | null = null;
private experiencePoints: number[][] = [];
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
private collisionLayer: EditorCollisionLayer | null = null;
private resize: ResizeObserver;
private abort = new AbortController();
private disposed = false;
private dirty = true;
private previous = "";
private points: AiWaypoint[] = [];
private route: number[][] = [];
clip = Infinity;
clipFloor = -Infinity;
height: [number, number] = [0, 1];
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
private onProject: (markers: EditorMarker[]) => void,
private onRouteProject: (points: ScreenPoint[]) => void = () => undefined) {
canvas.tabIndex = 0;
this.app = new Application(canvas, { graphicsDeviceOptions: { antialias: false, alpha: false,
preserveDrawingBuffer: false, powerPreference: "default" } });
const app = this.app;
this.camera = new Entity("Editor camera", app);
this.scan = new Entity("Editor Gaussian proxy", app);
app.autoRender = false; app.graphicsDevice.maxPixelRatio = 1;
app.setCanvasFillMode(FILLMODE_NONE, 1, 1); app.setCanvasResolution(RESOLUTION_AUTO);
this.camera.addComponent("camera", { nearClip: .05, farClip: 3000, fov: 60, clearColor: new Color(.025,.03,.04) });
this.controls = new EditorCamera(canvas.parentElement!, canvas);
this.surfacePicker = new EditorSurfacePicker(app, this.camera, canvas);
app.root.addChild(this.camera);
app.root.addChild(this.scan);
this.annotations = new PlannerMarkers(app,this.camera,canvas);
this.controls.pick = (x,y) => { const p=this.pick(x,y);return p?toEditor(p):null; };
this.controls.pickSurface = async (x,y) => {
this.syncCamera();
if(this.scan.enabled && this.scan.gsplat) return this.surfacePicker.pick(x,y);
if(!this.collisionVisible)return null;
const from=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,2000);
return this.terrain.pickSurface([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,false,this.clipFloor)?.toArray()??null;
};
const transform = new Mat4().set(localScene(cache).transforms.worldFromVisual);
this.scan.setPosition(transform.getTranslation());
this.scan.setRotation(new Quat().setFromMat4(transform));
this.scan.setLocalScale(transform.getScale());
app.scene.gsplat.splatBudget = 0;
this.resize = new ResizeObserver(() => {
const rect = canvas.parentElement!.getBoundingClientRect();
app.resizeCanvas(Math.max(1,rect.width), Math.max(1,rect.height));
this.controls.resize(Math.max(1,rect.width), Math.max(1,rect.height)); this.dirty = true;
});
this.resize.observe(canvas.parentElement!);
app.systems.gsplat?.on("frame:request", () => { app.renderNextFrame = true; });
app.on("update", (dt: number) => {
this.controls.update(dt); this.syncCamera();
if (this.annotations.setRotationCenter(this.controls.rotationCenter)) app.renderNextFrame = true;
if (this.annotations.update(dt)) app.renderNextFrame = true;
const matrix = this.camera.getWorldTransform().data.join(",")+this.controls.camera.projectionMatrix.elements.join(",");
if (matrix !== this.previous || this.dirty) {
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
this.semanticProject?.();this.cameraProject?.(this.controls.camera.quaternion.toArray());
this.onExperienceProject(this.experiencePoints.map(p=>this.project(...toEditor(p) as [number,number,number])));
this.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
this.onProject(this.points.map((p) => {
const [x,y,z] = toEditor(p.position);
return { id:p.id, base:this.project(x,y,z), top:this.project(x,y+this.preferences.waypoint.height,z),
x:this.project(x+this.annotations.axisLength,y,z), y:this.project(x,y+this.annotations.axisLength,z), z:this.project(x,y,z+this.annotations.axisLength) };
}));
}
});
app.start(); this.home();
}
async load() {
const scene = localScene(this.cache);
if (scene.collision.available && scene.collision.meshUrl)
await this.terrain.load(scene.collision.meshUrl, this.abort.signal, scene.transforms.worldFromCollision);
if (this.disposed) return;
const asset = new Asset("Route editor", "gsplat", { url: scene.visual.streamedSogUrl! });
this.asset = asset;
await new Promise<void>((resolve,reject) => {
asset.once("error", (e: string) => reject(new Error(e)));
asset.ready(() => resolve()); this.app.assets.add(asset); this.app.assets.load(asset);
});
if (this.disposed) { asset.unload(); return; }
this.scan.addComponent("gsplat", { asset, unified: true });
const bounds = new BoundingBox();
bounds.setFromTransformedAabb(this.scan.gsplat!.customAabb!, this.scan.getWorldTransform());
const low=bounds.getMin(),high=bounds.getMax();
this.visualBounds=[...Array(8)].map((_,i)=>[i&1?high.x:low.x,i&2?high.y:low.y,i&4?high.z:low.z]);
const terrain=this.terrain.bounds;
this.height = sceneClipBounds([low.y, high.y], terrain.isEmpty() ? null : [terrain.min.y, terrain.max.y]);
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
uniform float editorClip;
uniform float editorFloor;
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;
}` });
this.setPreferences(this.preferences);
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
else this.controls.sceneCenter = terrain.getCenter(this.controls.sceneCenter);
if (!scene.collision.available) { this.controls.top(this.visualBounds); this.syncCamera(); }
this.setClip(Infinity); this.dirty = true;
}
setExperience(document: UrbanMap, points: number[][], callback: (p: ScreenPoint[])=>void) {
this.experienceLayer?.dispose();this.experienceLayer=new EditorUrbanMapLayer(this.app,this.camera,document);
this.experiencePoints=points;this.onExperienceProject=callback;this.experienceLayer.setClip(this.clip,this.clipFloor);this.dirty=true;
}
showExperience(visible: boolean) {this.experienceLayer?.setVisible(visible);this.dirty=true;}
clearExperience() {this.experienceLayer?.dispose();this.experienceLayer=null;this.experiencePoints=[];this.onExperienceProject=()=>undefined;this.dirty=true;}
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;
}
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;}
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;}
watchSemantic(callback:(()=>void)|null) { this.semanticProject=callback;this.dirty=true; }
projectSemantic(point:number[]): ScreenPoint {
if(point[2]<this.clipFloor||point[2]>this.clip)return null;
return this.project(...toEditor(point) as [number,number,number]);
}
semanticSegmentParameter(a:number[],b:number[],u:number) {
if(isOrthographic(this.controls.camera))return u;
const depth=(p:number[])=>new Vec3(...toEditor(p)).sub(this.camera.getPosition()).dot(this.camera.forward);
const za=depth(a),zb=depth(b);
return u*za/((1-u)*zb+u*za);
}
/** Explicit planar edit: preserve source elevation, never pretend a ray hit ground. */
moveSemantic(point:number[],x:number,y:number,axis:import("../../core/simulation/semanticVector").SemanticAxis="xy") {
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const origin=toMission([from.x,from.y,from.z]),direction=toMission([to.x-from.x,to.y-from.y,to.z-from.z]);
let result:number[]|null;
if(axis.length===1)result=dragWaypoint(origin,direction,point,axis as "x"|"y"|"z");
else {
const normal=[0,1,2].find(k=>!axis.includes("xyz"[k]))!;
if(Math.abs(direction[normal])<1e-8)return null;
const t=(point[normal]-origin[normal])/direction[normal];if(t<0)return null;
result=point.map((v,k)=>k===normal?v:origin[k]+t*direction[k]);
}
if(!result)return null;
return result[2]>=this.clipFloor&&result[2]<=this.clip?result:null;
}
semanticGizmo(point:number[]) {
const depth=new Vec3(...toEditor(point)).sub(this.camera.getPosition()).dot(this.camera.forward);
const length=screenSpan(this.controls.camera,depth)*this.preferences.pivot.pixels*.7/Math.max(1,this.canvas.clientHeight);
return {length,colors:this.preferences.pivot,base:this.projectSemantic(point),
x:this.projectSemantic([point[0]+length,point[1],point[2]]),
y:this.projectSemantic([point[0],point[1]+length,point[2]]),
z:this.projectSemantic([point[0],point[1],point[2]+length])};
}
async pickSemanticSurface(x:number,y:number) {
if(!this.scan.enabled||!this.scan.gsplat)return null;
this.syncCamera();
const hit=await this.surfacePicker.pick(x,y);
if(!hit)return null;
const q=toMission(hit);
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; }
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
this.collisionLayer.setClip(this.clip,this.clipFloor);
}
this.scan.enabled = gaussian;
this.collisionLayer?.setMode(collision ? (gaussian ? "combined" : "collision") : "visual");
this.dirty = true;
}
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
top() {const points=(this.urbanVisible&&this.urbanBounds.length?this.urbanBounds:this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor);this.controls.top(points.length?points:this.visualBounds);this.syncCamera();this.dirty=true;}
setPoints(points: AiWaypoint[]) { this.points = points; this.annotations.set(points,this.selected,this.preferences);this.dirty = true; }
setSelected(id: string|null) {this.selected=id;this.annotations.set(this.points,id,this.preferences);this.dirty=true;}
setPreferences(preferences: PlannerPreferences) {
this.controls.navigation=preferences.navigation;
this.preferences=preferences;this.annotations.set(this.points,this.selected,preferences);
const profile=QUALITY_PROFILES[preferences.quality];
this.app.scene.gsplat.splatBudget=profile.splatBudget;
this.app.graphicsDevice.maxPixelRatio=Math.min(window.devicePixelRatio||1,profile.pixelRatio);
if(this.scan.gsplat) {
Object.assign(this.scan.gsplat,{lodBaseDistance:profile.lodBaseDistance,lodMultiplier:profile.lodMultiplier,lodRangeMin:profile.lodRangeMin,lodRangeMax:profile.lodRangeMax});
}
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
}
setClip(height: number, 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.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
}
this.dirty = true;
}
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;
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);
}
home() {
const first = this.points[0]?.position ?? [...this.cache.world.settings.spawn_xy, this.cache.world.settings.ground_z];
this.controls.home(toEditor(first)); this.syncCamera(); this.dirty = true;
}
pick(x: number,y: number) {
const width = this.canvas.clientWidth, height = this.canvas.clientHeight;
const from = this.camera.camera!.screenToWorld(x*width,y*height,.05);
const to = this.camera.camera!.screenToWorld(x*width,y*height,2000);
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,this.clipFloor);
return hit ? toMission(hit.toArray()) : null;
}
pickWaypoint(x:number,y:number) {
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const direction=[to.x-from.x,to.y-from.y,to.z-from.z];
let nearest=Infinity, id:string|null=null;
for(const point of this.points) {
const t=waypointHit([from.x,from.y,from.z],direction,toEditor(point.position),this.preferences.waypoint.diameter/2,this.preferences.waypoint.height);
if(t!==null && t<nearest){nearest=t;id=point.id;}
}
return id;
}
move(point: AiWaypoint, x: number, y: number, axis: WaypointAxis) {
const p = toEditor(point.position);
const from = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to = this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const hit = dragWaypoint([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],p,axis);
if (!hit) return null;
if (axis !== "xz") return toMission(hit);
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip,this.clipFloor);
return ground ? toMission(ground.toArray()) : null;
}
private project(x:number,y:number,z:number): ScreenPoint {
const point = this.camera.camera!.worldToScreen(new Vec3(x,y,z));
return new Vec3(x,y,z).sub(this.camera.getPosition()).dot(this.camera.forward) > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
}
dispose() {
this.disposed = true;
this.controls.dispose();
this.surfacePicker.dispose();
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
this.annotations.dispose();
this.collisionLayer?.dispose();
this.urbanLayer?.dispose();this.clearExperience();
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
}
}
@@ -0,0 +1,32 @@
import { lazy, Suspense, useEffect, useState } from "react";
import { LoadingRegion } from "@nodedc/ui-react";
import { connectPreviewStream } from "../../core/simulation/previewStream";
const SpatialPreview=lazy(()=>import("./AiSpatialPreview").then(m=>({default:m.AiSpatialPreview})));
export interface InferencePreview {
frame_id:number;simulation_time_ns:number;received_at:string;environment:"park"|"natural"|"urban";
layers:({id:string;label:string;ports?:string[];legend?:{class_id:number;label:string;color:string}[]} & (
{kind?:"image";jpeg:string} | {kind:"points3d";points:[number,number,number][];source_count:number;frame:string}
))[];
}
export function useInferencePreview(runId:string|undefined,active:boolean) {
const [preview,setPreview]=useState<InferencePreview|null>(null);
useEffect(()=>{
setPreview(null);if(!runId || !active)return;
return connectPreviewStream<InferencePreview>(runId,setPreview);
},[runId,active]);
return preview;
}
export function AiInferencePreview({preview,layer}:{preview:InferencePreview;layer:string}) {
const selected=preview.layers.find(p=>p.id===layer);
if(!selected)return null;
return <div className="ai-inference-preview" aria-label={`Результат AI: ${selected.label}`}>
{selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}>
<SpatialPreview points={selected.points} label={selected.label}/>
</Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>}
<div className="ai-inference-preview__caption">
Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
{selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null}
{selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null}
</div>
</div>;
}
@@ -0,0 +1,238 @@
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
import {PlannerCameraTools} from "./PlannerCameraTools";
import { heightSlice } from "../../core/heightSlice";
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 type { PreparedRoute } from "../../core/simulation/routePreparation";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, 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";
import type { WaypointAxis } from "../../core/simulation/waypointDrag";
import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
export type LocationMode = "view" | "semantic" | "planning";
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, 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;
}) {
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
const markerSvg=useRef<SVGSVGElement>(null);
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
const viewport = useRef<HTMLDivElement>(null), loadedPoints = useRef(initialPoints);
const [preferences] = usePlannerPreferences();
const runtime = useRef<AiEditorRuntime | null>(null);
const { expanded, toggle } = useSimulationFullscreen(host);
const [ready, setReady] = useState(false), [retry,setRetry] = useState(0);
const { cache,error,setError } = useLocalScene(world,retry);
const [editing,edit] = useReducer(editWaypoints,initialPoints,waypointEditing);
const {points,selected,sequence} = editing;
const press=useRef<{id:number;x:number;y:number}|null>(null);
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
const [layout,updateLayout]=useSimulationLayout();
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);
const draftId = useRef(crypto.randomUUID().replaceAll("-",""));
const drag = useRef<{ point: AiWaypoint; axis: WaypointAxis; offset: number[] } | null>(null);
const callback = useRef(onDraft); callback.current = onDraft;
useEffect(() => {
if (cache?.status !== "ready" || !canvas.current) return;
let active = true, loaded=false;
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);
setReady(false); setError(null); setClip(null);
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
catch (e) { clearInterval(timer);window.removeEventListener("pagehide",remember);setError((e as Error).message); return; }
runtime.current = view;
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]]);}
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); });
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]);
useEffect(() => {
runtime.current?.setPoints(planning?points:[]);
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]);
useEffect(()=>{
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
},[preparedRoute?.sha256,ready,planning]);
useEffect(()=>{
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]);
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
useEffect(()=>{
if(loadedPoints.current === initialPoints) return;
loadedPoints.current=initialPoints;
edit({type:"load",points:initialPoints});
},[initialPoints]);
const add = (x:number,y:number) => {
if (points.length >= 33) { setError("В задании может быть до 33 точек."); return; }
const position = runtime.current?.pick(x,y);
if (!position) { setError("Под курсором нет доступной поверхности. Измените ракурс или срез."); return; }
const point = { id:crypto.randomUUID().replaceAll("-","").slice(0,16),position };
edit({type:"replace",points:[...points,point],selected:point.id});
};
const position = (e: { clientX:number;clientY:number }) => {
const rect = canvas.current!.getBoundingClientRect();
return [(e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height];
};
const progress = cache ? Object.values(cache.files) : [];
const bytes = progress.reduce((n,f)=>n+f.uploaded_bytes,0), total = progress.reduce((n,f)=>n+f.byte_length,0);
const message = cache?.status === "uploading" ? `Копируем сцену на диск · ${Math.round(bytes/Math.max(1,total)*100)}%`
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
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}
<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}</>;
return <div className="ai-polygon__stage" ref={host}>
{expanded ? <>
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
</> : <>
{actionsHost ? createPortal(header,actionsHost) : null}
</>}
<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}
</div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
onKeyDown={(e)=>{
if(!planning)return;
const editable=!!(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"],.nodedc-workspace-window');
const action=waypointShortcut(e,editable);
if(!busy && ready && !drag.current && action){e.preventDefault();edit({type:action});setError(null);}
}}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning routeEditing={planning} semantic={semantic}>
{ready?<div className="ai-local-editor__tools nodedc-scene-controls" inert={busy}>
<div className="ai-local-editor__tool-row">
{runtime.current&&viewport.current?<PlannerCameraTools runtime={runtime.current} viewport={viewport.current} semantic={semantic} disabled={busy}/>:null} {planning?<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>:null}
{planning&&points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
}}><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!}
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!}
runtime={runtime.current} viewport={viewport.current} active={semantic} busy={busy} source={urbanMap} headerHost={semanticHeader}/>:null}
{semantic&&!urbanMap?<StatusBadge tone="neutral">Рассчитайте инфраструктуру для редактирования</StatusBadge>:null}
</div>:null}
</SimulationViewTools>
<div className="ai-local-editor__surface"
onPointerDownCapture={(e)=>{
if(!planning || e.target!==canvas.current || e.button!==0 || busy || !ready)return;
const id=runtime.current?.pickWaypoint(...position(e) as [number,number]);
if(!id)return;
e.preventDefault();e.stopPropagation();press.current=null;
canvas.current?.focus({preventScroll:true});edit({type:"select",id});
const base=markers.find(m=>m.id===id)?.base;
if(!base)return;
edit({type:"begin"});
drag.current={point:points.find(p=>p.id===id)!,axis:"xz",offset:base.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);markerSvg.current!.setPointerCapture(e.pointerId);
}}
onPointerDown={(e)=>{if(planning&&e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
onPointerCancel={()=>{press.current=null;}}
onPointerUp={(e)=>{
const start=press.current;press.current=null;
if(!planning||!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
if(mode==="add")add(...position(e) as [number,number]);else edit({type:"select",id:null});
}}><canvas ref={canvas} aria-label="Локальная Gaussian-сцена для маршрута" />
<svg ref={markerSvg} style={!planning?{display:"none"}:undefined} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
onPointerMove={(e)=>{
if (!drag.current) return;
const d=drag.current, [x,y]=position(e);
const moved=runtime.current?.move(d.point,x+d.offset[0],y+d.offset[1],d.axis);
if(moved)edit({type:"move",points:points.map(p=>p.id===d.point.id?{...p,position:moved}:p)});
}}
onPointerUp={(e)=>{
drag.current=null;edit({type:"commit"});
runtime.current?.setNavigation(!busy);if(e.currentTarget.hasPointerCapture(e.pointerId))e.currentTarget.releasePointerCapture(e.pointerId); }}
onPointerCancel={()=>{edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}}>
{preparedRoute?<path className="ai-route__line" d={routeProjection.map((p,i)=>p?`${i&&routeProjection[i-1]?"L":"M"}${p[0]*1280},${p[1]*720}`:"").join(" ")} />:null}
{!preparedRoute?<path className="ai-route__line" d={markers.map((m,i)=>m.base?`${i&&markers[i-1].base?"L":"M"}${m.base[0]*1280},${m.base[1]*720}`:"").join(" ")} />:null}
{markers.map((m,i)=>m.base&&m.top ? <g key={m.id} data-waypoint="true" className={`ai-route__marker ${selected===m.id?"is-selected":""}`}
onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
e.preventDefault();e.stopPropagation();edit({type:"select",id:m.id});edit({type:"begin"});
drag.current={point:points.find((p)=>p.id===m.id)!,axis:"xz",offset:m.base!.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
}}>
<text textAnchor={m.top[0]>.85?"end":"start"} x={m.top[0]*1280+(m.top[0]>.85?-10:10)} y={m.top[1]*720}>{i===0?"Старт":i===markers.length-1?`Финиш · ${i}`:i}</text>
{selected===m.id ? (["x","y","z"] as const).map((axis)=>m[axis] ? <g key={axis} className="ai-local-editor__axis-hit" onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
e.preventDefault();e.stopPropagation();edit({type:"begin"});drag.current={point:points.find((p)=>p.id===m.id)!,axis,offset:m.base!.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);e.currentTarget.ownerSVGElement!.setPointerCapture(e.pointerId);
}}><line x1={m.base![0]*1280} y1={m.base![1]*720} x2={m[axis]![0]*1280} y2={m[axis]![1]*720}/>
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
</g>:null)}
</svg></div>
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
selected={urbanClasses} onChange={setUrbanClasses} 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}
</div>
</div>
</div>;
}
@@ -0,0 +1,74 @@
import { useState } from "react";
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
}) {
const queue=useInfrastructureQueue();
const [editing, setEditing] = useState<AiWorld | null>(null);
const [name, setName] = useState("");
const [confirming, setConfirming] = useState(false);
const [showRemoved, setShowRemoved] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const update = async (world: AiWorld, changes: {display_name?:string;removed?:boolean}) => {
if (busy) return;
setBusy(world.world_id); setError(null);
try {
await updateAiWorld(world.world_id, changes);
await onChanged();
setConfirming(false); setEditing(null);
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Не удалось сохранить изменения.");
} finally { setBusy(null); }
};
return <>
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
actions={<>
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
<IconButton label={`Настройки ${world.name}`} onClick={() => {
setEditing(world); setName(world.name); setConfirming(false); setError(null);
}}><Icon name="settings"/></IconButton>
</>}/>
</li>;})}</ResourceList>
{removedWorlds.length ? <>
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
Удалённые локации · {removedWorlds.length}</Button>
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
<Button disabled={busy !== null} loading={busy === world.world_id}
onClick={() => void update(world, {removed:false})}>Восстановить</Button>}/>
</li>)}</ResourceList> : null}
</> : null}
<Window open={!!editing && !confirming} title="Настройки локации" size="sm"
onClose={() => {if (!busy) setEditing(null);}}
footer={<WindowFooterActions>
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
onClick={() => setConfirming(true)}>Удалить локацию</Button>
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
</WindowFooterActions>}>
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
onChange={event => setName(event.target.value)}/>
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null}
</Window>
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
Восстановить её можно в списке удалённых локаций.</>}
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
onDismiss={() => setError(null)}/> : null}
</>;
}
@@ -0,0 +1,17 @@
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}: {
error:string|null;name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
onClose:()=>void;onSave:()=>void;
}) {
return <Window open title={launch?"Сохранить задание и запустить":"Сохранить задание"}
size="sm" onClose={()=>{if(!busy)onClose();}}
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
<div className="ai-polygon__form">
{error?<p role="alert">{error}</p>:null}
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
</div>
</Window>;
}
@@ -0,0 +1,18 @@
import {useState} from 'react';
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function AiProfileWindow({initialName='',editing=false,busy,onClose,onSave,onRemove}: {
initialName?:string;editing?:boolean;busy:boolean;onClose:()=>void;
onSave:(name:string)=>void;onRemove?:()=>void;
}) {
const [name,setName]=useState(initialName);
return <Window open size="sm" title={editing?'Редактировать профиль AI':'Сохранить профиль AI'}
onClose={()=>{if(!busy)onClose();}} footer={<WindowFooterActions>
{onRemove&&<Button icon={<Icon name="trash"/>} disabled={busy} onClick={onRemove}>Удалить профиль</Button>}
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={()=>onSave(name.trim())}>
{editing?'Сохранить имя':'Сохранить профиль'}</Button>
</WindowFooterActions>}>
<TextField label="Название профиля" maxLength={120} value={name} disabled={busy}
onChange={e=>setName(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!busy&&name.trim())onSave(name.trim());}}/>
</Window>;
}
@@ -0,0 +1,140 @@
import { useEffect, useRef, useState, type PointerEvent } from "react";
import { Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon";
import { useAiPlanningControls } from "./useAiPlanningControls";
const xy = (p: NonNullable<ScreenPoint>) => `${p[0] * 1280},${p[1] * 720}`;
function path(points: ScreenPoint[]) {
let drawing = false;
return points.map((p) => {
if (!p) { drawing = false; return ""; }
const command = `${drawing ? "L" : "M"}${xy(p)}`; drawing = true; return command;
}).join(" ");
}
type Drag = { start: [number, number]; last: [number, number]; at: number;
action: "orbit" | "pan" | "move"; point_id?: string; axis?: "x" | "y" | "xy";
base?: NonNullable<ScreenPoint>; moved: boolean };
/** Screen-space annotations only. All geometry/projection and terrain picking belong to Worker. */
export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: { run: AiRun; onChange: (run: AiRun) => void; videoReady: boolean; visible?: boolean }) {
const host = useRef<HTMLDivElement>(null);
const svg = useRef<SVGSVGElement>(null);
const drag = useRef<Drag | null>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const [selected, setSelected] = useState<string | null>(null);
const [mode, setMode] = useState<"view" | "add">("view");
const [clip, setClip] = useState<number | null>(null);
const editing = run.request?.purpose === "planning";
const data = run.telemetry?.route_overlay;
const draft = run.telemetry?.planning;
const cameraReady = videoReady && editing && !!draft && run.control !== "stop";
const { send, busy, error, keyDown, stopKeys } = useAiPlanningControls(run, onChange, cameraReady);
const pending = busy || (run.planning_sequence ?? 0) > (draft?.sequence ?? 0);
const ready = cameraReady && !pending && !draft?.camera_moving;
const low = draft?.height_min, high = draft?.height_max;
useEffect(() => { if (!pending) setClip(draft?.clip_height ?? null); }, [pending, draft?.clip_height]);
useEffect(() => {
if (!host.current) return;
const resize = new ResizeObserver(([entry]) => {
const width = (editing ? Math.min : Math.max)(entry.contentRect.width, entry.contentRect.height * 16 / 9);
setSize({ width, height: width * 9 / 16 });
});
resize.observe(host.current); return () => resize.disconnect();
}, []);
const controls = useRef({ send, cameraReady }); controls.current = { send, cameraReady };
useEffect(() => {
const element = host.current;
const wheel = (event: WheelEvent) => {
if (!(event.target instanceof Element) || !event.target.closest(".ai-route__canvas")) return;
if (!controls.current.cameraReady) return;
event.preventDefault();
const pixels = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 720 : 1);
controls.current.send({ action: "zoom", amount: Math.max(-3, Math.min(3, pixels * .006)) });
};
element?.addEventListener("wheel", wheel, { passive: false });
return () => element?.removeEventListener("wheel", wheel);
}, []);
const position = (event: { clientX: number; clientY: number }): [number, number] => {
const rect = svg.current!.getBoundingClientRect();
return [(event.clientX - rect.left) / rect.width, (event.clientY - rect.top) / rect.height];
};
const start = (event: PointerEvent<SVGElement>, point?: string, axis?: Drag["axis"]) => {
if (!cameraReady || (point && !ready)) return;
event.stopPropagation(); event.preventDefault();
svg.current?.focus({ preventScroll: true });
const marker = data?.markers.find((m) => m.id === point);
if (point) setSelected(point);
const p = position(event);
drag.current = { start: p, last: p, at: performance.now(), moved: false,
action: point ? "move" : event.shiftKey || event.button === 1 ? "pan" : "orbit",
point_id: point, axis, base: marker?.base ?? undefined };
svg.current?.setPointerCapture(event.pointerId);
};
const move = (event: PointerEvent<SVGSVGElement>) => {
const d = drag.current; if (!d) return;
const p = position(event);
d.moved ||= Math.hypot(p[0] - d.start[0], p[1] - d.start[1]) > .005;
if (d.action !== "move" && d.moved && performance.now() - d.at > 100) {
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
d.last = p; d.at = performance.now();
}
};
const end = (event: PointerEvent<SVGSVGElement>) => {
const d = drag.current; drag.current = null; if (!d) return;
const p = position(event);
if (d.action === "move" && d.moved && d.base) {
send({ action: "move", point_id: d.point_id, axis: d.axis ?? "xy",
x: Math.max(0, Math.min(1, d.base[0] + p[0] - d.start[0])),
y: Math.max(0, Math.min(1, d.base[1] + p[1] - d.start[1])) });
} else if (!d.moved && !d.point_id && mode === "add" && ready) send({ action: "add", x: p[0], y: p[1] });
else if (d.moved && d.action !== "move") {
send({ action: d.action, x: p[0] - d.last[0], y: p[1] - d.last[1] });
}
if (svg.current?.hasPointerCapture(event.pointerId)) svg.current.releasePointerCapture(event.pointerId);
};
return <div className="ai-route" ref={host} hidden={!videoReady}>
{data && visible ? <svg ref={svg} viewBox="0 0 1280 720" style={size}
className={`ai-route__canvas ${editing ? "ai-route__canvas--editing" : ""}`}
tabIndex={editing ? 0 : undefined} onKeyDown={keyDown} onBlur={stopKeys}
aria-label="Маршрут и точки задания" onContextMenu={(e) => e.preventDefault()}
onPointerDown={(e) => start(e)} onPointerMove={move} onPointerUp={end}
onPointerCancel={() => { drag.current = null; }}>
<path className="ai-route__line" d={path(data.markers.map((m) => m.base))} />
<path className="ai-route__trace" d={path(data.trace)} />
{data.markers.map((m, i) => m.base && m.top ? <g key={m.id}
className={`ai-route__marker ${selected === m.id ? "is-selected" : ""} ${!editing && i === data.active_index ? "is-active" : ""}`}
onPointerDown={(e) => start(e, m.id, "xy")}>
<line className="ai-route__beam" x1={m.base[0]*1280} y1={m.base[1]*720} x2={m.top[0]*1280} y2={m.top[1]*720} />
<circle cx={m.base[0]*1280} cy={m.base[1]*720} r="8" />
<text x={m.top[0]*1280+10} y={m.top[1]*720}>{i === 0 ? "Старт" : i === data.markers.length-1 ? `Финиш · ${i}` : i}</text>
{editing && selected === m.id ? (["x", "y"] as const).map((axis) => {
const p = axis === "x" ? m.x_axis : m.y_axis;
return p ? <g key={axis} className="ai-route__axis" onPointerDown={(e) => start(e, m.id, axis)}>
<line x1={m.base![0]*1280} y1={m.base![1]*720} x2={p[0]*1280} y2={p[1]*720} />
<circle cx={p[0]*1280} cy={p[1]*720} r="12" />
</g> : null;
}) : null}
</g> : null)}
</svg> : null}
{editing && low != null && high != null && high > low ? <div className="ai-route__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={clip ?? high}
min={low} max={high} step="any" disabled={!cameraReady}
formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`}
formatLimit={(value) => value.toFixed(1).replace('.', ',')}
onChange={(value) => {
const height = value >= high - Math.max(1, high-low)*1e-9 ? null : value;
setClip(height); send({ action: "clip", amount: value, enabled: height != null });
}} />
</div> : null}
{editing ? <div className="ai-route__tools nodedc-viewport-controls">
<SegmentedControl label="Инструмент маршрута" size="dense" value={mode} onChange={setMode}
items={[{ value: "view", label: "Обзор" }, { value: "add", label: "Точка по клику" }]} />
<Button disabled={!ready} onClick={() => send({ action: "add", x: .5, y: .5 })}>Добавить waypoint</Button>
<Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button>
<Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p>
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null}
</div> : null}
</div>;
}
@@ -14,12 +14,12 @@ export function AiRunActions({ run, onChange }: { run: AiRun; onChange: (run: Ai
}; };
return <> return <>
{!terminal ? <> {!terminal ? <>
<Button disabled={!!busy || pending || ["starting", "stopping", "disconnected"].includes(run.state)} {run.state !== "stopping" && run.state !== "starting" ? <Button disabled={!!busy || pending || ["starting", "stopping", "disconnected"].includes(run.state)}
variant={run.state === "ready" ? "primary" : "secondary"} variant={run.state === "ready" ? "primary" : "secondary"}
loading={busy === "pause" || busy === "play"} loading={busy === "pause" || busy === "play"}
onClick={() => command(run.state === "running" ? "pause" : "play")}> onClick={() => command(run.state === "running" ? "pause" : "play")}>
{run.state === "starting" ? "Подготовка…" : run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"} {run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
</Button> </Button> : null}
<Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"} <Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"}
icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button> icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button>
</> : null} </> : null}
@@ -0,0 +1,73 @@
import { Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
import type { AiModules, AiRun } from "../../core/simulation/aiPolygon";
import { AiSessionSection, useSessionLayout } from "./AiSessionSection";
const outcomes = {
"goal-reached": "Маршрут пройден", "time-limit": "Лимит времени",
"operator-stop": "Остановлен оператором", stuck: "Проезд не найден",
unstable: "Опасный наклон", error: "Ошибка выполнения", "not-evaluated": "Результат не определён",
};
const reasons: Record<string, string> = {
"stale-camera": "Устарел кадр камеры", "stale-command": "Устарело решение",
"inference-error": "Ошибка inference", "no-road": "Не найдена поверхность для движения",
obstacle: "Препятствие", waiting: "Ожидание пути", uncertain: "Недостаточно данных",
paused: "Пауза оператора", "goal-reached": "Достижение цели", stuck: "Нет проезда",
unstable: "Опасный наклон", unknown: "Причина не записана",
};
const measured = (value: number | null, unit: string, digits = 1) =>
value === null ? "Нет измерения" : `${value.toFixed(digits)} ${unit}`;
export function AiRunReport({ runs, modules, onRemove, removing, worldId }: { worldId:string; runs: AiRun[]; modules: AiModules|null;
onRemove:(run:AiRun)=>void; removing:string|null }) {
const [open,setOpen] = useSessionLayout(`${worldId}:runs`, []);
const names = new Map(modules?.catalog.groups.flatMap(g=>g.modules.map(m=>[m.moduleId,m.label] as const)) ?? []);
const available = runs.filter((run) => run.request?.purpose !== "planning");
return <AiSessionSection scope={`${worldId}:results`} title="Результаты сессии">
{available.length ? <Inspector variant="panel" openSections={open} onOpenSectionsChange={setOpen} className="ai-polygon__history" sections={available.map((run)=>({
id:run.run_id, icon:<Icon name="activity"/>,
label:`${run.created_at || run.report?.generated_at ? new Date(run.created_at ?? run.report!.generated_at).toLocaleString("ru-RU") : "Время не записано"} · ${run.robot?.name ?? "Ровер не записан"} · ${run.plan_display_name ?? run.plan?.name ?? "Без задания"}`,
description:`${run.report ? outcomes[run.report.mission_outcome] : run.message ?? "Прогон выполняется"} · ${(run.request?.composition?.selections ?? []).map(s=>names.get(s.module_id) ?? s.module_id).join(" · ") || "AI не запускался"}`,
content:<GlassSurface padding="md"><RunDetails run={run}/></GlassSurface>,
action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`,
icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
onAction:()=>onRemove(run)},
}))}/> : <p>В этой локации ещё нет прогонов.</p>}
</AiSessionSection>;
}
function RunDetails({run}:{run:AiRun}) {
if(!run.report)return <p>{run.message ?? "Отчёт появится после завершения прогона."}</p>;
const report=run.report;
return <div className="ai-polygon__form ai-polygon__report">
<StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}>
{outcomes[report.mission_outcome]}
</StatusBadge>
<dl>
{run.state==='failed'&&run.message?<div><dt>Причина остановки</dt><dd>{run.message}</dd></div>:null}
<div><dt>Задание</dt><dd>{run.plan_display_name ?? run.plan?.name ?? "Без сохранённого задания"}</dd></div>
<div><dt>Ровер</dt><dd>{run.robot?.name ?? "Не записан"}</dd></div>
{run.rover_configuration?<div><dt>Масса / груз</dt><dd>{run.rover_configuration.total_mass_kg} / {run.rover_configuration.settings.payload_mass_kg} кг</dd></div>:null}
{report.speed?<><div><dt>Скорость · заданная / пиковая</dt><dd>{measured(report.speed.requested_max_mps,"м/с",3)} / {measured(report.speed.measured_max_mps,"м/с",3)}</dd></div>
<div><dt>Максимальное превышение / длительность</dt><dd>{measured(report.speed.maximum_excess_mps,"м/с",4)} / {measured(report.speed.seconds_above_requested,"с",2)}</dd></div></>:null}
<div><dt>Цели после стартовой точки</dt><dd>{report.waypoints_reached === null ? "Нет измерения" : `${report.waypoints_reached} / ${report.waypoint_count}`}</dd></div>
<div><dt>Пройдено</dt><dd>{measured(report.distance_m, "м", 2)}</dd></div>
<div><dt>Время мира</dt><dd>{measured(report.simulation_seconds, "с")}</dd></div>
<div><dt>До конечной цели</dt><dd>{measured(report.goal_error_m, "м", 2)}</dd></div>
<div><dt>Решения AI / ошибки</dt><dd>{report.inference_count} / {report.inference_errors}</dd></div>
<div><dt>Задержка AI · медиана / P95</dt><dd>{measured(report.inference_ms_p50, "мс", 0)} / {measured(report.inference_ms_p95, "мс", 0)}</dd></div>
<div><dt>Столкновения</dt><dd>{report.collision_count === null ? "Учёт ещё не подключён" : report.collision_count}</dd></div>
</dl>
<h3>Остановки после начала движения</h3>
{report.stops.length ? <dl>{report.stops.map((stop) => <div key={stop.reason}>
<dt>{reasons[stop.reason] ?? stop.reason}</dt><dd>{stop.events} · {stop.seconds.toFixed(1)} с</dd>
</div>)}</dl> : <p>Переходов от движения к нулевой команде не записано.</p>}
<p>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</p>
<dl className="ai-polygon__report-identities">
<div><dt>Прогон</dt><dd>{report.run_id}</dd></div>
<div><dt>Профиль ровера</dt><dd>{report.robot_sha256 ?? "Не записан"}</dd></div>
<div><dt>Композиция AI</dt><dd>{report.composition_sha256 ?? "Не запускалась"}</dd></div>
<div><dt>SHA-256 отчёта</dt><dd>{report.report_sha256}</dd></div>
<div><dt>SHA-256 архива</dt><dd>{report.manifest_sha256}</dd></div>
</dl>
</div>;
}
@@ -1,4 +1,3 @@
import type { ReactNode } from "react";
import { StatusBadge } from "@nodedc/ui-react"; import { StatusBadge } from "@nodedc/ui-react";
import { type AiRun } from "../../core/simulation/aiPolygon"; import { type AiRun } from "../../core/simulation/aiPolygon";
@@ -16,37 +15,42 @@ const REASONS: Record<string, string> = {
"goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон", "goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон",
waiting: "Ожидаем возможность движения", waiting: "Ожидаем возможность движения",
}; };
export function AiRunView({ run, connection }: { run: AiRun; connection: ReactNode }) { export function AiRunView({ run }: { run: AiRun }) {
const terminal = ["completed", "stopped", "failed"].includes(run.state); const terminal = ["completed", "stopped", "failed"].includes(run.state);
const telemetry = run.telemetry; const telemetry = run.telemetry;
const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0); const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0);
const preparingModels = run.state === "running" && run.phase === "models"; const preparingModels = run.state === "running" && run.phase === "models";
const reason = telemetry?.stop_reason === "unstable" ? "Остановка: опасный наклон" const missionStopped = ["stuck", "goal-reached", "unstable"].includes(telemetry?.decision?.reason ?? "");
const reason = missionStopped ? REASONS[telemetry!.decision!.reason] : telemetry?.stop_reason === "unstable" ? "Остановка: опасный наклон"
: telemetry?.stop_reason === "stale-camera" || telemetry?.stop_reason === "stale-command" : telemetry?.stop_reason === "stale-camera" || telemetry?.stop_reason === "stale-command"
? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error" ? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error"
? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01 ? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01
? "Ровер не движется" : REASONS[telemetry?.decision?.reason ?? ""]; ? "Ровер не движется" : REASONS[telemetry?.decision?.reason ?? ""];
const showTelemetry = telemetry && !terminal && !["stopping", "disconnected"].includes(run.state);
const live = showTelemetry && run.state === "running";
const metrics = [
["Скорость", showTelemetry ? `${Math.abs(telemetry.speed_mps).toFixed(2)} м/с` : "—"],
["Пройдено", (terminal?run.report?.distance_m:telemetry?.distance_m) != null ? `${(terminal?run.report!.distance_m:telemetry!.distance_m)!.toFixed(1)} м` : "—"],
["Время мира", showTelemetry ? `${(telemetry.simulation_time_ns / 1e9).toFixed(1)} с` : "—"],
["Симуляция", live ? `${telemetry.rtf.toFixed(2)}×` : "—"],
["Камера", live ? `${telemetry.sensor_fps.toFixed(1)} FPS` : "—"],
["AI", live ? `${telemetry.ai_hz.toFixed(1)} решений/с` : "—"],
["Inference", live && telemetry.inference_ms !== null ? `${telemetry.inference_ms.toFixed(0)} мс` : "—"],
["Возраст кадра", live && telemetry.frame_age_ms !== null ? `${telemetry.frame_age_ms.toFixed(0)} мс` : "—"],
];
return <section className="ai-polygon__run" aria-label="Управление симуляцией"> return <section className="ai-polygon__run" aria-label="Управление симуляцией">
<div className="ai-polygon__telemetry-row"> <dl className="ai-polygon__run-metrics">
<div className="ai-polygon__facts"> <div className="ai-polygon__run-metric ai-polygon__run-metric--status">
{run.state !== "ready" && run.state !== "running" || preparingModels || pending ? <StatusBadge tone={run.state === "failed" || run.state === "disconnected" ? "warning" : "neutral"}> <dt>Состояние</dt><dd>
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : STATES[run.state]} <StatusBadge tone={run.state === "failed" || run.state === "disconnected" || (run.state === "running" && telemetry?.decision?.reason === "stuck") ? "warning" : run.state === "running" && !preparingModels && !pending ? "success" : "neutral"}>
</StatusBadge> : null} {preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : run.state === "running" && reason ? reason : STATES[run.state]}
{telemetry && !terminal && run.state !== "stopping" && run.state !== "disconnected" ? <div className="ai-polygon__facts"> </StatusBadge>
{run.state === "running" && !preparingModels && reason ? <strong>{reason}</strong> : null} </dd>
<span>Скорость: {Math.abs(telemetry.speed_mps).toFixed(2)} м/с</span> </div>
<span>Время мира: {(telemetry.simulation_time_ns / 1e9).toFixed(1)} с</span> {metrics.map(([label, value]) => <div className="ai-polygon__run-metric" key={label}>
{run.state === "running" ? <> <dt>{label}</dt><dd>{value}</dd>
<span>Симуляция: {telemetry.rtf.toFixed(2)}×</span> </div>)}
<span>Камера: {telemetry.sensor_fps.toFixed(1)} FPS</span> </dl>
<span>AI: {telemetry.ai_hz.toFixed(1)} решений/с</span>
{telemetry.inference_ms !== null ? <span>Inference: {telemetry.inference_ms.toFixed(0)} мс</span> : null}
{telemetry.frame_age_ms !== null ? <span>Возраст кадра: {telemetry.frame_age_ms.toFixed(0)} мс</span> : null}
</> : null}
</div> : null}
</div>
{connection}
</div>
{run.state === "failed" && run.message ? <p>{run.message}</p> : null} {run.state === "failed" && run.message ? <p>{run.message}</p> : null}
</section>; </section>;
} }
@@ -0,0 +1,27 @@
import { useState, type ReactNode } from "react";
import { GlassSurface, Icon, Inspector } from "@nodedc/ui-react";
/** Layout belongs to the operator and location, not a particular live run. */
export function useSessionLayout(scope: string, initial: string[]) {
const key = `nodedc.simulation.layout.v1:${scope}`;
const [open, setOpen] = useState<string[]>(() => {
try {
const value: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
if (Array.isArray(value) && value.every(id => typeof id === "string")) return value;
} catch { /* Private browsing or older invalid preferences use the default. */ }
return initial;
});
return [open, (ids: string[]) => {
setOpen(ids);
try { localStorage.setItem(key, JSON.stringify(ids)); } catch { /* This session still works. */ }
}] as const;
}
export function AiSessionSection({ scope, title, children, initiallyOpen = true }: {
scope: string; title: string; children: ReactNode; initiallyOpen?: boolean;
}) {
const [open, setOpen] = useSessionLayout(scope, initiallyOpen ? ["body"] : []);
return <Inspector variant="panel" openSections={open} onOpenSectionsChange={setOpen}
sections={[{ id: "body", label: title, icon: <Icon name={scope.endsWith("results") ? "activity" : "settings"} />,
content: <GlassSurface padding="md" className="ai-polygon__section">{children}</GlassSurface> }]} />;
}
@@ -0,0 +1,11 @@
import { LaboratoryMetricEvidenceScene, type LaboratoryMetricPoint3 } from "../laboratory/LaboratoryMetricEvidenceScene";
const EMPTY: [] = [];
// View framing only; no fabricated rig or corridor is drawn on sensor evidence.
const FRAMING = { forwardLengthM: 8, rearMarginM: 0, halfWidthM: 0 };
const NO_RIG = { lengthM: 0, widthM: 0, nominalSensorHeightM: 0 };
export function AiSpatialPreview({ points, label }: { points: LaboratoryMetricPoint3[]; label:string }) {
return <LaboratoryMetricEvidenceScene pointCloudBodyXyzM={points} localSurfaceBodyXyzM={EMPTY}
obstacles={EMPTY} rig={NO_RIG} corridor={FRAMING} occupiedVoxelSizeM={0.1} mode="3d" label={label}
showCurrentIncrement showLocalSurface={false} showRollingMap={false} showReferenceGeometry={false} showRenderStats={false}/>;
}
@@ -0,0 +1,39 @@
import { useState } from "react";
import { Button, Icon, InspectorSelectField, Select, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { aiPlanName, updateAiPlan, type AiPlan } from "../../core/simulation/aiPolygon";
export function AiTaskSelect({plans,value,disabled,onChange,onUpdated,inspector=false}: {
inspector?:boolean;plans:AiPlan[];value:string;disabled:boolean;onChange:(id:string)=>void;onUpdated:(plan:AiPlan)=>void;
}) {
const TaskSelect = inspector ? InspectorSelectField : Select;
const [editing,setEditing]=useState<AiPlan|null>(null);
const [name,setName]=useState("");
const [busy,setBusy]=useState(false);
const [error,setError]=useState<string|null>(null);
const save=(removed=false)=>{
if(!editing||busy)return;
setBusy(true);
void updateAiPlan(editing.plan_id,removed?{removed:true}:{display_name:name.trim()})
.then(plan=>{onUpdated(plan);setEditing(null);})
.catch((caught:Error)=>setError(caught.message)).finally(()=>setBusy(false));
};
return <>
<div className="ai-polygon__plan-select"><TaskSelect label="Задание" value={value} disabled={disabled}
onChange={onChange} options={[
{value:"",label:"Новое задание"},
...plans.map(plan=>({value:plan.plan_id,label:aiPlanName(plan),
description:`${plan.points.length} точек · ${plan.length_m.toFixed(1)} м`,
action:{label:`Редактировать задание «${aiPlanName(plan)}»`,icon:<Icon name="edit"/>,
onAction:()=>{setName(aiPlanName(plan));setEditing(plan);setError(null);}},
})),
]}/></div>
<Window open={!!editing} title="Редактировать задание" size="sm" onClose={()=>{if(!busy)setEditing(null);}}
footer={<WindowFooterActions>
<Button icon={<Icon name="trash"/>} disabled={busy} onClick={()=>save(true)}>Удалить задание</Button>
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={()=>save()}>Сохранить имя</Button>
</WindowFooterActions>}>
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={e=>setName(e.target.value)}/>
</Window>
{error?<ToastStack items={[{id:"task-edit",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</>;
}
@@ -1,12 +1,11 @@
import { useState } from "react"; import { useState } from "react";
import { Button, TextField, TextAreaField, ToastStack } from "@nodedc/ui-react"; import { Button, TextField, ToastStack } from "@nodedc/ui-react";
import { configureAiWorld, type AiWorld, type AiWorldSettings } from "../../core/simulation/aiPolygon"; import { configureAiWorld, type AiWorld, type AiWorldSettings } from "../../core/simulation/aiPolygon";
export function AiWorldSetup({ world, disabled, onSaved }: { export function AiWorldSetup({ world, disabled, onSaved }: {
world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void; world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void;
}) { }) {
const [draft, setDraft] = useState<AiWorldSettings>(world.settings); const [draft, setDraft] = useState<AiWorldSettings>(world.settings);
const [route, setRoute] = useState((world.settings.route_xy ?? []).map((p) => p.join(" ")).join("\n"));
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const field = (label: string, value: number, change: (value: number) => void) => const field = (label: string, value: number, change: (value: number) => void) =>
@@ -26,16 +25,9 @@ export function AiWorldSetup({ world, disabled, onSaved }: {
{field("Направление, °", draft.heading_degrees, (v) => setDraft({ ...draft, heading_degrees: v }))} {field("Направление, °", draft.heading_degrees, (v) => setDraft({ ...draft, heading_degrees: v }))}
{field("Высота камеры, м", draft.camera_height_m, (v) => setDraft({ ...draft, camera_height_m: v }))} {field("Высота камеры, м", draft.camera_height_m, (v) => setDraft({ ...draft, camera_height_m: v }))}
{field("Скорость до, м/с", draft.max_speed_mps, (v) => setDraft({ ...draft, max_speed_mps: v }))} {field("Скорость до, м/с", draft.max_speed_mps, (v) => setDraft({ ...draft, max_speed_mps: v }))}
<TextAreaField label="Точки маршрута, X Y в метрах" rows={3} value={route}
hint="Каждая точка — с новой строки. Пустое поле: движение по видимой тропе."
disabled={disabled || busy} onChange={(e) => setRoute(e.target.value)} />
<Button disabled={disabled} loading={busy} onClick={() => { <Button disabled={disabled} loading={busy} onClick={() => {
const points = route.trim() ? route.trim().split(/\n+/).map((line) => line.trim().split(/\s+/).map(Number)) : [];
if (points.length > 32 || points.some((p) => p.length !== 2 || p.some((v) => !Number.isFinite(v)))) {
setError("Укажите не более 32 точек: два числа X Y в каждой строке."); return;
}
setBusy(true); setError(null); setBusy(true); setError(null);
void configureAiWorld(world, { ...draft, route_xy: points as [number, number][], prepared: true }).then(onSaved) void configureAiWorld(world, { ...draft, prepared: true }).then(onSaved)
.catch((caught: Error) => setError(caught.message)).finally(() => setBusy(false)); .catch((caught: Error) => setError(caught.message)).finally(() => setBusy(false));
}}>Сохранить старт и масштаб</Button> }}>Сохранить старт и масштаб</Button>
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Настройки не сохранены", description: error }]} onDismiss={() => setError(null)} /> : null} {error ? <ToastStack items={[{ id: "error", tone: "error", title: "Настройки не сохранены", description: error }]} onDismiss={() => setError(null)} /> : null}
@@ -1,88 +1,38 @@
import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { useCallback, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { Button, Icon, IconButton, LoadingRegion, SegmentedControl, StatusBadge } from "@nodedc/ui-react"; import { Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon"; import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon";
import { WorkerVideo, type WorkerVideoState } from "./WorkerVideo";
import { AiRouteOverlay } from "./AiRouteOverlay";
import { useInferencePreview } from "./AiInferencePreview";
import { SimulationObservationDeck } from "./SimulationObservationDeck";
import { useObserverInput } from "./useObserverInput";
import { useSimulationFullscreen } from "./useSimulationFullscreen"; import { useSimulationFullscreen } from "./useSimulationFullscreen";
// NVIDIA has process-global browser listeners. Serialize replacement/cleanup,
// including React StrictMode, without letting an old viewer terminate a new one.
let streamLifecycle: Promise<unknown> = Promise.resolve();
/** Decode the actual Worker stream. This component never loads a world or creates a 3D engine. */ /** Decode the actual Worker stream. This component never loads a world or creates a 3D engine. */
export function AiWorldStream({ world, run, onBack, onChange, controls, headerActions, actionsHost }: { export function AiWorldStream({ world, run, onBack, onChange, controls, headerActions, actionsHost }: {
world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode; world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode;
headerActions?: ReactNode; actionsHost?: HTMLElement | null; headerActions?: ReactNode; actionsHost?: HTMLElement | null;
}) { }) {
const frame = useRef<HTMLDivElement>(null); const frame = useRef<HTMLDivElement>(null), surface=useRef<HTMLDivElement>(null);
const video = useRef<HTMLVideoElement>(null);
const id = useId().replaceAll(":", "");
const { expanded, toggle } = useSimulationFullscreen(frame); const { expanded, toggle } = useSimulationFullscreen(frame);
const [state, setState] = useState<"connecting" | "live" | "failed" | "stalled">("connecting"); const [state, setState] = useState<WorkerVideoState>("connecting");
const [fps, setFps] = useState<number | null>(null); const [fps, setFps] = useState<number | null>(null);
const [revision, setRevision] = useState(0); const [revision, setRevision] = useState(0);
const [cameraError, setCameraError] = useState(false); const [cameraError, setCameraError] = useState(false);
const [routeVisible, setRouteVisible] = useState(true);
const endpoint = run?.worker?.stream; const endpoint = run?.worker?.stream;
const terminal = !run || ["completed", "stopped", "failed"].includes(run.state); const terminal = !run || ["completed", "stopped", "failed"].includes(run.state);
const connectable = !terminal && !!run?.telemetry?.stream_ready && !!endpoint; const connectable = !terminal && !!run?.telemetry?.stream_ready && !!endpoint;
const endpointKey = JSON.stringify(endpoint);
useEffect(() => {
if (!connectable || !endpoint || !video.current) return;
let disposed = false;
let stream: import("@nvidia/ov-web-rtc").AppStreamer | undefined;
let settle!: () => void;
const settled = new Promise<void>((resolve) => { settle = resolve; });
let callback = 0;
let lastFrame = performance.now();
let frames = 0;
let measuredAt = performance.now();
let connected = false;
setState("connecting"); setFps(null);
const element = video.current;
const received = () => {
if (disposed) return;
lastFrame = performance.now(); frames += 1; connected = true; setState("live");
callback = element.requestVideoFrameCallback(received);
};
callback = element.requestVideoFrameCallback(received);
const timer = setInterval(() => {
const now = performance.now();
setFps(frames * 1000 / (now - measuredAt));
frames = 0; measuredAt = now;
if (connected && now - lastFrame > 3000) setState("stalled");
}, 1000);
const setup = streamLifecycle.catch(() => undefined).then(async () => {
const sdk = await import("@nvidia/ov-web-rtc");
if (disposed) { settle(); return; }
stream = new sdk.AppStreamer();
await stream.connect({ streamSource: sdk.StreamType.DIRECT, logLevel: sdk.LogLevel.WARN,
streamConfig: { signalingServer: endpoint.server, signalingPort: endpoint.signaling_port,
signalingPath: "/", mediaServer: endpoint.server, mediaPort: endpoint.media_port,
width: endpoint.width, height: endpoint.height, fps: endpoint.fps,
videoElementId: `polygon-video-${id}`, audioElementId: `polygon-audio-${id}`,
autoLaunch: true, mic: false, enableAV1Support: false, fitStreamResolution: false,
maxReconnects: 1, reconnectDelay: 2000, connectivityTimeout: 5000,
onStart: (event) => {
if (event.status === sdk.EventStatus.SUCCESS || event.status === sdk.EventStatus.ERROR
|| event.status === sdk.EventStatus.CANCELED) settle();
if (!disposed && event.status === sdk.EventStatus.ERROR) setState("failed");
},
onStop: () => { settle(); if (!disposed) setState("stalled"); },
} });
if (stream.streamStatus !== sdk.StreamStatus.STARTING) settle();
}).catch(() => { settle(); if (!disposed) setState("failed"); });
streamLifecycle = setup;
return () => {
disposed = true; clearInterval(timer); element.cancelVideoFrameCallback(callback);
// connect() resolves with IN_PROGRESS; terminate() during STARTING does
// not dispose the SDK. Await its final callback before admitting a new owner.
streamLifecycle = setup.then(async () => {
await settled;
await stream?.terminate(false);
}).catch(() => undefined);
};
// A telemetry refresh must never reconnect or reload the stream.
}, [connectable, endpointKey, run?.run_id, id, revision]);
const mode = run?.camera ?? "follow"; const mode = run?.camera ?? "follow";
const cameraOptions: { value: AiCamera; label: string; disabled: boolean }[] = [
{ value: "follow", label: "От третьего лица", disabled: terminal },
{ value: "overview", label: "Свободный обзор", disabled: terminal },
{ value: "camera", label: "От первого лица", disabled: terminal },
];
const preview=useInferencePreview(run?.run_id,!terminal);
const inputError=useCallback(()=>setCameraError(true),[]);
useObserverInput(surface,run?.run_id,mode,connectable&&state==="live",inputError);
const changeCamera = (camera: AiCamera) => { const changeCamera = (camera: AiCamera) => {
if (!run) return; if (!run) return;
setCameraError(false); setCameraError(false);
@@ -99,35 +49,33 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
</div> : null} </div> : null}
{controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null} {controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null}
<div className="ai-polygon__viewer"> <div className="ai-polygon__viewer">
<div className="ai-polygon__viewer-toolbar"> <SimulationObservationDeck preview={preview}
<SegmentedControl<AiCamera> label="Вид симуляции" size="dense" value={mode} onChange={changeCamera} toolbar={<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}><Icon name={expanded ? "minimize" : "expand"} /></IconButton>}
items={[{ value: "follow", label: "За ровером", disabled: terminal }, videoActions={<Dropdown placement="bottom-end" width={280} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><IconButton ref={setTriggerRef} label="Настройки вида симуляции" aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}><Icon name="settings"/></IconButton>}>
{ value: "overview", label: "Обзор", disabled: terminal }, { value: "camera", label: "Камера AI", disabled: terminal }]} /> <div className="ai-polygon__layer-options">
<div className="ai-polygon__actions"> {run?.request?.purpose === "planning" ? <StatusBadge tone="neutral">Планирование маршрута</StatusBadge> : <Select<AiCamera> label="Вид симуляции" value={mode} onChange={changeCamera} options={cameraOptions} disabled={terminal} />}
{connectable ? <StatusBadge tone={state === "live" ? "success" : "warning"}> {run?.telemetry?.route_overlay && run.request?.purpose !== "planning" ? <Checker label="Показывать маршрут" checked={routeVisible} onChange={setRouteVisible}/> : null}
{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : "Ожидаем видео"} </div>
</StatusBadge> : null} </Dropdown>}
<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}> video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
<Icon name={expanded ? "minimize" : "expand"} /> <div className="ai-polygon__stream-picture">
</IconButton> {connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
</div>
</div>
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null} {cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
<div className="ai-polygon__viewport">
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")} <LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}> label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
<div className="ai-polygon__video" inert> <div className="ai-polygon__video" inert>
<video ref={video} id={`polygon-video-${id}`} autoPlay muted playsInline tabIndex={-1} {connectable&&endpoint&&state!=="failed"?<WorkerVideo key={`${run?.run_id}:${revision}`} endpoint={endpoint}
aria-label={`Видео симуляции ${world.name} с Worker`} /> onState={(status,value)=>{setState(status);setFps(value);}}/>:null}
<audio id={`polygon-audio-${id}`} muted />
</div> </div>
</LoadingRegion> </LoadingRegion>
{!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null}
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div> {terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div>
: connectable && (state === "failed" || state === "stalled") ? <div className="ai-polygon__preview-error" role="status"> : connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
<p>Видеопоток прерван. Состояние симуляции показано выше.</p> <p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
<Button onClick={() => setRevision((value) => value + 1)}>Подключить видео</Button> <Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
</div> : null} </div> : null}
</div> </div>
</div>}/>
</div> </div>
</div>; </div>;
} }
@@ -0,0 +1,183 @@
import type {SceneView} from "../../core/simulation/simulationLayout";
import { DEFAULT_PLANNER_PREFERENCES, panSensitivity } from "../../core/simulation/plannerPreferences";
import { zoomDisplacement } from "../../core/simulation/editorZoom";
import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/editorNavigation";
import { PerspectiveCamera, Vector3 } from "three";
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 {
camera:ProjectionCamera = new PerspectiveCamera(60, 1, .05, 3000);
private aspect=1;
get projection():EditorProjection {return isOrthographic(this.camera)?"orthographic":"perspective";}
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 navigationBlocks=new Set<NavigationOwner>();
private get enabled(){return this.navigationBlocks.size===0;}
private topPoints:number[][]|null=null;
private addMode=false;
semanticSelection=false;
private gesture: {id:number;x:number;y:number;nextX:number;nextY:number;anchor:Vector3;depth:number;distance:number;pan:boolean;pending:boolean}|null=null;
private lastAnchor: Vector3|null = null;
private forward = new Vector3();
private right = new Vector3();
private delta = new Vector3();
sceneCenter = new Vector3();
pick: ((x:number,y:number)=>number[]|null)|null = null;
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
surface.addEventListener("wheel",this.zoom,{passive:false});
surface.addEventListener("pointerdown",this.pointerDown);
surface.addEventListener("pointermove",this.pointerMove);
surface.addEventListener("pointerup",this.pointerEnd);
surface.addEventListener("pointercancel",this.pointerEnd);
surface.addEventListener("lostpointercapture",this.pointerEnd);
window.addEventListener("keydown",this.keyDown);
window.addEventListener("keyup",this.keyUp);
window.addEventListener("blur",this.clear);
canvas.addEventListener("blur",this.clear);
}
private anchor(x:number,y:number) {
const hit=this.pick?.(x,y);
if(hit)return new Vector3(...hit);
// Empty sky: retain useful depth, but keep the pivot on the clicked ray.
const depth=this.lastAnchor?navigationDepth(this.camera,this.lastAnchor):Math.max(2,this.camera.position.distanceTo(this.sceneCenter));
const forward=this.camera.getWorldDirection(new Vector3());
const ray=cameraRay(this.camera,x,y);
return ray.at((depth-ray.origin.clone().sub(this.camera.position).dot(forward))/Math.max(.01,ray.direction.dot(forward)),new Vector3());
}
private pointerDown=(e:PointerEvent)=>{
const editOrbit=this.semanticSelection&&e.ctrlKey&&[0,2].includes(e.button);
// Ctrl-drag may start on a semantic gizmo as well as the underlying canvas.
if(e.target!==this.canvas&&!(editOrbit&&(e.target as Element).closest("[data-semantic-axis],[data-semantic-handle]")))return;
this.canvas.focus({preventScroll:true});
if(!this.enabled || (e.target as Element).closest("[data-waypoint]") || ![0,1,2].includes(e.button))return;
if(e.button===0&&(this.semanticSelection&&!editOrbit||this.addMode&&!editOrbit))return;
if(editOrbit)e.preventDefault();
this.cancelGesture();
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const anchor=this.anchor(x,y);this.lastAnchor=anchor.clone();
const g=this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,nextX:e.clientX,nextY:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0&&!editOrbit,pending:!!this.pickSurface};
this.surface.setPointerCapture(e.pointerId);
if(this.pickSurface)void this.pickSurface(x,y).catch(()=>null).then(hit=>{
if(this.gesture!==g)return; // Released pointer, new gesture, resize or view change.
if(hit?.length===3&&hit.every(Number.isFinite)){g.anchor.set(...hit as [number,number,number]);this.lastAnchor=g.anchor.clone();}
g.depth=navigationDepth(this.camera,g.anchor);g.distance=this.camera.position.distanceTo(g.anchor);g.pending=false;
this.moveGesture(g.nextX,g.nextY);
});
};
private pointerMove=(e:PointerEvent)=>{
const g=this.gesture;if(!g||g.id!==e.pointerId||!this.enabled)return;
g.nextX=e.clientX;g.nextY=e.clientY;
if(!g.pending)this.moveGesture(e.clientX,e.clientY);
};
private moveGesture(x:number,y:number){
const g=this.gesture;if(!g)return;
const dx=x-g.x,dy=y-g.y;g.x=x;g.y=y;
if(!dx&&!dy)return;
this.topPoints=null;
if(g.pan){const before=this.camera.position.clone();panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);this.lastAnchor?.add(this.camera.position.clone().sub(before));}
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
}
private pointerEnd=(e:PointerEvent)=>{
if(this.gesture?.id!==e.pointerId)return;
this.cancelGesture();
};
private zoom=(e:WheelEvent)=>{
if(!this.enabled||e.target!==this.canvas)return;
this.cancelGesture();
this.topPoints=null;
e.preventDefault();this.canvas.focus({preventScroll:true});
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const anchor=this.anchor(x,y),ray=cameraRay(this.camera,x,y).direction;
const depth=this.camera.position.distanceTo(anchor);
if(this.semanticSelection&&!e.ctrlKey&&!e.metaKey) {
const before=this.camera.position.clone();panCamera(this.camera,navigationDepth(this.camera,anchor),e.deltaX,e.deltaY,this.canvas.clientHeight);
this.lastAnchor=anchor.add(this.camera.position.clone().sub(before));
this.camera.updateMatrixWorld();return;
}
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?rect.height:1);
if(isOrthographic(this.camera)) {
const factor=Math.exp(Math.max(-.8,Math.min(.8,delta*this.navigation.zoom*.002)));
const next=Math.max(.05,Math.min(5000,this.camera.top*factor)),ratio=next/this.camera.top;
const offset=anchor.clone().sub(this.camera.position);offset.addScaledVector(this.camera.getWorldDirection(new Vector3()),-navigationDepth(this.camera,anchor));
this.camera.position.addScaledVector(offset,1-ratio);
this.camera.top=next;this.camera.bottom=-next;this.camera.left=-next*this.aspect;this.camera.right=next*this.aspect;this.camera.updateProjectionMatrix();
} else this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));
this.lastAnchor=anchor;this.camera.updateMatrixWorld();
};
private keyDown=(e:KeyboardEvent)=>{
if(document.activeElement!==this.canvas || e.ctrlKey || e.metaKey || e.altKey || !KEYS.has(e.code))return;
e.preventDefault();this.keys.add(e.code);
};
private keyUp=(e:KeyboardEvent)=>{this.keys.delete(e.code);};
private cancelGesture(){const id=this.gesture?.id;this.gesture=null;if(id!==undefined&&this.surface.hasPointerCapture(id))this.surface.releasePointerCapture(id);}
private clear=()=>{this.keys.clear();this.cancelGesture();};
resize(width:number,height:number){this.cancelGesture();this.aspect=width/height;if(isOrthographic(this.camera)){this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;}else this.camera.aspect=this.aspect;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
setProjection(mode:EditorProjection){this.clear();this.camera=switchProjection(this.camera,mode,this.aspect,navigationDepth(this.camera,this.lastAnchor??this.sceneCenter));}
view(direction:number[]){
this.clear();this.topPoints=null;
const depth=navigationDepth(this.camera,this.lastAnchor??this.sceneCenter),target=this.camera.position.clone().addScaledVector(this.camera.getWorldDirection(new Vector3()),depth);
const d=new Vector3(...direction).normalize();this.camera.position.copy(target).addScaledVector(d,depth);
this.camera.up.set(0,1,0);if(Math.abs(d.y)>.999)this.camera.up.set(0,0,-Math.sign(d.y));
this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();this.lastAnchor=target;
}
home(point:number[]){
this.clear();this.lastAnchor=null;
this.topPoints=null;
const target=new Vector3(...point);
if(isOrthographic(this.camera)){this.camera.top=6.5;this.camera.bottom=-6.5;this.camera.left=-6.5*this.aspect;this.camera.right=6.5*this.aspect;this.camera.updateProjectionMatrix();}
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
}
top(points:number[][]){
if(!points.length)return;
this.clear();this.lastAnchor=null;
this.topPoints=points;
const low=[0,1,2].map(i=>Math.min(...points.map(p=>p[i])));
const high=[0,1,2].map(i=>Math.max(...points.map(p=>p[i])));
const target=new Vector3(...low.map((v,i)=>(v+high[i])/2));
const span=Math.max((high[0]-low[0])/this.aspect,high[2]-low[2],10);
const distance=span/(2*Math.tan(Math.PI/6))*1.15+high[1]-low[1];
if(isOrthographic(this.camera)){this.camera.top=span*.575;this.camera.bottom=-this.camera.top;this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;this.camera.updateProjectionMatrix();}
this.lastAnchor=target;this.camera.position.copy(target).add(new Vector3(0,distance,0));
this.camera.up.set(0,0,-1);this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();
}
snapshot(){return {position:this.camera.position.toArray(),quaternion:this.camera.quaternion.toArray(),anchor:this.lastAnchor?.toArray()??null,projection:this.projection,span:isOrthographic(this.camera)?this.camera.top:null};}
restore(view:SceneView){
this.clear();this.topPoints=null;this.setProjection(view.projection);
this.camera.position.fromArray(view.position);this.camera.quaternion.fromArray(view.quaternion);
this.lastAnchor=view.anchor?new Vector3(...view.anchor):null;
if(isOrthographic(this.camera)&&view.span!==null){this.camera.top=view.span;this.camera.bottom=-view.span;this.camera.left=-view.span*this.aspect;this.camera.right=view.span*this.aspect;}
this.camera.updateProjectionMatrix();this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.cancelGesture();this.addMode=add;}
invalidateSurface(){this.cancelGesture();this.lastAnchor=null;}
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();
this.topPoints=null;
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
this.delta.copy(this.forward).multiplyScalar(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown"))
.addScaledVector(this.right,pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft"));
this.delta.y+=pressed("KeyE")-pressed("KeyQ");
this.delta.normalize().multiplyScalar(Math.min(.1,Math.max(0,dt))*(pressed("ShiftLeft","ShiftRight")?16:4));
this.camera.position.add(this.delta);this.camera.updateMatrixWorld();
}
dispose(){
this.clear();this.surface.removeEventListener("wheel",this.zoom);
this.surface.removeEventListener("pointerdown",this.pointerDown);this.surface.removeEventListener("pointermove",this.pointerMove);
this.surface.removeEventListener("pointerup",this.pointerEnd);this.surface.removeEventListener("pointercancel",this.pointerEnd);
this.surface.removeEventListener("lostpointercapture",this.pointerEnd);
window.removeEventListener("keydown",this.keyDown);window.removeEventListener("keyup",this.keyUp);
window.removeEventListener("blur",this.clear);this.canvas.removeEventListener("blur",this.clear);
}
}
@@ -0,0 +1,78 @@
import {
Application, BLEND_NONE, BLEND_NORMAL, CULLFACE_NONE, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance,
SEMANTIC_POSITION, ShaderMaterial,
} from "playcanvas";
import type { SimulationViewMode } from "./PlayCanvasRuntime";
export interface CollisionRenderData {
positions: Float32Array;
indices: Uint16Array | Uint32Array;
}
/** Displays the exact calibrated picking mesh; visibility never changes its geometry or BVH. */
export class EditorCollisionLayer {
private entity: Entity;
private material: ShaderMaterial;
private layer = new Layer({ name: "Planning collision surface", clearDepthBuffer: true });
constructor(private app: Application, private camera: Entity, geometry: CollisionRenderData[]) {
// Unified splats occupy the world pass; the mesh overlay must follow that pass.
app.scene.layers.insert(this.layer, app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1);
camera.camera!.layers = [...camera.camera!.layers, this.layer.id];
this.entity = new Entity("Planning collision layer", app);
this.material = new ShaderMaterial({
uniqueName: "planning-collision-surface",
attributes: { vertex_position: SEMANTIC_POSITION },
vertexGLSL: `
attribute vec3 vertex_position;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
varying vec3 surfacePosition;
void main(void) {
vec4 world = matrix_model * vec4(vertex_position, 1.0);
surfacePosition = world.xyz;
gl_Position = matrix_viewProjection * world;
}`,
fragmentGLSL: `
varying vec3 surfacePosition;
uniform float surfaceClip;
uniform float surfaceFloor;
uniform float surfaceOpacity;
void main(void) {
if (surfacePosition.y > surfaceClip || surfacePosition.y < surfaceFloor) discard;
vec3 normal = normalize(cross(dFdx(surfacePosition), dFdy(surfacePosition)));
float shade = 0.42 + 0.58 * abs(dot(normal, normalize(vec3(0.3, 1.0, 0.4))));
gl_FragColor = vec4(vec3(0.2, 0.95, 0.42) * shade, surfaceOpacity);
}`,
});
this.material.cull = CULLFACE_NONE;
const instances = geometry.map(({ positions, indices }) => {
const mesh = new Mesh(app.graphicsDevice);
mesh.setPositions(positions);
mesh.setIndices(indices);
mesh.update();
return new MeshInstance(mesh, this.material, this.entity);
});
this.entity.addComponent("render", { meshInstances: instances, layers: [this.layer.id], castShadows: false, receiveShadows: false });
app.root.addChild(this.entity);
this.setClip(Infinity);
this.setMode("visual");
}
setMode(mode: SimulationViewMode) {
this.entity.enabled = mode !== "visual";
const combined = mode === "combined";
this.material.setParameter("surfaceOpacity", combined ? 0.34 : 1);
this.material.blendType = combined ? BLEND_NORMAL : BLEND_NONE;
this.material.depthWrite = true;
this.material.update();
}
setClip(height: number, floor = -Infinity) {
this.material.setParameter("surfaceFloor", Number.isFinite(floor) ? floor : -1e9);
this.material.setParameter("surfaceClip", Number.isFinite(height) ? height : 1e9);
}
dispose() {
this.camera.camera!.layers = this.camera.camera!.layers.filter(id => id !== this.layer.id);
this.app.scene.layers.remove(this.layer);
this.entity.destroy();
this.material.destroy();
}
}
@@ -0,0 +1,38 @@
import { Application, Entity, LAYERID_WORLD, Picker } from "playcanvas";
/** Visual navigation only. Gaussian depth never becomes a route/collision surface. */
export class EditorSurfacePicker {
private picker: Picker | null = null;
private tail: Promise<void> = Promise.resolve();
private request = 0;
private disposed = false;
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {}
pick(x: number, y: number): Promise<number[] | null> {
const request = ++this.request;
// Keep one GPU readback in flight; superseded clicks never resize its buffer.
const result = this.tail.then(async () => {
if (this.disposed || request !== this.request || x < 0 || x >= 1 || y < 0 || y >= 1) return null;
const world = this.app.scene.layers.getLayerById(LAYERID_WORLD);
if (!world) return null;
const width = Math.max(1, Math.round(this.canvas.clientWidth));
const height = Math.max(1, Math.round(this.canvas.clientHeight));
this.picker ??= new Picker(this.app, width, height, true);
this.picker.resize(width, height);
// Exclude infrastructure, route markers and gizmos from the depth measurement.
this.picker.prepare(this.camera.camera!, this.app.scene, [world]);
const point = await this.picker.getWorldPointAsync(x * width, y * height);
if (this.disposed || request !== this.request || !point) return null;
const xyz = [point.x, point.y, point.z];
return xyz.every(Number.isFinite) ? xyz : null;
});
this.tail = result.then(() => undefined, () => undefined);
return result;
}
invalidate() { this.request++; }
dispose() {
this.disposed = true; this.invalidate();
this.picker?.destroy(); this.picker = null;
}
}
@@ -0,0 +1,74 @@
import type { CollisionRenderData } from "./EditorCollisionLayer";
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Mesh, Matrix4, Ray, Vector3 } from "three";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { MeshBVH } from "three-mesh-bvh";
import { GenerateMeshBVHWorker } from "three-mesh-bvh/worker";
/** CPU picking only: no Three renderer, physical stepping, or AI in the editor. */
export class EditorTerrain {
private draco = new DRACOLoader().setDecoderPath({
js: "/vendor/playcanvas/draco/1.5.7/draco_wasm_wrapper_gltf.js",
wasm: "/vendor/playcanvas/draco/1.5.7/draco_decoder_gltf.wasm",
}).setWorkerLimit(1);
private builder: GenerateMeshBVHWorker | null = new GenerateMeshBVHWorker();
private trees: MeshBVH[] = [];
private geometries: BufferGeometry[] = [];
private disposed = false;
bounds = new Box3();
async load(url: string, signal: AbortSignal, transform?: number[]) {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error("Не удалось открыть поверхность локации.");
const gltf = await new GLTFLoader().setDRACOLoader(this.draco).parseAsync(await response.arrayBuffer(), "");
if (this.disposed || signal.aborted) {
gltf.scene.traverse((object) => { if (object instanceof Mesh) object.geometry.dispose(); });
throw new DOMException("Aborted", "AbortError");
}
if (transform) gltf.scene.applyMatrix4(new Matrix4().fromArray(transform));
gltf.scene.updateMatrixWorld(true);
gltf.scene.traverse((object) => {
if (!(object instanceof Mesh)) return;
const input = object.geometry;
const geometry = new BufferGeometry();
const position = input.getAttribute("position");
const xyz = new Float32Array(position.count * 3);
const p = new Vector3();
for (let i = 0; i < position.count; i++) {
p.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
xyz[i*3] = p.x; xyz[i*3+1] = p.y; xyz[i*3+2] = p.z;
}
geometry.setAttribute("position", new BufferAttribute(xyz, 3));
geometry.setIndex(input.index!.clone());
geometry.computeBoundingBox(); this.bounds.union(geometry.boundingBox!);
this.geometries.push(geometry); input.dispose();
});
for (const geometry of this.geometries) {
if (this.disposed || signal.aborted) throw new DOMException("Aborted", "AbortError");
this.trees.push(await this.builder!.generate(geometry, { maxLeafTris: 10 }));
}
this.builder?.dispose(); this.builder = null;
}
renderData(): CollisionRenderData[] {
return this.geometries.map((geometry) => ({
positions: geometry.getAttribute("position").array as Float32Array,
indices: geometry.index!.array as Uint16Array | Uint32Array,
}));
}
pick(origin: number[], direction: number[], clip = Infinity, floor = -Infinity) {
return this.pickSurface(origin,direction,clip,true,floor);
}
/** Camera navigation may select walls; waypoint admission remains ground-only. */
pickSurface(origin: number[], direction: number[], clip = Infinity, groundOnly = false, floor = -Infinity) {
const ray = new Ray(new Vector3(...origin), new Vector3(...direction).normalize());
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && (!groundOnly || Math.abs(hit.face?.normal.y ?? 0) > .35))
.sort((a, b) => a.distance - b.distance)[0]?.point ?? null;
}
ground(x: number, z: number, near: number, clip = Infinity, floor = -Infinity) {
const ray = new Ray(new Vector3(x, this.bounds.max.y + 1, z), new Vector3(0, -1, 0));
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && Math.abs(hit.face?.normal.y ?? 0) > .35)
.sort((a, b) => Math.abs(a.point.y - near) - Math.abs(b.point.y - near))[0]?.point ?? null;
}
dispose() { this.disposed = true; this.draco.dispose(); this.builder?.dispose(); this.builder = null; this.geometries.forEach((g) => g.dispose()); this.trees = []; }
}
@@ -0,0 +1,58 @@
import { Application, BLEND_NORMAL, CULLFACE_NONE, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, PRIMITIVE_TRIANGLES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import { URBAN_COLORS, urbanPaths, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
import { urbanSurface } from "../../core/simulation/urbanSurface";
/** Read-only observed surfaces and physical contours; never routing or collision input. */
export class EditorUrbanMapLayer {
private entity: Entity;
private meshes: Mesh[] = [];
private groups = new Map<string,Entity>();
private materials: ShaderMaterial[];
private surfaceLayer = new Layer({ name: "Urban pedestrian coverage" });
private layer = new Layer({ name: "Urban infrastructure observations" });
constructor(private app: Application, private camera: Entity, document: UrbanMap) {
const at=app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1;
app.scene.layers.insert(this.surfaceLayer,at);app.scene.layers.insert(this.layer,at+2);
camera.camera!.layers = [...camera.camera!.layers, this.surfaceLayer.id, this.layer.id];
this.materials=[false,true].map(surface=>{
const material=new ShaderMaterial({ uniqueName: surface?"urban-ground-coverage":"urban-map-contours", attributes: { vertex_position: SEMANTIC_POSITION, vertex_color: SEMANTIC_COLOR },
vertexGLSL: `attribute vec3 vertex_position; attribute vec4 vertex_color;
uniform mat4 matrix_model; uniform mat4 matrix_viewProjection;
varying vec4 mapColor; varying float mapHeight;
void main(void) { vec4 p=matrix_model*vec4(vertex_position,1.0); mapColor=vertex_color; mapHeight=p.y; gl_Position=matrix_viewProjection*p; }`,
fragmentGLSL: `precision highp float; varying vec4 mapColor; varying float mapHeight; uniform float mapClip; uniform float mapFloor;
void main(void) { if(mapHeight>mapClip || mapHeight<mapFloor) discard; gl_FragColor=mapColor; }` });
material.depthTest=false;material.depthWrite=false;
if(surface){material.blendType=BLEND_NORMAL;material.cull=CULLFACE_NONE;}
return material;
});
this.entity = new Entity("Urban infrastructure",app);
const groups = new Map<string, {positions:number[];colors:number[];surface:boolean}>();
for (const feature of document.features) {
const color = URBAN_COLORS[feature.properties.class]; if (!color) continue;
const surface=urbanSurface(feature),key=feature.properties.class+(surface?":surface":":line");
if (!groups.has(key)) groups.set(key,{positions:[],colors:[],surface:!!surface});
const group=groups.get(key)!;
if(surface){
for(const i of surface.indices){group.positions.push(...toEditor(surface.positions.slice(i*3,i*3+3)));group.colors.push(...color,48);}
}else for (const ring of urbanPaths(feature)) for (let i=1;i<ring.length;i++) {
group.positions.push(...toEditor(ring[i-1]), ...toEditor(ring[i]));
group.colors.push(...color,255,...color,255);
}
}
for (const [key,{positions,colors,surface}] of groups) {
if (!positions.length) continue;
const mesh=new Mesh(app.graphicsDevice);mesh.setPositions(positions);mesh.setColors32(colors);mesh.update(surface?PRIMITIVE_TRIANGLES:PRIMITIVE_LINES);this.meshes.push(mesh);
const entity=new Entity(key,app);entity.addComponent("render",{meshInstances:[new MeshInstance(mesh,this.materials[surface?1:0])],layers:[surface?this.surfaceLayer.id:this.layer.id],castShadows:false,receiveShadows:false});
this.entity.addChild(entity);this.groups.set(key,entity);
}
this.entity.enabled=false; app.root.addChild(this.entity); this.setClip(Infinity);
}
setClasses(selected:readonly UrbanClassId[]) {
for (const [key,entity] of this.groups) entity.enabled=selected.includes(key.split(":")[0] as UrbanClassId);
}
setVisible(visible: boolean) { this.entity.enabled=visible; }
setClip(height: number, floor = -Infinity) { for(const material of this.materials) { material.setParameter("mapClip",Number.isFinite(height)?height:1e9); material.setParameter("mapFloor",Number.isFinite(floor)?floor:-1e9); } }
dispose() { this.camera.camera!.layers=this.camera.camera!.layers.filter(id=>id!==this.layer.id&&id!==this.surfaceLayer.id);this.app.scene.layers.remove(this.layer);this.app.scene.layers.remove(this.surfaceLayer);this.entity.destroy();for(const mesh of this.meshes)mesh.destroy();for(const material of this.materials)material.destroy(); }
}
@@ -0,0 +1,23 @@
import { useState } from "react";
import { Icon, IconButton, LayerStackIndicator, ProgressButton, ToastStack } from "@nodedc/ui-react";
import type { UrbanMap } from "../../core/simulation/urbanMap";
import { analysisProgressLabel, useInfrastructureAnalysis } from "../../core/simulation/infrastructureAnalysis";
export function InfrastructureAnalysis({worldId,worldSha,busy,hasMap,onMap}:{worldId:string;worldSha:string;busy:boolean;hasMap:boolean;onMap:(map:UrbanMap)=>void}) {
const {job,error,clearError,sending,checking,start,cancel}=useInfrastructureAnalysis(worldId,worldSha,onMap);
const [dismissedFailure,setDismissedFailure]=useState<string|null>(null);
const pending=job?.status==="queued"||job?.status==="running";
const phase=sending?(pending?"Отменяем расчёт":"Запускаем расчёт"):checking?"Проверяем состояние":pending?analysisProgressLabel(job):null;
const recalculate=hasMap||job?.status==="ready";
return <>
{!phase&&!busy?<IconButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} title={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} onClick={()=>void start(recalculate)}><Icon name="layers"/></IconButton>:null}
{phase?<ProgressButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"}
icon={phase?<LayerStackIndicator/>:<Icon name="layers"/>} disabled={busy}
title={pending?"Прогноз уточняется по выполненным этапам. Ожидание Worker и подготовка исходного проекта считаются отдельно.":undefined}
progress={phase?{label:phase,value:pending&&!job.progress?.stale?job.progress?.fraction??undefined:undefined}:undefined}
onClick={()=>void start(recalculate)}/>:null}
{pending&&!job.cancel_requested?<IconButton label="Отменить расчёт инфраструктуры" loading={sending}
onClick={()=>void cancel()}><Icon name="stop"/></IconButton>:null}
{error?<ToastStack items={[{id:"infrastructure",tone:"error",title:"Не удалось выполнить расчёт",description:error}]} onDismiss={clearError}/>:null}
{job?.status==="failed"&&job.error&&dismissedFailure!==job.key?<ToastStack items={[{id:job.key,tone:"error",title:"Расчёт не завершён",description:job.error}]} onDismiss={()=>setDismissedFailure(job.key)}/>:null}
</>;
}
@@ -0,0 +1,55 @@
import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon";
import type { RoverSettings } from "../../core/simulation/roverSettings";
import { toEditor } from "../../core/simulation/aiEditor";
import { PlayCanvasRuntime } from "./PlayCanvasRuntime";
import { localScene } from "./localScene";
import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export function LocalManualScene({world,robot,settings,actionsHost,headerActions}: {
world:AiWorld; robot:AiRobot; settings?:RoverSettings; actionsHost:HTMLElement|null; headerActions:React.ReactNode;
}) {
const [preferences]=usePlannerPreferences();
const host=useRef<HTMLDivElement>(null), canvas=useRef<HTMLCanvasElement>(null);
const viewport=useRef<HTMLDivElement>(null);
const runtime=useRef<PlayCanvasRuntime|null>(null);
const [retry,setRetry]=useState(0), [ready,setReady]=useState(false), [speed,setSpeed]=useState(0);
const {cache,error,setError}=useLocalScene(world,retry);
const {expanded,toggle}=useSimulationFullscreen(host);
useEffect(()=>{
if(cache?.status!=="ready"||!canvas.current)return;
let active=true;
const view=new PlayCanvasRuntime(); runtime.current=view; setReady(false);
void (async()=>{
await view.mount(canvas.current!); if(!active)return;
view.setQuality(preferences.quality);
await view.loadWorld(localScene(cache)); if(!active)return;
const configured = settings ? {...robot,physics:{...robot.physics,mass_kg:settings.base_mass_kg+settings.payload_mass_kg}} : robot;
await view.setRobot(configured,toEditor([...world.settings.spawn_xy,world.settings.ground_z]),90+world.settings.heading_degrees,settings?.max_speed_mps);
if(!active)return;
await view.setControlMode("ugv"); if(active)setReady(true);
})().catch((e:Error)=>{if(active)setError(e.message);});
const timer=setInterval(()=>{if(active)setSpeed(view.speed);},250);
return ()=>{active=false;clearInterval(timer);view.dispose();runtime.current=null;};
},[cache?.key,cache?.status,robot.sha256,retry]);
useEffect(()=>{runtime.current?.setQuality(preferences.quality);},[preferences.quality,ready]);
return <div className="ai-polygon__stage" ref={host}>
{expanded?<div className="ai-polygon__actions">{headerActions}</div>:actionsHost?createPortal(headerActions,actionsHost):null}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready?"success":"neutral"}>{ready?"Ручное управление · локально":"Подготовка сцены"}</StatusBadge></div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport}/>
<canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} />
{ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null}
{!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null}
{error?<div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
</div>
</div>
</div>;
}
@@ -0,0 +1,22 @@
import {usePlannerPreferences} from "./usePlannerPreferences";
import {useEffect,useState} from "react";
import {Button,Dropdown,Icon,IconButton,NavigationCube} from "@nodedc/ui-react";
import {createPortal} from "react-dom";
import {useSimulationLayout} from "./useSimulationLayout";
import type {AiEditorRuntime} from "./AiEditorRuntime";
export function PlannerCameraTools({runtime,viewport,disabled}:{runtime:AiEditorRuntime;viewport:HTMLElement;semantic:boolean;disabled:boolean}) {
const [preferences]=usePlannerPreferences();
const [layout,updateLayout]=useSimulationLayout();
const projection=layout.projection;
const [quaternion,setQuaternion]=useState<[number,number,number,number]>([0,0,0,1]);
useEffect(()=>{viewport.style.setProperty("--planner-cube-size",`${preferences.cube.size}px`);return()=>{viewport.style.removeProperty("--planner-cube-size");};},[viewport,preferences.cube.size]);
useEffect(()=>{runtime.watchCamera(setQuaternion);return()=>runtime.watchCamera(null);},[runtime]);
useEffect(()=>{runtime.setProjection(projection);},[runtime,projection]);
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>)}<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)}
</>;
}
@@ -0,0 +1,10 @@
import {ColorField,ControlRow,RangeControl} from "@nodedc/ui-react";
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
export function PlannerCubeSettings({value,set}:{value:PlannerPreferences["cube"];set:(key:string,value:string|number)=>void}) {
return <>
<RangeControl label="Размер 3D-куба" min={48} max={160} step={1} value={value.size} onChange={v=>set("size",v)} formatValue={v=>`${v} px`}/>
<RangeControl label="Непрозрачность куба" min={.2} max={1} step={.05} value={value.opacity} onChange={v=>set("opacity",v)} formatValue={v=>`${Math.round(v*100)}%`}/>
<RangeControl label="Прозрачность линий" min={0} max={1} step={.05} value={1-value.edgeOpacity} onChange={v=>set("edgeOpacity",1-v)} formatValue={v=>`${Math.round(v*100)}%`}/>
{([["face","Грани"],["text","Подписи"],["edge","Рёбра"],["hover","Подсветка"],["hoverText","Подписи при наведении"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
</>;
}
@@ -0,0 +1,54 @@
import {useSimulationLayout} from "./useSimulationLayout";
import { useEffect, useState } from "react";
import { 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";
import type { AiEditorRuntime } from "./AiEditorRuntime";
import { URBAN_COLORS } from "../../core/simulation/urbanMap";
export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilityChange}: {
worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;onVisibilityChange:(visible:boolean)=>void;
}) {
const [memory,setMemory]=useState<SpatialExperience|null>(null);
const [layout,updateLayout]=useSimulationLayout();
const visible=layout.memory,setVisible=(memory:boolean)=>updateLayout({memory});
const [projected,setProjected]=useState<ScreenPoint[]>([]),[error,setError]=useState<string|null>(null);
useEffect(()=>{
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const refresh=async()=>{
try {const value=await loadExperience(worldId,worldSha,abort.signal);
if(abort.signal.aborted)return;setMemory(value);setError(null);
if(value)runtime.setExperience(experienceMap(value),value.attempts.map(a=>a.xyz),setProjected);
} catch(e) {if(!abort.signal.aborted)setError((e as Error).message);}
if(!abort.signal.aborted)timer=setTimeout(refresh,5000);
};
void refresh();return ()=>{abort.abort();clearTimeout(timer);runtime.clearExperience();};
},[worldId,worldSha,runtime]);
useEffect(()=>{runtime.showExperience(visible);onVisibilityChange(visible&&!!memory);},[runtime,visible,memory,onVisibilityChange]);
useEffect(()=>()=>onVisibilityChange(false),[onVisibilityChange]);
return <>
<Dropdown placement="bottom-start" width={340} surfaceRole="dialog"
trigger={({open,toggle,setTriggerRef,surfaceId})=><SegmentedButton ref={setTriggerRef} aria-label="Память локации" active={visible||open}
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>
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>}
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p>
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p>
</div>
</Dropdown>
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
</g>;
})}
</svg>,viewport):null}
</>;
}
@@ -0,0 +1,21 @@
import { GlassSurface, SegmentedControl } from "@nodedc/ui-react";
import { URBAN_COLORS, URBAN_LABELS, availableUrbanClasses, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
export function PlannerLegend({map,memory,selected,onChange,disabled=false}: {
map:UrbanMap|null;memory:boolean;selected:readonly UrbanClassId[];
onChange:(selected:UrbanClassId[])=>void;disabled?:boolean;
}) {
const classes=map?availableUrbanClasses(map):[];
if(!classes.length&&!memory)return null;
const swatch=(id:string)=><i className="ai-local-editor__legend-swatch" aria-hidden="true"
style={{background:`rgb(${URBAN_COLORS[id].join(",")})`}}/>;
return <div className="ai-local-editor__legend nodedc-scene-controls" inert={disabled}>
{classes.length?<SegmentedControl label="Слои инфраструктуры" selectionMode="multiple"
className="ai-local-editor__legend-controls" value={selected} onChange={onChange}
items={classes.map(id=>({value:id,label:URBAN_LABELS[id],icon:swatch(id)}))}/>:null}
{memory?<GlassSurface padding="sm" materialRim={false} aria-label="Легенда памяти">
<span className="ai-inference-preview__legend">{[["visited","Проехал"],["attempt","Попытка проезда"],["revisited","Позже проехал"]].map(([id,label])=>
<span key={id}>{swatch(id)}{label}</span>)}</span>
</GlassSurface>:null}
</div>;
}
@@ -0,0 +1,102 @@
import { Application, BLEND_NORMAL, Color, Entity, Layer, PROJECTION_ORTHOGRAPHIC, StandardMaterial, Vec3 } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import type { AiWaypoint } from "../../core/simulation/aiPolygon";
import { axisWorldLength, DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
/** Operator-only geometry: never exported into the Worker scene or inference camera. */
export class PlannerMarkers {
private centroid:Entity|null=null;
private layer = new Layer({name:"Planner annotations", clearDepthBuffer:true});
private root = new Entity("Route annotations");
private materials: StandardMaterial[] = [];
private beams: { entity: Entity; material: StandardMaterial; index: number }[] = [];
private pivot = new Entity("Waypoint pivot");
private arrows: {shaft: Entity; cone: Entity; axis: "x"|"y"|"z"}[] = [];
private points: AiWaypoint[] = [];
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private elapsed = 0;
axisLength = 1;
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {
app.scene.layers.push(this.layer);
camera.camera!.layers=[...camera.camera!.layers,this.layer.id];
app.root.addChild(this.root); this.root.addChild(this.pivot);
const light = new Entity("Annotation light");
light.addComponent("light", {type:"directional",color:new Color(1,1,1),intensity:1,layers:[this.layer.id]});
light.setEulerAngles(35,25,0);this.root.addChild(light);
app.scene.ambientLight = new Color(.45,.45,.45);
}
private material(color: string, opacity: number) {
const m = new StandardMaterial(); m.diffuse.fromString(color);m.emissive.copy(m.diffuse).mulScalar(.12);
m.opacity=opacity;m.blendType=BLEND_NORMAL;m.depthWrite=false;m.update();this.materials.push(m);return m;
}
private shape(name: string, type: "cylinder"|"cone"|"sphere", material: StandardMaterial, parent: Entity) {
const entity=new Entity(name);entity.addComponent("render",{type,material,layers:[this.layer.id],castShadows:false,receiveShadows:false});parent.addChild(entity);return entity;
}
set(points: AiWaypoint[], selected: string|null, preferences: PlannerPreferences) {
if(this.centroid && this.selected===selected && this.preferences===preferences && points.length===this.points.length && points.every((v,i)=>v.id===this.points[i].id)) {
this.points=points;
this.beams.forEach(({entity},i)=>{const [x,y,z]=toEditor(points[i].position);entity.setPosition(x,y+preferences.waypoint.height/2,z);});
return;
}
this.points=points;this.selected=selected;this.preferences=preferences;
this.centroid?.destroy();this.centroid=null;
this.beams.forEach(({entity})=>entity.destroy());this.beams=[];
this.arrows.forEach(({shaft,cone})=>{shaft.destroy();cone.destroy();});this.arrows=[];
this.materials.forEach(m=>m.destroy());this.materials=[];
const w=preferences.waypoint,p=preferences.pivot,n=preferences.navigation;
this.centroid=this.shape("Rotation centre","sphere",this.material(n.centroidColor,n.centroidOpacity),this.root);
this.centroid.enabled=false;
for(const [index,point] of points.entries()) {
const [x,y,z]=toEditor(point.position),material=this.material(w.color,w.opacity);
material.emissive.fromString(w.emissionColor);material.emissiveIntensity=w.emission;material.update();
const entity=this.shape(point.id,"cylinder",material,this.root);
entity.setPosition(x,y+w.height/2,z);entity.setLocalScale(w.diameter,w.height,w.diameter);
this.beams.push({entity,material,index});
}
this.pivot.enabled=!!points.find(point=>point.id===selected);
if(this.pivot.enabled) for(const axis of ["x","y","z"] as const) {
const material=this.material(p[axis],p.opacity);
// Gizmo remains visible when its origin is inside the selected beam.
material.depthTest=false;material.update();
this.arrows.push({axis,shaft:this.shape(`${axis} shaft`,"cylinder",material,this.pivot),cone:this.shape(`${axis} cone`,"cone",material,this.pivot)});
}
}
setRotationCenter(point:{x:number;y:number;z:number}|null) {
if(!this.centroid)return false;
const changed=this.centroid.enabled!==!!point;
this.centroid.enabled=!!point;
if(point)this.centroid.setPosition(point.x,point.y,point.z);
return changed;
}
private pixelLength(depth:number,pixels:number) {
return this.camera.camera!.projection===PROJECTION_ORTHOGRAPHIC?2*this.camera.camera!.orthoHeight*pixels/Math.max(1,this.canvas.clientHeight):axisWorldLength(depth,this.canvas.clientHeight,pixels);
}
update(dt: number) {
this.elapsed+=dt;
if(this.centroid?.enabled) {
const depth=this.centroid.getPosition().clone().sub(this.camera.getPosition()).dot(this.camera.forward);
const size=this.pixelLength(depth,this.preferences.navigation.centroidPixels);
this.centroid.setLocalScale(size,size,size);
}
const w=this.preferences.waypoint,p=this.preferences.pivot;
const motion=window.matchMedia("(prefers-reduced-motion: reduce)").matches?0:w.frequency;
this.beams.forEach(({material,index})=>{material.opacity=w.opacity*(motion? .8+.2*Math.cos(this.elapsed*motion*Math.PI*2-index*.3):1);material.update();});
const point=this.points.find(v=>v.id===this.selected);
if(point) {
const position=new Vec3(...toEditor(point.position));this.pivot.setPosition(position);
const depth=position.clone().sub(this.camera.getPosition()).dot(this.camera.forward);
this.pivot.enabled=depth>0;
this.axisLength=this.pixelLength(depth,p.pixels);
const unit=this.axisLength/p.pixels,tip=p.cone*unit,stem=this.axisLength-tip;
for(const {axis,shaft,cone} of this.arrows) {
const v=axis==="x"?new Vec3(1,0,0):axis==="y"?new Vec3(0,1,0):new Vec3(0,0,1);
shaft.setLocalPosition(v.clone().mulScalar(stem/2));cone.setLocalPosition(v.clone().mulScalar(stem+tip/2));
for(const shape of [shaft,cone])shape.setLocalEulerAngles(axis==="z"?90:0,0,axis==="x"?-90:0);
shaft.setLocalScale(p.diameter*unit,stem,p.diameter*unit);cone.setLocalScale(tip*.7,tip,tip*.7);
}
}
return this.beams.length>0 && motion>0;
}
dispose() {this.app.scene.layers.remove(this.layer);this.root.destroy();this.materials.forEach(m=>m.destroy());}
}
@@ -0,0 +1,98 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
import {PlannerCubeSettings} from "./PlannerCubeSettings";
import {PlannerToolbarSettings} from "./PlannerToolbarSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<HTMLDivElement|null>; onClose: () => void }) {
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation"|"toolbar"|"cube">("pivot");
const [saved,update] = usePlannerPreferences();
const [value,setValue] = useState(saved);
const [rect,setRect] = useState(()=>{
const bounds=boundsRef.current?.getBoundingClientRect();
const y=(boundsRef.current?.querySelector(".ai-simulation__view-tools")?.getBoundingClientRect().height??48)+24;
return {x:96,y,width:400,height:Math.max(230,Math.min(490,(bounds?.height??600)-y-12))};
});
const [maximized,setMaximized] = useState(false);
const editing = useRef(false), pending = useRef<PlannerPreferences|null>(null);
const [error,setError] = useState<string|null>(null);
const commit = () => {
editing.current=false;
const next=pending.current; pending.current=null;
if(!next)return;
try { update(next);setError(null); }
catch { setError("Не удалось сохранить настройки в этом браузере."); }
};
const commitRef=useRef(commit);commitRef.current=commit;
useEffect(()=>{if(!editing.current)setValue(saved);},[saved]);
useEffect(()=>{
const release=()=>commitRef.current();
const escape=(e:KeyboardEvent)=>{
if(e.key!=="Escape" || e.defaultPrevented || document.querySelector(".nodedc-dropdown-surface"))return;
e.preventDefault();release();onClose();
};
window.addEventListener("pointerup",release);window.addEventListener("pointercancel",release);
window.addEventListener("keyup",release);window.addEventListener("blur",release);
window.addEventListener("keydown",escape);
return ()=>{
window.removeEventListener("pointerup",release);window.removeEventListener("pointercancel",release);
window.removeEventListener("keyup",release);window.removeEventListener("blur",release);
window.removeEventListener("keydown",escape);
};
},[onClose]);
const set = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, next: string|number|boolean) => {
const base=pending.current??value;
const changed={...base,[group]:{...base[group],[key]:next}};
pending.current=changed;setValue(changed);
if(!editing.current)commit();
};
const range = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, label: string, min: number, max: number, step: number, unit: string) =>
<RangeControl key={key} label={label} min={min} max={max} step={step}
value={Number(value[group][key as keyof typeof value[typeof group]])} onChange={(v)=>set(group,key,v)}
formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
return <WorkspaceWindow boundsRef={boundsRef} rect={rect} onRectChange={setRect}
resizeIndicator={false}
maximized={maximized} onMaximizedChange={setMaximized} minWidth={320} minHeight={230}
zIndex={100} title="Настройки планировщика" closeLabel="Закрыть настройки планировщика"
onClose={()=>{commit();onClose();}}>
<div className="ai-polygon__form" onPointerDownCapture={(e)=>{
if((e.target as Element).closest('input[type="range"], [role="slider"]'))editing.current=true;
}} onKeyDownCapture={(e)=>{
if((e.target as Element).matches('input[type="range"], [role="slider"]') && ["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(e.key))editing.current=true;
}}>
<Select label="Раздел настроек планировщика" value={section} onChange={setSection}
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"},{value:"toolbar",label:"Тулбар"},{value:"cube",label:"3D-куб"}]}/>
{section === "cube" ? <PlannerCubeSettings value={value.cube} set={(key,v)=>set("cube",key,v)}/> : section === "toolbar" ? <PlannerToolbarSettings value={value.toolbar} set={(key,v)=>set("toolbar",key,v)}/> : section === "pivot" ? <>
{range("pivot","pixels","Размер осей",50,220,5,"px")}
{range("pivot","diameter","Диаметр стержня",2,16,1,"px")}
{range("pivot","cone","Размер конусов",10,40,1,"px")}
{range("pivot","opacity","Непрозрачность",.15,1,.05,"")}
{(["x","y","z"] as const).map((axis)=><ControlRow key={axis} label={`Цвет ${axis.toUpperCase()}`}><ColorField label={`Цвет ${axis.toUpperCase()}`} value={value.pivot[axis]} onChange={(v)=>set("pivot",axis,v)}/></ControlRow>)}
</> : section === "waypoint" ? <>
{range("waypoint","diameter","Диаметр",.05,3,.05,"м")}
{range("waypoint","height","Высота",.2,50,.1,"м")}
<ControlRow label="Цвет waypoint"><ColorField label="Цвет waypoint" value={value.waypoint.color} onChange={(v)=>set("waypoint","color",v)}/></ControlRow>
{range("waypoint","opacity","Непрозрачность",.1,1,.05,"")}
{range("waypoint","frequency","Пульсация",0,3,.1,"Гц")}
<strong>Свечение</strong>
{range("waypoint","emission","Сила эмиссии",0,5,.1,"")}
<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow>
</> : <>
<strong>Сдвиг камеры</strong>
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p>
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")}
{range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")}
{range("navigation","farPan","Чувствительность вдали",.1,5,.1,"×")}
<strong>Зум</strong>
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
<strong>Центр вращения</strong>
<p>Шарик появляется в точке нажатия на время вращения.</p>
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
</>}
{error?<ToastStack items={[{id:"preferences",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</div>
</WorkspaceWindow>;
}
@@ -0,0 +1,16 @@
import {Checker,ColorField,ControlRow,RangeControl,Select} from "@nodedc/ui-react";
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
type Settings=PlannerPreferences["toolbar"];
export function PlannerToolbarSettings({value,set}:{value:Settings;set:(key:string,value:string|number|boolean)=>void}) {
const range=(key:keyof Settings,label:string,min:number,max:number,step:number,unit:string)=><RangeControl label={label} value={Number(value[key])} min={min} max={max} step={step} onChange={v=>set(key,v)} formatValue={v=>`${unit==="с"?v/1000:v} ${unit}`}/>;
return <>
<Select label="Положение тулбара" value={value.placement} options={[{value:"left",label:"Слева"},{value:"right",label:"Справа"},{value:"top",label:"Сверху"},{value:"bottom",label:"Снизу"}]} onChange={v=>set("placement",v)}/>
{range("minSize","Минимальный размер",18,42,1,"px")}
{range("maxSize","Максимальный размер",value.minSize,88,1,"px")}
{range("lensCount","Линза",1,13,2,"иконок")}
{range("gap","Расстояние между кнопками",0,24,1,"px")}
<Checker label="Автоскрытие" checked={value.autoHide} onChange={v=>set("autoHide",v)}/>
{value.autoHide?range("hideDelay","Задержка скрытия",0,15000,250,"с"):null}
{([["background","Фон"],["border","Рамка"],["outline","Подсветка"],["accent","Цвет инструментов"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
</>;
}
@@ -1,3 +1,4 @@
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import { import {
Application, Application,
Asset, Asset,
@@ -18,6 +19,7 @@ import {
type ModelComponent, type ModelComponent,
type ScriptType, type ScriptType,
} from "playcanvas"; } from "playcanvas";
import type { AiRobot } from "../../core/simulation/aiPolygon";
import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs"; import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs";
import { import {
@@ -76,24 +78,10 @@ const HOME_POSITION = new Vec3(0, 1, 0);
const HOME_FOCUS = new Vec3(1, 1, 0); const HOME_FOCUS = new Vec3(1, 1, 0);
const DRACO_DECODER_ROOT = "/vendor/playcanvas/draco/1.5.7"; const DRACO_DECODER_ROOT = "/vendor/playcanvas/draco/1.5.7";
const QUALITY_PROFILES: Record<SimulationQuality, {
lodBaseDistance: number;
lodMultiplier: number;
lodRangeMin: number;
lodRangeMax: number;
pixelRatio: number;
splatBudget: number;
targetFps: number;
}> = {
low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 350_000, targetFps: 30 },
medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 700_000, targetFps: 45 },
high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 1_200_000, targetFps: 60 },
ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 2_500_000, targetFps: 60 },
maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60 },
};
export class PlayCanvasRuntime implements SimulationRuntime { export class PlayCanvasRuntime implements SimulationRuntime {
private app: Application | null = null; private app: Application | null = null;
private robotAsset: Asset | null = null;
private canvas: HTMLCanvasElement | null = null; private canvas: HTMLCanvasElement | null = null;
private camera: Entity | null = null; private camera: Entity | null = null;
private cameraController: CameraController | null = null; private cameraController: CameraController | null = null;
@@ -155,7 +143,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
antialias: true, antialias: true,
alpha: false, alpha: false,
preserveDrawingBuffer: false, preserveDrawingBuffer: false,
powerPreference: "high-performance", powerPreference: "default",
}, },
}); });
this.app = app; this.app = app;
@@ -306,6 +294,27 @@ export class PlayCanvasRuntime implements SimulationRuntime {
} }
} }
async setRobot(robot: AiRobot, ground: number[], headingDegrees: number, maxSpeedMps = .5): Promise<void> {
const app = this.requiredApp();
const publicRoot = "apps/control-station/public/";
if (!robot.visual.source.startsWith(publicRoot)) throw new Error("Модель ровера недоступна.");
const asset = new Asset(robot.name,"container",{ url: "/"+robot.visual.source.slice(publicRoot.length) });
this.robotAsset = asset; app.assets.add(asset);
await new Promise<void>((resolve,reject) => {
asset.ready(()=>resolve()); asset.once("error",()=>reject(new Error("Модель ровера не загрузилась.")));
app.assets.load(asset);
});
if (this.disposed) { asset.unload(); return; }
const resource = asset.resource as ContainerResource;
this.setUgvPreset({ presetName: robot.name, massKg: robot.physics.mass_kg,
dimensionsMeters: { length:robot.physics.length_m, width:robot.physics.width_m,
height:robot.physics.height_m, groundClearance: .15 },
maxSpeedMetersPerSecond: maxSpeedMps, maxTurnRateDegrees: 45, invertSteering: false });
this.ugvController!.setRobot(()=>resource.instantiateRenderEntity(),new Vec3(...ground),headingDegrees,robot.visual.motion);
}
get speed(): number { return this.ugvController?.speed ?? 0; }
setQuality(quality: SimulationQuality): void { setQuality(quality: SimulationQuality): void {
this.quality = quality; this.quality = quality;
this.applyQuality(); this.applyQuality();
@@ -380,6 +389,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
this.unloadWorld(); this.unloadWorld();
this.ugvController?.dispose(); this.ugvController?.dispose();
this.ugvController = null; this.ugvController = null;
this.robotAsset?.unload(); this.robotAsset = null;
if (this.app) { if (this.app) {
this.app.autoRender = false; this.app.autoRender = false;
this.app.renderNextFrame = false; this.app.renderNextFrame = false;
@@ -0,0 +1,33 @@
import { useState } from "react";
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import type { AiRobot } from "../../core/simulation/aiPolygon";
import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings";
export function RoverSettingsWindow({robot,value,manual,onApply,onClose}:{
robot:AiRobot; value:RoverSettings; manual:boolean;
onApply:(value:RoverSettings)=>void; onClose:()=>void;
}) {
const [draft,setDraft] = useState(value);
const field = (key:Exclude<keyof RoverSettings,"schema_version">, label:string, min:number, max:number|undefined, step:number) =>
<TextField label={label} type="number" min={min} max={max} step={step}
value={Number.isFinite(draft[key])?draft[key]:""}
onChange={e=>setDraft({...draft,[key]:e.target.value===""?NaN:Number(e.target.value)})}/>;
const valid=validRoverSettings(draft,robot);
return <Window open title={`Настройки ровера · ${robot.name}`} onClose={onClose}
footer={<WindowFooterActions>
<Button onClick={()=>setDraft(current=>({...defaultRoverSettings(robot,value.max_speed_mps),max_speed_mps:current.max_speed_mps}))}>Сбросить массу и нагрузку</Button>
<Button variant="primary" disabled={!valid} onClick={()=>onApply(draft)}>Применить</Button>
</WindowFooterActions>}>
<div className="ai-polygon__form ai-polygon__report">
{field("max_speed_mps","Скорость до, м/с",.05,undefined,.01)}
{field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)}
{field("payload_mass_kg","Дополнительный груз, кг",0,500,1)}
{field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)}
<p>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</p>
<p>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</p>
{manual?<p>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</p>:null}
<p>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</p>
{!valid?<p role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</p>:null}
</div>
</Window>;
}
@@ -0,0 +1,36 @@
import { Entity } from "playcanvas";
import { beltPose, type RoverMotion } from "../../core/simulation/roverMotion";
export class RoverTrackMotion {
private distance = { L:0, R:0 };
private links: { node:Entity; side:"L"|"R"; index:number }[] = [];
private wheels: { node:Entity; side:"L"|"R"; radius:number; angle:number }[] = [];
constructor(root: Entity, private motion: RoverMotion) {
const requireNode = (name: string) => {
const node = root.findByName(name) as Entity | null;
if (!node) throw new Error(`В модели отсутствует узел анимации ${name}`);
return node;
};
for (const side of ["L","R"] as const) {
for (let index=0;index<motion.link_count;index++) {
this.links.push({node:requireNode(`${side}_BELT_${String(index).padStart(2,"0")}`),side,index});
}
}
this.wheels = motion.wheels.map(w => ({node:requireNode(w.node),side:w.node[0] as "L"|"R",radius:w.radius_m,angle:0}));
}
update(dt: number, forwardSpeed: number, yawRate: number) {
// Local controller uses +Z forward, +Y up: positive yaw turns right.
const speed={L:forwardSpeed+yawRate*this.motion.track_width_m/2,R:forwardSpeed-yawRate*this.motion.track_width_m/2};
const step=Math.min(.1,Math.max(0,dt));
for (const side of ["L","R"] as const) this.distance[side]=(this.distance[side]+speed[side]*step)%this.motion.length_m;
for (const w of this.wheels) {
w.angle=(w.angle-speed[w.side]*step/w.radius)%(2*Math.PI);
w.node.setLocalEulerAngles(0,0,w.angle*180/Math.PI);
}
for (const link of this.links) {
const pose=beltPose(this.motion,this.distance[link.side],link.side,link.index);
link.node.setLocalPosition(pose.position[0],pose.position[1],pose.position[2]);
link.node.setLocalEulerAngles(0,0,pose.angle*180/Math.PI);
}
}
}
@@ -0,0 +1,58 @@
import {useEffect,useState} from "react";
import {createPortal} from "react-dom";
import {semanticPaths,semanticMembers,isRigidMarking} from "../../core/simulation/semanticEdits";
import {curveControlScale,curveControlPoint} from "../../core/simulation/semanticCurveControls";
import {editablePaths,knots} from "../../core/simulation/semanticVector";
import {URBAN_COLORS} from "../../core/simulation/urbanMap";
import {useSemanticGestures} from "./useSemanticGestures";
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
export type {SemanticChoice} from "./semanticEditorTypes";
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(()=>{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(" ");};
const selectedIds=new Set([...(selected?[selected.feature_id]:[]),...props.selection.map(v=>v.feature_id)]);
const chosen=[...new Set([...selectedIds].flatMap(id=>semanticMembers(map,id)))],highlight=hover?semanticMembers(map,hover):[];
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=>(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="Редактор контуров">
{original?.features.filter(f=>f.properties.review_status!=="rejected").flatMap(f=>semanticPaths(f).map((r,i)=><path key={`${f.id}-${i}`} d={line(r)} fill="none" stroke={`rgb(${URBAN_COLORS[f.properties.class]?.join(",")??"255,255,255"})`} strokeWidth={1.5} strokeDasharray="5 5" opacity={.65}/>))}
{visible.map(f=><g key={f.id} data-semantic-feature={f.id}>
{semanticPaths(f).map((r,i)=><g key={i}>
{chosen.includes(f)||highlight.includes(f)?<><path d={line(r)} fill="none" stroke="var(--nodedc-glass-panel-bg)" strokeWidth={6}/><path d={line(r)} fill="none" stroke={highlight.includes(f)?"var(--nodedc-text-primary)":featureColor(f.properties.class)} strokeWidth={3}/></>:null}
</g>)}
{props.editing&&!isRigidMarking(f)&&chosen.includes(f)?editablePaths(f).flatMap((r,i)=>r.slice(0,r.length-Number(f.geometry.type==="Polygon")).map((v,k)=>{const p=project(v);const active=props.selection.some(s=>!s.object&&s.feature_id===f.id&&s.path===i&&s.index===k);return p?<circle key={`${i}-${k}`} data-semantic-vertex={`${f.id}:${i}:${k}`} cx={p[0]} cy={p[1]} r={active?5:3} fill={active?"var(--nodedc-text-primary)":featureColor(f.properties.class)} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={1.5}/>:null;})):null}
</g>)}
{ghostMap?.features.map(f=><path key={f.id} d={semanticPaths(f).map(line).join(" ")} fill={color} fillRule="evenodd" fillOpacity={.4} stroke={color} strokeWidth={2}/>)}
{brush.length?<><path d={line(brush)} fill="none" stroke={color} strokeWidth={2}/>{brush.map((v,i)=>{const p=project(v);return p?<circle key={i} cx={p[0]} cy={p[1]} r={i?3:6} fill={color}/>:null;})}</>:null}
{marquee?<rect x={Math.min(marquee[0],marquee[2])} y={Math.min(marquee[1],marquee[3])} width={Math.abs(marquee[2]-marquee[0])} height={Math.abs(marquee[3]-marquee[1])} fill="var(--nodedc-text-primary)" fillOpacity={.1} stroke="var(--nodedc-text-primary)" strokeDasharray="4 3"/>:null}
{props.editing&&!props.blocked&&base&&g?<g aria-label="Пивот перемещения">
{(["x","y","z"] as const).map(axis=>{const end=g[axis];if(!end)return null;const p=[end[0]*rect.width,end[1]*rect.height],d=Math.hypot(p[0]-base[0],p[1]-base[1]);if(d<12)return null;
const ux=(p[0]-base[0])/d,uy=(p[1]-base[1])/d;
return <g key={axis} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
<title>{`Переместить по ${axis.toUpperCase()}`}</title>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke="transparent" strokeWidth={18}/>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke={g.colors[axis]} strokeWidth={3}/>
<path d={`M${p[0]},${p[1]} L${p[0]-ux*12-uy*5},${p[1]-uy*12+ux*5} L${p[0]-ux*12+uy*5},${p[1]-uy*12-ux*5} Z`} fill={g.colors[axis]}/>
<text x={p[0]+7} y={p[1]-7} fill={g.colors[axis]} fontSize={12}>{axis.toUpperCase()}</text>
</g>;
})}
<rect data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>{`Переместить: ${props.axis.toUpperCase()}`}</title></rect>
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}><title>Повернуть элемент в плоскости</title></circle>:null}
</g>:null}
{props.editing&&node&&props.selection.length===1?(["incoming","outgoing"] as const).map(key=>{
const a=project(node.point),b=project(curveControlPoint(node,key,handleScale));
if(!a||!b||!node[key].some(Boolean))return null;
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>Ручка кривой</title></circle></g>;
}):null}
</svg>,viewport);
}
@@ -0,0 +1,134 @@
import {useSimulationLayout} from "./useSimulationLayout";
import {useSemanticDocument} from "./useSemanticDocument";
import {useEffect,useRef,useState} from "react";
import {createPortal} from "react-dom";
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,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";
import type {SemanticTool} from "./semanticEditorTypes";
import {duplicateIndex,type SemanticAxis} from "../../core/simulation/semanticVector";
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 [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);};
const axis=layout.axis,setAxis=(axis:SemanticAxis)=>updateLayout({axis});
const areaMode=layout.areaMode,setAreaMode=(areaMode:typeof layout.areaMode)=>updateLayout({areaMode});
const layers=layout.layers,setLayers=(layers:UrbanClassId[])=>updateLayout({layers});
const selected=selection[0]??null;
const setSelected=(v:Vertex|null)=>selectVertices(v?[v]:[]);
const [choices,setChoices]=useState<SemanticChoice[]>([]);
const [tool,setTool]=useState<SemanticTool>("select");
const [template,setTemplate]=useState<string|null>(null);
const [preview,setPreview]=useState<SemanticOperation|null>(null);
const current=useRef({draft,revision});current.current={draft,revision};
useEffect(()=>{
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||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});
if(op.kind==="insert")setSelected({...op,index:op.index+1});
}
catch(e){setError((e as Error).message);}
};
const removeSelected=()=>{
if(!selected||!draft)return;
const f=draft.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
operate(isRigidMarking(f)||selected.object?{kind:"remove",feature_id:f.id}:{kind:"delete_vertices",vertices:selection});setSelected(null);
};
const display=draft?.map??source;
let overlay=display;
if(preview)try{overlay=semanticOperation(display,preview);}catch{/* Retain the last valid preview. */}
useEffect(()=>{
if(!active)return;
const hidden=editing&&selected&&preview?.kind!=="duplicate_marking"?semanticMembers(display,selected.feature_id):[];
const rendered=hidden.length?{...display,features:display.features.filter(f=>!hidden.includes(f))}:display;
runtime.setUrbanMap(rendered);runtime.setUrbanClasses(layers);runtime.showUrbanMap(visible.user);
},[runtime,active,display,editing,selected?.feature_id,visible.user,preview?.kind,layers]);
useEffect(()=>{
if(!active)return;
runtime.setAddMode(false);
const keyboard=(e:KeyboardEvent)=>{
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);
}else if(!e.ctrlKey&&!e.metaKey&&["KeyV","KeyA","KeyP","KeyR"].includes(e.code)) {
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id)),area=layers.some(id=>["pedestrian_area","sidewalk"].includes(id));
if((e.code==="KeyA"&&!contours&&!selection.some(v=>{const f=display.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);}))||(["KeyP","KeyR"].includes(e.code)&&!area))return;
e.preventDefault();e.stopImmediatePropagation();setTemplate(null);setTool(e.code==="KeyV"?"select":e.code==="KeyA"?"insert":e.code==="KeyP"?"pen":"rectangle");
}else if((e.key==="Delete"||e.key==="Backspace")&&selected){
e.preventDefault();e.stopImmediatePropagation();removeSelected();
}
};
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]);
if(!active)return null;
const classes=availableUrbanClasses(display);
if(!classes.includes("road_marking"))classes.push("road_marking");
const overlaySelection=preview?.kind==="duplicate_marking"&&overlay!==display?[{feature_id:preview.new_feature_id,path:0,index:0,object:true as const}]:preview?.kind==="duplicate_vertex"&&overlay!==display?[{feature_id:preview.feature_id,path:preview.path,index:duplicateIndex(preview.index,display.features.find(f=>f.id===preview.feature_id)!.geometry.type==="Polygon",preview.side)}]:selection;
const marking=layers.some(id=>["road_marking","crosswalk_marking"].includes(id));
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id));
const chooseTool=(next:SemanticTool)=>{setTool(next);setTemplate(null);setPreview(null);};
const undo=()=>{setDraft(s=>s?undoSemantic(s):s);setSelected(null);};
const redo=()=>{setDraft(s=>s?redoSemantic(s):s);setSelected(null);};
const controls=<>
{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}
{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} 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&&(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)}/>
</>;
}
@@ -0,0 +1,47 @@
import {Button,Checker,Toolbar,type ToolbarItem} from "@nodedc/ui-react";
import {createPortal} from "react-dom";
import {MARKING_TEMPLATES,isEditableMarking,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import type {UrbanMap} from "../../core/simulation/urbanMap";
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};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);});
const menu=(children:React.ReactNode)=><div className="semantic-tools__menu">{children}</div>;
if(p.editing){
items.push({id:"select",label:"Выделение",shortcut:"V",icon:"select",active:p.tool==="select"&&!p.template,onSelect:()=>p.setTool("select")});
if(p.contours||editableMarking)items.push({id:"insert",label:"Добавить точку на контур",shortcut:"A",icon:"add-point",active:p.tool==="insert",onSelect:()=>p.setTool("insert")});
if(p.area){
items.push({id:"pen",label:"Перо: замкните контур или Enter",shortcut:"P",icon:"pen",active:p.tool==="pen",onSelect:()=>p.setTool("pen")},
{id:"rectangle",label:"Прямоугольник: два противоположных угла",shortcut:"R",icon:"rectangle",active:p.tool==="rectangle",onSelect:()=>p.setTool("rectangle")},
{id:"area-mode",label:"Действие области",icon:p.areaMode==="union"?"plus":"trash",onSelect:()=>{},menu:close=>menu(([['union','Заполнить область'],['difference','Вырезать область']] as const).map(([id,label])=><Button key={id} width="full" variant={p.areaMode===id?"primary":"secondary"} tone="neutral" aria-pressed={p.areaMode===id} onClick={()=>{p.setAreaMode(id);close();}}>{label}</Button>))});
}
items.push({id:"axes",label:`Оси перемещения: ${p.axis.toUpperCase()}`,icon:"target",onSelect:()=>{},menu:close=>menu((["x","y","z","xy","xz","yz"] as const).map(axis=><Button key={axis} width="full" variant={p.axis===axis?"primary":"secondary"} tone="neutral" aria-pressed={p.axis===axis} onClick={()=>{p.setAxis(axis);close();}}>{axis.toUpperCase()}</Button>))});
if(p.selection.length===1&&!p.selection[0].object){
const v=p.selection[0],f=p.map.features.find(f=>f.id===v.feature_id),nodes=f?knots(f,v.path):[],n=nodes[v.index];
const curved=!!n&&[...n.incoming,...n.outgoing].some(Boolean);
if(n)items.push({id:"properties",label:"Свойства точки",icon:"curve",onSelect:()=>{},menu:close=>menu(<>
<Button width="full" variant={!curved?"primary":"secondary"} tone="neutral" aria-pressed={!curved} onClick={()=>{p.operate({...v,kind:"curve",incoming:[0,0],outgoing:[0,0]});close();}}>Угловая точка</Button>
<Button width="full" variant={curved?"primary":"secondary"} tone="neutral" aria-pressed={curved} onClick={()=>{
const closed=f!.geometry.type==="Polygon",prev=nodes[v.index-1]??(closed?nodes.at(-1)!:n),next=nodes[v.index+1]??(closed?nodes[0]:n);
const tangent=next.point.slice(0,2).map((a,k)=>a-prev.point[k]),length=Math.hypot(...tangent)||1;
const before=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-prev.point[k]))/3,after=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-next.point[k]))/3;
p.operate({...v,kind:"curve",incoming:tangent.map(x=>-x/length*before),outgoing:tangent.map(x=>x/length*after)});close();
}}>Кривая с ручками</Button>
</>)});
}
if(p.selection.length)items.push({id:"delete",label:"Удалить выделенное",shortcut:"Delete",icon:"trash",onSelect:p.remove});
if(p.canUndo)items.push({id:"undo",label:"Отменить",shortcut:"Control+Z Meta+Z",icon:"undo",onSelect:p.undo});
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.user} onChange={user=>p.setVisible({...p.visible,user})}/>
{p.compareAvailable?<Checker label="Сравнить с исходной алгоритмической" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>:null}
</>)}, {id:"quality",label:"Качество Gaussian-сцены",icon:"sliders",onSelect:()=>{},menu:close=>menu(([["low","Низкое"],["medium","Среднее"],["high","Высокое"],["ultra","Ультра"],["maximum","Максимум"]] as const).map(([quality,label])=><Button key={quality} width="full" variant={prefs.quality===quality?"primary":"secondary"} tone="neutral" aria-pressed={prefs.quality===quality} onClick={()=>{try{update({...prefs,quality});close();}catch{p.onError("Не удалось сохранить качество.");}}}>{label}</Button>))});
if(p.editing&&p.marking)items.push({id:"marking",label:"Добавить элемент разметки",icon:"plus",active:!!p.template,onSelect:()=>{},menu:close=>menu(MARKING_TEMPLATES.templates.filter(t=>!(t as {hidden?:boolean}).hidden).map(t=><Button key={t.id} width="full" onClick={()=>{p.setTemplate(t.id);close();}}>{t.label}</Button>))});
return createPortal(<Toolbar container={p.viewport} {...prefs.toolbar} label="Инструменты семантики" items={items}/>,p.viewport);
}
@@ -0,0 +1,56 @@
import {useEffect,useRef,useState,type ReactNode} from 'react';
import {createPortal} from 'react-dom';
import {Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout';
import {useObservationPresets} from '../../core/fleet/useObservationPresets';
import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets';
import {ObservationLayoutSaveWindow} from '../observation/ObservationLayoutSaveWindow';
import {ObservationDeck} from '../observation/ObservationDeck';
import {ObservationPanelHeader} from '../observation/ObservationPanelHeader';
import {AiInferencePreview,type InferencePreview} from './AiInferencePreview';
import '../observation/observation.css';
const storageKey='missioncore.simulation.observation.v1';
export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{video:ReactNode;videoActions:ReactNode;toolbar:ReactNode;preview:null|InferencePreview}){
const presets=useObservationPresets('missioncore.simulation.observation-presets.v1',storageKey);
const {layout,setLayout}=presets;
const [saving,setSaving]=useState(false);
const [editing,setEditing]=useState<string|null>(null);
const edited=presets.presets.find(p=>p.id===editing);
const [full,setFull]=useState<string|null>(null);
const mounts=useRef(new Map<string,HTMLElement>());
const sources=[{id:'video',label:'Симуляция'},...(preview?.layers??[])];
for(const source of sources)if(!mounts.current.has(source.id)){const element=document.createElement('div');element.className='observation-panel-mount';mounts.current.set(source.id,element);}
const ids=orderedObservationIDs(layout,sources.map(source=>source.id));
const visible=ids.filter(id=>!layout.hidden.includes(id)&&(id==='video'||layout.catalogVisible?.includes(id)));
const effectiveFull=full&&visible.includes(full)?full:null;
const show=(id:string,checked:boolean)=>setLayout(value=>({...value,catalogVisible:checked?[...new Set([...(value.catalogVisible??[]),id])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:checked?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key==='Escape'&&effectiveFull&&!document.querySelector('[role=dialog],[role=listbox]')){setFull(null);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull]);
return <div className="ai-polygon__observation">
<div className="ai-polygon__observation-toolbar nodedc-viewport-controls">
{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}
<Dropdown placement="bottom-end" width={340} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><Button ref={setTriggerRef} icon={<Icon name="layers"/>} aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Камеры и слои</Button>}>
{({close})=><div className="ai-polygon__layer-options" role="group" aria-label="Камеры и слои">
<Select label="Расположение окон" value={presets.selected} options={[...observationArrangements,...presets.presets.map(p=>({value:p.id,label:p.name,action:{label:`Редактировать раскладку «${p.name}»`,icon:<Icon name="edit"/>,onAction:()=>{close();presets.clearError();setEditing(p.id);}}}))]} onChange={value=>{presets.select(value);setFull(null);}}/>
{ids.map(id=>{const source=sources.find(item=>item.id===id)!;return <Checker key={id} label={source.label} checked={visible.includes(id)} onChange={checked=>show(id,checked)}/>;})}
<Button onClick={()=>{const known=[...new Set([...ids,...(layout.catalogVisible??[])])].filter(id=>!layout.hidden.includes(id)&&(id==='video'||layout.catalogVisible?.includes(id)));const tree=observationTree(layout,known);if(tree)setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)));close();setSaving(true);}}>Сохранить расположение</Button>
</div>}
</Dropdown>
{toolbar}
</div>
<div className="observation-deck">{visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.id,source.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
{sources.filter(source=>visible.includes(source.id)).map(source=>createPortal(
<div className="observation-panel"><GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
<ObservationPanelHeader><DockHandle id={source.id} label={source.label}/><div className="observation-panel__title"><h3 title={source.label}>{source.label}</h3></div><div className="observation-actions">
{source.id==='video'&&videoActions}
<IconButton label={`${effectiveFull===source.id?'Восстановить':'Развернуть'} · ${source.label}`} onClick={()=>setFull(value=>value===source.id?null:source.id)}><Icon name={effectiveFull===source.id?'minimize':'expand'}/></IconButton>
<IconButton label={`Скрыть · ${source.label}`} onClick={()=>show(source.id,false)}><Icon name="close"/></IconButton>
</div></ObservationPanelHeader>
<div className="observation-mount">{source.id==='video'?video:preview&&<AiInferencePreview preview={preview} layer={source.id}/>}</div>
</GlassSurface></div>,mounts.current.get(source.id)!,source.id))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
<ToastStack items={presets.error?[{id:"layout-save",tone:"error",title:"Раскладка не сохранена",description:presets.error}]:[]} onDismiss={presets.clearError}/>
</div>;
}
@@ -0,0 +1,53 @@
import { useEffect, useState } from "react";
import { Button, LoadingRegion, Window } from "@nodedc/ui-react";
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
import { SimulationProjectWindow } from "./SimulationProjectWindow";
/** Reuses the existing resumable Gaussian Pipeline admission workflow. */
export function SimulationSourceImport({open,onClose,onPly,onReady}: {
open:boolean; onClose:()=>void; onPly:()=>void; onReady:(worldId:string)=>void;
}) {
const [archive,setArchive]=useState(false), [project,setProject]=useState<SimulationProject|null>(null);
const [error,setError]=useState<string|null>(null);
const [pending,setPending]=useState<SimulationProject[]>([]);
useEffect(()=>{
if(!open)return;
const abort=new AbortController();setError(null);
void fetchSimulationProjects(abort.signal).then(rows=>{
if(!abort.signal.aborted)setPending(rows.filter(p=>p.status!=='ready'));
}).catch(e=>{if(!abort.signal.aborted)setError(e.message);});
return()=>abort.abort();
},[open]);
useEffect(()=>{
if(!project||project.status==='ready'||project.status==='failed')return;
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const poll=async()=>{
try {
const projects=await fetchSimulationProjects(abort.signal);
const next=projects.find(p=>p.projectId===project.projectId);
if(abort.signal.aborted)return;
if(next?.status==='ready'){setProject(null);onReady(next.projectId.replace('sim-','aiworld-'));return;}
if(next){setProject(next);if(next.status==='failed')return;}
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
if(!abort.signal.aborted)timer=setTimeout(()=>void poll(),2000);
};
void poll();return()=>{abort.abort();clearTimeout(timer);};
},[project?.projectId,project?.status]);
return <>
<Window open={open} title="Импорт локации" onClose={onClose}><div className="ai-polygon__actions">
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
</div>
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><p>{p.name}</p>
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
{error?<p role="alert">{error}</p>:null}
</Window>
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
<p>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</p>
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
</LoadingRegion>
</Window>:null}
</>;
}
@@ -13,6 +13,8 @@ import {
} from "playcanvas"; } from "playcanvas";
import { MeshoptSimplifier } from "meshoptimizer/simplifier"; import { MeshoptSimplifier } from "meshoptimizer/simplifier";
import type { SimulationUgvPreset } from "../../core/simulation/projects"; import type { SimulationUgvPreset } from "../../core/simulation/projects";
import type { RoverMotion } from "../../core/simulation/roverMotion";
import { RoverTrackMotion } from "./RoverTrackMotion";
const AMMO_MODULE_ROOT = "/vendor/playcanvas/ammo/2026-08-25"; const AMMO_MODULE_ROOT = "/vendor/playcanvas/ammo/2026-08-25";
const UGV_SPAWN_POSITION = new Vec3(0, 1.15, 0); const UGV_SPAWN_POSITION = new Vec3(0, 1.15, 0);
@@ -230,6 +232,12 @@ export class SimulationUgvController {
private orbitIdleSeconds = 0; private orbitIdleSeconds = 0;
private cameraOrbitInitialized = false; private cameraOrbitInitialized = false;
private active = false; private active = false;
private disposed = false;
private spawnGround = new Vec3(0,0,0);
private spawnRotation = UGV_SPAWN_ROTATION.clone();
private visualFactory: (() => Entity) | null = null;
private motion: RoverMotion | undefined;
private trackMotion: RoverTrackMotion | null = null;
private vehicleEntity: Entity | null = null; private vehicleEntity: Entity | null = null;
private vehicle: NativeRaycastVehicle | null = null; private vehicle: NativeRaycastVehicle | null = null;
private vehicleRaycaster: NativeObject | null = null; private vehicleRaycaster: NativeObject | null = null;
@@ -251,6 +259,16 @@ export class SimulationUgvController {
this.settings = cloneUgvPreset(initialSettings); this.settings = cloneUgvPreset(initialSettings);
} }
setRobot(visualFactory: () => Entity, ground: Vec3, headingDegrees: number, motion?: RoverMotion): void {
if (this.active) throw new Error("Сначала остановите ручное управление.");
this.visualFactory = visualFactory;
this.motion = motion;
this.spawnGround.copy(ground);
this.spawnRotation.set(0,headingDegrees,0);
}
get speed(): number { return (this.vehicle?.getCurrentSpeedKmHour() ?? 0) / 3.6; }
get enabled(): boolean { get enabled(): boolean {
return this.active; return this.active;
} }
@@ -269,9 +287,11 @@ export class SimulationUgvController {
async enable(collisionWorld: Entity): Promise<void> { async enable(collisionWorld: Entity): Promise<void> {
if (this.active) return; if (this.active) return;
await nextAnimationFrame(); await nextAnimationFrame();
if (this.disposed) return;
try { try {
await this.createStaticCollisionBodies(collisionWorld); await this.createStaticCollisionBodies(collisionWorld);
await nextAnimationFrame(); await nextAnimationFrame();
if (this.disposed) { this.disable(); return; }
this.spawnPosition.copy(this.findSafeSpawnPosition()); this.spawnPosition.copy(this.findSafeSpawnPosition());
this.createVehicle(); this.createVehicle();
this.attachInput(); this.attachInput();
@@ -302,6 +322,7 @@ export class SimulationUgvController {
} }
dispose(): void { dispose(): void {
this.disposed = true;
this.disable(); this.disable();
} }
@@ -309,7 +330,7 @@ export class SimulationUgvController {
const vehicleEntity = this.vehicleEntity as (Entity & NativeRigidBodyAccess) | null; const vehicleEntity = this.vehicleEntity as (Entity & NativeRigidBodyAccess) | null;
const rigidbody = vehicleEntity?.rigidbody; const rigidbody = vehicleEntity?.rigidbody;
if (!vehicleEntity || !rigidbody) return; if (!vehicleEntity || !rigidbody) return;
rigidbody.teleport(this.spawnPosition, UGV_SPAWN_ROTATION); rigidbody.teleport(this.spawnPosition, this.spawnRotation);
rigidbody.linearVelocity = ZERO; rigidbody.linearVelocity = ZERO;
rigidbody.angularVelocity = ZERO; rigidbody.angularVelocity = ZERO;
this.vehicle?.resetSuspension(); this.vehicle?.resetSuspension();
@@ -455,6 +476,11 @@ export class SimulationUgvController {
} }
body?.setActivationState(DISABLE_DEACTIVATION); body?.setActivationState(DISABLE_DEACTIVATION);
if (rigidbody && this.trackMotion) {
const forward = this.vehicleEntity.getRotation().transformVector(new Vec3(0,0,1));
const up = this.vehicleEntity.up;
this.trackMotion.update(deltaSeconds,rigidbody.linearVelocity.dot(forward),rigidbody.angularVelocity.dot(up));
}
if (this.vehicleEntity.getPosition().y < -8) this.reset(); if (this.vehicleEntity.getPosition().y < -8) this.reset();
this.updateCamera(deltaSeconds); this.updateCamera(deltaSeconds);
} }
@@ -593,6 +619,7 @@ export class SimulationUgvController {
const rootInverse = collisionWorld.getWorldTransform().clone().invert(); const rootInverse = collisionWorld.getWorldTransform().clone().invert();
for (let index = 0; index < meshInstances.length; index += 1) { for (let index = 0; index < meshInstances.length; index += 1) {
if (this.disposed) return;
const meshInstance = meshInstances[index]; const meshInstance = meshInstances[index];
const physicsMesh = createPhysicsProxyMesh( const physicsMesh = createPhysicsProxyMesh(
this.app, this.app,
@@ -707,6 +734,15 @@ export class SimulationUgvController {
}); });
} }
if (this.visualFactory) {
// Keep the physical contact proxy; the operator sees only the selected CAD model.
for (const render of vehicle.findComponents("render")) (render as { enabled: boolean }).enabled = false;
const visual = this.visualFactory();
visual.setLocalEulerAngles(0,-90,0); // glTF +X forward -> controller +Z forward
visual.setLocalPosition(0,-dimensions.originHeight,0);
vehicle.addChild(visual);
this.trackMotion = this.motion ? new RoverTrackMotion(visual,this.motion) : null;
}
vehicle.setLocalPosition(this.spawnPosition); vehicle.setLocalPosition(this.spawnPosition);
this.app.root.addChild(vehicle); this.app.root.addChild(vehicle);
@@ -827,12 +863,12 @@ export class SimulationUgvController {
const heights: number[] = []; const heights: number[] = [];
let suitable = true; let suitable = true;
for (const [sampleX, sampleZ] of footprint) { for (const [sampleX, sampleZ] of footprint) {
const x = UGV_SPAWN_POSITION.x + offsetX + sampleX; const x = this.spawnGround.x + offsetX + sampleX;
const z = UGV_SPAWN_POSITION.z + offsetZ + sampleZ; const z = this.spawnGround.z + offsetZ + sampleZ;
from.set(x, 8, z); from.set(x, this.spawnGround.y + 3, z);
to.set(x, -8, z); to.set(x, this.spawnGround.y - 3, z);
const hit = physics.raycastFirst(from, to); const hit = physics.raycastFirst(from, to);
if (!hit || hit.normal.y < 0.72 || Math.abs(hit.point.y) > 2.5) { if (!hit || hit.normal.y < 0.72 || Math.abs(hit.point.y - this.spawnGround.y) > 2.5) {
suitable = false; suitable = false;
break; break;
} }
@@ -843,8 +879,8 @@ export class SimulationUgvController {
const maximum = Math.max(...heights); const maximum = Math.max(...heights);
if (maximum - minimum > 0.32) continue; if (maximum - minimum > 0.32) continue;
const x = UGV_SPAWN_POSITION.x + offsetX; const x = this.spawnGround.x + offsetX;
const z = UGV_SPAWN_POSITION.z + offsetZ; const z = this.spawnGround.z + offsetZ;
const ground = heights.reduce((sum, height) => sum + height, 0) / heights.length; const ground = heights.reduce((sum, height) => sum + height, 0) / heights.length;
const clearanceHeight = ground + dimensions.originHeight; const clearanceHeight = ground + dimensions.originHeight;
const origin = new Vec3(x, clearanceHeight, z); const origin = new Vec3(x, clearanceHeight, z);
@@ -855,10 +891,11 @@ export class SimulationUgvController {
if (!blocked) return new Vec3(x, ground + dimensions.originHeight, z); if (!blocked) return new Vec3(x, ground + dimensions.originHeight, z);
} }
return UGV_SPAWN_POSITION.clone(); throw new Error("В месте старта нет опоры для ровера. Выберите другую точку старта.");
} }
private destroyVehicle(): void { private destroyVehicle(): void {
this.trackMotion = null;
if (this.vehicle && this.dynamicsWorld) { if (this.vehicle && this.dynamicsWorld) {
runCleanup("remove vehicle action", () => this.dynamicsWorld?.removeAction(this.vehicle as NativeObject)); runCleanup("remove vehicle action", () => this.dynamicsWorld?.removeAction(this.vehicle as NativeObject));
} }
@@ -890,6 +927,7 @@ export class SimulationUgvController {
window.addEventListener("keydown", this.onKeyDown, true); window.addEventListener("keydown", this.onKeyDown, true);
window.addEventListener("keyup", this.onKeyUp, true); window.addEventListener("keyup", this.onKeyUp, true);
window.addEventListener("blur", this.onWindowBlur); window.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("pointerdown", this.onOrbitPointerDown); this.canvas.addEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.addEventListener("pointermove", this.onOrbitPointerMove); this.canvas.addEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.addEventListener("pointerup", this.onOrbitPointerUp); this.canvas.addEventListener("pointerup", this.onOrbitPointerUp);
@@ -901,6 +939,7 @@ export class SimulationUgvController {
window.removeEventListener("keydown", this.onKeyDown, true); window.removeEventListener("keydown", this.onKeyDown, true);
window.removeEventListener("keyup", this.onKeyUp, true); window.removeEventListener("keyup", this.onKeyUp, true);
window.removeEventListener("blur", this.onWindowBlur); window.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("pointerdown", this.onOrbitPointerDown); this.canvas.removeEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.removeEventListener("pointermove", this.onOrbitPointerMove); this.canvas.removeEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.removeEventListener("pointerup", this.onOrbitPointerUp); this.canvas.removeEventListener("pointerup", this.onOrbitPointerUp);
@@ -965,7 +1004,7 @@ export class SimulationUgvController {
} }
private onKeyDown = (event: KeyboardEvent): void => { private onKeyDown = (event: KeyboardEvent): void => {
if (!this.active || isTextEntry(event.target)) return; if (!this.active || document.activeElement !== this.canvas || isTextEntry(event.target)) return;
if (!UGV_KEYS.has(event.code)) return; if (!UGV_KEYS.has(event.code)) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();

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