QGIS API Documentation 3.99.0-Master (d270888f95f)
Loading...
Searching...
No Matches
qgspointcloudlayerrenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgspointcloudlayerrenderer.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
19
20#include <memory>
21
22#include "delaunator.hpp"
23#include "qgsapplication.h"
24#include "qgscolorramp.h"
25#include "qgselevationmap.h"
26#include "qgslogger.h"
27#include "qgsmapclippingutils.h"
28#include "qgsmeshlayerutils.h"
29#include "qgsmessagelog.h"
33#include "qgspointcloudindex.h"
34#include "qgspointcloudlayer.h"
38#include "qgsrendercontext.h"
39#include "qgsruntimeprofiler.h"
40#include "qgsthreadingutils.h"
41#include "qgsvirtualpointcloudprovider.h"
42
43#include <QElapsedTimer>
44#include <QPointer>
45#include <QString>
46
47using namespace Qt::StringLiterals;
48
50 : QgsMapLayerRenderer( layer->id(), &context )
51 , mLayerName( layer->name() )
52 , mLayerAttributes( layer->attributes() )
53 , mSubIndexes( layer->dataProvider() ? layer->dataProvider()->subIndexes() : QVector<QgsPointCloudSubIndex>() )
54 , mFeedback( new QgsFeedback )
55 , mEnableProfile( context.flags() & Qgis::RenderContextFlag::RecordProfile )
56{
57 if ( !layer->dataProvider() || !layer->renderer() )
58 return;
59
60 mIndex = layer->index();
61
62 QElapsedTimer timer;
63 timer.start();
64
65 mRenderer.reset( layer->renderer()->clone() );
66 if ( !mSubIndexes.isEmpty() )
67 {
68 mSubIndexExtentRenderer = std::make_unique<QgsPointCloudExtentRenderer>( );
69 mSubIndexExtentRenderer->setShowLabels( mRenderer->showLabels() );
70 mSubIndexExtentRenderer->setLabelTextFormat( mRenderer->labelTextFormat() );
71 }
72
73 if ( mIndex )
74 {
75 mScale = mIndex.scale();
76 mOffset = mIndex.offset();
77 }
78
79 if ( const QgsPointCloudLayerElevationProperties *elevationProps = qobject_cast< const QgsPointCloudLayerElevationProperties * >( layer->elevationProperties() ) )
80 {
81 mZOffset = elevationProps->zOffset();
82 mZScale = elevationProps->zScale();
83 }
84
85 if ( const QgsVirtualPointCloudProvider *vpcProvider = dynamic_cast<QgsVirtualPointCloudProvider *>( layer->dataProvider() ) )
86 {
87 mIsVpc = true;
88 mAverageSubIndexWidth = vpcProvider->averageSubIndexWidth();
89 mAverageSubIndexHeight = vpcProvider->averageSubIndexHeight();
90 mOverviewIndex = vpcProvider->overview();
91 }
92
93 mCloudExtent = layer->dataProvider()->polygonBounds();
94
96
97 mReadyToCompose = false;
98
99 mPreparationTime = timer.elapsed();
100}
101
103{
104 QgsScopedThreadName threadName( u"render:%1"_s.arg( mLayerName ) );
105
106 std::unique_ptr< QgsScopedRuntimeProfile > profile;
107 if ( mEnableProfile )
108 {
109 profile = std::make_unique< QgsScopedRuntimeProfile >( mLayerName, u"rendering"_s, layerId() );
110 if ( mPreparationTime > 0 )
111 QgsApplication::profiler()->record( QObject::tr( "Create renderer" ), mPreparationTime / 1000.0, u"rendering"_s );
112 }
113
114 std::unique_ptr< QgsScopedRuntimeProfile > preparingProfile;
115 if ( mEnableProfile )
116 {
117 preparingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Preparing render" ), u"rendering"_s );
118 }
119
120 QgsPointCloudRenderContext context( *renderContext(), mScale, mOffset, mZScale, mZOffset, mFeedback.get() );
121
122 // Set up the render configuration options
123 QPainter *painter = context.renderContext().painter();
124
125 QgsScopedQPainterState painterState( painter );
126 context.renderContext().setPainterFlagsUsingContext( painter );
127
128 if ( !mClippingRegions.empty() )
129 {
130 bool needsPainterClipPath = false;
131 const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, *renderContext(), Qgis::LayerType::VectorTile, needsPainterClipPath );
132 if ( needsPainterClipPath )
133 renderContext()->painter()->setClipPath( path, Qt::IntersectClip );
134 }
135
136 if ( mRenderer->type() == "extent"_L1 )
137 {
138 // special case for extent only renderer!
139 mRenderer->startRender( context );
140 static_cast< QgsPointCloudExtentRenderer * >( mRenderer.get() )->renderExtent( mCloudExtent, context );
141 mRenderer->stopRender( context );
142 mReadyToCompose = true;
143 return true;
144 }
145
146 if ( mSubIndexes.isEmpty() && ( !mIndex || !mIndex.isValid() ) )
147 {
148 mReadyToCompose = true;
149 return false;
150 }
151
152 // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
153 // cached version of the layer during rendering instead of the usual progressive updates
154 if ( mRenderTimeHint > 0 && mRenderTimeHint <= MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
155 {
156 mBlockRenderUpdates = true;
157 mElapsedTimer.start();
158 }
159
160 mRenderer->startRender( context );
161
162 mAttributes.push_back( QgsPointCloudAttribute( u"X"_s, QgsPointCloudAttribute::Int32 ) );
163 mAttributes.push_back( QgsPointCloudAttribute( u"Y"_s, QgsPointCloudAttribute::Int32 ) );
164
165 if ( !context.renderContext().zRange().isInfinite() ||
166 mRenderer->drawOrder2d() == Qgis::PointCloudDrawOrder::BottomToTop ||
167 mRenderer->drawOrder2d() == Qgis::PointCloudDrawOrder::TopToBottom ||
168 renderContext()->elevationMap() )
169 mAttributes.push_back( QgsPointCloudAttribute( u"Z"_s, QgsPointCloudAttribute::Int32 ) );
170
171 // collect attributes required by renderer
172 QSet< QString > rendererAttributes = mRenderer->usedAttributes( context );
173
174
175 for ( const QString &attribute : std::as_const( rendererAttributes ) )
176 {
177 if ( mAttributes.indexOf( attribute ) >= 0 )
178 continue; // don't re-add attributes we are already going to fetch
179
180 const int layerIndex = mLayerAttributes.indexOf( attribute );
181 if ( layerIndex < 0 )
182 {
183 QgsMessageLog::logMessage( QObject::tr( "Required attribute %1 not found in layer" ).arg( attribute ), QObject::tr( "Point Cloud" ) );
184 continue;
185 }
186
187 mAttributes.push_back( mLayerAttributes.at( layerIndex ) );
188 }
189
190 QgsRectangle renderExtent;
191 try
192 {
194 }
195 catch ( QgsCsException & )
196 {
197 QgsDebugError( u"Transformation of extent failed!"_s );
198 }
199
200 preparingProfile.reset();
201 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
202 if ( mEnableProfile )
203 {
204 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering" ), u"rendering"_s );
205 }
206
207 bool canceled = false;
208 if ( mSubIndexes.isEmpty() )
209 {
210 canceled = !renderIndex( mIndex );
211 }
212 else if ( mIsVpc )
213 {
214 QVector< QgsPointCloudSubIndex > visibleIndexes;
215 for ( const QgsPointCloudSubIndex &si : mSubIndexes )
216 {
217 if ( renderExtent.intersects( si.extent() ) )
218 {
219 visibleIndexes.append( si );
220 }
221 }
222 const bool zoomedOut = renderExtent.width() > mAverageSubIndexWidth ||
223 renderExtent.height() > mAverageSubIndexHeight;
224 // if the overview of virtual point cloud exists, and we are zoomed out, we render just overview
225 if ( mOverviewIndex && mOverviewIndex->isValid() && zoomedOut &&
226 mRenderer->zoomOutBehavior() == Qgis::PointCloudZoomOutRenderBehavior::RenderOverview )
227 {
228 renderIndex( *mOverviewIndex );
229 }
230 else
231 {
232 // if the overview of virtual point cloud exists, and we are zoomed out, but we want both overview and extents,
233 // we render overview
234 if ( mOverviewIndex && mOverviewIndex->isValid() && zoomedOut &&
236 {
237 renderIndex( *mOverviewIndex );
238 }
239 mSubIndexExtentRenderer->startRender( context );
240 for ( const QgsPointCloudSubIndex &si : visibleIndexes )
241 {
242 if ( canceled )
243 break;
244
245 QgsPointCloudIndex pc = si.index();
246 // if the index of point cloud is invalid, or we are zoomed out and want extents, we render the point cloud extent
247 if ( !pc || !pc.isValid() || ( ( mRenderer->zoomOutBehavior() == Qgis::PointCloudZoomOutRenderBehavior::RenderExtents || mRenderer->zoomOutBehavior() == Qgis::PointCloudZoomOutRenderBehavior::RenderOverviewAndExtents ) &&
248 zoomedOut ) )
249 {
250 mSubIndexExtentRenderer->renderExtent( si.polygonBounds(), context );
251 if ( mSubIndexExtentRenderer->showLabels() )
252 {
253 mSubIndexExtentRenderer->renderLabel(
254 context.renderContext().mapToPixel().transformBounds( si.extent().toRectF() ),
255 si.uri().section( "/", -1 ).section( ".", 0, 0 ),
256 context );
257 }
258 }
259 // else we just render the visible point cloud
260 else
261 {
262 canceled = !renderIndex( pc );
263 }
264 }
265 mSubIndexExtentRenderer->stopRender( context );
266 }
267 }
268
269 mRenderer->stopRender( context );
270 mReadyToCompose = true;
271 return !canceled;
272}
273
274bool QgsPointCloudLayerRenderer::renderIndex( QgsPointCloudIndex &pc )
275{
277 pc.scale(),
278 pc.offset(),
279 mZScale,
280 mZOffset,
281 mFeedback.get() );
282
283
284#ifdef QGISDEBUG
285 QElapsedTimer t;
286 t.start();
287#endif
288
289 const QgsPointCloudNodeId root = pc.root();
290
291 const double maximumError = context.renderContext().convertToPainterUnits( mRenderer->maximumScreenError(), mRenderer->maximumScreenErrorUnit() );// in pixels
292
293 const QgsPointCloudNode rootNode = pc.getNode( root );
294 const QgsRectangle rootNodeExtentLayerCoords = pc.extent();
295 QgsRectangle rootNodeExtentMapCoords;
296 if ( !context.renderContext().coordinateTransform().isShortCircuited() )
297 {
298 try
299 {
300 QgsCoordinateTransform extentTransform = context.renderContext().coordinateTransform();
301 extentTransform.setBallparkTransformsAreAppropriate( true );
302 rootNodeExtentMapCoords = extentTransform.transformBoundingBox( rootNodeExtentLayerCoords );
303 }
304 catch ( QgsCsException & )
305 {
306 QgsDebugError( u"Could not transform node extent to map CRS"_s );
307 rootNodeExtentMapCoords = rootNodeExtentLayerCoords;
308 }
309 }
310 else
311 {
312 rootNodeExtentMapCoords = rootNodeExtentLayerCoords;
313 }
314
315 const double rootErrorInMapCoordinates = rootNodeExtentMapCoords.width() / pc.span(); // in map coords
316
317 double mapUnitsPerPixel = context.renderContext().mapToPixel().mapUnitsPerPixel();
318 if ( ( rootErrorInMapCoordinates < 0.0 ) || ( mapUnitsPerPixel < 0.0 ) || ( maximumError < 0.0 ) )
319 {
320 QgsDebugError( u"invalid screen error"_s );
321 return false;
322 }
323 double rootErrorPixels = rootErrorInMapCoordinates / mapUnitsPerPixel; // in pixels
324 const QVector<QgsPointCloudNodeId> nodes = traverseTree( pc, context.renderContext(), pc.root(), maximumError, rootErrorPixels );
325
326 QgsPointCloudRequest request;
327 request.setAttributes( mAttributes );
328
329 // drawing
330 int nodesDrawn = 0;
331 bool canceled = false;
332
333 Qgis::PointCloudDrawOrder drawOrder = mRenderer->drawOrder2d();
334 if ( mRenderer->renderAsTriangles() )
335 {
336 // Ordered rendering is ignored when drawing as surface, because all points are used for triangulation.
337 // We would need to have a way to detect if a point is occluded by some other points, which may be costly.
339 }
340
341 switch ( drawOrder )
342 {
345 {
346 nodesDrawn += renderNodesSorted( nodes, pc, context, request, canceled, mRenderer->drawOrder2d() );
347 break;
348 }
350 {
351 switch ( pc.accessType() )
352 {
354 {
355 nodesDrawn += renderNodesSync( nodes, pc, context, request, canceled );
356 break;
357 }
359 {
360 nodesDrawn += renderNodesAsync( nodes, pc, context, request, canceled );
361 break;
362 }
363 }
364 }
365 }
366
367#ifdef QGISDEBUG
368 QgsDebugMsgLevel( u"totals: %1 nodes | %2 points | %3ms"_s.arg( nodesDrawn )
369 .arg( context.pointsRendered() )
370 .arg( t.elapsed() ), 2 );
371#else
372 ( void )nodesDrawn;
373#endif
374
375 return !canceled;
376}
377
378int QgsPointCloudLayerRenderer::renderNodesSync( const QVector<QgsPointCloudNodeId> &nodes, QgsPointCloudIndex &pc, QgsPointCloudRenderContext &context, QgsPointCloudRequest &request, bool &canceled )
379{
380 QPainter *finalPainter = context.renderContext().painter();
381 if ( mRenderer->renderAsTriangles() && context.renderContext().previewRenderPainter() )
382 {
383 // swap out the destination painter for the preview render painter to render points
384 // until the actual triangles are ready to be rendered
386 }
387
388 int nodesDrawn = 0;
389 for ( const QgsPointCloudNodeId &n : nodes )
390 {
391 if ( context.renderContext().renderingStopped() )
392 {
393 QgsDebugMsgLevel( u"canceled"_s, 2 );
394 canceled = true;
395 break;
396 }
397 std::unique_ptr<QgsPointCloudBlock> block( pc.nodeData( n, request ) );
398
399 if ( !block )
400 continue;
401
402 QgsVector3D contextScale = context.scale();
403 QgsVector3D contextOffset = context.offset();
404
405 context.setScale( block->scale() );
406 context.setOffset( block->offset() );
407
408 context.setAttributes( block->attributes() );
409
410 mRenderer->renderBlock( block.get(), context );
411
412 context.setScale( contextScale );
413 context.setOffset( contextOffset );
414
415 ++nodesDrawn;
416
417 // as soon as first block is rendered, we can start showing layer updates.
418 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
419 // at most e.g. 3 seconds before we start forcing progressive updates.
420 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
421 {
422 mReadyToCompose = true;
423 }
424 }
425
426 if ( mRenderer->renderAsTriangles() )
427 {
428 // Switch back from the preview painter to the destination painter to render the triangles
429 context.renderContext().setPainter( finalPainter );
430 renderTriangulatedSurface( context );
431 }
432
433 return nodesDrawn;
434}
435
436int QgsPointCloudLayerRenderer::renderNodesAsync( const QVector<QgsPointCloudNodeId> &nodes, QgsPointCloudIndex &pc, QgsPointCloudRenderContext &context, QgsPointCloudRequest &request, bool &canceled )
437{
438 if ( nodes.isEmpty() )
439 return 0;
440
441 if ( context.feedback() && context.feedback()->isCanceled() )
442 return 0;
443
444 QPainter *finalPainter = context.renderContext().painter();
445 if ( mRenderer->renderAsTriangles() && context.renderContext().previewRenderPainter() )
446 {
447 // swap out the destination painter for the preview render painter to render points
448 // until the actual triangles are ready to be rendered
450 }
451
452 int nodesDrawn = 0;
453
454 // Async loading of nodes
455 QVector<QgsPointCloudBlockRequest *> blockRequests;
456 QEventLoop loop;
457 if ( context.feedback() )
458 QObject::connect( context.feedback(), &QgsFeedback::canceled, &loop, &QEventLoop::quit );
459
460 for ( int i = 0; i < nodes.size(); ++i )
461 {
462 const QgsPointCloudNodeId &n = nodes[i];
463 const QString nStr = n.toString();
464 QgsPointCloudBlockRequest *blockRequest = pc.asyncNodeData( n, request );
465 blockRequests.append( blockRequest );
466 QObject::connect( blockRequest, &QgsPointCloudBlockRequest::finished, &loop,
467 [ this, &canceled, &nodesDrawn, &loop, &blockRequests, &context, nStr, blockRequest ]()
468 {
469 blockRequests.removeOne( blockRequest );
470
471 // If all blocks are loaded, exit the event loop
472 if ( blockRequests.isEmpty() )
473 loop.exit();
474
475 std::unique_ptr<QgsPointCloudBlock> block( blockRequest->takeBlock() );
476
477 blockRequest->deleteLater();
478
479 if ( context.feedback() && context.feedback()->isCanceled() )
480 {
481 canceled = true;
482 return;
483 }
484
485 if ( !block )
486 {
487 QgsDebugError( u"Unable to load node %1, error: %2"_s.arg( nStr, blockRequest->errorStr() ) );
488 return;
489 }
490
491 QgsVector3D contextScale = context.scale();
492 QgsVector3D contextOffset = context.offset();
493
494 context.setScale( block->scale() );
495 context.setOffset( block->offset() );
496 context.setAttributes( block->attributes() );
497
498 mRenderer->renderBlock( block.get(), context );
499
500 context.setScale( contextScale );
501 context.setOffset( contextOffset );
502
503 ++nodesDrawn;
504
505 // as soon as first block is rendered, we can start showing layer updates.
506 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
507 // at most e.g. 3 seconds before we start forcing progressive updates.
508 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
509 {
510 mReadyToCompose = true;
511 }
512
513 } );
514 }
515
516 // Wait for all point cloud nodes to finish loading
517 if ( !blockRequests.isEmpty() )
518 loop.exec();
519
520 // Rendering may have got canceled and the event loop exited before finished()
521 // was called for all blocks, so let's clean up anything that is left
522 for ( QgsPointCloudBlockRequest *blockRequest : std::as_const( blockRequests ) )
523 {
524 std::unique_ptr<QgsPointCloudBlock> block = blockRequest->takeBlock();
525 block.reset();
526
527 blockRequest->deleteLater();
528 }
529
530 if ( mRenderer->renderAsTriangles() )
531 {
532 // Switch back from the preview painter to the destination painter to render the triangles
533 context.renderContext().setPainter( finalPainter );
534 renderTriangulatedSurface( context );
535 }
536
537 return nodesDrawn;
538}
539
540int QgsPointCloudLayerRenderer::renderNodesSorted( const QVector<QgsPointCloudNodeId> &nodes, QgsPointCloudIndex &pc, QgsPointCloudRenderContext &context, QgsPointCloudRequest &request, bool &canceled, Qgis::PointCloudDrawOrder order )
541{
542 int blockCount = 0;
543 int pointCount = 0;
544
545 QgsVector3D blockScale;
546 QgsVector3D blockOffset;
547 QgsPointCloudAttributeCollection blockAttributes;
548 int recordSize = 0;
549
550 // We'll collect byte array data from all blocks
551 QByteArray allByteArrays;
552 // And pairs of byte array start positions paired with their Z values for sorting
553 QVector<QPair<int, double>> allPairs;
554
555 for ( const QgsPointCloudNodeId &n : nodes )
556 {
557 if ( context.renderContext().renderingStopped() )
558 {
559 QgsDebugMsgLevel( u"canceled"_s, 2 );
560 canceled = true;
561 break;
562 }
563 std::unique_ptr<QgsPointCloudBlock> block( pc.nodeData( n, request ) );
564
565 if ( !block )
566 continue;
567
568 // Individual nodes may have different offset values than the root node
569 // we'll calculate the differences and translate x,y,z values to use the root node's offset
570 QgsVector3D offsetDifference = QgsVector3D( 0, 0, 0 );
571 if ( blockCount == 0 )
572 {
573 blockScale = block->scale();
574 blockOffset = block->offset();
575 blockAttributes = block->attributes();
576 }
577 else
578 {
579 offsetDifference = blockOffset - block->offset();
580 }
581
582 const char *ptr = block->data();
583
584 context.setScale( block->scale() );
585 context.setOffset( block->offset() );
586 context.setAttributes( block->attributes() );
587
588 recordSize = context.pointRecordSize();
589
590 for ( int i = 0; i < block->pointCount(); ++i )
591 {
592 allByteArrays.append( ptr + i * recordSize, recordSize );
593
594 // Calculate the translated values only for axes that have a different offset
595 if ( offsetDifference.x() != 0 )
596 {
597 qint32 ix = *reinterpret_cast< const qint32 * >( ptr + i * recordSize + context.xOffset() );
598 ix -= std::lround( offsetDifference.x() / context.scale().x() );
599 const char *xPtr = reinterpret_cast< const char * >( &ix );
600 allByteArrays.replace( pointCount * recordSize + context.xOffset(), 4, QByteArray( xPtr, 4 ) );
601 }
602 if ( offsetDifference.y() != 0 )
603 {
604 qint32 iy = *reinterpret_cast< const qint32 * >( ptr + i * recordSize + context.yOffset() );
605 iy -= std::lround( offsetDifference.y() / context.scale().y() );
606 const char *yPtr = reinterpret_cast< const char * >( &iy );
607 allByteArrays.replace( pointCount * recordSize + context.yOffset(), 4, QByteArray( yPtr, 4 ) );
608 }
609 // We need the Z value regardless of the node's offset
610 qint32 iz = *reinterpret_cast< const qint32 * >( ptr + i * recordSize + context.zOffset() );
611 if ( offsetDifference.z() != 0 )
612 {
613 iz -= std::lround( offsetDifference.z() / context.scale().z() );
614 const char *zPtr = reinterpret_cast< const char * >( &iz );
615 allByteArrays.replace( pointCount * recordSize + context.zOffset(), 4, QByteArray( zPtr, 4 ) );
616 }
617 allPairs.append( qMakePair( pointCount, double( iz ) + block->offset().z() ) );
618
619 ++pointCount;
620 }
621 ++blockCount;
622 }
623
624 if ( pointCount == 0 )
625 return 0;
626
627 switch ( order )
628 {
630 std::sort( allPairs.begin(), allPairs.end(), []( QPair<int, double> a, QPair<int, double> b ) { return a.second < b.second; } );
631 break;
633 std::sort( allPairs.begin(), allPairs.end(), []( QPair<int, double> a, QPair<int, double> b ) { return a.second > b.second; } );
634 break;
636 break;
637 }
638
639 // Now we can reconstruct a byte array sorted by Z value
640 QByteArray sortedByteArray;
641 sortedByteArray.reserve( allPairs.size() );
642 for ( QPair<int, double> pair : allPairs )
643 sortedByteArray.append( allByteArrays.mid( pair.first * recordSize, recordSize ) );
644
645 std::unique_ptr<QgsPointCloudBlock> bigBlock { new QgsPointCloudBlock( pointCount,
646 blockAttributes,
647 sortedByteArray,
648 blockScale,
649 blockOffset ) };
650
651 QgsVector3D contextScale = context.scale();
652 QgsVector3D contextOffset = context.offset();
653
654 context.setScale( bigBlock->scale() );
655 context.setOffset( bigBlock->offset() );
656 context.setAttributes( bigBlock->attributes() );
657
658 mRenderer->renderBlock( bigBlock.get(), context );
659
660 context.setScale( contextScale );
661 context.setOffset( contextOffset );
662
663 return blockCount;
664}
665
666inline bool isEdgeTooLong( const QPointF &p1, const QPointF &p2, float length )
667{
668 QPointF p = p1 - p2;
669 return p.x() * p.x() + p.y() * p.y() > length;
670}
671
672static void renderTriangle( QImage &img, QPointF *pts, QRgb c0, QRgb c1, QRgb c2, float horizontalFilter, float *elev, QgsElevationMap *elevationMap )
673{
674 if ( horizontalFilter > 0 )
675 {
676 float filterThreshold2 = horizontalFilter * horizontalFilter;
677 if ( isEdgeTooLong( pts[0], pts[1], filterThreshold2 ) ||
678 isEdgeTooLong( pts[1], pts[2], filterThreshold2 ) ||
679 isEdgeTooLong( pts[2], pts[0], filterThreshold2 ) )
680 return;
681 }
682
683 QgsRectangle screenBBox = QgsMeshLayerUtils::triangleBoundingBox( pts[0], pts[1], pts[2] );
684
685 QSize outputSize = img.size();
686
687 int topLim = std::max( int( screenBBox.yMinimum() ), 0 );
688 int bottomLim = std::min( int( screenBBox.yMaximum() ), outputSize.height() - 1 );
689 int leftLim = std::max( int( screenBBox.xMinimum() ), 0 );
690 int rightLim = std::min( int( screenBBox.xMaximum() ), outputSize.width() - 1 );
691
692 int red0 = qRed( c0 ), green0 = qGreen( c0 ), blue0 = qBlue( c0 );
693 int red1 = qRed( c1 ), green1 = qGreen( c1 ), blue1 = qBlue( c1 );
694 int red2 = qRed( c2 ), green2 = qGreen( c2 ), blue2 = qBlue( c2 );
695
696 QRgb *elevData = elevationMap ? elevationMap->rawElevationImageData() : nullptr;
697
698 for ( int j = topLim; j <= bottomLim; j++ )
699 {
700 QRgb *scanLine = ( QRgb * ) img.scanLine( j );
701 QRgb *elevScanLine = elevData ? elevData + static_cast<size_t>( outputSize.width() * j ) : nullptr;
702 for ( int k = leftLim; k <= rightLim; k++ )
703 {
704 QPointF pt( k, j );
705 double lam1, lam2, lam3;
706 if ( !QgsMeshLayerUtils::calculateBarycentricCoordinates( pts[0], pts[1], pts[2], pt, lam3, lam2, lam1 ) )
707 continue;
708
709 // interpolate color
710 int r = static_cast<int>( red0 * lam1 + red1 * lam2 + red2 * lam3 );
711 int g = static_cast<int>( green0 * lam1 + green1 * lam2 + green2 * lam3 );
712 int b = static_cast<int>( blue0 * lam1 + blue1 * lam2 + blue2 * lam3 );
713 scanLine[k] = qRgb( r, g, b );
714
715 // interpolate elevation - in case we are doing global map shading
716 if ( elevScanLine )
717 {
718 float z = static_cast<float>( elev[0] * lam1 + elev[1] * lam2 + elev[2] * lam3 );
719 elevScanLine[k] = QgsElevationMap::encodeElevation( z );
720 }
721 }
722 }
723}
724
725void QgsPointCloudLayerRenderer::renderTriangulatedSurface( QgsPointCloudRenderContext &context )
726{
727 const QgsPointCloudRenderContext::TriangulationData &triangulation = context.triangulationData();
728 const std::vector<double> &points = triangulation.points;
729
730 // Delaunator would crash if it gets less than three points
731 if ( points.size() < 3 )
732 {
733 QgsDebugMsgLevel( u"Need at least 3 points to triangulate"_s, 4 );
734 return;
735 }
736
737 std::unique_ptr<delaunator::Delaunator> delaunator;
738 try
739 {
740 delaunator = std::make_unique<delaunator::Delaunator>( points );
741 }
742 catch ( std::exception & )
743 {
744 // something went wrong, better to retrieve initial state
745 QgsDebugMsgLevel( u"Error with triangulation"_s, 4 );
746 return;
747 }
748
749 float horizontalFilter = 0;
750 if ( mRenderer->horizontalTriangleFilter() )
751 {
752 horizontalFilter = static_cast<float>( renderContext()->convertToPainterUnits(
753 mRenderer->horizontalTriangleFilterThreshold(), mRenderer->horizontalTriangleFilterUnit() ) );
754 }
755
756 QImage img( context.renderContext().deviceOutputSize(), QImage::Format_ARGB32_Premultiplied );
757 img.setDevicePixelRatio( context.renderContext().devicePixelRatio() );
758 img.fill( 0 );
759
760 const std::vector<size_t> &triangleIndexes = delaunator->triangles;
761 QPainter *painter = context.renderContext().painter();
762 QgsElevationMap *elevationMap = context.renderContext().elevationMap();
763 QPointF triangle[3];
764 float elev[3] {0, 0, 0};
765 for ( size_t i = 0; i < triangleIndexes.size(); i += 3 )
766 {
767 size_t v0 = triangleIndexes[i], v1 = triangleIndexes[i + 1], v2 = triangleIndexes[i + 2];
768 triangle[0].rx() = points[v0 * 2];
769 triangle[0].ry() = points[v0 * 2 + 1];
770 triangle[1].rx() = points[v1 * 2];
771 triangle[1].ry() = points[v1 * 2 + 1];
772 triangle[2].rx() = points[v2 * 2];
773 triangle[2].ry() = points[v2 * 2 + 1];
774
775 if ( elevationMap )
776 {
777 elev[0] = triangulation.elevations[v0];
778 elev[1] = triangulation.elevations[v1];
779 elev[2] = triangulation.elevations[v2];
780 }
781
782 QRgb c0 = triangulation.colors[v0], c1 = triangulation.colors[v1], c2 = triangulation.colors[v2];
783 renderTriangle( img, triangle, c0, c1, c2, horizontalFilter, elev, elevationMap );
784 }
785
786 painter->drawImage( 0, 0, img );
787}
788
790{
791 // when rendering as triangles we still want to show temporary incremental renders as points until
792 // the final triangulated surface is ready, which may be slow
793 // So we request here a preview render image for the temporary incremental updates:
794 if ( mRenderer->renderAsTriangles() )
796
798}
799
801{
802 // unless we are using the extent only renderer, point cloud layers should always be rasterized -- we don't want to export points as vectors
803 // to formats like PDF!
804 return mRenderer ? mRenderer->type() != "extent"_L1 : false;
805}
806
808{
809 mRenderTimeHint = time;
810}
811
812QVector<QgsPointCloudNodeId> QgsPointCloudLayerRenderer::traverseTree( const QgsPointCloudIndex &pc, const QgsRenderContext &context, QgsPointCloudNodeId n, double maxErrorPixels, double nodeErrorPixels )
813{
814 QVector<QgsPointCloudNodeId> nodes;
815
816 if ( context.renderingStopped() )
817 {
818 QgsDebugMsgLevel( u"canceled"_s, 2 );
819 return nodes;
820 }
821
822 QgsPointCloudNode node = pc.getNode( n );
823 QgsBox3D nodeExtent = node.bounds();
824
825 if ( !context.extent().intersects( nodeExtent.toRectangle() ) )
826 return nodes;
827
828 const QgsDoubleRange nodeZRange( nodeExtent.zMinimum(), nodeExtent.zMaximum() );
829 const QgsDoubleRange adjustedNodeZRange = QgsDoubleRange( nodeZRange.lower() + mZOffset, nodeZRange.upper() + mZOffset );
830 if ( !context.zRange().isInfinite() && !context.zRange().overlaps( adjustedNodeZRange ) )
831 return nodes;
832
833 if ( node.pointCount() > 0 )
834 nodes.append( n );
835
836 double childrenErrorPixels = nodeErrorPixels / 2.0;
837 if ( childrenErrorPixels < maxErrorPixels )
838 return nodes;
839
840 for ( const QgsPointCloudNodeId &nn : node.children() )
841 {
842 nodes += traverseTree( pc, context, nn, maxErrorPixels, childrenErrorPixels );
843 }
844
845 return nodes;
846}
847
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:59
QFlags< MapLayerRendererFlag > MapLayerRendererFlags
Flags which control how map layer renderers behave.
Definition qgis.h:2854
PointCloudDrawOrder
Pointcloud rendering order for 2d views.
Definition qgis.h:4317
@ BottomToTop
Draw points with larger Z values last.
Definition qgis.h:4319
@ Default
Draw points in the order they are stored.
Definition qgis.h:4318
@ TopToBottom
Draw points with larger Z values first.
Definition qgis.h:4320
@ RenderOverviewAndExtents
Render point cloud extents over overview point cloud.
Definition qgis.h:6354
@ RenderExtents
Render only point cloud extents when zoomed out.
Definition qgis.h:6352
@ RenderOverview
Render overview point cloud when zoomed out.
Definition qgis.h:6353
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
Definition qgis.h:198
@ RenderPartialOutputOverPreviousCachedImage
When rendering temporary in-progress preview renders, these preview renders can be drawn over any pre...
Definition qgis.h:2844
@ RenderPartialOutputs
The renderer benefits from rendering temporary in-progress preview renders. These are temporary resul...
Definition qgis.h:2843
@ Local
Local means the source is a local file on the machine.
Definition qgis.h:6341
@ Remote
Remote means it's loaded through a protocol like HTTP.
Definition qgis.h:6342
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2731
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
double zMaximum() const
Returns the maximum z value.
Definition qgsbox3d.h:261
QgsRectangle toRectangle() const
Converts the box to a 2D rectangle.
Definition qgsbox3d.h:381
double zMinimum() const
Returns the minimum z value.
Definition qgsbox3d.h:254
Handles coordinate transforms between two coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
bool isInfinite() const
Returns true if the range consists of all possible values.
Definition qgsrange.h:290
Stores a digital elevation model in a raster image which may get updated as a part of the map layer r...
static QRgb encodeElevation(float z)
Converts elevation value to an actual color.
QRgb * rawElevationImageData()
Returns pointer to the actual elevation image data.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void canceled()
Internal routines can connect to this signal if they use event loop.
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.
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.
QRectF transformBounds(const QRectF &bounds) const
Transforms a bounding box from map coordinates to device coordinates.
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).
Attribute for point cloud data pair of name and size in bytes.
QString errorStr() const
Returns the error message string of the request.
void finished()
Emitted when the request processing has finished.
std::unique_ptr< QgsPointCloudBlock > takeBlock()
Returns the requested block.
virtual QgsGeometry polygonBounds() const
Returns the polygon bounds of the layer.
A renderer for 2d visualisation of point clouds which shows the dataset's extents using a fill symbol...
void renderExtent(const QgsGeometry &extent, QgsPointCloudRenderContext &context)
Renders a polygon extent geometry to the specified render context.
Smart pointer for QgsAbstractPointCloudIndex.
int span() const
Returns the number of points in one direction in a single node.
QgsVector3D offset() const
Returns offset of data from CRS.
QgsVector3D scale() const
Returns scale of data relative to CRS.
QgsPointCloudBlockRequest * asyncNodeData(const QgsPointCloudNodeId &n, const QgsPointCloudRequest &request)
Returns a handle responsible for loading a node data block.
bool isValid() const
Returns whether index is loaded and valid.
QgsRectangle extent() const
Returns extent of the data.
std::unique_ptr< QgsPointCloudBlock > nodeData(const QgsPointCloudNodeId &n, const QgsPointCloudRequest &request)
Returns node data block.
QgsPointCloudNodeId root() const
Returns root node of the index.
QgsPointCloudNode getNode(const QgsPointCloudNodeId &id) const
Returns object for a given node.
Qgis::PointCloudAccessType accessType() const
Returns the access type of the data If the access type is Remote, data will be fetched from an HTTP s...
Point cloud layer specific subclass of QgsMapLayerElevationProperties.
~QgsPointCloudLayerRenderer() override
bool forceRasterRender() const override
Returns true if the renderer must be rendered to a raster paint device (e.g.
QgsPointCloudLayerRenderer(QgsPointCloudLayer *layer, QgsRenderContext &context)
Ctor.
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).
Qgis::MapLayerRendererFlags flags() const override
Returns flags which control how the map layer rendering behaves.
Represents a map layer supporting display of point clouds.
QgsMapLayerElevationProperties * elevationProperties() override
Returns the layer's elevation properties.
QgsPointCloudRenderer * renderer()
Returns the 2D renderer for the point cloud.
QgsPointCloudIndex index() const
Returns the point cloud index associated with the layer.
QgsPointCloudDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
Represents an indexed point cloud node's position in octree.
QString toString() const
Encode node to string.
Keeps metadata for an indexed point cloud node.
QList< QgsPointCloudNodeId > children() const
Returns IDs of child nodes.
qint64 pointCount() const
Returns number of points contained in node data.
QgsBox3D bounds() const
Returns node's bounding cube in CRS coords.
Encapsulates the render context for a 2D point cloud rendering operation.
int yOffset() const
Returns the offset for the y value in a point record.
QgsVector3D offset() const
Returns the offset of the layer's int32 coordinates compared to CRS coords.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
void setOffset(const QgsVector3D &offset)
Sets the offset of the layer's int32 coordinates compared to CRS coords.
void setScale(const QgsVector3D &scale)
Sets the scale of the layer's int32 coordinates compared to CRS coords.
int pointRecordSize() const
Returns the size of a single point record.
int xOffset() const
Returns the offset for the x value in a point record.
QgsVector3D scale() const
Returns the scale of the layer's int32 coordinates compared to CRS coords.
TriangulationData & triangulationData()
Returns reference to the triangulation data structure (only used when rendering as triangles is enabl...
int zOffset() const
Returns the offset for the y value in a point record.
QgsFeedback * feedback() const
Returns the feedback object used to cancel rendering.
void setAttributes(const QgsPointCloudAttributeCollection &attributes)
Sets the attributes associated with the rendered block.
virtual QgsPointCloudRenderer * clone() const =0
Create a deep copy of this renderer.
Point cloud data request.
void setAttributes(const QgsPointCloudAttributeCollection &attributes)
Set attributes filter in the request.
bool overlaps(const QgsRange< T > &other) const
Returns true if this range overlaps another range.
Definition qgsrange.h:179
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
bool intersects(const QgsRectangle &rect) const
Returns true when rectangle intersects with other rectangle.
double yMaximum
Contains information about the context of a rendering operation.
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).
QPainter * painter()
Returns the destination QPainter for the render operation.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
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...
float devicePixelRatio() const
Returns the device pixel ratio.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
QgsDoubleRange zRange() const
Returns the range of z-values which should be rendered.
QSize deviceOutputSize() const
Returns the device output size of the render.
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.
void record(const QString &name, double time, const QString &group="startup", const QString &id=QString())
Manually adds a profile event with the given name and total time (in seconds).
Scoped object for saving and restoring a QPainter object's state.
Scoped object for setting the current thread name.
double y() const
Returns Y coordinate.
Definition qgsvector3d.h:52
double z() const
Returns Z coordinate.
Definition qgsvector3d.h:54
double x() const
Returns X coordinate.
Definition qgsvector3d.h:50
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
bool isEdgeTooLong(const QPointF &p1, const QPointF &p2, float length)
std::vector< QRgb > colors
RGB color for each point.
std::vector< float > elevations
Z value for each point (only used when global map shading is enabled).
std::vector< double > points
X,Y for each point - kept in this structure so that we can use it without further conversions in Dela...