QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgsgeometrysnapper.cpp
Go to the documentation of this file.
1/***************************************************************************
2 * qgsgeometrysnapper.cpp *
3 * ------------------- *
4 * copyright : (C) 2014 by Sandro Mani / Sourcepole AG *
5 * email : [email protected] *
6 ***************************************************************************/
7
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17#include "qgsfeatureiterator.h"
18#include "qgsgeometry.h"
19#include "qgsvectorlayer.h"
20#include "qgsgeometrysnapper.h"
21#include "moc_qgsgeometrysnapper.cpp"
23#include "qgsgeometryutils.h"
24#include "qgssurface.h"
25#include "qgsmultisurface.h"
26#include "qgscurve.h"
27
28#include <QtConcurrentMap>
29#include <geos_c.h>
30
32
33QgsSnapIndex::PointSnapItem::PointSnapItem( const QgsSnapIndex::CoordIdx *_idx, bool isEndPoint )
34 : SnapItem( isEndPoint ? QgsSnapIndex::SnapEndPoint : QgsSnapIndex::SnapPoint )
35 , idx( _idx )
36{}
37
38QgsPoint QgsSnapIndex::PointSnapItem::getSnapPoint( const QgsPoint &/*p*/ ) const
39{
40 return idx->point();
41}
42
43QgsSnapIndex::SegmentSnapItem::SegmentSnapItem( const QgsSnapIndex::CoordIdx *_idxFrom, const QgsSnapIndex::CoordIdx *_idxTo )
44 : SnapItem( QgsSnapIndex::SnapSegment )
45 , idxFrom( _idxFrom )
46 , idxTo( _idxTo )
47{}
48
49QgsPoint QgsSnapIndex::SegmentSnapItem::getSnapPoint( const QgsPoint &p ) const
50{
51 return QgsGeometryUtils::projectPointOnSegment( p, idxFrom->point(), idxTo->point() );
52}
53
54bool QgsSnapIndex::SegmentSnapItem::getIntersection( const QgsPoint &p1, const QgsPoint &p2, QgsPoint &inter ) const
55{
56 const QgsPoint &q1 = idxFrom->point(), & q2 = idxTo->point();
57 QgsVector v( p2.x() - p1.x(), p2.y() - p1.y() );
58 QgsVector w( q2.x() - q1.x(), q2.y() - q1.y() );
59 const double vl = v.length();
60 const double wl = w.length();
61
62 if ( qgsDoubleNear( vl, 0, 0.000000000001 ) || qgsDoubleNear( wl, 0, 0.000000000001 ) )
63 {
64 return false;
65 }
66 v = v / vl;
67 w = w / wl;
68
69 const double d = v.y() * w.x() - v.x() * w.y();
70
71 if ( d == 0 )
72 return false;
73
74 const double dx = q1.x() - p1.x();
75 const double dy = q1.y() - p1.y();
76 const double k = ( dy * w.x() - dx * w.y() ) / d;
77
78 inter = QgsPoint( p1.x() + v.x() * k, p1.y() + v.y() * k );
79
80 const double lambdav = QgsVector( inter.x() - p1.x(), inter.y() - p1.y() ) * v;
81 if ( lambdav < 0. + 1E-8 || lambdav > vl - 1E-8 )
82 return false;
83
84 const double lambdaw = QgsVector( inter.x() - q1.x(), inter.y() - q1.y() ) * w;
85 return !( lambdaw < 0. + 1E-8 || lambdaw >= wl - 1E-8 );
86}
87
88bool QgsSnapIndex::SegmentSnapItem::getProjection( const QgsPoint &p, QgsPoint &pProj ) const
89{
90 const QgsPoint &s1 = idxFrom->point();
91 const QgsPoint &s2 = idxTo->point();
92 const double nx = s2.y() - s1.y();
93 const double ny = -( s2.x() - s1.x() );
94 const double t = ( p.x() * ny - p.y() * nx - s1.x() * ny + s1.y() * nx ) / ( ( s2.x() - s1.x() ) * ny - ( s2.y() - s1.y() ) * nx );
95 if ( t < 0. || t > 1. )
96 {
97 return false;
98 }
99 pProj = QgsPoint( s1.x() + ( s2.x() - s1.x() ) * t, s1.y() + ( s2.y() - s1.y() ) * t );
100 return true;
101}
102
103bool QgsSnapIndex::SegmentSnapItem::withinSquaredDistance( const QgsPoint &p, const double squaredDistance )
104{
105 double minDistX, minDistY;
106 return QgsGeometryUtilsBase::sqrDistToLine( p.x(), p.y(), idxFrom->point().x(), idxFrom->point().y(), idxTo->point().x(), idxTo->point().y(), minDistX, minDistY, 4 * std::numeric_limits<double>::epsilon() ) <= squaredDistance;
107}
108
110
111QgsSnapIndex::QgsSnapIndex()
112{
113 mSTRTree = GEOSSTRtree_create_r( QgsGeosContext::get(), ( size_t )10 );
114}
115
116QgsSnapIndex::~QgsSnapIndex()
117{
118 qDeleteAll( mCoordIdxs );
119 qDeleteAll( mSnapItems );
120
121 GEOSSTRtree_destroy_r( QgsGeosContext::get(), mSTRTree );
122}
123
124void QgsSnapIndex::addPoint( const CoordIdx *idx, bool isEndPoint )
125{
126 const QgsPoint p = idx->point();
127
128 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
129 geos::unique_ptr point( GEOSGeom_createPointFromXY_r( geosctxt, p.x(), p.y() ) );
130
131 PointSnapItem *item = new PointSnapItem( idx, isEndPoint );
132 GEOSSTRtree_insert_r( geosctxt, mSTRTree, point.get(), item );
133 mSnapItems << item;
134}
135
136void QgsSnapIndex::addSegment( const CoordIdx *idxFrom, const CoordIdx *idxTo )
137{
138 const QgsPoint pointFrom = idxFrom->point();
139 const QgsPoint pointTo = idxTo->point();
140
141 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
142
143 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
144 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pointFrom.x(), pointFrom.y() );
145 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pointTo.x(), pointTo.y() );
146 geos::unique_ptr segment( GEOSGeom_createLineString_r( geosctxt, coord ) );
147
148 SegmentSnapItem *item = new SegmentSnapItem( idxFrom, idxTo );
149 GEOSSTRtree_insert_r( geosctxt, mSTRTree, segment.get(), item );
150 mSnapItems << item;
151}
152
153void QgsSnapIndex::addGeometry( const QgsAbstractGeometry *geom )
154{
155 for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart )
156 {
157 for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing )
158 {
159 int nVerts = geom->vertexCount( iPart, iRing );
160
161 if ( qgsgeometry_cast< const QgsSurface * >( geom ) )
162 nVerts--;
163 else if ( const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geom ) )
164 {
165 if ( curve->isClosed() )
166 nVerts--;
167 }
168
169 for ( int iVert = 0; iVert < nVerts; ++iVert )
170 {
171 CoordIdx *idx = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert ) );
172 CoordIdx *idx1 = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert + 1 ) );
173 mCoordIdxs.append( idx );
174 mCoordIdxs.append( idx1 );
175 addPoint( idx, iVert == 0 || iVert == nVerts - 1 );
176 if ( iVert < nVerts - 1 )
177 addSegment( idx, idx1 );
178 }
179 }
180 }
181}
182
184{
185 QList< QgsSnapIndex::SnapItem * > *list;
186};
187
188void _GEOSQueryCallback( void *item, void *userdata )
189{
190 reinterpret_cast<_GEOSQueryCallbackData *>( userdata )->list->append( static_cast<QgsSnapIndex::SnapItem *>( item ) );
191}
192
193QgsPoint QgsSnapIndex::getClosestSnapToPoint( const QgsPoint &startPoint, const QgsPoint &midPoint )
194{
195 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
196
197 // Look for intersections on segment from the target point to the point opposite to the point reference point
198 // p2 = p1 + 2 * (q - p1)
199 const QgsPoint endPoint( 2 * midPoint.x() - startPoint.x(), 2 * midPoint.y() - startPoint.y() );
200
201 QgsPoint minPoint = startPoint;
202 double minDistance = std::numeric_limits<double>::max();
203
204 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
205 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, startPoint.x(), startPoint.y() );
206 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, endPoint.x(), endPoint.y() );
207 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
208
209 QList<SnapItem *> items;
210 struct _GEOSQueryCallbackData callbackData;
211 callbackData.list = &items;
212 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(), _GEOSQueryCallback, &callbackData );
213 for ( const SnapItem *item : std::as_const( items ) )
214 {
215 if ( item->type == SnapSegment )
216 {
217 QgsPoint inter;
218 if ( static_cast<const SegmentSnapItem *>( item )->getIntersection( startPoint, endPoint, inter ) )
219 {
220 const double dist = QgsGeometryUtils::sqrDistance2D( midPoint, inter );
221 if ( dist < minDistance )
222 {
223 minDistance = dist;
224 minPoint = inter;
225 }
226 }
227 }
228 }
229
230 return minPoint;
231}
232
233QgsSnapIndex::SnapItem *QgsSnapIndex::getSnapItem( const QgsPoint &pos, const double tolerance, QgsSnapIndex::PointSnapItem **pSnapPoint, QgsSnapIndex::SegmentSnapItem **pSnapSegment, bool endPointOnly ) const
234{
235 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
236
237 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
238 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pos.x() - tolerance, pos.y() - tolerance );
239 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pos.x() + tolerance, pos.y() + tolerance );
240
241 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
242
243 QList<SnapItem *> items;
244 struct _GEOSQueryCallbackData callbackData;
245 callbackData.list = &items;
246 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(), _GEOSQueryCallback, &callbackData );
247
248 double minDistSegment = std::numeric_limits<double>::max();
249 double minDistPoint = std::numeric_limits<double>::max();
250 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
251 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
252
253 const double squaredTolerance = tolerance * tolerance;
254 const auto constItems = items;
255 for ( QgsSnapIndex::SnapItem *item : constItems )
256 {
257 if ( ( ! endPointOnly && item->type == SnapPoint ) || item->type == SnapEndPoint )
258 {
259 const double dist = QgsGeometryUtils::sqrDistance2D( item->getSnapPoint( pos ), pos );
260 if ( dist < minDistPoint )
261 {
262 minDistPoint = dist;
263 snapPoint = static_cast<PointSnapItem *>( item );
264 }
265 }
266 else if ( item->type == SnapSegment && !endPointOnly )
267 {
268 if ( !static_cast<SegmentSnapItem *>( item )->withinSquaredDistance( pos, squaredTolerance ) )
269 continue;
270
271 QgsPoint pProj;
272 if ( !static_cast<SegmentSnapItem *>( item )->getProjection( pos, pProj ) )
273 continue;
274
275 const double dist = QgsGeometryUtils::sqrDistance2D( pProj, pos );
276 if ( dist < minDistSegment )
277 {
278 minDistSegment = dist;
279 snapSegment = static_cast<SegmentSnapItem *>( item );
280 }
281 }
282 }
283 snapPoint = minDistPoint < squaredTolerance ? snapPoint : nullptr;
284 snapSegment = minDistSegment < squaredTolerance ? snapSegment : nullptr;
285 if ( pSnapPoint ) *pSnapPoint = snapPoint;
286 if ( pSnapSegment ) *pSnapSegment = snapSegment;
287 return minDistPoint < minDistSegment ? static_cast<QgsSnapIndex::SnapItem *>( snapPoint ) : static_cast<QgsSnapIndex::SnapItem *>( snapSegment );
288}
289
291
292
293//
294// QgsGeometrySnapper
295//
296
298 : mReferenceSource( referenceSource )
299{
300 // Build spatial index
301 mIndex = QgsSpatialIndex( *mReferenceSource );
302}
303
304QgsFeatureList QgsGeometrySnapper::snapFeatures( const QgsFeatureList &features, double snapTolerance, SnapMode mode )
305{
306 QgsFeatureList list = features;
307 QtConcurrent::blockingMap( list, ProcessFeatureWrapper( this, snapTolerance, mode ) );
308 return list;
309}
310
311void QgsGeometrySnapper::processFeature( QgsFeature &feature, double snapTolerance, SnapMode mode )
312{
313 if ( !feature.geometry().isNull() )
314 feature.setGeometry( snapGeometry( feature.geometry(), snapTolerance, mode ) );
315 emit featureSnapped();
316}
317
318QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry &geometry, double snapTolerance, SnapMode mode ) const
319{
320 // Get potential reference features and construct snap index
321 QList<QgsGeometry> refGeometries;
322 mIndexMutex.lock();
323 QgsRectangle searchBounds = geometry.boundingBox();
324 searchBounds.grow( snapTolerance );
325 const QgsFeatureIds refFeatureIds = qgis::listToSet( mIndex.intersects( searchBounds ) );
326 mIndexMutex.unlock();
327
328 if ( refFeatureIds.isEmpty() )
329 return QgsGeometry( geometry );
330
331 refGeometries.reserve( refFeatureIds.size() );
332 QgsFeatureIds missingFeatureIds;
333 const QgsFeatureIds cachedIds = qgis::listToSet( mCachedReferenceGeometries.keys() );
334 for ( const QgsFeatureId id : refFeatureIds )
335 {
336 if ( cachedIds.contains( id ) )
337 {
338 refGeometries.append( mCachedReferenceGeometries[id] );
339 }
340 else
341 {
342 missingFeatureIds << id;
343 }
344 }
345
346 if ( missingFeatureIds.size() > 0 )
347 {
348
349 mReferenceLayerMutex.lock();
350 const QgsFeatureRequest refFeatureRequest = QgsFeatureRequest().setFilterFids( missingFeatureIds ).setNoAttributes();
351 QgsFeatureIterator refFeatureIt = mReferenceSource->getFeatures( refFeatureRequest );
352 QgsFeature refFeature;
353 while ( refFeatureIt.nextFeature( refFeature ) )
354 {
355 refGeometries.append( refFeature.geometry() );
356 }
357 mReferenceLayerMutex.unlock();
358 }
359
360 return snapGeometry( geometry, snapTolerance, refGeometries, mode );
361}
362
363QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry &geometry, double snapTolerance, const QList<QgsGeometry> &referenceGeometries, QgsGeometrySnapper::SnapMode mode )
364{
366 ( mode == EndPointPreferClosest || mode == EndPointPreferNodes || mode == EndPointToEndPoint ) )
367 return geometry;
368
369 const QgsPoint center = qgsgeometry_cast< const QgsPoint * >( geometry.constGet() ) ? *static_cast< const QgsPoint * >( geometry.constGet() ) :
370 QgsPoint( geometry.constGet()->boundingBox().center() );
371
372 QgsSnapIndex refSnapIndex;
373 for ( const QgsGeometry &geom : referenceGeometries )
374 {
375 refSnapIndex.addGeometry( geom.constGet() );
376 }
377
378 // Snap geometries
379 QgsAbstractGeometry *subjGeom = geometry.constGet()->clone();
380 QList < QList< QList<PointFlag> > > subjPointFlags;
381
382 // Pass 1: snap vertices of subject geometry to reference vertices
383 for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart )
384 {
385 subjPointFlags.append( QList< QList<PointFlag> >() );
386
387 for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing )
388 {
389 subjPointFlags[iPart].append( QList<PointFlag>() );
390
391 for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
392 {
393 if ( ( mode == EndPointPreferClosest || mode == EndPointPreferNodes || mode == EndPointToEndPoint ) &&
394 QgsWkbTypes::geometryType( subjGeom->wkbType() ) == Qgis::GeometryType::Line && ( iVert > 0 && iVert < nVerts - 1 ) )
395 {
396 //endpoint mode and not at an endpoint, skip
397 subjPointFlags[iPart][iRing].append( Unsnapped );
398 continue;
399 }
400
401 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
402 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
403 const QgsVertexId vidx( iPart, iRing, iVert );
404 const QgsPoint p = subjGeom->vertexAt( vidx );
405 if ( !refSnapIndex.getSnapItem( p, snapTolerance, &snapPoint, &snapSegment, mode == EndPointToEndPoint ) )
406 {
407 subjPointFlags[iPart][iRing].append( Unsnapped );
408 }
409 else
410 {
411 switch ( mode )
412 {
413 case PreferNodes:
417 {
418 // Prefer snapping to point
419 if ( snapPoint )
420 {
421 subjGeom->moveVertex( vidx, snapPoint->getSnapPoint( p ) );
422 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
423 }
424 else if ( snapSegment )
425 {
426 subjGeom->moveVertex( vidx, snapSegment->getSnapPoint( p ) );
427 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
428 }
429 break;
430 }
431
432 case PreferClosest:
435 {
436 QgsPoint nodeSnap, segmentSnap;
437 double distanceNode = std::numeric_limits<double>::max();
438 double distanceSegment = std::numeric_limits<double>::max();
439 if ( snapPoint )
440 {
441 nodeSnap = snapPoint->getSnapPoint( p );
442 distanceNode = nodeSnap.distanceSquared( p );
443 }
444 if ( snapSegment )
445 {
446 segmentSnap = snapSegment->getSnapPoint( p );
447 distanceSegment = segmentSnap.distanceSquared( p );
448 }
449 if ( snapPoint && distanceNode < distanceSegment )
450 {
451 subjGeom->moveVertex( vidx, nodeSnap );
452 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
453 }
454 else if ( snapSegment )
455 {
456 subjGeom->moveVertex( vidx, segmentSnap );
457 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
458 }
459 break;
460 }
461 }
462 }
463 }
464 }
465 }
466
467 // no extra vertices to add for point geometry
468 if ( qgsgeometry_cast< const QgsPoint * >( subjGeom ) )
469 return QgsGeometry( subjGeom );
470
471 // nor for no extra vertices modes and end point only snapping
473 {
474 QgsGeometry result( subjGeom );
475 result.removeDuplicateNodes();
476 return result;
477 }
478
479 std::unique_ptr< QgsSnapIndex > subjSnapIndex( new QgsSnapIndex() );
480 subjSnapIndex->addGeometry( subjGeom );
481
482 std::unique_ptr< QgsAbstractGeometry > origSubjGeom( subjGeom->clone() );
483 std::unique_ptr< QgsSnapIndex > origSubjSnapIndex( new QgsSnapIndex() );
484 origSubjSnapIndex->addGeometry( origSubjGeom.get() );
485
486 // Pass 2: add missing vertices to subject geometry
487 for ( const QgsGeometry &refGeom : referenceGeometries )
488 {
489 for ( int iPart = 0, nParts = refGeom.constGet()->partCount(); iPart < nParts; ++iPart )
490 {
491 for ( int iRing = 0, nRings = refGeom.constGet()->ringCount( iPart ); iRing < nRings; ++iRing )
492 {
493 for ( int iVert = 0, nVerts = polyLineSize( refGeom.constGet(), iPart, iRing ); iVert < nVerts; ++iVert )
494 {
495 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
496 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
497 const QgsPoint point = refGeom.constGet()->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
498 if ( subjSnapIndex->getSnapItem( point, snapTolerance, &snapPoint, &snapSegment ) )
499 {
500 // Snap to segment, unless a subject point was already snapped to the reference point
501 if ( snapPoint )
502 {
503 const QgsPoint snappedPoint = snapPoint->getSnapPoint( point );
504 if ( QgsGeometryUtils::sqrDistance2D( snappedPoint, point ) < 1E-16 )
505 continue;
506 }
507
508 if ( snapSegment )
509 {
510 // Look if there is a closer reference segment, if so, ignore this point
511 const QgsPoint pProj = snapSegment->getSnapPoint( point );
512 const QgsPoint closest = refSnapIndex.getClosestSnapToPoint( point, pProj );
513 if ( QgsGeometryUtils::sqrDistance2D( pProj, point ) > QgsGeometryUtils::sqrDistance2D( pProj, closest ) )
514 {
515 continue;
516 }
517
518 // If we are too far away from the original geometry, do nothing
519 if ( !origSubjSnapIndex->getSnapItem( point, snapTolerance ) )
520 {
521 continue;
522 }
523
524 const QgsSnapIndex::CoordIdx *idx = snapSegment->idxFrom;
525 subjGeom->insertVertex( QgsVertexId( idx->vidx.part, idx->vidx.ring, idx->vidx.vertex + 1 ), point );
526 subjPointFlags[idx->vidx.part][idx->vidx.ring].insert( idx->vidx.vertex + 1, SnappedToRefNode );
527 subjSnapIndex.reset( new QgsSnapIndex() );
528 subjSnapIndex->addGeometry( subjGeom );
529 }
530 }
531 }
532 }
533 }
534 }
535 subjSnapIndex.reset();
536 origSubjSnapIndex.reset();
537 origSubjGeom.reset();
538
539 // Pass 3: remove superfluous vertices: all vertices which are snapped to a segment and not preceded or succeeded by an unsnapped vertex
540 for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart )
541 {
542 for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing )
543 {
544 const bool ringIsClosed = subjGeom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ) == subjGeom->vertexAt( QgsVertexId( iPart, iRing, subjGeom->vertexCount( iPart, iRing ) - 1 ) );
545 for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
546 {
547 const int iPrev = ( iVert - 1 + nVerts ) % nVerts;
548 const int iNext = ( iVert + 1 ) % nVerts;
549 const QgsPoint pMid = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
550 const QgsPoint pPrev = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iPrev ) );
551 const QgsPoint pNext = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iNext ) );
552
553 if ( subjPointFlags[iPart][iRing][iVert] == SnappedToRefSegment &&
554 subjPointFlags[iPart][iRing][iPrev] != Unsnapped &&
555 subjPointFlags[iPart][iRing][iNext] != Unsnapped &&
556 QgsGeometryUtils::sqrDistance2D( QgsGeometryUtils::projectPointOnSegment( pMid, pPrev, pNext ), pMid ) < 1E-12 )
557 {
558 if ( ( ringIsClosed && nVerts > 3 ) || ( !ringIsClosed && nVerts > 2 ) )
559 {
560 subjGeom->deleteVertex( QgsVertexId( iPart, iRing, iVert ) );
561 subjPointFlags[iPart][iRing].removeAt( iVert );
562 iVert -= 1;
563 nVerts -= 1;
564 }
565 else
566 {
567 // Don't delete vertices if this would result in a degenerate geometry
568 break;
569 }
570 }
571 }
572 }
573 }
574
575 QgsGeometry result( subjGeom );
576 result.removeDuplicateNodes();
577 return result;
578}
579
580int QgsGeometrySnapper::polyLineSize( const QgsAbstractGeometry *geom, int iPart, int iRing )
581{
582 const int nVerts = geom->vertexCount( iPart, iRing );
583
584 if ( qgsgeometry_cast< const QgsSurface * >( geom ) || qgsgeometry_cast< const QgsMultiSurface * >( geom ) )
585 {
586 const QgsPoint front = geom->vertexAt( QgsVertexId( iPart, iRing, 0 ) );
587 const QgsPoint back = geom->vertexAt( QgsVertexId( iPart, iRing, nVerts - 1 ) );
588 if ( front == back )
589 return nVerts - 1;
590 }
591
592 return nVerts;
593}
594
595
596
597
598
599//
600// QgsInternalGeometrySnapper
601//
602
604 : mSnapTolerance( snapTolerance )
605 , mMode( mode )
606{}
607
609{
610 if ( !feature.hasGeometry() )
611 return QgsGeometry();
612
613 QgsFeature feat = feature;
614 QgsGeometry geometry = feat.geometry();
615 if ( !mFirstFeature )
616 {
617 // snap against processed geometries
618 // Get potential reference features and construct snap index
619 QgsRectangle searchBounds = geometry.boundingBox();
620 searchBounds.grow( mSnapTolerance );
621 const QgsFeatureIds refFeatureIds = qgis::listToSet( mProcessedIndex.intersects( searchBounds ) );
622 if ( !refFeatureIds.isEmpty() )
623 {
624 QList< QgsGeometry > refGeometries;
625 const auto constRefFeatureIds = refFeatureIds;
626 for ( const QgsFeatureId id : constRefFeatureIds )
627 {
628 refGeometries << mProcessedGeometries.value( id );
629 }
630
631 geometry = QgsGeometrySnapper::snapGeometry( geometry, mSnapTolerance, refGeometries, mMode );
632 }
633 }
634 mProcessedGeometries.insert( feat.id(), geometry );
635 mProcessedIndex.addFeature( feat );
636 mFirstFeature = false;
637 return geometry;
638}
639
@ Polygon
Polygons.
Abstract base class for all geometries.
virtual int ringCount(int part=0) const =0
Returns the number of rings of which this geometry is built.
virtual bool moveVertex(QgsVertexId position, const QgsPoint &newPos)=0
Moves a vertex within the geometry.
virtual int vertexCount(int part=0, int ring=0) const =0
Returns the number of vertices of which this geometry is built.
virtual QgsRectangle boundingBox() const
Returns the minimal bounding box for the geometry.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
virtual bool insertVertex(QgsVertexId position, const QgsPoint &vertex)=0
Inserts a vertex into the geometry.
virtual int partCount() const =0
Returns count of parts contained in the geometry.
virtual bool deleteVertex(QgsVertexId position)=0
Deletes a vertex within the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
Abstract base class for curved geometry type.
Definition qgscurve.h:35
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.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
An interface for objects which provide features via a getFeatures method.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
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
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
void featureSnapped()
Emitted each time a feature has been processed when calling snapFeatures()
QgsFeatureList snapFeatures(const QgsFeatureList &features, double snapTolerance, SnapMode mode=PreferNodes)
Snaps a set of features to the reference layer and returns the result.
QgsGeometry snapGeometry(const QgsGeometry &geometry, double snapTolerance, SnapMode mode=PreferNodes) const
Snaps a geometry to the reference layer and returns the result.
SnapMode
Snapping modes.
@ EndPointPreferClosest
Only snap start/end points of lines (point features will also be snapped, polygon features will not b...
@ PreferClosestNoExtraVertices
Snap to closest point, regardless of it is a node or a segment. No new nodes will be inserted.
@ EndPointPreferNodes
Only snap start/end points of lines (point features will also be snapped, polygon features will not b...
@ PreferNodes
Prefer to snap to nodes, even when a segment may be closer than a node. New nodes will be inserted to...
@ PreferClosest
Snap to closest point, regardless of it is a node or a segment. New nodes will be inserted to make ge...
@ EndPointToEndPoint
Only snap the start/end points of lines to other start/end points of lines.
@ PreferNodesNoExtraVertices
Prefer to snap to nodes, even when a segment may be closer than a node. No new nodes will be inserted...
QgsGeometrySnapper(QgsFeatureSource *referenceSource)
Constructor for QgsGeometrySnapper.
static double sqrDistToLine(double ptX, double ptY, double x1, double y1, double x2, double y2, double &minDistX, double &minDistY, double epsilon)
Returns the squared distance between a point and a line.
static QgsPoint projectPointOnSegment(const QgsPoint &p, const QgsPoint &s1, const QgsPoint &s2)
Project the point on a segment.
static Q_DECL_DEPRECATED double sqrDistance2D(double x1, double y1, double x2, double y2)
Returns the squared 2D distance between (x1, y1) and (x2, y2).
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.
bool removeDuplicateNodes(double epsilon=4 *std::numeric_limits< double >::epsilon(), bool useZValues=false)
Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerat...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static GEOSContextHandle_t get()
Returns a thread local instance of a GEOS context, safe for use in the current thread.
QgsInternalGeometrySnapper(double snapTolerance, QgsGeometrySnapper::SnapMode mode=QgsGeometrySnapper::PreferNodes)
Constructor for QgsInternalGeometrySnapper.
QgsGeometry snapFeature(const QgsFeature &feature)
Snaps a single feature's geometry against all feature geometries already processed by calls to snapFe...
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
QgsPoint vertexAt(QgsVertexId) const override
Returns the point corresponding to a specified vertex id.
Definition qgspoint.cpp:527
double x
Definition qgspoint.h:52
double distanceSquared(double x, double y) const
Returns the Cartesian 2D squared distance between this point a specified x, y coordinate.
Definition qgspoint.h:415
double y
Definition qgspoint.h:53
A rectangle specified with double values.
QgsPointXY center() const
Returns the center point of the rectangle.
void grow(double delta)
Grows the rectangle in place by the specified amount.
A spatial index for QgsFeature objects.
QList< QgsFeatureId > intersects(const QgsRectangle &rectangle) const
Returns a list of features with a bounding box which intersects the specified rectangle.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a feature to the index.
A class to represent a vector.
Definition qgsvector.h:30
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:5958
QList< QgsFeature > QgsFeatureList
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
void _GEOSQueryCallback(void *item, void *userdata)
QLineF segment(int index, QRectF rect, double radius)
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30
QList< const QgsPointCloudLayerProfileResults::PointResult * > * list