32 QgsPointXY topLeftLonLat( -180, 180.0 / M_PI * std::atan( std::sinh( M_PI ) ) );
33 QgsPointXY bottomRightLonLat( 180, 180.0 / M_PI * std::atan( std::sinh( -M_PI ) ) );
36 mXSpan = ( bottomRight.
x() - topLeft.
x() );
50 ds.
uri =
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png";
59 QString uri = QString(
"type=xyz&url=%1&zmin=%2&zmax=%3" ).arg( mDataSource.
uri ).arg( mDataSource.
zMin ).arg( mDataSource.
zMax );
64 void QgsTerrainDownloader::adjustExtentAndResolution(
double mupp,
const QgsRectangle &extentOrig,
QgsRectangle &extent,
int &res )
66 double xMin = floor( extentOrig.
xMinimum() / mupp ) * mupp;
67 double xMax = ceil( extentOrig.
xMaximum() / mupp ) * mupp;
69 double yMin = floor( extentOrig.
yMinimum() / mupp ) * mupp;
70 double yMax = ceil( extentOrig.
yMaximum() / mupp ) * mupp;
73 res = round( ( xMax - xMin ) / mupp );
77 double QgsTerrainDownloader::findBestTileResolution(
double requestedMupp )
80 for ( ; zoom <= 15; ++zoom )
82 double tileMupp = mXSpan / ( 256 * ( 1 << zoom ) );
83 if ( tileMupp <= requestedMupp )
87 if ( zoom > 15 ) zoom = 15;
88 double finalMupp = mXSpan / ( 256 * ( 1 << zoom ) );
93 void QgsTerrainDownloader::tileImageToHeightMap(
const QImage &img, QByteArray &heightMap )
99 const QRgb *rgb =
reinterpret_cast<const QRgb *
>( img.constBits() );
100 int count = img.width() * img.height();
101 heightMap.resize(
sizeof(
float ) * count );
102 float *hData =
reinterpret_cast<float *
>( heightMap.data() );
103 for (
int i = 0; i < count; ++i )
106 if ( qAlpha(
c ) == 255 )
108 float h = qRed(
c ) * 256 + qGreen(
c ) + qBlue(
c ) / 256.f - 32768;
113 *hData++ = std::numeric_limits<float>::quiet_NaN();
121 if ( !mOnlineDtm || !mOnlineDtm->isValid() )
128 if ( destCrs != mOnlineDtm->crs() )
135 double requestedMupp = extentTr.
width() / res;
136 double finalMupp = findBestTileResolution( requestedMupp );
142 adjustExtentAndResolution( finalMupp, extentTr, extent, res );
146 QgsRasterBlock *b = mOnlineDtm->dataProvider()->block( 1, extent, res, res );
147 QImage img = b->
image();
149 if ( !tmpFilenameImg.isEmpty() )
150 img.save( tmpFilenameImg );
154 QByteArray heightMap;
155 tileImageToHeightMap( img, heightMap );
161 if ( !tmpFilenameTif.isEmpty() )
166 if ( !hSrcDS || !hDstDS )
168 QgsDebugMsg(
"failed to create GDAL dataset for heightmap" );
172 CPLErr err = GDALRasterIO( GDALGetRasterBand( hSrcDS.get(), 1 ), GF_Write, 0, 0, res, res, heightMap.data(), res, res, GDT_Float32, 0, 0 );
173 if ( err != CE_None )
175 QgsDebugMsg(
"failed to write heightmap data to GDAL dataset" );
183 QByteArray heightMapOut;
184 heightMapOut.resize( resOrig * resOrig *
sizeof(
float ) );
185 char *data = heightMapOut.data();
189 CPLErr err2 = GDALRasterIO( GDALGetRasterBand( hDstDS.get(), 1 ), GF_Read, 0, 0, resOrig, resOrig, data, resOrig, resOrig, GDT_Float32, 0, 0 );
190 if ( err2 != CE_None )
192 QgsDebugMsg(
"failed to read heightmap data from GDAL dataset" );