QGIS API Documentation 3.99.0-Master (21b3aa880ba)
Loading...
Searching...
No Matches
qgsterraindownloader.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsterraindownloader.cpp
3 --------------------------------------
4 Date : March 2019
5 Copyright : (C) 2019 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 <memory>
19
20#include "qgs3dutils.h"
22#include "qgsgdalutils.h"
23#include "qgslogger.h"
24#include "qgsrasterlayer.h"
25
27{
29
30 // the whole world is projected to a square:
31 // X going from 180 W to 180 E
32 // Y going from ~85 N to ~85 S (=atan(sinh(pi)) ... to get a square)
33 QgsCoordinateTransform ct( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ), QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3857" ) ), transformContext );
35 const QgsPointXY topLeftLonLat( -180, 180.0 / M_PI * std::atan( std::sinh( M_PI ) ) );
36 const QgsPointXY bottomRightLonLat( 180, 180.0 / M_PI * std::atan( std::sinh( -M_PI ) ) );
37 const QgsPointXY topLeft = ct.transform( topLeftLonLat );
38 const QgsPointXY bottomRight = ct.transform( bottomRightLonLat );
39 mXSpan = ( bottomRight.x() - topLeft.x() );
40}
41
43
45{
46 // using terrain tiles stored on AWS and listed within Registry of Open Data on AWS
47 // see https://registry.opendata.aws/terrain-tiles/
48 //
49 // tiles are generated using a variety of sources (SRTM, ETOPO1 and more detailed data for some countries)
50 // for more details and attribution see https://github.com/tilezen/joerd/blob/master/docs/data-sources.md
51
52 DataSource ds;
53 ds.uri = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png";
54 ds.zMin = 0;
55 ds.zMax = 15;
56 return ds;
57}
58
60{
61 mDataSource = ds;
62 const QString uri = QString( "type=xyz&url=%1&zmin=%2&zmax=%3" ).arg( mDataSource.uri ).arg( mDataSource.zMin ).arg( mDataSource.zMax );
63 mOnlineDtm = std::make_unique<QgsRasterLayer>( uri, "terrarium", "wms" );
64}
65
66
67void QgsTerrainDownloader::adjustExtentAndResolution( double mupp, const QgsRectangle &extentOrig, QgsRectangle &extent, int &res )
68{
69 const double xMin = floor( extentOrig.xMinimum() / mupp ) * mupp;
70 const double xMax = ceil( extentOrig.xMaximum() / mupp ) * mupp;
71
72 const double yMin = floor( extentOrig.yMinimum() / mupp ) * mupp;
73 const double yMax = ceil( extentOrig.yMaximum() / mupp ) * mupp;
74
75 extent = QgsRectangle( xMin, yMin, xMax, yMax );
76 res = round( ( xMax - xMin ) / mupp );
77}
78
79
80double QgsTerrainDownloader::findBestTileResolution( double requestedMupp ) const
81{
82 int zoom = 0;
83 for ( ; zoom <= 15; ++zoom )
84 {
85 const double tileMupp = mXSpan / ( 256 * ( 1 << zoom ) );
86 if ( tileMupp <= requestedMupp )
87 break;
88 }
89
90 if ( zoom > 15 )
91 zoom = 15;
92 const double finalMupp = mXSpan / ( 256 * ( 1 << zoom ) );
93 return finalMupp;
94}
95
96
97void QgsTerrainDownloader::tileImageToHeightMap( const QImage &img, QByteArray &heightMap )
98{
99 // for description of the "terrarium" format:
100 // https://github.com/tilezen/joerd/blob/master/docs/formats.md
101
102 // assuming ARGB premultiplied but with alpha 255
103 const QRgb *rgb = reinterpret_cast<const QRgb *>( img.constBits() );
104 const int count = img.width() * img.height();
105 heightMap.resize( sizeof( float ) * count );
106 float *hData = reinterpret_cast<float *>( heightMap.data() );
107 for ( int i = 0; i < count; ++i )
108 {
109 const QRgb c = rgb[i];
110 if ( qAlpha( c ) == 255 )
111 {
112 const float h = qRed( c ) * 256 + qGreen( c ) + qBlue( c ) / 256.f - 32768;
113 *hData++ = h;
114 }
115 else
116 {
117 *hData++ = std::numeric_limits<float>::quiet_NaN();
118 }
119 }
120}
121
122
123QByteArray QgsTerrainDownloader::getHeightMap( const QgsRectangle &extentOrig, int res, const QgsCoordinateReferenceSystem &destCrs, const QgsCoordinateTransformContext &context, QString tmpFilenameImg, QString tmpFilenameTif )
124{
125 if ( !mOnlineDtm || !mOnlineDtm->isValid() )
126 {
127 QgsDebugError( "missing a valid data source" );
128 return QByteArray();
129 }
130
131 QgsRectangle extentTr = Qgs3DUtils::tryReprojectExtent2D( extentOrig, destCrs, mOnlineDtm->crs(), context );
132 const double requestedMupp = extentTr.width() / res;
133 const double finalMupp = findBestTileResolution( requestedMupp );
134
135 // adjust extent to match native resolution of terrain tiles
136
137 QgsRectangle extent;
138 const int resOrig = res;
139 adjustExtentAndResolution( finalMupp, extentTr, extent, res );
140
141 // request tile
142
143 QgsRasterBlock *b = mOnlineDtm->dataProvider()->block( 1, extent, res, res );
144 const QImage img = b->image();
145 delete b;
146 if ( !tmpFilenameImg.isEmpty() )
147 img.save( tmpFilenameImg );
148
149 // convert to height data
150
151 QByteArray heightMap;
152 tileImageToHeightMap( img, heightMap );
153
154 // prepare source/destination datasets for resampling
155
156 const gdal::dataset_unique_ptr hSrcDS( QgsGdalUtils::createSingleBandMemoryDataset( GDT_Float32, extent, res, res, mOnlineDtm->crs() ) );
158 if ( !tmpFilenameTif.isEmpty() )
159 hDstDS = QgsGdalUtils::createSingleBandTiffDataset( tmpFilenameTif, GDT_Float32, extentOrig, resOrig, resOrig, destCrs );
160 else
161 hDstDS = QgsGdalUtils::createSingleBandMemoryDataset( GDT_Float32, extentOrig, resOrig, resOrig, destCrs );
162
163 if ( !hSrcDS || !hDstDS )
164 {
165 QgsDebugError( "failed to create GDAL dataset for heightmap" );
166 return QByteArray();
167 }
168
169 const CPLErr err = GDALRasterIO( GDALGetRasterBand( hSrcDS.get(), 1 ), GF_Write, 0, 0, res, res, heightMap.data(), res, res, GDT_Float32, 0, 0 );
170 if ( err != CE_None )
171 {
172 QgsDebugError( "failed to write heightmap data to GDAL dataset" );
173 return QByteArray();
174 }
175
176 // resample to the desired extent + resolution
177 QgsGdalUtils::resampleSingleBandRaster( hSrcDS.get(), hDstDS.get(), GRA_Bilinear, context.calculateCoordinateOperation( mOnlineDtm->crs(), destCrs ).toUtf8().constData() );
178
179 QByteArray heightMapOut;
180 heightMapOut.resize( resOrig * resOrig * sizeof( float ) );
181 char *data = heightMapOut.data();
182
183 // read the data back
184
185 const CPLErr err2 = GDALRasterIO( GDALGetRasterBand( hDstDS.get(), 1 ), GF_Read, 0, 0, resOrig, resOrig, data, resOrig, resOrig, GDT_Float32, 0, 0 );
186 if ( err2 != CE_None )
187 {
188 QgsDebugError( "failed to read heightmap data from GDAL dataset" );
189 return QByteArray();
190 }
191
192 return heightMapOut;
193}
static QgsRectangle tryReprojectExtent2D(const QgsRectangle &extent, const QgsCoordinateReferenceSystem &crs1, const QgsCoordinateReferenceSystem &crs2, const QgsCoordinateTransformContext &context)
Reprojects extent from crs1 to crs2 coordinate reference system with context context.
Represents a coordinate reference system (CRS).
Contains information about the context in which a coordinate transform is executed.
QString calculateCoordinateOperation(const QgsCoordinateReferenceSystem &source, const QgsCoordinateReferenceSystem &destination) const
Returns the Proj coordinate operation string to use when transforming from the specified source CRS t...
Handles coordinate transforms between two coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
static bool resampleSingleBandRaster(GDALDatasetH hSrcDS, GDALDatasetH hDstDS, GDALResampleAlg resampleAlg, const char *pszCoordinateOperation)
Resamples a single band raster to the destination dataset with different resolution (and possibly wit...
static gdal::dataset_unique_ptr createSingleBandTiffDataset(const QString &filename, GDALDataType dataType, const QgsRectangle &extent, int width, int height, const QgsCoordinateReferenceSystem &crs)
Creates a new single band TIFF dataset with given parameters.
static gdal::dataset_unique_ptr createSingleBandMemoryDataset(GDALDataType dataType, const QgsRectangle &extent, int width, int height, const QgsCoordinateReferenceSystem &crs)
Creates a new single band memory dataset with given parameters.
Represents a 2D point.
Definition qgspointxy.h:60
double x
Definition qgspointxy.h:63
Raster data container.
QImage image() const
Returns an image containing the block data, if the block's data type is color.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum
QgsTerrainDownloader(const QgsCoordinateTransformContext &transformContext)
Constructs a QgsTerrainDownloader object.
static DataSource defaultDataSource()
Returns the data source used by default.
QByteArray getHeightMap(const QgsRectangle &extentOrig, int res, const QgsCoordinateReferenceSystem &destCrs, const QgsCoordinateTransformContext &context=QgsCoordinateTransformContext(), QString tmpFilenameImg=QString(), QString tmpFilenameTif=QString())
For given extent and resolution (number of pixels for width/height) in specified CRS,...
void setDataSource(const DataSource &ds)
Configures data source to be used for download of terrain tiles.
std::unique_ptr< std::remove_pointer< GDALDatasetH >::type, GDALDatasetCloser > dataset_unique_ptr
Scoped GDAL dataset.
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
#define QgsDebugError(str)
Definition qgslogger.h:57
Definition of data source for terrain tiles (assuming "terrarium" data encoding with usual XYZ tiling...
QString uri
HTTP(S) template for XYZ tiles requests (e.g. http://example.com/{z}/{x}/{y}.png).
int zMin
Minimum zoom level (Z) with valid data.
int zMax
Maximum zoom level (Z) with valid data.