QGIS API Documentation 4.3.0-Master (45633be667c)
Loading...
Searching...
No Matches
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
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsSnapGeometriesAlgorithm::name() const
31{
32 return u"snapgeometries"_s;
33}
34
35QString QgsSnapGeometriesAlgorithm::displayName() const
36{
37 return QObject::tr( "Snap geometries to layer" );
38}
39
40QString QgsSnapGeometriesAlgorithm::shortHelpString() const
41{
42 return QObject::tr(
43 "This algorithm snaps the geometries in a layer. Snapping can be done either to the geometries "
44 "from another layer, or to geometries within the same layer."
45 )
46 + u"\n\n"_s
47 + QObject::tr(
48 "A tolerance is specified in layer units to control how close vertices need "
49 "to be to the reference layer geometries before they are snapped."
50 )
51 + u"\n\n"_s
52 + QObject::tr(
53 "Snapping occurs to both nodes and edges. Depending on the snapping behavior, "
54 "either nodes or edges will be preferred."
55 )
56 + u"\n\n"_s
57 + QObject::tr(
58 "Vertices will be inserted or removed as required to make the geometries match "
59 "the reference geometries."
60 );
61}
62
63QString QgsSnapGeometriesAlgorithm::shortDescription() const
64{
65 return QObject::tr( "Snaps the geometries to the geometries within the same layer or from another layer." );
66}
67
68QStringList QgsSnapGeometriesAlgorithm::tags() const
69{
70 return QObject::tr( "geometry,snap,tolerance" ).split( ',' );
71}
72
73QString QgsSnapGeometriesAlgorithm::group() const
74{
75 return QObject::tr( "Vector geometry" );
76}
77
78QString QgsSnapGeometriesAlgorithm::groupId() const
79{
80 return u"vectorgeometry"_s;
81}
82
83Qgis::ProcessingAlgorithmFlags QgsSnapGeometriesAlgorithm::flags() const
84{
87 return f;
88}
89
90bool QgsSnapGeometriesAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
91{
92 const QgsVectorLayer *layer = qobject_cast<const QgsVectorLayer *>( l );
93 if ( !layer )
94 return false;
95
96 return layer->isSpatial();
97}
98
99void QgsSnapGeometriesAlgorithm::initAlgorithm( const QVariantMap & )
100{
101 addParameter( new QgsProcessingParameterFeatureSource(
102 u"INPUT"_s,
103 QObject::tr( "Input layer" ),
104 QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
105 ) );
106 addParameter( new QgsProcessingParameterFeatureSource(
107 u"REFERENCE_LAYER"_s,
108 QObject::tr( "Reference layer" ),
109 QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
110 ) );
111
112 auto tolParam = std::make_unique<QgsProcessingParameterDistance>( u"TOLERANCE"_s, QObject::tr( "Tolerance" ), 10.0, u"INPUT"_s, false, 0.00000001 );
113 tolParam->setMetadata( { QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"decimals"_s, 8 } } ) } } ) } );
114 addParameter( tolParam.release() );
115
116 const QStringList options = QStringList()
117 << QObject::tr( "Prefer aligning nodes, insert extra vertices where required" )
118 << QObject::tr( "Prefer closest point, insert extra vertices where required" )
119 << QObject::tr( "Prefer aligning nodes, don't insert new vertices" )
120 << QObject::tr( "Prefer closest point, don't insert new vertices" )
121 << QObject::tr( "Move end points only, prefer aligning nodes" )
122 << QObject::tr( "Move end points only, prefer closest point" )
123 << QObject::tr( "Snap end points to end points only" )
124 << QObject::tr( "Snap to anchor nodes (single layer only)" );
125 addParameter( new QgsProcessingParameterEnum( u"BEHAVIOR"_s, QObject::tr( "Behavior" ), options, false, QVariantList() << 0 ) );
126 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Snapped geometry" ), Qgis::ProcessingSourceType::VectorAnyGeometry ) );
127}
128
129QgsSnapGeometriesAlgorithm *QgsSnapGeometriesAlgorithm::createInstance() const
130{
131 return new QgsSnapGeometriesAlgorithm();
132}
133
134QVariantMap QgsSnapGeometriesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
135{
136 QGS_MARK_ALGORITHM_SOURCE
137
138 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
139 if ( !source )
140 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
141
142 const std::unique_ptr<QgsProcessingFeatureSource> referenceSource( parameterAsSource( parameters, u"REFERENCE_LAYER"_s, context ) );
143 if ( !referenceSource )
144 throw QgsProcessingException( invalidSourceError( parameters, u"REFERENCE_LAYER"_s ) );
145
146 const double tolerance = parameterAsDouble( parameters, u"TOLERANCE"_s, context );
147 const QgsGeometrySnapper::SnapMode mode = static_cast<QgsGeometrySnapper::SnapMode>( parameterAsEnum( parameters, u"BEHAVIOR"_s, context ) );
148
149 QString dest;
150 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, source->fields(), source->wkbType(), source->sourceCrs() ) );
151 if ( !sink )
152 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
153
154 QgsFeatureIterator features = source->getFeatures();
155
156 if ( parameters.value( u"INPUT"_s ) != parameters.value( u"REFERENCE_LAYER"_s ) )
157 {
158 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
159 if ( mode == 7 )
160 throw QgsProcessingException( QObject::tr( "This mode applies when the input and reference layer are the same." ) );
161
162 const QgsGeometrySnapper snapper( referenceSource.get() );
163 long long processed = 0;
164 QgsFeature f;
165 while ( features.nextFeature( f ) )
166 {
167 if ( feedback->isCanceled() )
168 break;
169
170 if ( f.hasGeometry() )
171 {
172 QgsFeature outFeature( f );
173 outFeature.setGeometry( snapper.snapGeometry( f.geometry(), tolerance, mode ) );
174 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
175 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
176 else
177 feedback->featureAddedToSink( u"OUTPUT"_s );
178 }
179 else
180 {
181 if ( !sink->addFeature( f ) )
182 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
183 else
184 feedback->featureAddedToSink( u"OUTPUT"_s );
185 }
186 processed += 1;
187 feedback->setProgress( processed * step );
188 }
189 }
190 else if ( mode == 7 )
191 {
192 // input layer == reference layer
193 const int modified = QgsGeometrySnapperSingleSource::run( *source, *sink, tolerance, feedback );
194 feedback->pushInfo( QObject::tr( "Snapped %n geometries.", nullptr, modified ) );
195 }
196 else
197 {
198 // snapping internally
199 const double step = source->featureCount() > 0 ? 100.0 / ( source->featureCount() * 2 ) : 1;
200 long long processed = 0;
201
202 QgsInternalGeometrySnapper snapper( tolerance, mode );
203 QgsFeature f;
204 QList<QgsFeatureId> editedFeatureIds;
205 QMap<QgsFeatureId, QgsFeature> editedFeatures;
206 while ( features.nextFeature( f ) )
207 {
208 if ( feedback->isCanceled() )
209 break;
210
211 QgsFeature editedFeature( f );
212 if ( f.hasGeometry() )
213 {
214 editedFeature.setGeometry( snapper.snapFeature( f ) );
215 }
216 editedFeatureIds << editedFeature.id();
217 editedFeatures.insert( editedFeature.id(), editedFeature );
218 processed += 1;
219 }
220
221 // reversed order snapping round is required to insure geometries are snapped against all features
222 snapper = QgsInternalGeometrySnapper( tolerance, mode );
223 std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
224 for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
225 {
226 if ( feedback->isCanceled() )
227 break;
228
229 QgsFeature editedFeature( editedFeatures.value( fid ) );
230 if ( editedFeature.hasGeometry() )
231 {
232 editedFeature.setGeometry( snapper.snapFeature( editedFeature ) );
233 editedFeatures.insert( editedFeature.id(), editedFeature );
234 }
235 }
236 std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
237 processed += 1;
238
239 if ( !feedback->isCanceled() )
240 {
241 for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
242 {
243 QgsFeature outFeature( editedFeatures.value( fid ) );
244 if ( !sink->addFeature( outFeature ) )
245 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
246 else
247 feedback->featureAddedToSink( u"OUTPUT"_s );
248
249 feedback->setProgress( processed * step );
250 }
251 }
252 }
253
254 sink->finalize();
255 feedback->featureSinkFinalized( u"OUTPUT"_s );
256
257 QVariantMap outputs;
258 outputs.insert( u"OUTPUT"_s, dest );
259 return outputs;
260}
261
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3751
@ VectorPoint
Vector point layers.
Definition qgis.h:3752
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3754
@ VectorLine
Vector line layers.
Definition qgis.h:3753
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3828
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3809
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.
@ 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
QgsGeometry geometry
Definition qgsfeature.h:66
bool hasGeometry() const
Returns true if the feature has an associated 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
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...
Allows a geometry to be snapped to the geometries within a different reference layer.
SnapMode
Snapping modes.
Allows a set of geometries to be snapped to each other.
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.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
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...
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features