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