QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmbuffer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmbuffer.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
18#include "qgsalgorithmbuffer.h"
19
20#include "qgsmessagelog.h"
21#include "qgsvectorlayer.h"
22
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsBufferAlgorithm::name() const
30{
31 return u"buffer"_s;
32}
33
34QString QgsBufferAlgorithm::displayName() const
35{
36 return QObject::tr( "Buffer" );
37}
38
39QStringList QgsBufferAlgorithm::tags() const
40{
41 return QObject::tr( "buffer,grow,fixed,variable,distance" ).split( ',' );
42}
43
44QString QgsBufferAlgorithm::group() const
45{
46 return QObject::tr( "Vector geometry" );
47}
48
49QString QgsBufferAlgorithm::groupId() const
50{
51 return u"vectorgeometry"_s;
52}
53
54void QgsBufferAlgorithm::initAlgorithm( const QVariantMap & )
55{
56 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ) ) );
57
58 auto bufferParam = std::make_unique<QgsProcessingParameterDistance>( u"DISTANCE"_s, QObject::tr( "Distance" ), 10, u"INPUT"_s );
59 bufferParam->setIsDynamic( true );
60 bufferParam->setDynamicPropertyDefinition( QgsPropertyDefinition( u"Distance"_s, QObject::tr( "Buffer distance" ), QgsPropertyDefinition::Double ) );
61 bufferParam->setDynamicLayerParameterName( u"INPUT"_s );
62 addParameter( bufferParam.release() );
63 auto segmentParam = std::make_unique<QgsProcessingParameterNumber>( u"SEGMENTS"_s, QObject::tr( "Segments" ), Qgis::ProcessingNumberParameterType::Integer, 5, false, 1 );
64 segmentParam->setHelp( QObject::tr( "The segments parameter controls the number of line segments to use to approximate a quarter circle when creating rounded offsets." ) );
65 addParameter( segmentParam.release() );
66 addParameter( new QgsProcessingParameterEnum( u"END_CAP_STYLE"_s, QObject::tr( "End cap style" ), QStringList() << QObject::tr( "Round" ) << QObject::tr( "Flat" ) << QObject::tr( "Square" ), false, 0 ) );
67 addParameter( new QgsProcessingParameterEnum( u"JOIN_STYLE"_s, QObject::tr( "Join style" ), QStringList() << QObject::tr( "Round" ) << QObject::tr( "Miter" ) << QObject::tr( "Bevel" ), false, 0 ) );
68 addParameter( new QgsProcessingParameterNumber( u"MITER_LIMIT"_s, QObject::tr( "Miter limit" ), Qgis::ProcessingNumberParameterType::Double, 2, false, 1 ) );
69
70 addParameter( new QgsProcessingParameterBoolean( u"DISSOLVE"_s, QObject::tr( "Dissolve result" ), false ) );
71
72 auto keepDisjointParam = std::make_unique<QgsProcessingParameterBoolean>( u"SEPARATE_DISJOINT"_s, QObject::tr( "Keep disjoint results separate" ), false );
73 keepDisjointParam->setFlags( keepDisjointParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
74 keepDisjointParam->setHelp( QObject::tr( "If checked, then any disjoint parts in the buffer results will be output as separate single-part features." ) );
75 addParameter( keepDisjointParam.release() );
76
77 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Buffered" ), Qgis::ProcessingSourceType::VectorPolygon, QVariant(), false, true, true ) );
78}
79
80QString QgsBufferAlgorithm::shortHelpString() const
81{
82 return QObject::tr( "This algorithm computes a buffer area for all the features in an input layer, using a fixed or dynamic distance.\n\n"
83 "The segments parameter controls the number of line segments to use to approximate a quarter circle when creating rounded offsets.\n\n"
84 "The end cap style parameter controls how line endings are handled in the buffer.\n\n"
85 "The join style parameter specifies whether round, miter or beveled joins should be used when offsetting corners in a line.\n\n"
86 "The miter limit parameter is only applicable for miter join styles, and controls the maximum distance from the offset curve to use when creating a mitered join." );
87}
88
89QString QgsBufferAlgorithm::shortDescription() const
90{
91 return QObject::tr( "Computes a buffer area for all the features in an input layer, using a fixed or dynamic distance." );
92}
93
94Qgis::ProcessingAlgorithmDocumentationFlags QgsBufferAlgorithm::documentationFlags() const
95{
97}
98
99QgsBufferAlgorithm *QgsBufferAlgorithm::createInstance() const
100{
101 return new QgsBufferAlgorithm();
102}
103
104QVariantMap QgsBufferAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
105{
106 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
107 if ( !source )
108 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
109
110 // fixed parameters
111 const bool dissolve = parameterAsBoolean( parameters, u"DISSOLVE"_s, context );
112 const bool keepDisjointSeparate = parameterAsBoolean( parameters, u"SEPARATE_DISJOINT"_s, context );
113 const int segments = parameterAsInt( parameters, u"SEGMENTS"_s, context );
114 const Qgis::EndCapStyle endCapStyle = static_cast<Qgis::EndCapStyle>( 1 + parameterAsInt( parameters, u"END_CAP_STYLE"_s, context ) );
115 const Qgis::JoinStyle joinStyle = static_cast<Qgis::JoinStyle>( 1 + parameterAsInt( parameters, u"JOIN_STYLE"_s, context ) );
116 const double miterLimit = parameterAsDouble( parameters, u"MITER_LIMIT"_s, context );
117 const double bufferDistance = parameterAsDouble( parameters, u"DISTANCE"_s, context );
118 const bool dynamicBuffer = QgsProcessingParameters::isDynamic( parameters, u"DISTANCE"_s );
119
120 QString dest;
121 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, source->fields(), Qgis::WkbType::MultiPolygon, source->sourceCrs(), keepDisjointSeparate ? QgsFeatureSink::RegeneratePrimaryKey : QgsFeatureSink::SinkFlags() ) );
122 if ( !sink )
123 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
124
125 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, source.get() );
126 QgsProperty bufferProperty;
127 if ( dynamicBuffer )
128 {
129 bufferProperty = parameters.value( u"DISTANCE"_s ).value<QgsProperty>();
130 }
131
132 const long count = source->featureCount();
133
134 QgsFeature f;
135 // buffer doesn't care about invalid features, and buffering can be used to repair geometries
137
138 const double step = count > 0 ? 100.0 / count : 1;
139 int current = 0;
140
141 QVector<QgsGeometry> bufferedGeometriesForDissolve;
142 QgsAttributes dissolveAttrs;
143
144 while ( it.nextFeature( f ) )
145 {
146 if ( feedback->isCanceled() )
147 {
148 break;
149 }
150 if ( dissolveAttrs.isEmpty() )
151 dissolveAttrs = f.attributes();
152
153 QgsFeature out = f;
154 if ( out.hasGeometry() )
155 {
156 double distance = bufferDistance;
157 if ( dynamicBuffer )
158 {
159 expressionContext.setFeature( f );
160 distance = bufferProperty.valueAsDouble( expressionContext, bufferDistance );
161 }
162
163 QgsGeometry outputGeometry = f.geometry().buffer( distance, segments, endCapStyle, joinStyle, miterLimit );
164 if ( outputGeometry.isNull() )
165 {
166 QgsMessageLog::logMessage( QObject::tr( "Error calculating buffer for feature %1" ).arg( f.id() ), QObject::tr( "Processing" ), Qgis::MessageLevel::Warning );
167 }
168 if ( dissolve )
169 {
170 bufferedGeometriesForDissolve << outputGeometry;
171 }
172 else
173 {
174 outputGeometry.convertToMultiType();
175
176 if ( !keepDisjointSeparate )
177 {
178 out.setGeometry( outputGeometry );
179
180 if ( !sink->addFeature( out, QgsFeatureSink::FastInsert ) )
181 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
182 }
183 else
184 {
185 for ( auto partIt = outputGeometry.const_parts_begin(); partIt != outputGeometry.const_parts_end(); ++partIt )
186 {
187 if ( const QgsAbstractGeometry *part = *partIt )
188 {
189 out.setGeometry( QgsGeometry( part->clone() ) );
190 if ( !sink->addFeature( out, QgsFeatureSink::FastInsert ) )
191 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
192 }
193 }
194 }
195 }
196 }
197 else if ( !dissolve )
198 {
199 if ( !sink->addFeature( out, QgsFeatureSink::FastInsert ) )
200 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
201 }
202
203 feedback->setProgress( current * step );
204 current++;
205 }
206
207 if ( dissolve && !bufferedGeometriesForDissolve.isEmpty() )
208 {
209 QgsGeometry finalGeometry = QgsGeometry::unaryUnion( bufferedGeometriesForDissolve );
210 finalGeometry.convertToMultiType();
211 QgsFeature f;
212 f.setAttributes( dissolveAttrs );
213
214 if ( !keepDisjointSeparate )
215 {
216 f.setGeometry( finalGeometry );
217 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
218 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
219 }
220 else
221 {
222 for ( auto partIt = finalGeometry.const_parts_begin(); partIt != finalGeometry.const_parts_end(); ++partIt )
223 {
224 if ( const QgsAbstractGeometry *part = *partIt )
225 {
226 f.setGeometry( QgsGeometry( part->clone() ) );
227 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
228 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
229 }
230 }
231 }
232 }
233
234 sink->finalize();
235
236 QVariantMap outputs;
237 outputs.insert( u"OUTPUT"_s, dest );
238 return outputs;
239}
240
241Qgis::ProcessingAlgorithmFlags QgsBufferAlgorithm::flags() const
242{
245 return f;
246}
247
248QgsProcessingAlgorithm::VectorProperties QgsBufferAlgorithm::sinkProperties( const QString &sink, const QVariantMap &parameters, QgsProcessingContext &context, const QMap<QString, QgsProcessingAlgorithm::VectorProperties> &sourceProperties ) const
249{
250 const bool keepDisjointSeparate = parameterAsBoolean( parameters, u"SEPARATE_DISJOINT"_s, context );
251
253 if ( sink == "OUTPUT"_L1 )
254 {
255 if ( sourceProperties.value( u"INPUT"_s ).availability == Qgis::ProcessingPropertyAvailability::Available )
256 {
257 const VectorProperties inputProps = sourceProperties.value( u"INPUT"_s );
258 result.fields = inputProps.fields;
259 result.crs = inputProps.crs;
260 result.wkbType = keepDisjointSeparate ? Qgis::WkbType::Polygon : Qgis::WkbType::MultiPolygon;
262 return result;
263 }
264 else
265 {
266 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
267 if ( source )
268 {
269 result.fields = source->fields();
270 result.crs = source->sourceCrs();
271 result.wkbType = keepDisjointSeparate ? Qgis::WkbType::Polygon : Qgis::WkbType::MultiPolygon;
273 return result;
274 }
275 }
276 }
277 return result;
278}
279
280bool QgsBufferAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
281{
282 const QgsVectorLayer *vlayer = qobject_cast<const QgsVectorLayer *>( layer );
283 if ( !vlayer )
284 return false;
285 //Only Polygons
286 return vlayer->wkbType() == Qgis::WkbType::Polygon || vlayer->wkbType() == Qgis::WkbType::MultiPolygon;
287}
288
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3607
@ Warning
Warning message.
Definition qgis.h:161
@ Available
Properties are available.
Definition qgis.h:3715
JoinStyle
Join styles for buffers.
Definition qgis.h:2179
@ RegeneratesPrimaryKeyInSomeScenarios
Algorithm may drop the existing primary keys or FID values in some scenarios, depending on algorithm ...
Definition qgis.h:3691
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3680
EndCapStyle
End cap styles for buffers.
Definition qgis.h:2166
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3701
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3782
@ Polygon
Polygon.
Definition qgis.h:284
@ MultiPolygon
MultiPolygon.
Definition qgis.h:288
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3661
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
@ Double
Double/float values.
Definition qgis.h:3875
Abstract base class for all geometries.
A vector of attributes.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
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.
Wraps a request for features to a vector layer (or directly its vector data provider).
QFlags< SinkFlag > SinkFlags
@ 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:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsFeatureId id
Definition qgsfeature.h:68
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
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.
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
QgsGeometry buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
Base class for all map layer types.
Definition qgsmaplayer.h:83
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
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.
A boolean parameter for processing algorithms.
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.
A numeric parameter for processing algorithms.
static bool isDynamic(const QVariantMap &parameters, const QString &name)
Returns true if the parameter with matching name is a dynamic parameter, and must be evaluated once f...
Definition for a property.
Definition qgsproperty.h:47
@ Double
Double value (including negative values).
Definition qgsproperty.h:57
A store for object properties.
QVariant value(const QgsExpressionContext &context, const QVariant &defaultValue=QVariant(), bool *ok=nullptr) const
Calculates the current value of the property, including any transforms which are set for the property...
double valueAsDouble(const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property and interprets it as a double.
Represents a vector layer which manages a vector based dataset.
Q_INVOKABLE Qgis::WkbType wkbType() const final
Returns the WKBType or WKBUnknown in case of error.
Properties of a vector source or sink used in an algorithm.
Qgis::WkbType wkbType
Geometry (WKB) type.
QgsCoordinateReferenceSystem crs
Coordinate Reference System.
Qgis::ProcessingPropertyAvailability availability
Availability of the properties. By default properties are not available.