QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
qgsvectorlayerrenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectorlayerrenderer.cpp
3 --------------------------------------
4 Date : December 2013
5 Copyright : (C) 2013 by Martin Dobias
6 Email : wonder dot sk at gmail 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
17
18#include "qgsmessagelog.h"
19#include "qgspallabeling.h"
20#include "qgsrenderer.h"
21#include "qgsrendercontext.h"
23#include "qgssymbollayer.h"
24#include "qgssymbol.h"
25#include "qgsvectorlayer.h"
30#include "qgspainteffect.h"
32#include "qgsexception.h"
33#include "qgslabelsink.h"
34#include "qgslogger.h"
40#include "qgsmapclippingutils.h"
43#include "qgsruntimeprofiler.h"
44#include "qgsapplication.h"
45
46#include <QPicture>
47#include <QTimer>
48#include <QThread>
49
51 : QgsMapLayerRenderer( layer->id(), &context )
52 , mFeedback( std::make_unique< QgsFeedback >() )
53 , mLayer( layer )
54 , mLayerName( layer->name() )
55 , mFields( layer->fields() )
56 , mSource( std::make_unique< QgsVectorLayerFeatureSource >( layer ) )
57 , mNoSetLayerExpressionContext( layer->customProperty( QStringLiteral( "_noset_layer_expression_context" ) ).toBool() )
58 , mEnableProfile( context.flags() & Qgis::RenderContextFlag::RecordProfile )
59{
60 QElapsedTimer timer;
61 timer.start();
62 std::unique_ptr< QgsFeatureRenderer > mainRenderer( layer->renderer() ? layer->renderer()->clone() : nullptr );
63
64 QgsVectorLayerSelectionProperties *selectionProperties = qobject_cast< QgsVectorLayerSelectionProperties * >( layer->selectionProperties() );
65 switch ( selectionProperties->selectionRenderingMode() )
66 {
68 break;
69
71 {
72 // overwrite default selection color if layer has a specific selection color set
73 const QColor layerSelectionColor = selectionProperties->selectionColor();
74 if ( layerSelectionColor.isValid() )
75 context.setSelectionColor( layerSelectionColor );
76 break;
77 }
78
80 {
81 if ( QgsSymbol *selectionSymbol = qobject_cast< QgsVectorLayerSelectionProperties * >( layer->selectionProperties() )->selectionSymbol() )
82 mSelectionSymbol.reset( selectionSymbol->clone() );
83 break;
84 }
85 }
86
87 if ( !mainRenderer )
88 return;
89
90 QList< const QgsFeatureRendererGenerator * > generators = layer->featureRendererGenerators();
91 std::sort( generators.begin(), generators.end(), []( const QgsFeatureRendererGenerator * g1, const QgsFeatureRendererGenerator * g2 )
92 {
93 return g1->level() < g2->level();
94 } );
95
96 bool insertedMainRenderer = false;
97 double prevLevel = std::numeric_limits< double >::lowest();
98 // cppcheck-suppress danglingLifetime
99 mRenderer = mainRenderer.get();
100 for ( const QgsFeatureRendererGenerator *generator : std::as_const( generators ) )
101 {
102 if ( generator->level() >= 0 && prevLevel < 0 && !insertedMainRenderer )
103 {
104 // insert main renderer when level changes from <0 to >0
105 mRenderers.emplace_back( std::move( mainRenderer ) );
106 insertedMainRenderer = true;
107 }
108 mRenderers.emplace_back( generator->createRenderer() );
109 prevLevel = generator->level();
110 }
111 // cppcheck-suppress accessMoved
112 if ( mainRenderer )
113 {
114 // cppcheck-suppress accessMoved
115 mRenderers.emplace_back( std::move( mainRenderer ) );
116 }
117
118 mSelectedFeatureIds = layer->selectedFeatureIds();
119
120 mDrawVertexMarkers = nullptr != layer->editBuffer();
121
122 mGeometryType = layer->geometryType();
123
124 mFeatureBlendMode = layer->featureBlendMode();
125
126 if ( context.isTemporal() )
127 {
128 QgsVectorLayerTemporalContext temporalContext;
129 temporalContext.setLayer( layer );
130 mTemporalFilter = qobject_cast< const QgsVectorLayerTemporalProperties * >( layer->temporalProperties() )->createFilterString( temporalContext, context.temporalRange() );
131 QgsDebugMsgLevel( "Rendering with Temporal Filter: " + mTemporalFilter, 2 );
132 }
133
134 // if there's already a simplification method specified via the context, we respect that. Otherwise, we fall back
135 // to the layer's individual setting
136 if ( renderContext()->vectorSimplifyMethod().simplifyHints() != QgsVectorSimplifyMethod::NoSimplification )
137 {
138 mSimplifyMethod = renderContext()->vectorSimplifyMethod();
141 }
142 else
143 {
144 mSimplifyMethod = layer->simplifyMethod();
146 }
147
149
151 if ( markerTypeString == QLatin1String( "Cross" ) )
152 {
153 mVertexMarkerStyle = Qgis::VertexMarkerType::Cross;
154 }
155 else if ( markerTypeString == QLatin1String( "SemiTransparentCircle" ) )
156 {
158 }
159 else
160 {
161 mVertexMarkerStyle = Qgis::VertexMarkerType::NoMarker;
162 }
163
165
166 // cppcheck-suppress danglingLifetime
167 QgsDebugMsgLevel( "rendering v2:\n " + mRenderer->dump(), 2 );
168
169 if ( mDrawVertexMarkers )
170 {
171 // set editing vertex markers style (main renderer only)
172 mRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
173 }
174 if ( !mNoSetLayerExpressionContext )
176
177 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
178 {
179 mAttrNames.unite( renderer->usedAttributes( context ) );
180 }
181 if ( context.hasRenderedFeatureHandlers() )
182 {
183 const QList< QgsRenderedFeatureHandlerInterface * > handlers = context.renderedFeatureHandlers();
184 for ( QgsRenderedFeatureHandlerInterface *handler : handlers )
185 mAttrNames.unite( handler->usedAttributes( layer, context ) );
186 }
187
188 //register label and diagram layer to the labeling engine
189 prepareLabeling( layer, mAttrNames );
190 prepareDiagrams( layer, mAttrNames );
191
192 mClippingRegions = QgsMapClippingUtils::collectClippingRegionsForLayer( context, layer );
193
194 if ( std::any_of( mRenderers.begin(), mRenderers.end(), []( const auto & renderer ) { return renderer->forceRasterRender(); } ) )
195 {
196 //raster rendering is forced for this layer
197 mForceRasterRender = true;
198 }
199
201 ( ( layer->blendMode() != QPainter::CompositionMode_SourceOver )
202 || ( layer->featureBlendMode() != QPainter::CompositionMode_SourceOver )
203 || ( !qgsDoubleNear( layer->opacity(), 1.0 ) ) ) )
204 {
205 //layer properties require rasterization
206 mForceRasterRender = true;
207 }
208
209 mReadyToCompose = false;
210 mPreparationTime = timer.elapsed();
211}
212
214
216{
217 mRenderTimeHint = time;
218}
219
221{
222 return mFeedback.get();
223}
224
226{
227 return mForceRasterRender;
228}
229
231{
232 if ( mGeometryType == Qgis::GeometryType::Null || mGeometryType == Qgis::GeometryType::Unknown )
233 {
234 mReadyToCompose = true;
235 return true;
236 }
237
238 if ( mRenderers.empty() )
239 {
240 mReadyToCompose = true;
241 mErrors.append( QObject::tr( "No renderer for drawing." ) );
242 return false;
243 }
244
245 std::unique_ptr< QgsScopedRuntimeProfile > profile;
246 if ( mEnableProfile )
247 {
248 profile = std::make_unique< QgsScopedRuntimeProfile >( mLayerName, QStringLiteral( "rendering" ), layerId() );
249 if ( mPreparationTime > 0 )
250 QgsApplication::profiler()->record( QObject::tr( "Create renderer" ), mPreparationTime / 1000.0, QStringLiteral( "rendering" ) );
251 }
252
253 // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
254 // cached version of the layer during rendering instead of the usual progressive updates
255 if ( mRenderTimeHint > 0 && mRenderTimeHint <= MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
256 {
257 mBlockRenderUpdates = true;
258 mElapsedTimer.start();
259 }
260
261 bool res = true;
262 int rendererIndex = 0;
263 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
264 {
265 if ( mFeedback->isCanceled() || !res )
266 {
267 break;
268 }
269 res = renderInternal( renderer.get(), rendererIndex++ ) && res;
270 }
271
272 mReadyToCompose = true;
273 return res && !renderContext()->renderingStopped();
274}
275
276bool QgsVectorLayerRenderer::renderInternal( QgsFeatureRenderer *renderer, int rendererIndex )
277{
278 const bool isMainRenderer = renderer == mRenderer;
279
280 QgsRenderContext &context = *renderContext();
281 context.setSymbologyReferenceScale( renderer->referenceScale() );
282
283 if ( renderer->type() == QLatin1String( "nullSymbol" ) )
284 {
285 // a little shortcut for the null symbol renderer - most of the time it is not going to render anything
286 // so we can even skip the whole loop to fetch features
287 if ( !isMainRenderer ||
288 ( !mDrawVertexMarkers && !mLabelProvider && !mDiagramProvider && mSelectedFeatureIds.isEmpty() ) )
289 return true;
290 }
291
292 std::unique_ptr< QgsScopedRuntimeProfile > preparingProfile;
293 if ( mEnableProfile )
294 {
295 QString title;
296 if ( mRenderers.size() > 1 )
297 title = QObject::tr( "Preparing render %1" ).arg( rendererIndex + 1 );
298 else
299 title = QObject::tr( "Preparing render" );
300 preparingProfile = std::make_unique< QgsScopedRuntimeProfile >( title, QStringLiteral( "rendering" ) );
301 }
302
303 QgsScopedQPainterState painterState( context.painter() );
304
305 bool usingEffect = false;
306 if ( renderer->paintEffect() && renderer->paintEffect()->enabled() )
307 {
308 usingEffect = true;
309 renderer->paintEffect()->begin( context );
310 }
311
312 // Per feature blending mode
313 if ( context.useAdvancedEffects() && mFeatureBlendMode != QPainter::CompositionMode_SourceOver )
314 {
315 // set the painter to the feature blend mode, so that features drawn
316 // on this layer will interact and blend with each other
317 context.painter()->setCompositionMode( mFeatureBlendMode );
318 }
319
320 renderer->startRender( context, mFields );
321
322 if ( renderer->canSkipRender() )
323 {
324 // nothing to draw for now...
325 renderer->stopRender( context );
326 return true;
327 }
328
329 QString rendererFilter = renderer->filter( mFields );
330
331 QgsRectangle requestExtent = context.extent();
332 if ( !mClippingRegions.empty() )
333 {
334 mClipFilterGeom = QgsMapClippingUtils::calculateFeatureRequestGeometry( mClippingRegions, context, mApplyClipFilter );
335 requestExtent = requestExtent.intersect( mClipFilterGeom.boundingBox() );
336
337 mClipFeatureGeom = QgsMapClippingUtils::calculateFeatureIntersectionGeometry( mClippingRegions, context, mApplyClipGeometries );
338
339 bool needsPainterClipPath = false;
340 const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, context, Qgis::LayerType::Vector, needsPainterClipPath );
341 if ( needsPainterClipPath )
342 context.painter()->setClipPath( path, Qt::IntersectClip );
343
344 mLabelClipFeatureGeom = QgsMapClippingUtils::calculateLabelIntersectionGeometry( mClippingRegions, context, mApplyLabelClipGeometries );
345
346 if ( mDiagramProvider )
347 mDiagramProvider->setClipFeatureGeometry( mLabelClipFeatureGeom );
348 }
349 renderer->modifyRequestExtent( requestExtent, context );
350
351 QgsFeatureRequest featureRequest = QgsFeatureRequest()
352 .setFilterRect( requestExtent )
353 .setSubsetOfAttributes( mAttrNames, mFields )
355 if ( renderer->orderByEnabled() )
356 {
357 featureRequest.setOrderBy( renderer->orderBy() );
358 }
359
360 const QgsFeatureFilterProvider *featureFilterProvider = context.featureFilterProvider();
361 if ( featureFilterProvider )
362 {
363 featureFilterProvider->filterFeatures( mLayer, featureRequest );
364 }
365 if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) )
366 {
367 featureRequest.combineFilterExpression( rendererFilter );
368 }
369 if ( !mTemporalFilter.isEmpty() )
370 {
371 featureRequest.combineFilterExpression( mTemporalFilter );
372 }
373
374 if ( renderer->usesEmbeddedSymbols() )
375 {
376 featureRequest.setFlags( featureRequest.flags() | Qgis::FeatureRequestFlag::EmbeddedSymbols );
377 }
378
379 // enable the simplification of the geometries (Using the current map2pixel context) before send it to renderer engine.
380 if ( mSimplifyGeometry )
381 {
382 double map2pixelTol = mSimplifyMethod.threshold();
383 bool validTransform = true;
384
385 const QgsMapToPixel &mtp = context.mapToPixel();
386 map2pixelTol *= mtp.mapUnitsPerPixel();
387 const QgsCoordinateTransform ct = context.coordinateTransform();
388
389 // resize the tolerance using the change of size of an 1-BBOX from the source CoordinateSystem to the target CoordinateSystem
390 if ( ct.isValid() && !ct.isShortCircuited() )
391 {
392 try
393 {
394 QgsCoordinateTransform toleranceTransform = ct;
395 QgsPointXY center = context.extent().center();
396 double rectSize = toleranceTransform.sourceCrs().mapUnits() == Qgis::DistanceUnit::Degrees ? 0.0008983 /* ~100/(40075014/360=111319.4833) */ : 100;
397
398 QgsRectangle sourceRect = QgsRectangle( center.x(), center.y(), center.x() + rectSize, center.y() + rectSize );
399 toleranceTransform.setBallparkTransformsAreAppropriate( true );
400 QgsRectangle targetRect = toleranceTransform.transform( sourceRect );
401
402 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceTransformRect=%1" ).arg( sourceRect.toString( 16 ) ), 4 );
403 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetTransformRect=%1" ).arg( targetRect.toString( 16 ) ), 4 );
404
405 if ( !sourceRect.isEmpty() && sourceRect.isFinite() && !targetRect.isEmpty() && targetRect.isFinite() )
406 {
407 QgsPointXY minimumSrcPoint( sourceRect.xMinimum(), sourceRect.yMinimum() );
408 QgsPointXY maximumSrcPoint( sourceRect.xMaximum(), sourceRect.yMaximum() );
409 QgsPointXY minimumDstPoint( targetRect.xMinimum(), targetRect.yMinimum() );
410 QgsPointXY maximumDstPoint( targetRect.xMaximum(), targetRect.yMaximum() );
411
412 double sourceHypothenuse = std::sqrt( minimumSrcPoint.sqrDist( maximumSrcPoint ) );
413 double targetHypothenuse = std::sqrt( minimumDstPoint.sqrDist( maximumDstPoint ) );
414
415 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceHypothenuse=%1" ).arg( sourceHypothenuse ), 4 );
416 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetHypothenuse=%1" ).arg( targetHypothenuse ), 4 );
417
418 if ( !qgsDoubleNear( targetHypothenuse, 0.0 ) )
419 map2pixelTol *= ( sourceHypothenuse / targetHypothenuse );
420 }
421 }
422 catch ( QgsCsException &cse )
423 {
424 QgsMessageLog::logMessage( QObject::tr( "Simplify transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
425 validTransform = false;
426 }
427 }
428
429 if ( validTransform )
430 {
431 QgsSimplifyMethod simplifyMethod;
433 simplifyMethod.setTolerance( map2pixelTol );
434 simplifyMethod.setThreshold( mSimplifyMethod.threshold() );
435 simplifyMethod.setForceLocalOptimization( mSimplifyMethod.forceLocalOptimization() );
436 featureRequest.setSimplifyMethod( simplifyMethod );
437
438 QgsVectorSimplifyMethod vectorMethod = mSimplifyMethod;
439 vectorMethod.setTolerance( map2pixelTol );
440 context.setVectorSimplifyMethod( vectorMethod );
441 }
442 else
443 {
444 QgsVectorSimplifyMethod vectorMethod;
446 context.setVectorSimplifyMethod( vectorMethod );
447 }
448 }
449 else
450 {
451 QgsVectorSimplifyMethod vectorMethod;
453 context.setVectorSimplifyMethod( vectorMethod );
454 }
455
456 featureRequest.setFeedback( mFeedback.get() );
457 // also set the interruption checker for the expression context, in case the renderer uses some complex expression
458 // which could benefit from early exit paths...
459 context.expressionContext().setFeedback( mFeedback.get() );
460
461 std::unique_ptr< QgsScopedRuntimeProfile > preparingFeatureItProfile;
462 if ( mEnableProfile )
463 {
464 preparingFeatureItProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Prepare feature iteration" ), QStringLiteral( "rendering" ) );
465 }
466
467 QgsFeatureIterator fit = mSource->getFeatures( featureRequest );
468 // Attach an interruption checker so that iterators that have potentially
469 // slow fetchFeature() implementations, such as in the WFS provider, can
470 // check it, instead of relying on just the mContext.renderingStopped() check
471 // in drawRenderer()
472
473 fit.setInterruptionChecker( mFeedback.get() );
474
475 preparingFeatureItProfile.reset();
476 preparingProfile.reset();
477
478 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
479 if ( mEnableProfile )
480 {
481 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering" ), QStringLiteral( "rendering" ) );
482 }
483
484 if ( ( renderer->capabilities() & QgsFeatureRenderer::SymbolLevels ) && renderer->usingSymbolLevels() )
485 drawRendererLevels( renderer, fit );
486 else
487 drawRenderer( renderer, fit );
488
489 if ( !fit.isValid() )
490 {
491 mErrors.append( QStringLiteral( "Data source invalid" ) );
492 }
493
494 if ( usingEffect )
495 {
496 renderer->paintEffect()->end( context );
497 }
498
499 context.expressionContext().setFeedback( nullptr );
500 return true;
501}
502
503
504void QgsVectorLayerRenderer::drawRenderer( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
505{
506 QElapsedTimer timer;
507 timer.start();
508 quint64 totalLabelTime = 0;
509
510 const bool isMainRenderer = renderer == mRenderer;
511
513 QgsRenderContext &context = *renderContext();
514 context.expressionContext().appendScope( symbolScope );
515
516 std::unique_ptr< QgsGeometryEngine > clipEngine;
517 if ( mApplyClipFilter )
518 {
519 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
520 clipEngine->prepareGeometry();
521 }
522
523 if ( mSelectionSymbol && isMainRenderer )
524 mSelectionSymbol->startRender( context, mFields );
525
526 QgsFeature fet;
527 while ( fit.nextFeature( fet ) )
528 {
529 try
530 {
531 if ( context.renderingStopped() )
532 {
533 QgsDebugMsgLevel( QStringLiteral( "Drawing of vector layer %1 canceled." ).arg( layerId() ), 2 );
534 break;
535 }
536
537 if ( !fet.hasGeometry() || fet.geometry().isEmpty() )
538 continue; // skip features without geometry
539
540 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
541 continue; // skip features outside of clipping region
542
543 if ( mApplyClipGeometries )
544 context.setFeatureClipGeometry( mClipFeatureGeom );
545
546 if ( ! mNoSetLayerExpressionContext )
547 context.expressionContext().setFeature( fet );
548
549 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fet.id() );
550 bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
551
552 // render feature
553 bool rendered = false;
555 {
556 if ( featureIsSelected && mSelectionSymbol )
557 {
558 // note: here we pass "false" for the selected argument, as we don't want to change
559 // the user's defined selection symbol colors or settings in any way
560 mSelectionSymbol->renderFeature( fet, context, -1, false, drawMarker );
561 rendered = renderer->willRenderFeature( fet, context );
562 }
563 else
564 {
565 rendered = renderer->renderFeature( fet, context, -1, featureIsSelected, drawMarker );
566 }
567 }
568 else
569 {
570 rendered = renderer->willRenderFeature( fet, context );
571 }
572
573 // labeling - register feature
574 if ( rendered )
575 {
576 // as soon as first feature is rendered, we can start showing layer updates.
577 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
578 // at most e.g. 3 seconds before we start forcing progressive updates.
579 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
580 {
581 mReadyToCompose = true;
582 }
583
584 // new labeling engine
585 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
586 {
587 const quint64 startLabelTime = timer.elapsed();
588 QgsGeometry obstacleGeometry;
589 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
590 QgsSymbol *symbol = nullptr;
591 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
592 {
593 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
594 }
595
596 if ( !symbols.isEmpty() )
597 {
598 symbol = symbols.at( 0 );
600 }
601
602 if ( mApplyLabelClipGeometries )
603 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
604
605 if ( mLabelProvider )
606 {
607 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
608 }
609 if ( mDiagramProvider )
610 {
611 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
612 }
613
614 if ( mApplyLabelClipGeometries )
616
617 totalLabelTime += ( timer.elapsed() - startLabelTime );
618 }
619 }
620 }
621 catch ( const QgsCsException &cse )
622 {
623 Q_UNUSED( cse )
624 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
625 .arg( fet.id() ).arg( cse.what() ) );
626 }
627 }
628
629 delete context.expressionContext().popScope();
630
631 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
632 if ( mEnableProfile )
633 {
634 QgsApplication::profiler()->record( QObject::tr( "Rendering features" ), ( timer.elapsed() - totalLabelTime ) / 1000.0, QStringLiteral( "rendering" ) );
635 if ( totalLabelTime > 0 )
636 {
637 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
638 }
639 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
640 }
641
642 if ( mSelectionSymbol && isMainRenderer )
643 mSelectionSymbol->stopRender( context );
644
645 stopRenderer( renderer, nullptr );
646}
647
648void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
649{
650 const bool isMainRenderer = renderer == mRenderer;
651
652 // We need to figure out in which order all the features should be rendered.
653 // Ordering is based on (a) a "level" which is determined by the configured
654 // feature rendering order" and (b) the symbol level. The "level" is
655 // determined by the values of the attributes defined in the feature
656 // rendering order settings. Each time the attribute(s) have a new distinct
657 // value, a new empty QHash is added to the "features" list. This QHash is
658 // then filled by mappings from the symbol to a list of all the features
659 // that should be rendered by that symbol.
660 //
661 // If orderBy is not enabled, this list will only ever contain a single
662 // element.
663 QList<QHash< QgsSymbol *, QList<QgsFeature> >> features;
664
665 // We have at least one "level" for the features.
666 features.push_back( {} );
667
668 QSet<int> orderByAttributeIdx;
669 if ( renderer->orderByEnabled() )
670 {
671 orderByAttributeIdx = renderer->orderBy().usedAttributeIndices( mSource->fields() );
672 }
673
674 QgsRenderContext &context = *renderContext();
675
676 QgsSingleSymbolRenderer *selRenderer = nullptr;
677 if ( !mSelectedFeatureIds.isEmpty() )
678 {
679 selRenderer = new QgsSingleSymbolRenderer( QgsSymbol::defaultSymbol( mGeometryType ) );
680 selRenderer->symbol()->setColor( context.selectionColor() );
681 selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
682 selRenderer->startRender( context, mFields );
683 }
684
686 std::unique_ptr< QgsExpressionContextScopePopper > scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
687
688
689 std::unique_ptr< QgsGeometryEngine > clipEngine;
690 if ( mApplyClipFilter )
691 {
692 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
693 clipEngine->prepareGeometry();
694 }
695
696 if ( mApplyLabelClipGeometries )
697 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
698
699 std::unique_ptr< QgsScopedRuntimeProfile > fetchFeaturesProfile;
700 if ( mEnableProfile )
701 {
702 fetchFeaturesProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Fetching features" ), QStringLiteral( "rendering" ) );
703 }
704
705 QElapsedTimer timer;
706 timer.start();
707 quint64 totalLabelTime = 0;
708
709 // 1. fetch features
710 QgsFeature fet;
711 QVector<QVariant> prevValues; // previous values of ORDER BY attributes
712 while ( fit.nextFeature( fet ) )
713 {
714 if ( context.renderingStopped() )
715 {
716 qDebug( "rendering stop!" );
717 stopRenderer( renderer, selRenderer );
718 return;
719 }
720
721 if ( !fet.hasGeometry() )
722 continue; // skip features without geometry
723
724 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
725 continue; // skip features outside of clipping region
726
727 if ( ! mNoSetLayerExpressionContext )
728 context.expressionContext().setFeature( fet );
729 QgsSymbol *sym = renderer->symbolForFeature( fet, context );
730 if ( !sym )
731 {
732 continue;
733 }
734
735 if ( renderer->orderByEnabled() )
736 {
737 QVector<QVariant> currentValues;
738 for ( const int idx : std::as_const( orderByAttributeIdx ) )
739 {
740 currentValues.push_back( fet.attribute( idx ) );
741 }
742 if ( prevValues.empty() )
743 {
744 prevValues = std::move( currentValues );
745 }
746 else if ( currentValues != prevValues )
747 {
748 // Current values of ORDER BY attributes are different than previous
749 // values of these attributes. Start a new level.
750 prevValues = std::move( currentValues );
751 features.push_back( {} );
752 }
753 }
754
756 {
757 QHash<QgsSymbol *, QList<QgsFeature> > &featuresBack = features.back();
758 auto featuresBackIt = featuresBack.find( sym );
759 if ( featuresBackIt == featuresBack.end() )
760 {
761 featuresBackIt = featuresBack.insert( sym, QList<QgsFeature>() );
762 }
763 featuresBackIt->append( fet );
764 }
765
766 // new labeling engine
767 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
768 {
769 const quint64 startLabelTime = timer.elapsed();
770
771 QgsGeometry obstacleGeometry;
772 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
773 QgsSymbol *symbol = nullptr;
774 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
775 {
776 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
777 }
778
779 if ( !symbols.isEmpty() )
780 {
781 symbol = symbols.at( 0 );
783 }
784
785 if ( mLabelProvider )
786 {
787 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
788 }
789 if ( mDiagramProvider )
790 {
791 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
792 }
793
794 totalLabelTime += ( timer.elapsed() - startLabelTime );
795 }
796 }
797
798 fetchFeaturesProfile.reset();
799 if ( mEnableProfile )
800 {
801 if ( totalLabelTime > 0 )
802 {
803 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
804 }
805 }
806
807 if ( mApplyLabelClipGeometries )
809
810 scopePopper.reset();
811
812 if ( features.back().empty() )
813 {
814 // nothing to draw
815 stopRenderer( renderer, selRenderer );
816 return;
817 }
818
819
820 std::unique_ptr< QgsScopedRuntimeProfile > sortingProfile;
821 if ( mEnableProfile )
822 {
823 sortingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Sorting features" ), QStringLiteral( "rendering" ) );
824 }
825 // find out the order
826 QgsSymbolLevelOrder levels;
827 QgsSymbolList symbols = renderer->symbols( context );
828 for ( int i = 0; i < symbols.count(); i++ )
829 {
830 QgsSymbol *sym = symbols[i];
831 for ( int j = 0; j < sym->symbolLayerCount(); j++ )
832 {
833 int level = sym->symbolLayer( j )->renderingPass();
834 if ( level < 0 || level >= 1000 ) // ignore invalid levels
835 continue;
836 QgsSymbolLevelItem item( sym, j );
837 while ( level >= levels.count() ) // append new empty levels
838 levels.append( QgsSymbolLevel() );
839 levels[level].append( item );
840 }
841 }
842 sortingProfile.reset();
843
844 if ( mApplyClipGeometries )
845 context.setFeatureClipGeometry( mClipFeatureGeom );
846
847 // 2. draw features in correct order
848 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
849 {
850 for ( int l = 0; l < levels.count(); l++ )
851 {
852 const QgsSymbolLevel &level = levels[l];
853 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
854 if ( mEnableProfile )
855 {
856 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering symbol level %1" ).arg( l + 1 ), QStringLiteral( "rendering" ) );
857 }
858
859 for ( int i = 0; i < level.count(); i++ )
860 {
861 const QgsSymbolLevelItem &item = level[i];
862 if ( !featureLists.contains( item.symbol() ) )
863 {
864 QgsDebugError( QStringLiteral( "level item's symbol not found!" ) );
865 continue;
866 }
867 const int layer = item.layer();
868 const QList<QgsFeature> &lst = featureLists[item.symbol()];
869 for ( const QgsFeature &feature : lst )
870 {
871 if ( context.renderingStopped() )
872 {
873 stopRenderer( renderer, selRenderer );
874 return;
875 }
876
877 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( feature.id() );
878 if ( featureIsSelected && mSelectionSymbol )
879 continue; // defer rendering of selected symbols
880
881 // maybe vertex markers should be drawn only during the last pass...
882 const bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
883
884 if ( ! mNoSetLayerExpressionContext )
885 context.expressionContext().setFeature( feature );
886
887 try
888 {
889 renderer->renderFeature( feature, context, layer, featureIsSelected, drawMarker );
890
891 // as soon as first feature is rendered, we can start showing layer updates.
892 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
893 // at most e.g. 3 seconds before we start forcing progressive updates.
894 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
895 {
896 mReadyToCompose = true;
897 }
898 }
899 catch ( const QgsCsException &cse )
900 {
901 Q_UNUSED( cse )
902 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
903 .arg( fet.id() ).arg( cse.what() ) );
904 }
905 }
906 }
907 }
908 }
909
910 if ( mSelectionSymbol && !mSelectedFeatureIds.empty() && isMainRenderer && context.showSelection() )
911 {
912 mSelectionSymbol->startRender( context, mFields );
913
914 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
915 {
916 for ( auto it = featureLists.constBegin(); it != featureLists.constEnd(); ++it )
917 {
918 const QList<QgsFeature> &lst = it.value();
919 for ( const QgsFeature &feature : lst )
920 {
921 if ( context.renderingStopped() )
922 {
923 break;
924 }
925
926 const bool featureIsSelected = mSelectedFeatureIds.contains( feature.id() );
927 if ( !featureIsSelected )
928 continue;
929
930 const bool drawMarker = mDrawVertexMarkers && context.drawEditingInformation();
931 // note: here we pass "false" for the selected argument, as we don't want to change
932 // the user's defined selection symbol colors or settings in any way
933 mSelectionSymbol->renderFeature( feature, context, -1, false, drawMarker );
934 }
935 }
936 }
937
938 mSelectionSymbol->stopRender( context );
939 }
940
941 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
942 if ( mEnableProfile )
943 {
944 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
945 }
946
947 stopRenderer( renderer, selRenderer );
948}
949
950void QgsVectorLayerRenderer::stopRenderer( QgsFeatureRenderer *renderer, QgsSingleSymbolRenderer *selRenderer )
951{
952 QgsRenderContext &context = *renderContext();
953 renderer->stopRender( context );
954 if ( selRenderer )
955 {
956 selRenderer->stopRender( context );
957 delete selRenderer;
958 }
959}
960
961void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer *layer, QSet<QString> &attributeNames )
962{
963 QgsRenderContext &context = *renderContext();
964 // TODO: add attributes for geometry generator
965 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
966 {
967 if ( layer->labelsEnabled() )
968 {
969 if ( context.labelSink() )
970 {
971 if ( const QgsRuleBasedLabeling *rbl = dynamic_cast<const QgsRuleBasedLabeling *>( layer->labeling() ) )
972 {
973 mLabelProvider = new QgsRuleBasedLabelSinkProvider( *rbl, layer, context.labelSink() );
974 }
975 else
976 {
977 QgsPalLayerSettings settings = layer->labeling()->settings();
978 mLabelProvider = new QgsLabelSinkProvider( layer, QString(), context.labelSink(), &settings );
979 }
980 }
981 else
982 {
983 mLabelProvider = layer->labeling()->provider( layer );
984 }
985 if ( mLabelProvider )
986 {
987 engine2->addProvider( mLabelProvider );
988 if ( !mLabelProvider->prepare( context, attributeNames ) )
989 {
990 engine2->removeProvider( mLabelProvider );
991 mLabelProvider = nullptr; // deleted by engine
992 }
993 }
994 }
995 }
996
997#if 0 // TODO: limit of labels, font not found
998 QgsPalLayerSettings &palyr = mContext.labelingEngine()->layer( mLayerID );
999
1000 // see if feature count limit is set for labeling
1001 if ( palyr.limitNumLabels && palyr.maxNumLabels > 0 )
1002 {
1003 QgsFeatureIterator fit = getFeatures( QgsFeatureRequest()
1004 .setFilterRect( mContext.extent() )
1005 .setNoAttributes() );
1006
1007 // total number of features that may be labeled
1008 QgsFeature f;
1009 int nFeatsToLabel = 0;
1010 while ( fit.nextFeature( f ) )
1011 {
1012 nFeatsToLabel++;
1013 }
1014 palyr.mFeaturesToLabel = nFeatsToLabel;
1015 }
1016
1017 // notify user about any font substitution
1018 if ( !palyr.mTextFontFound && !mLabelFontNotFoundNotified )
1019 {
1020 emit labelingFontNotFound( this, palyr.mTextFontFamily );
1021 mLabelFontNotFoundNotified = true;
1022 }
1023#endif
1024}
1025
1026void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer *layer, QSet<QString> &attributeNames )
1027{
1028 QgsRenderContext &context = *renderContext();
1029 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
1030 {
1031 if ( layer->diagramsEnabled() )
1032 {
1033 mDiagramProvider = new QgsVectorLayerDiagramProvider( layer );
1034 // need to be added before calling prepare() - uses map settings from engine
1035 engine2->addProvider( mDiagramProvider );
1036 if ( !mDiagramProvider->prepare( context, attributeNames ) )
1037 {
1038 engine2->removeProvider( mDiagramProvider );
1039 mDiagramProvider = nullptr; // deleted by engine
1040 }
1041 }
1042 }
1043}
1044
The Qgis class provides global constants for use throughout the application.
Definition: qgis.h:54
@ Degrees
Degrees, for planar geographic CRS distance measurements.
@ EmbeddedSymbols
Retrieve any embedded feature symbology (since QGIS 3.20)
@ Unknown
Unknown types.
@ Null
No geometry.
@ Vector
Vector layer.
@ SkipSymbolRendering
Disable symbol rendering while still drawing labels if enabled (since QGIS 3.24)
@ UseAdvancedEffects
Enable layer opacity and blending effects.
@ SemiTransparentCircle
Semi-transparent circle marker.
@ Cross
Cross marker.
@ CustomColor
Use default symbol with a custom selection color.
@ CustomSymbol
Use a custom symbol.
@ Default
Use default symbol and selection colors.
virtual QgsPalLayerSettings settings(const QString &providerId=QString()) const =0
Gets associated label settings.
virtual QgsVectorLayerLabelProvider * provider(QgsVectorLayer *layer) const
Factory for label provider implementation.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
Q_GADGET Qgis::DistanceUnit mapUnits
Class for doing transforms between two map coordinate systems.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source coordinate reference system, which the transform will transform coordinates from.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
bool isShortCircuited() const
Returns true if the transform short circuits because the source and destination are equivalent.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:67
QString what() const
Definition: qgsexception.h:49
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the expression engine to check if expressio...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Abstract interface for use by classes that filter the features or attributes of a layer.
virtual void filterFeatures(const QgsVectorLayer *layer, QgsFeatureRequest &featureRequest) const =0
Add additional filters to the feature request to further restrict the features returned by the reques...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
void setInterruptionChecker(QgsFeedback *interruptionChecker)
Attach an object that can be queried regularly by the iterator to check if it must stopped.
bool isValid() const
Will return if this iterator is valid.
An interface for objects which generate feature renderers for vector layers.
virtual bool canSkipRender()
Returns true if the renderer can be entirely skipped, i.e.
virtual void modifyRequestExtent(QgsRectangle &extent, QgsRenderContext &context)
Allows for a renderer to modify the extent of a feature request prior to rendering.
virtual QString filter(const QgsFields &fields=QgsFields())
If a renderer does not require all the features this method may be overridden and return an expressio...
Definition: qgsrenderer.h:213
QgsPaintEffect * paintEffect() const
Returns the current paint effect for the renderer.
virtual QgsSymbolList symbols(QgsRenderContext &context) const
Returns list of symbols used by the renderer.
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
QString type() const
Definition: qgsrenderer.h:142
virtual bool usesEmbeddedSymbols() const
Returns true if the renderer uses embedded symbols for features.
virtual bool renderFeature(const QgsFeature &feature, QgsRenderContext &context, int layer=-1, bool selected=false, bool drawVertexMarker=false)
Render a feature using this renderer in the given context.
double referenceScale() const
Returns the symbology reference scale.
Definition: qgsrenderer.h:483
bool usingSymbolLevels() const
Definition: qgsrenderer.h:298
virtual QString dump() const
Returns debug information about this renderer.
virtual QgsFeatureRenderer::Capabilities capabilities()
Returns details about internals of this renderer.
Definition: qgsrenderer.h:290
virtual QgsSymbol * symbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const =0
To be overridden.
@ SymbolLevels
Rendering with symbol levels (i.e. implements symbols(), symbolForFeature())
Definition: qgsrenderer.h:270
bool orderByEnabled() const
Returns whether custom ordering will be applied before features are processed by this renderer.
virtual bool willRenderFeature(const QgsFeature &feature, QgsRenderContext &context) const
Returns whether the renderer will render a feature or not.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
Definition: qgsrenderer.cpp:90
void setVertexMarkerAppearance(Qgis::VertexMarkerType type, double size)
Sets type and size of editing vertex markers for subsequent rendering.
QgsFeatureRequest::OrderBy orderBy() const
Gets the order in which features shall be processed by this renderer.
virtual QgsSymbolList originalSymbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
QSet< int > CORE_EXPORT usedAttributeIndices(const QgsFields &fields) const
Returns a set of used, validated attribute indices.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSimplifyMethod(const QgsSimplifyMethod &simplifyMethod)
Set a simplification method for geometries that will be fetched.
QgsFeatureRequest & combineFilterExpression(const QString &expression)
Modifies the existing filter expression to add an additional expression filter.
Qgis::FeatureRequestFlags flags() const
Returns the flags which affect how features are fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the iterator to check if it should be cance...
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setOrderBy(const OrderBy &orderBy)
Set a list of order by clauses.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:230
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Definition: qgsfeature.cpp:335
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition: qgsfeedback.h:44
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:162
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::GeometryType type
Definition: qgsgeometry.h:165
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Implements a derived label provider for use with QgsLabelSink.
Definition: qgslabelsink.h:75
The QgsLabelingEngine class provides map labeling functionality.
static QPainterPath calculatePainterClipRegion(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, Qgis::LayerType layerType, bool &shouldClip)
Returns a QPainterPath representing the intersection of clipping regions from context which should be...
static QList< QgsMapClippingRegion > collectClippingRegionsForLayer(const QgsRenderContext &context, const QgsMapLayer *layer)
Collects the list of map clipping regions from a context which apply to a map layer.
static QgsGeometry calculateLabelIntersectionGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldClip)
Returns the geometry representing the intersection of clipping regions from context which should be u...
static QgsGeometry calculateFeatureIntersectionGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldClip)
Returns the geometry representing the intersection of clipping regions from context which should be u...
static QgsGeometry calculateFeatureRequestGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldFilter)
Returns the geometry representing the intersection of clipping regions from context.
Base class for utility classes that encapsulate information necessary for rendering of map layers.
bool mReadyToCompose
The flag must be set to false in renderer's constructor if wants to use the smarter map redraws funct...
static constexpr int MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE
Maximum time (in ms) to allow display of a previously cached preview image while rendering layers,...
QString layerId() const
Gets access to the ID of the layer rendered by this class.
QgsRenderContext * renderContext()
Returns the render context associated with the renderer.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
double opacity
Definition: qgsmaplayer.h:84
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:39
double mapUnitsPerPixel() const
Returns the current map units per pixel.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
virtual void begin(QgsRenderContext &context)
Begins intercepting paint operations to a render context.
virtual void end(QgsRenderContext &context)
Ends interception of paint operations to a render context, and draws the result to the render context...
bool enabled() const
Returns whether the effect is enabled.
Contains settings for how a map layer will be labeled.
A class to represent a 2D point.
Definition: qgspointxy.h:60
double y
Definition: qgspointxy.h:64
Q_GADGET double x
Definition: qgspointxy.h:63
A rectangle specified with double values.
Definition: qgsrectangle.h:42
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:201
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:211
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:196
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:206
QgsPointXY center() const
Returns the center point of the rectangle.
Definition: qgsrectangle.h:262
bool isEmpty() const
Returns true if the rectangle has no area.
Definition: qgsrectangle.h:492
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
Definition: qgsrectangle.h:355
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Definition: qgsrectangle.h:588
Contains information about the context of a rendering operation.
bool useAdvancedEffects() const
Returns true if advanced effects such as blend modes such be used.
bool hasRenderedFeatureHandlers() const
Returns true if the context has any rendered feature handlers.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setVectorSimplifyMethod(const QgsVectorSimplifyMethod &simplifyMethod)
Sets the simplification setting to use when rendering vector layers.
QgsLabelSink * labelSink() const
Returns the associated label sink, or nullptr if not set.
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
bool testFlag(Qgis::RenderContextFlag flag) const
Check whether a particular flag is enabled.
void setFeatureClipGeometry(const QgsGeometry &geometry)
Sets a geometry to use to clip features at render time.
const QgsFeatureFilterProvider * featureFilterProvider() const
Gets the filter feature provider used for additional filtering of rendered features.
QList< QgsRenderedFeatureHandlerInterface * > renderedFeatureHandlers() const
Returns the list of rendered feature handlers to use while rendering map layers.
void setSymbologyReferenceScale(double scale)
Sets the symbology reference scale.
bool showSelection() const
Returns true if vector selections should be shown in the rendered map.
const QgsVectorSimplifyMethod & vectorSimplifyMethod() const
Returns the simplification settings to use when rendering vector layers.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QColor selectionColor() const
Returns the color to use when rendering selected features.
bool drawEditingInformation() const
Returns true if edit markers should be drawn during the render operation.
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
QgsLabelingEngine * labelingEngine() const
Gets access to new labeling engine (may be nullptr).
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
void setSelectionColor(const QColor &color)
Sets the color to use when rendering selected features.
An interface for classes which provider custom handlers for features rendered as part of a map render...
Implements a derived label provider for rule based labels for use with QgsLabelSink.
Definition: qgslabelsink.h:95
Rule based labeling for a vector layer.
void record(const QString &name, double time, const QString &group="startup", const QString &id=QString())
Manually adds a profile event with the given name and total time (in seconds).
Scoped object for saving and restoring a QPainter object's state.
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
static const QgsSettingsEntryDouble * settingsDigitizingMarkerSizeMm
Settings entry digitizing marker size mm.
static const QgsSettingsEntryBool * settingsDigitizingMarkerOnlyForSelected
Settings entry digitizing marker only for selected.
static const QgsSettingsEntryString * settingsDigitizingMarkerStyle
Settings entry digitizing marker style.
This class contains information about how to simplify geometries fetched from a QgsFeatureIterator.
void setTolerance(double tolerance)
Sets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
void setThreshold(float threshold)
Sets the simplification threshold in pixels. Represents the maximum distance in pixels between two co...
void setForceLocalOptimization(bool localOptimization)
Sets whether the simplification executes after fetch the geometries from provider,...
void setMethodType(MethodType methodType)
Sets the simplification type.
@ OptimizeForRendering
Simplify using the map2pixel data to optimize the rendering of geometries.
QgsSymbol * symbol() const
Returns the symbol which will be rendered for every feature.
void stopRender(QgsRenderContext &context) override
Must be called when a render cycle has finished, to allow the renderer to clean up.
void startRender(QgsRenderContext &context, const QgsFields &fields) override
Must be called when a new render cycle is started.
int renderingPass() const
Specifies the rendering pass in which this symbol layer should be rendered.
int layer() const
The layer of this symbol level.
QgsSymbol * symbol() const
The symbol of this symbol level.
Abstract base class for all rendered symbols.
Definition: qgssymbol.h:94
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
Definition: qgssymbol.cpp:760
void setColor(const QColor &color) const
Sets the color for the symbol.
Definition: qgssymbol.cpp:902
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Definition: qgssymbol.h:215
static QgsSymbol * defaultSymbol(Qgis::GeometryType geomType)
Returns a new default symbol for the specified geometry type.
Definition: qgssymbol.cpp:705
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
bool isTemporal() const
Returns true if the object's temporal range is enabled, and the object will be filtered when renderin...
The QgsVectorLayerDiagramProvider class implements support for diagrams within the labeling engine.
virtual bool prepare(const QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
virtual void registerFeature(QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry())
Register a feature for labeling as one or more QgsLabelFeature objects stored into mFeatures.
void setClipFeatureGeometry(const QgsGeometry &geometry)
Sets a geometry to use to clip features to when registering them as diagrams.
Partial snapshot of vector layer's state (only the members necessary for access to features)
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
static QgsGeometry getPointObstacleGeometry(QgsFeature &fet, QgsRenderContext &context, const QgsSymbolList &symbols)
Returns the geometry for a point feature which should be used as an obstacle for labels.
virtual QList< QgsLabelFeature * > registerFeature(const QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling as one or more QgsLabelFeature objects stored into mLabels.
bool forceRasterRender() const override
Returns true if the renderer must be rendered to a raster paint device (e.g.
QgsVectorLayerRenderer(QgsVectorLayer *layer, QgsRenderContext &context)
~QgsVectorLayerRenderer() override
void setLayerRenderingTimeHint(int time) override
Sets approximate render time (in ms) for the layer to render.
bool render() override
Do the rendering (based on data stored in the class).
QgsFeedback * feedback() const override
Access to feedback object of the layer renderer (may be nullptr)
Implementation of layer selection properties for vector layers.
Qgis::SelectionRenderingMode selectionRenderingMode() const
Returns the selection rendering mode to use for selected features in the layer.
QColor selectionColor() const
Returns the color to use for rendering selected features in the layer.
Encapsulates the context in which a QgsVectorLayer's temporal capabilities will be applied.
void setLayer(QgsVectorLayer *layer)
Sets the associated layer.
Represents a vector layer which manages a vector based data sets.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
QgsMapLayerTemporalProperties * temporalProperties() override
Returns the layer's temporal properties.
QPainter::CompositionMode featureBlendMode() const
Returns the current blending mode for features.
bool diagramsEnabled() const
Returns whether the layer contains diagrams which are enabled and should be drawn.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
QgsFeatureRenderer * renderer()
Returns the feature renderer used for rendering the features in the layer in 2D map views.
Q_INVOKABLE QgsVectorLayerEditBuffer * editBuffer()
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
const QgsVectorSimplifyMethod & simplifyMethod() const
Returns the simplification settings for fast rendering of features.
bool simplifyDrawingCanbeApplied(const QgsRenderContext &renderContext, QgsVectorSimplifyMethod::SimplifyHint simplifyHint) const
Returns whether the VectorLayer can apply the specified simplification hint.
QList< const QgsFeatureRendererGenerator * > featureRendererGenerators() const
Returns a list of the feature renderer generators owned by the layer.
QgsMapLayerSelectionProperties * selectionProperties() override
Returns the layer's selection properties.
This class contains information how to simplify geometries fetched from a vector layer.
bool forceLocalOptimization() const
Gets where the simplification executes, after fetch the geometries from provider, or when supported,...
void setSimplifyHints(SimplifyHints simplifyHints)
Sets the simplification hints of the vector layer managed.
SimplifyHints simplifyHints() const
Gets the simplification hints of the vector layer managed.
void setTolerance(double tolerance)
Sets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
float threshold() const
Gets the simplification threshold of the vector layer managed.
@ GeometrySimplification
The geometries can be simplified using the current map2pixel context state.
@ FullSimplification
All simplification hints can be applied ( Geometry + AA-disabling )
@ NoSimplification
No simplification can be applied.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:5207
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
#define QgsDebugError(str)
Definition: qgslogger.h:38
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition: qgsrenderer.h:88
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition: qgsrenderer.h:84
QList< QgsSymbol * > QgsSymbolList
Definition: qgsrenderer.h:44