QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
qgs3dsceneexporter.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgs3dsceneexporter.cpp
3 --------------------------------------
4 Date : June 2020
5 Copyright : (C) 2020 by Belgacem Nedjima
6 Email : gb underscore nedjima at esi dot dz
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
16#include "qgs3dsceneexporter.h"
17#include "moc_qgs3dsceneexporter.cpp"
18
19#include <QVector>
20#include <Qt3DCore/QEntity>
21#include <Qt3DCore/QComponent>
22#include <Qt3DCore/QNode>
23
24#if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
25#include <Qt3DRender/QAttribute>
26#include <Qt3DRender/QBuffer>
27#include <Qt3DRender/QGeometry>
28
29typedef Qt3DRender::QAttribute Qt3DQAttribute;
30typedef Qt3DRender::QBuffer Qt3DQBuffer;
31typedef Qt3DRender::QGeometry Qt3DQGeometry;
32#else
33#include <Qt3DCore/QAttribute>
34#include <Qt3DCore/QBuffer>
35#include <Qt3DCore/QGeometry>
36
37typedef Qt3DCore::QAttribute Qt3DQAttribute;
38typedef Qt3DCore::QBuffer Qt3DQBuffer;
39typedef Qt3DCore::QGeometry Qt3DQGeometry;
40#endif
41
42#include <Qt3DRender/QGeometryRenderer>
43#include <Qt3DExtras/QPlaneGeometry>
44#include <Qt3DCore/QTransform>
45#include <Qt3DExtras/QDiffuseSpecularMaterial>
46#include <Qt3DExtras/QTextureMaterial>
47#include <Qt3DRender/QTextureImage>
48#include <Qt3DRender/QTexture>
49#include <Qt3DRender/QMesh>
50#include <Qt3DRender/QSceneLoader>
51#include <Qt3DRender/QAbstractTexture>
52#include <Qt3DExtras/QCylinderGeometry>
53#include <Qt3DExtras/QConeGeometry>
54#include <Qt3DExtras/QSphereGeometry>
55#include <Qt3DExtras/QCuboidGeometry>
56#include <Qt3DExtras/QTorusGeometry>
57#include <Qt3DExtras/QExtrudedTextMesh>
58#include <Qt3DExtras/QPhongMaterial>
59#include <Qt3DRender/QAbstractTextureImage>
60
61#include <QByteArray>
62#include <QFile>
63#include <QTextStream>
64
67#include "qgsterrainentity.h"
68#include "qgschunknode.h"
69#include "qgsterraingenerator.h"
70#include "qgs3dmapsettings.h"
75#include "qgs3dexportobject.h"
78#include "qgsmeshterraingenerator.h"
79#include "qgsmeshterraintileloader_p.h"
80#include "qgsvectorlayer.h"
83#include "qgs3dutils.h"
84#include "qgsimagetexture.h"
86
87#include <numeric>
88
89template<typename T>
90QVector<T> getAttributeData( Qt3DQAttribute *attribute, const QByteArray &data )
91{
92 const uint bytesOffset = attribute->byteOffset();
93 const uint bytesStride = attribute->byteStride();
94 const uint vertexSize = attribute->vertexSize();
95 const uint dataSize = static_cast<uint>( data.size() );
96 QVector<T> result;
97
98 if ( bytesStride == 0 )
99 {
100 QgsDebugError( "bytesStride==0, the attribute probably was not set properly" );
101 return result;
102 }
103
104 const char *pData = data.constData();
105 for ( unsigned int i = bytesOffset; i < dataSize; i += bytesStride )
106 {
107 for ( unsigned int j = 0; j < vertexSize * sizeof( T ); j += sizeof( T ) )
108 {
109 T v;
110 memcpy( &v, pData + i + j, sizeof( T ) );
111 result.push_back( v );
112 }
113 }
114 return result;
115}
116
117template<typename T>
118QVector<uint> _getIndexDataImplementation( const QByteArray &data )
119{
120 QVector<uint> result;
121 const char *pData = data.constData();
122 for ( int i = 0; i < data.size(); i += sizeof( T ) )
123 {
124 T v;
125 memcpy( &v, pData + i, sizeof( T ) );
126 result.push_back( ( uint ) v );
127 }
128 return result;
129}
130
131QVector<uint> getIndexData( Qt3DQAttribute *indexAttribute, const QByteArray &data )
132{
133 switch ( indexAttribute->vertexBaseType() )
134 {
135 case Qt3DQAttribute::VertexBaseType::Int:
136 return _getIndexDataImplementation<int>( data );
137 case Qt3DQAttribute::VertexBaseType::UnsignedInt:
138 return _getIndexDataImplementation<uint>( data );
139 case Qt3DQAttribute::VertexBaseType::Short:
140 return _getIndexDataImplementation<short>( data );
141 case Qt3DQAttribute::VertexBaseType::UnsignedShort:
142 return _getIndexDataImplementation<ushort>( data );
143 case Qt3DQAttribute::VertexBaseType::Byte:
144 return _getIndexDataImplementation<char>( data );
145 case Qt3DQAttribute::VertexBaseType::UnsignedByte:
146 return _getIndexDataImplementation<uchar>( data );
147 default:
148 QgsDebugError( "Probably trying to get index data using an attribute that has vertex data" );
149 break;
150 }
151 return QVector<uint>();
152}
153
154QByteArray getData( Qt3DQBuffer *buffer )
155{
156 QByteArray bytes = buffer->data();
157 if ( bytes.isNull() )
158 {
159 QgsDebugError( "QBuffer is null" );
160 }
161 return bytes;
162}
163
164Qt3DQAttribute *findAttribute( Qt3DQGeometry *geometry, const QString &name, Qt3DQAttribute::AttributeType type )
165{
166 QVector<Qt3DQAttribute *> attributes = geometry->attributes();
167 for ( Qt3DQAttribute *attribute : attributes )
168 {
169 if ( attribute->attributeType() != type )
170 continue;
171 if ( name.isEmpty() || attribute->name() == name )
172 return attribute;
173 }
174 return nullptr;
175}
176
177template<typename Component>
178Component *findTypedComponent( Qt3DCore::QEntity *entity )
179{
180 if ( !entity )
181 return nullptr;
182 QVector<Qt3DCore::QComponent *> components = entity->components();
183 for ( Qt3DCore::QComponent *component : components )
184 {
185 Component *typedComponent = qobject_cast<Component *>( component );
186 if ( typedComponent )
187 return typedComponent;
188 }
189 return nullptr;
190}
191
192bool Qgs3DSceneExporter::parseVectorLayerEntity( Qt3DCore::QEntity *entity, QgsVectorLayer *layer )
193{
194 QgsAbstract3DRenderer *abstractRenderer = layer->renderer3D();
195 const QString rendererType = abstractRenderer->type();
196
197 if ( rendererType == "rulebased" )
198 {
199 int prevSize = mObjects.size();
200 // Potential bug: meshes loaded using Qt3DRender::QSceneLoader will probably have wrong scale and translation
201 const QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
202 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
203 {
204 Qt3DCore::QEntity *parentEntity = qobject_cast<Qt3DCore::QEntity *>( renderer->parent() );
205 if ( !parentEntity )
206 continue;
207 Qgs3DExportObject *object = processGeometryRenderer( renderer, layer->name() + QStringLiteral( "_" ) );
208 if ( !object )
209 continue;
210 if ( mExportTextures )
211 processEntityMaterial( parentEntity, object );
212 mObjects.push_back( object );
213 }
214 return mObjects.size() > prevSize;
215 }
216
217 else if ( rendererType == "vector" )
218 {
219 QgsVectorLayer3DRenderer *vectorLayerRenderer = dynamic_cast<QgsVectorLayer3DRenderer *>( abstractRenderer );
220 if ( vectorLayerRenderer )
221 {
222 const QgsAbstract3DSymbol *symbol = vectorLayerRenderer->symbol();
223 return symbol->exportGeometries( this, entity, layer->name() + QStringLiteral( "_" ) );
224 }
225 else
226 return false;
227 }
228
229 else
230 {
231 // TODO: handle pointcloud/mesh/etc. layers
232 QgsDebugMsgLevel( QStringLiteral( "Type '%1' of layer '%2' is not exportable." ).arg( layer->name(), rendererType ), 2 );
233 return false;
234 }
235
236 return false;
237}
238
239void Qgs3DSceneExporter::processEntityMaterial( Qt3DCore::QEntity *entity, Qgs3DExportObject *object )
240{
241 Qt3DExtras::QPhongMaterial *phongMaterial = findTypedComponent<Qt3DExtras::QPhongMaterial>( entity );
242 if ( phongMaterial )
243 {
245 object->setupMaterial( &material );
246 }
247
248 Qt3DExtras::QDiffuseSpecularMaterial *diffuseMapMaterial = findTypedComponent<Qt3DExtras::QDiffuseSpecularMaterial>( entity );
249 if ( diffuseMapMaterial )
250 {
251 const Qt3DRender::QTexture2D *diffuseTexture = diffuseMapMaterial->diffuse().value<Qt3DRender::QTexture2D *>();
252 if ( diffuseTexture )
253 {
254 const QVector<Qt3DRender::QAbstractTextureImage *> textureImages = diffuseTexture->textureImages();
255 for ( const Qt3DRender::QAbstractTextureImage *tex : textureImages )
256 {
257 const QgsImageTexture *imageTexture = dynamic_cast<const QgsImageTexture *>( tex );
258 if ( imageTexture )
259 {
260 const QImage image = imageTexture->getImage();
261 object->setTextureImage( image );
262 break;
263 }
264 }
265 }
266 }
267}
268
269void Qgs3DSceneExporter::parseTerrain( QgsTerrainEntity *terrain, const QString &layerName )
270{
271 Qgs3DMapSettings *settings = terrain->mapSettings();
272 if ( !settings->terrainRenderingEnabled() )
273 return;
274
275 QgsChunkNode *node = terrain->rootNode();
276
277 QgsTerrainGenerator *generator = settings->terrainGenerator();
278 if ( !generator )
279 return;
280 QgsTerrainTileEntity *terrainTile = nullptr;
281 QgsTerrainTextureGenerator *textureGenerator = terrain->textureGenerator();
282 textureGenerator->waitForFinished();
283 const QSize oldResolution = textureGenerator->textureSize();
284 textureGenerator->setTextureSize( QSize( mTerrainTextureResolution, mTerrainTextureResolution ) );
285 switch ( generator->type() )
286 {
288 terrainTile = getDemTerrainEntity( terrain, node );
289 parseDemTile( terrainTile, layerName + QStringLiteral( "_" ) );
290 break;
292 terrainTile = getFlatTerrainEntity( terrain, node );
293 parseFlatTile( terrainTile, layerName + QStringLiteral( "_" ) );
294 break;
296 terrainTile = getMeshTerrainEntity( terrain, node );
297 parseMeshTile( terrainTile, layerName + QStringLiteral( "_" ) );
298 break;
299 // TODO: implement other terrain types
302 break;
303 }
304 textureGenerator->setTextureSize( oldResolution );
305}
306
307QgsTerrainTileEntity *Qgs3DSceneExporter::getFlatTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
308{
309 QgsFlatTerrainGenerator *generator = dynamic_cast<QgsFlatTerrainGenerator *>( terrain->mapSettings()->terrainGenerator() );
310 FlatTerrainChunkLoader *flatTerrainLoader = qobject_cast<FlatTerrainChunkLoader *>( generator->createChunkLoader( node ) );
311 if ( mExportTextures )
312 terrain->textureGenerator()->waitForFinished();
313 // the entity we created will be deallocated once the scene exporter is deallocated
314 Qt3DCore::QEntity *entity = flatTerrainLoader->createEntity( this );
315 QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( entity );
316 return tileEntity;
317}
318
319QgsTerrainTileEntity *Qgs3DSceneExporter::getDemTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
320{
321 // Just create a new tile (we don't need to export exact level of details as in the scene)
322 // create the entity synchronously and then it will be deleted once our scene exporter instance is deallocated
323 QgsDemTerrainGenerator *generator = dynamic_cast<QgsDemTerrainGenerator *>( terrain->mapSettings()->terrainGenerator()->clone() );
324 generator->setResolution( mTerrainResolution );
325 QgsDemTerrainTileLoader *loader = qobject_cast<QgsDemTerrainTileLoader *>( generator->createChunkLoader( node ) );
326 generator->heightMapGenerator()->waitForFinished();
327 if ( mExportTextures )
328 terrain->textureGenerator()->waitForFinished();
329 QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( loader->createEntity( this ) );
330 delete generator;
331 return tileEntity;
332}
333
334QgsTerrainTileEntity *Qgs3DSceneExporter::getMeshTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
335{
336 QgsMeshTerrainGenerator *generator = dynamic_cast<QgsMeshTerrainGenerator *>( terrain->mapSettings()->terrainGenerator() );
337 QgsMeshTerrainTileLoader *loader = qobject_cast<QgsMeshTerrainTileLoader *>( generator->createChunkLoader( node ) );
338 // TODO: export textures
339 QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( loader->createEntity( this ) );
340 return tileEntity;
341}
342
343void Qgs3DSceneExporter::parseFlatTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
344{
345 Qt3DRender::QGeometryRenderer *mesh = findTypedComponent<Qt3DRender::QGeometryRenderer>( tileEntity );
346 Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( tileEntity );
347
348 Qt3DQGeometry *geometry = mesh->geometry();
349 Qt3DExtras::QPlaneGeometry *tileGeometry = qobject_cast<Qt3DExtras::QPlaneGeometry *>( geometry );
350 if ( !tileGeometry )
351 {
352 QgsDebugError( "Qt3DExtras::QPlaneGeometry* is expected but something else was given" );
353 return;
354 }
355
356 // Generate vertice data
357 Qt3DQAttribute *positionAttribute = tileGeometry->positionAttribute();
358 if ( !positionAttribute )
359 {
360 QgsDebugError( QString( "Cannot export '%1' - geometry has no position attribute!" ).arg( layerName ) );
361 return;
362 }
363 const QByteArray verticesBytes = getData( positionAttribute->buffer() );
364 if ( verticesBytes.isNull() )
365 {
366 QgsDebugError( QString( "Geometry for '%1' has position attribute with empty data!" ).arg( layerName ) );
367 return;
368 }
369 const QVector<float> positionBuffer = getAttributeData<float>( positionAttribute, verticesBytes );
370
371 // Generate index data
372 Qt3DQAttribute *indexAttribute = tileGeometry->indexAttribute();
373 if ( !indexAttribute )
374 {
375 QgsDebugError( QString( "Cannot export '%1' - geometry has no index attribute!" ).arg( layerName ) );
376 return;
377 }
378 const QByteArray indexBytes = getData( indexAttribute->buffer() );
379 if ( indexBytes.isNull() )
380 {
381 QgsDebugError( QString( "Geometry for '%1' has index attribute with empty data!" ).arg( layerName ) );
382 return;
383 }
384 const QVector<uint> indexesBuffer = getIndexData( indexAttribute, indexBytes );
385
386 QString objectNamePrefix = layerName;
387 if ( objectNamePrefix != QString() )
388 objectNamePrefix += QString();
389
390 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "Flat_tile" ) ) );
391 mObjects.push_back( object );
392
393 object->setSmoothEdges( mSmoothEdges );
394 object->setupPositionCoordinates( positionBuffer, transform->matrix() );
395 object->setupFaces( indexesBuffer );
396
397 if ( mExportNormals )
398 {
399 // Everts
400 QVector<float> normalsBuffer;
401 for ( int i = 0; i < positionBuffer.size(); i += 3 )
402 normalsBuffer << 0.0f << 1.0f << 0.0f;
403 object->setupNormalCoordinates( normalsBuffer, transform->matrix() );
404 }
405
406 Qt3DQAttribute *texCoordsAttribute = tileGeometry->texCoordAttribute();
407 if ( mExportTextures && texCoordsAttribute )
408 {
409 // Reuse vertex buffer data for texture coordinates
410 const QVector<float> texCoords = getAttributeData<float>( texCoordsAttribute, verticesBytes );
411 object->setupTextureCoordinates( texCoords );
412
413 QgsTerrainTextureImage *textureImage = tileEntity->textureImage();
414 const QImage img = textureImage->getImage();
415 object->setTextureImage( img );
416 }
417}
418
419void Qgs3DSceneExporter::parseDemTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
420{
421 Qt3DRender::QGeometryRenderer *mesh = findTypedComponent<Qt3DRender::QGeometryRenderer>( tileEntity );
422 Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( tileEntity );
423
424 Qt3DQGeometry *geometry = mesh->geometry();
425 DemTerrainTileGeometry *tileGeometry = qobject_cast<DemTerrainTileGeometry *>( geometry );
426 if ( !tileGeometry )
427 {
428 QgsDebugError( "DemTerrainTileGeometry* is expected but something else was given" );
429 return;
430 }
431
432 Qt3DQAttribute *positionAttribute = tileGeometry->positionAttribute();
433 const QByteArray positionBytes = positionAttribute->buffer()->data();
434 const QVector<float> positionBuffer = getAttributeData<float>( positionAttribute, positionBytes );
435
436 Qt3DQAttribute *indexAttribute = tileGeometry->indexAttribute();
437 const QByteArray indexBytes = indexAttribute->buffer()->data();
438 const QVector<unsigned int> indexBuffer = getIndexData( indexAttribute, indexBytes );
439
440 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( layerName + QStringLiteral( "DEM_tile" ) ) );
441 mObjects.push_back( object );
442
443 object->setSmoothEdges( mSmoothEdges );
444 object->setupPositionCoordinates( positionBuffer, transform->matrix() );
445 object->setupFaces( indexBuffer );
446
447 Qt3DQAttribute *normalsAttributes = tileGeometry->normalAttribute();
448 if ( mExportNormals && normalsAttributes )
449 {
450 const QByteArray normalsBytes = normalsAttributes->buffer()->data();
451 const QVector<float> normalsBuffer = getAttributeData<float>( normalsAttributes, normalsBytes );
452 object->setupNormalCoordinates( normalsBuffer, transform->matrix() );
453 }
454
455 Qt3DQAttribute *texCoordsAttribute = tileGeometry->texCoordsAttribute();
456 if ( mExportTextures && texCoordsAttribute )
457 {
458 const QByteArray texCoordsBytes = texCoordsAttribute->buffer()->data();
459 const QVector<float> texCoordsBuffer = getAttributeData<float>( texCoordsAttribute, texCoordsBytes );
460 object->setupTextureCoordinates( texCoordsBuffer );
461
462 QgsTerrainTextureImage *textureImage = tileEntity->textureImage();
463 const QImage img = textureImage->getImage();
464 object->setTextureImage( img );
465 }
466}
467
468void Qgs3DSceneExporter::parseMeshTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
469{
470 QString objectNamePrefix = layerName;
471 if ( objectNamePrefix != QString() )
472 objectNamePrefix += QStringLiteral( "_" );
473
474 const QList<Qt3DRender::QGeometryRenderer *> renderers = tileEntity->findChildren<Qt3DRender::QGeometryRenderer *>();
475 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
476 {
477 Qgs3DExportObject *obj = processGeometryRenderer( renderer, objectNamePrefix );
478 if ( !obj )
479 continue;
480 mObjects << obj;
481 }
482}
483
484QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processInstancedPointGeometry( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
485{
486 QVector<Qgs3DExportObject *> objects;
487 const QList<Qt3DQGeometry *> geometriesList = entity->findChildren<Qt3DQGeometry *>();
488 for ( Qt3DQGeometry *geometry : geometriesList )
489 {
490 Qt3DQAttribute *positionAttribute = findAttribute( geometry, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
491 Qt3DQAttribute *indexAttribute = findAttribute( geometry, QString(), Qt3DQAttribute::IndexAttribute );
492 if ( !positionAttribute || !indexAttribute )
493 {
494 QgsDebugError( QString( "Cannot export '%1' - geometry has no position or index attribute!" ).arg( objectNamePrefix ) );
495 continue;
496 }
497
498 const QByteArray vertexBytes = positionAttribute->buffer()->data();
499 const QByteArray indexBytes = indexAttribute->buffer()->data();
500 if ( vertexBytes.isNull() || indexBytes.isNull() )
501 {
502 QgsDebugError( QString( "Geometry for '%1' has position or index attribute with empty data!" ).arg( objectNamePrefix ) );
503 continue;
504 }
505
506 const QVector<float> positionData = getAttributeData<float>( positionAttribute, vertexBytes );
507 const QVector<uint> indexData = getIndexData( indexAttribute, indexBytes );
508
509 Qt3DQAttribute *instanceDataAttribute = findAttribute( geometry, QStringLiteral( "pos" ), Qt3DQAttribute::VertexAttribute );
510 if ( !instanceDataAttribute )
511 {
512 QgsDebugError( QString( "Cannot export '%1' - geometry has no instanceData attribute!" ).arg( objectNamePrefix ) );
513 continue;
514 }
515 const QByteArray instancePositionBytes = getData( instanceDataAttribute->buffer() );
516 if ( instancePositionBytes.isNull() )
517 {
518 QgsDebugError( QString( "Geometry for '%1' has instanceData attribute with empty data!" ).arg( objectNamePrefix ) );
519 continue;
520 }
521 QVector<float> instancePosition = getAttributeData<float>( instanceDataAttribute, instancePositionBytes );
522
523 for ( int i = 0; i < instancePosition.size(); i += 3 )
524 {
525 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "instance_point" ) ) );
526 objects.push_back( object );
527 QMatrix4x4 instanceTransform;
528 instanceTransform.translate( instancePosition[i], instancePosition[i + 1], instancePosition[i + 2] );
529 object->setupPositionCoordinates( positionData, instanceTransform );
530 object->setupFaces( indexData );
531
532 object->setSmoothEdges( mSmoothEdges );
533
534 Qt3DQAttribute *normalsAttribute = findAttribute( geometry, Qt3DQAttribute::defaultNormalAttributeName(), Qt3DQAttribute::VertexAttribute );
535 if ( mExportNormals && normalsAttribute )
536 {
537 // Reuse vertex bytes
538 const QVector<float> normalsData = getAttributeData<float>( normalsAttribute, vertexBytes );
539 object->setupNormalCoordinates( normalsData, instanceTransform );
540 }
541 }
542 }
543
544 return objects;
545}
546
547QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processSceneLoaderGeometries( Qt3DRender::QSceneLoader *sceneLoader, const QString &objectNamePrefix )
548{
549 QVector<Qgs3DExportObject *> objects;
550 Qt3DCore::QEntity *sceneLoaderParent = qobject_cast<Qt3DCore::QEntity *>( sceneLoader->parent() );
551 Qt3DCore::QTransform *entityTransform = findTypedComponent<Qt3DCore::QTransform>( sceneLoaderParent );
552 QMatrix4x4 sceneTransform;
553 if ( entityTransform )
554 {
555 sceneTransform = entityTransform->matrix();
556 }
557 QStringList entityNames = sceneLoader->entityNames();
558 for ( const QString &entityName : entityNames )
559 {
560 Qt3DRender::QGeometryRenderer *mesh = qobject_cast<Qt3DRender::QGeometryRenderer *>( sceneLoader->component( entityName, Qt3DRender::QSceneLoader::GeometryRendererComponent ) );
561 Qgs3DExportObject *object = processGeometryRenderer( mesh, objectNamePrefix, sceneTransform );
562 if ( !object )
563 continue;
564 objects.push_back( object );
565 }
566 return objects;
567}
568
569Qgs3DExportObject *Qgs3DSceneExporter::processGeometryRenderer( Qt3DRender::QGeometryRenderer *geomRenderer, const QString &objectNamePrefix, const QMatrix4x4 &sceneTransform )
570{
571 // We only export triangles for now
572 if ( geomRenderer->primitiveType() != Qt3DRender::QGeometryRenderer::Triangles )
573 return nullptr;
574
575 Qt3DQGeometry *geometry = geomRenderer->geometry();
576 if ( !geometry )
577 return nullptr;
578
579 // === Compute triangleIndexStartingIndiceToKeep according to duplicated features
580 //
581 // In the case of polygons, we have multiple feature geometries within the same geometry object (QgsTessellatedPolygonGeometry).
582 // The QgsTessellatedPolygonGeometry class holds the list of all feature ids included.
583 // To avoid exporting the same geometry (it can be included in multiple QgsTessellatedPolygonGeometry) more than once,
584 // we keep a list of already exported fid and compare with the fid of the current QgsTessellatedPolygonGeometry.
585 // As we cannot retrieve the specific geometry part for a featureId from the QgsTessellatedPolygonGeometry, we only reject
586 // the geometry if all the featureid are already present.
587 QVector<std::pair<uint, uint>> triangleIndexStartingIndiceToKeep;
588 QgsTessellatedPolygonGeometry *tessGeom = dynamic_cast<QgsTessellatedPolygonGeometry *>( geometry );
589 if ( tessGeom )
590 {
591 QVector<QgsFeatureId> featureIds = tessGeom->featureIds();
592
593 QSet<QgsFeatureId> tempFeatToAdd;
594 QVector<uint> triangleIndex = tessGeom->triangleIndexStartingIndices();
595
596 for ( int idx = 0; idx < featureIds.size(); idx++ )
597 {
598 const QgsFeatureId feat = featureIds[idx];
599 if ( !mExportedFeatureIds.contains( feat ) )
600 {
601 // add the feature (as it was unknown) to temp set and not to the mExportedFeatureIds (as featureIds can have the same id multiple times)
602 tempFeatToAdd += feat;
603
604 // keep the feature triangle indexes
605 const uint startIdx = triangleIndex[idx] * 3;
606 const uint endIdx = idx < triangleIndex.size() - 1 ? triangleIndex[idx + 1] * 3 : std::numeric_limits<uint>::max();
607
608 if ( startIdx < endIdx ) // keep only valid intervals
609 triangleIndexStartingIndiceToKeep.append( std::pair<uint, uint>( startIdx, endIdx ) );
610 }
611 }
612 mExportedFeatureIds += tempFeatToAdd;
613
614 if ( triangleIndexStartingIndiceToKeep.isEmpty() ) // all featureid are already exported
615 {
616 return nullptr;
617 }
618 }
619
620 // === Compute inherited scale and translation from child entity to parent
621 QMatrix4x4 transformMatrix = sceneTransform;
622 QObject *parent = geomRenderer->parent();
623 while ( parent )
624 {
625 Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( parent );
626 Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( entity );
627 if ( transform )
628 {
629 transformMatrix = transform->matrix() * transformMatrix;
630 }
631 parent = parent->parent();
632 }
633
634 Qt3DQAttribute *positionAttribute = nullptr;
635 Qt3DQAttribute *indexAttribute = nullptr;
636 QByteArray indexBytes, vertexBytes;
637 QVector<uint> indexDataTmp;
638 QVector<uint> indexData;
639 QVector<float> positionData;
640
641 // === Extract position data
642 positionAttribute = findAttribute( geometry, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
643 if ( !positionAttribute )
644 {
645 QgsDebugError( QString( "Cannot export '%1' - geometry has no position attribute!" ).arg( objectNamePrefix ) );
646 return nullptr;
647 }
648
649 vertexBytes = getData( positionAttribute->buffer() );
650 if ( vertexBytes.isNull() )
651 {
652 QgsDebugError( QString( "Will not export '%1' as geometry has empty position data!" ).arg( objectNamePrefix ) );
653 return nullptr;
654 }
655
656 positionData = getAttributeData<float>( positionAttribute, vertexBytes );
657
658 // === Search for face index data
659 QVector<Qt3DQAttribute *> attributes = geometry->attributes();
660 for ( Qt3DQAttribute *attribute : attributes )
661 {
662 if ( attribute->attributeType() == Qt3DQAttribute::IndexAttribute )
663 {
664 indexAttribute = attribute;
665 indexBytes = getData( indexAttribute->buffer() );
666 if ( indexBytes.isNull() )
667 {
668 QgsDebugError( QString( "Geometry for '%1' has index attribute with empty data!" ).arg( objectNamePrefix ) );
669 }
670 else
671 {
672 indexDataTmp = getIndexData( indexAttribute, indexBytes );
673 break;
674 }
675 }
676 }
677
678 // for tessellated polygons that don't have index attributes, build them from positionData
679 if ( !indexAttribute )
680 {
681 for ( uint i = 0; i < static_cast<uint>( positionData.size() / 3 ); ++i )
682 {
683 indexDataTmp.push_back( i );
684 }
685 }
686
687 // === Filter face index data if needed
688 if ( triangleIndexStartingIndiceToKeep.isEmpty() )
689 {
690 // when geometry is NOT a QgsTessellatedPolygonGeometry, no filter, take them all
691 indexData.append( indexDataTmp );
692 }
693 else
694 {
695 // when geometry is a QgsTessellatedPolygonGeometry, filter according to triangleIndexStartingIndiceToKeep
696 int intervalIdx = 0;
697 const int triangleIndexStartingIndiceToKeepSize = triangleIndexStartingIndiceToKeep.size();
698 const uint indexDataTmpSize = static_cast<uint>( indexDataTmp.size() );
699 for ( uint i = 0; i < indexDataTmpSize; ++i )
700 {
701 uint idx = indexDataTmp[static_cast<int>( i )];
702 // search for valid triangle index interval
703 while ( intervalIdx < triangleIndexStartingIndiceToKeepSize
704 && idx > triangleIndexStartingIndiceToKeep[intervalIdx].first
705 && idx >= triangleIndexStartingIndiceToKeep[intervalIdx].second )
706 {
707 intervalIdx++;
708 }
709
710 // keep only the one within the triangle index interval
711 if ( intervalIdx < triangleIndexStartingIndiceToKeepSize
712 && idx >= triangleIndexStartingIndiceToKeep[intervalIdx].first
713 && idx < triangleIndexStartingIndiceToKeep[intervalIdx].second )
714 {
715 indexData.push_back( idx );
716 }
717 }
718 }
719
720 // === Create Qgs3DExportObject
721 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "mesh_geometry" ) ) );
722 object->setupPositionCoordinates( positionData, transformMatrix );
723 object->setupFaces( indexData );
724
725 Qt3DQAttribute *normalsAttribute = findAttribute( geometry, Qt3DQAttribute::defaultNormalAttributeName(), Qt3DQAttribute::VertexAttribute );
726 if ( mExportNormals && normalsAttribute )
727 {
728 // Reuse vertex bytes
729 const QVector<float> normalsData = getAttributeData<float>( normalsAttribute, vertexBytes );
730 object->setupNormalCoordinates( normalsData, transformMatrix );
731 }
732
733 Qt3DQAttribute *texCoordsAttribute = findAttribute( geometry, Qt3DQAttribute::defaultTextureCoordinateAttributeName(), Qt3DQAttribute::VertexAttribute );
734 if ( mExportTextures && texCoordsAttribute )
735 {
736 // Reuse vertex bytes
737 const QVector<float> texCoordsData = getAttributeData<float>( texCoordsAttribute, vertexBytes );
738 object->setupTextureCoordinates( texCoordsData );
739 }
740
741 return object;
742}
743
744QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processLines( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
745{
746 QVector<Qgs3DExportObject *> objs;
747 const QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
748 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
749 {
750 if ( renderer->primitiveType() != Qt3DRender::QGeometryRenderer::LineStripAdjacency )
751 continue;
752 Qt3DQGeometry *geom = renderer->geometry();
753 Qt3DQAttribute *positionAttribute = findAttribute( geom, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
754 Qt3DQAttribute *indexAttribute = findAttribute( geom, QString(), Qt3DQAttribute::IndexAttribute );
755 if ( !positionAttribute || !indexAttribute )
756 {
757 QgsDebugError( QString( "Cannot export '%1' - geometry has no position or index attribute!" ).arg( objectNamePrefix ) );
758 continue;
759 }
760
761 const QByteArray vertexBytes = getData( positionAttribute->buffer() );
762 const QByteArray indexBytes = getData( indexAttribute->buffer() );
763 if ( vertexBytes.isNull() || indexBytes.isNull() )
764 {
765 QgsDebugError( QString( "Geometry for '%1' has position or index attribute with empty data!" ).arg( objectNamePrefix ) );
766 continue;
767 }
768 const QVector<float> positionData = getAttributeData<float>( positionAttribute, vertexBytes );
769 const QVector<uint> indexData = getIndexData( indexAttribute, indexBytes );
770
771 Qgs3DExportObject *exportObject = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "line" ) ) );
772 exportObject->setType( Qgs3DExportObject::LineStrip );
773 exportObject->setupPositionCoordinates( positionData, QMatrix4x4() );
774 exportObject->setupLine( indexData );
775
776 objs.push_back( exportObject );
777 }
778 return objs;
779}
780
781Qgs3DExportObject *Qgs3DSceneExporter::processPoints( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
782{
783 QVector<float> points;
784 const QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
785 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
786 {
787 Qt3DQGeometry *geometry = qobject_cast<QgsBillboardGeometry *>( renderer->geometry() );
788 if ( !geometry )
789 continue;
790 Qt3DQAttribute *positionAttribute = findAttribute( geometry, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
791 if ( !positionAttribute )
792 {
793 QgsDebugError( QString( "Cannot export '%1' - geometry has no position attribute!" ).arg( objectNamePrefix ) );
794 continue;
795 }
796 const QByteArray positionBytes = getData( positionAttribute->buffer() );
797 if ( positionBytes.isNull() )
798 {
799 QgsDebugError( QString( "Geometry for '%1' has position attribute with empty data!" ).arg( objectNamePrefix ) );
800 continue;
801 }
802 const QVector<float> positions = getAttributeData<float>( positionAttribute, positionBytes );
803 points << positions;
804 }
805 Qgs3DExportObject *obj = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "points" ) ) );
807 obj->setupPositionCoordinates( points, QMatrix4x4() );
808 return obj;
809}
810
811bool Qgs3DSceneExporter::save( const QString &sceneName, const QString &sceneFolderPath, int precision )
812{
813 if ( mObjects.isEmpty() )
814 {
815 return false;
816 }
817
818 const QString objFilePath = QDir( sceneFolderPath ).filePath( sceneName + QStringLiteral( ".obj" ) );
819 const QString mtlFilePath = QDir( sceneFolderPath ).filePath( sceneName + QStringLiteral( ".mtl" ) );
820
821 QFile file( objFilePath );
822 if ( !file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
823 {
824 QgsDebugError( QStringLiteral( "Scene can not be exported to '%1'. File access error." ).arg( objFilePath ) );
825 return false;
826 }
827 QFile mtlFile( mtlFilePath );
828 if ( !mtlFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
829 {
830 QgsDebugError( QStringLiteral( "Scene can not be exported to '%1'. File access error." ).arg( mtlFilePath ) );
831 return false;
832 }
833
834 float maxfloat = std::numeric_limits<float>::max(), minFloat = std::numeric_limits<float>::lowest();
835 float minX = maxfloat, minY = maxfloat, minZ = maxfloat, maxX = minFloat, maxY = minFloat, maxZ = minFloat;
836 for ( Qgs3DExportObject *obj : qAsConst( mObjects ) )
837 {
838 obj->objectBounds( minX, minY, minZ, maxX, maxY, maxZ );
839 }
840
841 float diffX = 1.0f, diffY = 1.0f, diffZ = 1.0f;
842 diffX = maxX - minX;
843 diffY = maxY - minY;
844 diffZ = maxZ - minZ;
845
846 const float centerX = ( minX + maxX ) / 2.0f;
847 const float centerY = ( minY + maxY ) / 2.0f;
848 const float centerZ = ( minZ + maxZ ) / 2.0f;
849
850 const float scale = std::max( diffX, std::max( diffY, diffZ ) );
851
852 QTextStream out( &file );
853 // set material library name
854 const QString mtlLibName = sceneName + ".mtl";
855 out << "mtllib " << mtlLibName << "\n";
856
857 QTextStream mtlOut( &mtlFile );
858 for ( Qgs3DExportObject *obj : qAsConst( mObjects ) )
859 {
860 if ( !obj )
861 continue;
862 // Set object name
863 const QString material = obj->saveMaterial( mtlOut, sceneFolderPath );
864 out << "o " << obj->name() << "\n";
865 if ( material != QString() )
866 out << "usemtl " << material << "\n";
867 obj->saveTo( out, scale / mScale, QVector3D( centerX, centerY, centerZ ), precision );
868 }
869
870 QgsDebugMsgLevel( QStringLiteral( "Scene exported to '%1'" ).arg( objFilePath ), 2 );
871 return true;
872}
873
874QString Qgs3DSceneExporter::getObjectName( const QString &name )
875{
876 QString ret = name;
877 if ( usedObjectNamesCounter.contains( name ) )
878 {
879 ret = QStringLiteral( "%1%2" ).arg( name ).arg( usedObjectNamesCounter[name] );
880 usedObjectNamesCounter[name]++;
881 }
882 else
883 usedObjectNamesCounter[name] = 2;
884 return ret;
885}
Manages the data of each object of the scene (positions, normals, texture coordinates ....
void setType(ObjectType type)
Sets the object type.
void setupPositionCoordinates(const QVector< float > &positionsBuffer, const QMatrix4x4 &transform)
Sets positions coordinates and does the translation, rotation and scaling.
void objectBounds(float &minX, float &minY, float &minZ, float &maxX, float &maxY, float &maxZ)
Updates the box bounds explained with the current object bounds This expands the bounding box if the ...
void saveTo(QTextStream &out, float scale, const QVector3D &center, int precision=6)
Saves the current object to the output stream while scaling the object and centering it to be visible...
QString name() const
Returns the object name.
QString saveMaterial(QTextStream &mtlOut, const QString &folder)
saves the texture of the object and material information
void setupLine(const QVector< uint > &facesIndexes)
sets line vertex indexes
QgsTerrainGenerator * terrainGenerator() const
Returns the terrain generator.
bool terrainRenderingEnabled() const
Returns whether the 2D terrain surface will be rendered.
bool save(const QString &sceneName, const QString &sceneFolderPath, int precision=6)
Saves the scene to a .obj file Returns false if the operation failed.
void parseTerrain(QgsTerrainEntity *terrain, const QString &layer)
Creates terrain export objects from the terrain entity.
float scale() const
Returns the scale of the exported 3D model.
bool parseVectorLayerEntity(Qt3DCore::QEntity *entity, QgsVectorLayer *layer)
Creates necessary export objects from entity if it represents valid vector layer entity Returns false...
static QgsPhongMaterialSettings phongMaterialFromQt3DComponent(Qt3DExtras::QPhongMaterial *material)
Returns phong material settings object based on the Qt3D material.
Base class for all renderers that may to participate in 3D view.
virtual QString type() const =0
Returns unique identifier of the renderer class (used to identify subclass)
virtual bool exportGeometries(Qgs3DSceneExporter *exporter, Qt3DCore::QEntity *entity, const QString &objectNamePrefix) const
Exports the geometries contained within the hierarchy of entity.
QgsDemHeightMapGenerator * heightMapGenerator()
Returns height map generator object - takes care of extraction of elevations from the layer)
QgsChunkLoader * createChunkLoader(QgsChunkNode *node) const override
void setResolution(int resolution)
Sets resolution of the generator (how many elevation samples on one side of a terrain tile)
QgsChunkLoader * createChunkLoader(QgsChunkNode *node) const override SIP_FACTORY
Holds an image that can be used as a texture in the 3D view.
QImage getImage() const
Returns the image.
QString name
Definition qgsmaplayer.h:80
QgsAbstract3DRenderer * renderer3D() const
Returns 3D renderer associated with the layer.
@ QuantizedMesh
Terrain is built from quantized mesh tiles.
@ Dem
Terrain is built from raster layer with digital elevation model.
@ Online
Terrain is built from downloaded tiles with digital elevation model.
@ Mesh
Terrain is built from mesh layer with z value on vertices.
@ Flat
The whole terrain is flat area.
virtual Type type() const =0
What texture generator implementation is this.
QVector< QgsFeatureId > featureIds() const
Returns included feature ids.
QVector< uint > triangleIndexStartingIndices() const
Returns triangle index for features. For a feature featureIds()[i], matching triangles start at trian...
3D renderer that renders all features of a vector layer with the same 3D symbol.
const QgsAbstract3DSymbol * symbol() const
Returns 3D symbol associated with the renderer.
Represents a vector layer which manages a vector based data sets.
Qt3DCore::QAttribute Qt3DQAttribute
Qt3DCore::QBuffer Qt3DQBuffer
QVector< T > getAttributeData(Qt3DQAttribute *attribute, const QByteArray &data)
Qt3DQAttribute * findAttribute(Qt3DQGeometry *geometry, const QString &name, Qt3DQAttribute::AttributeType type)
Qt3DCore::QAttribute Qt3DQAttribute
QVector< uint > getIndexData(Qt3DQAttribute *indexAttribute, const QByteArray &data)
QByteArray getData(Qt3DQBuffer *buffer)
Qt3DCore::QBuffer Qt3DQBuffer
QVector< uint > _getIndexDataImplementation(const QByteArray &data)
Component * findTypedComponent(Qt3DCore::QEntity *entity)
Qt3DCore::QGeometry Qt3DQGeometry
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
#define QgsDebugError(str)
Definition qgslogger.h:38
int precision