QGIS API Documentation  3.26.3-Buenos Aires (65e4edfdad)
qgsalgorithmsnapgeometries.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmsnapgeometries.cpp
3  ---------------------
4  begin : May 2020
5  copyright : (C) 2020 by Alexander Bruy
6  email : alexander dot bruy 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 
20 #include "qgsvectorlayer.h"
23 
25 
26 QString QgsSnapGeometriesAlgorithm::name() const
27 {
28  return QStringLiteral( "snapgeometries" );
29 }
30 
31 QString QgsSnapGeometriesAlgorithm::displayName() const
32 {
33  return QObject::tr( "Snap geometries to layer" );
34 }
35 
36 QString QgsSnapGeometriesAlgorithm::shortHelpString() const
37 {
38  return QObject::tr( "Snaps the geometries in a layer. Snapping can be done either to the geometries "
39  "from another layer, or to geometries within the same layer." )
40  + QStringLiteral( "\n\n" )
41  + QObject::tr( "A tolerance is specified in layer units to control how close vertices need "
42  "to be to the reference layer geometries before they are snapped." )
43  + QStringLiteral( "\n\n" )
44  + QObject::tr( "Snapping occurs to both nodes and edges. Depending on the snapping behavior, "
45  "either nodes or edges will be preferred." )
46  + QStringLiteral( "\n\n" )
47  + QObject::tr( "Vertices will be inserted or removed as required to make the geometries match "
48  "the reference geometries." );
49 }
50 
51 QStringList QgsSnapGeometriesAlgorithm::tags() const
52 {
53  return QObject::tr( "geometry,snap,tolerance" ).split( ',' );
54 }
55 
56 QString QgsSnapGeometriesAlgorithm::group() const
57 {
58  return QObject::tr( "Vector geometry" );
59 }
60 
61 QString QgsSnapGeometriesAlgorithm::groupId() const
62 {
63  return QStringLiteral( "vectorgeometry" );
64 }
65 
66 QgsProcessingAlgorithm::Flags QgsSnapGeometriesAlgorithm::flags() const
67 {
70  return f;
71 }
72 
73 bool QgsSnapGeometriesAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
74 {
75  const QgsVectorLayer *layer = qobject_cast< const QgsVectorLayer * >( l );
76  if ( !layer )
77  return false;
78 
79  return layer->isSpatial();
80 }
81 
82 void QgsSnapGeometriesAlgorithm::initAlgorithm( const QVariantMap & )
83 {
84  addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
86  addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "REFERENCE_LAYER" ), QObject::tr( "Reference layer" ),
88 
89  std::unique_ptr< QgsProcessingParameterDistance > tolParam = std::make_unique< QgsProcessingParameterDistance >( QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), 10.0, QStringLiteral( "INPUT" ), false, 0.00000001 );
90  tolParam->setMetadata(
91  {
92  QVariantMap( {{
93  QStringLiteral( "widget_wrapper" ),
94  QVariantMap( {{
95  QStringLiteral( "decimals" ), 8
96  }} )
97  }} )
98  } );
99  addParameter( tolParam.release() );
100 
101  const QStringList options = QStringList()
102  << QObject::tr( "Prefer aligning nodes, insert extra vertices where required" )
103  << QObject::tr( "Prefer closest point, insert extra vertices where required" )
104  << QObject::tr( "Prefer aligning nodes, don't insert new vertices" )
105  << QObject::tr( "Prefer closest point, don't insert new vertices" )
106  << QObject::tr( "Move end points only, prefer aligning nodes" )
107  << QObject::tr( "Move end points only, prefer closest point" )
108  << QObject::tr( "Snap end points to end points only" )
109  << QObject::tr( "Snap to anchor nodes (single layer only)" );
110  addParameter( new QgsProcessingParameterEnum( QStringLiteral( "BEHAVIOR" ), QObject::tr( "Behavior" ), options, false, QVariantList() << 0 ) );
111  addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ),
112  QObject::tr( "Snapped geometry" ), QgsProcessing::TypeVectorAnyGeometry ) );
113 }
114 
115 QgsSnapGeometriesAlgorithm *QgsSnapGeometriesAlgorithm::createInstance() const
116 {
117  return new QgsSnapGeometriesAlgorithm();
118 }
119 
120 QVariantMap QgsSnapGeometriesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
121 {
122  std::unique_ptr< QgsProcessingFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
123  if ( !source )
124  throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
125 
126  const std::unique_ptr< QgsProcessingFeatureSource > referenceSource( parameterAsSource( parameters, QStringLiteral( "REFERENCE_LAYER" ), context ) );
127  if ( !referenceSource )
128  throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "REFERENCE_LAYER" ) ) );
129 
130  const double tolerance = parameterAsDouble( parameters, QStringLiteral( "TOLERANCE" ), context );
131  const QgsGeometrySnapper::SnapMode mode = static_cast<QgsGeometrySnapper::SnapMode>( parameterAsEnum( parameters, QStringLiteral( "BEHAVIOR" ), context ) );
132 
133  QString dest;
134  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(), source->wkbType(), source->sourceCrs() ) );
135  if ( !sink )
136  throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
137 
138  QgsFeatureIterator features = source->getFeatures();
139 
140  if ( parameters.value( QStringLiteral( "INPUT" ) ) != parameters.value( QStringLiteral( "REFERENCE_LAYER" ) ) )
141  {
142  const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
143  if ( mode == 7 )
144  throw QgsProcessingException( QObject::tr( "This mode applies when the input and reference layer are the same." ) );
145 
146  const QgsGeometrySnapper snapper( referenceSource.get() );
147  long long processed = 0;
148  QgsFeature f;
149  while ( features.nextFeature( f ) )
150  {
151  if ( feedback->isCanceled() )
152  break;
153 
154  if ( f.hasGeometry() )
155  {
156  QgsFeature outFeature( f );
157  outFeature.setGeometry( snapper.snapGeometry( f.geometry(), tolerance, mode ) );
158  if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
159  throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
160  }
161  else
162  {
163  if ( !sink->addFeature( f ) )
164  throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
165  }
166  processed += 1;
167  feedback->setProgress( processed * step );
168  }
169  }
170  else if ( mode == 7 )
171  {
172  // input layer == reference layer
173  const int modified = QgsGeometrySnapperSingleSource::run( *source, *sink, tolerance, feedback );
174  feedback->pushInfo( QObject::tr( "Snapped %n geometries.", nullptr, modified ) );
175  }
176  else
177  {
178  // snapping internally
179  const double step = source->featureCount() > 0 ? 100.0 / ( source->featureCount() * 2 ) : 1;
180  long long processed = 0;
181 
182  QgsInternalGeometrySnapper snapper( tolerance, mode );
183  QgsFeature f;
184  QList<QgsFeatureId> editedFeatureIds;
185  QMap<QgsFeatureId, QgsFeature> editedFeatures;
186  while ( features.nextFeature( f ) )
187  {
188  if ( feedback->isCanceled() )
189  break;
190 
191  QgsFeature editedFeature( f );
192  if ( f.hasGeometry() )
193  {
194  editedFeature.setGeometry( snapper.snapFeature( f ) );
195  }
196  editedFeatureIds << editedFeature.id();
197  editedFeatures.insert( editedFeature.id(), editedFeature );
198  processed += 1;
199  }
200 
201  // reversed order snapping round is required to insure geometries are snapped against all features
202  snapper = QgsInternalGeometrySnapper( tolerance, mode );
203  std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
204  for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
205  {
206  if ( feedback->isCanceled() )
207  break;
208 
209  QgsFeature editedFeature( editedFeatures.value( fid ) );
210  if ( editedFeature.hasGeometry() )
211  {
212  editedFeature.setGeometry( snapper.snapFeature( editedFeature ) );
213  editedFeatures.insert( editedFeature.id(), editedFeature );
214  }
215  }
216  std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
217  processed += 1;
218 
219  if ( !feedback->isCanceled() )
220  {
221  for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
222  {
223  QgsFeature outFeature( editedFeatures.value( fid ) );
224  if ( !sink->addFeature( outFeature ) )
225  throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
226 
227  feedback->setProgress( processed * step );
228  }
229  }
230  }
231 
232  QVariantMap outputs;
233  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
234  return outputs;
235 }
236 
QgsFeedback::setProgress
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:76
qgsgeometrysnappersinglesource.h
QgsProcessingFeedback
Base class for providing feedback from a processing algorithm.
Definition: qgsprocessingfeedback.h:37
QgsGeometrySnapperSingleSource::run
static int run(const QgsFeatureSource &source, QgsFeatureSink &sink, double thresh, QgsFeedback *feedback)
Run the algorithm on given source and output results to the sink, using threshold value in the source...
Definition: qgsgeometrysnappersinglesource.cpp:304
QgsProcessingFeedback::pushInfo
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
Definition: qgsprocessingfeedback.cpp:77
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
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:3733
QgsGeometrySnapper::SnapMode
SnapMode
Snapping modes.
Definition: qgsgeometrysnapper.h:49
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
QgsProcessing::TypeVectorPoint
@ TypeVectorPoint
Vector point layers.
Definition: qgsprocessing.h:49
QgsProcessingParameterFeatureSink
A feature sink output for processing algorithms.
Definition: qgsprocessingparameters.h:3219
QgsProcessingContext
Contains information about the context in which a processing algorithm is executed.
Definition: qgsprocessingcontext.h:46
QgsProcessing::TypeVectorAnyGeometry
@ TypeVectorAnyGeometry
Any vector layer with geometry.
Definition: qgsprocessing.h:48
qgsalgorithmsnapgeometries.h
qgsvectorlayer.h
QgsFeatureIterator::nextFeature
bool nextFeature(QgsFeature &f)
Definition: qgsfeatureiterator.h:399
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
QgsInternalGeometrySnapper
QgsInternalGeometrySnapper allows a set of geometries to be snapped to each other....
Definition: qgsgeometrysnapper.h:136
qgsgeometrysnapper.h
QgsMapLayer
Base class for all map layer types. This is the base class for all map layer types (vector,...
Definition: qgsmaplayer.h:72
QgsFeature
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:55
QgsProcessingParameterEnum
An enum based parameter for processing algorithms, allowing for selection from predefined values.
Definition: qgsprocessingparameters.h:2540
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
QgsGeometrySnapper
QgsGeometrySnapper allows a geometry to be snapped to the geometries within a different reference lay...
Definition: qgsgeometrysnapper.h:42
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