QGIS API Documentation 3.28.0-Firenze (ed3ad0430f)
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"
22
23QString QgsSplitWithLinesAlgorithm::name() const
24{
25 return QStringLiteral( "splitwithlines" );
26}
27
28QString QgsSplitWithLinesAlgorithm::displayName() const
29{
30 return QObject::tr( "Split with lines" );
31}
32
33QStringList QgsSplitWithLinesAlgorithm::tags() const
34{
35 return QObject::tr( "split,cut,lines" ).split( ',' );
36}
37
38QString QgsSplitWithLinesAlgorithm::group() const
39{
40 return QObject::tr( "Vector overlay" );
41}
42
43QString QgsSplitWithLinesAlgorithm::groupId() const
44{
45 return QStringLiteral( "vectoroverlay" );
46}
47
48void QgsSplitWithLinesAlgorithm::initAlgorithm( const QVariantMap & )
49{
50 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ),
51 QObject::tr( "Input layer" ), QList< int >() << QgsProcessing::TypeVectorLine << QgsProcessing::TypeVectorPolygon ) );
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "LINES" ),
53 QObject::tr( "Split layer" ), QList< int >() << QgsProcessing::TypeVectorLine ) );
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 in another layer to define the breaking points. "
60 "Intersection between geometries in both layers are considered as split points." );
61}
62
63QgsSplitWithLinesAlgorithm *QgsSplitWithLinesAlgorithm::createInstance() const
64{
65 return new QgsSplitWithLinesAlgorithm();
66}
67
68QgsProcessingAlgorithm::Flags QgsSplitWithLinesAlgorithm::flags() const
69{
72 return f;
73}
74
75bool QgsSplitWithLinesAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
76{
77 const QgsVectorLayer *layer = qobject_cast< const QgsVectorLayer * >( l );
78 if ( !layer )
79 return false;
80
82 return false;
83
84 return true;
85}
86
87QVariantMap QgsSplitWithLinesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
88{
89 std::unique_ptr< QgsFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
90 if ( !source )
91 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
92
93 std::unique_ptr< QgsFeatureSource > linesSource( parameterAsSource( parameters, QStringLiteral( "LINES" ), context ) );
94 if ( !linesSource )
95 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "LINES" ) ) );
96
97 bool sameLayer = parameters.value( QStringLiteral( "INPUT" ) ) == parameters.value( QStringLiteral( "LINES" ) );
98
99 QString dest;
100 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(),
101 QgsWkbTypes::multiType( source->wkbType() ), source->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
102 if ( !sink )
103 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
104
105 QgsFeatureRequest request;
106 request.setNoAttributes();
107 request.setDestinationCrs( source->sourceCrs(), context.transformContext() );
108
109 QgsFeatureIterator splitLines = linesSource->getFeatures( request );
110 QgsFeature aSplitFeature;
111
112 const QgsSpatialIndex splitLinesIndex( splitLines, feedback, QgsSpatialIndex::FlagStoreFeatureGeometries );
113
114 QgsFeature outFeat;
115 QgsFeatureIterator features = source->getFeatures();
116
117 double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
118 int i = 0;
119 QgsFeature inFeatureA;
120 while ( features.nextFeature( inFeatureA ) )
121 {
122 i++;
123 if ( feedback->isCanceled() )
124 {
125 break;
126 }
127
128 if ( !inFeatureA.hasGeometry() )
129 {
130 if ( !sink->addFeature( inFeatureA, QgsFeatureSink::FastInsert ) )
131 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
132 continue;
133 }
134
135 const QgsGeometry originalGeometry = inFeatureA.geometry();
136 outFeat.setAttributes( inFeatureA.attributes() );
137
138 QVector< QgsGeometry > inGeoms = originalGeometry.asGeometryCollection();
139
140 const QgsFeatureIds splitLineCandidates = qgis::listToSet( splitLinesIndex.intersects( originalGeometry.boundingBox() ) );
141 if ( !splitLineCandidates.empty() ) // has intersection of bounding boxes
142 {
143 QVector< QgsGeometry > splittingLines;
144
145 // use prepared geometries for faster intersection tests
146 std::unique_ptr< QgsGeometryEngine > originalGeometryEngine;
147
148 for ( QgsFeatureId splitLineCandidateId : splitLineCandidates )
149 {
150 // check if trying to self-intersect
151 if ( sameLayer && inFeatureA.id() == splitLineCandidateId )
152 continue;
153
154 const QgsGeometry splitLineCandidate = splitLinesIndex.geometry( splitLineCandidateId );
155 if ( !originalGeometryEngine )
156 {
157 originalGeometryEngine.reset( QgsGeometry::createGeometryEngine( originalGeometry.constGet() ) );
158 originalGeometryEngine->prepareGeometry();
159 }
160
161 if ( originalGeometryEngine->intersects( splitLineCandidate.constGet() ) )
162 {
163 QVector< QgsGeometry > splitGeomParts = splitLineCandidate.asGeometryCollection();
164 splittingLines.append( splitGeomParts );
165 }
166 }
167
168 if ( !splittingLines.empty() )
169 {
170 for ( const QgsGeometry &splitGeom : std::as_const( splittingLines ) )
171 {
172 QgsPointSequence splitterPList;
173 QVector< QgsGeometry > outGeoms;
174
175 // use prepared geometries for faster intersection tests
176 std::unique_ptr< QgsGeometryEngine > splitGeomEngine( QgsGeometry::createGeometryEngine( splitGeom.constGet() ) );
177 splitGeomEngine->prepareGeometry();
178 while ( !inGeoms.empty() )
179 {
180 if ( feedback->isCanceled() )
181 {
182 break;
183 }
184
185 QgsGeometry inGeom = inGeoms.takeFirst();
186 if ( inGeom.isNull() )
187 continue;
188
189 if ( splitGeomEngine->intersects( inGeom.constGet() ) )
190 {
191 QgsGeometry before = inGeom;
192 if ( splitterPList.empty() )
193 {
194 const QgsCoordinateSequence sequence = splitGeom.constGet()->coordinateSequence();
195 for ( const QgsRingSequence &part : sequence )
196 {
197 for ( const QgsPointSequence &ring : part )
198 {
199 for ( const QgsPoint &pt : ring )
200 {
201 splitterPList << pt;
202 }
203 }
204 }
205 }
206
207 QVector< QgsGeometry > newGeometries;
208 QgsPointSequence topologyTestPoints;
209 Qgis::GeometryOperationResult result = inGeom.splitGeometry( splitterPList, newGeometries, false, topologyTestPoints, true );
210
211 // splitGeometry: If there are several intersections
212 // between geometry and splitLine, only the first one is considered.
214 {
215 // sometimes the resultant geometry has changed from the input, but only because of numerical precision issues.
216 // and is effectively indistinguishable from the input. By testing the Hausdorff distance is less than this threshold
217 // we are checking that the maximum "change" between the result and the input is actually significant enough to be meaningful...
218 if ( inGeom.hausdorffDistance( before ) < 1e-12 )
219 {
220 // effectively no change!!
221 outGeoms.append( inGeom );
222 }
223 else
224 {
225 outGeoms.append( inGeom );
226 outGeoms.append( newGeometries );
227 }
228 }
229 else
230 {
231 outGeoms.append( inGeom );
232 }
233 }
234 else
235 {
236 outGeoms.append( inGeom );
237 }
238
239 }
240 inGeoms = outGeoms;
241 }
242 }
243 }
244
245 QVector< QgsGeometry > parts;
246 for ( const QgsGeometry &aGeom : std::as_const( inGeoms ) )
247 {
248 if ( feedback->isCanceled() )
249 {
250 break;
251 }
252
253 bool passed = true;
254 if ( QgsWkbTypes::geometryType( aGeom.wkbType() ) == QgsWkbTypes::LineGeometry )
255 {
256 int numPoints = aGeom.constGet()->nCoordinates();
257
258 if ( numPoints <= 2 )
259 {
260 if ( numPoints == 2 )
261 passed = !static_cast< const QgsCurve * >( aGeom.constGet() )->isClosed(); // tests if vertex 0 = vertex 1
262 else
263 passed = false; // sometimes splitting results in lines of zero length
264 }
265 }
266
267 if ( passed )
268 parts.append( aGeom );
269 }
270
271 for ( const QgsGeometry &g : parts )
272 {
273 outFeat.setGeometry( g );
274 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
275 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
276 }
277
278 feedback->setProgress( i * step );
279 }
280
281 QVariantMap outputs;
282 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
283 return outputs;
284}
285
286
287
289
290
GeometryOperationResult
Success or failure of a geometry operation.
Definition: qgis.h:955
@ Success
Operation succeeded.
virtual QgsCoordinateSequence coordinateSequence() const =0
Retrieves the sequence of geometries, rings and nodes.
Abstract base class for curved geometry type.
Definition: qgscurve.h:36
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 & 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:56
QgsAttributes attributes
Definition: qgsfeature.h:65
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:160
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:233
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:170
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
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:164
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
Q_GADGET bool isNull
Definition: qgsgeometry.h:166
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine representing the specified geometry.
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.
Base class for all map layer types.
Definition: qgsmaplayer.h:73
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:49
virtual Flags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
@ FlagSupportsInPlaceEdits
Algorithm supports in-place editing.
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.
Definition: qgsexception.h:83
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.
@ TypeVectorLine
Vector line layers.
Definition: qgsprocessing.h:50
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:51
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 data sets.
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
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 multiType(Type type) SIP_HOLDGIL
Returns the multi type for a WKB type.
Definition: qgswkbtypes.h:304
QVector< QgsRingSequence > QgsCoordinateSequence
QVector< QgsPointSequence > QgsRingSequence
QVector< QgsPoint > QgsPointSequence
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