This commit is contained in:
2026-02-02 11:00:40 +03:00
parent 87a1a628d3
commit 2d0f236fa4
22 changed files with 1119 additions and 461 deletions

View File

@@ -88,6 +88,8 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
const [allSensorsOverlayCircles, setAllSensorsOverlayCircles] = useState<
{ sensorId: string; left: number; top: number; colorHex: string }[]
>([])
// NEW: State for tracking hovered sensor in overlay circles
const [hoveredSensorId, setHoveredSensorId] = useState<string | null>(null)
const handlePan = () => setPanActive(!panActive);
@@ -223,6 +225,82 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
);
}
};
// NEW: Function to handle overlay circle click
const handleOverlayCircleClick = (sensorId: string) => {
console.log('[ModelViewer] Overlay circle clicked:', sensorId)
// Find the mesh for this sensor
const allMeshes = importedMeshesRef.current || []
const sensorMeshes = collectSensorMeshes(allMeshes)
const targetMesh = sensorMeshes.find(m => getSensorIdFromMesh(m) === sensorId)
if (!targetMesh) {
console.warn(`[ModelViewer] Mesh not found for sensor: ${sensorId}`)
return
}
const scene = sceneRef.current
const camera = scene?.activeCamera as ArcRotateCamera
if (!scene || !camera) return
// Calculate bounding box of the sensor mesh
const bbox = (typeof targetMesh.getHierarchyBoundingVectors === 'function')
? targetMesh.getHierarchyBoundingVectors()
: {
min: targetMesh.getBoundingInfo().boundingBox.minimumWorld,
max: targetMesh.getBoundingInfo().boundingBox.maximumWorld
}
const center = bbox.min.add(bbox.max).scale(0.5)
const size = bbox.max.subtract(bbox.min)
const maxDimension = Math.max(size.x, size.y, size.z)
// Calculate optimal camera distance
const targetRadius = Math.max(camera.lowerRadiusLimit ?? 2, maxDimension * 1.5)
// Stop any current animations
scene.stopAnimation(camera)
// Setup easing
const ease = new CubicEase()
ease.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT)
const frameRate = 60
const durationMs = 600 // 0.6 seconds for smooth animation
const totalFrames = Math.round((durationMs / 1000) * frameRate)
// Animate camera target position
Animation.CreateAndStartAnimation(
'camTarget',
camera,
'target',
frameRate,
totalFrames,
camera.target.clone(),
center.clone(),
Animation.ANIMATIONLOOPMODE_CONSTANT,
ease
)
// Animate camera radius (zoom)
Animation.CreateAndStartAnimation(
'camRadius',
camera,
'radius',
frameRate,
totalFrames,
camera.radius,
targetRadius,
Animation.ANIMATIONLOOPMODE_CONSTANT,
ease
)
// Call callback to display tooltip
onSensorPick?.(sensorId)
console.log('[ModelViewer] Camera animation started for sensor:', sensorId)
}
useEffect(() => {
isDisposedRef.current = false
@@ -343,160 +421,168 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
}, [onError])
useEffect(() => {
if (!isInitializedRef.current || isDisposedRef.current) {
return
}
if (!modelPath || modelPath.trim() === '') {
console.warn('[ModelViewer] No model path provided')
// Не вызываем onError для пустого пути - это нормальное состояние при инициализации
setIsLoading(false)
return
}
if (!modelPath || !sceneRef.current || !engineRef.current) return
const scene = sceneRef.current
setIsLoading(true)
setLoadingProgress(0)
setShowModel(false)
setModelReady(false)
const loadModel = async () => {
if (!sceneRef.current || isDisposedRef.current) {
return
}
const currentModelPath = modelPath;
console.log('[ModelViewer] Starting model load:', currentModelPath);
setIsLoading(true)
setLoadingProgress(0)
setShowModel(false)
setModelReady(false)
setPanActive(false)
const oldMeshes = sceneRef.current.meshes.slice();
const activeCameraId = sceneRef.current.activeCamera?.uniqueId;
console.log('[ModelViewer] Cleaning up old meshes. Total:', oldMeshes.length);
oldMeshes.forEach(m => {
if (m.uniqueId !== activeCameraId) {
m.dispose();
}
});
console.log('[ModelViewer] Loading GLTF model:', currentModelPath)
// UI элемент загрузчика (есть эффект замедленности)
const progressInterval = setInterval(() => {
setLoadingProgress(prev => {
if (prev >= 90) {
clearInterval(progressInterval)
return 90
}
return prev + Math.random() * 15
})
}, 100)
try {
console.log('[ModelViewer] Calling ImportMeshAsync with path:', currentModelPath);
console.log('[ModelViewer] Starting to load model:', modelPath)
// Проверим доступность файла через fetch
try {
const testResponse = await fetch(currentModelPath, { method: 'HEAD' });
console.log('[ModelViewer] File availability check:', {
url: currentModelPath,
status: testResponse.status,
statusText: testResponse.statusText,
ok: testResponse.ok
});
} catch (fetchError) {
console.error('[ModelViewer] File fetch error:', fetchError);
// UI элемент загрузчика (есть эффект замедленности)
const progressInterval = setInterval(() => {
setLoadingProgress(prev => {
if (prev >= 90) {
clearInterval(progressInterval)
return 90
}
return prev + Math.random() * 15
})
}, 100)
// Use the correct ImportMeshAsync signature: (url, scene, onProgress)
const result = await ImportMeshAsync(modelPath, scene, (evt) => {
if (evt.lengthComputable) {
const progress = (evt.loaded / evt.total) * 100
setLoadingProgress(progress)
console.log('[ModelViewer] Loading progress:', progress)
}
})
clearInterval(progressInterval)
if (isDisposedRef.current) {
console.log('[ModelViewer] Component disposed during load')
return
}
const result = await ImportMeshAsync(currentModelPath, sceneRef.current)
console.log('[ModelViewer] ImportMeshAsync completed successfully');
console.log('[ModelViewer] Import result:', {
console.log('[ModelViewer] Model loaded successfully:', {
meshesCount: result.meshes.length,
particleSystemsCount: result.particleSystems.length,
skeletonsCount: result.skeletons.length,
animationGroupsCount: result.animationGroups.length
});
if (isDisposedRef.current || modelPath !== currentModelPath) {
console.log('[ModelViewer] Model loading aborted - model changed during load')
clearInterval(progressInterval)
setIsLoading(false)
return;
}
})
importedMeshesRef.current = result.meshes
clearInterval(progressInterval)
setLoadingProgress(100)
console.log('[ModelViewer] GLTF Model loaded successfully!', result)
if (result.meshes.length > 0) {
const boundingBox = result.meshes[0].getHierarchyBoundingVectors()
const size = boundingBox.max.subtract(boundingBox.min)
const maxDimension = Math.max(size.x, size.y, size.z)
const camera = sceneRef.current!.activeCamera as ArcRotateCamera
camera.radius = maxDimension * 2
camera.target = result.meshes[0].position
importedMeshesRef.current = result.meshes
setModelReady(true)
onModelLoaded?.({
meshes: result.meshes,
boundingBox: {
min: boundingBox.min,
max: boundingBox.max
}
min: { x: boundingBox.min.x, y: boundingBox.min.y, z: boundingBox.min.z },
max: { x: boundingBox.max.x, y: boundingBox.max.y, z: boundingBox.max.z },
},
})
}
// Плавное появление модели
setTimeout(() => {
if (!isDisposedRef.current && modelPath === currentModelPath) {
setShowModel(true)
setIsLoading(false)
} else {
console.log('Model display aborted - model changed during animation')
}
}, 500)
} else {
console.warn('No meshes found in model')
onError?.('В модели не найдена геометрия')
setIsLoading(false)
}
} catch (error) {
clearInterval(progressInterval)
if (!isDisposedRef.current && modelPath === currentModelPath) {
console.error('Error loading GLTF model:', error)
const errorMessage = error instanceof Error ? error.message : String(error)
onError?.(`Ошибка загрузки модели: ${errorMessage}`)
} else {
console.log('Error occurred but loading was aborted - model changed')
}
setLoadingProgress(100)
setShowModel(true)
setModelReady(true)
setIsLoading(false)
} catch (error) {
if (isDisposedRef.current) return
const errorMessage = error instanceof Error ? error.message : 'Неизвестная ошибка'
console.error('[ModelViewer] Error loading model:', errorMessage)
const message = `Ошибка при загрузке модели: ${errorMessage}`
onError?.(message)
setIsLoading(false)
setModelReady(false)
}
}
// Загрузка модлеи начинается после появления спиннера
requestIdleCallback(() => loadModel(), { timeout: 50 })
}, [modelPath, onError, onModelLoaded])
loadModel()
}, [modelPath, onModelLoaded, onError])
useEffect(() => {
if (!sceneRef.current || isDisposedRef.current || !modelReady) return
useEffect(() => {
if (!highlightAllSensors || focusSensorId || !modelReady) {
setAllSensorsOverlayCircles([])
return
}
if (highlightAllSensors) {
const allMeshes = importedMeshesRef.current || []
const sensorMeshes = collectSensorMeshes(allMeshes)
applyHighlightToMeshes(
highlightLayerRef.current,
highlightedMeshesRef,
sensorMeshes,
mesh => {
const sid = getSensorIdFromMesh(mesh)
const status = sid ? sensorStatusMap?.[sid] : undefined
return statusToColor3(status ?? null)
},
)
const scene = sceneRef.current
const engine = engineRef.current
if (!scene || !engine) {
setAllSensorsOverlayCircles([])
return
}
const allMeshes = importedMeshesRef.current || []
const sensorMeshes = collectSensorMeshes(allMeshes)
if (sensorMeshes.length === 0) {
setAllSensorsOverlayCircles([])
return
}
const engineTyped = engine as Engine
const updateCircles = () => {
const circles = computeSensorOverlayCircles({
scene,
engine: engineTyped,
meshes: sensorMeshes,
sensorStatusMap,
})
setAllSensorsOverlayCircles(circles)
}
updateCircles()
const observer = scene.onBeforeRenderObservable.add(updateCircles)
return () => {
scene.onBeforeRenderObservable.remove(observer)
setAllSensorsOverlayCircles([])
}
}, [highlightAllSensors, focusSensorId, modelReady, sensorStatusMap])
useEffect(() => {
if (!highlightAllSensors || focusSensorId || !modelReady) {
return
}
const scene = sceneRef.current
if (!scene) return
const allMeshes = importedMeshesRef.current || []
if (allMeshes.length === 0) {
return
}
const sensorMeshes = collectSensorMeshes(allMeshes)
console.log('[ModelViewer] Total meshes in model:', allMeshes.length)
console.log('[ModelViewer] Sensor meshes found:', sensorMeshes.length)
// Log first 5 sensor IDs found in meshes
const sensorIds = sensorMeshes.map(m => getSensorIdFromMesh(m)).filter(Boolean).slice(0, 5)
console.log('[ModelViewer] Sample sensor IDs from meshes:', sensorIds)
if (sensorMeshes.length === 0) {
console.warn('[ModelViewer] No sensor meshes found in 3D model!')
return
}
applyHighlightToMeshes(
highlightLayerRef.current,
highlightedMeshesRef,
sensorMeshes,
mesh => {
const sid = getSensorIdFromMesh(mesh)
const status = sid ? sensorStatusMap?.[sid] : undefined
return statusToColor3(status ?? null)
},
)
}, [highlightAllSensors, focusSensorId, modelReady, sensorStatusMap])
useEffect(() => {
if (!focusSensorId || !modelReady) {
for (const m of highlightedMeshesRef.current) { m.renderingGroupId = 0 }
highlightedMeshesRef.current = []
highlightLayerRef.current?.removeAllMeshes()
chosenMeshRef.current = null
setOverlayPos(null)
setOverlayData(null)
@@ -528,12 +614,14 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
}
const sensorMeshes = collectSensorMeshes(allMeshes)
const allSensorIds = sensorMeshes.map(m => getSensorIdFromMesh(m))
const chosen = sensorMeshes.find(m => getSensorIdFromMesh(m) === sensorId)
console.log('[ModelViewer] Sensor focus', {
requested: sensorId,
totalImportedMeshes: allMeshes.length,
totalSensorMeshes: sensorMeshes.length,
allSensorIds: allSensorIds,
chosen: chosen ? { id: chosen.id, name: chosen.name, uniqueId: chosen.uniqueId, parent: chosen.parent?.name } : null,
source: 'result.meshes',
})
@@ -593,7 +681,6 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [focusSensorId, modelReady, highlightAllSensors])
// Включение выбора на основе взаимодействия с моделью только при готовности модели и включении выбора сенсоров
useEffect(() => {
const scene = sceneRef.current
if (!scene || !modelReady || !isSensorSelectionEnabled) return
@@ -621,7 +708,6 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
}
}, [modelReady, isSensorSelectionEnabled, onSensorPick])
// Расчет позиции оверлея
const computeOverlayPosition = React.useCallback((mesh: AbstractMesh | null) => {
if (!sceneRef.current || !mesh) return null
const scene = sceneRef.current
@@ -644,49 +730,12 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
}
}, [])
// Позиция оверлея изначально
useEffect(() => {
if (!chosenMeshRef.current || !overlayData) return
const pos = computeOverlayPosition(chosenMeshRef.current)
setOverlayPos(pos)
}, [overlayData, computeOverlayPosition])
useEffect(() => {
const scene = sceneRef.current
const engine = engineRef.current
if (!scene || !engine || !modelReady) {
setAllSensorsOverlayCircles([])
return
}
if (!highlightAllSensors || focusSensorId || !sensorStatusMap) {
setAllSensorsOverlayCircles([])
return
}
const allMeshes = importedMeshesRef.current || []
const sensorMeshes = collectSensorMeshes(allMeshes)
if (sensorMeshes.length === 0) {
setAllSensorsOverlayCircles([])
return
}
const engineTyped = engine as Engine
const updateCircles = () => {
const circles = computeSensorOverlayCircles({
scene,
engine: engineTyped,
meshes: sensorMeshes,
sensorStatusMap,
})
setAllSensorsOverlayCircles(circles)
}
updateCircles()
const observer = scene.onBeforeRenderObservable.add(updateCircles)
return () => {
scene.onBeforeRenderObservable.remove(observer)
setAllSensorsOverlayCircles([])
}
}, [highlightAllSensors, focusSensorId, modelReady, sensorStatusMap])
// Позиция оверлея при движущейся камере
useEffect(() => {
if (!sceneRef.current || !chosenMeshRef.current || !overlayData) return
const scene = sceneRef.current
@@ -767,13 +816,19 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
/>
</>
)}
{/* UPDATED: Interactive overlay circles with hover effects */}
{allSensorsOverlayCircles.map(circle => {
const size = 36
const radius = size / 2
const fill = hexWithAlpha(circle.colorHex, 0.2)
const isHovered = hoveredSensorId === circle.sensorId
return (
<div
key={`${circle.sensorId}-${Math.round(circle.left)}-${Math.round(circle.top)}`}
onClick={() => handleOverlayCircleClick(circle.sensorId)}
onMouseEnter={() => setHoveredSensorId(circle.sensorId)}
onMouseLeave={() => setHoveredSensorId(null)}
style={{
position: 'absolute',
left: circle.left - radius,
@@ -783,8 +838,16 @@ const ModelViewer: React.FC<ModelViewerProps> = ({
borderRadius: '9999px',
border: `2px solid ${circle.colorHex}`,
backgroundColor: fill,
pointerEvents: 'none',
pointerEvents: 'auto',
cursor: 'pointer',
transition: 'all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1)',
transform: isHovered ? 'scale(1.4)' : 'scale(1)',
boxShadow: isHovered
? `0 0 25px ${circle.colorHex}, inset 0 0 10px ${circle.colorHex}`
: `0 0 8px ${circle.colorHex}`,
zIndex: isHovered ? 50 : 10,
}}
title={`Датчик: ${circle.sensorId}`}
/>
)
})}