GuLiMmo
2024-03-19 aec00ecc093be803860c8675cbe1c4c776a7cb4e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
<template>
  <div class="route-edit-box">
    <div class="btn-group">
      <a-popover
        :visible="modfiyPopupShow"
        overlayClassName="popup-container"
        placement="leftBottom"
        :getPopupContainer="(triggerNode: any) => triggerNode.parentNode">
        <template #content>
          <div class="popup-text">返回将退出航线编辑器,您要保存吗?如果不保存,您更改的内容将会丢失。</div>
          <div class="btn-tool">
            <a-button size="small" class="btn-cancel" @click="modfiyPopupShow = false">取消</a-button>
            <a-button size="small" class="btn-cancel" @click="handleModfiySave(false)">不保存</a-button>
            <a-button size="small" type="primary" @click="handleModfiySave(true)">保存</a-button>
          </div>
        </template>
        <a-button type="text" @click="backPage">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
      </a-popover>
      <div class="save-button" @click="saveWaylineFile">
        <SaveOutlined />
      </div>
      <setting v-model:loadCompleted="loadCompleted">
        <template #show>
          <a-button type="text" class="setting-btn">
            <div class="router-setting">
              <img class="wayline-icon" :src="getResource('wayline.png')" alt="icon" />
              <span class="text">航线设置</span>
              <CaretDownOutlined />
            </div>
          </a-button>
        </template>
      </setting>
    </div>
    <div class="wayline-info">
      <div class="info-box" v-for="(item, index) in waylineDetails" :key="index">
        <div class="title">{{ item.title }}</div>
        <div class="info">{{ item.value }}</div>
      </div>
    </div>
    <ul class="point-list">
      <li
        v-for="(item, index) in tragetPointArr"
        :key="index"
        :class="{ 'active-point': index == selectPointIndex }"
        @click="pointSelect(item, index)">
        <a-tooltip placement="top">
          <template #title>
            <span>{{ item.isUseGlobalHeight ? '跟随全局' : '不跟随全局' }}</span>
          </template>
          <div class="graph">
            <div class="left" :style="{ borderTopColor: item.isUseGlobalHeight ? '#61d396' : '#409eff' }"></div>
            <div class="right">{{ index + 1 }}</div>
          </div>
        </a-tooltip>
        <contextMenu :menu="[{ title: '删除航点', value: { index, item } }]">
          <div class="graph-right">
            <div v-for="(event, index) in item.eventList" :key="index" class="s-event-icon">
              <a-tooltip placement="top">
                <template #title>
                  {{ event.name }}
                </template>
                <img :src="event.icon" alt="icon" />
              </a-tooltip>
            </div>
          </div>
        </contextMenu>
      </li>
    </ul>
  </div>
</template>
 
