diff --git a/zlt-web/react-web-next/package.json b/zlt-web/react-web-next/package.json index e5ae8976..289aa9b2 100644 --- a/zlt-web/react-web-next/package.json +++ b/zlt-web/react-web-next/package.json @@ -15,8 +15,8 @@ "prebuild:test:mgnt": "npm run copy:cesium", "prebuild:pre:mgnt": "npm run copy:cesium", "prebuild:prod:mgnt": "npm run copy:cesium", - "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", - "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", + "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev", + "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev", "start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev", "start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build", @@ -24,7 +24,7 @@ "build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre API_PREFIX=http://119.45.169.13:9900 umi build", "build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod umi build", "build:test:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/mgnt API_PREFIX=https://test.goflytec.com umi build", - "build:pre:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/mgnt API_PREFIX=https://local.goflytec.com umi build", + "build:pre:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/mgnt API_PREFIX=https://yeehaitec.com umi build", "build:prod:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/mgnt umi build", "lint": "eslint --ext .ts,.tsx src", "tsc": "tsc --noEmit" diff --git a/zlt-web/yingyan/package.json b/zlt-web/yingyan/package.json index a1b172b0..df80a718 100644 --- a/zlt-web/yingyan/package.json +++ b/zlt-web/yingyan/package.json @@ -13,13 +13,13 @@ "prebuild:test": "npm run copy:cesium", "prebuild:pre": "npm run copy:cesium", "prebuild:prod": "npm run copy:cesium", - "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", - "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", + "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev", + "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev", "start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev", "start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build", "build:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/web API_PREFIX=https://test.goflytec.com umi build", - "build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/web API_PREFIX=https://local.goflytec.com umi build", + "build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/web API_PREFIX=https://yeehaitec.com umi build", "build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/web umi build", "lint": "eslint --ext .ts,.tsx src", "tsc": "tsc --noEmit" diff --git a/zlt-web/yingyan/public/chuan-model.glb b/zlt-web/yingyan/public/chuan-model.glb new file mode 100644 index 00000000..ec64c9a5 Binary files /dev/null and b/zlt-web/yingyan/public/chuan-model.glb differ diff --git a/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx index 9d9bf58c..8e371536 100644 --- a/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx +++ b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx @@ -1,5 +1,5 @@ -import React, { useEffect, useRef, useState, useCallback } from 'react'; -import { message } from 'antd'; +import React, { useEffect, useRef, useState, useCallback } from 'react'; +import { App } from 'antd'; import { useTilesetLoader } from '@/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader'; import { useCesiumRouteLibraryRenderer } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer'; import { useRoutePreview } from '../../hooks/useRoutePreview'; @@ -34,9 +34,12 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute const trackPositionsRef = useRef([]); const terrainLoadedRef = useRef(false); const sailingCameraStateRef = useRef(null); + const sailingInitialViewRouteRef = useRef(null); + const initRetryCountRef = useRef(0); + const { message: messageApi } = App.useApp(); const { loadTileset, unloadAllTilesets } = useTilesetLoader(); - const { isPreviewing, startPreview, stopPreview } = useRoutePreview({ viewerRef }); + const { isPreviewing, startPreview, stopPreview } = useRoutePreview({ viewerRef, messageApi }); // 预览状态变化时通知父组件 useEffect(() => { @@ -45,7 +48,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute const lastPreviewStopSignalRef = useRef(previewStopSignal); - // 外部停止通道:例如 HUD 点击”结束预览”时由父组件递增信号 + // 外部停止通道:例如 HUD 点击"结束预览"时由父组件递增信号 useEffect(() => { if (previewStopSignal == null) return; if (lastPreviewStopSignalRef.current === previewStopSignal) return; @@ -56,7 +59,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute } }, [previewStopSignal, isPreviewing, stopPreview]); - // 外部启动预览通道:LeftPanel 点击”预览航线”时由父组件递增信号 + // 外部启动预览通道:LeftPanel 点击"预览航线"时由父组件递增信号 const lastPreviewStartSignalRef = useRef(previewStartSignal); useEffect(() => { if (previewStartSignal == null) return; @@ -69,11 +72,11 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute if (waypoints && waypoints.length >= 2) { startPreview(waypoints, 2); } else { - message.warning('航点数据不足或未加载,无法预览'); + messageApi.warning('航点数据不足或未加载,无法预览'); } }, 300); return () => clearTimeout(timer); - }, [previewStartSignal, selectedRouteId, startPreview]); + }, [previewStartSignal, selectedRouteId, startPreview, messageApi]); // 航线渲染数据(含航点) const [routeRenderItems, setRouteRenderItems] = useState([]); @@ -85,12 +88,38 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute routes: routeRenderItems, }); + // 检查容器尺寸是否有效 + const isContainerValid = useCallback(() => { + if (!containerRef.current) return false; + const rect = containerRef.current.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0; + }, []); + // 初始化 Cesium(参考鹰眼 CesiumContainer 初始化模式) useEffect(() => { let destroyed = false; + let retryTimer: ReturnType | null = null; const initCesium = async () => { - if (!containerRef.current) return; + // 检查容器是否有效 + if (!containerRef.current) { + console.warn('[CenterView] 容器未就绪'); + return; + } + + // 关键修复:检查容器尺寸 + if (!isContainerValid()) { + console.warn('[CenterView] 容器尺寸无效,延迟初始化'); + if (initRetryCountRef.current < 10) { + initRetryCountRef.current++; + retryTimer = setTimeout(() => { + if (!destroyed) initCesium(); + }, 100); + } else { + console.error('[CenterView] 容器尺寸始终无效,初始化失败'); + } + return; + } if (!Cesium) { const cesiumModule = (window as any).Cesium || await import('cesium'); @@ -118,45 +147,70 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute if (destroyed) return; - const viewer = new Cesium.Viewer(containerRef.current, { - terrainProvider: new Cesium.EllipsoidTerrainProvider(), - scene3DOnly: false, - shouldAnimate: true, - animation: false, - timeline: false, - fullscreenButton: false, - geocoder: false, - homeButton: false, - sceneModePicker: false, - baseLayerPicker: false, - navigationHelpButton: false, - infoBox: false, - selectionIndicator: false, - requestRenderMode: true, - maximumRenderTimeChange: Infinity, - }); + // 再次检查容器尺寸(双重保险) + if (!isContainerValid()) { + console.warn('[CenterView] 初始化前容器尺寸再次检查失败'); + if (initRetryCountRef.current < 10) { + initRetryCountRef.current++; + retryTimer = setTimeout(() => { + if (!destroyed) initCesium(); + }, 100); + } + return; + } - // 移除默认图层,添加 ArcGIS 影像 - viewer.imageryLayers.remove(viewer.imageryLayers.get(0)); - viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b'); - viewer.imageryLayers.addImageryProvider( - new Cesium.UrlTemplateImageryProvider({ - url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', - minimumLevel: 0, - maximumLevel: 18, - }) - ); + try { + const viewer = new Cesium.Viewer(containerRef.current, { + terrainProvider: new Cesium.EllipsoidTerrainProvider(), + scene3DOnly: false, + shouldAnimate: true, + animation: false, + timeline: false, + fullscreenButton: false, + geocoder: false, + homeButton: false, + sceneModePicker: false, + baseLayerPicker: false, + navigationHelpButton: false, + infoBox: false, + selectionIndicator: false, + requestRenderMode: true, + maximumRenderTimeChange: Infinity, + }); - viewer.scene.globe.enableLighting = false; - viewer.scene.skyAtmosphere.show = true; + // 移除默认图层,添加 ArcGIS 影像 + viewer.imageryLayers.remove(viewer.imageryLayers.get(0)); + viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b'); + viewer.imageryLayers.addImageryProvider( + new Cesium.UrlTemplateImageryProvider({ + url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', + minimumLevel: 0, + maximumLevel: 18, + }) + ); - viewerRef.current = viewer; - setViewerReady(true); + viewer.scene.globe.enableLighting = false; + viewer.scene.skyAtmosphere.show = true; - // 隐藏 Cesium 水印 - const creditContainer = viewer.cesiumWidget?.creditContainer; - if (creditContainer) { - creditContainer.style.display = 'none'; + viewerRef.current = viewer; + setViewerReady(true); + initRetryCountRef.current = 0; // 重置重试计数 + + // 隐藏 Cesium 水印 + const creditContainer = viewer.cesiumWidget?.creditContainer; + if (creditContainer) { + creditContainer.style.display = 'none'; + } + + console.log('[CenterView] Cesium 初始化成功'); + } catch (error) { + console.error('[CenterView] Cesium 初始化失败:', error); + if (initRetryCountRef.current < 3) { + initRetryCountRef.current++; + retryTimer = setTimeout(() => { + if (!destroyed) initCesium(); + }, 500); + } } }; @@ -164,13 +218,19 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute return () => { destroyed = true; + if (retryTimer) clearTimeout(retryTimer); if (viewerRef.current && !viewerRef.current.isDestroyed()) { - unloadAllTilesets(viewerRef.current); - viewerRef.current.destroy(); + try { + unloadAllTilesets(viewerRef.current); + viewerRef.current.destroy(); + } catch (e) { + console.warn('[CenterView] Viewer 销毁时出错:', e); + } viewerRef.current = null; } + setViewerReady(false); }; - }, []); + }, [isContainerValid, unloadAllTilesets]); /** * 动态切换高程地形(参考鹰眼 switchToElevationTerrain) @@ -306,7 +366,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute loadModels(); return () => { cancelled = true; }; - }, [viewerReady, deviceSn]); + }, [viewerReady, deviceSn, switchToElevationTerrain, loadTileset, unloadAllTilesets, onModelCenter]); // 选中航线时加载航点详情并渲染 useEffect(() => { @@ -332,7 +392,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute routeDetailCacheRef.current.set(selectedRouteId, waypoints); } } catch { - message.error('线路详情加载失败'); + messageApi.error('线路详情加载失败'); return; } } @@ -345,38 +405,86 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute visible: true, highlighted: true, }]); - // 使用 useCesiumRouteLibraryRenderer 的 flyToRoute(基于 Rectangle,视角更可靠) - // 延迟一帧让 routeRenderItems 生效,entity 创建后再飞 - setTimeout(() => flyToRouteLibrary(selectedRouteId), 100); + // 普通浏览模式下飞到航线总览;执行/预览模式由专用相机逻辑接管 + if (!isSailing && !isPreviewing) { + setTimeout(() => flyToRouteLibrary(selectedRouteId), 100); + } } }; loadAndRender(); - }, [viewerReady, selectedRouteId]); + }, [viewerReady, selectedRouteId, routes, flyToRouteLibrary, isSailing, isPreviewing]); // 实时船位渲染 useEffect(() => { - if (!viewerReady || !Cesium || !boatData?.longitude || !boatData?.latitude) return; + if (!viewerReady || !Cesium) return; const viewer = viewerRef.current; if (!viewer || viewer.isDestroyed()) return; - const position = Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 2); - trackPositionsRef.current.push(position); - // 限制轨迹点数 - if (trackPositionsRef.current.length > 500) { - trackPositionsRef.current = trackPositionsRef.current.slice(-400); + let position: any = null; + let headingRad = 0; + let shouldTrack = false; + + if (boatData?.longitude && boatData?.latitude) { + position = Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 2); + headingRad = Cesium.Math.toRadians(boatData.heading || 0); + shouldTrack = true; + } else if (isSailing && selectedRouteId) { + const waypoints = routeDetailCacheRef.current.get(selectedRouteId) || []; + if (waypoints.length >= 1) { + const wp0 = waypoints[0]; + const wp1 = waypoints[1] || wp0; + const dLon = (wp1.longitude - wp0.longitude) * Math.PI / 180; + const lat1 = wp0.latitude * Math.PI / 180; + const lat2 = wp1.latitude * Math.PI / 180; + const y = Math.sin(dLon) * Math.cos(lat2); + const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); + headingRad = Math.atan2(y, x); + position = Cesium.Cartesian3.fromDegrees(wp0.longitude, wp0.latitude, 2); + } + } + + if (!position) { + if (boatEntityRef.current && !isSailing) { + try { + viewer.entities.remove(boatEntityRef.current); + } catch { /* ignore */ } + boatEntityRef.current = null; + } + return; + } + + const MODEL_HEADING_OFFSET = -Math.PI / 2; + const orientation = Cesium.Transforms?.headingPitchRollQuaternion + ? Cesium.Transforms.headingPitchRollQuaternion( + position, + new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0), + ) + : undefined; + + if (shouldTrack) { + trackPositionsRef.current.push(position); + // 限制轨迹点数 + if (trackPositionsRef.current.length > 500) { + trackPositionsRef.current = trackPositionsRef.current.slice(-400); + } } // 更新/创建船位 Entity if (!boatEntityRef.current) { boatEntityRef.current = viewer.entities.add({ position, - point: { - pixelSize: 12, - color: Cesium.Color.fromCssColorString('#00d4ff'), - outlineColor: Cesium.Color.WHITE, - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, + orientation, + model: { + uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`, + scale: 0.001, + minimumPixelSize: 64, + maximumScale: 200, + runAnimations: true, + colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, + color: Cesium.Color.WHITE, + silhouetteSize: 0, + heightReference: Cesium.HeightReference?.CLAMP_TO_3D_TILE || Cesium.HeightReference?.RELATIVE_TO_GROUND || undefined, }, label: { text: '当前位置', @@ -387,15 +495,16 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute outlineColor: Cesium.Color.BLACK, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, pixelOffset: new Cesium.Cartesian2(0, -16), - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + }, }); } else { boatEntityRef.current.position = position; + if (orientation) { + boatEntityRef.current.orientation = orientation; + } } // 轨迹线 - if (trackPositionsRef.current.length >= 2) { + if (shouldTrack && trackPositionsRef.current.length >= 2) { const trackId = 'client-boat-track'; let trackEntity = viewer.entities.getById(trackId); if (!trackEntity) { @@ -415,7 +524,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute } viewer.scene.requestRender(); - }, [viewerReady, boatData]); + }, [viewerReady, boatData, isSailing, selectedRouteId, routeRenderItems]); // 执行航线时第一视角跟踪(与预览模式相同的追踪相机) useEffect(() => { @@ -423,8 +532,19 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute const viewer = viewerRef.current; if (!viewer || viewer.isDestroyed()) return; + const setInitialSailingView = (waypoints: BoatWaypointDTO[]) => { + if (!selectedRouteId || !waypoints || waypoints.length < 2) return false; + try { + flyToRouteLibrary(selectedRouteId); + viewer.scene.requestRender(); + return true; + } catch { + return false; + } + }; + if (isSailing) { - // 首次进入执行模式:保存相机并定位到航线起点 + // 首次进入执行模式:保存相机,飞到第一个航点上方 if (!sailingCameraStateRef.current) { sailingCameraStateRef.current = { position: viewer.camera.position.clone(), @@ -432,36 +552,21 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute pitch: viewer.camera.pitch, roll: viewer.camera.roll, }; - - // 从缓存获取航线航点,定位到起点 - const waypoints = routeDetailCacheRef.current.get(selectedRouteId || ''); - if (waypoints && waypoints.length >= 2) { - const wp0 = waypoints[0]; - const wp1 = waypoints[1]; - // 计算起点到第二航点的航向 - const dLon = (wp1.longitude - wp0.longitude) * Math.PI / 180; - const lat1 = wp0.latitude * Math.PI / 180; - const lat2 = wp1.latitude * Math.PI / 180; - const y = Math.sin(dLon) * Math.cos(lat2); - const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); - const headingRad = Math.atan2(y, x); - - try { - const startPos = Cesium.Cartesian3.fromDegrees(wp0.longitude, wp0.latitude, 2); - const enu = Cesium.Transforms.eastNorthUpToFixedFrame(startPos); - const localUp = new Cesium.Cartesian3(0, 0, 0.8); - const target = Cesium.Matrix4.multiplyByPoint(enu, localUp, new Cesium.Cartesian3()); - viewer.camera.lookAt( - target, - new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(-20), 22), - ); - viewer.scene.requestRender(); - } catch { /* ignore */ } - return; // 首帧用起点位置,后续帧跟随 boatData - } + sailingInitialViewRouteRef.current = null; } - // 后续帧:跟随实际船位 + const waypoints = routeDetailCacheRef.current.get(selectedRouteId || ''); + if ((!boatData?.longitude || !boatData?.latitude) && waypoints && waypoints.length >= 2) { + if (sailingInitialViewRouteRef.current !== selectedRouteId) { + const ok = setInitialSailingView(waypoints); + if (ok) { + sailingInitialViewRouteRef.current = selectedRouteId || null; + } + } + return; + } + + // 有实际船位数据时:跟随船位 if (boatData?.longitude && boatData?.latitude) { try { const headingRad = Cesium.Math.toRadians(boatData.heading || 0); @@ -507,19 +612,20 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute }); } catch { /* ignore */ } sailingCameraStateRef.current = null; + sailingInitialViewRouteRef.current = null; } - }, [viewerReady, isSailing, boatData, selectedRouteId]); + }, [viewerReady, isSailing, boatData, selectedRouteId, routeRenderItems, flyToRouteLibrary]); // 预览选中航线(供外部调用,通过 ref 或直接调用) const handlePreviewRoute = useCallback(async () => { if (!selectedRouteId) return; const waypoints = routeDetailCacheRef.current.get(selectedRouteId); if (!waypoints || waypoints.length < 2) { - message.warning('航点数据不足,无法预览'); + messageApi.warning('航点数据不足,无法预览'); return; } await startPreview(waypoints, 2); - }, [selectedRouteId, startPreview]); + }, [selectedRouteId, startPreview, messageApi]); return (
diff --git a/zlt-web/yingyan/src/pages/client/hooks/useNavigationState.ts b/zlt-web/yingyan/src/pages/client/hooks/useNavigationState.ts index 5e0ad514..394800c5 100644 --- a/zlt-web/yingyan/src/pages/client/hooks/useNavigationState.ts +++ b/zlt-web/yingyan/src/pages/client/hooks/useNavigationState.ts @@ -5,7 +5,8 @@ * 暂停/恢复/结束:调用真实无人船控制API,携带missionCode */ import { useState, useCallback, useRef } from 'react'; -import { Modal, message } from 'antd'; +import { Modal } from 'antd'; +import type { MessageInstance } from 'antd/es/message/interface'; import { createBoatMission, pauseBoatMission, @@ -46,6 +47,8 @@ export function useNavigationState( selectedRouteId: string | null, setSelectedRouteId: (id: string | null) => void, routes: BoatRouteListVO[], + messageApi?: MessageInstance, + modalApi?: { confirm: (config: any) => void }, ): UseNavigationStateReturn { const [activeRoute, setActiveRoute] = useState({ mode: null, routeId: null }); const [isPaused, setIsPaused] = useState(false); @@ -64,12 +67,12 @@ export function useNavigationState( const handleStartSailing = useCallback(async (routeId: string) => { if (!deviceSn) { - message.error('设备SN缺失,无法开始航行'); + messageApi?.error('设备SN缺失,无法开始航行'); return; } const route = routes.find((r) => r.routeId === routeId); if (!route) { - message.error('航线信息不存在'); + messageApi?.error('航线信息不存在'); return; } @@ -88,13 +91,13 @@ export function useNavigationState( }); if (res.resp_code !== 0) { - message.error(res.resp_msg || '创建任务失败'); + messageApi?.error(res.resp_msg || '创建任务失败'); return; } const code = res.data?.missionCode; if (!code) { - message.error('任务创建成功但未返回任务编码'); + messageApi?.error('任务创建成功但未返回任务编码'); return; } @@ -104,45 +107,45 @@ export function useNavigationState( setSelectedRouteId(routeId); setIsPaused(false); setCurrentWaypointIndex(0); - message.success('航行任务已启动'); + messageApi?.success('航行任务已启动'); } catch (e: any) { - message.error(e?.message || '启动航行失败,请重试'); + messageApi?.error(e?.message || '启动航行失败,请重试'); } finally { setSailingLoading(false); } - }, [deviceSn, routes, activeRoute.mode, setSelectedRouteId]); + }, [deviceSn, routes, activeRoute.mode, setSelectedRouteId, messageApi]); const handlePauseSailing = useCallback(() => { if (!isSailing) return; const code = missionCodeRef.current; if (!code) { - message.warning('任务编码缺失,无法暂停'); + messageApi?.warning('任务编码缺失,无法暂停'); return; } setIsPaused(true); pauseBoatMission(deviceSn, code).catch(() => { - message.error('暂停指令发送失败'); + messageApi?.error('暂停指令发送失败'); setIsPaused(false); }); - }, [deviceSn, isSailing]); + }, [deviceSn, isSailing, messageApi]); const handleResumeSailing = useCallback(() => { if (!isSailing) return; const code = missionCodeRef.current; if (!code) { - message.warning('任务编码缺失,无法恢复'); + messageApi?.warning('任务编码缺失,无法恢复'); return; } setIsPaused(false); resumeBoatMission(deviceSn, code).catch(() => { - message.error('恢复航行指令发送失败'); + messageApi?.error('恢复航行指令发送失败'); setIsPaused(true); }); - }, [deviceSn, isSailing]); + }, [deviceSn, isSailing, messageApi]); const handleStopSailing = useCallback(() => { const code = missionCodeRef.current; - Modal.confirm({ + (modalApi || Modal).confirm({ title: '确认结束航行', content: '结束后将退出导航模式,返回线路选择', okText: '结束航行', @@ -155,12 +158,12 @@ export function useNavigationState( setMissionCode(null); if (code) { undoBoatMission(deviceSn, code).catch(() => { - message.warning('终止指令发送失败,但已退出导航模式'); + messageApi?.warning('终止指令发送失败,但已退出导航模式'); }); } }, }); - }, [deviceSn]); + }, [deviceSn, modalApi, messageApi]); const handleStopPreview = useCallback(() => { setPreviewStopSignal((prev) => prev + 1); @@ -175,11 +178,11 @@ export function useNavigationState( setMissionCode(null); if (code) { undoBoatMission(deviceSn, code).catch(() => { - message.warning('紧急停靠指令发送失败'); + messageApi?.warning('紧急停靠指令发送失败'); }); } - message.warning('已执行紧急停靠'); - }, [deviceSn]); + messageApi?.warning('已执行紧急停靠'); + }, [deviceSn, messageApi]); const handlePreviewChange = useCallback((previewing: boolean) => { setActiveRoute((prev) => { diff --git a/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts b/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts index a0f8cb5f..4295ebbc 100644 --- a/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts +++ b/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts @@ -3,11 +3,12 @@ * 从鹰眼 RouteEditor 中提取的预览动画逻辑,用于客户端页面航线预览 */ import { useState, useRef, useCallback, useEffect } from 'react'; -import { message } from 'antd'; +import type { MessageInstance } from 'antd/es/message/interface'; import type { BoatWaypointDTO } from '@/types/boatRoute'; export interface UseRoutePreviewOptions { viewerRef: React.RefObject; + messageApi?: MessageInstance; } export interface UseRoutePreviewReturn { @@ -16,15 +17,21 @@ export interface UseRoutePreviewReturn { stopPreview: () => void; } -export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoutePreviewReturn { +export function useRoutePreview({ viewerRef, messageApi }: UseRoutePreviewOptions): UseRoutePreviewReturn { const [isPreviewing, setIsPreviewing] = useState(false); const previewAnimationRef = useRef(null); const savedCameraStateRef = useRef(null); - const previewBoatPartsRef = useRef<{ hull?: any; cabin?: any; mast?: any; marker?: any } | null>(null); - const previewRouteEntityRef = useRef(null); + const previewBoatPartsRef = useRef<{ boat?: any } | null>(null); + const previewRouteEntitiesRef = useRef([]); + const previewTravelDistanceRef = useRef(0); const getCesium = useCallback(() => (window as any).Cesium, []); + // GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差) + const MODEL_HEADING_OFFSET = -Math.PI / 2; + const PREVIEW_ROUTE_HEIGHT_OFFSET = 0.05; + const PREVIEW_BOAT_HEIGHT_OFFSET = 0.14; + const PREVIEW_ROUTE_BOAT_CLEARANCE = 0; // 设置为 0,取消空隙,保证所有航点完全连线 // 计算两点间航向角 const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => { const dLon = (to.longitude - from.longitude) * Math.PI / 180; @@ -54,11 +61,8 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute try { const viewer = viewerRef?.current; if (viewer && !viewer.isDestroyed?.()) { - const { hull, cabin, mast, marker } = previewBoatPartsRef.current; - if (hull) viewer.entities.remove(hull); - if (cabin) viewer.entities.remove(cabin); - if (mast) viewer.entities.remove(mast); - if (marker) viewer.entities.remove(marker); + const { boat } = previewBoatPartsRef.current; + if (boat) viewer.entities.remove(boat); } } catch { /* ignore */ } finally { previewBoatPartsRef.current = null; @@ -66,16 +70,28 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute } // 清理预览航线实体 - if (previewRouteEntityRef.current) { + if (previewRouteEntitiesRef.current.length > 0) { try { const viewer = viewerRef?.current; if (viewer && !viewer.isDestroyed?.()) { - viewer.entities.remove(previewRouteEntityRef.current); + previewRouteEntitiesRef.current.forEach((entity) => { + if (entity) viewer.entities.remove(entity); + }); } } catch { /* ignore */ } finally { - previewRouteEntityRef.current = null; + previewRouteEntitiesRef.current = []; } } + previewTravelDistanceRef.current = 0; + + // 恢复主视图中的静态航线实体 + if (viewerRef?.current && !viewerRef.current.isDestroyed?.() && viewerRef.current.entities) { + viewerRef.current.entities.values.forEach((entity: any) => { + if (entity.properties && entity.properties.type && entity.properties.type.getValue() === 'route-library-path') { + entity.show = true; + } + }); + } // 恢复相机 if (savedCameraStateRef.current && viewerRef?.current) { @@ -104,7 +120,7 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute const applyOffset = (cartesian: any) => { try { const carto = Cesium.Cartographic.fromCartesian(cartesian); - carto.height = (Number(carto.height) || 0) + 0.05; + carto.height = (Number(carto.height) || 0) + PREVIEW_ROUTE_HEIGHT_OFFSET; return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height); } catch { return cartesian; } }; @@ -136,17 +152,18 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute } const above = cartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); + const ground = cartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, 0)); const clampFn = viewer.scene?.clampToHeightMostDetailed; - if (typeof clampFn !== 'function') return above.map(applyOffset); + if (typeof clampFn !== 'function') return ground.map(applyOffset); try { const clamped = await clampFn.call(viewer.scene, above); - const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]); + const merged = (clamped || []).map((p: any, idx: number) => p || ground[idx]); const okCount = (clamped || []).filter(Boolean).length; - if (okCount < 2) return above.map(applyOffset); + if (okCount < 2) return ground.map(applyOffset); return merged.map(applyOffset); } catch { - return above.map(applyOffset); + return ground.map(applyOffset); } }, [viewerRef, getCesium]); @@ -156,26 +173,24 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute const Cesium = getCesium(); if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!waypoints || waypoints.length < 2) { - message.warning('至少需要2个航点才能预览'); + messageApi?.warning('至少需要2个航点才能预览'); return; } if (isPreviewing) stopPreview(); - const polylinePositions = await buildPreviewPolyline(waypoints); - if (!Array.isArray(polylinePositions) || polylinePositions.length < 2) { - message.warning('模型瓦片加载中,请稍后再试预览'); + const rawPolylinePositions = await buildPreviewPolyline(waypoints); + const polylinePositions = Array.isArray(rawPolylinePositions) ? rawPolylinePositions.filter(Boolean) : []; + if (polylinePositions.length < 2) { + messageApi?.warning('模型瓦片加载中,请稍后再试预览'); return; } // 清理旧船只 if (previewBoatPartsRef.current) { try { - const { hull, cabin, mast, marker } = previewBoatPartsRef.current; - if (hull) viewer.entities.remove(hull); - if (cabin) viewer.entities.remove(cabin); - if (mast) viewer.entities.remove(mast); - if (marker) viewer.entities.remove(marker); + const { boat } = previewBoatPartsRef.current; + if (boat) viewer.entities.remove(boat); } catch { /* ignore */ } finally { previewBoatPartsRef.current = null; } @@ -190,25 +205,18 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute }; setIsPreviewing(true); - message.info('开始航线预览,按ESC退出'); + messageApi?.info('开始航线预览,按ESC退出'); + + // 隐藏主视图中的静态航线实体 + if (viewer.entities) { + viewer.entities.values.forEach((entity: any) => { + if (entity.properties && entity.properties.type && entity.properties.type.getValue() === 'route-library-path') { + entity.show = false; + } + }); + } // 添加可见的预览航线实体(确保第一视角能看到整条航线) - try { - const routeEntity = viewer.entities.add({ - polyline: { - positions: polylinePositions, - width: 6, - material: new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.4, - color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.9), - }), - depthFailMaterial: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.5), - clampToGround: false, - }, - }); - previewRouteEntityRef.current = routeEntity; - } catch { /* ignore */ } - const chaseRange = 22; const chasePitch = -20; const ellipsoid = Cesium.Ellipsoid?.WGS84; @@ -220,7 +228,7 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute } const totalDist = distances[distances.length - 1] || 0; if (totalDist <= 1) { - message.warning('航线过短,无法预览'); + messageApi?.warning('航线过短,无法预览'); setIsPreviewing(false); return; } @@ -237,74 +245,32 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute } catch { return origin; } }; - // 创建船只实体 + // 创建船只实体(GLB 模型) try { const firstPos0 = polylinePositions[0]; - const boatAboveRoute = 0.05; + const boatAboveRoute = PREVIEW_BOAT_HEIGHT_OFFSET; const firstPos = offsetUp(firstPos0, boatAboveRoute); const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion - ? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(0, 0, 0)) + ? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(MODEL_HEADING_OFFSET, 0, 0)) : undefined; - const hull = viewer.entities.add({ + const boat = viewer.entities.add({ position: firstPos, orientation: initialOrientation, - box: { - dimensions: new Cesium.Cartesian3(1.35, 0.5, 0.2), - material: Cesium.Color.fromCssColorString('#0B3D91').withAlpha(0.92), - outline: true, outlineColor: Cesium.Color.fromCssColorString('#E6F7FF').withAlpha(0.8), - shadows: Cesium.ShadowMode.DISABLED, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), + model: { + uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`, + scale: 0.001, + minimumPixelSize: 64, + maximumScale: 200, + runAnimations: true, + colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, + color: Cesium.Color.WHITE, + silhouetteSize: 0, }, }); - const cabinOffsetFn = (basePos: any, headingRad: number) => { - if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return basePos; - const enu = Cesium.Transforms.eastNorthUpToFixedFrame(basePos); - const localOffset = new Cesium.Cartesian3( - Math.sin(headingRad) * 0.25, Math.cos(headingRad) * 0.25, 0.16 - ); - return Cesium.Matrix4.multiplyByPoint(enu, localOffset, new Cesium.Cartesian3()); - }; - - const cabinPos = cabinOffsetFn(firstPos, 0); - const cabin = viewer.entities.add({ - position: cabinPos, orientation: initialOrientation, - box: { - dimensions: new Cesium.Cartesian3(0.55, 0.38, 0.24), - material: Cesium.Color.fromCssColorString('#F5F5F5').withAlpha(0.95), - outline: true, outlineColor: Cesium.Color.fromCssColorString('#FA8C16').withAlpha(0.85), - shadows: Cesium.ShadowMode.DISABLED, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), - }, - }); - - const mast = viewer.entities.add({ - position: cabinPos, orientation: initialOrientation, - cylinder: { - length: 0.38, topRadius: 0.015, bottomRadius: 0.015, - material: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.9), - shadows: Cesium.ShadowMode.DISABLED, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), - }, - }); - - const markerImageUrl = typeof Cesium.buildModuleUrl === 'function' - ? Cesium.buildModuleUrl('Assets/Textures/maki/ferry.png') - : '/cesium/Assets/Textures/maki/ferry.png'; - const marker = viewer.entities.add({ - position: offsetUp(firstPos0, boatAboveRoute + 0.12), - billboard: { - image: markerImageUrl, scale: 0.55, - verticalOrigin: Cesium.VerticalOrigin.BOTTOM, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar(20.0, 1.0, 200.0, 0.6), - }, - }); - - previewBoatPartsRef.current = { hull, cabin, mast, marker }; + previewBoatPartsRef.current = { boat }; (previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute; - (previewBoatPartsRef.current as any).cabinOffset = cabinOffsetFn; } catch (e) { console.warn('创建预览船只实体失败:', e); } @@ -339,6 +305,86 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute }; // 拐点检测 + const samplePositionAtDistance = (d: number) => { + const pos = new Cesium.Cartesian3(); + const carto = new Cesium.Cartographic(); + fillSampleAtDistance(d, pos, carto); + return pos; + }; + + const dedupePositions = (positions: any[]) => { + const result: any[] = []; + positions.forEach((pos) => { + if (!pos) return; + const prev = result[result.length - 1]; + if (!prev || Cesium.Cartesian3.distance(prev, pos) > 0.01) { + result.push(pos); + } + }); + return result; + }; + + const buildSegmentPositions = (startDistance: number, endDistance: number) => { + const clampedStart = Math.max(0, Math.min(totalDist, startDistance)); + const clampedEnd = Math.max(0, Math.min(totalDist, endDistance)); + if (clampedEnd - clampedStart <= 0.05) return []; + + const positions: any[] = []; + positions.push(clampedStart <= 0.01 ? polylinePositions[0] : samplePositionAtDistance(clampedStart)); + + const startIdx = Math.max(1, findIndexByDistance(clampedStart)); + const endIdx = Math.min(polylinePositions.length - 1, findIndexByDistance(clampedEnd)); + for (let i = startIdx; i < endIdx; i++) { + positions.push(polylinePositions[i]); + } + + positions.push( + clampedEnd >= totalDist - 0.01 + ? polylinePositions[polylinePositions.length - 1] + : samplePositionAtDistance(clampedEnd) + ); + + return dedupePositions(positions); + }; + + previewTravelDistanceRef.current = 0; + + try { + const polylineStyle = { + width: 6, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.4, + color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.9), + }), + depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.4, + color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.9), + }), + clampToGround: false, + }; + const routeBeforeEntity = viewer.entities.add({ + polyline: { + ...polylineStyle, + positions: new Cesium.CallbackProperty( + () => buildSegmentPositions(0, previewTravelDistanceRef.current - PREVIEW_ROUTE_BOAT_CLEARANCE), + false, + ), + }, + }); + + const routeAfterEntity = viewer.entities.add({ + polyline: { + ...polylineStyle, + positions: new Cesium.CallbackProperty( + () => buildSegmentPositions(previewTravelDistanceRef.current + PREVIEW_ROUTE_BOAT_CLEARANCE, totalDist), + false, + ), + }, + }); + + previewRouteEntitiesRef.current = [routeBeforeEntity, routeAfterEntity]; + } catch { /* ignore */ } + const turnAngleThresholdDeg = 12; const turnHoldMs = 200; const turnRotateMs = 650; @@ -400,9 +446,11 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute } } + previewTravelDistanceRef.current = traveled; + if (traveled >= totalDist) { stopPreview(); - message.success('航线预览完成'); + messageApi?.success('航线预览完成'); return; } @@ -428,19 +476,15 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute // 更新船只位置 try { if (previewBoatPartsRef.current) { - const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.05; + const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || PREVIEW_BOAT_HEIGHT_OFFSET; const basePos = offsetUp(scratchPosCur, boatAboveRoute); const orientation = Cesium.Transforms?.headingPitchRollQuaternion - ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0)) + ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0)) : undefined; - const { hull, cabin, mast } = previewBoatPartsRef.current; - if (hull) { hull.position = basePos; if (orientation) hull.orientation = orientation; } - const cabinOffsetFn = (previewBoatPartsRef.current as any).cabinOffset; - const cabinPos = typeof cabinOffsetFn === 'function' ? cabinOffsetFn(basePos, headingRad) : basePos; - if (cabin) { cabin.position = cabinPos; if (orientation) cabin.orientation = orientation; } - if (mast) { mast.position = cabinPos; if (orientation) mast.orientation = orientation; } - if (previewBoatPartsRef.current.marker) { - previewBoatPartsRef.current.marker.position = offsetUp(scratchPosCur, boatAboveRoute + 0.12); + const { boat } = previewBoatPartsRef.current; + if (boat) { + boat.position = basePos; + if (orientation) boat.orientation = orientation; } } } catch { /* ignore */ } @@ -470,7 +514,7 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute const handleEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') stopPreview(); }; window.addEventListener('keydown', handleEsc); (previewAnimationRef as any).escHandler = handleEsc; - }, [viewerRef, getCesium, isPreviewing, stopPreview, calculateHeading, buildPreviewPolyline]); + }, [viewerRef, getCesium, isPreviewing, stopPreview, calculateHeading, buildPreviewPolyline, messageApi]); // 组件卸载清理 useEffect(() => { @@ -483,26 +527,26 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute try { const viewer = viewerRef?.current; if (viewer && !viewer.isDestroyed?.()) { - const { hull, cabin, mast, marker } = previewBoatPartsRef.current; - if (hull) viewer.entities.remove(hull); - if (cabin) viewer.entities.remove(cabin); - if (mast) viewer.entities.remove(mast); - if (marker) viewer.entities.remove(marker); + const { boat } = previewBoatPartsRef.current; + if (boat) viewer.entities.remove(boat); } } catch { /* ignore */ } finally { previewBoatPartsRef.current = null; } } - if (previewRouteEntityRef.current) { + if (previewRouteEntitiesRef.current.length > 0) { try { const viewer = viewerRef?.current; if (viewer && !viewer.isDestroyed?.()) { - viewer.entities.remove(previewRouteEntityRef.current); + previewRouteEntitiesRef.current.forEach((entity) => { + if (entity) viewer.entities.remove(entity); + }); } } catch { /* ignore */ } finally { - previewRouteEntityRef.current = null; + previewRouteEntitiesRef.current = []; } } + previewTravelDistanceRef.current = 0; if (savedCameraStateRef.current && viewerRef?.current) { const viewer = viewerRef.current; const Cesium = (window as any).Cesium; diff --git a/zlt-web/yingyan/src/pages/client/index.tsx b/zlt-web/yingyan/src/pages/client/index.tsx index 471bb684..82dfa98c 100644 --- a/zlt-web/yingyan/src/pages/client/index.tsx +++ b/zlt-web/yingyan/src/pages/client/index.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useCallback, useState, useRef, useMemo } from 'react'; -import { ConfigProvider, Button, Spin } from 'antd'; +import { App as AntdApp, ConfigProvider, Button, Spin, message, Modal } from 'antd'; import { LogoutOutlined, DisconnectOutlined, @@ -45,6 +45,8 @@ const formatElapsed = (totalSec: number) => { }; const ClientPage: React.FC = () => { + const [messageApi, messageContextHolder] = message.useMessage(); + const [modalApi, modalContextHolder] = Modal.useModal(); // ── 认证 ── const { boatData: sseBoatData, sseConnected, loading: sseLoading, deviceOffline, connectSSE, disconnectSSE } = useClientSSE(); const { deviceSn, deviceInfo, handleLogout } = useClientAuth(disconnectSSE); @@ -72,7 +74,7 @@ const ClientPage: React.FC = () => { handleStopPreview, handleEmergencyStop, handlePreviewChange, - } = useNavigationState(deviceSn, selectedRouteId, setSelectedRouteId, routes); + } = useNavigationState(deviceSn, selectedRouteId, setSelectedRouteId, routes, messageApi, modalApi); // ── SSE 连接 ── useEffect(() => { @@ -178,6 +180,9 @@ const ClientPage: React.FC = () => { return ( + + {messageContextHolder} + {modalContextHolder}
{/* ========== 普通模式 - 顶部导航栏 ========== */} @@ -362,6 +367,7 @@ const ClientPage: React.FC = () => {
+ ); }; diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx index 4744450e..5db5999b 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx @@ -457,11 +457,11 @@ const LayerPanel: React.FC = ({ // 忽略 } - const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)); + const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).filter(Boolean); if (positions.length < 3) return; const holes = poly.holes - .map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0))) + .map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).filter(Boolean)) .filter((ring) => ring.length >= 3) .map((ring) => new Cesium.PolygonHierarchy(ring)); diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx index 2f9d4e1c..c3c2952e 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx @@ -490,11 +490,13 @@ const TaskPanel: React.FC = ({ ? Cesium.Color.fromCssColorString('#52c41a').withAlpha(0.9) // 绿色 - 无人船 : Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9); // 蓝色 - 无人机 - // 绘制航线 + // 绘制航线(确保 positions 不含 undefined/null 值) + const validPolylinePositions = polylinePositions.filter(Boolean); + if (validPolylinePositions.length < 2) return; waylineEntityRef.current = viewer.entities.add({ name: isBoatRoute ? '无人船航线' : '无人机航线', polyline: { - positions: polylinePositions, + positions: validPolylinePositions, width: 6, material: routeColor, clampToGround: false, // 已经手动贴地,不需要clampToGround diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts index 662c537b..7a22657c 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts @@ -39,6 +39,9 @@ export function useCesiumBoatTrack({ return (window as any).Cesium; }, []); + // GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差) + const MODEL_HEADING_OFFSET = -Math.PI / 2; + /** * 飞到无人船位置 */ @@ -170,6 +173,13 @@ export function useCesiumBoatTrack({ realtimePosition.latitude, 0 // 无人船在水面,高度为0 ); + const headingRad = Cesium.Math.toRadians(realtimePosition.heading || 0); + const orientation = Cesium.Transforms?.headingPitchRollQuaternion + ? Cesium.Transforms.headingPitchRollQuaternion( + position, + new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0) + ) + : undefined; // 构建标签文本 const labelText = [ @@ -182,19 +192,26 @@ export function useCesiumBoatTrack({ // 更新或创建船位置Entity if (boatEntityRef.current) { boatEntityRef.current.position = position; + if (orientation) { + boatEntityRef.current.orientation = orientation; + } if (boatEntityRef.current.label) { boatEntityRef.current.label.text = labelText; } } else { boatEntityRef.current = viewer.entities.add({ name: '无人船实时位置', - position: position, - point: { - pixelSize: 16, - color: Cesium.Color.BLUE, - outlineColor: Cesium.Color.WHITE, - outlineWidth: 3, - disableDepthTestDistance: Number.POSITIVE_INFINITY, + position, + orientation, + model: { + uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`, + scale: 0.001, + minimumPixelSize: 64, + maximumScale: 200, + runAnimations: true, + colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, + color: Cesium.Color.WHITE, + silhouetteSize: 0, }, label: { text: labelText, @@ -204,7 +221,7 @@ export function useCesiumBoatTrack({ outlineWidth: 2, outlineColor: Cesium.Color.BLACK, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, - pixelOffset: new Cesium.Cartesian2(0, -20), + pixelOffset: new Cesium.Cartesian2(0, -28), disableDepthTestDistance: Number.POSITIVE_INFINITY, }, properties: { @@ -224,21 +241,21 @@ export function useCesiumBoatTrack({ } // 绘制飞行轨迹(至少2个点才能绘制线) - if (trackPositionsRef.current.length >= 2) { + const validTrackPositions = trackPositionsRef.current.filter(Boolean); + if (validTrackPositions.length >= 2) { if (trackEntityRef.current) { - trackEntityRef.current.polyline.positions = [...trackPositionsRef.current]; + trackEntityRef.current.polyline.positions = validTrackPositions; } else { trackEntityRef.current = viewer.entities.add({ name: '无人船航行轨迹', polyline: { - positions: [...trackPositionsRef.current], + positions: validTrackPositions, width: 4, material: new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.3, color: Cesium.Color.BLUE, }), clampToGround: true, - disableDepthTestDistance: Number.POSITIVE_INFINITY, }, properties: { type: 'boat-track', diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts index 214ae9d9..e5597de8 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts @@ -56,6 +56,8 @@ export interface UseTilesetLoaderResult { export const useTilesetLoader = (): UseTilesetLoaderResult => { const [tilesets, setTilesets] = useState>(new Map()); const tilesetsRef = useRef>(new Map()); + // 存储 loadProgress 事件移除函数,防止监听器泄漏 + const progressListenersRef = useRef void>>(new Map()); /** * 加载3D Tiles模型 @@ -139,8 +141,8 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { show: config.visible !== false, }); - // 监听加载进度 - tileset.loadProgress.addEventListener((numberOfPendingRequests: number, numberOfTilesProcessing: number) => { + // 监听加载进度(保存移除函数以便清理) + const progressHandler = (numberOfPendingRequests: number, numberOfTilesProcessing: number) => { const total = numberOfPendingRequests + numberOfTilesProcessing; const progress = total > 0 ? Math.min(99, 100 - (total * 2)) : 100; @@ -152,7 +154,9 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { } return newMap; }); - }); + }; + const removeListener = tileset.loadProgress.addEventListener(progressHandler); + progressListenersRef.current.set(config.id, removeListener); // 模型位置调整 - 根据当前地形类型选择对应的高度偏移 if (config.position) { @@ -271,6 +275,13 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { * 卸载指定模型 */ const unloadTileset = useCallback((id: string, viewer: any) => { + // 移除 loadProgress 监听器 + const removeListener = progressListenersRef.current.get(id); + if (removeListener) { + try { removeListener(); } catch { /* ignore */ } + progressListenersRef.current.delete(id); + } + const tileset = tilesetsRef.current.get(id); if (tileset && viewer && !viewer.isDestroyed?.() && viewer.scene) { viewer.scene.primitives.remove(tileset); @@ -292,6 +303,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { const unloadAllTilesets = useCallback((viewer: any) => { if (!viewer || viewer.isDestroyed?.() || !viewer.scene) return; + // 移除所有 loadProgress 监听器 + progressListenersRef.current.forEach((removeListener) => { + try { removeListener(); } catch { /* ignore */ } + }); + progressListenersRef.current.clear(); + tilesetsRef.current.forEach((tileset, id) => { viewer.scene.primitives.remove(tileset); }); diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx index 0d538741..51dbcaf2 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx @@ -605,14 +605,15 @@ const CesiumContainer: React.FC = (props) => { trackPositionsRef.current.push(pos); // 绘制飞行轨迹 - if (trackPositionsRef.current.length >= 2) { + const validTrackPositions = trackPositionsRef.current.filter(Boolean); + if (validTrackPositions.length >= 2) { if (flightTrackEntityRef.current) { - flightTrackEntityRef.current.polyline.positions = [...trackPositionsRef.current]; + flightTrackEntityRef.current.polyline.positions = validTrackPositions; } else { flightTrackEntityRef.current = viewerRef.current.entities.add({ name: '飞行轨迹', polyline: { - positions: [...trackPositionsRef.current], + positions: validTrackPositions, width: 4, material: new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.3, @@ -823,6 +824,11 @@ const CesiumContainer: React.FC = (props) => { creditContainer.style.display = 'none'; } + // 捕获 Cesium 渲染循环中的错误,避免页面崩溃 + viewerRef.current.scene.renderError.addEventListener((scene: any, error: any) => { + console.error('[CesiumContainer] 渲染循环错误:', error); + }); + setLoading(false); setViewerReady(true); // Viewer 初始化完成 console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true'); diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts index 04faf426..84d03703 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts @@ -1,6 +1,6 @@ /** - * Cesium 已规划航线渲染 Hook - * 负责在 Cesium 地图上渲染“航线库”里勾选显示的航线(只渲染线与起终点,避免太重) + * Cesium 已规划航线渲�?Hook + * 负责�?Cesium 地图上渲染“航线库”里勾选显示的航线(只渲染线与起终点,避免太重�? */ import { useCallback, useEffect, useMemo, useRef } from 'react'; import type { BoatWaypointDTO } from '@/types/boatRoute'; @@ -27,7 +27,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const surfaceRetryRef = useRef>(new Map()); const routesRef = useRef(routes); - // 贴近模型表面,避免航线“悬浮” + // 贴近模型表面,避免航线“悬浮�? const ROUTE_RENDER_HEIGHT_OFFSET = 0.05; const getCesium = useCallback(() => (window as any).Cesium, []); @@ -95,7 +95,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend return result; }, []); - const clampPositionsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => { + const clampPositionsToModelSurface = useCallback(async (Cesium: any, positions: any[], groundPositions?: any[]) => { const viewer = viewerRef?.current; if (!viewer || viewer.isDestroyed?.() || !Cesium) return null; if (!Array.isArray(positions) || positions.length < 2) return null; @@ -108,21 +108,21 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const clamped = await fn.call(scene, positions); if (!Array.isArray(clamped) || clamped.length !== positions.length) return null; + const fallbacks = groundPositions || positions; let definedCount = 0; const merged = clamped.map((p: any, idx: number) => { if (p) definedCount++; - return p || positions[idx]; + return p || fallbacks[idx]; }); - if (definedCount < 2) return null; + if (definedCount < 2) return merged.map((p: any) => applyHeightOffset(Cesium, p)).filter(Boolean); // If barely clamped, just return what we have (mixed with fallbacks) to prevent line breaks - return merged.map((p: any) => applyHeightOffset(Cesium, p)); - } catch { + return merged.map((p: any) => applyHeightOffset(Cesium, p)).filter(Boolean); } catch { return null; } }, [viewerRef, applyHeightOffset]); - const clampWaypointsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => { + const clampWaypointsToModelSurface = useCallback(async (Cesium: any, positions: any[], groundPositions?: any[]) => { const viewer = viewerRef?.current; if (!viewer || viewer.isDestroyed?.() || !Cesium) return null; if (!Array.isArray(positions) || positions.length < 1) return null; @@ -134,7 +134,11 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend try { const clamped = await fn.call(scene, positions); if (!Array.isArray(clamped) || clamped.length !== positions.length) return null; - return clamped.map((p: any, idx: number) => applyHeightOffset(Cesium, p || positions[idx])); + // �?clamp 失败时,用地面位置(高度0)而非 300m 探测位置 + const fallbacks = groundPositions || positions; + const result = clamped.map((p: any, idx: number) => applyHeightOffset(Cesium, p || fallbacks[idx])); + // Ensure no undefined/null values leak into position arrays + return result.every(Boolean) ? result : null; } catch { return null; } @@ -240,7 +244,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const key2 = buildWaypointsKey(cur2.waypoints); if (key2 !== key) return; - // 每次尝试前先触发一次渲染,让瓦片/深度尽量就绪 + // 每次尝试前先触发一次渲染,让瓦�?深度尽量就绪 try { viewer.scene?.requestRender?.(); } catch { @@ -252,10 +256,12 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const cartos = densifyWaypoints(Cesium2, cur2.waypoints); const densified = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); - const clampedLine = await clampPositionsToModelSurface(Cesium2, densified); + const densifiedGround = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, 0)); + const clampedLine = await clampPositionsToModelSurface(Cesium2, densified, densifiedGround); const wpAbove = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300)); - const clampedWp = await clampWaypointsToModelSurface(Cesium2, wpAbove); + const wpGround = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0)); + const clampedWp = await clampWaypointsToModelSurface(Cesium2, wpAbove, wpGround); if ((surfaceComputeSeqRef.current.get(routeId) || 0) !== seq) return; if (!clampedLine || clampedLine.length < 2) { @@ -271,7 +277,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend waypointPositions: Array.isArray(clampedWp) ? clampedWp : undefined, }); - // 触发一次增量更新(避免等下一轮effect) + // 触发一次增量更新(避免等下一轮effect�? try { const pathId = `library-route-${routeId}-path`; const startId = `library-route-${routeId}-start`; @@ -279,14 +285,19 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const path = viewer.entities.getById?.(pathId); if (path?.polyline) { - path.polyline.positions = clampedLine; - path.polyline.clampToGround = false; - if (Cesium2?.ArcType) path.polyline.arcType = Cesium2.ArcType.NONE; + const validPolyline = clampedLine.filter(Boolean); + if (validPolyline.length >= 2) { + path.polyline.positions = validPolyline; + path.polyline.clampToGround = false; + if (Cesium2?.ArcType) path.polyline.arcType = Cesium2.ArcType.NONE; + } } + const startPos = clampedLine[0]; + const endPos = clampedLine[clampedLine.length - 1]; const start = viewer.entities.getById?.(startId); - if (start) start.position = clampedLine[0]; + if (start && startPos) start.position = startPos; const end = viewer.entities.getById?.(endId); - if (end) end.position = clampedLine[clampedLine.length - 1]; + if (end && endPos) end.position = endPos; if (Array.isArray(clampedWp)) { const total = cur2.waypoints.length; @@ -295,7 +306,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend for (let i = 0; i < total; i += step) { const wpId = `library-route-${routeId}-wp-${i}`; const wpEntity = viewer.entities.getById?.(wpId); - if (wpEntity) wpEntity.position = clampedWp[i]; + if (wpEntity && clampedWp[i]) wpEntity.position = clampedWp[i]; } } viewer.scene?.requestRender?.(); @@ -341,13 +352,14 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend color: baseColor, }) : baseColor; - const depthFailMaterial = item.highlighted ? baseColor.withAlpha(0.55) : baseColor.withAlpha(0.55); + const depthFailMaterial = item.highlighted ? baseColor.withAlpha(0.65) : baseColor.withAlpha(0.65); const cached = surfaceCacheRef.current.get(routeId); const cachedPositions = cached && cached.key === waypointsKey ? cached.polyline : null; const fallbackPositions = item.waypoints.map((wp) => Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0)); - const positionsToUse = Array.isArray(cachedPositions) && cachedPositions.length >= 2 ? cachedPositions : fallbackPositions; - const useClampToGround = !(Array.isArray(cachedPositions) && cachedPositions.length >= 2); + const validCached = Array.isArray(cachedPositions) ? cachedPositions.filter(Boolean) : []; + const positionsToUse = validCached.length >= 2 ? validCached : fallbackPositions; + const useClampToGround = validCached.length < 2; if (existing?.polyline) { existing.polyline.positions = positionsToUse; @@ -378,7 +390,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend }); } } catch (e) { - console.error('渲染已规划航线失败:', e); + console.error('渲染已规划航线失�?', e); } // start / end @@ -392,7 +404,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const positionFromCache = cached && cached.key === waypointsKey ? (id === startId ? cached.start : cached.end) : null; - const position = positionFromCache || Cesium.Cartesian3.fromDegrees(lon, lat, 0); + const position = (positionFromCache && typeof positionFromCache === 'object') ? positionFromCache : Cesium.Cartesian3.fromDegrees(lon, lat, 0); + if (!position) return; if (existing) { existing.position = position; existing.show = true; @@ -454,7 +467,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const existing = viewer.entities.getById?.(wpId); const posFromCache = Array.isArray(cachedWp) ? cachedWp[i] : null; - const pos = posFromCache || Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0); + const pos = (posFromCache && typeof posFromCache === 'object') ? posFromCache : Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0); + if (!pos) continue; if (existing) { existing.position = pos; @@ -513,7 +527,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend entityIdsByRouteRef.current.set(routeId, ids); - // 贴模型:失败则自动重试(瓦片未就绪/不在视野时容易失败) + // 贴模型:失败则自动重试(瓦片未就�?不在视野时容易失败) scheduleSurfaceCompute(routeId); requestRender(); @@ -530,7 +544,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend return routes.filter((r) => r.visible && r.waypoints && r.waypoints.length >= 2); }, [routes]); - // 同步渲染:增量更新 + 移除未显示的航线 + // 同步渲染:增量更�?+ 移除未显示的航线 useEffect(() => { const viewer = viewerRef?.current; if (!viewer || viewer.isDestroyed?.()) return; @@ -571,7 +585,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const Cesium = getCesium(); if (!viewer || !Cesium || viewer.isDestroyed?.()) return; - const item = routes.find((r) => r.routeId === routeId); + const item = routesRef.current.find((r) => r.routeId === routeId); if (!item?.waypoints || item.waypoints.length === 0) return; const bounds = calculateBounds(item.waypoints); try { @@ -598,7 +612,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend } catch { // 忽略 } - }, [viewerRef, routes, getCesium, calculateBounds]); + }, [viewerRef, getCesium, calculateBounds]); return { flyToRoute, diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteRenderer.ts b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteRenderer.ts index 561fa4c4..ff4973da 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteRenderer.ts +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteRenderer.ts @@ -511,9 +511,8 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) { const entityId = `route-waypoint-${index}`; const cached = surfaceCacheRef.current; const useCached = cached?.key === waypointsKey && Array.isArray(cached?.waypointPositions) && cached!.waypointPositions.length === waypoints.length; - const position = useCached - ? cached!.waypointPositions[index] - : getFallbackPosition(wp); + const cachedPos = useCached ? cached!.waypointPositions[index] : null; + const position = (cachedPos && typeof cachedPos === 'object') ? cachedPos : getFallbackPosition(wp); if (!position) return; try { @@ -654,9 +653,9 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) { if (waypoints.length < 2) return; const cached = surfaceCacheRef.current; - const useCached = cached?.key === waypointsKey && Array.isArray(cached?.polylinePositions) && cached!.polylinePositions.length >= 2; - const positions = useCached - ? cached!.polylinePositions + const cachedLine = cached?.key === waypointsKey && Array.isArray(cached?.polylinePositions) ? cached!.polylinePositions.filter(Boolean) : []; + const positions = cachedLine.length >= 2 + ? cachedLine : waypoints.map((wp) => getFallbackPosition(wp)).filter(Boolean); if (positions.length < 2) return; @@ -675,7 +674,7 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) { existing.polyline.material = material; existing.polyline.clampToGround = false; existing.polyline.arcType = Cesium.ArcType?.NONE; - existing.polyline.depthFailMaterial = depthFailMaterial; + // removed depthFailMaterial to avoid rendering over boat model existing.show = true; } else { viewer.entities.add({ @@ -686,11 +685,9 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) { material, clampToGround: false, arcType: Cesium.ArcType?.NONE, - depthFailMaterial, } }); - } - entityIdsRef.current.add(entityId); + } entityIdsRef.current.add(entityId); } catch (e) { console.error('添加航线polyline失败:', e); } diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/index.tsx b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/index.tsx index 200f7ab8..714422ba 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/index.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/index.tsx @@ -494,9 +494,12 @@ const RouteEditor: React.FC = ({ const [isPreviewing, setIsPreviewing] = useState(false); const previewAnimationRef = useRef(null); const savedCameraStateRef = useRef(null); - const previewBoatPartsRef = useRef<{ hull?: any; cabin?: any; mast?: any; marker?: any } | null>(null); + const previewBoatPartsRef = useRef<{ boat?: any } | null>(null); const waypointPreviewListRef = useRef(null); + // GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差) + const MODEL_HEADING_OFFSET = -Math.PI / 2; + // 计算两点之间的航向角(度) const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => { const dLon = (to.longitude - from.longitude) * Math.PI / 180; @@ -529,11 +532,8 @@ const RouteEditor: React.FC = ({ try { const viewer = viewerRef?.current; if (viewer && !viewer.isDestroyed?.()) { - const { hull, cabin, mast, marker } = previewBoatPartsRef.current; - if (hull) viewer.entities.remove(hull); - if (cabin) viewer.entities.remove(cabin); - if (mast) viewer.entities.remove(mast); - if (marker) viewer.entities.remove(marker); + const { boat } = previewBoatPartsRef.current; + if (boat) viewer.entities.remove(boat); } } catch { // 忽略 @@ -611,23 +611,26 @@ const RouteEditor: React.FC = ({ const densifiedCartos = densify(); if (densifiedCartos.length < 2) { - return points.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).map(applyOffset); + return points + .map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)) + .map(applyOffset) + .filter(Boolean); } const above = densifiedCartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); const clampFn = viewer.scene?.clampToHeightMostDetailed; if (typeof clampFn !== 'function') { - return above.map(applyOffset); + return above.map(applyOffset).filter(Boolean); } try { const clamped = await clampFn.call(viewer.scene, above); const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]); const okCount = (clamped || []).filter(Boolean).length; - if (okCount < 2) return above.map(applyOffset); - return merged.map(applyOffset); + if (okCount < 2) return above.map(applyOffset).filter(Boolean); + return merged.map(applyOffset).filter(Boolean); } catch { - return above.map(applyOffset); + return above.map(applyOffset).filter(Boolean); } }, [viewerRef]); @@ -635,16 +638,17 @@ const RouteEditor: React.FC = ({ const viewer = viewerRef?.current; const Cesium = (window as any).Cesium; if (!viewer || !Cesium || viewer.isDestroyed?.()) return; - if (!Array.isArray(polylinePositions) || polylinePositions.length < 2) return; + polylinePositions = Array.isArray(polylinePositions) ? polylinePositions.filter(Boolean) : []; + if (polylinePositions.length < 2) { + message.warning('模型瓦片加载中,请稍后再试预览'); + return; + } // 预览开始前,清理上一次遗留的船只实体 if (previewBoatPartsRef.current) { try { - const { hull, cabin, mast, marker } = previewBoatPartsRef.current; - if (hull) viewer.entities.remove(hull); - if (cabin) viewer.entities.remove(cabin); - if (mast) viewer.entities.remove(mast); - if (marker) viewer.entities.remove(marker); + const { boat } = previewBoatPartsRef.current; + if (boat) viewer.entities.remove(boat); } catch { // 忽略 } finally { @@ -695,92 +699,34 @@ const RouteEditor: React.FC = ({ } }; - // 创建预览船只实体:临时“3D船体”(用几何体拼装),后续可替换为 glb/gltf + // 创建预览船只实体:使用 GLB 船模型 try { const firstPos0 = polylinePositions[0]; // 抬高过大会产生“视差”,看起来像是偏离航线;因此尽量贴近航线,靠标记图标保证可见 - const boatAboveRoute = 0.05; + const boatAboveRoute = 0.5; const firstPos = offsetUpFromCartesian(firstPos0, boatAboveRoute); const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion - ? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(0, 0, 0)) + ? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(MODEL_HEADING_OFFSET, 0, 0)) : undefined; - const hull = viewer.entities.add({ + const boat = viewer.entities.add({ position: firstPos, orientation: initialOrientation, - box: { - dimensions: new Cesium.Cartesian3(1.35, 0.5, 0.2), - material: Cesium.Color.fromCssColorString('#0B3D91').withAlpha(0.92), - outline: true, - outlineColor: Cesium.Color.fromCssColorString('#E6F7FF').withAlpha(0.8), - shadows: Cesium.ShadowMode.DISABLED, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), + model: { + uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`, + scale: 0.001, + minimumPixelSize: 64, + maximumScale: 200, + runAnimations: true, + colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, + color: Cesium.Color.WHITE, + silhouetteSize: 0, }, }); - const cabinOffset = (basePos: any, headingRad: number) => { - if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return basePos; - const enu = Cesium.Transforms.eastNorthUpToFixedFrame(basePos); - const forwardMeters = 0.25; - const rightMeters = 0.0; - const upMeters = 0.16; - const localOffset = new Cesium.Cartesian3( - Math.sin(headingRad) * forwardMeters + Math.cos(headingRad) * rightMeters, - Math.cos(headingRad) * forwardMeters - Math.sin(headingRad) * rightMeters, - upMeters - ); - return Cesium.Matrix4.multiplyByPoint(enu, localOffset, new Cesium.Cartesian3()); - }; - - const cabinPos = cabinOffset(firstPos, 0); - const cabin = viewer.entities.add({ - position: cabinPos, - orientation: initialOrientation, - box: { - dimensions: new Cesium.Cartesian3(0.55, 0.38, 0.24), - material: Cesium.Color.fromCssColorString('#F5F5F5').withAlpha(0.95), - outline: true, - outlineColor: Cesium.Color.fromCssColorString('#FA8C16').withAlpha(0.85), - shadows: Cesium.ShadowMode.DISABLED, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), - }, - }); - - const mastPos = cabinOffset(firstPos, 0); - const mast = viewer.entities.add({ - position: mastPos, - orientation: initialOrientation, - cylinder: { - length: 0.38, - topRadius: 0.015, - bottomRadius: 0.015, - material: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.9), - outline: true, - outlineColor: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.6), - shadows: Cesium.ShadowMode.DISABLED, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), - }, - }); - - // 额外加一个“标记图标”,保证在复杂模型表面也能看清船的位置 - const markerImageUrl = typeof Cesium.buildModuleUrl === 'function' - ? Cesium.buildModuleUrl('Assets/Textures/maki/ferry.png') - : '/cesium/Assets/Textures/maki/ferry.png'; - const marker = viewer.entities.add({ - position: offsetUpFromCartesian(firstPos0, boatAboveRoute + 0.12), - billboard: { - image: markerImageUrl, - scale: 0.55, - verticalOrigin: Cesium.VerticalOrigin.BOTTOM, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar(20.0, 1.0, 200.0, 0.6), - }, - }); - - previewBoatPartsRef.current = { hull, cabin, mast, marker }; + previewBoatPartsRef.current = { boat }; (previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute; - (previewBoatPartsRef.current as any).cabinOffset = cabinOffset; } catch (e) { console.warn('创建预览船只实体失败:', e); } @@ -959,30 +905,16 @@ const RouteEditor: React.FC = ({ // 更新船只位置与朝向(尽量贴合航线) try { if (previewBoatPartsRef.current) { - const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.14; + const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.5; const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute); const orientation = Cesium.Transforms?.headingPitchRollQuaternion - ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0)) + ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0)) : undefined; - const { hull, cabin, mast } = previewBoatPartsRef.current; - if (hull) { - hull.position = basePos; - if (orientation) hull.orientation = orientation; - } - - const cabinOffset = (previewBoatPartsRef.current as any).cabinOffset as ((p: any, h: number) => any) | undefined; - const cabinPos = typeof cabinOffset === 'function' ? cabinOffset(basePos, headingRad) : basePos; - if (cabin) { - cabin.position = cabinPos; - if (orientation) cabin.orientation = orientation; - } - if (mast) { - mast.position = cabinPos; - if (orientation) mast.orientation = orientation; - } - if (previewBoatPartsRef.current.marker) { - previewBoatPartsRef.current.marker.position = offsetUpFromCartesian(scratchPosCur, boatAboveRoute + 0.12); + const { boat } = previewBoatPartsRef.current; + if (boat) { + boat.position = basePos; + if (orientation) boat.orientation = orientation; } } } catch { @@ -1001,26 +933,15 @@ const RouteEditor: React.FC = ({ // 更新船只位置(兜底) try { if (previewBoatPartsRef.current) { - const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.14; + const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.5; const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute); const orientation = Cesium.Transforms?.headingPitchRollQuaternion - ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0)) + ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0)) : undefined; - const { hull, cabin, mast } = previewBoatPartsRef.current; - if (hull) { - hull.position = basePos; - if (orientation) hull.orientation = orientation; - } - if (cabin) { - cabin.position = basePos; - if (orientation) cabin.orientation = orientation; - } - if (mast) { - mast.position = basePos; - if (orientation) mast.orientation = orientation; - } - if (previewBoatPartsRef.current.marker) { - previewBoatPartsRef.current.marker.position = offsetUpFromCartesian(scratchPosCur, boatAboveRoute + 0.12); + const { boat } = previewBoatPartsRef.current; + if (boat) { + boat.position = basePos; + if (orientation) boat.orientation = orientation; } } } catch { @@ -1109,11 +1030,8 @@ const RouteEditor: React.FC = ({ try { const viewer = viewerRef?.current; if (viewer && !viewer.isDestroyed?.()) { - const { hull, cabin, mast, marker } = previewBoatPartsRef.current; - if (hull) viewer.entities.remove(hull); - if (cabin) viewer.entities.remove(cabin); - if (mast) viewer.entities.remove(mast); - if (marker) viewer.entities.remove(marker); + const { boat } = previewBoatPartsRef.current; + if (boat) viewer.entities.remove(boat); } } catch { // 忽略