no message

This commit is contained in:
2025-08-30 00:34:49 +08:00
parent ba1ae1bb6c
commit 529886cd66
2 changed files with 521 additions and 1 deletions

View File

@@ -50,7 +50,7 @@
</template>
<script>
import GlMap from './gl-map-3.vue'
import GlMap from './gl-map-4.vue'
import { driver } from 'driver.js'
import 'driver.js/dist/driver.css'
// import { startMapping } from '../../config/mork.js'

View File

@@ -0,0 +1,520 @@
<template>
<div class="point-cloud-map">
<div ref="canvasContainer" class="canvas-container">
<canvas ref="pointCloudCanvas"></canvas>
</div>
<el-button icon="el-icon-location" size="mini" class="locate-button" @click="locateCar">
</el-button>
<div v-if="isLoading" class="loading-indicator">{{ $t('Loading') }}</div>
</div>
</template>
<script>
/* eslint-disable */
import * as THREE from 'three'
import { mapGetters } from 'vuex'
// import { points } from '../../config/point.js'
// import { points1 } from '../../config/point1.js'
// import { points2 } from '../../config/point2.js'
export default {
name: 'PointCloudMap',
data() {
return {
// Three.js相关
scene: null,
camera: null,
renderer: null,
pointCloud: null,
pointMaterial: null,
pointGeometry: null,
carMesh: null,
carTexture: null,
// 点云数据
allPoints: [],
pointCount: 0,
maxPoints: 1000000, // 最大点数限制
// 小车相关
vehicleImage: require('../../images/new/agv.png'),
carMovementEnabled: true,
carSize: 30,
// 视图控制
isDragging: false,
previousTouchX: 0,
previousTouchY: 0,
cameraX: 0,
cameraY: 0,
cameraZoom: 1,
initialPinchDistance: null,
initialZoom: null,
// UI控制
pointSize: 1.5,
// WebSocket相关
socket: null,
isLoading: true,
reconnectTimer: null, // 重连计时器
animationFrameId: null,
// 优化相关参数
updateThrottle: 50, // 数据更新节流间隔(ms)
lastUpdateTime: 0,
resizeHandler: null // 存储resize事件处理函数
}
},
computed: {
...mapGetters(['serverUrl', 'userRole', 'carPosition']),
},
watch: {
carPosition: {
handler(newVal) {
this.updateCarPosition(newVal)
},
deep: true
}
},
beforeDestroy() {
this.cleanupResources();
},
methods: {
cleanupResources() {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
if (this.animationFrameId) cancelAnimationFrame(this.animationFrameId)
this.closeWebSocket()
// 清理Three.js资源
if (this.renderer) {
this.renderer.dispose();
this.renderer.forceContextLoss();
this.renderer = null;
}
if (this.pointGeometry) {
this.pointGeometry.dispose();
this.pointGeometry = null;
}
if (this.pointMaterial) {
this.pointMaterial.dispose();
this.pointMaterial = null;
}
if (this.carTexture) {
this.carTexture.dispose();
this.carTexture = null;
}
if (this.scene) {
this.scene.clear();
this.scene = null;
}
if (this.resizeHandler) {
window.removeEventListener('resize', this.resizeHandler);
this.resizeHandler = null;
}
const canvas = this.$refs.pointCloudCanvas;
if (canvas) {
canvas.removeEventListener('touchstart', null);
canvas.removeEventListener('touchmove', null);
canvas.removeEventListener('touchend', null);
canvas.removeEventListener('mousedown', null);
canvas.removeEventListener('mousemove', null);
canvas.removeEventListener('mouseup', null);
canvas.removeEventListener('mouseleave', null);
canvas.removeEventListener('wheel', null);
}
this.camera = null;
this.pointCloud = null;
this.carMesh = null;
this.allPoints = [];
this.pointCount = 0;
},
initThreeJS() {
// 初始化Three.js场景
const container = this.$refs.canvasContainer;
const aspectRatio = container.clientWidth / container.clientHeight;
const pointRange = 1000; // 点云范围 -500 到 500
const viewHeight = pointRange;
const viewWidth = viewHeight * aspectRatio;
this.scene = new THREE.Scene();
this.camera = new THREE.OrthographicCamera(
-viewWidth / 2,
viewWidth / 2,
viewHeight / 2,
-viewHeight / 2,
0.1,
2000
);
this.camera.position.z = 10;
const canvas = this.$refs.pointCloudCanvas;
this.renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: false,
alpha: true, // 关键启用alpha通道
transparent: true // 关键:允许透明
});
this.updateRendererSize();
this.createPointCloud();
this.createCar();
this.setupEventListeners();
this.animate();
},
createPointCloud() {
this.pointGeometry = new THREE.BufferGeometry();
this.pointMaterial = new THREE.PointsMaterial({
size: this.pointSize,
color: 0xFFFFFF,
sizeAttenuation: false,
transparent: false, // 不透明
depthWrite: true,
antialias: false
});
this.pointCloud = new THREE.Points(this.pointGeometry, this.pointMaterial);
this.scene.add(this.pointCloud);
},
createCar() {
const textureLoader = new THREE.TextureLoader();
textureLoader.load(this.vehicleImage, (texture) => {
this.carTexture = texture;
// 纹理过滤设置
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.needsUpdate = true;
const carMaterial = new THREE.SpriteMaterial({
map: texture,
transparent: true,
opacity: 1,
depthWrite: false // 避免z-fight
});
this.carMesh = new THREE.Sprite(carMaterial);
const container = this.$refs.canvasContainer;
const containerHeight = container.clientHeight;
const scale = this.carSize / containerHeight * 1000;
this.carMesh.scale.set(scale * 1.5, scale * 1.5, 1);
this.carMesh.position.set(this.carPosition.x, this.carPosition.y, 5);
this.carMesh.rotation.z = this.carPosition.angle;
this.scene.add(this.carMesh);
});
},
updatePointCloud(points) {
if (!points || !Array.isArray(points) || points.length === 0) return;
const pointSet = new Set();
this.allPoints.forEach(point => {
const key = `${point.x},${point.y}`;
pointSet.add(key);
});
const newUniquePoints = points.filter(point => {
const key = `${point.x},${point.y}`;
if (pointSet.has(key)) return false;
pointSet.add(key);
return true;
});
if (newUniquePoints.length === 0) return;
this.allPoints.push(...newUniquePoints);
if (this.allPoints.length > this.maxPoints) {
this.allPoints.splice(0, this.allPoints.length - this.maxPoints);
}
this.pointCount = this.allPoints.length;
this.updatePointCloudGeometry();
},
updatePointCloudGeometry() {
const positions = new Float32Array(this.pointCount * 3);
// 填充坐标数据
for (let i = 0; i < this.pointCount; i++) {
const point = this.allPoints[i];
positions[i * 3] = point.x || 0;
positions[i * 3 + 1] = point.y || 0;
positions[i * 3 + 2] = 0; // 固定z轴
}
// 正确处理缓冲区大小变化的情况
if (this.pointGeometry.attributes.position) {
// 如果数组大小不同,需要先删除旧属性再添加新属性
if (this.pointGeometry.attributes.position.array.length !== positions.length) {
this.pointGeometry.deleteAttribute('position');
this.pointGeometry.setAttribute(
'position',
new THREE.BufferAttribute(positions, 3)
);
} else {
// 大小相同则直接更新内容
this.pointGeometry.attributes.position.array.set(positions);
this.pointGeometry.attributes.position.needsUpdate = true;
}
} else {
// 首次创建属性
this.pointGeometry.setAttribute(
'position',
new THREE.BufferAttribute(positions, 3)
);
}
},
updateCarPosition(position) {
if (!this.carMovementEnabled || !this.carMesh) return;
this.carMesh.position.set(position.x, position.y, 5);
this.carMesh.rotation.z = position.angle;
},
animate() {
this.animationFrameId = requestAnimationFrame(this.animate);
let isCameraUpdated = false;
// 优化:仅在相机状态变化时更新
if (this.camera.position.x !== this.cameraX || this.camera.position.y !== this.cameraY) {
this.camera.position.x = this.cameraX;
this.camera.position.y = this.cameraY;
isCameraUpdated = true;
}
if (this.camera.zoom !== this.cameraZoom) {
this.camera.zoom = this.cameraZoom;
isCameraUpdated = true;
}
if (isCameraUpdated) {
this.camera.updateProjectionMatrix();
}
this.renderer.render(this.scene, this.camera);
},
updateRendererSize() {
const container = this.$refs.canvasContainer;
const width = container.clientWidth;
const height = container.clientHeight;
const aspectRatio = width / height;
const viewHeight = 1000;
const viewWidth = viewHeight * aspectRatio;
this.camera.left = -viewWidth / 2 / this.cameraZoom;
this.camera.right = viewWidth / 2 / this.cameraZoom;
this.camera.top = viewHeight / 2 / this.cameraZoom;
this.camera.bottom = -viewHeight / 2 / this.cameraZoom;
this.camera.updateProjectionMatrix();
this.renderer.setSize(width, height);
},
locateCar() {
// 将相机对准小车
this.cameraX = this.carPosition.x;
this.cameraY = this.carPosition.y;
},
setupEventListeners() {
const canvas = this.$refs.pointCloudCanvas;
this.resizeHandler = () => this.updateRendererSize();
window.addEventListener('resize', this.resizeHandler);
// 触摸事件 - 平移
canvas.addEventListener('touchstart', (e) => {
if (e.touches.length === 1) {
this.isDragging = true;
this.previousTouchX = e.touches[0].clientX;
this.previousTouchY = e.touches[0].clientY;
e.preventDefault();
}
});
canvas.addEventListener('touchmove', (e) => {
if (this.isDragging && e.touches.length === 1) {
const deltaX = e.touches[0].clientX - this.previousTouchX;
const deltaY = e.touches[0].clientY - this.previousTouchY;
// 添加最小移动阈值
if (Math.abs(deltaX) < 1 && Math.abs(deltaY) < 1) return;
// 移动相机(反转方向以获得自然拖动效果)
this.cameraX -= deltaX * 2 / this.cameraZoom;
this.cameraY += deltaY * 2 / this.cameraZoom;
this.previousTouchX = e.touches[0].clientX;
this.previousTouchY = e.touches[0].clientY;
e.preventDefault();
}
// 双指 pinch 缩放
if (e.touches.length === 2) {
const touch1 = e.touches[0];
const touch2 = e.touches[1];
// 计算当前两点间的距离
const currentDistance = Math.hypot(
touch1.clientX - touch2.clientX,
touch1.clientY - touch2.clientY
);
// 计算初始两点间的距离
if (!this.initialPinchDistance) {
this.initialPinchDistance = currentDistance;
this.initialZoom = this.cameraZoom;
}
// 计算缩放比例
const zoomFactor = currentDistance / this.initialPinchDistance;
this.cameraZoom = Math.max(0.2, Math.min(5, this.initialZoom * zoomFactor));
this.updateRendererSize();
e.preventDefault();
}
});
canvas.addEventListener('touchend', ()=> {
this.isDragging = false;
this.initialPinchDistance = null;
this.initialZoom = null
});
// 鼠标事件(用于桌面设备测试)
canvas.addEventListener('mousedown', (e) => {
this.isDragging = true;
this.previousTouchX = e.clientX;
this.previousTouchY = e.clientY;
});
canvas.addEventListener('mousemove', (e) => {
if (this.isDragging) {
const deltaX = e.clientX - this.previousTouchX;
const deltaY = e.clientY - this.previousTouchY;
if (Math.abs(deltaX) < 1 && Math.abs(deltaY) < 1) return;
this.cameraX -= deltaX * 2 / this.cameraZoom;
this.cameraY += deltaY * 2 / this.cameraZoom;
this.previousTouchX = e.clientX;
this.previousTouchY = e.clientY;
}
});
canvas.addEventListener('mouseup', () => {
this.isDragging = false;
});
canvas.addEventListener('mouseleave', () => {
this.isDragging = false;
});
// 鼠标滚轮缩放
canvas.addEventListener('wheel', (e)=> {
e.preventDefault();
// 优化:减小缩放步长
this.cameraZoom = e.deltaY < 0
? Math.min(5, this.cameraZoom * 1.05)
: Math.max(0.2, this.cameraZoom / 1.05);
this.updateRendererSize();
});
},
initWebSocket() {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
const protocol = this.serverUrl.startsWith('https') ? 'wss' : 'ws'
const wsHost = this.serverUrl.replace(/^https?:\/\//, '')
this.socket = new WebSocket(`${protocol}://${wsHost}/webSocket/PointCloudData/${this.userRole}`)
this.socket.onopen = () => {
console.log('WebSocket连接已建立')
this.isLoading = false
}
this.socket.onmessage = (event) => {
try {
const now = Date.now()
if (now - this.lastUpdateTime < this.updateInterval) {
return
}
this.lastUpdateTime = now
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
const pointData = JSON.parse(event.data)
this.updatePointCloud(pointData.data)
} catch (error) {
console.error('解析点云数据失败:', error)
}
}
this.socket.onclose = (event) => {
console.log('WebSocket连接已关闭代码:', event.code)
this.isLoading = true
this.reconnectTimer = setTimeout(() => this.initWebSocket(), 3000)
}
this.socket.onerror = (error) => {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
console.error('WebSocket错误:', error)
this.isLoading = true
}
},
closeWebSocket() {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
if (this.socket) {
this.socket.onopen = null
this.socket.onmessage = null
this.socket.onclose = null
this.socket.onerror = null
this.socket.close(1000, '组件销毁')
this.socket = null
}
this.allPoints = []
},
init() {
this.initThreeJS();
this.initWebSocket()
// this.isLoading = false;
// const pointData = points.data
// this.updatePointCloud(pointData);
// setTimeout(() => {
// const arr = points1.data
// this.updatePointCloud(arr);
// }, 1000)
// setTimeout(() => {
// const arr = points2.data
// this.updatePointCloud(arr);
// }, 2000)
}
}
}
</script>
<style lang="stylus" scoped>
.point-cloud-map
position relative
width 100%
height 100%
background-color rgba(4, 33, 58, 70%)
box-shadow inset 1px 1px 7px 2px #4d9bcd
overflow hidden
.canvas-container
display: flex;
align-items: center;
justify-content: center;
width: 100%
height: 100%
position: relative
z-index: 0
// 定位按钮样式
.locate-button
position: absolute
bottom: 20px
right: 20px
width: 40px
height: 40px
border-radius: 50%
background-color: rgba(255, 255, 255, 0.8)
border: none
color: #333
font-size: 18px
cursor: pointer
display: flex
align-items: center
justify-content: center
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2)
z-index: 100
transition: all 0.2s ease
&:hover
background-color: white
transform: scale(1.05)
&:active
transform: scale(0.95)
.loading-indicator
position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)
background-color: rgba(255, 255, 255, 0.8)
padding: .01rem .02rem
border-radius: 4px
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1)
font-size: .12rem
color: #333
z-index: 100
display: flex
align-items: center
</style>