<script setup lang="ts">
import _ from 'lodash'
import * as Cesium from 'cesium'
import setting from './components/setting.vue'
import useKmzTsa, { kmlStr, template as xmlTemplate } from '/@/utils/cesium/use-kmz-tsa'
import { ref, defineEmits, defineProps, watch, onMounted } from 'vue'
import { ArrowLeftOutlined, CaretDownOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { cesiumOperation } from '/@/hooks/use-cesium-tsa'
import { useMyStore } from '/@/store'
import useMapDraw, { kmlEntities as globalEntities, selectPointIndex as pointIdx } from '/@/utils/cesium/use-map-draw'
import contextMenu from './components/content-menu.vue'
const store = useMyStore()
const { appContext }: any = getCurrentInstance()
const global = appContext.config.globalProperties
 
const kmzUtils = useKmzTsa()
 
const { removeAllPoint, getEntityById, addPolyline, removeAllDataSource, addRightClick, removeRightClickEvent } =
  cesiumOperation()
 
interface waylineDetails {
  title: string
  value: number | string
}
interface eventParmas {
  key: string
  name: string
  distinguish?: string
  icon?: string
}
 
interface tragetPoint {
  position: Cesium.Cartesian3
  isUseGlobalHeight: boolean
  eventList: eventParmas[]
}
 
const getResource = (name: string) => {
  return new URL(`/src/assets/icons/${name}`, import.meta.url).href
}
 
const ellipsoid = global.$viewer.scene.globe.ellipsoid
 
const emits = defineEmits(['backFn'])
const props = defineProps<{
  isCreateWayline: boolean
}>()
 
const filePath = computed(() => store.state.waylineTool.kmzPath)
 
const tragetPointArr = ref<tragetPoint[]>([])
 
let kmlDataSource: { entities: { values: { _children: any }[] }; show: boolean } | null | any = null
 
let mouseRightClickEvent: any = null
 
// 绘制地图上的东西
let mapDraw: any = null
// 航线详情
const waylineDetails = ref<waylineDetails[]>([])
// 样式
const kmlEntities = ref<Cesium.Entity[]>([])
 
const loadCompleted = ref<boolean>(false)
 
// 编辑时初始化
const initDrawRoute = () => {
  const options = {
    camera: global.$viewer.scene.camera,
    canvas: global.$viewer.scene.canvas,
    screenOverlayContainer: global.$viewer.container,
  }
  if (kmlDataSource) {
    global.$viewer.dataSources.remove(kmlDataSource)
  }
  global.$viewer.dataSources.add(Cesium.KmlDataSource.load(filePath.value, options)).then((res: any) => {
    kmlDataSource = res
    mapDraw = useMapDraw(kmlDataSource, [], filePath.value, global)
    const {
      drawWayline,
      waylineDetails: details,
      waylinePointsEvent,
      kmlEntities: entities,
      clearWaylineData,
    } = mapDraw
    clearWaylineData()
    drawWayline()
    kmzUtils.init(filePath.value).then((kmlRes) => {
      loadCompleted.value = true
    })
    waylineDetails.value = details
    tragetPointArr.value = waylinePointsEvent.value
    watch(
      () => waylinePointsEvent.value,
      (val) => {
        tragetPointArr.value = val
      },
      {
        deep: true,
      },
    )
 
    kmlEntities.value = entities.value
    if (!mouseRightClickEvent) {
      // 添加右键事件
      addMapPointEvent()
    }
  })
}
// 新建航线初始化
const initCreateRoute = () => {
  mapDraw = useMapDraw('', [], '', global)
  const xml = kmzUtils.generateXML(xmlTemplate.value)
  mapDraw.drawWayline([], xml)
}
 
// 创建广告牌
const createBillboard = (title: string | number, color: string) => {
  // 创建canvas绘制广告牌
  const billboard = document.createElement('canvas')
  billboard.width = 30
  billboard.height = 30
  const ctx: HTMLCanvasElement | any = billboard.getContext('2d')
  ctx.beginPath()
  ctx.moveTo(0, 0)
  ctx.lineTo(30, 0)
  ctx.lineTo(15, 22)
  ctx.fillStyle = color
  ctx.fill()
  ctx.font = '18px serif'
  ctx.fillStyle = '#ffffff'
  ctx.fillText(Number(title) === 1 ? 'S' : title, 10, 15)
  ctx.closePath()
  return billboard
}
 
// 选择点位
let prevPointEntity: any = null
let nextPointEntity: any = null
// 选中的点
const selectPointIndex = ref<string | number | any>(null)
const pointSelect = (value: tragetPoint, index: number) => {
  removeCesiumChildDom(popupDom)
  if (selectPointIndex.value === index) {
    global.$viewer.entities.remove(prevPointEntity)
    global.$viewer.entities.remove(nextPointEntity)
    kmlEntities.value.forEach((entity: Cesium.Entity | any, i: number) => {
      entity.billboard.image = createBillboard(i + 1, '#61d396')
      entity.label.show = false
    })
    selectPointIndex.value = null
    pointIdx.value = null
    return
  }
  if (prevPointEntity) {
    global.$viewer.entities.remove(prevPointEntity)
  }
  if (nextPointEntity) {
    global.$viewer.entities.remove(nextPointEntity)
  }
  // 点击点相邻两个点的距离
  const points = _.cloneDeep(tragetPointArr.value)
  const currentPoint = points[index]?.position
  const prevPoint = points[index - 1]?.position
  const nextPoint = points[index + 1]?.position
  if (prevPoint) {
    // 获取中心点
    const centerPoint = Cesium.Cartesian3.lerp(currentPoint, prevPoint, 0.5, new Cesium.Cartesian3())
    // 获取两个点之间的距离
    let distance = Cesium.Cartesian3.distance(currentPoint, prevPoint)
    distance = Math.round(distance)
    prevPointEntity = createDistanceLabel(centerPoint, distance)
  }
  if (nextPoint) {
    // 获取中心点
    const centerPoint = Cesium.Cartesian3.lerp(currentPoint, nextPoint, 0.5, new Cesium.Cartesian3())
    // 获取两个点之间的距离
    let distance = Cesium.Cartesian3.distance(currentPoint, nextPoint)
    distance = Math.round(distance)
    nextPointEntity = createDistanceLabel(centerPoint, distance)
  }
  // 更新点击点的样式
  kmlEntities.value.forEach((entity: Cesium.Entity | any, i: number) => {
    if (i === index) {
      entity.billboard.image = createBillboard(index + 1, '#f3be4f')
      const dashLineEntity: Cesium.Entity | any = getEntityById(`dashLine${i}`)
      dashLineEntity.polyline.material = new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.fromBytes(235, 192, 99),
      })
      entity.label.show = true
    } else {
      entity.billboard.image = createBillboard(i + 1, '#61d396')
      const dashLineEntity: Cesium.Entity | any = getEntityById(`dashLine${i}`)
      dashLineEntity.polyline.material = new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.WHITE,
      })
      entity.label.show = false
    }
  })
  selectPointIndex.value = index
  pointIdx.value = index
}
 
