QGIS API Documentation 4.1.0-Master (31622b25bb0)
Loading...
Searching...
No Matches
qgspointcloudclassifiedrenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgspointcloudclassifiedrenderer.h
3 --------------------
4 begin : October 2020
5 copyright : (C) 2020 by Nyall Dawson
6 email : nyall dot dawson 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
19
20#include "qgscolorutils.h"
22#include "qgspointcloudblock.h"
24#include "qgsstyle.h"
25
26#include <QString>
27
28using namespace Qt::StringLiterals;
29
30QgsPointCloudCategory::QgsPointCloudCategory( const int value, const QColor &color, const QString &label, bool render, double pointSize )
31 : mValue( value )
32 , mColor( color )
34 , mLabel( label )
35 , mRender( render )
36{}
37
39{
40 return mValue == other.value() && mColor == other.color() && mPointSize == other.pointSize() && mLabel == other.label() && mRender == other.renderState();
41}
42
43//
44// QgsPointCloudClassifiedRenderer
45//
46
48 : mAttribute( attributeName )
49 , mCategories( categories )
50{}
51
53{
54 return u"classified"_s;
55}
56
58{
59 auto res = std::make_unique< QgsPointCloudClassifiedRenderer >();
60 res->mAttribute = mAttribute;
61 res->mCategories = mCategories;
62
63 copyCommonProperties( res.get() );
64
65 return res.release();
66}
67
69{
70 QgsRectangle visibleExtent = context.renderContext().extent();
71 if ( renderAsTriangles() )
72 {
73 // we need to include also points slightly outside of the visible extent,
74 // otherwise the triangulation may be missing triangles near the edges and corners
75 visibleExtent.grow( std::max( visibleExtent.width(), visibleExtent.height() ) * 0.05 );
76 }
77
78 const char *ptr = block->data();
79 int count = block->pointCount();
80 const QgsPointCloudAttributeCollection request = block->attributes();
81
82 const std::size_t recordSize = request.pointRecordSize();
83 int attributeOffset = 0;
84 const QgsPointCloudAttribute *attribute = request.find( mAttribute, attributeOffset );
85 if ( !attribute )
86 return;
87 const QgsPointCloudAttribute::DataType attributeType = attribute->type();
88
89 const bool renderElevation = context.renderContext().elevationMap();
90 const QgsDoubleRange zRange = context.renderContext().zRange();
91 const bool considerZ = !zRange.isInfinite() || renderElevation;
92
93 int rendered = 0;
94 double x = 0;
95 double y = 0;
96 double z = 0;
98 const bool reproject = ct.isValid();
99
100 QHash< int, QColor > colors;
101 QHash< int, int > pointSizes;
102
103 bool dataDefinedPropertiesActive = dataDefinedProperties().isActive( QgsPointCloudRenderer::Property::Color );
104 for ( const QgsPointCloudCategory &category : std::as_const( mCategories ) )
105 {
106 if ( !category.renderState() )
107 continue;
108
109 colors.insert( category.value(), category.color() );
110
111 const double size = category.pointSize() > 0 ? category.pointSize() : pointSize();
112 pointSizes.insert( category.value(), context.renderContext().convertToPainterUnits( size, pointSizeUnit(), pointSizeMapUnitScale() ) );
113 }
114
115 for ( int i = 0; i < count; ++i )
116 {
117 if ( context.renderContext().renderingStopped() )
118 {
119 break;
120 }
121
122 // z value filtering is cheapest, if we're doing it...
123 if ( considerZ )
124 {
125 z = pointZ( context, ptr, i );
126 if ( !zRange.contains( z ) )
127 continue;
128 }
129
130 int attributeValue = 0;
131 context.getAttribute( ptr, i * recordSize + attributeOffset, attributeType, attributeValue );
132 QColor color = colors.value( attributeValue );
133 if ( !color.isValid() )
134 continue;
135
136 if ( dataDefinedPropertiesActive )
137 color = colorFromExpression( block, i, color, context );
138
139 pointXY( context, ptr, i, x, y );
140 if ( visibleExtent.contains( x, y ) )
141 {
142 if ( reproject )
143 {
144 try
145 {
146 ct.transformInPlace( x, y, z );
147 }
148 catch ( QgsCsException & )
149 {
150 continue;
151 }
152 }
153
154 if ( renderAsTriangles() )
155 {
156 addPointToTriangulation( x, y, z, color, context );
157
158 // We don't want to render any points if we're rendering triangles and there is no preview painter
159 if ( !context.renderContext().previewRenderPainter() )
160 continue;
161 }
162
163 const double size = pointSizes.value( attributeValue );
164 drawPoint( x, y, color, size, context );
165 if ( renderElevation )
166 drawPointToElevationMap( x, y, z, size, context );
167
168 rendered++;
169 }
170 }
171 context.incrementPointsRendered( rendered );
172}
173
174bool QgsPointCloudClassifiedRenderer::willRenderPoint( const QVariantMap &pointAttributes )
175{
176 if ( !pointAttributes.contains( mAttribute ) )
177 return false;
178 bool parsedCorrectly;
179 int attributeInt = pointAttributes[mAttribute].toInt( &parsedCorrectly );
180 if ( !parsedCorrectly )
181 return false;
182 for ( const QgsPointCloudCategory &category : std::as_const( mCategories ) )
183 {
184 if ( category.value() == attributeInt )
185 return category.renderState();
186 }
187 return false;
188}
189
191{
192 auto r = std::make_unique< QgsPointCloudClassifiedRenderer >();
193
194 r->setAttribute( element.attribute( u"attribute"_s, u"Classification"_s ) );
195
197 const QDomElement catsElem = element.firstChildElement( u"categories"_s );
198 if ( !catsElem.isNull() )
199 {
200 QDomElement catElem = catsElem.firstChildElement();
201 while ( !catElem.isNull() )
202 {
203 if ( catElem.tagName() == "category"_L1 )
204 {
205 const int value = catElem.attribute( u"value"_s ).toInt();
206 const double size = catElem.attribute( u"pointSize"_s, u"0"_s ).toDouble();
207 const QString label = context.projectTranslator()->translate( u"project:layers:%1:legendsymbollabels"_s.arg( context.currentLayerId() ), catElem.attribute( u"label"_s ) );
208 QgsDebugMsgLevel( "context" + u"project:layers:%1:legendsymbollabels"_s.arg( context.currentLayerId() ) + " source " + catElem.attribute( u"label"_s ), 3 );
209
210 const bool render = catElem.attribute( u"render"_s ) != "false"_L1;
211 const QColor color = QgsColorUtils::colorFromString( catElem.attribute( u"color"_s ) );
212 categories.append( QgsPointCloudCategory( value, color, label, render, size ) );
213 }
214 catElem = catElem.nextSiblingElement();
215 }
216 r->setCategories( categories );
217 }
218
219 r->restoreCommonProperties( element, context );
220
221 return r.release();
222}
223
225{
246}
247
248QDomElement QgsPointCloudClassifiedRenderer::save( QDomDocument &doc, const QgsReadWriteContext &context ) const
249{
250 QDomElement rendererElem = doc.createElement( u"renderer"_s );
251
252 rendererElem.setAttribute( u"type"_s, u"classified"_s );
253 rendererElem.setAttribute( u"attribute"_s, mAttribute );
254
255 // categories
256 QDomElement catsElem = doc.createElement( u"categories"_s );
257 for ( const QgsPointCloudCategory &category : mCategories )
258 {
259 QDomElement catElem = doc.createElement( u"category"_s );
260 catElem.setAttribute( u"value"_s, QString::number( category.value() ) );
261 catElem.setAttribute( u"pointSize"_s, QString::number( category.pointSize() ) );
262 catElem.setAttribute( u"label"_s, category.label() );
263 catElem.setAttribute( u"color"_s, QgsColorUtils::colorToString( category.color() ) );
264 catElem.setAttribute( u"render"_s, category.renderState() ? "true" : "false" );
265 catsElem.appendChild( catElem );
266 }
267 rendererElem.appendChild( catsElem );
268
269 saveCommonProperties( rendererElem, context );
270
271 return rendererElem;
272}
273
275{
276 QSet<QString> res = QgsPointCloudRenderer::usedAttributes( context );
277 res << mAttribute;
278 return res;
279}
280
281QList<QgsLayerTreeModelLegendNode *> QgsPointCloudClassifiedRenderer::createLegendNodes( QgsLayerTreeLayer *nodeLayer )
282{
283 QList<QgsLayerTreeModelLegendNode *> nodes;
284
285 for ( const QgsPointCloudCategory &category : std::as_const( mCategories ) )
286 {
287 nodes << new QgsRasterSymbolLegendNode( nodeLayer, category.color(), category.label(), nullptr, true, QString::number( category.value() ) );
288 }
289
290 return nodes;
291}
292
294{
295 QStringList res;
296 for ( const QgsPointCloudCategory &category : std::as_const( mCategories ) )
297 {
298 res << QString::number( category.value() );
299 }
300 return res;
301}
302
304{
305 bool ok = false;
306 const int value = key.toInt( &ok );
307 if ( !ok )
308 return false;
309
310 for ( const QgsPointCloudCategory &category : std::as_const( mCategories ) )
311 {
312 if ( category.value() == value )
313 return category.renderState();
314 }
315 return false;
316}
317
318void QgsPointCloudClassifiedRenderer::checkLegendItem( const QString &key, bool state )
319{
320 bool ok = false;
321 const int value = key.toInt( &ok );
322 if ( !ok )
323 return;
324
325 for ( auto it = mCategories.begin(); it != mCategories.end(); ++it )
326 {
327 if ( it->value() == value )
328 {
329 it->setRenderState( state );
330 return;
331 }
332 }
333}
334
336{
337 return mAttribute;
338}
339
341{
342 mAttribute = attribute;
343}
344
349
354
356{
357 mCategories.append( category );
358}
359
360std::unique_ptr<QgsPreparedPointCloudRendererData> QgsPointCloudClassifiedRenderer::prepare()
361{
362 auto data = std::make_unique< QgsPointCloudClassifiedRendererPreparedData >();
363 data->attributeName = mAttribute;
364
365 for ( const QgsPointCloudCategory &category : std::as_const( mCategories ) )
366 {
367 if ( !category.renderState() )
368 continue;
369
370 data->colors.insert( category.value(), category.color() );
371 }
372
373 return data;
374}
375
380
382{
383 const QgsPointCloudAttributeCollection attributes = block->attributes();
384 const QgsPointCloudAttribute *attribute = attributes.find( attributeName, attributeOffset );
385 if ( !attribute )
386 return false;
387
388 attributeType = attribute->type();
389 return true;
390}
391
393{
394 int attributeValue = 0;
396 return colors.value( attributeValue );
397}
static QColor colorFromString(const QString &string)
Decodes a string into a color value.
static QString colorToString(const QColor &color)
Encodes a color into a string value.
Handles coordinate transforms between two coordinate systems.
void transformInPlace(double &x, double &y, double &z, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transforms an array of x, y and z double coordinates in place, from the source CRS to the destination...
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
Custom exception class for Coordinate Reference System related exceptions.
QgsRange which stores a range of double values.
Definition qgsrange.h:217
bool isInfinite() const
Returns true if the range consists of all possible values.
Definition qgsrange.h:266
Layer tree node points to a map layer.
A 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.
Attribute for point cloud data pair of name and size in bytes.
DataType
Systems of unit measurement.
DataType type() const
Returns the data type.
Base class for storing raw data from point cloud nodes.
const char * data() const
Returns raw pointer to data.
QgsPointCloudAttributeCollection attributes() const
Returns the attributes that are stored in the data block, along with their size.
int pointCount() const
Returns number of points that are stored in the block.
int pointRecordSize() const
Returns the total size of each individual point record.
Represents an individual category (class) from a QgsPointCloudClassifiedRenderer.
QgsPointCloudCategory()=default
int value() const
Returns the value corresponding to this category.
bool renderState() const
Returns true if the category is currently enabled and should be rendered.
QColor color() const
Returns the color which will be used to render this category.
double pointSize() const
Returns the point size for this category.
bool operator==(const QgsPointCloudCategory &other) const
Equality operator.
QString label() const
Returns the label for this category, which is used to represent the category within legends and the l...
QColor pointColor(const QgsPointCloudBlock *block, int i, double z) override
An optimised method of retrieving the color of a point from a point cloud block.
QSet< QString > usedAttributes() const override
Returns the set of attributes used by the prepared point cloud renderer.
bool prepareBlock(const QgsPointCloudBlock *block) override
Prepares the renderer for using the specified block.
void addCategory(const QgsPointCloudCategory &category)
Adds a category to the renderer.
QString attribute() const
Returns the attribute to use for the renderer.
QgsPointCloudClassifiedRenderer(const QString &attributeName=QString(), const QgsPointCloudCategoryList &categories=QgsPointCloudCategoryList())
Constructor for QgsPointCloudClassifiedRenderer.
bool willRenderPoint(const QVariantMap &pointAttributes) override
QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context) const override
Saves the renderer configuration to an XML element.
void checkLegendItem(const QString &key, bool state=true) override
Called when the check state of the legend item with the specified key is changed.
QSet< QString > usedAttributes(const QgsPointCloudRenderContext &context) const override
Returns a list of attributes required by this renderer.
static QgsPointCloudRenderer * create(QDomElement &element, const QgsReadWriteContext &context)
Creates an RGB renderer from an XML element.
QgsPointCloudCategoryList categories() const
Returns the classification categories used for rendering.
static QgsPointCloudCategoryList defaultCategories()
Returns the default list of categories.
bool legendItemChecked(const QString &key) override
Returns true if the legend item with the specified key is checked.
QgsPointCloudRenderer * clone() const override
Create a deep copy of this renderer.
void setCategories(const QgsPointCloudCategoryList &categories)
Sets the classification categories used for rendering.
QList< QgsLayerTreeModelLegendNode * > createLegendNodes(QgsLayerTreeLayer *nodeLayer) override
Creates a set of legend nodes representing the renderer.
void renderBlock(const QgsPointCloudBlock *block, QgsPointCloudRenderContext &context) override
Renders a block of point cloud data using the specified render context.
std::unique_ptr< QgsPreparedPointCloudRendererData > prepare() override
Returns prepared data container for bulk point color retrieval.
QStringList legendRuleKeys() const override
Returns a list of all rule keys for legend nodes created by the renderer.
void setAttribute(const QString &attribute)
Sets the attribute to use for the renderer.
QString type() const override
Returns the identifier of the renderer type.
static QMap< int, QString > translatedLasClassificationCodes()
Returns the map of LAS classification code to translated string value, corresponding to the ASPRS Sta...
Encapsulates the render context for a 2D point cloud rendering operation.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
void incrementPointsRendered(long count)
Increments the count of points rendered by the specified amount.
static void getAttribute(const char *data, std::size_t offset, QgsPointCloudAttribute::DataType type, T &value)
Retrieves the attribute value from data at the specified offset, where type indicates the original da...
bool renderAsTriangles() const
Returns whether points are triangulated to render solid surface.
void drawPointToElevationMap(double x, double y, double z, QgsPointCloudRenderContext &context) const
Draws a point at the elevation z using at the specified x and y (in map coordinates) on the elevation...
void saveCommonProperties(QDomElement &element, const QgsReadWriteContext &context) const
Saves common renderer properties (such as point size and screen error) to the specified DOM element.
const QgsMapUnitScale & pointSizeMapUnitScale() const
Returns the map unit scale used for the point size.
QColor colorFromExpression(const QgsPointCloudBlock *block, int pointIndex, const QColor &rendererColor, QgsPointCloudRenderContext &context)
Computes color from the expression set, uses expression referenced variables and renderer base color.
virtual QSet< QString > usedAttributes(const QgsPointCloudRenderContext &context) const
Returns a list of attributes required by this renderer.
void addPointToTriangulation(double x, double y, double z, const QColor &color, QgsPointCloudRenderContext &context)
Adds a point to the list of points to be triangulated (only used when renderAsTriangles() is enabled)...
void copyCommonProperties(QgsPointCloudRenderer *destination) const
Copies common point cloud properties (such as point size and screen error) to the destination rendere...
void drawPoint(double x, double y, const QColor &color, QgsPointCloudRenderContext &context) const
Draws a point using a color at the specified x and y (in map coordinates).
const QgsPropertyCollection & dataDefinedProperties() const
Returns the renderer's property collection, used for data defined overrides.
Qgis::RenderUnit pointSizeUnit() const
Returns the units used for the point size.
double pointSize() const
Returns the point size.
static double pointZ(QgsPointCloudRenderContext &context, const char *ptr, int i)
Retrieves the z value for the point at index i.
static void pointXY(QgsPointCloudRenderContext &context, const char *ptr, int i, double &x, double &y)
Retrieves the x and y coordinate for the point at index i.
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
Translates a string using the Qt QTranslator mechanism.
bool isActive(int key) const final
Returns true if the collection contains an active property with the specified key.
bool contains(const QgsRange< T > &other) const
Returns true if this range contains another range.
Definition qgsrange.h:138
Implementation of legend node interface for displaying raster legend entries.
A container for the context for various read/write operations on objects.
const QgsProjectTranslator * projectTranslator() const
Returns the project translator.
const QString currentLayerId() const
Returns the currently used layer id as string.
A rectangle specified with double values.
bool contains(const QgsRectangle &rect) const
Returns true when rectangle contains other rectangle.
void grow(double delta)
Grows the rectangle in place by the specified amount.
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
QgsElevationMap * elevationMap() const
Returns the destination elevation map for the render operation.
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
QgsDoubleRange zRange() const
Returns the range of z-values which should be rendered.
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
QPainter * previewRenderPainter()
Returns the const destination QPainter for temporary in-progress preview renders.
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
QList< QgsPointCloudCategory > QgsPointCloudCategoryList