QGIS API Documentation  2.99.0-Master (5d67572)
qgsrendercontext.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsrendercontext.cpp
3  --------------------
4  begin : March 16, 2008
5  copyright : (C) 2008 by Marco Hugentobler
6  email : marco dot hugentobler at karto dot baug dot ethz dot ch
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
18 
19 #include "qgsrendercontext.h"
20 
21 #include "qgsmapsettings.h"
22 #include "qgsexpression.h"
23 #include "qgsvectorlayer.h"
25 #include "qgslogger.h"
26 #include "qgspoint.h"
27 
28 #define POINTS_TO_MM 2.83464567
29 #define INCH_TO_MM 25.4
30 
32  : mFlags( DrawEditingInfo | UseAdvancedEffects | DrawSelection | UseRenderingOptimization )
33 {
35  // For RenderMetersInMapUnits support, when rendering in Degrees, the Ellipsoid must be set
36  // - for Previews/Icons the default Extent can be used
37  mDistanceArea.setEllipsoid( mDistanceArea.sourceCrs().ellipsoidAcronym() );
38 }
39 
41  : mFlags( rh.mFlags )
42  , mPainter( rh.mPainter )
43  , mCoordTransform( rh.mCoordTransform )
44  , mDistanceArea( rh.mDistanceArea )
45  , mExtent( rh.mExtent )
46  , mMapToPixel( rh.mMapToPixel )
47  , mRenderingStopped( rh.mRenderingStopped )
48  , mScaleFactor( rh.mScaleFactor )
49  , mRendererScale( rh.mRendererScale )
50  , mLabelingEngine( rh.mLabelingEngine )
51  , mSelectionColor( rh.mSelectionColor )
52  , mVectorSimplifyMethod( rh.mVectorSimplifyMethod )
53  , mExpressionContext( rh.mExpressionContext )
54  , mGeometry( rh.mGeometry )
55  , mFeatureFilterProvider( rh.mFeatureFilterProvider ? rh.mFeatureFilterProvider->clone() : nullptr )
56  , mSegmentationTolerance( rh.mSegmentationTolerance )
57  , mSegmentationToleranceType( rh.mSegmentationToleranceType )
58 {
59 }
60 
62 {
63  mFlags = rh.mFlags;
64  mPainter = rh.mPainter;
65  mCoordTransform = rh.mCoordTransform;
66  mExtent = rh.mExtent;
67  mMapToPixel = rh.mMapToPixel;
68  mRenderingStopped = rh.mRenderingStopped;
69  mScaleFactor = rh.mScaleFactor;
70  mRendererScale = rh.mRendererScale;
71  mLabelingEngine = rh.mLabelingEngine;
72  mSelectionColor = rh.mSelectionColor;
73  mVectorSimplifyMethod = rh.mVectorSimplifyMethod;
74  mExpressionContext = rh.mExpressionContext;
75  mGeometry = rh.mGeometry;
76  mFeatureFilterProvider.reset( rh.mFeatureFilterProvider ? rh.mFeatureFilterProvider->clone() : nullptr );
77  mSegmentationTolerance = rh.mSegmentationTolerance;
78  mSegmentationToleranceType = rh.mSegmentationToleranceType;
79  mDistanceArea = rh.mDistanceArea;
80  return *this;
81 }
82 
84 {
85  QgsRenderContext context;
86  context.setPainter( painter );
87  if ( painter && painter->device() )
88  {
89  context.setScaleFactor( painter->device()->logicalDpiX() / 25.4 );
90  }
91  else
92  {
93  context.setScaleFactor( 3.465 ); //assume 88 dpi as standard value
94  }
95  return context;
96 }
97 
98 void QgsRenderContext::setFlags( QgsRenderContext::Flags flags )
99 {
100  mFlags = flags;
101 }
102 
104 {
105  if ( on )
106  mFlags |= flag;
107  else
108  mFlags &= ~flag;
109 }
110 
111 QgsRenderContext::Flags QgsRenderContext::flags() const
112 {
113  return mFlags;
114 }
115 
117 {
118  return mFlags.testFlag( flag );
119 }
120 
122 {
123  QgsRenderContext ctx;
124  ctx.setMapToPixel( mapSettings.mapToPixel() );
125  ctx.setExtent( mapSettings.visibleExtent() );
131  ctx.setSelectionColor( mapSettings.selectionColor() );
138  ctx.setScaleFactor( mapSettings.outputDpi() / 25.4 ); // = pixels per mm
139  ctx.setRendererScale( mapSettings.scale() );
140  ctx.setExpressionContext( mapSettings.expressionContext() );
141  ctx.setSegmentationTolerance( mapSettings.segmentationTolerance() );
143  ctx.mDistanceArea.setSourceCrs( mapSettings.destinationCrs() );
144  ctx.mDistanceArea.setEllipsoid( mapSettings.ellipsoid() );
145  //this flag is only for stopping during the current rendering progress,
146  //so must be false at every new render operation
147  ctx.setRenderingStopped( false );
148 
149  return ctx;
150 }
151 
153 {
154  return mFlags.testFlag( ForceVectorOutput );
155 }
156 
158 {
159  return mFlags.testFlag( UseAdvancedEffects );
160 }
161 
163 {
164  setFlag( UseAdvancedEffects, enabled );
165 }
166 
168 {
169  return mFlags.testFlag( DrawEditingInfo );
170 }
171 
173 {
174  return mFlags.testFlag( DrawSelection );
175 }
176 
178 {
179  mCoordTransform = t;
180 }
181 
183 {
184  setFlag( DrawEditingInfo, b );
185 }
186 
188 {
189  setFlag( ForceVectorOutput, force );
190 }
191 
193 {
194  setFlag( DrawSelection, showSelection );
195 }
196 
198 {
199  return mFlags.testFlag( UseRenderingOptimization );
200 }
201 
203 {
204  setFlag( UseRenderingOptimization, enabled );
205 }
206 
208 {
209  if ( ffp )
210  {
211  mFeatureFilterProvider.reset( ffp->clone() );
212  }
213  else
214  {
215  mFeatureFilterProvider.reset( nullptr );
216  }
217 }
218 
220 {
221  return mFeatureFilterProvider.get();
222 }
223 
225 {
226  double conversionFactor = 1.0;
227  switch ( unit )
228  {
230  conversionFactor = mScaleFactor;
231  break;
232 
234  conversionFactor = mScaleFactor / POINTS_TO_MM;
235  break;
236 
238  conversionFactor = mScaleFactor * INCH_TO_MM;
239  break;
240 
242  {
243  size = convertMetersToMapUnits( size );
245  // Fall through to RenderMapUnits with size in meters converted to size in MapUnits
246  FALLTHROUGH;
247  }
249  {
250  double mup = scale.computeMapUnitsPerPixel( *this );
251  if ( mup > 0 )
252  {
253  conversionFactor = 1.0 / mup;
254  }
255  else
256  {
257  conversionFactor = 1.0;
258  }
259  break;
260  }
262  conversionFactor = 1.0;
263  break;
264 
267  //no sensible value
268  conversionFactor = 1.0;
269  break;
270  }
271 
272  double convertedSize = size * conversionFactor;
273 
274  if ( unit == QgsUnitTypes::RenderMapUnits )
275  {
276  //check max/min size
277  if ( scale.minSizeMMEnabled )
278  convertedSize = std::max( convertedSize, scale.minSizeMM * mScaleFactor );
279  if ( scale.maxSizeMMEnabled )
280  convertedSize = std::min( convertedSize, scale.maxSizeMM * mScaleFactor );
281  }
282 
283  return convertedSize;
284 }
285 
286 double QgsRenderContext::convertToMapUnits( double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale ) const
287 {
288  double mup = mMapToPixel.mapUnitsPerPixel();
289 
290  switch ( unit )
291  {
293  {
294  size = convertMetersToMapUnits( size );
295  // Fall through to RenderMapUnits with values of meters converted to MapUnits
296  FALLTHROUGH;
297  }
299  {
300  // check scale
301  double minSizeMU = -DBL_MAX;
302  if ( scale.minSizeMMEnabled )
303  {
304  minSizeMU = scale.minSizeMM * mScaleFactor * mup;
305  }
306  if ( !qgsDoubleNear( scale.minScale, 0.0 ) )
307  {
308  minSizeMU = std::max( minSizeMU, size * ( mRendererScale / scale.minScale ) );
309  }
310  size = std::max( size, minSizeMU );
311 
312  double maxSizeMU = DBL_MAX;
313  if ( scale.maxSizeMMEnabled )
314  {
315  maxSizeMU = scale.maxSizeMM * mScaleFactor * mup;
316  }
317  if ( !qgsDoubleNear( scale.maxScale, 0.0 ) )
318  {
319  maxSizeMU = std::min( maxSizeMU, size * ( mRendererScale / scale.maxScale ) );
320  }
321  size = std::min( size, maxSizeMU );
322 
323  return size;
324  }
326  {
327  return size * mScaleFactor * mup;
328  }
330  {
331  return size * mScaleFactor * mup / POINTS_TO_MM;
332  }
334  {
335  return size * mScaleFactor * mup * INCH_TO_MM;
336  }
338  {
339  return size * mup;
340  }
341 
344  //no sensible value
345  return 0.0;
346  }
347  return 0.0;
348 }
349 
350 double QgsRenderContext::convertFromMapUnits( double sizeInMapUnits, QgsUnitTypes::RenderUnit outputUnit ) const
351 {
352  double mup = mMapToPixel.mapUnitsPerPixel();
353 
354  switch ( outputUnit )
355  {
357  {
358  return sizeInMapUnits / convertMetersToMapUnits( 1.0 );
359  }
361  {
362  return sizeInMapUnits;
363  }
365  {
366  return sizeInMapUnits / ( mScaleFactor * mup );
367  }
369  {
370  return sizeInMapUnits / ( mScaleFactor * mup / POINTS_TO_MM );
371  }
373  {
374  return sizeInMapUnits / ( mScaleFactor * mup * INCH_TO_MM );
375  }
377  {
378  return sizeInMapUnits / mup;
379  }
380 
383  //no sensible value
384  return 0.0;
385  }
386  return 0.0;
387 }
388 
389 double QgsRenderContext::convertMetersToMapUnits( double meters ) const
390 {
391  switch ( mDistanceArea.sourceCrs().mapUnits() )
392  {
394  return meters;
396  {
397  QgsPointXY pointCenter = mExtent.center();
398  // The Extent is in the sourceCrs(), when different from destinationCrs()
399  // - the point must be transformed, since DistanceArea uses the destinationCrs()
400  // Note: the default QgsCoordinateTransform() : authid() will return an empty String
401  if ( !mCoordTransform.isShortCircuited() )
402  {
403  pointCenter = mCoordTransform.transform( pointCenter );
404  }
405  return mDistanceArea.measureLineProjected( pointCenter, meters );
406  }
415  return ( meters * QgsUnitTypes::fromUnitToUnitFactor( QgsUnitTypes::DistanceMeters, mDistanceArea.sourceCrs().mapUnits() ) );
416  }
417  return meters;
418 }
void setForceVectorOutput(bool force)
Meters value as Map units.
Definition: qgsunittypes.h:109
double convertToMapUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
Enable layer opacity and blending effects.
void setRenderingStopped(bool stopped)
double minSizeMM
The minimum size in millimeters, or 0.0 if unset.
Enable vector simplification and other rendering optimizations.
virtual QgsFeatureFilterProvider * clone() const =0
Create a clone of the feature filter provider.
const QgsExpressionContext & expressionContext() const
Gets the expression context.
void setFlags(QgsRenderContext::Flags flags)
Set combination of flags that will be used for rendering.
Use antialiasing while drawing.
double convertFromMapUnits(double sizeInMapUnits, QgsUnitTypes::RenderUnit outputUnit) const
Converts a size from map units to the specified units.
void setCoordinateTransform(const QgsCoordinateTransform &t)
Sets coordinate transformation.
A class to represent a 2D point.
Definition: qgspointxy.h:43
void setSimplifyHints(SimplifyHints simplifyHints)
Sets the simplification hints of the vector layer managed.
void setRendererScale(double scale)
Sets the renderer map scale.
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
double computeMapUnitsPerPixel(const QgsRenderContext &c) const
Computes a map units per pixel scaling factor, respecting the minimum and maximum scales set for the ...
Flags flags() const
Return combination of flags used for rendering.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
Percentage of another measurement (e.g., canvas size, feature size)
Definition: qgsunittypes.h:105
Enable layer opacity and blending effects.
Whether vector selections should be shown in the rendered map.
void setExtent(const QgsRectangle &extent)
QgsRectangle visibleExtent() const
Return the actual extent derived from requested extent that takes takes output image size into accoun...
bool qgsDoubleNear(double a, double b, double epsilon=4 *DBL_EPSILON)
Compare two doubles (but allow some difference)
Definition: qgis.h:227
double maxScale
The maximum scale, or 0.0 if unset.
const QgsFeatureFilterProvider * featureFilterProvider() const
Get the filter feature provider used for additional filtering of rendered features.
bool minSizeMMEnabled
Whether the minimum size in mm should be respected.
QgsCoordinateReferenceSystem destinationCrs() const
returns CRS of destination coordinate reference system
Vector graphics should not be cached and drawn as raster images.
The QgsMapSettings class contains configuration for rendering of the map.
double convertMetersToMapUnits(double meters) const
Convert meter distances to active MapUnit values for QgsUnitTypes::RenderMetersInMapUnits.
void setSelectionColor(const QColor &color)
No simplification can be applied.
QString ellipsoidAcronym() const
Returns the ellipsoid acronym for the ellipsoid used by the CRS.
void setUseAdvancedEffects(bool enabled)
Used to enable or disable advanced effects such as blend modes.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
#define FALLTHROUGH
Definition: qgis.h:512
QgsRenderContext & operator=(const QgsRenderContext &rh)
#define INCH_TO_MM
bool isShortCircuited() const
Returns true if the transform short circuits because the source and destination are equivalent...
Whether vector selections should be shown in the rendered map.
double scale() const
Returns the calculated map scale.
void setDrawEditingInformation(bool b)
Enable anti-aliasing for map rendering.
points (e.g., for font sizes)
Definition: qgsunittypes.h:107
static QgsRenderContext fromQPainter(QPainter *painter)
Creates a default render context given a pixel based QPainter destination.
bool drawEditingInformation() const
Draw bounds of symbols (for debugging/testing)
Degrees, for planar geographic CRS distance measurements.
Definition: qgsunittypes.h:51
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
Abstract interface for use by classes that filter the features of a layer.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
double mapUnitsPerPixel() const
Return current map units per pixel.
const QgsMapToPixel & mapToPixel() const
Draw bounds of symbols (for debugging/testing)
Vector graphics should not be cached and drawn as raster images.
Enable drawing of vertex markers for layers in editing mode.
QgsAbstractGeometry::SegmentationToleranceType segmentationToleranceType() const
Gets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
bool forceVectorOutput() const
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source spatial reference system.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
bool useRenderingOptimization() const
Returns true if the rendering optimization (geometry simplification) can be executed.
Draw map such that there are no problems between adjacent tiles.
Unknown distance unit.
Definition: qgsunittypes.h:54
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering...
double outputDpi() const
Return DPI used for conversion between real world units (e.g.
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering...
Contains information about the context of a rendering operation.
double convertToPainterUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to painter units (pixels).
#define POINTS_TO_MM
QString ellipsoid() const
Returns ellipsoid's acronym.
double segmentationTolerance() const
Gets the segmentation tolerance applied when rendering curved geometries.
QPainter * painter()
Returns the destination QPainter for the render operation.
double maxSizeMM
The maximum size in millimeters, or 0.0 if unset.
Struct for storing maximum and minimum scales for measurements in map units.
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
QgsPointXY transform(const QgsPointXY &point, TransformDirection direction=ForwardTransform) const
Transform the point from the source CRS to the destination CRS.
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
double measureLineProjected(const QgsPointXY &p1, double distance=1, double azimuth=M_PI_2, QgsPointXY *projectedPoint=nullptr) const
Calculates the distance from one point with distance in meters and azimuth (direction) When the sourc...
bool useAdvancedEffects() const
Returns true if advanced effects such as blend modes such be used.
void setMapToPixel(const QgsMapToPixel &mtp)
Class for doing transforms between two map coordinate systems.
void setUseRenderingOptimization(bool enabled)
bool showSelection() const
Returns true if vector selections should be shown in the rendered map.
void setFlag(Flag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
void setFeatureFilterProvider(const QgsFeatureFilterProvider *ffp)
Set a filter feature provider used for additional filtering of rendered features. ...
Enable vector simplification and other rendering optimizations.
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
void setSourceCrs(const QgsCoordinateReferenceSystem &srcCRS)
Sets source spatial reference system.
QColor selectionColor() const
Get color that is used for drawing of selected vector features.
QgsPointXY center() const
Returns the center point of the rectangle.
Definition: qgsrectangle.h:159
void setShowSelection(const bool showSelection)
Sets whether vector selections should be shown in the rendered map.
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
Terrestrial miles.
Definition: qgsunittypes.h:50
Draw map such that there are no problems between adjacent tiles.
Flag
Enumeration of flags that affect rendering operations.
static Q_INVOKABLE double fromUnitToUnitFactor(QgsUnitTypes::DistanceUnit fromUnit, QgsUnitTypes::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
Enable drawing of vertex markers for layers in editing mode.
double minScale
The minimum scale, or 0.0 if unset.
bool maxSizeMMEnabled
Whether the maximum size in mm should be respected.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:100
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.