Files
gofly-platform-services/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx
T

1205 lines
42 KiB
TypeScript
Raw Normal View History

2025-12-26 19:50:46 +08:00
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { message, Button, Tooltip } from 'antd';
import { AppstoreOutlined, BarsOutlined, ProfileOutlined, EditOutlined } from '@ant-design/icons';
2025-12-26 19:50:46 +08:00
import RightPanel from './3d/BottomPanel/RightPanel';
import LeftControlPanel from './3d/BottomPanel/LeftControlPanel';
import TaskPanel from './3d/BottomPanel/TaskPanel';
2026-01-06 18:09:20 +08:00
import LayerPanel, { LayerPanelProps } from './3d/BottomPanel/LayerPanel';
import RouteEditor from '../RouteEditor';
import BoundaryEditor from '../BoundaryEditor';
2025-12-26 19:50:46 +08:00
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
import { useDroneSSE } from './3d/hooks/useDroneSSE';
import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel';
2026-01-06 18:09:20 +08:00
import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel";
2025-12-26 19:50:46 +08:00
// 动态导入Cesium
let Cesium: any = null;
const DEFAULT_GLOBAL_VIEW = {
lon: 104.195397,
lat: 35.86166,
height: 19000000,
};
interface CesiumContainerProps {
deviceList: any[];
externalSelectedDevice?: any; // 接收外部选择的设备
2025-12-26 19:50:46 +08:00
onClearSelection?: () => void; // 清空选择的回调
}
const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const { deviceList, externalSelectedDevice, onClearSelection } = props;
2025-12-26 19:50:46 +08:00
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const entitiesRef = useRef<Map<string, any>>(new Map());
const pickHandlerRef = useRef<any>(null);
2025-12-26 19:50:46 +08:00
const [loading, setLoading] = useState(true);
2026-01-06 18:09:20 +08:00
const [viewerReady, setViewerReady] = useState(false); // 新增:viewer 是否完全就绪
2025-12-26 19:50:46 +08:00
// 3D 模式专属状态
const [selectedDevice, setSelectedDevice] = useState<any>(null);
2025-12-26 19:50:46 +08:00
const [rightPanelVisible, setRightPanelVisible] = useState(false);
const [leftPanelVisible, setLeftPanelVisible] = useState(false);
// 传递给 LeftControlPanel 的数据
const [controlDevice, setControlDevice] = useState<any>(null);
const [controlRealtimeData, setControlRealtimeData] = useState<any>(null);
// 任务管理面板状态
const [taskPanelVisible, setTaskPanelVisible] = useState(false);
const [taskPanelDevice, setTaskPanelDevice] = useState<any>(null);
const [taskPanelDockData, setTaskPanelDockData] = useState<any>(null);
2026-01-06 18:09:20 +08:00
// 航线规划面板状态(无人船)
const [routePlanningVisible, setRoutePlanningVisible] = useState(false);
const [routePlanningDevice, setRoutePlanningDevice] = useState<any>(null);
const [routePlanningBoundaryId, setRoutePlanningBoundaryId] = useState<string | null>(null);
2026-01-06 18:09:20 +08:00
// 边界编辑面板状态(水域边界)
const [boundaryEditorVisible, setBoundaryEditorVisible] = useState(false);
const [autoShowBoundaryId, setAutoShowBoundaryId] = useState<string | null>(null);
2026-01-06 18:09:20 +08:00
// 图层管理面板状态
const [layerPanelVisible, setLayerPanelVisible] = useState(false);
2025-12-26 19:50:46 +08:00
// 无人机SSE订阅(用于在3D地球上显示无人机位置)
const [droneDeviceSn, setDroneDeviceSn] = useState<string>('');
const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE();
// 无人机位置渲染相关引用
const droneEntityRef = useRef<any>(null);
const flightTrackEntityRef = useRef<any>(null);
const trackPositionsRef = useRef<any[]>([]);
const hasFlownToDroneRef = useRef<boolean>(false);
const lastDroneUpdateTimeRef = useRef<number>(0);
const lastDronePositionRef = useRef<{ lon: number; lat: number; height: number } | null>(null);
// 3D Tiles 模型管理
const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false);
const [currentDeviceModels, setCurrentDeviceModels] = useState<TilesetConfig[]>([]); // 当前设备的所有模型配置
2025-12-26 19:50:46 +08:00
const [modelLoading, setModelLoading] = useState(false);
const [terrainLoading, setTerrainLoading] = useState(false); // 是否正在加载高程地形
const terrainLoadedRef = useRef(false); // 是否已加载高程地形
const {
tilesets,
loadTileset,
unloadTileset,
unloadAllTilesets,
flyToTileset,
setTilesetVisible,
} = useTilesetLoader();
// 相机飞到设备位置
const flyToDevice = useCallback((device: any) => {
2025-12-26 19:50:46 +08:00
if (!viewerRef.current || !Cesium) return;
// 检查 viewer 是否已销毁
if (viewerRef.current.isDestroyed?.()) return;
const lon = parseFloat(device.longitude);
const lat = parseFloat(device.latitude);
2025-12-26 19:50:46 +08:00
if (isNaN(lon) || isNaN(lat)) return;
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 10000m 高度
2025-12-26 19:50:46 +08:00
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90), // 垂直俯视
roll: 0,
},
duration: 1.5,
});
}, []);
// 相机飞回全球视角
const flyToGlobal = useCallback(() => {
if (!viewerRef.current || !Cesium) return;
// 检查 viewer 是否已销毁
if (viewerRef.current.isDestroyed?.()) return;
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(DEFAULT_GLOBAL_VIEW.lon, DEFAULT_GLOBAL_VIEW.lat, DEFAULT_GLOBAL_VIEW.height),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
duration: 1.5,
});
}, []);
/**
* 动态切换到高程地形
* 在进入景区详情、加载3D模型时调用
* @param preferredTerrainType 优先使用的地形类型(从模型配置中获取)
*/
const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise<string> => {
if (!viewerRef.current || !Cesium) {
return 'ellipsoid';
}
// 如果已加载且地形类型匹配,跳过
if (terrainLoadedRef.current && !preferredTerrainType) {
return 'loaded';
}
setTerrainLoading(true);
console.log('开始加载高程地形...', preferredTerrainType ? `优先使用: ${preferredTerrainType}` : '');
let loadedTerrainType = 'ellipsoid';
// 根据优先地形类型决定加载顺序
if (preferredTerrainType === 'arcgis') {
// 优先尝试 ArcGIS
try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
console.log('高程地形加载成功: ArcGIS World Elevation (根据模型配置)');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'arcgis';
} catch (arcgisError) {
console.warn('ArcGIS 加载失败,尝试 Cesium Ion:', arcgisError);
try {
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: true,
});
console.log('高程地形加载成功: Cesium World Terrain (备用)');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'cesium_ion';
message.warning('ArcGIS地形加载失败,已切换到Cesium Ion,模型高度可能有偏差');
} catch (cesiumError) {
console.warn('Cesium Ion 也加载失败,保持椭球地形:', cesiumError);
loadedTerrainType = 'ellipsoid';
}
}
} else {
// 默认优先尝试 Cesium Ion
try {
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: true,
});
console.log('高程地形加载成功: Cesium World Terrain');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'cesium_ion';
} catch (cesiumError) {
console.warn('Cesium World Terrain 加载失败,尝试 ArcGIS:', cesiumError);
try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
console.log('高程地形加载成功: ArcGIS World Elevation');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'arcgis';
if (preferredTerrainType === 'cesium_ion') {
message.warning('Cesium Ion地形加载失败,已切换到ArcGIS,模型高度可能有偏差');
}
} catch (arcgisError) {
console.warn('ArcGIS World Elevation 也加载失败,保持椭球地形:', arcgisError);
loadedTerrainType = 'ellipsoid';
}
}
}
setTerrainLoading(false);
return loadedTerrainType;
}, []);
/**
* 加载设备绑定的模型
2025-12-26 19:50:46 +08:00
* 【优化】采用"先飞后加载"策略,用户点击后立即飞行,模型异步加载
* 策略:
* 1. 相机飞行已在 handleDeviceSelect 中执行,此处专注于加载
2025-12-26 19:50:46 +08:00
* 2. 高程和模型并行准备,减少等待时间
* 3. 模型加载完成后,平滑调整到最佳观察视角
*/
const loadDeviceModels = useCallback(async (deviceSn: string): Promise<boolean> => {
2025-12-26 19:50:46 +08:00
if (!viewerRef.current || !Cesium) {
console.log('Viewer或Cesium未准备好');
return false;
}
console.log('开始查询设备模型, deviceSn:', deviceSn);
2025-12-26 19:50:46 +08:00
setModelLoading(true);
// 先卸载之前的模型
unloadAllTilesets(viewerRef.current);
setCurrentDeviceModels([]);
2025-12-26 19:50:46 +08:00
try {
const res = await getModelsByDeviceSn(deviceSn);
console.log('查询设备模型结果:', res);
2025-12-26 19:50:46 +08:00
const modelList = res.datas || res.data; // 兼容两种返回格式
if (res.resp_code === 0 && modelList && modelList.length > 0) {
const configs = modelList.map((model: any) => convertToTilesetConfig(model));
console.log('转换后的模型配置:', configs);
// 保存所有模型配置(供模型面板使用)
setCurrentDeviceModels(configs);
2025-12-26 19:50:46 +08:00
// 【优化】并行执行:高程加载和模型配置准备
const firstModelTerrainType = configs[0]?.position?.terrainType;
console.log('第一个模型的地形类型配置:', firstModelTerrainType);
// 启动高程加载(不阻塞,让用户先看到地形变化)
const terrainPromise = switchToElevationTerrain(firstModelTerrainType);
// 确定要自动加载的模型数量
const autoLoadCount = configs.length <= 2 ? configs.length : 1;
const configsToLoad = configs.slice(0, autoLoadCount);
if (configs.length > autoLoadCount) {
message.info(`设备共有 ${configs.length} 个模型,已自动加载第 1 个,其他可通过模型面板加载`);
2025-12-26 19:50:46 +08:00
}
// 等待高程加载完成(通常很快,或者已缓存)
const loadedTerrainType = await terrainPromise;
console.log('实际加载的地形类型:', loadedTerrainType);
let loadedCount = 0;
let firstTileset: any = null;
// 加载指定数量的模型,传入实际加载的地形类型
for (const config of configsToLoad) {
console.log('准备加载模型:', config.name, 'URL:', config.url);
if (config.url) {
const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType);
if (tileset) {
loadedCount++;
if (loadedCount === 1) {
firstTileset = tileset;
}
message.success(`模型 [${config.name}] 加载成功`);
}
} else {
console.warn('模型URL为空,跳过加载:', config.name);
}
}
// 【优化】模型加载完成后,平滑调整到最佳观察视角
// 使用较短的动画时间,因为相机已经在设备附近了
2025-12-26 19:50:46 +08:00
if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) {
try {
const radius = Number(firstTileset?.boundingSphere?.radius);
const range = Number.isFinite(radius) && radius > 0 ? Math.max(40, radius * 0.7) : 80;
2025-12-26 19:50:46 +08:00
viewerRef.current.flyTo(firstTileset, {
duration: 0.8, // 缩短动画时间,因为已经在附近
2025-12-26 19:50:46 +08:00
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-70), // 改为70度俯视,更接近垂直俯视
range
2025-12-26 19:50:46 +08:00
),
});
} catch (e) {
console.warn('微调视角失败:', e);
}
}
setModelLoading(false);
return loadedCount > 0;
} else {
console.log('该设备没有绑定模型或查询结果为空');
2025-12-26 19:50:46 +08:00
setModelLoading(false);
return false;
}
} catch (error) {
console.error('加载设备模型失败:', error);
2025-12-26 19:50:46 +08:00
setModelLoading(false);
return false;
}
}, [loadTileset, unloadAllTilesets, switchToElevationTerrain]);
// 处理设备点击
2025-12-26 19:50:46 +08:00
// 优化策略:先飞行后加载,提升用户体验
const handleDeviceSelect = useCallback((device: any) => {
setSelectedDevice(device);
2025-12-26 19:50:46 +08:00
setRightPanelVisible(true);
// 切换设备时,关闭左侧操控台
2025-12-26 19:50:46 +08:00
setLeftPanelVisible(false);
// 【优化】立即飞到设备位置,不等待模型加载
2025-12-26 19:50:46 +08:00
// 这样用户点击后立刻能看到视角变化,体验更流畅
flyToDevice(device);
2025-12-26 19:50:46 +08:00
// 【优化】异步加载模型,不阻塞飞行动画
// 模型加载完成后会自动调整到最佳视角
if (device.deviceSn) {
loadDeviceModels(device.deviceSn);
2025-12-26 19:50:46 +08:00
}
}, [flyToDevice, loadDeviceModels]);
2025-12-26 19:50:46 +08:00
// 处理外部选择变化
useEffect(() => {
if (externalSelectedDevice && !loading) {
handleDeviceSelect(externalSelectedDevice);
2025-12-26 19:50:46 +08:00
}
}, [externalSelectedDevice, loading, handleDeviceSelect]);
2025-12-26 19:50:46 +08:00
// 清除无人机图层
const clearDroneLayers = useCallback(() => {
if (!viewerRef.current || viewerRef.current.isDestroyed?.()) return;
if (droneEntityRef.current) {
try {
viewerRef.current.entities.remove(droneEntityRef.current);
} catch (e) {}
droneEntityRef.current = null;
}
if (flightTrackEntityRef.current) {
try {
viewerRef.current.entities.remove(flightTrackEntityRef.current);
} catch (e) {}
flightTrackEntityRef.current = null;
}
trackPositionsRef.current = [];
hasFlownToDroneRef.current = false;
lastDroneUpdateTimeRef.current = 0;
lastDronePositionRef.current = null;
}, []);
// 处理从右侧面板点击"操控" - 打开操控台并订阅无人机SSE
const handleOpenControl = useCallback((device: any, realtimeData: any) => {
setControlDevice(device);
setControlRealtimeData(realtimeData);
setLeftPanelVisible(true);
// 打开操控台时开始订阅无人机SSE(msg_alarm)
const deviceSn = device?.deviceSn;
if (deviceSn && deviceSn !== droneDeviceSn) {
// 断开旧的SSE连接
if (droneDeviceSn) {
disconnectDroneSSE(droneDeviceSn);
}
// 清除旧的无人机图层
clearDroneLayers();
// 开始新的SSE订阅
setDroneDeviceSn(deviceSn);
connectDroneSSE(deviceSn);
}
}, [droneDeviceSn, disconnectDroneSSE, connectDroneSSE, clearDroneLayers]);
// 关闭操控台 - 断开无人机SSE
const handleCloseControl = useCallback(() => {
setLeftPanelVisible(false);
// 关闭操控台时断开无人机SSE(取消msg_alarm订阅)
if (droneDeviceSn) {
disconnectDroneSSE(droneDeviceSn);
setDroneDeviceSn('');
}
resetDroneData();
clearDroneLayers();
}, [droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]);
// 处理从右侧面板点击"任务管理"
const handleOpenTaskPanel = useCallback((device: any, dockData: any) => {
2025-12-26 19:50:46 +08:00
setTaskPanelDevice(device);
setTaskPanelDockData(dockData);
setTaskPanelVisible(true);
}, []);
2026-01-06 18:09:20 +08:00
// 处理从右侧面板点击"航线规划"(无人船)
const handleOpenRoutePlanning = useCallback((device: any) => {
setRoutePlanningDevice(device);
setRoutePlanningVisible(true);
setRoutePlanningBoundaryId(null);
2026-01-06 18:09:20 +08:00
// 关闭其他面板
setRightPanelVisible(false);
}, []);
// 关闭航线规划面板
const handleCloseRoutePlanning = useCallback(() => {
setRoutePlanningVisible(false);
setRoutePlanningDevice(null);
setRoutePlanningBoundaryId(null);
// 退出后恢复右侧面板入口
if (selectedDevice) {
setRightPanelVisible(true);
}
}, [selectedDevice]);
2026-01-06 18:09:20 +08:00
// 航线保存成功回调
const handleRoutesSaveSuccess = useCallback((routeId: string) => {
// 保持航线规划面板不关闭:由 RouteEditor 内部切回“航线库”并刷新列表
// 这里保留回调入口,便于后续做跨面板联动
void routeId;
2026-01-06 18:09:20 +08:00
}, []);
// 从图层管理面板:基于边界快速进入航线规划(仅可航行边界)
const handleOpenRoutePlanningByBoundary = useCallback((boundary: any) => {
if (!selectedDevice) {
message.warning('请先选择设备');
return;
}
const boundaryId = String(boundary?.boundaryId || '').trim();
if (!boundaryId) {
message.warning('边界ID无效,无法进入航线规划');
return;
}
setRoutePlanningDevice(selectedDevice);
setRoutePlanningVisible(true);
setRoutePlanningBoundaryId(boundaryId);
setLayerPanelVisible(false);
setRightPanelVisible(false);
}, [selectedDevice]);
2026-01-06 18:09:20 +08:00
// 处理从图层管理面板点击"新建边界"
const handleOpenBoundaryEditor = useCallback(() => {
const sn = String(selectedDevice?.deviceSn || '').trim();
if (!sn) {
message.warning('请先选择设备后再新建边界');
return;
}
2026-01-06 18:09:20 +08:00
setBoundaryEditorVisible(true);
// 关闭其他面板
setLayerPanelVisible(false);
setRightPanelVisible(false);
}, [selectedDevice]);
2026-01-06 18:09:20 +08:00
// 关闭边界编辑器
const handleCloseBoundaryEditor = useCallback(() => {
setBoundaryEditorVisible(false);
if (selectedDevice) {
setRightPanelVisible(true);
}
}, [selectedDevice]);
2026-01-06 18:09:20 +08:00
// 边界保存成功回调
const handleBoundarySaveSuccess = useCallback((boundaryId: string) => {
message.success('边界保存成功');
setBoundaryEditorVisible(false);
// 重新打开图层管理面板,显示新创建的边界
setLayerPanelVisible(true);
setAutoShowBoundaryId(boundaryId);
if (selectedDevice) {
setRightPanelVisible(true);
}
}, [selectedDevice]);
2026-01-06 18:09:20 +08:00
2025-12-26 19:50:46 +08:00
// 计算无人机实时位置
const realtimePosition = useMemo(() => {
if (!droneData) return null;
return {
longitude: droneData.longitude,
latitude: droneData.latitude,
height: droneData.height, // 相对高度(相对于起飞点)
elevation: droneData.elevation, // 海拔高度(椭球高度)
// 3D地图显示用 height(相对高度),与航线的 height 对应
altitude: droneData.height,
heading: droneData.attitude_head,
timestamp: Date.now(),
};
}, [droneData]);
// 飞到无人机位置
const flyToDrone = useCallback(() => {
if (!viewerRef.current || !Cesium || !realtimePosition) return;
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
const droneHeight = realtimePosition.altitude ?? 50;
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
realtimePosition.longitude,
realtimePosition.latitude,
droneHeight + 100 // 视角高度比无人机高100米
),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90), // 垂直俯视
roll: 0,
},
duration: 1.5,
});
}, [realtimePosition]);
// 无人机位置渲染(当收到SSE数据时在地图上显示无人机位置)
useEffect(() => {
if (!viewerRef.current || !Cesium || !realtimePosition) return;
if (viewerRef.current.isDestroyed?.()) return;
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
const now = Date.now();
const currentPos = {
lon: realtimePosition.longitude,
lat: realtimePosition.latitude,
height: realtimePosition.altitude ?? 0,
};
// 节流:1秒内且位置没变化则跳过
const timeSinceLastUpdate = now - lastDroneUpdateTimeRef.current;
const lastPos = lastDronePositionRef.current;
if (lastPos && timeSinceLastUpdate < 1000) {
const posChanged =
Math.abs(currentPos.lon - lastPos.lon) > 0.00001 ||
Math.abs(currentPos.lat - lastPos.lat) > 0.00001 ||
Math.abs(currentPos.height - lastPos.height) > 0.5;
if (!posChanged) {
return;
}
}
// 更新时间和位置记录
lastDroneUpdateTimeRef.current = now;
lastDronePositionRef.current = currentPos;
const displayHeight = realtimePosition.height ?? 50;
try {
const pos = Cesium.Cartesian3.fromDegrees(
realtimePosition.longitude,
realtimePosition.latitude,
displayHeight
);
const labelText = `无人机 H:${realtimePosition.height != null ? realtimePosition.height.toFixed(0) : '--'}m`;
// 更新或创建无人机entity
if (droneEntityRef.current) {
droneEntityRef.current.position = pos;
if (droneEntityRef.current.label) {
droneEntityRef.current.label.text = labelText;
}
} else {
droneEntityRef.current = viewerRef.current.entities.add({
name: '无人机实时位置',
position: pos,
point: {
pixelSize: 16,
color: Cesium.Color.RED,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 3,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: labelText,
font: '14px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -20),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
console.log('[CesiumContainer] 创建无人机entity');
}
// 添加航迹点
trackPositionsRef.current.push(pos);
// 绘制飞行轨迹
if (trackPositionsRef.current.length >= 2) {
if (flightTrackEntityRef.current) {
flightTrackEntityRef.current.polyline.positions = [...trackPositionsRef.current];
} else {
flightTrackEntityRef.current = viewerRef.current.entities.add({
name: '飞行轨迹',
polyline: {
positions: [...trackPositionsRef.current],
width: 4,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3,
color: Cesium.Color.LIME,
}),
clampToGround: false,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
console.log('[CesiumContainer] 创建飞行轨迹entity');
}
}
// 强制渲染
viewerRef.current.scene.requestRender();
// 首次收到位置数据时,自动飞到无人机位置
if (!hasFlownToDroneRef.current && trackPositionsRef.current.length === 1) {
hasFlownToDroneRef.current = true;
flyToDrone();
}
} catch (error) {
console.error('[CesiumContainer] 更新无人机位置出错:', error);
}
}, [realtimePosition, flyToDrone]);
// 获取设备的视频流地址(从设备数据中获取)
const getVideoStreamUrl = useCallback((device: any): string | undefined => {
// 从设备配置获取视频流地址
return device?.videoStreamUrl || undefined;
}, []);
// 关闭右侧面板
const handleRightPanelClose = useCallback(() => {
setRightPanelVisible(false);
setSelectedDevice(null);
2025-12-26 19:50:46 +08:00
setLeftPanelVisible(false); // 同时也关闭左侧
// 【修复】断开无人机SSE连接并清除图层
if (droneDeviceSn) {
disconnectDroneSSE(droneDeviceSn);
setDroneDeviceSn('');
}
resetDroneData();
clearDroneLayers();
// 【修复】卸载所有3D模型,避免返回地球时出现渲染问题(黑洞)
if (viewerRef.current) {
unloadAllTilesets(viewerRef.current);
}
setCurrentDeviceModels([]);
2025-12-26 19:50:46 +08:00
setTilesetPanelVisible(false);
// 【修复】重置地形为椭球地形(快速响应,避免地形问题)
if (viewerRef.current && Cesium) {
viewerRef.current.terrainProvider = new Cesium.EllipsoidTerrainProvider();
viewerRef.current.scene.globe.depthTestAgainstTerrain = false;
terrainLoadedRef.current = false;
}
// 【修复】通知父组件清空设备选择框
2025-12-26 19:50:46 +08:00
onClearSelection?.();
flyToGlobal();
}, [flyToGlobal, unloadAllTilesets, onClearSelection, droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]);
// 收起到“设备面板”(不清空设备、不卸载模型)
const handleRightPanelMinimize = useCallback(() => {
setRightPanelVisible(false);
}, []);
2025-12-26 19:50:46 +08:00
// ========== 3D Tiles 模型管理方法 ==========
// 加载模型
const handleLoadTileset = useCallback(async (config: TilesetConfig) => {
if (!viewerRef.current || !Cesium) {
message.warning('请等待地图加载完成');
return;
}
const tileset = await loadTileset(config, viewerRef.current, Cesium);
if (tileset) {
message.success(`模型 [${config.name}] 加载成功`);
}
}, [loadTileset]);
// 卸载模型
const handleUnloadTileset = useCallback((id: string) => {
unloadTileset(id, viewerRef.current);
message.info('模型已卸载');
}, [unloadTileset]);
// 飞往模型
const handleFlyToTileset = useCallback((id: string) => {
flyToTileset(id, viewerRef.current, Cesium);
}, [flyToTileset]);
// 切换模型可见性
const handleToggleTilesetVisible = useCallback((id: string, visible: boolean) => {
setTilesetVisible(id, visible);
// 更新当前设备模型配置状态
setCurrentDeviceModels(prev =>
2025-12-26 19:50:46 +08:00
prev.map(c => c.id === id ? { ...c, visible } : c)
);
}, [setTilesetVisible]);
// 初始化Cesium
useEffect(() => {
const initCesium = async () => {
try {
if (!Cesium) {
const cesiumModule = await import('cesium');
Cesium = cesiumModule;
2026-01-06 18:09:20 +08:00
// 将 Cesium 挂载到 window 上,供其他组件使用(如 BoundaryEditor)
(window as any).Cesium = cesiumModule;
console.log('[CesiumContainer] ✓ Cesium 已挂载到 window');
2025-12-26 19:50:46 +08:00
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
// 设置 Cesium Ion Access Token(用于加载 Cesium World Terrain)
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
if (cesiumToken) {
Cesium.Ion.defaultAccessToken = cesiumToken;
}
if (!document.querySelector('link[href*="cesium"]')) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `${cesiumBaseUrl}cesium/Widgets/widgets.css`;
document.head.appendChild(link);
}
}
if (!containerRef.current) return;
// 【重要】初始化时使用椭球地形(无高程),快速加载
// 原因:
// 1. 全球地形加载较慢,影响首屏体验
// 2. Cesium World Terrain 精度约30m,与大疆建图的厘米级精度差异大
// 会导致模型部分贴合、部分悬浮、部分嵌入地面的问题
// 3. 大疆建图的模型本身包含了高精度的地形信息,不需要额外的地形数据
// 解决方案:使用椭球地形 + 模型高度偏移微调
const terrainProvider = new Cesium.EllipsoidTerrainProvider();
console.log('地图仪表盘: 使用椭球地形(快速加载,模型自带高程)');
viewerRef.current = new Cesium.Viewer(containerRef.current, {
terrainProvider: terrainProvider,
scene3DOnly: false,
shouldAnimate: true,
animation: false,
timeline: false,
fullscreenButton: false,
geocoder: false,
homeButton: true,
sceneModePicker: true,
baseLayerPicker: false,
navigationHelpButton: false,
infoBox: false,
selectionIndicator: false,
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
});
// 使用椭球地形时不需要深度测试
// viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
viewerRef.current.imageryLayers.remove(viewerRef.current.imageryLayers.get(0));
viewerRef.current.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b');
const arcgisImagery = new Cesium.UrlTemplateImageryProvider({
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0,
maximumLevel: 18,
});
viewerRef.current.imageryLayers.addImageryProvider(arcgisImagery);
viewerRef.current.scene.globe.enableLighting = false;
viewerRef.current.scene.globe.show = true;
viewerRef.current.scene.skyAtmosphere.show = true;
viewerRef.current.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(DEFAULT_GLOBAL_VIEW.lon, DEFAULT_GLOBAL_VIEW.lat, DEFAULT_GLOBAL_VIEW.height),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
});
// 重写 Home 按钮行为
viewerRef.current.homeButton.viewModel.command.beforeExecute.addEventListener((e: any) => {
e.cancel = true; // 取消默认行为
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(DEFAULT_GLOBAL_VIEW.lon, DEFAULT_GLOBAL_VIEW.lat, DEFAULT_GLOBAL_VIEW.height),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
duration: 1.5,
});
});
const creditContainer = viewerRef.current.cesiumWidget.creditContainer;
if (creditContainer) {
creditContainer.style.display = 'none';
}
setLoading(false);
2026-01-06 18:09:20 +08:00
setViewerReady(true); // Viewer 初始化完成
console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true');
2025-12-26 19:50:46 +08:00
message.success('3D地图加载完成');
} catch (error) {
console.error('Cesium初始化失败:', error);
message.error('3D地图加载失败');
setLoading(false);
2026-01-06 18:09:20 +08:00
setViewerReady(false); // 初始化失败
2025-12-26 19:50:46 +08:00
}
};
initCesium();
return () => {
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
viewerRef.current.destroy();
}
2026-01-06 18:09:20 +08:00
setViewerReady(false); // 清理时重置状态
2025-12-26 19:50:46 +08:00
};
}, []);
// 更新设备标记
2025-12-26 19:50:46 +08:00
useEffect(() => {
if (loading || !viewerRef.current || !Cesium || !deviceList.length) return;
2025-12-26 19:50:46 +08:00
const viewer = viewerRef.current;
entitiesRef.current.forEach((entity, key) => {
if (key.startsWith('device_')) {
2025-12-26 19:50:46 +08:00
viewer.entities.remove(entity);
entitiesRef.current.delete(key);
}
});
const validDevices = deviceList.filter((device) => {
const lat = parseFloat(device.latitude);
const lng = parseFloat(device.longitude);
2025-12-26 19:50:46 +08:00
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
});
if (validDevices.length === 0) return;
2025-12-26 19:50:46 +08:00
validDevices.forEach((device) => {
const lon = parseFloat(device.longitude);
const lat = parseFloat(device.latitude);
// 设备默认显示绿色
const pointColor = '#52c41a';
2025-12-26 19:50:46 +08:00
const entity = viewer.entities.add({
id: `device_${device.deviceSn}`,
2025-12-26 19:50:46 +08:00
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
point: {
pixelSize: 20,
color: Cesium.Color.fromCssColorString(pointColor),
outlineColor: Cesium.Color.WHITE,
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
label: {
text: device.deviceName || device.deviceSn || '设备',
2025-12-26 19:50:46 +08:00
font: '14px sans-serif',
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -25),
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
deviceData: device,
2025-12-26 19:50:46 +08:00
},
});
entitiesRef.current.set(`device_${device.deviceSn}`, entity);
2025-12-26 19:50:46 +08:00
});
}, [deviceList, loading]);
2025-12-26 19:50:46 +08:00
// 点击事件
useEffect(() => {
if (loading || !viewerRef.current || !Cesium) return;
const viewer = viewerRef.current;
if (viewer.isDestroyed?.()) return;
2025-12-26 19:50:46 +08:00
// 清理旧的拾取 handler(React 18 dev 下 effect 可能会触发多次)
if (pickHandlerRef.current) {
try {
pickHandlerRef.current.destroy();
} catch {
// 忽略
}
pickHandlerRef.current = null;
}
try {
viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
} catch {
// 忽略
}
let handler: any = null;
try {
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
pickHandlerRef.current = handler;
} catch (e) {
console.warn('初始化拾取事件失败:', e);
return;
}
2025-12-26 19:50:46 +08:00
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.position);
if (Cesium.defined(pickedObject) && pickedObject.id) {
const entity = pickedObject.id;
const deviceData = entity.properties?.deviceData?.getValue();
if (deviceData) {
handleDeviceSelect(deviceData);
2025-12-26 19:50:46 +08:00
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.endPosition);
if (Cesium.defined(pickedObject) && pickedObject.id && pickedObject.id.point) {
pickedObject.id.point.pixelSize = 25;
document.body.style.cursor = 'pointer';
} else {
entitiesRef.current.forEach((entity) => {
if (entity.point) {
entity.point.pixelSize = 20;
}
});
document.body.style.cursor = 'default';
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
return () => {
if (pickHandlerRef.current === handler) {
try {
handler.destroy();
} catch {
// 忽略
}
pickHandlerRef.current = null;
}
2025-12-26 19:50:46 +08:00
document.body.style.cursor = 'default';
};
}, [loading, handleDeviceSelect]);
2025-12-26 19:50:46 +08:00
2026-01-06 18:09:20 +08:00
// @ts-ignore
2025-12-26 19:50:46 +08:00
return (
<div style={{ width: '100%', height: '100%', position: 'relative' }}>
<div ref={containerRef} style={{ width: '100%', height: '100%' }} />
{loading && (
<div
style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
color: '#fff',
fontSize: 16,
background: 'rgba(0,0,0,0.5)',
padding: '10px 20px',
borderRadius: 4,
}}
>
加载3D地图中...
</div>
)}
{/* 地形/模型加载中提示 - 优化为不阻塞视觉的提示 */}
{(terrainLoading || modelLoading) && (
<div
style={{
position: 'absolute',
top: 60,
left: '50%',
transform: 'translateX(-50%)',
color: '#fff',
fontSize: 14,
background: 'linear-gradient(135deg, rgba(0,100,150,0.85) 0%, rgba(0,60,100,0.85) 100%)',
padding: '10px 20px',
borderRadius: 20,
zIndex: 800,
display: 'flex',
alignItems: 'center',
gap: 10,
boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
border: '1px solid rgba(0,240,255,0.3)',
}}
>
<div
style={{
width: 16,
height: 16,
border: '2px solid rgba(255,255,255,0.3)',
borderTopColor: '#00f0ff',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
}}
/>
<span>
{terrainLoading ? '正在加载高程地形...' : '正在加载3D模型...'}
</span>
<style>{`
@keyframes spin {
to { transform: rotate(360deg); }
}
`}</style>
</div>
)}
{/* 3D模型管理按钮 - 当设备有绑定模型时显示 */}
{!loading && !boundaryEditorVisible && currentDeviceModels.length > 0 && (
2025-12-26 19:50:46 +08:00
<Tooltip title="3D模型管理">
<Button
type="primary"
icon={<AppstoreOutlined />}
onClick={() => setTilesetPanelVisible(!tilesetPanelVisible)}
style={{
position: 'absolute',
top: 10,
right: 180,
zIndex: 700,
background: tilesetPanelVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
{/* 航线规划按钮(无人船) - 放到图层/模型管理同一栏 */}
{!loading && !boundaryEditorVisible && selectedDevice?.deviceType === 4 && (
<Tooltip title="航线规划">
<Button
type="primary"
icon={<EditOutlined />}
onClick={() => handleOpenRoutePlanning(selectedDevice)}
style={{
position: 'absolute',
top: 10,
right: 130,
zIndex: 700,
background: routePlanningVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
2026-01-06 18:09:20 +08:00
{/* 图层管理按钮 - 航线和边界图层控制 */}
{!loading && !boundaryEditorVisible && selectedDevice && (
2026-01-06 18:09:20 +08:00
<Tooltip title="图层管理">
<Button
type="primary"
icon={<BarsOutlined />}
onClick={() => setLayerPanelVisible(!layerPanelVisible)}
style={{
position: 'absolute',
top: 10,
right: 230,
zIndex: 700,
background: layerPanelVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
{/* 设备面板按钮 - 重新打开右侧数据面板 */}
{!loading && !boundaryEditorVisible && selectedDevice && (
<Tooltip title="设备面板">
<Button
type="primary"
icon={<ProfileOutlined />}
onClick={() => setRightPanelVisible(v => !v)}
style={{
position: 'absolute',
top: 10,
right: 280,
zIndex: 700,
background: rightPanelVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
2026-01-06 18:09:20 +08:00
{/* 3D Tiles模型管理面板 - TODO: TilesetPanel组件未实现,暂时注释 */}
2025-12-26 19:50:46 +08:00
<TilesetPanel
visible={tilesetPanelVisible}
tilesets={tilesets}
configs={currentDeviceModels}
2025-12-26 19:50:46 +08:00
onLoad={handleLoadTileset}
onUnload={handleUnloadTileset}
onFlyTo={handleFlyToTileset}
onToggleVisible={handleToggleTilesetVisible}
onClose={() => setTilesetPanelVisible(false)}
/>
{/* 左侧操控台 */}
<LeftControlPanel
visible={leftPanelVisible}
onClose={handleCloseControl}
device={controlDevice}
realtimeData={controlRealtimeData}
videoStreamUrl={getVideoStreamUrl(controlDevice)}
droneData={droneData}
/>
{/* 右侧数据面板 */}
<RightPanel
visible={rightPanelVisible}
device={selectedDevice}
2025-12-26 19:50:46 +08:00
onClose={handleRightPanelClose}
onMinimize={handleRightPanelMinimize}
2025-12-26 19:50:46 +08:00
onControlClick={handleOpenControl}
onTaskPanelOpen={handleOpenTaskPanel}
2026-01-06 18:09:20 +08:00
onRoutePlanningOpen={handleOpenRoutePlanning}
2025-12-26 19:50:46 +08:00
viewer={viewerRef.current}
Cesium={Cesium}
/>
{/* 任务管理面板 - 左下角独立渲染 */}
<TaskPanel
visible={taskPanelVisible}
onClose={() => setTaskPanelVisible(false)}
device={taskPanelDevice}
viewer={viewerRef.current}
Cesium={Cesium}
droneData={droneData}
dockData={taskPanelDockData}
/>
2026-01-06 18:09:20 +08:00
{/* 图层管理面板 - 左下角 */}
<LayerPanel
visible={layerPanelVisible}
onClose={() => setLayerPanelVisible(false)}
viewer={viewerRef.current}
Cesium={Cesium}
deviceSn={selectedDevice?.deviceSn}
2026-01-06 18:09:20 +08:00
scenicId={selectedDevice?.scenicId}
onBoundaryEditorOpen={handleOpenBoundaryEditor}
onRoutePlanningOpen={handleOpenRoutePlanningByBoundary}
autoShowBoundaryId={autoShowBoundaryId || undefined}
onAutoShowBoundaryHandled={() => setAutoShowBoundaryId(null)}
2026-01-06 18:09:20 +08:00
/>
{/* 无人船航线规划面板 - 浮层形式,不遮挡地图点击 */}
{routePlanningVisible && routePlanningDevice && viewerReady && (
<RouteEditor
scenicId={routePlanningDevice.scenicId || 1}
deviceSn={routePlanningDevice.deviceSn}
boundaryId={routePlanningBoundaryId || undefined}
onSaveSuccess={handleRoutesSaveSuccess}
onCancel={handleCloseRoutePlanning}
viewerRef={viewerRef}
/>
2026-01-06 18:09:20 +08:00
)}
{/* 水域边界编辑器 - 工具栏浮层形式,不遮挡地图 */}
{/* 只有当 viewer 完全就绪后才渲染 */}
{boundaryEditorVisible && viewerReady && !!selectedDevice?.deviceSn && (
2026-01-06 18:09:20 +08:00
<BoundaryEditor
deviceSn={selectedDevice?.deviceSn}
2026-01-06 18:09:20 +08:00
onSaveSuccess={handleBoundarySaveSuccess}
onCancel={handleCloseBoundaryEditor}
viewerRef={viewerRef}
/>
)}
2025-12-26 19:50:46 +08:00
</div>
);
};
export default CesiumContainer;