QGIS API Documentation 3.41.0-Master (57ec4277f5e)
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
25
26QString QgsSnapGeometriesAlgorithm::name() const
27{
28 return QStringLiteral( "snapgeometries" );
29}
30
31QString QgsSnapGeometriesAlgorithm::displayName() const
32{
33 return QObject::tr( "Snap geometries to layer" );
34}
35
36QString 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
51QStringList QgsSnapGeometriesAlgorithm::tags() const
52{
53 return QObject::tr( "geometry,snap,tolerance" ).split( ',' );
54}
55
56QString QgsSnapGeometriesAlgorithm::group() const
57{
58 return QObject::tr( "Vector geometry" );
59}
60
61QString QgsSnapGeometriesAlgorithm::groupId() const
62{
63 return QStringLiteral( "vectorgeometry" );
64}
65
66Qgis::ProcessingAlgorithmFlags QgsSnapGeometriesAlgorithm::flags() const
67{
70 return f;
71}
72
73bool 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
82void QgsSnapGeometriesAlgorithm::initAlgorithm( const QVariantMap & )
83{
84 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
85 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "REFERENCE_LAYER" ), QObject::tr( "Reference layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
86
87 std::unique_ptr<QgsProcessingParameterDistance> tolParam = std::make_unique<QgsProcessingParameterDistance>( QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), 10.0, QStringLiteral( "INPUT" ), false, 0.00000001 );
88 tolParam->setMetadata(
89 { QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "decimals" ), 8 } } ) } } )
90 }
91 );
92 addParameter( tolParam.release() );
93
94 const QStringList options = QStringList()
95 << QObject::tr( "Prefer aligning nodes, insert extra vertices where required" )
96 << QObject::tr( "Prefer closest point, insert extra vertices where required" )
97 << QObject::tr( "Prefer aligning nodes, don't insert new vertices" )
98 << QObject::tr( "Prefer closest point, don't insert new vertices" )
99 << QObject::tr( "Move end points only, prefer aligning nodes" )
100 << QObject::tr( "Move end points only, prefer closest point" )
101 << QObject::tr( "Snap end points to end points only" )
102 << QObject::tr( "Snap to anchor nodes (single layer only)" );
103 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "BEHAVIOR" ), QObject::tr( "Behavior" ), options, false, QVariantList() << 0 ) );
104 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Snapped geometry" ), Qgis::ProcessingSourceType::VectorAnyGeometry ) );
105}
106
107QgsSnapGeometriesAlgorithm *QgsSnapGeometriesAlgorithm::createInstance() const
108{
109 return new QgsSnapGeometriesAlgorithm();
110}
111
112QVariantMap QgsSnapGeometriesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
113{
114 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
115 if ( !source )
116 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
117
118 const std::unique_ptr<QgsProcessingFeatureSource> referenceSource( parameterAsSource( parameters, QStringLiteral( "REFERENCE_LAYER" ), context ) );
119 if ( !referenceSource )
120 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "REFERENCE_LAYER" ) ) );
121
122 const double tolerance = parameterAsDouble( parameters, QStringLiteral( "TOLERANCE" ), context );
123 const QgsGeometrySnapper::SnapMode mode = static_cast<QgsGeometrySnapper::SnapMode>( parameterAsEnum( parameters, QStringLiteral( "BEHAVIOR" ), context ) );
124
125 QString dest;
126 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(), source->wkbType(), source->sourceCrs() ) );
127 if ( !sink )
128 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
129
130 QgsFeatureIterator features = source->getFeatures();
131
132 if ( parameters.value( QStringLiteral( "INPUT" ) ) != parameters.value( QStringLiteral( "REFERENCE_LAYER" ) ) )
133 {
134 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
135 if ( mode == 7 )
136 throw QgsProcessingException( QObject::tr( "This mode applies when the input and reference layer are the same." ) );
137
138 const QgsGeometrySnapper snapper( referenceSource.get() );
139 long long processed = 0;
140 QgsFeature f;
141 while ( features.nextFeature( f ) )
142 {
143 if ( feedback->isCanceled() )
144 break;
145
146 if ( f.hasGeometry() )
147 {
148 QgsFeature outFeature( f );
149 outFeature.setGeometry( snapper.snapGeometry( f.geometry(), tolerance, mode ) );
150 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
151 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
152 }
153 else
154 {
155 if ( !sink->addFeature( f ) )
156 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
157 }
158 processed += 1;
159 feedback->setProgress( processed * step );
160 }
161 }
162 else if ( mode == 7 )
163 {
164 // input layer == reference layer
165 const int modified = QgsGeometrySnapperSingleSource::run( *source, *sink, tolerance, feedback );
166 feedback->pushInfo( QObject::tr( "Snapped %n geometries.", nullptr, modified ) );
167 }
168 else
169 {
170 // snapping internally
171 const double step = source->featureCount() > 0 ? 100.0 / ( source->featureCount() * 2 ) : 1;
172 long long processed = 0;
173
174 QgsInternalGeometrySnapper snapper( tolerance, mode );
175 QgsFeature f;
176 QList<QgsFeatureId> editedFeatureIds;
177 QMap<QgsFeatureId, QgsFeature> editedFeatures;
178 while ( features.nextFeature( f ) )
179 {
180 if ( feedback->isCanceled() )
181 break;
182
183 QgsFeature editedFeature( f );
184 if ( f.hasGeometry() )
185 {
186 editedFeature.setGeometry( snapper.snapFeature( f ) );
187 }
188 editedFeatureIds << editedFeature.id();
189 editedFeatures.insert( editedFeature.id(), editedFeature );
190 processed += 1;
191 }
192
193 // reversed order snapping round is required to insure geometries are snapped against all features
194 snapper = QgsInternalGeometrySnapper( tolerance, mode );
195 std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
196 for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
197 {
198 if ( feedback->isCanceled() )
199 break;
200
201 QgsFeature editedFeature( editedFeatures.value( fid ) );
202 if ( editedFeature.hasGeometry() )
203 {
204 editedFeature.setGeometry( snapper.snapFeature( editedFeature ) );
205 editedFeatures.insert( editedFeature.id(), editedFeature );
206 }
207 }
208 std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
209 processed += 1;
210
211 if ( !feedback->isCanceled() )
212 {
213 for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
214 {
215 QgsFeature outFeature( editedFeatures.value( fid ) );
216 if ( !sink->addFeature( outFeature ) )
217 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
218
219 feedback->setProgress( processed * step );
220 }
221 }
222 }
223
224 sink->finalize();
225
226 QVariantMap outputs;
227 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
228 return outputs;
229}
230
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ VectorLine
Vector line layers.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3410
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
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:58
QgsGeometry geometry
Definition qgsfeature.h:69
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:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
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...
QgsGeometrySnapper allows a geometry to be snapped to the geometries within a different reference lay...
SnapMode
Snapping modes.
QgsInternalGeometrySnapper allows a set of geometries to be snapped to each other.
Base class for all map layer types.
Definition qgsmaplayer.h:76
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.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
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 data sets.
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