Coverage Report

Created: 2025-06-13 06:18

/src/gdal/alg/gdalapplyverticalshiftgrid.cpp
Line
Count
Source (jump to first uncovered line)
1
/******************************************************************************
2
 *
3
 * Project:  GDAL algorithms
4
 * Purpose:  Apply vertical shift grid
5
 * Author:   Even Rouault, even.rouault at spatialys.com
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2017, Even Rouault <even.rouault at spatialys.com>
9
 *
10
 * SPDX-License-Identifier: MIT
11
 ****************************************************************************/
12
13
#include "cpl_string.h"
14
#include "gdal.h"
15
#include "gdal_alg.h"
16
#include "gdal_alg_priv.h"
17
#include "gdal_priv.h"
18
#include "gdal_utils.h"
19
#include "gdalwarper.h"
20
#include "vrtdataset.h"
21
#include "ogr_spatialref.h"
22
23
#include "proj.h"
24
25
#include <cmath>
26
#include <limits>
27
28
/************************************************************************/
29
/*                        GDALApplyVSGDataset                           */
30
/************************************************************************/
31
32
class GDALApplyVSGDataset final : public GDALDataset
33
{
34
    friend class GDALApplyVSGRasterBand;
35
36
    GDALDataset *m_poSrcDataset = nullptr;
37
    GDALDataset *m_poReprojectedGrid = nullptr;
38
    bool m_bInverse = false;
39
    double m_dfSrcUnitToMeter = 0.0;
40
    double m_dfDstUnitToMeter = 0.0;
41
42
    CPL_DISALLOW_COPY_ASSIGN(GDALApplyVSGDataset)
43
44
  public:
45
    GDALApplyVSGDataset(GDALDataset *poSrcDataset,
46
                        GDALDataset *poReprojectedGrid, GDALDataType eDT,
47
                        bool bInverse, double dfSrcUnitToMeter,
48
                        double dfDstUnitToMeter, int nBlockSize);
49
    virtual ~GDALApplyVSGDataset();
50
51
    virtual int CloseDependentDatasets() override;
52
53
    virtual CPLErr GetGeoTransform(double *padfGeoTransform) override;
54
    virtual const OGRSpatialReference *GetSpatialRef() const override;
55
56
    bool IsInitOK();
57
};
58
59
/************************************************************************/
60
/*                       GDALApplyVSGRasterBand                         */
61
/************************************************************************/
62
63
class GDALApplyVSGRasterBand final : public GDALRasterBand
64
{
65
    friend class GDALApplyVSGDataset;
66
67
    float *m_pafSrcData = nullptr;
68
    float *m_pafGridData = nullptr;
69
70
    CPL_DISALLOW_COPY_ASSIGN(GDALApplyVSGRasterBand)
71
72
  public:
73
    GDALApplyVSGRasterBand(GDALDataType eDT, int nBlockSize);
74
    virtual ~GDALApplyVSGRasterBand();
75
76
    virtual CPLErr IReadBlock(int nBlockXOff, int nBlockYOff,
77
                              void *pData) override;
78
    virtual double GetNoDataValue(int *pbSuccess) override;
79
};
80
81
/************************************************************************/
82
/*                        GDALApplyVSGDataset()                         */
83
/************************************************************************/
84
85
GDALApplyVSGDataset::GDALApplyVSGDataset(GDALDataset *poSrcDataset,
86
                                         GDALDataset *poReprojectedGrid,
87
                                         GDALDataType eDT, bool bInverse,
88
                                         double dfSrcUnitToMeter,
89
                                         double dfDstUnitToMeter,
90
                                         int nBlockSize)
91
0
    : m_poSrcDataset(poSrcDataset), m_poReprojectedGrid(poReprojectedGrid),
92
0
      m_bInverse(bInverse), m_dfSrcUnitToMeter(dfSrcUnitToMeter),
