QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmsplitwithlines.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmsplitwithlines.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
19#include "qgsgeometryengine.h"
20#include "qgsvectorlayer.h"
21#include "qgsspatialindex.h"
22
24
25QString QgsSplitWithLinesAlgorithm::name() const
26{
27 return QStringLiteral( "splitwithlines" );
28}
29
30QString QgsSplitWithLinesAlgorithm::displayName() const
31{
32 return QObject::tr( "Split with lines" );
33}
34
35QStringList QgsSplitWithLinesAlgorithm::tags() const
36{
37 return QObject::tr( "split,cut,lines" ).split( ',' );
38}
39
40QString QgsSplitWithLinesAlgorithm::group() const
41{
42 return QObject::tr( "Vector overlay" );
43}
44
45QString QgsSplitWithLinesAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectoroverlay" );
48}
49
50void QgsSplitWithLinesAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
53 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "LINES" ), QObject::tr( "Split layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
54 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Split" ) ) );
55}
56
57QString QgsSplitWithLinesAlgorithm::shortHelpString() const
58{
59 return QObject::tr( "This algorithm splits the lines or polygons in one layer using the lines or polygon rings in another layer to define the breaking points. "
60 "Intersection between geometries in both layers are considered as split points." );
61}
62
63QString QgsSplitWithLinesAlgorithm::shortDescription() const
64{
65 return QObject::tr( "Splits the lines or polygons in one layer using the lines or polygon rings in another layer to define the breaking points." );
66}
67
68Qgis::ProcessingAlgorithmDocumentationFlags QgsSplitWithLinesAlgorithm::documentationFlags() const
69{
71}
72
73QgsSplitWithLinesAlgorithm *QgsSplitWithLinesAlgorithm::createInstance() const
74{
75 return new QgsSplitWithLinesAlgorithm();
76}
77
78Qgis::ProcessingAlgorithmFlags QgsSplitWithLinesAlgorithm::flags() const
79{
82 return f;
83}
84
85bool QgsSplitWithLinesAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
86{
87 const QgsVectorLayer *layer = qobject_cast<const QgsVectorLayer *>( l );
88 if ( !layer )
89 return false;
90
92 return false;
93
94 return true;
95}
96
97QVariantMap QgsSplitWithLinesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
98{
99 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
100 if ( !source )
101 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
102
103 std::unique_ptr<QgsFeatureSource> linesSource( parameterAsSource( parameters, QStringLiteral( "LINES" ), context ) );
104 if ( !linesSource )
105 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "LINES" ) ) );
106
107 bool sameLayer = parameters.value( QStringLiteral( "INPUT" ) ) == parameters.value( QStringLiteral( "LINES" ) );
108
109 QString dest;
110 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(), QgsWkbTypes::multiType( source->wkbType() ), source->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
111 if ( !sink )
112 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
113
114 QgsFeatureRequest request;
115 request.setNoAttributes();
116 request.setDestinationCrs( source->sourceCrs(), context.transformContext() );
117
118 QgsFeatureIterator splitFeatures = linesSource->getFeatures( request );
119 QgsFeature aSplitFeature;
120
121 const QgsSpatialIndex splitFeaturesIndex( splitFeatures, feedback, QgsSpatialIndex::FlagStoreFeatureGeometries );
122
123 QgsFeature outFeat;
124 QgsFeatureIterator features = source->getFeatures();
125
126 double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
127 int i = 0;
128 QgsFeature inFeatureA;
129 while ( features.nextFeature( inFeatureA ) )
130 {
131 i++;
132 if ( feedback->isCanceled() )
133 {
134 break;
135 }
136
137 if ( !inFeatureA.hasGeometry() )
138 {
139 if ( !sink->addFeature( inFeatureA, QgsFeatureSink::FastInsert ) )
140 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
141 continue;
142 }
143
144 const QgsGeometry originalGeometry = inFeatureA.geometry();
145 outFeat.setAttributes( inFeatureA.attributes() );
146
147 QVector<QgsGeometry> inGeoms = originalGeometry.asGeometryCollection();
148
149 const QgsFeatureIds splitFeatureCandidates = qgis::listToSet( splitFeaturesIndex.intersects( originalGeometry.boundingBox() ) );
150 if ( !splitFeatureCandidates.empty() ) // has intersection of bounding boxes
151 {
152 QVector<QgsGeometry> splittingLines;
153
154 // use prepared geometries for faster intersection tests
155 std::unique_ptr<QgsGeometryEngine> originalGeometryEngine;
156
157 for ( QgsFeatureId splitFeatureCandidateId : splitFeatureCandidates )
158 {
159 // check if trying to self-intersect
160 if ( sameLayer && inFeatureA.id() == splitFeatureCandidateId )
161 continue;
162
163 const QgsGeometry splitFeatureCandidate = splitFeaturesIndex.geometry( splitFeatureCandidateId );
164 if ( !originalGeometryEngine )
165 {
166 originalGeometryEngine.reset( QgsGeometry::createGeometryEngine( originalGeometry.constGet() ) );
167 originalGeometryEngine->prepareGeometry();
168 }
169
170 if ( originalGeometryEngine->intersects( splitFeatureCandidate.constGet() ) )
171 {
172 QVector<QgsGeometry> splitGeomParts = splitFeatureCandidate.convertToType( Qgis::GeometryType::Line, true ).asGeometryCollection();
173 splittingLines.append( splitGeomParts );
174 }
175 }
176
177 if ( !splittingLines.empty() )
178 {
179 for ( const QgsGeometry &splitGeom : std::as_const( splittingLines ) )
180 {
181 QgsPointSequence splitterPList;
182 QVector<QgsGeometry> outGeoms;
183
184 // use prepared geometries for faster intersection tests
185 std::unique_ptr<QgsGeometryEngine> splitGeomEngine( QgsGeometry::createGeometryEngine( splitGeom.constGet() ) );
186 splitGeomEngine->prepareGeometry();
187 while ( !inGeoms.empty() )
188 {
189 if ( feedback->isCanceled() )
190 {
191 break;
192 }
193
194 QgsGeometry inGeom = inGeoms.takeFirst();
195 if ( inGeom.isNull() )
196 continue;
197
198 if ( splitGeomEngine->intersects( inGeom.constGet() ) )
199 {
200 QgsGeometry before = inGeom;
201 if ( splitterPList.empty() )
202 {
203 const QgsCoordinateSequence sequence = splitGeom.constGet()->coordinateSequence();
204 for ( const QgsRingSequence &part : sequence )
205 {
206 for ( const QgsPointSequence &ring : part )
207 {
208 for ( const QgsPoint &pt : ring )
209 {
210 splitterPList << pt;
211 }
212 }
213 }
214 }
215
216 QVector<QgsGeometry> newGeometries;
217 QgsPointSequence topologyTestPoints;
218 Qgis::GeometryOperationResult result = inGeom.splitGeometry( splitterPList, newGeometries, false, topologyTestPoints, true );
219
220 // splitGeometry: If there are several intersections
221 // between geometry and splitLine, only the first one is considered.
223 {
224 // sometimes the resultant geometry has changed from the input, but only because of numerical precision issues.
225 // and is effectively indistinguishable from the input. By testing the Hausdorff distance is less than this threshold
226 // we are checking that the maximum "change" between the result and the input is actually significant enough to be meaningful...
227 if ( inGeom.hausdorffDistance( before ) < 1e-12 )
228 {
229 // effectively no change!!
230 outGeoms.append( inGeom );
231 }
232 else
233 {
234 outGeoms.append( inGeom );
235 outGeoms.append( newGeometries );
236 }
237 }
238 else
239 {
240 outGeoms.append( inGeom );
241 }
242 }
243 else
244 {
245 outGeoms.append( inGeom );
246 }
247 }
248 inGeoms = outGeoms;
249 }
250 }
251 }
252
253 QVector<QgsGeometry> parts;
254 for ( const QgsGeometry &aGeom : std::as_const( inGeoms ) )
255 {
256 if ( feedback->isCanceled() )
257 {
258 break;
259 }
260
261 bool passed = true;
262 if ( QgsWkbTypes::geometryType( aGeom.wkbType() ) == Qgis::GeometryType::Line )
263 {
264 int numPoints = aGeom.constGet()->nCoordinates();
265
266 if ( numPoints <= 2 )
267 {
268 if ( numPoints == 2 )
269 passed = !static_cast<const QgsCurve *>( aGeom.constGet() )->isClosed(); // tests if vertex 0 = vertex 1
270 else
271 passed = false; // sometimes splitting results in lines of zero length
272 }
273 }
274
275 if ( passed )
276 parts.append( aGeom );
277 }
278
279 for ( const QgsGeometry &g : parts )
280 {
281 outFeat.setGeometry( g );
282 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
283 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
284 }
285
286 feedback->setProgress( i * step );
287 }
288
289 sink->finalize();
290
291 QVariantMap outputs;
292 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
293 return outputs;
294}
295
296
@ VectorPolygon
Vector polygon layers.
@ VectorLine
Vector line layers.
GeometryOperationResult
Success or failure of a geometry operation.
Definition qgis.h:2005
@ Success
Operation succeeded.
@ Polygon
Polygons.
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3476
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3496
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
virtual QgsCoordinateSequence coordinateSequence() const =0
Retrieves the sequence of geometries, rings and nodes.
Abstract base class for curved geometry type.
Definition qgscurve.h:35
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).
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsAttributes attributes
Definition qgsfeature.h:67
QgsFeatureId id
Definition qgsfeature.h:66
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
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:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
A geometry is the spatial representation of a feature.
QgsGeometry convertToType(Qgis::GeometryType destType, bool destMultipart=false) const
Try to convert the geometry to the requested type.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
double hausdorffDistance(const QgsGeometry &geom) const
Returns the Hausdorff distance between this geometry and geom.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Q_DECL_DEPRECATED Qgis::GeometryOperationResult splitGeometry(const QVector< QgsPointXY > &splitLine, QVector< QgsGeometry > &newGeometries, bool topological, QVector< QgsPointXY > &topologyTestPoints, bool splitFeature=true)
Splits this geometry according to a given line.
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:77
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
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.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
Represents a vector layer which manages a vector based dataset.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
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 multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.
QVector< QgsRingSequence > QgsCoordinateSequence
QVector< QgsPointSequence > QgsRingSequence
QVector< QgsPoint > QgsPointSequence
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features