QGIS API Documentation  3.14.0-Pi (9f7028fd23)
qgsalgorithmclip.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmclip.cpp
3  ---------------------
4  begin : April 2017
5  copyright : (C) 2017 by Nyall Dawson
6  email : nyall dot dawson at gmail dot com
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
18 #include "qgsalgorithmclip.h"
19 #include "qgsgeometryengine.h"
20 #include "qgsoverlayutils.h"
21 #include "qgsvectorlayer.h"
22 
24 
25 QString QgsClipAlgorithm::name() const
26 {
27  return QStringLiteral( "clip" );
28 }
29 
30 QgsProcessingAlgorithm::Flags QgsClipAlgorithm::flags() const
31 {
34  return f;
35 }
36 
37 QString QgsClipAlgorithm::displayName() const
38 {
39  return QObject::tr( "Clip" );
40 }
41 
42 QStringList QgsClipAlgorithm::tags() const
43 {
44  return QObject::tr( "clip,intersect,intersection,mask" ).split( ',' );
45 }
46 
47 QString QgsClipAlgorithm::group() const
48 {
49  return QObject::tr( "Vector overlay" );
50 }
51 
52 QString QgsClipAlgorithm::groupId() const
53 {
54  return QStringLiteral( "vectoroverlay" );
55 }
56 
57 void QgsClipAlgorithm::initAlgorithm( const QVariantMap & )
58 {
59  addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
60  addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "OVERLAY" ), QObject::tr( "Overlay layer" ), QList< int >() << QgsProcessing::TypeVectorPolygon ) );
61 
62  addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Clipped" ) ) );
63 }
64 
65 QString QgsClipAlgorithm::shortHelpString() const
66 {
67  return QObject::tr( "This algorithm clips a vector layer using the features of an additional polygon layer. Only the parts of the features "
68  "in the Input layer that fall within the polygons of the Overlay layer will be added to the resulting layer." )
69  + QStringLiteral( "\n\n" )
70  + QObject::tr( "The attributes of the features are not modified, although properties such as area or length of the features will "
71  "be modified by the clipping operation. If such properties are stored as attributes, those attributes will have to "
72  "be manually updated." );
73 }
74 
75 QgsClipAlgorithm *QgsClipAlgorithm::createInstance() const
76 {
77  return new QgsClipAlgorithm();
78 }
79 
80 bool QgsClipAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
81 {
82  const QgsVectorLayer *layer = qobject_cast< const QgsVectorLayer * >( l );
83  if ( !layer )
84  return false;
85 
86  return layer->isSpatial();
87 }
88 
89 QVariantMap QgsClipAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
90 {
91  std::unique_ptr< QgsFeatureSource > featureSource( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
92  if ( !featureSource )
93  throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
94 
95  std::unique_ptr< QgsFeatureSource > maskSource( parameterAsSource( parameters, QStringLiteral( "OVERLAY" ), context ) );
96  if ( !maskSource )
97  throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "OVERLAY" ) ) );
98 
99  QString dest;
100  QgsWkbTypes::GeometryType sinkType = QgsWkbTypes::geometryType( featureSource->wkbType() );
101  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, featureSource->fields(), QgsWkbTypes::multiType( featureSource->wkbType() ), featureSource->sourceCrs() ) );
102 
103  if ( !sink )
104  throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
105 
106  // first build up a list of clip geometries
107  QVector< QgsGeometry > clipGeoms;
108  QgsFeatureIterator it = maskSource->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QList< int >() ).setDestinationCrs( featureSource->sourceCrs(), context.transformContext() ) );
109  QgsFeature f;
110  while ( it.nextFeature( f ) )
111  {
112  if ( f.hasGeometry() )
113  clipGeoms << f.geometry();
114  }
115 
116  QVariantMap outputs;
117  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
118 
119  if ( clipGeoms.isEmpty() )
120  return outputs;
121 
122  // are we clipping against a single feature? if so, we can show finer progress reports
123  bool singleClipFeature = false;
124  QgsGeometry combinedClipGeom;
125  if ( clipGeoms.length() > 1 )
126  {
127  combinedClipGeom = QgsGeometry::unaryUnion( clipGeoms );
128  if ( combinedClipGeom.isEmpty() )
129  {
130  throw QgsProcessingException( QObject::tr( "Could not create the combined clip geometry: %1" ).arg( combinedClipGeom.lastError() ) );
131  }
132  singleClipFeature = false;
133  }
134  else
135  {
136  combinedClipGeom = clipGeoms.at( 0 );
137  singleClipFeature = true;
138  }
139 
140  // use prepared geometries for faster intersection tests
141  std::unique_ptr< QgsGeometryEngine > engine( QgsGeometry::createGeometryEngine( combinedClipGeom.constGet() ) );
142  engine->prepareGeometry();
143 
144  QgsFeatureIds testedFeatureIds;
145 
146  int i = -1;
147  const auto constClipGeoms = clipGeoms;
148  for ( const QgsGeometry &clipGeom : constClipGeoms )
149  {
150  i++;
151  if ( feedback->isCanceled() )
152  {
153  break;
154  }
155  QgsFeatureIterator inputIt = featureSource->getFeatures( QgsFeatureRequest().setFilterRect( clipGeom.boundingBox() ) );
156  QgsFeatureList inputFeatures;
157  QgsFeature f;
158  while ( inputIt.nextFeature( f ) )
159  inputFeatures << f;
160 
161  if ( inputFeatures.isEmpty() )
162  continue;
163 
164  double step = 0;
165  if ( singleClipFeature )
166  step = 100.0 / inputFeatures.length();
167 
168  int current = 0;
169  const auto constInputFeatures = inputFeatures;
170  for ( const QgsFeature &inputFeature : constInputFeatures )
171  {
172  if ( feedback->isCanceled() )
173  {
174  break;
175  }
176 
177  if ( !inputFeature.hasGeometry() )
178  continue;
179 
180  if ( testedFeatureIds.contains( inputFeature.id() ) )
181  {
182  // don't retest a feature we have already checked
183  continue;
184  }
185  testedFeatureIds.insert( inputFeature.id() );
186 
187  if ( !engine->intersects( inputFeature.geometry().constGet() ) )
188  continue;
189 
190  QgsGeometry newGeometry;
191  if ( !engine->contains( inputFeature.geometry().constGet() ) )
192  {
193  QgsGeometry currentGeometry = inputFeature.geometry();
194  newGeometry = combinedClipGeom.intersection( currentGeometry );
195  if ( newGeometry.wkbType() == QgsWkbTypes::Unknown || QgsWkbTypes::flatType( newGeometry.wkbType() ) == QgsWkbTypes::GeometryCollection )
196  {
197  QgsGeometry intCom = inputFeature.geometry().combine( newGeometry );
198  QgsGeometry intSym = inputFeature.geometry().symDifference( newGeometry );
199  newGeometry = intCom.difference( intSym );
200  }
201  }
202  else
203  {
204  // clip geometry totally contains feature geometry, so no need to perform intersection
205  newGeometry = inputFeature.geometry();
206  }
207 
208  if ( !QgsOverlayUtils::sanitizeIntersectionResult( newGeometry, sinkType ) )
209  continue;
210 
211  QgsFeature outputFeature;
212  outputFeature.setGeometry( newGeometry );
213  outputFeature.setAttributes( inputFeature.attributes() );
214  sink->addFeature( outputFeature, QgsFeatureSink::FastInsert );
215 
216 
217  if ( singleClipFeature )
218  feedback->setProgress( current * step );
219  }
220 
221  if ( !singleClipFeature )
222  {
223  // coarse progress report for multiple clip geometries
224  feedback->setProgress( 100.0 * static_cast< double >( i ) / clipGeoms.length() );
225  }
226  }
227 
228  return outputs;
229 }
230 
QgsGeometry::combine
QgsGeometry combine(const QgsGeometry &geometry) const
Returns a geometry representing all the points in this geometry and other (a union geometry operation...
Definition: qgsgeometry.cpp:2417
QgsWkbTypes::multiType
static Type multiType(Type type)
Returns the multi type for a WKB type.
Definition: qgswkbtypes.h:301
QgsFeedback::setProgress
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:75
QgsProcessingFeedback
Definition: qgsprocessingfeedback.h:37
qgsalgorithmclip.h
QgsProcessing::TypeVectorPolygon
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:50
QgsFeature::geometry
QgsGeometry geometry
Definition: qgsfeature.h:71
QgsGeometry::wkbType
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
Definition: qgsgeometry.cpp:345
QgsVectorLayer::isSpatial
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
Definition: qgsvectorlayer.cpp:3591
QgsProcessingParameterFeatureSource
Definition: qgsprocessingparameters.h:2612
QgsGeometry::intersection
QgsGeometry intersection(const QgsGeometry &geometry) const
Returns a geometry representing the points shared by this geometry and other.
Definition: qgsgeometry.cpp:2395
QgsProcessingParameterFeatureSink
Definition: qgsprocessingparameters.h:2773
QgsFeatureRequest
Definition: qgsfeaturerequest.h:75
qgsgeometryengine.h
QgsWkbTypes::Unknown
@ Unknown
Definition: qgswkbtypes.h:70
QgsFeature::setGeometry
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:137
QgsProcessingContext
Definition: qgsprocessingcontext.h:43
QgsWkbTypes::GeometryCollection
@ GeometryCollection
Definition: qgswkbtypes.h:78
QgsFeatureList
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:572
QgsWkbTypes::geometryType
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
Definition: qgswkbtypes.h:937
QgsGeometry::isEmpty
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
Definition: qgsgeometry.cpp:367
QgsProcessingContext::transformContext
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Definition: qgsprocessingcontext.h:135
QgsGeometry::constGet
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Definition: qgsgeometry.cpp:128
QgsFeatureIds
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:34
qgsvectorlayer.h
QgsFeedback::isCanceled
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:66
QgsGeometry::createGeometryEngine
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine.
Definition: qgsgeometry.cpp:3659
QgsWkbTypes::GeometryType
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
Definition: qgswkbtypes.h:139
QgsFeatureIterator::nextFeature
bool nextFeature(QgsFeature &f)
Definition: qgsfeatureiterator.h:373
QgsGeometry
Definition: qgsgeometry.h:122
QgsGeometry::lastError
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
Definition: qgsgeometry.cpp:3018
QgsVectorLayer
Definition: qgsvectorlayer.h:385
QgsFeature::hasGeometry
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:197
QgsMapLayer
Definition: qgsmaplayer.h:81
QgsFeature
Definition: qgsfeature.h:55
QgsGeometry::symDifference
QgsGeometry symDifference(const QgsGeometry &geometry) const
Returns a geometry representing the points making up this geometry that do not make up other.
Definition: qgsgeometry.cpp:2476
qgsoverlayutils.h
QgsFeature::setAttributes
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:127
QgsProcessingAlgorithm::flags
virtual Flags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Definition: qgsprocessingalgorithm.cpp:88
QgsFeatureIterator
Definition: qgsfeatureiterator.h:263
QgsProcessingException
Definition: qgsexception.h:82
QgsGeometry::difference
QgsGeometry difference(const QgsGeometry &geometry) const
Returns a geometry representing the points making up this geometry that do not make up other.
Definition: qgsgeometry.cpp:2456
QgsWkbTypes::flatType
static Type flatType(Type type)
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:701
QgsProcessingAlgorithm::FlagSupportsInPlaceEdits
@ FlagSupportsInPlaceEdits
Algorithm supports in-place editing.
Definition: qgsprocessingalgorithm.h:77
QgsGeometry::unaryUnion
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries)
Compute the unary union on a list of geometries.
Definition: qgsgeometry.cpp:2785
QgsFeatureSink::FastInsert
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
Definition: qgsfeaturesink.h:70