18#include <Qt3DRender/QCamera>
19#include <Qt3DRender/QMesh>
20#include <Qt3DRender/QObjectPicker>
21#include <Qt3DRender/QPickEvent>
22#include <Qt3DRender/QPickingSettings>
23#include <Qt3DRender/QPickTriangleEvent>
24#include <Qt3DRender/QRenderSettings>
25#include <Qt3DRender/QSceneLoader>
26#include <Qt3DExtras/QForwardRenderer>
27#include <Qt3DExtras/QPhongMaterial>
28#include <Qt3DExtras/QPhongAlphaMaterial>
29#include <Qt3DExtras/QDiffuseSpecularMaterial>
30#include <Qt3DExtras/QSphereMesh>
31#include <Qt3DLogic/QFrameAction>
32#include <Qt3DRender/QEffect>
33#include <Qt3DRender/QTechnique>
34#include <Qt3DRender/QRenderPass>
35#include <Qt3DRender/QRenderState>
36#include <Qt3DRender/QCullFace>
37#include <Qt3DRender/QDepthTest>
42#include <QOpenGLContext>
43#include <QOpenGLFunctions>
94 onBackgroundColorChanged();
99 mEngine->
renderSettings()->setRenderPolicy( Qt3DRender::QRenderSettings::OnDemand );
102 mEngine->
renderSettings()->pickingSettings()->setPickMethod( Qt3DRender::QPickingSettings::TrianglePicking );
104 QRect viewportRect( QPoint( 0, 0 ), mEngine->
size() );
107 float aspectRatio = ( float )viewportRect.width() / viewportRect.height();
108 mEngine->
camera()->lens()->setPerspectiveProjection( mMap.
fieldOfView(), aspectRatio, 10.f, 10000.0f );
110 mFrameAction =
new Qt3DLogic::QFrameAction();
111 connect( mFrameAction, &Qt3DLogic::QFrameAction::triggered,
112 this, &Qgs3DMapScene::onFrameTriggered );
113 addComponent( mFrameAction );
121 addCameraViewCenterEntity( mEngine->
camera() );
122 addCameraRotationCenterEntity( mCameraController );
127 createTerrainDeferred();
156 const QList<QgsMapLayer *> modelVectorLayers = mModelVectorLayers;
162 if ( renderer->
type() == QLatin1String(
"vector" ) )
165 if ( pointSymbol->
shapeProperties()[QStringLiteral(
"model" )].toString() == url )
167 removeLayerEntity( layer );
168 addLayerEntity( layer );
171 else if ( renderer->
type() == QLatin1String(
"rulebased" ) )
174 for (
auto rule : rules )
177 if ( pointSymbol->
shapeProperties()[QStringLiteral(
"model" )].toString() == url )
179 removeLayerEntity( layer );
180 addLayerEntity( layer );
191 onRenderersChanged();
198 ChunkedEntity *testChunkEntity =
new ChunkedEntity( AABB( -500, 0, -500, 500, 100, 500 ), 2.f, 3.f, 7,
new TestChunkLoaderFactory );
199 testChunkEntity->setEnabled(
false );
200 testChunkEntity->setParent(
this );
201 chunkEntities << testChunkEntity;
212 Qt3DCore::QEntity *loaderEntity =
new Qt3DCore::QEntity;
213 Qt3DRender::QSceneLoader *loader =
new Qt3DRender::QSceneLoader;
214 loader->setSource( QUrl(
"file:///home/martin/Downloads/LowPolyModels/tree.dae" ) );
215 loaderEntity->addComponent( loader );
216 loaderEntity->setParent(
this );
220 Qt3DCore::QEntity *meshEntity =
new Qt3DCore::QEntity;
221 Qt3DRender::QMesh *mesh =
new Qt3DRender::QMesh;
222 mesh->setSource( QUrl(
"file:///home/martin/Downloads/LowPolyModels/tree.obj" ) );
223 meshEntity->addComponent( mesh );
224 Qt3DExtras::QPhongMaterial *material =
new Qt3DExtras::QPhongMaterial;
225 material->setAmbient( Qt::red );
226 meshEntity->addComponent( material );
227 Qt3DCore::QTransform *meshTransform =
new Qt3DCore::QTransform;
228 meshTransform->setScale( 1 );
229 meshEntity->addComponent( meshTransform );
230 meshEntity->setParent(
this );
232 onSkyboxSettingsChanged();
237 onEyeDomeShadingSettingsChanged();
239 onDebugShadowMapSettingsChanged();
240 onDebugDepthMapSettingsChanged();
242 onAmbientOcclusionSettingsChanged();
245 onCameraMovementSpeedChanged();
247 on3DAxisSettingsChanged();
253 float side = std::max( extent.
width(), extent.
height() );
254 float a = side / 2.0f / std::sin( qDegreesToRadians(
cameraController()->camera()->fieldOfView() ) / 2.0f );
256 mCameraController->
resetView( 1.5 * std::sqrt( a * a - side * side ) );
266 float xSide = std::abs( p1.
x() - p2.
x() );
267 float ySide = std::abs( p1.
z() - p2.
z() );
270 float fov = 2 * std::atan( std::tan( qDegreesToRadians(
cameraController()->camera()->fieldOfView() ) / 2 ) *
cameraController()->camera()->aspectRatio() );
271 float r = xSide / 2.0f / std::tan( fov / 2.0f );
276 float fov = qDegreesToRadians(
cameraController()->camera()->fieldOfView() );
277 float r = ySide / 2.0f / std::tan( fov / 2.0f );
284 Qt3DRender::QCamera *camera = mCameraController->
camera();
285 const QRect viewport = mCameraController->
viewport();
286 QVector<QgsPointXY> extent;
287 QVector<int> pointsOrder = { 0, 1, 3, 2 };
288 for (
int i : pointsOrder )
290 const QPoint p( ( ( i >> 0 ) & 1 ) ? 0 : viewport.width(), ( ( i >> 1 ) & 1 ) ? 0 : viewport.height() );
293 if ( dir.y() == 0.0 )
294 dir.setY( 0.000001 );
295 double t = - ray.
origin().y() / dir.y();
299 t = camera->farPlane();
304 t = std::min<float>( t, camera->farPlane() );
306 QVector3D planePoint = ray.
origin() + t * dir;
315 return mTerrain ? mTerrain->pendingJobsCount() : 0;
321 for ( QgsChunkedEntity *entity : std::as_const( mChunkEntities ) )
322 count += entity->pendingJobsCount();
328 if ( mPickHandlers.isEmpty() )
331 for ( Qt3DCore::QEntity *entity : mLayerEntities.values() )
333 if ( QgsChunkedEntity *chunkedEntity = qobject_cast<QgsChunkedEntity *>( entity ) )
334 chunkedEntity->setPickingEnabled(
true );
338 mPickHandlers.append( pickHandler );
343 mPickHandlers.removeOne( pickHandler );
345 if ( mPickHandlers.isEmpty() )
348 for ( Qt3DCore::QEntity *entity : mLayerEntities.values() )
350 if ( QgsChunkedEntity *chunkedEntity = qobject_cast<QgsChunkedEntity *>( entity ) )
351 chunkedEntity->setPickingEnabled(
false );
356void Qgs3DMapScene::onLayerEntityPickedObject( Qt3DRender::QPickEvent *pickEvent,
QgsFeatureId fid )
358 QgsMapLayer *layer = mLayerEntities.key( qobject_cast<QgsChunkedEntity *>( sender() ) );
368 pickHandler->handlePickOnVectorLayer( vlayer, fid, pickEvent->worldIntersection(), pickEvent );
374 Qt3DRender::QCamera *camera = mCameraController->
camera();
375 float fov = camera->fieldOfView();
376 QRect rect = mCameraController->
viewport();
377 float screenSizePx = std::max( rect.width(), rect.height() );
381 float frustumWidthAtDistance = 2 * distance * tan( fov / 2 );
382 float err = frustumWidthAtDistance * epsilon / screenSizePx;
388 Qt3DRender::QCamera *camera = cameraController->
camera();
389 QgsChunkedEntity::SceneState state;
390 state.cameraFov = camera->fieldOfView();
391 state.cameraPos = camera->position();
392 QRect rect = cameraController->
viewport();
393 state.screenSizePx = std::max( rect.width(), rect.height() );
394 state.viewProjectionMatrix = camera->projectionMatrix() * camera->viewMatrix();
398void Qgs3DMapScene::onCameraChanged()
400 if ( mMap.
projectionType() == Qt3DRender::QCameraLens::OrthographicProjection )
402 QRect viewportRect( QPoint( 0, 0 ), mEngine->
size() );
403 const float viewWidthFromCenter = mCameraController->
distance();
404 const float viewHeightFromCenter = viewportRect.height() * viewWidthFromCenter / viewportRect.width();
405 mEngine->
camera()->lens()->setOrthographicProjection( -viewWidthFromCenter, viewWidthFromCenter, -viewHeightFromCenter, viewHeightFromCenter, mEngine->
camera()->nearPlane(), mEngine->
camera()->farPlane() );
409 bool changedCameraPlanes = updateCameraNearFarPlanes();
411 if ( changedCameraPlanes )
416 updateCameraNearFarPlanes();
419 onShadowSettingsChanged();
427 QVector<Qt3DCore::QComponent *> toBeRemovedComponents;
428 for ( Qt3DCore::QComponent *component : entity->components() )
430 Qt3DRender::QLayer *layer = qobject_cast<Qt3DRender::QLayer *>( component );
431 if ( layer !=
nullptr )
432 toBeRemovedComponents.push_back( layer );
434 for ( Qt3DCore::QComponent *component : toBeRemovedComponents )
435 entity->removeComponent( component );
436 for ( Qt3DCore::QEntity *obj : entity->findChildren<Qt3DCore::QEntity *>() )
438 if ( obj !=
nullptr )
445 for ( Qt3DRender::QLayer *layer : layers )
446 entity->addComponent( layer );
447 for ( Qt3DCore::QEntity *child : entity->findChildren<Qt3DCore::QEntity *>() )
449 if ( child !=
nullptr )
454void Qgs3DMapScene::updateScene()
456 QgsEventTracing::addEvent( QgsEventTracing::Instant, QStringLiteral(
"3D" ), QStringLiteral(
"Update Scene" ) );
457 for ( QgsChunkedEntity *entity : std::as_const( mChunkEntities ) )
459 if ( entity->isEnabled() )
460 entity->update(
_sceneState( mCameraController ) );
465static void _updateNearFarPlane(
const QList<QgsChunkNode *> &activeNodes,
const QMatrix4x4 &viewMatrix,
float &fnear,
float &ffar )
467 for ( QgsChunkNode *node : activeNodes )
472 for (
int i = 0; i < 8; ++i )
474 QVector4D p( ( ( i >> 0 ) & 1 ) ? bbox.
xMin : bbox.
xMax,
475 ( ( i >> 1 ) & 1 ) ? bbox.
yMin : bbox.
yMax,
476 ( ( i >> 2 ) & 1 ) ? bbox.
zMin : bbox.
zMax, 1 );
478 QVector4D pc = viewMatrix * p;
482 fnear = std::min( fnear, dst );
483 ffar = std::max( ffar, dst );
488bool Qgs3DMapScene::updateCameraNearFarPlanes()
503 QMatrix4x4 viewMatrix = camera->viewMatrix();
506 QList<QgsChunkNode *> activeNodes;
508 activeNodes = mTerrain->activeNodes();
513 if ( mTerrain && activeNodes.isEmpty() )
514 activeNodes << mTerrain->rootNode();
516 _updateNearFarPlane( activeNodes, viewMatrix, fnear, ffar );
520 for ( QgsChunkedEntity *e : std::as_const( mChunkEntities ) )
524 QList<QgsChunkNode *> activeEntityNodes = e->activeNodes();
525 if ( activeEntityNodes.empty() )
526 activeEntityNodes << e->rootNode();
527 _updateNearFarPlane( activeEntityNodes, viewMatrix, fnear, ffar );
536 std::swap( fnear, ffar );
538 if ( fnear == 1e9 && ffar == 0 )
542 qWarning() <<
"oops... this should not happen! couldn't determine near/far plane. defaulting to 1...1e9";
548 float newFar = ffar * 2;
549 float newNear = fnear / 2;
552 camera->setFarPlane( newFar );
553 camera->setNearPlane( newNear );
560void Qgs3DMapScene::onFrameTriggered(
float dt )
564 for ( QgsChunkedEntity *entity : std::as_const( mChunkEntities ) )
566 if ( entity->isEnabled() && entity->needsUpdate() )
569 entity->update(
_sceneState( mCameraController ) );
576 static int frameCount = 0;
577 static float accumulatedTime = 0.0f;
587 accumulatedTime += dt;
588 if ( accumulatedTime >= 0.2f )
590 float fps = ( float )frameCount / accumulatedTime;
592 accumulatedTime = 0.0f;
597void Qgs3DMapScene::createTerrain()
601 mChunkEntities.removeOne( mTerrain );
603 mTerrain->deleteLater();
607 if ( !mTerrainUpdateScheduled )
610 QTimer::singleShot( 0,
this, &Qgs3DMapScene::createTerrainDeferred );
611 mTerrainUpdateScheduled =
true;
620void Qgs3DMapScene::createTerrainDeferred()
628 mMap.
terrainGenerator()->setupQuadtree( rootBbox, rootError, maxZoomLevel );
630 mTerrain =
new QgsTerrainEntity( mMap );
631 mTerrain->setParent(
this );
636 mChunkEntities << mTerrain;
648 const QList<QgsMapLayer *> layers = mMap.
layers();
652 removeLayerEntity( layer );
655 addLayerEntity( layer );
660 mTerrainUpdateScheduled =
false;
663void Qgs3DMapScene::onBackgroundColorChanged()
668void Qgs3DMapScene::updateLights()
670 for ( Qt3DCore::QEntity *entity : std::as_const( mLightEntities ) )
671 entity->deleteLater();
672 mLightEntities.clear();
674 const QList< QgsLightSource * > newLights = mMap.
lightSources();
677 mLightEntities.append( source->createEntity( mMap,
this ) );
680 onShadowSettingsChanged();
683void Qgs3DMapScene::updateCameraLens()
690void Qgs3DMapScene::onRenderersChanged()
693 qDeleteAll( mRenderersEntities );
694 mRenderersEntities.clear();
697 const QList<QgsAbstract3DRenderer *> renderers = mMap.
renderers();
700 Qt3DCore::QEntity *newEntity = renderer->createEntity( mMap );
703 newEntity->setParent(
this );
704 finalizeNewEntity( newEntity );
705 mRenderersEntities[renderer] = newEntity;
710void Qgs3DMapScene::onLayerRenderer3DChanged()
712 QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
716 removeLayerEntity( layer );
719 addLayerEntity( layer );
722void Qgs3DMapScene::onLayersChanged()
724 QSet<QgsMapLayer *> layersBefore = qgis::listToSet( mLayerEntities.keys() );
725 QList<QgsMapLayer *> layersAdded;
726 const QList<QgsMapLayer *> layers = mMap.
layers();
729 if ( !layersBefore.contains( layer ) )
731 layersAdded << layer;
735 layersBefore.remove( layer );
740 for (
QgsMapLayer *layer : std::as_const( layersBefore ) )
742 removeLayerEntity( layer );
745 for (
QgsMapLayer *layer : std::as_const( layersAdded ) )
747 addLayerEntity( layer );
753 for (
auto layer : mLayerEntities.keys() )
757 removeLayerEntity( layer );
758 addLayerEntity( layer );
763void Qgs3DMapScene::addLayerEntity(
QgsMapLayer *layer )
765 bool needsSceneUpdate =
false;
774 ( renderer->
type() == QLatin1String(
"vector" ) || renderer->
type() == QLatin1String(
"rulebased" ) ) )
777 if ( renderer->
type() == QLatin1String(
"vector" ) )
785 mModelVectorLayers.append( layer );
789 else if ( renderer->
type() == QLatin1String(
"rulebased" ) )
792 for (
auto rule : rules )
797 mModelVectorLayers.append( layer );
820 Qt3DCore::QEntity *newEntity = renderer->
createEntity( mMap );
823 newEntity->setParent(
this );
824 mLayerEntities.insert( layer, newEntity );
826 finalizeNewEntity( newEntity );
828 if ( QgsChunkedEntity *chunkedNewEntity = qobject_cast<QgsChunkedEntity *>( newEntity ) )
830 mChunkEntities.append( chunkedNewEntity );
831 needsSceneUpdate =
true;
833 chunkedNewEntity->setPickingEnabled( !mPickHandlers.isEmpty() );
834 connect( chunkedNewEntity, &QgsChunkedEntity::pickedObject,
this, &Qgs3DMapScene::onLayerEntityPickedObject );
836 connect( chunkedNewEntity, &QgsChunkedEntity::newEntityCreated,
this, [
this]( Qt3DCore::QEntity * entity )
838 finalizeNewEntity( entity );
846 if ( needsSceneUpdate )
871void Qgs3DMapScene::removeLayerEntity(
QgsMapLayer *layer )
873 Qt3DCore::QEntity *entity = mLayerEntities.take( layer );
875 if ( QgsChunkedEntity *chunkedEntity = qobject_cast<QgsChunkedEntity *>( entity ) )
877 mChunkEntities.removeOne( chunkedEntity );
881 entity->deleteLater();
890 mModelVectorLayers.removeAll( layer );
906void Qgs3DMapScene::finalizeNewEntity( Qt3DCore::QEntity *newEntity )
910 for ( QgsLineMaterial *lm : newEntity->findChildren<QgsLineMaterial *>() )
914 lm->setViewportSize( mCameraController->
viewport().size() );
924 bm->setViewportSize( mCameraController->
viewport().size() );
927 bm->setViewportSize( mCameraController->
viewport().size() );
933 for ( Qt3DRender::QMaterial *material : newEntity->findChildren<Qt3DRender::QMaterial *>() )
936 if ( Qt3DExtras::QDiffuseSpecularMaterial *ph = qobject_cast<Qt3DExtras::QDiffuseSpecularMaterial *>( material ) )
938 if ( ph->diffuse().value<QColor>().alphaF() != 1.0f )
940 Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( ph->parent() );
941 if ( entity && !entity->components().contains( transparentLayer ) )
943 entity->addComponent( transparentLayer );
950 Qt3DRender::QEffect *effect = material->effect();
953 for (
const auto *parameter : effect->parameters() )
955 if ( parameter->name() ==
"opacity" && parameter->value() != 1.0f )
957 Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( material->parent() );
958 if ( entity && !entity->components().contains( transparentLayer ) )
960 entity->addComponent( transparentLayer );
970int Qgs3DMapScene::maximumTextureSize()
const
972 QSurface *surface = mEngine->
surface();
973 QOpenGLContext context;
975 bool success = context.makeCurrent( surface );
979 QOpenGLFunctions openglFunctions = QOpenGLFunctions( &context );
982 openglFunctions.initializeOpenGLFunctions();
983 openglFunctions.glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
993void Qgs3DMapScene::addCameraViewCenterEntity( Qt3DRender::QCamera *camera )
995 mEntityCameraViewCenter =
new Qt3DCore::QEntity;
997 Qt3DCore::QTransform *trCameraViewCenter =
new Qt3DCore::QTransform;
998 mEntityCameraViewCenter->addComponent( trCameraViewCenter );
999 connect( camera, &Qt3DRender::QCamera::viewCenterChanged,
this, [trCameraViewCenter, camera]
1001 trCameraViewCenter->setTranslation( camera->viewCenter() );
1004 Qt3DExtras::QPhongMaterial *materialCameraViewCenter =
new Qt3DExtras::QPhongMaterial;
1005 materialCameraViewCenter->setAmbient( Qt::red );
1006 mEntityCameraViewCenter->addComponent( materialCameraViewCenter );
1008 Qt3DExtras::QSphereMesh *rendererCameraViewCenter =
new Qt3DExtras::QSphereMesh;
1009 rendererCameraViewCenter->setRadius( 10 );
1010 mEntityCameraViewCenter->addComponent( rendererCameraViewCenter );
1013 mEntityCameraViewCenter->setParent(
this );
1023 if ( mSceneState == state )
1025 mSceneState = state;
1029void Qgs3DMapScene::updateSceneState()
1031 if ( mTerrainUpdateScheduled )
1037 for ( QgsChunkedEntity *entity : std::as_const( mChunkEntities ) )
1039 if ( entity->isEnabled() && entity->pendingJobsCount() > 0 )
1046 setSceneState(
Ready );
1049void Qgs3DMapScene::onSkyboxSettingsChanged()
1052 if ( mSkybox !=
nullptr )
1054 mSkybox->deleteLater();
1062 QMap<QString, QString> faces;
1068 faces[QStringLiteral(
"posX" )], faces[QStringLiteral(
"posY" )], faces[QStringLiteral(
"posZ" )],
1069 faces[QStringLiteral(
"negX" )], faces[QStringLiteral(
"negY" )], faces[QStringLiteral(
"negZ" )],
1080void Qgs3DMapScene::onShadowSettingsChanged()
1084 const QList< QgsLightSource * > lightSources = mMap.
lightSources();
1085 QList< QgsDirectionalLightSettings * > directionalLightSources;
1090 directionalLightSources << qgis::down_cast< QgsDirectionalLightSettings * >( source );
1096 if ( shadowSettings.
renderShadows() && selectedLight >= 0 && selectedLight < directionalLightSources.count() )
1108void Qgs3DMapScene::onAmbientOcclusionSettingsChanged()
1118void Qgs3DMapScene::onDebugShadowMapSettingsChanged()
1124void Qgs3DMapScene::onDebugDepthMapSettingsChanged()
1130void Qgs3DMapScene::onDebugOverlayEnabledChanged()
1136void Qgs3DMapScene::onEyeDomeShadingSettingsChanged()
1146void Qgs3DMapScene::onCameraMovementSpeedChanged()
1151void Qgs3DMapScene::onCameraNavigationModeChanged()
1158 QVector<QString> notParsedLayers;
1168 for (
auto it = mLayerEntities.constBegin(); it != mLayerEntities.constEnd(); ++it )
1171 Qt3DCore::QEntity *rootEntity = it.value();
1173 switch ( layerType )
1177 notParsedLayers.push_back( layer->
name() );
1186 notParsedLayers.push_back( layer->
name() );
1196 if ( !notParsedLayers.empty() )
1198 QString message = tr(
"The following layers were not exported:" ) +
"\n";
1199 for (
const QString &layerName : notParsedLayers )
1200 message += layerName +
"\n";
1207 QVector<const QgsChunkNode *> chunks;
1208 if ( !mLayerEntities.contains( layer ) )
return chunks;
1209 if ( QgsChunkedEntity *
c = qobject_cast<QgsChunkedEntity *>( mLayerEntities[ layer ] ) )
1211 for ( QgsChunkNode *n :
c->activeNodes() )
1212 chunks.push_back( n );
1222 for (
QgsMapLayer *layer : mLayerEntities.keys() )
1224 Qt3DCore::QEntity *layerEntity = mLayerEntities[ layer ];
1225 QgsChunkedEntity *
c = qobject_cast<QgsChunkedEntity *>( layerEntity );
1228 QgsChunkNode *chunkNode =
c->rootNode();
1229 QgsAABB bbox = chunkNode->bbox();
1238 QgsRectangle terrainExtent = terrainGenerator->extent();
1251 mEntityRotationCenter =
new Qt3DCore::QEntity;
1253 Qt3DCore::QTransform *trCameraViewCenter =
new Qt3DCore::QTransform;
1254 mEntityRotationCenter->addComponent( trCameraViewCenter );
1255 Qt3DExtras::QPhongMaterial *materialCameraViewCenter =
new Qt3DExtras::QPhongMaterial;
1256 materialCameraViewCenter->setAmbient( Qt::blue );
1257 mEntityRotationCenter->addComponent( materialCameraViewCenter );
1258 Qt3DExtras::QSphereMesh *rendererCameraViewCenter =
new Qt3DExtras::QSphereMesh;
1259 rendererCameraViewCenter->setRadius( 10 );
1260 mEntityRotationCenter->addComponent( rendererCameraViewCenter );
1261 mEntityRotationCenter->setEnabled(
true );
1262 mEntityRotationCenter->setParent(
this );
1266 trCameraViewCenter->setTranslation( center );
1277void Qgs3DMapScene::on3DAxisSettingsChanged()
1287 m3DAxis =
new Qgs3DAxis(
static_cast<Qt3DExtras::Qt3DWindow *
>(
engine->window() ),
@ Directional
Directional light source.
void onAxisSettingsChanged()
Force update of the axis and the viewport when a setting has changed.
Manages the various settings the user can choose from when exporting a 3D scene 3.
bool exportNormals() const
Returns whether normals will be exported.
int terrrainResolution() const
Returns the terrain resolution.
QString sceneFolderPath() const
Returns the scene folder path.
float scale() const
Returns the scale of the exported model.
int terrainTextureResolution() const
Returns the terrain texture resolution.
QString sceneName() const
Returns the scene name.
bool smoothEdges() const
Returns whether triangles edges will look smooth.
bool exportTextures() const
Returns whether textures will be exported.
void unregisterPickHandler(Qgs3DMapScenePickHandler *pickHandler)
Unregisters previously registered pick handler. Pick handler is not deleted. Also removes object pick...
QVector< const QgsChunkNode * > getLayerActiveChunkNodes(QgsMapLayer *layer)
Returns the active chunk nodes of layer.
void exportScene(const Qgs3DMapExportSettings &exportSettings)
Exports the scene according to the scene export settings.
void terrainPendingJobsCountChanged()
Emitted when the number of terrain's pending jobs changes.
void viewed2DExtentFrom3DChanged(QVector< QgsPointXY > extent)
Emitted when the viewed 2D extent seen by the 3D camera has changed.
QgsAbstract3DEngine * engine()
Returns the abstract 3D engine.
void fpsCountChanged(float fpsCount)
Emitted when the FPS count changes.
QgsRectangle sceneExtent()
Returns the scene extent in the map's CRS.
void setViewFrom2DExtent(const QgsRectangle &extent)
Resets camera view to show the extent extent (top view)
void registerPickHandler(Qgs3DMapScenePickHandler *pickHandler)
Registers an object that will get results of pick events on 3D entities. Does not take ownership of t...
Qgs3DMapScene(Qgs3DMapSettings &map, QgsAbstract3DEngine *engine)
Constructs a 3D scene based on map settings and Qt 3D renderer configuration.
SceneState
Enumeration of possible states of the 3D scene.
@ Ready
The scene is fully loaded/updated.
@ Updating
The scene is still being loaded/updated.
int totalPendingJobsCount() const
Returns number of pending jobs for all chunked entities.
void updateTemporal()
Updates the temporale entities.
void totalPendingJobsCountChanged()
Emitted when the total number of pending jobs changes.
void fpsCounterEnabledChanged(bool fpsCounterEnabled)
Emitted when the FPS counter is activated or deactivated.
void sceneStateChanged()
Emitted when the scene's state has changed.
int terrainPendingJobsCount() const
Returns number of pending jobs of the terrain entity.
float worldSpaceError(float epsilon, float distance)
Given screen error (in pixels) and distance from camera (in 3D world coordinates),...
void terrainEntityChanged()
Emitted when the current terrain entity is replaced by a new one.
QgsCameraController * cameraController()
Returns camera controller.
QVector< QgsPointXY > viewFrustum2DExtent()
Calculates the 2D extent viewed by the 3D camera as the vertices of the viewed trapezoid.
void viewZoomFull()
Resets camera view to show the whole scene (top view)
void mapTileResolutionChanged()
Emitted when the map tile resoulution has changed.
void terrainVerticalScaleChanged()
Emitted when the vertical scale of the terrain has changed.
bool isDebugOverlayEnabled() const
Returns whether debug overlay is enabled.
Qt::Corner debugDepthMapCorner() const
Returns the corner where the shadow map preview is displayed.
void renderersChanged()
Emitted when the list of map's extra renderers have been modified.
void eyeDomeLightingDistanceChanged()
Emitted when the eye dome lighting distance has changed.
void terrainShadingChanged()
Emitted when terrain shading enabled flag or terrain shading material has changed.
QgsVector3D mapToWorldCoordinates(const QgsVector3D &mapCoords) const
Converts map coordinates to 3D world coordinates (applies offset and turns (x,y,z) into (x,...
double cameraMovementSpeed() const
Returns the camera movement speed.
Qt3DRender::QCameraLens::ProjectionType projectionType() const
Returns the camera lens' projection type.
bool debugDepthMapEnabled() const
Returns whether the shadow map debugging is enabled.
bool isSkyboxEnabled() const
Returns whether the skybox is enabled.
void debugDepthMapSettingsChanged()
Emitted when depth map debugging has changed.
double eyeDomeLightingStrength() const
Returns the eye dome lighting strength value.
void backgroundColorChanged()
Emitted when the background color has changed.
Qt::Corner debugShadowMapCorner() const
Returns the corner where the shadow map preview is displayed.
bool showCameraViewCenter() const
Returns whether to show camera's view center as a sphere (for debugging)
void showCameraRotationCenterChanged()
Emitted when the flag whether camera's rotation center is shown has changed.
void cameraNavigationModeChanged()
Emitted when the camera navigation mode was changed.
void shadowSettingsChanged()
Emitted when shadow rendering settings are changed.
float maxTerrainGroundError() const
Returns maximum ground error of terrain tiles in world units.
void eyeDomeLightingEnabledChanged()
Emitted when the flag whether eye dome lighting is used has changed.
void debugOverlayEnabledChanged(bool debugOverlayEnabled)
Emitted when the debug overaly is enabled or disabled.
void skyboxSettingsChanged()
Emitted when skybox settings are changed.
QgsShadowSettings shadowSettings() const
Returns the current configuration of shadows.
QList< QgsLightSource * > lightSources() const
Returns list of directional light sources defined in the scene.
double debugDepthMapSize() const
Returns the size of the shadow map preview.
QList< QgsAbstract3DRenderer * > renderers() const
Returns list of extra 3D renderers.
void projectionTypeChanged()
Emitted when the camera lens projection type changes.
float fieldOfView() const
Returns the camera lens' field of view.
QgsAmbientOcclusionSettings ambientOcclusionSettings() const
Returns the current configuration of screen space ambient occlusion.
int eyeDomeLightingDistance() const
Returns the eye dome lighting distance value (contributes to the contrast of the image)
void lightSourcesChanged()
Emitted when any of the light source settings in the map changes.
void showLightSourceOriginsChanged()
Emitted when the flag whether light source origins are shown has changed.
QgsTerrainGenerator * terrainGenerator() const
Returns the terrain generator.
QColor backgroundColor() const
Returns background color of the 3D map view.
double debugShadowMapSize() const
Returns the size of the shadow map preview.
QgsVector3D worldToMapCoordinates(const QgsVector3D &worldCoords) const
Converts 3D world coordinates to map coordinates (applies offset and turns (x,y,z) into (x,...
bool showTerrainBoundingBoxes() const
Returns whether to display bounding boxes of terrain tiles (for debugging)
void maxTerrainScreenErrorChanged()
Emitted when the maximum terrain screen error has changed.
int mapTileResolution() const
Returns resolution (in pixels) of the texture of a terrain tile.
bool debugShadowMapEnabled() const
Returns whether the shadow map debugging is enabled.
bool terrainRenderingEnabled() const
Returns whether the 2D terrain surface will be rendered.
void fpsCounterEnabledChanged(bool fpsCounterEnabled)
Emitted when the FPS counter is enabled or disabled.
void axisSettingsChanged()
Emitted when 3d axis rendering settings are changed.
void ambientOcclusionSettingsChanged()
Emitted when ambient occlusion rendering settings are changed.
void layersChanged()
Emitted when the list of map layers for 3d rendering has changed.
void eyeDomeLightingStrengthChanged()
Emitted when the eye dome lighting strength has changed.
QgsSkyboxSettings skyboxSettings() const
Returns the current configuration of the skybox.
void cameraMovementSpeedChanged()
Emitted when the camera movement speed was changed.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used in the 3D scene.
bool eyeDomeLightingEnabled() const
Returns whether eye dome lighting is used.
bool isFpsCounterEnabled() const
Returns whether FPS counter label is enabled.
void fieldOfViewChanged()
Emitted when the camera lens field of view changes.
QList< QgsMapLayer * > layers() const
Returns the list of 3D map layers to be rendered in the scene.
QgsCameraController::NavigationMode cameraNavigationMode() const
Returns the navigation mode used by the camera.
void terrainGeneratorChanged()
Emitted when the terrain generator has changed.
void debugShadowMapSettingsChanged()
Emitted when shadow map debugging has changed.
void showCameraViewCenterChanged()
Emitted when the flag whether camera's view center is shown has changed.
void maxTerrainGroundErrorChanged()
Emitted when the maximum terrain ground error has changed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
QgsVector3D origin() const
Returns coordinates in map CRS at which 3D scene has origin (0,0,0)
bool showCameraRotationCenter() const
Returns whether to show camera's rotation center as a sphere (for debugging)
Entity that handles the exporting of 3D scene.
void setExportTextures(bool exportTextures)
Sets whether the textures will be exported.
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.
void setTerrainResolution(int resolution)
Sets the terrain resolution.
void setTerrainTextureResolution(int resolution)
Sets the terrain texture resolution.
bool parseVectorLayerEntity(Qt3DCore::QEntity *entity, QgsVectorLayer *layer)
Creates necessary export objects from entity if it represents valid vector layer entity Returns false...
void setScale(float scale)
Sets the scale of the exported 3D model.
void setExportNormals(bool exportNormals)
Sets whether the normals will be exported.
void setSmoothEdges(bool smoothEdges)
Sets whether the triangles will look smooth.
static QgsRectangle worldToLayerExtent(const QgsAABB &bbox, const QgsCoordinateReferenceSystem &layerCrs, const QgsVector3D &mapOrigin, const QgsCoordinateReferenceSystem &mapCrs, const QgsCoordinateTransformContext &context)
Converts axis aligned bounding box in 3D world coordinates to extent in map layer CRS.
static int maxZoomLevel(double tile0width, double tileResolution, double maxError)
Calculates the highest needed zoom level for tiles in quad-tree given width of the base tile (zoom le...
static QgsRay3D rayFromScreenPoint(const QPoint &point, const QSize &windowSize, Qt3DRender::QCamera *camera)
Convert from clicked point on the screen to a ray in world coordinates.
virtual QSurface * surface() const =0
Returns the surface of the engine.
QgsShadowRenderingFrameGraph * frameGraph()
Returns the shadow rendering frame graph object used to render the scene.
virtual Qt3DRender::QCamera * camera()=0
Returns pointer to the engine's camera entity.
virtual void setClearColor(const QColor &color)=0
Sets background color of the scene.
virtual void setFrustumCullingEnabled(bool enabled)=0
Sets whether frustum culling is enabled (this should make rendering faster by not rendering entities ...
virtual QSize size() const =0
Returns size of the engine's rendering area in pixels.
virtual Qt3DRender::QRenderSettings * renderSettings()=0
Returns access to the engine's render settings (the frame graph can be accessed from here)
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 Qt3DCore::QEntity * createEntity(const Qgs3DMapSettings &map) const =0
Returns a 3D entity that will be used to show renderer's data in 3D scene.
class containing the configuration of ambient occlusion rendering 3
float radius() const
Returns the radius parameter of the ambient occlusion effect.
bool isEnabled() const
Returns whether ambient occlusion effect is enabled.
float intensity() const
Returns the shading factor of the ambient occlusion effect.
float threshold() const
Returns at what amount of occlusion the effect will kick in.
static QgsSourceCache * sourceCache()
Returns the application's source cache, used for caching embedded and remote source strings as local ...
void setViewport(QRect viewport)
Sets viewport rectangle. Called internally from 3D canvas. Allows conversion of mouse coordinates.
void setCameraNavigationMode(QgsCameraController::NavigationMode navigationMode)
Sets the navigation mode used by the camera controller.
Qt3DRender::QCamera * camera
float distance() const
Returns distance of the camera from the point it is looking at.
void setCamera(Qt3DRender::QCamera *camera)
Assigns camera that should be controlled by this class. Called internally from 3D scene.
void cameraChanged()
Emitted when camera has been updated.
void frameTriggered(float dt)
Called internally from 3D scene when a new frame is generated. Updates camera according to keyboard/m...
void resetView(float distance)
Move camera back to the initial position (looking down towards origin of world's coordinates)
void setViewFromTop(float worldX, float worldY, float distance, float yaw=0)
Sets camera to look down towards given point in world coordinate, in given distance from plane with z...
void setTerrainEntity(QgsTerrainEntity *te)
Connects to object picker attached to terrain entity.
void setCameraMovementSpeed(double movementSpeed)
Sets the camera movement speed.
void cameraRotationCenterChanged(QVector3D position)
Emitted when the camera rotation center changes.
void viewportChanged()
Emitted when viewport rectangle has been updated.
A skybox constructed from a 6 cube faces.
Base class for all map layer types.
QgsAbstract3DRenderer * renderer3D() const
Returns 3D renderer associated with the layer.
void request3DUpdate()
Signal emitted when a layer requires an update in any 3D maps.
QgsCoordinateReferenceSystem crs
void renderer3DChanged()
Signal emitted when 3D renderer associated with the layer has changed.
void rendererChanged()
Signal emitted when renderer is changed.
virtual QgsMapLayerTemporalProperties * temporalProperties()
Returns the layer's temporal properties.
void layerModified()
Emitted when modifications has been done on layer.
void setMaximumTextureSize(int maximumTextureSize)
Sets the maximum texture size supported by the hardware Used to store the GL_MAX_TEXTURE_SIZE value t...
QgsMesh3DSymbol * clone() const override SIP_FACTORY
Returns a new instance of the symbol with the same settings.
3D renderer that renders all mesh triangles of a mesh layer.
void setSymbol(QgsMesh3DSymbol *symbol)
Sets 3D symbol associated with the renderer.
const QgsMesh3DSymbol * symbol() const
Returns 3D symbol associated with the renderer.
void setLayer(QgsMeshLayer *layer)
Sets vector layer associated with the renderer.
Represents a mesh layer supporting display of data on structured or unstructured meshes.
virtual void showMessage(bool blocking=true)=0
display the message to the user and deletes itself
A skybox constructed from a panoramic image.
Shape shape() const
Returns 3D shape for points.
QVariantMap shapeProperties() const
Returns a key-value dictionary of point shape properties.
3D renderer that renders all points from a point cloud layer
void setLayer(QgsPointCloudLayer *layer)
Sets point cloud layer associated with the renderer.
Represents a map layer supporting display of point clouds.
void subsetStringChanged()
Emitted when the layer's subset string has changed.
A class to represent a 2D point.
static QgsProject * instance()
Returns the QgsProject singleton instance.
A representation of a ray in 3D.
QVector3D origin() const
Returns the origin of the ray.
QVector3D direction() const
Returns the direction of the ray see setDirection()
A rectangle specified with double values.
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
void setMinimal() SIP_HOLDGIL
Set a rectangle so that min corner is at max and max corner is at min.
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
QList< QgsRuleBased3DRenderer::Rule * > RuleList
void setupDepthMapDebugging(bool enabled, Qt::Corner corner, double size)
Sets the depth map debugging view port.
Qt3DRender::QLayer * transparentObjectLayer()
Returns a layer object used to indicate that the object is transparent.
void setAmbientOcclusionThreshold(float threshold)
Sets the ambient occlusion threshold.
void setupShadowMapDebugging(bool enabled, Qt::Corner corner, double size)
Sets the shadow map debugging view port.
void setShadowBias(float shadowBias)
Sets the shadow bias value.
void setAmbientOcclusionIntensity(float intensity)
Sets the ambient occlusion intensity.
void setShadowMapResolution(int resolution)
Sets the resolution of the shadow map.
void setupEyeDomeLighting(bool enabled, double strength, int distance)
Sets eye dome lighting shading related settings.
void setAmbientOcclusionRadius(float radius)
Sets the ambient occlusion radius.
void setDebugOverlayEnabled(bool enabled)
Sets whether debug overlay is enabled.
void setAmbientOcclusionEnabled(bool enabled)
Sets whether Screen Space Ambient Occlusion will be enabled.
void setupDirectionalLight(const QgsDirectionalLightSettings &light, float maximumShadowRenderingDistance)
Sets shadow rendering to use a directional light.
void setShadowRenderingEnabled(bool enabled)
Sets whether the shadow rendering is enabled.
class containing the configuration of shadows rendering 3
int selectedDirectionalLight() const
Returns the selected direcctional light used to cast shadows.
bool renderShadows() const
Returns whether shadow rendering is enabled.
int shadowMapResolution() const
Returns the resolution of the shadow map texture used to generate the shadows.
double maximumShadowRenderingDistance() const
Returns the maximum shadow rendering distance accounted for when rendering shadows Objects further aw...
double shadowBias() const
Returns the shadow bias used to correct the numerical imprecision of shadows (for the depth test) Thi...
Contains the configuration of a skybox entity.
QMap< QString, QString > cubeMapFacesPaths() const
Returns a map containing the path of each texture specified by the user.
QgsSkyboxEntity::SkyboxType skyboxType() const
Returns the type of the skybox.
QString panoramicTexturePath() const
Returns the panoramic texture path of a skybox of type "Panormaic skybox".
void remoteSourceFetched(const QString &url)
Emitted when the cache has finished retrieving a 3D model from a remote url.
bool isActive() const
Returns true if the temporal property is active.
virtual QgsRectangle extent() const =0
extent of the terrain in terrain's CRS
virtual float rootChunkError(const Qgs3DMapSettings &map) const
Returns error of the root chunk in world coordinates.
virtual QgsAABB rootChunkBbox(const Qgs3DMapSettings &map) const
Returns bounding box of the root chunk.
double y() const
Returns Y coordinate.
double z() const
Returns Z coordinate.
double x() const
Returns X coordinate.
3D renderer that renders all features of a vector layer with the same 3D symbol.
Represents a vector layer which manages a vector based data sets.
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
QgsMapLayerType
Types of layers that can be added to a map.
@ PointCloudLayer
Point cloud layer. Added in QGIS 3.18.
@ MeshLayer
Mesh layer. Added in QGIS 3.2.
@ VectorLayer
Vector layer.
@ RasterLayer
Raster layer.
@ GroupLayer
Composite group layer. Added in QGIS 3.24.
@ VectorTileLayer
Vector tile layer. Added in QGIS 3.14.
@ AnnotationLayer
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ PluginLayer
Plugin based layer.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
bool qgsFloatNear(float a, float b, float epsilon=4 *FLT_EPSILON)
Compare two floats (but allow some difference)
void addQLayerComponentsToHierarchy(Qt3DCore::QEntity *entity, const QVector< Qt3DRender::QLayer * > &layers)
QgsChunkedEntity::SceneState _sceneState(QgsCameraController *cameraController)
void removeQLayerComponentsFromHierarchy(Qt3DCore::QEntity *entity)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)