QGIS API Documentation 3.43.0-Master (56aa1fd18d7)
qgsalgorithmangletonearest.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmangletonearest.cpp
3 ---------------------
4 begin : July 2020
5 copyright : (C) 2020 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 "qgsspatialindex.h"
20#include "qgslinestring.h"
21#include "qgsvectorlayer.h"
22#include "qgsrenderer.h"
24#include "qgsmarkersymbol.h"
25
27
28class SetMarkerRotationVisitor : public QgsStyleEntityVisitorInterface
29{
30 public:
31 SetMarkerRotationVisitor( const QString &rotationField )
32 : mRotationField( rotationField )
33 {}
34
35 bool visit( const QgsStyleEntityVisitorInterface::StyleLeaf &entity ) override
36 {
37 if ( const QgsStyleSymbolEntity *symbolEntity = dynamic_cast<const QgsStyleSymbolEntity *>( entity.entity ) )
38 {
39 if ( QgsMarkerSymbol *marker = dynamic_cast<QgsMarkerSymbol *>( symbolEntity->symbol() ) )
40 {
41 marker->setDataDefinedAngle( QgsProperty::fromField( mRotationField ) );
42 }
43 }
44 return true;
45 }
46
47 private:
48 QString mRotationField;
49};
50
51class SetMarkerRotationPostProcessor : public QgsProcessingLayerPostProcessorInterface
52{
53 public:
54 SetMarkerRotationPostProcessor( std::unique_ptr<QgsFeatureRenderer> renderer, const QString &rotationField )
55 : mRenderer( std::move( renderer ) )
56 , mRotationField( rotationField )
57 {}
58
60 {
61 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
62 {
63 SetMarkerRotationVisitor visitor( mRotationField );
64 mRenderer->accept( &visitor );
65 vl->setRenderer( mRenderer.release() );
66 vl->triggerRepaint();
67 }
68 }
69
70 private:
71 std::unique_ptr<QgsFeatureRenderer> mRenderer;
72 QString mRotationField;
73};
74
75QString QgsAngleToNearestAlgorithm::name() const
76{
77 return QStringLiteral( "angletonearest" );
78}
79
80QString QgsAngleToNearestAlgorithm::displayName() const
81{
82 return QObject::tr( "Align points to features" );
83}
84
85QStringList QgsAngleToNearestAlgorithm::tags() const
86{
87 return QObject::tr( "align,marker,stroke,fill,orient,points,lines,angles,rotation,rotate" ).split( ',' );
88}
89
90QString QgsAngleToNearestAlgorithm::group() const
91{
92 return QObject::tr( "Cartography" );
93}
94
95QString QgsAngleToNearestAlgorithm::groupId() const
96{
97 return QStringLiteral( "cartography" );
98}
99
100QgsAngleToNearestAlgorithm::~QgsAngleToNearestAlgorithm() = default;
101
102void QgsAngleToNearestAlgorithm::initAlgorithm( const QVariantMap &configuration )
103{
104 mIsInPlace = configuration.value( QStringLiteral( "IN_PLACE" ) ).toBool();
105
106 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
107 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "REFERENCE_LAYER" ), QObject::tr( "Reference layer" ) ) );
108
109 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "MAX_DISTANCE" ), QObject::tr( "Maximum distance to consider" ), QVariant(), QStringLiteral( "INPUT" ), true, 0 ) );
110
111 if ( !mIsInPlace )
112 addParameter( new QgsProcessingParameterString( QStringLiteral( "FIELD_NAME" ), QObject::tr( "Angle field name" ), QStringLiteral( "rotation" ) ) );
113 else
114 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD_NAME" ), QObject::tr( "Angle field name" ), QStringLiteral( "rotation" ), QStringLiteral( "INPUT" ) ) );
115
116 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "APPLY_SYMBOLOGY" ), QObject::tr( "Automatically apply symbology" ), true ) );
117
118 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Aligned layer" ), Qgis::ProcessingSourceType::VectorPoint ) );
119}
120
121Qgis::ProcessingAlgorithmFlags QgsAngleToNearestAlgorithm::flags() const
122{
125 return f;
126}
127
128QString QgsAngleToNearestAlgorithm::shortHelpString() const
129{
130 return QObject::tr( "This algorithm calculates the rotation required to align point features with their nearest "
131 "feature from another reference layer. A new field is added to the output layer which is filled with the angle "
132 "(in degrees, clockwise) to the nearest reference feature.\n\n"
133 "Optionally, the output layer's symbology can be set to automatically use the calculated rotation "
134 "field to rotate marker symbols.\n\n"
135 "If desired, a maximum distance to use when aligning points can be set, to avoid aligning isolated points "
136 "to distant features." );
137}
138
139QString QgsAngleToNearestAlgorithm::shortDescription() const
140{
141 return QObject::tr( "Rotates point features to align them to nearby features." );
142}
143
144QgsAngleToNearestAlgorithm *QgsAngleToNearestAlgorithm::createInstance() const
145{
146 return new QgsAngleToNearestAlgorithm();
147}
148
149bool QgsAngleToNearestAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
150{
151 if ( const QgsVectorLayer *vl = qobject_cast<const QgsVectorLayer *>( layer ) )
152 {
153 return vl->geometryType() == Qgis::GeometryType::Point;
154 }
155 return false;
156}
157
158bool QgsAngleToNearestAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
159{
160 if ( !mIsInPlace )
161 {
162 if ( QgsVectorLayer *sourceLayer = parameterAsVectorLayer( parameters, QStringLiteral( "INPUT" ), context ) )
163 {
164 mSourceRenderer.reset( sourceLayer->renderer()->clone() );
165 }
166 }
167
168 return true;
169}
170
171QVariantMap QgsAngleToNearestAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
172{
173 const double maxDistance = parameters.value( QStringLiteral( "MAX_DISTANCE" ) ).isValid() ? parameterAsDouble( parameters, QStringLiteral( "MAX_DISTANCE" ), context ) : std::numeric_limits<double>::quiet_NaN();
174 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
175 if ( !input )
176 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
177
178 std::unique_ptr<QgsProcessingFeatureSource> referenceSource( parameterAsSource( parameters, QStringLiteral( "REFERENCE_LAYER" ), context ) );
179 if ( !referenceSource )
180 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "REFERENCE_LAYER" ) ) );
181
182 const QString fieldName = parameterAsString( parameters, QStringLiteral( "FIELD_NAME" ), context );
183
184 QgsFields outFields = input->fields();
185 int fieldIndex = -1;
186 if ( mIsInPlace )
187 {
188 fieldIndex = outFields.lookupField( fieldName );
189 }
190 else
191 {
192 if ( outFields.lookupField( fieldName ) >= 0 )
193 {
194 throw QgsProcessingException( QObject::tr( "A field with the same name (%1) already exists" ).arg( fieldName ) );
195 }
196 outFields.append( QgsField( fieldName, QMetaType::Type::Double ) );
197 }
198
199 QString dest;
200 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, input->wkbType(), input->sourceCrs() ) );
201 if ( parameters.value( QStringLiteral( "OUTPUT" ) ).isValid() && !sink )
202 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
203
204 // make spatial index
205 const QgsFeatureIterator f2 = referenceSource->getFeatures( QgsFeatureRequest().setDestinationCrs( input->sourceCrs(), context.transformContext() ).setNoAttributes() );
206 double step = referenceSource->featureCount() > 0 ? 50.0 / referenceSource->featureCount() : 1;
207 int i = 0;
208 const QgsSpatialIndex index( f2, [&]( const QgsFeature & ) -> bool {
209 i++;
210 if ( feedback->isCanceled() )
211 return false;
212
213 feedback->setProgress( i * step );
214
216
217 QgsFeature f;
218
219 // Create output vector layer with additional attributes
220 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
221 QgsFeatureIterator features = input->getFeatures();
222 i = 0;
223 while ( features.nextFeature( f ) )
224 {
225 i++;
226 if ( feedback->isCanceled() )
227 {
228 break;
229 }
230
231 feedback->setProgress( 50 + i * step );
232
233 QgsAttributes attributes = f.attributes();
234
235 if ( !f.hasGeometry() )
236 {
237 if ( !mIsInPlace )
238 attributes.append( QVariant() );
239 else
240 attributes[fieldIndex] = QVariant();
241 f.setAttributes( attributes );
242 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
243 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
244 }
245 else
246 {
247 const QList<QgsFeatureId> nearest = index.nearestNeighbor( f.geometry(), 1, std::isnan( maxDistance ) ? 0 : maxDistance );
248 if ( nearest.empty() )
249 {
250 feedback->pushInfo( QObject::tr( "No matching features found within search distance" ) );
251 if ( !mIsInPlace )
252 attributes.append( QVariant() );
253 else
254 attributes[fieldIndex] = QVariant();
255 f.setAttributes( attributes );
256 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
257 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
258 }
259 else
260 {
261 if ( nearest.count() > 1 )
262 {
263 feedback->pushInfo( QObject::tr( "Multiple matching features found at same distance from search feature, found %n feature(s)", nullptr, nearest.count() ) );
264 }
265
266 const QgsGeometry joinLine = f.geometry().shortestLine( index.geometry( nearest.at( 0 ) ) );
267 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( joinLine.constGet() ) )
268 {
269 if ( !mIsInPlace )
270 attributes.append( line->startPoint().azimuth( line->endPoint() ) );
271 else
272 attributes[fieldIndex] = line->startPoint().azimuth( line->endPoint() );
273 }
274 else
275 {
276 if ( !mIsInPlace )
277 attributes.append( QVariant() );
278 else
279 attributes[fieldIndex] = QVariant();
280 }
281 f.setAttributes( attributes );
282 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
283 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
284 }
285 }
286 }
287
288 if ( sink )
289 sink->finalize();
290
291 const bool applySymbology = parameterAsBool( parameters, QStringLiteral( "APPLY_SYMBOLOGY" ), context );
292 if ( applySymbology )
293 {
294 if ( mIsInPlace )
295 {
296 // get in place vector layer
297 // (possibly TODO - make this a reusable method!)
298 QVariantMap inPlaceParams = parameters;
299 inPlaceParams.insert( QStringLiteral( "INPUT" ), parameters.value( QStringLiteral( "INPUT" ) ).value<QgsProcessingFeatureSourceDefinition>().source );
300 if ( QgsVectorLayer *sourceLayer = parameterAsVectorLayer( inPlaceParams, QStringLiteral( "INPUT" ), context ) )
301 {
302 std::unique_ptr<QgsFeatureRenderer> sourceRenderer( sourceLayer->renderer()->clone() );
303 SetMarkerRotationPostProcessor processor( std::move( sourceRenderer ), fieldName );
304 processor.postProcessLayer( sourceLayer, context, feedback );
305 }
306 }
307 else if ( mSourceRenderer && context.willLoadLayerOnCompletion( dest ) )
308 {
309 context.layerToLoadOnCompletionDetails( dest ).setPostProcessor( new SetMarkerRotationPostProcessor( std::move( mSourceRenderer ), fieldName ) );
310 }
311 }
312
313 QVariantMap outputs;
314 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
315 return outputs;
316}
317
318
@ VectorPoint
Vector point layers.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3476
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
A vector of attributes.
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).
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
@ 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
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
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:70
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometry shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
Line string geometry type, with support for z-dimension and m-values.
Base class for all map layer types.
Definition qgsmaplayer.h:77
A marker symbol type, for rendering Point and MultiPoint geometries.
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
void setPostProcessor(QgsProcessingLayerPostProcessorInterface *processor)
Sets the layer post-processor.
Contains information about the context in which a processing algorithm is executed.
QgsProcessingContext::LayerDetails & layerToLoadOnCompletionDetails(const QString &layer)
Returns a reference to the details for a given layer which is loaded on completion of the algorithm o...
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
bool willLoadLayerOnCompletion(const QString &layer) const
Returns true if the given layer (by ID or datasource) will be loaded into the current project upon co...
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 interface for layer post-processing handlers for execution following a processing algorithm operat...
virtual void postProcessLayer(QgsMapLayer *layer, QgsProcessingContext &context, QgsProcessingFeedback *feedback)=0
Post-processes the specified layer, following successful execution of a processing algorithm.
A boolean parameter for processing algorithms.
A double numeric parameter for distance values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A string parameter for processing algorithms.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
An interface for classes which can visit style entity (e.g.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
A symbol entity for QgsStyle databases.
Definition qgsstyle.h:1397
Represents a vector layer which manages a vector based dataset.
Contains information relating to the style entity currently being visited.
const QgsStyleEntityInterface * entity
Reference to style entity being visited.