吉安感知网项目-前端
chenyao
21 hours ago c567cbca3b78a7e06a827acbab56a46657e31aa1
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
import * as Cesium from 'cesium'
import { MapTooltip } from '@ztzf/utils'
import { ToolBase } from '../ToolBase'
 
const POINT_ENTITY_NAME = 'draw-polygon-point'
const DEFAULT_STYLE = {
    fill: Cesium.Color.fromBytes(45, 140, 240, 99),
    outline: Cesium.Color.fromBytes(45, 140, 240, 255),
}
const resolveStyle = style => ({
    fill: style?.fill || DEFAULT_STYLE.fill,
    outline: style?.outline || DEFAULT_STYLE.outline,
})
const resolveColorWithAlpha = (baseColor, alphaSource) => {
    if (!baseColor) return alphaSource
    const alpha = typeof alphaSource?.alpha === 'number' ? alphaSource.alpha : 1
    return baseColor.withAlpha(alpha)
}
 
const normalizeRing = points => {
    if (!Array.isArray(points)) return []
    const ring = points.filter(Boolean)
    if (ring.length < 2) return ring
    const first = ring[0]
    const last = ring[ring.length - 1]
    if (Cesium.Cartesian3.equals(first, last)) {
        return ring.slice(0, -1)
    }
    return ring
}
 
const isSelfIntersecting = positions => {
    const ring = normalizeRing(positions)
    if (ring.length < 4) return false
    const epsilon = 1e-12
    const toPoint = cartesian => {
        const carto = Cesium.Cartographic.fromCartesian(cartesian)
        return { x: carto.longitude, y: carto.latitude }
    }
    const pts = ring.map(toPoint)
    const orientation = (a, b, c) => {
        const value = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y)
        if (Math.abs(value) < epsilon) return 0
        return value > 0 ? 1 : 2
    }
    const onSegment = (a, b, c) =>
        b.x <= Math.max(a.x, c.x) + epsilon &&
        b.x + epsilon >= Math.min(a.x, c.x) &&
        b.y <= Math.max(a.y, c.y) + epsilon &&
        b.y + epsilon >= Math.min(a.y, c.y)
    const segmentsIntersect = (p1, q1, p2, q2) => {
        const o1 = orientation(p1, q1, p2)
        const o2 = orientation(p1, q1, q2)
        const o3 = orientation(p2, q2, p1)
        const o4 = orientation(p2, q2, q1)
        if (o1 !== o2 && o3 !== o4) return true
        if (o1 === 0 && onSegment(p1, p2, q1)) return true
        if (o2 === 0 && onSegment(p1, q2, q1)) return true
        if (o3 === 0 && onSegment(p2, p1, q2)) return true
        if (o4 === 0 && onSegment(p2, q1, q2)) return true
        return false
    }
    const count = pts.length
    for (let i = 0; i < count; i += 1) {
        const p1 = pts[i]
        const q1 = pts[(i + 1) % count]
        for (let j = i + 1; j < count; j += 1) {
            const isAdjacent = j === i || j === i + 1 || (i === 0 && j === count - 1)
            if (isAdjacent) continue
            const p2 = pts[j]
            const q2 = pts[(j + 1) % count]
            if (segmentsIntersect(p1, q1, p2, q2)) return true
        }
    }
    return false
}
 
export class DrawPolygonTool extends ToolBase {
    constructor(viewer, options = {}) {
        super(viewer)
        this.tooltip = new MapTooltip(viewer)
        this.dataSource = null
        this.polygonEntity = null
        this.polylineEntity = null
        this.positions = []
        this.floatPosition = null
        this.isDrawing = false
        this.lastMousePosition = null
        this.isIntersecting = false
        this.style = resolveStyle(options?.style)
    }
 