93
0
      m_dfDstUnitToMeter(dfDstUnitToMeter)
94
0
{
95
0
    m_poSrcDataset->Reference();
96
0
    m_poReprojectedGrid->Reference();
97
98
0
    nRasterXSize = poSrcDataset->GetRasterXSize();
99
0
    nRasterYSize = poSrcDataset->GetRasterYSize();
100
0
    SetBand(1, new GDALApplyVSGRasterBand(eDT, nBlockSize));
101
0
}
102
103
/************************************************************************/
104
/*                       ~GDALApplyVSGDataset()                         */
105
/************************************************************************/
106
107
GDALApplyVSGDataset::~GDALApplyVSGDataset()
108
0
{
109
0
    GDALApplyVSGDataset::CloseDependentDatasets();
110
0
}
111
112
/************************************************************************/
113
/*                     CloseDependentDatasets()                         */
114
/************************************************************************/
115
116
int GDALApplyVSGDataset::CloseDependentDatasets()
117
0
{
118
0
    bool bRet = false;
119
0
    if (m_poSrcDataset != nullptr)
120
0
    {
121
0
        if (m_poSrcDataset->ReleaseRef())
122
0
        {
123
0
            bRet = true;
124
0
        }
125
0
        m_poSrcDataset = nullptr;
126
0
    }
127
0
    if (m_poReprojectedGrid != nullptr)
128
0
    {
129
0
        if (m_poReprojectedGrid->ReleaseRef())
130
0
        {
131
0
            bRet = true;
132
0
        }
133
0
        m_poReprojectedGrid = nullptr;
134
0
    }
135
0
    return bRet;
136
0
}
137
138
/************************************************************************/
139
/*                          GetGeoTransform()                           */
140
/************************************************************************/
141
142
CPLErr GDALApplyVSGDataset::GetGeoTransform(double *padfGeoTransform)
143
0
{
144
0
    return m_poSrcDataset->GetGeoTransform(padfGeoTransform);
145
0
}
146
147
/************************************************************************/
148
/*                          GetSpatialRef()                             */
149
/************************************************************************/
150
151
const OGRSpatialReference *GDALApplyVSGDataset::GetSpatialRef() const
152
0
{
153
0
    return m_poSrcDataset->GetSpatialRef();
154
0
}
155
156
/************************************************************************/
157
/*                             IsInitOK()                               */
158
/************************************************************************/
159
160
bool GDALApplyVSGDataset::IsInitOK()
161
0
{
162
0
    GDALApplyVSGRasterBand *poBand =
163
0
        reinterpret_cast<GDALApplyVSGRasterBand *>(GetRasterBand(1));
164
0
    return poBand->m_pafSrcData != nullptr && poBand->m_pafGridData != nullptr;
165
0
}
166
167
/************************************************************************/
168
/*                       GDALApplyVSGRasterBand()                       */
169
/************************************************************************/
170
171
GDALApplyVSGRasterBand::GDALApplyVSGRasterBand(GDALDataType eDT, int nBlockSize)
172
0
{
173
0
    eDataType = eDT;
174
0
    nBlockXSize = nBlockSize;
175
0
    nBlockYSize = nBlockSize;
176
0
    m_pafSrcData = static_cast<float *>(
177
0
        VSI_MALLOC3_VERBOSE(nBlockXSize, nBlockYSize, sizeof(float)));
178
0
    m_pafGridData = static_cast<float *>(
179
0
        VSI_MALLOC3_VERBOSE(nBlockXSize, nBlockYSize, sizeof(float)));
180
0
}
181
182
/************************************************************************/
183
/*                      ~GDALApplyVSGRasterBand()                       */
184
/************************************************************************/
185
186
GDALApplyVSGRasterBand::~GDALApplyVSGRasterBand()
187
0
{
188
0
    VSIFree(m_pafSrcData);
189
0
    VSIFree(m_pafGridData);
190
0
}
191
192
/************************************************************************/
193
/*                           GetNoDataValue()                           */
194
/************************************************************************/
195
196
double GDALApplyVSGRasterBand::GetNoDataValue(int *pbSuccess)
197
0
{
198
0
    GDALApplyVSGDataset *poGDS = reinterpret_cast<GDALApplyVSGDataset *>(poDS);
199
0
    return poGDS->m_poSrcDataset->GetRasterBand(1)->GetNoDataValue(pbSuccess);
200
0
}
201
202
/************************************************************************/
203
/*                              IReadBlock()                            */
204
/************************************************************************/
205
206
CPLErr GDALApplyVSGRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
207
                                          void *pData)
