QGIS API Documentation 3.99.0-Master (26c88405ac0)
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 "qgsgeometrysnapper.h"
18
19#include <geos_c.h>
20#include <memory>
21
22#include "qgscurve.h"
23#include "qgsfeatureiterator.h"
24#include "qgsgeometry.h"
25#include "qgsgeometryutils.h"
26#include "qgsmultisurface.h"
27#include "qgssurface.h"
29#include "qgsvectorlayer.h"
30
31#include <QtConcurrentMap>
32
33#include "moc_qgsgeometrysnapper.cpp"
34
36
37QgsSnapIndex::PointSnapItem::PointSnapItem( const QgsSnapIndex::CoordIdx *_idx, bool isEndPoint )
38 : SnapItem( isEndPoint ? QgsSnapIndex::SnapEndPoint : QgsSnapIndex::SnapPoint )
39 , idx( _idx )
40{}
41
42QgsPoint QgsSnapIndex::PointSnapItem::getSnapPoint( const QgsPoint & /*p*/ ) const
43{
44 return idx->point();
45}
46
47QgsSnapIndex::SegmentSnapItem::SegmentSnapItem( const QgsSnapIndex::CoordIdx *_idxFrom, const QgsSnapIndex::CoordIdx *_idxTo )
48 : SnapItem( QgsSnapIndex::SnapSegment )
49 , idxFrom( _idxFrom )
50 , idxTo( _idxTo )
51{}
52
53QgsPoint QgsSnapIndex::SegmentSnapItem::getSnapPoint( const QgsPoint &p ) const
54{
55 return QgsGeometryUtils::projectPointOnSegment( p, idxFrom->point(), idxTo->point() );
56}
57
58bool QgsSnapIndex::SegmentSnapItem::getIntersection( const QgsPoint &p1, const QgsPoint &p2, QgsPoint &inter ) const
59{
60 const QgsPoint &q1 = idxFrom->point(), &q2 = idxTo->point();
61 QgsVector v( p2.x() - p1.x(), p2.y() - p1.y() );
62 QgsVector w( q2.x() - q1.x(), q2.y() - q1.y() );
63 const double vl = v.length();
64 const double wl = w.length();
65
66 if ( qgsDoubleNear( vl, 0, 0.000000000001 ) || qgsDoubleNear( wl, 0, 0.000000000001 ) )
67 {
68 return false;
69 }
70 v = v / vl;
71 w = w / wl;
72
73 const double d = v.y() * w.x() - v.x() * w.y();
74
75 if ( d == 0 )
76 return false;
77
78 const double dx = q1.x() - p1.x();
79 const double dy = q1.y() - p1.y();
80 const double k = ( dy * w.x() - dx * w.y() ) / d;
81
82 inter = QgsPoint( p1.x() + v.x() * k, p1.y() + v.y() * k );
83
84 const double lambdav = QgsVector( inter.x() - p1.x(), inter.y() - p1.y() ) * v;
85 if ( lambdav < 0. + 1E-8 || lambdav > vl - 1E-8 )
86 return false;
87
88 const double lambdaw = QgsVector( inter.x() - q1.x(), inter.y() - q1.y() ) * w;
89 return !( lambdaw < 0. + 1E-8 || lambdaw >= wl - 1E-8 );
90}
91
92bool QgsSnapIndex::SegmentSnapItem::getProjection( const QgsPoint &p, QgsPoint &pProj ) const
93{
94 const QgsPoint &s1 = idxFrom->point();
95 const QgsPoint &s2 = idxTo->point();
96 const double nx = s2.y() - s1.y();
97 const double ny = -( s2.x() - s1.x() );
98 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 );
99 if ( t < 0. || t > 1. )
100 {
101 return false;
102 }
103 pProj = QgsPoint( s1.x() + ( s2.x() - s1.x() ) * t, s1.y() + ( s2.y() - s1.y() ) * t );
104 return true;
105}
106
107bool QgsSnapIndex::SegmentSnapItem::withinSquaredDistance( const QgsPoint &p, const double squaredDistance )
108{
109 double minDistX, minDistY;
110 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;
111}
112
114
115QgsSnapIndex::QgsSnapIndex()
116{
117 mSTRTree = GEOSSTRtree_create_r( QgsGeosContext::get(), ( size_t ) 10 );
118}
119
120QgsSnapIndex::~QgsSnapIndex()
121{
122 qDeleteAll( mCoordIdxs );
123 qDeleteAll( mSnapItems );
124
125 GEOSSTRtree_destroy_r( QgsGeosContext::get(), mSTRTree );
126}
127
128void QgsSnapIndex::addPoint( const CoordIdx *idx, bool isEndPoint )
129{
130 const QgsPoint p = idx->point();
131
132 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
133 geos::unique_ptr point( GEOSGeom_createPointFromXY_r( geosctxt, p.x(), p.y() ) );
134
135 PointSnapItem *item = new PointSnapItem( idx, isEndPoint );
136 GEOSSTRtree_insert_r( geosctxt, mSTRTree, point.get(), item );
137 mSnapItems << item;
138}
139
140void QgsSnapIndex::addSegment( const CoordIdx *idxFrom, const CoordIdx *idxTo )
141{
142 const QgsPoint pointFrom = idxFrom->point();
143 const QgsPoint pointTo = idxTo->point();
144
145 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
146
147 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
148 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pointFrom.x(), pointFrom.y() );
149 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pointTo.x(), pointTo.y() );
150 geos::unique_ptr segment( GEOSGeom_createLineString_r( geosctxt, coord ) );
151
152 SegmentSnapItem *item = new SegmentSnapItem( idxFrom, idxTo );
153 GEOSSTRtree_insert_r( geosctxt, mSTRTree, segment.get(), item );
154 mSnapItems << item;
155}
156
157void QgsSnapIndex::addGeometry( const QgsAbstractGeometry *geom )
158{
159 for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart )
160 {
161 for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing )
162 {
163 int nVerts = geom->vertexCount( iPart, iRing );
164
166 nVerts--;
167 else if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( geom ) )
168 {
169 if ( curve->isClosed() )
170 nVerts--;
171 }
172
173 for ( int iVert = 0; iVert < nVerts; ++iVert )
174 {
175 CoordIdx *idx = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert ) );
176 CoordIdx *idx1 = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert + 1 ) );
177 mCoordIdxs.append( idx );
178 mCoordIdxs.append( idx1 );
179 addPoint( idx, iVert == 0 || iVert == nVerts - 1 );
180 if ( iVert < nVerts - 1 )
181 addSegment( idx, idx1 );
182 }
183 }
184 }
185}
186
188{
189 QList<QgsSnapIndex::SnapItem *> *list;
190};
191
192void _GEOSQueryCallback( void *item, void *userdata )
193{
194 reinterpret_cast<_GEOSQueryCallbackData *>( userdata )->list->append( static_cast<QgsSnapIndex::SnapItem *>( item ) );
195}
196
197QgsPoint QgsSnapIndex::getClosestSnapToPoint( const QgsPoint &startPoint, const QgsPoint &midPoint )
198{
199 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
200
201 // Look for intersections on segment from the target point to the point opposite to the point reference point
202 // p2 = p1 + 2 * (q - p1)
203 const QgsPoint endPoint( 2 * midPoint.x() - startPoint.x(), 2 * midPoint.y() - startPoint.y() );
204
205 QgsPoint minPoint = startPoint;
206 double minDistance = std::numeric_limits<double>::max();
207
208 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
209 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, startPoint.x(), startPoint.y() );
210 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, endPoint.x(), endPoint.y() );
211 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
212
213 QList<SnapItem *> items;
214 struct _GEOSQueryCallbackData callbackData;
215 callbackData.list = &items;
216 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(), _GEOSQueryCallback, &callbackData );
217 for ( const SnapItem *item : std::as_const( items ) )
218 {
219 if ( item->type == SnapSegment )
220 {
221 QgsPoint inter;
222 if ( static_cast<const SegmentSnapItem *>( item )->getIntersection( startPoint, endPoint, inter ) )
223 {
224 const double dist = QgsGeometryUtils::sqrDistance2D( midPoint, inter );
225 if ( dist < minDistance )
226 {
227 minDistance = dist;
228 minPoint = inter;
229 }
230 }
231 }
232 }
233
234 return minPoint;
235}
236
237QgsSnapIndex::SnapItem *QgsSnapIndex::getSnapItem( const QgsPoint &pos, const double tolerance, QgsSnapIndex::PointSnapItem **pSnapPoint, QgsSnapIndex::SegmentSnapItem **pSnapSegment, bool endPointOnly ) const
238{
239 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
240
241 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
242 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pos.x() - tolerance, pos.y() - tolerance );
243 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pos.x() + tolerance, pos.y() + tolerance );
244
245 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
246
247 QList<SnapItem *> items;
248 struct _GEOSQueryCallbackData callbackData;
249 callbackData.list = &items;
250 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(), _GEOSQueryCallback, &callbackData );
251
252 double minDistSegment = std::numeric_limits<double>::max();
253 double minDistPoint = std::numeric_limits<double>::max();
254 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
255 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
256
257 const double squaredTolerance = tolerance * tolerance;
258 const auto constItems = items;
259 for ( QgsSnapIndex::SnapItem *item : constItems )
260 {
261 if ( ( !endPointOnly && item->type == SnapPoint ) || item->type == SnapEndPoint )
262 {
263 const double dist = QgsGeometryUtils::sqrDistance2D( item->getSnapPoint( pos ), pos );
264 if ( dist < minDistPoint )
265 {
266 minDistPoint = dist;
267 snapPoint = static_cast<PointSnapItem *>( item );
268 }
269 }
270 else if ( item->type == SnapSegment && !endPointOnly )
271 {
272 if ( !static_cast<SegmentSnapItem *>( item )->withinSquaredDistance( pos, squaredTolerance ) )
273 continue;
274
275 QgsPoint pProj;
276 if ( !static_cast<SegmentSnapItem *>( item )->getProjection( pos, pProj ) )
277 continue;
278
279 const double dist = QgsGeometryUtils::sqrDistance2D( pProj, pos );
280 if ( dist < minDistSegment )
281 {
282 minDistSegment = dist;
283 snapSegment = static_cast<SegmentSnapItem *>( item );
284 }
285 }
286 }
287 snapPoint = minDistPoint < squaredTolerance ? snapPoint : nullptr;
288 snapSegment = minDistSegment < squaredTolerance ? snapSegment : nullptr;
289 if ( pSnapPoint )
290 *pSnapPoint = snapPoint;
291 if ( pSnapSegment )
292 *pSnapSegment = snapSegment;
293 return minDistPoint < minDistSegment ? static_cast<QgsSnapIndex::SnapItem *>( snapPoint ) : static_cast<QgsSnapIndex::SnapItem *>( snapSegment );
294}
295
297
298
299//
300// QgsGeometrySnapper
301//
302
304 : mReferenceSource( referenceSource )
305{
306 // Build spatial index
307 mIndex = QgsSpatialIndex( *mReferenceSource );
308}
309
310QgsFeatureList QgsGeometrySnapper::snapFeatures( const QgsFeatureList &features, double snapTolerance, SnapMode mode )
311{
312 QgsFeatureList list = features;
313 QtConcurrent::blockingMap( list, ProcessFeatureWrapper( this, snapTolerance, mode ) );
314 return list;
315}
316
317void QgsGeometrySnapper::processFeature( QgsFeature &feature, double snapTolerance, SnapMode mode )
318{
319 if ( !feature.geometry().isNull() )
320 feature.setGeometry( snapGeometry( feature.geometry(), snapTolerance, mode ) );
321 emit featureSnapped();
322}
323
324QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry &geometry, double snapTolerance, SnapMode mode ) const
325{
326 // Get potential reference features and construct snap index
327 QList<QgsGeometry> refGeometries;
328 mIndexMutex.lock();
329 QgsRectangle searchBounds = geometry.boundingBox();
330 searchBounds.grow( snapTolerance );
331 const QgsFeatureIds refFeatureIds = qgis::listToSet( mIndex.intersects( searchBounds ) );
332 mIndexMutex.unlock();
333
334 if ( refFeatureIds.isEmpty() )
335 return QgsGeometry( geometry );
336
337 refGeometries.reserve( refFeatureIds.size() );
338 QgsFeatureIds missingFeatureIds;
339 const QgsFeatureIds cachedIds = qgis::listToSet( mCachedReferenceGeometries.keys() );
340 for ( const QgsFeatureId id : refFeatureIds )
341 {
342 if ( cachedIds.contains( id ) )
343 {
344 refGeometries.append( mCachedReferenceGeometries[id] );
345 }
346 else
347 {
348 missingFeatureIds << id;
349 }
350 }
351
352 if ( missingFeatureIds.size() > 0 )
353 {
354 mReferenceLayerMutex.lock();
355 const QgsFeatureRequest refFeatureRequest = QgsFeatureRequest().setFilterFids( missingFeatureIds ).setNoAttributes();
356 QgsFeatureIterator refFeatureIt = mReferenceSource->getFeatures( refFeatureRequest );
357 QgsFeature refFeature;
358 while ( refFeatureIt.nextFeature( refFeature ) )
359 {
360 refGeometries.append( refFeature.geometry() );
361 }
362 mReferenceLayerMutex.unlock();
363 }
364
365 return snapGeometry( geometry, snapTolerance, refGeometries, mode );
366}
367
368QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry &geometry, double snapTolerance, const QList<QgsGeometry> &referenceGeometries, QgsGeometrySnapper::SnapMode mode )
369{
371 return geometry;
372
373 const QgsPoint center = qgsgeometry_cast<const QgsPoint *>( geometry.constGet() ) ? *static_cast<const QgsPoint *>( geometry.constGet() ) : QgsPoint( geometry.constGet()->boundingBox().center() );
374
375 QgsSnapIndex refSnapIndex;
376 for ( const QgsGeometry &geom : referenceGeometries )
377 {
378 refSnapIndex.addGeometry( geom.constGet() );
379 }
380
381 // Snap geometries
382 QgsAbstractGeometry *subjGeom = geometry.constGet()->clone();
383 QList<QList<QList<PointFlag>>> subjPointFlags;
384
385 // Pass 1: snap vertices of subject geometry to reference vertices
386 for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart )
387 {
388 subjPointFlags.append( QList<QList<PointFlag>>() );
389
390 for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing )
391 {
392 subjPointFlags[iPart].append( QList<PointFlag>() );
393
394 for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
395 {
396 if ( ( mode == EndPointPreferClosest || mode == EndPointPreferNodes || mode == EndPointToEndPoint ) && QgsWkbTypes::geometryType( subjGeom->wkbType() ) == Qgis::GeometryType::Line && ( iVert > 0 && iVert < nVerts - 1 ) )
397 {
398 //endpoint mode and not at an endpoint, skip
399 subjPointFlags[iPart][iRing].append( Unsnapped );
400 continue;
401 }
402
403 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
404 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
405 const QgsVertexId vidx( iPart, iRing, iVert );
406 const QgsPoint p = subjGeom->vertexAt( vidx );
407 if ( !refSnapIndex.getSnapItem( p, snapTolerance, &snapPoint, &snapSegment, mode == EndPointToEndPoint ) )
408 {
409 subjPointFlags[iPart][iRing].append( Unsnapped );
410 }
411 else
412 {
413 switch ( mode )
414 {
415 case PreferNodes:
419 {
420 // Prefer snapping to point
421 if ( snapPoint )
422 {
423 subjGeom->moveVertex( vidx, snapPoint->getSnapPoint( p ) );
424 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
425 }
426 else if ( snapSegment )
427 {
428 subjGeom->moveVertex( vidx, snapSegment->getSnapPoint( p ) );
429 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
430 }
431 break;
432 }
433
434 case PreferClosest:
437 {
438 QgsPoint nodeSnap, segmentSnap;
439 double distanceNode = std::numeric_limits<double>::max();
440 double distanceSegment = std::numeric_limits<double>::max();
441 if ( snapPoint )
442 {
443 nodeSnap = snapPoint->getSnapPoint( p );
444 distanceNode = nodeSnap.distanceSquared( p );
445 }
446 if ( snapSegment )
447 {
448 segmentSnap = snapSegment->getSnapPoint( p );
449 distanceSegment = segmentSnap.distanceSquared( p );
450 }
451 if ( snapPoint && distanceNode < distanceSegment )
452 {
453 subjGeom->moveVertex( vidx, nodeSnap );
454 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
455 }
456 else if ( snapSegment )
457 {
458 subjGeom->moveVertex( vidx, segmentSnap );
459 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
460 }
461 break;
462 }
463 }
464 }
465 }
466 }
467 }
468
469 // no extra vertices to add for point geometry
470 if ( qgsgeometry_cast<const QgsPoint *>( subjGeom ) )
471 return QgsGeometry( subjGeom );
472
473 // nor for no extra vertices modes and end point only snapping
475 {
476 QgsGeometry result( subjGeom );
477 result.removeDuplicateNodes();
478 return result;
479 }
480
481 auto subjSnapIndex = std::make_unique<QgsSnapIndex>();
482 subjSnapIndex->addGeometry( subjGeom );
483
484 std::unique_ptr<QgsAbstractGeometry> origSubjGeom( subjGeom->clone() );
485 auto origSubjSnapIndex = std::make_unique<QgsSnapIndex>();
486 origSubjSnapIndex->addGeometry( origSubjGeom.get() );
487
488 // Pass 2: add missing vertices to subject geometry
489 for ( const QgsGeometry &refGeom : referenceGeometries )
490 {
491 for ( int iPart = 0, nParts = refGeom.constGet()->partCount(); iPart < nParts; ++iPart )
492 {
493 for ( int iRing = 0, nRings = refGeom.constGet()->ringCount( iPart ); iRing < nRings; ++iRing )
494 {
495 for ( int iVert = 0, nVerts = polyLineSize( refGeom.constGet(), iPart, iRing ); iVert < nVerts; ++iVert )
496 {
497 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
498 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
499 const QgsPoint point = refGeom.constGet()->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
500 if ( subjSnapIndex->getSnapItem( point, snapTolerance, &snapPoint, &snapSegment ) )
501 {
502 // Snap to segment, unless a subject point was already snapped to the reference point
503 if ( snapPoint )
504 {
505 const QgsPoint snappedPoint = snapPoint->getSnapPoint( point );
506 if ( QgsGeometryUtils::sqrDistance2D( snappedPoint, point ) < 1E-16 )
507 continue;
508 }
509
510 if ( snapSegment )
511 {
512 // Look if there is a closer reference segment, if so, ignore this point
513 const QgsPoint pProj = snapSegment->getSnapPoint( point );
514 const QgsPoint closest = refSnapIndex.getClosestSnapToPoint( point, pProj );
515 if ( QgsGeometryUtils::sqrDistance2D( pProj, point ) > QgsGeometryUtils::sqrDistance2D( pProj, closest ) )
516 {
517 continue;
518 }
519
520 // If we are too far away from the original geometry, do nothing
521 if ( !origSubjSnapIndex->getSnapItem( point, snapTolerance ) )
522 {
523 continue;
524 }
525
526 const QgsSnapIndex::CoordIdx *idx = snapSegment->idxFrom;
527 subjGeom->insertVertex( QgsVertexId( idx->vidx.part, idx->vidx.ring, idx->vidx.vertex + 1 ), point );
528 subjPointFlags[idx->vidx.part][idx->vidx.ring].insert( idx->vidx.vertex + 1, SnappedToRefNode );
529 subjSnapIndex = std::make_unique<QgsSnapIndex>();
530 subjSnapIndex->addGeometry( subjGeom );
531 }
532 }
533 }
534 }
535 }
536 }
537 subjSnapIndex.reset();
538 origSubjSnapIndex.reset();
539 origSubjGeom.reset();
540
541 // Pass 3: remove superfluous vertices: all vertices which are snapped to a segment and not preceded or succeeded by an unsnapped vertex
542 for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart )
543 {
544 for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing )
545 {
546 const bool ringIsClosed = subjGeom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ) == subjGeom->vertexAt( QgsVertexId( iPart, iRing, subjGeom->vertexCount( iPart, iRing ) - 1 ) );
547 for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
548 {
549 const int iPrev = ( iVert - 1 + nVerts ) % nVerts;
550 const int iNext = ( iVert + 1 ) % nVerts;
551 const QgsPoint pMid = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
552 const QgsPoint pPrev = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iPrev ) );
553 const QgsPoint pNext = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iNext ) );
554
555 if ( subjPointFlags[iPart][iRing][iVert] == SnappedToRefSegment && subjPointFlags[iPart][iRing][iPrev] != Unsnapped && subjPointFlags[iPart][iRing][iNext] != Unsnapped && QgsGeometryUtils::sqrDistance2D( QgsGeometryUtils::projectPointOnSegment( pMid, pPrev, pNext ), pMid ) < 1E-12 )
556 {
557 if ( ( ringIsClosed && nVerts > 3 ) || ( !ringIsClosed && nVerts > 2 ) )
558 {
559 subjGeom->deleteVertex( QgsVertexId( iPart, iRing, iVert ) );
560 subjPointFlags[iPart][iRing].removeAt( iVert );
561 iVert -= 1;
562 nVerts -= 1;
563 }
564 else
565 {
566 // Don't delete vertices if this would result in a degenerate geometry
567 break;
568 }
569 }
570 }
571 }
572 }
573
574 QgsGeometry result( subjGeom );
575 result.removeDuplicateNodes();
576 return result;
577}
578
579int QgsGeometrySnapper::polyLineSize( const QgsAbstractGeometry *geom, int iPart, int iRing )
580{
581 const int nVerts = geom->vertexCount( iPart, iRing );
582
584 {
585 const QgsPoint front = geom->vertexAt( QgsVertexId( iPart, iRing, 0 ) );
586 const QgsPoint back = geom->vertexAt( QgsVertexId( iPart, iRing, nVerts - 1 ) );
587 if ( front == back )
588 return nVerts - 1;
589 }
590
591 return nVerts;
592}
593
594
595//
596// QgsInternalGeometrySnapper
597//
598
600 : mSnapTolerance( snapTolerance )
601 , mMode( mode )
602{}
603
605{
606 if ( !feature.hasGeometry() )
607 return QgsGeometry();
608
609 QgsFeature feat = feature;
610 QgsGeometry geometry = feat.geometry();
611 if ( !mFirstFeature )
612 {
613 // snap against processed geometries
614 // Get potential reference features and construct snap index
615 QgsRectangle searchBounds = geometry.boundingBox();
616 searchBounds.grow( mSnapTolerance );
617 const QgsFeatureIds refFeatureIds = qgis::listToSet( mProcessedIndex.intersects( searchBounds ) );
618 if ( !refFeatureIds.isEmpty() )
619 {
620 QList<QgsGeometry> refGeometries;
621 const auto constRefFeatureIds = refFeatureIds;
622 for ( const QgsFeatureId id : constRefFeatureIds )
623 {
624 refGeometries << mProcessedGeometries.value( id );
625 }
626
627 geometry = QgsGeometrySnapper::snapGeometry( geometry, mSnapTolerance, refGeometries, mMode );
628 }
629 }
630 mProcessedGeometries.insert( feat.id(), geometry );
631 mProcessedIndex.addFeature( feat );
632 mFirstFeature = false;
633 return geometry;
634}
@ Line
Lines.
Definition qgis.h:360
@ Polygon
Polygons.
Definition qgis.h:361
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:36
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 & 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.
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:530
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:409
double y
Definition qgspoint.h:53
A rectangle specified with double values.
void grow(double delta)
Grows the rectangle in place by the specified amount.
QgsPointXY center
A spatial index for QgsFeature objects.
Represent a 2-dimensional vector.
Definition qgsvector.h:31
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...
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition qgsgeos.h:114
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6607
T qgsgeometry_cast(QgsAbstractGeometry *geom)
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