// 添加右键事件,弹出窗口
const showCreatePointPopup = ref<boolean>(false)
let popupDom: any = null
const addMapPointEvent = () => {
  mouseRightClickEvent = true
  addRightClick('', (click: { position: Cesium.Cartesian2 }) => {
    showCreatePointPopup.value = true
    removeCesiumChildDom(popupDom)
    const { position } = click
    const { x, y } = position
    const pointEvents = [
      {
        class: 'add-prev-point',
        title: `在${Number(selectPointIndex.value) + 1}号航点前插入`,
      },
      {
        class: 'add-next-point',
        title: `在${Number(selectPointIndex.value) + 1}号航点后插入`,
      },
    ]
    const defaultEvents = [{ class: 'finally-point', title: '在最后航点新增航点' }]
    const events = selectPointIndex.value !== null ? [...defaultEvents, ...pointEvents] : defaultEvents
    popupDom = createPointPopupDom(events)
    global.$viewer.container.appendChild(popupDom)
    popupDom.style.transform = `translate3d(${x}px, ${y}px, 0)`
    // 添加点击事件
    addMenuEvent(popupDom, position)
  })
}
 
// 创建距离标签
const createDistanceLabel = (position: Cesium.Cartesian3, dist: number) => {
  return global.$viewer.entities.add({
    position: position,
    name: 'distance',
    label: {
      text: `${dist}m`,
      font: '13px monospace',
      showBackground: true,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      pixelOffset: new Cesium.Cartesian2(0, -0),
    },
  })
}
 
// 创建右键弹窗
const createPointPopupDom = (arr: any[] = []) => {
  const pointPopup: HTMLDivElement | any = document.createElement('div')
  pointPopup.className = 'point-popup'
  arr.forEach((item) => {
    const title: HTMLDivElement | any = document.createElement('div')
    title.innerText = item.title
    title.className = item.class
    title.style = `
      cursor: pointer;
      padding: 5px 7px;
    `
    pointPopup.appendChild(title)
  })
  pointPopup.style = `
    width: 'fit-content';
    background-color: #232323;
    position: absolute;
    top: 0;
    left: 0;
    color: #fff;
  `
  return pointPopup
}
 
