QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsvectorlayerprofilegenerator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectorlayerprofilegenerator.cpp
3 ---------------
4 begin : March 2022
5 copyright : (C) 2022 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 ***************************************************************************/
18
19#include <memory>
20
21#include "qgis.h"
22#include "qgsabstractgeometry.h"
24#include "qgscurve.h"
26#include "qgsfeatureid.h"
27#include "qgsfillsymbol.h"
28#include "qgsgeos.h"
29#include "qgslinesymbol.h"
30#include "qgsmarkersymbol.h"
31#include "qgsmeshlayerutils.h"
32#include "qgsmultilinestring.h"
33#include "qgsmultipoint.h"
34#include "qgsmultipolygon.h"
35#include "qgspainting.h"
36#include "qgspolygon.h"
38#include "qgsprofilepoint.h"
39#include "qgsprofilerequest.h"
40#include "qgsprofilesnapping.h"
41#include "qgsterrainprovider.h"
42#include "qgstessellator.h"
43#include "qgsvectorlayer.h"
46
47#include <QPolygonF>
48#include <QString>
49
50using namespace Qt::StringLiterals;
51
52//
53// QgsVectorLayerProfileResults
54//
55
57{
58 return u"vector"_s;
59}
60
62{
63 QVector<QgsGeometry> res;
64 res.reserve( features.size() );
65 for ( auto it = features.constBegin(); it != features.constEnd(); ++it )
66 {
67 for ( const Feature &feature : it.value() )
68 {
69 res.append( feature.geometry );
70 }
71 }
72 return res;
73}
74
75QVector<QgsAbstractProfileResults::Feature> QgsVectorLayerProfileResults::asFeatures( Qgis::ProfileExportType type, QgsFeedback *feedback ) const
76{
77 switch ( profileType )
78 {
81 return asIndividualFeatures( type, feedback );
82 // distance vs elevation table results are always handled like a continuous surface
83 [[fallthrough]];
84
87 }
89}
90
92{
93 switch ( profileType )
94 {
96 return snapPointToIndividualFeatures( point, context );
98 return QgsAbstractProfileSurfaceResults::snapPoint( point, context );
99 }
101}
102
103
104QVector<QgsProfileIdentifyResults> QgsVectorLayerProfileResults::identify( const QgsDoubleRange &distanceRange, const QgsDoubleRange &elevationRange, const QgsProfileIdentifyContext & )
105{
106 QgsFeatureIds ids;
107 auto visitFeature = [&ids]( QgsFeatureId featureId ) { ids << featureId; };
108
109 visitFeaturesInRange( distanceRange, elevationRange, visitFeature );
110 if ( ids.empty() )
111 return {};
112
113 QVector< QVariantMap> idsList;
114 for ( auto it = ids.constBegin(); it != ids.constEnd(); ++it )
115 idsList.append( QVariantMap( { { u"id"_s, *it } } ) );
116
117 return { QgsProfileIdentifyResults( mLayer, idsList ) };
118}
119
120QVector<QgsProfileIdentifyResults> QgsVectorLayerProfileResults::identify( const QgsProfilePoint &point, const QgsProfileIdentifyContext &context )
121{
122 QHash< QgsFeatureId, QVariantMap > features;
123 auto visitFeature = [&features]( QgsFeatureId featureId, double delta, double distance, double elevation ) {
124 auto it = features.find( featureId );
125 if ( it == features.end() )
126 {
127 features[featureId] = QVariantMap( { { u"id"_s, featureId }, { u"delta"_s, delta }, { u"distance"_s, distance }, { u"elevation"_s, elevation } } );
128 }
129 else
130 {
131 const double currentDelta = it.value().value( u"delta"_s ).toDouble();
132 if ( delta < currentDelta )
133 {
134 *it = QVariantMap( { { u"id"_s, featureId }, { u"delta"_s, delta }, { u"distance"_s, distance }, { u"elevation"_s, elevation } } );
135 }
136 }
137 };
138
139 visitFeaturesAtPoint( point, context.maximumPointDistanceDelta, context.maximumPointElevationDelta, context.maximumSurfaceElevationDelta, visitFeature, true );
140
141 QVector< QVariantMap> attributes;
142 for ( auto it = features.constBegin(); it != features.constEnd(); ++it )
143 attributes.append( *it );
144
145 QVector<QgsProfileIdentifyResults> res;
146
147 if ( !attributes.empty() )
148 res.append( QgsProfileIdentifyResults( mLayer, attributes ) );
149
151 {
152 const QVector<QgsProfileIdentifyResults> surfaceResults = QgsAbstractProfileSurfaceResults::identify( point, context );
153 res.reserve( surfaceResults.size() );
154 for ( const QgsProfileIdentifyResults &surfaceResult : surfaceResults )
155 {
156 res.append( QgsProfileIdentifyResults( mLayer, surfaceResult.results() ) );
157 }
158 }
159
160 return res;
161}
162
163QgsProfileSnapResult QgsVectorLayerProfileResults::snapPointToIndividualFeatures( const QgsProfilePoint &point, const QgsProfileSnapContext &context )
164{
166 double bestSnapDistance = std::numeric_limits< double >::max();
167
168 auto visitFeature = [&bestSnapDistance, &res]( QgsFeatureId, double delta, double distance, double elevation ) {
169 if ( distance < bestSnapDistance )
170 {
171 bestSnapDistance = delta;
172 res.snappedPoint = QgsProfilePoint( distance, elevation );
173 }
174 };
175
176 visitFeaturesAtPoint( point, context.maximumPointDistanceDelta, context.maximumPointElevationDelta, context.maximumSurfaceElevationDelta, visitFeature, false );
177
178 return res;
179}
180
181void QgsVectorLayerProfileResults::visitFeaturesAtPoint(
182 const QgsProfilePoint &point,
183 double maximumPointDistanceDelta,
184 double maximumPointElevationDelta,
185 double maximumSurfaceElevationDelta,
186 const std::function< void( QgsFeatureId, double delta, double distance, double elevation ) > &visitor,
187 bool visitWithin
188) const
189{
190 // TODO -- add spatial index if performance is an issue
191
192 const QgsPoint targetPoint( point.distance(), point.elevation() );
193
194 for ( auto it = features.constBegin(); it != features.constEnd(); ++it )
195 {
196 for ( const Feature &feature : it.value() )
197 {
198 const QgsRectangle featureBounds = feature.crossSectionGeometry.boundingBox();
199 if ( ( featureBounds.xMinimum() - maximumPointDistanceDelta <= point.distance() ) && ( featureBounds.xMaximum() + maximumPointDistanceDelta >= point.distance() ) )
200 {
201 switch ( feature.crossSectionGeometry.type() )
202 {
204 {
205 for ( auto partIt = feature.crossSectionGeometry.const_parts_begin(); partIt != feature.crossSectionGeometry.const_parts_end(); ++partIt )
206 {
207 if ( const QgsPoint *candidatePoint = qgsgeometry_cast< const QgsPoint * >( *partIt ) )
208 {
209 const double snapDistanceDelta = std::fabs( point.distance() - candidatePoint->x() );
210 if ( snapDistanceDelta > maximumPointDistanceDelta )
211 continue;
212
213 const double snapHeightDelta = std::fabs( point.elevation() - candidatePoint->y() );
214 if ( snapHeightDelta > maximumPointElevationDelta )
215 continue;
216
217 const double snapDistance = candidatePoint->distance( targetPoint );
218 visitor( feature.featureId, snapDistance, candidatePoint->x(), candidatePoint->y() );
219 }
220 }
221 break;
222 }
223
225 {
226 for ( auto partIt = feature.crossSectionGeometry.const_parts_begin(); partIt != feature.crossSectionGeometry.const_parts_end(); ++partIt )
227 {
228 if ( const QgsCurve *line = qgsgeometry_cast< const QgsCurve * >( *partIt ) )
229 {
230 // might be a vertical line
231 if ( const QgsLineString *lineString = qgsgeometry_cast< const QgsLineString * >( line ) )
232 {
233 if ( lineString->numPoints() == 2 && qgsDoubleNear( lineString->pointN( 0 ).x(), lineString->pointN( 1 ).x() ) )
234 {
235 const double snapDistanceDelta = std::fabs( point.distance() - lineString->pointN( 0 ).x() );
236 if ( snapDistanceDelta > maximumPointDistanceDelta )
237 continue;
238
239 const double snapHeightDelta = std::fabs( point.elevation() - lineString->pointN( 0 ).y() );
240 if ( snapHeightDelta <= maximumPointElevationDelta )
241 {
242 const double snapDistanceP1 = lineString->pointN( 0 ).distance( targetPoint );
243 visitor( feature.featureId, snapDistanceP1, lineString->pointN( 0 ).x(), lineString->pointN( 0 ).y() );
244 }
245
246 const double snapHeightDelta2 = std::fabs( point.elevation() - lineString->pointN( 1 ).y() );
247 if ( snapHeightDelta2 <= maximumPointElevationDelta )
248 {
249 const double snapDistanceP2 = lineString->pointN( 1 ).distance( targetPoint );
250 visitor( feature.featureId, snapDistanceP2, lineString->pointN( 1 ).x(), lineString->pointN( 1 ).y() );
251 }
252
253 if ( visitWithin )
254 {
255 double elevation1 = lineString->pointN( 0 ).y();
256 double elevation2 = lineString->pointN( 1 ).y();
257 if ( elevation1 > elevation2 )
258 std::swap( elevation1, elevation2 );
259
260 if ( point.elevation() > elevation1 && point.elevation() < elevation2 )
261 {
262 const double snapDistance = std::fabs( lineString->pointN( 0 ).x() - point.distance() );
263 visitor( feature.featureId, snapDistance, lineString->pointN( 0 ).x(), point.elevation() );
264 }
265 }
266 continue;
267 }
268 }
269
270 const QgsRectangle partBounds = ( *partIt )->boundingBox();
271 if ( point.distance() < partBounds.xMinimum() - maximumPointDistanceDelta || point.distance() > partBounds.xMaximum() + maximumPointDistanceDelta )
272 continue;
273
274 const double snappedDistance = point.distance() < partBounds.xMinimum() ? partBounds.xMinimum() : point.distance() > partBounds.xMaximum() ? partBounds.xMaximum() : point.distance();
275
276 const QgsGeometry cutLine( new QgsLineString( QgsPoint( snappedDistance, qgsDoubleNear( minZ, maxZ ) ? minZ - 1 : minZ ), QgsPoint( snappedDistance, maxZ ) ) );
277 QgsGeos cutLineGeos( cutLine.constGet() );
278
279 const QgsGeometry points( cutLineGeos.intersection( line ) );
280
281 for ( auto vertexIt = points.vertices_begin(); vertexIt != points.vertices_end(); ++vertexIt )
282 {
283 const double snapHeightDelta = std::fabs( point.elevation() - ( *vertexIt ).y() );
284 if ( snapHeightDelta > maximumSurfaceElevationDelta )
285 continue;
286
287 const double snapDistance = ( *vertexIt ).distance( targetPoint );
288 visitor( feature.featureId, snapDistance, ( *vertexIt ).x(), ( *vertexIt ).y() );
289 }
290 }
291 }
292 break;
293 }
294
296 {
297 if ( visitWithin )
298 {
299 if ( feature.crossSectionGeometry.intersects( QgsGeometry::fromPointXY( QgsPointXY( point.distance(), point.elevation() ) ) ) )
300 {
301 visitor( feature.featureId, 0, point.distance(), point.elevation() );
302 break;
303 }
304 }
305 for ( auto partIt = feature.crossSectionGeometry.const_parts_begin(); partIt != feature.crossSectionGeometry.const_parts_end(); ++partIt )
306 {
307 if ( const QgsCurve *exterior = qgsgeometry_cast< const QgsPolygon * >( *partIt )->exteriorRing() )
308 {
309 const QgsRectangle partBounds = ( *partIt )->boundingBox();
310 if ( point.distance() < partBounds.xMinimum() - maximumPointDistanceDelta || point.distance() > partBounds.xMaximum() + maximumPointDistanceDelta )
311 continue;
312
313 const double snappedDistance = point.distance() < partBounds.xMinimum() ? partBounds.xMinimum() : point.distance() > partBounds.xMaximum() ? partBounds.xMaximum() : point.distance();
314
315 const QgsGeometry cutLine( new QgsLineString( QgsPoint( snappedDistance, qgsDoubleNear( minZ, maxZ ) ? minZ - 1 : minZ ), QgsPoint( snappedDistance, maxZ ) ) );
316 QgsGeos cutLineGeos( cutLine.constGet() );
317
318 const QgsGeometry points( cutLineGeos.intersection( exterior ) );
319 for ( auto vertexIt = points.vertices_begin(); vertexIt != points.vertices_end(); ++vertexIt )
320 {
321 const double snapHeightDelta = std::fabs( point.elevation() - ( *vertexIt ).y() );
322 if ( snapHeightDelta > maximumSurfaceElevationDelta )
323 continue;
324
325 const double snapDistance = ( *vertexIt ).distance( targetPoint );
326 visitor( feature.featureId, snapDistance, ( *vertexIt ).x(), ( *vertexIt ).y() );
327 }
328 }
329 }
330 break;
331 }
334 break;
335 }
336 }
337 }
338 }
339}
340
341void QgsVectorLayerProfileResults::visitFeaturesInRange( const QgsDoubleRange &distanceRange, const QgsDoubleRange &elevationRange, const std::function<void( QgsFeatureId )> &visitor ) const
342{
343 // TODO -- add spatial index if performance is an issue
344 const QgsRectangle profileRange( distanceRange.lower(), elevationRange.lower(), distanceRange.upper(), elevationRange.upper() );
345 const QgsGeometry profileRangeGeometry = QgsGeometry::fromRect( profileRange );
346 QgsGeos profileRangeGeos( profileRangeGeometry.constGet() );
347 profileRangeGeos.prepareGeometry();
348
349 for ( auto it = features.constBegin(); it != features.constEnd(); ++it )
350 {
351 for ( const Feature &feature : it.value() )
352 {
353 if ( feature.crossSectionGeometry.boundingBoxIntersects( profileRange ) )
354 {
355 switch ( feature.crossSectionGeometry.type() )
356 {
358 {
359 for ( auto partIt = feature.crossSectionGeometry.const_parts_begin(); partIt != feature.crossSectionGeometry.const_parts_end(); ++partIt )
360 {
361 if ( const QgsPoint *candidatePoint = qgsgeometry_cast< const QgsPoint * >( *partIt ) )
362 {
363 if ( profileRange.contains( candidatePoint->x(), candidatePoint->y() ) )
364 {
365 visitor( feature.featureId );
366 }
367 }
368 }
369 break;
370 }
371
374 {
375 if ( profileRangeGeos.intersects( feature.crossSectionGeometry.constGet() ) )
376 {
377 visitor( feature.featureId );
378 }
379 break;
380 }
381
384 break;
385 }
386 }
387 }
388 }
389}
390
392{
393 const QgsExpressionContextScopePopper scopePopper( context.renderContext().expressionContext(), mLayer ? mLayer->createExpressionContextScope() : nullptr );
394 switch ( profileType )
395 {
397 renderResultsAsIndividualFeatures( context );
398 break;
402 renderMarkersOverContinuousSurfacePlot( context );
403 break;
404 }
405}
406
407void QgsVectorLayerProfileResults::renderResultsAsIndividualFeatures( QgsProfileRenderContext &context )
408{
409 QPainter *painter = context.renderContext().painter();
410 if ( !painter )
411 return;
412
413 const QgsScopedQPainterState painterState( painter );
414
415 painter->setBrush( Qt::NoBrush );
416 painter->setPen( Qt::NoPen );
417
418 const double minDistance = context.distanceRange().lower();
419 const double maxDistance = context.distanceRange().upper();
420 const double minZ = context.elevationRange().lower();
421 const double maxZ = context.elevationRange().upper();
422
423 const QRectF visibleRegion( minDistance, minZ, maxDistance - minDistance, maxZ - minZ );
424 QPainterPath clipPath;
425 clipPath.addPolygon( context.worldTransform().map( visibleRegion ) );
426 painter->setClipPath( clipPath, Qt::ClipOperation::IntersectClip );
427
428 const QgsRectangle clipPathRect( clipPath.boundingRect() );
429
430 auto renderResult = [&context, &clipPathRect]( const Feature &profileFeature, QgsMarkerSymbol *markerSymbol, QgsLineSymbol *lineSymbol, QgsFillSymbol *fillSymbol ) {
431 if ( profileFeature.crossSectionGeometry.isEmpty() )
432 return;
433
434 QgsGeometry transformed = profileFeature.crossSectionGeometry;
435 transformed.transform( context.worldTransform() );
436
437 if ( !transformed.boundingBoxIntersects( clipPathRect ) )
438 return;
439
440 // we can take some shortcuts here, because we know that the geometry will already be segmentized and can't be a curved type
441 switch ( transformed.type() )
442 {
444 {
445 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( transformed.constGet() ) )
446 {
447 markerSymbol->renderPoint( QPointF( point->x(), point->y() ), nullptr, context.renderContext() );
448 }
449 else if ( const QgsMultiPoint *multipoint = qgsgeometry_cast< const QgsMultiPoint * >( transformed.constGet() ) )
450 {
451 const int numGeometries = multipoint->numGeometries();
452 for ( int i = 0; i < numGeometries; ++i )
453 {
454 markerSymbol->renderPoint( QPointF( multipoint->pointN( i )->x(), multipoint->pointN( i )->y() ), nullptr, context.renderContext() );
455 }
456 }
457 break;
458 }
459
461 {
462 if ( const QgsLineString *line = qgsgeometry_cast< const QgsLineString * >( transformed.constGet() ) )
463 {
464 lineSymbol->renderPolyline( line->asQPolygonF(), nullptr, context.renderContext() );
465 }
466 else if ( const QgsMultiLineString *multiLinestring = qgsgeometry_cast< const QgsMultiLineString * >( transformed.constGet() ) )
467 {
468 const int numGeometries = multiLinestring->numGeometries();
469 for ( int i = 0; i < numGeometries; ++i )
470 {
471 lineSymbol->renderPolyline( multiLinestring->lineStringN( i )->asQPolygonF(), nullptr, context.renderContext() );
472 }
473 }
474 break;
475 }
476
478 {
479 if ( const QgsPolygon *polygon = qgsgeometry_cast< const QgsPolygon * >( transformed.constGet() ) )
480 {
481 if ( const QgsCurve *exterior = polygon->exteriorRing() )
482 fillSymbol->renderPolygon( exterior->asQPolygonF(), nullptr, nullptr, context.renderContext() );
483 }
484 else if ( const QgsMultiPolygon *multiPolygon = qgsgeometry_cast< const QgsMultiPolygon * >( transformed.constGet() ) )
485 {
486 const int numGeometries = multiPolygon->numGeometries();
487 for ( int i = 0; i < numGeometries; ++i )
488 {
489 fillSymbol->renderPolygon( multiPolygon->polygonN( i )->exteriorRing()->asQPolygonF(), nullptr, nullptr, context.renderContext() );
490 }
491 }
492 break;
493 }
494
497 return;
498 }
499 };
500
501 QgsFeatureRequest req;
502 req.setFilterFids( qgis::listToSet( features.keys() ) );
503
504 if ( respectLayerSymbology && mLayer && mLayer->renderer() )
505 {
506 std::unique_ptr< QgsFeatureRenderer > renderer( mLayer->renderer()->clone() );
507 renderer->startRender( context.renderContext(), mLayer->fields() );
508
509 // if we are respecting the layer's symbology then we'll fire off a feature request and iterate through
510 // features from the profile, rendering each in turn
511 QSet<QString> attributes = renderer->usedAttributes( context.renderContext() );
512
513 std::unique_ptr< QgsMarkerSymbol > marker( mMarkerSymbol->clone() );
514 std::unique_ptr< QgsLineSymbol > line( mLineSymbol->clone() );
515 std::unique_ptr< QgsFillSymbol > fill( mFillSymbol->clone() );
516 attributes.unite( marker->usedAttributes( context.renderContext() ) );
517 attributes.unite( line->usedAttributes( context.renderContext() ) );
518 attributes.unite( fill->usedAttributes( context.renderContext() ) );
519
520 req.setSubsetOfAttributes( attributes, mLayer->fields() );
521
522 QgsFeature feature;
523 QgsFeatureIterator it = mLayer->getFeatures( req );
524 while ( it.nextFeature( feature ) )
525 {
526 context.renderContext().expressionContext().setFeature( feature );
527 const QgsSymbolList rendererSymbols = renderer->symbolsForFeature( feature, context.renderContext() );
528 for ( QgsSymbol *rendererSymbol : rendererSymbols )
529 {
530 if ( !rendererSymbol )
531 continue;
532
533 marker->setColor( rendererSymbol->color() );
534 marker->setOpacity( rendererSymbol->opacity() );
535 line->setColor( rendererSymbol->color() );
536 line->setOpacity( rendererSymbol->opacity() );
537 fill->setColor( rendererSymbol->color() );
538 fill->setOpacity( rendererSymbol->opacity() );
539
540 marker->startRender( context.renderContext() );
541 line->startRender( context.renderContext() );
542 fill->startRender( context.renderContext() );
543
544 const QVector< Feature > profileFeatures = features.value( feature.id() );
545 for ( const Feature &profileFeature : profileFeatures )
546 {
547 renderResult(
548 profileFeature,
549 rendererSymbol->type() == Qgis::SymbolType::Marker ? qgis::down_cast< QgsMarkerSymbol * >( rendererSymbol ) : marker.get(),
550 rendererSymbol->type() == Qgis::SymbolType::Line ? qgis::down_cast< QgsLineSymbol * >( rendererSymbol ) : line.get(),
551 rendererSymbol->type() == Qgis::SymbolType::Fill ? qgis::down_cast< QgsFillSymbol * >( rendererSymbol ) : fill.get()
552 );
553 }
554
555 marker->stopRender( context.renderContext() );
556 line->stopRender( context.renderContext() );
557 fill->stopRender( context.renderContext() );
558 }
559 }
560
561 renderer->stopRender( context.renderContext() );
562 }
563 else if ( mLayer )
564 {
565 QSet<QString> attributes;
566 attributes.unite( mMarkerSymbol->usedAttributes( context.renderContext() ) );
567 attributes.unite( mFillSymbol->usedAttributes( context.renderContext() ) );
568 attributes.unite( mLineSymbol->usedAttributes( context.renderContext() ) );
569
570 mMarkerSymbol->startRender( context.renderContext() );
571 mFillSymbol->startRender( context.renderContext() );
572 mLineSymbol->startRender( context.renderContext() );
573 req.setSubsetOfAttributes( attributes, mLayer->fields() );
574
575 QgsFeature feature;
576 QgsFeatureIterator it = mLayer->getFeatures( req );
577 while ( it.nextFeature( feature ) )
578 {
579 context.renderContext().expressionContext().setFeature( feature );
580 const QVector< Feature > profileFeatures = features.value( feature.id() );
581 for ( const Feature &profileFeature : profileFeatures )
582 {
583 renderResult( profileFeature, mMarkerSymbol.get(), mLineSymbol.get(), mFillSymbol.get() );
584 }
585 }
586 mMarkerSymbol->stopRender( context.renderContext() );
587 mFillSymbol->stopRender( context.renderContext() );
588 mLineSymbol->stopRender( context.renderContext() );
589 }
590}
591
592void QgsVectorLayerProfileResults::renderMarkersOverContinuousSurfacePlot( QgsProfileRenderContext &context )
593{
594 QPainter *painter = context.renderContext().painter();
595 if ( !painter )
596 return;
597
598 const QgsScopedQPainterState painterState( painter );
599
600 painter->setBrush( Qt::NoBrush );
601 painter->setPen( Qt::NoPen );
602
603 const double minDistance = context.distanceRange().lower();
604 const double maxDistance = context.distanceRange().upper();
605 const double minZ = context.elevationRange().lower();
606 const double maxZ = context.elevationRange().upper();
607
608 const QRectF visibleRegion( minDistance, minZ, maxDistance - minDistance, maxZ - minZ );
609 QPainterPath clipPath;
610 clipPath.addPolygon( context.worldTransform().map( visibleRegion ) );
611 painter->setClipPath( clipPath, Qt::ClipOperation::IntersectClip );
612
613 mMarkerSymbol->startRender( context.renderContext() );
614
615 // Retrieve the features. They are needed by mMarkerSymbol
616 // to render points with expressions
617 QHash< QgsFeatureId, QgsFeature > surfaceFeatures;
618 if ( mLayer )
619 {
620 QgsFeatureRequest request;
621 request.setFilterFids( qgis::listToSet( mDistanceToFeatureId.values() ) );
622 request.setSubsetOfAttributes( mMarkerSymbol->usedAttributes( context.renderContext() ), mLayer->fields() );
623 QgsFeature feature;
624 QgsFeatureIterator featIt = mLayer->getFeatures( request );
625 while ( featIt.nextFeature( feature ) )
626 {
627 surfaceFeatures.insert( feature.id(), feature );
628 }
629 }
630
631 for ( auto pointIt = mDistanceToHeightMap.constBegin(); pointIt != mDistanceToHeightMap.constEnd(); ++pointIt )
632 {
633 if ( std::isnan( pointIt.value() ) )
634 continue;
635
636 const QgsFeatureId featureId = mDistanceToFeatureId.value( pointIt.key(), FID_NULL );
637 context.renderContext().expressionContext().setFeature( surfaceFeatures.value( featureId ) );
638
639 mMarkerSymbol->renderPoint( context.worldTransform().map( QPointF( pointIt.key(), pointIt.value() ) ), nullptr, context.renderContext() );
640 }
641 mMarkerSymbol->stopRender( context.renderContext() );
642}
643
644QVector<QgsAbstractProfileResults::Feature> QgsVectorLayerProfileResults::asIndividualFeatures( Qgis::ProfileExportType type, QgsFeedback *feedback ) const
645{
646 QVector<QgsAbstractProfileResults::Feature> res;
647 res.reserve( features.size() );
648 for ( auto it = features.constBegin(); it != features.constEnd(); ++it )
649 {
650 if ( feedback && feedback->isCanceled() )
651 break;
652
653 for ( const Feature &feature : it.value() )
654 {
655 if ( feedback && feedback->isCanceled() )
656 break;
657
658 QgsAbstractProfileResults::Feature outFeature;
659 outFeature.layerIdentifier = mId;
660 outFeature.attributes = { { u"id"_s, feature.featureId } };
661 switch ( type )
662 {
664 outFeature.geometry = feature.geometry;
665 break;
666
668 outFeature.geometry = feature.crossSectionGeometry;
669 break;
670
672 break; // unreachable
673 }
674 res << outFeature;
675 }
676 }
677 return res;
678}
679
681{
683 const QgsVectorLayerProfileGenerator *vlGenerator = qgis::down_cast< const QgsVectorLayerProfileGenerator * >( generator );
684
685 mId = vlGenerator->mId;
686 profileType = vlGenerator->mType;
687 respectLayerSymbology = vlGenerator->mRespectLayerSymbology;
688 mMarkerSymbol.reset( vlGenerator->mProfileMarkerSymbol->clone() );
689 mShowMarkerSymbolInSurfacePlots = vlGenerator->mShowMarkerSymbolInSurfacePlots;
690}
691
692//
693// QgsVectorLayerProfileGenerator
694//
695
698 , mId( layer->id() )
699 , mFeedback( std::make_unique< QgsFeedback >() )
700 , mProfileCurve( request.profileCurve() ? request.profileCurve()->clone() : nullptr )
701 , mTerrainProvider( request.terrainProvider() ? request.terrainProvider()->clone() : nullptr )
702 , mTolerance( request.tolerance() )
703 , mSourceCrs( layer->crs3D() )
704 , mTargetCrs( request.crs() )
705 , mTransformContext( request.transformContext() )
706 , mExtent( layer->extent() )
707 , mSource( std::make_unique< QgsVectorLayerFeatureSource >( layer ) )
708 , mOffset( layer->elevationProperties()->zOffset() )
709 , mScale( layer->elevationProperties()->zScale() )
710 , mType( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->type() )
711 , mClamping( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->clamping() )
712 , mBinding( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->binding() )
713 , mExtrusionEnabled( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->extrusionEnabled() )
714 , mExtrusionHeight( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->extrusionHeight() )
715 , mCustomToleranceEnabled( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->customToleranceEnabled() )
716 , mCustomTolerance( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->customTolerance() )
717 , mExpressionContext( request.expressionContext() )
718 , mFields( layer->fields() )
719 , mDataDefinedProperties( layer->elevationProperties()->dataDefinedProperties() )
720 , mWkbType( layer->wkbType() )
721 , mRespectLayerSymbology( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->respectLayerSymbology() )
722 , mProfileMarkerSymbol( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->profileMarkerSymbol()->clone() )
723 , mShowMarkerSymbolInSurfacePlots( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->showMarkerSymbolInSurfacePlots() )
724 , mLayer( layer )
725{
726 if ( mTerrainProvider )
727 mTerrainProvider->prepare(); // must be done on main thread
728
729 // make sure profile curve is always 2d, or we may get unwanted z value averaging for intersections from GEOS
730 if ( mProfileCurve )
731 mProfileCurve->dropZValue();
732
733 mSymbology = qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->profileSymbology();
734 mElevationLimit = qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->elevationLimit();
735
736 mLineSymbol.reset( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->profileLineSymbol()->clone() );
737 mFillSymbol.reset( qgis::down_cast< QgsVectorLayerElevationProperties * >( layer->elevationProperties() )->profileFillSymbol()->clone() );
738}
739
741{
742 return mId;
743}
744
746{
747 return u"vector"_s;
748}
749
751
753{
754 if ( !mProfileCurve || mFeedback->isCanceled() )
755 return false;
756
757 if ( QgsLineString *profileLine = qgsgeometry_cast<QgsLineString *>( mProfileCurve.get() ) )
758 {
759 // The profile generation code can't deal with curves that enter a single
760 // point multiple times. We handle this for line strings by splitting them
761 // into multiple parts, each with no repeated points, and computing the
762 // profile for each by itself.
763 std::unique_ptr< QgsCurve > origCurve = std::move( mProfileCurve );
764 std::unique_ptr< QgsVectorLayerProfileResults > totalResults;
765 double distanceProcessed = 0;
766
767 QVector<QgsLineString *> disjointParts = profileLine->splitToDisjointXYParts();
768 for ( int i = 0; i < disjointParts.size(); i++ )
769 {
770 mProfileCurve.reset( disjointParts[i] );
771 if ( !generateProfileInner() )
772 {
773 mProfileCurve = std::move( origCurve );
774
775 // Free the rest of the parts
776 for ( int j = i + 1; j < disjointParts.size(); j++ )
777 delete disjointParts[j];
778
779 return false;
780 }
781
782 if ( !totalResults )
783 // Use the first result set as a base
784 totalResults = std::move( mResults );
785 else
786 {
787 // Merge the results, shifting them by distanceProcessed
788 totalResults->mRawPoints.append( mResults->mRawPoints );
789 totalResults->minZ = std::min( totalResults->minZ, mResults->minZ );
790 totalResults->maxZ = std::max( totalResults->maxZ, mResults->maxZ );
791 for ( auto it = mResults->mDistanceToHeightMap.constKeyValueBegin(); it != mResults->mDistanceToHeightMap.constKeyValueEnd(); ++it )
792 {
793 totalResults->mDistanceToHeightMap[it->first + distanceProcessed] = it->second;
794 }
795 for ( auto it = mResults->mDistanceToFeatureId.constKeyValueBegin(); it != mResults->mDistanceToFeatureId.constKeyValueEnd(); ++it )
796 {
797 totalResults->mDistanceToFeatureId[it->first + distanceProcessed] = it->second;
798 }
799 for ( auto it = mResults->features.constKeyValueBegin(); it != mResults->features.constKeyValueEnd(); ++it )
800 {
801 for ( QgsVectorLayerProfileResults::Feature feature : it->second )
802 {
803 feature.crossSectionGeometry.translate( distanceProcessed, 0 );
804 totalResults->features[it->first].push_back( feature );
805 }
806 }
807 }
808
809 distanceProcessed += mProfileCurve->length();
810 }
811
812 mProfileCurve = std::move( origCurve );
813 mResults = std::move( totalResults );
814 return true;
815 }
816
817 return generateProfileInner();
818}
819
820bool QgsVectorLayerProfileGenerator::generateProfileInner( const QgsProfileGenerationContext & )
821{
822 // we need to transform the profile curve to the vector's CRS
823 mTransformedCurve.reset( mProfileCurve->clone() );
824 mLayerToTargetTransform = QgsCoordinateTransform( mSourceCrs, mTargetCrs, mTransformContext );
825 if ( mTerrainProvider )
826 mTargetToTerrainProviderTransform = QgsCoordinateTransform( mTargetCrs, mTerrainProvider->crs(), mTransformContext );
827
828 try
829 {
830 mTransformedCurve->transform( mLayerToTargetTransform, Qgis::TransformDirection::Reverse );
831 }
832 catch ( QgsCsException & )
833 {
834 QgsDebugError( u"Error transforming profile line to vector CRS"_s );
835 return false;
836 }
837
838 const QgsRectangle profileCurveBoundingBox = mTransformedCurve->boundingBox();
839 if ( !profileCurveBoundingBox.intersects( mExtent ) )
840 return false;
841
842 if ( mFeedback->isCanceled() )
843 return false;
844
845 mResults = std::make_unique< QgsVectorLayerProfileResults >();
846 mResults->mLayer = mLayer;
847 mResults->copyPropertiesFromGenerator( this );
848
849 mProfileCurveEngine = std::make_unique<QgsGeos>( mProfileCurve.get() );
850 mProfileCurveEngine->prepareGeometry();
851
852 if ( tolerance() == 0.0 ) // geos does not handle very well buffer with 0 size
853 {
854 mProfileBufferedCurve = std::unique_ptr<QgsAbstractGeometry>( mProfileCurve->clone() );
855 }
856 else
857 {
858 mProfileBufferedCurve = std::unique_ptr<QgsAbstractGeometry>( mProfileCurveEngine->buffer( tolerance(), 8, Qgis::EndCapStyle::Flat, Qgis::JoinStyle::Round, 2, nullptr, mFeedback.get() ) );
859 }
860
861 mProfileBufferedCurveEngine = std::make_unique<QgsGeos>( mProfileBufferedCurve.get() );
862 mProfileBufferedCurveEngine->prepareGeometry();
863
864 mDataDefinedProperties.prepare( mExpressionContext );
865
866 if ( mFeedback->isCanceled() )
867 return false;
868
869 switch ( QgsWkbTypes::geometryType( mWkbType ) )
870 {
872 if ( !generateProfileForPoints() )
873 return false;
874 break;
875
877 if ( !generateProfileForLines() )
878 return false;
879 break;
880
882 if ( !generateProfileForPolygons() )
883 return false;
884 break;
885
888 return false;
889 }
890
891 return true;
892}
893
898
900{
901 return mFeedback.get();
902}
903
904bool QgsVectorLayerProfileGenerator::generateProfileForPoints()
905{
906 // get features from layer
907 QgsFeatureRequest request;
908 request.setCoordinateTransform( QgsCoordinateTransform( mSourceCrs, mTargetCrs, mTransformContext ) );
909 request.setDistanceWithin( QgsGeometry( mProfileCurve->clone() ), tolerance() );
910 request.setSubsetOfAttributes( mDataDefinedProperties.referencedFields( mExpressionContext ), mFields );
911 request.setFeedback( mFeedback.get() );
912
913 // our feature request is using the optimised distance within check (allowing use of spatial index)
914 // BUT this will also include points which are within the tolerance distance before/after the end of line.
915 // So we also need to double check that they fall within the flat buffered curve too.
916
917 QgsFeature feature;
918 QgsFeatureIterator it = mSource->getFeatures( request );
919 while ( !mFeedback->isCanceled() && it.nextFeature( feature ) )
920 {
921 mExpressionContext.setFeature( feature );
922
923 const QgsGeometry g = feature.geometry();
924 for ( auto it = g.const_parts_begin(); !mFeedback->isCanceled() && it != g.const_parts_end(); ++it )
925 {
926 if ( mProfileBufferedCurveEngine->intersects( *it ) )
927 {
928 processIntersectionPoint( qgsgeometry_cast< const QgsPoint * >( *it ), feature );
929 }
930 }
931 }
932 return !mFeedback->isCanceled();
933}
934
935void QgsVectorLayerProfileGenerator::processIntersectionPoint( const QgsPoint *point, const QgsFeature &feature )
936{
937 QString error;
938 const double offset = mDataDefinedProperties.valueAsDouble( QgsMapLayerElevationProperties::Property::ZOffset, mExpressionContext, mOffset );
939
940 const double height = featureZToHeight( point->x(), point->y(), point->z(), offset );
941 mResults->mRawPoints.append( QgsPoint( point->x(), point->y(), height ) );
942 mResults->minZ = std::min( mResults->minZ, height );
943 mResults->maxZ = std::max( mResults->maxZ, height );
944
945 const double distanceAlongProfileCurve = mProfileCurveEngine->lineLocatePoint( *point, &error );
946 mResults->mDistanceToHeightMap.insert( distanceAlongProfileCurve, height );
947 mResults->mDistanceToFeatureId.insert( distanceAlongProfileCurve, feature.id() );
948
949 QgsVectorLayerProfileResults::Feature resultFeature;
950 resultFeature.featureId = feature.id();
951 if ( mExtrusionEnabled )
952 {
953 const double extrusion = mDataDefinedProperties.valueAsDouble( QgsMapLayerElevationProperties::Property::ExtrusionHeight, mExpressionContext, mExtrusionHeight );
954
955 resultFeature.geometry = QgsGeometry( new QgsLineString( QgsPoint( point->x(), point->y(), height ), QgsPoint( point->x(), point->y(), height + extrusion ) ) );
956 resultFeature.crossSectionGeometry = QgsGeometry( new QgsLineString( QgsPoint( distanceAlongProfileCurve, height ), QgsPoint( distanceAlongProfileCurve, height + extrusion ) ) );
957 mResults->minZ = std::min( mResults->minZ, height + extrusion );
958 mResults->maxZ = std::max( mResults->maxZ, height + extrusion );
959 }
960 else
961 {
962 resultFeature.geometry = QgsGeometry( new QgsPoint( point->x(), point->y(), height ) );
963 resultFeature.crossSectionGeometry = QgsGeometry( new QgsPoint( distanceAlongProfileCurve, height ) );
964 }
965
966 mResults->features[resultFeature.featureId].append( resultFeature );
967}
968
969void QgsVectorLayerProfileGenerator::processIntersectionCurve( const QgsLineString *intersectionCurve, const QgsFeature &feature )
970{
971 QString error;
972
973 QgsVectorLayerProfileResults::Feature resultFeature;
974 resultFeature.featureId = feature.id();
975 double maxDistanceAlongProfileCurve = std::numeric_limits<double>::lowest();
976
977 const double offset = mDataDefinedProperties.valueAsDouble( QgsMapLayerElevationProperties::Property::ZOffset, mExpressionContext, mOffset );
978 const double extrusion = mDataDefinedProperties.valueAsDouble( QgsMapLayerElevationProperties::Property::ExtrusionHeight, mExpressionContext, mExtrusionHeight );
979
980 const int numPoints = intersectionCurve->numPoints();
981 QVector< double > newX( numPoints );
982 QVector< double > newY( numPoints );
983 QVector< double > newZ( numPoints );
984 QVector< double > newDistance( numPoints );
985
986 const double *inX = intersectionCurve->xData();
987 const double *inY = intersectionCurve->yData();
988 const double *inZ = intersectionCurve->is3D() ? intersectionCurve->zData() : nullptr;
989 double *outX = newX.data();
990 double *outY = newY.data();
991 double *outZ = newZ.data();
992 double *outDistance = newDistance.data();
993
994 QVector< double > extrudedZ;
995 double *extZOut = nullptr;
996 if ( mExtrusionEnabled )
997 {
998 extrudedZ.resize( numPoints );
999 extZOut = extrudedZ.data();
1000 }
1001
1002 for ( int i = 0; !mFeedback->isCanceled() && i < numPoints; ++i )
1003 {
1004 QgsPoint intersectionPoint( *inX, *inY, ( inZ ? *inZ : std::numeric_limits<double>::quiet_NaN() ) );
1005
1006 const double height = featureZToHeight( intersectionPoint.x(), intersectionPoint.y(), intersectionPoint.z(), offset );
1007 const double distanceAlongProfileCurve = mProfileCurveEngine->lineLocatePoint( intersectionPoint, &error );
1008
1009 maxDistanceAlongProfileCurve = std::max( maxDistanceAlongProfileCurve, distanceAlongProfileCurve );
1010
1011 mResults->mRawPoints.append( QgsPoint( intersectionPoint.x(), intersectionPoint.y(), height ) );
1012 mResults->minZ = std::min( mResults->minZ, height );
1013 mResults->maxZ = std::max( mResults->maxZ, height );
1014
1015 mResults->mDistanceToHeightMap.insert( distanceAlongProfileCurve, height );
1016 mResults->mDistanceToFeatureId.insert( distanceAlongProfileCurve, feature.id() );
1017 *outDistance++ = distanceAlongProfileCurve;
1018
1019 *outX++ = intersectionPoint.x();
1020 *outY++ = intersectionPoint.y();
1021 *outZ++ = height;
1022 if ( extZOut )
1023 *extZOut++ = height + extrusion;
1024
1025 if ( mExtrusionEnabled )
1026 {
1027 mResults->minZ = std::min( mResults->minZ, height + extrusion );
1028 mResults->maxZ = std::max( mResults->maxZ, height + extrusion );
1029 }
1030 inX++;
1031 inY++;
1032 if ( inZ )
1033 inZ++;
1034 }
1035
1036 mResults->mDistanceToHeightMap.insert( maxDistanceAlongProfileCurve + Qgis::DEFAULT_SEGMENT_EPSILON, std::numeric_limits<double>::quiet_NaN() );
1037
1038 if ( mFeedback->isCanceled() )
1039 return;
1040
1041 // create geometries from vector data
1042 if ( mExtrusionEnabled )
1043 {
1044 auto ring = std::make_unique< QgsLineString >( newX, newY, newZ );
1045 auto extrudedRing = std::make_unique< QgsLineString >( newX, newY, extrudedZ );
1046 std::unique_ptr< QgsLineString > reversedExtrusion( extrudedRing->reversed() );
1047 ring->append( reversedExtrusion.get() );
1048 ring->close();
1049 resultFeature.geometry = QgsGeometry( new QgsPolygon( ring.release() ) );
1050
1051 auto distanceVHeightRing = std::make_unique< QgsLineString >( newDistance, newZ );
1052 auto extrudedDistanceVHeightRing = std::make_unique< QgsLineString >( newDistance, extrudedZ );
1053 std::unique_ptr< QgsLineString > reversedDistanceVHeightExtrusion( extrudedDistanceVHeightRing->reversed() );
1054 distanceVHeightRing->append( reversedDistanceVHeightExtrusion.get() );
1055 distanceVHeightRing->close();
1056 resultFeature.crossSectionGeometry = QgsGeometry( new QgsPolygon( distanceVHeightRing.release() ) );
1057 }
1058 else
1059 {
1060 resultFeature.geometry = QgsGeometry( new QgsLineString( newX, newY, newZ ) );
1061 resultFeature.crossSectionGeometry = QgsGeometry( new QgsLineString( newDistance, newZ ) );
1062 }
1063
1064 mResults->features[resultFeature.featureId].append( resultFeature );
1065}
1066
1067bool QgsVectorLayerProfileGenerator::generateProfileForLines()
1068{
1069 // get features from layer
1070 QgsFeatureRequest request;
1071 request.setDestinationCrs( mTargetCrs, mTransformContext );
1072 if ( tolerance() > 0 )
1073 {
1074 request.setDistanceWithin( QgsGeometry( mProfileCurve->clone() ), tolerance() );
1075 }
1076 else
1077 {
1078 request.setFilterRect( mProfileCurve->boundingBox() );
1079 }
1080 request.setSubsetOfAttributes( mDataDefinedProperties.referencedFields( mExpressionContext ), mFields );
1081 request.setFeedback( mFeedback.get() );
1082
1083 auto processCurve = [this]( const QgsFeature &feature, const QgsCurve *featGeomPart ) {
1084 QString error;
1085 std::unique_ptr< QgsAbstractGeometry > intersection( mProfileBufferedCurveEngine->intersection( featGeomPart, &error ) );
1086 if ( !intersection )
1087 return;
1088
1089 if ( mFeedback->isCanceled() )
1090 return;
1091
1092 // Vertical line case
1093 // Intersection is empty : GEOS issue for vertical intersection : use feature geometry as intersection
1094 if ( intersection->isEmpty() )
1095 {
1096 intersection.reset( featGeomPart->clone() );
1097 for ( auto it = intersection->const_parts_begin(); !mFeedback->isCanceled() && it != intersection->const_parts_end(); ++it )
1098 {
1099 if ( const QgsLineString *intersectionCurve = qgsgeometry_cast< const QgsLineString * >( *it ) )
1100 processIntersectionCurve( intersectionCurve, feature );
1101 }
1102 return;
1103 }
1104
1105 QgsGeos featGeomPartGeos( featGeomPart );
1106 featGeomPartGeos.prepareGeometry();
1107
1108 for ( auto it = intersection->const_parts_begin(); !mFeedback->isCanceled() && it != intersection->const_parts_end(); ++it )
1109 {
1110 if ( const QgsPoint *intersectionPoint = qgsgeometry_cast< const QgsPoint * >( *it ) )
1111 {
1112 // unfortunately we need to do some work to interpolate the z value for the line -- GEOS doesn't give us this
1113 QString error;
1114 const double distance = featGeomPartGeos.lineLocatePoint( *intersectionPoint, &error );
1115 std::unique_ptr< QgsPoint > interpolatedPoint( featGeomPart->interpolatePoint( distance ) );
1116
1117 processIntersectionPoint( interpolatedPoint.get(), feature );
1118 }
1119 else if ( const QgsLineString *intersectionCurve = qgsgeometry_cast< const QgsLineString * >( *it ) )
1120 {
1121 // Intersection geometries may not preserve the original Z values
1122 // Rebuild the intersection curve by recovering the 3D coordinates from featGeomPart
1123 auto lineInterpolated = std::make_unique<QgsLineString>();
1124 for ( int i = 0; i < intersectionCurve->numPoints(); ++i )
1125 {
1126 const QgsPoint pt = intersectionCurve->pointN( i );
1127
1128 QString err;
1129 const double distance = featGeomPartGeos.lineLocatePoint( pt, &err );
1130
1131 std::unique_ptr<QgsPoint> pointWithInterpolatedZM( featGeomPart->interpolatePoint( distance ) );
1132 lineInterpolated->addVertex( *pointWithInterpolatedZM );
1133 }
1134
1135 processIntersectionCurve( lineInterpolated.get(), feature );
1136 }
1137 }
1138 };
1139
1140 QgsFeature feature;
1141 QgsFeatureIterator it = mSource->getFeatures( request );
1142 while ( !mFeedback->isCanceled() && it.nextFeature( feature ) )
1143 {
1144 mExpressionContext.setFeature( feature );
1145
1146 const QgsGeometry g = feature.geometry();
1147 for ( auto it = g.const_parts_begin(); !mFeedback->isCanceled() && it != g.const_parts_end(); ++it )
1148 {
1149 if ( mProfileBufferedCurveEngine->intersects( *it ) )
1150 {
1151 processCurve( feature, qgsgeometry_cast< const QgsCurve * >( *it ) );
1152 }
1153 }
1154 }
1155
1156 return !mFeedback->isCanceled();
1157}
1158
1159QgsPoint QgsVectorLayerProfileGenerator::interpolatePointOnTriangle( const QgsPolygon *triangle, double x, double y ) const
1160{
1161 QgsPoint p1, p2, p3;
1163 triangle->exteriorRing()->pointAt( 0, p1, vt );
1164 triangle->exteriorRing()->pointAt( 1, p2, vt );
1165 triangle->exteriorRing()->pointAt( 2, p3, vt );
1166 const double z = QgsMeshLayerUtils::interpolateFromVerticesData( p1, p2, p3, p1.z(), p2.z(), p3.z(), QgsPointXY( x, y ) );
1167 return QgsPoint( x, y, z );
1168};
1169
1170void QgsVectorLayerProfileGenerator::processTriangleIntersectForPoint(
1171 const QgsPolygon *triangle, const QgsPoint *p, QVector< QgsGeometry > &transformedParts, QVector< QgsGeometry > &crossSectionParts, const QgsFeatureId featureId
1172)
1173{
1174 const QgsPoint interpolatedPoint = interpolatePointOnTriangle( triangle, p->x(), p->y() );
1175 mResults->mRawPoints.append( interpolatedPoint );
1176 mResults->minZ = std::min( mResults->minZ, interpolatedPoint.z() );
1177 mResults->maxZ = std::max( mResults->maxZ, interpolatedPoint.z() );
1178
1179 QString lastError;
1180 const double distance = mProfileCurveEngine->lineLocatePoint( *p, &lastError );
1181 mResults->mDistanceToHeightMap.insert( distance, interpolatedPoint.z() );
1182 mResults->mDistanceToFeatureId.insert( distance, featureId );
1183
1184 if ( mExtrusionEnabled )
1185 {
1186 const double extrusion = mDataDefinedProperties.valueAsDouble( QgsMapLayerElevationProperties::Property::ExtrusionHeight, mExpressionContext, mExtrusionHeight );
1187
1188 transformedParts.append( QgsGeometry( new QgsLineString( interpolatedPoint, QgsPoint( interpolatedPoint.x(), interpolatedPoint.y(), interpolatedPoint.z() + extrusion ) ) ) );
1189 crossSectionParts.append( QgsGeometry( new QgsLineString( QgsPoint( distance, interpolatedPoint.z() ), QgsPoint( distance, interpolatedPoint.z() + extrusion ) ) ) );
1190 mResults->minZ = std::min( mResults->minZ, interpolatedPoint.z() + extrusion );
1191 mResults->maxZ = std::max( mResults->maxZ, interpolatedPoint.z() + extrusion );
1192 }
1193 else
1194 {
1195 transformedParts.append( QgsGeometry( new QgsPoint( interpolatedPoint ) ) );
1196 crossSectionParts.append( QgsGeometry( new QgsPoint( distance, interpolatedPoint.z() ) ) );
1197 }
1198}
1199
1200void QgsVectorLayerProfileGenerator::processTriangleIntersectForLine(
1201 const QgsPolygon *triangle, const QgsLineString *intersectionLine, QVector< QgsGeometry > &transformedParts, QVector< QgsGeometry > &crossSectionParts, const QgsFeatureId featureId
1202)
1203{
1204 if ( triangle->exteriorRing()->numPoints() < 4 ) // not a polygon
1205 return;
1206
1207 int numPoints = intersectionLine->numPoints();
1208 QVector< double > newX( numPoints );
1209 QVector< double > newY( numPoints );
1210 QVector< double > newZ( numPoints );
1211 QVector< double > newDistance( numPoints );
1212
1213 const double *inX = intersectionLine->xData();
1214 const double *inY = intersectionLine->yData();
1215 const double *inZ = intersectionLine->is3D() ? intersectionLine->zData() : nullptr;
1216 double *outX = newX.data();
1217 double *outY = newY.data();
1218 double *outZ = newZ.data();
1219 double *outDistance = newDistance.data();
1220
1221 double minDistanceAlongProfileCurve = std::numeric_limits< double >::max();
1222 double maxDistanceAlongProfileCurve = std::numeric_limits< double >::lowest();
1223 QVector< double > extrudedZ;
1224 double *extZOut = nullptr;
1225 double extrusion = 0;
1226
1227 if ( mExtrusionEnabled )
1228 {
1229 extrudedZ.resize( numPoints );
1230 extZOut = extrudedZ.data();
1231
1232 extrusion = mDataDefinedProperties.valueAsDouble( QgsMapLayerElevationProperties::Property::ExtrusionHeight, mExpressionContext, mExtrusionHeight );
1233 }
1234
1235 QString lastError;
1236 QVector< QPair< double, double > > segmentDistanceToHeight;
1237 segmentDistanceToHeight.reserve( numPoints );
1238 for ( int i = 0; !mFeedback->isCanceled() && i < numPoints; ++i )
1239 {
1240 double x = *inX++;
1241 double y = *inY++;
1242 double z = inZ ? *inZ++ : 0;
1243
1244 QgsPoint interpolatedPoint( x, y, z ); // general case (not a triangle)
1245
1246 *outX++ = x;
1247 *outY++ = y;
1248 if ( triangle->exteriorRing()->numPoints() == 4 ) // triangle case
1249 {
1250 interpolatedPoint = interpolatePointOnTriangle( triangle, x, y );
1251 }
1252 double tempOutZ = std::isnan( interpolatedPoint.z() ) ? 0.0 : interpolatedPoint.z();
1253 *outZ++ = tempOutZ;
1254
1255 if ( mExtrusionEnabled )
1256 *extZOut++ = tempOutZ + extrusion;
1257
1258 mResults->mRawPoints.append( interpolatedPoint );
1259 mResults->minZ = std::min( mResults->minZ, interpolatedPoint.z() );
1260 mResults->maxZ = std::max( mResults->maxZ, interpolatedPoint.z() );
1261 if ( mExtrusionEnabled )
1262 {
1263 mResults->minZ = std::min( mResults->minZ, interpolatedPoint.z() + extrusion );
1264 mResults->maxZ = std::max( mResults->maxZ, interpolatedPoint.z() + extrusion );
1265 }
1266
1267 const double distance = mProfileCurveEngine->lineLocatePoint( interpolatedPoint, &lastError );
1268 *outDistance++ = distance;
1269
1270 segmentDistanceToHeight.append( { distance, interpolatedPoint.z() } );
1271 minDistanceAlongProfileCurve = std::min( distance, minDistanceAlongProfileCurve );
1272 maxDistanceAlongProfileCurve = std::max( distance, maxDistanceAlongProfileCurve );
1273 }
1274
1275 if ( numPoints > 0 )
1276 {
1277 // The end of a segment may be at the same distance as the start of the next one
1278 // for adjacent parts, so one point would overwrite the other in mDistanceToHeightMap.
1279 // Shift the segment ends slightly inwards to keep both points.
1280 for ( const QPair< double, double > &point : std::as_const( segmentDistanceToHeight ) )
1281 {
1282 double distance = point.first;
1283 if ( qgsDoubleNear( distance, minDistanceAlongProfileCurve, Qgis::DEFAULT_SEGMENT_EPSILON ) )
1284 {
1286 }
1287 else if ( qgsDoubleNear( distance, maxDistanceAlongProfileCurve, Qgis::DEFAULT_SEGMENT_EPSILON ) )
1288 {
1290 }
1291
1292 mResults->mDistanceToHeightMap.insert( distance, point.second );
1293 mResults->mDistanceToFeatureId.insert( distance, featureId );
1294 }
1295
1296 // NaN separators are inserted by calling insertSurfaceSeparators()
1297 // once all features are processed.
1298 // This prevents splitting adjacent parts of the same surface.
1299 mSurfaceIntervals.append( { minDistanceAlongProfileCurve, maxDistanceAlongProfileCurve } );
1300 }
1301
1302 if ( mFeedback->isCanceled() )
1303 return;
1304
1305 if ( mExtrusionEnabled )
1306 {
1307 auto ring = std::make_unique< QgsLineString >( newX, newY, newZ );
1308 auto extrudedRing = std::make_unique< QgsLineString >( newX, newY, extrudedZ );
1309 std::unique_ptr< QgsLineString > reversedExtrusion( extrudedRing->reversed() );
1310 ring->append( reversedExtrusion.get() );
1311 ring->close();
1312 transformedParts.append( QgsGeometry( new QgsPolygon( ring.release() ) ) );
1313
1314 auto distanceVHeightRing = std::make_unique< QgsLineString >( newDistance, newZ );
1315 auto extrudedDistanceVHeightRing = std::make_unique< QgsLineString >( newDistance, extrudedZ );
1316 std::unique_ptr< QgsLineString > reversedDistanceVHeightExtrusion( extrudedDistanceVHeightRing->reversed() );
1317 distanceVHeightRing->append( reversedDistanceVHeightExtrusion.get() );
1318 distanceVHeightRing->close();
1319 crossSectionParts.append( QgsGeometry( new QgsPolygon( distanceVHeightRing.release() ) ) );
1320 }
1321 else
1322 {
1323 transformedParts.append( QgsGeometry( new QgsLineString( newX, newY, newZ ) ) );
1324 crossSectionParts.append( QgsGeometry( new QgsLineString( newDistance, newZ ) ) );
1325 }
1326};
1327
1328void QgsVectorLayerProfileGenerator::processTriangleIntersectForPolygon(
1329 const QgsPolygon *sourcePolygon, const QgsPolygon *intersectionPolygon, QVector< QgsGeometry > &transformedParts, QVector< QgsGeometry > &crossSectionParts, const QgsFeatureId featureId
1330)
1331{
1332 bool oldExtrusion = mExtrusionEnabled;
1333
1334 /* Polyone extrusion produces I or C or inverted C shapes because the starting and ending points are the same.
1335 We observe the same case with linestrings if the starting and ending points are not at the ends.
1336 In the case below, the Z polygon projected onto the curve produces a shape that cannot be used to represent the extrusion ==> we would obtain a 3D volume.
1337 In order to avoid having strange shapes that cannot be understood by the end user, extrusion is deactivated in the case of polygons.
1338
1339 .^..
1340 ./ | \..
1341 ../ | \...
1342 ../ | \...
1343 ../ | \.. ....^..
1344 ../ | ........\.../ \... ^
1345 ../ ......|......./ \... \.... .../ \
1346 /,........../ | \.. \... / \
1347 v | \... ..../ \... \
1348 | \ ./ \... \
1349 | v \.. \
1350 | `v
1351 |
1352 .^..
1353 ./ \..
1354 ../ \...
1355 ../ \...
1356 ../ \.. ....^..
1357 ../ ........\.../ \... ^
1358 ../ ............../ \... \.... .../ \
1359 /,........../ \.. \... / \
1360 v \... ..../ \... \
1361 \ ./ \... \
1362 v \.. \
1363 `v
1364 */
1365 mExtrusionEnabled = false;
1366 if ( mProfileBufferedCurveEngine->contains( sourcePolygon ) ) // sourcePolygon is entirely inside curve buffer, we keep it as whole
1367 {
1368 if ( const QgsCurve *exterior = sourcePolygon->exteriorRing() )
1369 {
1370 const QgsLineString *exteriorLine = qgsgeometry_cast<const QgsLineString *>( exterior );
1371 processTriangleIntersectForLine( sourcePolygon, exteriorLine, transformedParts, crossSectionParts, featureId );
1372 }
1373 for ( int i = 0; i < sourcePolygon->numInteriorRings(); ++i )
1374 {
1375 const QgsLineString *interiorLine = qgsgeometry_cast<const QgsLineString *>( sourcePolygon->interiorRing( i ) );
1376 processTriangleIntersectForLine( sourcePolygon, interiorLine, transformedParts, crossSectionParts, featureId );
1377 }
1378 }
1379 else // sourcePolygon is partially inside curve buffer, the intersectionPolygon is closed due to the intersection operation then
1380 // it must be 'reopened'
1381 {
1382 if ( const QgsCurve *exterior = intersectionPolygon->exteriorRing() )
1383 {
1384 QgsLineString *exteriorLine = qgsgeometry_cast<const QgsLineString *>( exterior )->clone();
1385 exteriorLine->deleteVertex( QgsVertexId( 0, 0, exteriorLine->numPoints() - 1 ) ); // open linestring
1386 processTriangleIntersectForLine( sourcePolygon, exteriorLine, transformedParts, crossSectionParts, featureId );
1387 delete exteriorLine;
1388 }
1389 for ( int i = 0; i < intersectionPolygon->numInteriorRings(); ++i )
1390 {
1391 const QgsLineString *interiorLine = qgsgeometry_cast<const QgsLineString *>( intersectionPolygon->interiorRing( i ) );
1392 if ( mProfileBufferedCurveEngine->contains( interiorLine ) ) // interiorLine is entirely inside curve buffer
1393 {
1394 processTriangleIntersectForLine( sourcePolygon, interiorLine, transformedParts, crossSectionParts, featureId );
1395 }
1396 else
1397 {
1398 std::unique_ptr< QgsLineString > newInteriorLine( qgsgeometry_cast<const QgsLineString *>( intersectionPolygon->interiorRing( i ) )->clone() );
1399 newInteriorLine->deleteVertex( QgsVertexId( 0, 0, interiorLine->numPoints() - 1 ) ); // open linestring
1400 processTriangleIntersectForLine( sourcePolygon, newInteriorLine.get(), transformedParts, crossSectionParts, featureId );
1401 }
1402 }
1403 }
1404
1405 mExtrusionEnabled = oldExtrusion;
1406};
1407
1408bool QgsVectorLayerProfileGenerator::generateProfileForPolygons()
1409{
1410 // get features from layer
1411 QgsFeatureRequest request;
1412 request.setDestinationCrs( mTargetCrs, mTransformContext );
1413 if ( tolerance() > 0 )
1414 {
1415 request.setDistanceWithin( QgsGeometry( mProfileCurve->clone() ), tolerance() );
1416 }
1417 else
1418 {
1419 request.setFilterRect( mProfileCurve->boundingBox() );
1420 }
1421 request.setSubsetOfAttributes( mDataDefinedProperties.referencedFields( mExpressionContext ), mFields );
1422 request.setFeedback( mFeedback.get() );
1423
1424 std::function< void( const QgsPolygon *triangle, const QgsAbstractGeometry *intersect, QVector< QgsGeometry > &, QVector< QgsGeometry > &, const QgsFeatureId ) > processTriangleLineIntersect;
1425 processTriangleLineIntersect =
1426 [this]( const QgsPolygon *triangle, const QgsAbstractGeometry *intersection, QVector< QgsGeometry > &transformedParts, QVector< QgsGeometry > &crossSectionParts, const QgsFeatureId featureId ) {
1427 for ( auto it = intersection->const_parts_begin(); !mFeedback->isCanceled() && it != intersection->const_parts_end(); ++it )
1428 {
1429 // intersect may be a (multi)point or (multi)linestring
1430 switch ( QgsWkbTypes::geometryType( ( *it )->wkbType() ) )
1431 {
1433 if ( const QgsPoint *p = qgsgeometry_cast< const QgsPoint * >( *it ) )
1434 {
1435 processTriangleIntersectForPoint( triangle, p, transformedParts, crossSectionParts, featureId );
1436 }
1437 break;
1438
1440 if ( const QgsLineString *intersectionLine = qgsgeometry_cast< const QgsLineString * >( *it ) )
1441 {
1442 processTriangleIntersectForLine( triangle, intersectionLine, transformedParts, crossSectionParts, featureId );
1443 }
1444 break;
1445
1447 if ( const QgsPolygon *poly = qgsgeometry_cast< const QgsPolygon * >( *it ) )
1448 {
1449 processTriangleIntersectForPolygon( triangle, poly, transformedParts, crossSectionParts, featureId );
1450 }
1451 break;
1452
1455 return;
1456 }
1457 }
1458 };
1459
1460 auto triangleIsCollinearInXYPlane = []( const QgsPolygon *polygon ) -> bool {
1461 const QgsLineString *ring = qgsgeometry_cast< const QgsLineString * >( polygon->exteriorRing() );
1462 return QgsGeometryUtilsBase::pointsAreCollinear( ring->xAt( 0 ), ring->yAt( 0 ), ring->xAt( 1 ), ring->yAt( 1 ), ring->xAt( 2 ), ring->yAt( 2 ), 0.005 );
1463 };
1464
1465 auto processPolygon =
1466 [this,
1467 &processTriangleLineIntersect,
1468 &triangleIsCollinearInXYPlane]( const QgsCurvePolygon *polygon, QVector< QgsGeometry > &transformedParts, QVector< QgsGeometry > &crossSectionParts, double offset, bool &wasCollinear, const QgsFeatureId featureId ) {
1469 std::unique_ptr< QgsPolygon > clampedPolygon;
1470 if ( const QgsPolygon *p = qgsgeometry_cast< const QgsPolygon * >( polygon ) )
1471 {
1472 clampedPolygon.reset( p->clone() );
1473 }
1474 else
1475 {
1476 clampedPolygon.reset( qgsgeometry_cast< QgsPolygon * >( polygon->segmentize() ) );
1477 }
1478 clampAltitudes( clampedPolygon.get(), offset );
1479
1480 if ( mFeedback->isCanceled() )
1481 return;
1482
1483 if ( tolerance() > 0.0 ) // if the tolerance is not 0.0 we will have a polygon / polygon intersection, we do not need tessellation
1484 {
1485 QString error;
1486 if ( mProfileBufferedCurveEngine->intersects( clampedPolygon.get(), &error ) )
1487 {
1488 std::unique_ptr< QgsAbstractGeometry > intersection;
1489 intersection.reset( mProfileBufferedCurveEngine->intersection( clampedPolygon.get(), &error ) );
1490 if ( error.isEmpty() )
1491 {
1492 processTriangleLineIntersect( clampedPolygon.get(), intersection.get(), transformedParts, crossSectionParts, featureId );
1493 }
1494 else
1495 {
1496 // this case may occur with vertical object as geos does not handle very well 3D data.
1497 // Geos works in 2D from the 3D coordinates then re-add the Z values, but when 2D-from-3D objects are vertical, they are topologically incorrects!
1498 // This piece of code is just a fix to handle this case, a better and real 3D capable library is needed (like SFCGAL).
1499 QgsLineString *ring = qgsgeometry_cast< QgsLineString * >( clampedPolygon->exteriorRing() );
1500 int numPoints = ring->numPoints();
1501 QVector< double > newX( numPoints );
1502 QVector< double > newY( numPoints );
1503 QVector< double > newZ( numPoints );
1504 double *outX = newX.data();
1505 double *outY = newY.data();
1506 double *outZ = newZ.data();
1507
1508 const double *inX = ring->xData();
1509 const double *inY = ring->yData();
1510 const double *inZ = ring->zData();
1511 for ( int i = 0; !mFeedback->isCanceled() && i < ring->numPoints() - 1; ++i )
1512 {
1513 *outX++ = inX[i] + i * 1.0e-9;
1514 *outY++ = inY[i] + i * 1.0e-9;
1515 *outZ++ = inZ[i];
1516 }
1517 std::unique_ptr< QgsPolygon > shiftedPoly;
1518 shiftedPoly = std::make_unique<QgsPolygon>( new QgsLineString( newX, newY, newZ ) );
1519
1520 intersection.reset( mProfileBufferedCurveEngine->intersection( shiftedPoly.get(), &error ) );
1521 if ( intersection )
1522 processTriangleLineIntersect( clampedPolygon.get(), intersection.get(), transformedParts, crossSectionParts, featureId );
1523#ifdef QGISDEBUG
1524 else
1525 {
1526 QgsDebugMsgLevel( u"processPolygon after shift bad geom! error: %1"_s.arg( error ), 0 );
1527 }
1528#endif
1529 }
1530 }
1531 }
1532 else // ie. polygon / line intersection ==> need tessellation
1533 {
1534 QgsGeometry tessellation;
1535 if ( clampedPolygon->numInteriorRings() == 0 && clampedPolygon->exteriorRing() && clampedPolygon->exteriorRing()->numPoints() == 4 && clampedPolygon->exteriorRing()->isClosed() )
1536 {
1537 // special case -- polygon is already a triangle, so no need to tessellate
1538 auto multiPolygon = std::make_unique< QgsMultiPolygon >();
1539 multiPolygon->addGeometry( clampedPolygon.release() );
1540 tessellation = QgsGeometry( std::move( multiPolygon ) );
1541 }
1542 else
1543 {
1544 const QgsRectangle bounds = clampedPolygon->boundingBox();
1545 QgsTessellator t;
1546 t.setBounds( bounds );
1547 t.addPolygon( *clampedPolygon, 0 );
1548
1549 tessellation = QgsGeometry( t.asMultiPolygon() );
1550 if ( mFeedback->isCanceled() )
1551 return;
1552
1553 tessellation.translate( bounds.xMinimum(), bounds.yMinimum() );
1554 }
1555
1556 // iterate through the tessellation, finding triangles which intersect the line
1557 const int numTriangles = qgsgeometry_cast< const QgsMultiPolygon * >( tessellation.constGet() )->numGeometries();
1558 for ( int i = 0; !mFeedback->isCanceled() && i < numTriangles; ++i )
1559 {
1560 const QgsPolygon *triangle = qgsgeometry_cast< const QgsPolygon * >( qgsgeometry_cast< const QgsMultiPolygon * >( tessellation.constGet() )->geometryN( i ) );
1561
1562 if ( triangleIsCollinearInXYPlane( triangle ) )
1563 {
1564 wasCollinear = true;
1565 const QgsLineString *ring = qgsgeometry_cast< const QgsLineString * >( triangle->exteriorRing() );
1566
1567 QString lastError;
1568 if ( const QgsLineString *ls = qgsgeometry_cast< const QgsLineString * >( mProfileCurve.get() ) )
1569 {
1570 for ( int curveSegmentIndex = 0; curveSegmentIndex < mProfileCurve->numPoints() - 1; ++curveSegmentIndex )
1571 {
1572 const QgsPoint p1 = ls->pointN( curveSegmentIndex );
1573 const QgsPoint p2 = ls->pointN( curveSegmentIndex + 1 );
1574
1575 QgsPoint intersectionPoint;
1576 bool intersectionFound = false;
1577 double minZ = std::numeric_limits< double >::max();
1578 double maxZ = std::numeric_limits< double >::lowest();
1579
1580 for ( auto vertexPair : std::array<std::pair<int, int>, 3> { { { 0, 1 }, { 1, 2 }, { 2, 0 } } } )
1581 {
1582 bool isIntersection = false;
1583 QgsPoint edgeIntersectionPoint;
1584 if ( QgsGeometryUtils::segmentIntersection( ring->pointN( vertexPair.first ), ring->pointN( vertexPair.second ), p1, p2, edgeIntersectionPoint, isIntersection ) )
1585 {
1586 if ( !edgeIntersectionPoint.isEmpty() && !intersectionFound )
1587 {
1588 intersectionPoint = edgeIntersectionPoint;
1589 intersectionFound = true;
1590 }
1591
1592
1593 const double fraction = QgsGeometryUtilsBase::pointFractionAlongLine(
1594 ring->xAt( vertexPair.first ), ring->yAt( vertexPair.first ), ring->xAt( vertexPair.second ), ring->yAt( vertexPair.second ), edgeIntersectionPoint.x(), edgeIntersectionPoint.y()
1595 );
1596 double intersectionZ = ring->zAt( vertexPair.first ) + ( ring->zAt( vertexPair.second ) - ring->zAt( vertexPair.first ) ) * fraction;
1597 minZ = std::min( minZ, intersectionZ );
1598 maxZ = std::max( maxZ, intersectionZ );
1599 }
1600 }
1601
1602 if ( intersectionFound )
1603 {
1604 // need z?
1605 mResults->mRawPoints.append( intersectionPoint );
1606 mResults->minZ = std::min( mResults->minZ, minZ );
1607 mResults->maxZ = std::max( mResults->maxZ, maxZ );
1608
1609 const double distance = mProfileCurveEngine->lineLocatePoint( intersectionPoint, &lastError );
1610
1611 crossSectionParts.append( QgsGeometry( new QgsLineString( QVector< double > { distance, distance }, QVector< double > { minZ, maxZ } ) ) );
1612
1613 mResults->mDistanceToHeightMap.insert( distance, minZ );
1614 mResults->mDistanceToHeightMap.insert( distance, maxZ );
1615 mResults->mDistanceToFeatureId.insert( distance, featureId );
1616 }
1617 }
1618 }
1619 else
1620 {
1621 // curved geometries, not supported yet, but not possible through the GUI anyway
1622 QgsDebugError( u"Collinear triangles with curved profile lines are not supported yet"_s );
1623 }
1624 }
1625 else // not collinear
1626 {
1627 QString error;
1628 if ( mProfileBufferedCurveEngine->intersects( triangle, &error ) )
1629 {
1630 std::unique_ptr< QgsAbstractGeometry > intersection( mProfileBufferedCurveEngine->intersection( triangle, &error ) );
1631 processTriangleLineIntersect( triangle, intersection.get(), transformedParts, crossSectionParts, featureId );
1632 }
1633 }
1634 }
1635 }
1636 };
1637
1638 // ========= MAIN JOB
1639 QgsFeature feature;
1640 QgsFeatureIterator it = mSource->getFeatures( request );
1641 while ( !mFeedback->isCanceled() && it.nextFeature( feature ) )
1642 {
1643 if ( !mProfileBufferedCurveEngine->intersects( feature.geometry().constGet() ) )
1644 continue;
1645
1646 mExpressionContext.setFeature( feature );
1647
1648 const double offset = mDataDefinedProperties.valueAsDouble( QgsMapLayerElevationProperties::Property::ZOffset, mExpressionContext, mOffset );
1649 const QgsGeometry g = feature.geometry();
1650 QVector< QgsGeometry > transformedParts;
1651 QVector< QgsGeometry > crossSectionParts;
1652 bool wasCollinear = false;
1653
1654 // === process intersection of geometry feature parts with the mProfileBoxEngine
1655 for ( auto it = g.const_parts_begin(); !mFeedback->isCanceled() && it != g.const_parts_end(); ++it )
1656 {
1657 if ( mProfileBufferedCurveEngine->intersects( *it ) )
1658 {
1659 if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( *it ) )
1660 {
1661 processPolygon( curvePolygon, transformedParts, crossSectionParts, offset, wasCollinear, feature.id() );
1662 }
1663 else if ( const QgsPolyhedralSurface *polySurface = qgsgeometry_cast< const QgsPolyhedralSurface * >( *it ) )
1664 {
1665 for ( int i = 0; i < polySurface->numPatches(); ++i )
1666 {
1667 const QgsPolygon *polygon = polySurface->patchN( i );
1668 if ( mProfileBufferedCurveEngine->intersects( polygon ) )
1669 {
1670 processPolygon( polygon, transformedParts, crossSectionParts, offset, wasCollinear, feature.id() );
1671 }
1672 }
1673 }
1674 else
1675 {
1676 QgsDebugError( u"Unhandled Geometry type: %1"_s.arg( ( *it )->wktTypeStr() ) );
1677 }
1678 }
1679 }
1680
1681 if ( mFeedback->isCanceled() )
1682 return false;
1683
1684 // === aggregate results for this feature
1685 QgsVectorLayerProfileResults::Feature resultFeature;
1686 resultFeature.featureId = feature.id();
1687 resultFeature.geometry = transformedParts.size() > 1 ? QgsGeometry::collectGeometry( transformedParts ) : transformedParts.value( 0 );
1688 if ( !crossSectionParts.empty() )
1689 {
1690 if ( !wasCollinear )
1691 {
1692 QgsGeometry unioned = QgsGeometry::unaryUnion( crossSectionParts );
1693 if ( unioned.isEmpty() )
1694 {
1695 resultFeature.crossSectionGeometry = QgsGeometry::collectGeometry( crossSectionParts );
1696 }
1697 else
1698 {
1699 if ( unioned.type() == Qgis::GeometryType::Line )
1700 {
1701 unioned = unioned.mergeLines();
1702 }
1703 resultFeature.crossSectionGeometry = unioned;
1704 }
1705 }
1706 else
1707 {
1708 resultFeature.crossSectionGeometry = QgsGeometry::collectGeometry( crossSectionParts );
1709 }
1710 }
1711 mResults->features[resultFeature.featureId].append( resultFeature );
1712 }
1713
1714 insertSurfaceSeparators();
1715 return true;
1716}
1717
1718double QgsVectorLayerProfileGenerator::tolerance() const
1719{
1720 return mCustomToleranceEnabled ? mCustomTolerance : mTolerance;
1721}
1722
1723double QgsVectorLayerProfileGenerator::terrainHeight( double x, double y ) const
1724{
1725 if ( !mTerrainProvider )
1726 return std::numeric_limits<double>::quiet_NaN();
1727
1728 // transform feature point to terrain provider crs
1729 try
1730 {
1731 double dummyZ = 0;
1732 mTargetToTerrainProviderTransform.transformInPlace( x, y, dummyZ );
1733 }
1734 catch ( QgsCsException & )
1735 {
1736 return std::numeric_limits<double>::quiet_NaN();
1737 }
1738
1739 return mTerrainProvider->heightAt( x, y );
1740}
1741
1742double QgsVectorLayerProfileGenerator::featureZToHeight( double x, double y, double z, double offset ) const
1743{
1744 switch ( mClamping )
1745 {
1747 break;
1748
1751 {
1752 const double terrainZ = terrainHeight( x, y );
1753 if ( !std::isnan( terrainZ ) )
1754 {
1755 switch ( mClamping )
1756 {
1758 if ( std::isnan( z ) )
1759 z = terrainZ;
1760 else
1761 z += terrainZ;
1762 break;
1763
1765 z = terrainZ;
1766 break;
1767
1769 break;
1770 }
1771 }
1772 break;
1773 }
1774 }
1775
1776 return ( std::isnan( z ) ? 0 : z ) * mScale + offset;
1777}
1778
1779void QgsVectorLayerProfileGenerator::clampAltitudes( QgsLineString *lineString, const QgsPoint &centroid, double offset ) const
1780{
1781 for ( int i = 0; i < lineString->nCoordinates(); ++i )
1782 {
1783 if ( mFeedback->isCanceled() )
1784 break;
1785
1786 double terrainZ = 0;
1787 switch ( mClamping )
1788 {
1791 {
1792 QgsPointXY pt;
1793 switch ( mBinding )
1794 {
1796 pt.setX( lineString->xAt( i ) );
1797 pt.setY( lineString->yAt( i ) );
1798 break;
1799
1801 pt.set( centroid.x(), centroid.y() );
1802 break;
1803 }
1804
1805 terrainZ = terrainHeight( pt.x(), pt.y() );
1806 break;
1807 }
1808
1810 break;
1811 }
1812
1813 double geomZ = 0;
1814
1815 switch ( mClamping )
1816 {
1819 geomZ = lineString->zAt( i );
1820 break;
1821
1823 break;
1824 }
1825
1826 const double z = ( terrainZ + ( std::isnan( geomZ ) ? 0 : geomZ ) ) * mScale + offset;
1827 lineString->setZAt( i, z );
1828 }
1829}
1830
1831bool QgsVectorLayerProfileGenerator::clampAltitudes( QgsPolygon *polygon, double offset ) const
1832{
1833 if ( !polygon->is3D() )
1834 polygon->addZValue( 0 );
1835
1836 QgsPoint centroid;
1837 switch ( mBinding )
1838 {
1840 break;
1841
1843 centroid = polygon->centroid();
1844 break;
1845 }
1846
1847 QgsCurve *curve = const_cast<QgsCurve *>( polygon->exteriorRing() );
1848 QgsLineString *lineString = qgsgeometry_cast<QgsLineString *>( curve );
1849 if ( !lineString )
1850 return false;
1851
1852 clampAltitudes( lineString, centroid, offset );
1853
1854 for ( int i = 0; i < polygon->numInteriorRings(); ++i )
1855 {
1856 if ( mFeedback->isCanceled() )
1857 break;
1858
1859 QgsCurve *curve = const_cast<QgsCurve *>( polygon->interiorRing( i ) );
1860 QgsLineString *lineString = qgsgeometry_cast<QgsLineString *>( curve );
1861 if ( !lineString )
1862 return false;
1863
1864 clampAltitudes( lineString, centroid, offset );
1865 }
1866 return true;
1867}
1868
1869void QgsVectorLayerProfileGenerator::insertSurfaceSeparators()
1870{
1871 // Insert a NaN separator only when there is a real gap between two parts of the surface
1872 if ( mSurfaceIntervals.size() <= 1 )
1873 {
1874 mSurfaceIntervals.clear();
1875 return;
1876 }
1877
1878 std::sort( mSurfaceIntervals.begin(), mSurfaceIntervals.end() );
1879 double currentEnd = mSurfaceIntervals[0].second;
1880 for ( auto intervalIt = mSurfaceIntervals.cbegin() + 1; intervalIt != mSurfaceIntervals.cend(); ++intervalIt )
1881 {
1882 const double newStart = intervalIt->first;
1883 if ( newStart > currentEnd + Qgis::DEFAULT_SEGMENT_EPSILON )
1884 {
1885 mResults->mDistanceToHeightMap.insert( currentEnd + Qgis::DEFAULT_SEGMENT_EPSILON, std::numeric_limits<double>::quiet_NaN() );
1886 }
1887 currentEnd = std::max( currentEnd, intervalIt->second );
1888 }
1889
1890 mSurfaceIntervals.clear();
1891}
@ Relative
Elevation is relative to terrain height (final elevation = terrain elevation + feature elevation).
Definition qgis.h:4259
@ Terrain
Elevation is clamped to terrain (final elevation = terrain elevation).
Definition qgis.h:4260
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
Definition qgis.h:4258
VertexType
Types of vertex.
Definition qgis.h:3315
@ Point
Points.
Definition qgis.h:400
@ Line
Lines.
Definition qgis.h:401
@ Polygon
Polygons.
Definition qgis.h:402
@ Unknown
Unknown types.
Definition qgis.h:403
@ Null
No geometry.
Definition qgis.h:404
@ Round
Use rounded joins.
Definition qgis.h:2294
@ Centroid
Clamp just centroid of feature.
Definition qgis.h:4272
@ Vertex
Clamp every vertex of feature.
Definition qgis.h:4271
@ Flat
Flat cap (in line with start/end of line).
Definition qgis.h:2282
static const double DEFAULT_SEGMENT_EPSILON
Default snapping tolerance for segments.
Definition qgis.h:7429
@ ContinuousSurface
The features should be treated as representing values on a continuous surface (eg contour lines).
Definition qgis.h:4677
@ IndividualFeatures
Treat each feature as an individual object (eg buildings).
Definition qgis.h:4676
ProfileExportType
Types of export for elevation profiles.
Definition qgis.h:4714
@ Profile2D
Export profiles as 2D profile lines, with elevation stored in exported geometry Y dimension and dista...
Definition qgis.h:4716
@ Features3D
Export profiles as 3D features, with elevation values stored in exported geometry Z values.
Definition qgis.h:4715
@ DistanceVsElevationTable
Export profiles as a table of sampled distance vs elevation values.
Definition qgis.h:4717
@ Marker
Marker symbol.
Definition qgis.h:672
@ Line
Line symbol.
Definition qgis.h:673
@ Fill
Fill symbol.
Definition qgis.h:674
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2884
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
virtual bool deleteVertex(QgsVertexId position)
Deletes a vertex within the geometry.
virtual QgsPoint centroid() const
Returns the centroid of the geometry.
Abstract base class for objects which generate elevation profiles.
Abstract base class for storage of elevation profiles.
QgsAbstractProfileSurfaceGenerator(const QgsProfileRequest &request)
Constructor for QgsAbstractProfileSurfaceGenerator.
void renderResults(QgsProfileRenderContext &context) override
Renders the results to the specified context.
void copyPropertiesFromGenerator(const QgsAbstractProfileGenerator *generator) override
Copies properties from specified generator to the results object.
QVector< QgsAbstractProfileResults::Feature > asFeatures(Qgis::ProfileExportType type, QgsFeedback *feedback=nullptr) const override
Returns a list of features representing the calculated elevation results.
QVector< QgsProfileIdentifyResults > identify(const QgsProfilePoint &point, const QgsProfileIdentifyContext &context) override
Identify results visible at the specified profile point.
QgsProfileSnapResult snapPoint(const QgsProfilePoint &point, const QgsProfileSnapContext &context) override
Snaps a point to the generated elevation profile.
Handles coordinate transforms between two coordinate systems.
int numInteriorRings() const
Returns the number of interior rings contained with the curve polygon.
bool addZValue(double zValue=0) override
Adds a z-dimension to the geometry, initialized to a preset value.
const QgsCurve * exteriorRing() const
Returns the curve polygon's exterior ring.
const QgsCurve * interiorRing(int i) const
Retrieves an interior ring from the curve polygon.
virtual int numPoints() const =0
Returns the number of points in the curve.
virtual bool pointAt(int node, QgsPoint &point, Qgis::VertexType &type) const =0
Returns the point and vertex type of a point within the curve.
QgsRange which stores a range of double values.
Definition qgsrange.h:217
RAII class to pop scope from an expression context on destruction.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setCoordinateTransform(const QgsCoordinateTransform &transform)
Sets the coordinate transform which will be used to transform the feature's geometries.
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the iterator to check if it should be cance...
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
QgsFeatureRequest & setDistanceWithin(const QgsGeometry &geometry, double distance)
Sets a reference geometry and a maximum distance from this geometry to retrieve features within.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsFeatureId id
Definition qgsfeature.h:63
QgsGeometry geometry
Definition qgsfeature.h:66
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:56
A fill symbol type, for rendering Polygon and MultiPolygon geometries.
static double pointFractionAlongLine(double x1, double y1, double x2, double y2, double px, double py)
Given the line (x1, y1) to (x2, y2) and a point (px, py) returns the fraction of the line length at w...
static bool pointsAreCollinear(double x1, double y1, double x2, double y2, double x3, double y3, double epsilon)
Given the points (x1, y1), (x2, y2) and (x3, y3) returns true if these points can be considered colli...
static bool segmentIntersection(const QgsPoint &p1, const QgsPoint &p2, const QgsPoint &q1, const QgsPoint &q2, QgsPoint &intersectionPoint, bool &isIntersection, double tolerance=1e-8, bool acceptImproperIntersection=false)
Compute the intersection between two segments.
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
Q_INVOKABLE bool boundingBoxIntersects(const QgsRectangle &rectangle) const
Returns true if the bounding box of this geometry intersects with a rectangle.
static QgsGeometry collectGeometry(const QVector< QgsGeometry > &geometries)
Creates a new multipart geometry from a list of QgsGeometry objects.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
Qgis::GeometryType type
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
Qgis::GeometryOperationResult translate(double dx, double dy, double dz=0.0, double dm=0.0)
Translates this geometry by dx, dy, dz and dm.
Line string geometry type, with support for z-dimension and m-values.
A line symbol type, for rendering LineString and MultiLineString geometries.
A marker symbol type, for rendering Point and MultiPoint geometries.
void setY(double y)
Sets the y value of the point.
Definition qgspointxy.h:132
void set(double x, double y)
Sets the x and y value of the point.
Definition qgspointxy.h:139
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
void setX(double x)
Sets the x value of the point.
Definition qgspointxy.h:122
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition qgspoint.cpp:138
double z
Definition qgspoint.h:58
double x
Definition qgspoint.h:56
bool isEmpty() const override
Returns true if the geometry is empty.
Definition qgspoint.cpp:775
double y
Definition qgspoint.h:57
Polygon geometry type.
Definition qgspolygon.h:37
Encapsulates the context in which an elevation profile is to be generated.
Encapsulates the context of identifying profile results.
double maximumPointElevationDelta
Maximum allowed snapping delta for the elevation values when identifying a point.
double maximumPointDistanceDelta
Maximum allowed snapping delta for the distance values when identifying a point.
double maximumSurfaceElevationDelta
Maximum allowed snapping delta for the elevation values when identifying a continuous elevation surfa...
Stores identify results generated by a QgsAbstractProfileResults object.
Encapsulates a point on a distance-elevation profile.
double elevation() const
Returns the elevation of the point.
double distance() const
Returns the distance of the point.
Abstract base class for storage of elevation profiles.
const QTransform & worldTransform() const
Returns the transform from world coordinates to painter coordinates.
QgsDoubleRange elevationRange() const
Returns the range of elevations to include in the render.
QgsDoubleRange distanceRange() const
Returns the range of distances to include in the render.
QgsRenderContext & renderContext()
Returns a reference to the component QgsRenderContext.
Encapsulates properties and constraints relating to fetching elevation profiles from different source...
Encapsulates the context of snapping a profile point.
double maximumPointDistanceDelta
Maximum allowed snapping delta for the distance values when snapping to a point.
double maximumSurfaceElevationDelta
Maximum allowed snapping delta for the elevation values when snapping to a continuous elevation surfa...
double maximumPointElevationDelta
Maximum allowed snapping delta for the elevation values when snapping to a point.
Encapsulates results of snapping a profile point.
QgsProfilePoint snappedPoint
Snapped point.
QSet< QString > referencedFields(const QgsExpressionContext &context=QgsExpressionContext(), bool ignoreContext=false) const final
Returns the set of any fields referenced by the active properties from the collection.
T lower() const
Returns the lower bound of the range.
Definition qgsrange.h:79
T upper() const
Returns the upper bound of the range.
Definition qgsrange.h:86
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.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
Scoped object for saving and restoring a QPainter object's state.
double yAt(int index) const override
Returns the y-coordinate of the specified node in the line string.
void setZAt(int index, double z)
Sets the z-coordinate of the specified node in the simple curve.
int numPoints() const override
Returns the number of points in the curve.
int nCoordinates() const override
Returns the number of nodes contained in the geometry.
double xAt(int index) const override
Returns the x-coordinate of the specified node in the line string.
const double * yData() const
Returns a const pointer to the y vertex data.
double zAt(int index) const override
Returns the z-coordinate of the specified node in the simple curve.
QgsPoint pointN(int i) const
Returns the specified point from inside the simple curve.
const double * xData() const
Returns a const pointer to the x vertex data.
const double * zData() const
Returns a const pointer to the z vertex data, or nullptr if the simple curve does not have z values.
std::unique_ptr< QgsMultiPolygon > asMultiPolygon() const
Returns the triangulation as a multipolygon geometry.
void setBounds(const QgsRectangle &bounds)
Sets scaling and the bounds of the input geometry coordinates.
void addPolygon(const QgsPolygon &polygon, float extrusionHeight)
Tessellates a triangle and adds its vertex entries to the output data array.
Vector layer specific subclass of QgsMapLayerElevationProperties.
Partial snapshot of vector layer's state (only the members necessary for access to features).
Implementation of QgsAbstractProfileGenerator for vector layers.
QgsAbstractProfileResults * takeResults() override
Takes results from the generator.
bool generateProfile(const QgsProfileGenerationContext &context=QgsProfileGenerationContext()) override
Generate the profile (based on data stored in the class).
QString sourceId() const override
Returns a unique identifier representing the source of the profile.
QString type() const override
Returns the unique string identifier for the results type.
~QgsVectorLayerProfileGenerator() override
QgsFeedback * feedback() const override
Access to feedback object of the generator (may be nullptr).
QgsVectorLayerProfileGenerator(QgsVectorLayer *layer, const QgsProfileRequest &request)
Constructor for QgsVectorLayerProfileGenerator.
QVector< QgsProfileIdentifyResults > identify(const QgsProfilePoint &point, const QgsProfileIdentifyContext &context) override
Identify results visible at the specified profile point.
std::unique_ptr< QgsMarkerSymbol > mMarkerSymbol
QVector< QgsGeometry > asGeometries() const override
Returns a list of geometries representing the calculated elevation results.
void renderResults(QgsProfileRenderContext &context) override
Renders the results to the specified context.
QVector< QgsAbstractProfileResults::Feature > asFeatures(Qgis::ProfileExportType type, QgsFeedback *feedback=nullptr) const override
Returns a list of features representing the calculated elevation results.
QgsProfileSnapResult snapPoint(const QgsProfilePoint &point, const QgsProfileSnapContext &context) override
Snaps a point to the generated elevation profile.
QString type() const override
Returns the unique string identifier for the results type.
QHash< QgsFeatureId, QVector< Feature > > features
QMap< double, QgsFeatureId > mDistanceToFeatureId
void copyPropertiesFromGenerator(const QgsAbstractProfileGenerator *generator) override
Copies properties from specified generator to the results object.
Represents a vector layer which manages a vector based dataset.
QgsMapLayerElevationProperties * elevationProperties() override
Returns the layer's elevation properties.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
#define BUILTIN_UNREACHABLE
Definition qgis.h:8483
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
T qgsgeometry_cast(QgsAbstractGeometry *geom)
#define FID_NULL
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:51
QString layerIdentifier
Identifier for grouping output features.
QVariantMap attributes
Exported attributes.
QgsGeometry crossSectionGeometry
Cross section distance vs height geometry for feature.
QgsGeometry geometry
Feature's geometry with any terrain height adjustment and extrusion applied.