QGIS API Documentation  3.24.2-Tisler (13c1a02865)
qgsgeometryvalidator.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsgeometryvalidator.cpp - geometry validation thread
3  -------------------------------------------------------------------
4 Date : 03.01.2012
5 Copyright : (C) 2012 by Juergen E. Fischer
6 email : jef at norbit dot de
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include "qgis.h"
17 #include "qgsgeometryvalidator.h"
18 #include "qgsgeometry.h"
19 #include "qgslogger.h"
20 #include "qgsgeos.h"
21 #include "qgsgeometrycollection.h"
22 #include "qgspolygon.h"
23 #include "qgscurvepolygon.h"
24 #include "qgscurve.h"
25 #include "qgsvertexid.h"
26 
27 QgsGeometryValidator::QgsGeometryValidator( const QgsGeometry &geometry, QVector<QgsGeometry::Error> *errors, Qgis::GeometryValidationEngine method )
28  : mGeometry( geometry )
29  , mErrors( errors )
30  , mStop( false )
31  , mErrorCount( 0 )
32  , mMethod( method )
33 {
34 }
35 
37 {
38  stop();
39  wait();
40 }
41 
43 {
44  mStop = true;
45 }
46 
47 void QgsGeometryValidator::checkRingIntersections( int partIndex0, int ringIndex0, const QgsLineString *ring0, int partIndex1, int ringIndex1, const QgsLineString *ring1 )
48 {
49  for ( int i = 0; !mStop && i < ring0->numPoints() - 1; i++ )
50  {
51  const double ring0XAti = ring0->xAt( i );
52  const double ring0YAti = ring0->yAt( i );
53  const QgsVector v( ring0->xAt( i + 1 ) - ring0XAti, ring0->yAt( i + 1 ) - ring0YAti );
54 
55  for ( int j = 0; !mStop && j < ring1->numPoints() - 1; j++ )
56  {
57  const double ring1XAtj = ring1->xAt( j );
58  const double ring1YAtj = ring1->yAt( j );
59  const QgsVector w( ring1->xAt( j + 1 ) - ring1XAtj, ring1->yAt( j + 1 ) - ring1YAtj );
60 
61  double sX;
62  double sY;
63  if ( intersectLines( ring0XAti, ring0YAti, v, ring1XAtj, ring1YAtj, w, sX, sY ) )
64  {
65  double d = -distLine2Point( ring0XAti, ring0YAti, v.perpVector(), sX, sY );
66 
67  if ( d >= 0 && d <= v.length() )
68  {
69  d = -distLine2Point( ring1XAtj, ring1YAtj, w.perpVector(), sX, sY );
70  if ( d > 0 && d < w.length() &&
71  ring0->pointN( i + 1 ) != ring1->pointN( j + 1 ) && ring0->pointN( i + 1 ) != ring1->pointN( j ) &&
72  ring0->pointN( i + 0 ) != ring1->pointN( j + 1 ) && ring0->pointN( i + 0 ) != ring1->pointN( j ) )
73  {
74  const QString msg = QObject::tr( "segment %1 of ring %2 of polygon %3 intersects segment %4 of ring %5 of polygon %6 at %7, %8" )
75  .arg( i ).arg( ringIndex0 ).arg( partIndex0 )
76  .arg( j ).arg( ringIndex1 ).arg( partIndex1 )
77  .arg( sX ).arg( sY );
78  emit errorFound( QgsGeometry::Error( msg, QgsPointXY( sX, sY ) ) );
79  mErrorCount++;
80  }
81  }
82  }
83  }
84  }
85 }
86 
87 void QgsGeometryValidator::validatePolyline( int i, const QgsLineString *line, bool ring )
88 {
89  if ( !line )
90  return;
91 
92  if ( ring )
93  {
94  if ( line->numPoints() < 4 )
95  {
96  const QString msg = QObject::tr( "ring %1 with less than four points" ).arg( i );
97  QgsDebugMsgLevel( msg, 2 );
98  emit errorFound( QgsGeometry::Error( msg ) );
99  mErrorCount++;
100  return;
101  }
102 
103  if ( !line->isClosed() )
104  {
105  const QgsPoint startPoint = line->startPoint();
106  const QgsPoint endPoint = line->endPoint();
107  QString msg;
108  if ( line->is3D() && line->isClosed2D() )
109  {
110  msg = QObject::tr( "ring %1 not closed, Z mismatch: %2 vs %3" ).arg( i ).arg( startPoint.z() ).arg( endPoint.z() );
111  }
112  else
113  {
114  msg = QObject::tr( "ring %1 not closed" ).arg( i );
115  QgsDebugMsgLevel( msg, 2 );
116  }
117  emit errorFound( QgsGeometry::Error( msg, QgsPointXY( startPoint.x(), startPoint.y() ) ) );
118  mErrorCount++;
119  return;
120  }
121  }
122  else if ( line->numPoints() < 2 )
123  {
124  const QString msg = QObject::tr( "line %1 with less than two points" ).arg( i );
125  QgsDebugMsgLevel( msg, 2 );
126  emit errorFound( QgsGeometry::Error( msg ) );
127  mErrorCount++;
128  return;
129  }
130 
131  std::unique_ptr< QgsLineString > noDupes;
132 
133  // test for duplicate nodes, and if we find any flag errors and then remove them so that the subsequent
134  // tests work OK.
135  const QVector< QgsVertexId > duplicateNodes = line->collectDuplicateNodes( 1E-8 );
136  if ( !duplicateNodes.empty() )
137  {
138  noDupes.reset( line->clone() );
139  for ( int j = duplicateNodes.size() - 1; j >= 0; j-- )
140  {
141  const QgsVertexId duplicateVertex = duplicateNodes.at( j );
142  const QgsPointXY duplicationLocation = noDupes->vertexAt( duplicateVertex );
143  noDupes->deleteVertex( duplicateVertex );
144  int n = 1;
145 
146  // count how many other points exist at this location too
147  for ( int k = j - 1; k >= 0; k-- )
148  {
149  const QgsVertexId prevDupe = duplicateNodes.at( k );
150  const QgsPoint prevPoint = noDupes->vertexAt( prevDupe );
151  if ( qgsDoubleNear( duplicationLocation.x(), prevPoint.x(), 1E-8 ) && qgsDoubleNear( duplicationLocation.y(), prevPoint.y(), 1E-8 ) )
152  {
153  noDupes->deleteVertex( prevDupe );
154  n++;
155  }
156  else
157  {
158  break;
159  }
160  }
161 
162  j -= n - 1;
163 
164  const QString msg = QObject::tr( "line %1 contains %n duplicate node(s) starting at vertex %2", "number of duplicate nodes", n + 1 ).arg( i + 1 ).arg( duplicateVertex.vertex - n + 1 );
165  QgsDebugMsgLevel( msg, 2 );
166  emit errorFound( QgsGeometry::Error( msg, duplicationLocation ) );
167  mErrorCount++;
168  }
169  line = noDupes.get();
170  }
171 
172  for ( int j = 0; !mStop && j < line->numPoints() - 3; j++ )
173  {
174  const double xAtJ = line->xAt( j );
175  const double yAtJ = line->yAt( j );
176  const QgsVector v( line->xAt( j + 1 ) - xAtJ, line->yAt( j + 1 ) - yAtJ );
177  const double vl = v.length();
178 
179  const int n = ( j == 0 && ring ) ? line->numPoints() - 2 : line->numPoints() - 1;
180 
181  for ( int k = j + 2; !mStop && k < n; k++ )
182  {
183  const double xAtK = line->xAt( k );
184  const double yAtK = line->yAt( k );
185 
186  const QgsVector w( line->xAt( k + 1 ) - xAtK, line->yAt( k + 1 ) - yAtK );
187 
188  double sX;
189  double sY;
190  if ( !intersectLines( xAtJ, yAtJ, v, xAtK, yAtK, w, sX, sY ) )
191  continue;
192 
193  double d = 0.0;
194  try
195  {
196  d = -distLine2Point( xAtJ, yAtJ, v.perpVector(), sX, sY );
197  }
198  catch ( QgsException &e )
199  {
200  Q_UNUSED( e )
201  QgsDebugMsg( "Error validating: " + e.what() );
202  continue;
203  }
204  if ( d < 0 || d > vl )
205  continue;
206 
207  try
208  {
209  d = -distLine2Point( xAtK, yAtK, w.perpVector(), sX, sY );
210  }
211  catch ( QgsException &e )
212  {
213  Q_UNUSED( e )
214  QgsDebugMsg( "Error validating: " + e.what() );
215  continue;
216  }
217 
218  if ( d <= 0 || d >= w.length() )
219  continue;
220 
221  const QString msg = QObject::tr( "segments %1 and %2 of line %3 intersect at %4, %5" ).arg( j ).arg( k ).arg( i ).arg( sX ).arg( sY );
222  QgsDebugMsgLevel( msg, 2 );
223  emit errorFound( QgsGeometry::Error( msg, QgsPointXY( sX, sY ) ) );
224  mErrorCount++;
225  }
226  }
227 }
228 
229 void QgsGeometryValidator::validatePolygon( int partIndex, const QgsCurvePolygon *polygon )
230 {
231  // check if holes are inside polygon
232  for ( int i = 0; !mStop && i < polygon->numInteriorRings(); ++i )
233  {
234  if ( !ringInRing( polygon->interiorRing( i ), polygon->exteriorRing() ) )
235  {
236  const QString msg = QObject::tr( "ring %1 of polygon %2 not in exterior ring" ).arg( i + 1 ).arg( partIndex );
237  QgsDebugMsg( msg );
238  emit errorFound( QgsGeometry::Error( msg ) );
239  mErrorCount++;
240  }
241  }
242 
243  // check holes for intersections
244  for ( int i = 0; !mStop && i < polygon->numInteriorRings(); i++ )
245  {
246  for ( int j = i + 1; !mStop && j < polygon->numInteriorRings(); j++ )
247  {
248  checkRingIntersections( partIndex, i + 1, qgsgeometry_cast< QgsLineString * >( polygon->interiorRing( i ) ),
249  partIndex, j + 1, qgsgeometry_cast< QgsLineString * >( polygon->interiorRing( j ) ) );
250  }
251  }
252 
253  // check if rings are self-intersecting
254  validatePolyline( 0, qgsgeometry_cast< const QgsLineString * >( polygon->exteriorRing() ), true );
255  for ( int i = 0; !mStop && i < polygon->numInteriorRings(); i++ )
256  {
257  validatePolyline( i + 1, qgsgeometry_cast< const QgsLineString * >( polygon->interiorRing( i ) ), true );
258  }
259 }
260 
262 {
263  mErrorCount = 0;
264  if ( mGeometry.isNull() )
265  {
266  return;
267  }
268 
269  switch ( mMethod )
270  {
271  case Qgis::GeometryValidationEngine::Geos:
272  {
273  // avoid calling geos for trivial point geometries
275  {
276  return;
277  }
278 
279  const QgsGeos geos( mGeometry.constGet() );
280  QString error;
281  QgsGeometry errorLoc;
282  if ( !geos.isValid( &error, true, &errorLoc ) )
283  {
284  if ( errorLoc.isNull() )
285  {
286  emit errorFound( QgsGeometry::Error( error ) );
287  mErrorCount++;
288  }
289  else
290  {
291  const QgsPointXY point = errorLoc.asPoint();
292  emit errorFound( QgsGeometry::Error( error, point ) );
293  mErrorCount++;
294  }
295  }
296 
297  break;
298  }
299 
300  case Qgis::GeometryValidationEngine::QgisInternal:
301  {
302  switch ( QgsWkbTypes::flatType( mGeometry.constGet()->wkbType() ) )
303  {
304  case QgsWkbTypes::Point:
306  break;
307 
309  validatePolyline( 0, qgsgeometry_cast< const QgsLineString * >( mGeometry.constGet() ) );
310  break;
311 
313  {
314  const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( mGeometry.constGet() );
315  for ( int i = 0; !mStop && i < collection->numGeometries(); i++ )
316  validatePolyline( i, qgsgeometry_cast< const QgsLineString * >( collection->geometryN( i ) ) );
317  break;
318  }
319 
322  validatePolygon( 0, qgsgeometry_cast< const QgsCurvePolygon * >( mGeometry.constGet() ) );
323  break;
324 
327  {
328  const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( mGeometry.constGet() );
329  for ( int i = 0; !mStop && i < collection->numGeometries(); i++ )
330  validatePolygon( i, qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( i ) ) );
331 
332  for ( int i = 0; !mStop && i < collection->numGeometries(); i++ )
333  {
334  const QgsCurvePolygon *poly = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( i ) );
335  if ( !poly->exteriorRing() || poly->exteriorRing()->isEmpty() )
336  {
337  emit errorFound( QgsGeometry::Error( QObject::tr( "Polygon %1 has no rings" ).arg( i ) ) );
338  mErrorCount++;
339  continue;
340  }
341 
342  for ( int j = i + 1; !mStop && j < collection->numGeometries(); j++ )
343  {
344  const QgsCurvePolygon *poly2 = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( j ) );
345  if ( !poly2->exteriorRing() || poly2->exteriorRing()->isEmpty() )
346  continue;
347 
348  if ( ringInRing( poly->exteriorRing(),
349  poly2->exteriorRing() ) )
350  {
351  emit errorFound( QgsGeometry::Error( QObject::tr( "Polygon %1 lies inside polygon %2" ).arg( i ).arg( j ) ) );
352  mErrorCount++;
353  }
354  else if ( ringInRing( poly2->exteriorRing(),
355  poly->exteriorRing() ) )
356  {
357  emit errorFound( QgsGeometry::Error( QObject::tr( "Polygon %1 lies inside polygon %2" ).arg( j ).arg( i ) ) );
358  mErrorCount++;
359  }
360  else
361  {
362  checkRingIntersections( i, 0, qgsgeometry_cast< const QgsLineString * >( poly->exteriorRing() ),
363  j, 0, qgsgeometry_cast< const QgsLineString * >( poly2->exteriorRing() ) );
364  }
365  }
366  }
367  break;
368  }
369 
371  {
372  emit errorFound( QgsGeometry::Error( QObject::tr( "Unknown geometry type %1" ).arg( mGeometry.wkbType() ) ) );
373  mErrorCount++;
374  break;
375  }
376 
377  default:
378  break;
379  }
380 
381  if ( mStop )
382  {
383  emit validationFinished( QObject::tr( "Geometry validation was aborted." ) );
384  }
385  else if ( mErrorCount > 0 )
386  {
387  emit validationFinished( QObject::tr( "Geometry has %n error(s).", nullptr, mErrorCount ) );
388  }
389  else
390  {
391  emit validationFinished( QObject::tr( "Geometry is valid." ) );
392  }
393  break;
394  }
395  }
396 }
397 
399 {
400  if ( mErrors )
401  *mErrors << e;
402 }
403 
404 void QgsGeometryValidator::validateGeometry( const QgsGeometry &geometry, QVector<QgsGeometry::Error> &errors, Qgis::GeometryValidationEngine method )
405 {
406  QgsGeometryValidator *gv = new QgsGeometryValidator( geometry, &errors, method );
408  gv->run();
409  gv->wait();
410 }
411 
412 //
413 // distance of point q from line through p in direction v
414 // return >0 => q lies left of the line
415 // <0 => q lies right of the line
416 //
417 double QgsGeometryValidator::distLine2Point( double px, double py, QgsVector v, double qX, double qY )
418 {
419  const double l = v.length();
420  if ( qgsDoubleNear( l, 0 ) )
421  {
422  throw QgsException( QObject::tr( "invalid line" ) );
423  }
424 
425  return ( v.x() * ( qY - py ) - v.y() * ( qX - px ) ) / l;
426 }
427 
428 bool QgsGeometryValidator::intersectLines( double px, double py, QgsVector v, double qx, double qy, QgsVector w, double &sX, double &sY )
429 {
430  const double d = v.y() * w.x() - v.x() * w.y();
431 
432  if ( qgsDoubleNear( d, 0 ) )
433  return false;
434 
435  const double dx = qx - px;
436  const double dy = qy - py;
437  const double k = ( dy * w.x() - dx * w.y() ) / d;
438 
439  sX = px + v.x() * k;
440  sY = py + v.y() * k;
441 
442  return true;
443 }
444 
445 bool QgsGeometryValidator::pointInRing( const QgsCurve *ring, double pX, double pY )
446 {
447  if ( !ring->boundingBox().contains( pX, pY ) )
448  return false;
449 
450  bool inside = false;
451  int j = ring->numPoints() - 1;
452 
453  for ( int i = 0; !mStop && i < ring->numPoints(); i++ )
454  {
455  const double xAti = ring->xAt( i );
456  const double yAti = ring->yAt( i );
457  const double xAtj = ring->xAt( j );
458  const double yAtj = ring->yAt( j );
459 
460  if ( qgsDoubleNear( xAti, pX ) && qgsDoubleNear( yAti, pY ) )
461  return true;
462 
463  if ( ( yAti < pY && yAtj >= pY ) ||
464  ( yAtj < pY && yAti >= pY ) )
465  {
466  if ( xAti + ( pY - yAti ) / ( yAtj - yAti ) * ( xAtj - xAti ) <= pX )
467  inside = !inside;
468  }
469 
470  j = i;
471  }
472 
473  return inside;
474 }
475 
476 bool QgsGeometryValidator::ringInRing( const QgsCurve *inside, const QgsCurve *outside )
477 {
478  if ( !outside->boundingBox().contains( inside->boundingBox() ) )
479  return false;
480 
481  for ( int i = 0; !mStop && i < inside->numPoints(); i++ )
482  {
483  if ( !pointInRing( outside, inside->xAt( i ), inside->yAt( i ) ) )
484  return false;
485  }
486 
487  return true;
488 }
GeometryValidationEngine
Available engines for validating geometries.
Definition: qgis.h:721
bool is3D() const SIP_HOLDGIL
Returns true if the geometry is 3D and contains a z-value.
virtual bool isEmpty() const
Returns true if the geometry is empty.
QgsWkbTypes::Type wkbType() const SIP_HOLDGIL
Returns the WKB type of the geometry.
Curve polygon geometry type.
const QgsCurve * interiorRing(int i) const SIP_HOLDGIL
Retrieves an interior ring from the curve polygon.
const QgsCurve * exteriorRing() const SIP_HOLDGIL
Returns the curve polygon's exterior ring.
int numInteriorRings() const SIP_HOLDGIL
Returns the number of interior rings contained with the curve polygon.
Abstract base class for curved geometry type.
Definition: qgscurve.h:36
QgsRectangle boundingBox() const override
Returns the minimal bounding box for the geometry.
Definition: qgscurve.cpp:238
virtual int numPoints() const =0
Returns the number of points in the curve.
virtual double xAt(int index) const =0
Returns the x-coordinate of the specified node in the line string.
virtual double yAt(int index) const =0
Returns the y-coordinate of the specified node in the line string.
Defines a QGIS exception class.
Definition: qgsexception.h:35
QString what() const
Definition: qgsexception.h:48
Geometry collection.
int numGeometries() const SIP_HOLDGIL
Returns the number of geometries within the collection.
const QgsAbstractGeometry * geometryN(int n) const
Returns a const reference to a geometry from within the collection.
void validationFinished(const QString &summary)
Sent when the validation is finished.
void errorFound(const QgsGeometry::Error &error)
Sent when an error has been found during the validation process.
QgsGeometryValidator(const QgsGeometry &geometry, QVector< QgsGeometry::Error > *errors=nullptr, Qgis::GeometryValidationEngine method=Qgis::GeometryValidationEngine::QgisInternal)
Constructor for QgsGeometryValidator.
static void validateGeometry(const QgsGeometry &geometry, QVector< QgsGeometry::Error > &errors, Qgis::GeometryValidationEngine method=Qgis::GeometryValidationEngine::QgisInternal)
Validate geometry and produce a list of geometry errors.
void addError(const QgsGeometry::Error &)
A geometry error.
Definition: qgsgeometry.h:2405
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:125
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsWkbTypes::Type wkbType() const SIP_HOLDGIL
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
Q_GADGET bool isNull
Definition: qgsgeometry.h:127
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
Does vector analysis using the geos library and handles import, export, exception handling*.
Definition: qgsgeos.h:104
Line string geometry type, with support for z-dimension and m-values.
Definition: qgslinestring.h:44
QgsPoint startPoint() const override SIP_HOLDGIL
Returns the starting point of the curve.
bool isClosed() const override SIP_HOLDGIL
Returns true if the curve is closed.
QgsPoint endPoint() const override SIP_HOLDGIL
Returns the end point of the curve.
int numPoints() const override SIP_HOLDGIL
Returns the number of points in the curve.
QgsPoint pointN(int i) const
Returns the specified point from inside the line string.
bool isClosed2D() const override SIP_HOLDGIL
Returns true if the curve is closed.
double yAt(int index) const override
Returns the y-coordinate of the specified node in the line string.
QVector< QgsVertexId > collectDuplicateNodes(double epsilon=4 *std::numeric_limits< double >::epsilon(), bool useZValues=false) const
Returns a list of any duplicate nodes contained in the geometry, within the specified tolerance.
QgsLineString * clone() const override
Clones the geometry by performing a deep copy.
double xAt(int index) const override
Returns the x-coordinate of the specified node in the line string.
A class to represent a 2D point.
Definition: qgspointxy.h:59
double y
Definition: qgspointxy.h:63
Q_GADGET double x
Definition: qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:49
Q_GADGET double x
Definition: qgspoint.h:52
QgsPoint vertexAt(QgsVertexId) const override
Returns the point corresponding to a specified vertex id.
Definition: qgspoint.cpp:525
bool deleteVertex(QgsVertexId position) override
Deletes a vertex within the geometry.
Definition: qgspoint.cpp:459
double z
Definition: qgspoint.h:54
double y
Definition: qgspoint.h:53
bool contains(const QgsRectangle &rect) const SIP_HOLDGIL
Returns true when rectangle contains other rectangle.
Definition: qgsrectangle.h:363
A class to represent a vector.
Definition: qgsvector.h:30
double y() const SIP_HOLDGIL
Returns the vector's y-component.
Definition: qgsvector.h:156
double x() const SIP_HOLDGIL
Returns the vector's x-component.
Definition: qgsvector.h:147
double length() const SIP_HOLDGIL
Returns the length of the vector.
Definition: qgsvector.h:128
static GeometryType geometryType(Type type) SIP_HOLDGIL
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
Definition: qgswkbtypes.h:968
static Type flatType(Type type) SIP_HOLDGIL
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:732
Contains geos related utilities and functions.
Definition: qgsgeos.h:42
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:1578
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
Utility class for identifying a unique vertex within a geometry.
Definition: qgsvertexid.h:31
int vertex
Vertex number.
Definition: qgsvertexid.h:95