// 给DOM添加点击事件
const addMenuEvent = (dom: HTMLElement, position: Cesium.Cartesian2) => {
  dom.addEventListener('click', (e: any) => {
    removeCesiumChildDom(popupDom)
    const className = e.target.className
    const c3Position = global.$viewer.scene.globe.pick(global.$viewer.camera.getPickRay(position), global.$viewer.scene)
    const c2Postion = ellipsoid.cartesianToCartographic(c3Position)
    const longitude = Cesium.Math.toDegrees(c2Postion.longitude)
    const latitude = Cesium.Math.toDegrees(c2Postion.latitude)
    // 获取全局高度
    const globalHeight: string = xmlTemplate.value.Folder.globalHeight['#text']
    const height = Number(globalHeight)
    // 右键点击的位置
    const createPointPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
    const entity: Cesium.Entity = global.$viewer.entities.add({
      position: createPointPosition,
    })
    // 起飞点海拔
    const takeOffRefPointAGLHeight = xmlTemplate.value.missionConfig.takeOffRefPointAGLHeight
    const posterHeight = Number(takeOffRefPointAGLHeight['#text'])
    // 当前点位个数
    const points = xmlTemplate.value.Folder.Placemark
    // 加入到解析的JSON对象中
    const setting = {
      Point: {
        coordinates: { '#text': `${longitude},${latitude}` },
      },
      index: { '#text': points.length },
      ellipsoidHeight: { '#text': height - posterHeight },
      height: { '#text': height },
      useGlobalHeadingParam: { '#text': 1 },
      useGlobalHeight: { '#text': 1 },
      useGlobalSpeed: { '#text': 1 },
      useGlobalTurnParam: { '#text': 1 },
      useStraightLine: { '#text': 1 },
      waypointHeadingParam: {
        waypointHeadingAngle: { '#text': 0 },
        waypointHeadingMode: { '#text': 'followWayline' },
        waypointHeadingPathMode: { '#text': 'followBadArc' },
        waypointHeadingPoiIndex: { '#text': 0 },
        waypointPoiPoint: { '#text': '0.000000,0.000000,0.000000' },
      },
      waypointSpeed: { '#text': 10 },
      waypointTurnParam: {
        waypointTurnDampingDist: { '#text': 0.2 },
        waypointTurnMode: { '#text': 'toPointAndStopWithDiscontinuityCurvature' },
      },
      isRisky: { '#text': 0 },
    }
    if (className === 'finally-point') {
      globalEntities.value.push(entity)
      xmlTemplate.value.Folder.Placemark.push(setting)
      tragetPointArr.value.push({
        position: createPointPosition,
        eventList: [],
        isUseGlobalHeight: Boolean(setting.useGlobalHeight['#text']),
      })
    }
    if (className === 'add-prev-point') {
      globalEntities.value.splice(selectPointIndex.value, 0, entity)
      xmlTemplate.value.Folder.Placemark.splice(selectPointIndex.value, 0, setting)
      tragetPointArr.value.splice(selectPointIndex.value, 0, {
        position: createPointPosition,
        eventList: [],
        isUseGlobalHeight: Boolean(setting.useGlobalHeight['#text']),
      })
    }
    if (className === 'add-next-point') {
      const index = _.cloneDeep(selectPointIndex.value + 1)
      globalEntities.value.splice(index, 0, entity)
      xmlTemplate.value.Folder.Placemark.splice(index, 0, setting)
      tragetPointArr.value.splice(index, 0, {
        position: createPointPosition,
        eventList: [],
        isUseGlobalHeight: Boolean(setting.useGlobalHeight['#text']),
      })
    }
    // 更新点位序号
    xmlTemplate.value.Folder.Placemark.forEach((placemark: { index: { [x: string]: number } }, index: number) => {
      placemark.index['#text'] = index
    })
    const xmlStr = kmzUtils.generateXML(xmlTemplate.value)
    mapDraw.drawWayline(globalEntities.value, xmlStr)
  })
}
 
// 移除popup弹窗
const removeCesiumChildDom = (dom: HTMLElement) => {
  if (dom) {
    global.$viewer.container.removeChild(dom)
    popupDom = null
  }
}
 
const modfiyPopupShow = ref<boolean>(false)
const backPage = () => {
  if (isModify.value) {
    modfiyPopupShow.value = true
  } else {
    mapDraw.clearWaylineData()
    kmlStr.value = ''
    emits('backFn')
  }
}
const handleModfiySave = (isSave: boolean) => {
  if (isSave) {
    saveWaylineFile()
    modfiyPopupShow.value = false
  } else {
    mapDraw.clearWaylineData()
    kmlStr.value = ''
    emits('backFn')
  }
}
// 清空画布
const clearCesiumMap = () => {
  removeAllPoint()
  global.$viewer.dataSources.removeAll()
 
  removeCesiumChildDom(popupDom)
 
  if (mouseRightClickEvent) {
    removeRightClickEvent()
  }
}
 
