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