QGIS API Documentation 3.99.0-Master (7d2ca374f2d)
Loading...
Searching...
No Matches
qgsrulebasedchunkloader_p.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsrulebasedchunkloader_p.cpp
3 --------------------------------------
4 Date : November 2019
5 Copyright : (C) 2019 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
18#include "qgs3dutils.h"
20#include "qgschunknode.h"
21#include "qgseventtracing.h"
24#include "qgsline3dsymbol.h"
25#include "qgspoint3dsymbol.h"
26#include "qgspolygon3dsymbol.h"
28#include "qgsvectorlayer.h"
31
32#include <QString>
33#include <Qt3DCore/QTransform>
34#include <QtConcurrentRun>
35
36#include "moc_qgsrulebasedchunkloader_p.cpp"
37
38using namespace Qt::StringLiterals;
39
41
42
43QgsRuleBasedChunkLoader::QgsRuleBasedChunkLoader( const QgsRuleBasedChunkLoaderFactory *factory, QgsChunkNode *node )
44 : QgsChunkLoader( node )
45 , mFactory( factory )
46 , mContext( factory->mRenderContext )
47 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
48{
49}
50
51void QgsRuleBasedChunkLoader::start()
52{
53 QgsChunkNode *node = chunk();
54
55 QgsVectorLayer *layer = mFactory->mLayer;
56
57 QgsExpressionContext exprContext;
59 exprContext.setFields( layer->fields() );
60 mContext.setExpressionContext( exprContext );
61
62 // factory is shared among multiple loaders which may be run at the same time
63 // so we need a local copy of our rule tree that does not intefere with others
64 // (e.g. it happened that filter expressions with invalid syntax would cause
65 // nasty crashes when trying to simultaneously record evaluation error)
66 mRootRule.reset( mFactory->mRootRule->clone() );
67
68 mRootRule->createHandlers( layer, mHandlers );
69
70 QSet<QString> attributeNames;
71 mRootRule->prepare( mContext, attributeNames, node->box3D(), mHandlers );
72
73 // build the feature request
74 // only a subset of data to be queried
75 const QgsRectangle rect = node->box3D().toRectangle();
77 req.setDestinationCrs( mContext.crs(), mContext.transformContext() );
78 req.setSubsetOfAttributes( attributeNames, layer->fields() );
79 req.setFilterRect( rect );
80
81 //
82 // this will be run in a background thread
83 //
84 mFutureWatcher = new QFutureWatcher<void>( this );
85
86 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, [this] {
87 if ( !mCanceled )
88 mFactory->mNodesAreLeafs[mNode->tileId().text()] = mNodeIsLeaf;
89 } );
90
91 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
92
93 const QFuture<void> future = QtConcurrent::run( [req = std::move( req ), this] {
94 const QgsEventTracing::ScopedEvent e( u"3D"_s, u"RB chunk load"_s );
95
96 QgsFeature f;
97 QgsFeatureIterator fi = mSource->getFeatures( req );
98 int featureCount = 0;
99 bool featureLimitReached = false;
100 while ( fi.nextFeature( f ) )
101 {
102 if ( mCanceled )
103 break;
104
105 if ( ++featureCount > mFactory->mMaxFeatures )
106 {
107 featureLimitReached = true;
108 break;
109 }
110
111 mContext.expressionContext().setFeature( f );
112 mRootRule->registerFeature( f, mContext, mHandlers );
113 }
114 if ( !featureLimitReached )
115 {
116 QgsDebugMsgLevel( u"All features fetched for node: %1"_s.arg( mNode->tileId().text() ), 3 );
117
118 if ( featureCount == 0 || std::max<double>( mNode->box3D().width(), mNode->box3D().height() ) < QgsVectorLayer3DTilingSettings::maximumLeafExtent() )
119 mNodeIsLeaf = true;
120 }
121 } );
122
123 // emit finished() as soon as the handler is populated with features
124 mFutureWatcher->setFuture( future );
125}
126
127QgsRuleBasedChunkLoader::~QgsRuleBasedChunkLoader()
128{
129 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
130 {
131 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
132 mFutureWatcher->waitForFinished();
133 }
134
135 qDeleteAll( mHandlers );
136 mHandlers.clear();
137}
138
139void QgsRuleBasedChunkLoader::cancel()
140{
141 mCanceled = true;
142}
143
144Qt3DCore::QEntity *QgsRuleBasedChunkLoader::createEntity( Qt3DCore::QEntity *parent )
145{
146 long long featureCount = 0;
147 for ( auto it = mHandlers.constBegin(); it != mHandlers.constEnd(); ++it )
148 {
149 featureCount += it.value()->featureCount();
150 }
151 if ( featureCount == 0 )
152 {
153 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
154 return nullptr;
155 }
156
157 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
158 float zMin = std::numeric_limits<float>::max();
159 float zMax = std::numeric_limits<float>::lowest();
160 for ( auto it = mHandlers.constBegin(); it != mHandlers.constEnd(); ++it )
161 {
162 QgsFeature3DHandler *handler = it.value();
163 handler->finalize( entity, mContext );
164 if ( handler->zMinimum() < zMin )
165 zMin = handler->zMinimum();
166 if ( handler->zMaximum() > zMax )
167 zMax = handler->zMaximum();
168 }
169
170 // fix the vertical range of the node from the estimated vertical range to the true range
171 if ( zMin != std::numeric_limits<float>::max() && zMax != std::numeric_limits<float>::lowest() )
172 {
173 QgsBox3D box = mNode->box3D();
174 box.setZMinimum( zMin );
175 box.setZMaximum( zMax );
176 mNode->setExactBox3D( box );
177 mNode->updateParentBoundingBoxesRecursively();
178 }
179
180 return entity;
181}
182
183
185
186
187QgsRuleBasedChunkLoaderFactory::QgsRuleBasedChunkLoaderFactory( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsRuleBased3DRenderer::Rule *rootRule, double zMin, double zMax, int maxFeatures )
188 : mRenderContext( context )
189 , mLayer( vl )
190 , mRootRule( rootRule->clone() )
191 , mMaxFeatures( maxFeatures )
192{
193 if ( context.crs().type() == Qgis::CrsType::Geocentric )
194 {
195 // TODO: add support for handling of vector layers
196 // (we're using dummy quadtree here to make sure the empty extent does not break the scene completely)
197 QgsDebugError( u"Vector layers in globe scenes are not supported yet!"_s );
198 setupQuadtree( QgsBox3D( -7e6, -7e6, -7e6, 7e6, 7e6, 7e6 ), -1, 3 );
199 return;
200 }
201
202 QgsBox3D rootBox3D( context.extent(), zMin, zMax );
203 // add small padding to avoid clipping of point features located at the edge of the bounding box
204 rootBox3D.grow( 1.0 );
205
206 const float rootError = static_cast<float>( std::max<double>( rootBox3D.width(), rootBox3D.height() ) * QgsVectorLayer3DTilingSettings::tileGeometryErrorRatio() );
207 setupQuadtree( rootBox3D, rootError );
208}
209
210QgsRuleBasedChunkLoaderFactory::~QgsRuleBasedChunkLoaderFactory() = default;
211
212QgsChunkLoader *QgsRuleBasedChunkLoaderFactory::createChunkLoader( QgsChunkNode *node ) const
213{
214 return new QgsRuleBasedChunkLoader( this, node );
215}
216
217bool QgsRuleBasedChunkLoaderFactory::canCreateChildren( QgsChunkNode *node )
218{
219 return mNodesAreLeafs.contains( node->tileId().text() );
220}
221
222QVector<QgsChunkNode *> QgsRuleBasedChunkLoaderFactory::createChildren( QgsChunkNode *node ) const
223{
224 if ( mNodesAreLeafs.value( node->tileId().text(), false ) )
225 return {};
226
227 return QgsQuadtreeChunkLoaderFactory::createChildren( node );
228}
229
231
232QgsRuleBasedChunkedEntity::QgsRuleBasedChunkedEntity( Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsRuleBased3DRenderer::Rule *rootRule )
233 : QgsChunkedEntity( map, 3, new QgsRuleBasedChunkLoaderFactory( Qgs3DRenderContext::fromMapSettings( map ), vl, rootRule, zMin, zMax, tilingSettings.maximumChunkFeatures() ), true )
234{
235 mTransform = new Qt3DCore::QTransform;
236 if ( applyTerrainOffset() )
237 {
238 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, static_cast<float>( map->terrainSettings()->elevationOffset() ) ) );
239 }
240 this->addComponent( mTransform );
241 connect( map, &Qgs3DMapSettings::terrainSettingsChanged, this, &QgsRuleBasedChunkedEntity::onTerrainElevationOffsetChanged );
242
243 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
244}
245
246QgsRuleBasedChunkedEntity::~QgsRuleBasedChunkedEntity()
247{
248 // cancel / wait for jobs
249 cancelActiveJobs();
250}
251
252// if the AltitudeClamping is `Absolute`, do not apply the offset
253bool QgsRuleBasedChunkedEntity::applyTerrainOffset() const
254{
255 QgsRuleBasedChunkLoaderFactory *loaderFactory = static_cast<QgsRuleBasedChunkLoaderFactory *>( mChunkLoaderFactory );
256 if ( loaderFactory )
257 {
258 QgsRuleBased3DRenderer::Rule *rootRule = loaderFactory->mRootRule.get();
259 const QgsRuleBased3DRenderer::RuleList rules = rootRule->children();
260 for ( const auto &rule : rules )
261 {
262 if ( rule->symbol() )
263 {
264 QString symbolType = rule->symbol()->type();
265 if ( symbolType == "line" )
266 {
267 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( rule->symbol() );
268 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
269 {
270 return false;
271 }
272 }
273 else if ( symbolType == "point" )
274 {
275 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( rule->symbol() );
276 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
277 {
278 return false;
279 }
280 }
281 else if ( symbolType == "polygon" )
282 {
283 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( rule->symbol() );
284 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
285 {
286 return false;
287 }
288 }
289 else
290 {
291 QgsDebugMsgLevel( u"QgsRuleBasedChunkedEntityChunkedEntity::applyTerrainOffset, unhandled symbol type %1"_s.arg( symbolType ), 2 );
292 }
293 }
294 }
295 }
296
297 return true;
298}
299
300void QgsRuleBasedChunkedEntity::onTerrainElevationOffsetChanged()
301{
302 const float previousOffset = mTransform->translation()[1];
303 float newOffset = static_cast<float>( qobject_cast<Qgs3DMapSettings *>( sender() )->terrainSettings()->elevationOffset() );
304 if ( !applyTerrainOffset() )
305 {
306 newOffset = 0.0;
307 }
308
309 if ( newOffset != previousOffset )
310 {
311 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, newOffset ) );
312 }
313}
314
315QList<QgsRayCastHit> QgsRuleBasedChunkedEntity::rayIntersection( const QgsRay3D &ray, const QgsRayCastContext &context ) const
316{
317 return QgsVectorLayerChunkedEntity::rayIntersection( activeNodes(), mTransform->matrix(), ray, context, mMapSettings->origin() );
318}
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
Definition qgis.h:4069
@ Geocentric
Geocentric CRS.
Definition qgis.h:2403
Definition of the world.
const QgsAbstractTerrainSettings * terrainSettings() const
Returns the terrain settings.
void terrainSettingsChanged()
Emitted when the terrain settings are changed.
Rendering context for preparation of 3D entities.
QgsCoordinateReferenceSystem crs() const
Returns the coordinate reference system used in the 3D scene.
QgsRectangle extent() const
Returns the 3D scene's 2D extent in the 3D scene's CRS.
double elevationOffset() const
Returns the elevation offset of the terrain (used to move the terrain up or down).
A 3-dimensional box composed of x, y, z coordinates.
Definition qgsbox3d.h:45
void setZMinimum(double z)
Sets the minimum z value.
Definition qgsbox3d.cpp:94
void setZMaximum(double z)
Sets the maximum z value.
Definition qgsbox3d.cpp:99
void grow(double delta)
Grows the box in place by the specified amount in all dimensions.
Definition qgsbox3d.cpp:307
Qgis::CrsType type() const
Returns the type of the CRS.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of 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 & 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.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
3D symbol that draws linestring geometries as planar polygons (created from lines using a buffer with...
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain).
3D symbol that draws point geometries as 3D objects using one of the predefined shapes.
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain).
3D symbol that draws polygon geometries as planar polygons, optionally extruded (with added walls).
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain).
A representation of a ray in 3D.
Definition qgsray3d.h:31
Responsible for defining parameters of the ray casting operations in 3D map canvases.
A rectangle specified with double values.
A child rule for a QgsRuleBased3DRenderer.
const QgsRuleBased3DRenderer::RuleList & children() const
Returns all children rules of this rule.
QList< QgsRuleBased3DRenderer::Rule * > RuleList
Defines configuration of how a vector layer gets tiled for 3D rendering.
static double tileGeometryErrorRatio()
This is the ratio of tile's largest size to geometry error and is used when setting the root tile's e...
bool showBoundingBoxes() const
Returns whether to display bounding boxes of entity's tiles (for debugging).
static double maximumLeafExtent()
This is the maximum width or height a tile can have and still be considered a leaf node.
Partial snapshot of vector layer's state (only the members necessary for access to features).
Represents a vector layer which manages a vector based dataset.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63