QGIS API Documentation 3.43.0-Master (261ee7da134)
qgsalgorithmtransect.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmtransect.cpp
3 -------------------------
4 begin : October 2017
5 copyright : (C) 2017 by Loïc Bartoletti
6 email : lbartoletti at tuxfamily dot org
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 "qgsmultilinestring.h"
20#include "qgslinestring.h"
21
23
24QString QgsTransectAlgorithm::name() const
25{
26 return QStringLiteral( "transect" );
27}
28
29QString QgsTransectAlgorithm::displayName() const
30{
31 return QObject::tr( "Transect" );
32}
33
34QStringList QgsTransectAlgorithm::tags() const
35{
36 return QObject::tr( "transect,station,lines,extend," ).split( ',' );
37}
38
39QString QgsTransectAlgorithm::group() const
40{
41 return QObject::tr( "Vector geometry" );
42}
43
44QString QgsTransectAlgorithm::groupId() const
45{
46 return QStringLiteral( "vectorgeometry" );
47}
48
49void QgsTransectAlgorithm::initAlgorithm( const QVariantMap & )
50{
51 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
52 auto length = std::make_unique<QgsProcessingParameterDistance>( QStringLiteral( "LENGTH" ), QObject::tr( "Length of the transect" ), 5.0, QStringLiteral( "INPUT" ), false, 0 );
53 length->setIsDynamic( true );
54 length->setDynamicPropertyDefinition( QgsPropertyDefinition( QStringLiteral( "LENGTH" ), QObject::tr( "Length of the transect" ), QgsPropertyDefinition::DoublePositive ) );
55 length->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
56 addParameter( length.release() );
57
58 auto angle = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "ANGLE" ), QObject::tr( "Angle in degrees from the original line at the vertices" ), Qgis::ProcessingNumberParameterType::Double, 90.0, false, 0, 360 );
59 angle->setIsDynamic( true );
60 angle->setDynamicPropertyDefinition( QgsPropertyDefinition( QStringLiteral( "ANGLE" ), QObject::tr( "Angle in degrees" ), QgsPropertyDefinition::Double ) );
61 angle->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
62 addParameter( angle.release() );
63
64 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "SIDE" ), QObject::tr( "Side to create the transects" ), QStringList() << QObject::tr( "Left" ) << QObject::tr( "Right" ) << QObject::tr( "Both" ), false ) );
65 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Transect" ), Qgis::ProcessingSourceType::VectorLine ) );
66}
67
68QString QgsTransectAlgorithm::shortHelpString() const
69{
70 return QObject::tr( "This algorithm creates transects on vertices for (multi)linestrings.\n" )
71 + QObject::tr( "A transect is a line oriented from an angle (by default perpendicular) to the input polylines (at vertices)." )
72 + QStringLiteral( "\n\n" )
73 + QObject::tr( "Field(s) from feature(s) are returned in the transect with these new fields:\n" )
74 + QObject::tr( "- TR_FID: ID of the original feature\n" )
75 + QObject::tr( "- TR_ID: ID of the transect. Each transect have an unique ID\n" )
76 + QObject::tr( "- TR_SEGMENT: ID of the segment of the linestring\n" )
77 + QObject::tr( "- TR_ANGLE: Angle in degrees from the original line at the vertex\n" )
78 + QObject::tr( "- TR_LENGTH: Total length of the transect returned\n" )
79 + QObject::tr( "- TR_ORIENT: Side of the transect (only on the left or right of the line, or both side)\n" );
80}
81
82QString QgsTransectAlgorithm::shortDescription() const
83{
84 return QObject::tr( "Creates transects on vertices for (multi)linestrings." );
85}
86
87Qgis::ProcessingAlgorithmDocumentationFlags QgsTransectAlgorithm::documentationFlags() const
88{
90}
91
92QgsTransectAlgorithm *QgsTransectAlgorithm::createInstance() const
93{
94 return new QgsTransectAlgorithm();
95}
96
97QVariantMap QgsTransectAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
98{
99 const Side orientation = static_cast<QgsTransectAlgorithm::Side>( parameterAsInt( parameters, QStringLiteral( "SIDE" ), context ) );
100 const double angle = fabs( parameterAsDouble( parameters, QStringLiteral( "ANGLE" ), context ) );
101 const bool dynamicAngle = QgsProcessingParameters::isDynamic( parameters, QStringLiteral( "ANGLE" ) );
102 QgsProperty angleProperty;
103 if ( dynamicAngle )
104 angleProperty = parameters.value( QStringLiteral( "ANGLE" ) ).value<QgsProperty>();
105
106 double length = parameterAsDouble( parameters, QStringLiteral( "LENGTH" ), context );
107 const bool dynamicLength = QgsProcessingParameters::isDynamic( parameters, QStringLiteral( "LENGTH" ) );
108 QgsProperty lengthProperty;
109 if ( dynamicLength )
110 lengthProperty = parameters.value( QStringLiteral( "LENGTH" ) ).value<QgsProperty>();
111
112 if ( orientation == QgsTransectAlgorithm::Both )
113 length /= 2.0;
114
115 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
116 if ( !source )
117 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
118
119 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, dynamic_cast<QgsProcessingFeatureSource *>( source.get() ) );
120
121 QgsFields newFields;
122 newFields.append( QgsField( QStringLiteral( "TR_FID" ), QMetaType::Type::Int, QString(), 20 ) );
123 newFields.append( QgsField( QStringLiteral( "TR_ID" ), QMetaType::Type::Int, QString(), 20 ) );
124 newFields.append( QgsField( QStringLiteral( "TR_SEGMENT" ), QMetaType::Type::Int, QString(), 20 ) );
125 newFields.append( QgsField( QStringLiteral( "TR_ANGLE" ), QMetaType::Type::Double, QString(), 5, 2 ) );
126 newFields.append( QgsField( QStringLiteral( "TR_LENGTH" ), QMetaType::Type::Double, QString(), 20, 6 ) );
127 newFields.append( QgsField( QStringLiteral( "TR_ORIENT" ), QMetaType::Type::Int, QString(), 1 ) );
128 QgsFields fields = QgsProcessingUtils::combineFields( source->fields(), newFields );
129
131 if ( QgsWkbTypes::hasZ( source->wkbType() ) )
132 outputWkb = QgsWkbTypes::addZ( outputWkb );
133 if ( QgsWkbTypes::hasM( source->wkbType() ) )
134 outputWkb = QgsWkbTypes::addM( outputWkb );
135
136 QString dest;
137 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, outputWkb, source->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
138 if ( !sink )
139 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
140
141 QgsFeatureIterator features = source->getFeatures();
142
143 int current = -1;
144 int number = 0;
145 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
146 QgsFeature feat;
147
148
149 while ( features.nextFeature( feat ) )
150 {
151 current++;
152 if ( feedback->isCanceled() )
153 {
154 break;
155 }
156
157 feedback->setProgress( current * step );
158 if ( !feat.hasGeometry() )
159 continue;
160
161 QgsGeometry inputGeometry = feat.geometry();
162
163 if ( dynamicLength || dynamicAngle )
164 {
165 expressionContext.setFeature( feat );
166 }
167
168 double evaluatedLength = length;
169 if ( dynamicLength )
170 evaluatedLength = lengthProperty.valueAsDouble( context.expressionContext(), length );
171 double evaluatedAngle = angle;
172 if ( dynamicAngle )
173 evaluatedAngle = angleProperty.valueAsDouble( context.expressionContext(), angle );
174
175 inputGeometry.convertToMultiType();
176 const QgsMultiLineString *multiLine = static_cast<const QgsMultiLineString *>( inputGeometry.constGet() );
177 for ( int id = 0; id < multiLine->numGeometries(); ++id )
178 {
179 const QgsLineString *line = multiLine->lineStringN( id );
181 while ( it != line->vertices_end() )
182 {
183 const QgsVertexId vertexId = it.vertexId();
184 const int i = vertexId.vertex;
185 QgsFeature outFeat;
186 QgsAttributes attrs = feat.attributes();
187 attrs << current << number << i + 1 << evaluatedAngle << ( ( orientation == QgsTransectAlgorithm::Both ) ? evaluatedLength * 2 : evaluatedLength ) << orientation;
188 outFeat.setAttributes( attrs );
189 const double angleAtVertex = line->vertexAngle( vertexId );
190 outFeat.setGeometry( calcTransect( *it, angleAtVertex, evaluatedLength, orientation, evaluatedAngle ) );
191 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
192 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
193 number++;
194 it++;
195 }
196 }
197 }
198
199 sink->finalize();
200
201 QVariantMap outputs;
202 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
203 return outputs;
204}
205
206
207QgsGeometry QgsTransectAlgorithm::calcTransect( const QgsPoint &point, const double angleAtVertex, const double length, const QgsTransectAlgorithm::Side orientation, const double angle )
208{
209 QgsPoint pLeft; // left point of the line
210 QgsPoint pRight; // right point of the line
211
212 QgsPolyline line;
213
214 if ( ( orientation == QgsTransectAlgorithm::Right ) || ( orientation == QgsTransectAlgorithm::Both ) )
215 {
216 pLeft = point.project( length, angle + 180.0 / M_PI * angleAtVertex );
217 if ( orientation != QgsTransectAlgorithm::Both )
218 pRight = point;
219 }
220
221 if ( ( orientation == QgsTransectAlgorithm::Left ) || ( orientation == QgsTransectAlgorithm::Both ) )
222 {
223 pRight = point.project( -length, angle + 180.0 / M_PI * angleAtVertex );
224 if ( orientation != QgsTransectAlgorithm::Both )
225 pLeft = point;
226 }
227
228 line.append( pLeft );
229 line.append( pRight );
230
231 return QgsGeometry::fromPolyline( line );
232}
233
@ VectorLine
Vector line layers.
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3496
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:256
@ LineString
LineString.
The vertex_iterator class provides an STL-style iterator for vertices.
QgsVertexId vertexId() const
Returns vertex ID of the current item.
vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
vertex_iterator vertices_begin() const
Returns STL-style iterator pointing to the first vertex of the geometry.
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.
@ 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:58
QgsAttributes attributes
Definition qgsfeature.h:67
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
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: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
int numGeometries() const
Returns the number of geometries within the collection.
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.
static QgsGeometry fromPolyline(const QgsPolyline &polyline)
Creates a new LineString geometry from a list of QgsPoint points.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
Line string geometry type, with support for z-dimension and m-values.
double vertexAngle(QgsVertexId vertex) const override
Returns approximate angle at a vertex.
Multi line string geometry collection.
QgsLineString * lineStringN(int index)
Returns the line string with the specified index.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
QgsPoint project(double distance, double azimuth, double inclination=90.0) const
Returns a new point which corresponds to this point projected by a specified distance with specified ...
Definition qgspoint.cpp:704
Contains information about the context in which a processing algorithm is executed.
QgsExpressionContext & expressionContext()
Returns the expression context.
Custom exception class for processing related exceptions.
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource,...
Base class for providing feedback from a processing 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.
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...
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
Definition for a property.
Definition qgsproperty.h:45
@ Double
Double value (including negative values)
Definition qgsproperty.h:55
@ DoublePositive
Positive double value (including 0)
Definition qgsproperty.h:56
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.
static Qgis::WkbType addM(Qgis::WkbType type)
Adds the m dimension to a WKB type and returns the new type.
static Qgis::WkbType addZ(Qgis::WkbType type)
Adds the z dimension to a WKB type and returns the new type.
static bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
QgsPointSequence QgsPolyline
Polyline as represented as a vector of points.
Definition qgsgeometry.h:70
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30
int vertex
Vertex number.
Definition qgsvertexid.h:94