208
0
{
209
0
    GDALApplyVSGDataset *poGDS = reinterpret_cast<GDALApplyVSGDataset *>(poDS);
210
211
0
    const int nXOff = nBlockXOff * nBlockXSize;
212
0
    const int nReqXSize = (nXOff > nRasterXSize - nBlockXSize)
213
0
                              ? nRasterXSize - nXOff
214
0
                              : nBlockXSize;
215
0
    const int nYOff = nBlockYOff * nBlockYSize;
216
0
    const int nReqYSize = (nYOff > nRasterYSize - nBlockYSize)
217
0
                              ? nRasterYSize - nYOff
218
0
                              : nBlockYSize;
219
220
0
    CPLErr eErr = poGDS->m_poSrcDataset->GetRasterBand(1)->RasterIO(
221
0
        GF_Read, nXOff, nYOff, nReqXSize, nReqYSize, m_pafSrcData, nReqXSize,
222
0
        nReqYSize, GDT_Float32, sizeof(float), nBlockXSize * sizeof(float),
223
0
        nullptr);
224
0
    if (eErr == CE_None)
225
0
        eErr = poGDS->m_poReprojectedGrid->GetRasterBand(1)->RasterIO(
226
0
            GF_Read, nXOff, nYOff, nReqXSize, nReqYSize, m_pafGridData,
227
0
            nReqXSize, nReqYSize, GDT_Float32, sizeof(float),
228
0
            nBlockXSize * sizeof(float), nullptr);
229
0
    if (eErr == CE_None)
230
0
    {
231
0
        const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
232
0
        int bHasNoData = FALSE;
233
0
        float fNoDataValue = static_cast<float>(GetNoDataValue(&bHasNoData));
234
0
        for (int iY = 0; iY < nReqYSize; iY++)
235
0
        {
236
0
            for (int iX = 0; iX < nReqXSize; iX++)
237
0
            {
238
0
                const float fSrcVal = m_pafSrcData[iY * nBlockXSize + iX];
239
0
                const float fGridVal = m_pafGridData[iY * nBlockXSize + iX];
240
0
                if (bHasNoData && fSrcVal == fNoDataValue)
241
0
                {
242
0
                }
243
0
                else if (std::isinf(fGridVal))
244
0
                {
245
0
                    CPLError(CE_Failure, CPLE_AppDefined,
246
0
                             "Missing vertical grid value at source (%d,%d)",
247
0
                             nXOff + iX, nYOff + iY);
248
0
                    return CE_Failure;
249
0
                }
250
0
                else if (poGDS->m_bInverse)
251
0
                {
252
0
                    m_pafSrcData[iY * nBlockXSize + iX] = static_cast<float>(
253
0
                        (fSrcVal * poGDS->m_dfSrcUnitToMeter - fGridVal) /
254
0
                        poGDS->m_dfDstUnitToMeter);
255
0
                }
256
0
                else
257
0
                {
258
0
                    m_pafSrcData[iY * nBlockXSize + iX] = static_cast<float>(
259
0
                        (fSrcVal * poGDS->m_dfSrcUnitToMeter + fGridVal) /
260
0
                        poGDS->m_dfDstUnitToMeter);
261
0
                }
262
0
            }
263
0
            GDALCopyWords(
264
0
                m_pafSrcData + iY * nBlockXSize, GDT_Float32, sizeof(float),
265
0
                static_cast<GByte *>(pData) + iY * nBlockXSize * nDTSize,
266
0
                eDataType, nDTSize, nReqXSize);
267
0
        }
268
0
    }
269
270
0
    return eErr;
271
0
}
272
273
/************************************************************************/
274
/*                      GDALApplyVerticalShiftGrid()                    */
275
/************************************************************************/
276
277
/** Apply a vertical shift grid to a source (DEM typically) dataset.
278
 *
279
 * hGridDataset will typically use WGS84 as horizontal datum (but this is
280
 * not a requirement) and its values are the values to add to go from geoid
281
 * elevations to WGS84 ellipsoidal heights.
282
 *
283
 * hGridDataset will be on-the-fly reprojected and resampled to the projection
284
 * and resolution of hSrcDataset, using bilinear resampling by default.
285
 *
286
 * Both hSrcDataset and hGridDataset must be single band datasets, and have
287
 * a valid geotransform and projection.
288
 *
289
 * On success, a reference will be taken on hSrcDataset and hGridDataset.
290
 * Reference counting semantics on the source and grid datasets should be
291
 * honoured. That is, don't just GDALClose() it, unless it was opened with
292
 * GDALOpenShared(), but rather use GDALReleaseDataset() if wanting to
293
 * immediately release the reference(s) and make the returned dataset the
294
 * owner of them.
295
 *
296
 * Valid use cases:
297
 *
298
 * \code
299
 * hSrcDataset = GDALOpen(...)
300
 * hGridDataset = GDALOpen(...)
301
 * hDstDataset = GDALApplyVerticalShiftGrid(hSrcDataset, hGridDataset, ...)
302
 * GDALReleaseDataset(hSrcDataset);
303
 * GDALReleaseDataset(hGridDataset);
304
 * if( hDstDataset )
305
 * {
306
 *     // Do things with hDstDataset
307
 *     GDALClose(hDstDataset) // will close hSrcDataset and hGridDataset
308
 * }
309
 * \endcode
310
311
 *
312
 * @param hSrcDataset source (DEM) dataset. Must not be NULL.
313
 * @param hGridDataset vertical grid shift dataset. Must not be NULL.
314
 * @param bInverse if set to FALSE, hGridDataset values will be added to
315
 *                 hSrcDataset. If set to TRUE, they will be subtracted.
316
 * @param dfSrcUnitToMeter the factor to convert values from hSrcDataset to
317
 *                         meters (1.0 if source values are in meter).
318
 * @param dfDstUnitToMeter the factor to convert shifted values from meter
319
 *                          (1.0 if output values must be in meter).
320
 * @param papszOptions list of options, or NULL. Supported options are:
321
 * <ul>
322
 * <li>RESAMPLING=NEAREST/BILINEAR/CUBIC. Defaults to BILINEAR.</li>
323
 * <li>MAX_ERROR=val. Maximum error measured in input pixels that is allowed in
324
 * approximating the transformation (0.0 for exact calculations). Defaults
325
 * to 0.125</li>
326
 * <li>DATATYPE=Byte/UInt16/Int16/Float32/Float64. Output data type. If not
327
 * specified will be the same as the one of hSrcDataset.
328
 * <li>ERROR_ON_MISSING_VERT_SHIFT=YES/NO. Whether a missing/nodata value in
329
 * hGridDataset should cause I/O requests to fail. Default is NO (in which case
330
 * 0 will be used)
331
 * <li>SRC_SRS=srs_def. Override projection on hSrcDataset;
332
 * </ul>
333
 *
334
 * @return a new dataset corresponding to hSrcDataset adjusted with
335
 * hGridDataset, or NULL. If not NULL, it must be closed with GDALClose().
336
 *
337
 * @since GDAL 2.2
338
 * @deprecated GDAL 3.4. Will be removed in GDAL 4.0. This function was used
339
 *             by gdalwarp initially, but is no longer needed.
340
 */
