QGIS API Documentation  3.26.3-Buenos Aires (65e4edfdad)
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 
23 QString QgsSplitWithLinesAlgorithm::name() const
24 {
25  return QStringLiteral( "splitwithlines" );
26 }
27 
28 QString QgsSplitWithLinesAlgorithm::displayName() const
29 {
30  return QObject::tr( "Split with lines" );
31 }
32 
33 QStringList QgsSplitWithLinesAlgorithm::tags() const
34 {
35  return QObject::tr( "split,cut,lines" ).split( ',' );
36 }
37 
38 QString QgsSplitWithLinesAlgorithm::group() const
39 {
40  return QObject::tr( "Vector overlay" );
41 }
42 
43 QString QgsSplitWithLinesAlgorithm::groupId() const
44 {
45  return QStringLiteral( "vectoroverlay" );
46 }
47 
48 void 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 
57 QString 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 
63 QgsSplitWithLinesAlgorithm *QgsSplitWithLinesAlgorithm::createInstance() const
64 {
65  return new QgsSplitWithLinesAlgorithm();
66 }
67 
68 QgsProcessingAlgorithm::Flags QgsSplitWithLinesAlgorithm::flags() const
69 {
72  return f;
73 }
74 
75 bool 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 
87 QVariantMap 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  inGeoms.append( inGeom );
226  inGeoms.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 
QgsCurve
Abstract base class for curved geometry type.
Definition: qgscurve.h:35
QgsAbstractGeometry::coordinateSequence
virtual QgsCoordinateSequence coordinateSequence() const =0
Retrieves the sequence of geometries, rings and nodes.
QgsCoordinateSequence
QVector< QgsRingSequence > QgsCoordinateSequence
Definition: qgsabstractgeometry.h:57
QgsFeedback::setProgress
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:76
QgsPoint
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:48
QgsProcessingFeedback
Base class for providing feedback from a processing algorithm.
Definition: qgsprocessingfeedback.h:37
qgsalgorithmsplitwithlines.h
QgsProcessing::TypeVectorPolygon
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:51
QgsFeature::geometry
QgsGeometry geometry
Definition: qgsfeature.h:71
QgsFeedback::isCanceled
bool isCanceled() const SIP_HOLDGIL
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:67
QgsProcessing::TypeVectorLine
@ TypeVectorLine
Vector line layers.
Definition: qgsprocessing.h:50
QgsProcessingParameterFeatureSource
An input feature source (such as vector layers) parameter for processing algorithms.
Definition: qgsprocessingparameters.h:3057
QgsWkbTypes::multiType
static Type multiType(Type type) SIP_HOLDGIL
Returns the multi type for a WKB type.
Definition: qgswkbtypes.h:304
QgsGeometry::splitGeometry
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.
Definition: qgsgeometry.cpp:926
QgsWkbTypes::PolygonGeometry
@ PolygonGeometry
Definition: qgswkbtypes.h:144
QgsGeometry::asGeometryCollection
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
Definition: qgsgeometry.cpp:2753
QgsProcessingParameterFeatureSink
A feature sink output for processing algorithms.
Definition: qgsprocessingparameters.h:3219
QgsFeature::id
QgsFeatureId id
Definition: qgsfeature.h:68
QgsFeatureRequest
This class wraps a request for features to a vector layer (or directly its vector data provider).
Definition: qgsfeaturerequest.h:83
qgsgeometryengine.h
QgsFeature::setGeometry
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:170
QgsProcessingContext
Contains information about the context in which a processing algorithm is executed.
Definition: qgsprocessingcontext.h:46
Qgis::GeometryOperationResult
GeometryOperationResult
Success or failure of a geometry operation.
Definition: qgis.h:901
QgsSpatialIndex
A spatial index for QgsFeature objects.
Definition: qgsspatialindex.h:67
QgsProcessingContext::transformContext
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Definition: qgsprocessingcontext.h:165
QgsGeometry::isNull
bool isNull
Definition: qgsgeometry.h:127
QgsFeatureRequest::setNoAttributes
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
Definition: qgsfeaturerequest.cpp:235
QgsRingSequence
QVector< QgsPointSequence > QgsRingSequence
Definition: qgsabstractgeometry.h:56
QgsGeometry::constGet
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Definition: qgsgeometry.cpp:136
QgsFeatureIds
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37
QgsFeatureSink::RegeneratePrimaryKey
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
Definition: qgsfeaturesink.h:55
QgsFeature::attributes
QgsAttributes attributes
Definition: qgsfeature.h:69
qgsvectorlayer.h
QgsGeometry::hausdorffDistance
double hausdorffDistance(const QgsGeometry &geom) const
Returns the Hausdorff distance between this geometry and geom.
Definition: qgsgeometry.cpp:1933
QgsSpatialIndex::FlagStoreFeatureGeometries
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
Definition: qgsspatialindex.h:77
QgsGeometry::createGeometryEngine
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine representing the specified geometry.
Definition: qgsgeometry.cpp:3972
QgsWkbTypes::LineGeometry
@ LineGeometry
Definition: qgswkbtypes.h:143
QgsFeatureIterator::nextFeature
bool nextFeature(QgsFeature &f)
Definition: qgsfeatureiterator.h:399
QgsPointSequence
QVector< QgsPoint > QgsPointSequence
Definition: qgsabstractgeometry.h:52
QgsGeometry
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
QgsVectorLayer
Represents a vector layer which manages a vector based data sets.
Definition: qgsvectorlayer.h:391
QgsFeature::hasGeometry
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:230
QgsMapLayer
Base class for all map layer types. This is the base class for all map layer types (vector,...
Definition: qgsmaplayer.h:72
Qgis::GeometryOperationResult::Success
@ Success
Operation succeeded.
QgsWkbTypes::geometryType
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
QgsGeometry::boundingBox
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Definition: qgsgeometry.cpp:1080
QgsFeature
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:55
QgsFeatureRequest::setDestinationCrs
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
Definition: qgsfeaturerequest.cpp:301
QgsFeature::setAttributes
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:160
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:90
QgsFeatureIterator
Wrapper for iterator of features from vector data provider or vector layer.
Definition: qgsfeatureiterator.h:289
QgsVectorLayer::geometryType
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
Definition: qgsvectorlayer.cpp:720
QgsProcessingException
Custom exception class for processing related exceptions.
Definition: qgsexception.h:82
QgsProcessingAlgorithm::FlagSupportsInPlaceEdits
@ FlagSupportsInPlaceEdits
Algorithm supports in-place editing.
Definition: qgsprocessingalgorithm.h:78
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
QgsFeatureId
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28