QGIS API Documentation  3.20.0-Odense (decaadbb31)
qgsoverlayutils.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsoverlayutils.cpp
3  ---------------------
4  Date : April 2018
5  Copyright : (C) 2018 by Martin Dobias
6  Email : wonder dot sk at gmail dot com
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 "qgsoverlayutils.h"
17 
18 #include "qgsgeometryengine.h"
19 #include "qgsprocessingalgorithm.h"
20 
22 
23 bool QgsOverlayUtils::sanitizeIntersectionResult( QgsGeometry &geom, QgsWkbTypes::GeometryType geometryType )
24 {
25  if ( geom.isNull() )
26  {
27  // TODO: not sure if this ever happens - if it does, that means GEOS failed badly - would be good to have a test for such situation
28  throw QgsProcessingException( QStringLiteral( "%1\n\n%2" ).arg( QObject::tr( "GEOS geoprocessing error: intersection failed." ), geom.lastError() ) );
29  }
30 
31  // Intersection of geometries may give use also geometries we do not want in our results.
32  // For example, two square polygons touching at the corner have a point as the intersection, but no area.
33  // In other cases we may get a mixture of geometries in the output - we want to keep only the expected types.
35  {
36  // try to filter out irrelevant parts with different geometry type than what we want
37  geom.convertGeometryCollectionToSubclass( geometryType );
38  if ( geom.isEmpty() )
39  return false;
40  }
41 
42  if ( QgsWkbTypes::geometryType( geom.wkbType() ) != geometryType )
43  {
44  // we can't make use of this resulting geometry
45  return false;
46  }
47 
48  // some data providers are picky about the geometries we pass to them: we can't add single-part geometries
49  // when we promised multi-part geometries, so ensure we have the right type
50  geom.convertToMultiType();
51 
52  return true;
53 }
54 
55 
57 static bool sanitizeDifferenceResult( QgsGeometry &geom, QgsWkbTypes::GeometryType geometryType )
58 {
59  if ( geom.isNull() )
60  {
61  // TODO: not sure if this ever happens - if it does, that means GEOS failed badly - would be good to have a test for such situation
62  throw QgsProcessingException( QStringLiteral( "%1\n\n%2" ).arg( QObject::tr( "GEOS geoprocessing error: difference failed." ), geom.lastError() ) );
63  }
64 
65  //fix geometry collections
67  {
68  // try to filter out irrelevant parts with different geometry type than what we want
69  geom.convertGeometryCollectionToSubclass( geometryType );
70  }
71 
72 
73  // if geomB covers the whole source geometry, we get an empty geometry collection
74  if ( geom.isEmpty() )
75  return false;
76 
77  // some data providers are picky about the geometries we pass to them: we can't add single-part geometries
78  // when we promised multi-part geometries, so ensure we have the right type
79  geom.convertToMultiType();
80 
81  return true;
82 }
83 
84 
85 void QgsOverlayUtils::difference( const QgsFeatureSource &sourceA, const QgsFeatureSource &sourceB, QgsFeatureSink &sink, QgsProcessingContext &context, QgsProcessingFeedback *feedback, long &count, long totalCount, QgsOverlayUtils::DifferenceOutput outputAttrs )
86 {
88  QgsFeatureRequest requestB;
89  requestB.setNoAttributes();
90  if ( outputAttrs != OutputBA )
91  requestB.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
92  QgsSpatialIndex indexB( sourceB.getFeatures( requestB ), feedback );
93  if ( feedback->isCanceled() )
94  return;
95 
96  int fieldsCountA = sourceA.fields().count();
97  int fieldsCountB = sourceB.fields().count();
98  QgsAttributes attrs;
99  attrs.resize( outputAttrs == OutputA ? fieldsCountA : ( fieldsCountA + fieldsCountB ) );
100 
101  if ( totalCount == 0 )
102  totalCount = 1; // avoid division by zero
103 
104  QgsFeature featA;
105  QgsFeatureRequest requestA;
106  requestA.setInvalidGeometryCheck( context.invalidGeometryCheck() );
107  if ( outputAttrs == OutputBA )
108  requestA.setDestinationCrs( sourceB.sourceCrs(), context.transformContext() );
109  QgsFeatureIterator fitA = sourceA.getFeatures( requestA );
110  while ( fitA.nextFeature( featA ) )
111  {
112  if ( feedback->isCanceled() )
113  break;
114 
115  if ( featA.hasGeometry() )
116  {
117  QgsGeometry geom( featA.geometry() );
118  QgsFeatureIds intersects = qgis::listToSet( indexB.intersects( geom.boundingBox() ) );
119 
120  QgsFeatureRequest request;
121  request.setFilterFids( intersects );
122  request.setNoAttributes();
123  if ( outputAttrs != OutputBA )
124  request.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
125 
126  std::unique_ptr< QgsGeometryEngine > engine;
127  if ( !intersects.isEmpty() )
128  {
129  // use prepared geometries for faster intersection tests
130  engine.reset( QgsGeometry::createGeometryEngine( geom.constGet() ) );
131  engine->prepareGeometry();
132  }
133 
134  QVector<QgsGeometry> geometriesB;
135  QgsFeature featB;
136  QgsFeatureIterator fitB = sourceB.getFeatures( request );
137  while ( fitB.nextFeature( featB ) )
138  {
139  if ( feedback->isCanceled() )
140  break;
141 
142  if ( engine->intersects( featB.geometry().constGet() ) )
143  geometriesB << featB.geometry();
144  }
145 
146  if ( !geometriesB.isEmpty() )
147  {
148  QgsGeometry geomB = QgsGeometry::unaryUnion( geometriesB );
149  if ( !geomB.lastError().isEmpty() )
150  {
151  // This may happen if input geometries from a layer do not line up well (for example polygons
152  // that are nearly touching each other, but there is a very tiny overlap or gap at one of the edges).
153  // It is possible to get rid of this issue in two steps:
154  // 1. snap geometries with a small tolerance (e.g. 1cm) using QgsGeometrySnapperSingleSource
155  // 2. fix geometries (removes polygons collapsed to lines etc.) using MakeValid
156  throw QgsProcessingException( QStringLiteral( "%1\n\n%2" ).arg( QObject::tr( "GEOS geoprocessing error: unary union failed." ), geomB.lastError() ) );
157  }
158  geom = geom.difference( geomB );
159  }
160 
161  if ( !sanitizeDifferenceResult( geom, geometryType ) )
162  continue;
163 
164  const QgsAttributes attrsA( featA.attributes() );
165  switch ( outputAttrs )
166  {
167  case OutputA:
168  attrs = attrsA;
169  break;
170  case OutputAB:
171  for ( int i = 0; i < fieldsCountA; ++i )
172  attrs[i] = attrsA[i];
173  break;
174  case OutputBA:
175  for ( int i = 0; i < fieldsCountA; ++i )
176  attrs[i + fieldsCountB] = attrsA[i];
177  break;
178  }
179 
180  QgsFeature outFeat;
181  outFeat.setGeometry( geom );
182  outFeat.setAttributes( attrs );
183  sink.addFeature( outFeat, QgsFeatureSink::FastInsert );
184  }
185  else
186  {
187  // TODO: should we write out features that do not have geometry?
188  sink.addFeature( featA, QgsFeatureSink::FastInsert );
189  }
190 
191  ++count;
192  feedback->setProgress( count / static_cast< double >( totalCount ) * 100. );
193  }
194 }
195 
196 
197 void QgsOverlayUtils::intersection( const QgsFeatureSource &sourceA, const QgsFeatureSource &sourceB, QgsFeatureSink &sink, QgsProcessingContext &context, QgsProcessingFeedback *feedback, long &count, long totalCount, const QList<int> &fieldIndicesA, const QList<int> &fieldIndicesB )
198 {
200  int attrCount = fieldIndicesA.count() + fieldIndicesB.count();
201 
202  QgsFeatureRequest request;
203  request.setNoAttributes();
204  request.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
205 
206  QgsFeature outFeat;
207  QgsSpatialIndex indexB( sourceB.getFeatures( request ), feedback );
208  if ( feedback->isCanceled() )
209  return;
210 
211  if ( totalCount == 0 )
212  totalCount = 1; // avoid division by zero
213 
214  QgsFeature featA;
215  QgsFeatureIterator fitA = sourceA.getFeatures( QgsFeatureRequest().setSubsetOfAttributes( fieldIndicesA ) );
216  while ( fitA.nextFeature( featA ) )
217  {
218  if ( feedback->isCanceled() )
219  break;
220 
221  if ( !featA.hasGeometry() )
222  continue;
223 
224  QgsGeometry geom( featA.geometry() );
225  QgsFeatureIds intersects = qgis::listToSet( indexB.intersects( geom.boundingBox() ) );
226 
227  QgsFeatureRequest request;
228  request.setFilterFids( intersects );
229  request.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
230  request.setSubsetOfAttributes( fieldIndicesB );
231 
232  std::unique_ptr< QgsGeometryEngine > engine;
233  if ( !intersects.isEmpty() )
234  {
235  // use prepared geometries for faster intersection tests
236  engine.reset( QgsGeometry::createGeometryEngine( geom.constGet() ) );
237  engine->prepareGeometry();
238  }
239 
240  QgsAttributes outAttributes( attrCount );
241  const QgsAttributes attrsA( featA.attributes() );
242  for ( int i = 0; i < fieldIndicesA.count(); ++i )
243  outAttributes[i] = attrsA[fieldIndicesA[i]];
244 
245  QgsFeature featB;
246  QgsFeatureIterator fitB = sourceB.getFeatures( request );
247  while ( fitB.nextFeature( featB ) )
248  {
249  if ( feedback->isCanceled() )
250  break;
251 
252  QgsGeometry tmpGeom( featB.geometry() );
253  if ( !engine->intersects( tmpGeom.constGet() ) )
254  continue;
255 
256  QgsGeometry intGeom = geom.intersection( tmpGeom );
257  if ( !sanitizeIntersectionResult( intGeom, geometryType ) )
258  continue;
259 
260  const QgsAttributes attrsB( featB.attributes() );
261  for ( int i = 0; i < fieldIndicesB.count(); ++i )
262  outAttributes[fieldIndicesA.count() + i] = attrsB[fieldIndicesB[i]];
263 
264  outFeat.setGeometry( intGeom );
265  outFeat.setAttributes( outAttributes );
266  sink.addFeature( outFeat, QgsFeatureSink::FastInsert );
267  }
268 
269  ++count;
270  feedback->setProgress( count / static_cast<double >( totalCount ) * 100. );
271  }
272 }
273 
274 void QgsOverlayUtils::resolveOverlaps( const QgsFeatureSource &source, QgsFeatureSink &sink, QgsProcessingFeedback *feedback )
275 {
276  long count = 0;
277  const long totalCount = source.featureCount();
278  if ( totalCount == 0 )
279  return; // nothing to do here
280 
281  QgsFeatureId newFid = -1;
282 
284 
285  QgsFeatureRequest requestOnlyGeoms;
286  requestOnlyGeoms.setNoAttributes();
287 
288  QgsFeatureRequest requestOnlyAttrs;
289  requestOnlyAttrs.setFlags( QgsFeatureRequest::NoGeometry );
290 
291  QgsFeatureRequest requestOnlyIds;
292  requestOnlyIds.setFlags( QgsFeatureRequest::NoGeometry );
293  requestOnlyIds.setNoAttributes();
294 
295  // make a set of used feature IDs so that we do not try to reuse them for newly added features
296  QgsFeature f;
297  QSet<QgsFeatureId> fids;
298  QgsFeatureIterator it = source.getFeatures( requestOnlyIds );
299  while ( it.nextFeature( f ) )
300  {
301  if ( feedback->isCanceled() )
302  return;
303 
304  fids.insert( f.id() );
305  }
306 
307  QHash<QgsFeatureId, QgsGeometry> geometries;
308  QgsSpatialIndex index;
309  QHash<QgsFeatureId, QList<QgsFeatureId> > intersectingIds; // which features overlap a particular area
310 
311  // resolve intersections
312 
313  it = source.getFeatures( requestOnlyGeoms );
314  while ( it.nextFeature( f ) )
315  {
316  if ( feedback->isCanceled() )
317  return;
318 
319  QgsFeatureId fid1 = f.id();
320  QgsGeometry g1 = f.geometry();
321  std::unique_ptr< QgsGeometryEngine > g1engine;
322 
323  geometries.insert( fid1, g1 );
324  index.addFeature( f );
325 
326  QgsRectangle bbox( f.geometry().boundingBox() );
327  const QList<QgsFeatureId> ids = index.intersects( bbox );
328  for ( QgsFeatureId fid2 : ids )
329  {
330  if ( fid1 == fid2 )
331  continue;
332 
333  if ( !g1engine )
334  {
335  // use prepared geometries for faster intersection tests
336  g1engine.reset( QgsGeometry::createGeometryEngine( g1.constGet() ) );
337  g1engine->prepareGeometry();
338  }
339 
340  QgsGeometry g2 = geometries.value( fid2 );
341  if ( !g1engine->intersects( g2.constGet() ) )
342  continue;
343 
344  QgsGeometry geomIntersection = g1.intersection( g2 );
345  if ( !sanitizeIntersectionResult( geomIntersection, geometryType ) )
346  continue;
347 
348  //
349  // add intersection geometry
350  //
351 
352  // figure out new fid
353  while ( fids.contains( newFid ) )
354  --newFid;
355  fids.insert( newFid );
356 
357  geometries.insert( newFid, geomIntersection );
358  QgsFeature fx( newFid );
359  fx.setGeometry( geomIntersection );
360 
361  index.addFeature( fx );
362 
363  // figure out which feature IDs belong to this intersection. Some of the IDs can be of the newly
364  // created geometries - in such case we need to retrieve original IDs
365  QList<QgsFeatureId> lst;
366  if ( intersectingIds.contains( fid1 ) )
367  lst << intersectingIds.value( fid1 );
368  else
369  lst << fid1;
370  if ( intersectingIds.contains( fid2 ) )
371  lst << intersectingIds.value( fid2 );
372  else
373  lst << fid2;
374  intersectingIds.insert( newFid, lst );
375 
376  //
377  // update f1
378  //
379 
380  QgsGeometry g12 = g1.difference( g2 );
381 
382  index.deleteFeature( f );
383  geometries.remove( fid1 );
384 
385  if ( sanitizeDifferenceResult( g12, geometryType ) )
386  {
387  geometries.insert( fid1, g12 );
388 
389  QgsFeature f1x( fid1 );
390  f1x.setGeometry( g12 );
391  index.addFeature( f1x );
392  }
393 
394  //
395  // update f2
396  //
397 
398  QgsGeometry g21 = g2.difference( g1 );
399 
400  QgsFeature f2old( fid2 );
401  f2old.setGeometry( g2 );
402  index.deleteFeature( f2old );
403 
404  geometries.remove( fid2 );
405 
406  if ( sanitizeDifferenceResult( g21, geometryType ) )
407  {
408  geometries.insert( fid2, g21 );
409 
410  QgsFeature f2x( fid2 );
411  f2x.setGeometry( g21 );
412  index.addFeature( f2x );
413  }
414 
415  // update our temporary copy of the geometry to what is left from it
416  g1 = g12;
417  g1engine.reset();
418  }
419 
420  ++count;
421  feedback->setProgress( count / static_cast< double >( totalCount ) * 100. );
422  }
423  if ( feedback->isCanceled() )
424  return;
425 
426  // release some memory of structures we don't need anymore
427 
428  fids.clear();
429  index = QgsSpatialIndex();
430 
431  // load attributes
432 
433  QHash<QgsFeatureId, QgsAttributes> attributesHash;
434  it = source.getFeatures( requestOnlyAttrs );
435  while ( it.nextFeature( f ) )
436  {
437  if ( feedback->isCanceled() )
438  return;
439 
440  attributesHash.insert( f.id(), f.attributes() );
441  }
442 
443  // store stuff in the sink
444 
445  for ( auto i = geometries.constBegin(); i != geometries.constEnd(); ++i )
446  {
447  if ( feedback->isCanceled() )
448  return;
449 
450  QgsFeature outFeature( i.key() );
451  outFeature.setGeometry( i.value() );
452 
453  if ( intersectingIds.contains( i.key() ) )
454  {
455  const QList<QgsFeatureId> ids = intersectingIds.value( i.key() );
456  for ( QgsFeatureId id : ids )
457  {
458  outFeature.setAttributes( attributesHash.value( id ) );
459  sink.addFeature( outFeature, QgsFeatureSink::FastInsert );
460  }
461  }
462  else
463  {
464  outFeature.setAttributes( attributesHash.value( i.key() ) );
465  sink.addFeature( outFeature, QgsFeatureSink::FastInsert );
466  }
467  }
468 }
469 
A vector of attributes.
Definition: qgsattributes.h:58
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets feature IDs that should be fetched.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setInvalidGeometryCheck(InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
An interface for objects which accept features via addFeature(s) methods.
virtual bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags())
Adds a single feature to the sink.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
An interface for objects which provide features via a getFeatures method.
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
virtual QgsCoordinateReferenceSystem sourceCrs() const =0
Returns the coordinate reference system for features in the source.
virtual QgsWkbTypes::Type wkbType() const =0
Returns the geometry type for features returned by this source.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
virtual long long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QgsAttributes attributes
Definition: qgsfeature.h:65
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:135
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:205
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:145
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
bool isCanceled() const SIP_HOLDGIL
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:63
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
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.)
QgsGeometry difference(const QgsGeometry &geometry) const
Returns a geometry representing the points making up this geometry that do not make up other.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries)
Compute the unary union on a list of geometries.
Q_GADGET bool isNull
Definition: qgsgeometry.h:126
QgsGeometry intersection(const QgsGeometry &geometry) const
Returns a geometry representing the points shared by this geometry and other.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine representing the specified geometry.
QString lastError() const SIP_HOLDGIL
Returns an error string referring to the last error encountered either when this geometry was created...
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
bool convertGeometryCollectionToSubclass(QgsWkbTypes::GeometryType geomType)
Converts geometry collection to a the desired geometry type subclass (multi-point,...
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsFeatureRequest::InvalidGeometryCheck invalidGeometryCheck() const
Returns the behavior used for checking invalid geometries in input layers.
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
Base class for providing feedback from a processing algorithm.
A rectangle specified with double values.
Definition: qgsrectangle.h:42
A spatial index for QgsFeature objects.
QList< QgsFeatureId > intersects(const QgsRectangle &rectangle) const
Returns a list of features with a bounding box which intersects the specified rectangle.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a feature to the index.
bool deleteFeature(const QgsFeature &feature)
Removes a feature from the index.
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:938
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
Definition: qgswkbtypes.h:141
@ GeometryCollection
Definition: qgswkbtypes.h:79
static Type flatType(Type type) SIP_HOLDGIL
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:702
static Type multiType(Type type) SIP_HOLDGIL
Returns the multi type for a WKB type.
Definition: qgswkbtypes.h:302
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28