341
GDALDatasetH GDALApplyVerticalShiftGrid(GDALDatasetH hSrcDataset,
342
                                        GDALDatasetH hGridDataset, int bInverse,
343
                                        double dfSrcUnitToMeter,
344
                                        double dfDstUnitToMeter,
345
                                        const char *const *papszOptions)
346
0
{
347
0
    VALIDATE_POINTER1(hSrcDataset, "GDALApplyVerticalShiftGrid", nullptr);
348
0
    VALIDATE_POINTER1(hGridDataset, "GDALApplyVerticalShiftGrid", nullptr);
349
350
0
    double adfSrcGT[6];
351
0
    if (GDALGetGeoTransform(hSrcDataset, adfSrcGT) != CE_None)
352
0
    {
353
0
        CPLError(CE_Failure, CPLE_NotSupported,
354
0
                 "Source dataset has no geotransform.");
355
0
        return nullptr;
356
0
    }
357
0
    const char *pszSrcProjection = CSLFetchNameValue(papszOptions, "SRC_SRS");
358
0
    OGRSpatialReference oSrcSRS;
359
0
    if (pszSrcProjection != nullptr && pszSrcProjection[0] != '\0')
360
0
    {
361
0
        oSrcSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
362
0
        oSrcSRS.SetFromUserInput(pszSrcProjection);
363
0
    }
364
0
    else
365
0
    {
366
0
        auto poSRS = GDALDataset::FromHandle(hSrcDataset)->GetSpatialRef();
367
0
        if (poSRS)
368
0
            oSrcSRS = *poSRS;
369
0
    }
370
371
0
    if (oSrcSRS.IsCompound())
372
0
    {
373
0
        oSrcSRS.StripVertical();
374
0
    }
375
376
0
    if (oSrcSRS.IsEmpty())
377
0
    {
378
0
        CPLError(CE_Failure, CPLE_NotSupported,
379
0
                 "Source dataset has no projection.");
380
0
        return nullptr;
381
0
    }
382
0
    if (GDALGetRasterCount(hSrcDataset) != 1)
383
0
    {
384
0
        CPLError(CE_Failure, CPLE_NotSupported,
385
0
                 "Only single band source dataset is supported.");
386
0
        return nullptr;
387
0
    }
388
389
0
    double adfGridGT[6];
390
0
    if (GDALGetGeoTransform(hGridDataset, adfGridGT) != CE_None)
391
0
    {
392
0
        CPLError(CE_Failure, CPLE_NotSupported,
393
0
                 "Grid dataset has no geotransform.");
394
0
        return nullptr;
395
0
    }
396
397
0
    OGRSpatialReferenceH hGridSRS = GDALGetSpatialRef(hGridDataset);
398
0
    if (hGridSRS == nullptr)
399
0
    {
400
0
        CPLError(CE_Failure, CPLE_NotSupported,
401
0
                 "Grid dataset has no projection.");
402
0
        return nullptr;
403
0
    }
404
0
    if (GDALGetRasterCount(hGridDataset) != 1)
405
0
    {
406
0
        CPLError(CE_Failure, CPLE_NotSupported,
407
0
                 "Only single band grid dataset is supported.");
408
0
        return nullptr;
409
0
    }
410
411
0
    GDALDataType eDT = GDALGetRasterDataType(GDALGetRasterBand(hSrcDataset, 1));
412
0
    const char *pszDataType = CSLFetchNameValue(papszOptions, "DATATYPE");
413
0
    if (pszDataType)
414
0
        eDT = GDALGetDataTypeByName(pszDataType);
415
0
    if (eDT == GDT_Unknown)
416
0
    {
417
0
        CPLError(CE_Failure, CPLE_NotSupported, "Invalid DATATYPE=%s",
418
0
                 pszDataType);
419
0
        return nullptr;
420
0
    }
421
422
0
    const int nSrcXSize = GDALGetRasterXSize(hSrcDataset);
423
0
    const int nSrcYSize = GDALGetRasterYSize(hSrcDataset);
424
425
0
    double dfWestLongitudeDeg = 0.0;
426
0
    double dfSouthLatitudeDeg = 0.0;
427
0
    double dfEastLongitudeDeg = 0.0;
428
0
    double dfNorthLatitudeDeg = 0.0;
429
0
    GDALComputeAreaOfInterest(&oSrcSRS, adfSrcGT, nSrcXSize, nSrcYSize,
430
0
                              dfWestLongitudeDeg, dfSouthLatitudeDeg,
431
0
                              dfEastLongitudeDeg, dfNorthLatitudeDeg);
432
433
0
    CPLStringList aosOptions;
434
0
    if (!(dfWestLongitudeDeg == 0.0 && dfSouthLatitudeDeg == 0.0 &&
435
0
          dfEastLongitudeDeg == 0.0 && dfNorthLatitudeDeg == 0.0))
436
0
    {
437
0
        aosOptions.SetNameValue(
438
0
            "AREA_OF_INTEREST",
439
0
            CPLSPrintf("%.16g,%.16g,%.16g,%.16g", dfWestLongitudeDeg,
440
0
                       dfSouthLatitudeDeg, dfEastLongitudeDeg,
441
0
                       dfNorthLatitudeDeg));
442
0
    }
443
0
    void *hTransform = GDALCreateGenImgProjTransformer4(
444
0
        hGridSRS, adfGridGT, OGRSpatialReference::ToHandle(&oSrcSRS), adfSrcGT,
445
0
        aosOptions.List());
446
0
    if (hTransform == nullptr)
447
0
        return nullptr;
448
0
    GDALWarpOptions *psWO = GDALCreateWarpOptions();
449
0
    psWO->hSrcDS = hGridDataset;
450
0
    psWO->eResampleAlg = GRA_Bilinear;
451
0
    const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
452
0
    if (pszResampling)
453
0
    {
454
0
        if (EQUAL(pszResampling, "NEAREST"))
455
0
            psWO->eResampleAlg = GRA_NearestNeighbour;
456
0
        else if (EQUAL(pszResampling, "BILINEAR"))
457
0
            psWO->eResampleAlg = GRA_Bilinear;
458
0
        else if (EQUAL(pszResampling, "CUBIC"))
459
0
            psWO->eResampleAlg = GRA_Cubic;
460
0
    }
461
0
    psWO->eWorkingDataType = GDT_Float32;
462
0
    int bHasNoData = FALSE;
463
0
    const double dfSrcNoData = GDALGetRasterNoDataValue(
464
0
        GDALGetRasterBand(hGridDataset, 1), &bHasNoData);
465
0
    if (bHasNoData)
466
0
    {
467
0
        psWO->padfSrcNoDataReal =
468
0
            static_cast<double *>(CPLMalloc(sizeof(double)));
469
0
        psWO->padfSrcNoDataReal[0] = dfSrcNoData;
470
0
    }
471
472
0
    psWO->padfDstNoDataReal = static_cast<double *>(CPLMalloc(sizeof(double)));
473
0
    const bool bErrorOnMissingShift =
474
0
        CPLFetchBool(papszOptions, "ERROR_ON_MISSING_VERT_SHIFT", false);
475
0
    psWO->padfDstNoDataReal[0] =
476
0
        (bErrorOnMissingShift) ? -std::numeric_limits<float>::infinity() : 0.0;
477
0
    psWO->papszWarpOptions =
478
0
        CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "NO_DATA");
