QGIS API Documentation  3.20.0-Odense (decaadbb31)
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 
18 #include <QVector>
19 #include <Qt3DCore/QEntity>
20 #include <Qt3DCore/QComponent>
21 #include <Qt3DCore/QNode>
22 #include <Qt3DRender/QGeometry>
23 #include <Qt3DRender/QAttribute>
24 #include <Qt3DRender/QBuffer>
25 #include <Qt3DRender/QGeometryRenderer>
26 #include <Qt3DExtras/QPlaneGeometry>
27 #include <Qt3DCore/QTransform>
28 #include <Qt3DRender/QMaterial>
29 #include <Qt3DExtras/QDiffuseSpecularMaterial>
30 #include <Qt3DExtras/QTextureMaterial>
31 #include <Qt3DRender/QTextureImage>
32 #include <Qt3DRender/QTexture>
33 #include <Qt3DRender/QBufferDataGenerator>
34 #include <Qt3DRender/QBufferDataGeneratorPtr>
35 #include <Qt3DRender/QMesh>
36 #include <Qt3DRender/QSceneLoader>
37 #include <Qt3DRender/QAbstractTexture>
38 #include <Qt3DExtras/QCylinderGeometry>
39 #include <Qt3DExtras/QConeGeometry>
40 #include <Qt3DExtras/QSphereGeometry>
41 #include <Qt3DExtras/QCuboidGeometry>
42 #include <Qt3DExtras/QTorusGeometry>
43 #include <Qt3DExtras/QExtrudedTextMesh>
44 #include <Qt3DExtras/QPhongMaterial>
45 #include <Qt3DRender/QAbstractTextureImage>
46 
47 #include <QByteArray>
48 #include <QFile>
49 #include <QTextStream>
50 
52 #include "qgsterraintileentity_p.h"
53 #include "qgsterrainentity_p.h"
54 #include "qgschunknode_p.h"
55 #include "qgsterraingenerator.h"
56 #include "qgs3dmapsettings.h"
58 #include "qgsdemterraingenerator.h"
61 #include "qgs3dexportobject.h"
64 #include "qgsmesh3dgeometry_p.h"
65 #include "qgsmeshlayer.h"
66 #include "qgsmesh3dentity_p.h"
67 #include "qgsmeshterraingenerator.h"
68 #include "qgsvectorlayer.h"
69 #include "qgsabstract3drenderer.h"
72 #include "qgspolygon3dsymbol.h"
73 #include "qgsline3dsymbol.h"
74 #include "qgspoint3dsymbol.h"
75 #include "qgsrulebased3drenderer.h"
76 #include "qgs3dutils.h"
77 #include "qgsbillboardgeometry.h"
78 #include "qgsimagetexture.h"
79 
80 #include <numeric>
81 
82 template<typename T>
83 QVector<T> getAttributeData( Qt3DRender::QAttribute *attribute, const QByteArray &data )
84 {
85  uint bytesOffset = attribute->byteOffset();
86  uint bytesStride = attribute->byteStride();
87  uint vertexSize = attribute->vertexSize();
88  QVector<T> result;
89 
90  if ( bytesStride == 0 )
91  {
92  QgsDebugMsg( "bytesStride==0, the attribute probably was not set properly" );
93  return result;
94  }
95 
96  const char *pData = data.constData();
97  for ( int i = bytesOffset; i < data.size(); i += bytesStride )
98  {
99  for ( unsigned int j = 0; j < vertexSize * sizeof( T ); j += sizeof( T ) )
100  {
101  T v;
102  memcpy( &v, pData + i + j, sizeof( T ) );
103  result.push_back( v );
104  }
105  }
106  return result;
107 }
108 
109 template<typename T>
110 QVector<uint> _getIndexDataImplementation( const QByteArray &data )
111 {
112  QVector<uint> result;
113  const char *pData = data.constData();
114  for ( int i = 0; i < data.size(); i += sizeof( T ) )
115  {
116  T v;
117  memcpy( &v, pData + i, sizeof( T ) );
118  result.push_back( ( uint ) v );
119  }
120  return result;
121 }
122 
123 QVector<uint> getIndexData( Qt3DRender::QAttribute *indexAttribute, const QByteArray &data )
124 {
125  switch ( indexAttribute->vertexBaseType() )
126  {
127  case Qt3DRender::QAttribute::VertexBaseType::Int:
128  return _getIndexDataImplementation<int>( data );
129  case Qt3DRender::QAttribute::VertexBaseType::UnsignedInt:
130  return _getIndexDataImplementation<uint>( data );
131  case Qt3DRender::QAttribute::VertexBaseType::Short:
132  return _getIndexDataImplementation<short>( data );
133  case Qt3DRender::QAttribute::VertexBaseType::UnsignedShort:
134  return _getIndexDataImplementation<ushort>( data );
135  case Qt3DRender::QAttribute::VertexBaseType::Byte:
136  return _getIndexDataImplementation<char>( data );
137  case Qt3DRender::QAttribute::VertexBaseType::UnsignedByte:
138  return _getIndexDataImplementation<uchar>( data );
139  default:
140  QgsDebugMsg( "Probably trying to get index data using an attribute that has vertex data" );
141  break;
142  }
143  return QVector<uint>();
144 }
145 
146 QByteArray getData( Qt3DRender::QBuffer *buffer )
147 {
148  QByteArray bytes = buffer->data();
149  if ( bytes.isNull() )
150  {
151  QgsDebugMsg( "QBuffer is null" );
152  }
153  return bytes;
154 }
155 
156 Qt3DRender::QAttribute *findAttribute( Qt3DRender::QGeometry *geometry, const QString &name, Qt3DRender::QAttribute::AttributeType type )
157 {
158  for ( Qt3DRender::QAttribute *attribute : geometry->attributes() )
159  {
160  if ( attribute->attributeType() != type ) continue;
161  if ( attribute->name() == name ) return attribute;
162  }
163  return nullptr;
164 }
165 
166 template<typename Component>
167 Component *findTypedComponent( Qt3DCore::QEntity *entity )
168 {
169  if ( entity == nullptr ) return nullptr;
170  for ( Qt3DCore::QComponent *component : entity->components() )
171  {
172  Component *typedComponent = qobject_cast<Component *>( component );
173  if ( typedComponent != nullptr )
174  return typedComponent;
175  }
176  return nullptr;
177 }
178 
179 bool Qgs3DSceneExporter::parseVectorLayerEntity( Qt3DCore::QEntity *entity, QgsVectorLayer *layer )
180 {
181  QgsAbstract3DRenderer *abstractRenderer = layer->renderer3D();
182  QString rendererType = abstractRenderer->type();
183 
184  if ( rendererType == "mesh" )
185  {
186  // TODO: handle mesh layers
187  }
188  else
189  {
190  QgsAbstractVectorLayer3DRenderer *abstractVectorRenderer = dynamic_cast< QgsAbstractVectorLayer3DRenderer *>( abstractRenderer );
191  if ( rendererType == "rulebased" )
192  {
193  // Potential bug: meshes loaded using Qt3DRender::QSceneLoader will probably have wrong scale and translation
194  QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
195  for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
196  {
197  Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( renderer->parent() );
198  if ( entity == nullptr ) continue;
199  Qgs3DExportObject *object = processGeometryRenderer( renderer, layer->name() + QStringLiteral( "_" ) );
200  if ( object == nullptr ) continue;
201  if ( mExportTextures )
202  processEntityMaterial( entity, object );
203  mObjects.push_back( object );
204  }
205  return true;
206  }
207  else
208  {
209  QgsVectorLayer3DRenderer *vectorLayerRenderer = dynamic_cast< QgsVectorLayer3DRenderer *>( abstractVectorRenderer );
210  const QgsAbstract3DSymbol *symbol = vectorLayerRenderer->symbol();
211  bool exported = symbol->exportGeometries( this, entity, layer->name() + QStringLiteral( "_" ) );
212  return exported;
213  }
214  }
215  return false;
216 }
217 
218 void Qgs3DSceneExporter::processEntityMaterial( Qt3DCore::QEntity *entity, Qgs3DExportObject *object )
219 {
220  Qt3DExtras::QPhongMaterial *phongMaterial = findTypedComponent<Qt3DExtras::QPhongMaterial>( entity );
221  if ( phongMaterial != nullptr )
222  {
224  object->setupMaterial( &material );
225  }
226  Qt3DExtras::QDiffuseSpecularMaterial *diffuseMapMaterial = findTypedComponent<Qt3DExtras::QDiffuseSpecularMaterial>( entity );
227 
228  if ( diffuseMapMaterial != nullptr )
229  {
230  QVector<Qt3DRender::QAbstractTextureImage *> textureImages = diffuseMapMaterial->diffuse().value< Qt3DRender::QTexture2D * >()->textureImages();
231  QgsImageTexture *imageTexture = nullptr;
232  for ( Qt3DRender::QAbstractTextureImage *tex : textureImages )
233  {
234  imageTexture = dynamic_cast<QgsImageTexture *>( tex );
235  if ( imageTexture != nullptr ) break;
236  }
237  if ( imageTexture != nullptr )
238  {
239  QImage image = imageTexture->getImage();
240  object->setTextureImage( image );
241  }
242  }
243 }
244 
245 void Qgs3DSceneExporter::parseTerrain( QgsTerrainEntity *terrain, const QString &layerName )
246 {
247  const Qgs3DMapSettings &settings = terrain->map3D();
248  QgsChunkNode *node = terrain->rootNode();
249 
250  QgsTerrainGenerator *generator = settings.terrainGenerator();
251  QgsTerrainTileEntity *terrainTile = nullptr;
252  QgsTerrainTextureGenerator *textureGenerator = terrain->textureGenerator();
253  textureGenerator->waitForFinished();
254  QSize oldResolution = textureGenerator->textureSize();
255  textureGenerator->setTextureSize( QSize( mTerrainTextureResolution, mTerrainTextureResolution ) );
256  switch ( generator->type() )
257  {
259  terrainTile = getDemTerrainEntity( terrain, node );
260  parseDemTile( terrainTile, layerName + QStringLiteral( "_" ) );
261  break;
263  terrainTile = getFlatTerrainEntity( terrain, node );
264  parseFlatTile( terrainTile, layerName + QStringLiteral( "_" ) );
265  break;
266  // TODO: implement other terrain types
268  terrainTile = getMeshTerrainEntity( terrain, node );
269  parseMeshTile( terrainTile, layerName + QStringLiteral( "_" ) );
270  break;
272  break;
273  }
274  textureGenerator->setTextureSize( oldResolution );
275 }
276 
277 QgsTerrainTileEntity *Qgs3DSceneExporter::getFlatTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
278 {
279  QgsFlatTerrainGenerator *generator = dynamic_cast<QgsFlatTerrainGenerator *>( terrain->map3D().terrainGenerator() );
280  FlatTerrainChunkLoader *flatTerrainLoader = qobject_cast<FlatTerrainChunkLoader *>( generator->createChunkLoader( node ) );
281  if ( mExportTextures )
282  terrain->textureGenerator()->waitForFinished();
283  // the entity we created will be deallocated once the scene exporter is deallocated
284  Qt3DCore::QEntity *entity = flatTerrainLoader->createEntity( this );
285  QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( entity );
286  return tileEntity;
287 }
288 
289 QgsTerrainTileEntity *Qgs3DSceneExporter::getDemTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
290 {
291  // Just create a new tile (we don't need to export exact level of details as in the scene)
292  // create the entity synchronously and then it will be deleted once our scene exporter instance is deallocated
293  QgsDemTerrainGenerator *generator = dynamic_cast<QgsDemTerrainGenerator *>( terrain->map3D().terrainGenerator()->clone() );
294  generator->setResolution( mTerrainResolution );
295  QgsDemTerrainTileLoader *loader = qobject_cast<QgsDemTerrainTileLoader *>( generator->createChunkLoader( node ) );
296  generator->heightMapGenerator()->waitForFinished();
297  if ( mExportTextures )
298  terrain->textureGenerator()->waitForFinished();
299  QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( loader->createEntity( this ) );
300  delete generator;
301  return tileEntity;
302 }
303 
304 QgsTerrainTileEntity *Qgs3DSceneExporter::getMeshTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
305 {
306  QgsMeshTerrainGenerator *generator = dynamic_cast<QgsMeshTerrainGenerator *>( terrain->map3D().terrainGenerator() );
307  QgsMeshTerrainTileLoader *loader = qobject_cast<QgsMeshTerrainTileLoader *>( generator->createChunkLoader( node ) );
308  // TODO: export textures
309  QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( loader->createEntity( this ) );
310  return tileEntity;
311 }
312 
313 void Qgs3DSceneExporter::parseFlatTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
314 {
315  Qt3DRender::QGeometryRenderer *mesh = findTypedComponent<Qt3DRender::QGeometryRenderer>( tileEntity );
316  Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( tileEntity );
317 
318  Qt3DRender::QGeometry *geometry = mesh->geometry();
319  Qt3DExtras::QPlaneGeometry *tileGeometry = qobject_cast<Qt3DExtras::QPlaneGeometry *>( geometry );
320  if ( tileGeometry == nullptr )
321  {
322  QgsDebugMsg( "Qt3DExtras::QPlaneGeometry* is expected but something else was given" );
323  return;
324  }
325 
326  float scale = transform->scale();
327  QVector3D translation = transform->translation();
328 
329  // Generate vertice data
330  Qt3DRender::QAttribute *positionAttribute = tileGeometry->positionAttribute();
331  QByteArray verticesBytes = getData( positionAttribute->buffer() );
332  QVector<float> positionBuffer = getAttributeData<float>( positionAttribute, verticesBytes );
333 
334  // Generate index data
335  Qt3DRender::QAttribute *indexAttribute = tileGeometry->indexAttribute();
336  QByteArray indexBytes = getData( indexAttribute->buffer() );
337  QVector<uint> indexesBuffer = getIndexData( indexAttribute, indexBytes );
338 
339  QString objectNamePrefix = layerName;
340  if ( objectNamePrefix != QString() ) objectNamePrefix += QString();
341 
342  Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "Flat_tile" ) ) );
343  mObjects.push_back( object );
344 
345  object->setSmoothEdges( mSmoothEdges );
346  object->setupPositionCoordinates( positionBuffer, scale, translation );
347  object->setupFaces( indexesBuffer );
348 
349  if ( mExportNormals )
350  {
351  // Everts
352  QVector<float> normalsBuffer;
353  for ( int i = 0; i < positionBuffer.size(); i += 3 ) normalsBuffer << 0.0f << 1.0f << 0.0f;
354  object->setupNormalCoordinates( normalsBuffer );
355  }
356 
357  Qt3DRender::QAttribute *texCoordsAttribute = tileGeometry->texCoordAttribute();
358  if ( mExportTextures && texCoordsAttribute != nullptr )
359  {
360  // Reuse vertex buffer data for texture coordinates
361  QVector<float> texCoords = getAttributeData<float>( texCoordsAttribute, verticesBytes );
362  object->setupTextureCoordinates( texCoords );
363 
364  QgsTerrainTextureImage *textureImage = tileEntity->textureImage();
365  QImage img = textureImage->getImage();
366  object->setTextureImage( img );
367  }
368 }
369 
370 void Qgs3DSceneExporter::parseDemTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
371 {
372  Qt3DRender::QGeometryRenderer *mesh = findTypedComponent<Qt3DRender::QGeometryRenderer>( tileEntity );
373  Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( tileEntity );
374 
375  Qt3DRender::QGeometry *geometry = mesh->geometry();
376  DemTerrainTileGeometry *tileGeometry = qobject_cast<DemTerrainTileGeometry *>( geometry );
377  if ( tileGeometry == nullptr )
378  {
379  QgsDebugMsg( "DemTerrainTileGeometry* is expected but something else was given" );
380  return;
381  }
382 
383  float scale = transform->scale();
384  QVector3D translation = transform->translation();
385 
386  Qt3DRender::QAttribute *positionAttribute = tileGeometry->positionAttribute();
387  QByteArray positionBytes = positionAttribute->buffer()->data();
388  QVector<float> positionBuffer = getAttributeData<float>( positionAttribute, positionBytes );
389 
390  Qt3DRender::QAttribute *indexAttribute = tileGeometry->indexAttribute();
391  QByteArray indexBytes = indexAttribute->buffer()->data();
392  QVector<unsigned int> indexBuffer = getIndexData( indexAttribute, indexBytes );
393 
394  QString objectNamePrefix = layerName;
395  if ( objectNamePrefix != QString() ) objectNamePrefix += QStringLiteral( "_" );
396 
397  Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( layerName + QStringLiteral( "DEM_tile" ) ) );
398  mObjects.push_back( object );
399 
400  object->setSmoothEdges( mSmoothEdges );
401  object->setupPositionCoordinates( positionBuffer, scale, translation );
402  object->setupFaces( indexBuffer );
403 
404  Qt3DRender::QAttribute *normalsAttributes = tileGeometry->normalAttribute();
405  if ( mExportNormals && normalsAttributes != nullptr )
406  {
407  QByteArray normalsBytes = normalsAttributes->buffer()->data();
408  QVector<float> normalsBuffer = getAttributeData<float>( normalsAttributes, normalsBytes );
409  object->setupNormalCoordinates( normalsBuffer );
410  }
411 
412  Qt3DRender::QAttribute *texCoordsAttribute = tileGeometry->texCoordsAttribute();
413  if ( mExportTextures && texCoordsAttribute != nullptr )
414  {
415  QByteArray texCoordsBytes = texCoordsAttribute->buffer()->data();
416  QVector<float> texCoordsBuffer = getAttributeData<float>( texCoordsAttribute, texCoordsBytes );
417  object->setupTextureCoordinates( texCoordsBuffer );
418 
419  QgsTerrainTextureImage *textureImage = tileEntity->textureImage();
420  QImage img = textureImage->getImage();
421  object->setTextureImage( img );
422  }
423 }
424 
425 void Qgs3DSceneExporter::parseMeshTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
426 {
427  QString objectNamePrefix = layerName;
428  if ( objectNamePrefix != QString() ) objectNamePrefix += QStringLiteral( "_" );
429 
430  QList<Qt3DRender::QGeometryRenderer *> renderers = tileEntity->findChildren<Qt3DRender::QGeometryRenderer *>();
431  for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
432  {
433  Qgs3DExportObject *obj = processGeometryRenderer( renderer, objectNamePrefix );
434  if ( obj == nullptr ) continue;
435  mObjects << obj;
436  }
437 }
438 
439 QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processInstancedPointGeometry( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
440 {
441  QVector<Qgs3DExportObject *> objects;
442  QList<Qt3DRender::QGeometry *> geometriesList = entity->findChildren<Qt3DRender::QGeometry *>();
443  for ( Qt3DRender::QGeometry *geometry : geometriesList )
444  {
445  Qt3DRender::QAttribute *positionAttribute = findAttribute( geometry, Qt3DRender::QAttribute::defaultPositionAttributeName(), Qt3DRender::QAttribute::VertexAttribute );
446  Qt3DRender::QAttribute *indexAttribute = nullptr;
447  for ( Qt3DRender::QAttribute *attribute : geometry->attributes() )
448  {
449  if ( attribute->attributeType() == Qt3DRender::QAttribute::IndexAttribute )
450  indexAttribute = attribute;
451  }
452  if ( positionAttribute == nullptr || indexAttribute == nullptr )
453  continue;
454  QByteArray vertexBytes = getData( positionAttribute->buffer() );
455  QByteArray indexBytes = getData( indexAttribute->buffer() );
456  QVector<float> positionData = getAttributeData<float>( positionAttribute, vertexBytes );
457  QVector<uint> indexData = getIndexData( indexAttribute, indexBytes );
458 
459  Qt3DRender::QAttribute *instanceDataAttribute = findAttribute( geometry, QStringLiteral( "pos" ), Qt3DRender::QAttribute::VertexAttribute );
460  QByteArray instancePositionBytes = getData( instanceDataAttribute->buffer() );
461  QVector<float> instancePosition = getAttributeData<float>( instanceDataAttribute, instancePositionBytes );
462  for ( int i = 0; i < instancePosition.size(); i += 3 )
463  {
464  Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "shape_geometry" ) ) );
465  objects.push_back( object );
466  object->setupPositionCoordinates( positionData, 1.0f, QVector3D( instancePosition[i], instancePosition[i + 1], instancePosition[i + 2] ) );
467  object->setupFaces( indexData );
468 
469  object->setSmoothEdges( mSmoothEdges );
470 
471  Qt3DRender::QAttribute *normalsAttribute = findAttribute( geometry, Qt3DRender::QAttribute::defaultNormalAttributeName(), Qt3DRender::QAttribute::VertexAttribute );
472  if ( mExportNormals && normalsAttribute != nullptr )
473  {
474  // Reuse vertex bytes
475  QVector<float> normalsData = getAttributeData<float>( normalsAttribute, vertexBytes );
476  object->setupNormalCoordinates( normalsData );
477  }
478  }
479  }
480  return objects;
481 }
482 
483 QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processSceneLoaderGeometries( Qt3DRender::QSceneLoader *sceneLoader, const QString &objectNamePrefix )
484 {
485  QVector<Qgs3DExportObject *> objects;
486  Qt3DCore::QEntity *sceneLoaderParent = qobject_cast<Qt3DCore::QEntity *>( sceneLoader->parent() );
487  Qt3DCore::QTransform *entityTransform = findTypedComponent<Qt3DCore::QTransform>( sceneLoaderParent );
488  float sceneScale = 1.0f;
489  QVector3D sceneTranslation( 0.0f, 0.0f, 0.0f );
490  if ( entityTransform != nullptr )
491  {
492  sceneScale = entityTransform->scale();
493  sceneTranslation = entityTransform->translation();
494  }
495  for ( QString entityName : sceneLoader->entityNames() )
496  {
497  Qt3DRender::QGeometryRenderer *mesh = qobject_cast<Qt3DRender::QGeometryRenderer *>( sceneLoader->component( entityName, Qt3DRender::QSceneLoader::GeometryRendererComponent ) );
498  Qgs3DExportObject *object = processGeometryRenderer( mesh, objectNamePrefix, sceneScale, sceneTranslation );
499  if ( object == nullptr ) continue;
500  objects.push_back( object );
501  }
502  return objects;
503 }
504 
505 Qgs3DExportObject *Qgs3DSceneExporter::processGeometryRenderer( Qt3DRender::QGeometryRenderer *mesh, const QString &objectNamePrefix, float sceneScale, QVector3D sceneTranslation )
506 {
507  // We only export triangles for now
508  if ( mesh->primitiveType() != Qt3DRender::QGeometryRenderer::Triangles ) return nullptr;
509 
510  float scale = 1.0f;
511  QVector3D translation( 0.0f, 0.0f, 0.0f );
512  QObject *parent = mesh->parent();
513  while ( parent != nullptr )
514  {
515  Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( parent );
516  Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( entity );
517  if ( transform != nullptr )
518  {
519  scale *= transform->scale();
520  translation += transform->translation();
521  }
522  parent = parent->parent();
523  }
524 
525  Qt3DRender::QGeometry *geometry = mesh->geometry();
526 
527  Qt3DRender::QAttribute *positionAttribute = findAttribute( geometry, Qt3DRender::QAttribute::defaultPositionAttributeName(), Qt3DRender::QAttribute::VertexAttribute );
528  Qt3DRender::QAttribute *indexAttribute = nullptr;
529  QByteArray indexBytes, vertexBytes;
530  QVector<uint> indexData;
531  QVector<float> positionData;
532  for ( Qt3DRender::QAttribute *attribute : geometry->attributes() )
533  {
534  if ( attribute->attributeType() == Qt3DRender::QAttribute::IndexAttribute )
535  indexAttribute = attribute;
536  }
537 
538  if ( indexAttribute != nullptr )
539  {
540  indexBytes = getData( indexAttribute->buffer() );
541  indexData = getIndexData( indexAttribute, indexBytes );
542  }
543 
544  if ( positionAttribute != nullptr )
545  {
546  vertexBytes = getData( positionAttribute->buffer() );
547  positionData = getAttributeData<float>( positionAttribute, vertexBytes );
548  }
549 
550 // For tessellated polygons that don't have index attributes
551  if ( positionAttribute != nullptr && indexAttribute == nullptr )
552  {
553  for ( int i = 0; i < positionData.size() / 3; ++i )
554  indexData.push_back( i );
555  }
556 
557  if ( positionAttribute == nullptr )
558  {
559  QgsDebugMsg( "Geometry renderer with null data was being processed" );
560  return nullptr;
561  }
562 
563  Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "mesh_geometry" ) ) );
564  object->setupPositionCoordinates( positionData, scale * sceneScale, translation + sceneTranslation );
565  object->setupFaces( indexData );
566 
567  Qt3DRender::QAttribute *normalsAttribute = findAttribute( geometry, Qt3DRender::QAttribute::defaultNormalAttributeName(), Qt3DRender::QAttribute::VertexAttribute );
568  if ( mExportNormals && normalsAttribute != nullptr )
569  {
570  // Reuse vertex bytes
571  QVector<float> normalsData = getAttributeData<float>( normalsAttribute, vertexBytes );
572  object->setupNormalCoordinates( normalsData );
573  }
574 
575  Qt3DRender::QAttribute *texCoordsAttribute = findAttribute( geometry, Qt3DRender::QAttribute::defaultTextureCoordinateAttributeName(), Qt3DRender::QAttribute::VertexAttribute );
576  if ( mExportTextures && texCoordsAttribute != nullptr )
577  {
578  // Reuse vertex bytes
579  QVector<float> texCoordsData = getAttributeData<float>( texCoordsAttribute, vertexBytes );
580  object->setupTextureCoordinates( texCoordsData );
581  }
582 
583  return object;
584 }
585 
586 QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processLines( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
587 {
588  QVector<Qgs3DExportObject *> objs;
589  QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
590  for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
591  {
592  if ( renderer->primitiveType() != Qt3DRender::QGeometryRenderer::LineStripAdjacency ) continue;
593  Qt3DRender::QGeometry *geom = renderer->geometry();
594  Qt3DRender::QAttribute *positionAttribute = findAttribute( geom, Qt3DRender::QAttribute::defaultPositionAttributeName(), Qt3DRender::QAttribute::VertexAttribute );
595  Qt3DRender::QAttribute *indexAttribute = nullptr;
596  for ( Qt3DRender::QAttribute *attribute : geom->attributes() )
597  {
598  if ( attribute->attributeType() == Qt3DRender::QAttribute::IndexAttribute )
599  {
600  indexAttribute = attribute;
601  break;
602  }
603  }
604  if ( positionAttribute == nullptr || indexAttribute == nullptr )
605  {
606  QgsDebugMsg( "Position or index attribute was not found" );
607  continue;
608  }
609 
610  QByteArray vertexBytes = getData( positionAttribute->buffer() );
611  QByteArray indexBytes = getData( indexAttribute->buffer() );
612  QVector<float> positionData = getAttributeData<float>( positionAttribute, vertexBytes );
613  QVector<uint> indexData = getIndexData( indexAttribute, indexBytes );
614 
615  Qgs3DExportObject *exportObject = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "line" ) ) );
616  exportObject->setType( Qgs3DExportObject::LineStrip );
617  exportObject->setupPositionCoordinates( positionData );
618  exportObject->setupLine( indexData );
619 
620  objs.push_back( exportObject );
621  }
622  return objs;
623 }
624 
625 Qgs3DExportObject *Qgs3DSceneExporter::processPoints( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
626 {
627  QVector<float> points;
628  QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
629  for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
630  {
631  Qt3DRender::QGeometry *geometry = qobject_cast<QgsBillboardGeometry *>( renderer->geometry() );
632  if ( geometry == nullptr )
633  continue;
634  Qt3DRender::QAttribute *positionAttribute = findAttribute( geometry, Qt3DRender::QAttribute::defaultPositionAttributeName(), Qt3DRender::QAttribute::VertexAttribute );
635  QByteArray positionBytes = getData( positionAttribute->buffer() );
636  if ( positionBytes.size() == 0 )
637  continue;
638  QVector<float> positions = getAttributeData<float>( positionAttribute, positionBytes );
639  points << positions;
640  }
641  Qgs3DExportObject *obj = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "points" ) ) );
643  obj->setupPositionCoordinates( points );
644  return obj;
645 }
646 
647 void Qgs3DSceneExporter::save( const QString &sceneName, const QString &sceneFolderPath )
648 {
649  QString objFilePath = QDir( sceneFolderPath ).filePath( sceneName + QStringLiteral( ".obj" ) );
650  QString mtlFilePath = QDir( sceneFolderPath ).filePath( sceneName + QStringLiteral( ".mtl" ) );
651 
652  QFile file( objFilePath );
653  if ( !file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
654  return;
655  QFile mtlFile( mtlFilePath );
656  if ( !mtlFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
657  return;
658 
659  float maxfloat = std::numeric_limits<float>::max(), minFloat = std::numeric_limits<float>::lowest();
660  float minX = maxfloat, minY = maxfloat, minZ = maxfloat, maxX = minFloat, maxY = minFloat, maxZ = minFloat;
661  for ( Qgs3DExportObject *obj : mObjects ) obj->objectBounds( minX, minY, minZ, maxX, maxY, maxZ );
662 
663  float diffX = 1.0f, diffY = 1.0f, diffZ = 1.0f;
664  diffX = maxX - minX;
665  diffY = maxY - minY;
666  diffZ = maxZ - minZ;
667 
668  float centerX = ( minX + maxX ) / 2.0f;
669  float centerY = ( minY + maxY ) / 2.0f;
670  float centerZ = ( minZ + maxZ ) / 2.0f;
671 
672  float scale = std::max( diffX, std::max( diffY, diffZ ) );
673 
674  QTextStream out( &file );
675  // set material library name
676  QString mtlLibName = sceneName + ".mtl";
677  out << "mtllib " << mtlLibName << "\n";
678 
679  QTextStream mtlOut( &mtlFile );
680  for ( Qgs3DExportObject *obj : mObjects )
681  {
682  if ( obj == nullptr ) continue;
683  // Set object name
684  QString material = obj->saveMaterial( mtlOut, sceneFolderPath );
685  out << "o " << obj->name() << "\n";
686  if ( material != QString() )
687  out << "usemtl " << material << "\n";
688  obj->saveTo( out, scale / mScale, QVector3D( centerX, centerY, centerZ ) );
689  }
690 }
691 
692 QString Qgs3DSceneExporter::getObjectName( const QString &name )
693 {
694  QString ret = name;
695  if ( usedObjectNamesCounter.contains( name ) )
696  {
697  ret = QStringLiteral( "%1%2" ).arg( name ).arg( usedObjectNamesCounter[name] );
698  usedObjectNamesCounter[name]++;
699  }
700  else
701  usedObjectNamesCounter[name] = 2;
702  return ret;
703 }
Manages the data of each object of the scene (positions, normals, texture coordinates ....
void saveTo(QTextStream &out, float scale, const QVector3D &center)
Saves the current object to the output stream while scaling the object and centering it to be visible...
void setType(ObjectType type)
Sets the object type.
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 setupPositionCoordinates(const QVector< float > &positionsBuffer, float scale=1.0f, const QVector3D &translation=QVector3D(0, 0, 0))
Sets positions coordinates and does the translation and scaling.
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 terrain generator. It takes care of producing terrain tiles from the input data.
void parseTerrain(QgsTerrainEntity *terrain, const QString &layer)
Creates terrain export objects from the terrain entity.
void save(const QString &sceneName, const QString &sceneFolderPath)
Saves the scene to a .obj file.
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.
Definition: qgs3dutils.cpp:563
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:73
QgsAbstract3DRenderer * renderer3D() const
Returns 3D renderer associated with the layer.
@ 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.
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.
QVector< uint > getIndexData(Qt3DRender::QAttribute *indexAttribute, const QByteArray &data)
Qt3DRender::QAttribute * findAttribute(Qt3DRender::QGeometry *geometry, const QString &name, Qt3DRender::QAttribute::AttributeType type)
Component * findTypedComponent(Qt3DCore::QEntity *entity)
QVector< T > getAttributeData(Qt3DRender::QAttribute *attribute, const QByteArray &data)
QByteArray getData(Qt3DRender::QBuffer *buffer)
QVector< uint > _getIndexDataImplementation(const QByteArray &data)
#define QgsDebugMsg(str)
Definition: qgslogger.h:38