QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
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
20#include "qgsgeometryengine.h"
21#include "qgsoverlayutils.h"
22#include "qgsvectorlayer.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsClipAlgorithm::name() const
31{
32 return u"clip"_s;
33}
34
35Qgis::ProcessingAlgorithmFlags QgsClipAlgorithm::flags() const
36{
39 return f;
40}
41
42QString QgsClipAlgorithm::displayName() const
43{
44 return QObject::tr( "Clip" );
45}
46
47QStringList QgsClipAlgorithm::tags() const
48{
49 return QObject::tr( "clip,intersect,intersection,mask" ).split( ',' );
50}
51
52QString QgsClipAlgorithm::group() const
53{
54 return QObject::tr( "Vector overlay" );
55}
56
57QString QgsClipAlgorithm::groupId() const
58{
59 return u"vectoroverlay"_s;
60}
61
62void QgsClipAlgorithm::initAlgorithm( const QVariantMap & )
63{
64 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ) ) );
65 addParameter( new QgsProcessingParameterFeatureSource( u"OVERLAY"_s, QObject::tr( "Overlay layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
66
67 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Clipped" ) ) );
68}
69
70QString QgsClipAlgorithm::shortHelpString() const
71{
72 return QObject::tr(
73 "This algorithm clips a vector layer using the features of an additional polygon layer. Only the parts of the features "
74 "in the Input layer that fall within the polygons of the Overlay layer will be added to the resulting layer."
75 )
76 + u"\n\n"_s
77 + QObject::tr(
78 "The attributes of the features are not modified, although properties such as area or length of the features will "
79 "be modified by the clipping operation. If such properties are stored as attributes, those attributes will have to "
80 "be manually updated."
81 );
82}
83
84QString QgsClipAlgorithm::shortDescription() const
85{
86 return QObject::tr( "Clips a vector layer using the features of an additional polygon layer." );
87}
88
89QgsClipAlgorithm *QgsClipAlgorithm::createInstance() const
90{
91 return new QgsClipAlgorithm();
92}
93
94bool QgsClipAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
95{
96 const QgsVectorLayer *layer = qobject_cast<const QgsVectorLayer *>( l );
97 if ( !layer )
98 return false;
99
100 return layer->isSpatial();
101}
102
103QVariantMap QgsClipAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
104{
105 std::unique_ptr<QgsFeatureSource> featureSource( parameterAsSource( parameters, u"INPUT"_s, context ) );
106 if ( !featureSource )
107 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
108
109 std::unique_ptr<QgsFeatureSource> maskSource( parameterAsSource( parameters, u"OVERLAY"_s, context ) );
110 if ( !maskSource )
111 throw QgsProcessingException( invalidSourceError( parameters, u"OVERLAY"_s ) );
112
113 if ( featureSource->hasSpatialIndex() == Qgis::SpatialIndexPresence::NotPresent )
114 feedback->pushWarning( QObject::tr( "No spatial index exists for input layer, performance will be severely degraded" ) );
115
116 QString dest;
117 const Qgis::GeometryType sinkType = QgsWkbTypes::geometryType( featureSource->wkbType() );
118 std::unique_ptr<QgsFeatureSink> sink(
119 parameterAsSink( parameters, u"OUTPUT"_s, context, dest, featureSource->fields(), QgsWkbTypes::promoteNonPointTypesToMulti( featureSource->wkbType() ), featureSource->sourceCrs() )
120 );
121
122 if ( !sink )
123 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
124
125 // first build up a list of clip geometries
126 QVector<QgsGeometry> clipGeoms;
127 QgsFeatureIterator it = maskSource->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QList<int>() ).setDestinationCrs( featureSource->sourceCrs(), context.transformContext() ) );
128 QgsFeature f;
129 while ( it.nextFeature( f ) )
130 {
131 if ( f.hasGeometry() )
132 clipGeoms << f.geometry();
133 }
134
135 QVariantMap outputs;
136 outputs.insert( u"OUTPUT"_s, dest );
137
138 if ( clipGeoms.isEmpty() )
139 return outputs;
140
141 // are we clipping against a single feature? if so, we can show finer progress reports
142 bool singleClipFeature = false;
143 QgsGeometry combinedClipGeom;
144 if ( clipGeoms.length() > 1 )
145 {
146 combinedClipGeom = QgsGeometry::unaryUnion( clipGeoms );
147 if ( combinedClipGeom.isEmpty() )
148 {
149 throw QgsProcessingException( QObject::tr( "Could not create the combined clip geometry: %1" ).arg( combinedClipGeom.lastError() ) );
150 }
151 singleClipFeature = false;
152 }
153 else
154 {
155 combinedClipGeom = clipGeoms.at( 0 );
156 singleClipFeature = true;
157 }
158
159 // use prepared geometries for faster intersection tests
160 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( combinedClipGeom.constGet() ) );
161 engine->prepareGeometry();
162
163 QgsFeatureIds testedFeatureIds;
164
165 int i = -1;
166 const auto constClipGeoms = clipGeoms;
167 for ( const QgsGeometry &clipGeom : constClipGeoms )
168 {
169 i++;
170 if ( feedback->isCanceled() )
171 {
172 break;
173 }
174 QgsFeatureIterator inputIt = featureSource->getFeatures( QgsFeatureRequest().setFilterRect( clipGeom.boundingBox() ) );
175 QgsFeatureList inputFeatures;
176 QgsFeature f;
177 while ( inputIt.nextFeature( f ) )
178 inputFeatures << f;
179
180 if ( inputFeatures.isEmpty() )
181 continue;
182
183 double step = 0;
184 if ( singleClipFeature )
185 step = 100.0 / inputFeatures.length();
186
187 const int current = 0;
188 const auto constInputFeatures = inputFeatures;
189 for ( const QgsFeature &inputFeature : constInputFeatures )
190 {
191 if ( feedback->isCanceled() )
192 {
193 break;
194 }
195
196 if ( !inputFeature.hasGeometry() )
197 continue;
198
199 if ( testedFeatureIds.contains( inputFeature.id() ) )
200 {
201 // don't retest a feature we have already checked
202 continue;
203 }
204 testedFeatureIds.insert( inputFeature.id() );
205
206 if ( !engine->intersects( inputFeature.geometry().constGet() ) )
207 continue;
208
209 QgsGeometry newGeometry;
210 if ( !engine->contains( inputFeature.geometry().constGet() ) )
211 {
212 const QgsGeometry currentGeometry = inputFeature.geometry();
213 newGeometry = combinedClipGeom.intersection( currentGeometry );
215 {
216 const QgsGeometry intCom = inputFeature.geometry().combine( newGeometry );
217 const QgsGeometry intSym = inputFeature.geometry().symDifference( newGeometry );
218 newGeometry = intCom.difference( intSym );
219 }
220 }
221 else
222 {
223 // clip geometry totally contains feature geometry, so no need to perform intersection
224 newGeometry = inputFeature.geometry();
225 }
226
227 if ( !QgsOverlayUtils::sanitizeIntersectionResult( newGeometry, sinkType, QgsOverlayUtils::SanitizeFlag::DontPromotePointGeometryToMultiPoint ) )
228 continue;
229
230 QgsFeature outputFeature;
231 outputFeature.setGeometry( newGeometry );
232 outputFeature.setAttributes( inputFeature.attributes() );
233 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
234 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
235
236
237 if ( singleClipFeature )
238 feedback->setProgress( current * step );
239 }
240
241 if ( !singleClipFeature )
242 {
243 // coarse progress report for multiple clip geometries
244 feedback->setProgress( 100.0 * static_cast<double>( i ) / clipGeoms.length() );
245 }
246 }
247
248 sink->finalize();
249
250 return outputs;
251}
252
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3650
@ NotPresent
No spatial index exists for the source.
Definition qgis.h:586
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:379
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3724
@ Unknown
Unknown.
Definition qgis.h:295
@ GeometryCollection
GeometryCollection.
Definition qgis.h:303
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3705
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
A geometry is the spatial representation of a feature.
QgsGeometry difference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points making up this geometry that do not make up other.
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
QgsGeometry combine(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing all the points in this geometry and other (a union geometry operation...
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
QgsGeometry symDifference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points making up this geometry that do not make up other.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Base class for all map layer types.
Definition qgsmaplayer.h:83
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
Represents a vector layer which manages a vector based dataset.
bool isSpatial() const final
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Qgis::WkbType promoteNonPointTypesToMulti(Qgis::WkbType type)
Promotes a WKB geometry type to its multi-type equivalent, with the exception of point geometry types...
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
QList< QgsFeature > QgsFeatureList
QSet< QgsFeatureId > QgsFeatureIds