479
480
0
    psWO->pfnTransformer = GDALGenImgProjTransform;
481
0
    psWO->pTransformerArg = hTransform;
482
0
    const double dfMaxError =
483
0
        CPLAtof(CSLFetchNameValueDef(papszOptions, "MAX_ERROR", "0.125"));
484
0
    if (dfMaxError > 0.0)
485
0
    {
486
0
        psWO->pTransformerArg = GDALCreateApproxTransformer(
487
0
            psWO->pfnTransformer, psWO->pTransformerArg, dfMaxError);
488
0
        psWO->pfnTransformer = GDALApproxTransform;
489
0
        GDALApproxTransformerOwnsSubtransformer(psWO->pTransformerArg, TRUE);
490
0
    }
491
0
    psWO->nBandCount = 1;
492
0
    psWO->panSrcBands = static_cast<int *>(CPLMalloc(sizeof(int)));
493
0
    psWO->panSrcBands[0] = 1;
494
0
    psWO->panDstBands = static_cast<int *>(CPLMalloc(sizeof(int)));
495
0
    psWO->panDstBands[0] = 1;
496
497
0
    VRTWarpedDataset *poReprojectedGrid =
498
0
        new VRTWarpedDataset(nSrcXSize, nSrcYSize);
499
    // This takes a reference on hGridDataset
