36#include <Qt3DExtras/QDiffuseMapMaterial>
37#include <Qt3DExtras/QPhongMaterial>
38#include <Qt3DRender/QAbstractTextureImage>
39#include <Qt3DRender/QCullFace>
40#include <Qt3DRender/QEffect>
41#include <Qt3DRender/QGeometryRenderer>
42#include <Qt3DRender/QTechnique>
43#include <Qt3DRender/QTexture>
48class QgsPolygon3DSymbolHandler :
public QgsFeature3DHandler
51 QgsPolygon3DSymbolHandler(
const QgsPolygon3DSymbol *symbol,
const QgsFeatureIds &selectedIds )
52 : mSymbol( static_cast<QgsPolygon3DSymbol *>( symbol->clone() ) )
53 , mSelectedIds( selectedIds )
56 bool prepare(
const Qgs3DRenderContext &context, QSet<QString> &attributeNames,
const QgsBox3D &chunkExtent )
override;
57 void processFeature(
const QgsFeature &f,
const Qgs3DRenderContext &context )
override;
58 void finalize( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context )
override;
64 std::unique_ptr<QgsTessellator> tessellator;
65 QVector<QgsFeatureId> triangleIndexFids;
66 QVector<uint> triangleIndexStartingIndices;
67 QByteArray materialDataDefined;
70 void processPolygon(
const QgsPolygon *poly,
QgsFeatureId fid,
float offset,
float extrusionHeight,
const Qgs3DRenderContext &context, PolygonData &out );
71 void processMaterialDatadefined( uint verticesCount,
const QgsExpressionContext &context, PolygonData &out );
72 void makeEntity( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context, PolygonData &out,
bool selected );
73 QgsMaterial *material(
const QgsPolygon3DSymbol *symbol,
bool isSelected,
const Qgs3DRenderContext &context )
const;
76 std::unique_ptr<QgsPolygon3DSymbol> mSymbol;
80 PolygonData outNormal;
81 PolygonData outSelected;
83 QgsLineVertexData outEdges;
86 bool mWasClippedToExtent =
false;
90bool QgsPolygon3DSymbolHandler::prepare(
const Qgs3DRenderContext &context, QSet<QString> &attributeNames,
const QgsBox3D &chunkExtent )
92 mChunkOrigin = chunkExtent.
center();
93 mChunkOrigin.
setZ( 0. );
94 mChunkExtent = chunkExtent;
96 outEdges.withAdjacency =
true;
97 outEdges.init( mSymbol->altitudeClamping(), mSymbol->altitudeBinding(), 0, context, mChunkOrigin );
101 auto tessellator = std::make_unique<QgsTessellator>();
102 tessellator->setOrigin( mChunkOrigin );
103 tessellator->setAddNormals(
true );
104 tessellator->setInvertNormals( mSymbol->invertNormals() );
105 tessellator->setBackFacesEnabled( mSymbol->addBackFaces() );
106 tessellator->setOutputZUp(
true );
107 tessellator->setExtrusionFaces( mSymbol->extrusionFaces() );
108 tessellator->setTextureRotation( texturedMaterialSettings ?
static_cast<float>( texturedMaterialSettings->
textureRotation() ) : 0.f );
110 tessellator->setOutputZUp(
true );
112 outNormal.tessellator = std::move( tessellator );
114 tessellator = std::make_unique<QgsTessellator>();
115 tessellator->setOrigin( mChunkOrigin );
116 tessellator->setAddNormals(
true );
117 tessellator->setInvertNormals( mSymbol->invertNormals() );
118 tessellator->setBackFacesEnabled( mSymbol->addBackFaces() );
119 tessellator->setOutputZUp(
true );
120 tessellator->setExtrusionFaces( mSymbol->extrusionFaces() );
121 tessellator->setTextureRotation( texturedMaterialSettings ?
static_cast<float>( texturedMaterialSettings->
textureRotation() ) : 0.f );
123 tessellator->setOutputZUp(
true );
125 outSelected.tessellator = std::move( tessellator );
127 QSet<QString> attrs = mSymbol->dataDefinedProperties().referencedFields( context.
expressionContext() );
128 attributeNames.unite( attrs );
129 attrs = mSymbol->materialSettings()->dataDefinedProperties().referencedFields( context.
expressionContext() );
130 attributeNames.unite( attrs );
136 std::unique_ptr<QgsPolygon> polyClone( poly->
clone() );
138 if ( mSymbol->edgesEnabled() )
147 if ( mWasClippedToExtent )
152 const QVector< QgsPointXY > extentPoints {
153 { mChunkExtent.xMinimum(), mChunkExtent.yMinimum() },
154 { mChunkExtent.xMaximum(), mChunkExtent.yMinimum() },
155 { mChunkExtent.xMaximum(), mChunkExtent.yMaximum() },
156 { mChunkExtent.xMinimum(), mChunkExtent.yMaximum() },
157 { mChunkExtent.xMinimum(), mChunkExtent.yMinimum() }
159 auto extentLinestring = std::make_unique<QgsLineString>( extentPoints );
163 cleanedExteriorRingGeometry = exteriorRingGeometry.
difference(
QgsGeometry( extentLinestring.release() ) );
171 outEdges.addLineString( *line, offset );
176 for (
int i = 0; i < mline->numGeometries(); ++i )
179 outEdges.addLineString( *line, offset );
185 for (
int i = 0; i < polyClone->numInteriorRings(); ++i )
186 outEdges.addLineString( *
static_cast<const QgsLineString *
>( polyClone->interiorRing( i ) ), offset );
188 if ( extrusionHeight != 0.f )
194 outEdges.addLineString( *line, extrusionHeight + offset );
195 outEdges.addVerticalLines( *line, extrusionHeight, offset );
200 for (
int i = 0; i < mline->numGeometries(); ++i )
203 outEdges.addLineString( *line, extrusionHeight + offset );
204 outEdges.addVerticalLines( *line, extrusionHeight, offset );
210 for (
int i = 0; i < polyClone->numInteriorRings(); ++i )
213 outEdges.addLineString( *interior, extrusionHeight + offset );
214 outEdges.addVerticalLines( *interior, extrusionHeight, offset );
221 Q_ASSERT( out.tessellator->dataVerticesCount() % 3 == 0 );
222 const uint startingTriangleIndex =
static_cast<uint
>( out.tessellator->dataVerticesCount() / 3 );
223 out.triangleIndexStartingIndices.append( startingTriangleIndex );
224 out.triangleIndexFids.append( fid );
226 const size_t oldVertexCount = out.tessellator->uniqueVertexCount();
227 out.tessellator->addPolygon( *polyClone, extrusionHeight );
228 if ( !out.tessellator->error().isEmpty() )
233 if ( mSymbol->materialSettings()->dataDefinedProperties().hasActiveProperties() )
235 const uint newUniqueVertices = out.tessellator->uniqueVertexCount() - oldVertexCount;
236 processMaterialDatadefined( newUniqueVertices, context.
expressionContext(), out );
240void QgsPolygon3DSymbolHandler::processMaterialDatadefined( uint verticesCount,
const QgsExpressionContext &context, QgsPolygon3DSymbolHandler::PolygonData &out )
242 const QByteArray bytes = mSymbol->materialSettings()->dataDefinedVertexColorsAsByte( context );
243 out.materialDataDefined.append( bytes.repeated( verticesCount ) );
251 PolygonData &out = mSelectedIds.contains( f.
id() ) ? outSelected : outNormal;
254 mWasClippedToExtent = clipGeometryIfTooLarge( geom );
272 float offset = mSymbol->offset();
273 float extrusionHeight = mSymbol->extrusionHeight();
276 if ( hasDDExtrusion )
281 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
285 for (
int i = 0; i < mpoly->numGeometries(); ++i )
287 const QgsPolygon *poly = mpoly->polygonN( i );
288 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
293 for (
int i = 0; i < gc->numGeometries(); ++i )
299 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
305 for (
int i = 0; i < polySurface->numPatches(); ++i )
307 const QgsPolygon *poly = polySurface->patchN( i );
308 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
312 qWarning() <<
"not a polygon";
317void QgsPolygon3DSymbolHandler::finalize( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context )
320 makeEntity( parent, context, outNormal,
false );
321 makeEntity( parent, context, outSelected,
true );
323 mZMin = std::min( outNormal.tessellator->zMinimum(), outSelected.tessellator->zMinimum() );
324 mZMax = std::max( outNormal.tessellator->zMaximum(), outSelected.tessellator->zMaximum() );
327 if ( mSymbol->edgesEnabled() && !outEdges.indexes.isEmpty() && !mHighlightingEnabled )
329 QgsLineMaterial *mat =
new QgsLineMaterial;
330 mat->setLineColor( mSymbol->edgeColor() );
331 mat->setLineWidth( mSymbol->edgeWidth() );
333 Qt3DCore::QEntity *entity =
new Qt3DCore::QEntity;
334 entity->setObjectName( parent->objectName() +
"_EDGES" );
337 Qt3DRender::QGeometryRenderer *renderer =
new Qt3DRender::QGeometryRenderer;
338 renderer->setPrimitiveType( Qt3DRender::QGeometryRenderer::LineStripAdjacency );
339 renderer->setGeometry( outEdges.createGeometry( entity ) );
340 renderer->setVertexCount( outEdges.indexes.count() );
341 renderer->setPrimitiveRestartEnabled(
true );
342 renderer->setRestartIndexValue( 0 );
345 QgsGeoTransform *tr =
new QgsGeoTransform;
346 tr->setGeoTranslation( mChunkOrigin );
349 entity->addComponent( renderer );
350 entity->addComponent( mat );
351 entity->addComponent( tr );
352 entity->setParent( parent );
357void QgsPolygon3DSymbolHandler::makeEntity( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context, PolygonData &polyData,
bool selected )
359 if ( polyData.tessellator->dataVerticesCount() == 0 )
362 QgsMaterial *mat = material( mSymbol.get(), selected, context );
365 const QByteArray vertexBuffer = polyData.tessellator->vertexBuffer();
366 const QByteArray indexBuffer = polyData.tessellator->indexBuffer();
367 const int vertexCount = polyData.tessellator->uniqueVertexCount();
368 const size_t indexCount = polyData.tessellator->dataVerticesCount();
375 geometry->
setVertexBufferData( vertexBuffer, vertexCount, polyData.triangleIndexFids, polyData.triangleIndexStartingIndices );
378 if ( mSymbol->materialSettings()->dataDefinedProperties().hasActiveProperties() )
379 mSymbol->materialSettings()->applyDataDefinedToGeometry( geometry, vertexCount, polyData.materialDataDefined );
380 Qt3DRender::QGeometryRenderer *renderer =
new Qt3DRender::QGeometryRenderer;
381 renderer->setGeometry( geometry );
384 QgsGeoTransform *tr =
new QgsGeoTransform;
385 tr->setGeoTranslation( mChunkOrigin );
388 Qt3DCore::QEntity *entity =
new Qt3DCore::QEntity;
389 entity->setObjectName( parent->objectName() +
"_CHUNK_MESH" );
390 entity->addComponent( renderer );
391 entity->addComponent( mat );
392 entity->addComponent( tr );
393 entity->setParent( parent );
405 const auto techniques = material->effect()->techniques();
406 for (
auto tit = techniques.constBegin(); tit != techniques.constEnd(); ++tit )
408 auto renderPasses = ( *tit )->renderPasses();
409 for (
auto rpit = renderPasses.begin(); rpit != renderPasses.end(); ++rpit )
411 Qt3DRender::QCullFace *cullFace =
new Qt3DRender::QCullFace;
413 ( *rpit )->addRenderState( cullFace );
425 const bool dataDefined = mSymbol->materialSettings()->dataDefinedProperties().hasActiveProperties();
428 applyCullingMode( symbol->
cullingMode(), material );
436namespace Qgs3DSymbolImpl
440 QgsFeature3DHandler *handlerForPolygon3DSymbol( QgsVectorLayer *layer,
const QgsAbstract3DSymbol *symbol )
442 const QgsPolygon3DSymbol *polygonSymbol =
dynamic_cast<const QgsPolygon3DSymbol *
>( symbol );
443 if ( !polygonSymbol )
Rendering context for preparation of 3D entities.
QColor selectionColor() const
Returns color used for selected features.
QgsExpressionContext & expressionContext()
Gets the expression context.
@ Main3DRenderer
Renderer for normal entities.
static const char * PROP_NAME_3D_RENDERER_FLAG
Qt property name to hold the 3D geometry renderer flag.
CullingMode
Triangle culling mode.
static Qt3DRender::QCullFace::CullingMode qt3DcullingMode(Qgs3DTypes::CullingMode mode)
Converts Qgs3DTypes::CullingMode mode into its Qt3D equivalent.
static void clampAltitudes(QgsLineString *lineString, Qgis::AltitudeClamping altClamp, Qgis::AltitudeBinding altBind, const QgsPoint ¢roid, float offset, const Qgs3DRenderContext &context)
Clamps altitude of vertices of a linestring according to the settings.
@ ExtrusionHeight
Extrusion height (zero means no extrusion).
@ Height
Height (altitude).
Abstract base class for all geometries.
virtual const QgsAbstractGeometry * simplifiedTypeRef() const
Returns a reference to the simplest lossless representation of this geometry, e.g.
virtual QgsAbstractGeometry * segmentize(double tolerance=M_PI/180., SegmentationToleranceType toleranceType=MaximumAngle) const
Returns a version of the geometry without curves.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
virtual QgsMaterial * toMaterial(QgsMaterialSettingsRenderingTechnique technique, const QgsMaterialContext &context) const =0
Creates a new QgsMaterial object representing the material settings.
double valueAsDouble(int key, const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a double.
A 3-dimensional box composed of x, y, z coordinates.
QgsVector3D center() const
Returns the center of the box as a vector.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
A geometry is the spatial representation of a feature.
QgsGeometry difference(const QgsGeometry &geometry, const QgsGeometryParameters ¶meters=QgsGeometryParameters()) const
Returns a geometry representing the points making up this geometry that do not make up other.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
bool convertGeometryCollectionToSubclass(Qgis::GeometryType geomType)
Converts geometry collection to a the desired geometry type subclass (multi-point,...
Line string geometry type, with support for z-dimension and m-values.
Context settings for a material.
void setIsSelected(bool isSelected)
Sets whether the material should represent a selected state.
void setSelectionColor(const QColor &color)
Sets the color for representing materials in a selected state.
void setIsHighlighted(bool isHighlighted)
Sets whether the material should represent a highlighted state.
Base class for all materials used within QGIS 3D views.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
Multi line string geometry collection.
Multi polygon geometry collection.
A Phong shading model with diffuse texture map.
bool requiresTextureCoordinates() const
Returns true if the material requires texture coordinates to be generated during triangulation....
double textureRotation() const
Returns the texture rotation, in degrees.
3D symbol that draws polygon geometries as planar polygons, optionally extruded (with added walls).
QgsAbstractMaterialSettings * materialSettings() const
Returns material settings used for shading of the symbol.
Qgs3DTypes::CullingMode cullingMode() const
Returns front/back culling mode.
QgsPolygon * clone() const override
Clones the geometry by performing a deep copy.
Polyhedral surface geometry type.
A grouped map of multiple QgsProperty objects, each referenced by an integer key value.
bool isActive(int key) const final
Returns true if the collection contains an active property with the specified key.
Qt3DRender::QGeometry subclass that represents polygons tessellated into 3D geometry.
void setVertexBufferData(const QByteArray &vertexBufferData, int vertexCount, const QVector< QgsFeatureId > &triangleIndexFids, const QVector< uint > &triangleIndexStartingIndices)
Initializes vertex buffer (and other members) from data that were already tessellated.
void setIndexBufferData(const QByteArray &indexBufferData, size_t indexCount)
Sets index buffer data.
void setZ(double z)
Sets Z coordinate.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
static Q_INVOKABLE bool isCurvedType(Qgis::WkbType type)
Returns true if the WKB type is a curved type or can contain curved geometries.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
@ Triangles
Triangle based rendering (default).
@ TrianglesDataDefined
Triangle based rendering with possibility of datadefined color.
T qgsgeometry_cast(QgsAbstractGeometry *geom)
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features