Compare commits

...
Author SHA1 Message Date
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
DCCONSTRUCTIONS 97614742bb Accept qualified ARNavi VPS 0.2.5 v1 compatibility contract 2026-10-01 14:38:42 +03:00
DCCONSTRUCTIONS a78fdeae66 Accept qualified ARNavi VPS 0.2.4 client contract 2026-10-01 09:13:14 +03:00
DCCONSTRUCTIONS b17ff5554e Preserve ARNavi full settings support through VPS 0.2.3 2026-10-01 01:07:13 +03:00
DCCONSTRUCTIONS 43b63e8eb9 Accept shared B2 VPS 0.2.1 for equipment settings and commands 2026-09-30 22:43:12 +03:00
DCCONSTRUCTIONS df36e92500 Accept ARNavi VPS 0.2.0 through the existing client contract 2026-09-30 15:34:24 +03:00
DCCONSTRUCTIONS 6dd652f71e Keep B2 client fixes and move VPS implementation to its standalone repository 2026-09-29 12:41:21 +03:00
DCCONSTRUCTIONS 03d44d0fb1 docs(handoff): record ARNavi cards, source revisions and closeout checks 2026-09-28 18:52:10 +03:00
DCCONSTRUCTIONS 21f46ac38a docs(arnavi): consolidate server and tracker handoff with qualification evidence 2026-09-28 18:44:50 +03:00
DCCONSTRUCTIONS 67ae1f4d77 feat(map): show independent tracker positions and recover unavailable layers 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS 031e01a99b feat(ui): add tracker provisioning, SIM policies, command history and firmware archive 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS f3a7592d90 feat(fleet): integrate independent trackers, VPS pairing and recoverable commands 2026-09-28 18:44:12 +03:00
DCCONSTRUCTIONS d684eb7e05 feat(vps): ship durable ARNavi host with reproducible install and recovery 2026-09-28 18:43:39 +03:00
DCCONSTRUCTIONS b6efae3272 feat(arnavi): add qualified B2 protocols, USB provisioning and SIM evidence 2026-09-28 18:43:32 +03:00
DCCONSTRUCTIONS fb33a6d45c fix(ui): label connectivity checks as Проверка состояния 2026-09-25 23:26:51 +03:00
DCCONSTRUCTIONS 0fb117fe7b docs: record worker recovery acceptance and deployment boundaries 2026-09-25 23:25:02 +03:00
DCCONSTRUCTIONS e2cf3078b6 fix(ui): unify connectivity labels and move contour refresh to header 2026-09-25 23:24:45 +03:00
DCCONSTRUCTIONS f3640026cf fix(telemetry): recover worker agent and Tailscale transport automatically 2026-09-25 23:24:27 +03:00
DCCONSTRUCTIONS bd5873ef34 fix(fleet): derive contour status from registered nodes and remove obsolete tabs 2026-09-25 22:28:42 +03:00
DCCONSTRUCTIONS aecae4a986 feat(fleet): edit apparatus name independently of onboard availability 2026-09-25 22:28:22 +03:00
DCCONSTRUCTIONS ee7576b7b4 refactor(fleet-ui): consolidate apparatus header and computer status 2026-09-25 21:58:57 +03:00
DCCONSTRUCTIONS e2b0d839eb feat(fleet-ui): organize apparatus equipment beneath its computer 2026-09-25 21:38:25 +03:00
DCCONSTRUCTIONS d2ec9e95b1 feat(fleet): replace onboard computer without replacing apparatus 2026-09-25 21:38:13 +03:00
DCCONSTRUCTIONS 8283f9ba85 feat(observation): expose offline sources with transparent viewport headers 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS db3b1d7b67 fix(navigation): return repeated section selections to their entry view 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS a993eda6b8 feat(rover): add live scene and material editing with environment migration 2026-09-25 19:13:52 +03:00
2214 changed files with 317369 additions and 5528 deletions
+8 -20
View File
@@ -193,7 +193,7 @@ The compact summary must cover:
- retained authority.
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,
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
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
the direct `nodedc-ops-agent` tools and write titled structured blocks in this
order:
1. Objective and architecture stage.
2. Decision question and hypothesis.
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.
Use the direct `nodedc-ops-agent` tools only for concise verified delivered
results: what works, what implementation is used, and the accepted scope.
Keep intermediate measurements, failed attempts, architecture proposals,
hypotheses and next-stage plans in local engineering evidence, not Ops.
Consolidate superseded intermediate blocks instead of appending a run diary.
Do not turn a partial experiment into a completed-product claim.
## Validation
+3
View File
@@ -56,3 +56,6 @@ node_modules
# Private experiment evidence and generated build archives.
/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,
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
- 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.
- Product UI must not expose implementation steps, roadmap gates, internal
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.
- 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
@@ -210,11 +280,49 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
- The compact summary must explain the decision question, immutable source,
tested method/models/algorithms, experimental mode, principal result,
limitations, and retained authority. It is not the engineering report.
- The complete engineering report belongs in the Mission Core Ops card as
titled structured blocks: objective and architecture stage, source evidence,
method/models/algorithms, worker/runtime, implementation, validation,
results, regressions and limitations, decision, next stage, and acceptance
checker.
- Owner reporting rule (2026-10-09): Ops contains concise, verified delivered
results only: what works, the implementation used, and its accepted scope.
Keep intermediate experiments, failed attempts, architecture proposals,
detailed logs and future plans in local engineering evidence, not Ops.
Consolidate superseded intermediate blocks instead of appending a run diary.
Never present a partial experiment as a completed product result.
- Spatial evidence uses 3D by default. Image-space reprojection may be offered
as a 2D diagnostic mode inside the same reusable viewer. Primary evidence
viewers must provide the canonical expand/restore action.
## 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.
+30
View File
@@ -1,5 +1,10 @@
# NODEDC MISSION CORE
ARNavi B2 VPS server development moved to
[NODEDC_MISSION_CORE_ARNAVI-VPS](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS).
Mission Core retains its B2 client and existing pairing; see the
[repository boundary](docs/arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning,
recording, and integration platform for NODEDC autonomous systems. This
repository is the canonical early-stage monorepo: it contains the Mission Core
@@ -202,6 +207,12 @@ See [the Dataset Gateway plan](docs/14_LIDAR_DATASET_GATEWAY.md),
## Simulation Polygon
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
autonomy qualification. Mission Core owns scenarios, qualification-run
lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4
@@ -627,3 +638,22 @@ Real captures, projects, router metadata, serials, credentials, maps, images,
and logs under `.runtime/`, canonical evidence roots and legacy `sessions/` are
ignored by normal Git. Redacted manifests and SHA-256 inventories are committed;
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",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1"
"three": "0.185.1",
"three-mesh-bvh": "0.9.15"
},
"devDependencies": {
"@types/node": "^24.0.0",
@@ -1756,6 +1758,16 @@
"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": {
"version": "8.5.19",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",
@@ -1816,6 +1828,12 @@
"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": {
"version": "4.62.2",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
@@ -1887,12 +1905,30 @@
"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": {
"version": "0.185.1",
"resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
"integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
"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": {
"version": "0.2.17",
"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",
"build": "tsc -b && vite build",
"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"
},
"dependencies": {
@@ -23,9 +23,11 @@
"@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1"
"three": "0.185.1",
"three-mesh-bvh": "0.9.15"
},
"devDependencies": {
"@types/node": "^24.0.0",
@@ -0,0 +1,174 @@
{
"schema_version": "missioncore.rover-motion/v1",
"source_scene": "DCD-006_rover_v020.blend",
"source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79",
"source_saved": false,
"visual_sha256": "4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e",
"forward_axis": "+X",
"up_axis": "Y",
"track_centres_m": {
"L": 0.3425,
"R": -0.3425
},
"track_width_m": 0.685,
"shift_m": [
-0.05350000038743019,
0.0,
0.0
],
"length_m": 2.222,
"pitch_m": 0.0505,
"phase_m": 0.03069696662739778,
"segments": [
[
"arc",
0,
0.060539054924808725,
[
-0.16593354688111153,
0.32184557191629776,
0.0655,
2.3390854961098873
]
],
[
"line",
0.060539054924808725,
0.5760464371429339,
[
-0.15575880346026824,
0.3865504758751169,
0.9878611291422765,
-0.1553395942113481,
0.15533959421134813,
0.9878611291422766
]
],
[
"arc",
0.6365854920677426,
0.15172294911931034,
[
0.40182697,
0.22413776,
0.07382606110411796,
1.4148251155784564
]
],
[
"line",
0.7883084411870529,
0.1629407568053742,
[
0.46102862009488454,
0.18003048254840684,
-0.5974486081464921,
-0.8019072020027126,
0.8019072020027126,
-0.5974486081464921
]
],
[
"arc",
0.9512491979924271,
0.06094648310379254,
[
0.31115497,
0.0885,
0.0655,
-0.6403156687217281
]
],
[
"line",
1.0121956810962196,
0.7185584980197575,
[
0.31115497,
0.022999999999999993,
-1.0,
0.0,
-0.0,
-1.0
]
],
[
"arc",
1.730754179115977,
0.15545137821999958,
[
-0.40740352801975754,
0.0885,
0.0655,
-1.5707963267948966
]
],
[
"line",
1.8862055573359766,
0.33579444266402353,
[
-0.45291987081346463,
0.1356010885085021,
0.719100587916063,
0.6949059968504895,
-0.6949059968504895,
0.719100587916063
]
]
],
"link_count": 44,
"wheels": [
{
"node": "R_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "R_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_DRIVE",
"radius_m": 0.07233592163526643
},
{
"node": "L_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "L_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_DRIVE",
"radius_m": 0.07233592163526643
}
],
"dimensions_m": [
1.1630001068115234,
0.9049999713897705,
0.7378441095352173
],
"minimum_m": [
-0.5814999938011169,
-0.45249998569488525,
-0.003844098187983036
],
"method": "44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; no track contact dynamics"
}
Binary file not shown.
File diff suppressed because it is too large Load Diff
+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.
@@ -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>
+29 -14
View File
@@ -152,6 +152,7 @@ export default function App() {
contentExpanded: true,
});
const [navigationRevision, setNavigationRevision] = useState(0);
const [activeRoot, setActiveRoot] = useState<RootId | null>(
polygonDatasetRoute.active ? "data" : null,
);
@@ -159,6 +160,7 @@ export default function App() {
const [launchProfile, setLaunchProfile] = useState<WorkspaceLaunchProfile>('direct');
const [sourceUrl, setSourceUrl] = useState("");
const [workspaceHeaderToolsHost, setWorkspaceHeaderToolsHost] = useState<HTMLDivElement | null>(null);
const [workspaceHeaderTitleHost, setWorkspaceHeaderTitleHost] = useState<HTMLSpanElement | null>(null);
const [recordedReplay, setRecordedReplay] = useState<ObservationSessionReplayLaunch | null>(null);
const [recordedReplayLabel, setRecordedReplayLabel] = useState<string | null>(null);
const [replayTransitioning, setReplayTransitioning] = useState(false);
@@ -457,6 +459,17 @@ export default function App() {
workspace.openView(viewId);
};
// Explicit menu navigation always returns to that workspace's entry screen.
const openNavigationView = (viewId: string) => {
if (!workspaceById(viewId)) return;
setNavigationRevision(value => value + 1);
sessionOverview.close();
setSourceWindowOpen(false);
setDisplayWindowOpen(false);
setLayerInspectorOpen(false);
openView(viewId);
};
const openSource = () => {
if (!sceneWorkspaceActive) return;
setSourceDraft(sourceUrl);
@@ -645,11 +658,8 @@ export default function App() {
return () => window.clearTimeout(timer);
}, [layoutSaveNotice]);
const [fleetCreateRequest, setFleetCreateRequest] = useState(0);
const sessionOverview = useSessionOverviewMode(activeDefinition?.kind === "recordings");
const onAddVehicle = useCallback(() => setFleetCreateRequest(value => value + 1), []);
const contentActions = useApplicationPanelActions({
onAddVehicle,
definition: activeDefinition,
refreshRuntime: runtime.refresh,
resetConnectionScenario: runtime.resetConnectionScenario,
@@ -712,9 +722,9 @@ export default function App() {
workspace.navigationOpen && activeRoot !== null
}
contentOpen={workspace.contentOpen && activeDefinition !== null}
contentExpanded={workspace.contentExpanded}
contentExpanded
header={header}
stage={
stage={activeDefinition ? null :
<LandingStage
root={currentRoot}
backendStatus={runtime.backendStatus}
@@ -729,6 +739,7 @@ export default function App() {
<SystemNavigationPanel
title={currentRoot.title}
onAdd={computeContourSettings.openCreate}
onNavigateRoot={() => openNavigationView("modules")}
onClose={workspace.closeNavigation}
/>
) : currentRoot ? (
@@ -755,7 +766,7 @@ export default function App() {
icon: <Icon name={item.icon} />,
}))}
activeId={workspace.activeView ?? undefined}
onItemChange={openView}
onItemChange={openNavigationView}
footer={
<>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
@@ -765,7 +776,8 @@ export default function App() {
{rootWorkspaces.length}{" "}
{rootWorkspaces.length === 1
? "рабочая поверхность"
: "рабочих поверхностей"}
: rootWorkspaces.length >= 2 && rootWorkspaces.length <= 4
? "рабочие поверхности" : "рабочих поверхностей"}
</span>
</>
}
@@ -776,15 +788,16 @@ export default function App() {
key={activeDefinition.id}
eyebrow={activeDefinition.eyebrow}
title={
activeDefinition.kind === "recordings"
activeDefinition.kind === "vehicles"
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
: activeDefinition.kind === "recordings"
&& replayPresented
&& recordedReplayLabel
? `${activeDefinition.title}: ${recordedReplayLabel}`
: activeDefinition.title
}
description={activeDefinition.description}
expanded={workspace.contentExpanded}
onExpandedChange={workspace.setContentExpanded}
expanded
headerTools={
activeDefinition.kind === "device" ? (
<StatusBadge tone={phaseTone(runtime.state?.phase)}>
@@ -822,16 +835,18 @@ export default function App() {
/>
) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" ? <div ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control
) : activeDefinition.kind === "observatory" ? (
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
) : activeDefinition.kind === "contour-health" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.root === "system" ? (
<SystemWorkspaceSelector
value={activeDefinition.id}
onChange={openView}
onChange={openNavigationView}
/>
) : (
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
@@ -840,7 +855,7 @@ export default function App() {
utilityActions={contentActions}
onClose={workspace.closeView}
>
<PlanningCaptureGuard
<PlanningCaptureGuard key={`${activeDefinition.id}:${navigationRevision}`}
enabled={launchProfile === 'direct' && (activeDefinition.kind === 'device' || activeDefinition.kind === 'spatial')}
onResume={() => openView('local-device', 'planning')}
>
@@ -860,8 +875,8 @@ export default function App() {
<WorkspaceRenderer
launchProfile={launchProfile}
definition={activeDefinition}
fleetCreateRequest={fleetCreateRequest}
headerToolsHost={workspaceHeaderToolsHost}
headerTitleHost={workspaceHeaderTitleHost}
state={activeRuntimeState}
backendStatus={runtime.backendStatus}
sourceUrl={effectiveSourceUrl}
@@ -0,0 +1,8 @@
import {createPortal} from 'react-dom';
import {Icon,IconButton} from '@nodedc/ui-react';
/** A nested workspace returns through the shared panel header. */
export function WorkspaceBackButton({label,onClick,host}:{label:string;onClick:()=>void;host?:HTMLElement|null}) {
const button=<IconButton label={label} onClick={onClick}><Icon name="chevron-left"/></IconButton>;
return host?createPortal(button,host):button;
}
@@ -171,7 +171,7 @@ export function CanonicalRecordedLabReplay<
>
{splitView || paneToolbarsAlwaysVisible ? (
<div
className="m4-replay-threat-visual__pane-toolbar"
className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="media"
data-multi-semantic={mediaMultiLayer ? "true" : undefined}
>
@@ -190,7 +190,7 @@ export function CanonicalRecordedLabReplay<
>
{splitView || paneToolbarsAlwaysVisible ? (
<div
className="m4-replay-threat-visual__pane-toolbar"
className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="spatial"
>
{spatialLeadingControl}
@@ -83,7 +83,7 @@ export function LaboratoryEvidenceViewer<
}, [expanded, onExpandedChange]);
const controls = (
<div className="laboratory-evidence-viewer__controls">
<div className="laboratory-evidence-viewer__controls nodedc-viewport-controls">
{actions}
{modeControlsVisible && secondaryMode ? (
<SegmentedControl
@@ -137,7 +137,7 @@ export function LaboratoryEvidenceViewer<
{children}
</div>
{transport ? (
<div className="laboratory-evidence-viewer__transport">
<div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport}
</div>
) : null}
@@ -149,7 +149,7 @@ export function LaboratoryEvidenceViewer<
</div>
{overlay}
{transport ? (
<div className="laboratory-evidence-viewer__transport">
<div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport}
</div>
) : null}
@@ -265,6 +265,8 @@ LaboratoryMetricEvidenceSceneHandle,
showCurrentIncrement: boolean;
showLocalSurface: boolean;
showRollingMap: boolean;
showReferenceGeometry?: boolean;
showRenderStats?: boolean;
showLowStep?: boolean;
pointSemanticClassIds?: readonly (number | null)[];
semanticClasses?: readonly RecordedEvidenceSemanticClass[];
@@ -287,6 +289,8 @@ LaboratoryMetricEvidenceSceneHandle,
showLocalSurface,
showRollingMap,
showLowStep = true,
showReferenceGeometry = true,
showRenderStats = true,
pointSemanticClassIds,
semanticClasses,
semanticPalette,
@@ -746,6 +750,7 @@ LaboratoryMetricEvidenceSceneHandle,
if (!host || !content) return;
clearGroup(content);
if (!showReferenceGeometry) { requestRenderRef.current(); return; }
const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM;
const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2;
const corridorMesh = new THREE.Mesh(
@@ -806,6 +811,7 @@ LaboratoryMetricEvidenceSceneHandle,
content.add(grid);
requestRenderRef.current();
}, [
showReferenceGeometry,
corridor.forwardLengthM,
corridor.halfWidthM,
corridor.rearMarginM,
@@ -912,7 +918,7 @@ LaboratoryMetricEvidenceSceneHandle,
{renderError ? <p>{renderError}</p> : null}
</div>
<div className="laboratory-metric-evidence-scene__legend">
{renderStats ? (
{showRenderStats && renderStats ? (
<span
data-decision="performance"
title="CPU-время отправки последнего WebGL render pass; это не GPU timer. В покое сцена не перерисовывается."
@@ -101,7 +101,7 @@ export function LaboratoryReviewWorkspaceFrame({
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>
{inspector ? <footer className="laboratory-review-workspace__inspector">{inspector}</footer> : null}
{overlays}
@@ -1,3 +1,4 @@
import {heightSlice} from "../../core/heightSlice";
import {useEffect,useRef,useState} from 'react';
import {Button,LoadingRegion,RangeControl} from '@nodedc/ui-react';
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 stateRef=useRef({active,revision});stateRef.current={active,revision};
const ceilingRef=useRef<number|null>(null);
const floorRef=useRef<number|null>(null);
const boundsRef=useRef<{min:number;max:number}|null>(null);
const host=useRef<HTMLDivElement>(null);
const [state,setState]=useState('loading'),[retry,setRetry]=useState(0);
const [bounds,setBounds]=useState<{min:number;max: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(()=>{
ceilingRef.current=null;
const next=heightBounds&&Number.isFinite(heightBounds.min)&&Number.isFinite(heightBounds.max)&&heightBounds.max>heightBounds.min?heightBounds:null;
boundsRef.current=next;
setBounds(next);setCeiling(null);
setBounds(next);
},[runId,heightBounds?.min,heightBounds?.max]);
useEffect(()=>{
if(!host.current)return;
@@ -54,6 +59,7 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
stopStream=startPlanningSceneStream({
url:`${plannerBase}/live-tests/${runId}/scene-delta.rrd`,
snapshot:()=>({...stateRef.current,options:{...optionsRef.current,
...(floorRef.current===null?{}:{floor_m:floorRef.current}),
...(ceilingRef.current===null?{}:{ceiling_m:ceilingRef.current})}}),
apply:async(bytes,delivery)=>{
if(disposed)return;
@@ -62,9 +68,6 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
const previous=boundsRef.current;
if(!previous||previous.min!==next.min||previous.max!==next.max){
boundsRef.current=next;setBounds(next);
if(ceilingRef.current!==null&&(ceilingRef.current<next.min||ceilingRef.current>next.max)){
ceilingRef.current=null;setCeiling(null);
}
}
}
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();};
},[runId,retry]);
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">
<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">
<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('.',',')}
onChange={value=>{
const next=value>=rangeBounds.max-Math.max(1,rangeBounds.max-rangeBounds.min)*1e-9?null:value;
ceilingRef.current=next;setCeiling(next);
const next=heightSlice(value,[rangeBounds.min,rangeBounds.max]);
floorRef.current=next.floor;setFloor(next.floor);ceilingRef.current=next.ceiling;setCeiling(next.ceiling);
}}/>
</div>}
{state==='error'&&<div className="session-overview__empty"><span>Обновление сцены недоступно.</span><Button onClick={()=>setRetry(v=>v+1)}>Повторить подключение сцены</Button></div>}
@@ -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 { Button, LoadingRegion, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost";
@@ -11,6 +12,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const [retry, setRetry] = useState(0);
const [metadata, setMetadata] = useState<OverviewSpatialMetadata | null>(null);
const [ceiling, setCeiling] = useState<number | null>(null);
const [floor, setFloor] = useState<number | null>(null);
const [mode, setMode] = useState<OverviewViewMode>("3d");
const [viewError, setViewError] = useState<string | 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();
appliedMode.current = null;
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);
void fetchOverviewSpatial(sourceUrl, abort.signal).then(data => {
if (disposed) return;
@@ -56,7 +58,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const timer = setTimeout(() => {
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,
comparison?.generation ?? null, comparison ? representation : "original").then(result => {
comparison?.generation ?? null, comparison ? representation : "original", floor).then(result => {
if (abort.signal.aborted || !controller.current) return;
controller.current.channel.send_rrd(result.bytes);
appliedMode.current = mode;
@@ -65,12 +67,12 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
}).catch(() => { if (!abort.signal.aborted) { setUpdating(false); setViewError("Не удалось обновить вид облака. Показан предыдущий вид."); } });
}, 180);
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 high = comparison?.height_max_m ?? metadata?.height_max_m;
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}
items={[{ value: "original", label: "Исходное", disabled: state !== "ready" }, { value: "corrected", label: "Исправленное", disabled: state !== "ready" }]} />}
<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">
<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">
<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('.', ',')}
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>}
{state === "error" && <div className="session-overview__empty"><span>Не удалось открыть облако.</span><Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
</LoadingRegion>
<span className="session-overview__note" role="status" aria-busy={updating}>
{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 />Выборка для просмотра. Исходная запись сохранена отдельно.</>}
</span>
{viewError && <div className="session-overview__note" role="alert">{viewError}<Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
@@ -0,0 +1,57 @@
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
.observation-toolbar h2, .observation-panel h3 { margin:0; }
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
.observation-actions { flex-shrink:0; }
.observation-deck { flex:1; min-height:0; min-width:0; }
.observation-layout { position:relative; height:100%; min-height:0; min-width:0; }
.observation-layout__slot { height:100%; min-height:0; }
.observation-layout__panel { position:absolute; min-height:0; min-width:0; }
.observation-layout__panel:has(.is-dragging) { z-index:var(--nodedc-layer-panel); }
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
.observation-panel__surface > .observation-mount { flex:1; }
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
.observation-header-slot:has(> div:empty) { display:none; }
.observation-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; }
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
.observation-source__notice--centered { inset:var(--observation-overlay-header-space, 0px) 0 0; margin:0; padding:var(--nodedc-space-4); display:grid; place-content:center; font-size:var(--nodedc-font-size-sm); pointer-events:none; }
.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)); }
@@ -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 {RoverObservationStatus} from '../../core/fleet/roverObservation';
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}):'—';
export function RoverTelemetry({state}:{state:RoverState}){
export function roverTelemetryTable(state:RoverState){
const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
const positions=drivePositions(profile?.layout??null);
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),
}));
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">
{!state.fresh?<p>Нет свежих показаний VESC.</p>:!readings.length?<p>Получение показаний VESC…</p>:readings.map(d=>{
const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined;
return <section key={d.uuid}><strong>{d.label}</strong><span>VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''}</span>
<dl><div><dt>Ток мотора</dt><dd>{number(v?.motor_current_a)} А</dd></div>
<div><dt>Ток батареи</dt><dd>{number(v?.input_current_a)} А</dd></div>
<div><dt>Напряжение</dt><dd>{number(v?.input_voltage_v)} В</dd></div>
<div><dt>Обороты, ERPM</dt><dd>{number(v?.erpm,0)}</dd></div>
<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>;
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;
const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const;
return {
columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')},
{id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')},
...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:''}`:'—';})})),
{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):'—';})}],
};
}
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,64 @@
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {roverDevEvent} from '../../core/fleet/roverDevEvents';
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
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 './rover.css';
const Scene=lazy(()=>import('./playcanvas/PlayCanvasViewer'));
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'};
const Scene=lazy(()=>import('./editor/RoverScene'));
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление вкл',driving:'Управление вкл',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выкл',fault:'Управление остановлено'};
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
export function RoverView({vehicleID,controller:c,header,active,observation}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
const storage=`missioncore.rover-view.v1:${vehicleID}`;
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const [open,setOpen]=useState(false),[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 [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
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]);
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
const focusAfterArm=useRef(false);
useEffect(()=>{
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();},[active,stop]);
useEffect(()=>{
if(!c.ready||!active||open||!stage.current)return;
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
if(!c.ready||!active||open||editing||!stage.current)return;
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);
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
},[c.ready,active,open,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
const showSettings=()=>{stop();setOpen(true);};
const preparing=c.pending||(c.armed&&!c.ready);
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null;
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
},[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
const showSettings=()=>{setEditing(false);stop();setOpen(true);};
const preparing=c.recovering||c.pending||(c.armed&&!c.ready);
const duty=c.controlMode!=='rpm';
const limits=(c.state.snapshot.devices??[]).filter(d=>d.slot&&d.current_limits);
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 tone=preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral';
const status=c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение');
const running=c.armed||c.pending||c.recovering;
return <>
{createPortal(<IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton>,header.actionsTarget)}
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
{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={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-вид и управление ровером"
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера">
<Suspense fallback={null}><Scene modelUrl="/rover-scene/dcd006-v020.glb" cameraAutoRotate={false} onModelState={setModelState}/></Suspense>
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
<div className="rover-view__status"><StatusBadge tone={tone}>{status}</StatusBadge></div>
{c.ready&&<div className="rover-view__controls">
{c.ready&&!editing&&<div className="rover-view__controls">
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
disabled={!c.ready||!active} pressed={held.has(code)}
@@ -50,20 +69,17 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
</div>
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
</div>}
<div className="rover-view__authority">
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
</div>
</div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:'dcd006-v020',label:'DCD-006 · полный ровер v020'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
<TextField label="Предел тока каждого мотора, А" type="number" min={.5} max={30} step={.5} value={settings.currentA} onChange={e=>setSettings(v=>({...v,currentA:Number(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)}))}/>
<Switch label="Моторы остановлены, движение можно начинать" checked={confirmed} onChange={setConfirmed}/>
{availability&&<StatusBadge tone="warning">{availability}</StatusBadge>}
<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}
onClick={async()=>{const acquired=await c.arm(settings.currentA,settings.maxErpm);if(acquired){setOpen(false);if(document.hasFocus())stage.current?.focus();}}}>Включить управление</Button>
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button>
</div></Window>
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
</>;
@@ -0,0 +1,23 @@
import {LutField} from './LutField';
import {useRef} from 'react';
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
const groups=[...new Set(environmentFields.map(f=>f.group))];
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>;
}
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
if(f.type==='action')return <Button onClick={onResetCamera}>Сбросить камеру</Button>;
if(f.type==='toggle')return <Switch label={f.label} checked={!!value} disabled={disabled} onChange={onChange}/>;
if(f.type==='color')return <ControlRow label={f.label}><ColorField label={f.label} value={String(value)} disabled={disabled} onChange={onChange}/></ControlRow>;
if(f.type==='select')return <InspectorSelectField label={f.label} value={String(value)} options={f.options??[]} disabled={disabled} onChange={onChange}/>;
if(f.type==='doubleSlider'){const range=value as number[];return <>{['Начало тумана, м','Конец тумана, м'].map((label,i)=><RangeControl key={i} label={label} min={f.min??0} max={f.max??100} step={f.step??1} exactValueBounds={{min:f.min,max:f.max}} value={range[i]} disabled={disabled} onChange={v=>onChange(i?[range[0],v]:[v,range[1]])}/>)}</>;}
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
}
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){
const input=useRef<HTMLInputElement>(null);
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
}
@@ -0,0 +1,7 @@
import {useRef,useState} from 'react';
import {Button,Icon,IconButton} from '@nodedc/ui-react';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
export function LutField({value,onChange,onError}:{value:string|null|undefined;onChange:(value:string|null)=>void;onError:(error:string)=>void}){
const input=useRef<HTMLInputElement>(null),[loading,setLoading]=useState(false);
return <div className="rover-scene-fields"><p className="rover-scene-note">PNG 256 × 16 · горизонтальная таблица 16³</p><div className="rover-scene-actions"><Button loading={loading} onClick={()=>input.current?.click()}>{value?'Заменить LUT':'Загрузить LUT'}</Button>{value&&<IconButton label="Удалить LUT" onClick={()=>onChange(null)}><Icon name="trash"/></IconButton>}</div><input hidden ref={input} type="file" accept="image/png" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setLoading(true);try{const bitmap=await createImageBitmap(file);const valid=bitmap.width===256&&bitmap.height===16;bitmap.close();if(!valid||file.type!=='image/png')throw new Error('Нужна PNG-таблица LUT размером 256 × 16.');onChange((await textureFromFile(file)).data);}catch(error){onError(error instanceof Error?error.message:'Не удалось прочитать LUT.');}finally{setLoading(false);}}}/></div>;
}
@@ -0,0 +1,17 @@
import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
]}/><Button onClick={onReset}>Исходный материал</Button></>;
}
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
}
@@ -0,0 +1,38 @@
import {useCallback,useEffect,useState,type CSSProperties} from 'react';
import {Button,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,Window} from '@nodedc/ui-react';
import {assignMaterial,createMaterial,changeField,defaultScene,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
import PlayCanvasViewer from '../playcanvas/PlayCanvasViewer';
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
import {MaterialInspector} from './MaterialInspector';
import './sceneEditor.css';
export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
const scene=useSceneDocument(vehicleID),[palette,setPalette]=useState(false),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
const [selectedGroup,setSelectedGroup]=useState<string|null>(null);
const pick=useCallback((id:string,group?:string)=>{setSelected(id);if(group)setSelectedGroup(group);setMaterialOpen(true);},[]);
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=128){scene.setError('В сцене может быть не больше 128 материалов.');return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{const next={...scene.document,materials:{...scene.document.materials,[id]:{...scene.document.materials[id],...patch}}};if(textureBytes(next)>28_000_000){scene.setError('Суммарный объём текстур превышает 20 МБ. Удалите ненужную текстуру.');return;}scene.update(doc=>({...doc,materials:{...doc.materials,[id]:{...doc.materials[id],...patch}}}));};
useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]);
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
const material=selected?scene.document.materials[selected]:null;
return <>
<LoadingRegion className="rover-view__scene" style={{bottom:editing&&palette?150:0}} loading={!scene.ready} label="Загрузка настроек сцены">
{scene.ready&&<PlayCanvasViewer modelUrl="/rover-scene/dcd006-v020.glb?materials-v2" postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} materials={scene.document.materials} assignments={scene.document.assignments} editing={editing} onMaterialPick={pick} onModelState={onModelState} onTextureState={setTextureState}/>}
</LoadingRegion>
{editing&&<>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
{palette&&<GlassSurface className="rover-material-palette"><div className="rover-material-palette__header"><span>Материалы · выберите в палитре или на модели</span><IconButton label="Скрыть палитру материалов" onClick={()=>setPalette(false)}><Icon name="close"/></IconButton></div><div className="rover-material-palette__items">{Object.entries(scene.document.materials).map(([id,m])=><Button key={id} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':m.color,'--material-gloss':1-m.roughness} as CSSProperties}/><span>{m.name}</span></span></Button>)}<Button aria-label="Добавить материал" title="Добавить материал" onClick={addMaterial}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button></div></GlassSurface>}
</>}
<Window open={editing&&environment} title="Окружение сцены" placement="end" draggable onClose={()=>setEnvironment(false)} footer={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaultScene().postFx}))}/>}>
<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>
</Window>
<Window open={editing&&materialOpen&&!!material} title={material?.name||'Материал'} subtitle="Материал сцены" placement="end" draggable style={{position:'fixed',left:'var(--nodedc-space-4)',top:'6rem',right:'auto'}} onClose={()=>setMaterialOpen(false)}>
{material&&selected&&<>
{selectedGroup?<div className="rover-scene-fields"><p className="rover-scene-note">Выбранная группа: {defaultScene().materials[selectedGroup]?.name}</p><Button disabled={(scene.document.assignments[selectedGroup]??selectedGroup)===selected} onClick={()=>scene.update(doc=>assignMaterial(doc,selectedGroup,selected))}>Назначить выбранной группе</Button></div>:<p className="rover-scene-note">Нажмите на деталь в сцене, затем выберите материал в палитре, чтобы назначить его группе.</p>}
<MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaultScene().materials[selected]??createMaterial(defaultScene(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/>
</>}
</Window>
<ToastStack items={scene.error?[{id:'rover-scene-error',tone:'error',title:'Настройки сцены',description:scene.error}]:[]} onDismiss={()=>scene.setError('')}/>
</>;
}
@@ -0,0 +1,17 @@
.rover-scene-tools {position:absolute;right:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3));}
.rover-scene-tools__surface,.rover-scene-actions {display:flex;align-items:center;gap:var(--nodedc-space-2);flex-wrap:wrap;}
.rover-scene-tools__surface {padding:var(--nodedc-space-1);}
.rover-scene-save {position:absolute;left:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + 3rem);pointer-events:none;}
.rover-material-palette {position:absolute;bottom:var(--nodedc-space-3);left:var(--nodedc-space-3);right:var(--nodedc-space-3);padding:var(--nodedc-space-2);}
.rover-material-palette__header {display:flex;align-items:center;justify-content:space-between;gap:var(--nodedc-space-2);font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);}
.rover-material-palette__items {display:flex;gap:var(--nodedc-space-2);overflow:auto;}
.rover-material-palette__items > * {flex:0 0 auto;}
.rover-material-tile {display:grid;justify-items:center;gap:var(--nodedc-space-1);width:100px;white-space:normal;font-size:var(--nodedc-font-size-xs);}
/* Domain material thumbnail: a swatch, not a replacement control. */
.rover-material-swatch {display:block;width:38px;height:38px;border-radius:50%;background:radial-gradient(ellipse at 35% 25%,#ffffffb0,transparent 45%),radial-gradient(ellipse at 60% 75%,transparent,var(--material-color) 70%),var(--material-color);box-shadow:inset -5px -5px 12px #0008;}
.rover-scene-fields {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-scene-note {font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);}
.rover-scene-texture__row {display:flex;gap:var(--nodedc-space-2);align-items:center;min-width:0;}
.rover-scene-texture__row img {width:36px;height:36px;object-fit:cover;}
.rover-scene-texture__row .nodedc-button {min-width:0;overflow:hidden;}
@container(max-width:460px){.rover-scene-save{top:calc(var(--observation-overlay-header-space, 0px) + 4.5rem)}.rover-material-tile{width:82px}.rover-material-palette__header>span{max-width:210px}}
@@ -11,6 +11,13 @@
"No fallback to a different vehicle",
"Removed unused node-editor type helper; rendering settings unchanged",
"Observe the host pane on resize; preserve responsive canvas CSS sizing",
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect"
]
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect",
"Scene editing uses canonical modeless Design Guideline inspectors; all 109 donor camera/post-FX fields retained as a versioned field catalog",
"Original NodeDC environment preset restored by owner request; editor reset changes environment only",
"Semantic material groups, UV texture editing, GPU surface picking and bounded texture disposal",
"Live grid step/diameter and ambient fill added; wireframe application and LUT loading corrected",
"Responsive scene framing and palette space without drive authority"
],
"inspector_source_sha256": "8f1df16bd8c12fb1b8481480690ff4ed0e6b2645cb3fba527888c0f9acb59192",
"model_revision": "dcd006-v020-materials-v2"
}
@@ -3,13 +3,16 @@ import * as pc from 'playcanvas'
import { buildSceneTree } from './sceneTree'
import { mergePostFxDefaults, type PostFxSettings } from './playcanvasPostFx'
import {useLutTexture} from './useLutTexture'
import {useSceneMaterials,type SceneMaterialsProps} from './useSceneMaterials'
const DEFAULT_MODEL_URL = ''
const PIXELFORMAT_RGBA8 = (pc as any).PIXELFORMAT_RGBA8 ?? 7
const PIXELFORMAT_111110F = (pc as any).PIXELFORMAT_111110F ?? 18
const PIXELFORMAT_RGBA16F = (pc as any).PIXELFORMAT_RGBA16F ?? 12
const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
export type PlayCanvasViewerProps = {
export type PlayCanvasViewerProps = SceneMaterialsProps & {
modelUrl: string | null
postFx?: Partial<PostFxSettings> | null
viewportSize?: { width: number; height: number }
@@ -390,16 +393,9 @@ function toColor(value: ColorInput, fallback?: pc.Color): pc.Color {
}
function setWireframeForScene(app: pc.Application, enabled: boolean) {
const renders = app.root.findComponents('render') as any[]
for (const r of renders) {
const meshInstances = r?.meshInstances ?? []
for (const mi of meshInstances) {
const mat = mi.material as any
if (mat && 'wireframe' in mat) {
mat.wireframe = enabled
mat.update?.()
}
}
const root = app.root.findByName('ModelRoot') as pc.Entity | null
for (const mi of collectMeshInstances(root)) {
mi.renderStyle = enabled ? pc.RENDERSTYLE_WIREFRAME : pc.RENDERSTYLE_SOLID
}
}
@@ -805,7 +801,7 @@ function applyPostFx(
}
frame.rendering.renderTargetScale = fx.rendering.renderTargetScale
frame.rendering.samples = Number.isFinite(overrides?.samples) ? Number(overrides?.samples) : fx.rendering.samples
frame.rendering.sceneColorMap = true
frame.rendering.sceneColorMap = !!fx.rendering.sceneColorMap
frame.rendering.sceneDepthMap = !!fx.rendering.sceneDepthMap
frame.rendering.toneMapping = fx.rendering.toneMapping
frame.rendering.sharpness = fx.rendering.sharpness
@@ -882,6 +878,7 @@ function applyPostFx(
export default function PlayCanvasViewer({
modelUrl,
materials, assignments, editing, onMaterialPick, onTextureState,
postFx,
viewportSize,
onSceneReady,
@@ -928,7 +925,11 @@ export default function PlayCanvasViewer({
const [skyboxVersion, setSkyboxVersion] = useState(0)
const [modelVersion, setModelVersion] = useState(0)
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,editing,onMaterialPick,onTextureState})
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
useLutTexture(appRef,cameraFrameRef,lutTextureRef,fx.lut.textureUrl,appReady,lutError)
useEffect(() => {
cameraStateRef.current = cameraState ?? null
@@ -962,7 +963,7 @@ export default function PlayCanvasViewer({
if (bounds && orbit) {
const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * w / h)
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1))
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
}
}, [])
@@ -1112,6 +1113,8 @@ export default function PlayCanvasViewer({
`,
fragmentGLSL: `
uniform vec2 uHalfExtents;
uniform float uGridStep;
uniform float uGridRadius;
uniform vec3 uColorX;
uniform vec3 uColorZ;
uniform vec3 uColorMain;
@@ -1182,7 +1185,9 @@ export default function PlayCanvasViewer({
void main(void) {
vec2 uv = uv0;
vec2 pos = (uv * 2.0 - 1.0) * uHalfExtents;
vec2 worldPos = (uv * 2.0 - 1.0) * uHalfExtents;
if (length(worldPos) > uGridRadius) discard;
vec2 pos = worldPos / uGridStep;
vec2 ddx = dFdx(pos);
vec2 ddy = dFdy(pos);
@@ -1262,7 +1267,7 @@ export default function PlayCanvasViewer({
float fadeEnd = max(0.0, uFadeEnd);
float fade = 1.0;
if (fadeEnd > fadeStart && fadeEnd > 0.0) {
float d = length(pos);
float d = length(worldPos);
fade = 1.0 - smoothstep(fadeStart, fadeEnd, d);
}
outAlpha *= fade;
@@ -1312,6 +1317,8 @@ export default function PlayCanvasViewer({
gridMaterial.setParameter('uFadeStart', 0)
gridMaterial.setParameter('uFadeEnd', 0)
gridMaterial.setParameter('uResolution', 2)
gridMaterial.setParameter('uGridStep', fx.grid.step)
gridMaterial.setParameter('uGridRadius', fx.grid.diameter / 2)
const gridHalfExtents = new pc.Vec2(500, 500)
gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y])
gridMaterial.update()
@@ -1528,7 +1535,7 @@ export default function PlayCanvasViewer({
const cam = cameraEntityRef.current?.camera
const vertical = (cam?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1))
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1))
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
}
if (exposeSceneGraph || onSceneGraph) {
@@ -1617,7 +1624,7 @@ export default function PlayCanvasViewer({
if (!aabb) return
orbit.setState({
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
distance: Math.max(1.8, aabb.halfExtents.length() * 2.5),
distance: Math.max(1.8,aabb.halfExtents.length() / Math.sin(Math.min(14*Math.PI/180,Math.atan(Math.tan(14*Math.PI/180)*(cameraEntityRef.current?.camera?.aspectRatio??1))))*.88),
azimuthDeg: 45,
elevationDeg: 10,
})
@@ -1638,6 +1645,9 @@ export default function PlayCanvasViewer({
const gridVisible = !!fx.grid.enabled || !!fx.grid.dotsEnabled || !!fx.grid.crossEnabled
grid.enabled = gridVisible
grid.setLocalScale(fx.grid.diameter,1,fx.grid.diameter)
mat.setParameter('uGridStep',fx.grid.step)
mat.setParameter('uGridRadius',fx.grid.diameter/2)
const cX = toColor(fx.grid.colorX)
const cZ = toColor(fx.grid.colorZ)
const cMain = toColor(fx.grid.colorMain)
@@ -1661,6 +1671,7 @@ export default function PlayCanvasViewer({
mat.setParameter('uFadeEnd', Math.max(0, Number(fx.grid.fadeEnd) || 0))
mat.update()
}, [
fx.grid.step,fx.grid.diameter,
fx.grid.enabled,
fx.grid.colorX,
fx.grid.colorZ,
@@ -1690,7 +1701,7 @@ export default function PlayCanvasViewer({
const app = appRef.current
if (!app) return
setWireframeForScene(app, fx.rendering.wireframe)
}, [fx.rendering.wireframe])
}, [fx.rendering.wireframe,modelVersion])
useEffect(() => {
const frame: any = cameraFrameRef.current
@@ -1703,9 +1714,10 @@ export default function PlayCanvasViewer({
const app = appRef.current
if (!app) return
if (fx.lighting) {
app.scene.ambientLight = new pc.Color(fx.lighting.ambientIntensity,fx.lighting.ambientIntensity,fx.lighting.ambientIntensity)
app.scene.exposure = fx.lighting.exposure
}
}, [fx.lighting?.exposure])
}, [fx.lighting?.exposure,fx.lighting.ambientIntensity])
useEffect(() => {
const app = appRef.current
@@ -1924,6 +1936,8 @@ export default function PlayCanvasViewer({
envAtlasVersion,
skyboxVersion,
modelVersion,
materials,
assignments,
fx.envAtlas.enabled,
fx.envAtlas.background,
fx.envAtlas.reflection,
@@ -1,393 +1,2 @@
export type PostFxSettings = {
lighting: {
exposure: number
skyBoxIntensity: number
}
envAtlas: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
brightness: number
contrast: number
saturation: number
toneMapping: number
mip: number
rotation: number
}
skybox: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
mip: number
rotation: number
colorA: string
colorB: string
}
rendering: {
backgroundColor: string
wireframe: boolean
renderFormat: number
renderFormatFallback0: number
renderFormatFallback1: number
stencil: boolean
renderTargetScale: number
samples: number
sharpness: number
toneMapping: number
sceneColorMap: boolean
sceneDepthMap: boolean
fog: 'none' | 'linear' | 'exp' | 'exp2'
fogColor: string
fogRange: [number, number]
fogDensity: number
fogStart: number
fogEnd: number
}
grid: {
enabled: boolean
colorX: string
colorZ: string
colorMain: string
alphaX: number
alphaZ: number
alphaMain: number
dotsEnabled: boolean
dotsColor: string
dotsAlpha: number
dotsDiameter: number
crossEnabled: boolean
crossColor: string
crossAlpha: number
crossLength: number
crossWidth: number
fadeStart: number
fadeEnd: number
}
ssao: {
type: 'none' | 'lighting' | 'combine'
blurEnabled: boolean
intensity: number
radius: number
samples: number
power: number
minAngle: number
scale: number
}
bloom: {
enabled: boolean
intensity: number
lastMipLevel: number
}
chromaticAberration: {
enabled: boolean
intensity: number
}
taa: {
enabled: boolean
jitter: number
}
grading: {
enabled: boolean
brightness: number
contrast: number
saturation: number
tint: string
}
lut: {
intensity: number
textureUrl?: string | null
}
vignette: {
enabled: boolean
intensity: number
inner: number
outer: number
curvature: number
color: string
}
directionalLight: {
enabled: boolean
color: string
intensity: number
azimuth: number
elevation: number
castShadows: boolean
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
shadowCatcher: {
enabled: boolean
size: number
yOffset: number
lightIntensity: number
lightColor: string
lightAzimuth: number
lightElevation: number
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
}
export const DEFAULT_POSTFX: PostFxSettings = {
lighting: {
exposure: 1.21,
skyBoxIntensity: 0.86,
},
envAtlas: {
enabled: true,
background: false,
reflection: true,
intensity: 0.76,
reflectionIntensity: 0.6,
brightness: 1.65,
contrast: 1,
saturation: 1,
toneMapping: 0,
mip: 1,
rotation: 247,
},
skybox: {
enabled: false,
background: false,
reflection: true,
intensity: 0.62,
reflectionIntensity: 1,
mip: 0,
rotation: 0,
colorA: '#c5bfbf',
colorB: '#c7bcbc',
},
rendering: {
backgroundColor: '#111113',
wireframe: false,
renderFormat: 18,
renderFormatFallback0: 12,
renderFormatFallback1: 14,
stencil: false,
renderTargetScale: 1,
samples: 4,
sharpness: 0,
toneMapping: 4,
sceneColorMap: false,
sceneDepthMap: false,
fog: 'exp',
fogColor: '#dcc2ff',
fogRange: [0, 100],
fogDensity: 0.008,
fogStart: 0,
fogEnd: 100,
},
grid: {
enabled: true,
colorX: '#ffffff',
colorZ: '#ffffff',
colorMain: '#7a3cff',
alphaX: 0.18,
alphaZ: 0.18,
alphaMain: 0.6,
dotsEnabled: false,
dotsColor: '#ffffff',
dotsAlpha: 0.5,
dotsDiameter: 0.06,
crossEnabled: false,
crossColor: '#ffffff',
crossAlpha: 0.5,
crossLength: 0.5,
crossWidth: 0.06,
fadeStart: 0,
fadeEnd: 0,
},
ssao: {
type: 'none',
blurEnabled: true,
intensity: 0.5,
radius: 30,
samples: 12,
power: 6,
minAngle: 10,
scale: 1,
},
bloom: {
enabled: true,
intensity: 0.03,
lastMipLevel: 4,
},
chromaticAberration: {
enabled: true,
intensity: 30,
},
taa: {
enabled: false,
jitter: 1,
},
grading: {
enabled: true,
brightness: 0.837,
contrast: 1.1,
saturation: 1.126,
tint: '#ffffff',
},
lut: {
intensity: 1,
textureUrl: null,
},
vignette: {
enabled: true,
intensity: 1,
inner: 0.25,
outer: 1.52,
curvature: 0.78,
color: '#000000',
},
directionalLight: {
enabled: true,
color: '#ffffff',
intensity: 0.4,
azimuth: 0,
elevation: 0,
castShadows: false,
shadowIntensity: 0.5,
shadowDistance: 16,
shadowResolution: 1024,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
shadowCatcher: {
enabled: true,
size: 9,
yOffset: 0.001,
lightIntensity: 0.3,
lightColor: '#ffffff',
lightAzimuth: 20,
lightElevation: 60,
shadowIntensity: 0.29,
shadowDistance: 16,
shadowResolution: 2048,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
}
function isObject(value: any): value is Record<string, any> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
const merge = (target: any, source: any) => {
if (!isObject(source)) return
for (const [key, value] of Object.entries(source)) {
if (isObject(value)) {
if (!isObject(target[key])) target[key] = {}
merge(target[key], value)
} else {
target[key] = value
}
}
}
merge(out, raw)
const legacy: any = raw as any
if (legacy?.hdrLight) {
const src = legacy.hdrLight
const env = legacy?.envAtlas ?? {}
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
}
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
if (typeof legacy.hdrReflection.enabled === 'boolean') {
out.envAtlas.reflection = legacy.hdrReflection.enabled
}
}
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
}
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
out.envAtlas.brightness = 1
}
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
out.envAtlas.contrast = 1
}
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
out.envAtlas.saturation = 1
}
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
out.envAtlas.toneMapping = 0
}
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
out.skybox.reflectionIntensity = out.skybox.intensity
}
if (out.grid && typeof out.grid.enabled !== 'boolean') {
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
}
if (out.grid && typeof out.grid.colorX !== 'string') {
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
}
if (out.grid && typeof out.grid.colorZ !== 'string') {
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
}
if (out.grid && typeof out.grid.colorMain !== 'string') {
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
}
if (out.grid && typeof out.grid.alphaX !== 'number') {
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
}
if (out.grid && typeof out.grid.alphaZ !== 'number') {
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
}
if (out.grid && typeof out.grid.alphaMain !== 'number') {
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
}
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
}
if (out.grid && typeof out.grid.dotsColor !== 'string') {
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
}
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
}
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
}
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
}
if (out.grid && typeof out.grid.crossColor !== 'string') {
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
}
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
}
if (out.grid && typeof out.grid.crossLength !== 'number') {
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
}
if (out.grid && typeof out.grid.crossWidth !== 'number') {
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
}
return out as PostFxSettings
}
// Shared serializable contract; donor defaults remain available.
export * from '../../../core/roverScene/postFx';
@@ -0,0 +1,17 @@
import {useEffect,type RefObject} from 'react';
import * as pc from 'playcanvas';
export function useLutTexture(appRef:RefObject<pc.Application|null>,frameRef:RefObject<any>,textureRef:RefObject<pc.Texture|null>,url:string|null|undefined,ready:boolean,onError?:()=>void){
useEffect(()=>{
const app=appRef.current;let cancelled=false;
const clear=()=>{if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=null;frameRef.current.update?.();}textureRef.current?.destroy();textureRef.current=null;};
clear();if(!app||!ready||!url)return;
const img=new Image();img.onload=()=>{
if(cancelled)return;
if(img.width!==256||img.height!==16){onError?.();return;}
const texture=new pc.Texture(app.graphicsDevice,{name:'Rover color LUT',format:pc.PIXELFORMAT_SRGBA8,mipmaps:false,minFilter:pc.FILTER_LINEAR,magFilter:pc.FILTER_LINEAR,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});
texture.setSource(img);textureRef.current=texture;
if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=texture;frameRef.current.update?.();}
};img.onerror=()=>{if(!cancelled)onError?.();};img.src=url;
return()=>{cancelled=true;clear();};
},[appRef,frameRef,textureRef,url,ready,onError]);
}
@@ -0,0 +1,83 @@
import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas';
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;editing?:boolean;onMaterialPick?:(id:string,group:string)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,editing,onMaterialPick,onTextureState}:SceneMaterialsProps){
const latest=useRef({materials,onMaterialPick,onTextureState});latest.current={materials,onMaterialPick,onTextureState};
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
const generation=useRef(0);
const originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>());
const customMaterials=useRef(new Map<string,pc.StandardMaterial>());
useEffect(()=>{
const app=appRef.current;if(!app||!modelVersion||!materials)return;
const current=++generation.current;let pending=0,failed=false;
const map=new Map<string,pc.StandardMaterial>();
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
if(!(mi.material instanceof pc.StandardMaterial))continue;
if(!originalGroups.current.has(mi))originalGroups.current.set(mi,{id:mi.material.name,material:mi.material});
const source=originalGroups.current.get(mi)!;map.set(source.id,source.material);
}
for(const id of Object.keys(materials))if(id.startsWith('custom/')){
if(!customMaterials.current.has(id)){const m=new pc.StandardMaterial();m.name=id;customMaterials.current.set(id,m);}
map.set(id,customMaterials.current.get(id)!);
}
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(assignments?.[source.id]??source.id)??source.material;
}
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{
(m as any)[maps[slot]]=texture;
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update();
};
const used=new Set<string>();
for(const [id,spec] of Object.entries(materials)){
const m=map.get(id);if(!m)continue;
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
// Specular factor is independent from the donor's global IBL multiplier.
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
m.depthWrite=m.blendType===pc.BLEND_NONE;
for(const slot of Object.keys(maps) as TextureSlot[]){
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;}
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
let item=textures.current.get(key);
if(!item){
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
item={promise};textures.current.set(key,item);const cached=item;
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
}
if(item.texture)applyTexture(m,slot,item.texture,spec);
else{
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
}
}
m.update();
}
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
onTextureState?.(pending?'loading':'ready');
return()=>{generation.current++;};
},[materials,assignments,modelVersion,appRef,onTextureState]);
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
useEffect(()=>{
const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current;
if(!editing||!app||!canvas||!camera?.camera||!modelVersion)return;
const picker=new pc.Picker(app,1,1);let start:{x:number;y:number}|null=null;
const down=(e:PointerEvent)=>{start=e.button===0?{x:e.clientX,y:e.clientY}:null;};
const up=(e:PointerEvent)=>{
const p=start;start=null;if(!p||Math.hypot(p.x-e.clientX,p.y-e.clientY)>4)return;
const rect=canvas.getBoundingClientRect();picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height)));
picker.prepare(camera.camera!,app.scene);
const hit=picker.getSelection(e.clientX-rect.left,e.clientY-rect.top).find(mi=>!!latest.current.materials?.[mi.material.name]);
if(hit instanceof pc.MeshInstance){const source=originalGroups.current.get(hit);if(source)latest.current.onMaterialPick?.(hit.material.name,source.id);}
};
canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up);
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);picker.destroy();};
},[editing,modelVersion,appRef,cameraRef,canvasRef]);
}
@@ -2,19 +2,11 @@
.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__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
.rover-view__status { position:absolute; top:var(--nodedc-space-3); left:var(--nodedc-space-3); }
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; transform:scale(.8); transform-origin:bottom right; }
.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-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-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
@container (max-width: 380px) {
.rover-view__authority { top:48px; bottom:auto; }
}
.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-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 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; }
.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%;}
@@ -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";
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;
}) {
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 }) =>
<FieldFrame key={group} label={labels[group]}>
<Select label={`Модуль: ${labels[group]}`} disabled={disabled}
<InspectorSelectField key={group} label={labels[group]} disabled={disabled}
value={selection.selections.find((row) => row.group === group)?.module_id ?? ""}
options={options.map((module) => ({ value: module.moduleId, label: module.label }))}
onChange={(value) => {
@@ -20,7 +23,6 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }:
onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), {
group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults,
}] });
}} />
</FieldFrame>)}
}} />)}
</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 } 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) {
this.controls.setNavigation(enabled);
}
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 <>
{!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"}
loading={busy === "pause" || busy === "play"}
onClick={() => command(run.state === "running" ? "pause" : "play")}>
{run.state === "starting" ? "Подготовка…" : run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
</Button>
{run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
</Button> : null}
<Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"}
icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button>
</> : 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 { type AiRun } from "../../core/simulation/aiPolygon";
@@ -16,37 +15,42 @@ const REASONS: Record<string, string> = {
"goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон",
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 telemetry = run.telemetry;
const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0);
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"
? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error"
? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01
? "Ровер не движется" : 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="Управление симуляцией">
<div className="ai-polygon__telemetry-row">
<div className="ai-polygon__facts">
{run.state !== "ready" && run.state !== "running" || preparingModels || pending ? <StatusBadge tone={run.state === "failed" || run.state === "disconnected" ? "warning" : "neutral"}>
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : STATES[run.state]}
</StatusBadge> : null}
{telemetry && !terminal && run.state !== "stopping" && run.state !== "disconnected" ? <div className="ai-polygon__facts">
{run.state === "running" && !preparingModels && reason ? <strong>{reason}</strong> : null}
<span>Скорость: {Math.abs(telemetry.speed_mps).toFixed(2)} м/с</span>
<span>Время мира: {(telemetry.simulation_time_ns / 1e9).toFixed(1)} с</span>
{run.state === "running" ? <>
<span>Симуляция: {telemetry.rtf.toFixed(2)}×</span>
<span>Камера: {telemetry.sensor_fps.toFixed(1)} FPS</span>
<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>
<dl className="ai-polygon__run-metrics">
<div className="ai-polygon__run-metric ai-polygon__run-metric--status">
<dt>Состояние</dt><dd>
<StatusBadge tone={run.state === "failed" || run.state === "disconnected" || (run.state === "running" && telemetry?.decision?.reason === "stuck") ? "warning" : run.state === "running" && !preparingModels && !pending ? "success" : "neutral"}>
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : run.state === "running" && reason ? reason : STATES[run.state]}
</StatusBadge>
</dd>
</div>
{metrics.map(([label, value]) => <div className="ai-polygon__run-metric" key={label}>
<dt>{label}</dt><dd>{value}</dd>
</div>)}
</dl>
{run.state === "failed" && run.message ? <p>{run.message}</p> : null}
</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 { 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";
export function AiWorldSetup({ world, disabled, onSaved }: {
world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void;
}) {
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 [error, setError] = useState<string | null>(null);
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.camera_height_m, (v) => setDraft({ ...draft, camera_height_m: 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={() => {
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);
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));
}}>Сохранить старт и масштаб</Button>
{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 { 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 { 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";
// 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. */
export function AiWorldStream({ world, run, onBack, onChange, controls, headerActions, actionsHost }: {
world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode;
headerActions?: ReactNode; actionsHost?: HTMLElement | null;
}) {
const frame = useRef<HTMLDivElement>(null);
const video = useRef<HTMLVideoElement>(null);
const id = useId().replaceAll(":", "");
const frame = useRef<HTMLDivElement>(null), surface=useRef<HTMLDivElement>(null);
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 [revision, setRevision] = useState(0);
const [cameraError, setCameraError] = useState(false);
const [routeVisible, setRouteVisible] = useState(true);
const endpoint = run?.worker?.stream;
const terminal = !run || ["completed", "stopped", "failed"].includes(run.state);
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 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) => {
if (!run) return;
setCameraError(false);
@@ -99,35 +49,33 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
</div> : null}
{controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null}
<div className="ai-polygon__viewer">
<div className="ai-polygon__viewer-toolbar">
<SegmentedControl<AiCamera> label="Вид симуляции" size="dense" value={mode} onChange={changeCamera}
items={[{ value: "follow", label: "За ровером", disabled: terminal },
{ value: "overview", label: "Обзор", disabled: terminal }, { value: "camera", label: "Камера AI", disabled: terminal }]} />
<div className="ai-polygon__actions">
{connectable ? <StatusBadge tone={state === "live" ? "success" : "warning"}>
{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : "Ожидаем видео"}
</StatusBadge> : null}
<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}>
<Icon name={expanded ? "minimize" : "expand"} />
</IconButton>
</div>
</div>
<SimulationObservationDeck preview={preview}
toolbar={<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}><Icon name={expanded ? "minimize" : "expand"} /></IconButton>}
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>}>
<div className="ai-polygon__layer-options">
{run?.request?.purpose === "planning" ? <StatusBadge tone="neutral">Планирование маршрута</StatusBadge> : <Select<AiCamera> label="Вид симуляции" value={mode} onChange={changeCamera} options={cameraOptions} disabled={terminal} />}
{run?.telemetry?.route_overlay && run.request?.purpose !== "planning" ? <Checker label="Показывать маршрут" checked={routeVisible} onChange={setRouteVisible}/> : null}
</div>
</Dropdown>}
video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
<div className="ai-polygon__stream-picture">
{connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
<div className="ai-polygon__viewport">
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
<div className="ai-polygon__video" inert>
<video ref={video} id={`polygon-video-${id}`} autoPlay muted playsInline tabIndex={-1}
aria-label={`Видео симуляции ${world.name} с Worker`} />
<audio id={`polygon-audio-${id}`} muted />
{connectable&&endpoint&&state!=="failed"?<WorkerVideo key={`${run?.run_id}:${revision}`} endpoint={endpoint}
onState={(status,value)=>{setState(status);setFps(value);}}/>:null}
</div>
</LoadingRegion>
{!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null}
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div>
: connectable && (state === "failed" || state === "stalled") ? <div className="ai-polygon__preview-error" role="status">
<p>Видеопоток прерван. Состояние симуляции показано выше.</p>
<Button onClick={() => setRevision((value) => value + 1)}>Подключить видео</Button>
: connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
<p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
<Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
</div> : null}
</div>
</div>}/>
</div>
</div>;
}
@@ -0,0 +1,177 @@
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";
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 enabled=true;
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){this.enabled=enabled;if(!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>)}</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 {
Application,
Asset,
@@ -18,6 +19,7 @@ import {
type ModelComponent,
type ScriptType,
} from "playcanvas";
import type { AiRobot } from "../../core/simulation/aiPolygon";
import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs";
import {
@@ -76,24 +78,10 @@ const HOME_POSITION = new Vec3(0, 1, 0);
const HOME_FOCUS = new Vec3(1, 1, 0);
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 {
private app: Application | null = null;
private robotAsset: Asset | null = null;
private canvas: HTMLCanvasElement | null = null;
private camera: Entity | null = null;
private cameraController: CameraController | null = null;
@@ -155,7 +143,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
antialias: true,
alpha: false,
preserveDrawingBuffer: false,
powerPreference: "high-performance",
powerPreference: "default",
},
});
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 {
this.quality = quality;
this.applyQuality();
@@ -380,6 +389,7 @@ export class PlayCanvasRuntime implements SimulationRuntime {
this.unloadWorld();
this.ugvController?.dispose();
this.ugvController = null;
this.robotAsset?.unload(); this.robotAsset = null;
if (this.app) {
this.app.autoRender = 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,57 @@
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(()=>{runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime]);
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=>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,147 @@
import {useSimulationLayout} from "./useSimulationLayout";
import {useEffect,useRef,useState} from "react";
import {createPortal} from "react-dom";
import {Button,Icon,IconButton,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
import {URBAN_LABELS,availableUrbanClasses,visibleUrbanMap,type UrbanMap,type UrbanClassId} from "../../core/simulation/urbanMap";
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticDraft,semanticOperation,semanticRequest,undoSemantic,
type SemanticDraft,type SemanticOperation,type SemanticRevision,type Vertex} from "../../core/simulation/semanticEdits";
import 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 [revision,setRevision]=useState<SemanticRevision|null>(null);
const [draft,setDraft]=useState<SemanticDraft|null>(null);
const [error,setError]=useState<string|null>(null),[saving,setSaving]=useState(false);
const [loading,setLoading]=useState(true);
const [editing,setEditing]=useState(true);
const [layout,updateLayout]=useSimulationLayout();
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 attempt=useRef<{key:string;signature:string}|null>(null);
const current=useRef({draft,revision});current.current={draft,revision};
const accept=(value:SemanticRevision)=>{
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
throw new Error("Правки относятся к другой сцене.");
setRevision(value);setDraft(semanticDraft(value.edited));attempt.current=null;setSelected(null);
};
useEffect(()=>{
if(!active||revision)return;
const abort=new AbortController();
setLoading(true);setError(null);
void semanticRequest(worldId,undefined,abort.signal).then(accept)
.catch(e=>{if(!abort.signal.aborted)setError(e.message);})
.finally(()=>{if(!abort.signal.aborted)setLoading(false);});
return()=>abort.abort();
},[active,worldId,worldSha,revision]);
useEffect(()=>{if(active){setEditing(true);}},[active]);
useEffect(()=>{runtime.setSemanticSelection(active&&editing);viewport.dataset.semanticEditing=String(active&&editing);
return()=>{runtime.setSemanticSelection(false);delete viewport.dataset.semanticEditing;};},[runtime,viewport,active,editing]);
const operate=(op:SemanticOperation)=>{
if(busy||saving)return;
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||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||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();
}
};
document.addEventListener("keydown",keyboard,true);
return()=>document.removeEventListener("keydown",keyboard,true);
},[active,editing,busy,saving,preview,selection,layers,viewport,runtime,display]);
useEffect(()=>{
if(!draft?.operations.length)return;
const warn=(e:BeforeUnloadEvent)=>{e.preventDefault();};
window.addEventListener("beforeunload",warn);return()=>window.removeEventListener("beforeunload",warn);
},[draft?.operations.length]);
const save=async()=>{
const s=current.current;if(!s.draft?.operations.length||!s.revision||saving)return;
const body={expected_revision:s.revision.revision,model_sha256:s.revision.model_sha256,operations:s.draft.operations};
const signature=JSON.stringify(body);
if(attempt.current?.signature!==signature)attempt.current={signature,key:crypto.randomUUID()};
setSaving(true);setError(null);
try{accept(await semanticRequest(worldId,{...body,request_id:attempt.current.key}));}
catch(e){setError((e as Error).message);}
finally{setSaving(false);}
};
if(!active)return null;
const classes=availableUrbanClasses(display);
if(!classes.includes("road_marking"))classes.push("road_marking");
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=<>
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing}
onClick={()=>{setEditing(v=>!v);setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
{draft?.operations.length?<IconButton label="Сохранить правки" title="Сохранить правки" loading={saving} onClick={()=>void save()}><Icon name="save"/></IconButton>:null}
</>;
return <>
{headerHost?createPortal(controls,headerHost):null}
{!revision?<Button loading={loading} onClick={()=>{setLoading(true);setError(null);void semanticRequest(worldId).then(accept).catch(e=>setError(e.message)).finally(()=>setLoading(false));}}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
{revision?<SemanticTools viewport={viewport} editing={editing&&visible.user&&layers.length>0&&!busy&&!saving} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
area={layers.some(id=>["pedestrian_area","sidewalk"].includes(id))} template={template} setTemplate={id=>{setTemplate(id);setSelected(null);setTool("select");}}
selection={selection} map={display} operate={operate} remove={removeSelected} undo={undo} redo={redo} canUndo={!!draft?.operations.length} canRedo={!!draft?.future.length}
axis={axis} setAxis={setAxis} visible={visible} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
{createPortal(<div className="ai-local-editor__legend nodedc-scene-controls">
{classes.length?<SegmentedControl label="Видимые и редактируемые слои" selectionMode="multiple" value={layers} onChange={v=>{setLayers(v);setSelection(s=>s.filter(x=>v.includes(display.features.find(f=>f.id===x.feature_id)?.properties.class as UrbanClassId)));chooseTool("select");}}
items={classes.map(id=>({value:id,label:URBAN_LABELS[id]}))}/>:null}
</div>,viewport)}
<SemanticEditOverlay runtime={runtime} viewport={viewport} map={visibleUrbanMap(overlay,visible.user?layers:[])}
original={visible.model&&revision?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
editing={editing&&visible.user&&layers.length>0} blocked={busy||saving} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
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>
<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};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.model} onChange={model=>p.setVisible({...p.visible,model})}/>
<Checker label="Ручная разметка" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
</>)}, {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";
import { MeshoptSimplifier } from "meshoptimizer/simplifier";
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 UGV_SPAWN_POSITION = new Vec3(0, 1.15, 0);
@@ -230,6 +232,12 @@ export class SimulationUgvController {
private orbitIdleSeconds = 0;
private cameraOrbitInitialized = 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 vehicle: NativeRaycastVehicle | null = null;
private vehicleRaycaster: NativeObject | null = null;
@@ -251,6 +259,16 @@ export class SimulationUgvController {
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 {
return this.active;
}
@@ -269,9 +287,11 @@ export class SimulationUgvController {
async enable(collisionWorld: Entity): Promise<void> {
if (this.active) return;
await nextAnimationFrame();
if (this.disposed) return;
try {
await this.createStaticCollisionBodies(collisionWorld);
await nextAnimationFrame();
if (this.disposed) { this.disable(); return; }
this.spawnPosition.copy(this.findSafeSpawnPosition());
this.createVehicle();
this.attachInput();
@@ -302,6 +322,7 @@ export class SimulationUgvController {
}
dispose(): void {
this.disposed = true;
this.disable();
}
@@ -309,7 +330,7 @@ export class SimulationUgvController {
const vehicleEntity = this.vehicleEntity as (Entity & NativeRigidBodyAccess) | null;
const rigidbody = vehicleEntity?.rigidbody;
if (!vehicleEntity || !rigidbody) return;
rigidbody.teleport(this.spawnPosition, UGV_SPAWN_ROTATION);
rigidbody.teleport(this.spawnPosition, this.spawnRotation);
rigidbody.linearVelocity = ZERO;
rigidbody.angularVelocity = ZERO;
this.vehicle?.resetSuspension();
@@ -455,6 +476,11 @@ export class SimulationUgvController {
}
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();
this.updateCamera(deltaSeconds);
}
@@ -593,6 +619,7 @@ export class SimulationUgvController {
const rootInverse = collisionWorld.getWorldTransform().clone().invert();
for (let index = 0; index < meshInstances.length; index += 1) {
if (this.disposed) return;
const meshInstance = meshInstances[index];
const physicsMesh = createPhysicsProxyMesh(
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);
this.app.root.addChild(vehicle);
@@ -827,12 +863,12 @@ export class SimulationUgvController {
const heights: number[] = [];
let suitable = true;
for (const [sampleX, sampleZ] of footprint) {
const x = UGV_SPAWN_POSITION.x + offsetX + sampleX;
const z = UGV_SPAWN_POSITION.z + offsetZ + sampleZ;
from.set(x, 8, z);
to.set(x, -8, z);
const x = this.spawnGround.x + offsetX + sampleX;
const z = this.spawnGround.z + offsetZ + sampleZ;
from.set(x, this.spawnGround.y + 3, z);
to.set(x, this.spawnGround.y - 3, z);
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;
break;
}
@@ -843,8 +879,8 @@ export class SimulationUgvController {
const maximum = Math.max(...heights);
if (maximum - minimum > 0.32) continue;
const x = UGV_SPAWN_POSITION.x + offsetX;
const z = UGV_SPAWN_POSITION.z + offsetZ;
const x = this.spawnGround.x + offsetX;
const z = this.spawnGround.z + offsetZ;
const ground = heights.reduce((sum, height) => sum + height, 0) / heights.length;
const clearanceHeight = ground + dimensions.originHeight;
const origin = new Vec3(x, clearanceHeight, z);
@@ -855,10 +891,11 @@ export class SimulationUgvController {
if (!blocked) return new Vec3(x, ground + dimensions.originHeight, z);
}
return UGV_SPAWN_POSITION.clone();
throw new Error("В месте старта нет опоры для ровера. Выберите другую точку старта.");
}
private destroyVehicle(): void {
this.trackMotion = null;
if (this.vehicle && this.dynamicsWorld) {
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("keyup", this.onKeyUp, true);
window.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("blur", this.onWindowBlur);
this.canvas.addEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.addEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.addEventListener("pointerup", this.onOrbitPointerUp);
@@ -901,6 +939,7 @@ export class SimulationUgvController {
window.removeEventListener("keydown", this.onKeyDown, true);
window.removeEventListener("keyup", this.onKeyUp, true);
window.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("blur", this.onWindowBlur);
this.canvas.removeEventListener("pointerdown", this.onOrbitPointerDown);
this.canvas.removeEventListener("pointermove", this.onOrbitPointerMove);
this.canvas.removeEventListener("pointerup", this.onOrbitPointerUp);
@@ -965,7 +1004,7 @@ export class SimulationUgvController {
}
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;
event.preventDefault();
event.stopPropagation();
@@ -0,0 +1,34 @@
import { useState, type ReactNode, type RefObject } from "react";
import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { PlannerSettings } from "./PlannerSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function SimulationViewTools({expanded,toggle,semantic=false,planning=false,routeEditing=planning,boundsRef,children}: {expanded:boolean;toggle:()=>void;semantic?:boolean;planning?:boolean;routeEditing?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
const [prefs,update]=usePlannerPreferences();
const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState<string|null>(null);
return <>
<div className={`ai-simulation__view-tools nodedc-scene-controls ${planning?"ai-simulation__view-tools--planning":""}`}>
{!planning?children:null}
<div className="ai-simulation__display-tools">
{!semantic?<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
options={[{value:"low",label:"Низкое"},{value:"medium",label:"Среднее"},{value:"high",label:"Высокое"},{value:"ultra",label:"Ультра"},{value:"maximum",label:"Максимум"}]}
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>:null}
<IconButton label="Помощь по управлению" onClick={()=>setHelp(true)}><Icon name="info"/></IconButton>
{planning?<IconButton label="Настройки сцены" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
<IconButton label={expanded?"Свернуть просмотр":"Развернуть просмотр"} onClick={toggle}><Icon name={expanded?"minimize":"expand"}/></IconButton>
</div>
{planning?children:null}
</div>
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
<div className="ai-polygon__form">{planning?<>
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p>
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null}
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null}
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
</Window>
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</>;
}
@@ -258,7 +258,7 @@ export function SimulationViewport({
</StatusBadge>
<span>Engine 2.21.4</span>
</div>
<div className="simulation-viewport__controls">
<div className="simulation-viewport__controls nodedc-viewport-controls">
<Select
label="Качество Gaussian-сцены"
value={quality}
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from "react";
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
import { streamRecovery } from "../../core/simulation/streamRecovery";
export type WorkerVideoState="connecting"|"live"|"failed";
export function WorkerVideo({endpoint,onState}:{endpoint:AiStreamEndpoint;onState:(state:WorkerVideoState,fps:number|null)=>void}){
const frame=useRef<HTMLIFrameElement>(null),callback=useRef(onState);callback.current=onState;
const [attempt,setAttempt]=useState(0);
useEffect(()=>{
const started=performance.now();let lastFrame:number|null=null,failedAt:number|null=null,finished=false;
callback.current("connecting",null);
const receive=(e:MessageEvent)=>{
if(finished||e.origin!==location.origin||e.source!==frame.current?.contentWindow||e.data?.type!=="missioncore-worker-video")return;
if(e.data.state==="live"&&Number.isFinite(e.data.fps)){
lastFrame=performance.now();failedAt=null;callback.current("live",e.data.fps);
}else if(e.data.state==="failed")failedAt??=performance.now();
};
const timer=setInterval(()=>{
const action=streamRecovery(performance.now(),started,lastFrame,failedAt,attempt);
if(finished||action==="wait")return;
finished=true;
if(action==="retry")setAttempt(n=>n+1);else callback.current("failed",null);
},500);
window.addEventListener("message",receive);
return ()=>{finished=true;clearInterval(timer);window.removeEventListener("message",receive);};
},[attempt]);
return <iframe key={attempt} ref={frame} className="ai-polygon__video-frame" title="Видеопоток Worker"
src="/simulation-stream.html" allow="autoplay" tabIndex={-1}
onLoad={()=>frame.current?.contentWindow?.postMessage({type:"missioncore-worker-connect",endpoint},location.origin)}/>;
}
@@ -0,0 +1,20 @@
import { Mat4, Quat, Vec3 } from "playcanvas";
import { editorAssetUrl, type EditorCache } from "../../core/simulation/aiEditor";
import type { SimulationWorldManifest } from "../../core/simulation/projects";
/** Both local modes consume the same disk-backed assets and metric transforms. */
export function localScene(cache: EditorCache): SimulationWorldManifest {
const saved = cache.local_scene;
const matrix = (r: number[]) => new Mat4().setFromEulerAngles(r[0],r[1],r[2]);
const visual = saved ? matrix(saved.visual_rotation) : new Mat4().mul2(
matrix([-90,0,0]), new Mat4().setTRS(new Vec3(),
new Quat().setFromEulerAngles(...cache.world.settings.rotation_degrees),
new Vec3().set(cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit,cache.world.settings.meters_per_unit)));
return {
schemaVersion: "missioncore.simulation-world-manifest/v1", projectId: cache.world.world_id,
visual: { previewSogUrl: null, streamedSogUrl: saved?.visual_url ?? editorAssetUrl(cache.key,"scene.sog") },
collision: { meshUrl: saved ? saved.collision_url : editorAssetUrl(cache.key,"collision.glb"), available: saved ? !!saved.collision_url : true },
transforms: { worldFromVisual: Array.from(visual.data),
worldFromCollision: Array.from((saved ? matrix(saved.collision_rotation) : new Mat4()).data) },
};
}
@@ -0,0 +1,20 @@
import type {UrbanClassId,UrbanMap} from "../../core/simulation/urbanMap";
import {isRigidMarking,semanticMembers,semanticPivot,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import type {AiEditorRuntime} from "./AiEditorRuntime";
export type SemanticTool="select"|"insert"|"pen"|"rectangle";
export type SemanticChoice={vertex:Vertex;selection:Vertex[];wholeContour?:boolean;operation?:SemanticOperation};
export interface SemanticOverlayProps {
runtime:AiEditorRuntime;viewport:HTMLElement;map:UrbanMap;original:UrbanMap|null;layers:readonly UrbanClassId[];
selected:Vertex|null;selection:Vertex[];wholeContour?:boolean;editing:boolean;blocked:boolean;tool:SemanticTool;template:string|null;
axis:SemanticAxis;areaMode:"union"|"difference";
onSelect:(v:Vertex|null)=>void;onSelection:(v:Vertex[],wholeContour?:boolean)=>void;onChoose:(v:SemanticChoice[])=>void;
onPlaced:()=>void;onOperation:(op:SemanticOperation)=>void;onPreview:(op:SemanticOperation|null)=>void;
onError:(message:string)=>void;onExit:()=>void;
}
export function semanticAnchor(p:SemanticOverlayProps) {
const members=p.selected?semanticMembers(p.map,p.selected.feature_id):[];if(!members.length)return null;
if(isRigidMarking(members[0])||p.selected?.object)return semanticPivot(members);
const points=p.selection.flatMap(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);const q=f?knots(f,v.path)[v.index]?.point:null;return q?[q]:[];});
return points.length?[0,1,2].map(k=>points.reduce((n,q)=>n+q[k],0)/points.length):null;
}
@@ -0,0 +1,5 @@
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #000; }
body { display: grid; place-items: center; }
/* Round the decoded picture itself, including when the viewport letterboxes. */
video { display: block; width: 100%; height: 100%; object-fit: cover; }
audio { display: none; }
@@ -0,0 +1,54 @@
import { AppStreamer, StreamType, LogLevel, EventStatus } from "@nvidia/ov-web-rtc";
import { StreamDiagnostics } from "../../core/simulation/streamDiagnostics";
import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon";
import "@nodedc/tokens/tokens.css";
import "./streamFrame.css";
// A dedicated document owns NVIDIA's window-global handlers and peer connection.
// Removing this iframe releases them even if the SDK is stuck in STARTING.
const video=document.getElementById("worker-video") as HTMLVideoElement;
const fitVideo=(width:number,height:number)=>{
if(!(width>0&&height>0))return;
video.style.setProperty("--stream-width-for-height",`${100*width/height}vh`);
video.style.setProperty("--stream-height-for-width",`${100*height/width}vw`);
};
video.addEventListener("loadedmetadata",()=>fitVideo(video.videoWidth,video.videoHeight));
let started=false;
const report=(state:string,fps=0)=>window.parent.postMessage({type:"missioncore-worker-video",state,fps},location.origin);
window.addEventListener("message",(e:MessageEvent)=>{
if(started || e.source!==window.parent || e.origin!==location.origin || e.data?.type!=="missioncore-worker-connect")return;
started=true;
const endpoint=e.data.endpoint as AiStreamEndpoint;
fitVideo(endpoint.width,endpoint.height);
const diagnostics=new StreamDiagnostics();
let frames=0,measuredAt=performance.now(),decoded=0;
const frame:VideoFrameRequestCallback=(now,metadata)=>{
frames++;diagnostics.observeFrame(now,metadata);video.requestVideoFrameCallback(frame);
};
video.requestVideoFrameCallback(frame);
const timer=setInterval(()=>{
const now=performance.now();
// Presentation callbacks can be throttled independently of decoding in a
// background view. Prefer decoded, non-dropped video frames for telemetry.
const quality=video.getVideoPlaybackQuality?.();
const total=quality?quality.totalVideoFrames-quality.droppedVideoFrames:decoded+frames;
const count=Math.max(0,total-decoded);
const fps=count*1000/(now-measuredAt);
video.dataset.streamDiagnostics=JSON.stringify(diagnostics.snapshot(now,fps));
if(count>0)report("live",fps);
decoded=total;frames=0;measuredAt=now;
},1000);
const stream=new AppStreamer();
void stream.connect({streamSource:StreamType.DIRECT,logLevel:LogLevel.WARN,streamConfig:{
signalingServer:endpoint.server,signalingPort:endpoint.signaling_port,signalingPath:"/",
mediaServer:endpoint.server,mediaPort:endpoint.media_port,
width:endpoint.width,height:endpoint.height,fps:endpoint.fps,
videoElementId:"worker-video",audioElementId:"worker-audio",
autoLaunch:true,mic:false,enableAV1Support:false,fitStreamResolution:false,
maxReconnects:0,connectivityTimeout:5000,
onStart:event=>{if(event.status===EventStatus.ERROR||event.status===EventStatus.CANCELED)report("failed");},
onStop:()=>report("failed"),
onStreamStats:event=>diagnostics.observeNative(performance.now(),event.data?.stats),
}}).catch(()=>report("failed"));
window.addEventListener("pagehide",()=>{clearInterval(timer);delete video.dataset.streamDiagnostics;void stream.terminate(false).catch(()=>undefined);},{once:true});
});
@@ -0,0 +1,99 @@
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { sendAiPlanningCommand, type AiPlanningCommand, type AiRun } from "../../core/simulation/aiPolygon";
const motion = new Set(["orbit", "pan", "zoom", "fly"]);
const keys = new Set(["KeyW", "KeyA", "KeyS", "KeyD", "KeyQ", "KeyE", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ShiftLeft", "ShiftRight"]);
const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value));
/** Bounded operator intents only; Worker integrates and renders the camera. */
export function useAiPlanningControls(run: AiRun, onChange: (run: AiRun) => void, enabled: boolean) {
const current = useRef({ run, onChange, enabled }); current.current = { run, onChange, enabled };
const queue = useRef<AiPlanningCommand[]>([]);
const sending = useRef(false);
const alive = useRef(true);
const held = useRef(new Set<string>());
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const flush = async () => {
if (sending.current || !alive.current) return;
sending.current = true;
try {
while (queue.current.length && alive.current && current.current.enabled) {
const run = current.current.run;
if ((run.planning_sequence ?? 0) - (run.telemetry?.planning?.sequence ?? 0) >= 4) {
await new Promise((resolve) => setTimeout(resolve, 100));
continue;
}
const command = queue.current.shift()!;
const updated = await sendAiPlanningCommand(current.current.run, command);
if (alive.current) current.current.onChange(updated);
}
} catch (caught) {
queue.current = []; held.current.clear();
if (alive.current) setError(caught instanceof Error ? caught.message : "Не удалось изменить обзор.");
} finally {
sending.current = false;
if (alive.current) setBusy(false);
}
};
const send = (command: AiPlanningCommand) => {
if (!current.current.enabled) return;
// Do not accumulate motion while Worker is behind; subsequent key ticks retry.
const pending = (current.current.run.planning_sequence ?? 0) - (current.current.run.telemetry?.planning?.sequence ?? 0);
if (motion.has(command.action) && pending >= 4) return;
const previous = queue.current.at(-1);
if (command.action === "clip" && previous?.action === "clip") queue.current.pop();
else if (motion.has(command.action) && previous?.action === command.action) {
queue.current.pop();
command = { ...command, x: clamp((previous.x ?? 0) + (command.x ?? 0), 1),
y: clamp((previous.y ?? 0) + (command.y ?? 0), 1),
amount: clamp((previous.amount ?? 0) + (command.amount ?? 0), 3) };
}
if (queue.current.length >= 8) return;
queue.current.push(command); setBusy(true); setError(null); void flush();
};
const sender = useRef(send); sender.current = send;
const stopKeys = () => {
held.current.clear();
queue.current = queue.current.filter((command) => command.action !== "fly");
};
useEffect(() => {
alive.current = true;
const release = (event: globalThis.KeyboardEvent) => held.current.delete(event.code);
const hide = () => { if (document.hidden) stopKeys(); };
window.addEventListener("keyup", release); window.addEventListener("blur", stopKeys);
document.addEventListener("visibilitychange", hide);
let last = performance.now();
const timer = setInterval(() => {
const now = performance.now(), dt = Math.min(.12, (now-last)/1000); last = now;
const h = held.current;
if (!current.current.enabled || document.hidden || !h.size) return;
const pressed = (...codes: string[]) => Number(codes.some((code) => h.has(code)));
const x = pressed("KeyD", "ArrowRight")-pressed("KeyA", "ArrowLeft");
const y = pressed("KeyW", "ArrowUp")-pressed("KeyS", "ArrowDown");
const z = pressed("KeyE")-pressed("KeyQ");
const length = Math.hypot(x, y, z); if (!length) return;
const distance = dt * (pressed("ShiftLeft", "ShiftRight") ? 8 : 2.5) / length;
sender.current({ action: "fly", x: x*distance, y: y*distance, amount: z*distance });
}, 100);
return () => {
alive.current = false; clearInterval(timer); stopKeys(); queue.current = [];
window.removeEventListener("keyup", release); window.removeEventListener("blur", stopKeys);
document.removeEventListener("visibilitychange", hide);
};
}, []);
useEffect(() => { if (!enabled) { stopKeys(); queue.current = []; } }, [enabled]);
const keyDown = (event: KeyboardEvent<SVGSVGElement>) => {
if (keys.has(event.code)) {
event.preventDefault(); event.stopPropagation();
if (!held.current.has(event.code) && !event.code.startsWith("Shift")) {
const x = Number(["KeyD", "ArrowRight"].includes(event.code))-Number(["KeyA", "ArrowLeft"].includes(event.code));
const y = Number(["KeyW", "ArrowUp"].includes(event.code))-Number(["KeyS", "ArrowDown"].includes(event.code));
send({ action: "fly", x: x*.1, y: y*.1, amount: (Number(event.code === "KeyE")-Number(event.code === "KeyQ"))*.1 });
}
held.current.add(event.code);
}
else if (event.code === "Home") { event.preventDefault(); send({ action: "home" }); }
};
return { send, busy, error, keyDown, stopKeys };
}
@@ -0,0 +1,23 @@
import { useEffect, useState } from "react";
import { fetchEditor, prepareEditor, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWorld } from "../../core/simulation/aiPolygon";
export function useLocalScene(world: AiWorld, retry: number) {
const [cache,setCache] = useState<EditorCache | null>(null);
const [error,setError] = useState<string | null>(null);
useEffect(() => {
const abort = new AbortController(); let timer: ReturnType<typeof setTimeout>;
const poll = async (key?: string) => {
try {
const value = key ? await fetchEditor(key,abort.signal) : await prepareEditor(world,abort.signal);
if (abort.signal.aborted) return;
setCache(value);
if (value.status === "failed") setError(value.error);
else if (value.status !== "ready") timer = setTimeout(() => void poll(value.key),1000);
} catch (e) { if (!abort.signal.aborted) setError((e as Error).message); }
};
setCache(null); setError(null); void poll();
return () => { abort.abort(); clearTimeout(timer); };
}, [world.world_id,retry]);
return { cache,error,setError };
}
@@ -0,0 +1,59 @@
import { useEffect, type RefObject } from "react";
import { polygonRequest, type AiCamera } from "../../core/simulation/aiPolygon";
/** Bounded, coalesced operator input. Never forwards device/drive commands. */
export function useObserverInput(surface:RefObject<HTMLDivElement|null>,runId:string|undefined,mode:AiCamera,enabled:boolean,onError:()=>void) {
useEffect(()=>{
const element=surface.current;if(!element || !runId || !enabled)return;
const input={session:crypto.randomUUID().replaceAll("-",""),sequence:0,orbit:[0,0],move:[0,0,0],zoom:0};
let gesture:{id:number;x:number;y:number;pan:boolean}|null=null, dirty=false, sending=false, closed=false;
const keys=new Set<string>();
const allowed=new Set(["KeyW","KeyS","KeyA","KeyD","KeyQ","KeyE","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","ShiftLeft","ShiftRight"]);
const clamp=(v:number)=>Math.max(-9999,Math.min(9999,v));
const down=(e:PointerEvent)=>{
if((e.target as Element).closest('button,[role="button"],[role="slider"],.nodedc-select-anchor') || ![0,1,2].includes(e.button))return;
e.preventDefault();element.focus({preventScroll:true});
gesture={id:e.pointerId,x:e.clientX,y:e.clientY,pan:e.button!==0};element.setPointerCapture(e.pointerId);
};
const move=(e:PointerEvent)=>{
if(!gesture || gesture.id!==e.pointerId)return;
const dx=e.clientX-gesture.x,dy=e.clientY-gesture.y;gesture.x=e.clientX;gesture.y=e.clientY;
if(gesture.pan){input.move[0]=clamp(input.move[0]-dx*.02);input.move[2]=clamp(input.move[2]+dy*.02);}
else{input.orbit[0]=clamp(input.orbit[0]-dx*.005);input.orbit[1]=clamp(input.orbit[1]-dy*.005);}
dirty=true;
};
const end=()=>{gesture=null;};
const wheel=(e:WheelEvent)=>{
if((e.target as Element).closest('button,.nodedc-select-anchor'))return;
e.preventDefault();input.zoom=clamp(input.zoom+e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?element.clientHeight:1)*.0015);dirty=true;
};
const keyDown=(e:KeyboardEvent)=>{if(document.activeElement!==element || e.ctrlKey || e.metaKey || e.altKey || !allowed.has(e.code))return;e.preventDefault();keys.add(e.code);};
const keyUp=(e:KeyboardEvent)=>keys.delete(e.code);
const clear=()=>{keys.clear();end();};
const context=(e:Event)=>e.preventDefault();
element.addEventListener("pointerdown",down);element.addEventListener("pointermove",move);element.addEventListener("pointerup",end);element.addEventListener("pointercancel",end);
element.addEventListener("wheel",wheel,{passive:false});element.addEventListener("contextmenu",context);element.addEventListener("blur",clear);
window.addEventListener("keydown",keyDown);window.addEventListener("keyup",keyUp);window.addEventListener("blur",clear);
let last=performance.now();
const tick=window.setInterval(()=>{
const now=performance.now(),dt=Math.min(.15,(now-last)/1000);last=now;
if(mode==="overview" && keys.size && document.visibilityState==="visible") {
const pressed=(...codes:string[])=>Number(codes.some(k=>keys.has(k)));
const speed=dt*(pressed("ShiftLeft","ShiftRight")?16:4);
input.move[0]=clamp(input.move[0]+speed*(pressed("KeyD","ArrowRight")-pressed("KeyA","ArrowLeft")));
input.move[1]=clamp(input.move[1]+speed*(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown")));
input.move[2]=clamp(input.move[2]+speed*(pressed("KeyE")-pressed("KeyQ")));dirty=true;
}
if(!dirty || sending)return;
dirty=false;sending=true;input.sequence++;
void polygonRequest(`/runs/${runId}/view`,{method:"PUT",body:JSON.stringify({camera:mode,navigation:input})})
.catch(()=>{if(!closed){dirty=true;onError();}}).finally(()=>{sending=false;});
},100);
return ()=>{
closed=true;clearInterval(tick);clear();
element.removeEventListener("pointerdown",down);element.removeEventListener("pointermove",move);element.removeEventListener("pointerup",end);element.removeEventListener("pointercancel",end);
element.removeEventListener("wheel",wheel);element.removeEventListener("contextmenu",context);element.removeEventListener("blur",clear);
window.removeEventListener("keydown",keyDown);window.removeEventListener("keyup",keyUp);window.removeEventListener("blur",clear);
};
},[surface,runId,mode,enabled,onError]);
}
@@ -0,0 +1,20 @@
import { useSyncExternalStore } from "react";
import { DEFAULT_PLANNER_PREFERENCES, normalizePlannerPreferences, PLANNER_PREFERENCES_KEY, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
const listeners = new Set<() => void>();
let current = DEFAULT_PLANNER_PREFERENCES;
try { current = normalizePlannerPreferences(JSON.parse(localStorage.getItem(PLANNER_PREFERENCES_KEY) ?? "null")); } catch { /* Defaults remain usable if storage is unavailable. */ }
window.addEventListener("storage", (event) => {
if (event.key !== PLANNER_PREFERENCES_KEY) return;
try { current = normalizePlannerPreferences(JSON.parse(event.newValue ?? "null")); } catch { return; }
listeners.forEach((notify) => notify());
});
export function usePlannerPreferences() {
const value = useSyncExternalStore((notify) => { listeners.add(notify); return () => { listeners.delete(notify); }; }, () => current);
const update = (next: PlannerPreferences) => {
const valid = normalizePlannerPreferences(next);
// Persist before accepting, so a quota/privacy failure is visible to the caller.
localStorage.setItem(PLANNER_PREFERENCES_KEY, JSON.stringify(valid));
current = valid; listeners.forEach((notify) => notify());
};
return [value, update] as const;
}
@@ -0,0 +1,170 @@
import {curveControlScale,moveCurveControl} from "../../core/simulation/semanticCurveControls";
import {useEffect,useRef,useState} from "react";
import {isMarking,isRigidMarking,semanticOperation,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {semanticHits,semanticHitSelection} from "../../core/simulation/semanticPicking";
import {duplicateSide,editablePaths,knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import {regionOperation} from "../../core/simulation/semanticArea";
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
export function useSemanticGestures(props:SemanticOverlayProps) {
const latest=useRef(props);latest.current=props;
const [hover,setHover]=useState<string|null>(null),[ghost,setGhost]=useState<SemanticOperation|null>(null);
const [marquee,setMarquee]=useState<number[]|null>(null),[brush,setBrush]=useState<number[][]>([]);
useEffect(()=>{
const {runtime,viewport}=props,canvas=viewport.querySelector("canvas")!;
let generation=0,disposed=false,picking=false,pending:number[]|null=null,placing=false;
let shape:number[][]=[],rectangle:number[]|null=null,orbit:number|null=null;
let box:{id:number;start:number[];shift:boolean}|null=null;
let drag:{id:number;point:number[];start:number[];screen:number[];axis:SemanticAxis|"rotate";op:SemanticOperation|null;selected:Vertex;selection:Vertex[];map:SemanticOverlayProps["map"];handle?:"incoming"|"outgoing";handleScale?:number;handleStart?:number[];duplicate?:Vertex;copy?:{feature_id:string;new_feature_id:string}}|null=null;
const stop=(e:Event)=>{e.preventDefault();e.stopImmediatePropagation();};
const screen=(e:PointerEvent)=>{const r=canvas.getBoundingClientRect();return [e.clientX-r.left,e.clientY-r.top];};
const norm=(e:PointerEvent)=>{const xy=screen(e);return [xy[0]/canvas.clientWidth,xy[1]/canvas.clientHeight];};
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*canvas.clientWidth,q[1]*canvas.clientHeight]:null;};
const hits=(e:PointerEvent)=>semanticHits(latest.current.map,latest.current.layers,screen(e),project,latest.current.tool==="select",latest.current.selection.map(v=>v.feature_id));
const focus=()=>canvas.focus({preventScroll:true});
const place=(position:number[],id:string):Extract<SemanticOperation,{kind:"place"}>=>({kind:"place",feature_id:id,template_id:latest.current.template!,position,surface:"gaussian-visual"});
const pick=async()=>{
if(picking||!pending)return;const xy=pending;pending=null;picking=true;const version=generation;
try{const point=await runtime.pickSemanticSurface(xy[0],xy[1]);
if(!disposed&&version===generation&&latest.current.template)setGhost(point?place(point,"user-preview-placement"):null);
}catch{if(!disposed)setGhost(null);}finally{picking=false;if(pending&&!disposed)void pick();}
};
const release=(id:number)=>{if(viewport.hasPointerCapture(id))viewport.releasePointerCapture(id);};
const finish=(cancel:boolean)=>{
const d=drag;drag=null;latest.current.onPreview(null);
if(d){if(!cancel&&d.op)latest.current.onOperation(d.op);release(d.id);}
if(box){const id=box.id;box=null;release(id);}setMarquee(null);
runtime.setNavigation(!latest.current.blocked);
};
const commitShape=(points:number[][])=>{
try{const p=latest.current,f=p.map.features.find(f=>f.id===p.selected?.feature_id&&["pedestrian_area","sidewalk"].includes(f.properties.class));
p.onOperation(regionOperation(f,[...points,points[0]],p.areaMode));
}catch(e){latest.current.onError((e as Error).message);}
shape=[];rectangle=null;setBrush([]);
};
const beginDrag=(e:PointerEvent,p:SemanticOverlayProps,selected:Vertex,selection:Vertex[],activeAxis:SemanticAxis|"rotate",handle?:"incoming"|"outgoing")=>{
const f=p.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
const copy=e.shiftKey&&!handle&&activeAxis!=="rotate"&&isMarking(f)&&(isRigidMarking(f)||selected.object);
const duplicate=e.shiftKey&&!handle&&activeAxis!=="rotate"&&!copy&&!isRigidMarking(f);
if(duplicate&&selection.length!==1){stop(e);p.onError("Для продолжения сплайна выберите одну точку.");return;}
const point=semanticAnchor({...p,selected,selection});if(!point)return;
const [x,y]=norm(e),start=runtime.moveSemantic(point,x,y,activeAxis==="rotate"?"xy":activeAxis);if(!start)return;
stop(e);focus();drag={id:e.pointerId,point,start,screen:screen(e),axis:activeAxis,op:null,selected,selection,map:p.map,handle,
duplicate:duplicate?{feature_id:selected.feature_id,path:selected.path,index:selected.index}:undefined,
copy:copy?{feature_id:selected.feature_id,new_feature_id:`user-${crypto.randomUUID()}`}:undefined};
if(handle){const nodes=knots(f,selected.path);drag.handleScale=curveControlScale(nodes,selected.index,f.geometry.type==="Polygon",project);drag.handleStart=nodes[selected.index][handle];}
runtime.setNavigation(false);viewport.setPointerCapture(e.pointerId);
};
const down=(e:PointerEvent)=>{
const p=latest.current;if(!p.editing||p.blocked)return;
const target=e.target as Element,[x,y]=norm(e);
if(e.ctrlKey&&[0,2].includes(e.button)&&(target===canvas||target.closest("[data-semantic-axis],[data-semantic-handle]"))){
if(drag||box)return;
generation++;pending=null;setGhost(null);setHover(null);orbit=e.pointerId;
e.preventDefault();return; // Bubble to EditorCamera; never edit during this gesture.
}
if(e.button!==0)return;
const axis=target.closest<SVGElement>("[data-semantic-axis]")?.dataset.semanticAxis as SemanticAxis|"rotate"|undefined;
const handle=target.closest<SVGElement>("[data-semantic-handle]")?.dataset.semanticHandle as "incoming"|"outgoing"|undefined;
if((axis||handle)&&p.selected){
beginDrag(e,p,p.selected,p.selection,handle?"xy":axis!,handle);return;
}
if(e.target!==canvas)return;stop(e);focus();
if(p.template){
if(placing)return;placing=true;generation++;pending=null;const version=generation;
void runtime.pickSemanticSurface(x,y).then(point=>{
if(!disposed&&version===generation&&point){const op=place(point,`user-${crypto.randomUUID()}`);p.onOperation(op);p.onSelect({feature_id:op.feature_id,path:0,index:0,object:true});p.onPlaced();setGhost(null);}
}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
}
if(p.tool==="pen"||p.tool==="rectangle"){
if(shape.length>=128){p.onError("Замкните область: не более 128 точек за один контур.");return;}
const first=shape[0]?project(shape[0]):null;
if(p.tool==="pen"&&shape.length>=3&&first&&Math.hypot(screen(e)[0]-first[0],screen(e)[1]-first[1])<12){commitShape(shape);return;}
const version=generation;
if(p.tool==="rectangle"&&rectangle){const q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)commitShape([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]]]);return;}
if(placing)return;placing=true;
void runtime.pickSemanticSurface(x,y).then(point=>{if(!disposed&&version===generation&&point){
if(p.tool==="rectangle")rectangle=point;shape=[...shape,point];setBrush(shape);
}}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
}
const options=hits(e);
if(!options.length){box={id:e.pointerId,start:screen(e),shift:e.shiftKey};viewport.setPointerCapture(e.pointerId);return;}
const best=options[0],near=options.filter(c=>!!c.point===!!best.point&&c.distance<=best.distance+2);
const ids=[...new Set(near.map(c=>c.vertex.feature_id))];
const choice=(h:typeof best)=>{
const s=h.segment,t=s?s.start+(s.end-s.start)*runtime.semanticSegmentParameter(s.a,s.b,s.t):h.t;
const selection=p.tool==="select"?semanticHitSelection(p.map,h):[h.vertex],vertex=selection[0];
return {vertex,selection,wholeContour:p.tool==="select"&&!h.point&&!vertex.object,operation:p.tool==="insert"&&t>0&&t<1?{...h.vertex,kind:"insert" as const,t}:undefined};
};
if(ids.length>1){p.onChoose(ids.map(id=>choice(near.find(c=>c.vertex.feature_id===id)!)));return;}
const picked=choice(best),vertex=picked.vertex;
if(p.tool==="select"&&!best.point&&!vertex.object){
const selection=e.shiftKey?[...p.selection.filter(v=>!v.object),...picked.selection]:picked.selection;
p.onSelection([...new Map(selection.map(v=>[JSON.stringify(v),v])).values()],!e.shiftKey);
}else if(e.shiftKey&&p.tool==="select"&&!vertex.object){
const previous=p.selection.filter(v=>!v.object),exists=previous.some(v=>JSON.stringify(v)===JSON.stringify(vertex));p.onSelection(exists?previous.filter(v=>JSON.stringify(v)!==JSON.stringify(vertex)):[...previous,vertex]);
}else if(p.tool==="select"&&best.point){
const selected=!p.wholeContour&&p.selection.some(v=>!v.object&&v.feature_id===vertex.feature_id&&v.path===vertex.path&&v.index===vertex.index)?p.selection:[vertex];
p.onSelection(selected);beginDrag(e,p,vertex,selected,p.axis);
}else p.onSelect(vertex);
if(p.tool==="insert"&&choice(best).operation)p.onOperation(choice(best).operation!);
};
const move=(e:PointerEvent)=>{
if(orbit===e.pointerId)return;
const p=latest.current;
if(box&&e.pointerId===box.id){stop(e);setMarquee([...box.start,...screen(e)]);return;}
if(!drag){
if(!p.editing||p.blocked||e.target!==canvas){setHover(null);return;}
if(rectangle){const [x,y]=norm(e),q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)setBrush([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]],rectangle]);return;}
if(p.template){pending=norm(e);void pick();}else setHover(hits(e)[0]?.vertex.feature_id??null);return;
}
if(e.pointerId!==drag.id)return;if(p.blocked){finish(true);return;}stop(e);
if(Math.hypot(...screen(e).map((v,k)=>v-drag!.screen[k]))<2){drag.op=null;p.onPreview(null);return;}
const [x,y]=norm(e),q=runtime.moveSemantic(drag.point,x,y,drag.axis==="rotate"?"xy":drag.axis);if(!q)return;
const selected=drag.selected,selection=drag.selection,map=drag.map;
if(drag.handle){const f=map.features.find(f=>f.id===selected.feature_id)!;const node=knots(f,selected.path)[selected.index];
const value=moveCurveControl(drag.handleStart!,drag.start,q,drag.handleScale!);
drag.op={kind:"curve",...selected,incoming:drag.handle==="incoming"?value:node.incoming,outgoing:drag.handle==="outgoing"?value:node.outgoing};
}else if(drag.axis==="rotate"){
const angle=Math.atan2(q[1]-drag.point[1],q[0]-drag.point[0])-Math.atan2(drag.start[1]-drag.point[1],drag.start[0]-drag.point[0]);
drag.op={kind:"transform",feature_id:selected.feature_id,delta:[0,0],angle};
}else {
const delta=q.map((v,k)=>drag!.axis.includes("xyz"[k])?v-drag!.start[k]:0);
drag.op=drag.copy?{kind:"duplicate_marking",...drag.copy,axis:drag.axis,delta}:drag.duplicate?{kind:"duplicate_vertex",...drag.duplicate,axis:drag.axis,delta,
side:duplicateSide(knots(map.features.find(f=>f.id===drag!.duplicate!.feature_id)!,drag.duplicate.path),drag.duplicate.index,map.features.find(f=>f.id===drag!.duplicate!.feature_id)!.geometry.type==="Polygon",delta)}:
{kind:!selected.object?"translate_vertices":"translate",feature_id:selected.feature_id,vertices:selection.filter(v=>!v.object),axis:drag.axis,delta};
}
p.onPreview(drag.op);
};
const up=(e:PointerEvent)=>{
if(orbit===e.pointerId){orbit=null;return;}
if(box&&box.id===e.pointerId){stop(e);const p=latest.current,end=screen(e),start=box.start;
const selected:Vertex[]=box.shift?p.selection.filter(v=>!v.object):[];
if(Math.hypot(end[0]-start[0],end[1]-start[1])>3)for(const f of p.map.features){
if(!p.layers.includes(f.properties.class as typeof p.layers[number])||f.properties.review_status==="rejected"||isRigidMarking(f))continue;
editablePaths(f).forEach((path,j)=>path.slice(0,path.length-Number(f.geometry.type==="Polygon")).forEach((v,i)=>{
const q=project(v);if(q&&q.every((v,k)=>v>=Math.min(start[k],end[k])&&v<=Math.max(start[k],end[k])))selected.push({feature_id:f.id,path:j,index:i});
}));
}
p.onSelection([...new Map(selected.map(v=>[JSON.stringify(v),v])).values()]);finish(true);
}else if(drag&&e.pointerId===drag.id){stop(e);finish(false);}
};
const cancel=()=>{orbit=null;generation++;pending=null;finish(true);shape=[];rectangle=null;setBrush([]);setGhost(null);};
const key=(e:KeyboardEvent)=>{
const p=latest.current;if(!p.editing||p.blocked||e.defaultPrevented)return;
if(e.key==="Escape"){
// Dropdown gets the first Escape. Editor owns placement even after focus left canvas.
if(document.querySelector('[data-dropdown-lineage]'))return;
stop(e);
if(drag||box||shape.length||p.template||p.tool!=="select"){cancel();p.onPlaced();}
else if(p.selection.length)p.onSelection([]);else p.onExit();
}else if(e.key==="Enter"&&shape.length>=3){stop(e);commitShape(shape);}
};
const leave=()=>{if(!drag&&!box){generation++;pending=null;setGhost(null);setHover(null);}};
viewport.addEventListener("pointerdown",down,true);viewport.addEventListener("pointermove",move,true);viewport.addEventListener("pointerup",up,true);
viewport.addEventListener("pointercancel",cancel,true);viewport.addEventListener("pointerleave",leave);document.addEventListener("keydown",key,true);
window.addEventListener("blur",cancel);
return()=>{disposed=true;cancel();viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
},[props.runtime,props.viewport,props.editing,props.tool,props.template,props.layers]);
const ghostMap=ghost?semanticOperation({...props.map,features:[]},ghost):null;
return {hover,ghostMap,marquee,brush};
}
@@ -6,6 +6,7 @@ export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>)
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
const escape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return;
if (view.current.querySelector('[data-semantic-editing="true"], [role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
event.preventDefault();
event.stopPropagation();
void document.exitFullscreen().catch(() => undefined);
@@ -0,0 +1,22 @@
import {useSyncExternalStore} from "react";
import {normalizeSimulationLayout,normalizeSceneView,type SimulationLayout,type SceneView} from "../../core/simulation/simulationLayout";
const KEY="missioncore.simulation-layout/v1",SCENES="missioncore.simulation-cameras/v1";
const listeners=new Set<()=>void>();
function read(key:string){try{return JSON.parse(localStorage.getItem(key)??"null");}catch{return null;}}
let current=normalizeSimulationLayout(read(KEY));
export const getSimulationLayout=()=>current;
export function updateSimulationLayout(patch:Partial<SimulationLayout>){
const next=normalizeSimulationLayout({...current,...patch});
// UI choices stay usable in private/blocked storage; no edits or observations are stored here.
try{localStorage.setItem(KEY,JSON.stringify(next));}catch{/* Session-only fallback. */}
current=next;listeners.forEach(fn=>fn());
}
window.addEventListener("storage",e=>{if(e.key!==KEY&&e.key!==null)return;current=normalizeSimulationLayout(read(KEY));listeners.forEach(fn=>fn());});
export function useSimulationLayout(){return [useSyncExternalStore(fn=>{listeners.add(fn);return()=>{listeners.delete(fn);};},getSimulationLayout),updateSimulationLayout] as const;}
export function readSceneView(key:string){return normalizeSceneView(read(SCENES)?.[key]);}
export function writeSceneView(key:string,value:SceneView){
const valid=normalizeSceneView(value);if(!valid)return;
const old=read(SCENES),entries=old&&typeof old==="object"?Object.entries(old):[];
const next=Object.fromEntries([...entries.filter(([k,v])=>k!==key&&normalizeSceneView(v)).slice(-15),[key,valid]]);
try{localStorage.setItem(SCENES,JSON.stringify(next));}catch{/* Keep the live scene usable. */}
}
@@ -9,12 +9,14 @@ import { useComputeContours } from "../../core/system/ComputeContourContext";
interface SystemNavigationPanelProps {
title: string;
onAdd: () => void;
onNavigateRoot: () => void;
onClose: () => void;
}
export function SystemNavigationPanel({
title,
onAdd,
onNavigateRoot,
onClose,
}: SystemNavigationPanelProps) {
const { contours, selectedContour, selectContour } = useComputeContours();
@@ -40,7 +42,7 @@ export function SystemNavigationPanel({
description: contour.expected_node_id,
icon: <Icon name="apps" />,
active: selectedContour?.contour_id === contour.contour_id,
onSelect: () => selectContour(contour.contour_id),
onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
}))}
items={[]}
onItemChange={() => undefined}
@@ -5,7 +5,6 @@ import type { WorkspaceDefinition } from "../productModel";
interface ApplicationPanelActionsOptions {
definition: WorkspaceDefinition | null;
onAddVehicle?: () => void;
refreshRuntime: () => void;
resetConnectionScenario?: () => Promise<boolean>;
connectionScenarioResetting: boolean;
@@ -45,7 +44,6 @@ export function deviceRuntimeUtilityAction({
export function useApplicationPanelActions({
definition,
onAddVehicle,
refreshRuntime,
resetConnectionScenario,
connectionScenarioResetting,
@@ -56,7 +54,6 @@ export function useApplicationPanelActions({
}: ApplicationPanelActionsOptions): ApplicationPanelUtilityAction[] {
return useMemo(() => {
const actions: ApplicationPanelUtilityAction[] = [];
if (definition?.kind === "vehicles" && onAddVehicle) actions.push({ label: "Добавить аппарат", icon: "plus", onClick: onAddVehicle });
if (definition?.kind === "device") {
actions.push(deviceRuntimeUtilityAction({
refreshRuntime,
@@ -81,7 +78,6 @@ export function useApplicationPanelActions({
return actions;
}, [
definition,
onAddVehicle,
refreshRuntime,
resetConnectionScenario,
connectionScenarioResetting,
@@ -1,3 +1,4 @@
import {usbCanSensorUi} from '../../../../plugins/usb-can/frontend/src/plugin';
import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin';
import type { DeviceUiPlugin } from "../core/device-plugins/contracts";
import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin";
@@ -11,4 +12,4 @@ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([
// Node-executed camera controls use the existing sensor contribution contract;
// they do not register a desktop capture/AI runtime or a new product workspace.
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi]);
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi,usbCanSensorUi]);
@@ -2,42 +2,51 @@ import {useEffect,useState} from 'react';
export interface MetricDefinition {label:string;group:string;resource:string;unit:string;reason:string|null}
export interface BoardMonitor {
available:boolean;fresh:boolean;storage:string;source_id:string;
available:boolean;fresh:boolean;mode:'live';history_available:false;ttl_seconds:number;
source_id:string|null;
latest:{seq:number;at:number;boot_id:string;values:Record<string,number|null>}|null;
definitions:Record<string,MetricDefinition>;received_at:number;backlog:number;
database_bytes:number|null;database_budget_bytes:number;archive_since:number|null;
start:number;end:number;bucket_seconds:number;
series:{at:number;min:number|null;max:number|null;mean:number|null;count:number}[];
definitions:Record<string,MetricDefinition>;received_at:number|null;
sample_age_seconds:number|null;received_age_seconds:number|null;expires_in_seconds:number;
events:{at:number;code:string;kind:string;locations:string[]}[];
}
export function useBoardMonitor(vehicle:string,metric:string,window:number,end:number|null){
const [value,setValue]=useState<BoardMonitor|null>(null),[error,setError]=useState('');
export function ageBoardMonitor(value:BoardMonitor|null,elapsed:number):BoardMonitor|null {
if(!value)return null;
const age=Math.max(0,elapsed);
if(!value.available||!Number.isFinite(age)||age>=value.expires_in_seconds){
return {...value,available:false,fresh:false,latest:null,definitions:{},events:[],source_id:null,received_at:null,expires_in_seconds:0};
}
return {...value,fresh:value.fresh&&(value.sample_age_seconds??Infinity)+age<10&&(value.received_age_seconds??Infinity)+age<15};
}
export function useBoardMonitor(vehicle:string){
const [snapshot,setSnapshot]=useState<{vehicle:string;value:BoardMonitor;tick:number;wall:number}|null>(null);
const [error,setError]=useState(''),[loading,setLoading]=useState(true),[,setTick]=useState(0);
useEffect(()=>{
let active=true;let pending:AbortController|undefined;let timer:ReturnType<typeof setTimeout>|undefined;
setValue(null);setError('');
setSnapshot(null);setError('');setLoading(true);
// Expiry still reaches the screen when requests fail, hang, or a suspended tab resumes.
const expiry=setInterval(()=>setTick(value=>value+1),1000);
const read=async()=>{
const controller=new AbortController();pending=controller;
const started=performance.now(),wall=Date.now();
const deadline=setTimeout(()=>controller.abort(),12000);
try {
const query=new URLSearchParams({metric,window:String(window),...(end===null?{}:{end:String(end)})});
const response=await fetch(`/api/v1/fleet/${encodeURIComponent(vehicle)}/monitor?${query}`,{credentials:'same-origin',cache:'no-store',signal:controller.signal});
const response=await fetch(`/api/v1/fleet/${encodeURIComponent(vehicle)}/monitor`,{credentials:'same-origin',cache:'no-store',signal:controller.signal});
if(!response.ok)throw new Error('Мониторинг БК недоступен.');
const next=await response.json() as BoardMonitor;
if(active){setValue(next);setError('');}
if(next.mode!=='live'||next.history_available!==false||!Number.isFinite(next.expires_in_seconds)||next.expires_in_seconds<0||next.expires_in_seconds>30)throw new Error('Invalid live monitor contract');
if(active){setSnapshot({vehicle,value:next,tick:started,wall});setError('');}
}catch {if(active)setError('Не удалось обновить мониторинг БК.');}
finally {clearTimeout(deadline);if(active)timer=setTimeout(()=>void read(),5000);}
finally {clearTimeout(deadline);if(active){setLoading(false);timer=setTimeout(()=>void read(),5000);}}
};
void read();return()=>{active=false;pending?.abort();clearTimeout(timer);};
},[vehicle,metric,window,end]);
return {value,error,dismissError:()=>setError('')};
}
export function monitorSeries(value:BoardMonitor,mode:'min'|'max'|'mean') {
const count=Math.ceil((value.end-value.start)/value.bucket_seconds)+1;
const values:Array<number|null>=Array(Math.min(count,302)).fill(null);
const first=Math.floor(value.start/value.bucket_seconds)*value.bucket_seconds;
for(const point of value.series){const index=Math.round((point.at-first)/value.bucket_seconds);if(index>=0&&index<values.length)values[index]=point[mode];}
return values;
void read();return()=>{active=false;pending?.abort();clearTimeout(timer);clearInterval(expiry);};
},[vehicle]);
const current=snapshot?.vehicle===vehicle?snapshot:null;
const elapsed=current?Math.max(performance.now()-current.tick,Date.now()-current.wall)/1000:0;
return {value:ageBoardMonitor(current?.value??null,elapsed),error,loading,dismissError:()=>setError('')};
}
export function monitorValue(value:number|null|undefined,unit=''){
if(value==null||!Number.isFinite(value))return 'Нет измерения';
if(unit==='bytes'||unit==='bytes/s'){
@@ -0,0 +1,62 @@
import type {CellularNetwork,CellularStamp,TrackerTelemetry} from './vps';
export function cellularFresh(value:CellularStamp|undefined,now=Date.now()/1000){
return !!value&&now-value.measured_at>=0&&now-value.measured_at<90;
}
// Public INTERNAL TAG table examples. A serving network never selects an APN.
const networks:Record<string,string>={'250:1':'МТС','250:2':'МегаФон','250:99':'Билайн'};
export function cellularCardOperator(telemetry:TrackerTelemetry|undefined,slot:string){
const card=telemetry?.sim_identity?.slots[slot];
const home=card?.binding_current?card.known_card?.home_network:undefined;
return home?({'25001':'МТС','25002':'МегаФон','25099':'Билайн'} as Record<string,string>)[home]:undefined;
}
export function cellularOperator(value:CellularNetwork|undefined){
return value?.mcc==null?undefined:networks[`${value.mcc}:${value.mnc}`];
}
/** Losing freshness does not prove card removal; retain explicitly labelled history. */
export function cellularSimOptions(telemetry:TrackerTelemetry|undefined,now=Date.now()/1000){
const status=telemetry?.cellular?.status;
if(!status||status.measured_at>now)return [];
const current=!!telemetry?.online&&cellularFresh(status,now);
return (['1','2'] as const).filter(slot=>[1,2,3,5,6].includes(status!.sim_states[slot])).map(slot=>{
const network=telemetry?.cellular?.networks[slot];
const registered=[1,5].includes(status!.sim_states[slot]);
const knownNetwork=network&&network.measured_at<=now&&(current?cellularFresh(network,now):network.measured_at<=status.measured_at);
const operator=cellularCardOperator(telemetry,slot)??(registered&&knownNetwork?cellularOperator(network):undefined);
return {value:slot,label:`SIM ${slot} (${operator??'оператор не определён'})${current?'':' · последние данные'}`};
});
}
export function cellularSimCurrent(telemetry:TrackerTelemetry|undefined,slot:number,now=Date.now()/1000){
return !!telemetry?.online&&cellularFresh(telemetry.cellular?.status,now)&&[1,2,3,5,6].includes(telemetry.cellular!.status!.sim_states[String(slot)]);
}
export function cellularNetworkLabel(value:CellularNetwork|undefined){
if(!value||value.mcc===null)return 'Оператор не определён';
const code=`${String(value.mcc).padStart(3,'0')}-${String(value.mnc).padStart(2,'0')}`;
const name=cellularOperator(value);
return name?`${name} · ${code}`:`Оператор не определён · код ${code}`;
}
export function cellularSlotDescription(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const view=cellularSlotView(telemetry,slot,now);
if(view.absent)return 'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.';
const operator=cellularCardOperator(telemetry,slot);
if(operator)return operator;
if(view.current&&view.network?.mcc==null)return view.internet?'Интернет подключён. B2 ещё не передал код сети оператора.':'B2 ещё не передал код сети оператора.';
return cellularNetworkLabel(view.network);
}
export function cellularSlotView(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const status=telemetry?.cellular?.status;
const current=!!telemetry?.online&&cellularFresh(status,now);
const absent=current&&status?.sim_states[slot]===0;
// A fresh removal invalidates the old serving-network reading for this slot.
const network=absent?undefined:telemetry?.cellular?.networks[slot];
const selected=current&&!absent&&status?.active_sim===Number(slot);
const internet=selected&&status?.gsm_state===4;
const role=!current?'Последнее полученное состояние':absent?'SIM не обнаружена':internet?'Используется для интернета':selected?'Выбрана модемом':'Не выбрана для интернета';
return {current,absent,network,internet,role};
}
export function cellularSimLabel(value:number|undefined){
return ({0:'SIM не обнаружена',1:'Регистрация в домашней сети',2:'Поиск сети',3:'Регистрация отклонена',5:'Регистрация в роуминге',6:'Ошибка PIN'} as Record<number,string>)[value??-1]??'Нет сведений';
}
export function cellularModemLabel(value:number|undefined){
return ({0:'Модем выключен',1:'Модем включён',2:'Модем отвечает',3:'Подключение GPRS',4:'GPRS подключён'} as Record<number,string>)[value??-1]??'Нет сведений о модеме';
}
@@ -0,0 +1,29 @@
import type {EquipmentCommand,EquipmentNetworkOperation,IndependentDevice} from './equipment';
export interface CommandPreset {id:string;label:string;command:EquipmentCommand;wire:string;encoding:string;queue_seconds:number;confirmation:string;firmware:string;unavailable:string}
export interface CommandEvent {state:string;attempt?:number;stage?:string;observed_at:number;occurred_at?:number;historical:boolean}
export interface CommandEntry extends Omit<EquipmentNetworkOperation,'scope'> {sequence?:number;delivered_at?:number;delivery_seconds?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial<CommandPreset>;firmware?:string;queue_deadline?:number;finished_at?:number;updated_at?:number;reason?:string;events:CommandEvent[]}
export interface CommandRuntime {items:CommandEntry[];tracked_items:CommandEntry[];next_before:number|null;counts:Record<string,number>;catalog:CommandPreset[];device:IndependentDevice;capacity:number|null;durable_kinds?:string[]}
export const commandPending=(state:string)=>['waiting','submitting','queued','dispatched'].includes(state);
export const commandTracked=(entry:CommandEntry)=>commandPending(entry.state)||entry.reconcile_pending===true;
export const commandStatus=(state:string)=>({delivered:'Доставлено',accepted:'Принято B2',stopped:'Повторы остановлены',attempt_started:'Начата попытка',waiting:'В очереди Core',submitting:'Передача на VPS',queued:'В очереди VPS',dispatched:'Отправлено B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',reconnected:'Связь после перезапуска подтверждена',expired:'Срок истёк',unconfirmed:'Результат не подтверждён',uncertain:'Результат неизвестен',cancelled:'Отменено до отправки',rejected:'Отклонено',observed:'Прочитано',verified:'Настройки проверены',sim_selected:'SIM подключена',not_applied:'Не применено'} as Record<string,string>)[state]??'Неизвестный статус';
export const commandTone=(state:string):'success'|'warning'|'neutral'=>['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
export const commandDate=(value?:number)=>value===undefined?'—':new Date(value*1000).toLocaleString('ru-RU');
export const commandDuration=(value?:number)=>value===undefined?'—':`${value.toFixed(3)} с`;
export function mergeCommands(current:CommandEntry[],incoming:CommandEntry[]):CommandEntry[]{
const values=new Map(current.map(item=>[item.id,item]));for(const item of incoming){const old=values.get(item.id);if(!old||(item.updated_at??0)>=(old.updated_at??0))values.set(item.id,item);}
return [...values.values()].sort((a,b)=>(b.sequence??0)-(a.sequence??0));
}
export function commandReason(value:CommandEntry):string{
if(value.reason==='pulse_result_unknown')return 'Импульс был отправлен, но доставка не подтверждена. Автоматический повтор может вызвать второй импульс. Проверьте результат перед повторной отправкой.';
if(value.state==='expired'&&value.vps_created_at&&!value.dispatched_at)return 'VPS не дождался готового соединения с B2 до истечения срока. Команда трекеру не отправлена.';
return ({settings_changed:'Настройки изменились после запроса повтора. Команда не отправлена.',queue_deadline:'Время ожидания в Core истекло; передача на VPS не начиналась.',device_changed:'После постановки в очередь изменилось устройство или его привязка.',host_changed:'Изменилась привязка VPS.',operator_cancelled:'Оператор отменил команду до передачи на VPS.',historical_result_missing:'Окончательный результат этой старой операции не сохранился.'} as Record<string,string>)[value.reason??'']??'';
}
export function commandReceipt(value:CommandEntry):string{
if(value.delivered_at!==undefined)return 'Доставка команды подтверждена. Это не подтверждение переключения контактов выхода.';
if(value.device_code===undefined&&value.description?.encoding?.includes('FC'))return 'Текстовый ответ B2 не содержит идентификатора команды. Исполнение по такому ответу подтвердить нельзя.';
if(value.device_code===undefined)return 'Ответ трекера не получен';
return ({0:value.kind==='restart'?'B2 принял команду перезапуска':'B2 подтвердил команду без ошибки',1:'B2 не распознал команду',2:'Недостаточно аргументов',3:'Слишком много аргументов',4:'Некорректное значение аргумента',5:'B2 сообщил об ошибке выполнения',6:'B2 принял команду; требуется время на выполнение',7:'Очередь команд B2 заполнена',8:'Подключённое устройство недоступно',9:'Подключённое устройство не ответило'} as Record<number,string>)[value.device_code]??'Неизвестный ответ B2';
}
export const commandEntryStatus=(value:CommandEntry)=>value.durable&&commandPending(value.state)&&value.stop_requested?'Остановка повторов':value.durable&&commandPending(value.state)&&value.runtime_phase&&value.runtime_phase!=='executing'?({'waiting-link':'Ожидает связи с B2','retry-wait':'Ожидает следующей попытки','checking-result':'Проверка состояния B2',reconciling:'Уточнение результата у VPS'} as Record<string,string>)[value.runtime_phase]??commandStatus(value.state):value.state==='dispatched'&&value.device_accepted_at!==undefined?commandStatus('device_accepted'):commandStatus(value.state);

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