QGIS API Documentation 3.41.0-Master (25ec5511245)
Loading...
Searching...
No Matches
qgsgeometrymissingvertexcheck.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgeometrymissingvertexcheck.cpp
3 ---------------------
4 begin : September 2018
5 copyright : (C) 2018 Matthias Kuhn
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
18#include "qgsfeedback.h"
20#include "qgsmultipolygon.h"
21#include "qgscurvepolygon.h"
22#include "qgscurve.h"
23#include "qgsgeometryengine.h"
24#include "qgsgeometryutils.h"
25#include "qgsapplication.h"
26
27QgsGeometryMissingVertexCheck::QgsGeometryMissingVertexCheck( const QgsGeometryCheckContext *context, const QVariantMap &geometryCheckConfiguration )
28 : QgsGeometryCheck( context, geometryCheckConfiguration )
29
30{}
31
32void QgsGeometryMissingVertexCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
33{
34 Q_UNUSED( messages )
35 if ( feedback )
36 feedback->setProgress( feedback->progress() + 1.0 );
37
38 QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds( featurePools ) : ids.toMap();
39
40 QgsFeaturePool *featurePool = featurePools.value( featureIds.firstKey() );
41
42 const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds, compatibleGeometryTypes(), nullptr, mContext, true );
43
44 for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
45 {
46 if ( feedback && feedback->isCanceled() )
47 {
48 break;
49 }
50
51 const QgsGeometry geometry = layerFeature.geometry();
52 const QgsAbstractGeometry *geom = geometry.constGet();
53
54 if ( QgsCurvePolygon *polygon = qgsgeometry_cast<QgsCurvePolygon *>( geom ) )
55 {
56 processPolygon( polygon, featurePool, errors, layerFeature, feedback );
57 }
58 else if ( QgsGeometryCollection *collection = qgsgeometry_cast<QgsGeometryCollection *>( geom ) )
59 {
60 const int numGeometries = collection->numGeometries();
61 for ( int i = 0; i < numGeometries; ++i )
62 {
63 if ( QgsCurvePolygon *polygon = qgsgeometry_cast<QgsCurvePolygon *>( collection->geometryN( i ) ) )
64 {
65 processPolygon( polygon, featurePool, errors, layerFeature, feedback );
66 }
67 }
68 }
69 }
70}
71
72void QgsGeometryMissingVertexCheck::fixError( const QMap<QString, QgsFeaturePool *> &featurePools, QgsGeometryCheckError *error, int method, const QMap<QString, int> & /*mergeAttributeIndices*/, Changes &changes ) const
73{
74 Q_UNUSED( featurePools )
75 Q_UNUSED( changes )
76
77 QMetaEnum metaEnum = QMetaEnum::fromType<QgsGeometryMissingVertexCheck::ResolutionMethod>();
78 if ( !metaEnum.isValid() || !metaEnum.valueToKey( method ) )
79 {
80 error->setFixFailed( tr( "Unknown method" ) );
81 }
82 else
83 {
84 ResolutionMethod methodValue = static_cast<ResolutionMethod>( method );
85 switch ( methodValue )
86 {
87 case NoChange:
88 error->setFixed( method );
89 break;
90
92 {
93 QgsFeaturePool *featurePool = featurePools[ error->layerId() ];
94
95 QgsFeature feature;
96 featurePool->getFeature( error->featureId(), feature );
97
98 QgsPointXY pointOnSegment; // Should be equal to location
99 int vertexIndex;
100 QgsGeometry geometry = feature.geometry();
101 geometry.closestSegmentWithContext( error->location(), pointOnSegment, vertexIndex );
102 geometry.insertVertex( QgsPoint( error->location() ), vertexIndex );
103 feature.setGeometry( geometry );
104
105 featurePool->updateFeature( feature );
106 // TODO update "changes" structure
107
108 error->setFixed( method );
109 }
110 break;
111 }
112 }
113}
114
116{
117 static QStringList methods = QStringList()
118 << tr( "No action" )
119 << tr( "Add missing vertex" );
120 return methods;
121}
122
124{
125 return factoryDescription();
126}
127
128void QgsGeometryMissingVertexCheck::processPolygon( const QgsCurvePolygon *polygon, QgsFeaturePool *featurePool, QList<QgsGeometryCheckError *> &errors, const QgsGeometryCheckerUtils::LayerFeature &layerFeature, QgsFeedback *feedback ) const
129{
130 const QgsFeature &currentFeature = layerFeature.feature();
131 std::unique_ptr<QgsMultiPolygon> boundaries = std::make_unique<QgsMultiPolygon>();
132
133 std::unique_ptr< QgsGeometryEngine > geomEngine( QgsGeometry::createGeometryEngine( polygon->exteriorRing()->clone(), mContext->tolerance ) );
134 boundaries->addGeometry( geomEngine->buffer( mContext->tolerance, 5 ) );
135
136 const int numRings = polygon->numInteriorRings();
137 for ( int i = 0; i < numRings; ++i )
138 {
139 geomEngine.reset( QgsGeometry::createGeometryEngine( polygon->interiorRing( i ), mContext->tolerance ) );
140 boundaries->addGeometry( geomEngine->buffer( mContext->tolerance, 5 ) );
141 }
142
143 geomEngine.reset( QgsGeometry::createGeometryEngine( boundaries.get(), mContext->tolerance ) );
144 geomEngine->prepareGeometry();
145
146 const QgsFeatureIds fids = featurePool->getIntersects( boundaries->boundingBox() );
147
148 QgsFeature compareFeature;
149 for ( QgsFeatureId fid : fids )
150 {
151 if ( fid == currentFeature.id() )
152 continue;
153
154 if ( featurePool->getFeature( fid, compareFeature ) )
155 {
156 if ( feedback && feedback->isCanceled() )
157 break;
158
159 const QgsGeometry compareGeometry = compareFeature.geometry();
160 QgsVertexIterator vertexIterator = compareGeometry.vertices();
161 while ( vertexIterator.hasNext() )
162 {
163 const QgsPoint &pt = vertexIterator.next();
164 if ( geomEngine->intersects( &pt ) )
165 {
166 QgsVertexId vertexId;
167 QgsPoint closestVertex = QgsGeometryUtils::closestVertex( *polygon, pt, vertexId );
168
169 if ( closestVertex.distance( pt ) > mContext->tolerance )
170 {
171 bool alreadyReported = false;
172 for ( QgsGeometryCheckError *error : std::as_const( errors ) )
173 {
174 // Only list missing vertices once
175 if ( error->featureId() == currentFeature.id() && error->location() == QgsPointXY( pt ) )
176 {
177 alreadyReported = true;
178 break;
179 }
180 }
181 if ( !alreadyReported )
182 {
183 std::unique_ptr<QgsGeometryMissingVertexCheckError> error = std::make_unique<QgsGeometryMissingVertexCheckError>( this, layerFeature, QgsPointXY( pt ) );
184 error->setAffectedAreaBBox( contextBoundingBox( polygon, vertexId, pt ) );
185 QMap<QString, QgsFeatureIds> involvedFeatures;
186 involvedFeatures[layerFeature.layerId()].insert( layerFeature.feature().id() );
187 involvedFeatures[featurePool->layerId()].insert( fid );
188 error->setInvolvedFeatures( involvedFeatures );
189
190 errors.append( error.release() );
191 }
192 }
193 }
194 }
195 }
196 }
197}
198
199QgsRectangle QgsGeometryMissingVertexCheck::contextBoundingBox( const QgsCurvePolygon *polygon, const QgsVertexId &vertexId, const QgsPoint &point ) const
200{
201 QgsVertexId vertexBefore;
202 QgsVertexId vertexAfter;
203
204 polygon->adjacentVertices( vertexId, vertexBefore, vertexAfter );
205
206 QgsPoint ptBefore = polygon->vertexAt( vertexBefore );
207 QgsPoint ptAt = polygon->vertexAt( vertexId );
208 QgsPoint ptAfter = polygon->vertexAt( vertexAfter );
209
210 double length = std::abs( ptAt.distance( ptBefore ) ) + std::abs( ptAt.distance( ptAfter ) );
211
212 QgsRectangle rect( point.x() - length / 2, point.y() - length / 2, point.x() + length / 2, point.y() + length / 2 );
213 return rect;
214}
215
217{
218 return factoryId();
219}
220
222{
223 return factoryCompatibleGeometryTypes();
224}
225
227{
228 return factoryFlags();
229}
230
232{
233 return factoryCheckType();
234}
235
237QList<Qgis::GeometryType> QgsGeometryMissingVertexCheck::factoryCompatibleGeometryTypes()
238{
240}
241
242bool QgsGeometryMissingVertexCheck::factoryIsCompatible( QgsVectorLayer *layer ) SIP_SKIP
243{
244 return factoryCompatibleGeometryTypes().contains( layer->geometryType() );
245}
246
247QString QgsGeometryMissingVertexCheck::factoryDescription()
248{
249 return tr( "Missing Vertex" );
250}
251
252QString QgsGeometryMissingVertexCheck::factoryId()
253{
254 return QStringLiteral( "QgsGeometryMissingVertexCheck" );
255}
256
257QgsGeometryCheck::Flags QgsGeometryMissingVertexCheck::factoryFlags()
258{
260}
261
262QgsGeometryCheck::CheckType QgsGeometryMissingVertexCheck::factoryCheckType()
263{
265}
267
269 : QgsGeometryCheckError( check, layerFeature, errorLocation, vidx, value, valueType )
270{
271}
272
274{
275 return mAffectedAreaBBox;
276}
277
279{
280 mAffectedAreaBBox = affectedAreaBBox;
281}
282
284{
285 return mInvolvedFeatures;
286}
287
288void QgsGeometryMissingVertexCheckError::setInvolvedFeatures( const QMap<QString, QgsFeatureIds> &involvedFeatures )
289{
290 mInvolvedFeatures = involvedFeatures;
291}
292
294{
295
297 return QgsApplication::getThemeIcon( QStringLiteral( "/algorithms/mAlgorithmCheckGeometry.svg" ) );
298 else
299 return QgsApplication::getThemeIcon( QStringLiteral( "/checks/MissingVertex.svg" ) );
300}
@ Polygon
Polygons.
Abstract base class for all geometries.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
Curve polygon geometry type.
int numInteriorRings() const
Returns the number of interior rings contained with the curve polygon.
const QgsCurve * exteriorRing() const
Returns the curve polygon's exterior ring.
const QgsCurve * interiorRing(int i) const
Retrieves an interior ring from the curve polygon.
void adjacentVertices(QgsVertexId vertex, QgsVertexId &previousVertex, QgsVertexId &nextVertex) const override
Returns the vertices adjacent to a specified vertex within a geometry.
QgsPoint vertexAt(QgsVertexId id) const override
Returns the point corresponding to a specified vertex id.
QgsCurve * clone() const override=0
Clones the geometry by performing a deep copy.
A feature pool is based on a vector layer and caches features.
virtual void updateFeature(QgsFeature &feature)=0
Updates a feature in this pool.
QString layerId() const
The layer id of the layer.
QgsFeatureIds getIntersects(const QgsRectangle &rect) const
Gets all feature ids in the bounding box rect.
bool getFeature(QgsFeatureId id, QgsFeature &feature)
Retrieves the feature with the specified id into feature.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
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
double progress() const
Returns the current progress reported by the feedback object.
Definition qgsfeedback.h:77
Base configuration for geometry checks.
const double tolerance
The tolerance to allow for in geometry checks.
This represents an error reported by a geometry check.
ValueType
Describes the type of an error value.
@ StatusFixed
The error is fixed.
Status status() const
The status of the error.
QgsFeatureId featureId() const
The id of the feature on which this error has been detected.
void setFixed(int method)
Set the status to fixed and specify the method that has been used to fix the error.
void setFixFailed(const QString &reason)
Set the error status to failed and specify the reason for failure.
const QString & layerId() const
The id of the layer on which this error has been detected.
const QgsPointXY & location() const
The location of the error in map units.
This class implements a geometry check.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
QFlags< Flag > Flags
const QgsGeometryCheckContext * mContext
@ AvailableInValidation
This geometry check should be available in layer validation on the vector layer peroperties.
CheckType
The type of a check.
@ LayerCheck
The check controls a whole layer (topology checks)
QMap< QString, QgsFeatureIds > allLayerFeatureIds(const QMap< QString, QgsFeaturePool * > &featurePools) const
Returns all layers and feature ids.
A layer feature combination to uniquely identify and access a feature in a set of layers.
QgsFeature feature() const
Returns the feature.
Contains a set of layers and feature ids in those layers to pass to a geometry check.
QgsGeometryMissingVertexCheckError(const QgsGeometryCheck *check, const QgsGeometryCheckerUtils::LayerFeature &layerFeature, const QgsPointXY &errorLocation, QgsVertexId vidx=QgsVertexId(), const QVariant &value=QVariant(), ValueType valueType=ValueOther)
Create a new missing vertex check error.
QIcon icon() const override
Returns an icon that should be shown for this kind of error.
void setAffectedAreaBBox(const QgsRectangle &affectedAreaBBox)
Set the bounding box of the affected area.
void setInvolvedFeatures(const QMap< QString, QgsFeatureIds > &involvedFeatures)
The two involved features, that share a common boundary but not all common vertices on this boundary.
QMap< QString, QgsFeatureIds > involvedFeatures() const override
Returns a list of involved features.
QgsRectangle affectedAreaBBox() const override
The bounding box of the affected area of the error.
QgsGeometryCheck::Flags flags() const override
Flags for this geometry check.
QString description() const override
Returns a human readable description for this check.
void fixError(const QMap< QString, QgsFeaturePool * > &featurePools, QgsGeometryCheckError *error, int method, const QMap< QString, int > &mergeAttributeIndices, Changes &changes) const override
Fixes the error error with the specified method.
QList< Qgis::GeometryType > compatibleGeometryTypes() const override
A list of geometry types for which this check can be performed.
Q_DECL_DEPRECATED QStringList resolutionMethods() const override
Returns a list of descriptions for available resolutions for errors.
QString id() const override
Returns an id for this check.
QgsGeometryCheck::CheckType checkType() const override
Returns the check type.
ResolutionMethod
The available resolutions for missing vertex check.
void collectErrors(const QMap< QString, QgsFeaturePool * > &featurePools, QList< QgsGeometryCheckError * > &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids=LayerFeatureIds()) const override
The main worker method.
QgsGeometryMissingVertexCheck(const QgsGeometryCheckContext *context, const QVariantMap &geometryCheckConfiguration)
Creates a new missing vertex geometry check with context and the provided geometryCheckConfiguration.
static QgsPoint closestVertex(const QgsAbstractGeometry &geom, const QgsPoint &pt, QgsVertexId &id)
Returns the closest vertex to a geometry for a specified point.
A geometry is the spatial representation of a feature.
QgsVertexIterator vertices() const
Returns a read-only, Java-style iterator for traversal of vertices of all the geometry,...
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool insertVertex(double x, double y, int beforeVertex)
Insert a new vertex before the given vertex index, ring and item (first number is index 0) If the req...
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
double closestSegmentWithContext(const QgsPointXY &point, QgsPointXY &minDistPoint, int &nextVertexIndex, int *leftOrRightOfSegment=nullptr, double epsilon=DEFAULT_SEGMENT_EPSILON) const
Searches for the closest segment of geometry to the given point.
A class to represent a 2D point.
Definition qgspointxy.h:60
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
double x
Definition qgspoint.h:52
double distance(double x, double y) const
Returns the Cartesian 2D distance between this point and a specified x, y coordinate.
Definition qgspoint.h:393
double y
Definition qgspoint.h:53
A rectangle specified with double values.
Represents a vector layer which manages a vector based data sets.
Java-style iterator for traversal of vertices of a geometry.
bool hasNext() const
Find out whether there are more vertices.
QgsPoint next()
Returns next vertex of the geometry (undefined behavior if hasNext() returns false before calling nex...
#define SIP_SKIP
Definition qgis_sip.h:126
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
A list of layers and feature ids for each of these layers.
QMap< QString, QgsFeatureIds > toMap() const
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30