QGIS API Documentation 4.5.0-Master (3b5d115045b)
Loading...
Searching...
No Matches
qgsgeos.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgeos.cpp
3 -------------------------------------------------------------------
4Date : 22 Sept 2014
5Copyright : (C) 2014 by Marco Hugentobler
6email : marco.hugentobler at sourcepole dot com
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
16#include "qgsgeos.h"
17
18#include <cstdio>
19#include <limits>
20#include <memory>
21
22#include "qgsabstractgeometry.h"
23#include "qgscircularstring.h"
24#include "qgsfeedback.h"
27#include "qgsgeometryfactory.h"
29#include "qgslinestring.h"
30#include "qgslogger.h"
31#include "qgsmulticurve.h"
32#include "qgsmultilinestring.h"
33#include "qgsmultipoint.h"
34#include "qgsmultipolygon.h"
35#include "qgspolygon.h"
38#include "qgssettingstree.h"
39
40#include <QString>
41
42using namespace Qt::StringLiterals;
43
44#define DEFAULT_QUADRANT_SEGMENTS 8
45
46#define CATCH_GEOS( r ) \
47 catch ( QgsGeosException & ) \
48 { \
49 return r; \
50 }
51
52#define CATCH_GEOS_WITH_ERRMSG( r ) \
53 catch ( QgsGeosException & e ) \
54 { \
55 if ( errorMsg ) \
56 { \
57 *errorMsg = e.what(); \
58 if ( errorMsg->startsWith( "InterruptedException"_L1, Qt::CaseInsensitive ) ) \
59 { \
60 errorMsg->clear(); \
61 } \
62 } \
63 return r; \
64 }
65
67
68static void throwQgsGeosException( const char *fmt, ... )
69{
70 va_list ap;
71 char buffer[1024];
72
73 va_start( ap, fmt );
74 vsnprintf( buffer, sizeof buffer, fmt, ap );
75 va_end( ap );
76
77 QString message = QString::fromUtf8( buffer );
78
79#ifdef _MSC_VER
80 // stupid stupid MSVC, *SOMETIMES* raises it's own exception if we throw QgsGeosException, resulting in a crash!
81 // see https://github.com/qgis/QGIS/issues/22709
82 // if you want to test alternative fixes for this, run the testqgsexpression.cpp test suite - that will crash
83 // and burn on the "line_interpolate_point point" test if a QgsGeosException is thrown.
84 // TODO - find a real fix for the underlying issue
85 try
86 {
87 throw QgsGeosException( message );
88 }
89 catch ( ... )
90 {
91 // oops, msvc threw an exception when we tried to throw the exception!
92 // just throw nothing instead (except your mouse at your monitor)
93 }
94#else
95 throw QgsGeosException( message );
96#endif
97}
98
99
100static void printGEOSNotice( const char *fmt, ... )
101{
102#if defined( QGISDEBUG )
103 va_list ap;
104 char buffer[1024];
105
106 va_start( ap, fmt );
107 vsnprintf( buffer, sizeof buffer, fmt, ap );
108 va_end( ap );
109#else
110 Q_UNUSED( fmt )
111#endif
112}
113
114//
115// QgsGeosContext
116//
117
118#if defined( USE_THREAD_LOCAL ) && !defined( Q_OS_WIN )
119thread_local QgsGeosContext QgsGeosContext::sGeosContext;
120#else
121QThreadStorage< QgsGeosContext * > QgsGeosContext::sGeosContext;
122#endif
123
124
126{
127 mContext = GEOS_init_r();
128 GEOSContext_setNoticeHandler_r( mContext, printGEOSNotice );
129 GEOSContext_setErrorHandler_r( mContext, throwQgsGeosException );
130
131#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
132 // Set CurveToLine and LineToCurve default params to the context.
133 // This ensures that if a GEOS method does not support curves, it will linearize
134 // any curve geometry input if needed, and will also convert any linear output
135 // to a curved type, if the inputs were converted to curves.
136 GEOSCurveToLineParams *curveToLineParams = GEOSCurveToLineParams_create();
137 GEOSContext_setCurveToLineParams_r( mContext, curveToLineParams );
138 GEOSCurveToLineParams_destroy( curveToLineParams );
139
140 // The second part of the conversion is managed by a hidden setting, so that
141 // we can enable/disable it at will to spot missing curve support in GEOS.
143 {
144 GEOSLineToCurveParams *lineToCurveParams = GEOSLineToCurveParams_create();
145 GEOSContext_setLineToCurveParams_r( mContext, lineToCurveParams );
146 GEOSLineToCurveParams_destroy( lineToCurveParams );
147 }
148#endif
149}
150
152{
153 GEOS_finish_r( mContext );
154}
155
156GEOSContextHandle_t QgsGeosContext::get()
157{
158#if defined( USE_THREAD_LOCAL ) && !defined( Q_OS_WIN )
159 return sGeosContext.mContext;
160#else
161 GEOSContextHandle_t gContext = nullptr;
162 if ( sGeosContext.hasLocalData() )
163 {
164 gContext = sGeosContext.localData()->mContext;
165 }
166 else
167 {
168 sGeosContext.setLocalData( new QgsGeosContext() );
169 gContext = sGeosContext.localData()->mContext;
170 }
171 return gContext;
172#endif
173}
174
175//
176// geos
177//
178
180{
181 GEOSGeom_destroy_r( QgsGeosContext::get(), geom );
182}
183
184void geos::GeosDeleter::operator()( const GEOSPreparedGeometry *geom ) const
185{
186 GEOSPreparedGeom_destroy_r( QgsGeosContext::get(), geom );
187}
188
189void geos::GeosDeleter::operator()( GEOSBufferParams *params ) const
190{
191 GEOSBufferParams_destroy_r( QgsGeosContext::get(), params );
192}
193
194void geos::GeosDeleter::operator()( GEOSCoordSequence *sequence ) const
195{
196 GEOSCoordSeq_destroy_r( QgsGeosContext::get(), sequence );
197}
198
200
201
202const QgsSettingsEntryBool *QgsGeos::settingLineToCurveParam
203 = new QgsSettingsEntryBool( u"line-to-curve-param"_s, QgsSettingsTree::sTreeGeos, false, u"Whether to convert any linear output of a GEOS method to a curved type, if the inputs were converted to curves."_s );
204
205QgsGeos::QgsGeos( const QgsAbstractGeometry *geometry, double precision, Qgis::GeosCreationFlags flags )
206 : QgsGeometryEngine( geometry )
207 , mGeos( nullptr )
208 , mPrecision( precision )
209{
210 cacheGeos( flags );
211}
212
214{
216 GEOSGeom_destroy_r( QgsGeosContext::get(), geos );
217 return g;
218}
219
225
226std::unique_ptr<QgsAbstractGeometry> QgsGeos::makeValid( Qgis::MakeValidMethod method, bool keepCollapsed, QString *errorMsg, QgsFeedback *feedback ) const
227{
228 if ( !mGeos )
229 {
230 return nullptr;
231 }
232
233 GEOSContextHandle_t context = QgsGeosContext::get();
234
235#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 10, 0 )
236 if ( method != Qgis::MakeValidMethod::Linework )
237 throw QgsNotSupportedException( QObject::tr( "The structured method to make geometries valid requires a QGIS build based on GEOS 3.10 or later" ) );
238
239 if ( keepCollapsed )
240 throw QgsNotSupportedException( QObject::tr( "The keep collapsed option for making geometries valid requires a QGIS build based on GEOS 3.10 or later" ) );
242 try
243 {
244 geos.reset( GEOSMakeValid_r( context, mGeos.get() ) );
245 }
246 CATCH_GEOS_WITH_ERRMSG( nullptr )
247#else
248
249 GEOSMakeValidParams *params = GEOSMakeValidParams_create_r( context );
250 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
251 switch ( method )
252 {
254 GEOSMakeValidParams_setMethod_r( context, params, GEOS_MAKE_VALID_LINEWORK );
255 break;
256
258 GEOSMakeValidParams_setMethod_r( context, params, GEOS_MAKE_VALID_STRUCTURE );
259 break;
260 }
261
262 GEOSMakeValidParams_setKeepCollapsed_r( context, params, keepCollapsed ? 1 : 0 );
263
265 try
266 {
267 geos.reset( GEOSMakeValidWithParams_r( context, mGeos.get(), params ) );
268 GEOSMakeValidParams_destroy_r( context, params );
269 }
270 catch ( QgsGeosException &e )
271 {
272 if ( errorMsg )
273 {
274 *errorMsg = e.what();
275 }
276 GEOSMakeValidParams_destroy_r( context, params );
277 return nullptr;
278 }
279#endif
280
281 return fromGeos( geos.get() );
282}
283
284geos::unique_ptr QgsGeos::asGeos( const QgsGeometry &geometry, double precision, Qgis::GeosCreationFlags flags )
285{
286 if ( geometry.isNull() )
287 {
288 return nullptr;
289 }
290
291 return asGeos( geometry.constGet(), precision, flags );
292}
293
295{
296 if ( geometry.isNull() )
297 {
299 }
300 if ( !newPart )
301 {
303 }
304
305 std::unique_ptr< QgsAbstractGeometry > geom = fromGeos( newPart );
306 return QgsGeometryEditUtils::addPart( geometry.get(), std::move( geom ) );
307}
308
310{
311 mGeos.reset();
312 mGeosPrepared.reset();
314}
315
317{
318 if ( mGeosPrepared )
319 {
320 // Already prepared
321 return;
322 }
323 if ( mGeos )
324 {
325#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
326 if ( mGeometry->hasCurvedSegments() )
327 {
328 // Segmentize the input until GEOSPrepare_r accepts curves
329 std::unique_ptr< QgsAbstractGeometry > segmentized( mGeometry->segmentize() );
330 mGeosPrepared.reset( GEOSPrepare_r( QgsGeosContext::get(), asGeos( segmentized.release() ).release() ) );
331 }
332 else
333 {
334#endif
335 mGeosPrepared.reset( GEOSPrepare_r( QgsGeosContext::get(), mGeos.get() ) );
336#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
337 }
338#endif
339 }
340}
341
342void QgsGeos::cacheGeos( Qgis::GeosCreationFlags flags ) const
343{
344 if ( mGeos )
345 {
346 // Already cached
347 return;
348 }
349 if ( !mGeometry )
350 {
351 return;
352 }
353
354 mGeos = asGeos( mGeometry, mPrecision, flags );
355}
356
357QgsAbstractGeometry *QgsGeos::intersection( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
358{
359 return overlay( geom, OverlayIntersection, errorMsg, parameters, feedback ).release();
360}
361
362QgsAbstractGeometry *QgsGeos::difference( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
363{
364 return overlay( geom, OverlayDifference, errorMsg, parameters, feedback ).release();
365}
366
367std::unique_ptr<QgsAbstractGeometry> QgsGeos::clip( const QgsRectangle &rect, QString *errorMsg, QgsFeedback *feedback ) const
368{
369 if ( !mGeos || rect.isNull() || rect.isEmpty() )
370 {
371 return nullptr;
372 }
373
374 try
375 {
376 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
377 geos::unique_ptr opGeom( GEOSClipByRect_r( QgsGeosContext::get(), mGeos.get(), rect.xMinimum(), rect.yMinimum(), rect.xMaximum(), rect.yMaximum() ) );
378 return fromGeos( opGeom.get() );
379 }
380 catch ( QgsGeosException &e )
381 {
382 logError( u"GEOS"_s, e.what() );
383 if ( errorMsg )
384 {
385 *errorMsg = e.what();
386 }
387 return nullptr;
388 }
389}
390
391void QgsGeos::subdivideRecursive( const GEOSGeometry *currentPart, int maxNodes, int depth, QgsGeometryCollection *parts, const QgsRectangle &clipRect, double gridSize ) const
392{
393 GEOSContextHandle_t context = QgsGeosContext::get();
394 int partType = GEOSGeomTypeId_r( context, currentPart );
395 if ( qgsDoubleNear( clipRect.width(), 0.0 ) && qgsDoubleNear( clipRect.height(), 0.0 ) )
396 {
397 if ( partType == GEOS_POINT )
398 {
399 parts->addGeometry( fromGeos( currentPart ).release() );
400 return;
401 }
402 else
403 {
404 return;
405 }
406 }
407
408 if ( partType == GEOS_MULTILINESTRING || partType == GEOS_MULTIPOLYGON || partType == GEOS_GEOMETRYCOLLECTION )
409 {
410 int partCount = GEOSGetNumGeometries_r( context, currentPart );
411 for ( int i = 0; i < partCount; ++i )
412 {
413 subdivideRecursive( GEOSGetGeometryN_r( context, currentPart, i ), maxNodes, depth, parts, clipRect, gridSize );
414 }
415 return;
416 }
417
418 if ( depth > 50 )
419 {
420 parts->addGeometry( fromGeos( currentPart ).release() );
421 return;
422 }
423
424 int vertexCount = GEOSGetNumCoordinates_r( context, currentPart );
425 if ( vertexCount == 0 )
426 {
427 return;
428 }
429 else if ( vertexCount < maxNodes )
430 {
431 parts->addGeometry( fromGeos( currentPart ).release() );
432 return;
433 }
434
435 // chop clipping rect in half by longest side
436 double width = clipRect.width();
437 double height = clipRect.height();
438 QgsRectangle halfClipRect1 = clipRect;
439 QgsRectangle halfClipRect2 = clipRect;
440 if ( width > height )
441 {
442 halfClipRect1.setXMaximum( clipRect.xMinimum() + width / 2.0 );
443 halfClipRect2.setXMinimum( halfClipRect1.xMaximum() );
444 }
445 else
446 {
447 halfClipRect1.setYMaximum( clipRect.yMinimum() + height / 2.0 );
448 halfClipRect2.setYMinimum( halfClipRect1.yMaximum() );
449 }
450
451 if ( height <= 0 )
452 {
453 halfClipRect1.setYMinimum( halfClipRect1.yMinimum() - std::numeric_limits<double>::epsilon() );
454 halfClipRect2.setYMinimum( halfClipRect2.yMinimum() - std::numeric_limits<double>::epsilon() );
455 halfClipRect1.setYMaximum( halfClipRect1.yMaximum() + std::numeric_limits<double>::epsilon() );
456 halfClipRect2.setYMaximum( halfClipRect2.yMaximum() + std::numeric_limits<double>::epsilon() );
457 }
458 if ( width <= 0 )
459 {
460 halfClipRect1.setXMinimum( halfClipRect1.xMinimum() - std::numeric_limits<double>::epsilon() );
461 halfClipRect2.setXMinimum( halfClipRect2.xMinimum() - std::numeric_limits<double>::epsilon() );
462 halfClipRect1.setXMaximum( halfClipRect1.xMaximum() + std::numeric_limits<double>::epsilon() );
463 halfClipRect2.setXMaximum( halfClipRect2.xMaximum() + std::numeric_limits<double>::epsilon() );
464 }
465
466 geos::unique_ptr clipPart1( GEOSClipByRect_r( context, currentPart, halfClipRect1.xMinimum(), halfClipRect1.yMinimum(), halfClipRect1.xMaximum(), halfClipRect1.yMaximum() ) );
467 geos::unique_ptr clipPart2( GEOSClipByRect_r( context, currentPart, halfClipRect2.xMinimum(), halfClipRect2.yMinimum(), halfClipRect2.xMaximum(), halfClipRect2.yMaximum() ) );
468
469 ++depth;
470
471 if ( clipPart1 )
472 {
473 if ( gridSize > 0 )
474 {
475 clipPart1.reset( GEOSIntersectionPrec_r( context, mGeos.get(), clipPart1.get(), gridSize ) );
476 }
477 subdivideRecursive( clipPart1.get(), maxNodes, depth, parts, halfClipRect1, gridSize );
478 }
479 if ( clipPart2 )
480 {
481 if ( gridSize > 0 )
482 {
483 clipPart2.reset( GEOSIntersectionPrec_r( context, mGeos.get(), clipPart2.get(), gridSize ) );
484 }
485 subdivideRecursive( clipPart2.get(), maxNodes, depth, parts, halfClipRect2, gridSize );
486 }
487}
488
489std::unique_ptr<QgsAbstractGeometry> QgsGeos::subdivide( int maxNodes, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
490{
491 if ( !mGeos )
492 {
493 return nullptr;
494 }
495
496 // minimum allowed max is 8
497 maxNodes = std::max( maxNodes, 8 );
498
499 std::unique_ptr< QgsGeometryCollection > parts = QgsGeometryFactory::createCollectionOfType( mGeometry->wkbType() );
500 try
501 {
502 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
503 subdivideRecursive( mGeos.get(), maxNodes, 0, parts.get(), mGeometry->boundingBox(), parameters.gridSize() );
504 }
505 CATCH_GEOS_WITH_ERRMSG( nullptr )
506
507 return std::move( parts );
508}
509
510QgsAbstractGeometry *QgsGeos::combine( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
511{
512 return overlay( geom, OverlayUnion, errorMsg, parameters, feedback ).release();
513}
514
515QgsAbstractGeometry *QgsGeos::combine( const QVector<QgsAbstractGeometry *> &geomList, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
516{
517 std::vector<geos::unique_ptr> geosGeometries;
518 geosGeometries.reserve( geomList.size() );
519 for ( const QgsAbstractGeometry *g : geomList )
520 {
521 if ( !g )
522 continue;
523
524 geosGeometries.emplace_back( asGeos( g, mPrecision ) );
525 }
526
527 GEOSContextHandle_t context = QgsGeosContext::get();
528 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
529 geos::unique_ptr geomUnion;
530 try
531 {
532 geos::unique_ptr geomCollection = createGeosCollection( GEOS_GEOMETRYCOLLECTION, geosGeometries );
533 if ( parameters.gridSize() > 0 )
534 {
535 geomUnion.reset( GEOSUnaryUnionPrec_r( context, geomCollection.get(), parameters.gridSize() ) );
536 }
537 else
538 {
539 geomUnion.reset( GEOSUnaryUnion_r( context, geomCollection.get() ) );
540 }
541 }
542 CATCH_GEOS_WITH_ERRMSG( nullptr )
543
544 std::unique_ptr< QgsAbstractGeometry > result = fromGeos( geomUnion.get() );
545 return result.release();
546}
547
548QgsAbstractGeometry *QgsGeos::combine( const QVector<QgsGeometry> &geomList, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
549{
550 std::vector<geos::unique_ptr> geosGeometries;
551 geosGeometries.reserve( geomList.size() );
552 for ( const QgsGeometry &g : geomList )
553 {
554 if ( g.isNull() )
555 continue;
556
557 geosGeometries.emplace_back( asGeos( g.constGet(), mPrecision ) );
558 }
559
560 GEOSContextHandle_t context = QgsGeosContext::get();
561 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
562 geos::unique_ptr geomUnion;
563 try
564 {
565 geos::unique_ptr geomCollection = createGeosCollection( GEOS_GEOMETRYCOLLECTION, geosGeometries );
566
567 if ( parameters.gridSize() > 0 )
568 {
569 geomUnion.reset( GEOSUnaryUnionPrec_r( context, geomCollection.get(), parameters.gridSize() ) );
570 }
571 else
572 {
573 geomUnion.reset( GEOSUnaryUnion_r( context, geomCollection.get() ) );
574 }
575 }
576 CATCH_GEOS_WITH_ERRMSG( nullptr )
577
578 std::unique_ptr< QgsAbstractGeometry > result = fromGeos( geomUnion.get() );
579 return result.release();
580}
581
582QgsAbstractGeometry *QgsGeos::symDifference( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
583{
584 return overlay( geom, OverlaySymDifference, errorMsg, parameters, feedback ).release();
585}
586
587static bool isZVerticalLine( const QgsAbstractGeometry *geom, double tolerance = 4 * std::numeric_limits<double>::epsilon() )
588{
589 // checks if the Geometry if a purely vertical 3D line LineString Z((X Y Z1, X Y Z2, ..., X Y Zn))
590 // This is needed because QgsGeos is not able to handle this type of geometry on distance computation.
591
593 {
594 return false;
595 }
596
597 bool isVertical = true;
598 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( geom ) )
599 {
600 const int nrPoints = line->numPoints();
601 if ( nrPoints == 1 )
602 {
603 return true;
604 }
605
606 // if the 2D part of two points of the line are different, this means
607 // that the line is not purely vertical
608 const double sqrTolerance = tolerance * tolerance;
609 const double *lineX = line->xData();
610 const double *lineY = line->yData();
611 for ( int iVert = nrPoints - 1, jVert = 0; jVert < nrPoints; iVert = jVert++ )
612 {
613 if ( QgsGeometryUtilsBase::sqrDistance2D( lineX[iVert], lineY[iVert], lineX[jVert], lineY[jVert] ) > sqrTolerance )
614 {
615 isVertical = false;
616 break;
617 }
618 }
619 }
620
621 return isVertical;
622}
623
624double QgsGeos::distance( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
625{
626 double distance = -1.0;
627 if ( !mGeos )
628 {
629 return distance;
630 }
631
632 geos::unique_ptr otherGeosGeom;
633 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
634
635 // GEOSPreparedDistance_r is not able to properly compute the distance if one
636 // of the geometries if a vertical line (LineString Z((X Y Z1, X Y Z2, ..., X Y Zn))).
637 // In that case, replace `geom` by a single point.
638 // However, GEOSDistance_r works.
639 if ( mGeosPrepared && isZVerticalLine( geom->simplifiedTypeRef() ) )
640 {
641 QgsPoint firstPoint = geom->vertexAt( QgsVertexId( 0, 0, 0 ) );
642 otherGeosGeom = asGeos( &firstPoint, mPrecision );
643 }
644 else
645 {
646 otherGeosGeom = asGeos( geom, mPrecision );
647 }
648
649 if ( !otherGeosGeom )
650 {
651 return distance;
652 }
653
654 GEOSContextHandle_t context = QgsGeosContext::get();
655 try
656 {
657 if ( mGeosPrepared && !isZVerticalLine( mGeometry->simplifiedTypeRef() ) )
658 {
659 GEOSPreparedDistance_r( context, mGeosPrepared.get(), otherGeosGeom.get(), &distance );
660 }
661 else
662 {
663 GEOSDistance_r( context, mGeos.get(), otherGeosGeom.get(), &distance );
664 }
665 }
667
668 return distance;
669}
670
671double QgsGeos::distance( double x, double y, QString *errorMsg, QgsFeedback *feedback ) const
672{
673 double distance = -1.0;
674 if ( !mGeos )
675 {
676 return distance;
677 }
678
679 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
680 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
681 if ( !point )
682 return distance;
683
684 GEOSContextHandle_t context = QgsGeosContext::get();
685 try
686 {
687 if ( mGeosPrepared )
688 {
689 GEOSPreparedDistance_r( context, mGeosPrepared.get(), point.get(), &distance );
690 }
691 else
692 {
693 GEOSDistance_r( context, mGeos.get(), point.get(), &distance );
694 }
695 }
697
698 return distance;
699}
700
701bool QgsGeos::distanceWithin( const QgsAbstractGeometry *geom, double maxdist, QString *errorMsg, QgsFeedback *feedback ) const
702{
703 if ( !mGeos )
704 {
705 return false;
706 }
707
708 if ( qgsDoubleNear( maxdist, 0.0 ) )
709 {
710 return intersects( geom, errorMsg, feedback );
711 }
712
713 geos::unique_ptr otherGeosGeom;
714
715 // GEOSPreparedDistanceWithin_r GEOSPreparedDistance_r are not able to properly compute the distance if one
716 // of the geometries if a vertical line (LineString Z((X Y Z1, X Y Z2, ..., X Y Zn))).
717 // In that case, replace `geom` by a single point.
718 // However, GEOSDistanceWithin_r and GEOSDistance_r work.
719 if ( mGeosPrepared && isZVerticalLine( geom->simplifiedTypeRef() ) )
720 {
721 QgsPoint firstPoint = geom->vertexAt( QgsVertexId( 0, 0, 0 ) );
722 otherGeosGeom = asGeos( &firstPoint );
723 }
724 else
725 {
726 otherGeosGeom = asGeos( geom, mPrecision );
727 }
728
729 if ( !otherGeosGeom )
730 {
731 return false;
732 }
733
734 // TODO: optimize implementation of this function to early-exit if
735 // any part of othergeosGeom is found to be within the given
736 // distance
737 double distance;
738
739 GEOSContextHandle_t context = QgsGeosContext::get();
740 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
741 try
742 {
743 if ( mGeosPrepared && !isZVerticalLine( mGeometry->simplifiedTypeRef() ) )
744 {
745#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
746 return GEOSPreparedDistanceWithin_r( context, mGeosPrepared.get(), otherGeosGeom.get(), maxdist );
747#else
748 GEOSPreparedDistance_r( context, mGeosPrepared.get(), otherGeosGeom.get(), &distance );
749#endif
750 }
751 else
752 {
753#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
754 return GEOSDistanceWithin_r( context, mGeos.get(), otherGeosGeom.get(), maxdist );
755#else
756 GEOSDistance_r( context, mGeos.get(), otherGeosGeom.get(), &distance );
757#endif
758 }
759 }
761
762 return distance <= maxdist;
763}
764
765bool QgsGeos::contains( double x, double y, QString *errorMsg, QgsFeedback *feedback ) const
766{
767 bool result = false;
768 GEOSContextHandle_t context = QgsGeosContext::get();
769 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
770 try
771 {
772#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
773 // defer point creation until after prepared geometry check, we may not need it
774#else
775 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
776 if ( !point )
777 return false;
778#endif
779 if ( mGeosPrepared ) //use faster version with prepared geometry
780 {
781#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
782 return GEOSPreparedContainsXY_r( context, mGeosPrepared.get(), x, y ) == 1;
783#else
784 return GEOSPreparedContains_r( context, mGeosPrepared.get(), point.get() ) == 1;
785#endif
786 }
787
788#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
789 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
790 if ( !point )
791 return false;
792#endif
793
794 result = ( GEOSContains_r( context, mGeos.get(), point.get() ) == 1 );
795 }
796 catch ( QgsGeosException &e )
797 {
798 logError( u"GEOS"_s, e.what() );
799 if ( errorMsg )
800 {
801 *errorMsg = e.what();
802 }
803 return false;
804 }
805
806 return result;
807}
808
809double QgsGeos::hausdorffDistance( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
810{
811 double distance = -1.0;
812 if ( !mGeos )
813 {
814 return distance;
815 }
816
817 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
818 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
819 if ( !otherGeosGeom )
820 {
821 return distance;
822 }
823
824 try
825 {
826 GEOSHausdorffDistance_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), &distance );
827 }
829
830 return distance;
831}
832
833double QgsGeos::hausdorffDistanceDensify( const QgsAbstractGeometry *geom, double densifyFraction, QString *errorMsg, QgsFeedback *feedback ) const
834{
835 double distance = -1.0;
836 if ( !mGeos )
837 {
838 return distance;
839 }
840
841 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
842 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
843 if ( !otherGeosGeom )
844 {
845 return distance;
846 }
847
848 try
849 {
850 GEOSHausdorffDistanceDensify_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), densifyFraction, &distance );
851 }
853
854 return distance;
855}
856
857double QgsGeos::frechetDistance( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
858{
859 double distance = -1.0;
860 if ( !mGeos )
861 {
862 return distance;
863 }
864
865 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
866 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
867 if ( !otherGeosGeom )
868 {
869 return distance;
870 }
871
872 try
873 {
874 GEOSFrechetDistance_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), &distance );
875 }
877
878 return distance;
879}
880
881double QgsGeos::frechetDistanceDensify( const QgsAbstractGeometry *geom, double densifyFraction, QString *errorMsg, QgsFeedback *feedback ) const
882{
883 double distance = -1.0;
884 if ( !mGeos )
885 {
886 return distance;
887 }
888
889 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
890 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
891 if ( !otherGeosGeom )
892 {
893 return distance;
894 }
895
896 try
897 {
898 GEOSFrechetDistanceDensify_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), densifyFraction, &distance );
899 }
901
902 return distance;
903}
904
905bool QgsGeos::intersects( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
906{
907 if ( !mGeos || !geom )
908 {
909 return false;
910 }
911
912 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
913#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
914 // special optimised case for point intersects
916 {
917 if ( mGeosPrepared )
918 {
919 try
920 {
921 return GEOSPreparedIntersectsXY_r( QgsGeosContext::get(), mGeosPrepared.get(), point->x(), point->y() ) == 1;
922 }
923 catch ( QgsGeosException &e )
924 {
925 logError( u"GEOS"_s, e.what() );
926 if ( errorMsg )
927 {
928 *errorMsg = e.what();
929 }
930 return false;
931 }
932 }
933 }
934#endif
935
936 return relation( geom, RelationIntersects, errorMsg );
937}
938
939bool QgsGeos::touches( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
940{
941 return relation( geom, RelationTouches, errorMsg, feedback );
942}
943
944bool QgsGeos::crosses( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
945{
946 return relation( geom, RelationCrosses, errorMsg, feedback );
947}
948
949bool QgsGeos::within( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
950{
951 return relation( geom, RelationWithin, errorMsg, feedback );
952}
953
954bool QgsGeos::overlaps( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
955{
956 return relation( geom, RelationOverlaps, errorMsg, feedback );
957}
958
959bool QgsGeos::contains( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
960{
961 if ( !mGeos || !geom )
962 {
963 return false;
964 }
965
966#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
967 // special optimised case for point containment
969 {
970 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
971 if ( mGeosPrepared )
972 {
973 try
974 {
975 return GEOSPreparedContainsXY_r( QgsGeosContext::get(), mGeosPrepared.get(), point->x(), point->y() ) == 1;
976 }
977 catch ( QgsGeosException &e )
978 {
979 logError( u"GEOS"_s, e.what() );
980 if ( errorMsg )
981 {
982 *errorMsg = e.what();
983 }
984 return false;
985 }
986 }
987 }
988#endif
989
990 return relation( geom, RelationContains, errorMsg, feedback );
991}
992
993bool QgsGeos::disjoint( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
994{
995 return relation( geom, RelationDisjoint, errorMsg, feedback );
996}
997
998QString QgsGeos::relate( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
999{
1000 if ( !mGeos )
1001 {
1002 return QString();
1003 }
1004
1005 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
1006 if ( !geosGeom )
1007 {
1008 return QString();
1009 }
1010
1011 QString result;
1012 GEOSContextHandle_t context = QgsGeosContext::get();
1013 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
1014 try
1015 {
1016 char *r = GEOSRelate_r( context, mGeos.get(), geosGeom.get() );
1017 if ( r )
1018 {
1019 result = QString( r );
1020 GEOSFree_r( context, r );
1021 }
1022 }
1023 catch ( QgsGeosException &e )
1024 {
1025 logError( u"GEOS"_s, e.what() );
1026 if ( errorMsg )
1027 {
1028 *errorMsg = e.what();
1029 }
1030 }
1031
1032 return result;
1033}
1034
1035bool QgsGeos::relatePattern( const QgsAbstractGeometry *geom, const QString &pattern, QString *errorMsg, QgsFeedback *feedback ) const
1036{
1037 if ( !mGeos || !geom )
1038 {
1039 return false;
1040 }
1041
1042 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
1043 if ( !geosGeom )
1044 {
1045 return false;
1046 }
1047
1048 bool result = false;
1049 GEOSContextHandle_t context = QgsGeosContext::get();
1050 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
1051
1052 try
1053 {
1054 result = ( GEOSRelatePattern_r( context, mGeos.get(), geosGeom.get(), pattern.toLocal8Bit().constData() ) == 1 );
1055 }
1056 catch ( QgsGeosException &e )
1057 {
1058 logError( u"GEOS"_s, e.what() );
1059 if ( errorMsg )
1060 {
1061 *errorMsg = e.what();
1062 }
1063 }
1064
1065 return result;
1066}
1067
1068double QgsGeos::area( QString *errorMsg ) const
1069{
1070 double area = -1.0;
1071 if ( !mGeos )
1072 {
1073 return area;
1074 }
1075
1076 try
1077 {
1078 if ( GEOSArea_r( QgsGeosContext::get(), mGeos.get(), &area ) != 1 )
1079 return -1.0;
1080 }
1082 return area;
1083}
1084
1085double QgsGeos::length( QString *errorMsg ) const
1086{
1087 double length = -1.0;
1088 if ( !mGeos )
1089 {
1090 return length;
1091 }
1092 try
1093 {
1094 if ( GEOSLength_r( QgsGeosContext::get(), mGeos.get(), &length ) != 1 )
1095 return -1.0;
1096 }
1098 return length;
1099}
1100
1101
1103 const QgsAbstractGeometry &splitGeom, QVector<QgsGeometry > &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, QString *errorMsg
1104) const
1105{
1106#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1107 if ( !mGeos || !mGeometry )
1108 {
1109 return InvalidBaseGeometry;
1110 }
1111
1112 if ( mGeometry->dimension() == 0 && QgsWkbTypes::flatType( mGeometry->wkbType() ) != Qgis::WkbType::GeometryCollection )
1113 {
1114 return SplitCannotSplitPoint; //cannot split points
1115 }
1116
1117 GEOSContextHandle_t context = QgsGeosContext::get();
1118 EngineOperationResult returnCode = Success;
1119
1120 try
1121 {
1122 if ( !GEOSisValid_r( context, mGeos.get() ) )
1123 return InvalidBaseGeometry;
1124
1125 geos::unique_ptr splitGeosGeom = asGeos( &splitGeom, mPrecision );
1126 if ( !splitGeosGeom || !GEOSisValid_r( context, splitGeosGeom.get() ) || !GEOSisSimple_r( context, splitGeosGeom.get() ) )
1127 {
1128 return InvalidInput;
1129 }
1130
1131 // TODO: Currently, points cannot split polygons, but it could change in the
1132 // future in GEOS. Remove this block when that happens. (See GEOS issue #1481)
1134 {
1135 return EngineError;
1136 }
1137
1138 if ( topological )
1139 {
1140 //find out candidate points for topological corrections
1141 if ( !topologicalTestPointsSplit( splitGeosGeom.get(), topologyTestPoints, errorMsg ) )
1142 {
1143 return InvalidInput; // TODO: is it really an invalid input?
1144 }
1145 }
1146
1147 newGeometries.clear();
1148
1149 geos::unique_ptr split( GEOSSplit_r( context, mGeos.get(), splitGeosGeom.get() ) );
1150 if ( !split )
1151 {
1152 returnCode = EngineError;
1153 }
1154 else
1155 {
1156 const int nParts = GEOSGetNumGeometries_r( context, split.get() );
1157 if ( nParts == 0 )
1158 {
1159 return NothingHappened;
1160 }
1161 for ( int i = 0; i < nParts; ++i )
1162 {
1163 newGeometries << QgsGeometry( fromGeos( GEOSGetGeometryN_r( context, split.get(), i ) ) );
1164 }
1165 returnCode = Success;
1166 }
1167 }
1169
1170 return returnCode;
1171#else
1173 {
1174 const QgsLineString *splitLine = qgis::down_cast< const QgsLineString * >( &splitGeom );
1175 if ( splitLine )
1176 {
1177 return splitGeometry( *splitLine, newGeometries, topological, topologyTestPoints, errorMsg, false );
1178 }
1179 else
1180 {
1181 return InvalidInput;
1182 }
1183 }
1184 else
1185 {
1186 return MethodNotImplemented;
1187 }
1188#endif
1189}
1190
1192 const QgsLineString &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, QString *errorMsg, bool skipIntersectionCheck
1193) const
1194{
1195 EngineOperationResult returnCode = Success;
1196 if ( !mGeos || !mGeometry )
1197 {
1198 return InvalidBaseGeometry;
1199 }
1200
1201 //return if this type is point/multipoint
1202 if ( mGeometry->dimension() == 0 )
1203 {
1204 return SplitCannotSplitPoint; //cannot split points
1205 }
1206
1207 GEOSContextHandle_t context = QgsGeosContext::get();
1208 if ( !GEOSisValid_r( context, mGeos.get() ) )
1209 return InvalidBaseGeometry;
1210
1211 //make sure splitLine is valid
1212 if ( ( mGeometry->dimension() == 1 && splitLine.numPoints() < 1 ) || ( mGeometry->dimension() == 2 && splitLine.numPoints() < 2 ) )
1213 return InvalidInput;
1214
1215 newGeometries.clear();
1216 geos::unique_ptr splitLineGeos;
1217
1218 try
1219 {
1220 if ( splitLine.numPoints() > 1 )
1221 {
1222 splitLineGeos = createGeosLinestring( &splitLine, mPrecision );
1223 }
1224 else if ( splitLine.numPoints() == 1 )
1225 {
1226 splitLineGeos = createGeosPointXY( splitLine.xAt( 0 ), splitLine.yAt( 0 ), false, 0, false, 0, 2, mPrecision );
1227 }
1228 else
1229 {
1230 return InvalidInput;
1231 }
1232
1233 if ( !GEOSisValid_r( context, splitLineGeos.get() ) || !GEOSisSimple_r( context, splitLineGeos.get() ) )
1234 {
1235 return InvalidInput;
1236 }
1237
1238 if ( topological )
1239 {
1240 //find out candidate points for topological corrections
1241 if ( !topologicalTestPointsSplit( splitLineGeos.get(), topologyTestPoints, errorMsg ) )
1242 {
1243 return InvalidInput; // TODO: is it really an invalid input?
1244 }
1245 }
1246
1247 //call split function depending on geometry type
1248 if ( mGeometry->dimension() == 1 )
1249 {
1250 returnCode = splitLinearGeometry( splitLineGeos.get(), newGeometries, skipIntersectionCheck );
1251 }
1252 else if ( mGeometry->dimension() == 2 )
1253 {
1254 returnCode = splitPolygonGeometry( splitLineGeos.get(), newGeometries, skipIntersectionCheck );
1255 }
1256 else
1257 {
1258 return InvalidInput;
1259 }
1260 }
1262
1263 return returnCode;
1264}
1265
1266
1267bool QgsGeos::topologicalTestPointsSplit( const GEOSGeometry *splitLine, QgsPointSequence &testPoints, QString *errorMsg ) const
1268{
1269 //Find out the intersection points between splitLineGeos and this geometry.
1270 //These points need to be tested for topological correctness by the calling function
1271 //if topological editing is enabled
1272
1273 if ( !mGeos )
1274 {
1275 return false;
1276 }
1277
1278 GEOSContextHandle_t context = QgsGeosContext::get();
1279 try
1280 {
1281 testPoints.clear();
1282 geos::unique_ptr intersectionGeom( GEOSIntersection_r( context, mGeos.get(), splitLine ) );
1283 if ( !intersectionGeom )
1284 return false;
1285
1286 // TODO: Remove this if block when this method has curve support (e.g., CircularString or CoumpoundCurve).
1287 // That is, when we extract vertices from curve intersections.
1288 if ( !( GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_POINT
1289 || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_LINESTRING
1290 || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_MULTIPOINT
1291 || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_MULTILINESTRING ) )
1292 {
1293 if ( errorMsg )
1294 {
1295 *errorMsg = u"Extracting topological points from curves or polygons is not yet supported."_s;
1296 }
1297 return false;
1298 }
1299
1300 bool simple = false;
1301 int nIntersectGeoms = 1;
1302 if ( GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_LINESTRING || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_POINT )
1303 simple = true;
1304
1305 if ( !simple )
1306 nIntersectGeoms = GEOSGetNumGeometries_r( context, intersectionGeom.get() );
1307
1308 for ( int i = 0; i < nIntersectGeoms; ++i )
1309 {
1310 const GEOSGeometry *currentIntersectGeom = nullptr;
1311 if ( simple )
1312 currentIntersectGeom = intersectionGeom.get();
1313 else
1314 currentIntersectGeom = GEOSGetGeometryN_r( context, intersectionGeom.get(), i );
1315
1316 const GEOSCoordSequence *lineSequence = GEOSGeom_getCoordSeq_r( context, currentIntersectGeom );
1317 unsigned int sequenceSize = 0;
1318 double x, y, z;
1319 if ( GEOSCoordSeq_getSize_r( context, lineSequence, &sequenceSize ) != 0 )
1320 {
1321 for ( unsigned int i = 0; i < sequenceSize; ++i )
1322 {
1323 if ( GEOSCoordSeq_getXYZ_r( context, lineSequence, i, &x, &y, &z ) )
1324 {
1325 testPoints.push_back( QgsPoint( x, y, z ) );
1326 }
1327 }
1328 }
1329 }
1330 }
1332
1333 return true;
1334}
1335
1336geos::unique_ptr QgsGeos::linePointDifference( GEOSGeometry *GEOSsplitPoint ) const
1337{
1338 GEOSContextHandle_t context = QgsGeosContext::get();
1339 int type = GEOSGeomTypeId_r( context, mGeos.get() );
1340
1341 std::unique_ptr< QgsMultiCurve > multiCurve;
1342 if ( type == GEOS_MULTILINESTRING )
1343 {
1344 multiCurve.reset( qgsgeometry_cast<QgsMultiCurve *>( mGeometry->clone() ) );
1345 }
1346 else if ( type == GEOS_LINESTRING )
1347 {
1348 multiCurve = std::make_unique<QgsMultiCurve>();
1349 multiCurve->addGeometry( mGeometry->clone() );
1350 }
1351 else
1352 {
1353 return nullptr;
1354 }
1355
1356 if ( !multiCurve )
1357 {
1358 return nullptr;
1359 }
1360
1361
1362 // we might have a point or a multipoint, depending on number of
1363 // intersections between the geometry and the split geometry
1364 std::unique_ptr< QgsMultiPoint > splitPoints;
1365 {
1366 std::unique_ptr< QgsAbstractGeometry > splitGeom( fromGeos( GEOSsplitPoint ) );
1367
1368 if ( qgsgeometry_cast<QgsMultiPoint *>( splitGeom.get() ) )
1369 {
1370 splitPoints.reset( qgis::down_cast<QgsMultiPoint *>( splitGeom.release() ) );
1371 }
1372 else if ( qgsgeometry_cast<QgsPoint *>( splitGeom.get() ) )
1373 {
1374 splitPoints = std::make_unique< QgsMultiPoint >();
1375 if ( qgsgeometry_cast<QgsPoint *>( splitGeom.get() ) )
1376 {
1377 splitPoints->addGeometry( qgis::down_cast<QgsPoint *>( splitGeom.release() ) );
1378 }
1379 }
1380 }
1381
1382 if ( !splitPoints )
1383 return nullptr;
1384
1385 QgsMultiCurve lines;
1386
1387 //For each part
1388 for ( int geometryIndex = 0; geometryIndex < multiCurve->numGeometries(); ++geometryIndex )
1389 {
1390 const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( multiCurve->geometryN( geometryIndex ) );
1391 if ( !line )
1392 {
1393 const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( multiCurve->geometryN( geometryIndex ) );
1394 line = curve->curveToLine();
1395 }
1396 if ( !line )
1397 {
1398 return nullptr;
1399 }
1400 // we gather the intersection points and their distance from previous node grouped by segment
1401 QMap< int, QVector< QPair< double, QgsPoint > > > pointMap;
1402 for ( int splitPointIndex = 0; splitPointIndex < splitPoints->numGeometries(); ++splitPointIndex )
1403 {
1404 const QgsPoint *intersectionPoint = splitPoints->pointN( splitPointIndex );
1405
1406 QgsPoint segmentPoint2D;
1407 QgsVertexId nextVertex;
1408 // With closestSegment we only get a 2D point so we need to interpolate if we
1409 // don't want to lose Z data
1410 line->closestSegment( *intersectionPoint, segmentPoint2D, nextVertex );
1411
1412 // The intersection might belong to another part, skip it
1413 // Note: cannot test for equality because of Z
1414 if ( !qgsDoubleNear( intersectionPoint->x(), segmentPoint2D.x() ) || !qgsDoubleNear( intersectionPoint->y(), segmentPoint2D.y() ) )
1415 {
1416 continue;
1417 }
1418
1419 const QgsLineString segment = QgsLineString( line->pointN( nextVertex.vertex - 1 ), line->pointN( nextVertex.vertex ) );
1420 const double distance = segmentPoint2D.distance( line->pointN( nextVertex.vertex - 1 ) );
1421
1422 // Due to precision issues, distance can be a tad larger than the actual segment length, making interpolatePoint() return nullptr
1423 // In that case we'll use the segment's endpoint instead of interpolating
1424 std::unique_ptr< QgsPoint > correctSegmentPoint( distance > segment.length() ? segment.endPoint().clone() : segment.interpolatePoint( distance ) );
1425
1426 const QPair< double, QgsPoint > pair = qMakePair( distance, *correctSegmentPoint.get() );
1427 if ( pointMap.contains( nextVertex.vertex - 1 ) )
1428 pointMap[nextVertex.vertex - 1].append( pair );
1429 else
1430 pointMap[nextVertex.vertex - 1] = QVector< QPair< double, QgsPoint > >() << pair;
1431 }
1432
1433 // When we have more than one intersection point on a segment we need those points
1434 // to be sorted by their distance from the previous geometry vertex
1435 for ( auto &p : pointMap )
1436 {
1437 std::sort( p.begin(), p.end(), []( const QPair< double, QgsPoint > &a, const QPair< double, QgsPoint > &b ) { return a.first < b.first; } );
1438 }
1439
1440 //For each segment
1441 QgsLineString newLine;
1442 int nVertices = line->numPoints();
1443 QgsPoint splitPoint;
1444 for ( int vertexIndex = 0; vertexIndex < nVertices; ++vertexIndex )
1445 {
1446 QgsPoint currentPoint = line->pointN( vertexIndex );
1447 newLine.addVertex( currentPoint );
1448 if ( pointMap.contains( vertexIndex ) )
1449 {
1450 // For each intersecting point
1451 for ( int k = 0; k < pointMap[vertexIndex].size(); ++k )
1452 {
1453 splitPoint = pointMap[vertexIndex][k].second;
1454 if ( splitPoint == currentPoint )
1455 {
1456 lines.addGeometry( newLine.clone() );
1457 newLine = QgsLineString();
1458 newLine.addVertex( currentPoint );
1459 }
1460 else if ( splitPoint == line->pointN( vertexIndex + 1 ) )
1461 {
1462 newLine.addVertex( line->pointN( vertexIndex + 1 ) );
1463 lines.addGeometry( newLine.clone() );
1464 newLine = QgsLineString();
1465 }
1466 else
1467 {
1468 newLine.addVertex( splitPoint );
1469 lines.addGeometry( newLine.clone() );
1470 newLine = QgsLineString();
1471 newLine.addVertex( splitPoint );
1472 }
1473 }
1474 }
1475 }
1476 lines.addGeometry( newLine.clone() );
1477 }
1478
1479 return asGeos( &lines, mPrecision );
1480}
1481
1482QgsGeometryEngine::EngineOperationResult QgsGeos::splitLinearGeometry( const GEOSGeometry *splitLine, QVector<QgsGeometry> &newGeometries, bool skipIntersectionCheck ) const
1483{
1484 Q_UNUSED( skipIntersectionCheck )
1485 if ( !splitLine )
1486 return InvalidInput;
1487
1488 if ( !mGeos )
1489 return InvalidBaseGeometry;
1490
1491 GEOSContextHandle_t context = QgsGeosContext::get();
1492
1493 geos::unique_ptr intersectGeom( GEOSIntersection_r( context, splitLine, mGeos.get() ) );
1494 if ( !intersectGeom || GEOSisEmpty_r( context, intersectGeom.get() ) )
1495 return NothingHappened;
1496
1497 //check that split line has no linear intersection
1498 const int linearIntersect = GEOSRelatePattern_r( context, mGeos.get(), splitLine, "1********" );
1499 if ( linearIntersect > 0 )
1500 return InvalidInput;
1501
1502 geos::unique_ptr splitGeom = linePointDifference( intersectGeom.get() );
1503
1504 if ( !splitGeom )
1505 return InvalidBaseGeometry;
1506
1507 std::vector<geos::unique_ptr> lineGeoms;
1508
1509 const int splitType = GEOSGeomTypeId_r( context, splitGeom.get() );
1510 if ( splitType == GEOS_MULTILINESTRING )
1511 {
1512 const int nGeoms = GEOSGetNumGeometries_r( context, splitGeom.get() );
1513 lineGeoms.reserve( nGeoms );
1514 for ( int i = 0; i < nGeoms; ++i )
1515 lineGeoms.emplace_back( GEOSGeom_clone_r( context, GEOSGetGeometryN_r( context, splitGeom.get(), i ) ) );
1516 }
1517 else
1518 {
1519 lineGeoms.emplace_back( GEOSGeom_clone_r( context, splitGeom.get() ) );
1520 }
1521
1522 mergeGeometriesMultiTypeSplit( lineGeoms );
1523
1524 for ( geos::unique_ptr &lineGeom : lineGeoms )
1525 {
1526 newGeometries << QgsGeometry( fromGeos( lineGeom.get() ) );
1527 }
1528
1529 return Success;
1530}
1531
1532QgsGeometryEngine::EngineOperationResult QgsGeos::splitPolygonGeometry( const GEOSGeometry *splitLine, QVector<QgsGeometry> &newGeometries, bool skipIntersectionCheck ) const
1533{
1534 if ( !splitLine )
1535 return InvalidInput;
1536
1537 if ( !mGeos )
1538 return InvalidBaseGeometry;
1539
1540 // we will need prepared geometry for intersection tests
1541 const_cast<QgsGeos *>( this )->prepareGeometry();
1542 if ( !mGeosPrepared )
1543 return EngineError;
1544
1545 GEOSContextHandle_t context = QgsGeosContext::get();
1546
1547 //first test if linestring intersects geometry. If not, return straight away
1548 if ( !skipIntersectionCheck && !GEOSPreparedIntersects_r( context, mGeosPrepared.get(), splitLine ) )
1549 return NothingHappened;
1550
1551 //first union all the polygon rings together (to get them noded, see JTS developer guide)
1552 geos::unique_ptr nodedGeometry = nodeGeometries( splitLine, mGeos.get() );
1553 if ( !nodedGeometry )
1554 return NodedGeometryError; //an error occurred during noding
1555
1556 const GEOSGeometry *noded = nodedGeometry.get();
1557 geos::unique_ptr polygons( GEOSPolygonize_r( context, &noded, 1 ) );
1558 if ( !polygons )
1559 {
1560 return InvalidBaseGeometry;
1561 }
1562 const int numberOfGeometriesPolygon = numberOfGeometries( polygons.get() );
1563 if ( numberOfGeometriesPolygon == 0 )
1564 {
1565 return InvalidBaseGeometry;
1566 }
1567
1568 //test every polygon is contained in original geometry
1569 //include in result if yes
1570 std::vector<geos::unique_ptr> testedGeometries;
1571
1572 // test whether the polygon parts returned from polygonize algorithm actually
1573 // belong to the source polygon geometry (if the source polygon contains some holes,
1574 // those would be also returned by polygonize and we need to skip them)
1575 for ( int i = 0; i < numberOfGeometriesPolygon; i++ )
1576 {
1577 const GEOSGeometry *polygon = GEOSGetGeometryN_r( context, polygons.get(), i );
1578
1579 geos::unique_ptr pointOnSurface( GEOSPointOnSurface_r( context, polygon ) );
1580 if ( pointOnSurface && GEOSPreparedIntersects_r( context, mGeosPrepared.get(), pointOnSurface.get() ) )
1581 testedGeometries.emplace_back( GEOSGeom_clone_r( context, polygon ) );
1582 }
1583
1584 const size_t nGeometriesThis = numberOfGeometries( mGeos.get() ); //original number of geometries
1585 if ( testedGeometries.empty() || testedGeometries.size() == nGeometriesThis )
1586 {
1587 //no split done, preserve original geometry
1588 return NothingHappened;
1589 }
1590
1591 // For multi-part geometries, try to identify parts that have been unchanged and try to merge them back
1592 // to a single multi-part geometry. For example, if there's a multi-polygon with three parts, but only
1593 // one part is being split, this function makes sure that the other two parts will be kept in a multi-part
1594 // geometry rather than being separated into two single-part geometries.
1595 mergeGeometriesMultiTypeSplit( testedGeometries );
1596
1597 size_t i;
1598 for ( i = 0; i < testedGeometries.size() && GEOSisValid_r( context, testedGeometries[i].get() ); ++i )
1599 ;
1600
1601 if ( i < testedGeometries.size() )
1602 {
1603 return InvalidBaseGeometry;
1604 }
1605
1606 for ( geos::unique_ptr &testedGeometry : testedGeometries )
1607 {
1608 newGeometries << QgsGeometry( fromGeos( testedGeometry.get() ) );
1609 }
1610
1611 return Success;
1612}
1613
1614geos::unique_ptr QgsGeos::nodeGeometries( const GEOSGeometry *splitLine, const GEOSGeometry *geom )
1615{
1616 if ( !splitLine || !geom )
1617 return nullptr;
1618
1619 geos::unique_ptr geometryBoundary;
1620 GEOSContextHandle_t context = QgsGeosContext::get();
1621 if ( GEOSGeom_getDimensions_r( context, geom ) == 2 )
1622 geometryBoundary.reset( GEOSBoundary_r( context, geom ) );
1623 else
1624 geometryBoundary.reset( GEOSGeom_clone_r( context, geom ) );
1625
1626 geos::unique_ptr splitLineClone( GEOSGeom_clone_r( context, splitLine ) );
1627 geos::unique_ptr unionGeometry( GEOSUnion_r( context, splitLineClone.get(), geometryBoundary.get() ) );
1628
1629 return unionGeometry;
1630}
1631
1632int QgsGeos::mergeGeometriesMultiTypeSplit( std::vector<geos::unique_ptr> &splitResult ) const
1633{
1634 if ( !mGeos )
1635 return 1;
1636
1637 //convert mGeos to geometry collection
1638 GEOSContextHandle_t context = QgsGeosContext::get();
1639 int type = GEOSGeomTypeId_r( context, mGeos.get() );
1640 if ( type != GEOS_GEOMETRYCOLLECTION && type != GEOS_MULTILINESTRING && type != GEOS_MULTIPOLYGON && type != GEOS_MULTIPOINT )
1641 return 0;
1642
1643 //collect all the geometries that belong to the initial multifeature
1644 std::vector<geos::unique_ptr> unionGeom;
1645
1646 std::vector<geos::unique_ptr> newSplitResult;
1647
1648 for ( size_t i = 0; i < splitResult.size(); ++i )
1649 {
1650 //is this geometry a part of the original multitype?
1651 bool isPart = false;
1652 for ( int j = 0; j < GEOSGetNumGeometries_r( context, mGeos.get() ); j++ )
1653 {
1654 if ( GEOSEquals_r( context, splitResult[i].get(), GEOSGetGeometryN_r( context, mGeos.get(), j ) ) )
1655 {
1656 isPart = true;
1657 break;
1658 }
1659 }
1660
1661 if ( isPart )
1662 {
1663 unionGeom.emplace_back( std::move( splitResult[i] ) );
1664 }
1665 else
1666 {
1667 std::vector<geos::unique_ptr> geomVector;
1668 geomVector.emplace_back( std::move( splitResult[i] ) );
1669
1670 if ( type == GEOS_MULTILINESTRING )
1671 newSplitResult.emplace_back( createGeosCollection( GEOS_MULTILINESTRING, geomVector ) );
1672 else if ( type == GEOS_MULTIPOLYGON )
1673 newSplitResult.emplace_back( createGeosCollection( GEOS_MULTIPOLYGON, geomVector ) );
1674 }
1675 }
1676
1677 splitResult = std::move( newSplitResult );
1678
1679 //make multifeature out of unionGeom
1680 if ( !unionGeom.empty() )
1681 {
1682 if ( type == GEOS_MULTILINESTRING )
1683 splitResult.emplace_back( createGeosCollection( GEOS_MULTILINESTRING, unionGeom ) );
1684 else if ( type == GEOS_MULTIPOLYGON )
1685 splitResult.emplace_back( createGeosCollection( GEOS_MULTIPOLYGON, unionGeom ) );
1686 }
1687
1688 return 0;
1689}
1690
1691geos::unique_ptr QgsGeos::createGeosCollection( int typeId, std::vector<geos::unique_ptr> &geoms )
1692{
1693 std::vector<GEOSGeometry *> geomarr;
1694 geomarr.reserve( geoms.size() );
1695
1696 GEOSContextHandle_t context = QgsGeosContext::get();
1697 for ( geos::unique_ptr &geomUniquePtr : geoms )
1698 {
1699 if ( geomUniquePtr )
1700 {
1701 if ( !GEOSisEmpty_r( context, geomUniquePtr.get() ) )
1702 {
1703 // don't add empty parts to a geos collection, it can cause crashes in GEOS
1704 // transfer ownership of the geometries to GEOSGeom_createCollection_r()
1705 geomarr.emplace_back( geomUniquePtr.release() );
1706 }
1707 }
1708 }
1709 geos::unique_ptr geomRes;
1710
1711 try
1712 {
1713 geomRes.reset( GEOSGeom_createCollection_r( context, typeId, geomarr.data(), geomarr.size() ) );
1714 }
1715 catch ( QgsGeosException & )
1716 {
1717 for ( GEOSGeometry *geom : geomarr )
1718 {
1719 GEOSGeom_destroy_r( context, geom );
1720 }
1721 }
1722
1723 return geomRes;
1724}
1725
1726std::unique_ptr<QgsAbstractGeometry> QgsGeos::fromGeos( const GEOSGeometry *geos )
1727{
1728 if ( !geos )
1729 {
1730 return nullptr;
1731 }
1732
1733 GEOSContextHandle_t context = QgsGeosContext::get();
1734#ifdef GEOS_SUPPORTS_ZM
1735 bool hasZ = GEOSHasZ_r( context, geos );
1736 bool hasM = GEOSHasM_r( context, geos );
1737#else
1738 int nCoordDims = GEOSGeom_getCoordinateDimension_r( context, geos );
1739 int nDims = GEOSGeom_getDimensions_r( context, geos );
1740 bool hasZ = ( nCoordDims == 3 );
1741 bool hasM = ( ( nDims - nCoordDims ) == 1 );
1742#endif
1743
1744 switch ( GEOSGeomTypeId_r( context, geos ) )
1745 {
1746 case GEOS_POINT: // a point
1747 {
1748 if ( GEOSisEmpty_r( context, geos ) )
1749 return nullptr;
1750
1751 const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( context, geos );
1752 unsigned int nPoints = 0;
1753 GEOSCoordSeq_getSize_r( context, cs, &nPoints );
1754 if ( nPoints == 0 )
1755 {
1756 return nullptr;
1757 }
1758 // Since GEOS 3.13, Points with NAN coordinates are not considered empty anymore
1759 // See: https://github.com/libgeos/geos/pull/927
1760 // Handle this change by checking if QgsPoint is empty
1761 const QgsPoint point = coordSeqPoint( cs, 0, hasZ, hasM );
1762 return !point.isEmpty() ? std::unique_ptr<QgsAbstractGeometry>( point.clone() ) : nullptr;
1763 }
1764 case GEOS_LINESTRING:
1765 {
1766 return sequenceToLinestring( geos, hasZ, hasM );
1767 }
1768#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1769 case GEOS_CIRCULARSTRING:
1770 {
1771 return sequenceToCircularString( geos, hasZ, hasM );
1772 }
1773 case GEOS_COMPOUNDCURVE:
1774 {
1775 auto compoundCurve = std::make_unique< QgsCompoundCurve >();
1776 const int nCurves = GEOSGetNumCurves_r( context, geos );
1777 for ( int i = 0; i < nCurves; i++ )
1778 {
1779 std::unique_ptr< QgsSimpleCurve > curve = sequenceToSimpleCurve( GEOSGetCurveN_r( context, geos, i ), hasZ, hasM );
1780 compoundCurve->addCurve( curve.release(), true );
1781 }
1782 return std::move( compoundCurve );
1783 }
1784#endif
1785 case GEOS_POLYGON:
1786 {
1787 return fromGeosPolygon( geos );
1788 }
1789#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1790 case GEOS_CURVEPOLYGON:
1791 {
1792 return fromGeosCurvePolygon( geos );
1793 }
1794#endif
1795 case GEOS_MULTIPOINT:
1796 {
1797 auto multiPoint = std::make_unique<QgsMultiPoint>();
1798 const int nParts = GEOSGetNumGeometries_r( context, geos );
1799 multiPoint->reserve( nParts );
1800 for ( int i = 0; i < nParts; ++i )
1801 {
1802 const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( context, GEOSGetGeometryN_r( context, geos, i ) );
1803 if ( cs )
1804 {
1805 unsigned int nPoints = 0;
1806 GEOSCoordSeq_getSize_r( context, cs, &nPoints );
1807 if ( nPoints > 0 )
1808 multiPoint->addGeometry( coordSeqPoint( cs, 0, hasZ, hasM ).clone() );
1809 }
1810 }
1811 return std::move( multiPoint );
1812 }
1813 case GEOS_MULTILINESTRING:
1814 {
1815 auto multiLineString = std::make_unique<QgsMultiLineString>();
1816 const int nParts = GEOSGetNumGeometries_r( context, geos );
1817 multiLineString->reserve( nParts );
1818 for ( int i = 0; i < nParts; ++i )
1819 {
1820 std::unique_ptr< QgsLineString > line( sequenceToLinestring( GEOSGetGeometryN_r( context, geos, i ), hasZ, hasM ) );
1821 if ( line )
1822 {
1823 multiLineString->addGeometry( line.release() );
1824 }
1825 }
1826 return std::move( multiLineString );
1827 }
1828#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1829 case GEOS_MULTICURVE:
1830 {
1831 auto multiCurve = std::make_unique<QgsMultiCurve>();
1832 const int nParts = GEOSGetNumGeometries_r( context, geos );
1833 multiCurve->reserve( nParts );
1834 for ( int i = 0; i < nParts; ++i )
1835 {
1836 std::unique_ptr< QgsAbstractGeometry > curve( fromGeos( GEOSGetGeometryN_r( context, geos, i ) ) );
1837 multiCurve->addGeometry( curve.release() );
1838 }
1839 return std::move( multiCurve );
1840 }
1841#endif
1842 case GEOS_MULTIPOLYGON:
1843 {
1844 auto multiPolygon = std::make_unique<QgsMultiPolygon>();
1845
1846 const int nParts = GEOSGetNumGeometries_r( context, geos );
1847 multiPolygon->reserve( nParts );
1848 for ( int i = 0; i < nParts; ++i )
1849 {
1850 std::unique_ptr< QgsPolygon > poly = fromGeosPolygon( GEOSGetGeometryN_r( context, geos, i ) );
1851 if ( poly )
1852 {
1853 multiPolygon->addGeometry( poly.release() );
1854 }
1855 }
1856 return std::move( multiPolygon );
1857 }
1858#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1859 case GEOS_MULTISURFACE:
1860 {
1861 auto multiSurface = std::make_unique<QgsMultiSurface>();
1862 const int nParts = GEOSGetNumGeometries_r( context, geos );
1863 multiSurface->reserve( nParts );
1864 for ( int i = 0; i < nParts; ++i )
1865 {
1866 std::unique_ptr< QgsAbstractGeometry > polygon( fromGeos( GEOSGetGeometryN_r( context, geos, i ) ) );
1867 multiSurface->addGeometry( polygon.release() );
1868 }
1869 return std::move( multiSurface );
1870 }
1871#endif
1872 case GEOS_GEOMETRYCOLLECTION:
1873 {
1874 auto geomCollection = std::make_unique<QgsGeometryCollection>();
1875 const int nParts = GEOSGetNumGeometries_r( context, geos );
1876 geomCollection->reserve( nParts );
1877 for ( int i = 0; i < nParts; ++i )
1878 {
1879 std::unique_ptr< QgsAbstractGeometry > geom( fromGeos( GEOSGetGeometryN_r( context, geos, i ) ) );
1880 if ( geom )
1881 {
1882 geomCollection->addGeometry( geom.release() );
1883 }
1884 }
1885 return std::move( geomCollection );
1886 }
1887 }
1888 return nullptr;
1889}
1890
1891#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1892std::unique_ptr<QgsCurvePolygon> QgsGeos::fromGeosCurvePolygon( const GEOSGeometry *geos )
1893{
1894 GEOSContextHandle_t context = QgsGeosContext::get();
1895 if ( GEOSGeomTypeId_r( context, geos ) != GEOS_CURVEPOLYGON )
1896 {
1897 return nullptr;
1898 }
1899
1900#ifdef GEOS_SUPPORTS_ZM
1901 bool hasZ = GEOSHasZ_r( context, geos );
1902 bool hasM = GEOSHasM_r( context, geos );
1903#else
1904 int nCoordDims = GEOSGeom_getCoordinateDimension_r( context, geos );
1905 int nDims = GEOSGeom_getDimensions_r( context, geos );
1906 bool hasZ = ( nCoordDims == 3 );
1907 bool hasM = ( ( nDims - nCoordDims ) == 1 );
1908#endif
1909
1910 auto curvePolygon = std::make_unique<QgsCurvePolygon>();
1911
1912 const GEOSGeometry *ring = GEOSGetExteriorRing_r( context, geos );
1913 if ( ring )
1914 {
1915 if ( GEOSGeomTypeId_r( context, ring ) == GEOS_COMPOUNDCURVE )
1916 {
1917 curvePolygon->setExteriorRing( qgis::down_cast< QgsCompoundCurve *>( fromGeos( ring ).release() ) );
1918 }
1919 else
1920 {
1921 curvePolygon->setExteriorRing( sequenceToSimpleCurve( ring, hasZ, hasM ).release() );
1922 }
1923 }
1924
1925 QVector<QgsCurve *> interiorRings;
1926 const int ringCount = GEOSGetNumInteriorRings_r( context, geos );
1927 interiorRings.reserve( ringCount );
1928 for ( int i = 0; i < ringCount; ++i )
1929 {
1930 ring = GEOSGetInteriorRingN_r( context, geos, i );
1931 if ( ring )
1932 {
1933 if ( GEOSGeomTypeId_r( context, ring ) == GEOS_COMPOUNDCURVE )
1934 {
1935 interiorRings.push_back( qgis::down_cast< QgsCompoundCurve *>( fromGeos( ring ).release() ) );
1936 }
1937 else
1938 {
1939 interiorRings.push_back( sequenceToSimpleCurve( ring, hasZ, hasM ).release() );
1940 }
1941 }
1942 }
1943 curvePolygon->setInteriorRings( interiorRings );
1944
1945 return curvePolygon;
1946}
1947#endif
1948
1949std::unique_ptr<QgsPolygon> QgsGeos::fromGeosPolygon( const GEOSGeometry *geos )
1950{
1951 GEOSContextHandle_t context = QgsGeosContext::get();
1952 if ( GEOSGeomTypeId_r( context, geos ) != GEOS_POLYGON )
1953 {
1954 return nullptr;
1955 }
1956
1957#ifdef GEOS_SUPPORTS_ZM
1958 bool hasZ = GEOSHasZ_r( context, geos );
1959 bool hasM = GEOSHasM_r( context, geos );
1960#else
1961 int nCoordDims = GEOSGeom_getCoordinateDimension_r( context, geos );
1962 int nDims = GEOSGeom_getDimensions_r( context, geos );
1963 bool hasZ = ( nCoordDims == 3 );
1964 bool hasM = ( ( nDims - nCoordDims ) == 1 );
1965#endif
1966
1967 auto polygon = std::make_unique<QgsPolygon>();
1968
1969 const GEOSGeometry *ring = GEOSGetExteriorRing_r( context, geos );
1970 if ( ring )
1971 {
1972 polygon->setExteriorRing( sequenceToLinestring( ring, hasZ, hasM ).release() );
1973 }
1974
1975 QVector<QgsCurve *> interiorRings;
1976 const int ringCount = GEOSGetNumInteriorRings_r( context, geos );
1977 interiorRings.reserve( ringCount );
1978 for ( int i = 0; i < ringCount; ++i )
1979 {
1980 ring = GEOSGetInteriorRingN_r( context, geos, i );
1981 if ( ring )
1982 {
1983 interiorRings.push_back( sequenceToLinestring( ring, hasZ, hasM ).release() );
1984 }
1985 }
1986 polygon->setInteriorRings( interiorRings );
1987
1988 return polygon;
1989}
1990
1991std::unique_ptr<QgsSimpleCurve> QgsGeos::sequenceToSimpleCurve( const GEOSGeometry *geos, bool hasZ, bool hasM )
1992{
1993 GEOSContextHandle_t context = QgsGeosContext::get();
1994
1995 const int geometryType = GEOSGeomTypeId_r( context, geos );
1996 if ( !( geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING || geometryType == GEOS_CIRCULARSTRING ) )
1997 return nullptr;
1998
1999 const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( context, geos );
2000
2001 unsigned int nPoints;
2002 GEOSCoordSeq_getSize_r( context, cs, &nPoints );
2003
2004 QVector< double > xOut( nPoints );
2005 QVector< double > yOut( nPoints );
2006 QVector< double > zOut;
2007 if ( hasZ )
2008 zOut.resize( nPoints );
2009 QVector< double > mOut;
2010 if ( hasM )
2011 mOut.resize( nPoints );
2012
2013 double *x = xOut.data();
2014 double *y = yOut.data();
2015 double *z = zOut.data();
2016 double *m = mOut.data();
2017
2018#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
2019 GEOSCoordSeq_copyToArrays_r( context, cs, x, y, hasZ ? z : nullptr, hasM ? m : nullptr );
2020#else
2021 for ( unsigned int i = 0; i < nPoints; ++i )
2022 {
2023 if ( hasZ )
2024 GEOSCoordSeq_getXYZ_r( context, cs, i, x++, y++, z++ );
2025 else
2026 GEOSCoordSeq_getXY_r( context, cs, i, x++, y++ );
2027 if ( hasM )
2028 {
2029 GEOSCoordSeq_getOrdinate_r( context, cs, i, 3, m++ );
2030 }
2031 }
2032#endif
2033
2034 std::unique_ptr< QgsSimpleCurve > simpleCurve;
2035 if ( geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING )
2036 {
2037 simpleCurve = std::make_unique<QgsLineString>( xOut, yOut, zOut, mOut );
2038 }
2039 else if ( geometryType == GEOS_CIRCULARSTRING )
2040 {
2041 simpleCurve = std::make_unique<QgsCircularString>( xOut, yOut, zOut, mOut );
2042 }
2043 return simpleCurve;
2044}
2045
2046std::unique_ptr<QgsLineString> QgsGeos::sequenceToLinestring( const GEOSGeometry *geos, bool hasZ, bool hasM )
2047{
2048 return std::unique_ptr<QgsLineString>( qgis::down_cast<QgsLineString *>( sequenceToSimpleCurve( geos, hasZ, hasM ).release() ) );
2049}
2050
2051#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2052std::unique_ptr<QgsCircularString> QgsGeos::sequenceToCircularString( const GEOSGeometry *geos, bool hasZ, bool hasM )
2053{
2054 return std::unique_ptr<QgsCircularString>( qgis::down_cast<QgsCircularString *>( sequenceToSimpleCurve( geos, hasZ, hasM ).release() ) );
2055}
2056#endif
2057
2058int QgsGeos::numberOfGeometries( GEOSGeometry *g )
2059{
2060 if ( !g )
2061 return 0;
2062
2063 GEOSContextHandle_t context = QgsGeosContext::get();
2064 int geometryType = GEOSGeomTypeId_r( context, g );
2065 if ( geometryType == GEOS_POINT || geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING || geometryType == GEOS_POLYGON )
2066 return 1;
2067
2068 //calling GEOSGetNumGeometries is save for multi types and collections also in geos2
2069 return GEOSGetNumGeometries_r( context, g );
2070}
2071
2072QgsPoint QgsGeos::coordSeqPoint( const GEOSCoordSequence *cs, int i, bool hasZ, bool hasM )
2073{
2074 if ( !cs )
2075 {
2076 return QgsPoint();
2077 }
2078
2079 GEOSContextHandle_t context = QgsGeosContext::get();
2080
2081 double x, y;
2082 double z = 0;
2083 double m = 0;
2084 if ( hasZ )
2085 GEOSCoordSeq_getXYZ_r( context, cs, i, &x, &y, &z );
2086 else
2087 GEOSCoordSeq_getXY_r( context, cs, i, &x, &y );
2088 if ( hasM )
2089 {
2090 GEOSCoordSeq_getOrdinate_r( context, cs, i, 3, &m );
2091 }
2092
2094 if ( hasZ && hasM )
2095 {
2097 }
2098 else if ( hasZ )
2099 {
2101 }
2102 else if ( hasM )
2103 {
2105 }
2106 return QgsPoint( t, x, y, z, m );
2107}
2108
2110{
2111 if ( !geom )
2112 return nullptr;
2113
2114 int coordDims = 2;
2115 if ( geom->is3D() )
2116 {
2117 ++coordDims;
2118 }
2119 if ( geom->isMeasure() )
2120 {
2121 ++coordDims;
2122 }
2123
2125 {
2126 int geosType;
2127 switch ( QgsWkbTypes::flatType( geom->wkbType() ) )
2128 {
2130 geosType = GEOS_MULTIPOINT;
2131 break;
2132
2134#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2136#endif
2137 geosType = GEOS_MULTILINESTRING;
2138 break;
2139
2141#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2143#endif
2144 geosType = GEOS_MULTIPOLYGON;
2145 break;
2146
2147#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2149 geosType = GEOS_MULTICURVE;
2150 break;
2151
2153 geosType = GEOS_MULTISURFACE;
2154 break;
2155#endif
2156
2158 geosType = GEOS_GEOMETRYCOLLECTION;
2159 break;
2160
2163 default:
2164 return nullptr;
2165 }
2166
2168
2169 if ( !c )
2170 return nullptr;
2171
2172 std::vector<geos::unique_ptr> geomVector;
2173 geomVector.reserve( c->numGeometries() );
2174 for ( int i = 0; i < c->numGeometries(); ++i )
2175 {
2176 geos::unique_ptr geosGeom = asGeos( c->geometryN( i ), precision, flags );
2177 if ( flags & Qgis::GeosCreationFlag::RejectOnInvalidSubGeometry && !geosGeom )
2178 {
2179 return nullptr;
2180 }
2181 geomVector.emplace_back( std::move( geosGeom ) );
2182 }
2183 return createGeosCollection( geosType, geomVector );
2184 }
2185 else
2186 {
2187 switch ( QgsWkbTypes::flatType( geom->wkbType() ) )
2188 {
2190 return createGeosPoint( geom, coordDims, precision, flags );
2191
2195#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2197 return createGeosLinestring( geom, precision, flags );
2198#else // GEOS >= 3.15
2199 return createGeosSimpleCurve( geom, precision, flags );
2200
2202 return createGeosCompoundCurve( geom, precision, flags );
2203#endif
2204
2207#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2209#endif
2210 return createGeosPolygon( geom, precision, flags );
2211
2212#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2214 return createGeosCurvePolygon( geom, precision, flags );
2215#endif
2216
2217 case Qgis::WkbType::TIN:
2219 {
2220 // PolyhedralSurface and TIN support
2221 // convert it to a geos MultiPolygon
2223 if ( !polyhedralSurface )
2224 return nullptr;
2225
2226 std::vector<geos::unique_ptr> geomVector;
2227 geomVector.reserve( polyhedralSurface->numPatches() );
2228 for ( int i = 0; i < polyhedralSurface->numPatches(); ++i )
2229 {
2230 geos::unique_ptr geosPolygon = createGeosPolygon( polyhedralSurface->patchN( i ), precision );
2231 if ( flags & Qgis::GeosCreationFlag::RejectOnInvalidSubGeometry && !geosPolygon )
2232 {
2233 return nullptr;
2234 }
2235 geomVector.emplace_back( std::move( geosPolygon ) );
2236 }
2237
2238 return createGeosCollection( GEOS_MULTIPOLYGON, geomVector );
2239 }
2240
2243 default:
2244 return nullptr;
2245 }
2246 }
2247 return nullptr;
2248}
2249
2250std::unique_ptr<QgsAbstractGeometry> QgsGeos::overlay( const QgsAbstractGeometry *geom, Overlay op, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
2251{
2252 if ( !mGeos || !geom )
2253 {
2254 return nullptr;
2255 }
2256
2257 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2258 if ( !geosGeom )
2259 {
2260 return nullptr;
2261 }
2262
2263 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2264
2265 const double gridSize = parameters.gridSize();
2266
2267 GEOSContextHandle_t context = QgsGeosContext::get();
2268 try
2269 {
2270 geos::unique_ptr opGeom;
2271 switch ( op )
2272 {
2273 case OverlayIntersection:
2274 if ( gridSize > 0 )
2275 {
2276 opGeom.reset( GEOSIntersectionPrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2277 }
2278 else
2279 {
2280 opGeom.reset( GEOSIntersection_r( context, mGeos.get(), geosGeom.get() ) );
2281 }
2282 break;
2283
2284 case OverlayDifference:
2285 if ( gridSize > 0 )
2286 {
2287 opGeom.reset( GEOSDifferencePrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2288 }
2289 else
2290 {
2291 opGeom.reset( GEOSDifference_r( context, mGeos.get(), geosGeom.get() ) );
2292 }
2293 break;
2294
2295 case OverlayUnion:
2296 {
2297 geos::unique_ptr unionGeometry;
2298 if ( gridSize > 0 )
2299 {
2300 unionGeometry.reset( GEOSUnionPrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2301 }
2302 else
2303 {
2304 unionGeometry.reset( GEOSUnion_r( context, mGeos.get(), geosGeom.get() ) );
2305 }
2306
2307#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2308 if ( unionGeometry && GEOSGeomTypeId_r( context, unionGeometry.get() ) == GEOS_MULTILINESTRING )
2309 {
2310 geos::unique_ptr mergedLines( GEOSLineMerge_r( context, unionGeometry.get() ) );
2311 if ( mergedLines )
2312 {
2313 unionGeometry = std::move( mergedLines );
2314 }
2315 }
2316#endif
2317
2318 opGeom = std::move( unionGeometry );
2319 }
2320 break;
2321
2322 case OverlaySymDifference:
2323 if ( gridSize > 0 )
2324 {
2325 opGeom.reset( GEOSSymDifferencePrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2326 }
2327 else
2328 {
2329 opGeom.reset( GEOSSymDifference_r( context, mGeos.get(), geosGeom.get() ) );
2330 }
2331 break;
2332 }
2333 return fromGeos( opGeom.get() );
2334 }
2335 catch ( QgsGeosException &e )
2336 {
2337 logError( u"GEOS"_s, e.what() );
2338 if ( errorMsg )
2339 {
2340 *errorMsg = e.what();
2341 }
2342 return nullptr;
2343 }
2344}
2345
2346bool QgsGeos::relation( const QgsAbstractGeometry *geom, Relation r, QString *errorMsg, QgsFeedback *feedback ) const
2347{
2348 if ( !mGeos || !geom )
2349 {
2350 return false;
2351 }
2352
2353 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2354 if ( !geosGeom )
2355 {
2356 return false;
2357 }
2358
2359 GEOSContextHandle_t context = QgsGeosContext::get();
2360 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2361
2362 bool result = false;
2363 try
2364 {
2365 if ( mGeosPrepared ) //use faster version with prepared geometry
2366 {
2367 switch ( r )
2368 {
2369 case RelationIntersects:
2370 result = ( GEOSPreparedIntersects_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2371 break;
2372 case RelationTouches:
2373 result = ( GEOSPreparedTouches_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2374 break;
2375 case RelationCrosses:
2376 result = ( GEOSPreparedCrosses_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2377 break;
2378 case RelationWithin:
2379 result = ( GEOSPreparedWithin_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2380 break;
2381 case RelationContains:
2382 result = ( GEOSPreparedContains_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2383 break;
2384 case RelationDisjoint:
2385 result = ( GEOSPreparedDisjoint_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2386 break;
2387 case RelationOverlaps:
2388 result = ( GEOSPreparedOverlaps_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2389 break;
2390 }
2391 return result;
2392 }
2393
2394 switch ( r )
2395 {
2396 case RelationIntersects:
2397 result = ( GEOSIntersects_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2398 break;
2399 case RelationTouches:
2400 result = ( GEOSTouches_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2401 break;
2402 case RelationCrosses:
2403 result = ( GEOSCrosses_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2404 break;
2405 case RelationWithin:
2406 result = ( GEOSWithin_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2407 break;
2408 case RelationContains:
2409 result = ( GEOSContains_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2410 break;
2411 case RelationDisjoint:
2412 result = ( GEOSDisjoint_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2413 break;
2414 case RelationOverlaps:
2415 result = ( GEOSOverlaps_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2416 break;
2417 }
2418 }
2419 catch ( QgsGeosException &e )
2420 {
2421 logError( u"GEOS"_s, e.what() );
2422 if ( errorMsg )
2423 {
2424 *errorMsg = e.what();
2425 }
2426 return false;
2427 }
2428
2429 return result;
2430}
2431
2432QgsAbstractGeometry *QgsGeos::buffer( double distance, int segments, QString *errorMsg, QgsFeedback *feedback ) const
2433{
2434 if ( !mGeos )
2435 {
2436 return nullptr;
2437 }
2438
2440 try
2441 {
2442 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2443
2444 geos.reset( GEOSBuffer_r( QgsGeosContext::get(), mGeos.get(), distance, segments ) );
2445 }
2446 CATCH_GEOS_WITH_ERRMSG( nullptr )
2447 return fromGeos( geos.get() ).release();
2448}
2449
2450QgsAbstractGeometry *QgsGeos::buffer( double distance, int segments, Qgis::EndCapStyle endCapStyle, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback ) const
2451{
2452 geos::unique_ptr geos = buffer( mGeos.get(), distance, segments, endCapStyle, joinStyle, miterLimit, errorMsg, feedback );
2453 return fromGeos( geos.get() ).release();
2454}
2455
2457 const GEOSGeometry *geometry, double distance, int segments, Qgis::EndCapStyle endCapStyle, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback
2458)
2459{
2460 if ( !geometry )
2461 {
2462 return nullptr;
2463 }
2464
2466 try
2467 {
2468 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2469 geos.reset( GEOSBufferWithStyle_r( QgsGeosContext::get(), geometry, distance, segments, static_cast< int >( endCapStyle ), static_cast< int >( joinStyle ), miterLimit ) );
2470 }
2471 CATCH_GEOS_WITH_ERRMSG( nullptr )
2472 return geos;
2473}
2474
2475QgsAbstractGeometry *QgsGeos::simplify( double tolerance, QString *errorMsg, QgsFeedback *feedback ) const
2476{
2477 if ( !mGeos )
2478 {
2479 return nullptr;
2480 }
2482 try
2483 {
2484 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2485 geos.reset( GEOSTopologyPreserveSimplify_r( QgsGeosContext::get(), mGeos.get(), tolerance ) );
2486 }
2487 CATCH_GEOS_WITH_ERRMSG( nullptr )
2488 return fromGeos( geos.get() ).release();
2489}
2490
2491QgsAbstractGeometry *QgsGeos::interpolate( double distance, QString *errorMsg, QgsFeedback *feedback ) const
2492{
2493 if ( !mGeos )
2494 {
2495 return nullptr;
2496 }
2498 try
2499 {
2500 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2501 geos.reset( GEOSInterpolate_r( QgsGeosContext::get(), mGeos.get(), distance ) );
2502 }
2503 CATCH_GEOS_WITH_ERRMSG( nullptr )
2504 return fromGeos( geos.get() ).release();
2505}
2506
2507QgsPoint *QgsGeos::centroid( QString *errorMsg, QgsFeedback *feedback ) const
2508{
2509 if ( !mGeos )
2510 {
2511 return nullptr;
2512 }
2513
2515 double x;
2516 double y;
2517
2518 GEOSContextHandle_t context = QgsGeosContext::get();
2519 try
2520 {
2521 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2522 geos.reset( GEOSGetCentroid_r( context, mGeos.get() ) );
2523
2524 if ( !geos )
2525 return nullptr;
2526
2527 GEOSGeomGetX_r( context, geos.get(), &x );
2528 GEOSGeomGetY_r( context, geos.get(), &y );
2529 }
2530 CATCH_GEOS_WITH_ERRMSG( nullptr )
2531
2532 return new QgsPoint( x, y );
2533}
2534
2535QgsAbstractGeometry *QgsGeos::envelope( QString *errorMsg ) const
2536{
2537 if ( !mGeos )
2538 {
2539 return nullptr;
2540 }
2542 try
2543 {
2544 geos.reset( GEOSEnvelope_r( QgsGeosContext::get(), mGeos.get() ) );
2545 }
2546 CATCH_GEOS_WITH_ERRMSG( nullptr )
2547 return fromGeos( geos.get() ).release();
2548}
2549
2550QgsPoint *QgsGeos::pointOnSurface( QString *errorMsg, QgsFeedback *feedback ) const
2551{
2552 if ( !mGeos )
2553 {
2554 return nullptr;
2555 }
2556
2557 double x;
2558 double y;
2559
2560 GEOSContextHandle_t context = QgsGeosContext::get();
2562 try
2563 {
2564 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2565 geos.reset( GEOSPointOnSurface_r( context, mGeos.get() ) );
2566
2567 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
2568 {
2569 return nullptr;
2570 }
2571
2572 GEOSGeomGetX_r( context, geos.get(), &x );
2573 GEOSGeomGetY_r( context, geos.get(), &y );
2574 }
2575 CATCH_GEOS_WITH_ERRMSG( nullptr )
2576
2577 return new QgsPoint( x, y );
2578}
2579
2580QgsAbstractGeometry *QgsGeos::convexHull( QString *errorMsg, QgsFeedback *feedback ) const
2581{
2582 if ( !mGeos )
2583 {
2584 return nullptr;
2585 }
2586
2587 try
2588 {
2589 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2590 geos::unique_ptr cHull( GEOSConvexHull_r( QgsGeosContext::get(), mGeos.get() ) );
2591 std::unique_ptr< QgsAbstractGeometry > cHullGeom = fromGeos( cHull.get() );
2592 return cHullGeom.release();
2593 }
2594 CATCH_GEOS_WITH_ERRMSG( nullptr )
2595}
2596
2597std::unique_ptr< QgsAbstractGeometry > QgsGeos::concaveHull( double targetPercent, bool allowHoles, QString *errorMsg, QgsFeedback *feedback ) const
2598{
2599#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 11, 0 )
2600 ( void ) allowHoles;
2601 ( void ) targetPercent;
2602 ( void ) errorMsg;
2603 throw QgsNotSupportedException( QObject::tr( "Calculating concaveHull requires a QGIS build based on GEOS 3.11 or later" ) );
2604#else
2605 if ( !mGeos )
2606 {
2607 return nullptr;
2608 }
2609
2610 try
2611 {
2612 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2613 geos::unique_ptr concaveHull( GEOSConcaveHull_r( QgsGeosContext::get(), mGeos.get(), targetPercent, allowHoles ) );
2614 std::unique_ptr< QgsAbstractGeometry > concaveHullGeom = fromGeos( concaveHull.get() );
2615 return concaveHullGeom;
2616 }
2617 CATCH_GEOS_WITH_ERRMSG( nullptr )
2618#endif
2619}
2620
2621std::unique_ptr<QgsAbstractGeometry> QgsGeos::concaveHullOfPolygons( double lengthRatio, bool allowHoles, bool isTight, QString *errorMsg, QgsFeedback *feedback ) const
2622{
2623#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 11, 0 )
2624 ( void ) allowHoles;
2625 ( void ) targetPercent;
2626 ( void ) errorMsg;
2627 throw QgsNotSupportedException( QObject::tr( "Calculating concaveHullOfPolygons requires a QGIS build based on GEOS 3.11 or later" ) );
2628#else
2629 if ( !mGeos )
2630 {
2631 return nullptr;
2632 }
2633
2634 try
2635 {
2636 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2637 geos::unique_ptr concaveHull( GEOSConcaveHullOfPolygons_r( QgsGeosContext::get(), mGeos.get(), lengthRatio, isTight ? 1 : 0, allowHoles ? 1 : 0 ) );
2638 std::unique_ptr< QgsAbstractGeometry > concaveHullGeom = fromGeos( concaveHull.get() );
2639 return concaveHullGeom;
2640 }
2641 CATCH_GEOS_WITH_ERRMSG( nullptr )
2642#endif
2643}
2644
2645Qgis::CoverageValidityResult QgsGeos::validateCoverage( double gapWidth, std::unique_ptr<QgsAbstractGeometry> *invalidEdges, QString *errorMsg, QgsFeedback *feedback ) const
2646{
2647#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 12, 0 )
2648 ( void ) gapWidth;
2649 ( void ) invalidEdges;
2650 ( void ) errorMsg;
2651 throw QgsNotSupportedException( QObject::tr( "Validating coverages requires a QGIS build based on GEOS 3.12 or later" ) );
2652#else
2653 if ( !mGeos )
2654 {
2655 if ( errorMsg )
2656 *errorMsg = u"Input geometry was not set"_s;
2658 }
2659
2660 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2661 GEOSContextHandle_t context = QgsGeosContext::get();
2662 try
2663 {
2664 GEOSGeometry *invalidEdgesGeos = nullptr;
2665 const int result = GEOSCoverageIsValid_r( context, mGeos.get(), gapWidth, invalidEdges ? &invalidEdgesGeos : nullptr );
2666 if ( invalidEdges && invalidEdgesGeos )
2667 {
2668 *invalidEdges = fromGeos( invalidEdgesGeos );
2669 }
2670 if ( invalidEdgesGeos )
2671 {
2672 GEOSGeom_destroy_r( context, invalidEdgesGeos );
2673 invalidEdgesGeos = nullptr;
2674 }
2675
2676 switch ( result )
2677 {
2678 case 0:
2680 case 1:
2682 case 2:
2683 break;
2684 }
2686 }
2688#endif
2689}
2690
2691std::unique_ptr<QgsAbstractGeometry> QgsGeos::simplifyCoverageVW( double tolerance, bool preserveBoundary, QString *errorMsg, QgsFeedback *feedback ) const
2692{
2693#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 12, 0 )
2694 ( void ) tolerance;
2695 ( void ) preserveBoundary;
2696 ( void ) errorMsg;
2697 throw QgsNotSupportedException( QObject::tr( "Simplifying coverages requires a QGIS build based on GEOS 3.12 or later" ) );
2698#else
2699 if ( !mGeos )
2700 {
2701 if ( errorMsg )
2702 *errorMsg = u"Input geometry was not set"_s;
2703 return nullptr;
2704 }
2705
2706 try
2707 {
2708 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2709 geos::unique_ptr simplified( GEOSCoverageSimplifyVW_r( QgsGeosContext::get(), mGeos.get(), tolerance, preserveBoundary ? 1 : 0 ) );
2710 std::unique_ptr< QgsAbstractGeometry > simplifiedGeom = fromGeos( simplified.get() );
2711 return simplifiedGeom;
2712 }
2713 CATCH_GEOS_WITH_ERRMSG( nullptr )
2714#endif
2715}
2716
2717std::unique_ptr<QgsAbstractGeometry> QgsGeos::unionCoverage( QString *errorMsg, QgsFeedback *feedback ) const
2718{
2719 if ( !mGeos )
2720 {
2721 if ( errorMsg )
2722 *errorMsg = u"Input geometry was not set"_s;
2723 return nullptr;
2724 }
2725
2726 try
2727 {
2728 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2729 geos::unique_ptr unioned( GEOSCoverageUnion_r( QgsGeosContext::get(), mGeos.get() ) );
2730 std::unique_ptr< QgsAbstractGeometry > result = fromGeos( unioned.get() );
2731 return result;
2732 }
2733 CATCH_GEOS_WITH_ERRMSG( nullptr )
2734}
2735
2736std::unique_ptr< QgsAbstractGeometry > QgsGeos::cleanCoverage( const QgsCoverageCleanParameters &parameters, QString *errorMsg, QgsFeedback *feedback ) const
2737{
2738#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 14, 0 )
2739 ( void ) parameters;
2740 ( void ) errorMsg;
2741 ( void ) feedback;
2742 throw QgsNotSupportedException( QObject::tr( "Cleaning coverages requires a QGIS build based on GEOS 3.14 or later" ) );
2743#else
2744 if ( !mGeos )
2745 {
2746 if ( errorMsg )
2747 *errorMsg = u"Input geometry was not set"_s;
2748 return nullptr;
2749 }
2750
2751 GEOSCoverageCleanParams *params = nullptr;
2752 try
2753 {
2754 params = GEOSCoverageCleanParams_create_r( QgsGeosContext::get() );
2755 if ( parameters.snappingDistance() >= 0 )
2756 {
2757 GEOSCoverageCleanParams_setSnappingDistance_r( QgsGeosContext::get(), params, parameters.snappingDistance() );
2758 }
2759 GEOSCoverageCleanParams_setGapMaximumWidth_r( QgsGeosContext::get(), params, parameters.maximumGapWidth() );
2760 switch ( parameters.overlapMergeStrategy() )
2761 {
2763 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 0 );
2764 break;
2766 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 1 );
2767 break;
2769 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 2 );
2770 break;
2772 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 3 );
2773 break;
2774 }
2775
2776 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2777 geos::unique_ptr cleaned( GEOSCoverageCleanWithParams_r( QgsGeosContext::get(), mGeos.get(), params ) );
2778 GEOSCoverageCleanParams_destroy_r( QgsGeosContext::get(), params );
2779
2780 std::unique_ptr< QgsAbstractGeometry> cleanedGeom = fromGeos( cleaned.get() );
2781
2782 return cleanedGeom;
2783 }
2784 catch ( QgsGeosException &e )
2785 {
2786 if ( params )
2787 {
2788 GEOSCoverageCleanParams_destroy_r( QgsGeosContext::get(), params );
2789 params = nullptr;
2790 }
2791
2792 if ( errorMsg )
2793 {
2794 *errorMsg = e.what();
2795 if ( errorMsg->startsWith( "InterruptedException"_L1, Qt::CaseInsensitive ) )
2796 {
2797 errorMsg->clear();
2798 }
2799 }
2800 return nullptr;
2801 }
2802#endif
2803}
2804
2805std::unique_ptr<QgsAbstractGeometry> QgsGeos::extractCoverageEdges( Qgis::CoverageEdgeType edgeType, QString *errorMsg, QgsFeedback *feedback ) const
2806{
2807#if GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR < 15
2808 ( void ) edgeType;
2809 ( void ) errorMsg;
2810 ( void ) feedback;
2811 throw QgsNotSupportedException( QObject::tr( "Extracting coverage edges requires a QGIS build based on GEOS 3.15 or later" ) );
2812#else
2813 if ( !mGeos )
2814 {
2815 if ( errorMsg )
2816 *errorMsg = u"Input geometry was not set"_s;
2817 return nullptr;
2818 }
2819
2820 int geosEdgeType = 0;
2821 switch ( edgeType )
2822 {
2824 geosEdgeType = 0;
2825 break;
2827 geosEdgeType = 1;
2828 break;
2830 geosEdgeType = 2;
2831 break;
2832 }
2833
2834 try
2835 {
2836 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2837 geos::unique_ptr edges( GEOSCoverageEdges_r( QgsGeosContext::get(), mGeos.get(), geosEdgeType ) );
2838
2839 std::unique_ptr< QgsAbstractGeometry> result = fromGeos( edges.get() );
2840
2841 return result;
2842 }
2843 CATCH_GEOS_WITH_ERRMSG( nullptr )
2844#endif
2845}
2846
2847bool QgsGeos::isValid( QString *errorMsg, const bool allowSelfTouchingHoles, QgsGeometry *errorLoc, QgsFeedback *feedback ) const
2848{
2849 if ( !mGeos )
2850 {
2851 if ( errorMsg )
2852 *errorMsg = QObject::tr( "QGIS geometry cannot be converted to a GEOS geometry", "GEOS Error" );
2853 return false;
2854 }
2855
2856 GEOSContextHandle_t context = QgsGeosContext::get();
2857 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2858 try
2859 {
2860 GEOSGeometry *g1 = nullptr;
2861 char *r = nullptr;
2862 char res = GEOSisValidDetail_r( context, mGeos.get(), allowSelfTouchingHoles ? GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE : 0, &r, &g1 );
2863 const bool invalid = res != 1;
2864
2865 QString error;
2866 if ( r )
2867 {
2868 error = QString( r );
2869 GEOSFree_r( context, r );
2870 }
2871
2872 if ( invalid && errorMsg )
2873 {
2874 // Copied from https://github.com/libgeos/geos/blob/main/src/operation/valid/TopologyValidationError.cpp
2875 static const std::map< QString, QString > sTranslatedErrors {
2876 { u"topology validation error"_s, QObject::tr( "Topology validation error", "GEOS Error" ) },
2877 { u"repeated point"_s, QObject::tr( "Repeated point", "GEOS Error" ) },
2878 { u"hole lies outside shell"_s, QObject::tr( "Hole lies outside shell", "GEOS Error" ) },
2879 { u"holes are nested"_s, QObject::tr( "Holes are nested", "GEOS Error" ) },
2880 { u"interior is disconnected"_s, QObject::tr( "Interior is disconnected", "GEOS Error" ) },
2881 { u"self-intersection"_s, QObject::tr( "Self-intersection", "GEOS Error" ) },
2882 { u"ring self-intersection"_s, QObject::tr( "Ring self-intersection", "GEOS Error" ) },
2883 { u"nested shells"_s, QObject::tr( "Nested shells", "GEOS Error" ) },
2884 { u"duplicate rings"_s, QObject::tr( "Duplicate rings", "GEOS Error" ) },
2885 { u"too few points in geometry component"_s, QObject::tr( "Too few points in geometry component", "GEOS Error" ) },
2886 { u"invalid coordinate"_s, QObject::tr( "Invalid coordinate", "GEOS Error" ) },
2887 { u"ring is not closed"_s, QObject::tr( "Ring is not closed", "GEOS Error" ) },
2888 };
2889
2890 const auto translatedError = sTranslatedErrors.find( error.toLower() );
2891 if ( translatedError != sTranslatedErrors.end() )
2892 *errorMsg = translatedError->second;
2893 else
2894 *errorMsg = error;
2895
2896 if ( g1 && errorLoc )
2897 {
2898 *errorLoc = geometryFromGeos( g1 );
2899 }
2900 else if ( g1 )
2901 {
2902 GEOSGeom_destroy_r( context, g1 );
2903 }
2904 }
2905 return !invalid;
2906 }
2907 CATCH_GEOS_WITH_ERRMSG( false )
2908}
2909
2910bool QgsGeos::isEqual( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
2911{
2912 if ( !mGeos || !geom )
2913 {
2914 return false;
2915 }
2916
2917 try
2918 {
2919 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2920 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2921 if ( !geosGeom )
2922 {
2923 return false;
2924 }
2925 bool equal = GEOSEquals_r( QgsGeosContext::get(), mGeos.get(), geosGeom.get() );
2926 return equal;
2927 }
2928 CATCH_GEOS_WITH_ERRMSG( false )
2929}
2930
2931bool QgsGeos::isFuzzyEqual( const QgsAbstractGeometry *geom, double epsilon, QString *errorMsg, QgsFeedback *feedback ) const
2932{
2933 if ( !mGeos || !geom )
2934 {
2935 return false;
2936 }
2937
2938 try
2939 {
2940 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2941
2942 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2943 if ( !geosGeom )
2944 {
2945 return false;
2946 }
2947 bool equal = GEOSEqualsExact_r( QgsGeosContext::get(), mGeos.get(), geosGeom.get(), epsilon );
2948 return equal;
2949 }
2950 CATCH_GEOS_WITH_ERRMSG( false )
2951}
2952
2953bool QgsGeos::isEmpty( QString *errorMsg ) const
2954{
2955 if ( !mGeos )
2956 {
2957 return false;
2958 }
2959
2960 try
2961 {
2962 return GEOSisEmpty_r( QgsGeosContext::get(), mGeos.get() );
2963 }
2964 CATCH_GEOS_WITH_ERRMSG( false )
2965}
2966
2967bool QgsGeos::isSimple( QString *errorMsg ) const
2968{
2969 if ( !mGeos )
2970 {
2971 return false;
2972 }
2973
2974 try
2975 {
2976 return GEOSisSimple_r( QgsGeosContext::get(), mGeos.get() );
2977 }
2978 CATCH_GEOS_WITH_ERRMSG( false )
2979}
2980
2981GEOSCoordSequence *QgsGeos::createCoordinateSequence( const QgsCurve *curve, double precision, bool forceClose )
2982{
2983 GEOSContextHandle_t context = QgsGeosContext::get();
2984 const QgsSimpleCurve *simpleCurve;
2985
2986#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2988 {
2989 simpleCurve = qgsgeometry_cast< const QgsCircularString * >( curve );
2990 }
2991 else
2992 {
2993#endif
2994 simpleCurve = qgsgeometry_cast< const QgsLineString *>( curve );
2995
2996 std::unique_ptr< QgsLineString > segmentized;
2997 if ( !simpleCurve )
2998 {
2999 segmentized.reset( curve->curveToLine() );
3000 simpleCurve = segmentized.get();
3001 }
3002#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
3003 }
3004#endif
3005
3006 if ( !simpleCurve )
3007 {
3008 return nullptr;
3009 }
3010 GEOSCoordSequence *coordSeq = nullptr;
3011
3012 const int numPoints = simpleCurve->numPoints();
3013
3014 const bool hasZ = simpleCurve->is3D();
3015#ifdef GEOS_SUPPORTS_ZM
3016 const bool hasM = simpleCurve->isMeasure();
3017#else
3018 const bool hasM = false; //disabled until geos supports m-coordinates
3019#endif
3020
3021#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
3022 if ( qgsDoubleNear( precision, 0 ) )
3023 {
3024 if ( !forceClose || ( simpleCurve->pointN( 0 ) == simpleCurve->pointN( numPoints - 1 ) ) )
3025 {
3026 // use optimised method if we don't have to force close an open ring
3027 try
3028 {
3029#ifdef GEOS_SUPPORTS_ZM
3030 coordSeq = GEOSCoordSeq_copyFromArrays_r( context, simpleCurve->xData(), simpleCurve->yData(), simpleCurve->zData(), simpleCurve->mData(), numPoints );
3031#else
3032 coordSeq = GEOSCoordSeq_copyFromArrays_r( context, simpleCurve->xData(), simpleCurve->yData(), simpleCurve->zData(), nullptr, numPoints );
3033#endif
3034 if ( !coordSeq )
3035 {
3036 QgsDebugError( u"GEOS Exception: Could not create coordinate sequence for %1 points"_s.arg( numPoints ) );
3037 return nullptr;
3038 }
3039 }
3040 CATCH_GEOS( nullptr )
3041 }
3042 else
3043 {
3044 QVector< double > x = simpleCurve->xVector();
3045 if ( numPoints > 0 )
3046 x.append( x.at( 0 ) );
3047 QVector< double > y = simpleCurve->yVector();
3048 if ( numPoints > 0 )
3049 y.append( y.at( 0 ) );
3050 QVector< double > z = simpleCurve->zVector();
3051 if ( hasZ && numPoints > 0 )
3052 z.append( z.at( 0 ) );
3053 QVector< double > m = simpleCurve->mVector();
3054 if ( hasM && numPoints > 0 )
3055 m.append( m.at( 0 ) );
3056 try
3057 {
3058 coordSeq = GEOSCoordSeq_copyFromArrays_r( context, x.constData(), y.constData(), !hasZ ? nullptr : z.constData(), !hasM ? nullptr : m.constData(), numPoints + 1 );
3059 if ( !coordSeq )
3060 {
3061 QgsDebugError( u"GEOS Exception: Could not create closed coordinate sequence for %1 points"_s.arg( numPoints + 1 ) );
3062 return nullptr;
3063 }
3064 }
3065 CATCH_GEOS( nullptr )
3066 }
3067 return coordSeq;
3068 }
3069#endif
3070
3071 int coordDims = 2;
3072
3073 if ( hasZ )
3074 {
3075 ++coordDims;
3076 }
3077 if ( hasM )
3078 {
3079 ++coordDims;
3080 }
3081
3082 int numOutPoints = numPoints;
3083 if ( forceClose && ( simpleCurve->pointN( 0 ) != simpleCurve->pointN( numPoints - 1 ) ) )
3084 {
3085 ++numOutPoints;
3086 }
3087
3088 try
3089 {
3090 coordSeq = GEOSCoordSeq_create_r( context, numOutPoints, coordDims );
3091 if ( !coordSeq )
3092 {
3093 QgsDebugError( u"GEOS Exception: Could not create coordinate sequence for %1 points in %2 dimensions"_s.arg( numPoints ).arg( coordDims ) );
3094 return nullptr;
3095 }
3096
3097 const double *xData = simpleCurve->xData();
3098 const double *yData = simpleCurve->yData();
3099 const double *zData = hasZ ? simpleCurve->zData() : nullptr;
3100 const double *mData = hasM ? simpleCurve->mData() : nullptr;
3101
3102 if ( precision > 0. )
3103 {
3104 for ( int i = 0; i < numOutPoints; ++i )
3105 {
3106 if ( i >= numPoints )
3107 {
3108 // start reading back from start of line
3109 xData = simpleCurve->xData();
3110 yData = simpleCurve->yData();
3111 zData = hasZ ? simpleCurve->zData() : nullptr;
3112 mData = hasM ? simpleCurve->mData() : nullptr;
3113 }
3114 if ( hasZ )
3115 {
3116 GEOSCoordSeq_setXYZ_r( context, coordSeq, i, std::round( *xData++ / precision ) * precision, std::round( *yData++ / precision ) * precision, std::round( *zData++ / precision ) * precision );
3117 }
3118 else
3119 {
3120 GEOSCoordSeq_setXY_r( context, coordSeq, i, std::round( *xData++ / precision ) * precision, std::round( *yData++ / precision ) * precision );
3121 }
3122 if ( hasM )
3123 {
3124 GEOSCoordSeq_setOrdinate_r( context, coordSeq, i, 3, *mData++ );
3125 }
3126 }
3127 }
3128 else
3129 {
3130 for ( int i = 0; i < numOutPoints; ++i )
3131 {
3132 if ( i >= numPoints )
3133 {
3134 // start reading back from start of line
3135 xData = simpleCurve->xData();
3136 yData = simpleCurve->yData();
3137 zData = hasZ ? simpleCurve->zData() : nullptr;
3138 mData = hasM ? simpleCurve->mData() : nullptr;
3139 }
3140 if ( hasZ )
3141 {
3142 GEOSCoordSeq_setXYZ_r( context, coordSeq, i, *xData++, *yData++, *zData++ );
3143 }
3144 else
3145 {
3146 GEOSCoordSeq_setXY_r( context, coordSeq, i, *xData++, *yData++ );
3147 }
3148 if ( hasM )
3149 {
3150 GEOSCoordSeq_setOrdinate_r( context, coordSeq, i, 3, *mData++ );
3151 }
3152 }
3153 }
3154 }
3155 CATCH_GEOS( nullptr )
3156
3157 return coordSeq;
3158}
3159
3160geos::unique_ptr QgsGeos::createGeosPoint( const QgsAbstractGeometry *point, int coordDims, double precision, Qgis::GeosCreationFlags )
3161{
3162 const QgsPoint *pt = qgsgeometry_cast<const QgsPoint *>( point );
3163 if ( !pt )
3164 return nullptr;
3165
3166 return createGeosPointXY( pt->x(), pt->y(), pt->is3D(), pt->z(), pt->isMeasure(), pt->m(), coordDims, precision );
3167}
3168
3169geos::unique_ptr QgsGeos::createGeosPointXY( double x, double y, bool hasZ, double z, bool hasM, double m, int coordDims, double precision, Qgis::GeosCreationFlags )
3170{
3171#ifndef GEOS_SUPPORTS_ZM
3172 Q_UNUSED( hasM )
3173 Q_UNUSED( m )
3174#endif
3175
3176 geos::unique_ptr geosPoint;
3177 GEOSContextHandle_t context = QgsGeosContext::get();
3178 try
3179 {
3180 if ( coordDims == 2 )
3181 {
3182 // optimised constructor
3183 if ( precision > 0. )
3184 geosPoint.reset( GEOSGeom_createPointFromXY_r( context, std::round( x / precision ) * precision, std::round( y / precision ) * precision ) );
3185 else
3186 geosPoint.reset( GEOSGeom_createPointFromXY_r( context, x, y ) );
3187 return geosPoint;
3188 }
3189
3190#ifdef GEOS_SUPPORTS_ZM
3191 GEOSCoordSequence *coordSeq = GEOSCoordSeq_createWithDimensions_r( context, 1, hasZ ? 1 : 0, hasM ? 1 : 0 );
3192#else
3193 GEOSCoordSequence *coordSeq = GEOSCoordSeq_create_r( context, 1, coordDims );
3194#endif
3195 if ( !coordSeq )
3196 {
3197 QgsDebugError( u"GEOS Exception: Could not create coordinate sequence for point with %1 dimensions"_s.arg( coordDims ) );
3198 return nullptr;
3199 }
3200 if ( precision > 0. )
3201 {
3202 GEOSCoordSeq_setX_r( context, coordSeq, 0, std::round( x / precision ) * precision );
3203 GEOSCoordSeq_setY_r( context, coordSeq, 0, std::round( y / precision ) * precision );
3204 if ( hasZ )
3205 {
3206#ifdef GEOS_SUPPORTS_ZM
3207 GEOSCoordSeq_setZ_r( context, coordSeq, 0, z );
3208#else
3209 GEOSCoordSeq_setOrdinate_r( context, coordSeq, 0, 2, std::round( z / precision ) * precision );
3210#endif
3211 }
3212 }
3213 else
3214 {
3215 GEOSCoordSeq_setX_r( context, coordSeq, 0, x );
3216 GEOSCoordSeq_setY_r( context, coordSeq, 0, y );
3217 if ( hasZ )
3218 {
3219#ifdef GEOS_SUPPORTS_ZM
3220 GEOSCoordSeq_setZ_r( context, coordSeq, 0, z );
3221#else
3222 GEOSCoordSeq_setOrdinate_r( context, coordSeq, 0, 2, z );
3223#endif
3224 }
3225 }
3226#ifdef GEOS_SUPPORTS_ZM
3227 if ( hasM )
3228 {
3229 GEOSCoordSeq_setM_r( context, coordSeq, 0, m );
3230 }
3231#endif
3232 geosPoint.reset( GEOSGeom_createPoint_r( context, coordSeq ) );
3233 }
3234 CATCH_GEOS( nullptr )
3235 return geosPoint;
3236}
3237
3238geos::unique_ptr QgsGeos::createGeosLinestring( const QgsAbstractGeometry *curve, double precision, Qgis::GeosCreationFlags )
3239{
3240 const QgsCurve *c = qgsgeometry_cast<const QgsCurve *>( curve );
3241 if ( !c )
3242 return nullptr;
3243
3244 GEOSCoordSequence *coordSeq = createCoordinateSequence( c, precision );
3245 if ( !coordSeq )
3246 return nullptr;
3247
3248 geos::unique_ptr geosGeom;
3249 try
3250 {
3251 geosGeom.reset( GEOSGeom_createLineString_r( QgsGeosContext::get(), coordSeq ) );
3252 }
3253 CATCH_GEOS( nullptr )
3254 return geosGeom;
3255}
3256
3257#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
3258geos::unique_ptr QgsGeos::createGeosSimpleCurve( const QgsAbstractGeometry *curve, double precision, Qgis::GeosCreationFlags )
3259{
3260 const QgsCurve *c = qgsgeometry_cast<const QgsCurve *>( curve );
3261 if ( !c )
3262 return nullptr;
3263
3264 if ( !c->isSimpleCurve() )
3265 return nullptr;
3266
3267 GEOSCoordSequence *coordSeq = createCoordinateSequence( c, precision );
3268 if ( !coordSeq )
3269 return nullptr;
3270
3271 geos::unique_ptr geosGeom;
3272 try
3273 {
3274 if ( !c->hasCurvedSegments() )
3275 {
3276 geosGeom.reset( GEOSGeom_createLineString_r( QgsGeosContext::get(), coordSeq ) );
3277 }
3278 else
3279 {
3280 geosGeom.reset( GEOSGeom_createCircularString_r( QgsGeosContext::get(), coordSeq ) );
3281 }
3282 }
3283 CATCH_GEOS( nullptr )
3284 return geosGeom;
3285}
3286
3287geos::unique_ptr QgsGeos::createGeosCompoundCurve( const QgsAbstractGeometry *curve, double precision, Qgis::GeosCreationFlags flags )
3288{
3289 const QgsCompoundCurve *c = qgsgeometry_cast<const QgsCompoundCurve *>( curve );
3290 if ( !c )
3291 return nullptr;
3292
3293 GEOSContextHandle_t context = QgsGeosContext::get();
3294 geos::unique_ptr geosCurve;
3295
3296 try
3297 {
3298 const int nCurves = c->nCurves();
3299 GEOSGeometry **curves = new GEOSGeometry *[nCurves];
3300
3301 for ( int i = 0; i < nCurves; i++ )
3302 {
3303 if ( c->curveAt( i )->isSimpleCurve() )
3304 {
3305 curves[i] = createGeosSimpleCurve( c->curveAt( i ), precision, flags ).release();
3306 }
3307 }
3308 geosCurve.reset( GEOSGeom_createCompoundCurve_r( context, curves, nCurves ) );
3309 delete[] curves;
3310 }
3311 CATCH_GEOS( nullptr )
3312 return geosCurve;
3313}
3314
3315geos::unique_ptr QgsGeos::createGeosCurvePolygon( const QgsAbstractGeometry *poly, double precision, Qgis::GeosCreationFlags flags )
3316{
3317 const QgsCurvePolygon *polygon = qgsgeometry_cast<const QgsCurvePolygon *>( poly );
3318 if ( !polygon )
3319 return nullptr;
3320
3321 const QgsCurve *exteriorRing = polygon->exteriorRing();
3322 if ( !exteriorRing )
3323 {
3324 return nullptr;
3325 }
3326
3327 GEOSContextHandle_t context = QgsGeosContext::get();
3328 geos::unique_ptr geosCurvePolygon;
3329 try
3330 {
3331 geos::unique_ptr exteriorRingGeos;
3332 if ( exteriorRing->isSimpleCurve() )
3333 {
3334 exteriorRingGeos.reset( createGeosSimpleCurve( exteriorRing, precision, flags ).release() );
3335 }
3336 else
3337 {
3338 exteriorRingGeos.reset( createGeosCompoundCurve( exteriorRing, precision, flags ).release() );
3339 }
3340
3341 const int nInteriorRings = polygon->numInteriorRings();
3342 QList< const QgsCurve * > holesToExport;
3343 holesToExport.reserve( nInteriorRings );
3344 for ( int i = 0; i < nInteriorRings; ++i )
3345 {
3346 const QgsCurve *interiorRing = polygon->interiorRing( i );
3347 if ( !( flags & Qgis::GeosCreationFlag::SkipEmptyInteriorRings ) || !interiorRing->isEmpty() )
3348 {
3349 holesToExport << interiorRing;
3350 }
3351 }
3352
3353 GEOSGeometry **holes = nullptr;
3354 if ( !holesToExport.empty() )
3355 {
3356 holes = new GEOSGeometry *[holesToExport.size()];
3357 for ( int i = 0; i < holesToExport.size(); ++i )
3358 {
3359 if ( holesToExport[i]->isSimpleCurve() )
3360 {
3361 holes[i] = createGeosSimpleCurve( holesToExport[i], precision, flags ).release();
3362 }
3363 else
3364 {
3365 holes[i] = createGeosCompoundCurve( holesToExport[i], precision, flags ).release();
3366 }
3367 }
3368 }
3369
3370 geosCurvePolygon.reset( GEOSGeom_createCurvePolygon_r( context, exteriorRingGeos.release(), holes, holesToExport.size() ) );
3371 delete[] holes;
3372 }
3373 CATCH_GEOS( nullptr )
3374
3375 return geosCurvePolygon;
3376}
3377#endif
3378
3379geos::unique_ptr QgsGeos::createGeosPolygon( const QgsAbstractGeometry *poly, double precision, Qgis::GeosCreationFlags flags )
3380{
3381 const QgsCurvePolygon *polygon = qgsgeometry_cast<const QgsCurvePolygon *>( poly );
3382 if ( !polygon )
3383 return nullptr;
3384
3385 const QgsCurve *exteriorRing = polygon->exteriorRing();
3386 if ( !exteriorRing )
3387 {
3388 return nullptr;
3389 }
3390
3391 GEOSContextHandle_t context = QgsGeosContext::get();
3392 geos::unique_ptr geosPolygon;
3393 try
3394 {
3395 geos::unique_ptr exteriorRingGeos( GEOSGeom_createLinearRing_r( context, createCoordinateSequence( exteriorRing, precision, true ) ) );
3396
3397 const int nInteriorRings = polygon->numInteriorRings();
3398 QList< const QgsCurve * > holesToExport;
3399 holesToExport.reserve( nInteriorRings );
3400 for ( int i = 0; i < nInteriorRings; ++i )
3401 {
3402 const QgsCurve *interiorRing = polygon->interiorRing( i );
3403 if ( !( flags & Qgis::GeosCreationFlag::SkipEmptyInteriorRings ) || !interiorRing->isEmpty() )
3404 {
3405 holesToExport << interiorRing;
3406 }
3407 }
3408
3409 GEOSGeometry **holes = nullptr;
3410 if ( !holesToExport.empty() )
3411 {
3412 holes = new GEOSGeometry *[holesToExport.size()];
3413 for ( int i = 0; i < holesToExport.size(); ++i )
3414 {
3415 holes[i] = GEOSGeom_createLinearRing_r( context, createCoordinateSequence( holesToExport[i], precision, true ) );
3416 }
3417 }
3418
3419 geosPolygon.reset( GEOSGeom_createPolygon_r( context, exteriorRingGeos.release(), holes, holesToExport.size() ) );
3420 delete[] holes;
3421 }
3422 CATCH_GEOS( nullptr )
3423
3424 return geosPolygon;
3425}
3426
3427geos::unique_ptr QgsGeos::offsetCurve( const GEOSGeometry *geometry, double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback )
3428{
3429 if ( !geometry )
3430 return nullptr;
3431
3432 geos::unique_ptr offset;
3433 try
3434 {
3435 // Force quadrant segments to be at least 8, see
3436 // https://github.com/qgis/QGIS/issues/53165#issuecomment-1563470832
3437 if ( segments < 8 )
3438 segments = 8;
3439 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3440 offset.reset( GEOSOffsetCurve_r( QgsGeosContext::get(), geometry, distance, segments, static_cast< int >( joinStyle ), miterLimit ) );
3441 }
3442 CATCH_GEOS_WITH_ERRMSG( nullptr )
3443 return offset;
3444}
3445
3446QgsAbstractGeometry *QgsGeos::offsetCurve( double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback ) const
3447{
3448 geos::unique_ptr res = offsetCurve( mGeos.get(), distance, segments, joinStyle, miterLimit, errorMsg, feedback );
3449 if ( !res )
3450 return nullptr;
3451
3452 return fromGeos( res.get() ).release();
3453}
3454
3455std::unique_ptr<QgsAbstractGeometry> QgsGeos::singleSidedBuffer(
3456 double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback
3457) const
3458{
3459 if ( !mGeos )
3460 {
3461 return nullptr;
3462 }
3463
3465 GEOSContextHandle_t context = QgsGeosContext::get();
3466 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3467 try
3468 {
3469 geos::buffer_params_unique_ptr bp( GEOSBufferParams_create_r( context ) );
3470 GEOSBufferParams_setSingleSided_r( context, bp.get(), 1 );
3471 GEOSBufferParams_setQuadrantSegments_r( context, bp.get(), segments );
3472 GEOSBufferParams_setJoinStyle_r( context, bp.get(), static_cast< int >( joinStyle ) );
3473 GEOSBufferParams_setMitreLimit_r( context, bp.get(), miterLimit ); //#spellok
3474
3475 if ( side == Qgis::BufferSide::Right )
3476 {
3477 distance = -distance;
3478 }
3479 geos.reset( GEOSBufferWithParams_r( context, mGeos.get(), bp.get(), distance ) );
3480 }
3481 CATCH_GEOS_WITH_ERRMSG( nullptr )
3482 return fromGeos( geos.get() );
3483}
3484
3485std::unique_ptr<QgsAbstractGeometry> QgsGeos::maximumInscribedCircle( double tolerance, QString *errorMsg, QgsFeedback *feedback ) const
3486{
3487 if ( !mGeos )
3488 {
3489 return nullptr;
3490 }
3491
3493 try
3494 {
3495 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3496 geos.reset( GEOSMaximumInscribedCircle_r( QgsGeosContext::get(), mGeos.get(), tolerance ) );
3497 }
3498 CATCH_GEOS_WITH_ERRMSG( nullptr )
3499 return fromGeos( geos.get() );
3500}
3501
3502std::unique_ptr<QgsAbstractGeometry> QgsGeos::largestEmptyCircle( double tolerance, const QgsAbstractGeometry *boundary, QString *errorMsg, QgsFeedback *feedback ) const
3503{
3504 if ( !mGeos )
3505 {
3506 return nullptr;
3507 }
3508
3510 try
3511 {
3512 geos::unique_ptr boundaryGeos;
3513 if ( boundary )
3514 boundaryGeos = asGeos( boundary );
3515
3516 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3517 geos.reset( GEOSLargestEmptyCircle_r( QgsGeosContext::get(), mGeos.get(), boundaryGeos.get(), tolerance ) );
3518 }
3519 CATCH_GEOS_WITH_ERRMSG( nullptr )
3520 return fromGeos( geos.get() );
3521}
3522
3523std::unique_ptr<QgsAbstractGeometry> QgsGeos::minimumWidth( QString *errorMsg, QgsFeedback *feedback ) const
3524{
3525 if ( !mGeos )
3526 {
3527 return nullptr;
3528 }
3529
3531 try
3532 {
3533 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3534 geos.reset( GEOSMinimumWidth_r( QgsGeosContext::get(), mGeos.get() ) );
3535 }
3536 CATCH_GEOS_WITH_ERRMSG( nullptr )
3537 return fromGeos( geos.get() );
3538}
3539
3540double QgsGeos::minimumClearance( QString *errorMsg, QgsFeedback *feedback ) const
3541{
3542 if ( !mGeos )
3543 {
3544 return std::numeric_limits< double >::quiet_NaN();
3545 }
3546
3548 double res = 0;
3549 try
3550 {
3551 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3552 if ( GEOSMinimumClearance_r( QgsGeosContext::get(), mGeos.get(), &res ) != 0 )
3553 return std::numeric_limits< double >::quiet_NaN();
3554 }
3555 CATCH_GEOS_WITH_ERRMSG( std::numeric_limits< double >::quiet_NaN() )
3556 return res;
3557}
3558
3559std::unique_ptr<QgsAbstractGeometry> QgsGeos::minimumClearanceLine( QString *errorMsg, QgsFeedback *feedback ) const
3560{
3561 if ( !mGeos )
3562 {
3563 return nullptr;
3564 }
3565
3567 try
3568 {
3569 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3570 geos.reset( GEOSMinimumClearanceLine_r( QgsGeosContext::get(), mGeos.get() ) );
3571 }
3572 CATCH_GEOS_WITH_ERRMSG( nullptr )
3573 return fromGeos( geos.get() );
3574}
3575
3576std::unique_ptr<QgsAbstractGeometry> QgsGeos::node( QString *errorMsg, QgsFeedback *feedback ) const
3577{
3578 if ( !mGeos )
3579 {
3580 return nullptr;
3581 }
3582
3584 try
3585 {
3586 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3587 geos.reset( GEOSNode_r( QgsGeosContext::get(), mGeos.get() ) );
3588 }
3589 CATCH_GEOS_WITH_ERRMSG( nullptr )
3590 return fromGeos( geos.get() );
3591}
3592
3593std::unique_ptr<QgsAbstractGeometry> QgsGeos::sharedPaths( const QgsAbstractGeometry *other, QString *errorMsg, QgsFeedback *feedback ) const
3594{
3595 if ( !mGeos || !other )
3596 {
3597 return nullptr;
3598 }
3599
3601 try
3602 {
3603 geos::unique_ptr otherGeos = asGeos( other );
3604 if ( !otherGeos )
3605 return nullptr;
3606
3607 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3608 geos.reset( GEOSSharedPaths_r( QgsGeosContext::get(), mGeos.get(), otherGeos.get() ) );
3609 }
3610 CATCH_GEOS_WITH_ERRMSG( nullptr )
3611 return fromGeos( geos.get() );
3612}
3613
3614std::unique_ptr<QgsAbstractGeometry> QgsGeos::reshapeGeometry( const QgsLineString &reshapeWithLine, EngineOperationResult *errorCode, QString *errorMsg ) const
3615{
3616 if ( !mGeos || mGeometry->dimension() == 0 )
3617 {
3618 if ( errorCode )
3619 {
3620 *errorCode = InvalidBaseGeometry;
3621 }
3622 return nullptr;
3623 }
3624
3625 if ( reshapeWithLine.numPoints() < 2 )
3626 {
3627 if ( errorCode )
3628 {
3629 *errorCode = InvalidInput;
3630 }
3631 return nullptr;
3632 }
3633
3634 geos::unique_ptr reshapeLineGeos = createGeosLinestring( &reshapeWithLine, mPrecision );
3635
3636 GEOSContextHandle_t context = QgsGeosContext::get();
3637 //single or multi?
3638 int numGeoms = GEOSGetNumGeometries_r( context, mGeos.get() );
3639 if ( numGeoms == -1 )
3640 {
3641 if ( errorCode )
3642 {
3643 *errorCode = InvalidBaseGeometry;
3644 }
3645 return nullptr;
3646 }
3647
3648 bool isMultiGeom = false;
3649 int geosTypeId = GEOSGeomTypeId_r( context, mGeos.get() );
3650 if ( geosTypeId == GEOS_MULTILINESTRING || geosTypeId == GEOS_MULTIPOLYGON )
3651 isMultiGeom = true;
3652
3653 bool isLine = ( mGeometry->dimension() == 1 );
3654
3655 if ( !isMultiGeom )
3656 {
3657 geos::unique_ptr reshapedGeometry;
3658 if ( isLine )
3659 {
3660 reshapedGeometry = reshapeLine( mGeos.get(), reshapeLineGeos.get(), mPrecision );
3661 }
3662 else
3663 {
3664 reshapedGeometry = reshapePolygon( mGeos.get(), reshapeLineGeos.get(), mPrecision );
3665 }
3666
3667 if ( errorCode )
3668 {
3669 if ( reshapedGeometry )
3670 *errorCode = Success;
3671 else
3672 *errorCode = NothingHappened;
3673 }
3674
3675 std::unique_ptr< QgsAbstractGeometry > reshapeResult = fromGeos( reshapedGeometry.get() );
3676 return reshapeResult;
3677 }
3678 else
3679 {
3680 try
3681 {
3682 //call reshape for each geometry part and replace mGeos with new geometry if reshape took place
3683 bool reshapeTookPlace = false;
3684
3685 geos::unique_ptr currentReshapeGeometry;
3686 GEOSGeometry **newGeoms = new GEOSGeometry *[numGeoms];
3687
3688 for ( int i = 0; i < numGeoms; ++i )
3689 {
3690 if ( isLine )
3691 currentReshapeGeometry = reshapeLine( GEOSGetGeometryN_r( context, mGeos.get(), i ), reshapeLineGeos.get(), mPrecision );
3692 else
3693 currentReshapeGeometry = reshapePolygon( GEOSGetGeometryN_r( context, mGeos.get(), i ), reshapeLineGeos.get(), mPrecision );
3694
3695 if ( currentReshapeGeometry )
3696 {
3697 newGeoms[i] = currentReshapeGeometry.release();
3698 reshapeTookPlace = true;
3699 }
3700 else
3701 {
3702 newGeoms[i] = GEOSGeom_clone_r( context, GEOSGetGeometryN_r( context, mGeos.get(), i ) );
3703 }
3704 }
3705
3706 geos::unique_ptr newMultiGeom;
3707 if ( isLine )
3708 {
3709 newMultiGeom.reset( GEOSGeom_createCollection_r( context, GEOS_MULTILINESTRING, newGeoms, numGeoms ) );
3710 }
3711 else //multipolygon
3712 {
3713 newMultiGeom.reset( GEOSGeom_createCollection_r( context, GEOS_MULTIPOLYGON, newGeoms, numGeoms ) );
3714 }
3715
3716 delete[] newGeoms;
3717 if ( !newMultiGeom )
3718 {
3719 if ( errorCode )
3720 {
3721 *errorCode = EngineError;
3722 }
3723 return nullptr;
3724 }
3725
3726 if ( reshapeTookPlace )
3727 {
3728 if ( errorCode )
3729 *errorCode = Success;
3730 std::unique_ptr< QgsAbstractGeometry > reshapedMultiGeom = fromGeos( newMultiGeom.get() );
3731 return reshapedMultiGeom;
3732 }
3733 else
3734 {
3735 if ( errorCode )
3736 {
3737 *errorCode = NothingHappened;
3738 }
3739 return nullptr;
3740 }
3741 }
3742 CATCH_GEOS_WITH_ERRMSG( nullptr )
3743 }
3744}
3745
3746std::unique_ptr< QgsAbstractGeometry > QgsGeos::mergeLines( QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
3747{
3748 if ( !mGeos )
3749 {
3750 return nullptr;
3751 }
3752
3753 GEOSContextHandle_t context = QgsGeosContext::get();
3754 if ( GEOSGeomTypeId_r( context, mGeos.get() ) != GEOS_MULTILINESTRING )
3755 return nullptr;
3756
3757 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3759 try
3760 {
3761 double gridSize = parameters.gridSize();
3762 if ( gridSize > 0 )
3763 {
3764 geos::unique_ptr geosFixedSize( GEOSGeom_setPrecision_r( context, mGeos.get(), gridSize, 0 ) );
3765 geos.reset( GEOSLineMerge_r( context, geosFixedSize.get() ) );
3766 }
3767 else
3768 geos.reset( GEOSLineMerge_r( context, mGeos.get() ) );
3769 }
3770 CATCH_GEOS_WITH_ERRMSG( nullptr )
3771 return fromGeos( geos.get() );
3772}
3773
3774std::unique_ptr<QgsAbstractGeometry> QgsGeos::closestPoint( const QgsGeometry &other, QString *errorMsg, QgsFeedback *feedback ) const
3775{
3776 if ( !mGeos || isEmpty() || other.isEmpty() )
3777 {
3778 return nullptr;
3779 }
3780
3781 geos::unique_ptr otherGeom( asGeos( other.constGet(), mPrecision ) );
3782 if ( !otherGeom )
3783 {
3784 return nullptr;
3785 }
3786
3787 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3788 GEOSContextHandle_t context = QgsGeosContext::get();
3789 double nx = 0.0;
3790 double ny = 0.0;
3791 try
3792 {
3794 if ( mGeosPrepared ) // use faster version with prepared geometry
3795 {
3796 nearestCoord.reset( GEOSPreparedNearestPoints_r( context, mGeosPrepared.get(), otherGeom.get() ) );
3797 }
3798 else
3799 {
3800 nearestCoord.reset( GEOSNearestPoints_r( context, mGeos.get(), otherGeom.get() ) );
3801 }
3802
3803 ( void ) GEOSCoordSeq_getX_r( context, nearestCoord.get(), 0, &nx );
3804 ( void ) GEOSCoordSeq_getY_r( context, nearestCoord.get(), 0, &ny );
3805 }
3806 catch ( QgsGeosException &e )
3807 {
3808 logError( u"GEOS"_s, e.what() );
3809 if ( errorMsg )
3810 {
3811 *errorMsg = e.what();
3812 }
3813 return nullptr;
3814 }
3815
3816 return std::make_unique< QgsPoint >( nx, ny );
3817}
3818
3819std::unique_ptr<QgsAbstractGeometry> QgsGeos::shortestLine( const QgsGeometry &other, QString *errorMsg, QgsFeedback *feedback ) const
3820{
3821 if ( !mGeos || other.isEmpty() )
3822 {
3823 return nullptr;
3824 }
3825
3826 return shortestLine( other.constGet(), errorMsg, feedback );
3827}
3828
3829std::unique_ptr< QgsAbstractGeometry > QgsGeos::shortestLine( const QgsAbstractGeometry *other, QString *errorMsg, QgsFeedback *feedback ) const
3830{
3831 if ( !other || other->isEmpty() )
3832 return nullptr;
3833
3834 geos::unique_ptr otherGeom( asGeos( other, mPrecision ) );
3835 if ( !otherGeom )
3836 {
3837 return nullptr;
3838 }
3839
3840 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3841 GEOSContextHandle_t context = QgsGeosContext::get();
3842 double nx1 = 0.0;
3843 double ny1 = 0.0;
3844 double nx2 = 0.0;
3845 double ny2 = 0.0;
3846 try
3847 {
3848 geos::coord_sequence_unique_ptr nearestCoord( GEOSNearestPoints_r( context, mGeos.get(), otherGeom.get() ) );
3849
3850 if ( !nearestCoord )
3851 {
3852 if ( errorMsg )
3853 *errorMsg = u"GEOS returned no nearest points"_s;
3854 return nullptr;
3855 }
3856
3857 ( void ) GEOSCoordSeq_getX_r( context, nearestCoord.get(), 0, &nx1 );
3858 ( void ) GEOSCoordSeq_getY_r( context, nearestCoord.get(), 0, &ny1 );
3859 ( void ) GEOSCoordSeq_getX_r( context, nearestCoord.get(), 1, &nx2 );
3860 ( void ) GEOSCoordSeq_getY_r( context, nearestCoord.get(), 1, &ny2 );
3861 }
3862 catch ( QgsGeosException &e )
3863 {
3864 logError( u"GEOS"_s, e.what() );
3865 if ( errorMsg )
3866 {
3867 *errorMsg = e.what();
3868 }
3869 return nullptr;
3870 }
3871
3872 auto line = std::make_unique< QgsLineString >();
3873 line->addVertex( QgsPoint( nx1, ny1 ) );
3874 line->addVertex( QgsPoint( nx2, ny2 ) );
3875 return line;
3876}
3877
3878double QgsGeos::lineLocatePoint( const QgsPoint &point, QString *errorMsg, QgsFeedback *feedback ) const
3879{
3880 if ( !mGeos )
3881 {
3882 return -1;
3883 }
3884
3885 geos::unique_ptr otherGeom( asGeos( &point, mPrecision ) );
3886 if ( !otherGeom )
3887 {
3888 return -1;
3889 }
3890
3891 double distance = -1;
3892 try
3893 {
3894 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3895 distance = GEOSProject_r( QgsGeosContext::get(), mGeos.get(), otherGeom.get() );
3896 }
3897 catch ( QgsGeosException &e )
3898 {
3899 logError( u"GEOS"_s, e.what() );
3900 if ( errorMsg )
3901 {
3902 *errorMsg = e.what();
3903 }
3904 return -1;
3905 }
3906
3907 return distance;
3908}
3909
3910double QgsGeos::lineLocatePoint( double x, double y, QString *errorMsg, QgsFeedback *feedback ) const
3911{
3912 if ( !mGeos )
3913 {
3914 return -1;
3915 }
3916
3917 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
3918 if ( !point )
3919 return false;
3920
3921 double distance = -1;
3922 try
3923 {
3924 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3925 distance = GEOSProject_r( QgsGeosContext::get(), mGeos.get(), point.get() );
3926 }
3927 catch ( QgsGeosException &e )
3928 {
3929 logError( u"GEOS"_s, e.what() );
3930 if ( errorMsg )
3931 {
3932 *errorMsg = e.what();
3933 }
3934 return -1;
3935 }
3936
3937 return distance;
3938}
3939
3940QgsGeometry QgsGeos::polygonize( const QVector<const QgsAbstractGeometry *> &geometries, QString *errorMsg, QgsFeedback *feedback )
3941{
3942 GEOSGeometry **const lineGeosGeometries = new GEOSGeometry *[geometries.size()];
3943 int validLines = 0;
3944 for ( const QgsAbstractGeometry *g : geometries )
3945 {
3946 geos::unique_ptr l = asGeos( g );
3947 if ( l )
3948 {
3949 lineGeosGeometries[validLines] = l.release();
3950 validLines++;
3951 }
3952 }
3953
3954 GEOSContextHandle_t context = QgsGeosContext::get();
3955 try
3956 {
3957 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3958 geos::unique_ptr result( GEOSPolygonize_r( context, lineGeosGeometries, validLines ) );
3959 for ( int i = 0; i < validLines; ++i )
3960 {
3961 GEOSGeom_destroy_r( context, lineGeosGeometries[i] );
3962 }
3963 delete[] lineGeosGeometries;
3964 return QgsGeometry( fromGeos( result.get() ) );
3965 }
3966 catch ( QgsGeosException &e )
3967 {
3968 if ( errorMsg )
3969 {
3970 *errorMsg = e.what();
3971 }
3972 for ( int i = 0; i < validLines; ++i )
3973 {
3974 GEOSGeom_destroy_r( context, lineGeosGeometries[i] );
3975 }
3976 delete[] lineGeosGeometries;
3977 return QgsGeometry();
3978 }
3979}
3980
3981std::unique_ptr<QgsAbstractGeometry> QgsGeos::voronoiDiagram( const QgsAbstractGeometry *extent, double tolerance, bool edgesOnly, QString *errorMsg, QgsFeedback *feedback ) const
3982{
3983 if ( !mGeos )
3984 {
3985 return nullptr;
3986 }
3987
3988 geos::unique_ptr extentGeosGeom;
3989 if ( extent )
3990 {
3991 extentGeosGeom = asGeos( extent, mPrecision );
3992 if ( !extentGeosGeom )
3993 {
3994 return nullptr;
3995 }
3996 }
3997
3999 GEOSContextHandle_t context = QgsGeosContext::get();
4000 try
4001 {
4002 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
4003 geos.reset( GEOSVoronoiDiagram_r( context, mGeos.get(), extentGeosGeom.get(), tolerance, edgesOnly ) );
4004
4005 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
4006 {
4007 return nullptr;
4008 }
4009
4010 return fromGeos( geos.get() );
4011 }
4012 CATCH_GEOS_WITH_ERRMSG( nullptr )
4013}
4014
4015std::unique_ptr<QgsAbstractGeometry> QgsGeos::delaunayTriangulation( double tolerance, bool edgesOnly, QString *errorMsg, QgsFeedback *feedback ) const
4016{
4017 if ( !mGeos )
4018 {
4019 return nullptr;
4020 }
4021
4022 GEOSContextHandle_t context = QgsGeosContext::get();
4024 try
4025 {
4026 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
4027 geos.reset( GEOSDelaunayTriangulation_r( context, mGeos.get(), tolerance, edgesOnly ) );
4028
4029 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
4030 {
4031 return nullptr;
4032 }
4033
4034 return fromGeos( geos.get() );
4035 }
4036 CATCH_GEOS_WITH_ERRMSG( nullptr )
4037}
4038
4039std::unique_ptr<QgsAbstractGeometry> QgsGeos::constrainedDelaunayTriangulation( QString *errorMsg, QgsFeedback *feedback ) const
4040{
4041#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 11, 0 )
4042 ( void ) errorMsg;
4043 throw QgsNotSupportedException( QObject::tr( "Calculating constrainedDelaunayTriangulation requires a QGIS build based on GEOS 3.11 or later" ) );
4044#else
4045 if ( !mGeos )
4046 {
4047 return nullptr;
4048 }
4049
4051 GEOSContextHandle_t context = QgsGeosContext::get();
4052 try
4053 {
4054 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
4055 geos.reset( GEOSConstrainedDelaunayTriangulation_r( context, mGeos.get() ) );
4056
4057 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
4058 {
4059 return nullptr;
4060 }
4061
4062 std::unique_ptr< QgsAbstractGeometry > res = fromGeos( geos.get() );
4063 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( res.get() ) )
4064 {
4065 return std::unique_ptr< QgsAbstractGeometry >( collection->extractPartsByType( Qgis::WkbType::Polygon, true ) );
4066 }
4067 else
4068 {
4069 return res;
4070 }
4071 }
4072 CATCH_GEOS_WITH_ERRMSG( nullptr )
4073#endif
4074}
4075
4077static bool _linestringEndpoints( const GEOSGeometry *linestring, double &x1, double &y1, double &x2, double &y2 )
4078{
4079 GEOSContextHandle_t context = QgsGeosContext::get();
4080 const GEOSCoordSequence *coordSeq = GEOSGeom_getCoordSeq_r( context, linestring );
4081 if ( !coordSeq )
4082 return false;
4083
4084 unsigned int coordSeqSize;
4085 if ( GEOSCoordSeq_getSize_r( context, coordSeq, &coordSeqSize ) == 0 )
4086 return false;
4087
4088 if ( coordSeqSize < 2 )
4089 return false;
4090
4091 GEOSCoordSeq_getX_r( context, coordSeq, 0, &x1 );
4092 GEOSCoordSeq_getY_r( context, coordSeq, 0, &y1 );
4093 GEOSCoordSeq_getX_r( context, coordSeq, coordSeqSize - 1, &x2 );
4094 GEOSCoordSeq_getY_r( context, coordSeq, coordSeqSize - 1, &y2 );
4095 return true;
4096}
4097
4098
4100static geos::unique_ptr _mergeLinestrings( const GEOSGeometry *line1, const GEOSGeometry *line2, const QgsPointXY &intersectionPoint )
4101{
4102 double x1, y1, x2, y2;
4103 if ( !_linestringEndpoints( line1, x1, y1, x2, y2 ) )
4104 return nullptr;
4105
4106 double rx1, ry1, rx2, ry2;
4107 if ( !_linestringEndpoints( line2, rx1, ry1, rx2, ry2 ) )
4108 return nullptr;
4109
4110 bool intersectionAtOrigLineEndpoint = ( intersectionPoint.x() == x1 && intersectionPoint.y() == y1 ) != ( intersectionPoint.x() == x2 && intersectionPoint.y() == y2 );
4111 bool intersectionAtReshapeLineEndpoint = ( intersectionPoint.x() == rx1 && intersectionPoint.y() == ry1 ) || ( intersectionPoint.x() == rx2 && intersectionPoint.y() == ry2 );
4112
4113 GEOSContextHandle_t context = QgsGeosContext::get();
4114 // the intersection must be at the begin/end of both lines
4115 if ( intersectionAtOrigLineEndpoint && intersectionAtReshapeLineEndpoint )
4116 {
4117 geos::unique_ptr g1( GEOSGeom_clone_r( context, line1 ) );
4118 geos::unique_ptr g2( GEOSGeom_clone_r( context, line2 ) );
4119 GEOSGeometry *geoms[2] = { g1.release(), g2.release() };
4120 geos::unique_ptr multiGeom( GEOSGeom_createCollection_r( context, GEOS_MULTILINESTRING, geoms, 2 ) );
4121 geos::unique_ptr res( GEOSLineMerge_r( context, multiGeom.get() ) );
4122
4123 //keep the original orientation if the result has a start or end point in common with the original line
4124 //and this point is not the start or the end point for both lines
4125 double x1res, y1res, x2res, y2res;
4126 if ( !_linestringEndpoints( res.get(), x1res, y1res, x2res, y2res ) )
4127 return nullptr;
4128 if ( ( x1res == x2 && y1res == y2 ) || ( x2res == x1 && y2res == y1 ) )
4129 res.reset( GEOSReverse_r( context, res.get() ) );
4130
4131 return res;
4132 }
4133 else
4134 return nullptr;
4135}
4136
4137
4138geos::unique_ptr QgsGeos::reshapeLine( const GEOSGeometry *line, const GEOSGeometry *reshapeLineGeos, double precision )
4139{
4140 if ( !line || !reshapeLineGeos )
4141 return nullptr;
4142
4143 bool atLeastTwoIntersections = false;
4144 bool oneIntersection = false;
4145 QgsPointXY oneIntersectionPoint;
4146
4147 GEOSContextHandle_t context = QgsGeosContext::get();
4148 try
4149 {
4150 //make sure there are at least two intersection between line and reshape geometry
4151 geos::unique_ptr intersectGeom( GEOSIntersection_r( context, line, reshapeLineGeos ) );
4152 if ( intersectGeom )
4153 {
4154 const int geomType = GEOSGeomTypeId_r( context, intersectGeom.get() );
4155 atLeastTwoIntersections = ( geomType == GEOS_MULTIPOINT && GEOSGetNumGeometries_r( context, intersectGeom.get() ) > 1 )
4156 || ( geomType == GEOS_GEOMETRYCOLLECTION && GEOSGetNumGeometries_r( context, intersectGeom.get() ) > 0 ) // a collection implies at least two points!
4157 || ( geomType == GEOS_MULTILINESTRING && GEOSGetNumGeometries_r( context, intersectGeom.get() ) > 0 );
4158 // one point is enough when extending line at its endpoint
4159 if ( GEOSGeomTypeId_r( context, intersectGeom.get() ) == GEOS_POINT )
4160 {
4161 const GEOSCoordSequence *intersectionCoordSeq = GEOSGeom_getCoordSeq_r( context, intersectGeom.get() );
4162 double xi, yi;
4163 GEOSCoordSeq_getX_r( context, intersectionCoordSeq, 0, &xi );
4164 GEOSCoordSeq_getY_r( context, intersectionCoordSeq, 0, &yi );
4165 oneIntersection = true;
4166 oneIntersectionPoint = QgsPointXY( xi, yi );
4167 }
4168 }
4169 }
4170 catch ( QgsGeosException & )
4171 {
4172 atLeastTwoIntersections = false;
4173 }
4174
4175 // special case when extending line at its endpoint
4176 if ( oneIntersection )
4177 return _mergeLinestrings( line, reshapeLineGeos, oneIntersectionPoint );
4178
4179 if ( !atLeastTwoIntersections )
4180 return nullptr;
4181
4182 //begin and end point of original line
4183 double x1, y1, x2, y2;
4184 if ( !_linestringEndpoints( line, x1, y1, x2, y2 ) )
4185 return nullptr;
4186
4187 geos::unique_ptr beginLineVertex = createGeosPointXY( x1, y1, false, 0, false, 0, 2, precision );
4188 geos::unique_ptr endLineVertex = createGeosPointXY( x2, y2, false, 0, false, 0, 2, precision );
4189
4190 bool isRing = false;
4191 if ( GEOSGeomTypeId_r( context, line ) == GEOS_LINEARRING || GEOSEquals_r( context, beginLineVertex.get(), endLineVertex.get() ) == 1 )
4192 isRing = true;
4193
4194 //node line and reshape line
4195 geos::unique_ptr nodedGeometry = nodeGeometries( reshapeLineGeos, line );
4196 if ( !nodedGeometry )
4197 {
4198 return nullptr;
4199 }
4200
4201 //and merge them together
4202 geos::unique_ptr mergedLines( GEOSLineMerge_r( context, nodedGeometry.get() ) );
4203 if ( !mergedLines )
4204 {
4205 return nullptr;
4206 }
4207
4208 int numMergedLines = GEOSGetNumGeometries_r( context, mergedLines.get() );
4209 if ( numMergedLines < 2 ) //some special cases. Normally it is >2
4210 {
4211 if ( numMergedLines == 1 ) //reshape line is from begin to endpoint. So we keep the reshapeline
4212 {
4213 geos::unique_ptr result( GEOSGeom_clone_r( context, reshapeLineGeos ) );
4214 return result;
4215 }
4216 else
4217 return nullptr;
4218 }
4219
4220 QVector<GEOSGeometry *> resultLineParts; //collection with the line segments that will be contained in result
4221 QVector<GEOSGeometry *> probableParts; //parts where we can decide on inclusion only after going through all the candidates
4222
4223 for ( int i = 0; i < numMergedLines; ++i )
4224 {
4225 const GEOSGeometry *currentGeom = GEOSGetGeometryN_r( context, mergedLines.get(), i );
4226
4227 // have we already added this part?
4228 bool alreadyAdded = false;
4229 double distance = 0;
4230 double bufferDistance = std::pow( 10.0L, geomDigits( currentGeom ) - 11 );
4231 for ( const GEOSGeometry *other : std::as_const( resultLineParts ) )
4232 {
4233 GEOSHausdorffDistance_r( context, currentGeom, other, &distance );
4234 if ( distance < bufferDistance )
4235 {
4236 alreadyAdded = true;
4237 break;
4238 }
4239 }
4240 if ( alreadyAdded )
4241 continue;
4242
4243 const GEOSCoordSequence *currentCoordSeq = GEOSGeom_getCoordSeq_r( context, currentGeom );
4244 unsigned int currentCoordSeqSize;
4245 GEOSCoordSeq_getSize_r( context, currentCoordSeq, &currentCoordSeqSize );
4246 if ( currentCoordSeqSize < 2 )
4247 continue;
4248
4249 //get the two endpoints of the current line merge result
4250 double xBegin, xEnd, yBegin, yEnd;
4251 GEOSCoordSeq_getX_r( context, currentCoordSeq, 0, &xBegin );
4252 GEOSCoordSeq_getY_r( context, currentCoordSeq, 0, &yBegin );
4253 GEOSCoordSeq_getX_r( context, currentCoordSeq, currentCoordSeqSize - 1, &xEnd );
4254 GEOSCoordSeq_getY_r( context, currentCoordSeq, currentCoordSeqSize - 1, &yEnd );
4255 geos::unique_ptr beginCurrentGeomVertex = createGeosPointXY( xBegin, yBegin, false, 0, false, 0, 2, precision );
4256 geos::unique_ptr endCurrentGeomVertex = createGeosPointXY( xEnd, yEnd, false, 0, false, 0, 2, precision );
4257
4258 //check how many endpoints of the line merge result are on the (original) line
4259 int nEndpointsOnOriginalLine = 0;
4260 if ( pointContainedInLine( beginCurrentGeomVertex.get(), line ) == 1 )
4261 nEndpointsOnOriginalLine += 1;
4262
4263 if ( pointContainedInLine( endCurrentGeomVertex.get(), line ) == 1 )
4264 nEndpointsOnOriginalLine += 1;
4265
4266 //check how many endpoints equal the endpoints of the original line
4267 int nEndpointsSameAsOriginalLine = 0;
4268 if ( GEOSEquals_r( context, beginCurrentGeomVertex.get(), beginLineVertex.get() ) == 1 || GEOSEquals_r( context, beginCurrentGeomVertex.get(), endLineVertex.get() ) == 1 )
4269 nEndpointsSameAsOriginalLine += 1;
4270
4271 if ( GEOSEquals_r( context, endCurrentGeomVertex.get(), beginLineVertex.get() ) == 1 || GEOSEquals_r( context, endCurrentGeomVertex.get(), endLineVertex.get() ) == 1 )
4272 nEndpointsSameAsOriginalLine += 1;
4273
4274 //check if the current geometry overlaps the original geometry (GEOSOverlap does not seem to work with linestrings)
4275 bool currentGeomOverlapsOriginalGeom = false;
4276 bool currentGeomOverlapsReshapeLine = false;
4277 if ( lineContainedInLine( currentGeom, line ) == 1 )
4278 currentGeomOverlapsOriginalGeom = true;
4279
4280 if ( lineContainedInLine( currentGeom, reshapeLineGeos ) == 1 )
4281 currentGeomOverlapsReshapeLine = true;
4282
4283 //logic to decide if this part belongs to the result
4284 if ( !isRing && nEndpointsSameAsOriginalLine == 1 && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom )
4285 {
4286 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4287 }
4288 //for closed rings, we take one segment from the candidate list
4289 else if ( isRing && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom )
4290 {
4291 probableParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4292 }
4293 else if ( nEndpointsOnOriginalLine == 2 && !currentGeomOverlapsOriginalGeom )
4294 {
4295 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4296 }
4297 else if ( nEndpointsSameAsOriginalLine == 2 && !currentGeomOverlapsOriginalGeom )
4298 {
4299 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4300 }
4301 else if ( currentGeomOverlapsOriginalGeom && currentGeomOverlapsReshapeLine )
4302 {
4303 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4304 }
4305 }
4306
4307 //add the longest segment from the probable list for rings (only used for polygon rings)
4308 if ( isRing && !probableParts.isEmpty() )
4309 {
4310 geos::unique_ptr maxGeom; //the longest geometry in the probabla list
4311 GEOSGeometry *currentGeom = nullptr;
4312 double maxLength = -std::numeric_limits<double>::max();
4313 double currentLength = 0;
4314 for ( int i = 0; i < probableParts.size(); ++i )
4315 {
4316 currentGeom = probableParts.at( i );
4317 GEOSLength_r( context, currentGeom, &currentLength );
4318 if ( currentLength > maxLength )
4319 {
4320 maxLength = currentLength;
4321 maxGeom.reset( currentGeom );
4322 }
4323 else
4324 {
4325 GEOSGeom_destroy_r( context, currentGeom );
4326 }
4327 }
4328 resultLineParts.push_back( maxGeom.release() );
4329 }
4330
4331 geos::unique_ptr result;
4332 if ( resultLineParts.empty() )
4333 return nullptr;
4334
4335 if ( resultLineParts.size() == 1 ) //the whole result was reshaped
4336 {
4337 result.reset( resultLineParts[0] );
4338 }
4339 else //>1
4340 {
4341 GEOSGeometry **lineArray = new GEOSGeometry *[resultLineParts.size()];
4342 for ( int i = 0; i < resultLineParts.size(); ++i )
4343 {
4344 lineArray[i] = resultLineParts[i];
4345 }
4346
4347 //create multiline from resultLineParts
4348 geos::unique_ptr multiLineGeom( GEOSGeom_createCollection_r( context, GEOS_MULTILINESTRING, lineArray, resultLineParts.size() ) );
4349 delete[] lineArray;
4350
4351 //then do a linemerge with the newly combined partstrings
4352 result.reset( GEOSLineMerge_r( context, multiLineGeom.get() ) );
4353 }
4354
4355 //now test if the result is a linestring. Otherwise something went wrong
4356 if ( GEOSGeomTypeId_r( context, result.get() ) != GEOS_LINESTRING )
4357 {
4358 return nullptr;
4359 }
4360
4361 //keep the original orientation
4362 bool reverseLine = false;
4363 if ( isRing )
4364 {
4365 //for closed linestring check clockwise/counter-clockwise
4366 char isResultCCW = 0, isOriginCCW = 0;
4367 if ( GEOSCoordSeq_isCCW_r( context, GEOSGeom_getCoordSeq_r( context, result.get() ), &isResultCCW ) && GEOSCoordSeq_isCCW_r( context, GEOSGeom_getCoordSeq_r( context, line ), &isOriginCCW ) )
4368 {
4369 //reverse line if orientations are different
4370 reverseLine = ( isOriginCCW == 1 && isResultCCW == 0 ) || ( isOriginCCW == 0 && isResultCCW == 1 );
4371 }
4372 }
4373 else
4374 {
4375 //for linestring, check if the result has a start or end point in common with the original line
4376 double x1res, y1res, x2res, y2res;
4377 if ( !_linestringEndpoints( result.get(), x1res, y1res, x2res, y2res ) )
4378 return nullptr;
4379 geos::unique_ptr beginResultLineVertex = createGeosPointXY( x1res, y1res, false, 0, false, 0, 2, precision );
4380 geos::unique_ptr endResultLineVertex = createGeosPointXY( x2res, y2res, false, 0, false, 0, 2, precision );
4381 reverseLine = GEOSEquals_r( context, beginLineVertex.get(), endResultLineVertex.get() ) == 1 || GEOSEquals_r( context, endLineVertex.get(), beginResultLineVertex.get() ) == 1;
4382 }
4383 if ( reverseLine )
4384 result.reset( GEOSReverse_r( context, result.get() ) );
4385
4386 return result;
4387}
4388
4389geos::unique_ptr QgsGeos::reshapePolygon( const GEOSGeometry *polygon, const GEOSGeometry *reshapeLineGeos, double precision )
4390{
4391 //go through outer shell and all inner rings and check if there is exactly one intersection of a ring and the reshape line
4392 int nIntersections = 0;
4393 int lastIntersectingRing = -2;
4394 const GEOSGeometry *lastIntersectingGeom = nullptr;
4395
4396 GEOSContextHandle_t context = QgsGeosContext::get();
4397 int nRings = GEOSGetNumInteriorRings_r( context, polygon );
4398 if ( nRings < 0 )
4399 return nullptr;
4400
4401 //does outer ring intersect?
4402 const GEOSGeometry *outerRing = GEOSGetExteriorRing_r( context, polygon );
4403 if ( GEOSIntersects_r( context, outerRing, reshapeLineGeos ) == 1 )
4404 {
4405 ++nIntersections;
4406 lastIntersectingRing = -1;
4407 lastIntersectingGeom = outerRing;
4408 }
4409
4410 //do inner rings intersect?
4411 const GEOSGeometry **innerRings = new const GEOSGeometry *[nRings];
4412
4413 try
4414 {
4415 for ( int i = 0; i < nRings; ++i )
4416 {
4417 innerRings[i] = GEOSGetInteriorRingN_r( context, polygon, i );
4418 if ( GEOSIntersects_r( context, innerRings[i], reshapeLineGeos ) == 1 )
4419 {
4420 ++nIntersections;
4421 lastIntersectingRing = i;
4422 lastIntersectingGeom = innerRings[i];
4423 }
4424 }
4425 }
4426 catch ( QgsGeosException & )
4427 {
4428 nIntersections = 0;
4429 }
4430
4431 if ( nIntersections != 1 ) //reshape line is only allowed to intersect one ring
4432 {
4433 delete[] innerRings;
4434 return nullptr;
4435 }
4436
4437 //we have one intersecting ring, let's try to reshape it
4438 geos::unique_ptr reshapeResult = reshapeLine( lastIntersectingGeom, reshapeLineGeos, precision );
4439 if ( !reshapeResult )
4440 {
4441 delete[] innerRings;
4442 return nullptr;
4443 }
4444
4445 //if reshaping took place, we need to reassemble the polygon and its rings
4446 GEOSGeometry *newRing = nullptr;
4447 const GEOSCoordSequence *reshapeSequence = GEOSGeom_getCoordSeq_r( context, reshapeResult.get() );
4448 GEOSCoordSequence *newCoordSequence = GEOSCoordSeq_clone_r( context, reshapeSequence );
4449
4450 reshapeResult.reset();
4451
4452 try
4453 {
4454 newRing = GEOSGeom_createLinearRing_r( context, newCoordSequence );
4455 }
4456 catch ( QgsGeosException & )
4457 {
4458 // nothing to do: on exception newRing will be null
4459 }
4460
4461 if ( !newRing )
4462 {
4463 delete[] innerRings;
4464 return nullptr;
4465 }
4466
4467 GEOSGeometry *newOuterRing = nullptr;
4468 if ( lastIntersectingRing == -1 )
4469 newOuterRing = newRing;
4470 else
4471 newOuterRing = GEOSGeom_clone_r( context, outerRing );
4472
4473 //check if all the rings are still inside the outer boundary
4474 QVector<GEOSGeometry *> ringList;
4475 if ( nRings > 0 )
4476 {
4477 GEOSGeometry *outerRingPoly = GEOSGeom_createPolygon_r( context, GEOSGeom_clone_r( context, newOuterRing ), nullptr, 0 );
4478 if ( outerRingPoly )
4479 {
4480 ringList.reserve( nRings );
4481 GEOSGeometry *currentRing = nullptr;
4482 for ( int i = 0; i < nRings; ++i )
4483 {
4484 if ( lastIntersectingRing == i )
4485 currentRing = newRing;
4486 else
4487 currentRing = GEOSGeom_clone_r( context, innerRings[i] );
4488
4489 //possibly a ring is no longer contained in the result polygon after reshape
4490 if ( GEOSContains_r( context, outerRingPoly, currentRing ) == 1 )
4491 ringList.push_back( currentRing );
4492 else
4493 GEOSGeom_destroy_r( context, currentRing );
4494 }
4495 }
4496 GEOSGeom_destroy_r( context, outerRingPoly );
4497 }
4498
4499 GEOSGeometry **newInnerRings = new GEOSGeometry *[ringList.size()];
4500 for ( int i = 0; i < ringList.size(); ++i )
4501 newInnerRings[i] = ringList.at( i );
4502
4503 delete[] innerRings;
4504
4505 geos::unique_ptr reshapedPolygon( GEOSGeom_createPolygon_r( context, newOuterRing, newInnerRings, ringList.size() ) );
4506 delete[] newInnerRings;
4507
4508 return reshapedPolygon;
4509}
4510
4511int QgsGeos::lineContainedInLine( const GEOSGeometry *line1, const GEOSGeometry *line2 )
4512{
4513 if ( !line1 || !line2 )
4514 {
4515 return -1;
4516 }
4517
4518 double bufferDistance = std::pow( 10.0L, geomDigits( line2 ) - 11 );
4519
4520 GEOSContextHandle_t context = QgsGeosContext::get();
4521 geos::unique_ptr bufferGeom( GEOSBuffer_r( context, line2, bufferDistance, DEFAULT_QUADRANT_SEGMENTS ) );
4522 if ( !bufferGeom )
4523 return -2;
4524
4525 geos::unique_ptr intersectionGeom( GEOSIntersection_r( context, bufferGeom.get(), line1 ) );
4526
4527 //compare ratio between line1Length and intersectGeomLength (usually close to 1 if line1 is contained in line2)
4528 double intersectGeomLength;
4529 double line1Length;
4530
4531 GEOSLength_r( context, intersectionGeom.get(), &intersectGeomLength );
4532 GEOSLength_r( context, line1, &line1Length );
4533
4534 double intersectRatio = line1Length / intersectGeomLength;
4535 if ( intersectRatio > 0.9 && intersectRatio < 1.1 )
4536 return 1;
4537
4538 return 0;
4539}
4540
4541int QgsGeos::pointContainedInLine( const GEOSGeometry *point, const GEOSGeometry *line )
4542{
4543 if ( !point || !line )
4544 return -1;
4545
4546 double bufferDistance = std::pow( 10.0L, geomDigits( line ) - 11 );
4547
4548 GEOSContextHandle_t context = QgsGeosContext::get();
4549 geos::unique_ptr lineBuffer( GEOSBuffer_r( context, line, bufferDistance, 8 ) );
4550 if ( !lineBuffer )
4551 return -2;
4552
4553 bool contained = false;
4554 if ( GEOSContains_r( context, lineBuffer.get(), point ) == 1 )
4555 contained = true;
4556
4557 return contained;
4558}
4559
4560int QgsGeos::geomDigits( const GEOSGeometry *geom )
4561{
4562 GEOSContextHandle_t context = QgsGeosContext::get();
4563 geos::unique_ptr bbox( GEOSEnvelope_r( context, geom ) );
4564 if ( !bbox )
4565 return -1;
4566
4567 const GEOSGeometry *bBoxRing = GEOSGetExteriorRing_r( context, bbox.get() );
4568 if ( !bBoxRing )
4569 return -1;
4570
4571 const GEOSCoordSequence *bBoxCoordSeq = GEOSGeom_getCoordSeq_r( context, bBoxRing );
4572
4573 if ( !bBoxCoordSeq )
4574 return -1;
4575
4576 unsigned int nCoords = 0;
4577 if ( !GEOSCoordSeq_getSize_r( context, bBoxCoordSeq, &nCoords ) )
4578 return -1;
4579
4580 int maxDigits = -1;
4581 for ( unsigned int i = 0; i < nCoords - 1; ++i )
4582 {
4583 double t;
4584 GEOSCoordSeq_getX_r( context, bBoxCoordSeq, i, &t );
4585
4586 int digits;
4587 digits = std::ceil( std::log10( std::fabs( t ) ) );
4588 if ( digits > maxDigits )
4589 maxDigits = digits;
4590
4591 GEOSCoordSeq_getY_r( context, bBoxCoordSeq, i, &t );
4592 digits = std::ceil( std::log10( std::fabs( t ) ) );
4593 if ( digits > maxDigits )
4594 maxDigits = digits;
4595 }
4596
4597 return maxDigits;
4598}
4599
4601#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 14, 0 )
4602 : mFeedback( feedback )
4603{
4604 GEOSContext_setInterruptCallback_r( QgsGeosContext::get(), &callback, reinterpret_cast< void * >( mFeedback ) );
4605}
4606#else
4607{
4608 ( void ) feedback;
4609}
4610#endif
4611
4612
4614{
4615#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 14, 0 )
4616 GEOSContext_setInterruptCallback_r( QgsGeosContext::get(), nullptr, nullptr );
4617#endif
4618}
4619
4620#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 14, 0 )
4621int QgsScopedGeosContextRegisterFeedback::callback( void *userData )
4622{
4623 if ( !userData )
4624 return 0;
4625
4626 QgsFeedback *feedback = reinterpret_cast< QgsFeedback * >( userData );
4627 return feedback && feedback->isCanceled() ? 1 : 0;
4628}
4629#endif
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:62
BufferSide
Side of line to buffer.
Definition qgis.h:2269
@ Right
Buffer to right of line.
Definition qgis.h:2271
@ LongestBorder
Polygon with longest common border is selected to merge overlapping polygons into.
Definition qgis.h:7145
@ MaximumArea
Polygon with largest area is selected to merge overlapping polygons into.
Definition qgis.h:7146
@ MinimumArea
Polygon with minimum area is selected to merge overlapping polygons into.
Definition qgis.h:7147
@ MinimumIndex
Polygon with smallest input index is selected to merge overlapping polygons into.
Definition qgis.h:7148
GeometryOperationResult
Success or failure of a geometry operation.
Definition qgis.h:2213
@ AddPartNotMultiGeometry
The source geometry is not multi.
Definition qgis.h:2224
@ InvalidBaseGeometry
The base geometry on which the operation is done is invalid or empty.
Definition qgis.h:2216
@ RejectOnInvalidSubGeometry
Don't allow geometries with invalid sub-geometries to be created.
Definition qgis.h:2333
@ SkipEmptyInteriorRings
Skip any empty polygon interior ring.
Definition qgis.h:2334
QFlags< GeosCreationFlag > GeosCreationFlags
Geos geometry creation behavior flags.
Definition qgis.h:2343
CoverageEdgeType
Coverage edge types.
Definition qgis.h:2365
@ AllEdges
All edges (both exterior and interior).
Definition qgis.h:2366
@ Exterior
Exterior (non-shared) edges.
Definition qgis.h:2367
@ Interior
Interior (shared) edges.
Definition qgis.h:2368
@ Point
Points.
Definition qgis.h:400
@ Polygon
Polygons.
Definition qgis.h:402
JoinStyle
Join styles for buffers.
Definition qgis.h:2294
EndCapStyle
End cap styles for buffers.
Definition qgis.h:2281
CoverageValidityResult
Coverage validity results.
Definition qgis.h:2352
@ Valid
Coverage is valid.
Definition qgis.h:2354
@ Invalid
Coverage is invalid. Invalidity includes polygons that overlap, that have gaps smaller than the gap w...
Definition qgis.h:2353
@ Error
An exception occurred while determining validity.
Definition qgis.h:2355
MakeValidMethod
Algorithms to use when repairing invalid geometries.
Definition qgis.h:2378
@ Linework
Combines all rings into a set of noded lines and then extracts valid polygons from that linework.
Definition qgis.h:2379
@ Structure
Structured method, first makes all rings valid and then merges shells and subtracts holes from shells...
Definition qgis.h:2380
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:314
@ CompoundCurve
CompoundCurve.
Definition qgis.h:325
@ Point
Point.
Definition qgis.h:316
@ LineString
LineString.
Definition qgis.h:317
@ TIN
TIN.
Definition qgis.h:330
@ MultiPoint
MultiPoint.
Definition qgis.h:320
@ LineStringZM
LineStringZM.
Definition qgis.h:366
@ Polygon
Polygon.
Definition qgis.h:318
@ MultiPolygon
MultiPolygon.
Definition qgis.h:322
@ Triangle
Triangle.
Definition qgis.h:319
@ NurbsCurve
NurbsCurve.
Definition qgis.h:331
@ NoGeometry
No geometry.
Definition qgis.h:332
@ MultiLineString
MultiLineString.
Definition qgis.h:321
@ Unknown
Unknown.
Definition qgis.h:315
@ PointM
PointM.
Definition qgis.h:349
@ CircularString
CircularString.
Definition qgis.h:324
@ PointZ
PointZ.
Definition qgis.h:333
@ GeometryCollection
GeometryCollection.
Definition qgis.h:323
@ MultiCurve
MultiCurve.
Definition qgis.h:327
@ CurvePolygon
CurvePolygon.
Definition qgis.h:326
@ PointZM
PointZM.
Definition qgis.h:365
@ LineStringZ
LineStringZ.
Definition qgis.h:334
@ PolyhedralSurface
PolyhedralSurface.
Definition qgis.h:329
@ MultiSurface
MultiSurface.
Definition qgis.h:328
Abstract base class for all geometries.
virtual const QgsAbstractGeometry * simplifiedTypeRef() const
Returns a reference to the simplest lossless representation of this geometry, e.g.
bool isMeasure() const
Returns true if the geometry contains m values.
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
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 isEmpty() const
Returns true if the geometry is empty.
Encapsulates parameters for a coverage cleaning operation.
double maximumGapWidth() const
Returns the maximum gap width.
Qgis::CoverageCleanOverlapMergeStrategy overlapMergeStrategy() const
Returns the overlap merge strategy to use during cleaning.
double snappingDistance() const
Returns the snapping distance.
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.
Abstract base class for curved geometry type.
Definition qgscurve.h:36
virtual bool isSimpleCurve() const =0
This method returns true for classes that can be cast to the QgsSimpleCurve class.
virtual QgsLineString * curveToLine(double tolerance=M_PI_2/90, SegmentationToleranceType toleranceType=MaximumAngle) const =0
Returns a new line string geometry corresponding to a segmentized approximation of the curve.
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:56
virtual bool addGeometry(QgsAbstractGeometry *g)
Adds a geometry and takes ownership. Returns true in case of success.
static Qgis::GeometryOperationResult addPart(QgsAbstractGeometry *geometry, std::unique_ptr< QgsAbstractGeometry > part)
Add a part to multi type geometry.
const QgsAbstractGeometry * mGeometry
EngineOperationResult
Success or failure of a geometry operation.
@ NothingHappened
Nothing happened, without any error.
@ InvalidBaseGeometry
The geometry on which the operation occurs is not valid.
@ InvalidInput
The input is not valid.
@ NodedGeometryError
Error occurred while creating a noded geometry.
@ EngineError
Error occurred in the geometry engine.
@ SplitCannotSplitPoint
Points cannot be split.
@ Success
Operation succeeded.
@ MethodNotImplemented
Method not implemented in geometry engine.
QgsGeometryEngine(const QgsAbstractGeometry *geometry)
void logError(const QString &engineName, const QString &message) const
Logs an error message encountered during an operation.
static std::unique_ptr< QgsGeometryCollection > createCollectionOfType(Qgis::WkbType type)
Returns a new geometry collection matching a specified WKB type.
Encapsulates parameters under which a geometry operation is performed.
double gridSize() const
Returns the grid size which will be used to snap vertices of a geometry.
static 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.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
Used to create and store a GEOS context object, correctly freeing the context upon destruction.
Definition qgsgeos.h:63
static GEOSContextHandle_t get()
Returns a thread local instance of a GEOS context, safe for use in the current thread.
std::unique_ptr< QgsAbstractGeometry > singleSidedBuffer(double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a single sided buffer for a geometry.
Definition qgsgeos.cpp:3455
double minimumClearance(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Computes the minimum clearance of a geometry.
Definition qgsgeos.cpp:3540
bool intersects(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom intersects this.
Definition qgsgeos.cpp:905
bool distanceWithin(const QgsAbstractGeometry *geom, double maxdistance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom is within maxdistance distance from this geometry.
Definition qgsgeos.cpp:701
std::unique_ptr< QgsAbstractGeometry > concaveHull(double targetPercent, bool allowHoles=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a possibly concave geometry that encloses the input geometry.
Definition qgsgeos.cpp:2597
std::unique_ptr< QgsAbstractGeometry > reshapeGeometry(const QgsLineString &reshapeWithLine, EngineOperationResult *errorCode, QString *errorMsg=nullptr) const
Reshapes the geometry using a line.
Definition qgsgeos.cpp:3614
double distance(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculates the distance between this and geom.
Definition qgsgeos.cpp:624
std::unique_ptr< QgsAbstractGeometry > sharedPaths(const QgsAbstractGeometry *other, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Find paths shared between the two given lineal geometries (this and other).
Definition qgsgeos.cpp:3593
std::unique_ptr< QgsAbstractGeometry > minimumClearanceLine(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a LineString whose endpoints define the minimum clearance of a geometry.
Definition qgsgeos.cpp:3559
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlags())
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
Definition qgsgeos.cpp:284
QgsAbstractGeometry * symDifference(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the symmetric difference of this and geom.
Definition qgsgeos.cpp:582
std::unique_ptr< QgsAbstractGeometry > closestPoint(const QgsGeometry &other, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the closest point on the geometry to the other geometry.
Definition qgsgeos.cpp:3774
std::unique_ptr< QgsAbstractGeometry > unionCoverage(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap.
Definition qgsgeos.cpp:2717
bool isFuzzyEqual(const QgsAbstractGeometry *geom, double epsilon, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if this is equal to geom ie.
Definition qgsgeos.cpp:2931
QgsAbstractGeometry * simplify(double tolerance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Simplifies the geometery.
Definition qgsgeos.cpp:2475
static const QgsSettingsEntryBool * settingLineToCurveParam
Settings entry - Whether to convert any linear output of a GEOS method to a curved type,...
Definition qgsgeos.h:199
static geos::unique_ptr offsetCurve(const GEOSGeometry *geometry, double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr)
Directly calculates the offset curve for a GEOS geometry object and returns a GEOS geometry result.
Definition qgsgeos.cpp:3427
std::unique_ptr< QgsAbstractGeometry > cleanCoverage(const QgsCoverageCleanParameters &parameters, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Operates on a coverage (represented as a list of polygonal geometry), to fix cases where the geometry...
Definition qgsgeos.cpp:2736
QgsAbstractGeometry * intersection(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the intersection of this and geom.
Definition qgsgeos.cpp:357
double lineLocatePoint(const QgsPoint &point, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a distance representing the location along this linestring of the closest point on this lines...
Definition qgsgeos.cpp:3878
std::unique_ptr< QgsAbstractGeometry > subdivide(int maxNodes, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Subdivides the geometry.
Definition qgsgeos.cpp:489
bool touches(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom touches this.
Definition qgsgeos.cpp:939
static std::unique_ptr< QgsPolygon > fromGeosPolygon(const GEOSGeometry *geos)
Definition qgsgeos.cpp:1949
std::unique_ptr< QgsAbstractGeometry > largestEmptyCircle(double tolerance, const QgsAbstractGeometry *boundary=nullptr, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance.
Definition qgsgeos.cpp:3502
QgsAbstractGeometry * envelope(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:2535
Qgis::CoverageValidityResult validateCoverage(double gapWidth, std::unique_ptr< QgsAbstractGeometry > *invalidEdges, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Analyze a coverage (represented as a collection of polygonal geometry with exactly matching edge geom...
Definition qgsgeos.cpp:2645
QgsAbstractGeometry * buffer(double distance, int segments, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Buffers the geometry.
Definition qgsgeos.cpp:2432
QString relate(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Returns the Dimensional Extended 9 Intersection Model (DE-9IM) representation of the relationship bet...
Definition qgsgeos.cpp:998
std::unique_ptr< QgsAbstractGeometry > constrainedDelaunayTriangulation(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a constrained Delaunay triangulation for the vertices of the geometry.
Definition qgsgeos.cpp:4039
bool within(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom is within this.
Definition qgsgeos.cpp:949
bool contains(double x, double y, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns true if the geometry contains the point at (x, y).
Definition qgsgeos.cpp:765
bool isSimple(QString *errorMsg=nullptr) const override
Determines whether the geometry is simple (according to OGC definition).
Definition qgsgeos.cpp:2967
bool isValid(QString *errorMsg=nullptr, bool allowSelfTouchingHoles=false, QgsGeometry *errorLoc=nullptr, QgsFeedback *feedback=nullptr) const override
Returns true if the geometry is valid.
Definition qgsgeos.cpp:2847
std::unique_ptr< QgsAbstractGeometry > minimumWidth(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a linestring geometry which represents the minimum diameter of the geometry.
Definition qgsgeos.cpp:3523
std::unique_ptr< QgsAbstractGeometry > simplifyCoverageVW(double tolerance, bool preserveBoundary, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geomet...
Definition qgsgeos.cpp:2691
QgsGeos(const QgsAbstractGeometry *geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
GEOS geometry engine constructor.
Definition qgsgeos.cpp:205
std::unique_ptr< QgsAbstractGeometry > shortestLine(const QgsGeometry &other, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the shortest line joining this geometry to the other geometry.
Definition qgsgeos.cpp:3819
QgsAbstractGeometry * convexHull(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculate the convex hull of this geometry.
Definition qgsgeos.cpp:2580
void prepareGeometry() override
Prepares the geometry, so that subsequent calls to spatial relation methods are much faster.
Definition qgsgeos.cpp:316
std::unique_ptr< QgsAbstractGeometry > makeValid(Qgis::MakeValidMethod method=Qgis::MakeValidMethod::Linework, bool keepCollapsed=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Repairs the geometry using GEOS make valid routine.
Definition qgsgeos.cpp:226
QgsPoint * pointOnSurface(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculate a point that is guaranteed to be on the surface of this.
Definition qgsgeos.cpp:2550
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
Definition qgsgeos.cpp:1726
std::unique_ptr< QgsAbstractGeometry > node(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.
Definition qgsgeos.cpp:3576
QgsAbstractGeometry * combine(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the combination of this and geom.
Definition qgsgeos.cpp:510
bool disjoint(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom is disjoint from this.
Definition qgsgeos.cpp:993
std::unique_ptr< QgsAbstractGeometry > extractCoverageEdges(Qgis::CoverageEdgeType edgeType=Qgis::CoverageEdgeType::AllEdges, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geomet...
Definition qgsgeos.cpp:2805
bool relatePattern(const QgsAbstractGeometry *geom, const QString &pattern, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Tests whether two geometries are related by a specified Dimensional Extended 9 Intersection Model (DE...
Definition qgsgeos.cpp:1035
double hausdorffDistanceDensify(const QgsAbstractGeometry *geometry, double densifyFraction, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Hausdorff distance between this geometry and another geometry.
Definition qgsgeos.cpp:833
bool isEqual(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Check if geometries are topologically equivalent.
Definition qgsgeos.cpp:2910
static std::unique_ptr< QgsCurvePolygon > fromGeosCurvePolygon(const GEOSGeometry *geos)
Definition qgsgeos.cpp:1892
std::unique_ptr< QgsAbstractGeometry > maximumInscribedCircle(double tolerance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the maximum inscribed circle.
Definition qgsgeos.cpp:3485
std::unique_ptr< QgsAbstractGeometry > voronoiDiagram(const QgsAbstractGeometry *extent=nullptr, double tolerance=0.0, bool edgesOnly=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Creates a Voronoi diagram for the nodes contained within the geometry.
Definition qgsgeos.cpp:3981
double frechetDistanceDensify(const QgsAbstractGeometry *geometry, double densifyFraction, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Fréchet distance between this geometry and another geometry, restricted to discrete point...
Definition qgsgeos.cpp:881
std::unique_ptr< QgsAbstractGeometry > delaunayTriangulation(double tolerance=0.0, bool edgesOnly=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Delaunay triangulation for the vertices of the geometry.
Definition qgsgeos.cpp:4015
bool crosses(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom crosses this.
Definition qgsgeos.cpp:944
std::unique_ptr< QgsAbstractGeometry > concaveHullOfPolygons(double lengthRatio, bool allowHoles=false, bool isTight=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Constructs a concave hull of a set of polygons, respecting the polygons as constraints.
Definition qgsgeos.cpp:2621
std::unique_ptr< QgsAbstractGeometry > clip(const QgsRectangle &rectangle, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Performs a fast, non-robust intersection between the geometry and a rectangle.
Definition qgsgeos.cpp:367
bool isEmpty(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:2953
static Qgis::GeometryOperationResult addPart(QgsGeometry &geometry, GEOSGeometry *newPart)
Adds a new island polygon to a multipolygon feature.
Definition qgsgeos.cpp:294
bool overlaps(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom overlaps this.
Definition qgsgeos.cpp:954
QgsPoint * centroid(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculates the centroid of this.
Definition qgsgeos.cpp:2507
std::unique_ptr< QgsAbstractGeometry > mergeLines(QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
Definition qgsgeos.cpp:3746
QgsAbstractGeometry * difference(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the difference of this and geom.
Definition qgsgeos.cpp:362
void geometryChanged() override
Should be called whenever the geometry associated with the engine has been modified and the engine mu...
Definition qgsgeos.cpp:309
double area(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:1068
double length(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:1085
double hausdorffDistance(const QgsAbstractGeometry *geometry, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Hausdorff distance between this geometry and another geometry.
Definition qgsgeos.cpp:809
double frechetDistance(const QgsAbstractGeometry *geometry, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Fréchet distance between this geometry and another geometry, restricted to discrete point...
Definition qgsgeos.cpp:857
QgsAbstractGeometry * interpolate(double distance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Interpolates a point by distance along the geometry.
Definition qgsgeos.cpp:2491
static QgsPoint coordSeqPoint(const GEOSCoordSequence *cs, int i, bool hasZ, bool hasM)
Definition qgsgeos.cpp:2072
static QgsGeometry polygonize(const QVector< const QgsAbstractGeometry * > &geometries, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr)
Creates a GeometryCollection geometry containing possible polygons formed from the constituent linewo...
Definition qgsgeos.cpp:3940
static QgsGeometry geometryFromGeos(GEOSGeometry *geos)
Creates a new QgsGeometry object, feeding in a geometry in GEOS format.
Definition qgsgeos.cpp:213
QgsGeometryEngine::EngineOperationResult splitGeometry(const QgsAbstractGeometry &splitGeom, QVector< QgsGeometry > &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, QString *errorMsg=nullptr) const override
Splits this geometry according to a given geometry.
Definition qgsgeos.cpp:1102
Line string geometry type, with support for z-dimension and m-values.
double closestSegment(const QgsPoint &pt, QgsPoint &segmentPt, QgsVertexId &vertexAfter, int *leftOf=nullptr, double epsilon=4 *std::numeric_limits< double >::epsilon()) const override
Searches for the closest segment of the geometry to a given point.
void addVertex(const QgsPoint &pt)
Adds a new vertex to the end of the line string.
QgsLineString * clone() const override
Clones the geometry by performing a deep copy.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Custom exception class which is raised when an operation is not supported.
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition qgspoint.cpp:138
double z
Definition qgspoint.h:58
double x
Definition qgspoint.h:56
bool isEmpty() const override
Returns true if the geometry is empty.
Definition qgspoint.cpp:775
double distance(double x, double y) const
Returns the Cartesian 2D distance between this point and a specified x, y coordinate.
Definition qgspoint.h:466
double m
Definition qgspoint.h:59
double y
Definition qgspoint.h:57
Polyhedral surface geometry type.
int numPatches() const
Returns the number of patches contained with the polyhedral surface.
const QgsPolygon * patchN(int i) const
Retrieves a patch from the polyhedral surface.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
void setYMinimum(double y)
Set the minimum y value.
void setXMinimum(double x)
Set the minimum x value.
void setYMaximum(double y)
Set the maximum y value.
void setXMaximum(double x)
Set the maximum x value.
double yMaximum
Scoped object for setting the current thread GEOS context feedback object.
Definition qgsgeos.h:101
QgsScopedGeosContextRegisterFeedback(QgsFeedback *feedback)
Registers a feedback object for GEOS interruption checking.
Definition qgsgeos.cpp:4600
~QgsScopedGeosContextRegisterFeedback()
Resets the GEOS interruption checker for the current thread.
Definition qgsgeos.cpp:4613
static QgsSettingsTreeNode * sTreeGeos
Abstract base class for simple curved geometry type.
double yAt(int index) const override
Returns the y-coordinate of the specified node in the line string.
QVector< double > yVector() const
Returns the y vertex values as a vector.
int numPoints() const override
Returns the number of points in the curve.
const double * mData() const
Returns a const pointer to the m vertex data, or nullptr if the simple curve does not have m values.
QVector< double > zVector() const
Returns the z vertex values as a vector.
QVector< double > xVector() const
Returns the x vertex values as a vector.
double xAt(int index) const override
Returns the x-coordinate of the specified node in the line string.
const double * yData() const
Returns a const pointer to the y vertex data.
QgsPoint pointN(int i) const
Returns the specified point from inside the simple curve.
const double * xData() const
Returns a const pointer to the x vertex data.
QVector< double > mVector() const
Returns the m vertex values as a vector.
const double * zData() const
Returns a const pointer to the z vertex data, or nullptr if the simple curve does not have z values.
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...
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
static Q_INVOKABLE bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
Contains geos related utilities and functions.
Definition qgsgeos.h:129
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition qgsgeos.h:165
std::unique_ptr< GEOSCoordSequence, GeosDeleter > coord_sequence_unique_ptr
Scoped GEOS coordinate sequence pointer.
Definition qgsgeos.h:180
std::unique_ptr< GEOSBufferParams, GeosDeleter > buffer_params_unique_ptr
Scoped GEOS buffer params pointer.
Definition qgsgeos.h:175
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7826
T qgsgeometry_cast(QgsAbstractGeometry *geom)
QVector< QgsPoint > QgsPointSequence
#define CATCH_GEOS(r)
Definition qgsgeos.cpp:46
#define DEFAULT_QUADRANT_SEGMENTS
Definition qgsgeos.cpp:44
#define CATCH_GEOS_WITH_ERRMSG(r)
Definition qgsgeos.cpp:52
#define QgsDebugError(str)
Definition qgslogger.h:71
QLineF segment(int index, QRectF rect, double radius)
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:35
int vertex
Vertex number.
void CORE_EXPORT operator()(GEOSGeometry *geom) const
Destroys the GEOS geometry geom, using the static QGIS geos context.
struct GEOSGeom_t GEOSGeometry
Definition util.h:41