Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL Utilities
4 : * Purpose: Command line application to build VRT datasets from raster products
5 : * or content of SHP tile index
6 : * Author: Even Rouault, <even dot rouault at spatialys dot com>
7 : *
8 : ******************************************************************************
9 : * Copyright (c) 2007-2016, Even Rouault <even dot rouault at spatialys dot com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : ****************************************************************************/
13 :
14 : #include "ogr_api.h"
15 : #include "ogr_srs_api.h"
16 :
17 : #include "cpl_port.h"
18 : #include "gdal_utils.h"
19 : #include "gdal_utils_priv.h"
20 : #include "gdalargumentparser.h"
21 :
22 : #include <cassert>
23 : #include <cmath>
24 : #include <cstdio>
25 : #include <cstdlib>
26 : #include <cstring>
27 :
28 : #include <algorithm>
29 : #include <memory>
30 : #include <set>
31 : #include <string>
32 : #include <vector>
33 :
34 : #include "commonutils.h"
35 : #include "cpl_conv.h"
36 : #include "cpl_error.h"
37 : #include "cpl_float.h"
38 : #include "cpl_progress.h"
39 : #include "cpl_string.h"
40 : #include "cpl_vsi.h"
41 : #include "cpl_vsi_virtual.h"
42 : #include "gdal.h"
43 : #include "gdal_vrt.h"
44 : #include "gdal_priv.h"
45 : #include "gdal_proxy.h"
46 : #include "ogr_api.h"
47 : #include "ogr_core.h"
48 : #include "ogr_srs_api.h"
49 : #include "ogr_spatialref.h"
50 : #include "ogrsf_frmts.h"
51 : #include "vrtdataset.h"
52 :
53 : #define GEOTRSFRM_TOPLEFT_X 0
54 : #define GEOTRSFRM_WE_RES 1
55 : #define GEOTRSFRM_ROTATION_PARAM1 2
56 : #define GEOTRSFRM_TOPLEFT_Y 3
57 : #define GEOTRSFRM_ROTATION_PARAM2 4
58 : #define GEOTRSFRM_NS_RES 5
59 :
60 : namespace gdal::GDALBuildVRT
61 : {
62 : typedef enum
63 : {
64 : LOWEST_RESOLUTION,
65 : HIGHEST_RESOLUTION,
66 : AVERAGE_RESOLUTION,
67 : SAME_RESOLUTION,
68 : USER_RESOLUTION,
69 : COMMON_RESOLUTION,
70 : } ResolutionStrategy;
71 :
72 : struct DatasetProperty
73 : {
74 : int isFileOK = FALSE;
75 : int nRasterXSize = 0;
76 : int nRasterYSize = 0;
77 : GDALGeoTransform gt{};
78 : int nBlockXSize = 0;
79 : int nBlockYSize = 0;
80 : std::vector<GDALDataType> aeBandType{};
81 : std::vector<bool> abHasNoData{};
82 : std::vector<double> adfNoDataValues{};
83 : std::vector<bool> abHasOffset{};
84 : std::vector<double> adfOffset{};
85 : std::vector<bool> abHasScale{};
86 : std::vector<bool> abHasMaskBand{};
87 : std::vector<double> adfScale{};
88 : int bHasDatasetMask = 0;
89 : bool bLastBandIsAlpha = false;
90 : int nMaskBlockXSize = 0;
91 : int nMaskBlockYSize = 0;
92 : std::vector<int> anOverviewFactors{};
93 : };
94 :
95 : struct BandProperty
96 : {
97 : GDALColorInterp colorInterpretation = GCI_Undefined;
98 : GDALDataType dataType = GDT_Unknown;
99 : std::unique_ptr<GDALColorTable> colorTable{};
100 : bool bHasNoData = false;
101 : double noDataValue = 0;
102 : bool bHasOffset = false;
103 : double dfOffset = 0;
104 : bool bHasScale = false;
105 : double dfScale = 0;
106 : };
107 : } // namespace gdal::GDALBuildVRT
108 :
109 : using namespace gdal::GDALBuildVRT;
110 :
111 : /************************************************************************/
112 : /* GetSrcDstWin() */
113 : /************************************************************************/
114 :
115 2342 : static int GetSrcDstWin(DatasetProperty *psDP, double we_res, double ns_res,
116 : double minX, double minY, double maxX, double maxY,
117 : int nTargetXSize, int nTargetYSize, double *pdfSrcXOff,
118 : double *pdfSrcYOff, double *pdfSrcXSize,
119 : double *pdfSrcYSize, double *pdfDstXOff,
120 : double *pdfDstYOff, double *pdfDstXSize,
121 : double *pdfDstYSize)
122 : {
123 2342 : if (we_res == 0 || ns_res == 0)
124 : {
125 : // should not happen. to please Coverity
126 0 : return FALSE;
127 : }
128 :
129 : /* Check that the destination bounding box intersects the source bounding
130 : * box */
131 2342 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] +
132 2342 : psDP->nRasterXSize * psDP->gt[GEOTRSFRM_WE_RES] <=
133 : minX)
134 0 : return FALSE;
135 2342 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] >= maxX)
136 1 : return FALSE;
137 2341 : if (psDP->gt[GEOTRSFRM_TOPLEFT_Y] +
138 2341 : psDP->nRasterYSize * psDP->gt[GEOTRSFRM_NS_RES] >=
139 : maxY)
140 0 : return FALSE;
141 2341 : if (psDP->gt[GEOTRSFRM_TOPLEFT_Y] <= minY)
142 0 : return FALSE;
143 :
144 2341 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] < minX)
145 : {
146 3 : *pdfSrcXOff =
147 3 : (minX - psDP->gt[GEOTRSFRM_TOPLEFT_X]) / psDP->gt[GEOTRSFRM_WE_RES];
148 3 : *pdfDstXOff = 0.0;
149 : }
150 : else
151 : {
152 2338 : *pdfSrcXOff = 0.0;
153 2338 : *pdfDstXOff = ((psDP->gt[GEOTRSFRM_TOPLEFT_X] - minX) / we_res);
154 : }
155 2341 : if (maxY < psDP->gt[GEOTRSFRM_TOPLEFT_Y])
156 : {
157 5 : *pdfSrcYOff = (psDP->gt[GEOTRSFRM_TOPLEFT_Y] - maxY) /
158 5 : -psDP->gt[GEOTRSFRM_NS_RES];
159 5 : *pdfDstYOff = 0.0;
160 : }
161 : else
162 : {
163 2336 : *pdfSrcYOff = 0.0;
164 2336 : *pdfDstYOff = ((maxY - psDP->gt[GEOTRSFRM_TOPLEFT_Y]) / -ns_res);
165 : }
166 :
167 2341 : *pdfSrcXSize = psDP->nRasterXSize;
168 2341 : *pdfSrcYSize = psDP->nRasterYSize;
169 2341 : if (*pdfSrcXOff > 0)
170 3 : *pdfSrcXSize -= *pdfSrcXOff;
171 2341 : if (*pdfSrcYOff > 0)
172 5 : *pdfSrcYSize -= *pdfSrcYOff;
173 :
174 2341 : const double dfSrcToDstXSize = psDP->gt[GEOTRSFRM_WE_RES] / we_res;
175 2341 : *pdfDstXSize = *pdfSrcXSize * dfSrcToDstXSize;
176 2341 : const double dfSrcToDstYSize = psDP->gt[GEOTRSFRM_NS_RES] / ns_res;
177 2341 : *pdfDstYSize = *pdfSrcYSize * dfSrcToDstYSize;
178 :
179 2341 : if (*pdfDstXOff + *pdfDstXSize > nTargetXSize)
180 : {
181 7 : *pdfDstXSize = nTargetXSize - *pdfDstXOff;
182 7 : *pdfSrcXSize = *pdfDstXSize / dfSrcToDstXSize;
183 : }
184 :
185 2341 : if (*pdfDstYOff + *pdfDstYSize > nTargetYSize)
186 : {
187 5 : *pdfDstYSize = nTargetYSize - *pdfDstYOff;
188 5 : *pdfSrcYSize = *pdfDstYSize / dfSrcToDstYSize;
189 : }
190 :
191 4682 : return *pdfSrcXSize > 0 && *pdfDstXSize > 0 && *pdfSrcYSize > 0 &&
192 4682 : *pdfDstYSize > 0;
193 : }
194 :
195 : /************************************************************************/
196 : /* VRTBuilder */
197 : /************************************************************************/
198 :
199 : class VRTBuilder
200 : {
201 : /* Input parameters */
202 : bool bStrict = false;
203 : char *pszOutputFilename = nullptr;
204 : int nInputFiles = 0;
205 : char **ppszInputFilenames = nullptr;
206 : int nSrcDSCount = 0;
207 : GDALDatasetH *pahSrcDS = nullptr;
208 : int nTotalBands = 0;
209 : bool bLastBandIsAlpha = false;
210 : bool bExplicitBandList = false;
211 : int nMaxSelectedBandNo = 0;
212 : int nSelectedBands = 0;
213 : int *panSelectedBandList = nullptr;
214 : ResolutionStrategy resolutionStrategy = AVERAGE_RESOLUTION;
215 : int nCountValid = 0;
216 : double we_res = 0;
217 : double ns_res = 0;
218 : int bTargetAlignedPixels = 0;
219 : double minX = 0;
220 : double minY = 0;
221 : double maxX = 0;
222 : double maxY = 0;
223 : int bSeparate = 0;
224 : int bAllowProjectionDifference = 0;
225 : int bAddAlpha = 0;
226 : int bHideNoData = 0;
227 : int nSubdataset = 0;
228 : char *pszSrcNoData = nullptr;
229 : char *pszVRTNoData = nullptr;
230 : char *pszOutputSRS = nullptr;
231 : char *pszResampling = nullptr;
232 : char **papszOpenOptions = nullptr;
233 : bool bUseSrcMaskBand = true;
234 : bool bNoDataFromMask = false;
235 : double dfMaskValueThreshold = 0;
236 : const CPLStringList aosCreateOptions;
237 : std::string osPixelFunction{};
238 : const CPLStringList aosPixelFunctionArgs;
239 : const bool bWriteAbsolutePath;
240 :
241 : /* Internal variables */
242 : char *pszProjectionRef = nullptr;
243 : std::vector<BandProperty> asBandProperties{};
244 : int bFirst = TRUE;
245 : int bHasGeoTransform = 0;
246 : int nRasterXSize = 0;
247 : int nRasterYSize = 0;
248 : std::vector<DatasetProperty> asDatasetProperties{};
249 : int bUserExtent = 0;
250 : int bAllowSrcNoData = TRUE;
251 : double *padfSrcNoData = nullptr;
252 : int nSrcNoDataCount = 0;
253 : int bAllowVRTNoData = TRUE;
254 : double *padfVRTNoData = nullptr;
255 : int nVRTNoDataCount = 0;
256 : int bHasRunBuild = 0;
257 : int bHasDatasetMask = 0;
258 :
259 : std::string AnalyseRaster(GDALDatasetH hDS,
260 : DatasetProperty *psDatasetProperties);
261 :
262 : void CreateVRTSeparate(VRTDataset *poVTDS);
263 : void CreateVRTNonSeparate(VRTDataset *poVRTDS);
264 :
265 : CPL_DISALLOW_COPY_ASSIGN(VRTBuilder)
266 :
267 : public:
268 : VRTBuilder(bool bStrictIn, const char *pszOutputFilename, int nInputFiles,
269 : const char *const *ppszInputFilenames, GDALDatasetH *pahSrcDSIn,
270 : const int *panSelectedBandListIn, int nBandCount,
271 : ResolutionStrategy resolutionStrategy, double we_res,
272 : double ns_res, int bTargetAlignedPixels, double minX,
273 : double minY, double maxX, double maxY, int bSeparate,
274 : int bAllowProjectionDifference, int bAddAlpha, int bHideNoData,
275 : int nSubdataset, const char *pszSrcNoData,
276 : const char *pszVRTNoData, bool bUseSrcMaskBand,
277 : bool bNoDataFromMask, double dfMaskValueThreshold,
278 : const char *pszOutputSRS, const char *pszResampling,
279 : const char *pszPixelFunctionName,
280 : const CPLStringList &aosPixelFunctionArgs,
281 : const char *const *papszOpenOptionsIn,
282 : const CPLStringList &aosCreateOptionsIn,
283 : bool bWriteAbsolutePathIn);
284 :
285 : ~VRTBuilder();
286 :
287 : std::unique_ptr<GDALDataset> Build(GDALProgressFunc pfnProgress,
288 : void *pProgressData);
289 :
290 : std::string m_osProgramName{};
291 : };
292 :
293 : /************************************************************************/
294 : /* VRTBuilder() */
295 : /************************************************************************/
296 :
297 221 : VRTBuilder::VRTBuilder(
298 : bool bStrictIn, const char *pszOutputFilenameIn, int nInputFilesIn,
299 : const char *const *ppszInputFilenamesIn, GDALDatasetH *pahSrcDSIn,
300 : const int *panSelectedBandListIn, int nBandCount,
301 : ResolutionStrategy resolutionStrategyIn, double we_resIn, double ns_resIn,
302 : int bTargetAlignedPixelsIn, double minXIn, double minYIn, double maxXIn,
303 : double maxYIn, int bSeparateIn, int bAllowProjectionDifferenceIn,
304 : int bAddAlphaIn, int bHideNoDataIn, int nSubdatasetIn,
305 : const char *pszSrcNoDataIn, const char *pszVRTNoDataIn,
306 : bool bUseSrcMaskBandIn, bool bNoDataFromMaskIn,
307 : double dfMaskValueThresholdIn, const char *pszOutputSRSIn,
308 : const char *pszResamplingIn, const char *pszPixelFunctionIn,
309 : const CPLStringList &aosPixelFunctionArgsIn,
310 : const char *const *papszOpenOptionsIn,
311 221 : const CPLStringList &aosCreateOptionsIn, bool bWriteAbsolutePathIn)
312 : : bStrict(bStrictIn), aosCreateOptions(aosCreateOptionsIn),
313 : aosPixelFunctionArgs(aosPixelFunctionArgsIn),
314 221 : bWriteAbsolutePath(bWriteAbsolutePathIn)
315 : {
316 221 : pszOutputFilename = CPLStrdup(pszOutputFilenameIn);
317 221 : nInputFiles = nInputFilesIn;
318 221 : papszOpenOptions = CSLDuplicate(const_cast<char **>(papszOpenOptionsIn));
319 :
320 221 : if (pszPixelFunctionIn != nullptr)
321 : {
322 3 : osPixelFunction = pszPixelFunctionIn;
323 : }
324 :
325 221 : if (ppszInputFilenamesIn)
326 : {
327 133 : ppszInputFilenames =
328 133 : static_cast<char **>(CPLMalloc(nInputFiles * sizeof(char *)));
329 1355 : for (int i = 0; i < nInputFiles; i++)
330 : {
331 1222 : ppszInputFilenames[i] = CPLStrdup(ppszInputFilenamesIn[i]);
332 : }
333 : }
334 88 : else if (pahSrcDSIn)
335 : {
336 88 : nSrcDSCount = nInputFiles;
337 88 : pahSrcDS = static_cast<GDALDatasetH *>(
338 88 : CPLMalloc(nInputFiles * sizeof(GDALDatasetH)));
339 88 : memcpy(pahSrcDS, pahSrcDSIn, nInputFiles * sizeof(GDALDatasetH));
340 88 : ppszInputFilenames =
341 88 : static_cast<char **>(CPLMalloc(nInputFiles * sizeof(char *)));
342 1227 : for (int i = 0; i < nInputFiles; i++)
343 : {
344 2278 : ppszInputFilenames[i] =
345 1139 : CPLStrdup(GDALGetDescription(pahSrcDSIn[i]));
346 : }
347 : }
348 :
349 221 : bExplicitBandList = nBandCount != 0;
350 221 : nSelectedBands = nBandCount;
351 221 : if (nBandCount)
352 : {
353 19 : panSelectedBandList =
354 19 : static_cast<int *>(CPLMalloc(nSelectedBands * sizeof(int)));
355 19 : memcpy(panSelectedBandList, panSelectedBandListIn,
356 19 : nSelectedBands * sizeof(int));
357 : }
358 :
359 221 : resolutionStrategy = resolutionStrategyIn;
360 221 : we_res = we_resIn;
361 221 : ns_res = ns_resIn;
362 221 : bTargetAlignedPixels = bTargetAlignedPixelsIn;
363 221 : minX = minXIn;
364 221 : minY = minYIn;
365 221 : maxX = maxXIn;
366 221 : maxY = maxYIn;
367 221 : bSeparate = bSeparateIn;
368 221 : bAllowProjectionDifference = bAllowProjectionDifferenceIn;
369 221 : bAddAlpha = bAddAlphaIn;
370 221 : bHideNoData = bHideNoDataIn;
371 221 : nSubdataset = nSubdatasetIn;
372 221 : pszSrcNoData = (pszSrcNoDataIn) ? CPLStrdup(pszSrcNoDataIn) : nullptr;
373 221 : pszVRTNoData = (pszVRTNoDataIn) ? CPLStrdup(pszVRTNoDataIn) : nullptr;
374 221 : pszOutputSRS = (pszOutputSRSIn) ? CPLStrdup(pszOutputSRSIn) : nullptr;
375 221 : pszResampling = (pszResamplingIn) ? CPLStrdup(pszResamplingIn) : nullptr;
376 221 : bUseSrcMaskBand = bUseSrcMaskBandIn;
377 221 : bNoDataFromMask = bNoDataFromMaskIn;
378 221 : dfMaskValueThreshold = dfMaskValueThresholdIn;
379 221 : }
380 :
381 : /************************************************************************/
382 : /* ~VRTBuilder() */
383 : /************************************************************************/
384 :
385 221 : VRTBuilder::~VRTBuilder()
386 : {
387 221 : CPLFree(pszOutputFilename);
388 221 : CPLFree(pszSrcNoData);
389 221 : CPLFree(pszVRTNoData);
390 221 : CPLFree(panSelectedBandList);
391 :
392 221 : if (ppszInputFilenames)
393 : {
394 2582 : for (int i = 0; i < nInputFiles; i++)
395 : {
396 2361 : CPLFree(ppszInputFilenames[i]);
397 : }
398 : }
399 221 : CPLFree(ppszInputFilenames);
400 221 : CPLFree(pahSrcDS);
401 :
402 221 : CPLFree(pszProjectionRef);
403 221 : CPLFree(padfSrcNoData);
404 221 : CPLFree(padfVRTNoData);
405 221 : CPLFree(pszOutputSRS);
406 221 : CPLFree(pszResampling);
407 221 : CSLDestroy(papszOpenOptions);
408 221 : }
409 :
410 : /************************************************************************/
411 : /* ProjAreEqual() */
412 : /************************************************************************/
413 :
414 2138 : static int ProjAreEqual(const char *pszWKT1, const char *pszWKT2)
415 : {
416 2138 : if (EQUAL(pszWKT1, pszWKT2))
417 2136 : return TRUE;
418 :
419 2 : OGRSpatialReferenceH hSRS1 = OSRNewSpatialReference(pszWKT1);
420 2 : OGRSpatialReferenceH hSRS2 = OSRNewSpatialReference(pszWKT2);
421 2 : int bRet = hSRS1 != nullptr && hSRS2 != nullptr && OSRIsSame(hSRS1, hSRS2);
422 2 : if (hSRS1)
423 2 : OSRDestroySpatialReference(hSRS1);
424 2 : if (hSRS2)
425 2 : OSRDestroySpatialReference(hSRS2);
426 2 : return bRet;
427 : }
428 :
429 : /************************************************************************/
430 : /* GetProjectionName() */
431 : /************************************************************************/
432 :
433 4 : static CPLString GetProjectionName(const char *pszProjection)
434 : {
435 4 : if (!pszProjection)
436 0 : return "(null)";
437 :
438 8 : OGRSpatialReference oSRS;
439 4 : oSRS.SetFromUserInput(pszProjection);
440 4 : const char *pszRet = nullptr;
441 4 : if (oSRS.IsProjected())
442 0 : pszRet = oSRS.GetAttrValue("PROJCS");
443 4 : else if (oSRS.IsGeographic())
444 3 : pszRet = oSRS.GetAttrValue("GEOGCS");
445 4 : return pszRet ? pszRet : "(null)";
446 : }
447 :
448 : /************************************************************************/
449 : /* AnalyseRaster() */
450 : /************************************************************************/
451 :
452 2348 : static void checkNoDataValues(const std::vector<BandProperty> &asProperties)
453 : {
454 5992 : for (const auto &oProps : asProperties)
455 : {
456 3698 : if (oProps.bHasNoData && GDALDataTypeIsInteger(oProps.dataType) &&
457 54 : !GDALIsValueExactAs(oProps.noDataValue, oProps.dataType))
458 : {
459 2 : CPLError(CE_Warning, CPLE_NotSupported,
460 : "Band data type of %s cannot represent the specified "
461 : "NoData value of %g",
462 2 : GDALGetDataTypeName(oProps.dataType), oProps.noDataValue);
463 : }
464 : }
465 2348 : }
466 :
467 2359 : std::string VRTBuilder::AnalyseRaster(GDALDatasetH hDS,
468 : DatasetProperty *psDatasetProperties)
469 : {
470 2359 : GDALDataset *poDS = GDALDataset::FromHandle(hDS);
471 2359 : const char *dsFileName = poDS->GetDescription();
472 2359 : char **papszMetadata = poDS->GetMetadata("SUBDATASETS");
473 2359 : if (CSLCount(papszMetadata) > 0 && poDS->GetRasterCount() == 0)
474 : {
475 0 : ppszInputFilenames = static_cast<char **>(CPLRealloc(
476 0 : ppszInputFilenames,
477 0 : sizeof(char *) * (nInputFiles + CSLCount(papszMetadata))));
478 0 : if (nSubdataset < 0)
479 : {
480 0 : int count = 1;
481 : char subdatasetNameKey[80];
482 0 : snprintf(subdatasetNameKey, sizeof(subdatasetNameKey),
483 : "SUBDATASET_%d_NAME", count);
484 0 : while (*papszMetadata != nullptr)
485 : {
486 0 : if (EQUALN(*papszMetadata, subdatasetNameKey,
487 : strlen(subdatasetNameKey)))
488 : {
489 0 : asDatasetProperties.resize(nInputFiles + 1);
490 0 : ppszInputFilenames[nInputFiles] = CPLStrdup(
491 0 : *papszMetadata + strlen(subdatasetNameKey) + 1);
492 0 : nInputFiles++;
493 0 : count++;
494 0 : snprintf(subdatasetNameKey, sizeof(subdatasetNameKey),
495 : "SUBDATASET_%d_NAME", count);
496 : }
497 0 : papszMetadata++;
498 : }
499 : }
500 : else
501 : {
502 : char subdatasetNameKey[80];
503 : const char *pszSubdatasetName;
504 :
505 0 : snprintf(subdatasetNameKey, sizeof(subdatasetNameKey),
506 : "SUBDATASET_%d_NAME", nSubdataset);
507 : pszSubdatasetName =
508 0 : CSLFetchNameValue(papszMetadata, subdatasetNameKey);
509 0 : if (pszSubdatasetName)
510 : {
511 0 : asDatasetProperties.resize(nInputFiles + 1);
512 0 : ppszInputFilenames[nInputFiles] = CPLStrdup(pszSubdatasetName);
513 0 : nInputFiles++;
514 : }
515 : }
516 0 : return "SILENTLY_IGNORE";
517 : }
518 :
519 2359 : const char *proj = poDS->GetProjectionRef();
520 2359 : auto > = psDatasetProperties->gt;
521 2359 : int bGotGeoTransform = poDS->GetGeoTransform(gt) == CE_None;
522 2359 : if (bSeparate)
523 : {
524 33 : std::string osProgramName(m_osProgramName);
525 33 : if (osProgramName == "gdalbuildvrt")
526 27 : osProgramName += " -separate";
527 :
528 33 : if (bFirst)
529 : {
530 18 : bHasGeoTransform = bGotGeoTransform;
531 18 : if (!bHasGeoTransform)
532 : {
533 1 : if (bUserExtent)
534 : {
535 0 : CPLError(CE_Warning, CPLE_NotSupported, "%s",
536 0 : ("User extent ignored by " + osProgramName +
537 : "with ungeoreferenced images.")
538 : .c_str());
539 : }
540 1 : if (resolutionStrategy == USER_RESOLUTION)
541 : {
542 0 : CPLError(CE_Warning, CPLE_NotSupported, "%s",
543 0 : ("User resolution ignored by " + osProgramName +
544 : " with ungeoreferenced images.")
545 : .c_str());
546 : }
547 : }
548 : }
549 15 : else if (bHasGeoTransform != bGotGeoTransform)
550 : {
551 : return osProgramName + " cannot stack ungeoreferenced and "
552 0 : "georeferenced images.";
553 : }
554 16 : else if (!bHasGeoTransform && (nRasterXSize != poDS->GetRasterXSize() ||
555 1 : nRasterYSize != poDS->GetRasterYSize()))
556 : {
557 : return osProgramName + " cannot stack ungeoreferenced images "
558 0 : "that have not the same dimensions.";
559 : }
560 : }
561 : else
562 : {
563 2326 : if (!bGotGeoTransform)
564 : {
565 0 : return m_osProgramName + " does not support ungeoreferenced image.";
566 : }
567 2326 : bHasGeoTransform = TRUE;
568 : }
569 :
570 2359 : if (bGotGeoTransform)
571 : {
572 4714 : if (gt[GEOTRSFRM_ROTATION_PARAM1] != 0 ||
573 2357 : gt[GEOTRSFRM_ROTATION_PARAM2] != 0)
574 : {
575 0 : return m_osProgramName +
576 0 : " does not support rotated geo transforms.";
577 : }
578 2357 : if (gt[GEOTRSFRM_NS_RES] >= 0)
579 : {
580 0 : return m_osProgramName +
581 0 : " does not support positive NS resolution.";
582 : }
583 : }
584 :
585 2359 : psDatasetProperties->nRasterXSize = poDS->GetRasterXSize();
586 2359 : psDatasetProperties->nRasterYSize = poDS->GetRasterYSize();
587 2359 : if (bFirst && bSeparate && !bGotGeoTransform)
588 : {
589 1 : nRasterXSize = poDS->GetRasterXSize();
590 1 : nRasterYSize = poDS->GetRasterYSize();
591 : }
592 :
593 2359 : double ds_minX = gt[GEOTRSFRM_TOPLEFT_X];
594 2359 : double ds_maxY = gt[GEOTRSFRM_TOPLEFT_Y];
595 2359 : double ds_maxX = ds_minX + GDALGetRasterXSize(hDS) * gt[GEOTRSFRM_WE_RES];
596 2359 : double ds_minY = ds_maxY + GDALGetRasterYSize(hDS) * gt[GEOTRSFRM_NS_RES];
597 :
598 2359 : int _nBands = GDALGetRasterCount(hDS);
599 2359 : if (_nBands == 0)
600 : {
601 0 : return "Dataset has no bands";
602 : }
603 2368 : if (bNoDataFromMask &&
604 9 : poDS->GetRasterBand(_nBands)->GetColorInterpretation() == GCI_AlphaBand)
605 3 : _nBands--;
606 :
607 2359 : GDALRasterBand *poFirstBand = poDS->GetRasterBand(1);
608 2359 : poFirstBand->GetBlockSize(&psDatasetProperties->nBlockXSize,
609 : &psDatasetProperties->nBlockYSize);
610 :
611 : /* For the -separate case */
612 2359 : psDatasetProperties->aeBandType.resize(_nBands);
613 :
614 2359 : psDatasetProperties->adfNoDataValues.resize(_nBands);
615 2359 : psDatasetProperties->abHasNoData.resize(_nBands);
616 :
617 2359 : psDatasetProperties->adfOffset.resize(_nBands);
618 2359 : psDatasetProperties->abHasOffset.resize(_nBands);
619 :
620 2359 : psDatasetProperties->adfScale.resize(_nBands);
621 2359 : psDatasetProperties->abHasScale.resize(_nBands);
622 :
623 2359 : psDatasetProperties->abHasMaskBand.resize(_nBands);
624 :
625 2359 : psDatasetProperties->bHasDatasetMask =
626 2359 : poFirstBand->GetMaskFlags() == GMF_PER_DATASET;
627 2359 : if (psDatasetProperties->bHasDatasetMask)
628 16 : bHasDatasetMask = TRUE;
629 2359 : poFirstBand->GetMaskBand()->GetBlockSize(
630 : &psDatasetProperties->nMaskBlockXSize,
631 : &psDatasetProperties->nMaskBlockYSize);
632 :
633 2359 : psDatasetProperties->bLastBandIsAlpha = false;
634 2359 : if (poDS->GetRasterBand(_nBands)->GetColorInterpretation() == GCI_AlphaBand)
635 14 : psDatasetProperties->bLastBandIsAlpha = true;
636 :
637 : // Collect overview factors. We only handle power-of-two situations for now
638 2359 : const int nOverviews = poFirstBand->GetOverviewCount();
639 2359 : int nExpectedOvFactor = 2;
640 2371 : for (int j = 0; j < nOverviews; j++)
641 : {
642 23 : GDALRasterBand *poOverview = poFirstBand->GetOverview(j);
643 23 : if (!poOverview)
644 0 : continue;
645 23 : if (poOverview->GetXSize() < 128 && poOverview->GetYSize() < 128)
646 : {
647 11 : break;
648 : }
649 :
650 12 : const int nOvFactor = GDALComputeOvFactor(
651 : poOverview->GetXSize(), poFirstBand->GetXSize(),
652 12 : poOverview->GetYSize(), poFirstBand->GetYSize());
653 :
654 12 : if (nOvFactor != nExpectedOvFactor)
655 0 : break;
656 :
657 12 : psDatasetProperties->anOverviewFactors.push_back(nOvFactor);
658 12 : nExpectedOvFactor *= 2;
659 : }
660 :
661 5887 : for (int j = 0; j < _nBands; j++)
662 : {
663 3528 : GDALRasterBand *poBand = poDS->GetRasterBand(j + 1);
664 :
665 3528 : psDatasetProperties->aeBandType[j] = poBand->GetRasterDataType();
666 :
667 3528 : if (!bSeparate && nSrcNoDataCount > 0)
668 : {
669 4 : psDatasetProperties->abHasNoData[j] = true;
670 4 : if (j < nSrcNoDataCount)
671 4 : psDatasetProperties->adfNoDataValues[j] = padfSrcNoData[j];
672 : else
673 0 : psDatasetProperties->adfNoDataValues[j] =
674 0 : padfSrcNoData[nSrcNoDataCount - 1];
675 : }
676 : else
677 : {
678 3524 : int bHasNoData = false;
679 7048 : psDatasetProperties->adfNoDataValues[j] =
680 3524 : poBand->GetNoDataValue(&bHasNoData);
681 3524 : psDatasetProperties->abHasNoData[j] = bHasNoData != 0;
682 : }
683 :
684 3528 : int bHasOffset = false;
685 3528 : psDatasetProperties->adfOffset[j] = poBand->GetOffset(&bHasOffset);
686 7056 : psDatasetProperties->abHasOffset[j] =
687 3528 : bHasOffset != 0 && psDatasetProperties->adfOffset[j] != 0.0;
688 :
689 3528 : int bHasScale = false;
690 3528 : psDatasetProperties->adfScale[j] = poBand->GetScale(&bHasScale);
691 7056 : psDatasetProperties->abHasScale[j] =
692 3528 : bHasScale != 0 && psDatasetProperties->adfScale[j] != 1.0;
693 :
694 3528 : const int nMaskFlags = poBand->GetMaskFlags();
695 3528 : psDatasetProperties->abHasMaskBand[j] =
696 6997 : (nMaskFlags != GMF_ALL_VALID && nMaskFlags != GMF_NODATA) ||
697 6997 : poBand->GetColorInterpretation() == GCI_AlphaBand;
698 : }
699 :
700 2359 : if (bSeparate)
701 : {
702 39 : for (int j = 0; j < nSelectedBands; j++)
703 : {
704 7 : if (panSelectedBandList[j] > _nBands)
705 : {
706 : return CPLSPrintf("%s has %d bands, but %d is requested",
707 1 : dsFileName, _nBands, panSelectedBandList[j]);
708 : }
709 : }
710 : }
711 :
712 2358 : if (bFirst)
713 : {
714 220 : nTotalBands = _nBands;
715 220 : if (bAddAlpha && psDatasetProperties->bLastBandIsAlpha)
716 : {
717 4 : bLastBandIsAlpha = true;
718 4 : nTotalBands--;
719 : }
720 :
721 220 : if (proj)
722 220 : pszProjectionRef = CPLStrdup(proj);
723 220 : if (!bUserExtent)
724 : {
725 207 : minX = ds_minX;
726 207 : minY = ds_minY;
727 207 : maxX = ds_maxX;
728 207 : maxY = ds_maxY;
729 : }
730 :
731 220 : if (!bSeparate)
732 : {
733 : // if not provided an explicit band list, take the one of the first
734 : // dataset
735 203 : if (nSelectedBands == 0)
736 : {
737 186 : nSelectedBands = nTotalBands;
738 186 : CPLFree(panSelectedBandList);
739 186 : panSelectedBandList =
740 186 : static_cast<int *>(CPLMalloc(nSelectedBands * sizeof(int)));
741 435 : for (int j = 0; j < nSelectedBands; j++)
742 : {
743 249 : panSelectedBandList[j] = j + 1;
744 : }
745 : }
746 681 : for (int j = 0; j < nSelectedBands; j++)
747 : {
748 478 : nMaxSelectedBandNo =
749 478 : std::max(nMaxSelectedBandNo, panSelectedBandList[j]);
750 : }
751 :
752 203 : asBandProperties.resize(nSelectedBands);
753 680 : for (int j = 0; j < nSelectedBands; j++)
754 : {
755 478 : const int nSelBand = panSelectedBandList[j];
756 478 : if (nSelBand <= 0 || nSelBand > nTotalBands)
757 : {
758 1 : return CPLSPrintf("Invalid band number: %d", nSelBand);
759 : }
760 477 : GDALRasterBand *poBand = poDS->GetRasterBand(nSelBand);
761 954 : asBandProperties[j].colorInterpretation =
762 477 : poBand->GetColorInterpretation();
763 477 : asBandProperties[j].dataType = poBand->GetRasterDataType();
764 477 : if (asBandProperties[j].colorInterpretation == GCI_PaletteIndex)
765 : {
766 2 : auto colorTable = poBand->GetColorTable();
767 2 : if (colorTable)
768 : {
769 2 : asBandProperties[j].colorTable.reset(
770 : colorTable->Clone());
771 : }
772 : }
773 : else
774 475 : asBandProperties[j].colorTable = nullptr;
775 :
776 477 : if (nVRTNoDataCount > 0)
777 : {
778 26 : asBandProperties[j].bHasNoData = true;
779 26 : if (j < nVRTNoDataCount)
780 20 : asBandProperties[j].noDataValue = padfVRTNoData[j];
781 : else
782 6 : asBandProperties[j].noDataValue =
783 6 : padfVRTNoData[nVRTNoDataCount - 1];
784 : }
785 : else
786 : {
787 451 : int bHasNoData = false;
788 902 : asBandProperties[j].noDataValue =
789 451 : poBand->GetNoDataValue(&bHasNoData);
790 451 : asBandProperties[j].bHasNoData = bHasNoData != 0;
791 : }
792 :
793 477 : int bHasOffset = false;
794 477 : asBandProperties[j].dfOffset = poBand->GetOffset(&bHasOffset);
795 477 : asBandProperties[j].bHasOffset =
796 477 : bHasOffset != 0 && asBandProperties[j].dfOffset != 0.0;
797 :
798 477 : int bHasScale = false;
799 477 : asBandProperties[j].dfScale = poBand->GetScale(&bHasScale);
800 477 : asBandProperties[j].bHasScale =
801 477 : bHasScale != 0 && asBandProperties[j].dfScale != 1.0;
802 : }
803 : }
804 : }
805 : else
806 : {
807 2138 : if ((proj != nullptr && pszProjectionRef == nullptr) ||
808 6414 : (proj == nullptr && pszProjectionRef != nullptr) ||
809 2138 : (proj != nullptr && pszProjectionRef != nullptr &&
810 2138 : ProjAreEqual(proj, pszProjectionRef) == FALSE))
811 : {
812 2 : if (!bAllowProjectionDifference)
813 : {
814 4 : CPLString osExpected = GetProjectionName(pszProjectionRef);
815 4 : CPLString osGot = GetProjectionName(proj);
816 2 : return m_osProgramName +
817 : CPLSPrintf(" does not support heterogeneous "
818 : "projection: expected %s, got %s.",
819 2 : osExpected.c_str(), osGot.c_str());
820 : }
821 : }
822 2136 : if (!bSeparate)
823 : {
824 2121 : if (!bExplicitBandList && _nBands != nTotalBands)
825 : {
826 9 : if (bAddAlpha && _nBands == nTotalBands + 1 &&
827 4 : psDatasetProperties->bLastBandIsAlpha)
828 : {
829 4 : bLastBandIsAlpha = true;
830 : }
831 : else
832 : {
833 5 : return m_osProgramName +
834 : CPLSPrintf(" does not support heterogeneous band "
835 : "numbers: expected %d, got %d.",
836 5 : nTotalBands, _nBands);
837 : }
838 : }
839 2112 : else if (bExplicitBandList && _nBands < nMaxSelectedBandNo)
840 : {
841 0 : return m_osProgramName +
842 : CPLSPrintf(" does not support heterogeneous band "
843 : "numbers: expected at least %d, got %d.",
844 0 : nMaxSelectedBandNo, _nBands);
845 : }
846 :
847 5285 : for (int j = 0; j < nSelectedBands; j++)
848 : {
849 3169 : const int nSelBand = panSelectedBandList[j];
850 3169 : CPLAssert(nSelBand >= 1 && nSelBand <= _nBands);
851 3169 : GDALRasterBand *poBand = poDS->GetRasterBand(nSelBand);
852 3169 : if (asBandProperties[j].colorInterpretation !=
853 3169 : poBand->GetColorInterpretation())
854 : {
855 0 : return m_osProgramName +
856 : CPLSPrintf(
857 : " does not support heterogeneous "
858 : "band color interpretation: expected %s, got "
859 : "%s.",
860 : GDALGetColorInterpretationName(
861 0 : asBandProperties[j].colorInterpretation),
862 : GDALGetColorInterpretationName(
863 0 : poBand->GetColorInterpretation()));
864 : }
865 3169 : if (asBandProperties[j].dataType != poBand->GetRasterDataType())
866 : {
867 0 : return m_osProgramName +
868 : CPLSPrintf(" does not support heterogeneous "
869 : "band data type: expected %s, got %s.",
870 : GDALGetDataTypeName(
871 0 : asBandProperties[j].dataType),
872 : GDALGetDataTypeName(
873 0 : poBand->GetRasterDataType()));
874 : }
875 3169 : if (asBandProperties[j].colorTable)
876 : {
877 2 : const GDALColorTable *colorTable = poBand->GetColorTable();
878 : int nRefColorEntryCount =
879 2 : asBandProperties[j].colorTable->GetColorEntryCount();
880 4 : if (colorTable == nullptr ||
881 2 : colorTable->GetColorEntryCount() != nRefColorEntryCount)
882 : {
883 0 : return m_osProgramName +
884 : " does not support rasters with "
885 : "different color tables (different number of "
886 0 : "color table entries)";
887 : }
888 :
889 : /* Check that the palette are the same too */
890 : /* We just warn and still process the file. It is not a
891 : * technical no-go, but the user */
892 : /* should check that the end result is OK for him. */
893 260 : for (int i = 0; i < nRefColorEntryCount; i++)
894 : {
895 : const GDALColorEntry *psEntry =
896 258 : colorTable->GetColorEntry(i);
897 : const GDALColorEntry *psEntryRef =
898 258 : asBandProperties[j].colorTable->GetColorEntry(i);
899 258 : if (psEntry->c1 != psEntryRef->c1 ||
900 258 : psEntry->c2 != psEntryRef->c2 ||
901 258 : psEntry->c3 != psEntryRef->c3 ||
902 258 : psEntry->c4 != psEntryRef->c4)
903 : {
904 : static int bFirstWarningPCT = TRUE;
905 0 : if (bFirstWarningPCT)
906 0 : CPLError(
907 : CE_Warning, CPLE_NotSupported,
908 : "%s has different values than the first "
909 : "raster for some entries in the color "
910 : "table.\n"
911 : "The end result might produce weird "
912 : "colors.\n"
913 : "You're advised to pre-process your "
914 : "rasters with other tools, such as "
915 : "pct2rgb.py or gdal_translate -expand RGB\n"
916 : "to operate %s on RGB rasters "
917 : "instead",
918 : dsFileName, m_osProgramName.c_str());
919 : else
920 0 : CPLError(CE_Warning, CPLE_NotSupported,
921 : "%s has different values than the "
922 : "first raster for some entries in the "
923 : "color table.",
924 : dsFileName);
925 0 : bFirstWarningPCT = FALSE;
926 0 : break;
927 : }
928 : }
929 : }
930 :
931 3169 : if (psDatasetProperties->abHasOffset[j] !=
932 6338 : asBandProperties[j].bHasOffset ||
933 3169 : (asBandProperties[j].bHasOffset &&
934 0 : psDatasetProperties->adfOffset[j] !=
935 0 : asBandProperties[j].dfOffset))
936 : {
937 0 : return m_osProgramName +
938 : CPLSPrintf(
939 : " does not support heterogeneous "
940 : "band offset: expected (%d,%f), got (%d,%f).",
941 0 : static_cast<int>(asBandProperties[j].bHasOffset),
942 0 : asBandProperties[j].dfOffset,
943 : static_cast<int>(
944 0 : psDatasetProperties->abHasOffset[j]),
945 0 : psDatasetProperties->adfOffset[j]);
946 : }
947 :
948 3169 : if (psDatasetProperties->abHasScale[j] !=
949 6338 : asBandProperties[j].bHasScale ||
950 3169 : (asBandProperties[j].bHasScale &&
951 0 : psDatasetProperties->adfScale[j] !=
952 0 : asBandProperties[j].dfScale))
953 : {
954 0 : return m_osProgramName +
955 : CPLSPrintf(
956 : " does not support heterogeneous "
957 : "band scale: expected (%d,%f), got (%d,%f).",
958 0 : static_cast<int>(asBandProperties[j].bHasScale),
959 0 : asBandProperties[j].dfScale,
960 : static_cast<int>(
961 0 : psDatasetProperties->abHasScale[j]),
962 0 : psDatasetProperties->adfScale[j]);
963 : }
964 : }
965 : }
966 2131 : if (!bUserExtent)
967 : {
968 2128 : if (ds_minX < minX)
969 4 : minX = ds_minX;
970 2128 : if (ds_minY < minY)
971 35 : minY = ds_minY;
972 2128 : if (ds_maxX > maxX)
973 697 : maxX = ds_maxX;
974 2128 : if (ds_maxY > maxY)
975 29 : maxY = ds_maxY;
976 : }
977 : }
978 :
979 2350 : if (resolutionStrategy == AVERAGE_RESOLUTION)
980 : {
981 2283 : ++nCountValid;
982 : {
983 2283 : const double dfDelta = gt[GEOTRSFRM_WE_RES] - we_res;
984 2283 : we_res += dfDelta / nCountValid;
985 : }
986 : {
987 2283 : const double dfDelta = gt[GEOTRSFRM_NS_RES] - ns_res;
988 2283 : ns_res += dfDelta / nCountValid;
989 : }
990 : }
991 67 : else if (resolutionStrategy == SAME_RESOLUTION)
992 : {
993 30 : if (bFirst)
994 : {
995 24 : we_res = gt[GEOTRSFRM_WE_RES];
996 24 : ns_res = gt[GEOTRSFRM_NS_RES];
997 : }
998 11 : else if (we_res != gt[GEOTRSFRM_WE_RES] ||
999 5 : ns_res != gt[GEOTRSFRM_NS_RES])
1000 : {
1001 : return CPLSPrintf("Dataset %s has resolution %f x %f, whereas "
1002 : "previous sources have resolution %f x %f",
1003 1 : dsFileName, gt[GEOTRSFRM_WE_RES],
1004 1 : gt[GEOTRSFRM_NS_RES], we_res, ns_res);
1005 : }
1006 : }
1007 37 : else if (resolutionStrategy != USER_RESOLUTION)
1008 : {
1009 24 : if (bFirst)
1010 : {
1011 12 : we_res = gt[GEOTRSFRM_WE_RES];
1012 12 : ns_res = gt[GEOTRSFRM_NS_RES];
1013 : }
1014 12 : else if (resolutionStrategy == HIGHEST_RESOLUTION)
1015 : {
1016 1 : we_res = std::min(we_res, gt[GEOTRSFRM_WE_RES]);
1017 : // ns_res is negative, the highest resolution is the max value.
1018 1 : ns_res = std::max(ns_res, gt[GEOTRSFRM_NS_RES]);
1019 : }
1020 11 : else if (resolutionStrategy == COMMON_RESOLUTION)
1021 : {
1022 10 : we_res = CPLGreatestCommonDivisor(we_res, gt[GEOTRSFRM_WE_RES]);
1023 10 : if (we_res == 0)
1024 : {
1025 1 : return "Failed to get common resolution";
1026 : }
1027 9 : ns_res = CPLGreatestCommonDivisor(ns_res, gt[GEOTRSFRM_NS_RES]);
1028 9 : if (ns_res == 0)
1029 : {
1030 0 : return "Failed to get common resolution";
1031 : }
1032 : }
1033 : else
1034 : {
1035 1 : we_res = std::max(we_res, gt[GEOTRSFRM_WE_RES]);
1036 : // ns_res is negative, the lowest resolution is the min value.
1037 1 : ns_res = std::min(ns_res, gt[GEOTRSFRM_NS_RES]);
1038 : }
1039 : }
1040 :
1041 2348 : checkNoDataValues(asBandProperties);
1042 :
1043 2348 : return "";
1044 : }
1045 :
1046 : /************************************************************************/
1047 : /* WriteAbsolutePath() */
1048 : /************************************************************************/
1049 :
1050 7 : static void WriteAbsolutePath(VRTSimpleSource *poSource, const char *dsFileName)
1051 : {
1052 7 : if (dsFileName[0])
1053 : {
1054 7 : if (CPLIsFilenameRelative(dsFileName))
1055 : {
1056 : VSIStatBufL sStat;
1057 2 : if (VSIStatL(dsFileName, &sStat) == 0)
1058 : {
1059 2 : if (char *pszCurDir = CPLGetCurrentDir())
1060 : {
1061 2 : poSource->SetSourceDatasetName(
1062 4 : CPLFormFilenameSafe(pszCurDir, dsFileName, nullptr)
1063 : .c_str(),
1064 : false);
1065 2 : CPLFree(pszCurDir);
1066 : }
1067 : }
1068 : }
1069 : else
1070 : {
1071 5 : poSource->SetSourceDatasetName(dsFileName, false);
1072 : }
1073 : }
1074 7 : }
1075 :
1076 : /************************************************************************/
1077 : /* CreateVRTSeparate() */
1078 : /************************************************************************/
1079 :
1080 17 : void VRTBuilder::CreateVRTSeparate(VRTDataset *poVRTDS)
1081 : {
1082 17 : int iBand = 1;
1083 49 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1084 : {
1085 32 : DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1086 :
1087 32 : if (psDatasetProperties->isFileOK == FALSE)
1088 0 : continue;
1089 :
1090 32 : const char *dsFileName = ppszInputFilenames[i];
1091 :
1092 : double dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1093 : dfDstYOff, dfDstXSize, dfDstYSize;
1094 32 : if (bHasGeoTransform)
1095 : {
1096 30 : if (!GetSrcDstWin(psDatasetProperties, we_res, ns_res, minX, minY,
1097 : maxX, maxY, nRasterXSize, nRasterYSize,
1098 : &dfSrcXOff, &dfSrcYOff, &dfSrcXSize, &dfSrcYSize,
1099 : &dfDstXOff, &dfDstYOff, &dfDstXSize, &dfDstYSize))
1100 : {
1101 0 : CPLDebug("BuildVRT",
1102 : "Skipping %s as not intersecting area of interest",
1103 : dsFileName);
1104 0 : continue;
1105 : }
1106 : }
1107 : else
1108 : {
1109 2 : dfSrcXOff = dfSrcYOff = dfDstXOff = dfDstYOff = 0;
1110 2 : dfSrcXSize = dfDstXSize = nRasterXSize;
1111 2 : dfSrcYSize = dfDstYSize = nRasterYSize;
1112 : }
1113 :
1114 : GDALDatasetH hSourceDS;
1115 32 : bool bDropRef = false;
1116 84 : if (nSrcDSCount == nInputFiles &&
1117 52 : GDALGetDatasetDriver(pahSrcDS[i]) != nullptr &&
1118 20 : (dsFileName[0] == '\0' || // could be a unnamed VRT file
1119 2 : EQUAL(GDALGetDescription(GDALGetDatasetDriver(pahSrcDS[i])),
1120 : "MEM")))
1121 : {
1122 20 : hSourceDS = pahSrcDS[i];
1123 : }
1124 : else
1125 : {
1126 12 : bDropRef = true;
1127 24 : GDALProxyPoolDatasetH hProxyDS = GDALProxyPoolDatasetCreate(
1128 : dsFileName, psDatasetProperties->nRasterXSize,
1129 : psDatasetProperties->nRasterYSize, GA_ReadOnly, TRUE,
1130 12 : pszProjectionRef, psDatasetProperties->gt.data());
1131 12 : hSourceDS = static_cast<GDALDatasetH>(hProxyDS);
1132 : cpl::down_cast<GDALProxyPoolDataset *>(
1133 : GDALDataset::FromHandle(hProxyDS))
1134 12 : ->SetOpenOptions(papszOpenOptions);
1135 :
1136 27 : for (int jBand = 0;
1137 27 : jBand <
1138 27 : static_cast<int>(psDatasetProperties->aeBandType.size());
1139 : ++jBand)
1140 : {
1141 15 : GDALProxyPoolDatasetAddSrcBandDescription(
1142 15 : hProxyDS, psDatasetProperties->aeBandType[jBand],
1143 : psDatasetProperties->nBlockXSize,
1144 : psDatasetProperties->nBlockYSize);
1145 : }
1146 : }
1147 :
1148 : const int nBandsToIter =
1149 32 : nSelectedBands > 0
1150 62 : ? nSelectedBands
1151 30 : : static_cast<int>(psDatasetProperties->aeBandType.size());
1152 72 : for (int iBandToIter = 0; iBandToIter < nBandsToIter; ++iBandToIter)
1153 : {
1154 : // 0-based
1155 80 : const int nSrcBandIdx = nSelectedBands > 0
1156 40 : ? panSelectedBandList[iBandToIter] - 1
1157 : : iBandToIter;
1158 40 : assert(nSrcBandIdx >= 0);
1159 40 : poVRTDS->AddBand(psDatasetProperties->aeBandType[nSrcBandIdx],
1160 40 : nullptr);
1161 :
1162 : VRTSourcedRasterBand *poVRTBand =
1163 : static_cast<VRTSourcedRasterBand *>(
1164 40 : poVRTDS->GetRasterBand(iBand));
1165 :
1166 40 : if (bHideNoData)
1167 0 : poVRTBand->SetMetadataItem("HideNoDataValue", "1", nullptr);
1168 :
1169 40 : if (bAllowVRTNoData)
1170 : {
1171 38 : if (nVRTNoDataCount > 0)
1172 : {
1173 4 : if (iBand - 1 < nVRTNoDataCount)
1174 4 : poVRTBand->SetNoDataValue(padfVRTNoData[iBand - 1]);
1175 : else
1176 0 : poVRTBand->SetNoDataValue(
1177 0 : padfVRTNoData[nVRTNoDataCount - 1]);
1178 : }
1179 34 : else if (psDatasetProperties->abHasNoData[nSrcBandIdx])
1180 : {
1181 2 : poVRTBand->SetNoDataValue(
1182 2 : psDatasetProperties->adfNoDataValues[nSrcBandIdx]);
1183 : }
1184 : }
1185 :
1186 : VRTSimpleSource *poSimpleSource;
1187 78 : if (bAllowSrcNoData &&
1188 72 : (nSrcNoDataCount > 0 ||
1189 74 : psDatasetProperties->abHasNoData[nSrcBandIdx]))
1190 : {
1191 6 : auto poComplexSource = new VRTComplexSource();
1192 6 : poSimpleSource = poComplexSource;
1193 6 : if (nSrcNoDataCount > 0)
1194 : {
1195 4 : if (iBand - 1 < nSrcNoDataCount)
1196 4 : poComplexSource->SetNoDataValue(
1197 4 : padfSrcNoData[iBand - 1]);
1198 : else
1199 0 : poComplexSource->SetNoDataValue(
1200 0 : padfSrcNoData[nSrcNoDataCount - 1]);
1201 : }
1202 : else /* if (psDatasetProperties->abHasNoData[nSrcBandIdx]) */
1203 : {
1204 2 : poComplexSource->SetNoDataValue(
1205 2 : psDatasetProperties->adfNoDataValues[nSrcBandIdx]);
1206 : }
1207 : }
1208 68 : else if (bUseSrcMaskBand &&
1209 68 : psDatasetProperties->abHasMaskBand[nSrcBandIdx])
1210 : {
1211 1 : auto poSource = new VRTComplexSource();
1212 1 : poSource->SetUseMaskBand(true);
1213 1 : poSimpleSource = poSource;
1214 : }
1215 : else
1216 33 : poSimpleSource = new VRTSimpleSource();
1217 :
1218 40 : if (pszResampling)
1219 0 : poSimpleSource->SetResampling(pszResampling);
1220 80 : poVRTBand->ConfigureSource(
1221 : poSimpleSource,
1222 : static_cast<GDALRasterBand *>(
1223 40 : GDALGetRasterBand(hSourceDS, nSrcBandIdx + 1)),
1224 : FALSE, dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1225 : dfDstYOff, dfDstXSize, dfDstYSize);
1226 :
1227 40 : if (bWriteAbsolutePath)
1228 3 : WriteAbsolutePath(poSimpleSource, dsFileName);
1229 :
1230 40 : if (psDatasetProperties->abHasOffset[nSrcBandIdx])
1231 0 : poVRTBand->SetOffset(
1232 0 : psDatasetProperties->adfOffset[nSrcBandIdx]);
1233 :
1234 40 : if (psDatasetProperties->abHasScale[nSrcBandIdx])
1235 0 : poVRTBand->SetScale(psDatasetProperties->adfScale[nSrcBandIdx]);
1236 :
1237 40 : poVRTBand->AddSource(poSimpleSource);
1238 :
1239 40 : iBand++;
1240 : }
1241 :
1242 32 : if (bDropRef)
1243 : {
1244 12 : GDALDereferenceDataset(hSourceDS);
1245 : }
1246 : }
1247 17 : }
1248 :
1249 : /************************************************************************/
1250 : /* CreateVRTNonSeparate() */
1251 : /************************************************************************/
1252 :
1253 198 : void VRTBuilder::CreateVRTNonSeparate(VRTDataset *poVRTDS)
1254 : {
1255 396 : CPLStringList aosOptions;
1256 :
1257 198 : if (!osPixelFunction.empty())
1258 : {
1259 3 : aosOptions.AddNameValue("subclass", "VRTDerivedRasterBand");
1260 3 : aosOptions.AddNameValue("PixelFunctionType", osPixelFunction.c_str());
1261 3 : aosOptions.AddNameValue("SkipNonContributingSources", "1");
1262 6 : CPLString osName;
1263 2 : for (const auto &[pszKey, pszValue] :
1264 5 : cpl::IterateNameValue(aosPixelFunctionArgs))
1265 : {
1266 1 : osName.Printf("_PIXELFN_ARG_%s", pszKey);
1267 1 : aosOptions.AddNameValue(osName.c_str(), pszValue);
1268 : }
1269 : }
1270 :
1271 671 : for (int j = 0; j < nSelectedBands; j++)
1272 : {
1273 473 : const char *pszSourceTransferType = "Float64";
1274 945 : if (osPixelFunction == "mean" || osPixelFunction == "min" ||
1275 472 : osPixelFunction == "max")
1276 : {
1277 : pszSourceTransferType =
1278 1 : GDALGetDataTypeName(asBandProperties[j].dataType);
1279 : }
1280 473 : aosOptions.AddNameValue("SourceTransferType", pszSourceTransferType);
1281 :
1282 473 : poVRTDS->AddBand(asBandProperties[j].dataType, aosOptions.List());
1283 473 : GDALRasterBand *poBand = poVRTDS->GetRasterBand(j + 1);
1284 473 : poBand->SetColorInterpretation(asBandProperties[j].colorInterpretation);
1285 473 : if (asBandProperties[j].colorInterpretation == GCI_PaletteIndex)
1286 : {
1287 2 : poBand->SetColorTable(asBandProperties[j].colorTable.get());
1288 : }
1289 473 : if (bAllowVRTNoData && asBandProperties[j].bHasNoData)
1290 39 : poBand->SetNoDataValue(asBandProperties[j].noDataValue);
1291 473 : if (bHideNoData)
1292 2 : poBand->SetMetadataItem("HideNoDataValue", "1");
1293 :
1294 473 : if (asBandProperties[j].bHasOffset)
1295 0 : poBand->SetOffset(asBandProperties[j].dfOffset);
1296 :
1297 473 : if (asBandProperties[j].bHasScale)
1298 0 : poBand->SetScale(asBandProperties[j].dfScale);
1299 : }
1300 :
1301 198 : VRTSourcedRasterBand *poMaskVRTBand = nullptr;
1302 198 : if (bAddAlpha)
1303 : {
1304 10 : poVRTDS->AddBand(GDT_Byte);
1305 10 : GDALRasterBand *poBand = poVRTDS->GetRasterBand(nSelectedBands + 1);
1306 10 : poBand->SetColorInterpretation(GCI_AlphaBand);
1307 : }
1308 188 : else if (bHasDatasetMask)
1309 : {
1310 12 : poVRTDS->CreateMaskBand(GMF_PER_DATASET);
1311 : poMaskVRTBand = static_cast<VRTSourcedRasterBand *>(
1312 12 : poVRTDS->GetRasterBand(1)->GetMaskBand());
1313 : }
1314 :
1315 198 : bool bCanCollectOverviewFactors = true;
1316 396 : std::set<int> anOverviewFactorsSet;
1317 396 : std::vector<int> anIdxValidDatasets;
1318 :
1319 2517 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1320 : {
1321 2319 : DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1322 :
1323 2319 : if (psDatasetProperties->isFileOK == FALSE)
1324 8 : continue;
1325 :
1326 2312 : const char *dsFileName = ppszInputFilenames[i];
1327 :
1328 : double dfSrcXOff;
1329 : double dfSrcYOff;
1330 : double dfSrcXSize;
1331 : double dfSrcYSize;
1332 : double dfDstXOff;
1333 : double dfDstYOff;
1334 : double dfDstXSize;
1335 : double dfDstYSize;
1336 2312 : if (!GetSrcDstWin(psDatasetProperties, we_res, ns_res, minX, minY, maxX,
1337 : maxY, nRasterXSize, nRasterYSize, &dfSrcXOff,
1338 : &dfSrcYOff, &dfSrcXSize, &dfSrcYSize, &dfDstXOff,
1339 : &dfDstYOff, &dfDstXSize, &dfDstYSize))
1340 : {
1341 1 : CPLDebug("BuildVRT",
1342 : "Skipping %s as not intersecting area of interest",
1343 : dsFileName);
1344 1 : continue;
1345 : }
1346 :
1347 2311 : anIdxValidDatasets.push_back(i);
1348 :
1349 2311 : if (bCanCollectOverviewFactors)
1350 : {
1351 2296 : if (std::abs(psDatasetProperties->gt[1] - we_res) >
1352 4573 : 1e-8 * std::abs(we_res) ||
1353 2277 : std::abs(psDatasetProperties->gt[5] - ns_res) >
1354 2277 : 1e-8 * std::abs(ns_res))
1355 : {
1356 19 : bCanCollectOverviewFactors = false;
1357 19 : anOverviewFactorsSet.clear();
1358 : }
1359 : }
1360 2311 : if (bCanCollectOverviewFactors)
1361 : {
1362 2286 : for (int nOvFactor : psDatasetProperties->anOverviewFactors)
1363 9 : anOverviewFactorsSet.insert(nOvFactor);
1364 : }
1365 :
1366 : GDALDatasetH hSourceDS;
1367 2311 : bool bDropRef = false;
1368 :
1369 5731 : if (nSrcDSCount == nInputFiles &&
1370 3420 : GDALGetDatasetDriver(pahSrcDS[i]) != nullptr &&
1371 1109 : (dsFileName[0] == '\0' || // could be a unnamed VRT file
1372 53 : EQUAL(GDALGetDescription(GDALGetDatasetDriver(pahSrcDS[i])),
1373 : "MEM")))
1374 : {
1375 1090 : hSourceDS = pahSrcDS[i];
1376 : }
1377 : else
1378 : {
1379 1221 : bDropRef = true;
1380 2442 : GDALProxyPoolDatasetH hProxyDS = GDALProxyPoolDatasetCreate(
1381 : dsFileName, psDatasetProperties->nRasterXSize,
1382 : psDatasetProperties->nRasterYSize, GA_ReadOnly, TRUE,
1383 1221 : pszProjectionRef, psDatasetProperties->gt.data());
1384 : cpl::down_cast<GDALProxyPoolDataset *>(
1385 : GDALDataset::FromHandle(hProxyDS))
1386 1221 : ->SetOpenOptions(papszOpenOptions);
1387 :
1388 3530 : for (int j = 0;
1389 3530 : j < nMaxSelectedBandNo +
1390 42 : (bAddAlpha && psDatasetProperties->bLastBandIsAlpha
1391 3572 : ? 1
1392 : : 0);
1393 : j++)
1394 : {
1395 2309 : GDALProxyPoolDatasetAddSrcBandDescription(
1396 : hProxyDS,
1397 2309 : j < static_cast<int>(asBandProperties.size())
1398 2304 : ? asBandProperties[j].dataType
1399 : : GDT_Byte,
1400 : psDatasetProperties->nBlockXSize,
1401 : psDatasetProperties->nBlockYSize);
1402 : }
1403 1221 : if (bHasDatasetMask && !bAddAlpha)
1404 : {
1405 : static_cast<GDALProxyPoolRasterBand *>(
1406 13 : cpl::down_cast<GDALProxyPoolDataset *>(
1407 : GDALDataset::FromHandle(hProxyDS))
1408 13 : ->GetRasterBand(1))
1409 13 : ->AddSrcMaskBandDescription(
1410 : GDT_Byte, psDatasetProperties->nMaskBlockXSize,
1411 : psDatasetProperties->nMaskBlockYSize);
1412 : }
1413 :
1414 1221 : hSourceDS = static_cast<GDALDatasetH>(hProxyDS);
1415 : }
1416 :
1417 5958 : for (int j = 0;
1418 5958 : j <
1419 5958 : nSelectedBands +
1420 5958 : (bAddAlpha && psDatasetProperties->bLastBandIsAlpha ? 1 : 0);
1421 : j++)
1422 : {
1423 : VRTSourcedRasterBandH hVRTBand = static_cast<VRTSourcedRasterBandH>(
1424 3647 : poVRTDS->GetRasterBand(j + 1));
1425 3647 : const int nSelBand = j == nSelectedBands ? nSelectedBands + 1
1426 3639 : : panSelectedBandList[j];
1427 :
1428 : /* Place the raster band at the right position in the VRT */
1429 3647 : VRTSourcedRasterBand *poVRTBand =
1430 : static_cast<VRTSourcedRasterBand *>(hVRTBand);
1431 :
1432 : VRTSimpleSource *poSimpleSource;
1433 3647 : if (bNoDataFromMask)
1434 : {
1435 15 : auto poNoDataFromMaskSource = new VRTNoDataFromMaskSource();
1436 15 : poSimpleSource = poNoDataFromMaskSource;
1437 15 : poNoDataFromMaskSource->SetParameters(
1438 15 : (nVRTNoDataCount > 0)
1439 15 : ? ((j < nVRTNoDataCount)
1440 15 : ? padfVRTNoData[j]
1441 6 : : padfVRTNoData[nVRTNoDataCount - 1])
1442 : : 0,
1443 : dfMaskValueThreshold);
1444 : }
1445 7264 : else if (bAllowSrcNoData &&
1446 7264 : psDatasetProperties->abHasNoData[nSelBand - 1])
1447 : {
1448 27 : auto poComplexSource = new VRTComplexSource();
1449 27 : poSimpleSource = poComplexSource;
1450 27 : poComplexSource->SetNoDataValue(
1451 27 : psDatasetProperties->adfNoDataValues[nSelBand - 1]);
1452 : }
1453 7210 : else if (bUseSrcMaskBand &&
1454 7210 : psDatasetProperties->abHasMaskBand[nSelBand - 1])
1455 : {
1456 57 : auto poSource = new VRTComplexSource();
1457 57 : poSource->SetUseMaskBand(true);
1458 57 : poSimpleSource = poSource;
1459 : }
1460 : else
1461 3548 : poSimpleSource = new VRTSimpleSource();
1462 3647 : if (pszResampling)
1463 23 : poSimpleSource->SetResampling(pszResampling);
1464 3647 : auto poSrcBand = GDALRasterBand::FromHandle(
1465 : GDALGetRasterBand(hSourceDS, nSelBand));
1466 3647 : poVRTBand->ConfigureSource(poSimpleSource, poSrcBand, FALSE,
1467 : dfSrcXOff, dfSrcYOff, dfSrcXSize,
1468 : dfSrcYSize, dfDstXOff, dfDstYOff,
1469 : dfDstXSize, dfDstYSize);
1470 :
1471 3647 : if (bWriteAbsolutePath)
1472 3 : WriteAbsolutePath(poSimpleSource, dsFileName);
1473 :
1474 3647 : poVRTBand->AddSource(poSimpleSource);
1475 : }
1476 :
1477 2311 : if (bAddAlpha && !psDatasetProperties->bLastBandIsAlpha)
1478 : {
1479 : VRTSourcedRasterBand *poVRTBand =
1480 : static_cast<VRTSourcedRasterBand *>(
1481 11 : poVRTDS->GetRasterBand(nSelectedBands + 1));
1482 : /* Little trick : we use an offset of 255 and a scaling of 0, so
1483 : * that in areas covered */
1484 : /* by the source, the value of the alpha band will be 255, otherwise
1485 : * it will be 0 */
1486 11 : poVRTBand->AddComplexSource(
1487 : GDALRasterBand::FromHandle(GDALGetRasterBand(hSourceDS, 1)),
1488 : dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1489 11 : dfDstYOff, dfDstXSize, dfDstYSize, 255, 0, VRT_NODATA_UNSET);
1490 : }
1491 2300 : else if (bHasDatasetMask)
1492 : {
1493 : VRTSimpleSource *poSource;
1494 15 : if (bUseSrcMaskBand)
1495 : {
1496 15 : auto poComplexSource = new VRTComplexSource();
1497 15 : poComplexSource->SetUseMaskBand(true);
1498 15 : poSource = poComplexSource;
1499 : }
1500 : else
1501 : {
1502 0 : poSource = new VRTSimpleSource();
1503 : }
1504 15 : if (pszResampling)
1505 4 : poSource->SetResampling(pszResampling);
1506 15 : assert(poMaskVRTBand);
1507 30 : poMaskVRTBand->ConfigureSource(
1508 : poSource,
1509 15 : static_cast<GDALRasterBand *>(GDALGetRasterBand(hSourceDS, 1)),
1510 : TRUE, dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1511 : dfDstYOff, dfDstXSize, dfDstYSize);
1512 :
1513 15 : if (bWriteAbsolutePath)
1514 1 : WriteAbsolutePath(poSource, dsFileName);
1515 :
1516 15 : poMaskVRTBand->AddSource(poSource);
1517 : }
1518 :
1519 2311 : if (bDropRef)
1520 : {
1521 1221 : GDALDereferenceDataset(hSourceDS);
1522 : }
1523 : }
1524 :
1525 2509 : for (int i : anIdxValidDatasets)
1526 : {
1527 2311 : const DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1528 2311 : for (auto oIter = anOverviewFactorsSet.begin();
1529 2320 : oIter != anOverviewFactorsSet.end();)
1530 : {
1531 9 : const int nGlobalOvrFactor = *oIter;
1532 9 : auto oIterNext = oIter;
1533 9 : ++oIterNext;
1534 :
1535 9 : if (psDatasetProperties->nRasterXSize / nGlobalOvrFactor < 128 &&
1536 0 : psDatasetProperties->nRasterYSize / nGlobalOvrFactor < 128)
1537 : {
1538 0 : break;
1539 : }
1540 9 : if (std::find(psDatasetProperties->anOverviewFactors.begin(),
1541 : psDatasetProperties->anOverviewFactors.end(),
1542 9 : nGlobalOvrFactor) ==
1543 18 : psDatasetProperties->anOverviewFactors.end())
1544 : {
1545 0 : anOverviewFactorsSet.erase(oIter);
1546 : }
1547 :
1548 9 : oIter = oIterNext;
1549 : }
1550 : }
1551 201 : if (!anOverviewFactorsSet.empty() &&
1552 3 : CPLTestBool(CPLGetConfigOption("VRT_VIRTUAL_OVERVIEWS", "YES")))
1553 : {
1554 6 : std::vector<int> anOverviewFactors;
1555 3 : anOverviewFactors.insert(anOverviewFactors.end(),
1556 : anOverviewFactorsSet.begin(),
1557 6 : anOverviewFactorsSet.end());
1558 3 : const char *const apszOptions[] = {"VRT_VIRTUAL_OVERVIEWS=YES",
1559 : nullptr};
1560 3 : poVRTDS->BuildOverviews(pszResampling ? pszResampling : "nearest",
1561 3 : static_cast<int>(anOverviewFactors.size()),
1562 3 : &anOverviewFactors[0], 0, nullptr, nullptr,
1563 : nullptr, apszOptions);
1564 : }
1565 198 : }
1566 :
1567 : /************************************************************************/
1568 : /* Build() */
1569 : /************************************************************************/
1570 :
1571 221 : std::unique_ptr<GDALDataset> VRTBuilder::Build(GDALProgressFunc pfnProgress,
1572 : void *pProgressData)
1573 : {
1574 221 : if (bHasRunBuild)
1575 0 : return nullptr;
1576 221 : bHasRunBuild = TRUE;
1577 :
1578 221 : if (pfnProgress == nullptr)
1579 0 : pfnProgress = GDALDummyProgress;
1580 :
1581 221 : bUserExtent = (minX != 0 || minY != 0 || maxX != 0 || maxY != 0);
1582 221 : if (bUserExtent)
1583 : {
1584 13 : if (minX >= maxX || minY >= maxY)
1585 : {
1586 0 : CPLError(CE_Failure, CPLE_IllegalArg, "Invalid user extent");
1587 0 : return nullptr;
1588 : }
1589 : }
1590 :
1591 221 : if (resolutionStrategy == USER_RESOLUTION)
1592 : {
1593 8 : if (we_res <= 0 || ns_res <= 0)
1594 : {
1595 0 : CPLError(CE_Failure, CPLE_IllegalArg, "Invalid user resolution");
1596 0 : return nullptr;
1597 : }
1598 :
1599 : /* We work with negative north-south resolution in all the following
1600 : * code */
1601 8 : ns_res = -ns_res;
1602 : }
1603 : else
1604 : {
1605 213 : we_res = ns_res = 0;
1606 : }
1607 :
1608 221 : asDatasetProperties.resize(nInputFiles);
1609 :
1610 221 : if (pszSrcNoData != nullptr)
1611 : {
1612 6 : if (EQUAL(pszSrcNoData, "none"))
1613 : {
1614 1 : bAllowSrcNoData = FALSE;
1615 : }
1616 : else
1617 : {
1618 5 : char **papszTokens = CSLTokenizeString(pszSrcNoData);
1619 5 : nSrcNoDataCount = CSLCount(papszTokens);
1620 5 : padfSrcNoData = static_cast<double *>(
1621 5 : CPLMalloc(sizeof(double) * nSrcNoDataCount));
1622 12 : for (int i = 0; i < nSrcNoDataCount; i++)
1623 : {
1624 7 : if (!ArgIsNumeric(papszTokens[i]) &&
1625 0 : !EQUAL(papszTokens[i], "nan") &&
1626 7 : !EQUAL(papszTokens[i], "-inf") &&
1627 0 : !EQUAL(papszTokens[i], "inf"))
1628 : {
1629 0 : CPLError(CE_Failure, CPLE_IllegalArg,
1630 : "Invalid -srcnodata value");
1631 0 : CSLDestroy(papszTokens);
1632 0 : return nullptr;
1633 : }
1634 7 : padfSrcNoData[i] = CPLAtofM(papszTokens[i]);
1635 : }
1636 5 : CSLDestroy(papszTokens);
1637 : }
1638 : }
1639 :
1640 221 : if (pszVRTNoData != nullptr)
1641 : {
1642 23 : if (EQUAL(pszVRTNoData, "none"))
1643 : {
1644 1 : bAllowVRTNoData = FALSE;
1645 : }
1646 : else
1647 : {
1648 22 : char **papszTokens = CSLTokenizeString(pszVRTNoData);
1649 22 : nVRTNoDataCount = CSLCount(papszTokens);
1650 22 : padfVRTNoData = static_cast<double *>(
1651 22 : CPLMalloc(sizeof(double) * nVRTNoDataCount));
1652 46 : for (int i = 0; i < nVRTNoDataCount; i++)
1653 : {
1654 24 : if (!ArgIsNumeric(papszTokens[i]) &&
1655 1 : !EQUAL(papszTokens[i], "nan") &&
1656 25 : !EQUAL(papszTokens[i], "-inf") &&
1657 0 : !EQUAL(papszTokens[i], "inf"))
1658 : {
1659 0 : CPLError(CE_Failure, CPLE_IllegalArg,
1660 : "Invalid -vrtnodata value");
1661 0 : CSLDestroy(papszTokens);
1662 0 : return nullptr;
1663 : }
1664 24 : padfVRTNoData[i] = CPLAtofM(papszTokens[i]);
1665 : }
1666 22 : CSLDestroy(papszTokens);
1667 : }
1668 : }
1669 :
1670 221 : bool bFoundValid = false;
1671 2578 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1672 : {
1673 2361 : const char *dsFileName = ppszInputFilenames[i];
1674 :
1675 2361 : if (!pfnProgress(1.0 * (i + 1) / nInputFiles, nullptr, pProgressData))
1676 : {
1677 0 : return nullptr;
1678 : }
1679 :
1680 2361 : GDALDatasetH hDS = (pahSrcDS)
1681 2361 : ? pahSrcDS[i]
1682 1222 : : GDALOpenEx(dsFileName, GDAL_OF_RASTER, nullptr,
1683 1222 : papszOpenOptions, nullptr);
1684 2361 : asDatasetProperties[i].isFileOK = FALSE;
1685 :
1686 2361 : if (hDS)
1687 : {
1688 2359 : const auto osErrorMsg = AnalyseRaster(hDS, &asDatasetProperties[i]);
1689 2359 : if (osErrorMsg.empty())
1690 : {
1691 2348 : asDatasetProperties[i].isFileOK = TRUE;
1692 2348 : bFoundValid = true;
1693 2348 : bFirst = FALSE;
1694 : }
1695 2359 : if (pahSrcDS == nullptr)
1696 1220 : GDALClose(hDS);
1697 2359 : if (!osErrorMsg.empty() && osErrorMsg != "SILENTLY_IGNORE")
1698 : {
1699 11 : if (bStrict)
1700 : {
1701 3 : CPLError(CE_Failure, CPLE_AppDefined, "%s",
1702 : osErrorMsg.c_str());
1703 3 : return nullptr;
1704 : }
1705 : else
1706 : {
1707 8 : CPLError(CE_Warning, CPLE_AppDefined, "%s Skipping %s",
1708 : osErrorMsg.c_str(), dsFileName);
1709 : }
1710 : }
1711 : }
1712 : else
1713 : {
1714 2 : if (bStrict)
1715 : {
1716 1 : CPLError(CE_Failure, CPLE_AppDefined, "Can't open %s.",
1717 : dsFileName);
1718 1 : return nullptr;
1719 : }
1720 : else
1721 : {
1722 1 : CPLError(CE_Warning, CPLE_AppDefined,
1723 : "Can't open %s. Skipping it", dsFileName);
1724 : }
1725 : }
1726 : }
1727 :
1728 217 : if (!bFoundValid)
1729 2 : return nullptr;
1730 :
1731 215 : if (bHasGeoTransform)
1732 : {
1733 214 : if (bTargetAlignedPixels)
1734 : {
1735 2 : minX = floor(minX / we_res) * we_res;
1736 2 : maxX = ceil(maxX / we_res) * we_res;
1737 2 : minY = floor(minY / -ns_res) * -ns_res;
1738 2 : maxY = ceil(maxY / -ns_res) * -ns_res;
1739 : }
1740 :
1741 214 : nRasterXSize = static_cast<int>(0.5 + (maxX - minX) / we_res);
1742 214 : nRasterYSize = static_cast<int>(0.5 + (maxY - minY) / -ns_res);
1743 : }
1744 :
1745 215 : if (nRasterXSize == 0 || nRasterYSize == 0)
1746 : {
1747 0 : CPLError(CE_Failure, CPLE_AppDefined,
1748 : "Computed VRT dimension is invalid. You've probably "
1749 : "specified inappropriate resolution.");
1750 0 : return nullptr;
1751 : }
1752 :
1753 215 : auto poDS = VRTDataset::CreateVRTDataset(pszOutputFilename, nRasterXSize,
1754 : nRasterYSize, 0, GDT_Unknown,
1755 430 : aosCreateOptions.List());
1756 215 : if (!poDS)
1757 : {
1758 0 : return nullptr;
1759 : }
1760 :
1761 215 : if (pszOutputSRS)
1762 : {
1763 1 : poDS->SetProjection(pszOutputSRS);
1764 : }
1765 214 : else if (pszProjectionRef)
1766 : {
1767 214 : poDS->SetProjection(pszProjectionRef);
1768 : }
1769 :
1770 215 : if (bHasGeoTransform)
1771 : {
1772 214 : GDALGeoTransform gt;
1773 214 : gt[GEOTRSFRM_TOPLEFT_X] = minX;
1774 214 : gt[GEOTRSFRM_WE_RES] = we_res;
1775 214 : gt[GEOTRSFRM_ROTATION_PARAM1] = 0;
1776 214 : gt[GEOTRSFRM_TOPLEFT_Y] = maxY;
1777 214 : gt[GEOTRSFRM_ROTATION_PARAM2] = 0;
1778 214 : gt[GEOTRSFRM_NS_RES] = ns_res;
1779 214 : poDS->SetGeoTransform(gt);
1780 : }
1781 :
1782 215 : if (bSeparate)
1783 : {
1784 17 : CreateVRTSeparate(poDS.get());
1785 : }
1786 : else
1787 : {
1788 198 : CreateVRTNonSeparate(poDS.get());
1789 : }
1790 :
1791 215 : return poDS;
1792 : }
1793 :
1794 : /************************************************************************/
1795 : /* add_file_to_list() */
1796 : /************************************************************************/
1797 :
1798 45 : static bool add_file_to_list(const char *filename, const char *tile_index,
1799 : CPLStringList &aosList)
1800 : {
1801 :
1802 45 : if (EQUAL(CPLGetExtensionSafe(filename).c_str(), "SHP"))
1803 : {
1804 : /* Handle gdaltindex Shapefile as a special case */
1805 1 : auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(filename));
1806 1 : if (poDS == nullptr)
1807 : {
1808 0 : CPLError(CE_Failure, CPLE_AppDefined,
1809 : "Unable to open shapefile `%s'.", filename);
1810 0 : return false;
1811 : }
1812 :
1813 1 : auto poLayer = poDS->GetLayer(0);
1814 1 : const auto poFDefn = poLayer->GetLayerDefn();
1815 :
1816 2 : if (poFDefn->GetFieldIndex("LOCATION") >= 0 &&
1817 1 : strcmp("LOCATION", tile_index) != 0)
1818 : {
1819 1 : CPLError(CE_Failure, CPLE_AppDefined,
1820 : "This shapefile seems to be a tile index of "
1821 : "OGR features and not GDAL products.");
1822 : }
1823 1 : const int ti_field = poFDefn->GetFieldIndex(tile_index);
1824 1 : if (ti_field < 0)
1825 : {
1826 0 : CPLError(CE_Failure, CPLE_AppDefined,
1827 : "Unable to find field `%s' in DBF file `%s'.", tile_index,
1828 : filename);
1829 0 : return false;
1830 : }
1831 :
1832 : /* Load in memory existing file names in SHP */
1833 1 : const auto nTileIndexFiles = poLayer->GetFeatureCount(TRUE);
1834 1 : if (nTileIndexFiles == 0)
1835 : {
1836 0 : CPLError(CE_Warning, CPLE_AppDefined,
1837 : "Tile index %s is empty. Skipping it.", filename);
1838 0 : return true;
1839 : }
1840 1 : if (nTileIndexFiles > 100 * 1024 * 1024)
1841 : {
1842 0 : CPLError(CE_Failure, CPLE_AppDefined,
1843 : "Too large feature count in tile index");
1844 0 : return false;
1845 : }
1846 :
1847 5 : for (auto &&poFeature : poLayer)
1848 : {
1849 4 : aosList.AddString(poFeature->GetFieldAsString(ti_field));
1850 : }
1851 : }
1852 : else
1853 : {
1854 44 : aosList.AddString(filename);
1855 : }
1856 :
1857 45 : return true;
1858 : }
1859 :
1860 : /************************************************************************/
1861 : /* GDALBuildVRTOptions */
1862 : /************************************************************************/
1863 :
1864 : /** Options for use with GDALBuildVRT(). GDALBuildVRTOptions* must be allocated
1865 : * and freed with GDALBuildVRTOptionsNew() and GDALBuildVRTOptionsFree()
1866 : * respectively.
1867 : */
1868 : struct GDALBuildVRTOptions
1869 : {
1870 : std::string osProgramName = "gdalbuildvrt";
1871 : std::string osTileIndex = "location";
1872 : bool bStrict = false;
1873 : std::string osResolution{};
1874 : bool bSeparate = false;
1875 : bool bAllowProjectionDifference = false;
1876 : double we_res = 0;
1877 : double ns_res = 0;
1878 : bool bTargetAlignedPixels = false;
1879 : double xmin = 0;
1880 : double ymin = 0;
1881 : double xmax = 0;
1882 : double ymax = 0;
1883 : bool bAddAlpha = false;
1884 : bool bHideNoData = false;
1885 : int nSubdataset = -1;
1886 : std::string osSrcNoData{};
1887 : std::string osVRTNoData{};
1888 : std::string osOutputSRS{};
1889 : std::vector<int> anSelectedBandList{};
1890 : std::string osResampling{};
1891 : CPLStringList aosOpenOptions{};
1892 : CPLStringList aosCreateOptions{};
1893 : bool bUseSrcMaskBand = true;
1894 : bool bNoDataFromMask = false;
1895 : double dfMaskValueThreshold = 0;
1896 : bool bWriteAbsolutePath = false;
1897 : std::string osPixelFunction{};
1898 : CPLStringList aosPixelFunctionArgs{};
1899 :
1900 : /*! allow or suppress progress monitor and other non-error output */
1901 : bool bQuiet = true;
1902 :
1903 : /*! the progress function to use */
1904 : GDALProgressFunc pfnProgress = GDALDummyProgress;
1905 :
1906 : /*! pointer to the progress data variable */
1907 : void *pProgressData = nullptr;
1908 : };
1909 :
1910 : /************************************************************************/
1911 : /* GDALBuildVRT() */
1912 : /************************************************************************/
1913 :
1914 : /* clang-format off */
1915 : /**
1916 : * Build a VRT from a list of datasets.
1917 : *
1918 : * This is the equivalent of the
1919 : * <a href="/programs/gdalbuildvrt.html">gdalbuildvrt</a> utility.
1920 : *
1921 : * GDALBuildVRTOptions* must be allocated and freed with
1922 : * GDALBuildVRTOptionsNew() and GDALBuildVRTOptionsFree() respectively. pahSrcDS
1923 : * and papszSrcDSNames cannot be used at the same time.
1924 : *
1925 : * @param pszDest the destination dataset path.
1926 : * @param nSrcCount the number of input datasets.
1927 : * @param pahSrcDS the list of input datasets (or NULL, exclusive with
1928 : * papszSrcDSNames). For practical purposes, the type
1929 : * of this argument should be considered as "const GDALDatasetH* const*", that
1930 : * is neither the array nor its values are mutated by this function.
1931 : * @param papszSrcDSNames the list of input dataset names (or NULL, exclusive
1932 : * with pahSrcDS)
1933 : * @param psOptionsIn the options struct returned by GDALBuildVRTOptionsNew() or
1934 : * NULL.
1935 : * @param pbUsageError pointer to a integer output variable to store if any
1936 : * usage error has occurred.
1937 : * @return the output dataset (new dataset that must be closed using
1938 : * GDALClose()) or NULL in case of error. If using pahSrcDS, the returned VRT
1939 : * dataset has a reference to each pahSrcDS[] element. Hence pahSrcDS[] elements
1940 : * should be closed after the returned dataset if using GDALClose().
1941 : * A safer alternative is to use GDALReleaseDataset() instead of using
1942 : * GDALClose(), in which case you can close datasets in any order.
1943 :
1944 : *
1945 : * @since GDAL 2.1
1946 : */
1947 : /* clang-format on */
1948 :
1949 222 : GDALDatasetH GDALBuildVRT(const char *pszDest, int nSrcCount,
1950 : GDALDatasetH *pahSrcDS,
1951 : const char *const *papszSrcDSNames,
1952 : const GDALBuildVRTOptions *psOptionsIn,
1953 : int *pbUsageError)
1954 : {
1955 222 : if (pszDest == nullptr)
1956 0 : pszDest = "";
1957 :
1958 222 : if (nSrcCount == 0)
1959 : {
1960 0 : CPLError(CE_Failure, CPLE_AppDefined, "No input dataset specified.");
1961 :
1962 0 : if (pbUsageError)
1963 0 : *pbUsageError = TRUE;
1964 0 : return nullptr;
1965 : }
1966 :
1967 : // cppcheck-suppress unreadVariable
1968 : GDALBuildVRTOptions sOptions(psOptionsIn ? *psOptionsIn
1969 444 : : GDALBuildVRTOptions());
1970 :
1971 8 : if (sOptions.we_res != 0 && sOptions.ns_res != 0 &&
1972 230 : !sOptions.osResolution.empty() &&
1973 0 : !EQUAL(sOptions.osResolution.c_str(), "user"))
1974 : {
1975 0 : CPLError(CE_Failure, CPLE_NotSupported,
1976 : "-tr option is not compatible with -resolution %s",
1977 : sOptions.osResolution.c_str());
1978 0 : if (pbUsageError)
1979 0 : *pbUsageError = TRUE;
1980 0 : return nullptr;
1981 : }
1982 :
1983 222 : if (sOptions.bTargetAlignedPixels && sOptions.we_res == 0 &&
1984 1 : sOptions.ns_res == 0)
1985 : {
1986 1 : CPLError(CE_Failure, CPLE_NotSupported,
1987 : "-tap option cannot be used without using -tr");
1988 1 : if (pbUsageError)
1989 1 : *pbUsageError = TRUE;
1990 1 : return nullptr;
1991 : }
1992 :
1993 221 : if (sOptions.bAddAlpha && sOptions.bSeparate)
1994 : {
1995 0 : CPLError(CE_Failure, CPLE_NotSupported,
1996 : "-addalpha option is not compatible with -separate.");
1997 0 : if (pbUsageError)
1998 0 : *pbUsageError = TRUE;
1999 0 : return nullptr;
2000 : }
2001 :
2002 221 : ResolutionStrategy eStrategy = AVERAGE_RESOLUTION;
2003 258 : if (sOptions.osResolution.empty() ||
2004 37 : EQUAL(sOptions.osResolution.c_str(), "user"))
2005 : {
2006 184 : if (sOptions.we_res != 0 || sOptions.ns_res != 0)
2007 8 : eStrategy = USER_RESOLUTION;
2008 176 : else if (EQUAL(sOptions.osResolution.c_str(), "user"))
2009 : {
2010 0 : CPLError(CE_Failure, CPLE_NotSupported,
2011 : "-tr option must be used with -resolution user.");
2012 0 : if (pbUsageError)
2013 0 : *pbUsageError = TRUE;
2014 0 : return nullptr;
2015 : }
2016 : }
2017 37 : else if (EQUAL(sOptions.osResolution.c_str(), "average"))
2018 1 : eStrategy = AVERAGE_RESOLUTION;
2019 36 : else if (EQUAL(sOptions.osResolution.c_str(), "highest"))
2020 1 : eStrategy = HIGHEST_RESOLUTION;
2021 35 : else if (EQUAL(sOptions.osResolution.c_str(), "lowest"))
2022 1 : eStrategy = LOWEST_RESOLUTION;
2023 34 : else if (EQUAL(sOptions.osResolution.c_str(), "same"))
2024 24 : eStrategy = SAME_RESOLUTION;
2025 10 : else if (EQUAL(sOptions.osResolution.c_str(), "common"))
2026 10 : eStrategy = COMMON_RESOLUTION;
2027 :
2028 : /* If -srcnodata is specified, use it as the -vrtnodata if the latter is not
2029 : */
2030 : /* specified */
2031 221 : if (!sOptions.osSrcNoData.empty() && sOptions.osVRTNoData.empty())
2032 2 : sOptions.osVRTNoData = sOptions.osSrcNoData;
2033 :
2034 : VRTBuilder oBuilder(
2035 221 : sOptions.bStrict, pszDest, nSrcCount, papszSrcDSNames, pahSrcDS,
2036 221 : sOptions.anSelectedBandList.empty()
2037 : ? nullptr
2038 19 : : sOptions.anSelectedBandList.data(),
2039 221 : static_cast<int>(sOptions.anSelectedBandList.size()), eStrategy,
2040 221 : sOptions.we_res, sOptions.ns_res, sOptions.bTargetAlignedPixels,
2041 : sOptions.xmin, sOptions.ymin, sOptions.xmax, sOptions.ymax,
2042 221 : sOptions.bSeparate, sOptions.bAllowProjectionDifference,
2043 221 : sOptions.bAddAlpha, sOptions.bHideNoData, sOptions.nSubdataset,
2044 227 : sOptions.osSrcNoData.empty() ? nullptr : sOptions.osSrcNoData.c_str(),
2045 23 : sOptions.osVRTNoData.empty() ? nullptr : sOptions.osVRTNoData.c_str(),
2046 221 : sOptions.bUseSrcMaskBand, sOptions.bNoDataFromMask,
2047 : sOptions.dfMaskValueThreshold,
2048 222 : sOptions.osOutputSRS.empty() ? nullptr : sOptions.osOutputSRS.c_str(),
2049 236 : sOptions.osResampling.empty() ? nullptr : sOptions.osResampling.c_str(),
2050 221 : sOptions.osPixelFunction.empty() ? nullptr
2051 3 : : sOptions.osPixelFunction.c_str(),
2052 221 : sOptions.aosPixelFunctionArgs, sOptions.aosOpenOptions.List(),
2053 1131 : sOptions.aosCreateOptions, sOptions.bWriteAbsolutePath);
2054 221 : oBuilder.m_osProgramName = sOptions.osProgramName;
2055 :
2056 221 : return GDALDataset::ToHandle(
2057 442 : oBuilder.Build(sOptions.pfnProgress, sOptions.pProgressData).release());
2058 : }
2059 :
2060 : /************************************************************************/
2061 : /* SanitizeSRS */
2062 : /************************************************************************/
2063 :
2064 1 : static char *SanitizeSRS(const char *pszUserInput)
2065 :
2066 : {
2067 : OGRSpatialReferenceH hSRS;
2068 1 : char *pszResult = nullptr;
2069 :
2070 1 : CPLErrorReset();
2071 :
2072 1 : hSRS = OSRNewSpatialReference(nullptr);
2073 1 : if (OSRSetFromUserInput(hSRS, pszUserInput) == OGRERR_NONE)
2074 1 : OSRExportToWkt(hSRS, &pszResult);
2075 : else
2076 : {
2077 0 : CPLError(CE_Failure, CPLE_AppDefined, "Translating SRS failed:\n%s",
2078 : pszUserInput);
2079 : }
2080 :
2081 1 : OSRDestroySpatialReference(hSRS);
2082 :
2083 1 : return pszResult;
2084 : }
2085 :
2086 : /************************************************************************/
2087 : /* GDALBuildVRTOptionsGetParser() */
2088 : /************************************************************************/
2089 :
2090 : static std::unique_ptr<GDALArgumentParser>
2091 225 : GDALBuildVRTOptionsGetParser(GDALBuildVRTOptions *psOptions,
2092 : GDALBuildVRTOptionsForBinary *psOptionsForBinary)
2093 : {
2094 : auto argParser = std::make_unique<GDALArgumentParser>(
2095 225 : "gdalbuildvrt", /* bForBinary=*/psOptionsForBinary != nullptr);
2096 :
2097 225 : argParser->add_description(_("Builds a VRT from a list of datasets."));
2098 :
2099 225 : argParser->add_epilog(_(
2100 : "\n"
2101 : "e.g.\n"
2102 : " % gdalbuildvrt doq_index.vrt doq/*.tif\n"
2103 : " % gdalbuildvrt -input_file_list my_list.txt doq_index.vrt\n"
2104 : "\n"
2105 : "NOTES:\n"
2106 : " o With -separate, each files goes into a separate band in the VRT "
2107 : "band.\n"
2108 : " Otherwise, the files are considered as tiles of a larger mosaic.\n"
2109 : " o -b option selects a band to add into vrt. Multiple bands can be "
2110 : "listed.\n"
2111 : " By default all bands are queried.\n"
2112 : " o The default tile index field is 'location' unless otherwise "
2113 : "specified by\n"
2114 : " -tileindex.\n"
2115 : " o In case the resolution of all input files is not the same, the "
2116 : "-resolution\n"
2117 : " flag enable the user to control the way the output resolution is "
2118 : "computed.\n"
2119 : " Average is the default.\n"
2120 : " o Input files may be any valid GDAL dataset or a GDAL raster tile "
2121 : "index.\n"
2122 : " o For a GDAL raster tile index, all entries will be added to the "
2123 : "VRT.\n"
2124 : " o If one GDAL dataset is made of several subdatasets and has 0 "
2125 : "raster bands,\n"
2126 : " its datasets will be added to the VRT rather than the dataset "
2127 : "itself.\n"
2128 : " Single subdataset could be selected by its number using the -sd "
2129 : "option.\n"
2130 : " o By default, only datasets of same projection and band "
2131 : "characteristics\n"
2132 : " may be added to the VRT.\n"
2133 : "\n"
2134 : "For more details, consult "
2135 225 : "https://gdal.org/programs/gdalbuildvrt.html"));
2136 :
2137 : argParser->add_quiet_argument(
2138 225 : psOptionsForBinary ? &psOptionsForBinary->bQuiet : nullptr);
2139 :
2140 : {
2141 225 : auto &group = argParser->add_mutually_exclusive_group();
2142 :
2143 225 : group.add_argument("-strict")
2144 225 : .flag()
2145 225 : .store_into(psOptions->bStrict)
2146 225 : .help(_("Turn warnings as failures."));
2147 :
2148 225 : group.add_argument("-non_strict")
2149 225 : .flag()
2150 0 : .action([psOptions](const std::string &)
2151 225 : { psOptions->bStrict = false; })
2152 : .help(_("Skip source datasets that have issues with warnings, and "
2153 225 : "continue processing."));
2154 : }
2155 :
2156 225 : argParser->add_argument("-tile_index")
2157 450 : .metavar("<field_name>")
2158 225 : .store_into(psOptions->osTileIndex)
2159 : .help(_("Use the specified value as the tile index field, instead of "
2160 225 : "the default value which is 'location'."));
2161 :
2162 225 : argParser->add_argument("-resolution")
2163 450 : .metavar("user|average|common|highest|lowest|same")
2164 : .action(
2165 226 : [psOptions](const std::string &s)
2166 : {
2167 37 : psOptions->osResolution = s;
2168 37 : if (!EQUAL(psOptions->osResolution.c_str(), "user") &&
2169 37 : !EQUAL(psOptions->osResolution.c_str(), "average") &&
2170 36 : !EQUAL(psOptions->osResolution.c_str(), "highest") &&
2171 35 : !EQUAL(psOptions->osResolution.c_str(), "lowest") &&
2172 84 : !EQUAL(psOptions->osResolution.c_str(), "same") &&
2173 10 : !EQUAL(psOptions->osResolution.c_str(), "common"))
2174 : {
2175 : throw std::invalid_argument(
2176 : CPLSPrintf("Illegal resolution value (%s).",
2177 0 : psOptions->osResolution.c_str()));
2178 : }
2179 262 : })
2180 225 : .help(_("Control the way the output resolution is computed."));
2181 :
2182 225 : argParser->add_argument("-tr")
2183 450 : .metavar("<xres> <yes>")
2184 225 : .nargs(2)
2185 225 : .scan<'g', double>()
2186 225 : .help(_("Set target resolution."));
2187 :
2188 225 : if (psOptionsForBinary)
2189 : {
2190 20 : argParser->add_argument("-input_file_list")
2191 40 : .metavar("<filename>")
2192 : .action(
2193 5 : [psOptions, psOptionsForBinary](const std::string &s)
2194 : {
2195 1 : const char *input_file_list = s.c_str();
2196 : auto f = VSIVirtualHandleUniquePtr(
2197 2 : VSIFOpenL(input_file_list, "r"));
2198 1 : if (f)
2199 : {
2200 : while (1)
2201 : {
2202 5 : const char *filename = CPLReadLineL(f.get());
2203 5 : if (filename == nullptr)
2204 1 : break;
2205 4 : if (!add_file_to_list(
2206 : filename, psOptions->osTileIndex.c_str(),
2207 4 : psOptionsForBinary->aosSrcFiles))
2208 : {
2209 : throw std::invalid_argument(
2210 0 : std::string("Cannot add ")
2211 0 : .append(filename)
2212 0 : .append(" to input file list"));
2213 : }
2214 4 : }
2215 : }
2216 21 : })
2217 20 : .help(_("Text file with an input filename on each line"));
2218 : }
2219 :
2220 : {
2221 225 : auto &group = argParser->add_mutually_exclusive_group();
2222 :
2223 225 : group.add_argument("-separate")
2224 225 : .flag()
2225 225 : .store_into(psOptions->bSeparate)
2226 225 : .help(_("Place each input file into a separate band."));
2227 :
2228 225 : group.add_argument("-pixel-function")
2229 450 : .metavar("<function>")
2230 : .action(
2231 9 : [psOptions](const std::string &s)
2232 : {
2233 : auto *poPixFun =
2234 5 : VRTDerivedRasterBand::GetPixelFunction(s.c_str());
2235 5 : if (poPixFun == nullptr)
2236 : {
2237 : throw std::invalid_argument(
2238 1 : s + " is not a registered pixel function.");
2239 : }
2240 :
2241 4 : psOptions->osPixelFunction = s;
2242 229 : })
2243 :
2244 225 : .help("Function to calculate value from overlapping inputs");
2245 : }
2246 :
2247 225 : argParser->add_argument("-pixel-function-arg")
2248 450 : .metavar("<NAME>=<VALUE>")
2249 225 : .append()
2250 2 : .action([psOptions](const std::string &s)
2251 227 : { psOptions->aosPixelFunctionArgs.AddString(s); })
2252 225 : .help(_("Pixel function argument(s)"));
2253 :
2254 225 : argParser->add_argument("-allow_projection_difference")
2255 225 : .flag()
2256 225 : .store_into(psOptions->bAllowProjectionDifference)
2257 : .help(_("Accept source files not in the same projection (but without "
2258 225 : "reprojecting them!)."));
2259 :
2260 225 : argParser->add_argument("-sd")
2261 450 : .metavar("<n>")
2262 225 : .store_into(psOptions->nSubdataset)
2263 : .help(_("Use subdataset of specified index (starting at 1), instead of "
2264 225 : "the source dataset itself."));
2265 :
2266 225 : argParser->add_argument("-tap")
2267 225 : .flag()
2268 225 : .store_into(psOptions->bTargetAlignedPixels)
2269 : .help(_("Align the coordinates of the extent of the output file to the "
2270 225 : "values of the resolution."));
2271 :
2272 225 : argParser->add_argument("-te")
2273 450 : .metavar("<xmin> <ymin> <xmax> <ymax>")
2274 225 : .nargs(4)
2275 225 : .scan<'g', double>()
2276 225 : .help(_("Set georeferenced extents of output file to be created."));
2277 :
2278 225 : argParser->add_argument("-addalpha")
2279 225 : .flag()
2280 225 : .store_into(psOptions->bAddAlpha)
2281 : .help(_("Adds an alpha mask band to the VRT when the source raster "
2282 225 : "have none."));
2283 :
2284 225 : argParser->add_argument("-b")
2285 450 : .metavar("<band>")
2286 225 : .append()
2287 225 : .store_into(psOptions->anSelectedBandList)
2288 225 : .help(_("Specify input band(s) number."));
2289 :
2290 225 : argParser->add_argument("-hidenodata")
2291 225 : .flag()
2292 225 : .store_into(psOptions->bHideNoData)
2293 225 : .help(_("Makes the VRT band not report the NoData."));
2294 :
2295 225 : if (psOptionsForBinary)
2296 : {
2297 20 : argParser->add_argument("-overwrite")
2298 20 : .flag()
2299 20 : .store_into(psOptionsForBinary->bOverwrite)
2300 20 : .help(_("Overwrite the VRT if it already exists."));
2301 : }
2302 :
2303 225 : argParser->add_argument("-srcnodata")
2304 450 : .metavar("\"<value>[ <value>]...\"")
2305 225 : .store_into(psOptions->osSrcNoData)
2306 225 : .help(_("Set nodata values for input bands."));
2307 :
2308 225 : argParser->add_argument("-vrtnodata")
2309 450 : .metavar("\"<value>[ <value>]...\"")
2310 225 : .store_into(psOptions->osVRTNoData)
2311 225 : .help(_("Set nodata values at the VRT band level."));
2312 :
2313 225 : argParser->add_argument("-a_srs")
2314 450 : .metavar("<srs_def>")
2315 : .action(
2316 2 : [psOptions](const std::string &s)
2317 : {
2318 1 : char *pszSRS = SanitizeSRS(s.c_str());
2319 1 : if (pszSRS == nullptr)
2320 : {
2321 0 : throw std::invalid_argument("Invalid value for -a_srs");
2322 : }
2323 1 : psOptions->osOutputSRS = pszSRS;
2324 1 : CPLFree(pszSRS);
2325 226 : })
2326 225 : .help(_("Override the projection for the output file.."));
2327 :
2328 225 : argParser->add_argument("-r")
2329 450 : .metavar("nearest|bilinear|cubic|cubicspline|lanczos|average|mode")
2330 225 : .store_into(psOptions->osResampling)
2331 225 : .help(_("Resampling algorithm."));
2332 :
2333 225 : argParser->add_open_options_argument(&psOptions->aosOpenOptions);
2334 :
2335 225 : argParser->add_creation_options_argument(psOptions->aosCreateOptions);
2336 :
2337 225 : argParser->add_argument("-write_absolute_path")
2338 225 : .flag()
2339 225 : .store_into(psOptions->bWriteAbsolutePath)
2340 : .help(_("Write the absolute path of the raster files in the tile index "
2341 225 : "file."));
2342 :
2343 225 : argParser->add_argument("-ignore_srcmaskband")
2344 225 : .flag()
2345 0 : .action([psOptions](const std::string &)
2346 225 : { psOptions->bUseSrcMaskBand = false; })
2347 225 : .help(_("Cause mask band of sources will not be taken into account."));
2348 :
2349 225 : argParser->add_argument("-nodata_max_mask_threshold")
2350 450 : .metavar("<threshold>")
2351 225 : .scan<'g', double>()
2352 : .action(
2353 18 : [psOptions](const std::string &s)
2354 : {
2355 9 : psOptions->bNoDataFromMask = true;
2356 9 : psOptions->dfMaskValueThreshold = CPLAtofM(s.c_str());
2357 225 : })
2358 : .help(_("Replaces the value of the source with the value of -vrtnodata "
2359 : "when the value of the mask band of the source is less or "
2360 225 : "equal to the threshold."));
2361 :
2362 225 : argParser->add_argument("-program_name")
2363 225 : .store_into(psOptions->osProgramName)
2364 225 : .hidden();
2365 :
2366 225 : if (psOptionsForBinary)
2367 : {
2368 20 : if (psOptionsForBinary->osDstFilename.empty())
2369 : {
2370 : // We normally go here, unless undocumented -o switch is used
2371 20 : argParser->add_argument("vrt_dataset_name")
2372 40 : .metavar("<vrt_dataset_name>")
2373 20 : .store_into(psOptionsForBinary->osDstFilename)
2374 20 : .help(_("Output VRT."));
2375 : }
2376 :
2377 20 : argParser->add_argument("src_dataset_name")
2378 40 : .metavar("<src_dataset_name>")
2379 20 : .nargs(argparse::nargs_pattern::any)
2380 : .action(
2381 41 : [psOptions, psOptionsForBinary](const std::string &s)
2382 : {
2383 41 : if (!add_file_to_list(s.c_str(),
2384 : psOptions->osTileIndex.c_str(),
2385 41 : psOptionsForBinary->aosSrcFiles))
2386 : {
2387 : throw std::invalid_argument(
2388 0 : std::string("Cannot add ")
2389 0 : .append(s)
2390 0 : .append(" to input file list"));
2391 : }
2392 61 : })
2393 20 : .help(_("Input dataset(s)."));
2394 : }
2395 :
2396 225 : return argParser;
2397 : }
2398 :
2399 : /************************************************************************/
2400 : /* GDALBuildVRTGetParserUsage() */
2401 : /************************************************************************/
2402 :
2403 1 : std::string GDALBuildVRTGetParserUsage()
2404 : {
2405 : try
2406 : {
2407 2 : GDALBuildVRTOptions sOptions;
2408 2 : GDALBuildVRTOptionsForBinary sOptionsForBinary;
2409 : auto argParser =
2410 2 : GDALBuildVRTOptionsGetParser(&sOptions, &sOptionsForBinary);
2411 1 : return argParser->usage();
2412 : }
2413 0 : catch (const std::exception &err)
2414 : {
2415 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
2416 0 : err.what());
2417 0 : return std::string();
2418 : }
2419 : }
2420 :
2421 : /************************************************************************/
2422 : /* GDALBuildVRTOptionsNew() */
2423 : /************************************************************************/
2424 :
2425 : /**
2426 : * Allocates a GDALBuildVRTOptions struct.
2427 : *
2428 : * @param papszArgv NULL terminated list of options (potentially including
2429 : * filename and open options too), or NULL. The accepted options are the ones of
2430 : * the <a href="/programs/gdalbuildvrt.html">gdalbuildvrt</a> utility.
2431 : * @param psOptionsForBinary (output) may be NULL (and should generally be
2432 : * NULL), otherwise (gdalbuildvrt_bin.cpp use case) must be allocated with
2433 : * GDALBuildVRTOptionsForBinaryNew() prior to this function. Will be filled
2434 : * with potentially present filename, open options,...
2435 : * @return pointer to the allocated GDALBuildVRTOptions struct. Must be freed
2436 : * with GDALBuildVRTOptionsFree().
2437 : *
2438 : * @since GDAL 2.1
2439 : */
2440 :
2441 : GDALBuildVRTOptions *
2442 224 : GDALBuildVRTOptionsNew(char **papszArgv,
2443 : GDALBuildVRTOptionsForBinary *psOptionsForBinary)
2444 : {
2445 448 : auto psOptions = std::make_unique<GDALBuildVRTOptions>();
2446 :
2447 448 : CPLStringList aosArgv;
2448 224 : const int nArgc = CSLCount(papszArgv);
2449 1154 : for (int i = 0;
2450 1154 : i < nArgc && papszArgv != nullptr && papszArgv[i] != nullptr; i++)
2451 : {
2452 930 : if (psOptionsForBinary && EQUAL(papszArgv[i], "-o") && i + 1 < nArgc &&
2453 0 : papszArgv[i + 1] != nullptr)
2454 : {
2455 : // Undocumented alternate way of specifying the destination file
2456 0 : psOptionsForBinary->osDstFilename = papszArgv[i + 1];
2457 0 : ++i;
2458 : }
2459 : // argparser will be confused if the value of a string argument
2460 : // starts with a negative sign.
2461 930 : else if (EQUAL(papszArgv[i], "-srcnodata") && i + 1 < nArgc)
2462 : {
2463 6 : ++i;
2464 6 : psOptions->osSrcNoData = papszArgv[i];
2465 : }
2466 : // argparser will be confused if the value of a string argument
2467 : // starts with a negative sign.
2468 924 : else if (EQUAL(papszArgv[i], "-vrtnodata") && i + 1 < nArgc)
2469 : {
2470 21 : ++i;
2471 21 : psOptions->osVRTNoData = papszArgv[i];
2472 : }
2473 :
2474 : else
2475 : {
2476 903 : aosArgv.AddString(papszArgv[i]);
2477 : }
2478 : }
2479 :
2480 : try
2481 : {
2482 : auto argParser =
2483 448 : GDALBuildVRTOptionsGetParser(psOptions.get(), psOptionsForBinary);
2484 :
2485 224 : argParser->parse_args_without_binary_name(aosArgv.List());
2486 :
2487 230 : if (auto adfTargetRes = argParser->present<std::vector<double>>("-tr"))
2488 : {
2489 8 : psOptions->we_res = (*adfTargetRes)[0];
2490 8 : psOptions->ns_res = (*adfTargetRes)[1];
2491 : }
2492 :
2493 235 : if (auto oTE = argParser->present<std::vector<double>>("-te"))
2494 : {
2495 13 : psOptions->xmin = (*oTE)[0];
2496 13 : psOptions->ymin = (*oTE)[1];
2497 13 : psOptions->xmax = (*oTE)[2];
2498 13 : psOptions->ymax = (*oTE)[3];
2499 : }
2500 :
2501 441 : if (psOptions->osPixelFunction.empty() &&
2502 219 : !psOptions->aosPixelFunctionArgs.empty())
2503 : {
2504 : throw std::runtime_error(
2505 1 : "Pixel function arguments provided without a pixel function");
2506 : }
2507 :
2508 221 : return psOptions.release();
2509 : }
2510 3 : catch (const std::exception &err)
2511 : {
2512 3 : CPLError(CE_Failure, CPLE_AppDefined, "%s", err.what());
2513 3 : return nullptr;
2514 : }
2515 : }
2516 :
2517 : /************************************************************************/
2518 : /* GDALBuildVRTOptionsFree() */
2519 : /************************************************************************/
2520 :
2521 : /**
2522 : * Frees the GDALBuildVRTOptions struct.
2523 : *
2524 : * @param psOptions the options struct for GDALBuildVRT().
2525 : *
2526 : * @since GDAL 2.1
2527 : */
2528 :
2529 220 : void GDALBuildVRTOptionsFree(GDALBuildVRTOptions *psOptions)
2530 : {
2531 220 : delete psOptions;
2532 220 : }
2533 :
2534 : /************************************************************************/
2535 : /* GDALBuildVRTOptionsSetProgress() */
2536 : /************************************************************************/
2537 :
2538 : /**
2539 : * Set a progress function.
2540 : *
2541 : * @param psOptions the options struct for GDALBuildVRT().
2542 : * @param pfnProgress the progress callback.
2543 : * @param pProgressData the user data for the progress callback.
2544 : *
2545 : * @since GDAL 2.1
2546 : */
2547 :
2548 20 : void GDALBuildVRTOptionsSetProgress(GDALBuildVRTOptions *psOptions,
2549 : GDALProgressFunc pfnProgress,
2550 : void *pProgressData)
2551 : {
2552 20 : psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
2553 20 : psOptions->pProgressData = pProgressData;
2554 20 : if (pfnProgress == GDALTermProgress)
2555 19 : psOptions->bQuiet = false;
2556 20 : }
|