QGIS API Documentation 3.99.0-Master (a26b91b364d)
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
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
175 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
176 {
177 mAttrNames.unite( renderer->usedAttributes( context ) );
178 }
179 if ( context.hasRenderedFeatureHandlers() )
180 {
181 const QList< QgsRenderedFeatureHandlerInterface * > handlers = context.renderedFeatureHandlers();
182 for ( QgsRenderedFeatureHandlerInterface *handler : handlers )
183 mAttrNames.unite( handler->usedAttributes( layer, context ) );
184 }
185
186 //register label and diagram layer to the labeling engine
187 prepareLabeling( layer, mAttrNames );
188 prepareDiagrams( layer, mAttrNames );
189
190 mClippingRegions = QgsMapClippingUtils::collectClippingRegionsForLayer( context, layer );
191
192 if ( std::any_of( mRenderers.begin(), mRenderers.end(), []( const auto & renderer ) { return renderer->forceRasterRender(); } ) )
193 {
194 //raster rendering is forced for this layer
195 mForceRasterRender = true;
196 }
197
198 const bool allowFlattening = context.rasterizedRenderingPolicy() != Qgis::RasterizedRenderingPolicy::ForceVector;
199 if ( allowFlattening &&
200 ( ( layer->blendMode() != QPainter::CompositionMode_SourceOver )
201 || ( layer->featureBlendMode() != QPainter::CompositionMode_SourceOver )
202 || ( !qgsDoubleNear( layer->opacity(), 1.0 ) ) ) )
203 {
204 //layer properties require rasterization
205 mForceRasterRender = true;
206 }
207
208 mReadyToCompose = false;
209 mPreparationTime = timer.elapsed();
210}
211
213
215{
216 mRenderTimeHint = time;
217}
218
220{
221 return mFeedback.get();
222}
223
225{
226 return mForceRasterRender;
227}
228
230{
232 if ( mRenderer && mRenderer->flags().testFlag( Qgis::FeatureRendererFlag::AffectsLabeling ) )
234 return res;
235}
236
238{
239 if ( mGeometryType == Qgis::GeometryType::Null || mGeometryType == Qgis::GeometryType::Unknown )
240 {
241 mReadyToCompose = true;
242 return true;
243 }
244
245 if ( mRenderers.empty() )
246 {
247 mReadyToCompose = true;
248 mErrors.append( QObject::tr( "No renderer for drawing." ) );
249 return false;
250 }
251
252 std::unique_ptr< QgsScopedRuntimeProfile > profile;
253 if ( mEnableProfile )
254 {
255 profile = std::make_unique< QgsScopedRuntimeProfile >( mLayerName, QStringLiteral( "rendering" ), layerId() );
256 if ( mPreparationTime > 0 )
257 QgsApplication::profiler()->record( QObject::tr( "Create renderer" ), mPreparationTime / 1000.0, QStringLiteral( "rendering" ) );
258 }
259
260 // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
261 // cached version of the layer during rendering instead of the usual progressive updates
262 if ( mRenderTimeHint > 0 && mRenderTimeHint <= MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
263 {
264 mBlockRenderUpdates = true;
265 mElapsedTimer.start();
266 }
267
268 bool res = true;
269 int rendererIndex = 0;
270 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
271 {
272 if ( mFeedback->isCanceled() || !res )
273 {
274 break;
275 }
276 res = renderInternal( renderer.get(), rendererIndex++ ) && res;
277 }
278
279 mReadyToCompose = true;
280 return res && !renderContext()->renderingStopped();
281}
282
283bool QgsVectorLayerRenderer::renderInternal( QgsFeatureRenderer *renderer, int rendererIndex )
284{
285 const bool isMainRenderer = renderer == mRenderer;
286
287 QgsRenderContext &context = *renderContext();
288 context.setSymbologyReferenceScale( renderer->referenceScale() );
289
290 if ( renderer->type() == QLatin1String( "nullSymbol" ) )
291 {
292 // a little shortcut for the null symbol renderer - most of the time it is not going to render anything
293 // so we can even skip the whole loop to fetch features
294 if ( !isMainRenderer ||
295 ( !mDrawVertexMarkers && !mLabelProvider && !mDiagramProvider && mSelectedFeatureIds.isEmpty() ) )
296 return true;
297 }
298
299 std::unique_ptr< QgsScopedRuntimeProfile > preparingProfile;
300 if ( mEnableProfile )
301 {
302 QString title;
303 if ( mRenderers.size() > 1 )
304 title = QObject::tr( "Preparing render %1" ).arg( rendererIndex + 1 );
305 else
306 title = QObject::tr( "Preparing render" );
307 preparingProfile = std::make_unique< QgsScopedRuntimeProfile >( title, QStringLiteral( "rendering" ) );
308 }
309
310 QgsScopedQPainterState painterState( context.painter() );
311
312 bool usingEffect = false;
313 if ( renderer->paintEffect() && renderer->paintEffect()->enabled() )
314 {
315 usingEffect = true;
316 renderer->paintEffect()->begin( context );
317 }
318
319 // Per feature blending mode
321 && mFeatureBlendMode != QPainter::CompositionMode_SourceOver )
322 {
323 // set the painter to the feature blend mode, so that features drawn
324 // on this layer will interact and blend with each other
325 context.painter()->setCompositionMode( mFeatureBlendMode );
326 }
327
328 renderer->startRender( context, mFields );
329
330 if ( renderer->canSkipRender() )
331 {
332 // nothing to draw for now...
333 renderer->stopRender( context );
334 return true;
335 }
336
337 QString rendererFilter = renderer->filter( mFields );
338
339 QgsRectangle requestExtent = context.extent();
340 if ( !mClippingRegions.empty() )
341 {
342 mClipFilterGeom = QgsMapClippingUtils::calculateFeatureRequestGeometry( mClippingRegions, context, mApplyClipFilter );
343 requestExtent = requestExtent.intersect( mClipFilterGeom.boundingBox() );
344
345 mClipFeatureGeom = QgsMapClippingUtils::calculateFeatureIntersectionGeometry( mClippingRegions, context, mApplyClipGeometries );
346
347 bool needsPainterClipPath = false;
348 const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, context, Qgis::LayerType::Vector, needsPainterClipPath );
349 if ( needsPainterClipPath )
350 context.painter()->setClipPath( path, Qt::IntersectClip );
351
352 mLabelClipFeatureGeom = QgsMapClippingUtils::calculateLabelIntersectionGeometry( mClippingRegions, context, mApplyLabelClipGeometries );
353
354 if ( mDiagramProvider )
355 mDiagramProvider->setClipFeatureGeometry( mLabelClipFeatureGeom );
356 }
357
358 renderer->modifyRequestExtent( requestExtent, context );
359
360 QgsFeatureRequest featureRequest = QgsFeatureRequest()
361 .setFilterRect( requestExtent )
362 .setSubsetOfAttributes( mAttrNames, mFields )
364 if ( renderer->orderByEnabled() )
365 {
366 featureRequest.setOrderBy( renderer->orderBy() );
367 }
368
369 const QgsFeatureFilterProvider *featureFilterProvider = context.featureFilterProvider();
370 if ( featureFilterProvider )
371 {
373 if ( featureFilterProvider->isFilterThreadSafe() )
374 {
375 featureFilterProvider->filterFeatures( layerId(), featureRequest );
376 }
377 else
378 {
379 featureFilterProvider->filterFeatures( mLayer, featureRequest );
380 }
382 }
383 if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) )
384 {
385 featureRequest.combineFilterExpression( rendererFilter );
386 }
387 if ( !mTemporalFilter.isEmpty() )
388 {
389 featureRequest.combineFilterExpression( mTemporalFilter );
390 }
391
392 if ( renderer->usesEmbeddedSymbols() )
393 {
394 featureRequest.setFlags( featureRequest.flags() | Qgis::FeatureRequestFlag::EmbeddedSymbols );
395 }
396
397 // enable the simplification of the geometries (Using the current map2pixel context) before send it to renderer engine.
398 if ( mSimplifyGeometry )
399 {
400 double map2pixelTol = mSimplifyMethod.threshold();
401 bool validTransform = true;
402
403 const QgsMapToPixel &mtp = context.mapToPixel();
404 map2pixelTol *= mtp.mapUnitsPerPixel();
405 const QgsCoordinateTransform ct = context.coordinateTransform();
406
407 // resize the tolerance using the change of size of an 1-BBOX from the source CoordinateSystem to the target CoordinateSystem
408 if ( ct.isValid() && !ct.isShortCircuited() )
409 {
410 try
411 {
412 QgsCoordinateTransform toleranceTransform = ct;
413 QgsPointXY center = context.extent().center();
414 double rectSize = toleranceTransform.sourceCrs().mapUnits() == Qgis::DistanceUnit::Degrees ? 0.0008983 /* ~100/(40075014/360=111319.4833) */ : 100;
415
416 QgsRectangle sourceRect = QgsRectangle( center.x(), center.y(), center.x() + rectSize, center.y() + rectSize );
417 toleranceTransform.setBallparkTransformsAreAppropriate( true );
418 QgsRectangle targetRect = toleranceTransform.transform( sourceRect );
419
420 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceTransformRect=%1" ).arg( sourceRect.toString( 16 ) ), 4 );
421 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetTransformRect=%1" ).arg( targetRect.toString( 16 ) ), 4 );
422
423 if ( !sourceRect.isEmpty() && sourceRect.isFinite() && !targetRect.isEmpty() && targetRect.isFinite() )
424 {
425 QgsPointXY minimumSrcPoint( sourceRect.xMinimum(), sourceRect.yMinimum() );
426 QgsPointXY maximumSrcPoint( sourceRect.xMaximum(), sourceRect.yMaximum() );
427 QgsPointXY minimumDstPoint( targetRect.xMinimum(), targetRect.yMinimum() );
428 QgsPointXY maximumDstPoint( targetRect.xMaximum(), targetRect.yMaximum() );
429
430 double sourceHypothenuse = std::sqrt( minimumSrcPoint.sqrDist( maximumSrcPoint ) );
431 double targetHypothenuse = std::sqrt( minimumDstPoint.sqrDist( maximumDstPoint ) );
432
433 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceHypothenuse=%1" ).arg( sourceHypothenuse ), 4 );
434 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetHypothenuse=%1" ).arg( targetHypothenuse ), 4 );
435
436 if ( !qgsDoubleNear( targetHypothenuse, 0.0 ) )
437 map2pixelTol *= ( sourceHypothenuse / targetHypothenuse );
438 }
439 }
440 catch ( QgsCsException &cse )
441 {
442 QgsMessageLog::logMessage( QObject::tr( "Simplify transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
443 validTransform = false;
444 }
445 }
446
447 if ( validTransform )
448 {
449 QgsSimplifyMethod simplifyMethod;
451 simplifyMethod.setTolerance( map2pixelTol );
452 simplifyMethod.setThreshold( mSimplifyMethod.threshold() );
453 simplifyMethod.setForceLocalOptimization( mSimplifyMethod.forceLocalOptimization() );
454 featureRequest.setSimplifyMethod( simplifyMethod );
455
456 QgsVectorSimplifyMethod vectorMethod = mSimplifyMethod;
457 vectorMethod.setTolerance( map2pixelTol );
458 context.setVectorSimplifyMethod( vectorMethod );
459 }
460 else
461 {
462 QgsVectorSimplifyMethod vectorMethod;
464 context.setVectorSimplifyMethod( vectorMethod );
465 }
466 }
467 else
468 {
469 QgsVectorSimplifyMethod vectorMethod;
471 context.setVectorSimplifyMethod( vectorMethod );
472 }
473
474 featureRequest.setFeedback( mFeedback.get() );
475 // also set the interruption checker for the expression context, in case the renderer uses some complex expression
476 // which could benefit from early exit paths...
477 context.expressionContext().setFeedback( mFeedback.get() );
478
479 std::unique_ptr< QgsScopedRuntimeProfile > preparingFeatureItProfile;
480 if ( mEnableProfile )
481 {
482 preparingFeatureItProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Prepare feature iteration" ), QStringLiteral( "rendering" ) );
483 }
484
485 QgsFeatureIterator fit = mSource->getFeatures( featureRequest );
486 // Attach an interruption checker so that iterators that have potentially
487 // slow fetchFeature() implementations, such as in the WFS provider, can
488 // check it, instead of relying on just the mContext.renderingStopped() check
489 // in drawRenderer()
490
491 fit.setInterruptionChecker( mFeedback.get() );
492
493 preparingFeatureItProfile.reset();
494 preparingProfile.reset();
495
496 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
497 if ( mEnableProfile )
498 {
499 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering" ), QStringLiteral( "rendering" ) );
500 }
501
502 if ( ( renderer->capabilities() & QgsFeatureRenderer::SymbolLevels ) && renderer->usingSymbolLevels() )
503 drawRendererLevels( renderer, fit );
504 else
505 drawRenderer( renderer, fit );
506
507 if ( !fit.isValid() )
508 {
509 mErrors.append( QStringLiteral( "Data source invalid" ) );
510 }
511
512 if ( usingEffect )
513 {
514 renderer->paintEffect()->end( context );
515 }
516
517 context.expressionContext().setFeedback( nullptr );
518 return true;
519}
520
521
522void QgsVectorLayerRenderer::drawRenderer( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
523{
524 QElapsedTimer timer;
525 timer.start();
526 quint64 totalLabelTime = 0;
527
528 const bool isMainRenderer = renderer == mRenderer;
529
531 QgsRenderContext &context = *renderContext();
532 context.expressionContext().appendScope( symbolScope );
533
534 std::unique_ptr< QgsGeometryEngine > clipEngine;
535 if ( mApplyClipFilter )
536 {
537 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
538 clipEngine->prepareGeometry();
539 }
540
541 if ( mSelectionSymbol && isMainRenderer )
542 mSelectionSymbol->startRender( context, mFields );
543
544 QgsFeature fet;
545 while ( fit.nextFeature( fet ) )
546 {
547 try
548 {
549 if ( context.renderingStopped() )
550 {
551 QgsDebugMsgLevel( QStringLiteral( "Drawing of vector layer %1 canceled." ).arg( layerId() ), 2 );
552 break;
553 }
554
555 if ( !fet.hasGeometry() || fet.geometry().isEmpty() )
556 continue; // skip features without geometry
557
558 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
559 continue; // skip features outside of clipping region
560
561 if ( mApplyClipGeometries )
562 context.setFeatureClipGeometry( mClipFeatureGeom );
563
564 if ( ! mNoSetLayerExpressionContext )
565 context.expressionContext().setFeature( fet );
566
567 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fet.id() );
568 bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
569
570 // render feature
571 bool rendered = false;
573 {
574 if ( featureIsSelected && mSelectionSymbol )
575 {
576 // note: here we pass "false" for the selected argument, as we don't want to change
577 // the user's defined selection symbol colors or settings in any way
578 mSelectionSymbol->renderFeature( fet, context, -1, false, drawMarker );
579 rendered = renderer->willRenderFeature( fet, context );
580 }
581 else
582 {
583 rendered = renderer->renderFeature( fet, context, -1, featureIsSelected, drawMarker );
584 }
585 }
586 else
587 {
588 rendered = renderer->willRenderFeature( fet, context );
589 }
590
591 // labeling - register feature
592 if ( rendered )
593 {
594 // as soon as first feature is rendered, we can start showing layer updates.
595 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
596 // at most e.g. 3 seconds before we start forcing progressive updates.
597 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
598 {
599 mReadyToCompose = true;
600 }
601
602 // new labeling engine
603 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
604 {
605 const quint64 startLabelTime = timer.elapsed();
606 QgsGeometry obstacleGeometry;
607 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
608 QgsSymbol *symbol = nullptr;
609 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
610 {
611 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
612 }
613
614 if ( !symbols.isEmpty() )
615 {
616 symbol = symbols.at( 0 );
618 }
619
620 if ( mApplyLabelClipGeometries )
621 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
622
623 if ( mLabelProvider )
624 {
625 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
626 }
627 if ( mDiagramProvider )
628 {
629 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
630 }
631
632 if ( mApplyLabelClipGeometries )
634
635 totalLabelTime += ( timer.elapsed() - startLabelTime );
636 }
637 }
638 }
639 catch ( const QgsCsException &cse )
640 {
641 Q_UNUSED( cse )
642 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
643 .arg( fet.id() ).arg( cse.what() ) );
644 }
645 }
646
647 delete context.expressionContext().popScope();
648
649 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
650 if ( mEnableProfile )
651 {
652 QgsApplication::profiler()->record( QObject::tr( "Rendering features" ), ( timer.elapsed() - totalLabelTime ) / 1000.0, QStringLiteral( "rendering" ) );
653 if ( totalLabelTime > 0 )
654 {
655 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
656 }
657 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
658 }
659
660 if ( mSelectionSymbol && isMainRenderer )
661 mSelectionSymbol->stopRender( context );
662
663 stopRenderer( renderer, nullptr );
664}
665
666void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
667{
668 const bool isMainRenderer = renderer == mRenderer;
669
670 // We need to figure out in which order all the features should be rendered.
671 // Ordering is based on (a) a "level" which is determined by the configured
672 // feature rendering order" and (b) the symbol level. The "level" is
673 // determined by the values of the attributes defined in the feature
674 // rendering order settings. Each time the attribute(s) have a new distinct
675 // value, a new empty QHash is added to the "features" list. This QHash is
676 // then filled by mappings from the symbol to a list of all the features
677 // that should be rendered by that symbol.
678 //
679 // If orderBy is not enabled, this list will only ever contain a single
680 // element.
681 QList<QHash< QgsSymbol *, QList<QgsFeature> >> features;
682
683 // We have at least one "level" for the features.
684 features.push_back( {} );
685
686 QSet<int> orderByAttributeIdx;
687 if ( renderer->orderByEnabled() )
688 {
689 orderByAttributeIdx = renderer->orderBy().usedAttributeIndices( mSource->fields() );
690 }
691
692 QgsRenderContext &context = *renderContext();
693
694 QgsSingleSymbolRenderer *selRenderer = nullptr;
695 if ( !mSelectedFeatureIds.isEmpty() )
696 {
697 selRenderer = new QgsSingleSymbolRenderer( QgsSymbol::defaultSymbol( mGeometryType ) );
698 selRenderer->symbol()->setColor( context.selectionColor() );
699 selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
700 selRenderer->startRender( context, mFields );
701 }
702
704 auto scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
705
706
707 std::unique_ptr< QgsGeometryEngine > clipEngine;
708 if ( mApplyClipFilter )
709 {
710 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
711 clipEngine->prepareGeometry();
712 }
713
714 if ( mApplyLabelClipGeometries )
715 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
716
717 std::unique_ptr< QgsScopedRuntimeProfile > fetchFeaturesProfile;
718 if ( mEnableProfile )
719 {
720 fetchFeaturesProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Fetching features" ), QStringLiteral( "rendering" ) );
721 }
722
723 QElapsedTimer timer;
724 timer.start();
725 quint64 totalLabelTime = 0;
726
727 // 1. fetch features
728 QgsFeature fet;
729 QVector<QVariant> prevValues; // previous values of ORDER BY attributes
730 while ( fit.nextFeature( fet ) )
731 {
732 if ( context.renderingStopped() )
733 {
734 qDebug( "rendering stop!" );
735 stopRenderer( renderer, selRenderer );
736 return;
737 }
738
739 if ( !fet.hasGeometry() )
740 continue; // skip features without geometry
741
742 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
743 continue; // skip features outside of clipping region
744
745 if ( ! mNoSetLayerExpressionContext )
746 context.expressionContext().setFeature( fet );
747 QgsSymbol *sym = renderer->symbolForFeature( fet, context );
748 if ( !sym )
749 {
750 continue;
751 }
752
753 if ( renderer->orderByEnabled() )
754 {
755 QVector<QVariant> currentValues;
756 for ( const int idx : std::as_const( orderByAttributeIdx ) )
757 {
758 currentValues.push_back( fet.attribute( idx ) );
759 }
760 if ( prevValues.empty() )
761 {
762 prevValues = std::move( currentValues );
763 }
764 else if ( currentValues != prevValues )
765 {
766 // Current values of ORDER BY attributes are different than previous
767 // values of these attributes. Start a new level.
768 prevValues = std::move( currentValues );
769 features.push_back( {} );
770 }
771 }
772
774 {
775 QHash<QgsSymbol *, QList<QgsFeature> > &featuresBack = features.back();
776 auto featuresBackIt = featuresBack.find( sym );
777 if ( featuresBackIt == featuresBack.end() )
778 {
779 featuresBackIt = featuresBack.insert( sym, QList<QgsFeature>() );
780 }
781 featuresBackIt->append( fet );
782 }
783
784 // new labeling engine
785 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
786 {
787 const quint64 startLabelTime = timer.elapsed();
788
789 QgsGeometry obstacleGeometry;
790 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
791 QgsSymbol *symbol = nullptr;
792 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
793 {
794 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
795 }
796
797 if ( !symbols.isEmpty() )
798 {
799 symbol = symbols.at( 0 );
801 }
802
803 if ( mLabelProvider )
804 {
805 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
806 }
807 if ( mDiagramProvider )
808 {
809 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
810 }
811
812 totalLabelTime += ( timer.elapsed() - startLabelTime );
813 }
814 }
815
816 fetchFeaturesProfile.reset();
817 if ( mEnableProfile )
818 {
819 if ( totalLabelTime > 0 )
820 {
821 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
822 }
823 }
824
825 if ( mApplyLabelClipGeometries )
827
828 scopePopper.reset();
829
830 if ( features.back().empty() )
831 {
832 // nothing to draw
833 stopRenderer( renderer, selRenderer );
834 return;
835 }
836
837
838 std::unique_ptr< QgsScopedRuntimeProfile > sortingProfile;
839 if ( mEnableProfile )
840 {
841 sortingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Sorting features" ), QStringLiteral( "rendering" ) );
842 }
843 // find out the order
844 QgsSymbolLevelOrder levels;
845 QgsSymbolList symbols = renderer->symbols( context );
846 for ( int i = 0; i < symbols.count(); i++ )
847 {
848 QgsSymbol *sym = symbols[i];
849 for ( int j = 0; j < sym->symbolLayerCount(); j++ )
850 {
851 int level = sym->symbolLayer( j )->renderingPass();
852 if ( level < 0 || level >= 1000 ) // ignore invalid levels
853 continue;
854 QgsSymbolLevelItem item( sym, j );
855 while ( level >= levels.count() ) // append new empty levels
856 levels.append( QgsSymbolLevel() );
857 levels[level].append( item );
858 }
859 }
860 sortingProfile.reset();
861
862 if ( mApplyClipGeometries )
863 context.setFeatureClipGeometry( mClipFeatureGeom );
864
865 // 2. draw features in correct order
866 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
867 {
868 for ( int l = 0; l < levels.count(); l++ )
869 {
870 const QgsSymbolLevel &level = levels[l];
871 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
872 if ( mEnableProfile )
873 {
874 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering symbol level %1" ).arg( l + 1 ), QStringLiteral( "rendering" ) );
875 }
876
877 for ( int i = 0; i < level.count(); i++ )
878 {
879 const QgsSymbolLevelItem &item = level[i];
880 if ( !featureLists.contains( item.symbol() ) )
881 {
882 QgsDebugError( QStringLiteral( "level item's symbol not found!" ) );
883 continue;
884 }
885 const int layer = item.layer();
886 const QList<QgsFeature> &lst = featureLists[item.symbol()];
887 for ( const QgsFeature &feature : lst )
888 {
889 if ( context.renderingStopped() )
890 {
891 stopRenderer( renderer, selRenderer );
892 return;
893 }
894
895 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( feature.id() );
896 if ( featureIsSelected && mSelectionSymbol )
897 continue; // defer rendering of selected symbols
898
899 // maybe vertex markers should be drawn only during the last pass...
900 const bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
901
902 if ( ! mNoSetLayerExpressionContext )
903 context.expressionContext().setFeature( feature );
904
905 try
906 {
907 renderer->renderFeature( feature, context, layer, featureIsSelected, drawMarker );
908
909 // as soon as first feature is rendered, we can start showing layer updates.
910 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
911 // at most e.g. 3 seconds before we start forcing progressive updates.
912 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
913 {
914 mReadyToCompose = true;
915 }
916 }
917 catch ( const QgsCsException &cse )
918 {
919 Q_UNUSED( cse )
920 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
921 .arg( fet.id() ).arg( cse.what() ) );
922 }
923 }
924 }
925 }
926 }
927
928 if ( mSelectionSymbol && !mSelectedFeatureIds.empty() && isMainRenderer && context.showSelection() )
929 {
930 mSelectionSymbol->startRender( context, mFields );
931
932 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
933 {
934 for ( auto it = featureLists.constBegin(); it != featureLists.constEnd(); ++it )
935 {
936 const QList<QgsFeature> &lst = it.value();
937 for ( const QgsFeature &feature : lst )
938 {
939 if ( context.renderingStopped() )
940 {
941 break;
942 }
943
944 const bool featureIsSelected = mSelectedFeatureIds.contains( feature.id() );
945 if ( !featureIsSelected )
946 continue;
947
948 const bool drawMarker = mDrawVertexMarkers && context.drawEditingInformation();
949 // note: here we pass "false" for the selected argument, as we don't want to change
950 // the user's defined selection symbol colors or settings in any way
951 mSelectionSymbol->renderFeature( feature, context, -1, false, drawMarker );
952 }
953 }
954 }
955
956 mSelectionSymbol->stopRender( context );
957 }
958
959 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
960 if ( mEnableProfile )
961 {
962 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
963 }
964
965 stopRenderer( renderer, selRenderer );
966}
967
968void QgsVectorLayerRenderer::stopRenderer( QgsFeatureRenderer *renderer, QgsSingleSymbolRenderer *selRenderer )
969{
970 QgsRenderContext &context = *renderContext();
971 renderer->stopRender( context );
972 if ( selRenderer )
973 {
974 selRenderer->stopRender( context );
975 delete selRenderer;
976 }
977}
978
979void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer *layer, QSet<QString> &attributeNames )
980{
981 QgsRenderContext &context = *renderContext();
982 // TODO: add attributes for geometry generator
983 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
984 {
985 if ( layer->labelsEnabled() )
986 {
987 if ( context.labelSink() )
988 {
989 if ( const QgsRuleBasedLabeling *rbl = dynamic_cast<const QgsRuleBasedLabeling *>( layer->labeling() ) )
990 {
991 mLabelProvider = new QgsRuleBasedLabelSinkProvider( *rbl, layer, context.labelSink() );
992 }
993 else
994 {
995 QgsPalLayerSettings settings = layer->labeling()->settings();
996 mLabelProvider = new QgsLabelSinkProvider( layer, QString(), context.labelSink(), &settings );
997 }
998 }
999 else
1000 {
1001 mLabelProvider = layer->labeling()->provider( layer );
1002 }
1003 if ( mLabelProvider )
1004 {
1005 engine2->addProvider( mLabelProvider );
1006 if ( !mLabelProvider->prepare( context, attributeNames ) )
1007 {
1008 engine2->removeProvider( mLabelProvider );
1009 mLabelProvider = nullptr; // deleted by engine
1010 }
1011 }
1012 }
1013 }
1014
1015#if 0 // TODO: limit of labels, font not found
1016 QgsPalLayerSettings &palyr = mContext.labelingEngine()->layer( mLayerID );
1017
1018 // see if feature count limit is set for labeling
1019 if ( palyr.limitNumLabels && palyr.maxNumLabels > 0 )
1020 {
1021 QgsFeatureIterator fit = getFeatures( QgsFeatureRequest()
1022 .setFilterRect( mContext.extent() )
1023 .setNoAttributes() );
1024
1025 // total number of features that may be labeled
1026 QgsFeature f;
1027 int nFeatsToLabel = 0;
1028 while ( fit.nextFeature( f ) )
1029 {
1030 nFeatsToLabel++;
1031 }
1032 palyr.mFeaturesToLabel = nFeatsToLabel;
1033 }
1034
1035 // notify user about any font substitution
1036 if ( !palyr.mTextFontFound && !mLabelFontNotFoundNotified )
1037 {
1038 emit labelingFontNotFound( this, palyr.mTextFontFamily );
1039 mLabelFontNotFoundNotified = true;
1040 }
1041#endif
1042}
1043
1044void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer *layer, QSet<QString> &attributeNames )
1045{
1046 QgsRenderContext &context = *renderContext();
1047 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
1048 {
1049 if ( layer->diagramsEnabled() )
1050 {
1051 mDiagramProvider = new QgsVectorLayerDiagramProvider( layer );
1052 // need to be added before calling prepare() - uses map settings from engine
1053 engine2->addProvider( mDiagramProvider );
1054 if ( !mDiagramProvider->prepare( context, attributeNames ) )
1055 {
1056 engine2->removeProvider( mDiagramProvider );
1057 mDiagramProvider = nullptr; // deleted by engine
1058 }
1059 }
1060 }
1061}
1062
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:54
@ ForceVector
Always force vector-based rendering, even when the result will be visually different to a raster-base...
QFlags< MapLayerRendererFlag > MapLayerRendererFlags
Flags which control how map layer renderers behave.
Definition qgis.h:2746
QFlags< VectorRenderingSimplificationFlag > VectorRenderingSimplificationFlags
Simplification flags for vector feature rendering.
Definition qgis.h:2973
@ NoSimplification
No simplification can be applied.
@ FullSimplification
All simplification hints can be applied ( Geometry + AA-disabling )
@ GeometrySimplification
The geometries can be simplified using the current map2pixel context state.
@ Degrees
Degrees, for planar geographic CRS distance measurements.
@ EmbeddedSymbols
Retrieve any embedded feature symbology.
@ AffectsLabeling
If present, indicates that the renderer will participate in the map labeling problem.
@ Unknown
Unknown types.
@ Null
No geometry.
@ Vector
Vector layer.
@ AffectsLabeling
The layer rendering will interact with the map labeling.
@ SkipSymbolRendering
Disable symbol rendering while still drawing labels if enabled.
@ 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.
Handles coordinate transforms between two 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.
QString what() const
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.
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 Q_DECL_DEPRECATED void filterFeatures(const QgsVectorLayer *layer, QgsFeatureRequest &featureRequest) const
Add additional filters to the feature request to further restrict the features returned by the reques...
virtual Q_DECL_DEPRECATED bool isFilterThreadSafe() const
Returns true if the filterFeature function is thread safe, which will lead to reliance on layer ID in...
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.
Abstract base class for all 2D vector feature renderers.
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...
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 Qgis::FeatureRendererFlags flags() const
Returns flags associated with 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
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.
bool usingSymbolLevels() const
virtual QString dump() const
Returns debug information about this renderer.
virtual QgsFeatureRenderer::Capabilities capabilities()
Returns details about internals of this renderer.
virtual QgsSymbol * symbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const =0
To be overridden.
@ SymbolLevels
Rendering with symbol levels (i.e. implements symbols(), symbolForFeature())
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.
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.
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:58
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
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.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::GeometryType type
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, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
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.
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:90
Perform transforms between map coordinates and device coordinates.
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, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
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.
Represents a 2D point.
Definition qgspointxy.h:60
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
A rectangle specified with double values.
Q_INVOKABLE 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
double yMinimum
double xMaximum
double yMaximum
QgsPointXY center
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Contains information about the context of a rendering operation.
bool hasRenderedFeatureHandlers() const
Returns true if the context has any rendered feature handlers.
QgsVectorSimplifyMethod & vectorSimplifyMethod()
Returns the simplification settings to use when rendering vector layers.
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 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.
Qgis::RasterizedRenderingPolicy rasterizedRenderingPolicy() const
Returns the policy controlling when rasterisation of content during renders is permitted.
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 provide custom handlers for features rendered as part of a map render ...
Implements a derived label provider for rule based labels for use with QgsLabelSink.
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.
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.
A feature renderer which renders all features with the same symbol.
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.
Represents a symbol level during vector rendering operations.
Definition qgsrenderer.h:65
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:231
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
void setColor(const QColor &color) const
Sets the color for the symbol.
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Definition qgssymbol.h:353
static QgsSymbol * defaultSymbol(Qgis::GeometryType geomType)
Returns a new default symbol for the specified geometry type.
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...
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.
Qgis::MapLayerRendererFlags flags() const override
Returns flags which control how the map layer rendering behaves.
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.
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 dataset.
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.
bool simplifyDrawingCanbeApplied(const QgsRenderContext &renderContext, Qgis::VectorRenderingSimplificationFlag simplifyHint) const
Returns whether the VectorLayer can apply the specified simplification hint.
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.
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.
Contains settings for simplifying geometries fetched from a vector layer.
bool forceLocalOptimization() const
Gets where the simplification executes, after fetch the geometries from provider, or when supported,...
Qgis::VectorRenderingSimplificationFlags simplifyHints() const
Gets the simplification hints of the vector layer managed.
void setSimplifyHints(Qgis::VectorRenderingSimplificationFlags simplifyHints)
Sets 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.
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:6945
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:6944
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:6392
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:41
#define QgsDebugError(str)
Definition qgslogger.h:40
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition qgsrenderer.h:93
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition qgsrenderer.h:89
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:48