forked from minorua/Qgis2threejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeometry.py
479 lines (372 loc) · 14.2 KB
/
geometry.py
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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Qgis2threejs
A QGIS plugin
export terrain data, map canvas image and vector data to web browser
-------------------
copyright : (C) 2014 Minoru Akagi
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from osgeo import ogr
from qgis.core import (
QgsGeometry, QgsPointXY, QgsRectangle, QgsFeature, QgsSpatialIndex, QgsCoordinateTransform, QgsFeatureRequest,
QgsPoint, QgsMultiPoint, QgsLineString, QgsMultiLineString)
from .qgis2threejstools import logMessage
class Point:
def __init__(self, x, y, z=0):
self.x = x
self.y = y
self.z = z
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z
def __ne__(self, other):
return self.x != other.x or self.y != other.y or self.z != other.z
def pointToQgsPoint(point):
return QgsPointXY(point.x, point.y)
def lineToQgsPolyline(line):
return [pointToQgsPoint(pt) for pt in line]
def polygonToQgsPolygon(polygon):
return [lineToQgsPolyline(line) for line in polygon]
class Geometry:
NotUseZM = 0
UseZ = 1
UseM = 2
class PointGeometry(Geometry):
def __init__(self):
self.pts = []
def asList(self):
return [[pt.x, pt.y, pt.z] for pt in self.pts]
def toQgsGeometry(self):
count = len(self.pts)
if count > 1:
pts = [pointToQgsPoint(pt) for pt in self.pts]
return QgsGeometry.fromMultiPointXY(pts)
if count == 1:
return QgsGeometry.fromPointXY(pointToQgsPoint(self.pts[0]))
return QgsGeometry()
@classmethod
def fromQgsGeometry(cls, geometry, z_func, transform_func, useZM=Geometry.NotUseZM):
geom = cls()
if useZM == Geometry.NotUseZM:
pts = geometry.asMultiPoint() if geometry.isMultipart() else [geometry.asPoint()]
geom.pts = [transform_func(pt.x(), pt.y(), z_func(pt.x(), pt.y())) for pt in pts]
else:
g = geometry.geometry()
if isinstance(g, QgsPoint):
pts = [g]
elif isinstance(g, QgsMultiPoint):
pts = [g.geometryN(i) for i in range(g.numGeometries())]
else:
logMessage("Unknown point geometry type: " + type(g))
pts = []
if useZM == Geometry.UseZ:
geom.pts = [transform_func(pt.x(), pt.y(), pt.z() + z_func(pt.x(), pt.y())) for pt in pts]
else: # UseM
geom.pts = [transform_func(pt.x(), pt.y(), pt.m() + z_func(pt.x(), pt.y())) for pt in pts]
return geom
#TODO: remove
@staticmethod
def fromOgrGeometry25D(geometry, transform_func):
geomType = geometry.GetGeometryType()
if geomType == ogr.wkbPoint25D:
geoms = [geometry]
elif geomType == ogr.wkbMultiPoint25D:
geoms = [geometry.GetGeometryRef(i) for i in range(geometry.GetGeometryCount())]
else:
return None
pts = []
for geom in geoms:
if hasattr(geom, "GetPoints"):
pts += geom.GetPoints()
else:
pts += [geom.GetPoint(i) for i in range(geom.GetPointCount())]
point_geom = PointGeometry()
point_geom.pts = [transform_func(pt[0], pt[1], pt[2]) for pt in pts]
return point_geom
class LineGeometry(Geometry):
def __init__(self):
self.lines = []
def asList(self):
return [[[pt.x, pt.y, pt.z] for pt in line] for line in self.lines]
def asList2(self):
return [[[pt.x, pt.y] for pt in line] for line in self.lines]
def toQgsGeometry(self):
count = len(self.lines)
if count > 1:
lines = [lineToQgsPolyline(line) for line in self.lines]
return QgsGeometry.fromMultiPolylineXY(lines)
if count == 1:
return QgsGeometry.fromPolylineXY(lineToQgsPolyline(self.lines[0]))
return QgsGeometry()
@classmethod
def fromQgsGeometry(cls, geometry, z_func, transform_func, useZM=Geometry.NotUseZM):
geom = cls()
if useZM == Geometry.NotUseZM:
lines = geometry.asMultiPolyline() if geometry.isMultipart() else [geometry.asPolyline()]
geom.lines = [[transform_func(pt.x(), pt.y(), z_func(pt.x(), pt.y())) for pt in line] for line in lines]
else:
g = geometry.geometry()
if isinstance(g, QgsLineString):
lines = [g.points()]
elif isinstance(g, QgsMultiLineString):
lines = [g.geometryN(i).points() for i in range(g.numGeometries())]
else:
logMessage("Unknown line geometry type: " + type(g))
lines = []
if useZM == Geometry.UseZ:
geom.lines = [[transform_func(pt.x(), pt.y(), pt.z() + z_func(pt.x(), pt.y())) for pt in line] for line in lines]
else: # UseM
geom.lines = [[transform_func(pt.x(), pt.y(), pt.m() + z_func(pt.x(), pt.y())) for pt in line] for line in lines]
return geom
#TODO: remove
@staticmethod
def fromOgrGeometry25D(geometry, transform_func):
geomType = geometry.GetGeometryType()
if geomType == ogr.wkbLineString25D:
geoms = [geometry]
elif geomType == ogr.wkbMultiLineString25D:
geoms = [geometry.GetGeometryRef(i) for i in range(geometry.GetGeometryCount())]
else:
return None
line_geom = LineGeometry()
for geom in geoms:
if hasattr(geom, "GetPoints"):
pts = geom.GetPoints()
else:
pts = [geom.GetPoint(i) for i in range(geom.GetPointCount())]
points = [transform_func(pt[0], pt[1], pt[2]) for pt in pts]
line_geom.lines.append(points)
return line_geom
class PolygonGeometry(Geometry):
def __init__(self):
self.polygons = []
self.centroids = []
self.split_polygons = []
def splitPolygon(self, triMesh):
"""split polygon by TriangleMesh"""
self.split_polygons = []
for polygon in triMesh.splitPolygons(self.toQgsGeometry()):
boundaries = []
# outer boundary
points = [Point(pt.x(), pt.y(), 0) for pt in polygon[0]]
if not GeometryUtils.isClockwise(points):
points.reverse() # to clockwise
boundaries.append(points)
# inner boundaries
for boundary in polygon[1:]:
points = [Point(pt.x(), pt.y(), 0) for pt in boundary]
if GeometryUtils.isClockwise(points):
points.reverse() # to counter-clockwise
boundaries.append(points)
self.split_polygons.append(boundaries)
def asList(self):
p = []
for boundaries in self.polygons:
# outer boundary
pts = [[pt.x, pt.y, pt.z] for pt in boundaries[0]]
if not GeometryUtils.isClockwise(boundaries[0]):
pts.reverse() # to clockwise
b = [pts]
# inner boundaries
for boundary in boundaries[1:]:
pts = [[pt.x, pt.y, pt.z] for pt in boundary]
if GeometryUtils.isClockwise(boundary):
pts.reverse() # to counter-clockwise
b.append(pts)
p.append(b)
return p
def toQgsGeometry(self):
count = len(self.polygons)
if count > 1:
polys = [polygonToQgsPolygon(poly) for poly in self.polygons]
return QgsGeometry.fromMultiPolygonXY(polys)
if count == 1:
return QgsGeometry.fromPolygonXY(polygonToQgsPolygon(self.polygons[0]))
return QgsGeometry()
#TODO: z/m support
@classmethod
def fromQgsGeometry(cls, geometry, z_func, transform_func, calcCentroid=False):
useCentroidHeight = True
centroidPerPolygon = True
polygons = geometry.asMultiPolygon() if geometry.isMultipart() else [geometry.asPolygon()]
geom = cls()
if calcCentroid and not centroidPerPolygon:
pt = geometry.centroid().asPoint()
centroidHeight = z_func(pt.x(), pt.y())
geom.centroids.append(transform_func(pt.x(), pt.y(), centroidHeight))
for polygon in polygons:
if useCentroidHeight or calcCentroid:
centroid = QgsGeometry.fromPolygonXY(polygon).centroid()
if centroid is None:
continue
pt = centroid.asPoint()
centroidHeight = z_func(pt.x(), pt.y())
if calcCentroid and centroidPerPolygon:
geom.centroids.append(transform_func(pt.x(), pt.y(), centroidHeight))
if useCentroidHeight:
z_func = lambda x, y: centroidHeight
boundaries = []
# outer boundary
points = []
for pt in polygon[0]:
points.append(transform_func(pt.x(), pt.y(), z_func(pt.x(), pt.y())))
if not GeometryUtils.isClockwise(points):
points.reverse() # to clockwise
boundaries.append(points)
# inner boundaries
for boundary in polygon[1:]:
points = [transform_func(pt.x(), pt.y(), z_func(pt.x(), pt.y())) for pt in boundary]
if GeometryUtils.isClockwise(points):
points.reverse() # to counter-clockwise
boundaries.append(points)
geom.polygons.append(boundaries)
return geom
#TODO: remove
# @staticmethod
# def fromOgrGeometry25D(geometry, transform_func):
# pass
class GeometryUtils:
#TODO:
@staticmethod
def convertToList(qgs_geom, z_func, transform_func, useZM=False):
pass
@staticmethod
def _signedArea(p):
"""Calculates signed area of polygon."""
area = 0
for i in range(len(p) - 1):
area += (p[i].x - p[i + 1].x) * (p[i].y + p[i + 1].y)
return area / 2
@staticmethod
def isClockwise(linearRing):
"""Returns whether given linear ring is clockwise."""
return GeometryUtils._signedArea(linearRing) < 0
class TriangleMesh:
# 0 - 3
# | / |
# 1 - 2
def __init__(self, xmin, ymin, xmax, ymax, x_segments, y_segments):
self.vbands = []
self.hbands = []
self.vidx = QgsSpatialIndex()
self.hidx = QgsSpatialIndex()
xres = (xmax - xmin) / x_segments
yres = (ymax - ymin) / y_segments
self.xmin, self.ymax, self.xres, self.yres = xmin, ymax, xres, yres
def addVBand(idx, geom):
f = QgsFeature(idx)
f.setGeometry(geom)
self.vbands.append(f)
self.vidx.insertFeature(f)
def addHBand(idx, geom):
f = QgsFeature(idx)
f.setGeometry(geom)
self.hbands.append(f)
self.hidx.insertFeature(f)
for x in range(x_segments):
addVBand(x, QgsGeometry.fromRect(QgsRectangle(xmin + x * xres, ymin, xmin + (x + 1) * xres, ymax)))
for y in range(y_segments):
addHBand(y, QgsGeometry.fromRect(QgsRectangle(xmin, ymax - (y + 1) * yres, xmax, ymax - y * yres)))
def vSplit(self, geom):
"""split polygon vertically"""
for idx in self.vidx.intersects(geom.boundingBox()):
yield idx, geom.intersection(self.vbands[idx].geometry())
def hIntersects(self, geom):
"""indices of horizontal bands that intersect with geom"""
for idx in self.hidx.intersects(geom.boundingBox()):
if geom.intersects(self.hbands[idx].geometry()):
yield idx
def splitPolygons(self, geom):
xmin, ymax, xres, yres = self.xmin, self.ymax, self.xres, self.yres
for x, vi in self.vSplit(geom):
for y in self.hIntersects(vi):
pt0 = QgsPointXY(xmin + x * xres, ymax - y * yres)
pt1 = QgsPointXY(xmin + x * xres, ymax - (y + 1) * yres)
pt2 = QgsPointXY(xmin + (x + 1) * xres, ymax - (y + 1) * yres)
pt3 = QgsPointXY(xmin + (x + 1) * xres, ymax - y * yres)
quad = QgsGeometry.fromPolygonXY([[pt0, pt1, pt2, pt3, pt0]])
tris = [[[pt0, pt1, pt3, pt0]], [[pt3, pt1, pt2, pt3]]]
if geom.contains(quad):
yield tris[0]
yield tris[1]
else:
for i, tri in enumerate(map(QgsGeometry.fromPolygonXY, tris)):
if geom.contains(tri):
yield tris[i]
elif geom.intersects(tri):
poly = geom.intersection(tri)
if poly.isMultipart():
for sp in poly.asMultiPolygon():
yield sp
else:
yield poly.asPolygon()
class Triangles:
def __init__(self):
self.vertices = []
self.faces = []
self.vdict = {} # dict to find whether a vertex already exists: [y][x] = vertex index
def addTriangle(self, v1, v2, v3):
vi1 = self._vertexIndex(v1)
vi2 = self._vertexIndex(v2)
vi3 = self._vertexIndex(v3)
self.faces.append([vi1, vi2, vi3])
def _vertexIndex(self, v):
x_dict = self.vdict.get(v.y)
if x_dict:
vi = x_dict.get(v.x)
if vi is not None:
return vi
vi = len(self.vertices)
self.vertices.append(v)
if x_dict:
x_dict[v.x] = vi
else:
self.vdict[v.y] = {v.x: vi}
return vi
#TODO: parameters - extent, layer, projectCrs
def dissolvePolygonsOnCanvas(settings, layer):
"""dissolve polygons of the layer and clip the dissolution with base extent"""
baseExtent = settings.baseExtent
baseExtentGeom = baseExtent.geometry()
rotation = baseExtent.rotation()
transform = QgsCoordinateTransform(layer.crs(), settings.crs)
combi = None
request = QgsFeatureRequest()
request.setFilterRect(transform.transformBoundingBox(baseExtent.boundingBox(), QgsCoordinateTransform.ReverseTransform))
for f in layer.getFeatures(request):
geometry = f.geometry()
if geometry is None:
logMessage("null geometry skipped")
continue
# coordinate transformation - layer crs to project crs
geom = QgsGeometry(geometry)
if geom.transform(transform) != 0:
logMessage("Failed to transform geometry")
continue
# check if geometry intersects with the base extent (rotated rect)
if rotation and not baseExtentGeom.intersects(geom):
continue
if combi:
combi = combi.combine(geom)
else:
combi = geom
# clip geom with slightly smaller extent than base extent
# to make sure that the clipped polygon stays within the base extent
geom = combi.intersection(baseExtent.clone().scale(0.999999).geometry())
if geom is None:
return None
# check if geometry is empty
if geom.isEmpty():
logMessage("empty geometry")
return None
return geom