QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
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 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{
233 if ( mRenderer && mRenderer->flags().testFlag( Qgis::FeatureRendererFlag::AffectsLabeling ) )
235 return res;
236}
237
239{
240 if ( mGeometryType == Qgis::GeometryType::Null || mGeometryType == Qgis::GeometryType::Unknown )
241 {
242 mReadyToCompose = true;
243 return true;
244 }
245
246 if ( mRenderers.empty() )
247 {
248 mReadyToCompose = true;
249 mErrors.append( QObject::tr( "No renderer for drawing." ) );
250 return false;
251 }
252
253 std::unique_ptr< QgsScopedRuntimeProfile > profile;
254 if ( mEnableProfile )
255 {
256 profile = std::make_unique< QgsScopedRuntimeProfile >( mLayerName, QStringLiteral( "rendering" ), layerId() );
257 if ( mPreparationTime > 0 )
258 QgsApplication::profiler()->record( QObject::tr( "Create renderer" ), mPreparationTime / 1000.0, QStringLiteral( "rendering" ) );
259 }
260
261 // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
262 // cached version of the layer during rendering instead of the usual progressive updates
263 if ( mRenderTimeHint > 0 && mRenderTimeHint <= MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
264 {
265 mBlockRenderUpdates = true;
266 mElapsedTimer.start();
267 }
268
269 bool res = true;
270 int rendererIndex = 0;
271 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
272 {
273 if ( mFeedback->isCanceled() || !res )
274 {
275 break;
276 }
277 res = renderInternal( renderer.get(), rendererIndex++ ) && res;
278 }
279
280 mReadyToCompose = true;
281 return res && !renderContext()->renderingStopped();
282}
283
284bool QgsVectorLayerRenderer::renderInternal( QgsFeatureRenderer *renderer, int rendererIndex )
285{
286 const bool isMainRenderer = renderer == mRenderer;
287
288 QgsRenderContext &context = *renderContext();
289 context.setSymbologyReferenceScale( renderer->referenceScale() );
290
291 if ( renderer->type() == QLatin1String( "nullSymbol" ) )
292 {
293 // a little shortcut for the null symbol renderer - most of the time it is not going to render anything
294 // so we can even skip the whole loop to fetch features
295 if ( !isMainRenderer ||
296 ( !mDrawVertexMarkers && !mLabelProvider && !mDiagramProvider && mSelectedFeatureIds.isEmpty() ) )
297 return true;
298 }
299
300 std::unique_ptr< QgsScopedRuntimeProfile > preparingProfile;
301 if ( mEnableProfile )
302 {
303 QString title;
304 if ( mRenderers.size() > 1 )
305 title = QObject::tr( "Preparing render %1" ).arg( rendererIndex + 1 );
306 else
307 title = QObject::tr( "Preparing render" );
308 preparingProfile = std::make_unique< QgsScopedRuntimeProfile >( title, QStringLiteral( "rendering" ) );
309 }
310
311 QgsScopedQPainterState painterState( context.painter() );
312
313 bool usingEffect = false;
314 if ( renderer->paintEffect() && renderer->paintEffect()->enabled() )
315 {
316 usingEffect = true;
317 renderer->paintEffect()->begin( context );
318 }
319
320 // Per feature blending mode
321 if ( context.useAdvancedEffects() && 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 {
372 featureFilterProvider->filterFeatures( mLayer, featureRequest );
373 }
374 if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) )
375 {
376 featureRequest.combineFilterExpression( rendererFilter );
377 }
378 if ( !mTemporalFilter.isEmpty() )
379 {
380 featureRequest.combineFilterExpression( mTemporalFilter );
381 }
382
383 if ( renderer->usesEmbeddedSymbols() )
384 {
385 featureRequest.setFlags( featureRequest.flags() | Qgis::FeatureRequestFlag::EmbeddedSymbols );
386 }
387
388 // enable the simplification of the geometries (Using the current map2pixel context) before send it to renderer engine.
389 if ( mSimplifyGeometry )
390 {
391 double map2pixelTol = mSimplifyMethod.threshold();
392 bool validTransform = true;
393
394 const QgsMapToPixel &mtp = context.mapToPixel();
395 map2pixelTol *= mtp.mapUnitsPerPixel();
396 const QgsCoordinateTransform ct = context.coordinateTransform();
397
398 // resize the tolerance using the change of size of an 1-BBOX from the source CoordinateSystem to the target CoordinateSystem
399 if ( ct.isValid() && !ct.isShortCircuited() )
400 {
401 try
402 {
403 QgsCoordinateTransform toleranceTransform = ct;
404 QgsPointXY center = context.extent().center();
405 double rectSize = toleranceTransform.sourceCrs().mapUnits() == Qgis::DistanceUnit::Degrees ? 0.0008983 /* ~100/(40075014/360=111319.4833) */ : 100;
406
407 QgsRectangle sourceRect = QgsRectangle( center.x(), center.y(), center.x() + rectSize, center.y() + rectSize );
408 toleranceTransform.setBallparkTransformsAreAppropriate( true );
409 QgsRectangle targetRect = toleranceTransform.transform( sourceRect );
410
411 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceTransformRect=%1" ).arg( sourceRect.toString( 16 ) ), 4 );
412 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetTransformRect=%1" ).arg( targetRect.toString( 16 ) ), 4 );
413
414 if ( !sourceRect.isEmpty() && sourceRect.isFinite() && !targetRect.isEmpty() && targetRect.isFinite() )
415 {
416 QgsPointXY minimumSrcPoint( sourceRect.xMinimum(), sourceRect.yMinimum() );
417 QgsPointXY maximumSrcPoint( sourceRect.xMaximum(), sourceRect.yMaximum() );
418 QgsPointXY minimumDstPoint( targetRect.xMinimum(), targetRect.yMinimum() );
419 QgsPointXY maximumDstPoint( targetRect.xMaximum(), targetRect.yMaximum() );
420
421 double sourceHypothenuse = std::sqrt( minimumSrcPoint.sqrDist( maximumSrcPoint ) );
422 double targetHypothenuse = std::sqrt( minimumDstPoint.sqrDist( maximumDstPoint ) );
423
424 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceHypothenuse=%1" ).arg( sourceHypothenuse ), 4 );
425 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetHypothenuse=%1" ).arg( targetHypothenuse ), 4 );
426
427 if ( !qgsDoubleNear( targetHypothenuse, 0.0 ) )
428 map2pixelTol *= ( sourceHypothenuse / targetHypothenuse );
429 }
430 }
431 catch ( QgsCsException &cse )
432 {
433 QgsMessageLog::logMessage( QObject::tr( "Simplify transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
434 validTransform = false;
435 }
436 }
437
438 if ( validTransform )
439 {
440 QgsSimplifyMethod simplifyMethod;
442 simplifyMethod.setTolerance( map2pixelTol );
443 simplifyMethod.setThreshold( mSimplifyMethod.threshold() );
444 simplifyMethod.setForceLocalOptimization( mSimplifyMethod.forceLocalOptimization() );
445 featureRequest.setSimplifyMethod( simplifyMethod );
446
447 QgsVectorSimplifyMethod vectorMethod = mSimplifyMethod;
448 vectorMethod.setTolerance( map2pixelTol );
449 context.setVectorSimplifyMethod( vectorMethod );
450 }
451 else
452 {
453 QgsVectorSimplifyMethod vectorMethod;
455 context.setVectorSimplifyMethod( vectorMethod );
456 }
457 }
458 else
459 {
460 QgsVectorSimplifyMethod vectorMethod;
462 context.setVectorSimplifyMethod( vectorMethod );
463 }
464
465 featureRequest.setFeedback( mFeedback.get() );
466 // also set the interruption checker for the expression context, in case the renderer uses some complex expression
467 // which could benefit from early exit paths...
468 context.expressionContext().setFeedback( mFeedback.get() );
469
470 std::unique_ptr< QgsScopedRuntimeProfile > preparingFeatureItProfile;
471 if ( mEnableProfile )
472 {
473 preparingFeatureItProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Prepare feature iteration" ), QStringLiteral( "rendering" ) );
474 }
475
476 QgsFeatureIterator fit = mSource->getFeatures( featureRequest );
477 // Attach an interruption checker so that iterators that have potentially
478 // slow fetchFeature() implementations, such as in the WFS provider, can
479 // check it, instead of relying on just the mContext.renderingStopped() check
480 // in drawRenderer()
481
482 fit.setInterruptionChecker( mFeedback.get() );
483
484 preparingFeatureItProfile.reset();
485 preparingProfile.reset();
486
487 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
488 if ( mEnableProfile )
489 {
490 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering" ), QStringLiteral( "rendering" ) );
491 }
492
493 if ( ( renderer->capabilities() & QgsFeatureRenderer::SymbolLevels ) && renderer->usingSymbolLevels() )
494 drawRendererLevels( renderer, fit );
495 else
496 drawRenderer( renderer, fit );
497
498 if ( !fit.isValid() )
499 {
500 mErrors.append( QStringLiteral( "Data source invalid" ) );
501 }
502
503 if ( usingEffect )
504 {
505 renderer->paintEffect()->end( context );
506 }
507
508 context.expressionContext().setFeedback( nullptr );
509 return true;
510}
511
512
513void QgsVectorLayerRenderer::drawRenderer( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
514{
515 QElapsedTimer timer;
516 timer.start();
517 quint64 totalLabelTime = 0;
518
519 const bool isMainRenderer = renderer == mRenderer;
520
522 QgsRenderContext &context = *renderContext();
523 context.expressionContext().appendScope( symbolScope );
524
525 std::unique_ptr< QgsGeometryEngine > clipEngine;
526 if ( mApplyClipFilter )
527 {
528 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
529 clipEngine->prepareGeometry();
530 }
531
532 if ( mSelectionSymbol && isMainRenderer )
533 mSelectionSymbol->startRender( context, mFields );
534
535 QgsFeature fet;
536 while ( fit.nextFeature( fet ) )
537 {
538 try
539 {
540 if ( context.renderingStopped() )
541 {
542 QgsDebugMsgLevel( QStringLiteral( "Drawing of vector layer %1 canceled." ).arg( layerId() ), 2 );
543 break;
544 }
545
546 if ( !fet.hasGeometry() || fet.geometry().isEmpty() )
547 continue; // skip features without geometry
548
549 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
550 continue; // skip features outside of clipping region
551
552 if ( mApplyClipGeometries )
553 context.setFeatureClipGeometry( mClipFeatureGeom );
554
555 if ( ! mNoSetLayerExpressionContext )
556 context.expressionContext().setFeature( fet );
557
558 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fet.id() );
559 bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
560
561 // render feature
562 bool rendered = false;
564 {
565 if ( featureIsSelected && mSelectionSymbol )
566 {
567 // note: here we pass "false" for the selected argument, as we don't want to change
568 // the user's defined selection symbol colors or settings in any way
569 mSelectionSymbol->renderFeature( fet, context, -1, false, drawMarker );
570 rendered = renderer->willRenderFeature( fet, context );
571 }
572 else
573 {
574 rendered = renderer->renderFeature( fet, context, -1, featureIsSelected, drawMarker );
575 }
576 }
577 else
578 {
579 rendered = renderer->willRenderFeature( fet, context );
580 }
581
582 // labeling - register feature
583 if ( rendered )
584 {
585 // as soon as first feature is rendered, we can start showing layer updates.
586 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
587 // at most e.g. 3 seconds before we start forcing progressive updates.
588 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
589 {
590 mReadyToCompose = true;
591 }
592
593 // new labeling engine
594 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
595 {
596 const quint64 startLabelTime = timer.elapsed();
597 QgsGeometry obstacleGeometry;
598 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
599 QgsSymbol *symbol = nullptr;
600 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
601 {
602 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
603 }
604
605 if ( !symbols.isEmpty() )
606 {
607 symbol = symbols.at( 0 );
609 }
610
611 if ( mApplyLabelClipGeometries )
612 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
613
614 if ( mLabelProvider )
615 {
616 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
617 }
618 if ( mDiagramProvider )
619 {
620 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
621 }
622
623 if ( mApplyLabelClipGeometries )
625
626 totalLabelTime += ( timer.elapsed() - startLabelTime );
627 }
628 }
629 }
630 catch ( const QgsCsException &cse )
631 {
632 Q_UNUSED( cse )
633 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
634 .arg( fet.id() ).arg( cse.what() ) );
635 }
636 }
637
638 delete context.expressionContext().popScope();
639
640 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
641 if ( mEnableProfile )
642 {
643 QgsApplication::profiler()->record( QObject::tr( "Rendering features" ), ( timer.elapsed() - totalLabelTime ) / 1000.0, QStringLiteral( "rendering" ) );
644 if ( totalLabelTime > 0 )
645 {
646 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
647 }
648 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
649 }
650
651 if ( mSelectionSymbol && isMainRenderer )
652 mSelectionSymbol->stopRender( context );
653
654 stopRenderer( renderer, nullptr );
655}
656
657void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
658{
659 const bool isMainRenderer = renderer == mRenderer;
660
661 // We need to figure out in which order all the features should be rendered.
662 // Ordering is based on (a) a "level" which is determined by the configured
663 // feature rendering order" and (b) the symbol level. The "level" is
664 // determined by the values of the attributes defined in the feature
665 // rendering order settings. Each time the attribute(s) have a new distinct
666 // value, a new empty QHash is added to the "features" list. This QHash is
667 // then filled by mappings from the symbol to a list of all the features
668 // that should be rendered by that symbol.
669 //
670 // If orderBy is not enabled, this list will only ever contain a single
671 // element.
672 QList<QHash< QgsSymbol *, QList<QgsFeature> >> features;
673
674 // We have at least one "level" for the features.
675 features.push_back( {} );
676
677 QSet<int> orderByAttributeIdx;
678 if ( renderer->orderByEnabled() )
679 {
680 orderByAttributeIdx = renderer->orderBy().usedAttributeIndices( mSource->fields() );
681 }
682
683 QgsRenderContext &context = *renderContext();
684
685 QgsSingleSymbolRenderer *selRenderer = nullptr;
686 if ( !mSelectedFeatureIds.isEmpty() )
687 {
688 selRenderer = new QgsSingleSymbolRenderer( QgsSymbol::defaultSymbol( mGeometryType ) );
689 selRenderer->symbol()->setColor( context.selectionColor() );
690 selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
691 selRenderer->startRender( context, mFields );
692 }
693
695 std::unique_ptr< QgsExpressionContextScopePopper > scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
696
697
698 std::unique_ptr< QgsGeometryEngine > clipEngine;
699 if ( mApplyClipFilter )
700 {
701 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
702 clipEngine->prepareGeometry();
703 }
704
705 if ( mApplyLabelClipGeometries )
706 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
707
708 std::unique_ptr< QgsScopedRuntimeProfile > fetchFeaturesProfile;
709 if ( mEnableProfile )
710 {
711 fetchFeaturesProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Fetching features" ), QStringLiteral( "rendering" ) );
712 }
713
714 QElapsedTimer timer;
715 timer.start();
716 quint64 totalLabelTime = 0;
717
718 // 1. fetch features
719 QgsFeature fet;
720 QVector<QVariant> prevValues; // previous values of ORDER BY attributes
721 while ( fit.nextFeature( fet ) )
722 {
723 if ( context.renderingStopped() )
724 {
725 qDebug( "rendering stop!" );
726 stopRenderer( renderer, selRenderer );
727 return;
728 }
729
730 if ( !fet.hasGeometry() )
731 continue; // skip features without geometry
732
733 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
734 continue; // skip features outside of clipping region
735
736 if ( ! mNoSetLayerExpressionContext )
737 context.expressionContext().setFeature( fet );
738 QgsSymbol *sym = renderer->symbolForFeature( fet, context );
739 if ( !sym )
740 {
741 continue;
742 }
743
744 if ( renderer->orderByEnabled() )
745 {
746 QVector<QVariant> currentValues;
747 for ( const int idx : std::as_const( orderByAttributeIdx ) )
748 {
749 currentValues.push_back( fet.attribute( idx ) );
750 }
751 if ( prevValues.empty() )
752 {
753 prevValues = std::move( currentValues );
754 }
755 else if ( currentValues != prevValues )
756 {
757 // Current values of ORDER BY attributes are different than previous
758 // values of these attributes. Start a new level.
759 prevValues = std::move( currentValues );
760 features.push_back( {} );
761 }
762 }
763
765 {
766 QHash<QgsSymbol *, QList<QgsFeature> > &featuresBack = features.back();
767 auto featuresBackIt = featuresBack.find( sym );
768 if ( featuresBackIt == featuresBack.end() )
769 {
770 featuresBackIt = featuresBack.insert( sym, QList<QgsFeature>() );
771 }
772 featuresBackIt->append( fet );
773 }
774
775 // new labeling engine
776 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
777 {
778 const quint64 startLabelTime = timer.elapsed();
779
780 QgsGeometry obstacleGeometry;
781 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
782 QgsSymbol *symbol = nullptr;
783 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
784 {
785 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
786 }
787
788 if ( !symbols.isEmpty() )
789 {
790 symbol = symbols.at( 0 );
792 }
793
794 if ( mLabelProvider )
795 {
796 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
797 }
798 if ( mDiagramProvider )
799 {
800 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
801 }
802
803 totalLabelTime += ( timer.elapsed() - startLabelTime );
804 }
805 }
806
807 fetchFeaturesProfile.reset();
808 if ( mEnableProfile )
809 {
810 if ( totalLabelTime > 0 )
811 {
812 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
813 }
814 }
815
816 if ( mApplyLabelClipGeometries )
818
819 scopePopper.reset();
820
821 if ( features.back().empty() )
822 {
823 // nothing to draw
824 stopRenderer( renderer, selRenderer );
825 return;
826 }
827
828
829 std::unique_ptr< QgsScopedRuntimeProfile > sortingProfile;
830 if ( mEnableProfile )
831 {
832 sortingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Sorting features" ), QStringLiteral( "rendering" ) );
833 }
834 // find out the order
835 QgsSymbolLevelOrder levels;
836 QgsSymbolList symbols = renderer->symbols( context );
837 for ( int i = 0; i < symbols.count(); i++ )
838 {
839 QgsSymbol *sym = symbols[i];
840 for ( int j = 0; j < sym->symbolLayerCount(); j++ )
841 {
842 int level = sym->symbolLayer( j )->renderingPass();
843 if ( level < 0 || level >= 1000 ) // ignore invalid levels
844 continue;
845 QgsSymbolLevelItem item( sym, j );
846 while ( level >= levels.count() ) // append new empty levels
847 levels.append( QgsSymbolLevel() );
848 levels[level].append( item );
849 }
850 }
851 sortingProfile.reset();
852
853 if ( mApplyClipGeometries )
854 context.setFeatureClipGeometry( mClipFeatureGeom );
855
856 // 2. draw features in correct order
857 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
858 {
859 for ( int l = 0; l < levels.count(); l++ )
860 {
861 const QgsSymbolLevel &level = levels[l];
862 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
863 if ( mEnableProfile )
864 {
865 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering symbol level %1" ).arg( l + 1 ), QStringLiteral( "rendering" ) );
866 }
867
868 for ( int i = 0; i < level.count(); i++ )
869 {
870 const QgsSymbolLevelItem &item = level[i];
871 if ( !featureLists.contains( item.symbol() ) )
872 {
873 QgsDebugError( QStringLiteral( "level item's symbol not found!" ) );
874 continue;
875 }
876 const int layer = item.layer();
877 const QList<QgsFeature> &lst = featureLists[item.symbol()];
878 for ( const QgsFeature &feature : lst )
879 {
880 if ( context.renderingStopped() )
881 {
882 stopRenderer( renderer, selRenderer );
883 return;
884 }
885
886 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( feature.id() );
887 if ( featureIsSelected && mSelectionSymbol )
888 continue; // defer rendering of selected symbols
889
890 // maybe vertex markers should be drawn only during the last pass...
891 const bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
892
893 if ( ! mNoSetLayerExpressionContext )
894 context.expressionContext().setFeature( feature );
895
896 try
897 {
898 renderer->renderFeature( feature, context, layer, featureIsSelected, drawMarker );
899
900 // as soon as first feature is rendered, we can start showing layer updates.
901 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
902 // at most e.g. 3 seconds before we start forcing progressive updates.
903 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
904 {
905 mReadyToCompose = true;
906 }
907 }
908 catch ( const QgsCsException &cse )
909 {
910 Q_UNUSED( cse )
911 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
912 .arg( fet.id() ).arg( cse.what() ) );
913 }
914 }
915 }
916 }
917 }
918
919 if ( mSelectionSymbol && !mSelectedFeatureIds.empty() && isMainRenderer && context.showSelection() )
920 {
921 mSelectionSymbol->startRender( context, mFields );
922
923 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
924 {
925 for ( auto it = featureLists.constBegin(); it != featureLists.constEnd(); ++it )
926 {
927 const QList<QgsFeature> &lst = it.value();
928 for ( const QgsFeature &feature : lst )
929 {
930 if ( context.renderingStopped() )
931 {
932 break;
933 }
934
935 const bool featureIsSelected = mSelectedFeatureIds.contains( feature.id() );
936 if ( !featureIsSelected )
937 continue;
938
939 const bool drawMarker = mDrawVertexMarkers && context.drawEditingInformation();
940 // note: here we pass "false" for the selected argument, as we don't want to change
941 // the user's defined selection symbol colors or settings in any way
942 mSelectionSymbol->renderFeature( feature, context, -1, false, drawMarker );
943 }
944 }
945 }
946
947 mSelectionSymbol->stopRender( context );
948 }
949
950 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
951 if ( mEnableProfile )
952 {
953 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
954 }
955
956 stopRenderer( renderer, selRenderer );
957}
958
959void QgsVectorLayerRenderer::stopRenderer( QgsFeatureRenderer *renderer, QgsSingleSymbolRenderer *selRenderer )
960{
961 QgsRenderContext &context = *renderContext();
962 renderer->stopRender( context );
963 if ( selRenderer )
964 {
965 selRenderer->stopRender( context );
966 delete selRenderer;
967 }
968}
969
970void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer *layer, QSet<QString> &attributeNames )
971{
972 QgsRenderContext &context = *renderContext();
973 // TODO: add attributes for geometry generator
974 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
975 {
976 if ( layer->labelsEnabled() )
977 {
978 if ( context.labelSink() )
979 {
980 if ( const QgsRuleBasedLabeling *rbl = dynamic_cast<const QgsRuleBasedLabeling *>( layer->labeling() ) )
981 {
982 mLabelProvider = new QgsRuleBasedLabelSinkProvider( *rbl, layer, context.labelSink() );
983 }
984 else
985 {
986 QgsPalLayerSettings settings = layer->labeling()->settings();
987 mLabelProvider = new QgsLabelSinkProvider( layer, QString(), context.labelSink(), &settings );
988 }
989 }
990 else
991 {
992 mLabelProvider = layer->labeling()->provider( layer );
993 }
994 if ( mLabelProvider )
995 {
996 engine2->addProvider( mLabelProvider );
997 if ( !mLabelProvider->prepare( context, attributeNames ) )
998 {
999 engine2->removeProvider( mLabelProvider );
1000 mLabelProvider = nullptr; // deleted by engine
1001 }
1002 }
1003 }
1004 }
1005
1006#if 0 // TODO: limit of labels, font not found
1007 QgsPalLayerSettings &palyr = mContext.labelingEngine()->layer( mLayerID );
1008
1009 // see if feature count limit is set for labeling
1010 if ( palyr.limitNumLabels && palyr.maxNumLabels > 0 )
1011 {
1012 QgsFeatureIterator fit = getFeatures( QgsFeatureRequest()
1013 .setFilterRect( mContext.extent() )
1014 .setNoAttributes() );
1015
1016 // total number of features that may be labeled
1017 QgsFeature f;
1018 int nFeatsToLabel = 0;
1019 while ( fit.nextFeature( f ) )
1020 {
1021 nFeatsToLabel++;
1022 }
1023 palyr.mFeaturesToLabel = nFeatsToLabel;
1024 }
1025
1026 // notify user about any font substitution
1027 if ( !palyr.mTextFontFound && !mLabelFontNotFoundNotified )
1028 {
1029 emit labelingFontNotFound( this, palyr.mTextFontFamily );
1030 mLabelFontNotFoundNotified = true;
1031 }
1032#endif
1033}
1034
1035void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer *layer, QSet<QString> &attributeNames )
1036{
1037 QgsRenderContext &context = *renderContext();
1038 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
1039 {
1040 if ( layer->diagramsEnabled() )
1041 {
1042 mDiagramProvider = new QgsVectorLayerDiagramProvider( layer );
1043 // need to be added before calling prepare() - uses map settings from engine
1044 engine2->addProvider( mDiagramProvider );
1045 if ( !mDiagramProvider->prepare( context, attributeNames ) )
1046 {
1047 engine2->removeProvider( mDiagramProvider );
1048 mDiagramProvider = nullptr; // deleted by engine
1049 }
1050 }
1051 }
1052}
1053
The Qgis class provides global constants for use throughout the application.
Definition qgis.h:54
QFlags< MapLayerRendererFlag > MapLayerRendererFlags
Flags which control how map layer renderers behave.
Definition qgis.h:2676
QFlags< VectorRenderingSimplificationFlag > VectorRenderingSimplificationFlags
Simplification flags for vector feature rendering.
Definition qgis.h:2884
@ 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.
@ 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.
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.
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.
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.
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.
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: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.
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:88
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)
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
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 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.
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.
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.
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: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...
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.
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 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.
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.
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,...
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.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:6066
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
#define QgsDebugError(str)
Definition qgslogger.h:38
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition qgsrenderer.h:91
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition qgsrenderer.h:87
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:47