QGIS API Documentation 4.3.0-Master (52aa6503bed)
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 <functional>
19
20#include "qgs3dutils.h"
22#include "qgschunknode.h"
23#include "qgseventtracing.h"
26#include "qgsline3dsymbol.h"
27#include "qgspoint3dsymbol.h"
28#include "qgspolygon3dsymbol.h"
30#include "qgsthreadingutils.h"
31#include "qgsvectorlayer.h"
34
35#include <QMutex>
36#include <QString>
37#include <Qt3DCore/QTransform>
38#include <QtConcurrentRun>
39
40#include "moc_qgsrulebasedchunkloader_p.cpp"
41
42using namespace Qt::StringLiterals;
43
45
46
47QgsRuleBasedChunkLoader::QgsRuleBasedChunkLoader( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsRuleBased3DRenderer::Rule *rootRule, double zMin, double zMax, int maxFeatures )
48 : mRenderContext( context )
49 , mLayer( vl )
50 , mRootRule( rootRule->clone() )
51 , mNodesAreLeafs( std::make_shared<NodeIsLeafMap>() )
52 , mMaxFeatures( maxFeatures )
53{
54 if ( context.crs().type() == Qgis::CrsType::Geocentric )
55 {
56 // TODO: add support for handling of vector layers
57 // (we're using dummy quadtree here to make sure the empty extent does not break the scene completely)
58 QgsDebugError( u"Vector layers in globe scenes are not supported yet!"_s );
59 setupQuadtree( QgsBox3D( -7e6, -7e6, -7e6, 7e6, 7e6, 7e6 ), -1, 3 );
60 return;
61 }
62
63 // choose the smaller root extent between context and mLayer ones:
64 QgsRectangle extent = context.extent();
65 const QgsRectangle layerExtentInMapCrs = Qgs3DUtils::tryReprojectExtent2D( mLayer->extent(), mLayer->crs(), context.crs(), context.transformContext() );
66 if ( layerExtentInMapCrs.isValid() )
67 {
68 extent = context.extent().intersect( layerExtentInMapCrs );
69 }
70 if ( extent.isValid() )
71 {
72 QgsBox3D rootBox3D( extent, zMin, zMax );
73 // add small padding to avoid clipping of point features located at the edge of the bounding box
74 rootBox3D.grow( 1.0 );
75
76 const float rootError = static_cast<float>( std::max<double>( rootBox3D.width(), rootBox3D.height() ) * QgsVectorLayer3DTilingSettings::tileGeometryErrorRatio() );
77 setupQuadtree( rootBox3D, rootError );
78 }
79}
80
81QgsRuleBasedChunkLoader::~QgsRuleBasedChunkLoader() = default;
82
83QFuture<QgsChunkLoaderResult> QgsRuleBasedChunkLoader::loadChunk( QgsChunkNode *node )
84{
85 QgsExpressionContext exprContext;
87 exprContext.setFields( mLayer->fields() );
88 Qgs3DRenderContext renderCtx = mRenderContext; // Copy since we mutate it
89 renderCtx.setExpressionContext( exprContext );
90
91 // loader is shared among multiple threads which may be run at the same time
92 // so we need a local copy of our rule tree that does not intefere with others
93 // (e.g. it happened that filter expressions with invalid syntax would cause
94 // nasty crashes when trying to simultaneously record evaluation error)
95 std::unique_ptr<QgsRuleBased3DRenderer::Rule> rootRule( mRootRule->clone() );
96
98 rootRule->createHandlers( mLayer, handlers );
99
100 QSet<QString> attributeNames;
101 rootRule->prepare( renderCtx, attributeNames, node->box3D(), handlers );
102
103 // build the feature request
104 // only a subset of data to be queried
105 const QgsRectangle rect = node->box3D().toRectangle();
107 req.setDestinationCrs( renderCtx.crs(), renderCtx.transformContext() );
108 req.setSubsetOfAttributes( attributeNames, mLayer->fields() );
109 req.setFilterRect( rect );
110
111 auto source = std::make_unique<QgsVectorLayerFeatureSource>( mLayer );
112
113 return QtConcurrent::run( &QgsRuleBasedChunkLoader::loadChunkInWorker, std::move( handlers ), std::move( renderCtx ), std::move( rootRule ), std::move( source ), std::move( req ), node, mMaxFeatures, mNodesAreLeafs )
114 .then( this, [this, node]( ChunkData data ) { return QgsChunkLoaderResult { std::bind_front( &QgsRuleBasedChunkLoader::createEntity, this, node, data ) }; } );
115}
116
117void QgsRuleBasedChunkLoader::loadChunkInWorker(
118 QPromise<ChunkData> &promise,
120 Qgs3DRenderContext renderCtx,
121 const std::unique_ptr<QgsRuleBased3DRenderer::Rule> &rootRule,
122 const std::unique_ptr<QgsVectorLayerFeatureSource> &source,
123 const QgsFeatureRequest &req,
124 QgsChunkNode *node,
125 int maxFeatures,
126 const std::shared_ptr<NodeIsLeafMap> &nodesAreLeaves
127)
128{
129 const QgsScopedEvent e( u"3D"_s, u"RB chunk load"_s );
130
131 QgsFeature f;
132 QgsFeatureIterator fi = source->getFeatures( req );
133 int featureCount = 0;
134 bool featureLimitReached = false;
135 while ( fi.nextFeature( f ) )
136 {
137 if ( promise.isCanceled() )
138 break;
139
140 if ( ++featureCount > maxFeatures )
141 {
142 featureLimitReached = true;
143 break;
144 }
145
146 renderCtx.expressionContext().setFeature( f );
147 rootRule->registerFeature( f, renderCtx, handlers );
148 }
149
150 bool nodeIsLeaf = false;
151 if ( !featureLimitReached )
152 {
153 QgsDebugMsgLevel( u"All features fetched for node: %1"_s.arg( node->tileId().text() ), 3 );
154
155 if ( featureCount == 0 || std::max<double>( node->box3D().width(), node->box3D().height() ) < QgsVectorLayer3DTilingSettings::maximumLeafExtent() )
156 nodeIsLeaf = true;
157 }
158
159 {
160 QMutexLocker<QMutex> locker( &nodesAreLeaves->mutex );
161 nodesAreLeaves->map[node->tileId().text()] = nodeIsLeaf;
162 }
163
164 promise.addResult( ChunkData { .handlers = std::move( handlers ), .renderCtx = std::move( renderCtx ) } );
165}
166
167Qt3DCore::QEntity *QgsRuleBasedChunkLoader::createEntity( QgsChunkNode *node, ChunkData data, Qt3DCore::QEntity *parent )
168{
170 long long featureCount = 0;
171 for ( auto it = data.handlers.constBegin(); it != data.handlers.constEnd(); ++it )
172 {
173 featureCount += it.value()->featureCount();
174 }
175 if ( featureCount == 0 )
176 {
177 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
178 return nullptr;
179 }
180
181 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
182 float zMin = std::numeric_limits<float>::max();
183 float zMax = std::numeric_limits<float>::lowest();
184 for ( auto it = data.handlers.constBegin(); it != data.handlers.constEnd(); ++it )
185 {
186 QgsFeature3DHandler *handler = it.value();
187 handler->finalize( entity, data.renderCtx );
188 if ( handler->zMinimum() < zMin )
189 zMin = handler->zMinimum();
190 if ( handler->zMaximum() > zMax )
191 zMax = handler->zMaximum();
192 }
193 // fix the vertical range of the node from the estimated vertical range to the true range
194 if ( zMin != std::numeric_limits<float>::max() && zMax != std::numeric_limits<float>::lowest() )
195 {
196 QgsBox3D box = node->box3D();
197 box.setZMinimum( zMin );
198 box.setZMaximum( zMax );
199 node->setExactBox3D( box );
200 node->updateParentBoundingBoxesRecursively();
201 }
202
203 // TODO: Use smart pointers not to leak data.handlers if createEntity is never called.
204 qDeleteAll( data.handlers );
205
206 return entity;
207}
208
209QFuture<QVector<QgsChunkNode *>> QgsRuleBasedChunkLoader::createChildren( QgsChunkNode *node )
210{
211 {
212 QMutexLocker<QMutex> locker( &mNodesAreLeafs->mutex );
213 if ( mNodesAreLeafs->map.value( node->tileId().text(), false ) )
214 return QtFuture::makeReadyValueFuture( QVector<QgsChunkNode *> {} );
215 }
216
217 return QgsQuadtreeChunkLoader::createChildren( node );
218}
219
221
222QgsRuleBasedChunkedEntity::QgsRuleBasedChunkedEntity(
223 Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsRuleBased3DRenderer::Rule *rootRule
224)
225 : QgsAbstractFeatureBasedChunkedEntity( map, 3, new QgsRuleBasedChunkLoader( Qgs3DRenderContext::fromMapSettings( map ), vl, rootRule, zMin, zMax, tilingSettings.maximumChunkFeatures() ), true )
226{
227 onTerrainElevationOffsetChanged();
228 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
229}
230
231QgsRuleBasedChunkedEntity::~QgsRuleBasedChunkedEntity()
232{
233 // cancel / wait for jobs
234 cancelActiveJobs();
235}
236
237// if the AltitudeClamping is `Absolute`, do not apply the offset
238bool QgsRuleBasedChunkedEntity::applyTerrainOffset() const
239{
240 QgsRuleBasedChunkLoader *loader = static_cast<QgsRuleBasedChunkLoader *>( mChunkLoader );
241 if ( loader )
242 {
243 QgsRuleBased3DRenderer::Rule *rootRule = loader->mRootRule.get();
244 const QgsRuleBased3DRenderer::RuleList rules = rootRule->children();
245 for ( const auto &rule : rules )
246 {
247 if ( rule->symbol() )
248 {
249 QString symbolType = rule->symbol()->type();
250 if ( symbolType == "line" )
251 {
252 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( rule->symbol() );
253 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
254 {
255 return false;
256 }
257 }
258 else if ( symbolType == "point" )
259 {
260 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( rule->symbol() );
261 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
262 {
263 return false;
264 }
265 }
266 else if ( symbolType == "polygon" )
267 {
268 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( rule->symbol() );
269 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
270 {
271 return false;
272 }
273 }
274 else
275 {
276 QgsDebugMsgLevel( u"QgsRuleBasedChunkedEntityChunkedEntity::applyTerrainOffset, unhandled symbol type %1"_s.arg( symbolType ), 2 );
277 }
278 }
279 }
280 }
281
282 return true;
283}
284
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
Definition qgis.h:4246
@ Geocentric
Geocentric CRS.
Definition qgis.h:2516
Definition of the world.
Rendering context for preparation of 3D entities.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
QgsCoordinateReferenceSystem crs() const
Returns the coordinate reference system used in the 3D scene.
QgsExpressionContext & expressionContext()
Gets the expression context.
QgsRectangle extent() const
Returns the 3D scene's 2D extent in the 3D scene's CRS.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
static QgsRectangle tryReprojectExtent2D(const QgsRectangle &extent, const QgsCoordinateReferenceSystem &crs1, const QgsCoordinateReferenceSystem &crs2, const QgsCoordinateTransformContext &context)
Reprojects extent from crs1 to crs2 coordinate reference system with context context.
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
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 setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
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 rectangle specified with double values.
A child rule for a QgsRuleBased3DRenderer.
void prepare(const Qgs3DRenderContext &context, QSet< QString > &attributeNames, const QgsBox3D &chunkExtent, RuleToHandlerMap &handlers) const
call prepare() on handlers and populate attributeNames
const QgsRuleBased3DRenderer::RuleList & children() const
Returns all children rules of this rule.
void createHandlers(QgsVectorLayer *layer, RuleToHandlerMap &handlers) const
add handlers
QHash< const QgsRuleBased3DRenderer::Rule *, QgsFeature3DHandler * > RuleToHandlerMap
QList< QgsRuleBased3DRenderer::Rule * > RuleList
Defines configuration of how a vector layer gets tiled for 3D rendering.
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.
Represents a vector layer which manages a vector based dataset.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QGIS_CHECK_MAIN_THREAD_ACCESS