26#include "moc_qgssnappingutils.cpp"
28using namespace Qt::StringLiterals;
33 , mEnableSnappingForInvisibleFeature( enableSnappingForInvisibleFeature )
48 if ( !mLocators.contains( vl ) )
52 connect( vl, &QObject::destroyed,
this, [
this, vl]()
54 delete mLocators.take( vl );
57 mLocators.insert( vl, vlpl );
59 return mLocators.value( vl );
64 qDeleteAll( mLocators );
67 qDeleteAll( mTemporaryLocators );
68 mTemporaryLocators.clear();
77 QgsRectangle aoi( pointMap.
x() - tolerance, pointMap.
y() - tolerance,
78 pointMap.
x() + tolerance, pointMap.
y() + tolerance );
82 if ( loc->
isIndexing() || isIndexPrepared( loc, aoi ) )
85 return temporaryLocatorForLayer( vl, pointMap, tolerance );
90 if ( mTemporaryLocators.contains( vl ) )
91 delete mTemporaryLocators.take( vl );
93 QgsRectangle rect( pointMap.
x() - tolerance, pointMap.
y() - tolerance,
94 pointMap.
x() + tolerance, pointMap.
y() + tolerance );
96 QgsPointLocator *vlpl =
new QgsPointLocator( vl, destinationCrs(), mMapSettings.transformContext(), &rect );
99 mTemporaryLocators.insert( vl, vlpl );
100 return mTemporaryLocators.value( vl );
111 QgsRectangle aoi( areaOfInterest );
118 if ( segments.isEmpty() )
121 QSet<QgsPointXY> endpoints;
124 QVector<QgsGeometry> geoms;
125 const auto constSegments = segments;
131 m.edgePoints( pl[0], pl[1] );
133 endpoints << pl[0] << pl[1];
140 QList<QgsPointXY> newPoints;
146 if ( !endpoints.contains( p ) )
155 const auto constPl = pl;
158 if ( !endpoints.contains( p ) )
164 if ( newPoints.isEmpty() )
169 double minSqrDist = 1e20;
170 const auto constNewPoints = newPoints;
173 double sqrDist = pt.
sqrDist( p.x(), p.y() );
174 if ( sqrDist < minSqrDist )
176 minSqrDist = sqrDist;
187 if ( !candidateMatch.
isValid() || candidateMatch.
distance() > maxDistance )
207 bestMatch = candidateMatch;
216 bestMatch = candidateMatch;
228 bestMatch = candidateMatch;
235 _replaceIfBetter( bestMatch, loc->
nearestVertex( pointMap, tolerance, filter, relaxed ), tolerance );
239 _replaceIfBetter( bestMatch, loc->
nearestEdge( pointMap, tolerance, filter, relaxed ), tolerance );
246 _replaceIfBetter( bestMatch, loc->
nearestArea( pointMap, tolerance, filter, relaxed ), tolerance );
250 _replaceIfBetter( bestMatch, loc->
nearestCentroid( pointMap, tolerance, filter, relaxed ), tolerance );
254 _replaceIfBetter( bestMatch, loc->
nearestMiddleOfSegment( pointMap, tolerance, filter, relaxed ), tolerance );
258 _replaceIfBetter( bestMatch, loc->
nearestLineEndpoints( pointMap, tolerance, filter, relaxed ), tolerance );
270 return snapToMap( mMapSettings.mapToPixel().toMapCoordinates( point ), filter, relaxed );
275 return QgsRectangle( point.
x() - tolerance, point.
y() - tolerance,
276 point.
x() + tolerance, point.
y() + tolerance );
281 if ( !mMapSettings.hasValidSettings() || !mSnappingConfig.enabled() )
295 prepareIndex( QList<LayerAndAreaOfInterest>() << qMakePair( mCurrentLayer,
_areaOfInterest( pointMap, tolerance ) ), relaxed );
298 QgsPointLocator *loc = locatorForLayerUsingStrategy( mCurrentLayer, pointMap, tolerance );
304 _updateBestMatch( bestMatch, pointMap, loc, type, tolerance, filter, relaxed );
305 if ( mSnappingConfig.intersectionSnapping() )
306 edges = loc->
edgesInRect( pointMap, tolerance, filter, relaxed );
310 QgsPointLocator *loc = locatorForLayerUsingStrategy( vl, pointMap, tolerance );
311 _updateBestMatch( bestMatch, pointMap, loc, type, tolerance, filter,
false );
312 if ( mSnappingConfig.intersectionSnapping() )
313 edges << loc->
edgesInRect( pointMap, tolerance, filter,
false );
316 if ( mSnappingConfig.intersectionSnapping() )
318 _replaceIfBetter( bestMatch, _findClosestSegmentIntersection( pointMap, edges ), tolerance );
325 QList<LayerAndAreaOfInterest>
layers;
326 QList<LayerConfig> filteredConfigs;
331 bool inRangeGlobal = ( mSnappingConfig.minimumScale() <= 0.0 || mMapSettings.scale() <= mSnappingConfig.minimumScale() )
332 && ( mSnappingConfig.maximumScale() <= 0.0 || mMapSettings.scale() >= mSnappingConfig.maximumScale() );
334 for (
const LayerConfig &layerConfig : std::as_const( mLayers ) )
349 filteredConfigs << layerConfig;
352 prepareIndex(
layers, relaxed );
356 double maxTolerance = 0;
359 for (
const LayerConfig &layerConfig : std::as_const( filteredConfigs ) )
362 if (
QgsPointLocator *loc = locatorForLayerUsingStrategy( layerConfig.layer, pointMap, tolerance ) )
364 _updateBestMatch( bestMatch, pointMap, loc, layerConfig.type, tolerance, filter, relaxed );
365 if ( mSnappingConfig.intersectionSnapping() )
366 edges << loc->
edgesInRect( pointMap, tolerance, filter, relaxed );
369 maxTolerance = std::max( maxTolerance, tolerance );
377 QgsPointLocator *loc = locatorForLayerUsingStrategy( vl, pointMap, maxTolerance );
378 _updateBestMatch( bestMatch, pointMap, loc, maxTypes, maxTolerance, filter,
false );
379 if ( mSnappingConfig.intersectionSnapping() )
380 edges << loc->
edgesInRect( pointMap, maxTolerance, filter,
false );
383 if ( mSnappingConfig.intersectionSnapping() )
384 _replaceIfBetter( bestMatch, _findClosestSegmentIntersection( pointMap, edges ), maxTolerance );
395 QList<LayerAndAreaOfInterest>
layers;
396 const auto constLayers = mMapSettings.layers(
true );
398 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
399 layers << qMakePair( vl, aoi );
400 prepareIndex(
layers, relaxed );
405 for (
const LayerAndAreaOfInterest &entry : std::as_const(
layers ) )
408 if (
QgsPointLocator *loc = locatorForLayerUsingStrategy( vl, pointMap, tolerance ) )
410 _updateBestMatch( bestMatch, pointMap, loc, type, tolerance, filter, relaxed );
411 if ( mSnappingConfig.intersectionSnapping() )
412 edges << loc->
edgesInRect( pointMap, tolerance, filter, relaxed );
418 QgsPointLocator *loc = locatorForLayerUsingStrategy( vl, pointMap, tolerance );
419 _updateBestMatch( bestMatch, pointMap, loc, type, tolerance, filter,
false );
420 if ( mSnappingConfig.intersectionSnapping() )
421 edges << loc->
edgesInRect( pointMap, tolerance, filter,
false );
424 if ( mSnappingConfig.intersectionSnapping() )
425 _replaceIfBetter( bestMatch, _findClosestSegmentIntersection( pointMap, edges ), tolerance );
433void QgsSnappingUtils::onInitFinished(
bool ok )
441 mHybridMaxAreaPerLayer[loc->
layer()->
id()] /= 4;
445void QgsSnappingUtils::prepareIndex(
const QList<LayerAndAreaOfInterest> &layers,
bool relaxed )
448 QList<LayerAndAreaOfInterest> layersToIndex;
449 const auto constLayers =
layers;
450 for (
const LayerAndAreaOfInterest &entry : constLayers )
452 QgsVectorLayer *vl = entry.first;
459 if ( !loc->
isIndexing() && !isIndexPrepared( loc, entry.second ) )
460 layersToIndex << entry;
462 if ( !layersToIndex.isEmpty() )
474 for (
const LayerAndAreaOfInterest &entry : layersToIndex )
476 QgsVectorLayer *vl = entry.first;
485 if ( !mEnableSnappingForInvisibleFeature )
493 QgsRectangle rect( mMapSettings.visibleExtent() );
495 loc->
init( -1, relaxed );
500 if ( !mHybridMaxAreaPerLayer.contains( vl->
id() ) )
503 if ( totalFeatureCount < mHybridPerLayerFeatureLimit )
506 mHybridMaxAreaPerLayer[vl->
id()] = -1;
512 QgsRectangle layerExtent = mMapSettings.layerExtentToOutputExtent( vl, vl->
extent() );
513 double totalArea = layerExtent.
width() * layerExtent.
height();
514 mHybridMaxAreaPerLayer[vl->
id()] = totalArea * mHybridPerLayerFeatureLimit / totalFeatureCount / 4;
518 double indexReasonableArea = mHybridMaxAreaPerLayer[vl->
id()];
519 if ( indexReasonableArea == -1 )
522 loc->
init( -1, relaxed );
527 QgsPointXY
c = entry.second.center();
528 double halfSide = std::sqrt( indexReasonableArea ) / 2;
529 QgsRectangle rect(
c.x() - halfSide,
c.y() - halfSide,
530 c.x() + halfSide,
c.y() + halfSide );
534 loc->
init( mHybridPerLayerFeatureLimit, relaxed );
539 loc->
init( relaxed );
554 return mSnappingConfig;
559 mEnableSnappingForInvisibleFeature = enable;
564 if ( mSnappingConfig ==
config )
567 if ( mSnappingConfig.individualLayerSettings() !=
config.individualLayerSettings() )
568 onIndividualLayerSettingsChanged(
config.individualLayerSettings() );
577 mSnappingConfig.setEnabled( !mSnappingConfig.enabled() );
583 if ( !mCurrentLayer )
586 QgsPointXY pointMap = mMapSettings.mapToPixel().toMapCoordinates( point );
589 QgsPointLocator *loc = locatorForLayerUsingStrategy( mCurrentLayer, pointMap, tolerance );
594 _updateBestMatch( bestMatch, pointMap, loc, type, tolerance, filter,
false );
600 QString oldDestCRS = mMapSettings.destinationCrs().authid();
602 mMapSettings = settings;
604 if ( newDestCRS != oldDestCRS )
610 mCurrentLayer = layer;
615 QString msg = u
"--- SNAPPING UTILS DUMP ---\n"_s;
617 if ( !mMapSettings.hasValidSettings() )
619 msg +=
"invalid map settings!"_L1;
623 QList<LayerConfig>
layers;
629 msg +=
"no current layer!"_L1;
633 layers <<
LayerConfig( mCurrentLayer, _snappingTypeToPointLocatorType( mSnappingConfig.typeFlag() ), mSnappingConfig.tolerance(), mSnappingConfig.units() );
637 const auto constLayers = mMapSettings.layers(
true );
640 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
641 layers <<
LayerConfig( vl, _snappingTypeToPointLocatorType( mSnappingConfig.typeFlag() ), mSnappingConfig.tolerance(), mSnappingConfig.units() );
649 const auto constLayers =
layers;
652 msg += QString(
"layer : %1\n"
653 "config: %2 tolerance %3 %4\n" )
654 .arg( layer.layer->name() )
655 .arg(
static_cast<int>( layer.type ) ).arg( layer.tolerance ).arg(
static_cast<int>( layer.unit ) );
661 QString extentStr, cachedGeoms, limit( u
"no max area"_s );
664 extentStr = u
" extent %1"_s.arg( r->toString() );
667 extentStr = u
"full extent"_s;
671 cachedGeoms = u
"not initialized"_s;
674 if ( mHybridMaxAreaPerLayer.contains( layer.layer->id() ) )
676 double maxArea = mStrategy ==
IndexHybrid ? mHybridMaxAreaPerLayer[layer.layer->id()] : -1;
678 limit = u
"max area %1"_s.arg( maxArea );
681 limit = u
"not evaluated"_s;
683 msg += u
"index : YES | %1 | %2 | %3\n"_s.arg( cachedGeoms, extentStr, limit );
686 msg +=
"index : ???\n"_L1;
689 msg +=
"index : NO\n"_L1;
701void QgsSnappingUtils::onIndividualLayerSettingsChanged(
const QHash<QgsVectorLayer *, QgsSnappingConfig::IndividualLayerSettings> &layerSettings )
705 QHash<QgsVectorLayer *, QgsSnappingConfig::IndividualLayerSettings>::const_iterator i;
707 for ( i = layerSettings.constBegin(); i != layerSettings.constEnd(); ++i )
711 mLayers.append(
LayerConfig( i.key(), _snappingTypeToPointLocatorType(
static_cast<Qgis::SnappingTypes>( i->typeFlag() ) ), i->tolerance(), i->units() ) );
QFlags< SnappingType > SnappingTypes
Snapping types.
@ ActiveLayer
On the active layer.
@ AdvancedConfiguration
On a per layer configuration basis.
@ AllLayers
On all vector layers.
@ MultiLineString
MultiLineString.
Represents a coordinate reference system (CRS).
A geometry is the spatial representation of a feature.
static QgsGeometry fromPolylineXY(const QgsPolylineXY &polyline)
Creates a new LineString geometry from a list of QgsPointXY points.
QgsPolylineXY asPolyline() const
Returns the contents of the geometry as a polyline.
QgsMultiPolylineXY asMultiPolyline() const
Returns the contents of the geometry as a multi-linestring.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters ¶meters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
Base class for all map layer types.
QgsCoordinateTransformContext transformContext() const
Returns the layer data provider coordinate transform context or a default transform context if the la...
Contains configuration for rendering maps.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
Defines the interface for querying point locations.
Match nearestEdge(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Find nearest edge to the specified point - up to distance specified by tolerance Optional filter may ...
void setRenderContext(const QgsRenderContext *context)
Configure render context - if not nullptr, it will use to index only visible feature.
int cachedGeometryCount() const
Returns how many geometries are cached in the index.
void setExtent(const QgsRectangle *extent)
Configure extent - if not nullptr, it will index only that area.
bool init(int maxFeaturesToIndex=-1, bool relaxed=false)
Prepare the index for queries.
QgsVectorLayer * layer() const
Gets associated layer.
class QList< QgsPointLocator::Match > MatchList
Match nearestVertex(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Find nearest vertex to the specified point - up to distance specified by tolerance Optional filter ma...
bool isIndexing() const
Returns true if the point locator is currently indexing the data.
const QgsRectangle * extent() const
Gets extent of the area point locator covers - if nullptr then it caches the whole layer.
MatchList edgesInRect(const QgsRectangle &rect, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Find edges within a specified rectangle Optional filter may discard unwanted matches.
bool hasIndex() const
Indicate whether the data have been already indexed.
Match nearestMiddleOfSegment(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Find nearest middle of segment to the specified point - up to distance specified by tolerance Optiona...
void waitForIndexingFinished()
If the point locator has been initialized relaxedly and is currently indexing, this methods waits for...
Match nearestCentroid(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Find nearest centroid to the specified point - up to distance specified by tolerance Optional filter ...
void initFinished(bool ok)
Emitted whenever index has been built and initialization is finished.
Match nearestArea(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Find nearest area to the specified point - up to distance specified by tolerance Optional filter may ...
Type
The type of a snap result or the filter type for a snap request.
@ Area
Snapped to an area.
@ MiddleOfSegment
Snapped to the middle of a segment.
@ Vertex
Snapped to a vertex. Can be a vertex of the geometry or an intersection.
@ Centroid
Snapped to a centroid.
@ Edge
Snapped to an edge.
@ LineEndpoint
Start or end points of lines only.
Match nearestLineEndpoints(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Find nearest line endpoint (start or end vertex) to the specified point - up to distance specified by...
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
A rectangle specified with double values.
bool contains(const QgsRectangle &rect) const
Returns true when rectangle contains other rectangle.
bool intersects(const QgsRectangle &rect) const
Returns true when rectangle intersects with other rectangle.
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
A container of advanced configuration (per layer) of the snapping of the project.
double maximumScale() const
Returns max scale on which snapping is limited.
double minimumScale() const
Returns minimum scale on which snapping is limited.
Stores configuration of snapping settings for the project.
@ PerLayer
Scale dependency using min max range per layer.
@ Disabled
No scale dependency.
@ Global
Scale dependency using global min max range.
QgsPointLocator::Match snapToCurrentLayer(QPoint point, QgsPointLocator::Types type, QgsPointLocator::MatchFilter *filter=nullptr)
Snap to current layer.
void setMapSettings(const QgsMapSettings &settings)
Assign current map settings to the utils - used for conversion between screen coords to map coords.
void toggleEnabled()
Toggles the state of snapping.
@ IndexAlwaysFull
For all layers build index of full extent. Uses more memory, but queries are faster.
@ IndexHybrid
For "big" layers using IndexNeverFull, for the rest IndexAlwaysFull. Compromise between speed and mem...
@ IndexExtent
For all layer build index of extent given in map settings.
@ IndexNeverFull
For all layers only create temporary indexes of small extent. Low memory usage, slower queries.
QgsPointLocator * locatorForLayer(QgsVectorLayer *vl)
Gets a point locator for the given layer.
virtual void prepareIndexProgress(int index)
Called when finished indexing a layer with snapToMap. When index == count the indexing is complete.
QString dump()
Gets extra information about the instance.
void configChanged(const QgsSnappingConfig &snappingConfig)
Emitted when the snapping settings object changes.
~QgsSnappingUtils() override
void clearAllLocators()
Deletes all existing locators (e.g. when destination CRS has changed and we need to reindex).
void setCurrentLayer(QgsVectorLayer *layer)
Sets current layer so that if mode is SnapCurrentLayer we know which layer to use.
QgsPointLocator::Match snapToMap(QPoint point, QgsPointLocator::MatchFilter *filter=nullptr, bool relaxed=false)
Snap to map according to the current configuration.
QgsSnappingUtils(QObject *parent=nullptr, bool enableSnappingForInvisibleFeature=true)
Constructor for QgsSnappingUtils.
void setConfig(const QgsSnappingConfig &snappingConfig)
The snapping configuration controls the behavior of this object.
void setEnableSnappingForInvisibleFeature(bool enable)
Set if invisible features must be snapped or not.
QList< QgsSnappingUtils::LayerConfig > layers() const
Query layers used for snapping.
virtual void prepareIndexStarting(int count)
Called when starting to index with snapToMap - can be overridden and e.g. progress dialog can be prov...
static double vertexSearchRadius(const QgsMapSettings &mapSettings)
Static function to get vertex tolerance value.
static double toleranceInProjectUnits(double tolerance, QgsMapLayer *layer, const QgsMapSettings &mapSettings, Qgis::MapToolUnit units)
Static function to translate tolerance value into map units.
Represents a vector layer which manages a vector based dataset.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
QgsRectangle extent() const final
Returns the extent of the layer.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
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
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.
#define QgsDebugMsgLevel(str, level)
QgsRectangle _areaOfInterest(const QgsPointXY &point, double tolerance)
Interface that allows rejection of some matches in intersection queries (e.g.
double distance() const
for vertex / edge match units depending on what class returns it (geom.cache: layer units,...
QgsPointLocator::Type type() const
Configures how a certain layer should be handled in a snapping operation.