QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsvectortilemvtdecoder.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectortilemvtdecoder.cpp
3 --------------------------------------
4 Date : March 2020
5 Copyright : (C) 2020 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
18#include <string>
19
20#include "qgslinestring.h"
21#include "qgslogger.h"
22#include "qgsmultilinestring.h"
23#include "qgsmultipoint.h"
24#include "qgsmultipolygon.h"
25#include "qgspolygon.h"
26#include "qgsvectortileloader.h"
28#include "qgsvectortileutils.h"
29
30#include <QNetworkRequest>
31#include <QPointer>
32
34 : mStructure( structure )
35{}
36
38
40{
41 mLayerNameToIndex.clear();
42
43 QMap<QString, QByteArray>::const_iterator it = rawTileData.data.constBegin();
44 for ( ; it != rawTileData.data.constEnd(); ++it )
45 {
46 QString sourceId = it.key();
47
48 vector_tile::Tile tile;
49 if ( !tile.ParseFromArray( it.value().constData(), it.value().count() ) )
50 return false;
51
52 for ( int layerNum = 0; layerNum < tile.layers_size(); layerNum++ )
53 {
54 const ::vector_tile::Tile_Layer &layer = tile.layers( layerNum );
55 const QString layerName = layer.name().c_str();
56 mLayerNameToIndex[sourceId][layerName] = layerNum;
57 }
58
59 tiles[sourceId] = std::move( tile );
60
61 }
62
63 mTileID = rawTileData.tileGeometryId;
64
65 return true;
66}
67
69{
70 QStringList layerNames;
71 const int layerSize = std::accumulate( tiles.constBegin(), tiles.constEnd(), 0, []( int count, const vector_tile::Tile & tile ) {return count + tile.layers_size();} );
72 layerNames.reserve( layerSize );
73
74 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
75 for ( ; it != tiles.constEnd(); ++it )
76 {
77 for ( int layerNum = 0; layerNum < layerSize; layerNum++ )
78 {
79 const ::vector_tile::Tile_Layer &layer = it.value().layers( layerNum );
80 const QString layerName = layer.name().c_str();
81 layerNames << layerName;
82 }
83 }
84 return layerNames;
85}
86
87QStringList QgsVectorTileMVTDecoder::layerFieldNames( const QString &layerName ) const
88{
89 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
90 for ( ; it != tiles.constEnd(); ++it )
91 {
92 if ( !mLayerNameToIndex[it.key()].contains( layerName ) )
93 continue;
94
95 const ::vector_tile::Tile_Layer &layer = it.value().layers( mLayerNameToIndex[it.key()][layerName] );
96 QStringList fieldNames;
97 const int size = layer.keys_size();
98 fieldNames.reserve( size );
99 for ( int i = 0; i < size; ++i )
100 {
101 const QString fieldName = layer.keys( i ).c_str();
102 fieldNames << fieldName;
103 }
104 return fieldNames;
105 }
106 return QStringList();
107}
108
109QgsVectorTileFeatures QgsVectorTileMVTDecoder::layerFeatures( const QMap<QString, QgsFields> &perLayerFields, const QgsCoordinateTransform &ct, const QSet<QString> *layerSubset ) const
110{
111 QgsVectorTileFeatures features;
112
113 const int numTiles = static_cast<int>( pow( 2, mTileID.zoomLevel() ) ); // assuming we won't ever go over 30 zoom levels
114 const QgsTileMatrix &rootMatrix = mStructure.rootMatrix();
115 const double z0Width = rootMatrix.extent().width();
116 const double z0Height = rootMatrix.extent().height();
117 const double z0xMinimum = rootMatrix.extent().xMinimum();
118 const double z0yMaximum = rootMatrix.extent().yMaximum();
119
120 const double tileDX = z0Width / numTiles;
121 const double tileDY = z0Height / numTiles;
122 const double tileXMin = z0xMinimum + mTileID.column() * tileDX;
123 const double tileYMax = z0yMaximum - mTileID.row() * tileDY;
124
125 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
126 for ( ; it != tiles.constEnd(); ++it )
127 {
128 vector_tile::Tile tile = it.value();
129
130 for ( int layerNum = 0; layerNum < tile.layers_size(); layerNum++ )
131 {
132 const ::vector_tile::Tile_Layer &layer = tile.layers( layerNum );
133
134 const QString layerName = layer.name().c_str();
135 if ( layerSubset && !layerSubset->contains( QString() ) && !layerSubset->contains( layerName ) )
136 continue;
137
138 QVector<QgsFeature> layerFeatures;
139 QgsFields layerFields = perLayerFields[layerName];
140
141 const auto allLayerFields = perLayerFields.find( QString() );
142 if ( allLayerFields != perLayerFields.end() )
143 {
144 // need to add the fields from any "all layer" rules to every layer
145 for ( const QgsField &field : allLayerFields.value() )
146 {
147 if ( layerFields.lookupField( field.name() ) == -1 )
148 {
149 layerFields.append( field );
150 }
151 }
152 }
153
154 // figure out how field indexes in MVT encoding map to field indexes in QgsFields (we may not use all available fields)
155 QHash<int, int> tagKeyIndexToFieldIndex;
156 for ( int i = 0; i < layer.keys_size(); ++i )
157 {
158 const int fieldIndex = layerFields.indexOf( layer.keys( i ).c_str() );
159 if ( fieldIndex != -1 )
160 tagKeyIndexToFieldIndex.insert( i, fieldIndex );
161 }
162
163 // go through features of a layer
164 for ( int featureNum = 0; featureNum < layer.features_size(); featureNum++ )
165 {
166 const ::vector_tile::Tile_Feature &feature = layer.features( featureNum );
167
168 QgsFeatureId fid;
169 {
170 // There is no assigned ID, but some parts of QGIS do not work correctly if all IDs are zero
171 // (e.g. labeling will not register two features with the same FID within a single layer),
172 // so let's generate some pseudo-unique FIDs to keep those bits happy
173 fid = featureNum;
174 fid |= ( layerNum & 0xff ) << 24;
175 fid |= ( static_cast<QgsFeatureId>( mTileID.row() ) & 0xff ) << 32;
176 fid |= ( static_cast<QgsFeatureId>( mTileID.column() ) & 0xff ) << 40;
177 }
178
179 QgsFeature f( layerFields, fid );
180
181 //
182 // parse attributes
183 //
184
185 for ( int tagNum = 0; tagNum + 1 < feature.tags_size(); tagNum += 2 )
186 {
187 const int keyIndex = static_cast<int>( feature.tags( tagNum ) );
188 const int fieldIndex = tagKeyIndexToFieldIndex.value( keyIndex, -1 );
189 if ( fieldIndex == -1 )
190 continue;
191
192 const int valueIndex = static_cast<int>( feature.tags( tagNum + 1 ) );
193 if ( valueIndex >= layer.values_size() )
194 {
195 QgsDebugError( QStringLiteral( "Invalid value index for attribute" ) );
196 continue;
197 }
198 const ::vector_tile::Tile_Value &value = layer.values( valueIndex );
199
200 if ( value.has_string_value() )
201 f.setAttribute( fieldIndex, QString::fromStdString( value.string_value() ) );
202 else if ( value.has_float_value() )
203 f.setAttribute( fieldIndex, static_cast<double>( value.float_value() ) );
204 else if ( value.has_double_value() )
205 f.setAttribute( fieldIndex, value.double_value() );
206 else if ( value.has_int_value() )
207 f.setAttribute( fieldIndex, static_cast<long long>( value.int_value() ) );
208 else if ( value.has_uint_value() )
209 f.setAttribute( fieldIndex, static_cast<long long>( value.uint_value() ) );
210 else if ( value.has_sint_value() )
211 f.setAttribute( fieldIndex, static_cast<long long>( value.sint_value() ) );
212 else if ( value.has_bool_value() )
213 f.setAttribute( fieldIndex, static_cast<bool>( value.bool_value() ) );
214 else
215 {
216 QgsDebugError( QStringLiteral( "Unexpected attribute value" ) );
217 }
218 }
219
220 //
221 // parse geometry
222 //
223
224 const int extent = static_cast<int>( layer.extent() );
225 int cursorx = 0, cursory = 0;
226
227 QVector<QgsPoint *> outputPoints; // for point/multi-point
228 QVector<QgsLineString *> outputLinestrings; // for linestring/multi-linestring
229 QVector<QgsPolygon *> outputPolygons;
230 QVector<QgsPoint> tmpPoints;
231
232 for ( int i = 0; i < feature.geometry_size(); i ++ )
233 {
234 const unsigned g = feature.geometry( i );
235 const unsigned cmdId = g & 0x7;
236 const int cmdCount = static_cast<int>( g >> 3 );
237 if ( cmdId == 1 ) // MoveTo
238 {
239 if ( i + static_cast<int>( cmdCount ) * 2 >= feature.geometry_size() )
240 {
241 QgsDebugError( QStringLiteral( "Malformed geometry: invalid cmdCount" ) );
242 break;
243 }
244
245 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
246 outputPoints.reserve( static_cast<int>( outputPoints.size() ) + cmdCount );
247 else
248 tmpPoints.reserve( static_cast<int>( tmpPoints.size() ) + cmdCount );
249
250 for ( int j = 0; j < cmdCount; j++ )
251 {
252 const int v = static_cast<int>( feature.geometry( i + 1 ) );
253 const int w = static_cast<int>( feature.geometry( i + 2 ) );
254 const int dx = ( ( v >> 1 ) ^ ( -( v & 1 ) ) );
255 const int dy = ( ( w >> 1 ) ^ ( -( w & 1 ) ) );
256 cursorx += dx;
257 cursory += dy;
258 const double px = tileXMin + tileDX * double( cursorx ) / double( extent );
259 const double py = tileYMax - tileDY * double( cursory ) / double( extent );
260
261 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
262 {
263 outputPoints.append( new QgsPoint( px, py ) );
264 }
265 else if ( feature.type() == vector_tile::Tile_GeomType_LINESTRING )
266 {
267 if ( tmpPoints.size() > 0 )
268 {
269 outputLinestrings.append( new QgsLineString( tmpPoints ) );
270 tmpPoints.clear();
271 }
272 tmpPoints.append( QgsPoint( px, py ) );
273 }
274 else if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
275 {
276 tmpPoints.append( QgsPoint( px, py ) );
277 }
278 i += 2;
279 }
280 }
281 else if ( cmdId == 2 ) // LineTo
282 {
283 if ( i + static_cast<int>( cmdCount ) * 2 >= feature.geometry_size() )
284 {
285 QgsDebugError( QStringLiteral( "Malformed geometry: invalid cmdCount" ) );
286 break;
287 }
288 tmpPoints.reserve( tmpPoints.size() + cmdCount );
289 for ( int j = 0; j < cmdCount; j++ )
290 {
291 const int v = static_cast<int>( feature.geometry( i + 1 ) );
292 const int w = static_cast<int>( feature.geometry( i + 2 ) );
293 const int dx = ( v >> 1 ) ^ ( -( v & 1 ) );
294 const int dy = ( w >> 1 ) ^ ( -( w & 1 ) );
295 cursorx += dx;
296 cursory += dy;
297 const double px = tileXMin + tileDX * double( cursorx ) / double( extent );
298 const double py = tileYMax - tileDY * double( cursory ) / double( extent );
299
300 tmpPoints.push_back( QgsPoint( px, py ) );
301 i += 2;
302 }
303 }
304 else if ( cmdId == 7 ) // ClosePath
305 {
306 if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
307 {
308 tmpPoints.append( tmpPoints.first() ); // close the ring
309
310 auto ring = std::make_unique<QgsLineString>( tmpPoints );
311 tmpPoints.clear();
312
313 if ( QgsVectorTileMVTUtils::isExteriorRing( ring.get() ) )
314 {
315 // start a new polygon
316 QgsPolygon *p = new QgsPolygon;
317 p->setExteriorRing( ring.release() );
318 outputPolygons.append( p );
319 }
320 else
321 {
322 // interior ring (hole)
323 if ( outputPolygons.count() != 0 )
324 {
325 outputPolygons[outputPolygons.count() - 1]->addInteriorRing( ring.release() );
326 }
327 else
328 {
329 QgsDebugError( QStringLiteral( "Malformed geometry: first ring of a polygon is interior ring" ) );
330 }
331 }
332 }
333
334 }
335 else
336 {
337 QgsDebugError( QStringLiteral( "Unexpected command ID: %1" ).arg( cmdId ) );
338 }
339 }
340
341 QString geomType;
342 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
343 {
344 geomType = QStringLiteral( "Point" );
345 if ( outputPoints.count() == 1 )
346 f.setGeometry( QgsGeometry( outputPoints.at( 0 ) ) );
347 else
348 {
350 mp->reserve( outputPoints.count() );
351 for ( int k = 0; k < outputPoints.count(); ++k )
352 mp->addGeometry( outputPoints[k] );
353 f.setGeometry( QgsGeometry( mp ) );
354 }
355 }
356 else if ( feature.type() == vector_tile::Tile_GeomType_LINESTRING )
357 {
358 geomType = QStringLiteral( "LineString" );
359
360 // finish the linestring we have started
361 outputLinestrings.append( new QgsLineString( tmpPoints ) );
362
363 if ( outputLinestrings.count() == 1 )
364 f.setGeometry( QgsGeometry( outputLinestrings.at( 0 ) ) );
365 else
366 {
368 mls->reserve( outputLinestrings.size() );
369 for ( int k = 0; k < outputLinestrings.count(); ++k )
370 mls->addGeometry( outputLinestrings[k] );
371 f.setGeometry( QgsGeometry( mls ) );
372 }
373 }
374 else if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
375 {
376 geomType = QStringLiteral( "Polygon" );
377
378 if ( outputPolygons.count() == 1 )
379 f.setGeometry( QgsGeometry( outputPolygons.at( 0 ) ) );
380 else
381 {
383 mpl->reserve( outputPolygons.size() );
384 for ( int k = 0; k < outputPolygons.count(); ++k )
385 mpl->addGeometry( outputPolygons[k] );
386 f.setGeometry( QgsGeometry( mpl ) );
387 }
388 }
389
390 f.setAttribute( QStringLiteral( "_geom_type" ), geomType );
391 f.geometry().transform( ct );
392
393 layerFeatures.append( f );
394 }
395
396 features[layerName] = layerFeatures;
397 }
398 }
399 return features;
400}
Handles coordinate transforms between two coordinate systems.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
Q_INVOKABLE bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
QgsGeometry geometry
Definition qgsfeature.h:69
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:73
Q_INVOKABLE int indexOf(const QString &fieldName) const
Gets the field index from the field name.
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
void reserve(int size)
Attempts to allocate memory for at least size geometries.
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
Line string geometry type, with support for z-dimension and m-values.
Multi line string geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Multi point geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Multi polygon geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
Polygon geometry type.
Definition qgspolygon.h:33
void setExteriorRing(QgsCurve *ring) override
Sets the exterior ring of the polygon.
double xMinimum
double yMaximum
Defines a matrix of tiles for a single zoom level: it is defined by its size (width *.
Definition qgstiles.h:158
QgsRectangle extent() const
Returns extent of the tile matrix.
Definition qgstiles.h:213
QStringList layerFieldNames(const QString &layerName) const
Returns a list of all field names in a tile. It can only be called after a successful decode().
QStringList layers() const
Returns a list of sub-layer names in a tile. It can only be called after a successful decode().
bool decode(const QgsVectorTileRawData &rawTileData)
Tries to decode raw tile data, returns true on success.
QgsVectorTileMVTDecoder(const QgsVectorTileMatrixSet &structure)
Constructor for QgsVectorTileMVTDecoder, using the specified tile structure.
QgsVectorTileFeatures layerFeatures(const QMap< QString, QgsFields > &perLayerFields, const QgsCoordinateTransform &ct, const QSet< QString > *layerSubset=nullptr) const
Returns decoded features grouped by sub-layers.
static bool isExteriorRing(const QgsLineString *lineString)
Returns whether this linear ring forms an exterior ring according to MVT spec (depending on the orien...
Encapsulates properties of a vector tile matrix set, including tile origins and scaling information.
Keeps track of raw tile data from one or more sources that need to be decoded.
QMap< QString, QByteArray > data
Raw tile data by source ID.
QgsTileXYZ tileGeometryId
Tile id associated with the raw tile data.
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugError(str)
Definition qgslogger.h:57
QMap< QString, QVector< QgsFeature > > QgsVectorTileFeatures
Features of a vector tile, grouped by sub-layer names (key of the map).