QGIS API Documentation  3.20.0-Odense (decaadbb31)
qgspointcloudrenderer.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgspointcloudrenderer.cpp
3  --------------------
4  begin : October 2020
5  copyright : (C) 2020 by Peter Petrik
6  email : zilolv at gmail dot com
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 #include "qgspointcloudrenderer.h"
20 #include "qgsapplication.h"
21 #include "qgssymbollayerutils.h"
22 #include "qgspointcloudlayer.h"
23 #include "qgspointcloudindex.h"
25 #include "qgslogger.h"
26 #include "qgscircle.h"
27 #include <QThread>
28 #include <QPointer>
29 
30 QgsPointCloudRenderContext::QgsPointCloudRenderContext( QgsRenderContext &context, const QgsVector3D &scale, const QgsVector3D &offset, double zValueScale, double zValueFixedOffset, QgsFeedback *feedback )
31  : mRenderContext( context )
32  , mScale( scale )
33  , mOffset( offset )
34  , mZValueScale( zValueScale )
35  , mZValueFixedOffset( zValueFixedOffset )
36  , mFeedback( feedback )
37 {
38 
39 }
40 
42 {
43  return mPointsRendered;
44 }
45 
47 {
48  mPointsRendered += count;
49 }
50 
52 {
53  mAttributes = attributes;
54  mPointRecordSize = mAttributes.pointRecordSize();
55 
56  // fetch offset for x/y/z attributes
57  attributes.find( QStringLiteral( "X" ), mXOffset );
58  attributes.find( QStringLiteral( "Y" ), mYOffset );
59  attributes.find( QStringLiteral( "Z" ), mZOffset );
60 }
61 
63 {
64  if ( element.isNull() )
65  return nullptr;
66 
67  // load renderer
68  const QString rendererType = element.attribute( QStringLiteral( "type" ) );
69 
71  if ( !m )
72  return nullptr;
73 
74  std::unique_ptr< QgsPointCloudRenderer > r( m->createRenderer( element, context ) );
75  return r.release();
76 }
77 
79 {
80  return QSet< QString >();
81 }
82 
84 {
85 #ifdef QGISDEBUG
86  if ( !mThread )
87  {
88  mThread = QThread::currentThread();
89  }
90  else
91  {
92  Q_ASSERT_X( mThread == QThread::currentThread(), "QgsPointCloudRenderer::startRender", "startRender called in a different thread - use a cloned renderer instead" );
93  }
94 #endif
95 
97 
98  switch ( mPointSymbol )
99  {
100  case Square:
101  // for square point we always disable antialiasing -- it's not critical here and we benefit from the performance boost disabling it gives
102  context.renderContext().painter()->setRenderHint( QPainter::Antialiasing, false );
103  break;
104 
105  case Circle:
106  break;
107  }
108 }
109 
111 {
112 #ifdef QGISDEBUG
113  Q_ASSERT_X( mThread == QThread::currentThread(), "QgsPointCloudRenderer::stopRender", "stopRender called in a different thread - use a cloned renderer instead" );
114 #endif
115 }
116 
118 {
119  return false;
120 }
121 
122 void QgsPointCloudRenderer::checkLegendItem( const QString &, bool )
123 {
124 
125 }
126 
128 {
129  return mMaximumScreenError;
130 }
131 
133 {
134  mMaximumScreenError = error;
135 }
136 
138 {
139  return mMaximumScreenErrorUnit;
140 }
141 
143 {
144  mMaximumScreenErrorUnit = unit;
145 }
146 
147 QList<QgsLayerTreeModelLegendNode *> QgsPointCloudRenderer::createLegendNodes( QgsLayerTreeLayer * )
148 {
149  return QList<QgsLayerTreeModelLegendNode *>();
150 }
151 
153 {
154  return QStringList();
155 }
156 
158 {
159  destination->setPointSize( mPointSize );
160  destination->setPointSizeUnit( mPointSizeUnit );
161  destination->setPointSizeMapUnitScale( mPointSizeMapUnitScale );
162  destination->setMaximumScreenError( mMaximumScreenError );
163  destination->setMaximumScreenErrorUnit( mMaximumScreenErrorUnit );
164  destination->setPointSymbol( mPointSymbol );
165 }
166 
167 void QgsPointCloudRenderer::restoreCommonProperties( const QDomElement &element, const QgsReadWriteContext & )
168 {
169  mPointSize = element.attribute( QStringLiteral( "pointSize" ), QStringLiteral( "1" ) ).toDouble();
170  mPointSizeUnit = QgsUnitTypes::decodeRenderUnit( element.attribute( QStringLiteral( "pointSizeUnit" ), QStringLiteral( "MM" ) ) );
171  mPointSizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( element.attribute( QStringLiteral( "pointSizeMapUnitScale" ), QString() ) );
172 
173  mMaximumScreenError = element.attribute( QStringLiteral( "maximumScreenError" ), QStringLiteral( "0.3" ) ).toDouble();
174  mMaximumScreenErrorUnit = QgsUnitTypes::decodeRenderUnit( element.attribute( QStringLiteral( "maximumScreenErrorUnit" ), QStringLiteral( "MM" ) ) );
175  mPointSymbol = static_cast< PointSymbol >( element.attribute( QStringLiteral( "pointSymbol" ), QStringLiteral( "0" ) ).toInt() );
176 }
177 
178 void QgsPointCloudRenderer::saveCommonProperties( QDomElement &element, const QgsReadWriteContext & ) const
179 {
180  element.setAttribute( QStringLiteral( "pointSize" ), qgsDoubleToString( mPointSize ) );
181  element.setAttribute( QStringLiteral( "pointSizeUnit" ), QgsUnitTypes::encodeUnit( mPointSizeUnit ) );
182  element.setAttribute( QStringLiteral( "pointSizeMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mPointSizeMapUnitScale ) );
183 
184  element.setAttribute( QStringLiteral( "maximumScreenError" ), qgsDoubleToString( mMaximumScreenError ) );
185  element.setAttribute( QStringLiteral( "maximumScreenErrorUnit" ), QgsUnitTypes::encodeUnit( mMaximumScreenErrorUnit ) );
186  element.setAttribute( QStringLiteral( "pointSymbol" ), QString::number( mPointSymbol ) );
187 }
188 
190 {
191  return mPointSymbol;
192 }
193 
195 {
196  mPointSymbol = symbol;
197 }
198 
199 QVector<QVariantMap> QgsPointCloudRenderer::identify( QgsPointCloudLayer *layer, const QgsRenderContext &renderContext, const QgsGeometry &geometry, double toleranceForPointIdentification )
200 {
201  QVector<QVariantMap> selectedPoints;
202 
203  QgsPointCloudIndex *index = layer->dataProvider()->index();
204  const IndexedPointCloudNode root = index->root();
205 
206  const double maxErrorPixels = renderContext.convertToPainterUnits( maximumScreenError(), maximumScreenErrorUnit() );// in pixels
207 
208  const QgsRectangle rootNodeExtentLayerCoords = index->nodeMapExtent( root );
209  QgsRectangle rootNodeExtentMapCoords;
210  try
211  {
212  rootNodeExtentMapCoords = renderContext.coordinateTransform().transformBoundingBox( rootNodeExtentLayerCoords );
213  }
214  catch ( QgsCsException & )
215  {
216  QgsDebugMsg( QStringLiteral( "Could not transform node extent to map CRS" ) );
217  rootNodeExtentMapCoords = rootNodeExtentLayerCoords;
218  }
219 
220  const double rootErrorInMapCoordinates = rootNodeExtentMapCoords.width() / index->span();
221  const double rootErrorInLayerCoordinates = rootNodeExtentLayerCoords.width() / index->span();
222 
223  double mapUnitsPerPixel = renderContext.mapToPixel().mapUnitsPerPixel();
224  if ( ( rootErrorInMapCoordinates < 0.0 ) || ( mapUnitsPerPixel < 0.0 ) || ( maxErrorPixels < 0.0 ) )
225  {
226  QgsDebugMsg( QStringLiteral( "invalid screen error" ) );
227  return selectedPoints;
228  }
229 
230  const double maxErrorInMapCoordinates = maxErrorPixels * mapUnitsPerPixel;
231  const double maxErrorInLayerCoordinates = maxErrorInMapCoordinates * rootErrorInLayerCoordinates / rootErrorInMapCoordinates;
232 
233  QgsGeometry selectionGeometry = geometry;
234  if ( geometry.type() == QgsWkbTypes::PointGeometry )
235  {
236  double x = geometry.asPoint().x();
237  double y = geometry.asPoint().y();
238  const double toleranceInPixels = toleranceForPointIdentification / renderContext.mapToPixel().mapUnitsPerPixel();
239  const double pointSizePixels = renderContext.convertToPainterUnits( mPointSize, mPointSizeUnit, mPointSizeMapUnitScale );
240  switch ( pointSymbol() )
241  {
242  case QgsPointCloudRenderer::PointSymbol::Square:
243  {
244  QgsPointXY deviceCoords = renderContext.mapToPixel().transform( QgsPointXY( x, y ) );
245  QgsPointXY point1( deviceCoords.x() - std::max( toleranceInPixels, pointSizePixels / 2.0 ), deviceCoords.y() - std::max( toleranceInPixels, pointSizePixels / 2.0 ) );
246  QgsPointXY point2( deviceCoords.x() + std::max( toleranceInPixels, pointSizePixels / 2.0 ), deviceCoords.y() + std::max( toleranceInPixels, pointSizePixels / 2.0 ) );
247  QgsPointXY point1MapCoords = renderContext.mapToPixel().toMapCoordinates( point1.x(), point1.y() );
248  QgsPointXY point2MapCoords = renderContext.mapToPixel().toMapCoordinates( point2.x(), point2.y() );
249  QgsRectangle pointRect( point1MapCoords, point2MapCoords );
250  selectionGeometry = QgsGeometry::fromRect( pointRect );
251  break;
252  }
253  case QgsPointCloudRenderer::PointSymbol::Circle:
254  {
255  QgsPoint centerMapCoords( x, y );
256  QgsPointXY deviceCoords = renderContext.mapToPixel().transform( centerMapCoords );
257  QgsPoint point1( deviceCoords.x(), deviceCoords.y() - std::max( toleranceInPixels, pointSizePixels / 2.0 ) );
258  QgsPoint point2( deviceCoords.x(), deviceCoords.y() + std::max( toleranceInPixels, pointSizePixels / 2.0 ) );
259  QgsPointXY point1MapCoords = renderContext.mapToPixel().toMapCoordinates( point1.x(), point1.y() );
260  QgsPointXY point2MapCoords = renderContext.mapToPixel().toMapCoordinates( point2.x(), point2.y() );
261  QgsCircle circle = QgsCircle::from2Points( QgsPoint( point1MapCoords ), QgsPoint( point2MapCoords ) );
262  std::unique_ptr<QgsPolygon> polygon( circle.toPolygon( 6 ) );
263  QgsGeometry circleGeometry( std::move( polygon ) );
264  selectionGeometry = circleGeometry;
265  break;
266  }
267  }
268  }
269 
270  // selection geometry must be in layer CRS for QgsPointCloudDataProvider::identify
271  try
272  {
273  selectionGeometry.transform( renderContext.coordinateTransform(), QgsCoordinateTransform::ReverseTransform );
274  }
275  catch ( QgsCsException & )
276  {
277  QgsDebugMsg( QStringLiteral( "Could not transform geometry to layer CRS" ) );
278  return selectedPoints;
279  }
280 
281  selectedPoints = layer->dataProvider()->identify( maxErrorInLayerCoordinates, selectionGeometry, renderContext.zRange() );
282 
283  selectedPoints.erase( std::remove_if( selectedPoints.begin(), selectedPoints.end(), [this]( const QMap<QString, QVariant> &point ) { return !this->willRenderPoint( point ); } ), selectedPoints.end() );
284 
285  return selectedPoints;
286 }
Represents a indexed point cloud node in octree.
static QgsPointCloudRendererRegistry * pointCloudRendererRegistry()
Returns the application's point cloud renderer registry, used for managing point cloud layer 2D rende...
Circle geometry type.
Definition: qgscircle.h:44
static QgsCircle from2Points(const QgsPoint &pt1, const QgsPoint &pt2) SIP_HOLDGIL
Constructs a circle by 2 points on the circle.
Definition: qgscircle.cpp:37
@ ReverseTransform
Transform from destination to source CRS.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, TransformDirection direction=ForwardTransform, bool handle180Crossover=false) const SIP_THROW(QgsCsException)
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
virtual QgsPolygon * toPolygon(unsigned int segments=36) const
Returns a segmented polygon.
Definition: qgsellipse.cpp:224
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition: qgsfeedback.h:45
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
static QgsGeometry fromRect(const QgsRectangle &rect) SIP_HOLDGIL
Creates a new geometry from a QgsRectangle.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
QgsWkbTypes::GeometryType type
Definition: qgsgeometry.h:127
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
Layer tree node points to a map layer.
double mapUnitsPerPixel() const
Returns current map units per pixel.
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transform the point p from map (world) coordinates to device coordinates.
Definition: qgsmaptopixel.h:82
Collection of point cloud attributes.
int pointRecordSize() const
Returns total size of record.
const QgsPointCloudAttribute * find(const QString &attributeName, int &offset) const
Finds the attribute with the name.
QVector< QVariantMap > identify(double maxError, const QgsGeometry &extentGeometry, const QgsDoubleRange &extentZRange=QgsDoubleRange(), int pointsLimit=1000)
Returns the list of points of the point cloud according to a zoom level defined by maxError (in layer...
virtual QgsPointCloudIndex * index() const
Returns the point cloud index associated with the provider.
Represents a indexed point clouds data in octree.
int span() const
Returns the number of points in one direction in a single node.
QgsRectangle nodeMapExtent(const IndexedPointCloudNode &node) const
Returns the extent of a node in map coordinates.
IndexedPointCloudNode root()
Returns root node of the index.
Represents a map layer supporting display of point clouds.
QgsPointCloudDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
Encapsulates the render context for a 2D point cloud rendering operation.
void incrementPointsRendered(long count)
Increments the count of points rendered by the specified amount.
long pointsRendered() const
Returns the total number of points rendered.
QgsPointCloudAttributeCollection attributes() const
Returns the attributes associated with the rendered block.
QgsPointCloudRenderContext(QgsRenderContext &context, const QgsVector3D &scale, const QgsVector3D &offset, double zValueScale, double zValueFixedOffset, QgsFeedback *feedback=nullptr)
Constructor for QgsPointCloudRenderContext.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
void setAttributes(const QgsPointCloudAttributeCollection &attributes)
Sets the attributes associated with the rendered block.
Stores metadata about one point cloud renderer class.
virtual QgsPointCloudRenderer * createRenderer(QDomElement &elem, const QgsReadWriteContext &context)=0
Returns new instance of the renderer given the DOM element.
QgsPointCloudRendererAbstractMetadata * rendererMetadata(const QString &rendererName)
Returns the metadata for a specified renderer.
Abstract base class for 2d point cloud renderers.
const QgsMapUnitScale & pointSizeMapUnitScale() const
Returns the map unit scale used for the point size.
virtual void checkLegendItem(const QString &key, bool state=true)
Called when the check state of the legend item with the specified key is changed.
void setMaximumScreenError(double error)
Sets the maximum screen error allowed when rendering the point cloud.
void setPointSizeUnit(const QgsUnitTypes::RenderUnit units)
Sets the units used for the point size.
void restoreCommonProperties(const QDomElement &element, const QgsReadWriteContext &context)
Restores common renderer properties (such as point size and screen error) from the specified DOM elem...
PointSymbol pointSymbol() const
Returns the symbol used by the renderer for drawing points.
void saveCommonProperties(QDomElement &element, const QgsReadWriteContext &context) const
Saves common renderer properties (such as point size and screen error) to the specified DOM element.
void setPointSizeMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale used for the point size.
virtual QSet< QString > usedAttributes(const QgsPointCloudRenderContext &context) const
Returns a list of attributes required by this renderer.
virtual bool legendItemChecked(const QString &key)
Returns true if the legend item with the specified key is checked.
void setPointSize(double size)
Sets the point size.
PointSymbol
Rendering symbols for points.
@ Square
Renders points as squares.
@ Circle
Renders points as circles.
void setPointSymbol(PointSymbol symbol)
Sets the symbol used by the renderer for drawing points.
static QgsPointCloudRenderer * load(QDomElement &element, const QgsReadWriteContext &context)
Creates a renderer from an XML element.
QgsUnitTypes::RenderUnit maximumScreenErrorUnit() const
Returns the unit for the maximum screen error allowed when rendering the point cloud.
virtual QStringList legendRuleKeys() const
Returns a list of all rule keys for legend nodes created by the renderer.
QgsUnitTypes::RenderUnit pointSizeUnit() const
Returns the units used for the point size.
QVector< QVariantMap > identify(QgsPointCloudLayer *layer, const QgsRenderContext &context, const QgsGeometry &geometry, double toleranceForPointIdentification=0)
Returns the list of visible points of the point cloud layer layer and an extent defined by a geometry...
void copyCommonProperties(QgsPointCloudRenderer *destination) const
Copies common point cloud properties (such as point size and screen error) to the destination rendere...
double maximumScreenError() const
Returns the maximum screen error allowed when rendering the point cloud.
void setMaximumScreenErrorUnit(QgsUnitTypes::RenderUnit unit)
Sets the unit for the maximum screen error allowed when rendering the point cloud.
virtual void startRender(QgsPointCloudRenderContext &context)
Must be called when a new render cycle is started.
virtual void stopRender(QgsPointCloudRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
virtual QList< QgsLayerTreeModelLegendNode * > createLegendNodes(QgsLayerTreeLayer *nodeLayer)
Creates a set of legend nodes representing the renderer.
double pointSize() const
Returns the point size.
A class to represent a 2D point.
Definition: qgspointxy.h:59
double y
Definition: qgspointxy.h:63
Q_GADGET double x
Definition: qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:49
Q_GADGET double x
Definition: qgspoint.h:52
double y
Definition: qgspoint.h:53
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
Definition: qgsrectangle.h:42
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
Definition: qgsrectangle.h:223
Contains information about the context of a rendering operation.
QPainter * painter()
Returns the destination QPainter for the render operation.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QgsDoubleRange zRange() const
Returns the range of z-values which should be rendered.
double convertToPainterUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to painter units (pixels).
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
static Q_INVOKABLE QString encodeUnit(QgsUnitTypes::DistanceUnit unit)
Encodes a distance unit to a string.
static Q_INVOKABLE QgsUnitTypes::RenderUnit decodeRenderUnit(const QString &string, bool *ok=nullptr)
Decodes a render unit from a string.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:168
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition: qgis.h:550
#define QgsDebugMsg(str)
Definition: qgslogger.h:38