QGIS API Documentation  3.12.1-BucureČ™ti (121cc00ff0)
pal.cpp
Go to the documentation of this file.
1 /*
2  * libpal - Automated Placement of Labels Library
3  *
4  * Copyright (C) 2008 Maxence Laurent, MIS-TIC, HEIG-VD
5  * University of Applied Sciences, Western Switzerland
6  * http://www.hes-so.ch
7  *
8  * Contact:
9  * maxence.laurent <at> heig-vd <dot> ch
10  * or
11  * eric.taillard <at> heig-vd <dot> ch
12  *
13  * This file is part of libpal.
14  *
15  * libpal is free software: you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation, either version 3 of the License, or
18  * (at your option) any later version.
19  *
20  * libpal is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with libpal. If not, see <http://www.gnu.org/licenses/>.
27  *
28  */
29 
30 #include "qgsgeometry.h"
31 #include "pal.h"
32 #include "layer.h"
33 #include "palexception.h"
34 #include "palstat.h"
35 #include "costcalculator.h"
36 #include "feature.h"
37 #include "geomfunction.h"
38 #include "labelposition.h"
39 #include "problem.h"
40 #include "pointset.h"
41 #include "internalexception.h"
42 #include "util.h"
43 #include "palrtree.h"
44 #include "qgssettings.h"
45 #include <cfloat>
46 #include <list>
47 
48 using namespace pal;
49 
51 {
52  QgsSettings settings;
53  mGlobalCandidatesLimitPoint = settings.value( QStringLiteral( "rendering/label_candidates_limit_points" ), 0, QgsSettings::Core ).toInt();
54  mGlobalCandidatesLimitLine = settings.value( QStringLiteral( "rendering/label_candidates_limit_lines" ), 0, QgsSettings::Core ).toInt();
55  mGlobalCandidatesLimitPolygon = settings.value( QStringLiteral( "rendering/label_candidates_limit_polygons" ), 0, QgsSettings::Core ).toInt();
56 }
57 
58 Pal::~Pal() = default;
59 
60 void Pal::removeLayer( Layer *layer )
61 {
62  if ( !layer )
63  return;
64 
65  mMutex.lock();
66 
67  for ( auto it = mLayers.begin(); it != mLayers.end(); ++it )
68  {
69  if ( it->second.get() == layer )
70  {
71  mLayers.erase( it );
72  break;
73  }
74  }
75  mMutex.unlock();
76 }
77 
78 Layer *Pal::addLayer( QgsAbstractLabelProvider *provider, const QString &layerName, QgsPalLayerSettings::Placement arrangement, double defaultPriority, bool active, bool toLabel, bool displayAll )
79 {
80  mMutex.lock();
81 
82  Q_ASSERT( mLayers.find( provider ) == mLayers.end() );
83 
84  std::unique_ptr< Layer > layer = qgis::make_unique< Layer >( provider, layerName, arrangement, defaultPriority, active, toLabel, this, displayAll );
85  Layer *res = layer.get();
86  mLayers.insert( std::pair<QgsAbstractLabelProvider *, std::unique_ptr< Layer >>( provider, std::move( layer ) ) );
87  mMutex.unlock();
88 
89  return res;
90 }
91 
92 std::unique_ptr<Problem> Pal::extract( const QgsRectangle &extent, const QgsGeometry &mapBoundary )
93 {
94  // expand out the incoming buffer by 1000x -- that's the visible map extent, yet we may be getting features which exceed this extent
95  // (while 1000x may seem excessive here, this value is only used for scaling coordinates in the spatial indexes
96  // and the consequence of inserting coordinates outside this extent is worse than the consequence of setting this value too large.)
97  const QgsRectangle maxCoordinateExtentForSpatialIndices = extent.buffered( std::max( extent.width(), extent.height() ) * 1000 );
98 
99  // to store obstacles
100  PalRtree< FeaturePart > obstacles( maxCoordinateExtentForSpatialIndices );
101  PalRtree< LabelPosition > allCandidatesFirstRound( maxCoordinateExtentForSpatialIndices );
102  std::vector< FeaturePart * > allObstacleParts;
103  std::unique_ptr< Problem > prob = qgis::make_unique< Problem >( maxCoordinateExtentForSpatialIndices );
104 
105  double bbx[4];
106  double bby[4];
107 
108  bbx[0] = bbx[3] = prob->mMapExtentBounds[0] = extent.xMinimum();
109  bby[0] = bby[1] = prob->mMapExtentBounds[1] = extent.yMinimum();
110  bbx[1] = bbx[2] = prob->mMapExtentBounds[2] = extent.xMaximum();
111  bby[2] = bby[3] = prob->mMapExtentBounds[3] = extent.yMaximum();
112 
113  prob->pal = this;
114 
115  std::list< std::unique_ptr< Feats > > features;
116 
117  // prepare map boundary
118  geos::unique_ptr mapBoundaryGeos( QgsGeos::asGeos( mapBoundary ) );
119  geos::prepared_unique_ptr mapBoundaryPrepared( GEOSPrepare_r( QgsGeos::getGEOSHandler(), mapBoundaryGeos.get() ) );
120 
121  int obstacleCount = 0;
122 
123  // first step : extract features from layers
124 
125  std::size_t previousFeatureCount = 0;
126  int previousObstacleCount = 0;
127 
128  QStringList layersWithFeaturesInBBox;
129 
130  QMutexLocker palLocker( &mMutex );
131  for ( const auto &it : mLayers )
132  {
133  Layer *layer = it.second.get();
134  if ( !layer )
135  {
136  // invalid layer name
137  continue;
138  }
139 
140  // only select those who are active
141  if ( !layer->active() )
142  continue;
143 
144  // check for connected features with the same label text and join them
145  if ( layer->mergeConnectedLines() )
146  layer->joinConnectedFeatures();
147 
148  if ( isCanceled() )
149  return nullptr;
150 
152 
153  if ( isCanceled() )
154  return nullptr;
155 
156  QMutexLocker locker( &layer->mMutex );
157 
158  // generate candidates for all features
159  for ( FeaturePart *featurePart : qgis::as_const( layer->mFeatureParts ) )
160  {
161  if ( isCanceled() )
162  break;
163 
164  // Holes of the feature are obstacles
165  for ( int i = 0; i < featurePart->getNumSelfObstacles(); i++ )
166  {
167  FeaturePart *selfObstacle = featurePart->getSelfObstacle( i );
168  obstacles.insert( selfObstacle, selfObstacle->boundingBox() );
169  allObstacleParts.emplace_back( selfObstacle );
170 
171  if ( !featurePart->getSelfObstacle( i )->getHoleOf() )
172  {
173  //ERROR: SHOULD HAVE A PARENT!!!!!
174  }
175  }
176 
177  // generate candidates for the feature part
178  std::vector< std::unique_ptr< LabelPosition > > candidates = featurePart->createCandidates( this );
179 
180  if ( isCanceled() )
181  break;
182 
183  // purge candidates that are outside the bbox
184  candidates.erase( std::remove_if( candidates.begin(), candidates.end(), [&mapBoundaryPrepared, this]( std::unique_ptr< LabelPosition > &candidate )
185  {
186  if ( showPartialLabels() )
187  return !candidate->intersects( mapBoundaryPrepared.get() );
188  else
189  return !candidate->within( mapBoundaryPrepared.get() );
190  } ), candidates.end() );
191 
192  if ( isCanceled() )
193  break;
194 
195  if ( !candidates.empty() )
196  {
197  for ( std::unique_ptr< LabelPosition > &candidate : candidates )
198  {
199  candidate->insertIntoIndex( allCandidatesFirstRound );
200  }
201 
202  std::sort( candidates.begin(), candidates.end(), CostCalculator::candidateSortGrow );
203 
204  // valid features are added to fFeats
205  std::unique_ptr< Feats > ft = qgis::make_unique< Feats >();
206  ft->feature = featurePart;
207  ft->shape = nullptr;
208  ft->candidates = std::move( candidates );
209  ft->priority = featurePart->calculatePriority();
210  features.emplace_back( std::move( ft ) );
211  }
212  else
213  {
214  // features with no candidates are recorded in the unlabeled feature list
215  std::unique_ptr< LabelPosition > unplacedPosition = featurePart->createCandidatePointOnSurface( featurePart );
216  if ( unplacedPosition )
217  prob->positionsWithNoCandidates()->emplace_back( std::move( unplacedPosition ) );
218  }
219  }
220  if ( isCanceled() )
221  return nullptr;
222 
223  // collate all layer obstacles
224  for ( FeaturePart *obstaclePart : qgis::as_const( layer->mObstacleParts ) )
225  {
226  if ( isCanceled() )
227  break; // do not continue searching
228 
229  // insert into obstacles
230  obstacles.insert( obstaclePart, obstaclePart->boundingBox() );
231  allObstacleParts.emplace_back( obstaclePart );
232  obstacleCount++;
233  }
234 
235  if ( isCanceled() )
236  return nullptr;
237 
238  locker.unlock();
239 
240  if ( features.size() - previousFeatureCount > 0 || obstacleCount > previousObstacleCount )
241  {
242  layersWithFeaturesInBBox << layer->name();
243  }
244  previousFeatureCount = features.size();
245  previousObstacleCount = obstacleCount;
246  }
247  palLocker.unlock();
248 
249  if ( isCanceled() )
250  return nullptr;
251 
252  prob->mLayerCount = layersWithFeaturesInBBox.size();
253  prob->labelledLayersName = layersWithFeaturesInBBox;
254 
255  prob->mFeatureCount = features.size();
256  prob->mTotalCandidates = 0;
257  prob->mFeatNbLp.resize( prob->mFeatureCount );
258  prob->mFeatStartId.resize( prob->mFeatureCount );
259  prob->mInactiveCost.resize( prob->mFeatureCount );
260 
261  if ( !features.empty() )
262  {
263  // Filtering label positions against obstacles
264  for ( FeaturePart *obstaclePart : allObstacleParts )
265  {
266  if ( isCanceled() )
267  break; // do not continue searching
268 
269  allCandidatesFirstRound.intersects( obstaclePart->boundingBox(), [obstaclePart, this]( const LabelPosition * candidatePosition ) -> bool
270  {
271  // test whether we should ignore this obstacle for the candidate. We do this if:
272  // 1. it's not a hole, and the obstacle belongs to the same label feature as the candidate (e.g.,
273  // features aren't obstacles for their own labels)
274  // 2. it IS a hole, and the hole belongs to a different label feature to the candidate (e.g., holes
275  // are ONLY obstacles for the labels of the feature they belong to)
276  if ( ( !obstaclePart->getHoleOf() && candidatePosition->getFeaturePart()->hasSameLabelFeatureAs( obstaclePart ) )
277  || ( obstaclePart->getHoleOf() && !candidatePosition->getFeaturePart()->hasSameLabelFeatureAs( dynamic_cast< FeaturePart * >( obstaclePart->getHoleOf() ) ) ) )
278  {
279  return true;
280  }
281 
282  CostCalculator::addObstacleCostPenalty( const_cast< LabelPosition * >( candidatePosition ), obstaclePart, this );
283 
284  return true;
285  } );
286  }
287 
288  if ( isCanceled() )
289  {
290  return nullptr;
291  }
292 
293  int idlp = 0;
294  for ( std::size_t i = 0; i < prob->mFeatureCount; i++ ) /* foreach feature into prob */
295  {
296  std::unique_ptr< Feats > feat = std::move( features.front() );
297  features.pop_front();
298 
299  prob->mFeatStartId[i] = idlp;
300  prob->mInactiveCost[i] = std::pow( 2, 10 - 10 * feat->priority );
301 
302  std::size_t maxCandidates = 0;
303  switch ( feat->feature->getGeosType() )
304  {
305  case GEOS_POINT:
306  // this is usually 0, i.e. no maximum
307  maxCandidates = feat->feature->maximumPointCandidates();
308  break;
309 
310  case GEOS_LINESTRING:
311  maxCandidates = feat->feature->maximumLineCandidates();
312  break;
313 
314  case GEOS_POLYGON:
315  maxCandidates = feat->feature->maximumPolygonCandidates();
316  break;
317  }
318 
319  if ( isCanceled() )
320  return nullptr;
321 
322  switch ( mPlacementVersion )
323  {
325  break;
326 
328  {
329  // v2 placement rips out candidates where the candidate cost is too high when compared to
330  // their inactive cost
331 
332  // note, we start this at the SECOND candidate (you'll see why after this loop)
333  feat->candidates.erase( std::remove_if( feat->candidates.begin() + 1, feat->candidates.end(), [ & ]( std::unique_ptr< LabelPosition > &candidate )
334  {
335  if ( candidate->hasHardObstacleConflict() )
336  {
337  return true;
338  }
339  return false;
340  } ), feat->candidates.end() );
341 
342  if ( feat->candidates.size() == 1 && feat->candidates[ 0 ]->hasHardObstacleConflict() )
343  {
344  // we've ended up removing ALL candidates for this label. Oh well, that's allowed. We just need to
345  // make sure we move this last candidate to the unplaced labels list
346  prob->positionsWithNoCandidates()->emplace_back( std::move( feat->candidates.front() ) );
347  feat->candidates.clear();
348  }
349  }
350  }
351 
352  if ( feat->candidates.empty() )
353  continue;
354 
355  // calculate final costs
356  CostCalculator::finalizeCandidatesCosts( feat.get(), bbx, bby );
357 
358  // sort candidates list, best label to worst
359  std::sort( feat->candidates.begin(), feat->candidates.end(), CostCalculator::candidateSortGrow );
360 
361  // only keep the 'maxCandidates' best candidates
362  if ( maxCandidates > 0 && feat->candidates.size() > maxCandidates )
363  {
364  feat->candidates.resize( maxCandidates );
365  }
366 
367  if ( isCanceled() )
368  return nullptr;
369 
370  // update problem's # candidate
371  prob->mFeatNbLp[i] = static_cast< int >( feat->candidates.size() );
372  prob->mTotalCandidates += static_cast< int >( feat->candidates.size() );
373 
374  // add all candidates into a rtree (to speed up conflicts searching)
375  for ( std::unique_ptr< LabelPosition > &candidate : feat->candidates )
376  {
377  candidate->insertIntoIndex( prob->allCandidatesIndex() );
378  candidate->setProblemIds( static_cast< int >( i ), idlp++ );
379  }
380  features.emplace_back( std::move( feat ) );
381  }
382 
383  int nbOverlaps = 0;
384 
385  double amin[2];
386  double amax[2];
387  while ( !features.empty() ) // foreach feature
388  {
389  if ( isCanceled() )
390  return nullptr;
391 
392  std::unique_ptr< Feats > feat = std::move( features.front() );
393  features.pop_front();
394 
395  for ( std::unique_ptr< LabelPosition > &candidate : feat->candidates )
396  {
397  std::unique_ptr< LabelPosition > lp = std::move( candidate );
398 
399  lp->resetNumOverlaps();
400 
401  // make sure that candidate's cost is less than 1
402  lp->validateCost();
403 
404  //prob->feat[idlp] = j;
405 
406  // lookup for overlapping candidate
407  lp->getBoundingBox( amin, amax );
408  prob->allCandidatesIndex().intersects( QgsRectangle( amin[0], amin[1], amax[0], amax[1] ), [&lp]( const LabelPosition * lp2 )->bool
409  {
410  if ( lp->isInConflict( lp2 ) )
411  {
412  lp->incrementNumOverlaps();
413  }
414 
415  return true;
416 
417  } );
418 
419  nbOverlaps += lp->getNumOverlaps();
420 
421  prob->addCandidatePosition( std::move( lp ) );
422 
423  if ( isCanceled() )
424  return nullptr;
425  }
426  }
427  nbOverlaps /= 2;
428  prob->mAllNblp = prob->mTotalCandidates;
429  prob->mNbOverlap = nbOverlaps;
430  }
431 
432  return prob;
433 }
434 
435 void Pal::registerCancellationCallback( Pal::FnIsCanceled fnCanceled, void *context )
436 {
437  fnIsCanceled = fnCanceled;
438  fnIsCanceledContext = context;
439 }
440 
441 std::unique_ptr<Problem> Pal::extractProblem( const QgsRectangle &extent, const QgsGeometry &mapBoundary )
442 {
443  return extract( extent, mapBoundary );
444 }
445 
446 QList<LabelPosition *> Pal::solveProblem( Problem *prob, bool displayAll, QList<LabelPosition *> *unlabeled )
447 {
448  if ( !prob )
449  return QList<LabelPosition *>();
450 
451  prob->reduce();
452 
453  try
454  {
455  prob->chain_search();
456  }
457  catch ( InternalException::Empty & )
458  {
459  return QList<LabelPosition *>();
460  }
461 
462  return prob->getSolution( displayAll, unlabeled );
463 }
464 
465 void Pal::setMinIt( int min_it )
466 {
467  if ( min_it >= 0 )
468  mTabuMinIt = min_it;
469 }
470 
471 void Pal::setMaxIt( int max_it )
472 {
473  if ( max_it > 0 )
474  mTabuMaxIt = max_it;
475 }
476 
477 void Pal::setPopmusicR( int r )
478 {
479  if ( r > 0 )
480  mPopmusicR = r;
481 }
482 
483 void Pal::setEjChainDeg( int degree )
484 {
485  this->mEjChainDeg = degree;
486 }
487 
488 void Pal::setTenure( int tenure )
489 {
490  this->mTenure = tenure;
491 }
492 
493 void Pal::setCandListSize( double fact )
494 {
495  this->mCandListSize = fact;
496 }
497 
498 void Pal::setShowPartialLabels( bool show )
499 {
500  this->mShowPartialLabels = show;
501 }
502 
504 {
505  return mPlacementVersion;
506 }
507 
509 {
510  mPlacementVersion = placementVersion;
511 }
512 
513 int Pal::getMinIt()
514 {
515  return mTabuMaxIt;
516 }
517 
518 int Pal::getMaxIt()
519 {
520  return mTabuMinIt;
521 }
522 
524 {
525  return mShowPartialLabels;
526 }
static void addObstacleCostPenalty(pal::LabelPosition *lp, pal::FeaturePart *obstacle, Pal *pal)
Increase candidate&#39;s cost according to its collision with passed feature.
Layer * addLayer(QgsAbstractLabelProvider *provider, const QString &layerName, QgsPalLayerSettings::Placement arrangement, double defaultPriority, bool active, bool toLabel, bool displayAll=false)
add a new layer
Definition: pal.cpp:78
QList< FeaturePart * > mObstacleParts
List of obstacle parts.
Definition: layer.h:328
static bool candidateSortGrow(const std::unique_ptr< pal::LabelPosition > &c1, const std::unique_ptr< pal::LabelPosition > &c2)
Sorts label candidates in ascending order of cost.
A rectangle specified with double values.
Definition: qgsrectangle.h:41
bool mergeConnectedLines() const
Returns whether connected lines will be merged before labeling.
Definition: layer.h:265
void reduce()
Definition: problem.cpp:66
bool showPartialLabels() const
Returns whether partial labels should be allowed.
Definition: pal.cpp:523
This class is a composition of two QSettings instances:
Definition: qgssettings.h:58
Version 1, matches placement from QGIS <= 3.10.1.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
std::unique_ptr< const GEOSPreparedGeometry, GeosDeleter > prepared_unique_ptr
Scoped GEOS prepared geometry pointer.
Definition: qgsgeos.h:84
void registerCancellationCallback(FnIsCanceled fnCanceled, void *context)
Register a function that returns whether this job has been canceled - PAL calls it during the computa...
Definition: pal.cpp:435
A set of features which influence the labeling process.
Definition: layer.h:61
void chopFeaturesAtRepeatDistance()
Chop layer features at the repeat distance *.
Definition: layer.cpp:339
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:122
void setPlacementVersion(QgsLabelingEngineSettings::PlacementEngineVersion placementVersion)
Sets the placement engine version, which dictates how the label placement problem is solved...
Definition: pal.cpp:508
A rtree spatial index for use in the pal labeling engine.
Definition: palrtree.h:35
static GEOSContextHandle_t getGEOSHandler()
Definition: qgsgeos.cpp:2872
void removeLayer(Layer *layer)
remove a layer
Definition: pal.cpp:60
std::unique_ptr< Problem > extractProblem(const QgsRectangle &extent, const QgsGeometry &mapBoundary)
Extracts the labeling problem for the specified map extent - only features within this extent will be...
Definition: pal.cpp:441
bool intersects(const QgsRectangle &bounds, const std::function< bool(T *data)> &callback) const
Performs an intersection check against the index, for data intersecting the specified bounds...
Definition: palrtree.h:96
QgsRectangle buffered(double width) const
Gets rectangle enlarged by buffer.
Definition: qgsrectangle.h:304
Version 2 (default for new projects since QGIS 3.12)
void chain_search()
Test with very-large scale neighborhood.
Definition: problem.cpp:561
bool(* FnIsCanceled)(void *ctx)
Definition: pal.h:121
void joinConnectedFeatures()
Join connected features with the same label text.
Definition: layer.cpp:294
double width() const
Returns the width of the rectangle.
Definition: qgsrectangle.h:202
QgsLabelingEngineSettings::PlacementEngineVersion placementVersion() const
Returns the placement engine version, which dictates how the label placement problem is solved...
Definition: pal.cpp:503
bool isCanceled()
Check whether the job has been canceled.
Definition: pal.h:127
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition: qgsgeos.h:79
Main class to handle feature.
Definition: feature.h:95
The QgsAbstractLabelProvider class is an interface class.
Pal()
Create an new pal instance.
Definition: pal.cpp:50
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:177
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:162
Placement
Placement modes which determine how label candidates are generated for a feature. ...
QgsRectangle boundingBox() const
Returns the point set bounding box.
Definition: pointset.h:154
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0)
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
Definition: qgsgeos.cpp:166
QLinkedList< FeaturePart * > mFeatureParts
List of feature parts.
Definition: layer.h:325
FeaturePart * getSelfObstacle(int i)
Gets hole (inner ring) - considered as obstacle.
Definition: feature.h:331
QMutex mMutex
Definition: layer.h:355
QString name() const
Returns the layer&#39;s name.
Definition: layer.h:171
bool active() const
Returns whether the layer is currently active.
Definition: layer.h:207
LabelPosition is a candidate feature label position.
Definition: labelposition.h:55
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:167
Representation of a labeling problem.
Definition: problem.h:69
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:172
QList< LabelPosition * > solveProblem(Problem *prob, bool displayAll, QList< pal::LabelPosition *> *unlabeled=nullptr)
Solves the labeling problem, selecting the best candidate locations for all labels and returns a list...
Definition: pal.cpp:446
QList< LabelPosition * > getSolution(bool returnInactive, QList< LabelPosition *> *unlabeled=nullptr)
Solves the labeling problem, selecting the best candidate locations for all labels and returns a list...
Definition: problem.cpp:656
void insert(T *data, const QgsRectangle &bounds)
Inserts new data into the spatial index, with the specified bounds.
Definition: palrtree.h:59
PlacementEngineVersion
Placement engine version.
static void finalizeCandidatesCosts(Feats *feat, double bbx[4], double bby[4])
Sort candidates by costs, skip the worse ones, evaluate polygon candidates.
Thrown when trying to access an empty data set.
double height() const
Returns the height of the rectangle.
Definition: qgsrectangle.h:209
void setShowPartialLabels(bool show)
Sets whether partial labels show be allowed.
Definition: pal.cpp:498