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