-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgswcsprovider.cpp
1968 lines (1672 loc) · 71.1 KB
/
qgswcsprovider.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgswcsprovider.cpp - QGIS Data provider for
OGC Web Coverage Service layers
-------------------
begin : 2 July, 2012
copyright : (C) 2012 by Radim Blazek
email : radim dot blazek at gmail.com
Based on qgswmsprovider.cpp written by Brendan Morley.
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgslogger.h"
#include "qgswcsprovider.h"
#include "qgscoordinatetransform.h"
#include "qgsdatasourceuri.h"
#include "qgsrasteridentifyresult.h"
#include "qgsrasterlayer.h"
#include "qgsrectangle.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsnetworkaccessmanager.h"
#include "qgsnetworkreplyparser.h"
#include "qgsmessagelog.h"
#include "qgsexception.h"
#include "qgswcsdataitems.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkProxy>
#include <QUrl>
#include <QEventLoop>
#include <QFile>
#ifdef QGISDEBUG
#include <QDir>
#endif
#include "gdalwarper.h"
#include "ogr_srs_api.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#define ERR(message) QGS_ERROR_MESSAGE(message,"WCS provider")
#define SRVERR(message) QGS_ERROR_MESSAGE(message,"WCS server")
#define QGS_ERROR(message) QgsError(message,"WCS provider")
QString QgsWcsProvider::WCS_KEY = QStringLiteral( "wcs" );
QString QgsWcsProvider::WCS_DESCRIPTION = QStringLiteral( "OGC Web Coverage Service version 1.0/1.1 data provider" );
static QString DEFAULT_LATLON_CRS = QStringLiteral( "CRS:84" );
// TODO: colortable - use common baseclass with gdal, mapserver does not support http://trac.osgeo.org/mapserver/ticket/1671
QgsWcsProvider::QgsWcsProvider( const QString &uri, const ProviderOptions &options )
: QgsRasterDataProvider( uri, options )
, mCachedViewExtent( 0 )
{
QgsDebugMsg( "constructing with uri '" + mHttpUri + "'." );
mValid = false;
mCachedMemFilename = QStringLiteral( "/vsimem/qgis/wcs/%0.dat" ).arg( reinterpret_cast<std::uintptr_t>( this ) );
if ( !parseUri( uri ) ) return;
// GetCapabilities and DescribeCoverage
// TODO(?): do only DescribeCoverage to avoid one request
// We need to get at least server version, which is not set in of URI (if not part of url)
// and probably also rangeSet
QgsDataSourceUri capabilitiesUri;
capabilitiesUri.setEncodedUri( uri );
// remove non relevant params
capabilitiesUri.removeParam( QStringLiteral( "identifier" ) );
capabilitiesUri.removeParam( QStringLiteral( "crs" ) );
capabilitiesUri.removeParam( QStringLiteral( "format" ) );
// TODO: check if successful (add return to capabilities)
mCapabilities.setUri( capabilitiesUri );
// 1.0 get additional coverage info
if ( !mCapabilities.describeCoverage( mIdentifier ) )
{
appendError( ERR( tr( "Cannot describe coverage" ) ) );
return;
}
mCoverageSummary = mCapabilities.coverage( mIdentifier );
if ( !mCoverageSummary.valid )
{
// Should not happen if describeCoverage() did not fail
appendError( ERR( tr( "Coverage not found" ) ) );
return;
}
// It may happen that format is empty (e.g. uri created in python script),
// in that casei select one from available formats
if ( mFormat.isEmpty() )
{
// TIFF is known by GDAL
mFormat = mCoverageSummary.supportedFormat.filter( QStringLiteral( "tif" ), Qt::CaseInsensitive ).value( 0 );
}
if ( mFormat.isEmpty() )
{
// Take the first if TIFF was not found
mFormat = mCoverageSummary.supportedFormat.value( 0 );
}
// We cannot continue without format, it is required
if ( mFormat.isEmpty() ) return;
// It could happen (usually not with current QgsWCSSourceSelect if at least
// one CRS is available) that crs is not set in uri, in that case we
// use the native, if available or WGS84 or the first supported
if ( mCoverageCrs.isEmpty() )
{
QgsDebugMsg( "nativeCrs = " + mCoverageSummary.nativeCrs );
QgsDebugMsg( "supportedCrs = " + mCoverageSummary.supportedCrs.join( "," ) );
if ( !mCoverageSummary.nativeCrs.isEmpty() )
{
setCoverageCrs( mCoverageSummary.nativeCrs );
}
else if ( mCoverageSummary.supportedCrs.contains( QStringLiteral( "EPSG:4326" ), Qt::CaseInsensitive ) )
{
setCoverageCrs( QStringLiteral( "EPSG:4326" ) );
}
else if ( !mCoverageSummary.supportedCrs.isEmpty() )
{
setCoverageCrs( mCoverageSummary.supportedCrs.value( 0 ) );
}
}
QgsDebugMsg( "mCoverageCrs = " + mCoverageCrs );
// It may happen that coverage CRS is not given or it is unknown
// in that case we continue without CRS and user is asked for it
//if ( mCoverageCrs.isEmpty() ) return;
// Native size
mWidth = mCoverageSummary.width;
mHeight = mCoverageSummary.height;
mHasSize = mCoverageSummary.hasSize;
QgsDebugMsg( QStringLiteral( "mWidth = %1 mHeight = %2" ).arg( mWidth ).arg( mHeight ) );
// TODO: Consider if/how to recalculate mWidth, mHeight if non native CRS is used
if ( !calculateExtent() )
{
appendError( ERR( tr( "Cannot calculate extent" ) ) );
return;
}
// Get small piece of coverage to find GDAL data type and number of bands
int bandNo = 0; // All bands
int width;
int height;
QString crs;
QgsRectangle box; // box to use to calc extent
// Prefer native CRS
if ( !mCoverageSummary.nativeCrs.isEmpty() &&
!mCoverageSummary.nativeBoundingBox.isEmpty() &&
mCoverageSummary.supportedCrs.contains( mCoverageSummary.nativeCrs ) &&
mHasSize )
{
box = mCoverageSummary.nativeBoundingBox;
width = mWidth;
height = mHeight;
crs = mCoverageSummary.nativeCrs;
}
else
{
box = mCoverageExtent;
if ( mHasSize )
{
width = mWidth;
height = mHeight;
}
else
{
// just a number to get smaller piece of coverage
width = 1000;
height = 1000;
}
}
double xRes = box.width() / width;
double yRes = box.height() / height;
QgsPointXY p = box.center();
// width and height different to recognize rotation
int requestWidth = 6;
int requestHeight = 3;
// extent to be used for test request
double halfWidth = xRes * ( requestWidth / 2. );
double halfHeight = yRes * ( requestHeight / 2. );
// Using non native CRS (if we don't know which is native) it could easily happen,
// that a small part of bbox in request CRS near margin falls outside
// coverage native bbox and server reports error => take a piece from center
QgsRectangle extent = QgsRectangle( p.x() - halfWidth, p.y() - halfHeight, p.x() + halfWidth, p.y() + halfHeight );
getCache( bandNo, extent, requestWidth, requestHeight, crs );
if ( !mCachedGdalDataset )
{
setError( mCachedError );
appendError( ERR( tr( "Cannot get test dataset." ) ) );
return;
}
mBandCount = GDALGetRasterCount( mCachedGdalDataset.get() );
QgsDebugMsg( QStringLiteral( "mBandCount = %1" ).arg( mBandCount ) );
// Check for server particularities (bbox, rotation)
int responseWidth = GDALGetRasterXSize( mCachedGdalDataset.get() );
int responseHeight = GDALGetRasterYSize( mCachedGdalDataset.get() );
QgsDebugMsg( QStringLiteral( "requestWidth = %1 requestHeight = %2 responseWidth = %3 responseHeight = %4)" ).arg( requestWidth ).arg( requestHeight ).arg( responseWidth ).arg( responseHeight ) );
// GeoServer and ArcGIS are using for 1.1 box "pixel" edges
// Mapserver is using pixel centers according to 1.1. specification
if ( ( responseWidth == requestWidth - 1 && responseHeight == requestHeight - 1 ) ||
( responseWidth == requestHeight - 1 && responseHeight == requestWidth - 1 ) )
{
mFixBox = true;
QgsDebugMsg( QStringLiteral( "Test response size is smaller by pixel, using mFixBox" ) );
}
// Geoserver is giving rotated raster for geographic CRS - switched axis,
// Geoserver developers argue that changed axis order applies also to
// returned raster, that is exaggerated IMO but we have to handle that.
if ( ( responseWidth == requestHeight && responseHeight == requestWidth ) ||
( responseWidth == requestHeight - 1 && responseHeight == requestWidth - 1 ) )
{
mFixRotate = true;
QgsDebugMsg( QStringLiteral( "Test response is rotated, using mFixRotate" ) );
}
// Get types
// TODO: we are using the same data types like GDAL (not wider like GDAL provider)
// with expectation to replace 'no data' values by NaN
mSrcGdalDataType.reserve( mBandCount );
mGdalDataType.reserve( mBandCount );
for ( int i = 1; i <= mBandCount; i++ )
{
GDALRasterBandH gdalBand = GDALGetRasterBand( mCachedGdalDataset.get(), i );
GDALDataType myGdalDataType = GDALGetRasterDataType( gdalBand );
QgsDebugMsg( QStringLiteral( "myGdalDataType[%1] = %2" ).arg( i - 1 ).arg( myGdalDataType ) );
mSrcGdalDataType.append( myGdalDataType );
// UMN Mapserver does not automatically set null value, METADATA wcs_rangeset_nullvalue must be used
// http://lists.osgeo.org/pipermail/mapserver-users/2010-April/065328.html
// TODO: This could be shared with GDAL provider
int isValid = false;
double myNoDataValue = GDALGetRasterNoDataValue( gdalBand, &isValid );
if ( isValid )
{
QgsDebugMsg( QStringLiteral( "GDALGetRasterNoDataValue = %1" ).arg( myNoDataValue ) );
myNoDataValue = QgsRaster::representableValue( myNoDataValue, dataTypeFromGdal( myGdalDataType ) );
mSrcNoDataValue.append( myNoDataValue );
mSrcHasNoDataValue.append( true );
mUseSrcNoDataValue.append( true );
}
else
{
mSrcNoDataValue.append( std::numeric_limits<double>::quiet_NaN() );
mSrcHasNoDataValue.append( false );
mUseSrcNoDataValue.append( false );
}
// It may happen that nodata value given by GDAL is wrong and it has to be
// disabled by user, in that case we need another value to be used for nodata
// (for reprojection for example) -> always internaly represent as wider type
// with mInternalNoDataValue in reserve.
// No retyping, no internal values for now
#if 0
int myInternalGdalDataType = myGdalDataType;
double myInternalNoDataValue;
switch ( srcDataType( i ) )
{
case Qgis::Byte:
myInternalNoDataValue = -32768.0;
myInternalGdalDataType = GDT_Int16;
break;
case Qgis::Int16:
myInternalNoDataValue = -2147483648.0;
myInternalGdalDataType = GDT_Int32;
break;
case Qgis::UInt16:
myInternalNoDataValue = -2147483648.0;
myInternalGdalDataType = GDT_Int32;
break;
case Qgis::Int32:
// We believe that such values is no used in real data
myInternalNoDataValue = -2147483648.0;
break;
case Qgis::UInt32:
// We believe that such values is no used in real data
myInternalNoDataValue = 4294967295.0;
break;
default: // Float32, Float64
//myNoDataValue = std::numeric_limits<int>::max();
// NaN should work well
myInternalNoDataValue = std::numeric_limits<double>::quiet_NaN();
}
mGdalDataType.append( myInternalGdalDataType );
mInternalNoDataValue.append( myInternalNoDataValue );
QgsDebugMsg( QStringLiteral( "mInternalNoDataValue[%1] = %2" ).arg( i - 1 ).arg( mInternalNoDataValue[i - 1] ) );
#endif
mGdalDataType.append( myGdalDataType );
#if 0
// TODO: what to do if null values from DescribeCoverage differ?
if ( !mCoverageSummary.nullValues.contains( myNoDataValue ) )
{
QgsDebugMsg( QStringLiteral( "noDataValue %1 is missing in nullValues from CoverageDescription" ).arg( myNoDataValue ) );
}
#endif
QgsDebugMsg( QStringLiteral( "mSrcGdalDataType[%1] = %2" ).arg( i - 1 ).arg( mSrcGdalDataType.at( i - 1 ) ) );
QgsDebugMsg( QStringLiteral( "mGdalDataType[%1] = %2" ).arg( i - 1 ).arg( mGdalDataType.at( i - 1 ) ) );
QgsDebugMsg( QStringLiteral( "mSrcNoDataValue[%1] = %2" ).arg( i - 1 ).arg( mSrcNoDataValue.at( i - 1 ) ) );
// Create and store color table
// TODO: never tested because mapserver (6.0.3) does not support color tables
mColorTables.append( QgsGdalProviderBase::colorTable( mCachedGdalDataset.get(), i ) );
}
clearCache();
// Block size is used for for statistics
// TODO: How to find maximum block size supported by server?
if ( mHasSize )
{
// This is taken from GDAL, how they come to these numbers?
if ( mWidth > 1800 ) mXBlockSize = 1024;
else mXBlockSize = mWidth;
if ( mHeight > 900 ) mYBlockSize = 512;
else mYBlockSize = mHeight;
}
mValid = true;
QgsDebugMsg( QStringLiteral( "Constructed OK, provider valid." ) );
}
QgsWcsProvider::QgsWcsProvider( const QgsWcsProvider &other, const QgsDataProvider::ProviderOptions &providerOptions )
: QgsRasterDataProvider( other.dataSourceUri(), providerOptions )
, mHttpUri( other.mHttpUri )
, mBaseUrl( other.mBaseUrl )
, mIdentifier( other.mIdentifier )
, mTime( other.mTime )
, mFormat( other.mFormat )
, mValid( other.mValid )
, mCapabilities( other.mCapabilities )
, mCoverageSummary( other.mCoverageSummary )
, mSrid( other.mSrid )
, mCoverageExtent( other.mCoverageExtent )
, mWidth( other.mWidth )
, mHeight( other.mHeight )
, mXBlockSize( other.mXBlockSize )
, mYBlockSize( other.mYBlockSize )
, mHasSize( other.mHasSize )
, mBandCount( other.mBandCount )
, mGdalDataType( other.mGdalDataType )
, mSrcGdalDataType( other.mSrcGdalDataType )
, mColorTables( other.mColorTables )
, mExtentForLayer( other.mExtentForLayer )
, mCrsForLayer( other.mCrsForLayer )
, mQueryableForLayer( other.mQueryableForLayer )
, mCoverageCrs( other.mCoverageCrs )
// intentionally omitted:
// - mCachedData
// - mCachedMemFilename
// - mCachedMemFile
// - mCachedGdalDataset
// - mCachedError
// - mCachedViewExtent
// - mCachedViewWidth
// - mCachedViewHeight
, mMaxWidth( other.mMaxWidth )
, mMaxHeight( other.mMaxHeight )
// intentionally omitted:
// - mErrorCaption
// - mError
// - mErrorFormat
, mCoordinateTransform( other.mCoordinateTransform )
, mExtentDirty( other.mExtentDirty )
, mGetFeatureInfoUrlBase( other.mGetFeatureInfoUrlBase )
, mServiceMetadataURL( other.mServiceMetadataURL )
, mAuth( other.mAuth )
, mIgnoreGetCoverageUrl( other.mIgnoreGetCoverageUrl )
, mIgnoreAxisOrientation( other.mIgnoreAxisOrientation )
, mInvertAxisOrientation( other.mInvertAxisOrientation )
, mCrs( other.mCrs )
, mFixBox( other.mFixBox )
, mFixRotate( other.mFixRotate )
, mCacheLoadControl( other.mCacheLoadControl )
{
mCachedMemFilename = QStringLiteral( "/vsimem/qgis/wcs/%0.dat" ).arg( reinterpret_cast<std::uintptr_t>( this ) );
}
bool QgsWcsProvider::parseUri( const QString &uriString )
{
QgsDebugMsg( "uriString = " + uriString );
QgsDataSourceUri uri;
uri.setEncodedUri( uriString );
mMaxWidth = 0;
mMaxHeight = 0;
mHttpUri = uri.param( QStringLiteral( "url" ) );
mBaseUrl = prepareUri( mHttpUri );
QgsDebugMsg( "mBaseUrl = " + mBaseUrl );
mIgnoreGetCoverageUrl = uri.hasParam( QStringLiteral( "IgnoreGetMapUrl" ) );
mIgnoreAxisOrientation = uri.hasParam( QStringLiteral( "IgnoreAxisOrientation" ) ); // must be before parsing!
mInvertAxisOrientation = uri.hasParam( QStringLiteral( "InvertAxisOrientation" ) ); // must be before parsing!
mAuth.mUserName = uri.param( QStringLiteral( "username" ) );
QgsDebugMsg( "set username to " + mAuth.mUserName );
mAuth.mPassword = uri.param( QStringLiteral( "password" ) );
QgsDebugMsg( "set password to " + mAuth.mPassword );
if ( uri.hasParam( QStringLiteral( "authcfg" ) ) )
{
mAuth.mAuthCfg = uri.param( QStringLiteral( "authcfg" ) );
}
QgsDebugMsg( "set authcfg to " + mAuth.mAuthCfg );
mIdentifier = uri.param( QStringLiteral( "identifier" ) );
mTime = uri.param( QStringLiteral( "time" ) );
setFormat( uri.param( QStringLiteral( "format" ) ) );
if ( !uri.param( QStringLiteral( "crs" ) ).isEmpty() )
{
setCoverageCrs( uri.param( QStringLiteral( "crs" ) ) );
}
QString cache = uri.param( QStringLiteral( "cache" ) );
if ( !cache.isEmpty() )
{
mCacheLoadControl = QgsNetworkAccessManager::cacheLoadControlFromName( cache );
}
QgsDebugMsg( QStringLiteral( "mCacheLoadControl = %1" ).arg( mCacheLoadControl ) );
return true;
}
QString QgsWcsProvider::prepareUri( QString uri ) const
{
if ( !uri.contains( '?' ) )
{
uri.append( '?' );
}
else if ( uri.right( 1 ) != QLatin1String( "?" ) && uri.right( 1 ) != QLatin1String( "&" ) )
{
uri.append( '&' );
}
return uri;
}
QgsWcsProvider::~QgsWcsProvider()
{
QgsDebugMsg( QStringLiteral( "deconstructing." ) );
// Dispose of any cached image as created by draw()
clearCache();
}
QgsWcsProvider *QgsWcsProvider::clone() const
{
QgsDataProvider::ProviderOptions providerOptions;
providerOptions.transformContext = transformContext();
QgsWcsProvider *provider = new QgsWcsProvider( *this, providerOptions );
provider->copyBaseSettings( *this );
return provider;
}
QString QgsWcsProvider::baseUrl() const
{
return mBaseUrl;
}
QString QgsWcsProvider::format() const
{
return mFormat;
}
void QgsWcsProvider::setFormat( QString const &format )
{
QgsDebugMsg( "Setting format to " + format + '.' );
mFormat = format;
}
void QgsWcsProvider::setCoverageCrs( QString const &crs )
{
QgsDebugMsg( "Setting coverage CRS to " + crs + '.' );
if ( crs != mCoverageCrs && !crs.isEmpty() )
{
// delete old coordinate transform as it is no longer valid
mCoordinateTransform = QgsCoordinateTransform();
mExtentDirty = true;
mCoverageCrs = crs;
mCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mCoverageCrs );
}
}
void QgsWcsProvider::setQueryItem( QUrl &url, const QString &item, const QString &value ) const
{
url.removeQueryItem( item );
url.addQueryItem( item, value );
}
bool QgsWcsProvider::readBlock( int bandNo, QgsRectangle const &viewExtent, int pixelWidth, int pixelHeight, void *block, QgsRasterBlockFeedback *feedback )
{
// TODO: set block to null values, move that to function and call only if fails
memset( block, 0, pixelWidth * pixelHeight * QgsRasterBlock::typeSize( dataType( bandNo ) ) );
// Requested extent must at least partially overlap coverage extent, otherwise
// server gives error. QGIS usually does not request blocks outside raster extent
// (higher level checks) but it is better to do check here as well
if ( !viewExtent.intersects( mCoverageExtent ) )
{
return false;
}
// Can we reuse the previously cached coverage?
if ( !mCachedGdalDataset ||
mCachedViewExtent != viewExtent ||
mCachedViewWidth != pixelWidth ||
mCachedViewHeight != pixelHeight )
{
getCache( bandNo, viewExtent, pixelWidth, pixelHeight, QString(), feedback );
}
if ( mCachedGdalDataset )
{
// It may happen (Geoserver) that if requested BBOX is larger than coverage
// extent, the returned data cover intersection of requested BBOX and coverage
// extent scaled to requested WIDTH/HEIGHT => check extent
// Unfortunately if the received raster does not have a CRS, the extent is the raster size
// and in that case it cannot be used to verify extent
QgsCoordinateReferenceSystem cacheCrs;
if ( !cacheCrs.createFromWkt( GDALGetProjectionRef( mCachedGdalDataset.get() ) ) &&
!cacheCrs.createFromWkt( GDALGetGCPProjection( mCachedGdalDataset.get() ) ) )
{
QgsDebugMsg( QStringLiteral( "Cached does not have CRS" ) );
}
QgsDebugMsg( "Cache CRS: " + cacheCrs.userFriendlyIdentifier() );
QgsRectangle cacheExtent = QgsGdalProviderBase::extent( mCachedGdalDataset.get() );
QgsDebugMsg( "viewExtent = " + viewExtent.toString() );
QgsDebugMsg( "cacheExtent = " + cacheExtent.toString() );
// TODO: check also rotated
if ( cacheCrs.isValid() && !mFixRotate )
{
// using qgsDoubleNear is too precise, example accetable difference:
// 179.9999999306699863 x 179.9999999306700431
if ( !qgsDoubleNearSig( cacheExtent.xMinimum(), viewExtent.xMinimum(), 10 ) ||
!qgsDoubleNearSig( cacheExtent.yMinimum(), viewExtent.yMinimum(), 10 ) ||
!qgsDoubleNearSig( cacheExtent.xMaximum(), viewExtent.xMaximum(), 10 ) ||
!qgsDoubleNearSig( cacheExtent.yMaximum(), viewExtent.yMaximum(), 10 ) )
{
QgsDebugMsg( QStringLiteral( "cacheExtent and viewExtent differ" ) );
QgsMessageLog::logMessage( tr( "Received coverage has wrong extent %1 (expected %2)" ).arg( cacheExtent.toString(), viewExtent.toString() ), tr( "WCS" ) );
// We are doing all possible to avoid this situation,
// If it happens, it would be possible to rescale the portion we get
// to only part of the data block, but it is better to left it
// blank, so that the problem may be discovered in its origin.
return false;
}
}
int width = GDALGetRasterXSize( mCachedGdalDataset.get() );
int height = GDALGetRasterYSize( mCachedGdalDataset.get() );
QgsDebugMsg( QStringLiteral( "cached data width = %1 height = %2 (expected %3 x %4)" ).arg( width ).arg( height ).arg( pixelWidth ).arg( pixelHeight ) );
GDALRasterBandH gdalBand = GDALGetRasterBand( mCachedGdalDataset.get(), bandNo );
// TODO: check type?, check band count?
if ( mFixRotate && width == pixelHeight && height == pixelWidth )
{
// Rotate counter clockwise
// If GridOffsets With GeoServer,
QgsDebugMsg( QStringLiteral( "Rotating raster" ) );
int pixelSize = QgsRasterBlock::typeSize( dataType( bandNo ) );
QgsDebugMsg( QStringLiteral( "pixelSize = %1" ).arg( pixelSize ) );
int size = width * height * pixelSize;
void *tmpData = malloc( size );
if ( ! tmpData )
{
QgsDebugMsg( QStringLiteral( "Couldn't allocate memory of %1 bytes" ).arg( size ) );
return false;
}
if ( GDALRasterIO( gdalBand, GF_Read, 0, 0, width, height, tmpData, width, height, ( GDALDataType ) mGdalDataType.at( bandNo - 1 ), 0, 0 ) != CE_None )
{
QgsDebugMsg( QStringLiteral( "Raster IO Error" ) );
}
for ( int i = 0; i < pixelHeight; i++ )
{
for ( int j = 0; j < pixelWidth; j++ )
{
int destIndex = pixelSize * ( i * pixelWidth + j );
int srcIndex = pixelSize * ( j * width + ( width - i - 1 ) );
memcpy( ( char * )block + destIndex, ( char * )tmpData + srcIndex, pixelSize );
}
}
free( tmpData );
}
else if ( width == pixelWidth && height == pixelHeight )
{
if ( GDALRasterIO( gdalBand, GF_Read, 0, 0, pixelWidth, pixelHeight, block, pixelWidth, pixelHeight, ( GDALDataType ) mGdalDataType.at( bandNo - 1 ), 0, 0 ) != CE_None )
{
QgsDebugMsg( QStringLiteral( "Raster IO Error" ) );
}
else
{
QgsDebugMsg( QStringLiteral( "Block read OK" ) );
}
}
else
{
// This should not happen, but it is better to give distorted result + warning
if ( GDALRasterIO( gdalBand, GF_Read, 0, 0, width, height, block, pixelWidth, pixelHeight, ( GDALDataType ) mGdalDataType.at( bandNo - 1 ), 0, 0 ) != CE_None )
{
QgsDebugMsg( QStringLiteral( "Raster IO Error" ) );
}
QgsMessageLog::logMessage( tr( "Received coverage has wrong size %1 x %2 (expected %3 x %4)" ).arg( width ).arg( height ).arg( pixelWidth ).arg( pixelHeight ), tr( "WCS" ) );
}
}
return true;
}
void QgsWcsProvider::getCache( int bandNo, QgsRectangle const &viewExtent, int pixelWidth, int pixelHeight, QString crs, QgsRasterBlockFeedback *feedback ) const
{
Q_UNUSED( bandNo )
// delete cached data
clearCache();
if ( crs.isEmpty() )
{
crs = mCoverageCrs;
}
mCachedViewExtent = viewExtent;
mCachedViewWidth = pixelWidth;
mCachedViewHeight = pixelHeight;
// --------------- BOUNDING BOX --------------------------------
//according to the WCS spec for 1.1, some CRS have inverted axis
// box:
// 1.0.0: minx,miny,maxx,maxy
// 1.1.0, 1.1.2: OGC 07-067r5 (WCS 1.1.2) referes to OGC 06-121r3 which says
// "The number of axes included, and the order of these axes, shall be as specified
// by the referenced CRS." That means inverted for geographic.
bool changeXY = false;
if ( !mIgnoreAxisOrientation && ( mCapabilities.version().startsWith( QLatin1String( "1.1" ) ) ) )
{
//create CRS from string
QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs );
if ( srs.isValid() && srs.hasAxisInverted() )
{
changeXY = true;
}
}
if ( mInvertAxisOrientation ) changeXY = !changeXY;
double xRes = viewExtent.width() / pixelWidth;
double yRes = viewExtent.height() / pixelHeight;
QgsRectangle extent = viewExtent;
// WCS 1.1 grid is using grid points (surrounded by sample spaces) and
// "The spatial extent of a grid coverage extends only as far as the outermost
// grid points contained in the bounding box. It does NOT include any area
// (partial or whole grid cells or sample spaces) beyond those grid points."
// Mapserver and GDAL are using bbox defined by grid points, i.e. shrunk
// by 1 pixel, but Geoserver and ArcGIS are using full bbox including
// the space around edge grid points.
if ( mCapabilities.version().startsWith( QLatin1String( "1.1" ) ) && !mFixBox )
{
// shrink the extent to border cells centers by half cell size
extent = QgsRectangle( viewExtent.xMinimum() + xRes / 2., viewExtent.yMinimum() + yRes / 2., viewExtent.xMaximum() - xRes / 2., viewExtent.yMaximum() - yRes / 2. );
}
// Bounding box in WCS format (Warning: does not work with scientific notation)
QString bbox = QString( changeXY ? "%2,%1,%4,%3" : "%1,%2,%3,%4" )
.arg( qgsDoubleToString( extent.xMinimum() ),
qgsDoubleToString( extent.yMinimum() ),
qgsDoubleToString( extent.xMaximum() ),
qgsDoubleToString( extent.yMaximum() ) );
QUrl url( mIgnoreGetCoverageUrl ? mBaseUrl : mCapabilities.getCoverageUrl() );
// Version 1.0.0, 1.1.0, 1.1.2
setQueryItem( url, QStringLiteral( "SERVICE" ), QStringLiteral( "WCS" ) );
setQueryItem( url, QStringLiteral( "VERSION" ), mCapabilities.version() );
setQueryItem( url, QStringLiteral( "REQUEST" ), QStringLiteral( "GetCoverage" ) );
setQueryItem( url, QStringLiteral( "FORMAT" ), mFormat );
// Version 1.0.0
if ( mCapabilities.version().startsWith( QLatin1String( "1.0" ) ) )
{
setQueryItem( url, QStringLiteral( "COVERAGE" ), mIdentifier );
if ( !mTime.isEmpty() )
{
// It seems that Mmapserver (6.0.3) WCS 1.1 completely ignores
// TemporalDomain. Some code (copy-pasted from 1.0) is commented in
// msWCSDescribeCoverage_CoverageDescription11() and GetCoverage
// TimeSequence param is not supported at all. If a coverage is defined
// with timeposition in mapfile, the result of GetCoverage is empty
// raster (all values 0).
setQueryItem( url, QStringLiteral( "TIME" ), mTime );
}
setQueryItem( url, QStringLiteral( "BBOX" ), bbox );
setQueryItem( url, QStringLiteral( "CRS" ), crs ); // request BBOX CRS
setQueryItem( url, QStringLiteral( "RESPONSE_CRS" ), crs ); // response CRS
setQueryItem( url, QStringLiteral( "WIDTH" ), QString::number( pixelWidth ) );
setQueryItem( url, QStringLiteral( "HEIGHT" ), QString::number( pixelHeight ) );
}
// Version 1.1.0, 1.1.2
if ( mCapabilities.version().startsWith( QLatin1String( "1.1" ) ) )
{
setQueryItem( url, QStringLiteral( "IDENTIFIER" ), mIdentifier );
QString crsUrn = QStringLiteral( "urn:ogc:def:crs:%1::%2" ).arg( crs.split( ':' ).value( 0 ), crs.split( ':' ).value( 1 ) );
bbox += ',' + crsUrn;
if ( !mTime.isEmpty() )
{
setQueryItem( url, QStringLiteral( "TIMESEQUENCE" ), mTime );
}
setQueryItem( url, QStringLiteral( "BOUNDINGBOX" ), bbox );
// Example:
// GridBaseCRS=urn:ogc:def:crs:SG:6.6:32618
// GridType=urn:ogc:def:method:CS:1.1:2dGridIn2dCrs
// GridCS=urn:ogc:def:cs:OGC:0Grid2dSquareCS
// GridOrigin=0,0
// GridOffsets=0.0707,-0.0707,0.1414,0.1414&
setQueryItem( url, QStringLiteral( "GRIDBASECRS" ), crsUrn ); // response CRS
setQueryItem( url, QStringLiteral( "GRIDCS" ), QStringLiteral( "urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS" ) );
setQueryItem( url, QStringLiteral( "GRIDTYPE" ), QStringLiteral( "urn:ogc:def:method:WCS:1.1:2dSimpleGrid" ) );
// GridOrigin is BBOX minx, maxy
// Note: shifting origin to cell center (not really necessary nor making sense)
// does not work with Mapserver 6.0.3
// Mapserver 6.0.3 does not work with origin on yMinimum (lower left)
// Geoserver works OK with yMinimum (lower left)
QString gridOrigin = QString( changeXY ? "%2,%1" : "%1,%2" )
.arg( qgsDoubleToString( extent.xMinimum() ),
qgsDoubleToString( extent.yMaximum() ) );
setQueryItem( url, QStringLiteral( "GRIDORIGIN" ), gridOrigin );
// GridOffsets WCS 1.1:
// GridType urn:ogc:def:method:WCS:1.1:2dSimpleGrid : 2 values
// GridType urn:ogc:def:method:WCS:1.1:2dGridIn2dCrs : 4 values, the center two of these offsets will be zero when the GridCRS is not rotated or skewed in the GridBaseCRS.
// The yOff must be negative because origin is in upper corner
// WCS 1.1.2: BaseX = origin(1) + offsets(1) * GridX
// BaseY = origin(2) + offsets(2) * GridY
// otherwise GeoServer gives mirrored result, however
// Mapserver works OK with both positive and negative
// OTOH, the yOff offset must not be negative with mFixRotate and Geoserver 2.1-SNAPSHOT
// but it must be negative with GeoServer 2.1.3 and mFixRotate. I am not sure
// at this moment 100% -> disabling positive yOff for now - TODO: try other servers
//double yOff = mFixRotate ? yRes : -yRes; // this was working with some servers I think
double yOff = -yRes;
QString gridOffsets = QString( changeXY ? "%2,%1" : "%1,%2" )
//setQueryItem( url, "GRIDTYPE", "urn:ogc:def:method:WCS:1.1:2dGridIn2dCrs" );
//QString gridOffsets = QString( changeXY ? "%2,0,0,%1" : "%1,0,0,%2" )
.arg( qgsDoubleToString( xRes ),
qgsDoubleToString( yOff ) );
setQueryItem( url, QStringLiteral( "GRIDOFFSETS" ), gridOffsets );
}
QgsDebugMsg( QStringLiteral( "GetCoverage: %1" ).arg( url.toString() ) );
// cache some details for if the user wants to do an identifyAsHtml() later
//mGetFeatureInfoUrlBase = mIgnoreGetFeatureInfoUrl ? mBaseUrl : getFeatureInfoUrl();
emit statusChanged( tr( "Getting map via WCS." ) );
QgsWcsDownloadHandler handler( url, mAuth, mCacheLoadControl, mCachedData, mCapabilities.version(), mCachedError, feedback );
handler.blockingDownload();
QgsDebugMsg( QStringLiteral( "%1 bytes received" ).arg( mCachedData.size() ) );
if ( mCachedData.isEmpty() )
{
QgsMessageLog::logMessage( tr( "No data received" ), tr( "WCS" ) );
clearCache();
return;
}
#if 0
QFile myFile( "/tmp/qgiswcscache.dat" );
if ( myFile.open( QIODevice::WriteOnly ) )
{
QDataStream myStream( &myFile );
myStream.writeRawData( mCachedData.data(), mCachedData.size() );
myFile.close();
}
#endif
mCachedMemFile = VSIFileFromMemBuffer( mCachedMemFilename.toUtf8().constData(),
( GByte * )mCachedData.data(),
( vsi_l_offset )mCachedData.size(),
FALSE );
if ( !mCachedMemFile )
{
QgsMessageLog::logMessage( tr( "Cannot create memory file" ), tr( "WCS" ) );
clearCache();
return;
}
QgsDebugMsg( QStringLiteral( "Memory file created" ) );
CPLErrorReset();
mCachedGdalDataset.reset( GDALOpen( mCachedMemFilename.toUtf8().constData(), GA_ReadOnly ) );
if ( !mCachedGdalDataset )
{
QgsMessageLog::logMessage( QString::fromUtf8( CPLGetLastErrorMsg() ), tr( "WCS" ) );
clearCache();
return;
}
QgsDebugMsg( QStringLiteral( "Dataset opened" ) );
}
// For stats only, maybe change QgsRasterDataProvider::bandStatistics() to
// use standard readBlock with extent
bool QgsWcsProvider::readBlock( int bandNo, int xBlock, int yBlock, void *block )
{
QgsDebugMsg( QStringLiteral( "xBlock = %1 yBlock = %2" ).arg( xBlock ).arg( yBlock ) );
if ( !mHasSize )
return false;
double xRes = mCoverageExtent.width() / mWidth;
double yRes = mCoverageExtent.height() / mHeight;
// blocks on edges may run out of extent, that should not be problem (at least for
// stats - there is a check for it)
double xMin = mCoverageExtent.xMinimum() + xRes * xBlock * mXBlockSize;
double xMax = xMin + xRes * mXBlockSize;
double yMax = mCoverageExtent.yMaximum() - yRes * yBlock * mYBlockSize;
double yMin = yMax - yRes * mYBlockSize;
//QgsDebugMsg( QStringLiteral("yMin = %1 yMax = %2").arg(yMin).arg(yMax) );
QgsRectangle extent( xMin, yMin, xMax, yMax );
return readBlock( bandNo, extent, mXBlockSize, mYBlockSize, block, nullptr );
}
// This could be shared with GDAL provider
Qgis::DataType QgsWcsProvider::sourceDataType( int bandNo ) const
{
if ( bandNo < 0 || bandNo > mSrcGdalDataType.size() )
{
return Qgis::UnknownDataType;
}
return dataTypeFromGdal( mSrcGdalDataType[bandNo - 1] );
}
Qgis::DataType QgsWcsProvider::dataType( int bandNo ) const
{
if ( bandNo < 0 || bandNo > mGdalDataType.size() )
{
return Qgis::UnknownDataType;
}
return dataTypeFromGdal( mGdalDataType[bandNo - 1] );
}
int QgsWcsProvider::bandCount() const
{
return mBandCount;
}
// this is only called once when statistics are calculated
// TODO
int QgsWcsProvider::xBlockSize() const
{
return mXBlockSize;
}
int QgsWcsProvider::yBlockSize() const
{
return mYBlockSize;
}
int QgsWcsProvider::xSize() const { return mWidth; }
int QgsWcsProvider::ySize() const { return mHeight; }
void QgsWcsProvider::clearCache() const
{
if ( mCachedGdalDataset )
{
QgsDebugMsg( QStringLiteral( "Close mCachedGdalDataset" ) );
mCachedGdalDataset.reset();
QgsDebugMsg( QStringLiteral( "Closed" ) );
}
if ( mCachedMemFile )
{
QgsDebugMsg( QStringLiteral( "Close mCachedMemFile" ) );
VSIFCloseL( mCachedMemFile );
mCachedMemFile = nullptr;
QgsDebugMsg( QStringLiteral( "Closed" ) );
}
QgsDebugMsg( QStringLiteral( "Clear mCachedData" ) );
mCachedData.clear();
mCachedError.clear();
QgsDebugMsg( QStringLiteral( "Cleared" ) );
}
QList<QgsColorRampShader::ColorRampItem> QgsWcsProvider::colorTable( int bandNumber )const
{
return mColorTables.value( bandNumber - 1 );
}
int QgsWcsProvider::colorInterpretation( int bandNo ) const
{
GDALRasterBandH myGdalBand = GDALGetRasterBand( mCachedGdalDataset.get(), bandNo );
return colorInterpretationFromGdal( GDALGetRasterColorInterpretation( myGdalBand ) );
}
bool QgsWcsProvider::parseServiceExceptionReportDom( QByteArray const &xml, const QString &wcsVersion, QString &errorTitle, QString &errorText )
{
#ifdef QGISDEBUG
//test the content of the QByteArray
QString responsestring( xml );
QgsDebugMsg( "received the following data: " + responsestring );
#endif
// Convert completed document into a Dom
QDomDocument doc;
QString errorMsg;
int errorLine;
int errorColumn;
bool contentSuccess = doc.setContent( xml, false, &errorMsg, &errorLine, &errorColumn );
if ( !contentSuccess )
{
errorTitle = tr( "Dom Exception" );
errorText = tr( "Could not get WCS Service Exception at %1 at line %2 column %3\n\nResponse was:\n\n%4" )
.arg( errorMsg )
.arg( errorLine )
.arg( errorColumn )
.arg( QString( xml ) );
QgsLogger::debug( "Dom Exception: " + errorText );
return false;
}
QDomElement docElem = doc.documentElement();
// TODO: Assert the docElem.tagName() is
// ServiceExceptionReport // 1.0
// ows:ExceptionReport // 1.1
//QString version = docElem.attribute("version");
QDomElement e;
if ( wcsVersion.startsWith( QLatin1String( "1.0" ) ) )
{
e = QgsWcsCapabilities::domElement( docElem, QStringLiteral( "ServiceException" ) );
}
else // 1.1
{
e = QgsWcsCapabilities::domElement( docElem, QStringLiteral( "Exception" ) );
}
parseServiceException( e, wcsVersion, errorTitle, errorText );
QgsDebugMsg( QStringLiteral( "exiting." ) );