// 保存文件
const saveWaylineFile = () => {
  kmzUtils.save()
  mapDraw.clearWaylineData()
  kmlStr.value = ''
  emits('backFn')
}
 
// 判断当前文件是否被修改
const isModify = ref<boolean>(false)
watch(
  () => kmlStr.value,
  (val) => {
    isModify.value = true
  },
  {
    deep: true,
  },
)
 
onMounted(() => {
  // 清空画布
  clearCesiumMap()
  console.log(!!filePath.value)
  if (filePath.value) {
    initDrawRoute()
  } else {
    initCreateRoute()
  }
})
 
onUnmounted(() => {
  // if (kmlDataSource) {
  //   global.$viewer.dataSources.remove(kmlDataSource)
  // }
  clearCesiumMap()
  store.commit('SET_WAYLINE_INFO', {
    isShow: false,
    wayline: {},
    position: null,
  })
})
</script>
 
<style lang="scss" scoped>
.route-edit-box {
  .btn-group {
    height: 49px;
    width: 100%;
    border-bottom: 1px solid #4f4f4f;
    display: flex;
    align-items: center;
    justify-content: flex-start;
 
    :deep() {
      .popup-container {
        .ant-popover-content {
          .ant-popover-arrow,
          .ant-popover-inner {
            border-color: #282828;
            background-color: #282828;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
            .popup-text {
              color: #fff;
              width: 400px;
            }
            .btn-tool {
              margin-top: 10px;
              display: flex;
              justify-content: flex-end;
              .ant-btn {
                border: 0;
              }
              .btn-cancel {
                background-color: #3c3c3c;
                margin-right: 5px;
              }
            }
          }
        }
      }
    }
    .ant-btn {
      color: #fff;
    }
 
    .save-button {
      font-size: 20px;
      margin: 0 10px 0 auto;
      cursor: pointer;
 
      &:hover {
        color: #409eff;
      }
    }
 
    .setting-btn {
      background-color: #3c3c3c;
      margin-right: 10px;
 
      .router-setting {
        display: flex;
        align-items: center;
 
        .wayline-icon {
          width: 16px;
          height: 16px;
        }
 
        .text {
          margin: 0 3px;
        }
      }
    }
  }
 
  .wayline-info {
    display: flex;
    height: 50px;
    margin: 10px 0;
    text-align: center;
    align-items: center;
 
    .info-box {
      flex: 1;
      border-right: 1px solid hsla(0, 0%, 100%, 0.1);
 
      .title {
        color: hsla(0, 0%, 100%, 0.65);
        font-size: 12px;
        font-weight: bold;
      }
 
      .info {
        font-weight: bold;
      }
 
      &:last-child {
        border: 0;
      }
    }
  }
 
  .point-list {
    padding: 0;
    height: calc(100vh - 180px);
    overflow: auto;
 
    li {
      cursor: pointer;
      padding: 10px 0;
      margin: 0 7px;
      display: flex;
 
      .graph {
        width: 40px;
        display: flex;
        align-items: center;
 
        .left {
          width: 0;
          height: 0;
          border-top: 15px solid #61d396;
          border-right: 10px solid transparent;
          border-left: 10px solid transparent;
        }
 
        .right {
          margin-left: 3px;
        }
      }
 
      .graph-right {
        width: 100%;
        height: 30px;
        border-bottom: 1px solid #4f4f4f;
        display: flex;
        align-items: center;
 
        .s-event-icon {
          width: 25px;
          height: 25px;
          display: flex;
          justify-content: center;
          align-items: center;
 
          img {
            width: 70%;
          }
        }
      }
 
      &:hover {
        background-color: #3c3c3c;
      }
    }
  }
}
 
.active-point {
  background-color: #3c3c3c;
 
  .graph {
    .left {
      border-top-color: #f3bf4e !important;
    }
  }
}
</style>