500
0
    CPLErr eErr = poReprojectedGrid->Initialize(psWO);
501
0
    CPLAssert(eErr == CE_None);
502
0
    CPL_IGNORE_RET_VAL(eErr);
503
0
    GDALDestroyWarpOptions(psWO);
504
0
    poReprojectedGrid->SetGeoTransform(adfSrcGT);
505
0
    poReprojectedGrid->AddBand(GDT_Float32, nullptr);
506
507
0
    GDALApplyVSGDataset *poOutDS = new GDALApplyVSGDataset(
508
0
        GDALDataset::FromHandle(hSrcDataset), poReprojectedGrid, eDT,
509
0
        CPL_TO_BOOL(bInverse), dfSrcUnitToMeter, dfDstUnitToMeter,
510
        // Undocumented option. For testing only
511
0
        atoi(CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256")));
512
513
0
    poReprojectedGrid->ReleaseRef();
514
515
0
    if (!poOutDS->IsInitOK())
516
0
    {
517
0
        delete poOutDS;
518
0
        return nullptr;
519
0
    }
520
0
    poOutDS->SetDescription(GDALGetDescription(hSrcDataset));
521
0
    return reinterpret_cast<GDALDatasetH>(poOutDS);
522
0
}
523
524
/************************************************************************/
525
/*                           GetProj4Filename()                         */
526
/************************************************************************/
527
528
static CPLString GetProj4Filename(const char *pszFilename)
529
0
{
530
0
    CPLString osFilename;
531
532
    /* or fixed path: /name, ./name or ../name */
533
0
    if (!CPLIsFilenameRelative(pszFilename) || *pszFilename == '.')
534
0
    {
535
0
        return pszFilename;
536
0
    }
537
538
0
    PJ_GRID_INFO info = proj_grid_info(pszFilename);
539
0
    if (info.filename[0])
540
0
    {
541
0
        osFilename = info.filename;
542
0
    }
543
544
0
    return osFilename;
545
0
}
546
547
/************************************************************************/
548
/*                       GDALOpenVerticalShiftGrid()                    */
549
/************************************************************************/
550
551
/** Load proj.4 geoidgrids as GDAL dataset
552
 *
553
 * @param pszProj4Geoidgrids Value of proj.4 geoidgrids parameter.
554
 * @param pbError If not NULL, the pointed value will be set to TRUE if an
555
 *                error occurred.
556
 *
557
 * @return a dataset. If not NULL, it must be closed with GDALClose().
558
 *
559
 * @since GDAL 2.2
560
 * @deprecated GDAL 3.4. Will be removed in GDAL 4.0. This function was used
561
 *             by gdalwarp initially, but is no longer needed.
562
 */
563
GDALDatasetH GDALOpenVerticalShiftGrid(const char *pszProj4Geoidgrids,
564
                                       int *pbError)
565
0
{
566
0
    char **papszGrids = CSLTokenizeString2(pszProj4Geoidgrids, ",", 0);
567
0
    const int nGridCount = CSLCount(papszGrids);
568
0
    if (nGridCount == 1)
569
0
    {
570
0
        CSLDestroy(papszGrids);
571
572
0
        bool bMissingOk = false;
573
0
        if (*pszProj4Geoidgrids == '@')
574
0
        {
575
0
            pszProj4Geoidgrids++;
576
0
            bMissingOk = true;
577
0
        }
578
0
        const CPLString osFilename(GetProj4Filename(pszProj4Geoidgrids));
579
0
        const char *const papszOpenOptions[] = {
580
0
            "@SHIFT_ORIGIN_IN_MINUS_180_PLUS_180=YES", nullptr};
581
0
        GDALDatasetH hDS =
582
0
            GDALOpenEx(osFilename, 0, nullptr, papszOpenOptions, nullptr);
583
0
        if (hDS == nullptr)
584
0
        {
585
0
            CPLDebug("GDAL", "Cannot find file corresponding to %s",
586
0
                     pszProj4Geoidgrids);
587
0
        }
588
0
        if (pbError)
589
0
            *pbError = (!bMissingOk && hDS == nullptr);
590
0
        return hDS;
591
0
    }
592
593
0
    CPLStringList aosFilenames;
594
0
    for (int i = nGridCount - 1; i >= 0; i--)
595
0
    {
596
0
        const char *pszName = papszGrids[i];
597
0
        bool bMissingOk = false;
598
0
        if (*pszName == '@')
599
0
        {
600
0
            pszName++;
601
0
            bMissingOk = true;
602
0
        }
603
0
        const CPLString osFilename(GetProj4Filename(pszName));
604
0
        VSIStatBufL sStat;
605
0
        if (osFilename.empty() || VSIStatL(osFilename, &sStat) != 0)
606
0
        {
607
0
            CPLDebug("GDAL", "Cannot find file corresponding to %s", pszName);
608
0
            if (!bMissingOk)
609
0
            {
610
0
                if (pbError)
611
0
                    *pbError = true;
612
0
                CSLDestroy(papszGrids);
613
0
                return nullptr;
614
0
            }
615
0
        }
616
0
        else
617
0
        {
618
0
            aosFilenames.AddString(osFilename);
619
0
        }
620
0
    }
621
622
0
    CSLDestroy(papszGrids);
623
624
0
    if (aosFilenames.empty())
625
0
    {
626
0
        if (pbError)
627
0
            *pbError = false;
628
0
        return nullptr;
629
0
    }
630
631
0
    char **papszArgv = nullptr;
632
0
    papszArgv = CSLAddString(papszArgv, "-resolution");
633
0
    papszArgv = CSLAddString(papszArgv, "highest");
634
0
    papszArgv = CSLAddString(papszArgv, "-vrtnodata");
635
0
    papszArgv = CSLAddString(papszArgv, "-inf");
636
0
    papszArgv = CSLAddString(papszArgv, "-oo");
637
0
    papszArgv =
638
0
        CSLAddString(papszArgv, "@SHIFT_ORIGIN_IN_MINUS_180_PLUS_180=YES");
639
0
    GDALBuildVRTOptions *psOptions = GDALBuildVRTOptionsNew(papszArgv, nullptr);
640
0
    CSLDestroy(papszArgv);
641
0
    GDALDatasetH hDS = GDALBuildVRT("", aosFilenames.size(), nullptr,
642
0
                                    aosFilenames.List(), psOptions, nullptr);
643
0
    GDALBuildVRTOptionsFree(psOptions);
644
0
    if (pbError)
645
0
        *pbError = hDS != nullptr;
646
0
    return hDS;
647
0
}