feat: 可视化大屏展示
This commit is contained in:
@@ -0,0 +1,968 @@
|
||||
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
|
||||
import { message, Button, Tooltip } from 'antd';
|
||||
import { AppstoreOutlined } from '@ant-design/icons';
|
||||
import RightPanel from './3d/BottomPanel/RightPanel';
|
||||
import LeftControlPanel from './3d/BottomPanel/LeftControlPanel';
|
||||
import TaskPanel from './3d/BottomPanel/TaskPanel';
|
||||
import TilesetPanel from './3d/TilesetPanel';
|
||||
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
|
||||
import { useDroneSSE } from './3d/hooks/useDroneSSE';
|
||||
import { getModelsByTourismId, convertToTilesetConfig } from '@/services/threeDModel';
|
||||
|
||||
// 动态导入Cesium
|
||||
let Cesium: any = null;
|
||||
|
||||
const DEFAULT_GLOBAL_VIEW = {
|
||||
lon: 104.195397,
|
||||
lat: 35.86166,
|
||||
height: 19000000,
|
||||
};
|
||||
|
||||
interface CesiumContainerProps {
|
||||
tourismList: any[];
|
||||
externalSelectedTourism?: any; // 接收外部选择的景区
|
||||
onClearSelection?: () => void; // 清空选择的回调
|
||||
}
|
||||
|
||||
const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
const { tourismList, externalSelectedTourism, onClearSelection } = props;
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const viewerRef = useRef<any>(null);
|
||||
const entitiesRef = useRef<Map<string, any>>(new Map());
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// 3D 模式专属状态
|
||||
const [selectedTourism, setSelectedTourism] = useState<any>(null);
|
||||
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);
|
||||
const [taskPanelTourismId, setTaskPanelTourismId] = useState<number | undefined>(undefined);
|
||||
|
||||
// 无人机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 [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的所有模型配置
|
||||
const [modelLoading, setModelLoading] = useState(false);
|
||||
const [terrainLoading, setTerrainLoading] = useState(false); // 是否正在加载高程地形
|
||||
const terrainLoadedRef = useRef(false); // 是否已加载高程地形
|
||||
const {
|
||||
tilesets,
|
||||
loadTileset,
|
||||
unloadTileset,
|
||||
unloadAllTilesets,
|
||||
flyToTileset,
|
||||
setTilesetVisible,
|
||||
} = useTilesetLoader();
|
||||
|
||||
// 相机飞到景区
|
||||
const flyToTourism = useCallback((tourism: any) => {
|
||||
if (!viewerRef.current || !Cesium) return;
|
||||
// 检查 viewer 是否已销毁
|
||||
if (viewerRef.current.isDestroyed?.()) return;
|
||||
|
||||
const lon = parseFloat(tourism.longitude);
|
||||
const lat = parseFloat(tourism.latitude);
|
||||
|
||||
if (isNaN(lon) || isNaN(lat)) return;
|
||||
|
||||
viewerRef.current.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 5000km 高度
|
||||
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;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 加载景区绑定的模型
|
||||
* 【优化】采用"先飞后加载"策略,用户点击后立即飞行,模型异步加载
|
||||
* 策略:
|
||||
* 1. 相机飞行已在 handleTourismSelect 中执行,此处专注于加载
|
||||
* 2. 高程和模型并行准备,减少等待时间
|
||||
* 3. 模型加载完成后,平滑调整到最佳观察视角
|
||||
*/
|
||||
const loadTourismModels = useCallback(async (tourismId: number): Promise<boolean> => {
|
||||
if (!viewerRef.current || !Cesium) {
|
||||
console.log('Viewer或Cesium未准备好');
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('开始查询景区模型, tourismId:', tourismId);
|
||||
setModelLoading(true);
|
||||
|
||||
// 先卸载之前的模型
|
||||
unloadAllTilesets(viewerRef.current);
|
||||
setCurrentTourismModels([]);
|
||||
|
||||
try {
|
||||
const res = await getModelsByTourismId(tourismId);
|
||||
console.log('查询景区模型结果:', res);
|
||||
|
||||
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);
|
||||
|
||||
// 保存所有模型配置(供模型面板使用)
|
||||
setCurrentTourismModels(configs);
|
||||
|
||||
// 【优化】并行执行:高程加载和模型配置准备
|
||||
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 个,其他可通过模型面板加载`);
|
||||
}
|
||||
|
||||
// 等待高程加载完成(通常很快,或者已缓存)
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// 【优化】模型加载完成后,平滑调整到最佳观察视角
|
||||
// 使用较短的动画时间,因为相机已经在景区附近了
|
||||
if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) {
|
||||
try {
|
||||
viewerRef.current.flyTo(firstTileset, {
|
||||
duration: 1.0, // 缩短动画时间,因为已经在附近
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
Cesium.Math.toRadians(0),
|
||||
Cesium.Math.toRadians(-45),
|
||||
0
|
||||
),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('微调视角失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
setModelLoading(false);
|
||||
return loadedCount > 0;
|
||||
} else {
|
||||
console.log('该景区没有绑定模型或查询结果为空');
|
||||
setModelLoading(false);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载景区模型失败:', error);
|
||||
setModelLoading(false);
|
||||
return false;
|
||||
}
|
||||
}, [loadTileset, unloadAllTilesets, switchToElevationTerrain]);
|
||||
|
||||
// 处理景区点击
|
||||
// 优化策略:先飞行后加载,提升用户体验
|
||||
const handleTourismSelect = useCallback((tourism: any) => {
|
||||
setSelectedTourism(tourism);
|
||||
setRightPanelVisible(true);
|
||||
// 切换景区时,关闭左侧操控台
|
||||
setLeftPanelVisible(false);
|
||||
|
||||
// 【优化】立即飞到景区位置,不等待模型加载
|
||||
// 这样用户点击后立刻能看到视角变化,体验更流畅
|
||||
flyToTourism(tourism);
|
||||
|
||||
// 【优化】异步加载模型,不阻塞飞行动画
|
||||
// 模型加载完成后会自动调整到最佳视角
|
||||
if (tourism.id) {
|
||||
loadTourismModels(tourism.id);
|
||||
}
|
||||
}, [flyToTourism, loadTourismModels]);
|
||||
|
||||
// 处理外部选择变化
|
||||
useEffect(() => {
|
||||
if (externalSelectedTourism && !loading) {
|
||||
handleTourismSelect(externalSelectedTourism);
|
||||
}
|
||||
}, [externalSelectedTourism, loading, handleTourismSelect]);
|
||||
|
||||
// 清除无人机图层
|
||||
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, tourismId?: number) => {
|
||||
setTaskPanelDevice(device);
|
||||
setTaskPanelDockData(dockData);
|
||||
setTaskPanelTourismId(tourismId);
|
||||
setTaskPanelVisible(true);
|
||||
}, []);
|
||||
|
||||
// 计算无人机实时位置
|
||||
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);
|
||||
setSelectedTourism(null);
|
||||
setLeftPanelVisible(false); // 同时也关闭左侧
|
||||
|
||||
// 【修复】断开无人机SSE连接并清除图层
|
||||
if (droneDeviceSn) {
|
||||
disconnectDroneSSE(droneDeviceSn);
|
||||
setDroneDeviceSn('');
|
||||
}
|
||||
resetDroneData();
|
||||
clearDroneLayers();
|
||||
|
||||
// 【修复】卸载所有3D模型,避免返回地球时出现渲染问题(黑洞)
|
||||
if (viewerRef.current) {
|
||||
unloadAllTilesets(viewerRef.current);
|
||||
}
|
||||
setCurrentTourismModels([]);
|
||||
setTilesetPanelVisible(false);
|
||||
|
||||
// 【修复】重置地形为椭球地形(快速响应,避免地形问题)
|
||||
if (viewerRef.current && Cesium) {
|
||||
viewerRef.current.terrainProvider = new Cesium.EllipsoidTerrainProvider();
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = false;
|
||||
terrainLoadedRef.current = false;
|
||||
}
|
||||
|
||||
// 【修复】通知父组件清空景区选择框
|
||||
onClearSelection?.();
|
||||
|
||||
flyToGlobal();
|
||||
}, [flyToGlobal, unloadAllTilesets, onClearSelection, droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]);
|
||||
|
||||
// ========== 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);
|
||||
// 更新当前景区模型配置状态
|
||||
setCurrentTourismModels(prev =>
|
||||
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;
|
||||
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);
|
||||
message.success('3D地图加载完成');
|
||||
} catch (error) {
|
||||
console.error('Cesium初始化失败:', error);
|
||||
message.error('3D地图加载失败');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
initCesium();
|
||||
|
||||
return () => {
|
||||
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
|
||||
viewerRef.current.destroy();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 更新景区标记
|
||||
useEffect(() => {
|
||||
if (loading || !viewerRef.current || !Cesium || !tourismList.length) return;
|
||||
|
||||
const viewer = viewerRef.current;
|
||||
|
||||
entitiesRef.current.forEach((entity, key) => {
|
||||
if (key.startsWith('tourism_')) {
|
||||
viewer.entities.remove(entity);
|
||||
entitiesRef.current.delete(key);
|
||||
}
|
||||
});
|
||||
|
||||
const validTourisms = tourismList.filter((tourism) => {
|
||||
const lat = parseFloat(tourism.latitude);
|
||||
const lng = parseFloat(tourism.longitude);
|
||||
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
|
||||
});
|
||||
|
||||
if (validTourisms.length === 0) return;
|
||||
|
||||
validTourisms.forEach((tourism) => {
|
||||
const lon = parseFloat(tourism.longitude);
|
||||
const lat = parseFloat(tourism.latitude);
|
||||
const pointColor = tourism.status === 1 ? '#52c41a' : '#ff4d4f';
|
||||
|
||||
const entity = viewer.entities.add({
|
||||
id: `tourism_${tourism.id}`,
|
||||
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: tourism.tourismName || '景区',
|
||||
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: {
|
||||
tourismData: tourism,
|
||||
},
|
||||
});
|
||||
|
||||
entitiesRef.current.set(`tourism_${tourism.id}`, entity);
|
||||
});
|
||||
}, [tourismList, loading]);
|
||||
|
||||
// 点击事件
|
||||
useEffect(() => {
|
||||
if (loading || !viewerRef.current || !Cesium) return;
|
||||
|
||||
const viewer = viewerRef.current;
|
||||
viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
|
||||
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
||||
|
||||
handler.setInputAction((movement: any) => {
|
||||
const pickedObject = viewer.scene.pick(movement.position);
|
||||
if (Cesium.defined(pickedObject) && pickedObject.id) {
|
||||
const entity = pickedObject.id;
|
||||
const tourismData = entity.properties?.tourismData?.getValue();
|
||||
if (tourismData) {
|
||||
handleTourismSelect(tourismData);
|
||||
}
|
||||
}
|
||||
}, 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 () => {
|
||||
handler.destroy();
|
||||
document.body.style.cursor = 'default';
|
||||
};
|
||||
}, [loading, handleTourismSelect]);
|
||||
|
||||
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 && currentTourismModels.length > 0 && (
|
||||
<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>
|
||||
)}
|
||||
|
||||
{/* 3D Tiles模型管理面板 */}
|
||||
<TilesetPanel
|
||||
visible={tilesetPanelVisible}
|
||||
tilesets={tilesets}
|
||||
configs={currentTourismModels}
|
||||
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}
|
||||
tourism={selectedTourism}
|
||||
onClose={handleRightPanelClose}
|
||||
onControlClick={handleOpenControl}
|
||||
onTaskPanelOpen={handleOpenTaskPanel}
|
||||
viewer={viewerRef.current}
|
||||
Cesium={Cesium}
|
||||
/>
|
||||
|
||||
{/* 任务管理面板 - 左下角独立渲染 */}
|
||||
<TaskPanel
|
||||
visible={taskPanelVisible}
|
||||
onClose={() => setTaskPanelVisible(false)}
|
||||
device={taskPanelDevice}
|
||||
viewer={viewerRef.current}
|
||||
Cesium={Cesium}
|
||||
droneData={droneData}
|
||||
dockData={taskPanelDockData}
|
||||
tourismId={taskPanelTourismId}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CesiumContainer;
|
||||
Reference in New Issue
Block a user