    start() {
        if (!this.tooltip) {
            this.tooltip = new MapTooltip(this.viewer)
        }
        this.dataSource = new Cesium.CustomDataSource('draw-polygon')
        this.viewer.dataSources.add(this.dataSource)
        this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
        this.handler.setInputAction(click => this.handleLeftClick(click), Cesium.ScreenSpaceEventType.LEFT_CLICK)
        this.handler.setInputAction(click => this.handleRightClick(click), Cesium.ScreenSpaceEventType.RIGHT_CLICK)
        this.handler.setInputAction(movement => this.handleMouseMove(movement), Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        this.isDrawing = true
        this.tooltip.hide()
    }
 
    handleLeftClick(click) {
        if (!this.isDrawing) return
 
        const pickedEntity = this.viewer.scene.pick(click.position)?.id
        if (this.isFinishTrigger(pickedEntity)) {
            this.finishDrawing()
            return
        }
        if (pickedEntity?.name === POINT_ENTITY_NAME) return
 
        const position = this.getPositionFromScreen(click.position)
        if (!position) return
 
        const preview = [...this.positions, position]
        if (isSelfIntersecting(preview)) {
            this.isIntersecting = true
            this.tooltip.show(this.getTipText(), click.position)
            return
        }
 
        this.addPoint(position)
        this.tooltip.show(this.getTipText(), click.position)
    }
 
    handleRightClick(click) {
        if (!this.isDrawing) return
        const pickedEntity = this.viewer.scene.pick(click.position)?.id
        if (!pickedEntity || pickedEntity.name !== POINT_ENTITY_NAME) return
        const index = pickedEntity.customData?.index
        if (typeof index !== 'number') return
        this.removePoint(index)
        this.tooltip.show(this.getTipText(), click.position)
    }
 
    handleMouseMove(movement) {
        if (!this.isDrawing) return
        const tipText = this.getTipText()
        if (!this.tooltip?.isVisible) {
            this.tooltip?.show(tipText, movement.endPosition)
        } else {
            this.tooltip?.show(tipText)
            this.tooltip?.move(movement.endPosition)
        }
        if (this.positions.length === 0) return
        const position = this.getPositionFromScreen(movement.endPosition)
        if (!position) return
        this.lastMousePosition = position
        this.floatPosition = position
    }
 
    getTipText() {
        const preview = this.getPreviewPositions()
        this.isIntersecting = isSelfIntersecting(preview)
        if (this.isIntersecting) {
            return '区域存在交叉,请调整位置'
        }
        const count = this.positions.length
        if (count === 0) {
            return '单击增加点'
        }
        if (count < 3) {
            return '单击增加点,右击删除点'
        }
        return '单击增加点,右击删除点,双击结束绘制'
    }
 
    isFinishTrigger(pickedEntity) {
        if (!pickedEntity || pickedEntity.name !== POINT_ENTITY_NAME) return false
        if (this.positions.length < 3) return false
        const index = pickedEntity.customData?.index
        return index === this.positions.length - 1
    }
 
    addPoint(position) {
        this.positions.push(position)
        if (!this.polygonEntity) {
            this.createEntities()
        }
        this.rebuildPointEntities()
    }
 
    removePoint(index) {
        if (index < 0 || index >= this.positions.length) return
        this.positions.splice(index, 1)
        this.rebuildPointEntities()
        if (this.positions.length === 0) {
            this.floatPosition = null
            this.lastMousePosition = null
            return
        }
        if (this.lastMousePosition) {
            this.floatPosition = this.lastMousePosition
        } else {
            this.floatPosition = this.positions[this.positions.length - 1]
        }
    }
 
    getPreviewPositions() {
        if (this.positions.length === 0) return []
        if (!this.isDrawing || !this.floatPosition) return this.positions
        return [...this.positions, this.floatPosition]
    }
 
    createEntities() {
        const getIntersecting = () => {
            const preview = this.getPreviewPositions()
            this.isIntersecting = isSelfIntersecting(preview)
            return this.isIntersecting
        }
 
        this.polygonEntity = this.dataSource.entities.add({
            polygon: {
                hierarchy: new Cesium.CallbackProperty(
                    () => new Cesium.PolygonHierarchy(this.getPreviewPositions()),
                    false
                ),
                material: new Cesium.ColorMaterialProperty(
                    new Cesium.CallbackProperty(() => {
                        if (getIntersecting()) return resolveColorWithAlpha(Cesium.Color.RED, this.style.fill)
                        return this.style.fill
                    }, false)
                ),
                outline: false,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                show: new Cesium.CallbackProperty(() => this.getPreviewPositions().length >= 3, false),
            },
        })
 
        this.polylineEntity = this.dataSource.entities.add({
            polyline: {
                positions: new Cesium.CallbackProperty(() => {
                    const positions = this.getPreviewPositions()
                    if (positions.length < 2) return positions
                    if (positions.length >= 3) {
                        return [...positions, positions[0]]
                    }
                    return positions
                }, false),
                clampToGround: true,
                width: 2,
                material: new Cesium.ColorMaterialProperty(
                    new Cesium.CallbackProperty(() => {
                        if (getIntersecting()) return resolveColorWithAlpha(Cesium.Color.RED, this.style.outline)
                        return this.style.outline
                    }, false)
                ),
                show: new Cesium.CallbackProperty(() => this.getPreviewPositions().length >= 2, false),
            },
        })
    }
 
    rebuildPointEntities() {
        this.dataSource.entities.values
            .slice()
            .filter(entity => entity?.name === POINT_ENTITY_NAME)
            .forEach(entity => this.dataSource.entities.remove(entity))
 
        this.positions.forEach((position, index) => {
            this.dataSource.entities.add({
                name: POINT_ENTITY_NAME,
                position: position.clone ? position.clone() : position,
                point: {
                    pixelSize: 12,
                    color: Cesium.Color.WHITE,
                    outlineColor: this.style.outline,
                    outlineWidth: 2,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                },
                customData: {
                    index,
                },
            })
        })
    }
 
    finishDrawing() {
        if (this.positions.length < 3) return
        this.isDrawing = false
        this.floatPosition = null
        this.isIntersecting = false
        this.notify('getPolygonPositions', this.positions)
        this.tooltip?.hide()
        this.clearPreviewEntities()
    }
 
    setStyle(style) {
        this.style = resolveStyle(style)
        if (this.dataSource) {
            this.dataSource.entities.values
                .filter(entity => entity?.name === POINT_ENTITY_NAME)
                .forEach(entity => {
                    if (entity?.point) {
                        entity.point.outlineColor = this.style.outline
                    }
                })
        }
    }
 
    clearPreviewEntities() {
        if (!this.dataSource) return
        this.dataSource.entities.removeAll()
        this.polygonEntity = null
        this.polylineEntity = null
        this.isIntersecting = false
    }
 
    getPositionFromScreen(screenPosition) {
        const scene = this.viewer.scene
        const cartesian = scene.pickPosition(screenPosition)
        if (cartesian) return cartesian
        return scene.camera.pickEllipsoid(screenPosition, scene.globe.ellipsoid)
    }
 
    destroy() {
        if (this.dataSource) {
            this.dataSource.entities.removeAll()
            this.viewer.dataSources.remove(this.dataSource)
            this.dataSource = null
        }
        if (this.handler) {
            this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
            this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
            this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
            this.handler.destroy()
            this.handler = null
        }
        this.tooltip?.destroy()
        this.tooltip = null
        this.positions = []
        this.floatPosition = null
        this.isDrawing = false
        this.lastMousePosition = null
        this.isIntersecting = false
    }
}