QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgsquantizedmeshterraingenerator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsterraingenerator.h
3 --------------------------------------
4 Date : August 2024
5 Copyright : (C) 2024 by David Koňařík
6 Email : dvdkon at konarici dot cz
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 "qgs3dmapsettings.h"
20#include "qgsapplication.h"
21#include "qgschunkloader.h"
22#include "qgschunknode.h"
24#include "qgsgeotransform.h"
25#include "qgsgltf3dutils.h"
26#include "qgslogger.h"
27#include "qgsmesh3dentity_p.h"
28#include "qgsmeshlayerutils.h"
30#include "qgsproject.h"
33#include "qgsrectangle.h"
34#include "qgsterrainentity.h"
37#include "qgstiledsceneindex.h"
38#include "qgstiledscenelayer.h"
39#include "qgstiledscenetile.h"
40#include "qgstiles.h"
41#include "qgstriangularmesh.h"
42#include "qgsvector3d.h"
43
44#include <QComponent>
45#include <QDiffuseSpecularMaterial>
46#include <QEntity>
47#include <QPhongMaterial>
48#include <QString>
49#include <QTextureMaterial>
50#include <QThreadPool>
51#include <QtGlobal>
52
53#include "moc_qgsquantizedmeshterraingenerator.cpp"
54
55using namespace Qt::StringLiterals;
56
58
59class QgsQuantizedMeshTerrainChunkLoader : public QgsTerrainTileLoader
60{
61 Q_OBJECT
62 public:
63 QgsQuantizedMeshTerrainChunkLoader( QgsTerrainEntity *terrain, QgsChunkNode *node, long long tileId, QgsTiledSceneIndex index, const QgsCoordinateTransform &tileCrsToMapCrs );
64 void start() override;
65 Qt3DCore::QEntity *createEntity( Qt3DCore::QEntity *parent ) override;
66
67 protected:
68 void onTextureLoaded() override;
69
70 private:
71 QgsTerrainTileEntity *mEntity = nullptr;
72 bool mMeshLoaded = false;
73 bool mTextureLoaded = false;
74 std::mutex mFinishedMutex;
75 long long mTileId;
76 QgsTiledSceneIndex mIndex;
77 QgsCoordinateTransform mTileCrsToMapCrs;
78};
79
80QgsQuantizedMeshTerrainChunkLoader::QgsQuantizedMeshTerrainChunkLoader(
81 QgsTerrainEntity *terrain_, QgsChunkNode *node, long long tileId, QgsTiledSceneIndex index, const QgsCoordinateTransform &tileCrsToMapCrs
82)
83 : QgsTerrainTileLoader( terrain_, node )
84 , mTileId( tileId )
85 , mIndex( std::move( index ) )
86 , mTileCrsToMapCrs( tileCrsToMapCrs )
87{}
88
89void QgsQuantizedMeshTerrainChunkLoader::start()
90{
91 QgsChunkNode *node = chunk();
92
93 loadTexture(); // Start loading texture
94
95 // Access terrain only on the original thread.
96 Qgs3DMapSettings *map = terrain()->mapSettings();
97 double vertScale = map->terrainSettings()->verticalScale();
98 bool shadingEnabled = map->isTerrainShadingEnabled();
99 QgsVector3D chunkOrigin = node->box3D().center();
100
101 QThreadPool::globalInstance()->start( [this, node, vertScale, chunkOrigin, shadingEnabled]() {
102 if ( mTileId == QgsQuantizedMeshIndex::ROOT_TILE_ID )
103 {
104 // Nothing to load for imaginary root tile
105 emit finished();
106 return;
107 }
108
109 QgsTiledSceneTile tile = mIndex.getTile( mTileId );
110
111 QString uri = tile.resources().value( u"content"_s ).toString();
112 Q_ASSERT( !uri.isEmpty() );
113
114 uri = tile.baseUrl().resolved( uri ).toString();
115 QByteArray content = mIndex.retrieveContent( uri );
116
117 QgsGltf3DUtils::EntityTransform entityTransform;
118 entityTransform.tileTransform = ( tile.transform() ? *tile.transform() : QgsMatrix4x4() );
119 entityTransform.chunkOriginTargetCrs = chunkOrigin;
120 entityTransform.ecefToTargetCrs = &mTileCrsToMapCrs;
121 entityTransform.gltfUpAxis = static_cast<Qgis::Axis>( tile.metadata().value( u"gltfUpAxis"_s, static_cast<int>( Qgis::Axis::Y ) ).toInt() );
122
123 try
124 {
125 QgsBox3D box3D = node->box3D();
126 QgsQuantizedMeshTile qmTile( content );
127 qmTile.removeDegenerateTriangles();
128
129 // We now know the exact height range of the tile, set it to the node.
130 box3D.setZMinimum( qmTile.mHeader.MinimumHeight * vertScale );
131 box3D.setZMaximum( qmTile.mHeader.MaximumHeight * vertScale );
132 node->setExactBox3D( box3D );
133
134 if ( shadingEnabled && qmTile.mNormalCoords.size() == 0 )
135 {
136 qmTile.generateNormals();
137 }
138
139 tinygltf::Model model = qmTile.toGltf( true, 100, true );
140
141 QStringList errors;
142 Qt3DCore::QEntity *gltfEntity = QgsGltf3DUtils::parsedGltfToEntity( model, entityTransform, uri, &errors );
143 if ( !errors.isEmpty() )
144 {
145 QgsDebugError( "gltf load errors: " + errors.join( '\n' ) );
146 emit finished();
147 return;
148 }
149
150 QgsTerrainTileEntity *terrainEntity = new QgsTerrainTileEntity( node->tileId() );
151 // We count on only having one mesh.
152 Q_ASSERT( gltfEntity->children().size() == 1 );
153 gltfEntity->children()[0]->setParent( terrainEntity );
154
155 QgsGeoTransform *transform = new QgsGeoTransform;
156 transform->setGeoTranslation( chunkOrigin );
157 terrainEntity->addComponent( transform );
158
159 terrainEntity->moveToThread( QgsApplication::instance()->thread() );
160 mEntity = terrainEntity;
161 }
163 {
164 QgsDebugError( u"Failed to parse tile from '%1'"_s.arg( uri ) );
165 emit finished();
166 return;
167 }
168
169 {
170 std::lock_guard lock( mFinishedMutex );
171 if ( mTextureLoaded )
172 emit finished();
173 mMeshLoaded = true;
174 }
175 } );
176}
177
178Qt3DCore::QEntity *QgsQuantizedMeshTerrainChunkLoader::createEntity( Qt3DCore::QEntity *parent )
179{
180 if ( mEntity )
181 {
182 mEntity->setParent( parent );
183 Qt3DRender::QTexture2D *texture = createTexture( mEntity );
184
185 // Copied from part of QgsTerrainTileLoader::createTextureComponent, since we can't use that directly on the GLTF entity.
186 Qt3DRender::QMaterial *material = nullptr;
187 Qgs3DMapSettings *map = terrain()->mapSettings();
188 if ( map->isTerrainShadingEnabled() )
189 {
190 const QgsPhongMaterialSettings &shadingMaterial = map->terrainShadingMaterial();
191 Qt3DExtras::QDiffuseSpecularMaterial *diffuseMapMaterial = new Qt3DExtras::QDiffuseSpecularMaterial;
192 diffuseMapMaterial->setDiffuse( QVariant::fromValue( texture ) );
193 diffuseMapMaterial->setAmbient( shadingMaterial.ambient() );
194 diffuseMapMaterial->setSpecular( shadingMaterial.specular() );
195 diffuseMapMaterial->setShininess( shadingMaterial.shininess() );
196 material = diffuseMapMaterial;
197 }
198 else
199 {
200 Qt3DExtras::QTextureMaterial *textureMaterial = new Qt3DExtras::QTextureMaterial;
201 textureMaterial->setTexture( texture );
202 material = textureMaterial;
203 }
204 // Get the child that actually has the mesh and add the texture
205 Qt3DCore::QEntity *gltfEntity = mEntity->findChild<Qt3DCore::QEntity *>();
206 // Remove default material
207 auto oldMaterial = gltfEntity->componentsOfType<QgsMetalRoughMaterial>();
208 Q_ASSERT( oldMaterial.size() > 0 );
209 gltfEntity->removeComponent( oldMaterial[0] );
210 gltfEntity->addComponent( material );
211 }
212 return mEntity;
213}
214
215void QgsQuantizedMeshTerrainChunkLoader::onTextureLoaded()
216{
217 std::lock_guard lock( mFinishedMutex );
218 if ( mMeshLoaded )
219 emit finished();
220 mTextureLoaded = true;
221}
222
224
229
231{
232 mTerrain = t;
233 mTileCrsToMapCrs = QgsCoordinateTransform( mMetadata->mCrs, mTerrain->mapSettings()->crs(), mTerrain->mapSettings()->transformContext() );
234}
235
237{
239 if ( mIsValid )
240 clone->setLayer( layer() );
241 else
242 clone->mLayer = mLayer; // Copy just the reference
243 return clone;
244}
245
250
252{
253 mMapExtent = extent;
254}
255
257{
258 return mMetadata->mBoundingVolume.bounds().toRectangle();
259}
260
262{
263 Q_UNUSED( map );
264 return mMetadata->geometricErrorAtZoom( -1 );
265}
266
267void QgsQuantizedMeshTerrainGenerator::rootChunkHeightRange( float &hMin, float &hMax ) const
268{
269 hMin = mMetadata->mBoundingVolume.bounds().zMinimum();
270 hMax = mMetadata->mBoundingVolume.bounds().xMaximum();
271}
272float QgsQuantizedMeshTerrainGenerator::heightAt( double x, double y, const Qgs3DRenderContext &context ) const
273{
274 // We fetch the most detailed tile containing the given point and then interpolate.
275 QgsTileMatrix zoomedMatrix = QgsTileMatrix::fromTileMatrix( mMetadata->mMaxZoom, mMetadata->mTileMatrix );
276 QgsPointXY point = QgsCoordinateTransform( context.crs(), mMetadata->mCrs, context.transformContext() ).transform( QgsPointXY( x, y ) );
277 QPointF tileCoords = zoomedMatrix.mapToTileCoordinates( point );
278 QgsTileXYZ tileXyz( floor( tileCoords.x() ), floor( tileCoords.y() ), mMetadata->mMaxZoom );
279 if ( !mMetadata->containsTile( tileXyz ) )
280 {
281 // This doesn't deal with a possible dataset where the whole extent doesn't
282 // have full coverage at maxZoom, but has coverage at a lower zoom level.
283 QgsDebugError( u"Quantized Mesh layer doesn't contain max-zoom tile for %1, %2"_s.arg( x ).arg( y ) );
284 return 0;
285 }
286 // TODO: Make heightAt asynchronous?
287 QgsTiledSceneIndex index = mIndex; // Copy to get rid of const
288 QgsTiledSceneTile sceneTile = index.getTile( QgsQuantizedMeshIndex::encodeTileId( tileXyz ) );
289 QString uri = sceneTile.resources().value( u"content"_s ).toString();
290 Q_ASSERT( !uri.isEmpty() );
291
292 uri = sceneTile.baseUrl().resolved( uri ).toString();
293 QByteArray content = index.retrieveContent( uri );
294 QgsQuantizedMeshTile qmTile( content );
296 QgsMesh mesh = qmTile.toMesh( zoomedMatrix.tileExtent( tileXyz ) );
297 QgsTriangularMesh triMesh;
298 triMesh.update( &mesh );
299
300 return QgsMeshLayerUtils::interpolateZForPoint( triMesh, point.x(), point.y() );
301}
302
303QgsChunkLoader *QgsQuantizedMeshTerrainGenerator::createChunkLoader( QgsChunkNode *node ) const
304{
305 long long tileId = QgsQuantizedMeshIndex::encodeTileId( nodeIdToTile( node->tileId() ) );
306 return new QgsQuantizedMeshTerrainChunkLoader( mTerrain, node, tileId, mIndex, mTileCrsToMapCrs );
307}
308
310{
311 return new QgsChunkNode(
312 { 0, 0, 0 },
313 mRootBox3D, // Given to us by setupQuadtree()
314 mMetadata->geometricErrorAtZoom( -1 )
315 );
316}
317
318QVector<QgsChunkNode *> QgsQuantizedMeshTerrainGenerator::createChildren( QgsChunkNode *node ) const
319{
320 QVector<QgsChunkNode *> children;
321
322 for ( auto offset : std::vector<std::pair<int, int>> { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } } )
323 {
324 QgsChunkNodeId childId( node->tileId().d + 1, node->tileId().x * 2 + offset.first, node->tileId().y * 2 + offset.second );
325 QgsTileXYZ tile = nodeIdToTile( childId );
326 if ( !mMetadata->containsTile( tile ) )
327 continue;
328
329 QgsTileMatrix zoomedTileMatrix = QgsTileMatrix::fromTileMatrix( tile.zoomLevel(), mMetadata->mTileMatrix );
330 QgsRectangle extent2d = zoomedTileMatrix.tileExtent( tile );
331 if ( !extent2d.intersects( mMapExtent ) )
332 continue; // Don't render terrain inside layer extent, but outside map extent
333 Q_ASSERT( mTerrain );
334 QgsRectangle mapExtent2d = mTileCrsToMapCrs.transform( extent2d );
335 QgsVector3D corner1( mapExtent2d.xMinimum(), mapExtent2d.yMinimum(), mMetadata->dummyZRange.lower() );
336 QgsVector3D corner2( mapExtent2d.xMaximum(), mapExtent2d.yMaximum(), mMetadata->dummyZRange.upper() );
337 children.push_back( new QgsChunkNode( childId, QgsBox3D( corner1, corner2 ), mMetadata->geometricErrorAtZoom( tile.zoomLevel() ), node ) );
338 }
339
340 return children;
341}
342
344{
345 if ( !layer )
346 {
347 mIsValid = false;
348 return false;
349 }
350
351 mLayer = layer;
352 const QgsQuantizedMeshDataProvider *provider = qobject_cast<const QgsQuantizedMeshDataProvider *>( layer->dataProvider() );
353 if ( !provider )
354 {
355 QgsDebugError( "QgsQuantizedMeshTerrainGenerator provided with non-QM layer" );
356 return false;
357 }
358 mMetadata = provider->quantizedMeshMetadata();
359 mIndex = provider->index();
360
361 mTerrainTilingScheme = QgsTilingScheme( mMetadata->mTileMatrix.extent(), mMetadata->mCrs );
362
363 mIsValid = true;
364 return true;
365}
366
371
372QgsTileXYZ QgsQuantizedMeshTerrainGenerator::nodeIdToTile( QgsChunkNodeId nodeId ) const
373{
374 // nodeId zoom=0 is tile zoom=-1 to get unique root tile
375 if ( nodeId.d == 0 )
376 return { 0, 0, -1 };
377 return { nodeId.x, mMetadata->mTileScheme == "tms"_L1 ? ( 1 << ( nodeId.d - 1 ) ) - nodeId.y - 1 : nodeId.y, nodeId.d - 1 };
378}
379
380#include "qgsquantizedmeshterraingenerator.moc"
Axis
Cartesian axes.
Definition qgis.h:2540
@ Y
Y-axis.
Definition qgis.h:2542
Definition of the world.
const QgsAbstractTerrainSettings * terrainSettings() const
Returns the terrain settings.
bool isTerrainShadingEnabled() const
Returns whether terrain shading is enabled.
QgsPhongMaterialSettings terrainShadingMaterial() const
Returns terrain shading material.
Rendering context for preparation of 3D entities.
QgsCoordinateReferenceSystem crs() const
Returns the coordinate reference system used in the 3D scene.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
double verticalScale() const
Returns the vertical scale (exaggeration) for terrain.
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
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
Handles coordinate transforms between two coordinate systems.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
A simple 4x4 matrix implementation useful for transformation in 3D space.
Basic shading material used for rendering based on the Phong shading model with three color component...
void setDiffuse(const QColor &diffuse)
Sets diffuse color component.
QColor specular() const
Returns specular color component.
QColor ambient() const
Returns ambient color component.
double shininess() const
Returns shininess of the surface.
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Exception thrown on failure to parse Quantized Mesh tile (malformed data).
bool setLayer(QgsTiledSceneLayer *layer)
Set layer to take tiles from.
void setTerrain(QgsTerrainEntity *t) override
Sets terrain entity for the generator (does not transfer ownership).
QVector< QgsChunkNode * > createChildren(QgsChunkNode *node) const override
QgsTiledSceneLayer * layer() const
Returns the layer we take tiles from.
QgsRectangle rootChunkExtent() const override
extent of the terrain's root chunk in terrain's CRS
static QgsTerrainGenerator * create()
Creates a new instance of a QgsQuantizedMeshTerrainGenerator object.
void rootChunkHeightRange(float &hMin, float &hMax) const override
Returns height range of the root chunk in world coordinates.
QgsTerrainGenerator::Type type() const override
What texture generator implementation is this.
QgsTerrainGenerator * clone() const override
Makes a copy of the current instance.
float rootChunkError(const Qgs3DMapSettings &map) const override
Returns error of the root chunk in world coordinates.
QgsChunkLoader * createChunkLoader(QgsChunkNode *node) const override
float heightAt(double x, double y, const Qgs3DRenderContext &context) const override
Returns height at (x,y) in map's CRS.
void setExtent(const QgsRectangle &extent) override
sets the extent of the terrain in terrain's CRS
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
bool intersects(const QgsRectangle &rect) const
Returns true when rectangle intersects with other rectangle.
double yMaximum
Base class for generators of terrain.
Type
Enumeration of the available terrain generators.
@ QuantizedMesh
Terrain is built from quantized mesh tiles.
QgsTilingScheme mTerrainTilingScheme
Tiling scheme of the terrain.
QgsTerrainEntity * mTerrain
Defines a matrix of tiles for a single zoom level: it is defined by its size (width *.
Definition qgstiles.h:171
QgsRectangle tileExtent(QgsTileXYZ id) const
Returns extent of the given tile in this matrix.
Definition qgstiles.cpp:84
QPointF mapToTileCoordinates(const QgsPointXY &mapPoint) const
Returns row/column coordinates (floating point number) from the given point in map coordinates.
Definition qgstiles.cpp:124
static QgsTileMatrix fromTileMatrix(int zoomLevel, const QgsTileMatrix &tileMatrix)
Returns a tile matrix based on another one.
Definition qgstiles.cpp:64
Stores coordinates of a tile in a tile matrix set.
Definition qgstiles.h:43
int zoomLevel() const
Returns tile's zoom level (Z).
Definition qgstiles.h:57
An index for tiled scene data providers.
QByteArray retrieveContent(const QString &uri, QgsFeedback *feedback=nullptr)
Retrieves index content for the specified uri.
QgsTiledSceneTile getTile(long long id)
Returns the tile with matching id, or an invalid tile if the matching tile is not available.
Represents a map layer supporting display of tiled scene objects.
Represents an individual tile from a tiled scene data source.
QVariantMap resources() const
Returns the resources attached to the tile.
QVariantMap metadata() const
Returns additional metadata attached to the tile.
const QgsMatrix4x4 * transform() const
Returns the tile's transform.
QUrl baseUrl() const
Returns the tile's base URL.
Encapsulates tiling schemes (just like with WMTS / TMS / XYZ layers).
A triangular/derived mesh with vertices in map coordinates.
bool update(QgsMesh *nativeMesh, const QgsCoordinateTransform &transform)
Constructs triangular mesh from layer's native mesh and transform to destination CRS.
A 3D vector (similar to QVector3D) with the difference that it uses double precision instead of singl...
Definition qgsvector3d.h:33
#define QgsDebugError(str)
Definition qgslogger.h:59
Mesh - vertices, edges and faces.
QgsMesh toMesh(QgsRectangle tileBounds)