Coverage Report

Created: 2026-08-31 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PROJ/src/iso19111/io.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  PROJ
4
 * Purpose:  ISO19111:2019 implementation
5
 * Author:   Even Rouault <even dot rouault at spatialys dot com>
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com>
9
 *
10
 * Permission is hereby granted, free of charge, to any person obtaining a
11
 * copy of this software and associated documentation files (the "Software"),
12
 * to deal in the Software without restriction, including without limitation
13
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14
 * and/or sell copies of the Software, and to permit persons to whom the
15
 * Software is furnished to do so, subject to the following conditions:
16
 *
17
 * The above copyright notice and this permission notice shall be included
18
 * in all copies or substantial portions of the Software.
19
 *
20
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26
 * DEALINGS IN THE SOFTWARE.
27
 ****************************************************************************/
28
29
#ifndef FROM_PROJ_CPP
30
#define FROM_PROJ_CPP
31
#endif
32
33
#include <algorithm>
34
#include <cassert>
35
#include <cctype>
36
#include <cmath>
37
#include <cstring>
38
#include <limits>
39
#include <list>
40
#include <locale>
41
#include <map>
42
#include <set>
43
#include <sstream> // std::istringstream
44
#include <string>
45
#include <utility>
46
#include <vector>
47
48
#include "proj/common.hpp"
49
#include "proj/coordinateoperation.hpp"
50
#include "proj/coordinates.hpp"
51
#include "proj/coordinatesystem.hpp"
52
#include "proj/crs.hpp"
53
#include "proj/datum.hpp"
54
#include "proj/io.hpp"
55
#include "proj/metadata.hpp"
56
#include "proj/util.hpp"
57
58
#include "operation/coordinateoperation_internal.hpp"
59
#include "operation/esriparammappings.hpp"
60
#include "operation/oputils.hpp"
61
#include "operation/parammappings.hpp"
62
63
#include "proj/internal/coordinatesystem_internal.hpp"
64
#include "proj/internal/datum_internal.hpp"
65
#include "proj/internal/internal.hpp"
66
#include "proj/internal/io_internal.hpp"
67
68
#include "proj/internal/include_nlohmann_json.hpp"
69
70
#include "proj_constants.h"
71
72
#include "proj_json_streaming_writer.hpp"
73
#include "wkt1_parser.h"
74
#include "wkt2_parser.h"
75
76
// PROJ include order is sensitive
77
// clang-format off
78
#include "proj.h"
79
#include "proj_internal.h"
80
// clang-format on
81
82
using namespace NS_PROJ::common;
83
using namespace NS_PROJ::coordinates;
84
using namespace NS_PROJ::crs;
85
using namespace NS_PROJ::cs;
86
using namespace NS_PROJ::datum;
87
using namespace NS_PROJ::internal;
88
using namespace NS_PROJ::metadata;
89
using namespace NS_PROJ::operation;
90
using namespace NS_PROJ::util;
91
92
using json = nlohmann::json;
93
94
//! @cond Doxygen_Suppress
95
static const std::string emptyString{};
96
//! @endcond
97
98
#if 0
99
namespace dropbox{ namespace oxygen {
100
template<> nn<NS_PROJ::io::DatabaseContextPtr>::~nn() = default;
101
template<> nn<NS_PROJ::io::AuthorityFactoryPtr>::~nn() = default;
102
template<> nn<std::shared_ptr<NS_PROJ::io::IPROJStringExportable>>::~nn() = default;
103
template<> nn<std::unique_ptr<NS_PROJ::io::PROJStringFormatter, std::default_delete<NS_PROJ::io::PROJStringFormatter> > >::~nn() = default;
104
template<> nn<std::unique_ptr<NS_PROJ::io::WKTFormatter, std::default_delete<NS_PROJ::io::WKTFormatter> > >::~nn() = default;
105
template<> nn<std::unique_ptr<NS_PROJ::io::WKTNode, std::default_delete<NS_PROJ::io::WKTNode> > >::~nn() = default;
106
}}
107
#endif
108
109
NS_PROJ_START
110
namespace io {
111
112
//! @cond Doxygen_Suppress
113
const char *JSONFormatter::PROJJSON_v0_7 =
114
    "https://proj.org/schemas/v0.7/projjson.schema.json";
115
116
#define PROJJSON_DEFAULT_VERSION JSONFormatter::PROJJSON_v0_7
117
118
//! @endcond
119
120
// ---------------------------------------------------------------------------
121
122
//! @cond Doxygen_Suppress
123
13.6M
IWKTExportable::~IWKTExportable() = default;
124
125
// ---------------------------------------------------------------------------
126
127
0
std::string IWKTExportable::exportToWKT(WKTFormatter *formatter) const {
128
0
    _exportToWKT(formatter);
129
0
    return formatter->toString();
130
0
}
131
132
//! @endcond
133
134
// ---------------------------------------------------------------------------
135
136
//! @cond Doxygen_Suppress
137
struct WKTFormatter::Private {
138
    struct Params {
139
        WKTFormatter::Convention convention_ = WKTFormatter::Convention::WKT2;
140
        WKTFormatter::Version version_ = WKTFormatter::Version::WKT2;
141
        bool multiLine_ = true;
142
        bool strict_ = true;
143
        int indentWidth_ = 4;
144
        bool idOnTopLevelOnly_ = false;
145
        bool outputAxisOrder_ = false;
146
        bool primeMeridianOmittedIfGreenwich_ = false;
147
        bool ellipsoidUnitOmittedIfMetre_ = false;
148
        bool primeMeridianOrParameterUnitOmittedIfSameAsAxis_ = false;
149
        bool forceUNITKeyword_ = false;
150
        bool outputCSUnitOnlyOnceIfSame_ = false;
151
        bool primeMeridianInDegree_ = false;
152
        bool use2019Keywords_ = false;
153
        bool useESRIDialect_ = false;
154
        bool allowEllipsoidalHeightAsVerticalCRS_ = false;
155
        bool allowLINUNITNode_ = false;
156
        OutputAxisRule outputAxis_ = WKTFormatter::OutputAxisRule::YES;
157
    };
158
    Params params_{};
159
    DatabaseContextPtr dbContext_{};
160
161
    int indentLevel_ = 0;
162
    int level_ = 0;
163
    std::vector<bool> stackHasChild_{};
164
    std::vector<bool> stackHasId_{false};
165
    std::vector<bool> stackEmptyKeyword_{};
166
    std::vector<bool> stackDisableUsage_{};
167
    std::vector<bool> outputUnitStack_{true};
168
    std::vector<bool> outputIdStack_{true};
169
    std::vector<UnitOfMeasureNNPtr> axisLinearUnitStack_{
170
        util::nn_make_shared<UnitOfMeasure>(UnitOfMeasure::METRE)};
171
    std::vector<UnitOfMeasureNNPtr> axisAngularUnitStack_{
172
        util::nn_make_shared<UnitOfMeasure>(UnitOfMeasure::DEGREE)};
173
    bool abridgedTransformation_ = false;
174
    bool useDerivingConversion_ = false;
175
    std::vector<double> toWGS84Parameters_{};
176
    std::string hDatumExtension_{};
177
    std::string vDatumExtension_{};
178
    crs::GeographicCRSPtr geogCRSOfCompoundCRS_{};
179
    std::string result_{};
180
181
    // cppcheck-suppress functionStatic
182
    void addNewLine();
183
    void addIndentation();
184
    // cppcheck-suppress functionStatic
185
    void startNewChild();
186
};
187
//! @endcond
188
189
// ---------------------------------------------------------------------------
190
191
/** \brief Constructs a new formatter.
192
 *
193
 * A formatter can be used only once (its internal state is mutated)
194
 *
195
 * Its default behavior can be adjusted with the different setters.
196
 *
197
 * @param convention WKT flavor. Defaults to Convention::WKT2
198
 * @param dbContext Database context, to allow queries in it if needed.
199
 * This is used for example for WKT1_ESRI output to do name substitutions.
200
 *
201
 * @return new formatter.
202
 */
203
WKTFormatterNNPtr WKTFormatter::create(Convention convention,
204
                                       // cppcheck-suppress passedByValue
205
0
                                       DatabaseContextPtr dbContext) {
206
0
    auto ret = NN_NO_CHECK(WKTFormatter::make_unique<WKTFormatter>(convention));
207
0
    ret->d->dbContext_ = std::move(dbContext);
208
0
    return ret;
209
0
}
210
211
// ---------------------------------------------------------------------------
212
213
/** \brief Constructs a new formatter from another one.
214
 *
215
 * A formatter can be used only once (its internal state is mutated)
216
 *
217
 * Its default behavior can be adjusted with the different setters.
218
 *
219
 * @param other source formatter.
220
 * @return new formatter.
221
 */
222
0
WKTFormatterNNPtr WKTFormatter::create(const WKTFormatterNNPtr &other) {
223
0
    auto f = create(other->d->params_.convention_, other->d->dbContext_);
224
0
    f->d->params_ = other->d->params_;
225
0
    return f;
226
0
}
227
228
// ---------------------------------------------------------------------------
229
230
//! @cond Doxygen_Suppress
231
0
WKTFormatter::~WKTFormatter() = default;
232
//! @endcond
233
234
// ---------------------------------------------------------------------------
235
236
/** \brief Whether to use multi line output or not. */
237
0
WKTFormatter &WKTFormatter::setMultiLine(bool multiLine) noexcept {
238
0
    d->params_.multiLine_ = multiLine;
239
0
    return *this;
240
0
}
241
242
// ---------------------------------------------------------------------------
243
244
/** \brief Set number of spaces for each indentation level (defaults to 4).
245
 */
246
0
WKTFormatter &WKTFormatter::setIndentationWidth(int width) noexcept {
247
0
    d->params_.indentWidth_ = width;
248
0
    return *this;
249
0
}
250
251
// ---------------------------------------------------------------------------
252
253
/** \brief Set whether AXIS nodes should be output.
254
 */
255
WKTFormatter &
256
0
WKTFormatter::setOutputAxis(OutputAxisRule outputAxisIn) noexcept {
257
0
    d->params_.outputAxis_ = outputAxisIn;
258
0
    return *this;
259
0
}
260
261
// ---------------------------------------------------------------------------
262
263
/** \brief Set whether the formatter should operate on strict more or not.
264
 *
265
 * The default is strict mode, in which case a FormattingException can be
266
 * thrown.
267
 * In non-strict mode, a Geographic 3D CRS can be for example exported as
268
 * WKT1_GDAL with 3 axes, whereas this is normally not allowed.
269
 */
270
0
WKTFormatter &WKTFormatter::setStrict(bool strictIn) noexcept {
271
0
    d->params_.strict_ = strictIn;
272
0
    return *this;
273
0
}
274
275
// ---------------------------------------------------------------------------
276
277
/** \brief Returns whether the formatter is in strict mode. */
278
0
bool WKTFormatter::isStrict() const noexcept { return d->params_.strict_; }
279
280
// ---------------------------------------------------------------------------
281
282
/** \brief Set whether the formatter should export, in WKT1, a Geographic or
283
 * Projected 3D CRS as a compound CRS whose vertical part represents an
284
 * ellipsoidal height.
285
 */
286
WKTFormatter &
287
0
WKTFormatter::setAllowEllipsoidalHeightAsVerticalCRS(bool allow) noexcept {
288
0
    d->params_.allowEllipsoidalHeightAsVerticalCRS_ = allow;
289
0
    return *this;
290
0
}
291
292
// ---------------------------------------------------------------------------
293
294
/** \brief Return whether the formatter should export, in WKT1, a Geographic or
295
 * Projected 3D CRS as a compound CRS whose vertical part represents an
296
 * ellipsoidal height.
297
 */
298
0
bool WKTFormatter::isAllowedEllipsoidalHeightAsVerticalCRS() const noexcept {
299
0
    return d->params_.allowEllipsoidalHeightAsVerticalCRS_;
300
0
}
301
302
// ---------------------------------------------------------------------------
303
304
/** \brief Set whether the formatter should export, in WKT1_ESRI, a Geographic
305
 * 3D CRS with the relatively new (ArcGIS Pro >= 2.7) LINUNIT node.
306
 * Defaults to true.
307
 * @since PROJ 9.1
308
 */
309
0
WKTFormatter &WKTFormatter::setAllowLINUNITNode(bool allow) noexcept {
310
0
    d->params_.allowLINUNITNode_ = allow;
311
0
    return *this;
312
0
}
313
314
// ---------------------------------------------------------------------------
315
316
/** \brief Return whether the formatter should export, in WKT1_ESRI, a
317
 * Geographic 3D CRS with the relatively new (ArcGIS Pro >= 2.7) LINUNIT node.
318
 * Defaults to true.
319
 * @since PROJ 9.1
320
 */
321
0
bool WKTFormatter::isAllowedLINUNITNode() const noexcept {
322
0
    return d->params_.allowLINUNITNode_;
323
0
}
324
325
// ---------------------------------------------------------------------------
326
327
/** Returns the WKT string from the formatter. */
328
0
const std::string &WKTFormatter::toString() const {
329
0
    if (d->indentLevel_ > 0 || d->level_ > 0) {
330
        // For intermediary nodes, the formatter is in a inconsistent
331
        // state.
332
0
        throw FormattingException("toString() called on intermediate nodes");
333
0
    }
334
0
    if (d->axisLinearUnitStack_.size() != 1)
335
0
        throw FormattingException(
336
0
            "Unbalanced pushAxisLinearUnit() / popAxisLinearUnit()");
337
0
    if (d->axisAngularUnitStack_.size() != 1)
338
0
        throw FormattingException(
339
0
            "Unbalanced pushAxisAngularUnit() / popAxisAngularUnit()");
340
0
    if (d->outputIdStack_.size() != 1)
341
0
        throw FormattingException("Unbalanced pushOutputId() / popOutputId()");
342
0
    if (d->outputUnitStack_.size() != 1)
343
0
        throw FormattingException(
344
0
            "Unbalanced pushOutputUnit() / popOutputUnit()");
345
0
    if (d->stackHasId_.size() != 1)
346
0
        throw FormattingException("Unbalanced pushHasId() / popHasId()");
347
0
    if (!d->stackDisableUsage_.empty())
348
0
        throw FormattingException(
349
0
            "Unbalanced pushDisableUsage() / popDisableUsage()");
350
351
0
    return d->result_;
352
0
}
353
354
//! @cond Doxygen_Suppress
355
356
// ---------------------------------------------------------------------------
357
358
WKTFormatter::WKTFormatter(Convention convention)
359
0
    : d(std::make_unique<Private>()) {
360
0
    d->params_.convention_ = convention;
361
0
    switch (convention) {
362
0
    case Convention::WKT2_2019:
363
0
        d->params_.use2019Keywords_ = true;
364
0
        PROJ_FALLTHROUGH;
365
0
    case Convention::WKT2:
366
0
        d->params_.version_ = WKTFormatter::Version::WKT2;
367
0
        d->params_.outputAxisOrder_ = true;
368
0
        break;
369
370
0
    case Convention::WKT2_2019_SIMPLIFIED:
371
0
        d->params_.use2019Keywords_ = true;
372
0
        PROJ_FALLTHROUGH;
373
0
    case Convention::WKT2_SIMPLIFIED:
374
0
        d->params_.version_ = WKTFormatter::Version::WKT2;
375
0
        d->params_.idOnTopLevelOnly_ = true;
376
0
        d->params_.outputAxisOrder_ = false;
377
0
        d->params_.primeMeridianOmittedIfGreenwich_ = true;
378
0
        d->params_.ellipsoidUnitOmittedIfMetre_ = true;
379
0
        d->params_.primeMeridianOrParameterUnitOmittedIfSameAsAxis_ = true;
380
0
        d->params_.forceUNITKeyword_ = true;
381
0
        d->params_.outputCSUnitOnlyOnceIfSame_ = true;
382
0
        break;
383
384
0
    case Convention::WKT1_GDAL:
385
0
        d->params_.version_ = WKTFormatter::Version::WKT1;
386
0
        d->params_.outputAxisOrder_ = false;
387
0
        d->params_.forceUNITKeyword_ = true;
388
0
        d->params_.primeMeridianInDegree_ = true;
389
0
        d->params_.outputAxis_ =
390
0
            WKTFormatter::OutputAxisRule::WKT1_GDAL_EPSG_STYLE;
391
0
        break;
392
393
0
    case Convention::WKT1_ESRI:
394
0
        d->params_.version_ = WKTFormatter::Version::WKT1;
395
0
        d->params_.outputAxisOrder_ = false;
396
0
        d->params_.forceUNITKeyword_ = true;
397
0
        d->params_.primeMeridianInDegree_ = true;
398
0
        d->params_.useESRIDialect_ = true;
399
0
        d->params_.multiLine_ = false;
400
0
        d->params_.outputAxis_ = WKTFormatter::OutputAxisRule::NO;
401
0
        d->params_.allowLINUNITNode_ = true;
402
0
        break;
403
404
0
    default:
405
0
        assert(false);
406
0
        break;
407
0
    }
408
0
}
409
410
// ---------------------------------------------------------------------------
411
412
0
WKTFormatter &WKTFormatter::setOutputId(bool outputIdIn) {
413
0
    if (d->indentLevel_ != 0) {
414
0
        throw Exception(
415
0
            "setOutputId() shall only be called when the stack state is empty");
416
0
    }
417
0
    d->outputIdStack_[0] = outputIdIn;
418
0
    return *this;
419
0
}
420
421
// ---------------------------------------------------------------------------
422
423
0
void WKTFormatter::Private::addNewLine() { result_ += '\n'; }
424
425
// ---------------------------------------------------------------------------
426
427
0
void WKTFormatter::Private::addIndentation() {
428
0
    result_ += std::string(
429
0
        static_cast<size_t>(indentLevel_) * params_.indentWidth_, ' ');
430
0
}
431
432
// ---------------------------------------------------------------------------
433
434
0
void WKTFormatter::enter() {
435
0
    if (d->indentLevel_ == 0 && d->level_ == 0) {
436
0
        d->stackHasChild_.push_back(false);
437
0
    }
438
0
    ++d->level_;
439
0
}
440
441
// ---------------------------------------------------------------------------
442
443
0
void WKTFormatter::leave() {
444
0
    assert(d->level_ > 0);
445
0
    --d->level_;
446
0
    if (d->indentLevel_ == 0 && d->level_ == 0) {
447
0
        d->stackHasChild_.pop_back();
448
0
    }
449
0
}
450
451
// ---------------------------------------------------------------------------
452
453
0
bool WKTFormatter::isAtTopLevel() const {
454
0
    return d->level_ == 0 && d->indentLevel_ == 0;
455
0
}
456
457
// ---------------------------------------------------------------------------
458
459
0
void WKTFormatter::startNode(const std::string &keyword, bool hasId) {
460
0
    if (!d->stackHasChild_.empty()) {
461
0
        d->startNewChild();
462
0
    } else if (!d->result_.empty()) {
463
0
        d->result_ += ',';
464
0
        if (d->params_.multiLine_ && !keyword.empty()) {
465
0
            d->addNewLine();
466
0
        }
467
0
    }
468
469
0
    if (d->params_.multiLine_) {
470
0
        if ((d->indentLevel_ || d->level_) && !keyword.empty()) {
471
0
            if (!d->result_.empty()) {
472
0
                d->addNewLine();
473
0
            }
474
0
            d->addIndentation();
475
0
        }
476
0
    }
477
478
0
    if (!keyword.empty()) {
479
0
        d->result_ += keyword;
480
0
        d->result_ += '[';
481
0
    }
482
0
    d->indentLevel_++;
483
0
    d->stackHasChild_.push_back(false);
484
0
    d->stackEmptyKeyword_.push_back(keyword.empty());
485
486
    // Starting from a node that has a ID, we should emit ID nodes for :
487
    // - this node
488
    // - and for METHOD&PARAMETER nodes in WKT2, unless idOnTopLevelOnly_ is
489
    // set.
490
    // For WKT2, all other intermediate nodes shouldn't have ID ("not
491
    // recommended")
492
0
    if (!d->params_.idOnTopLevelOnly_ && d->indentLevel_ >= 2 &&
493
0
        d->params_.version_ == WKTFormatter::Version::WKT2 &&
494
0
        (keyword == WKTConstants::METHOD ||
495
0
         keyword == WKTConstants::PARAMETER)) {
496
0
        pushOutputId(d->outputIdStack_[0]);
497
0
    } else if (d->indentLevel_ >= 2 &&
498
0
               d->params_.version_ == WKTFormatter::Version::WKT2) {
499
0
        pushOutputId(d->outputIdStack_[0] && !d->stackHasId_.back());
500
0
    } else {
501
0
        pushOutputId(outputId());
502
0
    }
503
504
0
    d->stackHasId_.push_back(hasId || d->stackHasId_.back());
505
0
}
506
507
// ---------------------------------------------------------------------------
508
509
0
void WKTFormatter::endNode() {
510
0
    assert(d->indentLevel_ > 0);
511
0
    d->stackHasId_.pop_back();
512
0
    popOutputId();
513
0
    d->indentLevel_--;
514
0
    bool emptyKeyword = d->stackEmptyKeyword_.back();
515
0
    d->stackEmptyKeyword_.pop_back();
516
0
    d->stackHasChild_.pop_back();
517
0
    if (!emptyKeyword)
518
0
        d->result_ += ']';
519
0
}
520
521
// ---------------------------------------------------------------------------
522
523
0
WKTFormatter &WKTFormatter::simulCurNodeHasId() {
524
0
    d->stackHasId_.back() = true;
525
0
    return *this;
526
0
}
527
528
// ---------------------------------------------------------------------------
529
530
0
void WKTFormatter::Private::startNewChild() {
531
0
    assert(!stackHasChild_.empty());
532
0
    if (stackHasChild_.back()) {
533
0
        result_ += ',';
534
0
    }
535
0
    stackHasChild_.back() = true;
536
0
}
537
538
// ---------------------------------------------------------------------------
539
540
0
void WKTFormatter::addQuotedString(const char *str) {
541
0
    addQuotedString(std::string(str));
542
0
}
543
544
0
void WKTFormatter::addQuotedString(const std::string &str) {
545
0
    d->startNewChild();
546
0
    d->result_ += '"';
547
0
    d->result_ += replaceAll(str, "\"", "\"\"");
548
0
    d->result_ += '"';
549
0
}
550
551
// ---------------------------------------------------------------------------
552
553
0
void WKTFormatter::add(const std::string &str) {
554
0
    d->startNewChild();
555
0
    d->result_ += str;
556
0
}
557
558
// ---------------------------------------------------------------------------
559
560
0
void WKTFormatter::add(int number) {
561
0
    d->startNewChild();
562
0
    d->result_ += internal::toString(number);
563
0
}
564
565
// ---------------------------------------------------------------------------
566
567
#ifdef __MINGW32__
568
static std::string normalizeExponent(const std::string &in) {
569
    // mingw will output 1e-0xy instead of 1e-xy. Fix that
570
    auto pos = in.find("e-0");
571
    if (pos == std::string::npos) {
572
        return in;
573
    }
574
    if (pos + 4 < in.size() && isdigit(in[pos + 3]) && isdigit(in[pos + 4])) {
575
        return in.substr(0, pos + 2) + in.substr(pos + 3);
576
    }
577
    return in;
578
}
579
#else
580
922k
static inline std::string normalizeExponent(const std::string &in) {
581
922k
    return in;
582
922k
}
583
#endif
584
585
922k
static inline std::string normalizeSerializedString(const std::string &in) {
586
922k
    auto ret(normalizeExponent(in));
587
922k
    return ret;
588
922k
}
589
590
// ---------------------------------------------------------------------------
591
592
0
void WKTFormatter::add(double number, int precision) {
593
0
    d->startNewChild();
594
0
    if (number == 0.0) {
595
0
        if (d->params_.useESRIDialect_) {
596
0
            d->result_ += "0.0";
597
0
        } else {
598
0
            d->result_ += '0';
599
0
        }
600
0
    } else {
601
0
        std::string val(
602
0
            normalizeSerializedString(internal::toString(number, precision)));
603
0
        d->result_ += replaceAll(val, "e", "E");
604
0
        if (d->params_.useESRIDialect_ && val.find('.') == std::string::npos) {
605
0
            d->result_ += ".0";
606
0
        }
607
0
    }
608
0
}
609
610
// ---------------------------------------------------------------------------
611
612
0
void WKTFormatter::pushOutputUnit(bool outputUnitIn) {
613
0
    d->outputUnitStack_.push_back(outputUnitIn);
614
0
}
615
616
// ---------------------------------------------------------------------------
617
618
0
void WKTFormatter::popOutputUnit() { d->outputUnitStack_.pop_back(); }
619
620
// ---------------------------------------------------------------------------
621
622
0
bool WKTFormatter::outputUnit() const { return d->outputUnitStack_.back(); }
623
624
// ---------------------------------------------------------------------------
625
626
0
void WKTFormatter::pushOutputId(bool outputIdIn) {
627
0
    d->outputIdStack_.push_back(outputIdIn);
628
0
}
629
630
// ---------------------------------------------------------------------------
631
632
0
void WKTFormatter::popOutputId() { d->outputIdStack_.pop_back(); }
633
634
// ---------------------------------------------------------------------------
635
636
0
bool WKTFormatter::outputId() const {
637
0
    return !d->params_.useESRIDialect_ && d->outputIdStack_.back();
638
0
}
639
640
// ---------------------------------------------------------------------------
641
642
0
void WKTFormatter::pushHasId(bool hasId) { d->stackHasId_.push_back(hasId); }
643
644
// ---------------------------------------------------------------------------
645
646
0
void WKTFormatter::popHasId() { d->stackHasId_.pop_back(); }
647
648
// ---------------------------------------------------------------------------
649
650
0
void WKTFormatter::pushDisableUsage() { d->stackDisableUsage_.push_back(true); }
651
652
// ---------------------------------------------------------------------------
653
654
0
void WKTFormatter::popDisableUsage() { d->stackDisableUsage_.pop_back(); }
655
656
// ---------------------------------------------------------------------------
657
658
0
bool WKTFormatter::outputUsage() const {
659
0
    return outputId() && d->stackDisableUsage_.empty();
660
0
}
661
662
// ---------------------------------------------------------------------------
663
664
0
void WKTFormatter::pushAxisLinearUnit(const UnitOfMeasureNNPtr &unit) {
665
0
    d->axisLinearUnitStack_.push_back(unit);
666
0
}
667
// ---------------------------------------------------------------------------
668
669
0
void WKTFormatter::popAxisLinearUnit() { d->axisLinearUnitStack_.pop_back(); }
670
671
// ---------------------------------------------------------------------------
672
673
0
const UnitOfMeasureNNPtr &WKTFormatter::axisLinearUnit() const {
674
0
    return d->axisLinearUnitStack_.back();
675
0
}
676
677
// ---------------------------------------------------------------------------
678
679
0
void WKTFormatter::pushAxisAngularUnit(const UnitOfMeasureNNPtr &unit) {
680
0
    d->axisAngularUnitStack_.push_back(unit);
681
0
}
682
// ---------------------------------------------------------------------------
683
684
0
void WKTFormatter::popAxisAngularUnit() { d->axisAngularUnitStack_.pop_back(); }
685
686
// ---------------------------------------------------------------------------
687
688
0
const UnitOfMeasureNNPtr &WKTFormatter::axisAngularUnit() const {
689
0
    return d->axisAngularUnitStack_.back();
690
0
}
691
692
// ---------------------------------------------------------------------------
693
694
0
WKTFormatter::OutputAxisRule WKTFormatter::outputAxis() const {
695
0
    return d->params_.outputAxis_;
696
0
}
697
698
// ---------------------------------------------------------------------------
699
700
0
bool WKTFormatter::outputAxisOrder() const {
701
0
    return d->params_.outputAxisOrder_;
702
0
}
703
704
// ---------------------------------------------------------------------------
705
706
0
bool WKTFormatter::primeMeridianOmittedIfGreenwich() const {
707
0
    return d->params_.primeMeridianOmittedIfGreenwich_;
708
0
}
709
710
// ---------------------------------------------------------------------------
711
712
0
bool WKTFormatter::ellipsoidUnitOmittedIfMetre() const {
713
0
    return d->params_.ellipsoidUnitOmittedIfMetre_;
714
0
}
715
716
// ---------------------------------------------------------------------------
717
718
0
bool WKTFormatter::primeMeridianOrParameterUnitOmittedIfSameAsAxis() const {
719
0
    return d->params_.primeMeridianOrParameterUnitOmittedIfSameAsAxis_;
720
0
}
721
722
// ---------------------------------------------------------------------------
723
724
0
bool WKTFormatter::outputCSUnitOnlyOnceIfSame() const {
725
0
    return d->params_.outputCSUnitOnlyOnceIfSame_;
726
0
}
727
728
// ---------------------------------------------------------------------------
729
730
0
bool WKTFormatter::forceUNITKeyword() const {
731
0
    return d->params_.forceUNITKeyword_;
732
0
}
733
734
// ---------------------------------------------------------------------------
735
736
0
bool WKTFormatter::primeMeridianInDegree() const {
737
0
    return d->params_.primeMeridianInDegree_;
738
0
}
739
740
// ---------------------------------------------------------------------------
741
742
0
bool WKTFormatter::idOnTopLevelOnly() const {
743
0
    return d->params_.idOnTopLevelOnly_;
744
0
}
745
746
// ---------------------------------------------------------------------------
747
748
0
bool WKTFormatter::topLevelHasId() const {
749
0
    return d->stackHasId_.size() >= 2 && d->stackHasId_[1];
750
0
}
751
752
// ---------------------------------------------------------------------------
753
754
0
WKTFormatter::Version WKTFormatter::version() const {
755
0
    return d->params_.version_;
756
0
}
757
758
// ---------------------------------------------------------------------------
759
760
0
bool WKTFormatter::use2019Keywords() const {
761
0
    return d->params_.use2019Keywords_;
762
0
}
763
764
// ---------------------------------------------------------------------------
765
766
0
bool WKTFormatter::useESRIDialect() const { return d->params_.useESRIDialect_; }
767
768
// ---------------------------------------------------------------------------
769
770
0
const DatabaseContextPtr &WKTFormatter::databaseContext() const {
771
0
    return d->dbContext_;
772
0
}
773
774
// ---------------------------------------------------------------------------
775
776
0
void WKTFormatter::setAbridgedTransformation(bool outputIn) {
777
0
    d->abridgedTransformation_ = outputIn;
778
0
}
779
780
// ---------------------------------------------------------------------------
781
782
0
bool WKTFormatter::abridgedTransformation() const {
783
0
    return d->abridgedTransformation_;
784
0
}
785
786
// ---------------------------------------------------------------------------
787
788
0
void WKTFormatter::setUseDerivingConversion(bool useDerivingConversionIn) {
789
0
    d->useDerivingConversion_ = useDerivingConversionIn;
790
0
}
791
792
// ---------------------------------------------------------------------------
793
794
0
bool WKTFormatter::useDerivingConversion() const {
795
0
    return d->useDerivingConversion_;
796
0
}
797
798
// ---------------------------------------------------------------------------
799
800
0
void WKTFormatter::setTOWGS84Parameters(const std::vector<double> &params) {
801
0
    d->toWGS84Parameters_ = params;
802
0
}
803
804
// ---------------------------------------------------------------------------
805
806
0
const std::vector<double> &WKTFormatter::getTOWGS84Parameters() const {
807
0
    return d->toWGS84Parameters_;
808
0
}
809
810
// ---------------------------------------------------------------------------
811
812
0
void WKTFormatter::setVDatumExtension(const std::string &filename) {
813
0
    d->vDatumExtension_ = filename;
814
0
}
815
816
// ---------------------------------------------------------------------------
817
818
0
const std::string &WKTFormatter::getVDatumExtension() const {
819
0
    return d->vDatumExtension_;
820
0
}
821
822
// ---------------------------------------------------------------------------
823
824
0
void WKTFormatter::setHDatumExtension(const std::string &filename) {
825
0
    d->hDatumExtension_ = filename;
826
0
}
827
828
// ---------------------------------------------------------------------------
829
830
0
const std::string &WKTFormatter::getHDatumExtension() const {
831
0
    return d->hDatumExtension_;
832
0
}
833
834
// ---------------------------------------------------------------------------
835
836
0
void WKTFormatter::setGeogCRSOfCompoundCRS(const crs::GeographicCRSPtr &crs) {
837
0
    d->geogCRSOfCompoundCRS_ = crs;
838
0
}
839
840
// ---------------------------------------------------------------------------
841
842
0
const crs::GeographicCRSPtr &WKTFormatter::getGeogCRSOfCompoundCRS() const {
843
0
    return d->geogCRSOfCompoundCRS_;
844
0
}
845
846
// ---------------------------------------------------------------------------
847
848
0
std::string WKTFormatter::morphNameToESRI(const std::string &name) {
849
850
0
    for (const auto *suffix : {"(m)", "(ftUS)", "(E-N)", "(N-E)"}) {
851
0
        if (ends_with(name, suffix)) {
852
0
            return morphNameToESRI(
853
0
                       name.substr(0, name.size() - strlen(suffix))) +
854
0
                   suffix;
855
0
        }
856
0
    }
857
858
0
    std::string ret;
859
0
    bool insertUnderscore = false;
860
    // Replace any special character by underscore, except at the beginning
861
    // and of the name where those characters are removed.
862
0
    for (char ch : name) {
863
0
        if (ch == '+' || ch == '-' || (ch >= '0' && ch <= '9') ||
864
0
            (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
865
0
            if (insertUnderscore && !ret.empty()) {
866
0
                ret += '_';
867
0
            }
868
0
            ret += ch;
869
0
            insertUnderscore = false;
870
0
        } else {
871
0
            insertUnderscore = true;
872
0
        }
873
0
    }
874
0
    return ret;
875
0
}
876
877
// ---------------------------------------------------------------------------
878
879
0
void WKTFormatter::ingestWKTNode(const WKTNodeNNPtr &node) {
880
0
    startNode(node->value(), true);
881
0
    for (const auto &child : node->children()) {
882
0
        if (!child->children().empty()) {
883
0
            ingestWKTNode(child);
884
0
        } else {
885
0
            add(child->value());
886
0
        }
887
0
    }
888
0
    endNode();
889
0
}
890
891
//! @endcond
892
893
// ---------------------------------------------------------------------------
894
895
//! @cond Doxygen_Suppress
896
897
static WKTNodeNNPtr
898
    null_node(NN_NO_CHECK(std::make_unique<WKTNode>(std::string())));
899
900
186k
static inline bool isNull(const WKTNodeNNPtr &node) {
901
186k
    return &node == &null_node;
902
186k
}
903
904
struct WKTNode::Private {
905
    std::string value_{};
906
    std::vector<WKTNodeNNPtr> children_{};
907
908
72.6k
    explicit Private(const std::string &valueIn) : value_(valueIn) {}
909
910
    // cppcheck-suppress functionStatic
911
978k
    inline const std::string &value() PROJ_PURE_DEFN { return value_; }
912
913
    // cppcheck-suppress functionStatic
914
66.8k
    inline const std::vector<WKTNodeNNPtr> &children() PROJ_PURE_DEFN {
915
66.8k
        return children_;
916
66.8k
    }
917
918
    // cppcheck-suppress functionStatic
919
13.5k
    inline size_t childrenSize() PROJ_PURE_DEFN { return children_.size(); }
920
921
    // cppcheck-suppress functionStatic
922
    const WKTNodeNNPtr &lookForChild(const std::string &childName,
923
                                     int occurrence) const noexcept;
924
925
    // cppcheck-suppress functionStatic
926
    const WKTNodeNNPtr &lookForChild(const std::string &name) const noexcept;
927
928
    // cppcheck-suppress functionStatic
929
    const WKTNodeNNPtr &lookForChild(const std::string &name,
930
                                     const std::string &name2) const noexcept;
931
932
    // cppcheck-suppress functionStatic
933
    const WKTNodeNNPtr &lookForChild(const std::string &name,
934
                                     const std::string &name2,
935
                                     const std::string &name3) const noexcept;
936
937
    // cppcheck-suppress functionStatic
938
    const WKTNodeNNPtr &lookForChild(const std::string &name,
939
                                     const std::string &name2,
940
                                     const std::string &name3,
941
                                     const std::string &name4) const noexcept;
942
};
943
944
1.05M
#define GP() getPrivate()
945
946
// ---------------------------------------------------------------------------
947
948
const WKTNodeNNPtr &
949
WKTNode::Private::lookForChild(const std::string &childName,
950
206
                               int occurrence) const noexcept {
951
206
    int occCount = 0;
952
555
    for (const auto &child : children_) {
953
555
        if (ci_equal(child->GP()->value(), childName)) {
954
207
            if (occurrence == occCount) {
955
206
                return child;
956
206
            }
957
1
            occCount++;
958
1
        }
959
555
    }
960
0
    return null_node;
961
206
}
962
963
const WKTNodeNNPtr &
964
174k
WKTNode::Private::lookForChild(const std::string &name) const noexcept {
965
723k
    for (const auto &child : children_) {
966
723k
        const auto &v = child->GP()->value();
967
723k
        if (ci_equal(v, name)) {
968
4.61k
            return child;
969
4.61k
        }
970
723k
    }
971
169k
    return null_node;
972
174k
}
973
974
const WKTNodeNNPtr &
975
WKTNode::Private::lookForChild(const std::string &name,
976
6.22k
                               const std::string &name2) const noexcept {
977
19.8k
    for (const auto &child : children_) {
978
19.8k
        const auto &v = child->GP()->value();
979
19.8k
        if (ci_equal(v, name) || ci_equal(v, name2)) {
980
2.47k
            return child;
981
2.47k
        }
982
19.8k
    }
983
3.75k
    return null_node;
984
6.22k
}
985
986
const WKTNodeNNPtr &
987
WKTNode::Private::lookForChild(const std::string &name,
988
                               const std::string &name2,
989
2.11k
                               const std::string &name3) const noexcept {
990
4.03k
    for (const auto &child : children_) {
991
4.03k
        const auto &v = child->GP()->value();
992
4.03k
        if (ci_equal(v, name) || ci_equal(v, name2) || ci_equal(v, name3)) {
993
1.90k
            return child;
994
1.90k
        }
995
4.03k
    }
996
204
    return null_node;
997
2.11k
}
998
999
const WKTNodeNNPtr &WKTNode::Private::lookForChild(
1000
    const std::string &name, const std::string &name2, const std::string &name3,
1001
725
    const std::string &name4) const noexcept {
1002
1.56k
    for (const auto &child : children_) {
1003
1.56k
        const auto &v = child->GP()->value();
1004
1.56k
        if (ci_equal(v, name) || ci_equal(v, name2) || ci_equal(v, name3) ||
1005
1.08k
            ci_equal(v, name4)) {
1006
668
            return child;
1007
668
        }
1008
1.56k
    }
1009
57
    return null_node;
1010
725
}
1011
1012
//! @endcond
1013
1014
// ---------------------------------------------------------------------------
1015
1016
/** \brief Instantiate a WKTNode.
1017
 *
1018
 * @param valueIn the name of the node.
1019
 */
1020
WKTNode::WKTNode(const std::string &valueIn)
1021
72.6k
    : d(std::make_unique<Private>(valueIn)) {}
1022
1023
// ---------------------------------------------------------------------------
1024
1025
//! @cond Doxygen_Suppress
1026
72.6k
WKTNode::~WKTNode() = default;
1027
//! @endcond
1028
1029
// ---------------------------------------------------------------------------
1030
1031
/** \brief Adds a child to the current node.
1032
 *
1033
 * @param child child to add. This should not be a parent of this node.
1034
 */
1035
69.1k
void WKTNode::addChild(WKTNodeNNPtr &&child) {
1036
69.1k
    d->children_.push_back(std::move(child));
1037
69.1k
}
1038
1039
// ---------------------------------------------------------------------------
1040
1041
/** \brief Return the (occurrence-1)th sub-node of name childName.
1042
 *
1043
 * @param childName name of the child.
1044
 * @param occurrence occurrence index (starting at 0)
1045
 * @return the child, or nullptr.
1046
 */
1047
const WKTNodePtr &WKTNode::lookForChild(const std::string &childName,
1048
1.71k
                                        int occurrence) const noexcept {
1049
1.71k
    int occCount = 0;
1050
11.2k
    for (const auto &child : d->children_) {
1051
11.2k
        if (ci_equal(child->GP()->value(), childName)) {
1052
148
            if (occurrence == occCount) {
1053
148
                return child;
1054
148
            }
1055
0
            occCount++;
1056
0
        }
1057
11.2k
    }
1058
1.56k
    return null_node;
1059
1.71k
}
1060
1061
// ---------------------------------------------------------------------------
1062
1063
/** \brief Return the count of children of given name.
1064
 *
1065
 * @param childName name of the children to look for.
1066
 * @return count
1067
 */
1068
3.47k
int WKTNode::countChildrenOfName(const std::string &childName) const noexcept {
1069
3.47k
    int occCount = 0;
1070
19.5k
    for (const auto &child : d->children_) {
1071
19.5k
        if (ci_equal(child->GP()->value(), childName)) {
1072
224
            occCount++;
1073
224
        }
1074
19.5k
    }
1075
3.47k
    return occCount;
1076
3.47k
}
1077
1078
// ---------------------------------------------------------------------------
1079
1080
/** \brief Return the value of a node.
1081
 */
1082
0
const std::string &WKTNode::value() const { return d->value_; }
1083
1084
// ---------------------------------------------------------------------------
1085
1086
/** \brief Return the children of a node.
1087
 */
1088
0
const std::vector<WKTNodeNNPtr> &WKTNode::children() const {
1089
0
    return d->children_;
1090
0
}
1091
1092
// ---------------------------------------------------------------------------
1093
1094
//! @cond Doxygen_Suppress
1095
252k
static size_t skipSpace(const std::string &str, size_t start) {
1096
252k
    size_t i = start;
1097
255k
    while (i < str.size() && ::isspace(static_cast<unsigned char>(str[i]))) {
1098
3.54k
        ++i;
1099
3.54k
    }
1100
252k
    return i;
1101
252k
}
1102
//! @endcond
1103
1104
// ---------------------------------------------------------------------------
1105
1106
//! @cond Doxygen_Suppress
1107
// As used in examples of OGC 12-063r5
1108
static const std::string startPrintedQuote("\xE2\x80\x9C");
1109
static const std::string endPrintedQuote("\xE2\x80\x9D");
1110
//! @endcond
1111
1112
WKTNodeNNPtr WKTNode::createFrom(const std::string &wkt, size_t indexStart,
1113
72.9k
                                 int recLevel, size_t &indexEnd) {
1114
72.9k
    if (recLevel == 16) {
1115
2
        throw ParsingException("too many nesting levels");
1116
2
    }
1117
72.9k
    std::string value;
1118
72.9k
    size_t i = skipSpace(wkt, indexStart);
1119
72.9k
    if (i == wkt.size()) {
1120
0
        throw ParsingException("whitespace only string");
1121
0
    }
1122
72.9k
    std::string closingStringMarker;
1123
72.9k
    bool inString = false;
1124
1125
621k
    for (; i < wkt.size() &&
1126
621k
           (inString ||
1127
460k
            (wkt[i] != '[' && wkt[i] != '(' && wkt[i] != ',' && wkt[i] != ']' &&
1128
389k
             wkt[i] != ')' && !::isspace(static_cast<unsigned char>(wkt[i]))));
1129
548k
         ++i) {
1130
548k
        if (wkt[i] == '"') {
1131
20.0k
            if (!inString) {
1132
9.73k
                inString = true;
1133
9.73k
                closingStringMarker = "\"";
1134
10.2k
            } else if (closingStringMarker == "\"") {
1135
10.1k
                if (i + 1 < wkt.size() && wkt[i + 1] == '"') {
1136
404
                    i++;
1137
9.70k
                } else {
1138
9.70k
                    inString = false;
1139
9.70k
                    closingStringMarker.clear();
1140
9.70k
                }
1141
10.1k
            }
1142
528k
        } else if (i + 3 <= wkt.size() &&
1143
527k
                   wkt.substr(i, 3) == startPrintedQuote) {
1144
98
            if (!inString) {
1145
65
                inString = true;
1146
65
                closingStringMarker = endPrintedQuote;
1147
65
                value += '"';
1148
65
                i += 2;
1149
65
                continue;
1150
65
            }
1151
528k
        } else if (i + 3 <= wkt.size() &&
1152
527k
                   closingStringMarker == endPrintedQuote &&
1153
800
                   wkt.substr(i, 3) == endPrintedQuote) {
1154
27
            inString = false;
1155
27
            closingStringMarker.clear();
1156
27
            value += '"';
1157
27
            i += 2;
1158
27
            continue;
1159
27
        }
1160
548k
        value += wkt[i];
1161
548k
    }
1162
72.9k
    i = skipSpace(wkt, i);
1163
72.9k
    if (i == wkt.size()) {
1164
296
        if (indexStart == 0) {
1165
0
            throw ParsingException("missing [");
1166
296
        } else {
1167
296
            throw ParsingException("missing , or ]");
1168
296
        }
1169
296
    }
1170
1171
72.6k
    auto node = NN_NO_CHECK(std::make_unique<WKTNode>(value));
1172
1173
72.6k
    if (indexStart > 0) {
1174
69.7k
        if (wkt[i] == ',') {
1175
25.3k
            indexEnd = i + 1;
1176
25.3k
            return node;
1177
25.3k
        }
1178
44.3k
        if (wkt[i] == ']' || wkt[i] == ')') {
1179
21.0k
            indexEnd = i;
1180
21.0k
            return node;
1181
21.0k
        }
1182
44.3k
    }
1183
26.2k
    if (wkt[i] != '[' && wkt[i] != '(') {
1184
32
        throw ParsingException("missing [");
1185
32
    }
1186
26.1k
    ++i; // skip [
1187
26.1k
    i = skipSpace(wkt, i);
1188
95.9k
    while (i < wkt.size() && wkt[i] != ']' && wkt[i] != ')') {
1189
69.7k
        size_t indexEndChild;
1190
69.7k
        node->addChild(createFrom(wkt, i, recLevel + 1, indexEndChild));
1191
69.7k
        assert(indexEndChild > i);
1192
69.7k
        i = indexEndChild;
1193
69.7k
        i = skipSpace(wkt, i);
1194
69.7k
        if (i < wkt.size() && wkt[i] == ',') {
1195
9.82k
            ++i;
1196
9.82k
            i = skipSpace(wkt, i);
1197
9.82k
        }
1198
69.7k
    }
1199
26.1k
    if (i == wkt.size() || (wkt[i] != ']' && wkt[i] != ')')) {
1200
52
        throw ParsingException("missing ]");
1201
52
    }
1202
26.1k
    indexEnd = i + 1;
1203
26.1k
    return node;
1204
26.1k
}
1205
// ---------------------------------------------------------------------------
1206
1207
/** \brief Instantiate a WKTNode hierarchy from a WKT string.
1208
 *
1209
 * @param wkt the WKT string to parse.
1210
 * @param indexStart the start index in the wkt string.
1211
 * @throw ParsingException if the string cannot be parsed.
1212
 */
1213
0
WKTNodeNNPtr WKTNode::createFrom(const std::string &wkt, size_t indexStart) {
1214
0
    size_t indexEnd;
1215
0
    return createFrom(wkt, indexStart, 0, indexEnd);
1216
0
}
1217
1218
// ---------------------------------------------------------------------------
1219
1220
//! @cond Doxygen_Suppress
1221
0
static std::string escapeIfQuotedString(const std::string &str) {
1222
0
    if (str.size() > 2 && str[0] == '"' && str.back() == '"') {
1223
0
        std::string res("\"");
1224
0
        res += replaceAll(str.substr(1, str.size() - 2), "\"", "\"\"");
1225
0
        res += '"';
1226
0
        return res;
1227
0
    } else {
1228
0
        return str;
1229
0
    }
1230
0
}
1231
//! @endcond
1232
1233
// ---------------------------------------------------------------------------
1234
1235
/** \brief Return a WKT representation of the tree structure.
1236
 */
1237
0
std::string WKTNode::toString() const {
1238
0
    std::string str(escapeIfQuotedString(d->value_));
1239
0
    if (!d->children_.empty()) {
1240
0
        str += "[";
1241
0
        bool first = true;
1242
0
        for (auto &child : d->children_) {
1243
0
            if (!first) {
1244
0
                str += ',';
1245
0
            }
1246
0
            first = false;
1247
0
            str += child->toString();
1248
0
        }
1249
0
        str += "]";
1250
0
    }
1251
0
    return str;
1252
0
}
1253
1254
// ---------------------------------------------------------------------------
1255
1256
//! @cond Doxygen_Suppress
1257
struct WKTParser::Private {
1258
1259
    struct ci_less_struct {
1260
        bool operator()(const std::string &lhs,
1261
22.0k
                        const std::string &rhs) const noexcept {
1262
22.0k
            return ci_less(lhs, rhs);
1263
22.0k
        }
1264
    };
1265
1266
    bool strict_ = true;
1267
    bool unsetIdentifiersIfIncompatibleDef_ = true;
1268
    std::list<std::string> warningList_{};
1269
    std::list<std::string> grammarErrorList_{};
1270
    std::vector<double> toWGS84Parameters_{};
1271
    std::string datumPROJ4Grids_{};
1272
    bool esriStyle_ = false;
1273
    bool maybeEsriStyle_ = false;
1274
    DatabaseContextPtr dbContext_{};
1275
    crs::GeographicCRSPtr geogCRSOfCompoundCRS_{};
1276
1277
    static constexpr unsigned int MAX_PROPERTY_SIZE = 1024;
1278
    std::vector<std::unique_ptr<PropertyMap>> properties_{};
1279
1280
2.89k
    Private() = default;
1281
2.89k
    ~Private() = default;
1282
    Private(const Private &) = delete;
1283
    Private &operator=(const Private &) = delete;
1284
1285
    void emitRecoverableWarning(const std::string &warningMsg);
1286
    void emitGrammarError(const std::string &errorMsg);
1287
    void emitRecoverableMissingUNIT(const std::string &parentNodeName,
1288
                                    const UnitOfMeasure &fallbackUnit);
1289
1290
    BaseObjectNNPtr build(const WKTNodeNNPtr &node);
1291
1292
    IdentifierPtr buildId(const WKTNodeNNPtr &parentNode,
1293
                          const WKTNodeNNPtr &node, bool tolerant,
1294
                          bool removeInverseOf);
1295
1296
    PropertyMap &buildProperties(const WKTNodeNNPtr &node,
1297
                                 bool removeInverseOf = false,
1298
                                 bool hasName = true);
1299
1300
    ObjectDomainPtr buildObjectDomain(const WKTNodeNNPtr &node);
1301
1302
    static std::string stripQuotes(const WKTNodeNNPtr &node);
1303
1304
    static double asDouble(const WKTNodeNNPtr &node);
1305
1306
    UnitOfMeasure
1307
    buildUnit(const WKTNodeNNPtr &node,
1308
              UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN);
1309
1310
    UnitOfMeasure buildUnitInSubNode(
1311
        const WKTNodeNNPtr &node,
1312
        common::UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN);
1313
1314
    EllipsoidNNPtr buildEllipsoid(const WKTNodeNNPtr &node);
1315
1316
    PrimeMeridianNNPtr
1317
    buildPrimeMeridian(const WKTNodeNNPtr &node,
1318
                       const UnitOfMeasure &defaultAngularUnit);
1319
1320
    static optional<std::string> getAnchor(const WKTNodeNNPtr &node);
1321
1322
    static optional<common::Measure> getAnchorEpoch(const WKTNodeNNPtr &node);
1323
1324
    static void parseDynamic(const WKTNodeNNPtr &dynamicNode,
1325
                             double &frameReferenceEpoch,
1326
                             util::optional<std::string> &modelName);
1327
1328
    GeodeticReferenceFrameNNPtr
1329
    buildGeodeticReferenceFrame(const WKTNodeNNPtr &node,
1330
                                const PrimeMeridianNNPtr &primeMeridian,
1331
                                const WKTNodeNNPtr &dynamicNode);
1332
1333
    DatumEnsembleNNPtr buildDatumEnsemble(const WKTNodeNNPtr &node,
1334
                                          const PrimeMeridianPtr &primeMeridian,
1335
                                          bool expectEllipsoid);
1336
1337
    MeridianNNPtr buildMeridian(const WKTNodeNNPtr &node);
1338
    CoordinateSystemAxisNNPtr buildAxis(const WKTNodeNNPtr &node,
1339
                                        const UnitOfMeasure &unitIn,
1340
                                        const UnitOfMeasure::Type &unitType,
1341
                                        bool isGeocentric,
1342
                                        int expectedOrderNum);
1343
1344
    CoordinateSystemNNPtr buildCS(const WKTNodeNNPtr &node, /* maybe null */
1345
                                  const WKTNodeNNPtr &parentNode,
1346
                                  const UnitOfMeasure &defaultAngularUnit);
1347
1348
    GeodeticCRSNNPtr buildGeodeticCRS(const WKTNodeNNPtr &node,
1349
                                      bool forceGeocentricIfNoCs = false);
1350
1351
    CRSNNPtr buildDerivedGeodeticCRS(const WKTNodeNNPtr &node);
1352
1353
    static UnitOfMeasure
1354
    guessUnitForParameter(const std::string &paramName,
1355
                          const UnitOfMeasure &defaultLinearUnit,
1356
                          const UnitOfMeasure &defaultAngularUnit);
1357
1358
    void consumeParameters(const WKTNodeNNPtr &node, bool isAbridged,
1359
                           std::vector<OperationParameterNNPtr> &parameters,
1360
                           std::vector<ParameterValueNNPtr> &values,
1361
                           const UnitOfMeasure &defaultLinearUnit,
1362
                           const UnitOfMeasure &defaultAngularUnit);
1363
1364
    static std::string getExtensionProj4(const WKTNode::Private *nodeP);
1365
1366
    static void addExtensionProj4ToProp(const WKTNode::Private *nodeP,
1367
                                        PropertyMap &props);
1368
1369
    ConversionNNPtr buildConversion(const WKTNodeNNPtr &node,
1370
                                    const UnitOfMeasure &defaultLinearUnit,
1371
                                    const UnitOfMeasure &defaultAngularUnit);
1372
1373
    static bool hasWebMercPROJ4String(const WKTNodeNNPtr &projCRSNode,
1374
                                      const WKTNodeNNPtr &projectionNode);
1375
1376
    static std::string projectionGetParameter(const WKTNodeNNPtr &projCRSNode,
1377
                                              const char *paramName);
1378
1379
    ConversionNNPtr buildProjection(const GeodeticCRSNNPtr &baseGeodCRS,
1380
                                    const WKTNodeNNPtr &projCRSNode,
1381
                                    const WKTNodeNNPtr &projectionNode,
1382
                                    const UnitOfMeasure &defaultLinearUnit,
1383
                                    const UnitOfMeasure &defaultAngularUnit);
1384
1385
    ConversionNNPtr
1386
    buildProjectionStandard(const GeodeticCRSNNPtr &baseGeodCRS,
1387
                            const WKTNodeNNPtr &projCRSNode,
1388
                            const WKTNodeNNPtr &projectionNode,
1389
                            const UnitOfMeasure &defaultLinearUnit,
1390
                            const UnitOfMeasure &defaultAngularUnit);
1391
1392
    const ESRIMethodMapping *
1393
    getESRIMapping(const WKTNodeNNPtr &projCRSNode,
1394
                   const WKTNodeNNPtr &projectionNode,
1395
                   std::map<std::string, std::string, ci_less_struct>
1396
                       &mapParamNameToValue);
1397
1398
    static ConversionNNPtr
1399
    buildProjectionFromESRI(const GeodeticCRSNNPtr &baseGeodCRS,
1400
                            const WKTNodeNNPtr &projCRSNode,
1401
                            const WKTNodeNNPtr &projectionNode,
1402
                            const UnitOfMeasure &defaultLinearUnit,
1403
                            const UnitOfMeasure &defaultAngularUnit,
1404
                            const ESRIMethodMapping *esriMapping,
1405
                            std::map<std::string, std::string, ci_less_struct>
1406
                                &mapParamNameToValue);
1407
1408
    ConversionNNPtr
1409
    buildProjectionFromESRI(const GeodeticCRSNNPtr &baseGeodCRS,
1410
                            const WKTNodeNNPtr &projCRSNode,
1411
                            const WKTNodeNNPtr &projectionNode,
1412
                            const UnitOfMeasure &defaultLinearUnit,
1413
                            const UnitOfMeasure &defaultAngularUnit);
1414
1415
    ProjectedCRSNNPtr buildProjectedCRS(const WKTNodeNNPtr &node);
1416
1417
    VerticalReferenceFrameNNPtr
1418
    buildVerticalReferenceFrame(const WKTNodeNNPtr &node,
1419
                                const WKTNodeNNPtr &dynamicNode);
1420
1421
    TemporalDatumNNPtr buildTemporalDatum(const WKTNodeNNPtr &node);
1422
1423
    EngineeringDatumNNPtr buildEngineeringDatum(const WKTNodeNNPtr &node);
1424
1425
    ParametricDatumNNPtr buildParametricDatum(const WKTNodeNNPtr &node);
1426
1427
    CRSNNPtr buildVerticalCRS(const WKTNodeNNPtr &node);
1428
1429
    DerivedVerticalCRSNNPtr buildDerivedVerticalCRS(const WKTNodeNNPtr &node);
1430
1431
    CRSNNPtr buildCompoundCRS(const WKTNodeNNPtr &node);
1432
1433
    BoundCRSNNPtr buildBoundCRS(const WKTNodeNNPtr &node);
1434
1435
    TemporalCSNNPtr buildTemporalCS(const WKTNodeNNPtr &parentNode);
1436
1437
    TemporalCRSNNPtr buildTemporalCRS(const WKTNodeNNPtr &node);
1438
1439
    DerivedTemporalCRSNNPtr buildDerivedTemporalCRS(const WKTNodeNNPtr &node);
1440
1441
    EngineeringCRSNNPtr buildEngineeringCRS(const WKTNodeNNPtr &node);
1442
1443
    EngineeringCRSNNPtr
1444
    buildEngineeringCRSFromLocalCS(const WKTNodeNNPtr &node);
1445
1446
    DerivedEngineeringCRSNNPtr
1447
    buildDerivedEngineeringCRS(const WKTNodeNNPtr &node);
1448
1449
    ParametricCSNNPtr buildParametricCS(const WKTNodeNNPtr &parentNode);
1450
1451
    ParametricCRSNNPtr buildParametricCRS(const WKTNodeNNPtr &node);
1452
1453
    DerivedParametricCRSNNPtr
1454
    buildDerivedParametricCRS(const WKTNodeNNPtr &node);
1455
1456
    DerivedProjectedCRSNNPtr buildDerivedProjectedCRS(const WKTNodeNNPtr &node);
1457
1458
    CRSPtr buildCRS(const WKTNodeNNPtr &node);
1459
1460
    TransformationNNPtr buildCoordinateOperation(const WKTNodeNNPtr &node);
1461
1462
    PointMotionOperationNNPtr
1463
    buildPointMotionOperation(const WKTNodeNNPtr &node);
1464
1465
    ConcatenatedOperationNNPtr
1466
    buildConcatenatedOperation(const WKTNodeNNPtr &node);
1467
1468
    CoordinateMetadataNNPtr buildCoordinateMetadata(const WKTNodeNNPtr &node);
1469
};
1470
//! @endcond
1471
1472
// ---------------------------------------------------------------------------
1473
1474
2.89k
WKTParser::WKTParser() : d(std::make_unique<Private>()) {}
1475
1476
// ---------------------------------------------------------------------------
1477
1478
//! @cond Doxygen_Suppress
1479
2.89k
WKTParser::~WKTParser() = default;
1480
//! @endcond
1481
1482
// ---------------------------------------------------------------------------
1483
1484
/** \brief Set whether parsing should be done in strict mode.
1485
 */
1486
2.89k
WKTParser &WKTParser::setStrict(bool strict) {
1487
2.89k
    d->strict_ = strict;
1488
2.89k
    return *this;
1489
2.89k
}
1490
1491
// ---------------------------------------------------------------------------
1492
1493
/** \brief Set whether object identifiers should be unset when there is
1494
 *         a contradiction between the definition from WKT and the one from
1495
 *         the database.
1496
 *
1497
 * At time of writing, this only applies to the base geographic CRS of a
1498
 * projected CRS, when comparing its coordinate system.
1499
 */
1500
0
WKTParser &WKTParser::setUnsetIdentifiersIfIncompatibleDef(bool unset) {
1501
0
    d->unsetIdentifiersIfIncompatibleDef_ = unset;
1502
0
    return *this;
1503
0
}
1504
1505
// ---------------------------------------------------------------------------
1506
1507
/** \brief Return the list of warnings found during parsing.
1508
 *
1509
 * \note The list might be non-empty only is setStrict(false) has been called.
1510
 */
1511
0
std::list<std::string> WKTParser::warningList() const {
1512
0
    return d->warningList_;
1513
0
}
1514
1515
// ---------------------------------------------------------------------------
1516
1517
/** \brief Return the list of grammar errors found during parsing.
1518
 *
1519
 * Grammar errors are non-compliance issues with respect to the WKT grammar.
1520
 *
1521
 * \note The list might be non-empty only is setStrict(false) has been called.
1522
 *
1523
 * @since PROJ 9.5
1524
 */
1525
0
std::list<std::string> WKTParser::grammarErrorList() const {
1526
0
    return d->grammarErrorList_;
1527
0
}
1528
1529
// ---------------------------------------------------------------------------
1530
1531
//! @cond Doxygen_Suppress
1532
2.63k
void WKTParser::Private::emitRecoverableWarning(const std::string &errorMsg) {
1533
2.63k
    if (strict_) {
1534
0
        throw ParsingException(errorMsg);
1535
2.63k
    } else {
1536
2.63k
        warningList_.push_back(errorMsg);
1537
2.63k
    }
1538
2.63k
}
1539
//! @endcond
1540
1541
// ---------------------------------------------------------------------------
1542
1543
//! @cond Doxygen_Suppress
1544
1.00k
void WKTParser::Private::emitGrammarError(const std::string &errorMsg) {
1545
1.00k
    if (strict_) {
1546
0
        throw ParsingException(errorMsg);
1547
1.00k
    } else {
1548
1.00k
        grammarErrorList_.push_back(errorMsg);
1549
1.00k
    }
1550
1.00k
}
1551
//! @endcond
1552
1553
// ---------------------------------------------------------------------------
1554
1555
12.0k
static double asDouble(const std::string &val) { return c_locale_stod(val); }
1556
1557
// ---------------------------------------------------------------------------
1558
1559
147
PROJ_NO_RETURN static void ThrowNotEnoughChildren(const std::string &nodeName) {
1560
147
    throw ParsingException(
1561
147
        concat("not enough children in ", nodeName, " node"));
1562
147
}
1563
1564
// ---------------------------------------------------------------------------
1565
1566
PROJ_NO_RETURN static void
1567
27
ThrowNotRequiredNumberOfChildren(const std::string &nodeName) {
1568
27
    throw ParsingException(
1569
27
        concat("not required number of children in ", nodeName, " node"));
1570
27
}
1571
1572
// ---------------------------------------------------------------------------
1573
1574
333
PROJ_NO_RETURN static void ThrowMissing(const std::string &nodeName) {
1575
333
    throw ParsingException(concat("missing ", nodeName, " node"));
1576
333
}
1577
1578
// ---------------------------------------------------------------------------
1579
1580
PROJ_NO_RETURN static void
1581
0
ThrowNotExpectedCSType(const std::string &expectedCSType) {
1582
0
    throw ParsingException(concat("CS node is not of type ", expectedCSType));
1583
0
}
1584
1585
// ---------------------------------------------------------------------------
1586
1587
static ParsingException buildRethrow(const char *funcName,
1588
77
                                     const std::exception &e) {
1589
77
    std::string res(funcName);
1590
77
    res += ": ";
1591
77
    res += e.what();
1592
77
    return ParsingException(res);
1593
77
}
1594
1595
// ---------------------------------------------------------------------------
1596
1597
//! @cond Doxygen_Suppress
1598
32.2k
std::string WKTParser::Private::stripQuotes(const WKTNodeNNPtr &node) {
1599
32.2k
    return ::stripQuotes(node->GP()->value());
1600
32.2k
}
1601
1602
// ---------------------------------------------------------------------------
1603
1604
9.54k
double WKTParser::Private::asDouble(const WKTNodeNNPtr &node) {
1605
9.54k
    return io::asDouble(node->GP()->value());
1606
9.54k
}
1607
1608
// ---------------------------------------------------------------------------
1609
1610
IdentifierPtr WKTParser::Private::buildId(const WKTNodeNNPtr &parentNode,
1611
                                          const WKTNodeNNPtr &node,
1612
2.73k
                                          bool tolerant, bool removeInverseOf) {
1613
2.73k
    const auto *nodeP = node->GP();
1614
2.73k
    const auto &nodeChildren = nodeP->children();
1615
2.73k
    if (nodeChildren.size() >= 2) {
1616
2.28k
        auto codeSpace = stripQuotes(nodeChildren[0]);
1617
2.28k
        if (removeInverseOf && starts_with(codeSpace, "INVERSE(") &&
1618
53
            codeSpace.back() == ')') {
1619
48
            codeSpace = codeSpace.substr(strlen("INVERSE("));
1620
48
            codeSpace.resize(codeSpace.size() - 1);
1621
48
        }
1622
1623
2.28k
        PropertyMap propertiesId;
1624
2.28k
        if (nodeChildren.size() >= 3 &&
1625
1.26k
            nodeChildren[2]->GP()->childrenSize() == 0) {
1626
1.04k
            std::string version = stripQuotes(nodeChildren[2]);
1627
1628
            // IAU + 2015 -> IAU_2015
1629
1.04k
            if (dbContext_) {
1630
730
                std::string codeSpaceOut;
1631
730
                if (dbContext_->getVersionedAuthority(codeSpace, version,
1632
730
                                                      codeSpaceOut)) {
1633
0
                    codeSpace = std::move(codeSpaceOut);
1634
0
                    version.clear();
1635
0
                }
1636
730
            }
1637
1638
1.04k
            if (!version.empty()) {
1639
1.00k
                propertiesId.set(Identifier::VERSION_KEY, version);
1640
1.00k
            }
1641
1.04k
        }
1642
1643
2.28k
        auto code = stripQuotes(nodeChildren[1]);
1644
1645
        // Prior to PROJ 9.5, when synthetizing an ID for a CONVERSION UTM Zone
1646
        // south, we generated a wrong value. Auto-fix that
1647
2.28k
        const auto &parentNodeKeyword(parentNode->GP()->value());
1648
2.28k
        if (parentNodeKeyword == WKTConstants::CONVERSION &&
1649
239
            codeSpace == Identifier::EPSG) {
1650
25
            const auto &parentNodeChildren = parentNode->GP()->children();
1651
25
            if (!parentNodeChildren.empty()) {
1652
25
                const auto parentNodeName(stripQuotes(parentNodeChildren[0]));
1653
25
                if (ci_starts_with(parentNodeName, "UTM Zone ") &&
1654
0
                    parentNodeName.find('S') != std::string::npos) {
1655
0
                    const int nZone =
1656
0
                        atoi(parentNodeName.c_str() + strlen("UTM Zone "));
1657
0
                    if (nZone >= 1 && nZone <= 60) {
1658
0
                        code = internal::toString(16100 + nZone);
1659
0
                    }
1660
0
                }
1661
25
            }
1662
25
        }
1663
1664
2.28k
        auto &citationNode = nodeP->lookForChild(WKTConstants::CITATION);
1665
2.28k
        auto &uriNode = nodeP->lookForChild(WKTConstants::URI);
1666
1667
2.28k
        propertiesId.set(Identifier::CODESPACE_KEY, codeSpace);
1668
2.28k
        bool authoritySet = false;
1669
2.28k
        /*if (!isNull(citationNode))*/ {
1670
2.28k
            const auto *citationNodeP = citationNode->GP();
1671
2.28k
            if (citationNodeP->childrenSize() == 1) {
1672
10
                authoritySet = true;
1673
10
                propertiesId.set(Identifier::AUTHORITY_KEY,
1674
10
                                 stripQuotes(citationNodeP->children()[0]));
1675
10
            }
1676
2.28k
        }
1677
2.28k
        if (!authoritySet) {
1678
2.27k
            propertiesId.set(Identifier::AUTHORITY_KEY, codeSpace);
1679
2.27k
        }
1680
2.28k
        /*if (!isNull(uriNode))*/ {
1681
2.28k
            const auto *uriNodeP = uriNode->GP();
1682
2.28k
            if (uriNodeP->childrenSize() == 1) {
1683
14
                propertiesId.set(Identifier::URI_KEY,
1684
14
                                 stripQuotes(uriNodeP->children()[0]));
1685
14
            }
1686
2.28k
        }
1687
2.28k
        return Identifier::create(code, propertiesId);
1688
2.28k
    } else if (strict_ || !tolerant) {
1689
5
        ThrowNotEnoughChildren(nodeP->value());
1690
442
    } else {
1691
442
        std::string msg("not enough children in ");
1692
442
        msg += nodeP->value();
1693
442
        msg += " node";
1694
442
        warningList_.emplace_back(std::move(msg));
1695
442
    }
1696
442
    return nullptr;
1697
2.73k
}
1698
1699
// ---------------------------------------------------------------------------
1700
1701
PropertyMap &WKTParser::Private::buildProperties(const WKTNodeNNPtr &node,
1702
                                                 bool removeInverseOf,
1703
13.0k
                                                 bool hasName) {
1704
1705
13.0k
    if (properties_.size() >= MAX_PROPERTY_SIZE) {
1706
0
        throw ParsingException("MAX_PROPERTY_SIZE reached");
1707
0
    }
1708
13.0k
    properties_.push_back(std::make_unique<PropertyMap>());
1709
13.0k
    auto properties = properties_.back().get();
1710
1711
13.0k
    std::string authNameFromAlias;
1712
13.0k
    std::string codeFromAlias;
1713
13.0k
    const auto *nodeP = node->GP();
1714
13.0k
    const auto &nodeChildren = nodeP->children();
1715
1716
13.0k
    auto identifiers = ArrayOfBaseObject::create();
1717
48.7k
    for (const auto &subNode : nodeChildren) {
1718
48.7k
        const auto &subNodeName(subNode->GP()->value());
1719
48.7k
        if (ci_equal(subNodeName, WKTConstants::ID) ||
1720
46.1k
            ci_equal(subNodeName, WKTConstants::AUTHORITY)) {
1721
2.70k
            auto id = buildId(node, subNode, true, removeInverseOf);
1722
2.70k
            if (id) {
1723
2.26k
                identifiers->add(NN_NO_CHECK(id));
1724
2.26k
            }
1725
2.70k
        }
1726
48.7k
    }
1727
1728
13.0k
    if (hasName && !nodeChildren.empty()) {
1729
12.1k
        const auto &nodeName(nodeP->value());
1730
12.1k
        auto name(stripQuotes(nodeChildren[0]));
1731
12.1k
        if (removeInverseOf && starts_with(name, "Inverse of ")) {
1732
94
            name = name.substr(strlen("Inverse of "));
1733
94
        }
1734
1735
12.1k
        if (ends_with(name, " (deprecated)")) {
1736
2
            name.resize(name.size() - strlen(" (deprecated)"));
1737
2
            properties->set(common::IdentifiedObject::DEPRECATED_KEY, true);
1738
2
        }
1739
1740
        // Oracle WKT can contain names like
1741
        // "Reseau Geodesique Francais 1993 (EPSG ID 6171)"
1742
        // for WKT attributes to the auth_name = "IGN - Paris"
1743
        // Strip that suffix from the name and assign a true EPSG code to the
1744
        // object
1745
12.1k
        if (identifiers->empty()) {
1746
11.5k
            const auto pos = name.find(" (EPSG ID ");
1747
11.5k
            if (pos != std::string::npos && name.back() == ')') {
1748
157
                const auto code =
1749
157
                    name.substr(pos + strlen(" (EPSG ID "),
1750
157
                                name.size() - 1 - pos - strlen(" (EPSG ID "));
1751
157
                name.resize(pos);
1752
1753
157
                PropertyMap propertiesId;
1754
157
                propertiesId.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
1755
157
                propertiesId.set(Identifier::AUTHORITY_KEY, Identifier::EPSG);
1756
157
                identifiers->add(Identifier::create(code, propertiesId));
1757
157
            }
1758
11.5k
        }
1759
1760
12.1k
        const char *tableNameForAlias = nullptr;
1761
12.1k
        if (ci_equal(nodeName, WKTConstants::GEOGCS)) {
1762
1.25k
            if (starts_with(name, "GCS_")) {
1763
333
                esriStyle_ = true;
1764
333
                if (name == "GCS_WGS_1984") {
1765
154
                    name = "WGS 84";
1766
179
                } else if (name == "GCS_unknown") {
1767
0
                    name = "unknown";
1768
179
                } else {
1769
179
                    tableNameForAlias = "geodetic_crs";
1770
179
                }
1771
333
            }
1772
10.9k
        } else if (esriStyle_ && ci_equal(nodeName, WKTConstants::SPHEROID)) {
1773
369
            if (name == "WGS_1984") {
1774
154
                name = "WGS 84";
1775
154
                authNameFromAlias = Identifier::EPSG;
1776
154
                codeFromAlias = "7030";
1777
215
            } else {
1778
215
                tableNameForAlias = "ellipsoid";
1779
215
            }
1780
369
        }
1781
1782
12.1k
        if (dbContext_ && tableNameForAlias) {
1783
366
            std::string outTableName;
1784
366
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
1785
366
                                                        std::string());
1786
366
            auto officialName = authFactory->getOfficialNameFromAlias(
1787
366
                name, tableNameForAlias, "ESRI", false, outTableName,
1788
366
                authNameFromAlias, codeFromAlias);
1789
366
            if (!officialName.empty()) {
1790
169
                name = std::move(officialName);
1791
1792
                // Clearing authority for geodetic_crs because of
1793
                // potential axis order mismatch.
1794
169
                if (strcmp(tableNameForAlias, "geodetic_crs") == 0) {
1795
135
                    authNameFromAlias.clear();
1796
135
                    codeFromAlias.clear();
1797
135
                }
1798
169
            }
1799
366
        }
1800
1801
12.1k
        properties->set(IdentifiedObject::NAME_KEY, name);
1802
12.1k
    }
1803
1804
13.0k
    if (identifiers->empty() && !authNameFromAlias.empty()) {
1805
188
        identifiers->add(Identifier::create(
1806
188
            codeFromAlias,
1807
188
            PropertyMap()
1808
188
                .set(Identifier::CODESPACE_KEY, authNameFromAlias)
1809
188
                .set(Identifier::AUTHORITY_KEY, authNameFromAlias)));
1810
188
    }
1811
13.0k
    if (!identifiers->empty()) {
1812
971
        properties->set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
1813
971
    }
1814
1815
13.0k
    auto &remarkNode = nodeP->lookForChild(WKTConstants::REMARK);
1816
13.0k
    if (!isNull(remarkNode)) {
1817
65
        const auto &remarkChildren = remarkNode->GP()->children();
1818
65
        if (remarkChildren.size() == 1) {
1819
62
            properties->set(IdentifiedObject::REMARKS_KEY,
1820
62
                            stripQuotes(remarkChildren[0]));
1821
62
        } else {
1822
3
            ThrowNotRequiredNumberOfChildren(remarkNode->GP()->value());
1823
3
        }
1824
65
    }
1825
1826
13.0k
    ArrayOfBaseObjectNNPtr array = ArrayOfBaseObject::create();
1827
48.7k
    for (const auto &subNode : nodeP->children()) {
1828
48.7k
        const auto &subNodeName(subNode->GP()->value());
1829
48.7k
        if (ci_equal(subNodeName, WKTConstants::USAGE)) {
1830
115
            auto objectDomain = buildObjectDomain(subNode);
1831
115
            if (!objectDomain) {
1832
1
                throw ParsingException(
1833
1
                    concat("missing children in ", subNodeName, " node"));
1834
1
            }
1835
114
            array->add(NN_NO_CHECK(objectDomain));
1836
114
        }
1837
48.7k
    }
1838
13.0k
    if (!array->empty()) {
1839
33
        properties->set(ObjectUsage::OBJECT_DOMAIN_KEY, array);
1840
12.9k
    } else {
1841
12.9k
        auto objectDomain = buildObjectDomain(node);
1842
12.9k
        if (objectDomain) {
1843
344
            properties->set(ObjectUsage::OBJECT_DOMAIN_KEY,
1844
344
                            NN_NO_CHECK(objectDomain));
1845
344
        }
1846
12.9k
    }
1847
1848
13.0k
    auto &versionNode = nodeP->lookForChild(WKTConstants::VERSION);
1849
13.0k
    if (!isNull(versionNode)) {
1850
23
        const auto &versionChildren = versionNode->GP()->children();
1851
23
        if (versionChildren.size() == 1) {
1852
20
            properties->set(CoordinateOperation::OPERATION_VERSION_KEY,
1853
20
                            stripQuotes(versionChildren[0]));
1854
20
        } else {
1855
3
            ThrowNotRequiredNumberOfChildren(versionNode->GP()->value());
1856
3
        }
1857
23
    }
1858
1859
13.0k
    return *properties;
1860
13.0k
}
1861
1862
// ---------------------------------------------------------------------------
1863
1864
ObjectDomainPtr
1865
13.0k
WKTParser::Private::buildObjectDomain(const WKTNodeNNPtr &node) {
1866
1867
13.0k
    const auto *nodeP = node->GP();
1868
13.0k
    auto &scopeNode = nodeP->lookForChild(WKTConstants::SCOPE);
1869
13.0k
    auto &areaNode = nodeP->lookForChild(WKTConstants::AREA);
1870
13.0k
    auto &bboxNode = nodeP->lookForChild(WKTConstants::BBOX);
1871
13.0k
    auto &verticalExtentNode =
1872
13.0k
        nodeP->lookForChild(WKTConstants::VERTICALEXTENT);
1873
13.0k
    auto &temporalExtentNode = nodeP->lookForChild(WKTConstants::TIMEEXTENT);
1874
13.0k
    if (!isNull(scopeNode) || !isNull(areaNode) || !isNull(bboxNode) ||
1875
12.6k
        !isNull(verticalExtentNode) || !isNull(temporalExtentNode)) {
1876
490
        optional<std::string> scope;
1877
490
        const auto *scopeNodeP = scopeNode->GP();
1878
490
        const auto &scopeChildren = scopeNodeP->children();
1879
490
        if (scopeChildren.size() == 1) {
1880
0
            scope = stripQuotes(scopeChildren[0]);
1881
0
        }
1882
490
        ExtentPtr extent;
1883
490
        if (!isNull(areaNode) || !isNull(bboxNode)) {
1884
463
            util::optional<std::string> description;
1885
463
            std::vector<GeographicExtentNNPtr> geogExtent;
1886
463
            std::vector<VerticalExtentNNPtr> verticalExtent;
1887
463
            std::vector<TemporalExtentNNPtr> temporalExtent;
1888
463
            if (!isNull(areaNode)) {
1889
114
                const auto &areaChildren = areaNode->GP()->children();
1890
114
                if (areaChildren.size() == 1) {
1891
113
                    description = stripQuotes(areaChildren[0]);
1892
113
                } else {
1893
1
                    ThrowNotRequiredNumberOfChildren(areaNode->GP()->value());
1894
1
                }
1895
114
            }
1896
462
            if (!isNull(bboxNode)) {
1897
349
                const auto &bboxChildren = bboxNode->GP()->children();
1898
349
                if (bboxChildren.size() == 4) {
1899
336
                    double south, west, north, east;
1900
336
                    try {
1901
336
                        south = asDouble(bboxChildren[0]);
1902
336
                        west = asDouble(bboxChildren[1]);
1903
336
                        north = asDouble(bboxChildren[2]);
1904
336
                        east = asDouble(bboxChildren[3]);
1905
336
                    } catch (const std::exception &) {
1906
4
                        throw ParsingException(concat("not 4 double values in ",
1907
4
                                                      bboxNode->GP()->value(),
1908
4
                                                      " node"));
1909
4
                    }
1910
332
                    try {
1911
332
                        auto bbox = GeographicBoundingBox::create(west, south,
1912
332
                                                                  east, north);
1913
332
                        geogExtent.emplace_back(bbox);
1914
332
                    } catch (const std::exception &e) {
1915
4
                        throw ParsingException(concat("Invalid ",
1916
4
                                                      bboxNode->GP()->value(),
1917
4
                                                      " node: ") +
1918
4
                                               e.what());
1919
4
                    }
1920
332
                } else {
1921
13
                    ThrowNotRequiredNumberOfChildren(bboxNode->GP()->value());
1922
13
                }
1923
349
            }
1924
1925
441
            if (!isNull(verticalExtentNode)) {
1926
20
                const auto &verticalExtentChildren =
1927
20
                    verticalExtentNode->GP()->children();
1928
20
                const auto verticalExtentChildrenSize =
1929
20
                    verticalExtentChildren.size();
1930
20
                if (verticalExtentChildrenSize == 2 ||
1931
17
                    verticalExtentChildrenSize == 3) {
1932
17
                    double min;
1933
17
                    double max;
1934
17
                    try {
1935
17
                        min = asDouble(verticalExtentChildren[0]);
1936
17
                        max = asDouble(verticalExtentChildren[1]);
1937
17
                    } catch (const std::exception &) {
1938
3
                        throw ParsingException(
1939
3
                            concat("not 2 double values in ",
1940
3
                                   verticalExtentNode->GP()->value(), " node"));
1941
3
                    }
1942
14
                    UnitOfMeasure unit = UnitOfMeasure::METRE;
1943
14
                    if (verticalExtentChildrenSize == 3) {
1944
1
                        unit = buildUnit(verticalExtentChildren[2],
1945
1
                                         UnitOfMeasure::Type::LINEAR);
1946
1
                    }
1947
14
                    verticalExtent.emplace_back(VerticalExtent::create(
1948
14
                        min, max, util::nn_make_shared<UnitOfMeasure>(unit)));
1949
14
                } else {
1950
3
                    ThrowNotRequiredNumberOfChildren(
1951
3
                        verticalExtentNode->GP()->value());
1952
3
                }
1953
20
            }
1954
1955
435
            if (!isNull(temporalExtentNode)) {
1956
92
                const auto &temporalExtentChildren =
1957
92
                    temporalExtentNode->GP()->children();
1958
92
                if (temporalExtentChildren.size() == 2) {
1959
88
                    temporalExtent.emplace_back(TemporalExtent::create(
1960
88
                        stripQuotes(temporalExtentChildren[0]),
1961
88
                        stripQuotes(temporalExtentChildren[1])));
1962
88
                } else {
1963
4
                    ThrowNotRequiredNumberOfChildren(
1964
4
                        temporalExtentNode->GP()->value());
1965
4
                }
1966
92
            }
1967
431
            extent = Extent::create(description, geogExtent, verticalExtent,
1968
431
                                    temporalExtent)
1969
431
                         .as_nullable();
1970
431
        }
1971
458
        return ObjectDomain::create(scope, extent).as_nullable();
1972
490
    }
1973
1974
12.5k
    return nullptr;
1975
13.0k
}
1976
1977
// ---------------------------------------------------------------------------
1978
1979
UnitOfMeasure WKTParser::Private::buildUnit(const WKTNodeNNPtr &node,
1980
2.46k
                                            UnitOfMeasure::Type type) {
1981
2.46k
    const auto *nodeP = node->GP();
1982
2.46k
    const auto &children = nodeP->children();
1983
2.46k
    if ((type != UnitOfMeasure::Type::TIME && children.size() < 2) ||
1984
2.45k
        (type == UnitOfMeasure::Type::TIME && children.size() < 1)) {
1985
17
        ThrowNotEnoughChildren(nodeP->value());
1986
17
    }
1987
2.44k
    try {
1988
2.44k
        std::string unitName(stripQuotes(children[0]));
1989
2.44k
        PropertyMap properties(buildProperties(node));
1990
2.44k
        auto &idNode =
1991
2.44k
            nodeP->lookForChild(WKTConstants::ID, WKTConstants::AUTHORITY);
1992
2.44k
        if (!isNull(idNode) && idNode->GP()->childrenSize() < 2) {
1993
131
            emitRecoverableWarning("not enough children in " +
1994
131
                                   idNode->GP()->value() + " node");
1995
131
        }
1996
2.44k
        const bool hasValidIdNode =
1997
2.44k
            !isNull(idNode) && idNode->GP()->childrenSize() >= 2;
1998
1999
2.44k
        const auto &idNodeChildren(idNode->GP()->children());
2000
2.44k
        std::string codeSpace(hasValidIdNode ? stripQuotes(idNodeChildren[0])
2001
2.44k
                                             : std::string());
2002
2.44k
        std::string code(hasValidIdNode ? stripQuotes(idNodeChildren[1])
2003
2.44k
                                        : std::string());
2004
2005
2.44k
        bool queryDb = true;
2006
2.44k
        if (type == UnitOfMeasure::Type::UNKNOWN) {
2007
29
            if (ci_equal(unitName, "METER") || ci_equal(unitName, "METRE")) {
2008
0
                type = UnitOfMeasure::Type::LINEAR;
2009
0
                unitName = "metre";
2010
0
                if (codeSpace.empty()) {
2011
0
                    codeSpace = Identifier::EPSG;
2012
0
                    code = "9001";
2013
0
                    queryDb = false;
2014
0
                }
2015
29
            } else if (ci_equal(unitName, "DEGREE") ||
2016
29
                       ci_equal(unitName, "GRAD")) {
2017
0
                type = UnitOfMeasure::Type::ANGULAR;
2018
0
            }
2019
29
        }
2020
2021
2.44k
        if (esriStyle_ && dbContext_ && queryDb) {
2022
1.27k
            std::string outTableName;
2023
1.27k
            std::string authNameFromAlias;
2024
1.27k
            std::string codeFromAlias;
2025
1.27k
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2026
1.27k
                                                        std::string());
2027
1.27k
            auto officialName = authFactory->getOfficialNameFromAlias(
2028
1.27k
                unitName, "unit_of_measure", "ESRI", false, outTableName,
2029
1.27k
                authNameFromAlias, codeFromAlias);
2030
1.27k
            if (!officialName.empty()) {
2031
622
                unitName = std::move(officialName);
2032
622
                codeSpace = std::move(authNameFromAlias);
2033
622
                code = std::move(codeFromAlias);
2034
622
            }
2035
1.27k
        }
2036
2037
2.44k
        double convFactor = children.size() >= 2 ? asDouble(children[1]) : 0.0;
2038
2.44k
        constexpr double US_FOOT_CONV_FACTOR = 12.0 / 39.37;
2039
2.44k
        constexpr double REL_ERROR = 1e-10;
2040
        // Fix common rounding errors
2041
2.44k
        if (std::fabs(convFactor - UnitOfMeasure::DEGREE.conversionToSI()) <
2042
2.44k
            REL_ERROR * convFactor) {
2043
660
            convFactor = UnitOfMeasure::DEGREE.conversionToSI();
2044
1.78k
        } else if (std::fabs(convFactor - US_FOOT_CONV_FACTOR) <
2045
1.78k
                   REL_ERROR * convFactor) {
2046
10
            convFactor = US_FOOT_CONV_FACTOR;
2047
10
        }
2048
2049
2.44k
        return UnitOfMeasure(unitName, convFactor, type, codeSpace, code);
2050
2.44k
    } catch (const std::exception &e) {
2051
16
        throw buildRethrow(__FUNCTION__, e);
2052
16
    }
2053
2.44k
}
2054
2055
// ---------------------------------------------------------------------------
2056
2057
// node here is a parent node, not a UNIT/LENGTHUNIT/ANGLEUNIT/TIMEUNIT/... node
2058
UnitOfMeasure WKTParser::Private::buildUnitInSubNode(const WKTNodeNNPtr &node,
2059
7.84k
                                                     UnitOfMeasure::Type type) {
2060
7.84k
    const auto *nodeP = node->GP();
2061
7.84k
    {
2062
7.84k
        auto &unitNode = nodeP->lookForChild(WKTConstants::LENGTHUNIT);
2063
7.84k
        if (!isNull(unitNode)) {
2064
3
            return buildUnit(unitNode, UnitOfMeasure::Type::LINEAR);
2065
3
        }
2066
7.84k
    }
2067
2068
7.84k
    {
2069
7.84k
        auto &unitNode = nodeP->lookForChild(WKTConstants::ANGLEUNIT);
2070
7.84k
        if (!isNull(unitNode)) {
2071
5
            return buildUnit(unitNode, UnitOfMeasure::Type::ANGULAR);
2072
5
        }
2073
7.84k
    }
2074
2075
7.84k
    {
2076
7.84k
        auto &unitNode = nodeP->lookForChild(WKTConstants::SCALEUNIT);
2077
7.84k
        if (!isNull(unitNode)) {
2078
5
            return buildUnit(unitNode, UnitOfMeasure::Type::SCALE);
2079
5
        }
2080
7.84k
    }
2081
2082
7.83k
    {
2083
7.83k
        auto &unitNode = nodeP->lookForChild(WKTConstants::TIMEUNIT);
2084
7.83k
        if (!isNull(unitNode)) {
2085
1
            return buildUnit(unitNode, UnitOfMeasure::Type::TIME);
2086
1
        }
2087
7.83k
    }
2088
7.83k
    {
2089
7.83k
        auto &unitNode = nodeP->lookForChild(WKTConstants::TEMPORALQUANTITY);
2090
7.83k
        if (!isNull(unitNode)) {
2091
8
            return buildUnit(unitNode, UnitOfMeasure::Type::TIME);
2092
8
        }
2093
7.83k
    }
2094
2095
7.82k
    {
2096
7.82k
        auto &unitNode = nodeP->lookForChild(WKTConstants::PARAMETRICUNIT);
2097
7.82k
        if (!isNull(unitNode)) {
2098
2
            return buildUnit(unitNode, UnitOfMeasure::Type::PARAMETRIC);
2099
2
        }
2100
7.82k
    }
2101
2102
7.82k
    {
2103
7.82k
        auto &unitNode = nodeP->lookForChild(WKTConstants::UNIT);
2104
7.82k
        if (!isNull(unitNode)) {
2105
2.43k
            return buildUnit(unitNode, type);
2106
2.43k
        }
2107
7.82k
    }
2108
2109
5.38k
    return UnitOfMeasure::NONE;
2110
7.82k
}
2111
2112
// ---------------------------------------------------------------------------
2113
2114
2.15k
EllipsoidNNPtr WKTParser::Private::buildEllipsoid(const WKTNodeNNPtr &node) {
2115
2.15k
    const auto *nodeP = node->GP();
2116
2.15k
    const auto &children = nodeP->children();
2117
2.15k
    if (children.size() < 3) {
2118
7
        ThrowNotEnoughChildren(nodeP->value());
2119
7
    }
2120
2.15k
    try {
2121
2.15k
        UnitOfMeasure unit =
2122
2.15k
            buildUnitInSubNode(node, UnitOfMeasure::Type::LINEAR);
2123
2.15k
        if (unit == UnitOfMeasure::NONE) {
2124
1.56k
            unit = UnitOfMeasure::METRE;
2125
1.56k
        }
2126
2.15k
        Length semiMajorAxis(asDouble(children[1]), unit);
2127
        // Some WKT in the wild use "inf". Cf SPHEROID["unnamed",6370997,"inf"]
2128
        // in https://zenodo.org/record/3878979#.Y_P4g4CZNH4,
2129
        // https://zenodo.org/record/5831940#.Y_P4i4CZNH5
2130
        // or https://grasswiki.osgeo.org/wiki/Marine_Science
2131
2.15k
        const auto &invFlatteningChild = children[2];
2132
2.15k
        if (invFlatteningChild->GP()->value() == "\"inf\"") {
2133
0
            emitRecoverableWarning("Inverse flattening = \"inf\" is not "
2134
0
                                   "conformant, but understood");
2135
0
        }
2136
2.15k
        Scale invFlattening(invFlatteningChild->GP()->value() == "\"inf\""
2137
2.15k
                                ? 0
2138
2.15k
                                : asDouble(invFlatteningChild));
2139
2.15k
        const auto ellpsProperties = buildProperties(node);
2140
2.15k
        std::string ellpsName;
2141
2.15k
        ellpsProperties.getStringValue(IdentifiedObject::NAME_KEY, ellpsName);
2142
2.15k
        const auto celestialBody(Ellipsoid::guessBodyName(
2143
2.15k
            dbContext_, semiMajorAxis.getSIValue(), ellpsName));
2144
2.15k
        if (invFlattening.getSIValue() == 0) {
2145
964
            return Ellipsoid::createSphere(ellpsProperties, semiMajorAxis,
2146
964
                                           celestialBody);
2147
1.18k
        } else {
2148
1.18k
            return Ellipsoid::createFlattenedSphere(
2149
1.18k
                ellpsProperties, semiMajorAxis, invFlattening, celestialBody);
2150
1.18k
        }
2151
2.15k
    } catch (const std::exception &e) {
2152
50
        throw buildRethrow(__FUNCTION__, e);
2153
50
    }
2154
2.15k
}
2155
2156
// ---------------------------------------------------------------------------
2157
2158
PrimeMeridianNNPtr WKTParser::Private::buildPrimeMeridian(
2159
354
    const WKTNodeNNPtr &node, const UnitOfMeasure &defaultAngularUnit) {
2160
354
    const auto *nodeP = node->GP();
2161
354
    const auto &children = nodeP->children();
2162
354
    if (children.size() < 2) {
2163
3
        ThrowNotEnoughChildren(nodeP->value());
2164
3
    }
2165
351
    auto name = stripQuotes(children[0]);
2166
351
    UnitOfMeasure unit = buildUnitInSubNode(node, UnitOfMeasure::Type::ANGULAR);
2167
351
    if (unit == UnitOfMeasure::NONE) {
2168
351
        unit = defaultAngularUnit;
2169
351
        if (unit == UnitOfMeasure::NONE) {
2170
0
            unit = UnitOfMeasure::DEGREE;
2171
0
        }
2172
351
    }
2173
351
    try {
2174
351
        double angleValue = asDouble(children[1]);
2175
2176
        // Correct for GDAL WKT1 and WKT1-ESRI departure
2177
351
        if (name == "Paris" && std::fabs(angleValue - 2.33722917) < 1e-8 &&
2178
0
            unit._isEquivalentTo(UnitOfMeasure::GRAD,
2179
0
                                 util::IComparable::Criterion::EQUIVALENT)) {
2180
0
            angleValue = 2.5969213;
2181
351
        } else {
2182
351
            static const struct {
2183
351
                const char *name;
2184
351
                int deg;
2185
351
                int min;
2186
351
                double sec;
2187
351
            } primeMeridiansDMS[] = {
2188
351
                {"Lisbon", -9, 7, 54.862},  {"Bogota", -74, 4, 51.3},
2189
351
                {"Madrid", -3, 41, 14.55},  {"Rome", 12, 27, 8.4},
2190
351
                {"Bern", 7, 26, 22.5},      {"Jakarta", 106, 48, 27.79},
2191
351
                {"Ferro", -17, 40, 0},      {"Brussels", 4, 22, 4.71},
2192
351
                {"Stockholm", 18, 3, 29.8}, {"Athens", 23, 42, 58.815},
2193
351
                {"Oslo", 10, 43, 22.5},     {"Paris RGS", 2, 20, 13.95},
2194
351
                {"Paris_RGS", 2, 20, 13.95}};
2195
2196
            // Current epsg.org output may use the EPSG:9110 "sexagesimal DMS"
2197
            // unit and a DD.MMSSsss value, but this will likely be changed to
2198
            // use decimal degree.
2199
            // Or WKT1 may for example use the Paris RGS decimal degree value
2200
            // but with a GEOGCS with UNIT["Grad"]
2201
4.47k
            for (const auto &pmDef : primeMeridiansDMS) {
2202
4.47k
                if (name == pmDef.name) {
2203
2
                    double dmsAsDecimalValue =
2204
2
                        (pmDef.deg >= 0 ? 1 : -1) *
2205
2
                        (std::abs(pmDef.deg) + pmDef.min / 100. +
2206
2
                         pmDef.sec / 10000.);
2207
2
                    double dmsAsDecimalDegreeValue =
2208
2
                        (pmDef.deg >= 0 ? 1 : -1) *
2209
2
                        (std::abs(pmDef.deg) + pmDef.min / 60. +
2210
2
                         pmDef.sec / 3600.);
2211
2
                    if (std::fabs(angleValue - dmsAsDecimalValue) < 1e-8 ||
2212
2
                        std::fabs(angleValue - dmsAsDecimalDegreeValue) <
2213
2
                            1e-8) {
2214
0
                        angleValue = dmsAsDecimalDegreeValue;
2215
0
                        unit = UnitOfMeasure::DEGREE;
2216
0
                    }
2217
2
                    break;
2218
2
                }
2219
4.47k
            }
2220
351
        }
2221
2222
351
        auto &properties = buildProperties(node);
2223
351
        if (dbContext_ && esriStyle_) {
2224
314
            std::string outTableName;
2225
314
            std::string codeFromAlias;
2226
314
            std::string authNameFromAlias;
2227
314
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2228
314
                                                        std::string());
2229
314
            auto officialName = authFactory->getOfficialNameFromAlias(
2230
314
                name, "prime_meridian", "ESRI", false, outTableName,
2231
314
                authNameFromAlias, codeFromAlias);
2232
314
            if (!officialName.empty()) {
2233
0
                properties.set(IdentifiedObject::NAME_KEY, officialName);
2234
0
                if (!authNameFromAlias.empty()) {
2235
0
                    auto identifiers = ArrayOfBaseObject::create();
2236
0
                    identifiers->add(Identifier::create(
2237
0
                        codeFromAlias,
2238
0
                        PropertyMap()
2239
0
                            .set(Identifier::CODESPACE_KEY, authNameFromAlias)
2240
0
                            .set(Identifier::AUTHORITY_KEY,
2241
0
                                 authNameFromAlias)));
2242
0
                    properties.set(IdentifiedObject::IDENTIFIERS_KEY,
2243
0
                                   identifiers);
2244
0
                }
2245
0
            }
2246
314
        }
2247
2248
351
        Angle angle(angleValue, unit);
2249
351
        return PrimeMeridian::create(properties, angle);
2250
351
    } catch (const std::exception &e) {
2251
8
        throw buildRethrow(__FUNCTION__, e);
2252
8
    }
2253
351
}
2254
2255
// ---------------------------------------------------------------------------
2256
2257
1.92k
optional<std::string> WKTParser::Private::getAnchor(const WKTNodeNNPtr &node) {
2258
2259
1.92k
    auto &anchorNode = node->GP()->lookForChild(WKTConstants::ANCHOR);
2260
1.92k
    if (anchorNode->GP()->childrenSize() == 1) {
2261
0
        return optional<std::string>(
2262
0
            stripQuotes(anchorNode->GP()->children()[0]));
2263
0
    }
2264
1.92k
    return optional<std::string>();
2265
1.92k
}
2266
2267
// ---------------------------------------------------------------------------
2268
2269
optional<common::Measure>
2270
1.90k
WKTParser::Private::getAnchorEpoch(const WKTNodeNNPtr &node) {
2271
2272
1.90k
    auto &anchorEpochNode = node->GP()->lookForChild(WKTConstants::ANCHOREPOCH);
2273
1.90k
    if (anchorEpochNode->GP()->childrenSize() == 1) {
2274
0
        try {
2275
0
            double value = asDouble(anchorEpochNode->GP()->children()[0]);
2276
0
            return optional<common::Measure>(
2277
0
                common::Measure(value, common::UnitOfMeasure::YEAR));
2278
0
        } catch (const std::exception &e) {
2279
0
            throw buildRethrow(__FUNCTION__, e);
2280
0
        }
2281
0
    }
2282
1.90k
    return optional<common::Measure>();
2283
1.90k
}
2284
// ---------------------------------------------------------------------------
2285
2286
static const PrimeMeridianNNPtr &
2287
fixupPrimeMeridan(const EllipsoidNNPtr &ellipsoid,
2288
1.97k
                  const PrimeMeridianNNPtr &pm) {
2289
1.97k
    return (ellipsoid->celestialBody() != Ellipsoid::EARTH &&
2290
976
            pm.get() == PrimeMeridian::GREENWICH.get())
2291
1.97k
               ? PrimeMeridian::REFERENCE_MERIDIAN
2292
1.97k
               : pm;
2293
1.97k
}
2294
2295
// ---------------------------------------------------------------------------
2296
2297
GeodeticReferenceFrameNNPtr WKTParser::Private::buildGeodeticReferenceFrame(
2298
    const WKTNodeNNPtr &node, const PrimeMeridianNNPtr &primeMeridian,
2299
1.23k
    const WKTNodeNNPtr &dynamicNode) {
2300
1.23k
    const auto *nodeP = node->GP();
2301
1.23k
    auto &ellipsoidNode =
2302
1.23k
        nodeP->lookForChild(WKTConstants::ELLIPSOID, WKTConstants::SPHEROID);
2303
1.23k
    if (isNull(ellipsoidNode)) {
2304
76
        ThrowMissing(WKTConstants::ELLIPSOID);
2305
76
    }
2306
1.15k
    auto &properties = buildProperties(node);
2307
2308
    // do that before buildEllipsoid() so that esriStyle_ can be set
2309
1.15k
    auto name = stripQuotes(nodeP->children()[0]);
2310
2311
1.15k
    const auto identifyFromName = [&](const std::string &l_name) {
2312
156
        if (dbContext_) {
2313
143
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2314
143
                                                        std::string());
2315
143
            auto res = authFactory->createObjectsFromName(
2316
143
                l_name,
2317
143
                {AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, true,
2318
143
                1);
2319
143
            if (!res.empty()) {
2320
83
                bool foundDatumName = false;
2321
83
                const auto &refDatum = res.front();
2322
83
                if (metadata::Identifier::isEquivalentName(
2323
83
                        l_name.c_str(), refDatum->nameStr().c_str())) {
2324
16
                    foundDatumName = true;
2325
67
                } else if (refDatum->identifiers().size() == 1) {
2326
67
                    const auto &id = refDatum->identifiers()[0];
2327
67
                    const auto aliases =
2328
67
                        authFactory->databaseContext()->getAliases(
2329
67
                            *id->codeSpace(), id->code(), refDatum->nameStr(),
2330
67
                            "geodetic_datum", "not EPSG_OLD");
2331
81
                    for (const auto &alias : aliases) {
2332
81
                        if (metadata::Identifier::isEquivalentName(
2333
81
                                l_name.c_str(), alias.c_str())) {
2334
0
                            foundDatumName = true;
2335
0
                            break;
2336
0
                        }
2337
81
                    }
2338
67
                }
2339
83
                if (foundDatumName) {
2340
16
                    properties.set(IdentifiedObject::NAME_KEY,
2341
16
                                   refDatum->nameStr());
2342
16
                    if (!properties.get(Identifier::CODESPACE_KEY) &&
2343
16
                        refDatum->identifiers().size() == 1) {
2344
16
                        const auto &id = refDatum->identifiers()[0];
2345
16
                        auto identifiers = ArrayOfBaseObject::create();
2346
16
                        identifiers->add(Identifier::create(
2347
16
                            id->code(), PropertyMap()
2348
16
                                            .set(Identifier::CODESPACE_KEY,
2349
16
                                                 *id->codeSpace())
2350
16
                                            .set(Identifier::AUTHORITY_KEY,
2351
16
                                                 *id->codeSpace())));
2352
16
                        properties.set(IdentifiedObject::IDENTIFIERS_KEY,
2353
16
                                       identifiers);
2354
16
                    }
2355
16
                    return true;
2356
16
                }
2357
83
            } else {
2358
                // Get official name from database if AUTHORITY is present
2359
60
                auto &idNode = nodeP->lookForChild(WKTConstants::AUTHORITY);
2360
60
                if (!isNull(idNode)) {
2361
2
                    try {
2362
2
                        auto id = buildId(node, idNode, false, false);
2363
2
                        auto authFactory2 = AuthorityFactory::create(
2364
2
                            NN_NO_CHECK(dbContext_), *id->codeSpace());
2365
2
                        auto dbDatum =
2366
2
                            authFactory2->createGeodeticDatum(id->code());
2367
2
                        properties.set(IdentifiedObject::NAME_KEY,
2368
2
                                       dbDatum->nameStr());
2369
2
                        return true;
2370
2
                    } catch (const std::exception &) {
2371
2
                    }
2372
2
                }
2373
60
            }
2374
143
        }
2375
140
        return false;
2376
156
    };
2377
2378
    // Remap GDAL WGS_1984 to EPSG v9 "World Geodetic System 1984" official
2379
    // name.
2380
1.15k
    bool nameSet = false;
2381
1.15k
    if (name == "WGS_1984") {
2382
0
        nameSet = true;
2383
0
        properties.set(IdentifiedObject::NAME_KEY,
2384
0
                       GeodeticReferenceFrame::EPSG_6326->nameStr());
2385
0
    }
2386
    // Also remap EPSG v10 datum ensemble names to non-ensemble EPSG v9
2387
1.15k
    else if (internal::ends_with(name, " ensemble")) {
2388
0
        auto massagedName = DatumEnsemble::ensembleNameToNonEnsembleName(name);
2389
0
        if (!massagedName.empty()) {
2390
0
            nameSet = true;
2391
0
            properties.set(IdentifiedObject::NAME_KEY, massagedName);
2392
0
        }
2393
0
    }
2394
    // If we got hints this might be a ESRI WKT, then check in the DB to
2395
    // confirm
2396
1.15k
    std::string officialName;
2397
1.15k
    std::string authNameFromAlias;
2398
1.15k
    std::string codeFromAlias;
2399
1.15k
    if (!nameSet && maybeEsriStyle_ && dbContext_ &&
2400
896
        !(starts_with(name, "D_") || esriStyle_)) {
2401
574
        std::string outTableName;
2402
574
        auto authFactory =
2403
574
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
2404
574
        officialName = authFactory->getOfficialNameFromAlias(
2405
574
            name, "geodetic_datum", "ESRI", false, outTableName,
2406
574
            authNameFromAlias, codeFromAlias);
2407
574
        if (!officialName.empty()) {
2408
0
            maybeEsriStyle_ = false;
2409
0
            esriStyle_ = true;
2410
0
        }
2411
574
    }
2412
2413
1.15k
    if (!nameSet && (starts_with(name, "D_") || esriStyle_)) {
2414
372
        esriStyle_ = true;
2415
372
        const char *tableNameForAlias = nullptr;
2416
372
        if (name == "D_WGS_1984") {
2417
154
            name = "World Geodetic System 1984";
2418
154
            authNameFromAlias = Identifier::EPSG;
2419
154
            codeFromAlias = "6326";
2420
218
        } else if (name == "D_ETRS_1989") {
2421
0
            name = "European Terrestrial Reference System 1989";
2422
0
            authNameFromAlias = Identifier::EPSG;
2423
0
            codeFromAlias = "6258";
2424
218
        } else if (name == "D_unknown") {
2425
0
            name = "unknown";
2426
218
        } else if (name == "D_Unknown_based_on_WGS_84_ellipsoid") {
2427
0
            name = "Unknown based on WGS 84 ellipsoid";
2428
218
        } else {
2429
218
            tableNameForAlias = "geodetic_datum";
2430
218
        }
2431
2432
372
        bool setNameAndId = true;
2433
372
        if (dbContext_ && tableNameForAlias) {
2434
203
            if (officialName.empty()) {
2435
203
                std::string outTableName;
2436
203
                auto authFactory = AuthorityFactory::create(
2437
203
                    NN_NO_CHECK(dbContext_), std::string());
2438
203
                officialName = authFactory->getOfficialNameFromAlias(
2439
203
                    name, tableNameForAlias, "ESRI", false, outTableName,
2440
203
                    authNameFromAlias, codeFromAlias);
2441
203
            }
2442
203
            if (officialName.empty()) {
2443
75
                if (starts_with(name, "D_")) {
2444
                    // For the case of "D_GDA2020" where there is no D_GDA2020
2445
                    // ESRI alias, so just try without the D_ prefix.
2446
38
                    const auto nameWithoutDPrefix = name.substr(2);
2447
38
                    if (identifyFromName(nameWithoutDPrefix)) {
2448
0
                        setNameAndId =
2449
0
                            false; // already done in identifyFromName()
2450
0
                    }
2451
38
                }
2452
128
            } else {
2453
128
                if (primeMeridian->nameStr() !=
2454
128
                    PrimeMeridian::GREENWICH->nameStr()) {
2455
0
                    auto nameWithPM =
2456
0
                        officialName + " (" + primeMeridian->nameStr() + ")";
2457
0
                    if (dbContext_->isKnownName(nameWithPM, "geodetic_datum")) {
2458
0
                        officialName = std::move(nameWithPM);
2459
0
                    }
2460
0
                }
2461
128
                name = std::move(officialName);
2462
128
            }
2463
203
        }
2464
2465
372
        if (setNameAndId) {
2466
372
            properties.set(IdentifiedObject::NAME_KEY, name);
2467
372
            if (!authNameFromAlias.empty()) {
2468
282
                auto identifiers = ArrayOfBaseObject::create();
2469
282
                identifiers->add(Identifier::create(
2470
282
                    codeFromAlias,
2471
282
                    PropertyMap()
2472
282
                        .set(Identifier::CODESPACE_KEY, authNameFromAlias)
2473
282
                        .set(Identifier::AUTHORITY_KEY, authNameFromAlias)));
2474
282
                properties.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
2475
282
            }
2476
372
        }
2477
786
    } else if (!nameSet && name.find('_') != std::string::npos) {
2478
        // Likely coming from WKT1
2479
118
        identifyFromName(name);
2480
118
    }
2481
2482
1.15k
    auto ellipsoid = buildEllipsoid(ellipsoidNode);
2483
1.15k
    const auto &primeMeridianModified =
2484
1.15k
        fixupPrimeMeridan(ellipsoid, primeMeridian);
2485
2486
1.15k
    auto &TOWGS84Node = nodeP->lookForChild(WKTConstants::TOWGS84);
2487
1.15k
    if (!isNull(TOWGS84Node)) {
2488
2
        const auto &TOWGS84Children = TOWGS84Node->GP()->children();
2489
2
        const size_t TOWGS84Size = TOWGS84Children.size();
2490
2
        if (TOWGS84Size == 3 || TOWGS84Size == 7) {
2491
1
            try {
2492
2
                for (const auto &child : TOWGS84Children) {
2493
2
                    toWGS84Parameters_.push_back(asDouble(child));
2494
2
                }
2495
2496
1
                if (TOWGS84Size == 7 && dbContext_) {
2497
0
                    dbContext_->toWGS84AutocorrectWrongValues(
2498
0
                        toWGS84Parameters_[0], toWGS84Parameters_[1],
2499
0
                        toWGS84Parameters_[2], toWGS84Parameters_[3],
2500
0
                        toWGS84Parameters_[4], toWGS84Parameters_[5],
2501
0
                        toWGS84Parameters_[6]);
2502
0
                }
2503
2504
1
                for (size_t i = TOWGS84Size; i < 7; ++i) {
2505
0
                    toWGS84Parameters_.push_back(0.0);
2506
0
                }
2507
1
            } catch (const std::exception &) {
2508
1
                throw ParsingException("Invalid TOWGS84 node");
2509
1
            }
2510
1
        } else {
2511
1
            throw ParsingException("Invalid TOWGS84 node");
2512
1
        }
2513
2
    }
2514
2515
1.15k
    auto &extensionNode = nodeP->lookForChild(WKTConstants::EXTENSION);
2516
1.15k
    const auto &extensionChildren = extensionNode->GP()->children();
2517
1.15k
    if (extensionChildren.size() == 2) {
2518
4
        if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4_GRIDS")) {
2519
0
            datumPROJ4Grids_ = stripQuotes(extensionChildren[1]);
2520
0
        }
2521
4
    }
2522
2523
1.15k
    if (!isNull(dynamicNode)) {
2524
20
        double frameReferenceEpoch = 0.0;
2525
20
        util::optional<std::string> modelName;
2526
20
        parseDynamic(dynamicNode, frameReferenceEpoch, modelName);
2527
20
        return DynamicGeodeticReferenceFrame::create(
2528
20
            properties, ellipsoid, getAnchor(node), primeMeridianModified,
2529
20
            common::Measure(frameReferenceEpoch, common::UnitOfMeasure::YEAR),
2530
20
            modelName);
2531
20
    }
2532
2533
1.13k
    return GeodeticReferenceFrame::create(properties, ellipsoid,
2534
1.13k
                                          getAnchor(node), getAnchorEpoch(node),
2535
1.13k
                                          primeMeridianModified);
2536
1.15k
}
2537
2538
// ---------------------------------------------------------------------------
2539
2540
DatumEnsembleNNPtr
2541
WKTParser::Private::buildDatumEnsemble(const WKTNodeNNPtr &node,
2542
                                       const PrimeMeridianPtr &primeMeridian,
2543
220
                                       bool expectEllipsoid) {
2544
220
    const auto *nodeP = node->GP();
2545
220
    auto &ellipsoidNode =
2546
220
        nodeP->lookForChild(WKTConstants::ELLIPSOID, WKTConstants::SPHEROID);
2547
220
    if (expectEllipsoid && isNull(ellipsoidNode)) {
2548
10
        ThrowMissing(WKTConstants::ELLIPSOID);
2549
10
    }
2550
2551
210
    auto properties = buildProperties(node);
2552
2553
210
    std::vector<DatumNNPtr> datums;
2554
4.16k
    for (const auto &subNode : nodeP->children()) {
2555
4.16k
        if (ci_equal(subNode->GP()->value(), WKTConstants::MEMBER)) {
2556
1.18k
            if (subNode->GP()->childrenSize() == 0) {
2557
8
                throw ParsingException("Invalid MEMBER node");
2558
8
            }
2559
1.17k
            if (expectEllipsoid) {
2560
996
                datums.emplace_back(GeodeticReferenceFrame::create(
2561
996
                    buildProperties(subNode), buildEllipsoid(ellipsoidNode),
2562
996
                    optional<std::string>(),
2563
996
                    primeMeridian ? NN_NO_CHECK(primeMeridian)
2564
996
                                  : PrimeMeridian::GREENWICH));
2565
996
            } else {
2566
183
                datums.emplace_back(
2567
183
                    VerticalReferenceFrame::create(buildProperties(subNode)));
2568
183
            }
2569
1.17k
        }
2570
4.16k
    }
2571
2572
202
    if (datums.empty() && !nodeP->children().empty()) {
2573
6
        auto name = stripQuotes(nodeP->children()[0]);
2574
6
        if (dbContext_) {
2575
3
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2576
3
                                                        std::string());
2577
3
            auto res = authFactory->createObjectsFromName(
2578
3
                name, {AuthorityFactory::ObjectType::DATUM_ENSEMBLE}, true, 1);
2579
3
            if (res.size() == 1) {
2580
1
                auto datumEnsemble =
2581
1
                    dynamic_cast<const DatumEnsemble *>(res.front().get());
2582
1
                if (datumEnsemble) {
2583
1
                    datums = datumEnsemble->datums();
2584
1
                }
2585
2
            } else {
2586
2
                throw ParsingException(
2587
2
                    "No entry for datum ensemble '" + name +
2588
2
                    "' in database, and no explicit member specified");
2589
2
            }
2590
3
        } else {
2591
3
            throw ParsingException("Datum ensemble '" + name +
2592
3
                                   "' has no explicit member specified and no "
2593
3
                                   "connection to database");
2594
3
        }
2595
6
    }
2596
2597
197
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::ENSEMBLEACCURACY);
2598
197
    auto &accuracyNodeChildren = accuracyNode->GP()->children();
2599
197
    if (accuracyNodeChildren.empty()) {
2600
141
        ThrowMissing(WKTConstants::ENSEMBLEACCURACY);
2601
141
    }
2602
56
    auto accuracy =
2603
56
        PositionalAccuracy::create(accuracyNodeChildren[0]->GP()->value());
2604
2605
56
    try {
2606
56
        return DatumEnsemble::create(properties, datums, accuracy);
2607
56
    } catch (const util::Exception &e) {
2608
3
        throw buildRethrow(__FUNCTION__, e);
2609
3
    }
2610
56
}
2611
2612
// ---------------------------------------------------------------------------
2613
2614
0
MeridianNNPtr WKTParser::Private::buildMeridian(const WKTNodeNNPtr &node) {
2615
0
    const auto *nodeP = node->GP();
2616
0
    const auto &children = nodeP->children();
2617
0
    if (children.size() < 2) {
2618
0
        ThrowNotEnoughChildren(nodeP->value());
2619
0
    }
2620
0
    UnitOfMeasure unit = buildUnitInSubNode(node, UnitOfMeasure::Type::ANGULAR);
2621
0
    try {
2622
0
        double angleValue = asDouble(children[0]);
2623
0
        Angle angle(angleValue, unit);
2624
0
        return Meridian::create(angle);
2625
0
    } catch (const std::exception &e) {
2626
0
        throw buildRethrow(__FUNCTION__, e);
2627
0
    }
2628
0
}
2629
2630
// ---------------------------------------------------------------------------
2631
2632
8
PROJ_NO_RETURN static void ThrowParsingExceptionMissingUNIT() {
2633
8
    throw ParsingException("buildCS: missing UNIT");
2634
8
}
2635
2636
// ---------------------------------------------------------------------------
2637
2638
CoordinateSystemAxisNNPtr
2639
WKTParser::Private::buildAxis(const WKTNodeNNPtr &node,
2640
                              const UnitOfMeasure &unitIn,
2641
                              const UnitOfMeasure::Type &unitType,
2642
206
                              bool isGeocentric, int expectedOrderNum) {
2643
206
    const auto *nodeP = node->GP();
2644
206
    const auto &children = nodeP->children();
2645
206
    if (children.size() < 2) {
2646
10
        ThrowNotEnoughChildren(nodeP->value());
2647
10
    }
2648
2649
196
    auto &orderNode = nodeP->lookForChild(WKTConstants::ORDER);
2650
196
    if (!isNull(orderNode)) {
2651
9
        const auto &orderNodeChildren = orderNode->GP()->children();
2652
9
        if (orderNodeChildren.size() != 1) {
2653
0
            ThrowNotEnoughChildren(WKTConstants::ORDER);
2654
0
        }
2655
9
        const auto &order = orderNodeChildren[0]->GP()->value();
2656
9
        int orderNum;
2657
9
        try {
2658
9
            orderNum = std::stoi(order);
2659
9
        } catch (const std::exception &) {
2660
3
            throw ParsingException(
2661
3
                concat("buildAxis: invalid ORDER value: ", order));
2662
3
        }
2663
6
        if (orderNum != expectedOrderNum) {
2664
4
            throw ParsingException(
2665
4
                concat("buildAxis: did not get expected ORDER value: ", order));
2666
4
        }
2667
6
    }
2668
2669
    // The axis designation in WK2 can be: "name", "(abbrev)" or "name
2670
    // (abbrev)"
2671
189
    std::string axisDesignation(stripQuotes(children[0]));
2672
189
    size_t sepPos = axisDesignation.find(" (");
2673
189
    std::string axisName;
2674
189
    std::string abbreviation;
2675
189
    if (sepPos != std::string::npos && axisDesignation.back() == ')') {
2676
8
        axisName = CoordinateSystemAxis::normalizeAxisName(
2677
8
            axisDesignation.substr(0, sepPos));
2678
8
        abbreviation = axisDesignation.substr(sepPos + 2);
2679
8
        abbreviation.resize(abbreviation.size() - 1);
2680
181
    } else if (!axisDesignation.empty() && axisDesignation[0] == '(' &&
2681
36
               axisDesignation.back() == ')') {
2682
19
        abbreviation = axisDesignation.substr(1, axisDesignation.size() - 2);
2683
19
        if (abbreviation == AxisAbbreviation::E) {
2684
3
            axisName = AxisName::Easting;
2685
16
        } else if (abbreviation == AxisAbbreviation::N) {
2686
0
            axisName = AxisName::Northing;
2687
16
        } else if (abbreviation == AxisAbbreviation::lat) {
2688
0
            axisName = AxisName::Latitude;
2689
16
        } else if (abbreviation == AxisAbbreviation::lon) {
2690
0
            axisName = AxisName::Longitude;
2691
0
        }
2692
162
    } else {
2693
162
        axisName = CoordinateSystemAxis::normalizeAxisName(axisDesignation);
2694
162
        if (axisName == AxisName::Latitude) {
2695
0
            abbreviation = AxisAbbreviation::lat;
2696
162
        } else if (axisName == AxisName::Longitude) {
2697
0
            abbreviation = AxisAbbreviation::lon;
2698
162
        } else if (axisName == AxisName::Ellipsoidal_height) {
2699
0
            abbreviation = AxisAbbreviation::h;
2700
0
        }
2701
162
    }
2702
189
    const std::string &dirString = children[1]->GP()->value();
2703
189
    const AxisDirection *direction = AxisDirection::valueOf(dirString);
2704
2705
    // WKT2, geocentric CS: axis names are omitted
2706
189
    if (axisName.empty()) {
2707
18
        if (direction == &AxisDirection::GEOCENTRIC_X &&
2708
0
            abbreviation == AxisAbbreviation::X) {
2709
0
            axisName = AxisName::Geocentric_X;
2710
18
        } else if (direction == &AxisDirection::GEOCENTRIC_Y &&
2711
6
                   abbreviation == AxisAbbreviation::Y) {
2712
0
            axisName = AxisName::Geocentric_Y;
2713
18
        } else if (direction == &AxisDirection::GEOCENTRIC_Z &&
2714
0
                   abbreviation == AxisAbbreviation::Z) {
2715
0
            axisName = AxisName::Geocentric_Z;
2716
0
        }
2717
18
    }
2718
2719
    // WKT1
2720
189
    if (!direction && isGeocentric && axisName == AxisName::Geocentric_X) {
2721
21
        abbreviation = AxisAbbreviation::X;
2722
21
        direction = &AxisDirection::GEOCENTRIC_X;
2723
168
    } else if (!direction && isGeocentric &&
2724
20
               axisName == AxisName::Geocentric_Y) {
2725
0
        abbreviation = AxisAbbreviation::Y;
2726
0
        direction = &AxisDirection::GEOCENTRIC_Y;
2727
168
    } else if (isGeocentric && axisName == AxisName::Geocentric_Z &&
2728
6
               (dirString == AxisDirectionWKT1::NORTH.toString() ||
2729
6
                dirString == AxisDirectionWKT1::OTHER.toString())) {
2730
0
        abbreviation = AxisAbbreviation::Z;
2731
0
        direction = &AxisDirection::GEOCENTRIC_Z;
2732
168
    } else if (dirString == AxisDirectionWKT1::OTHER.toString()) {
2733
0
        direction = &AxisDirection::UNSPECIFIED;
2734
168
    } else if (dirString == "UNKNOWN") {
2735
        // Found in WKT1 of NSIDC's EASE-Grid Sea Ice Age datasets.
2736
        // Cf https://github.com/OSGeo/gdal/issues/7210
2737
0
        emitRecoverableWarning("UNKNOWN is not a valid direction name.");
2738
0
        direction = &AxisDirection::UNSPECIFIED;
2739
0
    }
2740
2741
189
    if (!direction) {
2742
88
        throw ParsingException(
2743
88
            concat("unhandled axis direction: ", children[1]->GP()->value()));
2744
88
    }
2745
101
    UnitOfMeasure unit(buildUnitInSubNode(node));
2746
101
    if (unit == UnitOfMeasure::NONE) {
2747
        // If no unit in the AXIS node, use the one potentially coming from
2748
        // the CS.
2749
88
        unit = unitIn;
2750
88
        if (unit == UnitOfMeasure::NONE &&
2751
8
            unitType != UnitOfMeasure::Type::NONE &&
2752
8
            unitType != UnitOfMeasure::Type::TIME) {
2753
8
            ThrowParsingExceptionMissingUNIT();
2754
8
        }
2755
88
    }
2756
2757
93
    auto &meridianNode = nodeP->lookForChild(WKTConstants::MERIDIAN);
2758
2759
93
    util::optional<double> minVal;
2760
93
    auto &axisMinValueNode = nodeP->lookForChild(WKTConstants::AXISMINVALUE);
2761
93
    if (!isNull(axisMinValueNode)) {
2762
0
        const auto &axisMinValueNodeChildren =
2763
0
            axisMinValueNode->GP()->children();
2764
0
        if (axisMinValueNodeChildren.size() != 1) {
2765
0
            ThrowNotEnoughChildren(WKTConstants::AXISMINVALUE);
2766
0
        }
2767
0
        const auto &val = axisMinValueNodeChildren[0];
2768
0
        try {
2769
0
            minVal = asDouble(val);
2770
0
        } catch (const std::exception &) {
2771
0
            throw ParsingException(concat(
2772
0
                "buildAxis: invalid AXISMINVALUE value: ", val->GP()->value()));
2773
0
        }
2774
0
    }
2775
2776
93
    util::optional<double> maxVal;
2777
93
    auto &axisMaxValueNode = nodeP->lookForChild(WKTConstants::AXISMAXVALUE);
2778
93
    if (!isNull(axisMaxValueNode)) {
2779
0
        const auto &axisMaxValueNodeChildren =
2780
0
            axisMaxValueNode->GP()->children();
2781
0
        if (axisMaxValueNodeChildren.size() != 1) {
2782
0
            ThrowNotEnoughChildren(WKTConstants::AXISMAXVALUE);
2783
0
        }
2784
0
        const auto &val = axisMaxValueNodeChildren[0];
2785
0
        try {
2786
0
            maxVal = asDouble(val);
2787
0
        } catch (const std::exception &) {
2788
0
            throw ParsingException(concat(
2789
0
                "buildAxis: invalid AXISMAXVALUE value: ", val->GP()->value()));
2790
0
        }
2791
0
    }
2792
2793
93
    util::optional<RangeMeaning> rangeMeaning;
2794
93
    auto &rangeMeaningNode = nodeP->lookForChild(WKTConstants::RANGEMEANING);
2795
93
    if (!isNull(rangeMeaningNode)) {
2796
10
        const auto &rangeMeaningNodeChildren =
2797
10
            rangeMeaningNode->GP()->children();
2798
10
        if (rangeMeaningNodeChildren.size() != 1) {
2799
1
            ThrowNotEnoughChildren(WKTConstants::RANGEMEANING);
2800
1
        }
2801
9
        const std::string &val = rangeMeaningNodeChildren[0]->GP()->value();
2802
9
        const RangeMeaning *meaning = RangeMeaning::valueOf(val);
2803
9
        if (meaning == nullptr) {
2804
9
            throw ParsingException(
2805
9
                concat("buildAxis: invalid RANGEMEANING value: ", val));
2806
9
        }
2807
0
        rangeMeaning = util::optional<RangeMeaning>(*meaning);
2808
0
    }
2809
2810
83
    return CoordinateSystemAxis::create(
2811
83
        buildProperties(node).set(IdentifiedObject::NAME_KEY, axisName),
2812
83
        abbreviation, *direction, unit, minVal, maxVal, rangeMeaning,
2813
83
        !isNull(meridianNode) ? buildMeridian(meridianNode).as_nullable()
2814
83
                              : nullptr);
2815
93
}
2816
2817
// ---------------------------------------------------------------------------
2818
2819
static const PropertyMap emptyPropertyMap{};
2820
2821
// ---------------------------------------------------------------------------
2822
2823
3
PROJ_NO_RETURN static void ThrowParsingException(const std::string &msg) {
2824
3
    throw ParsingException(msg);
2825
3
}
2826
2827
// ---------------------------------------------------------------------------
2828
2829
static ParsingException
2830
13
buildParsingExceptionInvalidAxisCount(const std::string &csType) {
2831
13
    return ParsingException(
2832
13
        concat("buildCS: invalid CS axis count for ", csType));
2833
13
}
2834
2835
// ---------------------------------------------------------------------------
2836
2837
void WKTParser::Private::emitRecoverableMissingUNIT(
2838
1.48k
    const std::string &parentNodeName, const UnitOfMeasure &fallbackUnit) {
2839
1.48k
    std::string msg("buildCS: missing UNIT in ");
2840
1.48k
    msg += parentNodeName;
2841
1.48k
    if (!strict_ && fallbackUnit == UnitOfMeasure::METRE) {
2842
1.00k
        msg += ". Assuming metre";
2843
1.00k
    } else if (!strict_ && fallbackUnit == UnitOfMeasure::DEGREE) {
2844
483
        msg += ". Assuming degree";
2845
483
    }
2846
1.48k
    emitRecoverableWarning(msg);
2847
1.48k
}
2848
2849
// ---------------------------------------------------------------------------
2850
2851
CoordinateSystemNNPtr
2852
WKTParser::Private::buildCS(const WKTNodeNNPtr &node, /* maybe null */
2853
                            const WKTNodeNNPtr &parentNode,
2854
2.87k
                            const UnitOfMeasure &defaultAngularUnit) {
2855
2.87k
    bool isGeocentric = false;
2856
2.87k
    std::string csType;
2857
2.87k
    const int numberOfAxis =
2858
2.87k
        parentNode->countChildrenOfName(WKTConstants::AXIS);
2859
2.87k
    int axisCount = numberOfAxis;
2860
2.87k
    const auto &parentNodeName = parentNode->GP()->value();
2861
2.87k
    if (!isNull(node)) {
2862
21
        const auto *nodeP = node->GP();
2863
21
        const auto &children = nodeP->children();
2864
21
        if (children.size() < 2) {
2865
6
            ThrowNotEnoughChildren(nodeP->value());
2866
6
        }
2867
15
        csType = children[0]->GP()->value();
2868
15
        try {
2869
15
            axisCount = std::stoi(children[1]->GP()->value());
2870
15
        } catch (const std::exception &) {
2871
3
            ThrowParsingException(concat("buildCS: invalid CS axis count: ",
2872
3
                                         children[1]->GP()->value()));
2873
3
        }
2874
2.85k
    } else {
2875
2.85k
        const char *csTypeCStr = CartesianCS::WKT2_TYPE;
2876
2.85k
        if (ci_equal(parentNodeName, WKTConstants::GEOCCS)) {
2877
            // csTypeCStr = CartesianCS::WKT2_TYPE;
2878
80
            isGeocentric = true;
2879
80
            if (axisCount == 0) {
2880
40
                auto unit =
2881
40
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2882
40
                if (unit == UnitOfMeasure::NONE) {
2883
33
                    unit = UnitOfMeasure::METRE;
2884
33
                    emitRecoverableMissingUNIT(parentNodeName, unit);
2885
33
                }
2886
40
                return CartesianCS::createGeocentric(unit);
2887
40
            }
2888
2.77k
        } else if (ci_equal(parentNodeName, WKTConstants::GEOGCS)) {
2889
1.01k
            csTypeCStr = EllipsoidalCS::WKT2_TYPE;
2890
1.01k
            if (axisCount == 0) {
2891
                // Missing axis with GEOGCS ? Presumably Long/Lat order
2892
                // implied
2893
1.01k
                auto unit = buildUnitInSubNode(parentNode,
2894
1.01k
                                               UnitOfMeasure::Type::ANGULAR);
2895
1.01k
                if (unit == UnitOfMeasure::NONE) {
2896
483
                    unit = defaultAngularUnit;
2897
483
                    emitRecoverableMissingUNIT(parentNodeName, unit);
2898
483
                }
2899
2900
                // ESRI WKT for geographic 3D CRS
2901
1.01k
                auto &linUnitNode =
2902
1.01k
                    parentNode->GP()->lookForChild(WKTConstants::LINUNIT);
2903
1.01k
                if (!isNull(linUnitNode)) {
2904
0
                    return EllipsoidalCS::
2905
0
                        createLongitudeLatitudeEllipsoidalHeight(
2906
0
                            unit, buildUnit(linUnitNode,
2907
0
                                            UnitOfMeasure::Type::LINEAR));
2908
0
                }
2909
2910
                // WKT1 --> long/lat
2911
1.01k
                return EllipsoidalCS::createLongitudeLatitude(unit);
2912
1.01k
            }
2913
1.76k
        } else if (ci_equal(parentNodeName, WKTConstants::BASEGEODCRS) ||
2914
1.76k
                   ci_equal(parentNodeName, WKTConstants::BASEGEOGCRS)) {
2915
0
            csTypeCStr = EllipsoidalCS::WKT2_TYPE;
2916
0
            if (axisCount == 0) {
2917
0
                auto unit = buildUnitInSubNode(parentNode,
2918
0
                                               UnitOfMeasure::Type::ANGULAR);
2919
0
                if (unit == UnitOfMeasure::NONE) {
2920
0
                    unit = defaultAngularUnit;
2921
0
                }
2922
                // WKT2 --> presumably lat/long
2923
0
                return EllipsoidalCS::createLatitudeLongitude(unit);
2924
0
            }
2925
1.76k
        } else if (ci_equal(parentNodeName, WKTConstants::PROJCS) ||
2926
1.03k
                   ci_equal(parentNodeName, WKTConstants::BASEPROJCRS) ||
2927
1.03k
                   ci_equal(parentNodeName, WKTConstants::BASEENGCRS)) {
2928
732
            csTypeCStr = CartesianCS::WKT2_TYPE;
2929
732
            if (axisCount == 0) {
2930
732
                auto unit =
2931
732
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2932
732
                if (unit == UnitOfMeasure::NONE) {
2933
397
                    unit = UnitOfMeasure::METRE;
2934
397
                    if (ci_equal(parentNodeName, WKTConstants::PROJCS)) {
2935
397
                        emitRecoverableMissingUNIT(parentNodeName, unit);
2936
397
                    }
2937
397
                }
2938
732
                return CartesianCS::createEastingNorthing(unit);
2939
732
            }
2940
1.03k
        } else if (ci_equal(parentNodeName, WKTConstants::VERT_CS) ||
2941
1.00k
                   ci_equal(parentNodeName, WKTConstants::VERTCS) ||
2942
669
                   ci_equal(parentNodeName, WKTConstants::BASEVERTCRS)) {
2943
669
            csTypeCStr = VerticalCS::WKT2_TYPE;
2944
2945
669
            bool downDirection = false;
2946
669
            if (ci_equal(parentNodeName, WKTConstants::VERTCS)) // ESRI
2947
644
            {
2948
2.93k
                for (const auto &childNode : parentNode->GP()->children()) {
2949
2.93k
                    const auto &childNodeChildren = childNode->GP()->children();
2950
2.93k
                    if (childNodeChildren.size() == 2 &&
2951
340
                        ci_equal(childNode->GP()->value(),
2952
340
                                 WKTConstants::PARAMETER) &&
2953
17
                        childNodeChildren[0]->GP()->value() ==
2954
17
                            "\"Direction\"") {
2955
0
                        const auto &paramValue =
2956
0
                            childNodeChildren[1]->GP()->value();
2957
0
                        try {
2958
0
                            double val = asDouble(childNodeChildren[1]);
2959
0
                            if (val == 1.0) {
2960
                                // ok
2961
0
                            } else if (val == -1.0) {
2962
0
                                downDirection = true;
2963
0
                            }
2964
0
                        } catch (const std::exception &) {
2965
0
                            throw ParsingException(
2966
0
                                concat("unhandled parameter value type : ",
2967
0
                                       paramValue));
2968
0
                        }
2969
0
                    }
2970
2.93k
                }
2971
644
            }
2972
2973
669
            if (axisCount == 0) {
2974
576
                auto unit =
2975
576
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2976
576
                if (unit == UnitOfMeasure::NONE) {
2977
483
                    unit = UnitOfMeasure::METRE;
2978
483
                    if (ci_equal(parentNodeName, WKTConstants::VERT_CS) ||
2979
483
                        ci_equal(parentNodeName, WKTConstants::VERTCS)) {
2980
483
                        emitRecoverableMissingUNIT(parentNodeName, unit);
2981
483
                    }
2982
483
                }
2983
576
                if (downDirection) {
2984
0
                    return VerticalCS::create(
2985
0
                        util::PropertyMap(),
2986
0
                        CoordinateSystemAxis::create(
2987
0
                            util::PropertyMap().set(IdentifiedObject::NAME_KEY,
2988
0
                                                    "depth"),
2989
0
                            "D", AxisDirection::DOWN, unit));
2990
0
                }
2991
576
                return VerticalCS::createGravityRelatedHeight(unit);
2992
576
            }
2993
669
        } else if (ci_equal(parentNodeName, WKTConstants::LOCAL_CS)) {
2994
363
            if (axisCount == 0) {
2995
290
                auto unit =
2996
290
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2997
290
                if (unit == UnitOfMeasure::NONE) {
2998
287
                    unit = UnitOfMeasure::METRE;
2999
287
                }
3000
290
                return CartesianCS::createEastingNorthing(unit);
3001
290
            } else if (axisCount == 1) {
3002
66
                csTypeCStr = VerticalCS::WKT2_TYPE;
3003
66
            } else if (axisCount == 2 || axisCount == 3) {
3004
5
                csTypeCStr = CartesianCS::WKT2_TYPE;
3005
5
            } else {
3006
2
                throw ParsingException(
3007
2
                    "buildCS: unexpected AXIS count for LOCAL_CS");
3008
2
            }
3009
363
        } else if (ci_equal(parentNodeName, WKTConstants::BASEPARAMCRS)) {
3010
0
            csTypeCStr = ParametricCS::WKT2_TYPE;
3011
0
            if (axisCount == 0) {
3012
0
                auto unit =
3013
0
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
3014
0
                if (unit == UnitOfMeasure::NONE) {
3015
0
                    unit = UnitOfMeasure("unknown", 1,
3016
0
                                         UnitOfMeasure::Type::PARAMETRIC);
3017
0
                }
3018
0
                return ParametricCS::create(
3019
0
                    emptyPropertyMap,
3020
0
                    CoordinateSystemAxis::create(
3021
0
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
3022
0
                                          "unknown parametric"),
3023
0
                        std::string(), AxisDirection::UNSPECIFIED, unit));
3024
0
            }
3025
0
        } else if (ci_equal(parentNodeName, WKTConstants::BASETIMECRS)) {
3026
0
            csTypeCStr = TemporalCS::WKT2_2015_TYPE;
3027
0
            if (axisCount == 0) {
3028
0
                auto unit =
3029
0
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::TIME);
3030
0
                if (unit == UnitOfMeasure::NONE) {
3031
0
                    unit =
3032
0
                        UnitOfMeasure("unknown", 1, UnitOfMeasure::Type::TIME);
3033
0
                }
3034
0
                return DateTimeTemporalCS::create(
3035
0
                    emptyPropertyMap,
3036
0
                    CoordinateSystemAxis::create(
3037
0
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
3038
0
                                          "unknown temporal"),
3039
0
                        std::string(), AxisDirection::FUTURE, unit));
3040
0
            }
3041
0
        } else {
3042
            // Shouldn't happen normally
3043
0
            throw ParsingException(
3044
0
                concat("buildCS: unexpected parent node: ", parentNodeName));
3045
0
        }
3046
207
        csType = csTypeCStr;
3047
207
    }
3048
3049
219
    if (axisCount != 1 && axisCount != 2 && axisCount != 3) {
3050
10
        throw buildParsingExceptionInvalidAxisCount(csType);
3051
10
    }
3052
209
    if (numberOfAxis != axisCount) {
3053
2
        throw ParsingException("buildCS: declared number of axis by CS node "
3054
2
                               "and number of AXIS are inconsistent");
3055
2
    }
3056
3057
207
    const auto unitType =
3058
207
        ci_equal(csType, EllipsoidalCS::WKT2_TYPE)
3059
207
            ? UnitOfMeasure::Type::ANGULAR
3060
207
        : ci_equal(csType, OrdinalCS::WKT2_TYPE) ? UnitOfMeasure::Type::NONE
3061
204
        : ci_equal(csType, ParametricCS::WKT2_TYPE)
3062
204
            ? UnitOfMeasure::Type::PARAMETRIC
3063
204
        : ci_equal(csType, CartesianCS::WKT2_TYPE) ||
3064
159
                ci_equal(csType, VerticalCS::WKT2_TYPE) ||
3065
0
                ci_equal(csType, AffineCS::WKT2_TYPE)
3066
204
            ? UnitOfMeasure::Type::LINEAR
3067
204
        : (ci_equal(csType, TemporalCS::WKT2_2015_TYPE) ||
3068
0
           ci_equal(csType, DateTimeTemporalCS::WKT2_2019_TYPE) ||
3069
0
           ci_equal(csType, TemporalCountCS::WKT2_2019_TYPE) ||
3070
0
           ci_equal(csType, TemporalMeasureCS::WKT2_2019_TYPE))
3071
0
            ? UnitOfMeasure::Type::TIME
3072
0
            : UnitOfMeasure::Type::UNKNOWN;
3073
207
    UnitOfMeasure unit = buildUnitInSubNode(parentNode, unitType);
3074
3075
207
    if (unit == UnitOfMeasure::NONE) {
3076
194
        if (ci_equal(parentNodeName, WKTConstants::VERT_CS) ||
3077
192
            ci_equal(parentNodeName, WKTConstants::VERTCS)) {
3078
93
            unit = UnitOfMeasure::METRE;
3079
93
            emitRecoverableMissingUNIT(parentNodeName, unit);
3080
93
        }
3081
194
    }
3082
3083
207
    std::vector<CoordinateSystemAxisNNPtr> axisList;
3084
413
    for (int i = 0; i < axisCount; i++) {
3085
206
        axisList.emplace_back(
3086
206
            buildAxis(parentNode->GP()->lookForChild(WKTConstants::AXIS, i),
3087
206
                      unit, unitType, isGeocentric, i + 1));
3088
206
    }
3089
3090
207
    const PropertyMap &csMap = emptyPropertyMap;
3091
207
    if (ci_equal(csType, EllipsoidalCS::WKT2_TYPE)) {
3092
0
        if (axisCount == 2) {
3093
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1]);
3094
0
        } else if (axisCount == 3) {
3095
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1],
3096
0
                                         axisList[2]);
3097
0
        }
3098
207
    } else if (ci_equal(csType, CartesianCS::WKT2_TYPE)) {
3099
4
        if (axisCount == 2) {
3100
1
            if (axisList[0]->unit() != axisList[1]->unit()) {
3101
0
                emitRecoverableWarning(
3102
0
                    "All axis of a CartesianCS must have the same unit");
3103
0
            }
3104
1
            return CartesianCS::create(csMap, axisList[0], axisList[1],
3105
1
                                       /* enforceSameUnit = */ false);
3106
3
        } else if (axisCount == 3) {
3107
0
            if (axisList[0]->unit() != axisList[1]->unit() ||
3108
0
                axisList[0]->unit() != axisList[2]->unit()) {
3109
0
                emitRecoverableWarning(
3110
0
                    "All axis of a CartesianCS must have the same unit");
3111
0
            }
3112
0
            return CartesianCS::create(csMap, axisList[0], axisList[1],
3113
0
                                       axisList[2],
3114
0
                                       /* enforceSameUnit = */ false);
3115
0
        }
3116
203
    } else if (ci_equal(csType, AffineCS::WKT2_TYPE)) {
3117
0
        if (axisCount == 2) {
3118
0
            return AffineCS::create(csMap, axisList[0], axisList[1]);
3119
0
        } else if (axisCount == 3) {
3120
0
            return AffineCS::create(csMap, axisList[0], axisList[1],
3121
0
                                    axisList[2]);
3122
0
        }
3123
203
    } else if (ci_equal(csType, VerticalCS::WKT2_TYPE)) {
3124
74
        if (axisCount == 1) {
3125
74
            return VerticalCS::create(csMap, axisList[0]);
3126
74
        }
3127
129
    } else if (ci_equal(csType, SphericalCS::WKT2_TYPE)) {
3128
0
        if (axisCount == 2) {
3129
            // Extension to ISO19111 to support (planet)-ocentric CS with
3130
            // geocentric latitude
3131
0
            return SphericalCS::create(csMap, axisList[0], axisList[1]);
3132
0
        } else if (axisCount == 3) {
3133
0
            return SphericalCS::create(csMap, axisList[0], axisList[1],
3134
0
                                       axisList[2]);
3135
0
        }
3136
129
    } else if (ci_equal(csType, OrdinalCS::WKT2_TYPE)) { // WKT2-2019
3137
0
        return OrdinalCS::create(csMap, axisList);
3138
129
    } else if (ci_equal(csType, ParametricCS::WKT2_TYPE)) {
3139
0
        if (axisCount == 1) {
3140
0
            return ParametricCS::create(csMap, axisList[0]);
3141
0
        }
3142
129
    } else if (ci_equal(csType, TemporalCS::WKT2_2015_TYPE)) {
3143
0
        if (axisCount == 1) {
3144
0
            if (isNull(
3145
0
                    parentNode->GP()->lookForChild(WKTConstants::TIMEUNIT)) &&
3146
0
                isNull(parentNode->GP()->lookForChild(WKTConstants::UNIT))) {
3147
0
                return DateTimeTemporalCS::create(csMap, axisList[0]);
3148
0
            } else {
3149
                // Default to TemporalMeasureCS
3150
                // TemporalCount could also be possible
3151
0
                return TemporalMeasureCS::create(csMap, axisList[0]);
3152
0
            }
3153
0
        }
3154
129
    } else if (ci_equal(csType, DateTimeTemporalCS::WKT2_2019_TYPE)) {
3155
0
        if (axisCount == 1) {
3156
0
            return DateTimeTemporalCS::create(csMap, axisList[0]);
3157
0
        }
3158
129
    } else if (ci_equal(csType, TemporalCountCS::WKT2_2019_TYPE)) {
3159
0
        if (axisCount == 1) {
3160
0
            return TemporalCountCS::create(csMap, axisList[0]);
3161
0
        }
3162
129
    } else if (ci_equal(csType, TemporalMeasureCS::WKT2_2019_TYPE)) {
3163
0
        if (axisCount == 1) {
3164
0
            return TemporalMeasureCS::create(csMap, axisList[0]);
3165
0
        }
3166
129
    } else {
3167
129
        throw ParsingException(concat("unhandled CS type: ", csType));
3168
129
    }
3169
3
    throw buildParsingExceptionInvalidAxisCount(csType);
3170
207
}
3171
3172
// ---------------------------------------------------------------------------
3173
3174
std::string
3175
2.72k
WKTParser::Private::getExtensionProj4(const WKTNode::Private *nodeP) {
3176
2.72k
    auto &extensionNode = nodeP->lookForChild(WKTConstants::EXTENSION);
3177
2.72k
    const auto &extensionChildren = extensionNode->GP()->children();
3178
2.72k
    if (extensionChildren.size() == 2) {
3179
203
        if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4")) {
3180
196
            return stripQuotes(extensionChildren[1]);
3181
196
        }
3182
203
    }
3183
2.53k
    return std::string();
3184
2.72k
}
3185
3186
// ---------------------------------------------------------------------------
3187
3188
void WKTParser::Private::addExtensionProj4ToProp(const WKTNode::Private *nodeP,
3189
1.84k
                                                 PropertyMap &props) {
3190
1.84k
    const auto extensionProj4(getExtensionProj4(nodeP));
3191
1.84k
    if (!extensionProj4.empty()) {
3192
52
        props.set("EXTENSION_PROJ4", extensionProj4);
3193
52
    }
3194
1.84k
}
3195
3196
// ---------------------------------------------------------------------------
3197
3198
GeodeticCRSNNPtr
3199
WKTParser::Private::buildGeodeticCRS(const WKTNodeNNPtr &node,
3200
1.35k
                                     bool forceGeocentricIfNoCs) {
3201
1.35k
    const auto *nodeP = node->GP();
3202
1.35k
    auto &datumNode = nodeP->lookForChild(
3203
1.35k
        WKTConstants::DATUM, WKTConstants::GEODETICDATUM, WKTConstants::TRF);
3204
1.35k
    auto &ensembleNode = nodeP->lookForChild(WKTConstants::ENSEMBLE);
3205
1.35k
    if (isNull(datumNode) && isNull(ensembleNode)) {
3206
10
        throw ParsingException("Missing DATUM or ENSEMBLE node");
3207
10
    }
3208
3209
    // Do that now so that esriStyle_ can be set before buildPrimeMeridian()
3210
1.34k
    auto props = buildProperties(node);
3211
3212
1.34k
    auto &dynamicNode = nodeP->lookForChild(WKTConstants::DYNAMIC);
3213
3214
1.34k
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
3215
1.34k
    const auto &nodeName = nodeP->value();
3216
1.34k
    if (isNull(csNode) && !ci_equal(nodeName, WKTConstants::GEOGCS) &&
3217
84
        !ci_equal(nodeName, WKTConstants::GEOCCS) &&
3218
1
        !ci_equal(nodeName, WKTConstants::BASEGEODCRS) &&
3219
1
        !ci_equal(nodeName, WKTConstants::BASEGEOGCRS)) {
3220
1
        ThrowMissing(WKTConstants::CS_);
3221
1
    }
3222
3223
1.34k
    auto &primeMeridianNode =
3224
1.34k
        nodeP->lookForChild(WKTConstants::PRIMEM, WKTConstants::PRIMEMERIDIAN);
3225
1.34k
    if (isNull(primeMeridianNode)) {
3226
        // PRIMEM is required in WKT1
3227
995
        if (ci_equal(nodeName, WKTConstants::GEOGCS) ||
3228
995
            ci_equal(nodeName, WKTConstants::GEOCCS)) {
3229
995
            emitRecoverableWarning(nodeName + " should have a PRIMEM node");
3230
995
        }
3231
995
    }
3232
3233
1.34k
    auto angularUnit =
3234
1.34k
        buildUnitInSubNode(node, ci_equal(nodeName, WKTConstants::GEOGCS)
3235
1.34k
                                     ? UnitOfMeasure::Type::ANGULAR
3236
1.34k
                                     : UnitOfMeasure::Type::UNKNOWN);
3237
1.34k
    if (angularUnit.type() != UnitOfMeasure::Type::ANGULAR) {
3238
789
        angularUnit = UnitOfMeasure::NONE;
3239
789
    }
3240
3241
1.34k
    auto primeMeridian =
3242
1.34k
        !isNull(primeMeridianNode)
3243
1.34k
            ? buildPrimeMeridian(primeMeridianNode, angularUnit)
3244
1.34k
            : PrimeMeridian::GREENWICH;
3245
1.34k
    if (angularUnit == UnitOfMeasure::NONE) {
3246
789
        angularUnit = primeMeridian->longitude().unit();
3247
789
    }
3248
3249
1.34k
    addExtensionProj4ToProp(nodeP, props);
3250
3251
    // No explicit AXIS node ? (WKT1)
3252
1.34k
    if (isNull(nodeP->lookForChild(WKTConstants::AXIS))) {
3253
1.27k
        props.set("IMPLICIT_CS", true);
3254
1.27k
    }
3255
3256
1.34k
    const std::string crsName = stripQuotes(nodeP->children()[0]);
3257
1.34k
    if (esriStyle_ && dbContext_) {
3258
359
        std::string outTableName;
3259
359
        std::string authNameFromAlias;
3260
359
        std::string codeFromAlias;
3261
359
        auto authFactory =
3262
359
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
3263
359
        auto officialName = authFactory->getOfficialNameFromAlias(
3264
359
            crsName, "geodetic_crs", "ESRI", false, outTableName,
3265
359
            authNameFromAlias, codeFromAlias);
3266
359
        if (!officialName.empty()) {
3267
289
            props.set(IdentifiedObject::NAME_KEY, officialName);
3268
289
        }
3269
359
    }
3270
3271
1.34k
    auto datum =
3272
1.34k
        !isNull(datumNode)
3273
1.34k
            ? buildGeodeticReferenceFrame(datumNode, primeMeridian, dynamicNode)
3274
1.13k
                  .as_nullable()
3275
1.34k
            : nullptr;
3276
1.34k
    auto datumEnsemble =
3277
1.34k
        !isNull(ensembleNode)
3278
1.34k
            ? buildDatumEnsemble(ensembleNode, primeMeridian, true)
3279
185
                  .as_nullable()
3280
1.34k
            : nullptr;
3281
1.34k
    auto cs = buildCS(csNode, node, angularUnit);
3282
3283
    // If there's no CS[] node, typically for a BASEGEODCRS of a projected CRS,
3284
    // in a few rare cases, this might be a Geocentric CRS, and thus a
3285
    // Cartesian CS, and not the ellipsoidalCS we assumed above. The only way
3286
    // to figure that is to resolve the CRS from its code...
3287
1.34k
    if (isNull(csNode) && dbContext_ &&
3288
946
        ci_equal(nodeName, WKTConstants::BASEGEODCRS)) {
3289
0
        const auto &nodeChildren = nodeP->children();
3290
0
        for (const auto &subNode : nodeChildren) {
3291
0
            const auto &subNodeName(subNode->GP()->value());
3292
0
            if (ci_equal(subNodeName, WKTConstants::ID) ||
3293
0
                ci_equal(subNodeName, WKTConstants::AUTHORITY)) {
3294
0
                auto id = buildId(node, subNode, true, false);
3295
0
                if (id) {
3296
0
                    try {
3297
0
                        auto authFactory = AuthorityFactory::create(
3298
0
                            NN_NO_CHECK(dbContext_), *id->codeSpace());
3299
0
                        auto dbCRS = authFactory->createGeodeticCRS(id->code());
3300
0
                        cs = dbCRS->coordinateSystem();
3301
0
                    } catch (const util::Exception &) {
3302
0
                    }
3303
0
                }
3304
0
            }
3305
0
        }
3306
0
    }
3307
1.34k
    if (forceGeocentricIfNoCs && isNull(csNode) &&
3308
0
        ci_equal(nodeName, WKTConstants::BASEGEODCRS)) {
3309
0
        cs = cs::CartesianCS::createGeocentric(UnitOfMeasure::METRE);
3310
0
    }
3311
3312
1.34k
    auto ellipsoidalCS = nn_dynamic_pointer_cast<EllipsoidalCS>(cs);
3313
1.34k
    if (ellipsoidalCS) {
3314
1.01k
        if (ci_equal(nodeName, WKTConstants::GEOCCS)) {
3315
0
            throw ParsingException("ellipsoidal CS not expected in GEOCCS");
3316
0
        }
3317
1.01k
        try {
3318
1.01k
            auto crs = GeographicCRS::create(props, datum, datumEnsemble,
3319
1.01k
                                             NN_NO_CHECK(ellipsoidalCS));
3320
            // In case of missing CS node, or to check it, query the coordinate
3321
            // system from the DB if possible (typically for the baseCRS of a
3322
            // ProjectedCRS)
3323
1.01k
            if (!crs->identifiers().empty() && dbContext_) {
3324
7
                GeographicCRSPtr dbCRS;
3325
7
                try {
3326
7
                    const auto &id = crs->identifiers()[0];
3327
7
                    auto authFactory = AuthorityFactory::create(
3328
7
                        NN_NO_CHECK(dbContext_), *id->codeSpace());
3329
7
                    dbCRS = authFactory->createGeographicCRS(id->code())
3330
7
                                .as_nullable();
3331
7
                } catch (const util::Exception &) {
3332
7
                }
3333
7
                if (dbCRS &&
3334
0
                    (!isNull(csNode) ||
3335
0
                     node->countChildrenOfName(WKTConstants::AXIS) != 0) &&
3336
0
                    !ellipsoidalCS->_isEquivalentTo(
3337
0
                        dbCRS->coordinateSystem().get(),
3338
0
                        util::IComparable::Criterion::EQUIVALENT)) {
3339
0
                    if (unsetIdentifiersIfIncompatibleDef_) {
3340
0
                        emitRecoverableWarning(
3341
0
                            "Coordinate system of GeographicCRS in the WKT "
3342
0
                            "definition is different from the one of the "
3343
0
                            "authority. Unsetting the identifier to avoid "
3344
0
                            "confusion");
3345
0
                        props.unset(Identifier::CODESPACE_KEY);
3346
0
                        props.unset(Identifier::AUTHORITY_KEY);
3347
0
                        props.unset(IdentifiedObject::IDENTIFIERS_KEY);
3348
0
                    }
3349
0
                    crs = GeographicCRS::create(props, datum, datumEnsemble,
3350
0
                                                NN_NO_CHECK(ellipsoidalCS));
3351
7
                } else if (dbCRS) {
3352
0
                    auto csFromDB = dbCRS->coordinateSystem();
3353
0
                    auto csFromDBAltered = csFromDB;
3354
0
                    if (!isNull(nodeP->lookForChild(WKTConstants::UNIT))) {
3355
0
                        csFromDBAltered =
3356
0
                            csFromDB->alterAngularUnit(angularUnit);
3357
0
                        if (unsetIdentifiersIfIncompatibleDef_ &&
3358
0
                            !csFromDBAltered->_isEquivalentTo(
3359
0
                                csFromDB.get(),
3360
0
                                util::IComparable::Criterion::EQUIVALENT)) {
3361
0
                            emitRecoverableWarning(
3362
0
                                "Coordinate system of GeographicCRS in the WKT "
3363
0
                                "definition is different from the one of the "
3364
0
                                "authority. Unsetting the identifier to avoid "
3365
0
                                "confusion");
3366
0
                            props.unset(Identifier::CODESPACE_KEY);
3367
0
                            props.unset(Identifier::AUTHORITY_KEY);
3368
0
                            props.unset(IdentifiedObject::IDENTIFIERS_KEY);
3369
0
                        }
3370
0
                    }
3371
0
                    crs = GeographicCRS::create(props, datum, datumEnsemble,
3372
0
                                                csFromDBAltered);
3373
0
                }
3374
7
            }
3375
1.01k
            return crs;
3376
1.01k
        } catch (const util::Exception &e) {
3377
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
3378
0
                                   e.what());
3379
0
        }
3380
1.01k
    } else if (ci_equal(nodeName, WKTConstants::GEOGCRS) ||
3381
41
               ci_equal(nodeName, WKTConstants::GEOGRAPHICCRS) ||
3382
41
               ci_equal(nodeName, WKTConstants::BASEGEOGCRS)) {
3383
        // This is a WKT2-2019 GeographicCRS. An ellipsoidal CS is expected
3384
0
        throw ParsingException(concat("ellipsoidal CS expected, but found ",
3385
0
                                      cs->getWKT2Type(true)));
3386
0
    }
3387
3388
331
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
3389
331
    if (cartesianCS) {
3390
41
        if (cartesianCS->axisList().size() != 3) {
3391
1
            throw ParsingException(
3392
1
                "Cartesian CS for a GeodeticCRS should have 3 axis");
3393
1
        }
3394
40
        try {
3395
40
            return GeodeticCRS::create(props, datum, datumEnsemble,
3396
40
                                       NN_NO_CHECK(cartesianCS));
3397
40
        } catch (const util::Exception &e) {
3398
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
3399
0
                                   e.what());
3400
0
        }
3401
40
    }
3402
3403
290
    auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs);
3404
290
    if (sphericalCS) {
3405
0
        try {
3406
0
            return GeodeticCRS::create(props, datum, datumEnsemble,
3407
0
                                       NN_NO_CHECK(sphericalCS));
3408
0
        } catch (const util::Exception &e) {
3409
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
3410
0
                                   e.what());
3411
0
        }
3412
0
    }
3413
3414
290
    throw ParsingException(
3415
290
        concat("unhandled CS type: ", cs->getWKT2Type(true)));
3416
290
}
3417
3418
// ---------------------------------------------------------------------------
3419
3420
0
CRSNNPtr WKTParser::Private::buildDerivedGeodeticCRS(const WKTNodeNNPtr &node) {
3421
0
    const auto *nodeP = node->GP();
3422
0
    auto &baseGeodCRSNode = nodeP->lookForChild(WKTConstants::BASEGEODCRS,
3423
0
                                                WKTConstants::BASEGEOGCRS);
3424
    // given the constraints enforced on calling code path
3425
0
    assert(!isNull(baseGeodCRSNode));
3426
3427
0
    auto &derivingConversionNode =
3428
0
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
3429
0
    if (isNull(derivingConversionNode)) {
3430
0
        ThrowMissing(WKTConstants::DERIVINGCONVERSION);
3431
0
    }
3432
0
    auto derivingConversion = buildConversion(
3433
0
        derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE);
3434
3435
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
3436
0
    if (isNull(csNode)) {
3437
0
        ThrowMissing(WKTConstants::CS_);
3438
0
    }
3439
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
3440
3441
0
    bool forceGeocentricIfNoCs = false;
3442
0
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
3443
0
    if (cartesianCS) {
3444
0
        if (cartesianCS->axisList().size() != 3) {
3445
0
            throw ParsingException(
3446
0
                "Cartesian CS for a GeodeticCRS should have 3 axis");
3447
0
        }
3448
0
        const int methodCode = derivingConversion->method()->getEPSGCode();
3449
0
        if ((methodCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC ||
3450
0
             methodCode ==
3451
0
                 EPSG_CODE_METHOD_COORDINATE_FRAME_FULL_MATRIX_GEOCENTRIC ||
3452
0
             methodCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC ||
3453
0
             methodCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC ||
3454
0
             methodCode ==
3455
0
                 EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC ||
3456
0
             methodCode ==
3457
0
                 EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC) &&
3458
0
            nodeP->lookForChild(WKTConstants::BASEGEODCRS) != nullptr) {
3459
0
            forceGeocentricIfNoCs = true;
3460
0
        }
3461
0
    }
3462
0
    auto baseGeodCRS = buildGeodeticCRS(baseGeodCRSNode, forceGeocentricIfNoCs);
3463
3464
0
    auto ellipsoidalCS = nn_dynamic_pointer_cast<EllipsoidalCS>(cs);
3465
0
    if (ellipsoidalCS) {
3466
3467
0
        if (ellipsoidalCS->axisList().size() == 3 &&
3468
0
            baseGeodCRS->coordinateSystem()->axisList().size() == 2) {
3469
0
            baseGeodCRS =
3470
0
                NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>(
3471
0
                    baseGeodCRS->promoteTo3D(std::string(), dbContext_)));
3472
0
        }
3473
3474
0
        return DerivedGeographicCRS::create(buildProperties(node), baseGeodCRS,
3475
0
                                            derivingConversion,
3476
0
                                            NN_NO_CHECK(ellipsoidalCS));
3477
0
    } else if (ci_equal(nodeP->value(), WKTConstants::GEOGCRS)) {
3478
        // This is a WKT2-2019 GeographicCRS. An ellipsoidal CS is expected
3479
0
        throw ParsingException(concat("ellipsoidal CS expected, but found ",
3480
0
                                      cs->getWKT2Type(true)));
3481
0
    }
3482
3483
0
    if (cartesianCS) {
3484
0
        return DerivedGeodeticCRS::create(buildProperties(node), baseGeodCRS,
3485
0
                                          derivingConversion,
3486
0
                                          NN_NO_CHECK(cartesianCS));
3487
0
    }
3488
3489
0
    auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs);
3490
0
    if (sphericalCS) {
3491
0
        return DerivedGeodeticCRS::create(buildProperties(node), baseGeodCRS,
3492
0
                                          derivingConversion,
3493
0
                                          NN_NO_CHECK(sphericalCS));
3494
0
    }
3495
3496
0
    throw ParsingException(
3497
0
        concat("unhandled CS type: ", cs->getWKT2Type(true)));
3498
0
}
3499
3500
// ---------------------------------------------------------------------------
3501
3502
UnitOfMeasure WKTParser::Private::guessUnitForParameter(
3503
    const std::string &paramName, const UnitOfMeasure &defaultLinearUnit,
3504
3.27k
    const UnitOfMeasure &defaultAngularUnit) {
3505
3.27k
    UnitOfMeasure unit;
3506
    // scale must be first because of 'Scale factor on pseudo standard parallel'
3507
3.27k
    if (ci_find(paramName, "scale") != std::string::npos ||
3508
3.19k
        ci_find(paramName, "scaling factor") != std::string::npos) {
3509
80
        unit = UnitOfMeasure::SCALE_UNITY;
3510
3.19k
    } else if (ci_find(paramName, "latitude") != std::string::npos ||
3511
2.91k
               ci_find(paramName, "longitude") != std::string::npos ||
3512
2.54k
               ci_find(paramName, "meridian") != std::string::npos ||
3513
2.53k
               ci_find(paramName, "parallel") != std::string::npos ||
3514
2.50k
               ci_find(paramName, "azimuth") != std::string::npos ||
3515
2.47k
               ci_find(paramName, "angle") != std::string::npos ||
3516
2.43k
               ci_find(paramName, "heading") != std::string::npos ||
3517
2.39k
               ci_find(paramName, "rotation") != std::string::npos) {
3518
857
        unit = defaultAngularUnit;
3519
2.33k
    } else if (ci_find(paramName, "easting") != std::string::npos ||
3520
2.00k
               ci_find(paramName, "northing") != std::string::npos ||
3521
1.62k
               ci_find(paramName, "height") != std::string::npos) {
3522
752
        unit = defaultLinearUnit;
3523
752
    }
3524
3.27k
    return unit;
3525
3.27k
}
3526
3527
// ---------------------------------------------------------------------------
3528
3529
static bool
3530
619
isEPSGCodeForInterpolationParameter(const OperationParameterNNPtr &parameter) {
3531
619
    const auto &name = parameter->nameStr();
3532
619
    const auto epsgCode = parameter->getEPSGCode();
3533
619
    return name == EPSG_NAME_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS ||
3534
615
           epsgCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS ||
3535
562
           name == EPSG_NAME_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS ||
3536
562
           epsgCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS;
3537
619
}
3538
3539
// ---------------------------------------------------------------------------
3540
3541
356
static bool isIntegerParameter(const OperationParameterNNPtr &parameter) {
3542
356
    return isEPSGCodeForInterpolationParameter(parameter);
3543
356
}
3544
3545
// ---------------------------------------------------------------------------
3546
3547
void WKTParser::Private::consumeParameters(
3548
    const WKTNodeNNPtr &node, bool isAbridged,
3549
    std::vector<OperationParameterNNPtr> &parameters,
3550
    std::vector<ParameterValueNNPtr> &values,
3551
    const UnitOfMeasure &defaultLinearUnit,
3552
356
    const UnitOfMeasure &defaultAngularUnit) {
3553
2.41k
    for (const auto &childNode : node->GP()->children()) {
3554
2.41k
        const auto &childNodeChildren = childNode->GP()->children();
3555
2.41k
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
3556
560
            if (childNodeChildren.size() < 2) {
3557
9
                ThrowNotEnoughChildren(childNode->GP()->value());
3558
9
            }
3559
551
            parameters.push_back(
3560
551
                OperationParameter::create(buildProperties(childNode)));
3561
551
            const auto &paramValue = childNodeChildren[1]->GP()->value();
3562
551
            if (!paramValue.empty() && paramValue[0] == '"') {
3563
176
                values.push_back(
3564
176
                    ParameterValue::create(stripQuotes(childNodeChildren[1])));
3565
375
            } else {
3566
375
                try {
3567
375
                    double val = asDouble(childNodeChildren[1]);
3568
375
                    auto unit = buildUnitInSubNode(childNode);
3569
375
                    if (unit == UnitOfMeasure::NONE) {
3570
356
                        const auto &paramName =
3571
356
                            childNodeChildren[0]->GP()->value();
3572
356
                        unit = guessUnitForParameter(
3573
356
                            paramName, defaultLinearUnit, defaultAngularUnit);
3574
356
                    }
3575
3576
375
                    if (isAbridged) {
3577
0
                        const auto &paramName = parameters.back()->nameStr();
3578
0
                        int paramEPSGCode = 0;
3579
0
                        const auto &paramIds = parameters.back()->identifiers();
3580
0
                        if (paramIds.size() == 1 &&
3581
0
                            ci_equal(*(paramIds[0]->codeSpace()),
3582
0
                                     Identifier::EPSG)) {
3583
0
                            paramEPSGCode = ::atoi(paramIds[0]->code().c_str());
3584
0
                        }
3585
0
                        const common::UnitOfMeasure *pUnit = nullptr;
3586
0
                        if (OperationParameterValue::convertFromAbridged(
3587
0
                                paramName, val, pUnit, paramEPSGCode)) {
3588
0
                            unit = *pUnit;
3589
0
                            parameters.back() = OperationParameter::create(
3590
0
                                buildProperties(childNode)
3591
0
                                    .set(Identifier::CODESPACE_KEY,
3592
0
                                         Identifier::EPSG)
3593
0
                                    .set(Identifier::CODE_KEY, paramEPSGCode));
3594
0
                        }
3595
0
                    }
3596
3597
375
                    if (isIntegerParameter(parameters.back())) {
3598
48
                        values.push_back(ParameterValue::create(
3599
48
                            std::stoi(childNodeChildren[1]->GP()->value())));
3600
327
                    } else {
3601
327
                        values.push_back(
3602
327
                            ParameterValue::create(Measure(val, unit)));
3603
327
                    }
3604
375
                } catch (const std::exception &) {
3605
24
                    throw ParsingException(concat(
3606
24
                        "unhandled parameter value type : ", paramValue));
3607
24
                }
3608
375
            }
3609
1.85k
        } else if (ci_equal(childNode->GP()->value(),
3610
1.85k
                            WKTConstants::PARAMETERFILE)) {
3611
60
            if (childNodeChildren.size() < 2) {
3612
3
                ThrowNotEnoughChildren(childNode->GP()->value());
3613
3
            }
3614
57
            parameters.push_back(
3615
57
                OperationParameter::create(buildProperties(childNode)));
3616
57
            values.push_back(ParameterValue::createFilename(
3617
57
                stripQuotes(childNodeChildren[1])));
3618
57
        }
3619
2.41k
    }
3620
356
}
3621
3622
// ---------------------------------------------------------------------------
3623
3624
static CRSPtr dealWithEPSGCodeForInterpolationCRSParameter(
3625
    DatabaseContextPtr &dbContext,
3626
    std::vector<OperationParameterNNPtr> &parameters,
3627
    std::vector<ParameterValueNNPtr> &values);
3628
3629
ConversionNNPtr
3630
WKTParser::Private::buildConversion(const WKTNodeNNPtr &node,
3631
                                    const UnitOfMeasure &defaultLinearUnit,
3632
364
                                    const UnitOfMeasure &defaultAngularUnit) {
3633
364
    auto &methodNode = node->GP()->lookForChild(WKTConstants::METHOD,
3634
364
                                                WKTConstants::PROJECTION);
3635
364
    if (isNull(methodNode)) {
3636
7
        ThrowMissing(WKTConstants::METHOD);
3637
7
    }
3638
357
    if (methodNode->GP()->childrenSize() == 0) {
3639
1
        ThrowNotEnoughChildren(WKTConstants::METHOD);
3640
1
    }
3641
3642
356
    std::vector<OperationParameterNNPtr> parameters;
3643
356
    std::vector<ParameterValueNNPtr> values;
3644
356
    consumeParameters(node, false, parameters, values, defaultLinearUnit,
3645
356
                      defaultAngularUnit);
3646
3647
356
    auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
3648
356
        dbContext_, parameters, values);
3649
3650
356
    auto &convProps = buildProperties(node);
3651
356
    auto &methodProps = buildProperties(methodNode);
3652
356
    std::string convName;
3653
356
    std::string methodName;
3654
356
    if (convProps.getStringValue(IdentifiedObject::NAME_KEY, convName) &&
3655
319
        methodProps.getStringValue(IdentifiedObject::NAME_KEY, methodName) &&
3656
319
        starts_with(convName, "Inverse of ") &&
3657
59
        starts_with(methodName, "Inverse of ")) {
3658
3659
47
        auto &invConvProps = buildProperties(node, true);
3660
47
        auto &invMethodProps = buildProperties(methodNode, true);
3661
47
        auto conv = NN_NO_CHECK(util::nn_dynamic_pointer_cast<Conversion>(
3662
47
            Conversion::create(invConvProps, invMethodProps, parameters, values)
3663
47
                ->inverse()));
3664
47
        if (interpolationCRS)
3665
0
            conv->setInterpolationCRS(interpolationCRS);
3666
47
        return conv;
3667
47
    }
3668
309
    auto conv = Conversion::create(convProps, methodProps, parameters, values);
3669
309
    if (interpolationCRS)
3670
0
        conv->setInterpolationCRS(interpolationCRS);
3671
309
    return conv;
3672
356
}
3673
3674
// ---------------------------------------------------------------------------
3675
3676
static CRSPtr dealWithEPSGCodeForInterpolationCRSParameter(
3677
    DatabaseContextPtr &dbContext,
3678
    std::vector<OperationParameterNNPtr> &parameters,
3679
320
    std::vector<ParameterValueNNPtr> &values) {
3680
    // Transform EPSG hacky PARAMETER["EPSG code for Interpolation CRS",
3681
    // crs_epsg_code] into proper interpolation CRS
3682
320
    if (dbContext != nullptr) {
3683
549
        for (size_t i = 0; i < parameters.size(); ++i) {
3684
263
            if (isEPSGCodeForInterpolationParameter(parameters[i])) {
3685
9
                const int code = values[i]->integerValue();
3686
9
                try {
3687
9
                    auto authFactory = AuthorityFactory::create(
3688
9
                        NN_NO_CHECK(dbContext), Identifier::EPSG);
3689
9
                    auto interpolationCRS =
3690
9
                        authFactory
3691
9
                            ->createGeographicCRS(internal::toString(code))
3692
9
                            .as_nullable();
3693
9
                    parameters.erase(parameters.begin() + i);
3694
9
                    values.erase(values.begin() + i);
3695
9
                    return interpolationCRS;
3696
9
                } catch (const util::Exception &) {
3697
9
                }
3698
9
            }
3699
263
        }
3700
286
    }
3701
320
    return nullptr;
3702
320
}
3703
3704
// ---------------------------------------------------------------------------
3705
3706
TransformationNNPtr
3707
13
WKTParser::Private::buildCoordinateOperation(const WKTNodeNNPtr &node) {
3708
13
    const auto *nodeP = node->GP();
3709
13
    auto &methodNode = nodeP->lookForChild(WKTConstants::METHOD);
3710
13
    if (isNull(methodNode)) {
3711
7
        ThrowMissing(WKTConstants::METHOD);
3712
7
    }
3713
6
    if (methodNode->GP()->childrenSize() == 0) {
3714
2
        ThrowNotEnoughChildren(WKTConstants::METHOD);
3715
2
    }
3716
3717
4
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
3718
4
    if (/*isNull(sourceCRSNode) ||*/ sourceCRSNode->GP()->childrenSize() != 1) {
3719
4
        ThrowMissing(WKTConstants::SOURCECRS);
3720
4
    }
3721
0
    auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]);
3722
0
    if (!sourceCRS) {
3723
0
        throw ParsingException("Invalid content in SOURCECRS node");
3724
0
    }
3725
3726
0
    auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS);
3727
0
    if (/*isNull(targetCRSNode) ||*/ targetCRSNode->GP()->childrenSize() != 1) {
3728
0
        ThrowMissing(WKTConstants::TARGETCRS);
3729
0
    }
3730
0
    auto targetCRS = buildCRS(targetCRSNode->GP()->children()[0]);
3731
0
    if (!targetCRS) {
3732
0
        throw ParsingException("Invalid content in TARGETCRS node");
3733
0
    }
3734
3735
0
    auto &interpolationCRSNode =
3736
0
        nodeP->lookForChild(WKTConstants::INTERPOLATIONCRS);
3737
0
    CRSPtr interpolationCRS;
3738
0
    if (/*!isNull(interpolationCRSNode) && */ interpolationCRSNode->GP()
3739
0
            ->childrenSize() == 1) {
3740
0
        interpolationCRS = buildCRS(interpolationCRSNode->GP()->children()[0]);
3741
0
    }
3742
3743
0
    std::vector<OperationParameterNNPtr> parameters;
3744
0
    std::vector<ParameterValueNNPtr> values;
3745
0
    const auto &defaultLinearUnit = UnitOfMeasure::NONE;
3746
0
    const auto &defaultAngularUnit = UnitOfMeasure::NONE;
3747
0
    consumeParameters(node, false, parameters, values, defaultLinearUnit,
3748
0
                      defaultAngularUnit);
3749
3750
0
    if (interpolationCRS == nullptr)
3751
0
        interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
3752
0
            dbContext_, parameters, values);
3753
3754
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
3755
0
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY);
3756
0
    if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) {
3757
0
        accuracies.push_back(PositionalAccuracy::create(
3758
0
            stripQuotes(accuracyNode->GP()->children()[0])));
3759
0
    }
3760
3761
0
    return Transformation::create(buildProperties(node), NN_NO_CHECK(sourceCRS),
3762
0
                                  NN_NO_CHECK(targetCRS), interpolationCRS,
3763
0
                                  buildProperties(methodNode), parameters,
3764
0
                                  values, accuracies);
3765
0
}
3766
3767
// ---------------------------------------------------------------------------
3768
3769
PointMotionOperationNNPtr
3770
1
WKTParser::Private::buildPointMotionOperation(const WKTNodeNNPtr &node) {
3771
1
    const auto *nodeP = node->GP();
3772
1
    auto &methodNode = nodeP->lookForChild(WKTConstants::METHOD);
3773
1
    if (isNull(methodNode)) {
3774
1
        ThrowMissing(WKTConstants::METHOD);
3775
1
    }
3776
0
    if (methodNode->GP()->childrenSize() == 0) {
3777
0
        ThrowNotEnoughChildren(WKTConstants::METHOD);
3778
0
    }
3779
3780
0
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
3781
0
    if (sourceCRSNode->GP()->childrenSize() != 1) {
3782
0
        ThrowMissing(WKTConstants::SOURCECRS);
3783
0
    }
3784
0
    auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]);
3785
0
    if (!sourceCRS) {
3786
0
        throw ParsingException("Invalid content in SOURCECRS node");
3787
0
    }
3788
3789
0
    std::vector<OperationParameterNNPtr> parameters;
3790
0
    std::vector<ParameterValueNNPtr> values;
3791
0
    const auto &defaultLinearUnit = UnitOfMeasure::NONE;
3792
0
    const auto &defaultAngularUnit = UnitOfMeasure::NONE;
3793
0
    consumeParameters(node, false, parameters, values, defaultLinearUnit,
3794
0
                      defaultAngularUnit);
3795
3796
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
3797
0
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY);
3798
0
    if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) {
3799
0
        accuracies.push_back(PositionalAccuracy::create(
3800
0
            stripQuotes(accuracyNode->GP()->children()[0])));
3801
0
    }
3802
3803
0
    return PointMotionOperation::create(
3804
0
        buildProperties(node), NN_NO_CHECK(sourceCRS),
3805
0
        buildProperties(methodNode), parameters, values, accuracies);
3806
0
}
3807
3808
// ---------------------------------------------------------------------------
3809
3810
ConcatenatedOperationNNPtr
3811
5
WKTParser::Private::buildConcatenatedOperation(const WKTNodeNNPtr &node) {
3812
3813
5
    const auto *nodeP = node->GP();
3814
5
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
3815
5
    if (/*isNull(sourceCRSNode) ||*/ sourceCRSNode->GP()->childrenSize() != 1) {
3816
5
        ThrowMissing(WKTConstants::SOURCECRS);
3817
5
    }
3818
0
    auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]);
3819
0
    if (!sourceCRS) {
3820
0
        throw ParsingException("Invalid content in SOURCECRS node");
3821
0
    }
3822
3823
0
    auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS);
3824
0
    if (/*isNull(targetCRSNode) ||*/ targetCRSNode->GP()->childrenSize() != 1) {
3825
0
        ThrowMissing(WKTConstants::TARGETCRS);
3826
0
    }
3827
0
    auto targetCRS = buildCRS(targetCRSNode->GP()->children()[0]);
3828
0
    if (!targetCRS) {
3829
0
        throw ParsingException("Invalid content in TARGETCRS node");
3830
0
    }
3831
3832
0
    std::vector<CoordinateOperationNNPtr> operations;
3833
0
    for (const auto &childNode : nodeP->children()) {
3834
0
        if (ci_equal(childNode->GP()->value(), WKTConstants::STEP)) {
3835
0
            if (childNode->GP()->childrenSize() != 1) {
3836
0
                throw ParsingException("Invalid content in STEP node");
3837
0
            }
3838
0
            auto op = nn_dynamic_pointer_cast<CoordinateOperation>(
3839
0
                build(childNode->GP()->children()[0]));
3840
0
            if (!op) {
3841
0
                throw ParsingException("Invalid content in STEP node");
3842
0
            }
3843
0
            operations.emplace_back(NN_NO_CHECK(op));
3844
0
        }
3845
0
    }
3846
3847
0
    ConcatenatedOperation::fixSteps(
3848
0
        NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), operations, dbContext_,
3849
0
        /* fixDirectionAllowed = */ true);
3850
3851
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
3852
0
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY);
3853
0
    if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) {
3854
0
        accuracies.push_back(PositionalAccuracy::create(
3855
0
            stripQuotes(accuracyNode->GP()->children()[0])));
3856
0
    }
3857
3858
0
    try {
3859
0
        return ConcatenatedOperation::create(buildProperties(node), operations,
3860
0
                                             accuracies);
3861
0
    } catch (const InvalidOperation &e) {
3862
0
        throw ParsingException(
3863
0
            std::string("Cannot build concatenated operation: ") + e.what());
3864
0
    }
3865
0
}
3866
3867
// ---------------------------------------------------------------------------
3868
3869
bool WKTParser::Private::hasWebMercPROJ4String(
3870
710
    const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode) {
3871
710
    if (projectionNode->GP()->childrenSize() == 0) {
3872
2
        ThrowNotEnoughChildren(WKTConstants::PROJECTION);
3873
2
    }
3874
708
    const std::string wkt1ProjectionName =
3875
708
        stripQuotes(projectionNode->GP()->children()[0]);
3876
3877
708
    auto &extensionNode = projCRSNode->lookForChild(WKTConstants::EXTENSION);
3878
3879
708
    if (metadata::Identifier::isEquivalentName(wkt1ProjectionName.c_str(),
3880
708
                                               "Mercator_1SP") &&
3881
0
        projCRSNode->countChildrenOfName("center_latitude") == 0) {
3882
3883
        // Hack to detect the hacky way of encodign webmerc in GDAL WKT1
3884
        // with a EXTENSION["PROJ4", "+proj=merc +a=6378137 +b=6378137
3885
        // +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m
3886
        // +nadgrids=@null +wktext +no_defs"] node
3887
0
        if (extensionNode && extensionNode->GP()->childrenSize() == 2 &&
3888
0
            ci_equal(stripQuotes(extensionNode->GP()->children()[0]),
3889
0
                     "PROJ4")) {
3890
0
            std::string projString =
3891
0
                stripQuotes(extensionNode->GP()->children()[1]);
3892
0
            if (projString.find("+proj=merc") != std::string::npos &&
3893
0
                projString.find("+a=6378137") != std::string::npos &&
3894
0
                projString.find("+b=6378137") != std::string::npos &&
3895
0
                projString.find("+lon_0=0") != std::string::npos &&
3896
0
                projString.find("+x_0=0") != std::string::npos &&
3897
0
                projString.find("+y_0=0") != std::string::npos &&
3898
0
                projString.find("+nadgrids=@null") != std::string::npos &&
3899
0
                (projString.find("+lat_ts=") == std::string::npos ||
3900
0
                 projString.find("+lat_ts=0") != std::string::npos) &&
3901
0
                (projString.find("+k=") == std::string::npos ||
3902
0
                 projString.find("+k=1") != std::string::npos) &&
3903
0
                (projString.find("+units=") == std::string::npos ||
3904
0
                 projString.find("+units=m") != std::string::npos)) {
3905
0
                return true;
3906
0
            }
3907
0
        }
3908
0
    }
3909
708
    return false;
3910
708
}
3911
3912
// ---------------------------------------------------------------------------
3913
3914
static const MethodMapping *
3915
selectSphericalOrEllipsoidal(const MethodMapping *mapping,
3916
4.50k
                             const GeodeticCRSNNPtr &baseGeodCRS) {
3917
4.50k
    if (mapping->epsg_code ==
3918
4.50k
            EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL ||
3919
4.50k
        mapping->epsg_code == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA) {
3920
128
        mapping = getMapping(
3921
128
            baseGeodCRS->ellipsoid()->isSphere()
3922
128
                ? EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL
3923
128
                : EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA);
3924
4.37k
    } else if (mapping->epsg_code ==
3925
4.37k
                   EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL ||
3926
4.37k
               mapping->epsg_code ==
3927
4.37k
                   EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA) {
3928
187
        mapping = getMapping(
3929
187
            baseGeodCRS->ellipsoid()->isSphere()
3930
187
                ? EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL
3931
187
                : EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA);
3932
4.19k
    } else if (mapping->epsg_code ==
3933
4.19k
                   EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL ||
3934
4.19k
               mapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL) {
3935
52
        mapping =
3936
52
            getMapping(baseGeodCRS->ellipsoid()->isSphere()
3937
52
                           ? EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL
3938
52
                           : EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL);
3939
52
    }
3940
4.50k
    return mapping;
3941
4.50k
}
3942
3943
// ---------------------------------------------------------------------------
3944
3945
const ESRIMethodMapping *WKTParser::Private::getESRIMapping(
3946
    const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode,
3947
945
    std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue) {
3948
945
    const std::string esriProjectionName =
3949
945
        stripQuotes(projectionNode->GP()->children()[0]);
3950
3951
    // Lambert_Conformal_Conic or Krovak may map to different WKT2 methods
3952
    // depending
3953
    // on the parameters / their values
3954
945
    const auto esriMappings = getMappingsFromESRI(esriProjectionName);
3955
945
    if (esriMappings.empty()) {
3956
409
        return nullptr;
3957
409
    }
3958
3959
    // Build a map of present parameters
3960
4.64k
    for (const auto &childNode : projCRSNode->GP()->children()) {
3961
4.64k
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
3962
2.19k
            const auto &childNodeChildren = childNode->GP()->children();
3963
2.19k
            if (childNodeChildren.size() < 2) {
3964
10
                ThrowNotEnoughChildren(WKTConstants::PARAMETER);
3965
10
            }
3966
2.18k
            const std::string parameterName(stripQuotes(childNodeChildren[0]));
3967
2.18k
            const auto &paramValue = childNodeChildren[1]->GP()->value();
3968
2.18k
            mapParamNameToValue[parameterName] = paramValue;
3969
2.18k
        }
3970
4.64k
    }
3971
3972
    // Compare parameters present with the ones expected in the mapping
3973
526
    const ESRIMethodMapping *esriMapping = nullptr;
3974
526
    int bestMatchCount = -1;
3975
777
    for (const auto &mapping : esriMappings) {
3976
777
        int matchCount = 0;
3977
777
        int unmatchCount = 0;
3978
5.49k
        for (const auto *param = mapping->params; param->esri_name; ++param) {
3979
4.73k
            auto iter = mapParamNameToValue.find(param->esri_name);
3980
4.73k
            if (iter != mapParamNameToValue.end()) {
3981
1.44k
                if (param->wkt2_name == nullptr) {
3982
31
                    bool ok = true;
3983
31
                    try {
3984
31
                        if (io::asDouble(param->fixed_value) ==
3985
31
                            io::asDouble(iter->second)) {
3986
13
                            matchCount++;
3987
18
                        } else {
3988
18
                            ok = false;
3989
18
                        }
3990
31
                    } catch (const std::exception &) {
3991
2
                        ok = false;
3992
2
                    }
3993
31
                    if (!ok) {
3994
18
                        matchCount = -1;
3995
18
                        break;
3996
18
                    }
3997
1.41k
                } else {
3998
1.41k
                    matchCount++;
3999
1.41k
                }
4000
3.29k
            } else if (param->is_fixed_value) {
4001
105
                mapParamNameToValue[param->esri_name] = param->fixed_value;
4002
3.18k
            } else {
4003
3.18k
                unmatchCount++;
4004
3.18k
            }
4005
4.73k
        }
4006
777
        if (matchCount > bestMatchCount &&
4007
726
            !(maybeEsriStyle_ && unmatchCount >= matchCount)) {
4008
349
            esriMapping = mapping;
4009
349
            bestMatchCount = matchCount;
4010
349
        }
4011
777
    }
4012
4013
526
    return esriMapping;
4014
526
}
4015
4016
// ---------------------------------------------------------------------------
4017
4018
ConversionNNPtr WKTParser::Private::buildProjectionFromESRI(
4019
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4020
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4021
    const UnitOfMeasure &defaultAngularUnit,
4022
    const ESRIMethodMapping *esriMapping,
4023
346
    std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue) {
4024
346
    std::map<std::string, const char *> mapWKT2NameToESRIName;
4025
1.90k
    for (const auto *param = esriMapping->params; param->esri_name; ++param) {
4026
1.55k
        if (param->wkt2_name) {
4027
1.49k
            mapWKT2NameToESRIName[param->wkt2_name] = param->esri_name;
4028
1.49k
        }
4029
1.55k
    }
4030
4031
346
    const std::string esriProjectionName =
4032
346
        stripQuotes(projectionNode->GP()->children()[0]);
4033
346
    const char *projectionMethodWkt2Name = esriMapping->wkt2_name;
4034
346
    if (ci_equal(esriProjectionName, "Krovak")) {
4035
17
        const std::string projCRSName =
4036
17
            stripQuotes(projCRSNode->GP()->children()[0]);
4037
17
        if (projCRSName.find("_East_North") != std::string::npos) {
4038
0
            projectionMethodWkt2Name = EPSG_NAME_METHOD_KROVAK_NORTH_ORIENTED;
4039
0
        }
4040
17
    }
4041
4042
346
    const auto *wkt2_mapping = getMapping(projectionMethodWkt2Name);
4043
346
    if (ci_equal(esriProjectionName, "Stereographic")) {
4044
20
        try {
4045
20
            const auto iterLatitudeOfOrigin =
4046
20
                mapParamNameToValue.find("Latitude_Of_Origin");
4047
20
            if (iterLatitudeOfOrigin != mapParamNameToValue.end() &&
4048
19
                std::fabs(io::asDouble(iterLatitudeOfOrigin->second)) == 90.0) {
4049
14
                wkt2_mapping =
4050
14
                    getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A);
4051
14
            }
4052
20
        } catch (const std::exception &) {
4053
0
        }
4054
20
    }
4055
346
    assert(wkt2_mapping);
4056
4057
346
    wkt2_mapping = selectSphericalOrEllipsoidal(wkt2_mapping, baseGeodCRS);
4058
4059
346
    PropertyMap propertiesMethod;
4060
346
    propertiesMethod.set(IdentifiedObject::NAME_KEY, wkt2_mapping->wkt2_name);
4061
346
    if (wkt2_mapping->epsg_code != 0) {
4062
157
        propertiesMethod.set(Identifier::CODE_KEY, wkt2_mapping->epsg_code);
4063
157
        propertiesMethod.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
4064
157
    }
4065
4066
346
    std::vector<OperationParameterNNPtr> parameters;
4067
346
    std::vector<ParameterValueNNPtr> values;
4068
4069
346
    if (wkt2_mapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL &&
4070
2
        ci_equal(esriProjectionName, "Plate_Carree")) {
4071
        // Add a fixed  Latitude of 1st parallel = 0 so as to have all
4072
        // parameters expected by Equidistant Cylindrical.
4073
2
        mapWKT2NameToESRIName[EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL] =
4074
2
            "Standard_Parallel_1";
4075
2
        mapParamNameToValue["Standard_Parallel_1"] = "0";
4076
344
    } else if ((wkt2_mapping->epsg_code ==
4077
344
                    EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A ||
4078
334
                wkt2_mapping->epsg_code ==
4079
334
                    EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B) &&
4080
10
               !ci_equal(esriProjectionName,
4081
10
                         "Rectified_Skew_Orthomorphic_Natural_Origin") &&
4082
0
               !ci_equal(esriProjectionName,
4083
0
                         "Rectified_Skew_Orthomorphic_Center")) {
4084
        // ESRI WKT lacks the angle to skew grid
4085
        // Take it from the azimuth value
4086
0
        mapWKT2NameToESRIName
4087
0
            [EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID] = "Azimuth";
4088
0
    }
4089
4090
1.81k
    for (int i = 0; wkt2_mapping->params[i] != nullptr; i++) {
4091
1.47k
        const auto *paramMapping = wkt2_mapping->params[i];
4092
4093
1.47k
        auto iter = mapWKT2NameToESRIName.find(paramMapping->wkt2_name);
4094
1.47k
        if (iter == mapWKT2NameToESRIName.end()) {
4095
14
            continue;
4096
14
        }
4097
1.46k
        const auto &esriParamName = iter->second;
4098
1.46k
        auto iter2 = mapParamNameToValue.find(esriParamName);
4099
1.46k
        auto mapParamNameToValueEnd = mapParamNameToValue.end();
4100
1.46k
        if (iter2 == mapParamNameToValueEnd) {
4101
            // In case we don't find a direct match, try the aliases
4102
130
            for (iter2 = mapParamNameToValue.begin();
4103
482
                 iter2 != mapParamNameToValueEnd; ++iter2) {
4104
356
                if (areEquivalentParameters(iter2->first, esriParamName)) {
4105
4
                    break;
4106
4
                }
4107
356
            }
4108
130
            if (iter2 == mapParamNameToValueEnd) {
4109
126
                continue;
4110
126
            }
4111
130
        }
4112
4113
1.33k
        PropertyMap propertiesParameter;
4114
1.33k
        propertiesParameter.set(IdentifiedObject::NAME_KEY,
4115
1.33k
                                paramMapping->wkt2_name);
4116
1.33k
        if (paramMapping->epsg_code != 0) {
4117
1.26k
            propertiesParameter.set(Identifier::CODE_KEY,
4118
1.26k
                                    paramMapping->epsg_code);
4119
1.26k
            propertiesParameter.set(Identifier::CODESPACE_KEY,
4120
1.26k
                                    Identifier::EPSG);
4121
1.26k
        }
4122
1.33k
        parameters.push_back(OperationParameter::create(propertiesParameter));
4123
4124
1.33k
        try {
4125
1.33k
            double val = io::asDouble(iter2->second);
4126
1.33k
            auto unit = guessUnitForParameter(
4127
1.33k
                paramMapping->wkt2_name, defaultLinearUnit, defaultAngularUnit);
4128
1.33k
            values.push_back(ParameterValue::create(Measure(val, unit)));
4129
1.33k
        } catch (const std::exception &) {
4130
7
            throw ParsingException(
4131
7
                concat("unhandled parameter value type : ", iter2->second));
4132
7
        }
4133
1.33k
    }
4134
4135
339
    return Conversion::create(
4136
339
               PropertyMap().set(IdentifiedObject::NAME_KEY,
4137
339
                                 esriProjectionName == "Gauss_Kruger"
4138
339
                                     ? "unnnamed (Gauss Kruger)"
4139
339
                                     : "unnamed"),
4140
339
               propertiesMethod, parameters, values)
4141
339
        ->identify();
4142
346
}
4143
4144
// ---------------------------------------------------------------------------
4145
4146
ConversionNNPtr WKTParser::Private::buildProjectionFromESRI(
4147
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4148
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4149
679
    const UnitOfMeasure &defaultAngularUnit) {
4150
4151
679
    std::map<std::string, std::string, ci_less_struct> mapParamNameToValue;
4152
679
    const auto esriMapping =
4153
679
        getESRIMapping(projCRSNode, projectionNode, mapParamNameToValue);
4154
679
    if (esriMapping == nullptr) {
4155
335
        return buildProjectionStandard(baseGeodCRS, projCRSNode, projectionNode,
4156
335
                                       defaultLinearUnit, defaultAngularUnit);
4157
335
    }
4158
4159
344
    return buildProjectionFromESRI(baseGeodCRS, projCRSNode, projectionNode,
4160
344
                                   defaultLinearUnit, defaultAngularUnit,
4161
344
                                   esriMapping, mapParamNameToValue);
4162
679
}
4163
4164
// ---------------------------------------------------------------------------
4165
4166
ConversionNNPtr WKTParser::Private::buildProjection(
4167
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4168
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4169
708
    const UnitOfMeasure &defaultAngularUnit) {
4170
708
    if (projectionNode->GP()->childrenSize() == 0) {
4171
0
        ThrowNotEnoughChildren(WKTConstants::PROJECTION);
4172
0
    }
4173
708
    if (esriStyle_ || maybeEsriStyle_) {
4174
679
        return buildProjectionFromESRI(baseGeodCRS, projCRSNode, projectionNode,
4175
679
                                       defaultLinearUnit, defaultAngularUnit);
4176
679
    }
4177
29
    return buildProjectionStandard(baseGeodCRS, projCRSNode, projectionNode,
4178
29
                                   defaultLinearUnit, defaultAngularUnit);
4179
708
}
4180
4181
// ---------------------------------------------------------------------------
4182
4183
std::string
4184
WKTParser::Private::projectionGetParameter(const WKTNodeNNPtr &projCRSNode,
4185
0
                                           const char *paramName) {
4186
0
    for (const auto &childNode : projCRSNode->GP()->children()) {
4187
0
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
4188
0
            const auto &childNodeChildren = childNode->GP()->children();
4189
0
            if (childNodeChildren.size() == 2 &&
4190
0
                metadata::Identifier::isEquivalentName(
4191
0
                    stripQuotes(childNodeChildren[0]).c_str(), paramName)) {
4192
0
                return childNodeChildren[1]->GP()->value();
4193
0
            }
4194
0
        }
4195
0
    }
4196
0
    return std::string();
4197
0
}
4198
4199
// ---------------------------------------------------------------------------
4200
4201
ConversionNNPtr WKTParser::Private::buildProjectionStandard(
4202
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4203
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4204
364
    const UnitOfMeasure &defaultAngularUnit) {
4205
364
    std::string wkt1ProjectionName =
4206
364
        stripQuotes(projectionNode->GP()->children()[0]);
4207
4208
364
    std::vector<OperationParameterNNPtr> parameters;
4209
364
    std::vector<ParameterValueNNPtr> values;
4210
364
    bool tryToIdentifyWKT1Method = true;
4211
4212
364
    auto &extensionNode = projCRSNode->lookForChild(WKTConstants::EXTENSION);
4213
364
    const auto &extensionChildren = extensionNode->GP()->children();
4214
4215
364
    bool gdal_3026_hack = false;
4216
364
    if (metadata::Identifier::isEquivalentName(wkt1ProjectionName.c_str(),
4217
364
                                               "Mercator_1SP") &&
4218
0
        projectionGetParameter(projCRSNode, "center_latitude").empty()) {
4219
4220
        // Hack for https://trac.osgeo.org/gdal/ticket/3026
4221
0
        std::string lat0(
4222
0
            projectionGetParameter(projCRSNode, "latitude_of_origin"));
4223
0
        if (!lat0.empty() && lat0 != "0" && lat0 != "0.0") {
4224
0
            wkt1ProjectionName = "Mercator_2SP";
4225
0
            gdal_3026_hack = true;
4226
0
        } else {
4227
            // The latitude of origin, which should always be zero, is
4228
            // missing
4229
            // in GDAL WKT1, but provisionned in the EPSG Mercator_1SP
4230
            // definition,
4231
            // so add it manually.
4232
0
            PropertyMap propertiesParameter;
4233
0
            propertiesParameter.set(IdentifiedObject::NAME_KEY,
4234
0
                                    "Latitude of natural origin");
4235
0
            propertiesParameter.set(Identifier::CODE_KEY, 8801);
4236
0
            propertiesParameter.set(Identifier::CODESPACE_KEY,
4237
0
                                    Identifier::EPSG);
4238
0
            parameters.push_back(
4239
0
                OperationParameter::create(propertiesParameter));
4240
0
            values.push_back(
4241
0
                ParameterValue::create(Measure(0, UnitOfMeasure::DEGREE)));
4242
0
        }
4243
4244
364
    } else if (metadata::Identifier::isEquivalentName(
4245
364
                   wkt1ProjectionName.c_str(), "Polar_Stereographic")) {
4246
90
        std::map<std::string, Measure> mapParameters;
4247
2.17k
        for (const auto &childNode : projCRSNode->GP()->children()) {
4248
2.17k
            const auto &childNodeChildren = childNode->GP()->children();
4249
2.17k
            if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER) &&
4250
781
                childNodeChildren.size() == 2) {
4251
716
                const std::string wkt1ParameterName(
4252
716
                    stripQuotes(childNodeChildren[0]));
4253
716
                try {
4254
716
                    double val = asDouble(childNodeChildren[1]);
4255
716
                    auto unit = guessUnitForParameter(wkt1ParameterName,
4256
716
                                                      defaultLinearUnit,
4257
716
                                                      defaultAngularUnit);
4258
716
                    mapParameters.insert(std::pair<std::string, Measure>(
4259
716
                        tolower(wkt1ParameterName), Measure(val, unit)));
4260
716
                } catch (const std::exception &) {
4261
45
                }
4262
716
            }
4263
2.17k
        }
4264
4265
90
        Measure latitudeOfOrigin = mapParameters["latitude_of_origin"];
4266
90
        Measure centralMeridian = mapParameters["central_meridian"];
4267
90
        Measure scaleFactorFromMap = mapParameters["scale_factor"];
4268
90
        Measure scaleFactor((scaleFactorFromMap.unit() == UnitOfMeasure::NONE)
4269
90
                                ? Measure(1.0, UnitOfMeasure::SCALE_UNITY)
4270
90
                                : scaleFactorFromMap);
4271
90
        Measure falseEasting = mapParameters["false_easting"];
4272
90
        Measure falseNorthing = mapParameters["false_northing"];
4273
90
        if (latitudeOfOrigin.unit() != UnitOfMeasure::NONE &&
4274
0
            scaleFactor.getSIValue() == 1.0) {
4275
0
            return Conversion::createPolarStereographicVariantB(
4276
0
                PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
4277
0
                Angle(latitudeOfOrigin.value(), latitudeOfOrigin.unit()),
4278
0
                Angle(centralMeridian.value(), centralMeridian.unit()),
4279
0
                Length(falseEasting.value(), falseEasting.unit()),
4280
0
                Length(falseNorthing.value(), falseNorthing.unit()));
4281
0
        }
4282
4283
90
        if (latitudeOfOrigin.unit() != UnitOfMeasure::NONE &&
4284
0
            std::fabs(std::fabs(latitudeOfOrigin.convertToUnit(
4285
0
                          UnitOfMeasure::DEGREE)) -
4286
0
                      90.0) < 1e-10) {
4287
0
            return Conversion::createPolarStereographicVariantA(
4288
0
                PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
4289
0
                Angle(latitudeOfOrigin.value(), latitudeOfOrigin.unit()),
4290
0
                Angle(centralMeridian.value(), centralMeridian.unit()),
4291
0
                Scale(scaleFactor.value(), scaleFactor.unit()),
4292
0
                Length(falseEasting.value(), falseEasting.unit()),
4293
0
                Length(falseNorthing.value(), falseNorthing.unit()));
4294
0
        }
4295
4296
90
        tryToIdentifyWKT1Method = false;
4297
        // Import GDAL PROJ4 extension nodes
4298
274
    } else if (extensionChildren.size() == 2 &&
4299
55
               ci_equal(stripQuotes(extensionChildren[0]), "PROJ4")) {
4300
52
        std::string projString = stripQuotes(extensionChildren[1]);
4301
52
        if (starts_with(projString, "+proj=")) {
4302
45
            if (projString.find(" +type=crs") == std::string::npos) {
4303
42
                projString += " +type=crs";
4304
42
            }
4305
45
            try {
4306
45
                auto projObj =
4307
45
                    PROJStringParser().createFromPROJString(projString);
4308
45
                auto projObjCrs =
4309
45
                    nn_dynamic_pointer_cast<ProjectedCRS>(projObj);
4310
45
                if (projObjCrs) {
4311
0
                    return projObjCrs->derivingConversion();
4312
0
                }
4313
45
            } catch (const io::ParsingException &) {
4314
42
            }
4315
45
        }
4316
52
    }
4317
4318
364
    std::string projectionName(std::move(wkt1ProjectionName));
4319
364
    const MethodMapping *mapping =
4320
364
        tryToIdentifyWKT1Method ? getMappingFromWKT1(projectionName) : nullptr;
4321
4322
364
    if (!mapping) {
4323
        // Sometimes non-WKT1:ESRI looking WKT can actually use WKT1:ESRI
4324
        // projection definitions
4325
266
        std::map<std::string, std::string, ci_less_struct> mapParamNameToValue;
4326
266
        const auto esriMapping =
4327
266
            getESRIMapping(projCRSNode, projectionNode, mapParamNameToValue);
4328
266
        if (esriMapping != nullptr) {
4329
9
            return buildProjectionFromESRI(
4330
9
                baseGeodCRS, projCRSNode, projectionNode, defaultLinearUnit,
4331
9
                defaultAngularUnit, esriMapping, mapParamNameToValue);
4332
9
        }
4333
266
    }
4334
4335
355
    if (mapping) {
4336
98
        mapping = selectSphericalOrEllipsoidal(mapping, baseGeodCRS);
4337
257
    } else if (metadata::Identifier::isEquivalentName(
4338
257
                   projectionName.c_str(), "Lambert Conformal Conic")) {
4339
        // Lambert Conformal Conic or Lambert_Conformal_Conic are respectively
4340
        // used by Oracle WKT and Trimble for either LCC 1SP or 2SP, so we
4341
        // have to look at parameters to figure out the variant.
4342
25
        bool found2ndStdParallel = false;
4343
25
        bool foundScaleFactor = false;
4344
208
        for (const auto &childNode : projCRSNode->GP()->children()) {
4345
208
            if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
4346
47
                const auto &childNodeChildren = childNode->GP()->children();
4347
47
                if (childNodeChildren.size() < 2) {
4348
3
                    ThrowNotEnoughChildren(WKTConstants::PARAMETER);
4349
3
                }
4350
44
                const std::string wkt1ParameterName(
4351
44
                    stripQuotes(childNodeChildren[0]));
4352
44
                if (metadata::Identifier::isEquivalentName(
4353
44
                        wkt1ParameterName.c_str(), WKT1_STANDARD_PARALLEL_2)) {
4354
5
                    found2ndStdParallel = true;
4355
39
                } else if (metadata::Identifier::isEquivalentName(
4356
39
                               wkt1ParameterName.c_str(), WKT1_SCALE_FACTOR)) {
4357
0
                    foundScaleFactor = true;
4358
0
                }
4359
44
            }
4360
208
        }
4361
22
        if (found2ndStdParallel && !foundScaleFactor) {
4362
5
            mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP);
4363
17
        } else if (!found2ndStdParallel && foundScaleFactor) {
4364
0
            mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP);
4365
17
        } else if (found2ndStdParallel && foundScaleFactor) {
4366
            // Not sure if that happens
4367
0
            mapping = getMapping(
4368
0
                EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN);
4369
0
        }
4370
22
    }
4371
4372
    // For Krovak, we need to look at axis to decide between the Krovak and
4373
    // Krovak East-North Oriented methods
4374
352
    if (ci_equal(projectionName, "Krovak") &&
4375
73
        projCRSNode->countChildrenOfName(WKTConstants::AXIS) == 2 &&
4376
0
        &buildAxis(projCRSNode->GP()->lookForChild(WKTConstants::AXIS, 0),
4377
0
                   defaultLinearUnit, UnitOfMeasure::Type::LINEAR, false, 1)
4378
0
                ->direction() == &AxisDirection::SOUTH &&
4379
0
        &buildAxis(projCRSNode->GP()->lookForChild(WKTConstants::AXIS, 1),
4380
0
                   defaultLinearUnit, UnitOfMeasure::Type::LINEAR, false, 2)
4381
0
                ->direction() == &AxisDirection::WEST) {
4382
0
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK);
4383
0
    }
4384
4385
352
    PropertyMap propertiesMethod;
4386
352
    if (mapping) {
4387
103
        projectionName = mapping->wkt2_name;
4388
103
        if (mapping->epsg_code != 0) {
4389
97
            propertiesMethod.set(Identifier::CODE_KEY, mapping->epsg_code);
4390
97
            propertiesMethod.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
4391
97
        }
4392
103
    }
4393
352
    propertiesMethod.set(IdentifiedObject::NAME_KEY, projectionName);
4394
4395
352
    std::vector<bool> foundParameters;
4396
352
    if (mapping) {
4397
103
        size_t countParams = 0;
4398
773
        while (mapping->params[countParams] != nullptr) {
4399
670
            ++countParams;
4400
670
        }
4401
103
        foundParameters.resize(countParams);
4402
103
    }
4403
4404
3.11k
    for (const auto &childNode : projCRSNode->GP()->children()) {
4405
3.11k
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
4406
1.10k
            const auto &childNodeChildren = childNode->GP()->children();
4407
1.10k
            if (childNodeChildren.size() < 2) {
4408
53
                ThrowNotEnoughChildren(WKTConstants::PARAMETER);
4409
53
            }
4410
1.04k
            const auto &paramValue = childNodeChildren[1]->GP()->value();
4411
4412
1.04k
            PropertyMap propertiesParameter;
4413
1.04k
            const std::string wkt1ParameterName(
4414
1.04k
                stripQuotes(childNodeChildren[0]));
4415
1.04k
            std::string parameterName(wkt1ParameterName);
4416
1.04k
            if (gdal_3026_hack) {
4417
0
                if (ci_equal(parameterName, "latitude_of_origin")) {
4418
0
                    parameterName = "standard_parallel_1";
4419
0
                } else if (ci_equal(parameterName, "scale_factor") &&
4420
0
                           paramValue == "1") {
4421
0
                    continue;
4422
0
                }
4423
0
            }
4424
1.04k
            auto *paramMapping =
4425
1.04k
                mapping ? getMappingFromWKT1(mapping, parameterName) : nullptr;
4426
1.04k
            if (mapping &&
4427
374
                mapping->epsg_code == EPSG_CODE_METHOD_MERCATOR_VARIANT_B &&
4428
0
                ci_equal(parameterName, "latitude_of_origin")) {
4429
                // Some illegal formulations of Mercator_2SP have a unexpected
4430
                // latitude_of_origin parameter. We accept it on import, but
4431
                // do not accept it when exporting to PROJ string, unless it is
4432
                // zero.
4433
                // No need to try to update foundParameters[] as this is a
4434
                // unexpected one.
4435
0
                parameterName = EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN;
4436
0
                propertiesParameter.set(
4437
0
                    Identifier::CODE_KEY,
4438
0
                    EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN);
4439
0
                propertiesParameter.set(Identifier::CODESPACE_KEY,
4440
0
                                        Identifier::EPSG);
4441
1.04k
            } else if (mapping && paramMapping) {
4442
15
                for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) {
4443
15
                    if (mapping->params[idx] == paramMapping) {
4444
9
                        foundParameters[idx] = true;
4445
9
                        break;
4446
9
                    }
4447
15
                }
4448
9
                parameterName = paramMapping->wkt2_name;
4449
9
                if (paramMapping->epsg_code != 0) {
4450
9
                    propertiesParameter.set(Identifier::CODE_KEY,
4451
9
                                            paramMapping->epsg_code);
4452
9
                    propertiesParameter.set(Identifier::CODESPACE_KEY,
4453
9
                                            Identifier::EPSG);
4454
9
                }
4455
9
            }
4456
1.04k
            propertiesParameter.set(IdentifiedObject::NAME_KEY, parameterName);
4457
1.04k
            parameters.push_back(
4458
1.04k
                OperationParameter::create(propertiesParameter));
4459
1.04k
            try {
4460
1.04k
                double val = io::asDouble(paramValue);
4461
1.04k
                auto unit = guessUnitForParameter(
4462
1.04k
                    wkt1ParameterName, defaultLinearUnit, defaultAngularUnit);
4463
1.04k
                values.push_back(ParameterValue::create(Measure(val, unit)));
4464
1.04k
            } catch (const std::exception &) {
4465
131
                throw ParsingException(
4466
131
                    concat("unhandled parameter value type : ", paramValue));
4467
131
            }
4468
1.04k
        }
4469
3.11k
    }
4470
4471
    // Add back important parameters that should normally be present, but
4472
    // are sometimes missing. Currently we only deal with Scale factor at
4473
    // natural origin. This is to avoid a default value of 0 to slip in later.
4474
    // But such WKT should be considered invalid.
4475
168
    if (mapping) {
4476
238
        for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) {
4477
204
            if (!foundParameters[idx] &&
4478
204
                mapping->params[idx]->epsg_code ==
4479
204
                    EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN) {
4480
4481
15
                emitRecoverableWarning(
4482
15
                    "The WKT string lacks a value "
4483
15
                    "for " EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN
4484
15
                    ". Default it to 1.");
4485
4486
15
                PropertyMap propertiesParameter;
4487
15
                propertiesParameter.set(
4488
15
                    Identifier::CODE_KEY,
4489
15
                    EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN);
4490
15
                propertiesParameter.set(Identifier::CODESPACE_KEY,
4491
15
                                        Identifier::EPSG);
4492
15
                propertiesParameter.set(
4493
15
                    IdentifiedObject::NAME_KEY,
4494
15
                    EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN);
4495
15
                parameters.push_back(
4496
15
                    OperationParameter::create(propertiesParameter));
4497
15
                values.push_back(ParameterValue::create(
4498
15
                    Measure(1.0, UnitOfMeasure::SCALE_UNITY)));
4499
15
            }
4500
204
        }
4501
34
    }
4502
4503
168
    if (mapping && (mapping->epsg_code ==
4504
34
                        EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A ||
4505
28
                    mapping->epsg_code ==
4506
28
                        EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B)) {
4507
        // Special case when importing some GDAL WKT of Hotine Oblique Mercator
4508
        // that have a Azimuth parameter but lacks the Rectified Grid Angle.
4509
        // We have code in the exportToPROJString() to deal with that situation,
4510
        // but also adds the rectified grid angle from the azimuth on import.
4511
6
        bool foundAngleRecifiedToSkewGrid = false;
4512
6
        bool foundAzimuth = false;
4513
48
        for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) {
4514
42
            if (foundParameters[idx] &&
4515
0
                mapping->params[idx]->epsg_code ==
4516
0
                    EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID) {
4517
0
                foundAngleRecifiedToSkewGrid = true;
4518
42
            } else if (foundParameters[idx] &&
4519
0
                       mapping->params[idx]->epsg_code ==
4520
0
                           EPSG_CODE_PARAMETER_AZIMUTH_PROJECTION_CENTRE) {
4521
0
                foundAzimuth = true;
4522
0
            }
4523
42
        }
4524
6
        if (!foundAngleRecifiedToSkewGrid && foundAzimuth) {
4525
0
            for (size_t idx = 0; idx < parameters.size(); ++idx) {
4526
0
                if (parameters[idx]->getEPSGCode() ==
4527
0
                    EPSG_CODE_PARAMETER_AZIMUTH_PROJECTION_CENTRE) {
4528
0
                    PropertyMap propertiesParameter;
4529
0
                    propertiesParameter.set(
4530
0
                        Identifier::CODE_KEY,
4531
0
                        EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID);
4532
0
                    propertiesParameter.set(Identifier::CODESPACE_KEY,
4533
0
                                            Identifier::EPSG);
4534
0
                    propertiesParameter.set(
4535
0
                        IdentifiedObject::NAME_KEY,
4536
0
                        EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID);
4537
0
                    parameters.push_back(
4538
0
                        OperationParameter::create(propertiesParameter));
4539
0
                    values.push_back(values[idx]);
4540
0
                }
4541
0
            }
4542
0
        }
4543
6
    }
4544
4545
168
    return Conversion::create(
4546
168
               PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
4547
168
               propertiesMethod, parameters, values)
4548
168
        ->identify();
4549
352
}
4550
4551
// ---------------------------------------------------------------------------
4552
4553
static ProjectedCRSNNPtr createPseudoMercator(const PropertyMap &props,
4554
0
                                              const cs::CartesianCSNNPtr &cs) {
4555
0
    auto conversion = Conversion::createPopularVisualisationPseudoMercator(
4556
0
        PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(0),
4557
0
        Angle(0), Length(0), Length(0));
4558
0
    return ProjectedCRS::create(props, GeographicCRS::EPSG_4326, conversion,
4559
0
                                cs);
4560
0
}
4561
4562
// ---------------------------------------------------------------------------
4563
4564
ProjectedCRSNNPtr
4565
823
WKTParser::Private::buildProjectedCRS(const WKTNodeNNPtr &node) {
4566
4567
823
    const auto *nodeP = node->GP();
4568
823
    auto &conversionNode = nodeP->lookForChild(WKTConstants::CONVERSION);
4569
823
    auto &projectionNode = nodeP->lookForChild(WKTConstants::PROJECTION);
4570
823
    if (isNull(conversionNode) && isNull(projectionNode)) {
4571
62
        ThrowMissing(WKTConstants::CONVERSION);
4572
62
    }
4573
4574
761
    auto &baseGeodCRSNode =
4575
761
        nodeP->lookForChild(WKTConstants::BASEGEODCRS,
4576
761
                            WKTConstants::BASEGEOGCRS, WKTConstants::GEOGCS);
4577
761
    if (isNull(baseGeodCRSNode)) {
4578
5
        throw ParsingException(
4579
5
            "Missing BASEGEODCRS / BASEGEOGCRS / GEOGCS node");
4580
5
    }
4581
756
    auto baseGeodCRS = buildGeodeticCRS(baseGeodCRSNode);
4582
4583
756
    auto props = buildProperties(node);
4584
4585
756
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
4586
756
    const auto &nodeValue = nodeP->value();
4587
756
    if (isNull(csNode) && !ci_equal(nodeValue, WKTConstants::PROJCS) &&
4588
0
        !ci_equal(nodeValue, WKTConstants::BASEPROJCRS)) {
4589
0
        ThrowMissing(WKTConstants::CS_);
4590
0
    }
4591
4592
756
    std::string projCRSName = stripQuotes(nodeP->children()[0]);
4593
4594
756
    auto cs = [this, &projCRSName, &nodeP, &csNode, &node, &nodeValue,
4595
756
               &conversionNode]() -> CoordinateSystemNNPtr {
4596
732
        if (isNull(csNode) && ci_equal(nodeValue, WKTConstants::BASEPROJCRS) &&
4597
0
            !isNull(conversionNode)) {
4598
            // A BASEPROJCRS (as of WKT2 18-010r11) normally lacks an explicit
4599
            // CS[] which cause issues to properly instantiate it. So we first
4600
            // start by trying to identify the BASEPROJCRS by its id or name.
4601
            // And fallback to exploring the conversion parameters to infer the
4602
            // CS AXIS unit from the linear parameter unit... Not fully bullet
4603
            // proof.
4604
0
            if (dbContext_) {
4605
                // Get official name from database if ID is present
4606
0
                auto &idNode = nodeP->lookForChild(WKTConstants::ID);
4607
0
                if (!isNull(idNode)) {
4608
0
                    try {
4609
0
                        auto id = buildId(node, idNode, false, false);
4610
0
                        auto authFactory = AuthorityFactory::create(
4611
0
                            NN_NO_CHECK(dbContext_), *id->codeSpace());
4612
0
                        auto projCRS =
4613
0
                            authFactory->createProjectedCRS(id->code());
4614
0
                        return projCRS->coordinateSystem();
4615
0
                    } catch (const std::exception &) {
4616
0
                    }
4617
0
                }
4618
4619
0
                auto authFactory = AuthorityFactory::create(
4620
0
                    NN_NO_CHECK(dbContext_), std::string());
4621
0
                auto res = authFactory->createObjectsFromName(
4622
0
                    projCRSName, {AuthorityFactory::ObjectType::PROJECTED_CRS},
4623
0
                    false, 2);
4624
0
                if (res.size() == 1) {
4625
0
                    auto projCRS =
4626
0
                        dynamic_cast<const ProjectedCRS *>(res.front().get());
4627
0
                    if (projCRS) {
4628
0
                        return projCRS->coordinateSystem();
4629
0
                    }
4630
0
                }
4631
0
            }
4632
4633
0
            auto conv = buildConversion(conversionNode, UnitOfMeasure::METRE,
4634
0
                                        UnitOfMeasure::DEGREE);
4635
0
            UnitOfMeasure linearUOM = UnitOfMeasure::NONE;
4636
0
            for (const auto &genOpParamvalue : conv->parameterValues()) {
4637
0
                auto opParamvalue =
4638
0
                    dynamic_cast<const operation::OperationParameterValue *>(
4639
0
                        genOpParamvalue.get());
4640
0
                if (opParamvalue) {
4641
0
                    const auto &parameterValue = opParamvalue->parameterValue();
4642
0
                    if (parameterValue->type() ==
4643
0
                        operation::ParameterValue::Type::MEASURE) {
4644
0
                        const auto &measure = parameterValue->value();
4645
0
                        const auto &unit = measure.unit();
4646
0
                        if (unit.type() == UnitOfMeasure::Type::LINEAR) {
4647
0
                            if (linearUOM == UnitOfMeasure::NONE) {
4648
0
                                linearUOM = unit;
4649
0
                            } else if (linearUOM != unit) {
4650
0
                                linearUOM = UnitOfMeasure::NONE;
4651
0
                                break;
4652
0
                            }
4653
0
                        }
4654
0
                    }
4655
0
                }
4656
0
            }
4657
0
            if (linearUOM != UnitOfMeasure::NONE) {
4658
0
                return CartesianCS::createEastingNorthing(linearUOM);
4659
0
            }
4660
0
        }
4661
732
        return buildCS(csNode, node, UnitOfMeasure::NONE);
4662
732
    }();
4663
756
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
4664
4665
756
    if (dbContext_ && ((!esriStyle_ && projCRSName == "ETRF2000-PL / CS92" &&
4666
0
                        baseGeodCRS->nameStr() == "ETRF2000-PL") ||
4667
649
                       (esriStyle_ && projCRSName == "ETRF2000-PL_CS92" &&
4668
0
                        (baseGeodCRS->nameStr() == "GCS_ETRF2000-PL" ||
4669
0
                         baseGeodCRS->nameStr() == "ETRF2000-PL")))) {
4670
        // Oddity: "ETRF2000-PL / CS92" (EPSG:2180) has switched back to
4671
        // "ETRS89 / PL-1992"
4672
0
        auto authFactoryEPSG =
4673
0
            io::AuthorityFactory::create(NN_NO_CHECK(dbContext_), "EPSG");
4674
0
        auto newProjCRS = authFactoryEPSG->createProjectedCRS("2180");
4675
0
        props.set(IdentifiedObject::NAME_KEY, newProjCRS->nameStr());
4676
0
        baseGeodCRS = newProjCRS->baseCRS();
4677
0
    }
4678
    // In EPSG v12.025, Norway projected systems based on ETRS89 (EPSG:4258)
4679
    // have switched to use ETRS89-NOR [EUREF89] (EPSG:10875).
4680
    // Similarly for other ETRS89-like datums in later releases
4681
756
    else if (dbContext_ &&
4682
649
             (((starts_with(projCRSName, "ETRS89 / ") ||
4683
649
                (esriStyle_ && starts_with(projCRSName, "ETRS_1989_"))) &&
4684
0
               baseGeodCRS->nameStr() == "ETRS89") ||
4685
649
              starts_with(projCRSName, "ETRF2000-PL /")) &&
4686
0
             util::isOfExactType<GeographicCRS>(*(baseGeodCRS.get())) &&
4687
0
             baseGeodCRS->coordinateSystem()->axisList().size() == 2) {
4688
0
        auto authFactoryEPSG =
4689
0
            io::AuthorityFactory::create(NN_NO_CHECK(dbContext_), "EPSG");
4690
0
        const auto objCandidates = authFactoryEPSG->createObjectsFromNameEx(
4691
0
            projCRSName, {io::AuthorityFactory::ObjectType::PROJECTED_CRS},
4692
0
            false, // approximateMatch
4693
0
            0,     // limit
4694
0
            true   // useAliases
4695
0
        );
4696
0
        for (const auto &[obj, name] : objCandidates) {
4697
0
            if (name == projCRSName) {
4698
0
                auto candidateProj =
4699
0
                    dynamic_cast<const crs::ProjectedCRS *>(obj.get());
4700
0
                if (candidateProj &&
4701
0
                    candidateProj->baseCRS()->nameStr() !=
4702
0
                        baseGeodCRS->nameStr() &&
4703
0
                    candidateProj->baseCRS()->_isEquivalentTo(
4704
0
                        baseGeodCRS.get(),
4705
0
                        util::IComparable::Criterion::
4706
0
                            EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS,
4707
0
                        dbContext_)) {
4708
0
                    props.set(IdentifiedObject::NAME_KEY,
4709
0
                              candidateProj->nameStr());
4710
0
                    baseGeodCRS = candidateProj->baseCRS();
4711
0
                    break;
4712
0
                }
4713
0
            }
4714
0
        }
4715
0
    }
4716
4717
756
    if (esriStyle_ && dbContext_) {
4718
350
        if (cartesianCS) {
4719
350
            std::string outTableName;
4720
350
            std::string authNameFromAlias;
4721
350
            std::string codeFromAlias;
4722
350
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
4723
350
                                                        std::string());
4724
350
            auto officialName = authFactory->getOfficialNameFromAlias(
4725
350
                projCRSName, "projected_crs", "ESRI", false, outTableName,
4726
350
                authNameFromAlias, codeFromAlias);
4727
350
            if (!officialName.empty()) {
4728
                // Special case for https://github.com/OSGeo/PROJ/issues/2086
4729
                // The name of the CRS to identify is
4730
                // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501
4731
                // whereas it should be
4732
                // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501_Feet
4733
0
                constexpr double US_FOOT_CONV_FACTOR = 12.0 / 39.37;
4734
0
                if (projCRSName.find("_FIPS_") != std::string::npos &&
4735
0
                    projCRSName.find("_Feet") == std::string::npos &&
4736
0
                    std::fabs(
4737
0
                        cartesianCS->axisList()[0]->unit().conversionToSI() -
4738
0
                        US_FOOT_CONV_FACTOR) < 1e-10 * US_FOOT_CONV_FACTOR) {
4739
0
                    auto officialNameFromFeet =
4740
0
                        authFactory->getOfficialNameFromAlias(
4741
0
                            projCRSName + "_Feet", "projected_crs", "ESRI",
4742
0
                            false, outTableName, authNameFromAlias,
4743
0
                            codeFromAlias);
4744
0
                    if (!officialNameFromFeet.empty()) {
4745
0
                        officialName = std::move(officialNameFromFeet);
4746
0
                    }
4747
0
                }
4748
4749
0
                projCRSName = officialName;
4750
0
                props.set(IdentifiedObject::NAME_KEY, officialName);
4751
0
            }
4752
350
        }
4753
350
    }
4754
4755
756
    if (isNull(conversionNode) && hasWebMercPROJ4String(node, projectionNode) &&
4756
0
        cartesianCS) {
4757
0
        toWGS84Parameters_.clear();
4758
0
        return createPseudoMercator(props, NN_NO_CHECK(cartesianCS));
4759
0
    }
4760
4761
    // WGS_84_Pseudo_Mercator: Particular case for corrupted ESRI WKT generated
4762
    // by older GDAL versions
4763
    // https://trac.osgeo.org/gdal/changeset/30732
4764
    // WGS_1984_Web_Mercator: deprecated ESRI:102113
4765
756
    if (cartesianCS && (metadata::Identifier::isEquivalentName(
4766
726
                            projCRSName.c_str(), "WGS_84_Pseudo_Mercator") ||
4767
726
                        metadata::Identifier::isEquivalentName(
4768
726
                            projCRSName.c_str(), "WGS_1984_Web_Mercator"))) {
4769
0
        toWGS84Parameters_.clear();
4770
0
        return createPseudoMercator(props, NN_NO_CHECK(cartesianCS));
4771
0
    }
4772
4773
    // For WKT2, if there is no explicit parameter unit, use metre for linear
4774
    // units and degree for angular units
4775
756
    const UnitOfMeasure linearUnit(
4776
756
        !isNull(conversionNode)
4777
756
            ? UnitOfMeasure::METRE
4778
756
            : buildUnitInSubNode(node, UnitOfMeasure::Type::LINEAR));
4779
756
    const auto &angularUnit =
4780
756
        !isNull(conversionNode)
4781
756
            ? UnitOfMeasure::DEGREE
4782
756
            : baseGeodCRS->coordinateSystem()->axisList()[0]->unit();
4783
4784
756
    auto conversion =
4785
756
        !isNull(conversionNode)
4786
756
            ? buildConversion(conversionNode, linearUnit, angularUnit)
4787
756
            : buildProjection(baseGeodCRS, node, projectionNode, linearUnit,
4788
738
                              angularUnit);
4789
4790
    // No explicit AXIS node ? (WKT1)
4791
756
    if (isNull(nodeP->lookForChild(WKTConstants::AXIS))) {
4792
522
        props.set("IMPLICIT_CS", true);
4793
522
    }
4794
4795
756
    if (isNull(csNode) && node->countChildrenOfName(WKTConstants::AXIS) == 0) {
4796
4797
522
        const auto methodCode = conversion->method()->getEPSGCode();
4798
        // Krovak south oriented ?
4799
522
        if (methodCode == EPSG_CODE_METHOD_KROVAK) {
4800
13
            cartesianCS =
4801
13
                CartesianCS::create(
4802
13
                    PropertyMap(),
4803
13
                    CoordinateSystemAxis::create(
4804
13
                        util::PropertyMap().set(IdentifiedObject::NAME_KEY,
4805
13
                                                AxisName::Southing),
4806
13
                        emptyString, AxisDirection::SOUTH, linearUnit),
4807
13
                    CoordinateSystemAxis::create(
4808
13
                        util::PropertyMap().set(IdentifiedObject::NAME_KEY,
4809
13
                                                AxisName::Westing),
4810
13
                        emptyString, AxisDirection::WEST, linearUnit))
4811
13
                    .as_nullable();
4812
509
        } else if (methodCode ==
4813
509
                       EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A ||
4814
495
                   methodCode ==
4815
495
                       EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA) {
4816
            // It is likely that the ESRI definition of EPSG:32661 (UPS North) &
4817
            // EPSG:32761 (UPS South) uses the easting-northing order, instead
4818
            // of the EPSG northing-easting order.
4819
            // Same for WKT1_GDAL
4820
19
            const double lat0 = conversion->parameterValueNumeric(
4821
19
                EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN,
4822
19
                common::UnitOfMeasure::DEGREE);
4823
19
            if (std::fabs(lat0 - 90) < 1e-10) {
4824
10
                cartesianCS =
4825
10
                    CartesianCS::createNorthPoleEastingSouthNorthingSouth(
4826
10
                        linearUnit)
4827
10
                        .as_nullable();
4828
10
            } else if (std::fabs(lat0 - -90) < 1e-10) {
4829
9
                cartesianCS =
4830
9
                    CartesianCS::createSouthPoleEastingNorthNorthingNorth(
4831
9
                        linearUnit)
4832
9
                        .as_nullable();
4833
9
            }
4834
490
        } else if (methodCode ==
4835
490
                   EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B) {
4836
3
            const double lat_ts = conversion->parameterValueNumeric(
4837
3
                EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL,
4838
3
                common::UnitOfMeasure::DEGREE);
4839
3
            if (lat_ts > 0) {
4840
3
                cartesianCS =
4841
3
                    CartesianCS::createNorthPoleEastingSouthNorthingSouth(
4842
3
                        linearUnit)
4843
3
                        .as_nullable();
4844
3
            } else if (lat_ts < 0) {
4845
0
                cartesianCS =
4846
0
                    CartesianCS::createSouthPoleEastingNorthNorthingNorth(
4847
0
                        linearUnit)
4848
0
                        .as_nullable();
4849
0
            }
4850
487
        } else if (methodCode ==
4851
487
                   EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED) {
4852
0
            cartesianCS =
4853
0
                CartesianCS::createWestingSouthing(linearUnit).as_nullable();
4854
0
        }
4855
522
    }
4856
756
    if (!cartesianCS) {
4857
0
        ThrowNotExpectedCSType(CartesianCS::WKT2_TYPE);
4858
0
    }
4859
4860
756
    if (cartesianCS->axisList().size() == 3 &&
4861
0
        baseGeodCRS->coordinateSystem()->axisList().size() == 2) {
4862
0
        baseGeodCRS = NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>(
4863
0
            baseGeodCRS->promoteTo3D(std::string(), dbContext_)));
4864
0
    }
4865
4866
756
    addExtensionProj4ToProp(nodeP, props);
4867
4868
756
    return ProjectedCRS::create(props, baseGeodCRS, conversion,
4869
756
                                NN_NO_CHECK(cartesianCS));
4870
756
}
4871
4872
// ---------------------------------------------------------------------------
4873
4874
void WKTParser::Private::parseDynamic(const WKTNodeNNPtr &dynamicNode,
4875
                                      double &frameReferenceEpoch,
4876
20
                                      util::optional<std::string> &modelName) {
4877
20
    auto &frameEpochNode = dynamicNode->lookForChild(WKTConstants::FRAMEEPOCH);
4878
20
    const auto &frameEpochChildren = frameEpochNode->GP()->children();
4879
20
    if (frameEpochChildren.empty()) {
4880
4
        ThrowMissing(WKTConstants::FRAMEEPOCH);
4881
4
    }
4882
16
    try {
4883
16
        frameReferenceEpoch = asDouble(frameEpochChildren[0]);
4884
16
    } catch (const std::exception &) {
4885
3
        throw ParsingException("Invalid FRAMEEPOCH node");
4886
3
    }
4887
13
    auto &modelNode = dynamicNode->GP()->lookForChild(
4888
13
        WKTConstants::MODEL, WKTConstants::VELOCITYGRID);
4889
13
    const auto &modelChildren = modelNode->GP()->children();
4890
13
    if (modelChildren.size() == 1) {
4891
0
        modelName = stripQuotes(modelChildren[0]);
4892
0
    }
4893
13
}
4894
4895
// ---------------------------------------------------------------------------
4896
4897
VerticalReferenceFrameNNPtr WKTParser::Private::buildVerticalReferenceFrame(
4898
803
    const WKTNodeNNPtr &node, const WKTNodeNNPtr &dynamicNode) {
4899
4900
803
    if (!isNull(dynamicNode)) {
4901
0
        double frameReferenceEpoch = 0.0;
4902
0
        util::optional<std::string> modelName;
4903
0
        parseDynamic(dynamicNode, frameReferenceEpoch, modelName);
4904
0
        return DynamicVerticalReferenceFrame::create(
4905
0
            buildProperties(node), getAnchor(node),
4906
0
            optional<RealizationMethod>(),
4907
0
            common::Measure(frameReferenceEpoch, common::UnitOfMeasure::YEAR),
4908
0
            modelName);
4909
0
    }
4910
4911
    // WKT1 VERT_DATUM has a datum type after the datum name
4912
803
    const auto *nodeP = node->GP();
4913
803
    const std::string &name(nodeP->value());
4914
803
    auto &props = buildProperties(node);
4915
803
    const auto &children = nodeP->children();
4916
4917
803
    if (esriStyle_ && dbContext_ && !children.empty()) {
4918
8
        std::string outTableName;
4919
8
        std::string authNameFromAlias;
4920
8
        std::string codeFromAlias;
4921
8
        auto authFactory =
4922
8
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
4923
8
        const std::string datumName = stripQuotes(children[0]);
4924
8
        auto officialName = authFactory->getOfficialNameFromAlias(
4925
8
            datumName, "vertical_datum", "ESRI", false, outTableName,
4926
8
            authNameFromAlias, codeFromAlias);
4927
8
        if (!officialName.empty()) {
4928
0
            props.set(IdentifiedObject::NAME_KEY, officialName);
4929
0
        }
4930
8
    }
4931
4932
803
    if (ci_equal(name, WKTConstants::VERT_DATUM)) {
4933
40
        if (children.size() >= 2) {
4934
27
            props.set("VERT_DATUM_TYPE", children[1]->GP()->value());
4935
27
        }
4936
40
    }
4937
4938
803
    return VerticalReferenceFrame::create(props, getAnchor(node),
4939
803
                                          getAnchorEpoch(node));
4940
803
}
4941
4942
// ---------------------------------------------------------------------------
4943
4944
TemporalDatumNNPtr
4945
19
WKTParser::Private::buildTemporalDatum(const WKTNodeNNPtr &node) {
4946
19
    const auto *nodeP = node->GP();
4947
19
    auto &calendarNode = nodeP->lookForChild(WKTConstants::CALENDAR);
4948
19
    std::string calendar = TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN;
4949
19
    const auto &calendarChildren = calendarNode->GP()->children();
4950
19
    if (calendarChildren.size() == 1) {
4951
0
        calendar = stripQuotes(calendarChildren[0]);
4952
0
    }
4953
4954
19
    auto &timeOriginNode = nodeP->lookForChild(WKTConstants::TIMEORIGIN);
4955
19
    std::string originStr;
4956
19
    const auto &timeOriginNodeChildren = timeOriginNode->GP()->children();
4957
19
    if (timeOriginNodeChildren.size() == 1) {
4958
3
        originStr = stripQuotes(timeOriginNodeChildren[0]);
4959
3
    }
4960
19
    auto origin = DateTime::create(originStr);
4961
19
    return TemporalDatum::create(buildProperties(node), origin, calendar);
4962
19
}
4963
4964
// ---------------------------------------------------------------------------
4965
4966
EngineeringDatumNNPtr
4967
6
WKTParser::Private::buildEngineeringDatum(const WKTNodeNNPtr &node) {
4968
6
    return EngineeringDatum::create(buildProperties(node), getAnchor(node));
4969
6
}
4970
4971
// ---------------------------------------------------------------------------
4972
4973
ParametricDatumNNPtr
4974
5
WKTParser::Private::buildParametricDatum(const WKTNodeNNPtr &node) {
4975
5
    return ParametricDatum::create(buildProperties(node), getAnchor(node));
4976
5
}
4977
4978
// ---------------------------------------------------------------------------
4979
4980
static CRSNNPtr
4981
createBoundCRSSourceTransformationCRS(const crs::CRSPtr &sourceCRS,
4982
17
                                      const crs::CRSPtr &targetCRS) {
4983
17
    CRSPtr sourceTransformationCRS;
4984
17
    if (dynamic_cast<GeographicCRS *>(targetCRS.get())) {
4985
17
        GeographicCRSPtr sourceGeographicCRS =
4986
17
            sourceCRS->extractGeographicCRS();
4987
17
        sourceTransformationCRS = sourceGeographicCRS;
4988
17
        if (sourceGeographicCRS) {
4989
0
            const auto &sourceDatum = sourceGeographicCRS->datum();
4990
0
            if (sourceDatum != nullptr && sourceGeographicCRS->primeMeridian()
4991
0
                                                  ->longitude()
4992
0
                                                  .getSIValue() != 0.0) {
4993
0
                sourceTransformationCRS =
4994
0
                    GeographicCRS::create(
4995
0
                        util::PropertyMap().set(
4996
0
                            common::IdentifiedObject::NAME_KEY,
4997
0
                            sourceGeographicCRS->nameStr() +
4998
0
                                " (with Greenwich prime meridian)"),
4999
0
                        datum::GeodeticReferenceFrame::create(
5000
0
                            util::PropertyMap().set(
5001
0
                                common::IdentifiedObject::NAME_KEY,
5002
0
                                sourceDatum->nameStr() +
5003
0
                                    " (with Greenwich prime meridian)"),
5004
0
                            sourceDatum->ellipsoid(),
5005
0
                            util::optional<std::string>(),
5006
0
                            datum::PrimeMeridian::GREENWICH),
5007
0
                        sourceGeographicCRS->coordinateSystem())
5008
0
                        .as_nullable();
5009
0
            }
5010
17
        } else {
5011
17
            auto vertSourceCRS =
5012
17
                std::dynamic_pointer_cast<VerticalCRS>(sourceCRS);
5013
17
            if (!vertSourceCRS) {
5014
0
                throw ParsingException(
5015
0
                    "Cannot find GeographicCRS or VerticalCRS in sourceCRS");
5016
0
            }
5017
17
            const auto &axis = vertSourceCRS->coordinateSystem()->axisList()[0];
5018
17
            if (axis->unit() == common::UnitOfMeasure::METRE &&
5019
10
                &(axis->direction()) == &AxisDirection::UP) {
5020
10
                sourceTransformationCRS = sourceCRS;
5021
10
            } else {
5022
7
                std::string sourceTransformationCRSName(
5023
7
                    vertSourceCRS->nameStr());
5024
7
                if (ends_with(sourceTransformationCRSName, " (ftUS)")) {
5025
0
                    sourceTransformationCRSName.resize(
5026
0
                        sourceTransformationCRSName.size() - strlen(" (ftUS)"));
5027
0
                }
5028
7
                if (ends_with(sourceTransformationCRSName, " depth")) {
5029
0
                    sourceTransformationCRSName.resize(
5030
0
                        sourceTransformationCRSName.size() - strlen(" depth"));
5031
0
                }
5032
7
                if (!ends_with(sourceTransformationCRSName, " height")) {
5033
7
                    sourceTransformationCRSName += " height";
5034
7
                }
5035
7
                sourceTransformationCRS =
5036
7
                    VerticalCRS::create(
5037
7
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
5038
7
                                          sourceTransformationCRSName),
5039
7
                        vertSourceCRS->datum(), vertSourceCRS->datumEnsemble(),
5040
7
                        VerticalCS::createGravityRelatedHeight(
5041
7
                            common::UnitOfMeasure::METRE))
5042
7
                        .as_nullable();
5043
7
            }
5044
17
        }
5045
17
    } else {
5046
0
        sourceTransformationCRS = sourceCRS;
5047
0
    }
5048
17
    return NN_NO_CHECK(sourceTransformationCRS);
5049
17
}
5050
5051
// ---------------------------------------------------------------------------
5052
5053
725
CRSNNPtr WKTParser::Private::buildVerticalCRS(const WKTNodeNNPtr &node) {
5054
725
    const auto *nodeP = node->GP();
5055
725
    const auto &nodeValue = nodeP->value();
5056
725
    auto &vdatumNode =
5057
725
        nodeP->lookForChild(WKTConstants::VDATUM, WKTConstants::VERT_DATUM,
5058
725
                            WKTConstants::VERTICALDATUM, WKTConstants::VRF);
5059
725
    auto &ensembleNode = nodeP->lookForChild(WKTConstants::ENSEMBLE);
5060
    // like in ESRI  VERTCS["WGS_1984",DATUM["D_WGS_1984",
5061
    //               SPHEROID["WGS_1984",6378137.0,298.257223563]],
5062
    //               PARAMETER["Vertical_Shift",0.0],
5063
    //               PARAMETER["Direction",1.0],UNIT["Meter",1.0]
5064
725
    auto &geogDatumNode = ci_equal(nodeValue, WKTConstants::VERTCS)
5065
725
                              ? nodeP->lookForChild(WKTConstants::DATUM)
5066
725
                              : null_node;
5067
725
    if (isNull(vdatumNode) && isNull(geogDatumNode) && isNull(ensembleNode)) {
5068
17
        throw ParsingException("Missing VDATUM or ENSEMBLE node");
5069
17
    }
5070
5071
3.12k
    for (const auto &childNode : nodeP->children()) {
5072
3.12k
        const auto &childNodeChildren = childNode->GP()->children();
5073
3.12k
        if (childNodeChildren.size() == 2 &&
5074
376
            ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER) &&
5075
19
            childNodeChildren[0]->GP()->value() == "\"Vertical_Shift\"") {
5076
0
            esriStyle_ = true;
5077
0
            break;
5078
0
        }
5079
3.12k
    }
5080
5081
708
    auto &dynamicNode = nodeP->lookForChild(WKTConstants::DYNAMIC);
5082
708
    auto vdatum =
5083
708
        !isNull(geogDatumNode)
5084
708
            ? VerticalReferenceFrame::create(
5085
16
                  PropertyMap()
5086
16
                      .set(IdentifiedObject::NAME_KEY,
5087
16
                           buildGeodeticReferenceFrame(geogDatumNode,
5088
16
                                                       PrimeMeridian::GREENWICH,
5089
16
                                                       null_node)
5090
16
                               ->nameStr())
5091
16
                      .set("VERT_DATUM_TYPE", "2002"))
5092
16
                  .as_nullable()
5093
708
        : !isNull(vdatumNode)
5094
692
            ? buildVerticalReferenceFrame(vdatumNode, dynamicNode).as_nullable()
5095
692
            : nullptr;
5096
708
    auto datumEnsemble =
5097
708
        !isNull(ensembleNode)
5098
708
            ? buildDatumEnsemble(ensembleNode, nullptr, false).as_nullable()
5099
708
            : nullptr;
5100
5101
708
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5102
708
    if (isNull(csNode) && !ci_equal(nodeValue, WKTConstants::VERT_CS) &&
5103
645
        !ci_equal(nodeValue, WKTConstants::VERTCS) &&
5104
1
        !ci_equal(nodeValue, WKTConstants::BASEVERTCRS)) {
5105
1
        ThrowMissing(WKTConstants::CS_);
5106
1
    }
5107
707
    auto verticalCS = nn_dynamic_pointer_cast<VerticalCS>(
5108
707
        buildCS(csNode, node, UnitOfMeasure::NONE));
5109
707
    if (!verticalCS) {
5110
0
        ThrowNotExpectedCSType(VerticalCS::WKT2_TYPE);
5111
0
    }
5112
5113
707
    if (vdatum && vdatum->getWKT1DatumType() == "2002" &&
5114
14
        &(verticalCS->axisList()[0]->direction()) == &(AxisDirection::UP)) {
5115
14
        verticalCS =
5116
14
            VerticalCS::create(
5117
14
                util::PropertyMap(),
5118
14
                CoordinateSystemAxis::create(
5119
14
                    util::PropertyMap().set(IdentifiedObject::NAME_KEY,
5120
14
                                            "ellipsoidal height"),
5121
14
                    "h", AxisDirection::UP, verticalCS->axisList()[0]->unit()))
5122
14
                .as_nullable();
5123
14
    }
5124
5125
707
    auto &props = buildProperties(node);
5126
5127
707
    if (esriStyle_ && dbContext_) {
5128
15
        std::string outTableName;
5129
15
        std::string authNameFromAlias;
5130
15
        std::string codeFromAlias;
5131
15
        auto authFactory =
5132
15
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
5133
15
        const std::string vertCRSName = stripQuotes(nodeP->children()[0]);
5134
15
        auto officialName = authFactory->getOfficialNameFromAlias(
5135
15
            vertCRSName, "vertical_crs", "ESRI", false, outTableName,
5136
15
            authNameFromAlias, codeFromAlias);
5137
15
        if (!officialName.empty()) {
5138
0
            props.set(IdentifiedObject::NAME_KEY, officialName);
5139
0
        }
5140
15
    }
5141
5142
    // Deal with Lidar WKT1 VertCRS that embeds geoid model in CRS name,
5143
    // following conventions from
5144
    // https://pubs.usgs.gov/tm/11b4/pdf/tm11-B4.pdf
5145
    // page 9
5146
707
    if (ci_equal(nodeValue, WKTConstants::VERT_CS) ||
5147
641
        ci_equal(nodeValue, WKTConstants::VERTCS)) {
5148
641
        std::string name;
5149
641
        if (props.getStringValue(IdentifiedObject::NAME_KEY, name)) {
5150
641
            std::string navd88GeoidName;
5151
641
            for (const char *prefix :
5152
641
                 {"NAVD88 - ", "NAVD88 via ", "NAVD88 height - ",
5153
2.41k
                  "NAVD88 height (ftUS) - "}) {
5154
2.41k
                if (starts_with(name, prefix)) {
5155
111
                    navd88GeoidName = name.substr(strlen(prefix));
5156
111
                    auto pos = navd88GeoidName.find_first_of(" (");
5157
111
                    if (pos != std::string::npos) {
5158
68
                        navd88GeoidName.resize(pos);
5159
68
                    }
5160
111
                    break;
5161
111
                }
5162
2.41k
            }
5163
5164
            // Deal with vertical CRS names like "Geoid 2012A"
5165
641
            if (navd88GeoidName.empty() && ci_starts_with(name, "Geoid") &&
5166
2
                geogCRSOfCompoundCRS_ &&
5167
0
                starts_with(geogCRSOfCompoundCRS_->nameStr(), "NAD83")) {
5168
                // Remove spaces
5169
0
                navd88GeoidName = replaceAll(name, " ", "");
5170
                // Morph "Geoid 20XX[Y]" to "GeoidXX[Y]"
5171
0
                if (navd88GeoidName.size() >= 9 &&
5172
0
                    ci_starts_with(navd88GeoidName, "Geoid20") &&
5173
0
                    navd88GeoidName[7] >= '0' && navd88GeoidName[7] <= '9' &&
5174
0
                    navd88GeoidName[8] >= '0' && navd88GeoidName[8] <= '9') {
5175
0
                    navd88GeoidName = "Geoid" + navd88GeoidName.substr(7);
5176
0
                }
5177
0
            }
5178
5179
641
            if (!navd88GeoidName.empty()) {
5180
111
                const auto &axis = verticalCS->axisList()[0];
5181
111
                const auto &dir = axis->direction();
5182
111
                if (dir == cs::AxisDirection::UP) {
5183
105
                    if (axis->unit() == common::UnitOfMeasure::METRE) {
5184
87
                        props.set(IdentifiedObject::NAME_KEY, "NAVD88 height");
5185
87
                        props.set(Identifier::CODE_KEY, 5703);
5186
87
                        props.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
5187
87
                    } else if (axis->unit().name() == "US survey foot") {
5188
0
                        props.set(IdentifiedObject::NAME_KEY,
5189
0
                                  "NAVD88 height (ftUS)");
5190
0
                        props.set(Identifier::CODE_KEY, 6360);
5191
0
                        props.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
5192
0
                    }
5193
105
                }
5194
111
                PropertyMap propsModel;
5195
111
                propsModel.set(IdentifiedObject::NAME_KEY,
5196
111
                               toupper(navd88GeoidName));
5197
111
                PropertyMap propsDatum;
5198
111
                propsDatum.set(IdentifiedObject::NAME_KEY,
5199
111
                               "North American Vertical Datum 1988");
5200
111
                propsDatum.set(Identifier::CODE_KEY, 5103);
5201
111
                propsDatum.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
5202
111
                vdatum =
5203
111
                    VerticalReferenceFrame::create(propsDatum).as_nullable();
5204
111
                const auto dummyCRS =
5205
111
                    VerticalCRS::create(PropertyMap(), vdatum, datumEnsemble,
5206
111
                                        NN_NO_CHECK(verticalCS));
5207
111
                const auto model(Transformation::create(
5208
111
                    propsModel, dummyCRS, dummyCRS, nullptr,
5209
111
                    OperationMethod::create(
5210
111
                        PropertyMap(), std::vector<OperationParameterNNPtr>()),
5211
111
                    {}, {}));
5212
111
                props.set("GEOID_MODEL", model);
5213
111
            }
5214
641
        }
5215
641
    }
5216
5217
707
    auto &geoidModelNode = nodeP->lookForChild(WKTConstants::GEOIDMODEL);
5218
707
    if (!isNull(geoidModelNode)) {
5219
49
        ArrayOfBaseObjectNNPtr arrayModels = ArrayOfBaseObject::create();
5220
428
        for (const auto &childNode : nodeP->children()) {
5221
428
            const auto &childNodeChildren = childNode->GP()->children();
5222
428
            if (childNodeChildren.size() >= 1 &&
5223
186
                ci_equal(childNode->GP()->value(), WKTConstants::GEOIDMODEL)) {
5224
101
                auto &propsModel = buildProperties(childNode);
5225
101
                const auto dummyCRS =
5226
101
                    VerticalCRS::create(PropertyMap(), vdatum, datumEnsemble,
5227
101
                                        NN_NO_CHECK(verticalCS));
5228
101
                const auto model(Transformation::create(
5229
101
                    propsModel, dummyCRS, dummyCRS, nullptr,
5230
101
                    OperationMethod::create(
5231
101
                        PropertyMap(), std::vector<OperationParameterNNPtr>()),
5232
101
                    {}, {}));
5233
101
                arrayModels->add(model);
5234
101
            }
5235
428
        }
5236
49
        props.set("GEOID_MODEL", arrayModels);
5237
49
    }
5238
5239
707
    auto crs = nn_static_pointer_cast<CRS>(VerticalCRS::create(
5240
707
        props, vdatum, datumEnsemble, NN_NO_CHECK(verticalCS)));
5241
5242
707
    if (!isNull(vdatumNode)) {
5243
621
        auto &extensionNode = vdatumNode->lookForChild(WKTConstants::EXTENSION);
5244
621
        const auto &extensionChildren = extensionNode->GP()->children();
5245
621
        if (extensionChildren.size() == 2) {
5246
18
            if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4_GRIDS")) {
5247
17
                const auto gridName(stripQuotes(extensionChildren[1]));
5248
                // This is the expansion of EPSG:5703 by old GDAL versions.
5249
                // See
5250
                // https://trac.osgeo.org/metacrs/changeset?reponame=&new=2281%40geotiff%2Ftrunk%2Flibgeotiff%2Fcsv%2Fvertcs.override.csv&old=1893%40geotiff%2Ftrunk%2Flibgeotiff%2Fcsv%2Fvertcs.override.csv
5251
                // It is unlikely that the user really explicitly wants this.
5252
17
                if (gridName != "g2003conus.gtx,g2003alaska.gtx,"
5253
17
                                "g2003h01.gtx,g2003p01.gtx" &&
5254
17
                    gridName != "g2012a_conus.gtx,g2012a_alaska.gtx,"
5255
17
                                "g2012a_guam.gtx,g2012a_hawaii.gtx,"
5256
17
                                "g2012a_puertorico.gtx,g2012a_samoa.gtx") {
5257
17
                    auto geogCRS =
5258
17
                        geogCRSOfCompoundCRS_ &&
5259
0
                                geogCRSOfCompoundCRS_->primeMeridian()
5260
0
                                        ->longitude()
5261
0
                                        .getSIValue() == 0 &&
5262
0
                                geogCRSOfCompoundCRS_->coordinateSystem()
5263
0
                                        ->axisList()[0]
5264
0
                                        ->unit() == UnitOfMeasure::DEGREE
5265
17
                            ? geogCRSOfCompoundCRS_->promoteTo3D(std::string(),
5266
0
                                                                 dbContext_)
5267
17
                            : GeographicCRS::EPSG_4979;
5268
5269
17
                    auto sourceTransformationCRS =
5270
17
                        createBoundCRSSourceTransformationCRS(
5271
17
                            crs.as_nullable(), geogCRS.as_nullable());
5272
17
                    auto transformation = Transformation::
5273
17
                        createGravityRelatedHeightToGeographic3D(
5274
17
                            PropertyMap().set(
5275
17
                                IdentifiedObject::NAME_KEY,
5276
17
                                sourceTransformationCRS->nameStr() + " to " +
5277
17
                                    geogCRS->nameStr() + " ellipsoidal height"),
5278
17
                            sourceTransformationCRS, geogCRS, nullptr, gridName,
5279
17
                            std::vector<PositionalAccuracyNNPtr>());
5280
17
                    return nn_static_pointer_cast<CRS>(
5281
17
                        BoundCRS::create(crs, geogCRS, transformation));
5282
17
                }
5283
17
            }
5284
18
        }
5285
621
    }
5286
5287
690
    return crs;
5288
707
}
5289
5290
// ---------------------------------------------------------------------------
5291
5292
DerivedVerticalCRSNNPtr
5293
3
WKTParser::Private::buildDerivedVerticalCRS(const WKTNodeNNPtr &node) {
5294
3
    const auto *nodeP = node->GP();
5295
3
    auto &baseVertCRSNode = nodeP->lookForChild(WKTConstants::BASEVERTCRS);
5296
    // given the constraints enforced on calling code path
5297
3
    assert(!isNull(baseVertCRSNode));
5298
5299
3
    auto baseVertCRS_tmp = buildVerticalCRS(baseVertCRSNode);
5300
3
    auto baseVertCRS = NN_NO_CHECK(baseVertCRS_tmp->extractVerticalCRS());
5301
5302
3
    auto &derivingConversionNode =
5303
3
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5304
3
    if (isNull(derivingConversionNode)) {
5305
0
        ThrowMissing(WKTConstants::DERIVINGCONVERSION);
5306
0
    }
5307
3
    auto derivingConversion = buildConversion(
5308
3
        derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE);
5309
5310
3
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5311
3
    if (isNull(csNode)) {
5312
0
        ThrowMissing(WKTConstants::CS_);
5313
0
    }
5314
3
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5315
5316
3
    auto verticalCS = nn_dynamic_pointer_cast<VerticalCS>(cs);
5317
3
    if (!verticalCS) {
5318
0
        throw ParsingException(
5319
0
            concat("vertical CS expected, but found ", cs->getWKT2Type(true)));
5320
0
    }
5321
5322
3
    return DerivedVerticalCRS::create(buildProperties(node), baseVertCRS,
5323
3
                                      derivingConversion,
5324
3
                                      NN_NO_CHECK(verticalCS));
5325
3
}
5326
5327
// ---------------------------------------------------------------------------
5328
5329
281
CRSNNPtr WKTParser::Private::buildCompoundCRS(const WKTNodeNNPtr &node) {
5330
281
    std::vector<CRSNNPtr> components;
5331
281
    bool bFirstNode = true;
5332
1.99k
    for (const auto &child : node->GP()->children()) {
5333
1.99k
        auto crs = buildCRS(child);
5334
1.99k
        if (crs) {
5335
763
            if (bFirstNode) {
5336
248
                geogCRSOfCompoundCRS_ = crs->extractGeographicCRS();
5337
248
                bFirstNode = false;
5338
248
            }
5339
763
            components.push_back(NN_NO_CHECK(crs));
5340
763
        }
5341
1.99k
    }
5342
5343
281
    if (ci_equal(node->GP()->value(), WKTConstants::COMPD_CS)) {
5344
199
        return CompoundCRS::createLax(buildProperties(node), components,
5345
199
                                      dbContext_);
5346
199
    } else {
5347
82
        return CompoundCRS::create(buildProperties(node), components);
5348
82
    }
5349
281
}
5350
5351
// ---------------------------------------------------------------------------
5352
5353
static TransformationNNPtr buildTransformationForBoundCRS(
5354
    DatabaseContextPtr &dbContext,
5355
    const util::PropertyMap &abridgedNodeProperties,
5356
    const util::PropertyMap &methodNodeProperties, const CRSNNPtr &sourceCRS,
5357
    const CRSNNPtr &targetCRS, std::vector<OperationParameterNNPtr> &parameters,
5358
0
    std::vector<ParameterValueNNPtr> &values) {
5359
5360
0
    auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
5361
0
        dbContext, parameters, values);
5362
5363
0
    const auto sourceTransformationCRS(
5364
0
        createBoundCRSSourceTransformationCRS(sourceCRS, targetCRS));
5365
0
    auto transformation = Transformation::create(
5366
0
        abridgedNodeProperties, sourceTransformationCRS, targetCRS,
5367
0
        interpolationCRS, methodNodeProperties, parameters, values,
5368
0
        std::vector<PositionalAccuracyNNPtr>());
5369
5370
    // If the transformation is a "Geographic3D to GravityRelatedHeight" one,
5371
    // then the sourceCRS is expected to be a GeographicCRS and the target a
5372
    // VerticalCRS. Due to how things work in a BoundCRS, we have the opposite,
5373
    // so use our "GravityRelatedHeight to Geographic3D" method instead.
5374
0
    if (Transformation::isGeographic3DToGravityRelatedHeight(
5375
0
            transformation->method(), true) &&
5376
0
        dynamic_cast<VerticalCRS *>(sourceTransformationCRS.get()) &&
5377
0
        dynamic_cast<GeographicCRS *>(targetCRS.get())) {
5378
0
        auto fileParameter = transformation->parameterValue(
5379
0
            EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME,
5380
0
            EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME);
5381
0
        if (fileParameter &&
5382
0
            fileParameter->type() == ParameterValue::Type::FILENAME) {
5383
0
            const auto &filename = fileParameter->valueFile();
5384
5385
0
            transformation =
5386
0
                Transformation::createGravityRelatedHeightToGeographic3D(
5387
0
                    abridgedNodeProperties, sourceTransformationCRS, targetCRS,
5388
0
                    interpolationCRS, filename,
5389
0
                    std::vector<PositionalAccuracyNNPtr>());
5390
0
        }
5391
0
    }
5392
0
    return transformation;
5393
0
}
5394
5395
// ---------------------------------------------------------------------------
5396
5397
15
BoundCRSNNPtr WKTParser::Private::buildBoundCRS(const WKTNodeNNPtr &node) {
5398
15
    const auto *nodeP = node->GP();
5399
15
    auto &abridgedNode =
5400
15
        nodeP->lookForChild(WKTConstants::ABRIDGEDTRANSFORMATION);
5401
15
    if (isNull(abridgedNode)) {
5402
6
        ThrowNotEnoughChildren(WKTConstants::ABRIDGEDTRANSFORMATION);
5403
6
    }
5404
5405
9
    auto &methodNode = abridgedNode->GP()->lookForChild(WKTConstants::METHOD);
5406
9
    if (isNull(methodNode)) {
5407
9
        ThrowMissing(WKTConstants::METHOD);
5408
9
    }
5409
0
    if (methodNode->GP()->childrenSize() == 0) {
5410
0
        ThrowNotEnoughChildren(WKTConstants::METHOD);
5411
0
    }
5412
5413
0
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
5414
0
    const auto &sourceCRSNodeChildren = sourceCRSNode->GP()->children();
5415
0
    if (sourceCRSNodeChildren.size() != 1) {
5416
0
        ThrowNotEnoughChildren(WKTConstants::SOURCECRS);
5417
0
    }
5418
0
    auto sourceCRS = buildCRS(sourceCRSNodeChildren[0]);
5419
0
    if (!sourceCRS) {
5420
0
        throw ParsingException("Invalid content in SOURCECRS node");
5421
0
    }
5422
5423
0
    auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS);
5424
0
    const auto &targetCRSNodeChildren = targetCRSNode->GP()->children();
5425
0
    if (targetCRSNodeChildren.size() != 1) {
5426
0
        ThrowNotEnoughChildren(WKTConstants::TARGETCRS);
5427
0
    }
5428
0
    auto targetCRS = buildCRS(targetCRSNodeChildren[0]);
5429
0
    if (!targetCRS) {
5430
0
        throw ParsingException("Invalid content in TARGETCRS node");
5431
0
    }
5432
5433
0
    std::vector<OperationParameterNNPtr> parameters;
5434
0
    std::vector<ParameterValueNNPtr> values;
5435
0
    const auto &defaultLinearUnit = UnitOfMeasure::NONE;
5436
0
    const auto &defaultAngularUnit = UnitOfMeasure::NONE;
5437
0
    consumeParameters(abridgedNode, true, parameters, values, defaultLinearUnit,
5438
0
                      defaultAngularUnit);
5439
5440
0
    const auto nnSourceCRS = NN_NO_CHECK(sourceCRS);
5441
0
    const auto nnTargetCRS = NN_NO_CHECK(targetCRS);
5442
0
    const auto transformation = buildTransformationForBoundCRS(
5443
0
        dbContext_, buildProperties(abridgedNode), buildProperties(methodNode),
5444
0
        nnSourceCRS, nnTargetCRS, parameters, values);
5445
5446
0
    return BoundCRS::create(buildProperties(node, false, false),
5447
0
                            NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS),
5448
0
                            transformation);
5449
0
}
5450
5451
// ---------------------------------------------------------------------------
5452
5453
TemporalCSNNPtr
5454
8
WKTParser::Private::buildTemporalCS(const WKTNodeNNPtr &parentNode) {
5455
5456
8
    auto &csNode = parentNode->GP()->lookForChild(WKTConstants::CS_);
5457
8
    if (isNull(csNode) &&
5458
5
        !ci_equal(parentNode->GP()->value(), WKTConstants::BASETIMECRS)) {
5459
5
        ThrowMissing(WKTConstants::CS_);
5460
5
    }
5461
3
    auto cs = buildCS(csNode, parentNode, UnitOfMeasure::NONE);
5462
3
    auto temporalCS = nn_dynamic_pointer_cast<TemporalCS>(cs);
5463
3
    if (!temporalCS) {
5464
0
        ThrowNotExpectedCSType(TemporalCS::WKT2_2015_TYPE);
5465
0
    }
5466
3
    return NN_NO_CHECK(temporalCS);
5467
3
}
5468
5469
// ---------------------------------------------------------------------------
5470
5471
TemporalCRSNNPtr
5472
12
WKTParser::Private::buildTemporalCRS(const WKTNodeNNPtr &node) {
5473
12
    auto &datumNode =
5474
12
        node->GP()->lookForChild(WKTConstants::TDATUM, WKTConstants::TIMEDATUM);
5475
12
    if (isNull(datumNode)) {
5476
4
        throw ParsingException("Missing TDATUM / TIMEDATUM node");
5477
4
    }
5478
5479
8
    return TemporalCRS::create(buildProperties(node),
5480
8
                               buildTemporalDatum(datumNode),
5481
8
                               buildTemporalCS(node));
5482
12
}
5483
5484
// ---------------------------------------------------------------------------
5485
5486
DerivedTemporalCRSNNPtr
5487
2
WKTParser::Private::buildDerivedTemporalCRS(const WKTNodeNNPtr &node) {
5488
2
    const auto *nodeP = node->GP();
5489
2
    auto &baseCRSNode = nodeP->lookForChild(WKTConstants::BASETIMECRS);
5490
    // given the constraints enforced on calling code path
5491
2
    assert(!isNull(baseCRSNode));
5492
5493
2
    auto &derivingConversionNode =
5494
2
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5495
2
    if (isNull(derivingConversionNode)) {
5496
2
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5497
2
    }
5498
5499
0
    return DerivedTemporalCRS::create(
5500
0
        buildProperties(node), buildTemporalCRS(baseCRSNode),
5501
0
        buildConversion(derivingConversionNode, UnitOfMeasure::NONE,
5502
0
                        UnitOfMeasure::NONE),
5503
0
        buildTemporalCS(node));
5504
2
}
5505
5506
// ---------------------------------------------------------------------------
5507
5508
EngineeringCRSNNPtr
5509
3
WKTParser::Private::buildEngineeringCRS(const WKTNodeNNPtr &node) {
5510
3
    const auto *nodeP = node->GP();
5511
3
    auto &datumNode = nodeP->lookForChild(WKTConstants::EDATUM,
5512
3
                                          WKTConstants::ENGINEERINGDATUM);
5513
3
    if (isNull(datumNode)) {
5514
3
        throw ParsingException("Missing EDATUM / ENGINEERINGDATUM node");
5515
3
    }
5516
5517
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5518
0
    if (isNull(csNode) && !ci_equal(nodeP->value(), WKTConstants::BASEENGCRS)) {
5519
0
        ThrowMissing(WKTConstants::CS_);
5520
0
    }
5521
5522
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5523
0
    return EngineeringCRS::create(buildProperties(node),
5524
0
                                  buildEngineeringDatum(datumNode), cs);
5525
0
}
5526
5527
// ---------------------------------------------------------------------------
5528
5529
EngineeringCRSNNPtr
5530
363
WKTParser::Private::buildEngineeringCRSFromLocalCS(const WKTNodeNNPtr &node) {
5531
363
    auto &datumNode = node->GP()->lookForChild(WKTConstants::LOCAL_DATUM);
5532
363
    auto cs = buildCS(null_node, node, UnitOfMeasure::NONE);
5533
363
    auto datum = EngineeringDatum::create(
5534
363
        !isNull(datumNode)
5535
363
            ? buildProperties(datumNode)
5536
363
            :
5537
            // In theory OGC 01-009 mandates LOCAL_DATUM, but GDAL
5538
            // has a tradition of emitting just LOCAL_CS["foo"]
5539
363
            []() {
5540
287
                PropertyMap map;
5541
287
                map.set(IdentifiedObject::NAME_KEY, UNKNOWN_ENGINEERING_DATUM);
5542
287
                return map;
5543
287
            }());
5544
363
    return EngineeringCRS::create(buildProperties(node), datum, cs);
5545
363
}
5546
5547
// ---------------------------------------------------------------------------
5548
5549
DerivedEngineeringCRSNNPtr
5550
0
WKTParser::Private::buildDerivedEngineeringCRS(const WKTNodeNNPtr &node) {
5551
0
    const auto *nodeP = node->GP();
5552
0
    auto &baseEngCRSNode = nodeP->lookForChild(WKTConstants::BASEENGCRS);
5553
    // given the constraints enforced on calling code path
5554
0
    assert(!isNull(baseEngCRSNode));
5555
5556
0
    auto baseEngCRS = buildEngineeringCRS(baseEngCRSNode);
5557
5558
0
    auto &derivingConversionNode =
5559
0
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5560
0
    if (isNull(derivingConversionNode)) {
5561
0
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5562
0
    }
5563
0
    auto derivingConversion = buildConversion(
5564
0
        derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE);
5565
5566
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5567
0
    if (isNull(csNode)) {
5568
0
        ThrowMissing(WKTConstants::CS_);
5569
0
    }
5570
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5571
5572
0
    return DerivedEngineeringCRS::create(buildProperties(node), baseEngCRS,
5573
0
                                         derivingConversion, cs);
5574
0
}
5575
5576
// ---------------------------------------------------------------------------
5577
5578
ParametricCSNNPtr
5579
0
WKTParser::Private::buildParametricCS(const WKTNodeNNPtr &parentNode) {
5580
5581
0
    auto &csNode = parentNode->GP()->lookForChild(WKTConstants::CS_);
5582
0
    if (isNull(csNode) &&
5583
0
        !ci_equal(parentNode->GP()->value(), WKTConstants::BASEPARAMCRS)) {
5584
0
        ThrowMissing(WKTConstants::CS_);
5585
0
    }
5586
0
    auto cs = buildCS(csNode, parentNode, UnitOfMeasure::NONE);
5587
0
    auto parametricCS = nn_dynamic_pointer_cast<ParametricCS>(cs);
5588
0
    if (!parametricCS) {
5589
0
        ThrowNotExpectedCSType(ParametricCS::WKT2_TYPE);
5590
0
    }
5591
0
    return NN_NO_CHECK(parametricCS);
5592
0
}
5593
5594
// ---------------------------------------------------------------------------
5595
5596
ParametricCRSNNPtr
5597
9
WKTParser::Private::buildParametricCRS(const WKTNodeNNPtr &node) {
5598
9
    auto &datumNode = node->GP()->lookForChild(WKTConstants::PDATUM,
5599
9
                                               WKTConstants::PARAMETRICDATUM);
5600
9
    if (isNull(datumNode)) {
5601
9
        throw ParsingException("Missing PDATUM / PARAMETRICDATUM node");
5602
9
    }
5603
5604
0
    return ParametricCRS::create(buildProperties(node),
5605
0
                                 buildParametricDatum(datumNode),
5606
0
                                 buildParametricCS(node));
5607
9
}
5608
5609
// ---------------------------------------------------------------------------
5610
5611
DerivedParametricCRSNNPtr
5612
5
WKTParser::Private::buildDerivedParametricCRS(const WKTNodeNNPtr &node) {
5613
5
    const auto *nodeP = node->GP();
5614
5
    auto &baseParamCRSNode = nodeP->lookForChild(WKTConstants::BASEPARAMCRS);
5615
    // given the constraints enforced on calling code path
5616
5
    assert(!isNull(baseParamCRSNode));
5617
5618
5
    auto &derivingConversionNode =
5619
5
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5620
5
    if (isNull(derivingConversionNode)) {
5621
5
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5622
5
    }
5623
5624
0
    return DerivedParametricCRS::create(
5625
0
        buildProperties(node), buildParametricCRS(baseParamCRSNode),
5626
0
        buildConversion(derivingConversionNode, UnitOfMeasure::NONE,
5627
0
                        UnitOfMeasure::NONE),
5628
0
        buildParametricCS(node));
5629
5
}
5630
5631
// ---------------------------------------------------------------------------
5632
5633
DerivedProjectedCRSNNPtr
5634
2
WKTParser::Private::buildDerivedProjectedCRS(const WKTNodeNNPtr &node) {
5635
2
    const auto *nodeP = node->GP();
5636
2
    auto &baseProjCRSNode = nodeP->lookForChild(WKTConstants::BASEPROJCRS);
5637
2
    if (isNull(baseProjCRSNode)) {
5638
2
        ThrowNotEnoughChildren(WKTConstants::BASEPROJCRS);
5639
2
    }
5640
0
    auto baseProjCRS = buildProjectedCRS(baseProjCRSNode);
5641
5642
0
    auto &conversionNode =
5643
0
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5644
0
    if (isNull(conversionNode)) {
5645
0
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5646
0
    }
5647
5648
0
    auto linearUnit = buildUnitInSubNode(node);
5649
0
    const auto &angularUnit =
5650
0
        baseProjCRS->baseCRS()->coordinateSystem()->axisList()[0]->unit();
5651
5652
0
    auto conversion = buildConversion(conversionNode, linearUnit, angularUnit);
5653
5654
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5655
0
    if (isNull(csNode) && !ci_equal(nodeP->value(), WKTConstants::PROJCS)) {
5656
0
        ThrowMissing(WKTConstants::CS_);
5657
0
    }
5658
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5659
5660
0
    if (cs->axisList().size() == 3 &&
5661
0
        baseProjCRS->coordinateSystem()->axisList().size() == 2) {
5662
0
        baseProjCRS = NN_NO_CHECK(util::nn_dynamic_pointer_cast<ProjectedCRS>(
5663
0
            baseProjCRS->promoteTo3D(std::string(), dbContext_)));
5664
0
    }
5665
5666
0
    return DerivedProjectedCRS::create(buildProperties(node), baseProjCRS,
5667
0
                                       conversion, cs);
5668
0
}
5669
5670
// ---------------------------------------------------------------------------
5671
5672
CoordinateMetadataNNPtr
5673
4
WKTParser::Private::buildCoordinateMetadata(const WKTNodeNNPtr &node) {
5674
4
    const auto *nodeP = node->GP();
5675
5676
4
    const auto &l_children = nodeP->children();
5677
4
    if (l_children.empty()) {
5678
0
        ThrowNotEnoughChildren(WKTConstants::COORDINATEMETADATA);
5679
0
    }
5680
5681
4
    auto crs = buildCRS(l_children[0]);
5682
4
    if (!crs) {
5683
1
        throw ParsingException("Invalid content in CRS node");
5684
1
    }
5685
5686
3
    auto &epochNode = nodeP->lookForChild(WKTConstants::EPOCH);
5687
3
    if (!isNull(epochNode)) {
5688
0
        const auto &epochChildren = epochNode->GP()->children();
5689
0
        if (epochChildren.empty()) {
5690
0
            ThrowMissing(WKTConstants::EPOCH);
5691
0
        }
5692
0
        double coordinateEpoch;
5693
0
        try {
5694
0
            coordinateEpoch = asDouble(epochChildren[0]);
5695
0
        } catch (const std::exception &) {
5696
0
            throw ParsingException("Invalid EPOCH node");
5697
0
        }
5698
0
        return CoordinateMetadata::create(NN_NO_CHECK(crs), coordinateEpoch,
5699
0
                                          dbContext_);
5700
0
    }
5701
5702
3
    return CoordinateMetadata::create(NN_NO_CHECK(crs));
5703
3
}
5704
5705
// ---------------------------------------------------------------------------
5706
5707
4.47k
static bool isGeodeticCRS(const std::string &name) {
5708
4.47k
    return ci_equal(name, WKTConstants::GEODCRS) ||       // WKT2
5709
4.47k
           ci_equal(name, WKTConstants::GEODETICCRS) ||   // WKT2
5710
4.47k
           ci_equal(name, WKTConstants::GEOGCRS) ||       // WKT2 2019
5711
4.47k
           ci_equal(name, WKTConstants::GEOGRAPHICCRS) || // WKT2 2019
5712
4.47k
           ci_equal(name, WKTConstants::GEOGCS) ||        // WKT1
5713
3.96k
           ci_equal(name, WKTConstants::GEOCCS);          // WKT1
5714
4.47k
}
5715
5716
// ---------------------------------------------------------------------------
5717
5718
4.47k
CRSPtr WKTParser::Private::buildCRS(const WKTNodeNNPtr &node) {
5719
4.47k
    const auto *nodeP = node->GP();
5720
4.47k
    const std::string &name(nodeP->value());
5721
5722
4.47k
    const auto applyHorizontalBoundCRSParams = [&](const CRSNNPtr &crs) {
5723
899
        if (!toWGS84Parameters_.empty()) {
5724
0
            auto ret = BoundCRS::createFromTOWGS84(crs, toWGS84Parameters_);
5725
0
            toWGS84Parameters_.clear();
5726
0
            return util::nn_static_pointer_cast<CRS>(ret);
5727
899
        } else if (!datumPROJ4Grids_.empty()) {
5728
0
            auto ret = BoundCRS::createFromNadgrids(crs, datumPROJ4Grids_);
5729
0
            datumPROJ4Grids_.clear();
5730
0
            return util::nn_static_pointer_cast<CRS>(ret);
5731
0
        }
5732
899
        return crs;
5733
899
    };
5734
5735
4.47k
    if (isGeodeticCRS(name)) {
5736
596
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEGEOGCRS,
5737
596
                                        WKTConstants::BASEGEODCRS))) {
5738
0
            return util::nn_static_pointer_cast<CRS>(
5739
0
                applyHorizontalBoundCRSParams(buildDerivedGeodeticCRS(node)));
5740
596
        } else {
5741
596
            return util::nn_static_pointer_cast<CRS>(
5742
596
                applyHorizontalBoundCRSParams(buildGeodeticCRS(node)));
5743
596
        }
5744
596
    }
5745
5746
3.88k
    if (ci_equal(name, WKTConstants::PROJCS) ||
5747
2.99k
        ci_equal(name, WKTConstants::PROJCRS) ||
5748
2.99k
        ci_equal(name, WKTConstants::PROJECTEDCRS)) {
5749
        // Get the EXTENSION "PROJ4" node before attempting to call
5750
        // buildProjectedCRS() since formulations of WKT1_GDAL from GDAL 2.x
5751
        // with the netCDF driver and the lack the required UNIT[] node
5752
887
        std::string projString = getExtensionProj4(nodeP);
5753
887
        if (!projString.empty() &&
5754
144
            (starts_with(projString, "+proj=ob_tran +o_proj=longlat") ||
5755
71
             starts_with(projString, "+proj=ob_tran +o_proj=lonlat") ||
5756
71
             starts_with(projString, "+proj=ob_tran +o_proj=latlong") ||
5757
111
             starts_with(projString, "+proj=ob_tran +o_proj=latlon"))) {
5758
            // Those are not a projected CRS, but a DerivedGeographic one...
5759
111
            if (projString.find(" +type=crs") == std::string::npos) {
5760
111
                projString += " +type=crs";
5761
111
            }
5762
111
            try {
5763
111
                auto projObj =
5764
111
                    PROJStringParser().createFromPROJString(projString);
5765
111
                auto crs = nn_dynamic_pointer_cast<CRS>(projObj);
5766
111
                if (crs) {
5767
62
                    return util::nn_static_pointer_cast<CRS>(
5768
62
                        applyHorizontalBoundCRSParams(NN_NO_CHECK(crs)));
5769
62
                }
5770
111
            } catch (const io::ParsingException &) {
5771
41
            }
5772
111
        }
5773
823
        return util::nn_static_pointer_cast<CRS>(
5774
823
            applyHorizontalBoundCRSParams(buildProjectedCRS(node)));
5775
887
    }
5776
5777
2.99k
    if (ci_equal(name, WKTConstants::VERT_CS) ||
5778
2.96k
        ci_equal(name, WKTConstants::VERTCS) ||
5779
2.41k
        ci_equal(name, WKTConstants::VERTCRS) ||
5780
2.41k
        ci_equal(name, WKTConstants::VERTICALCRS)) {
5781
577
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEVERTCRS))) {
5782
3
            return util::nn_static_pointer_cast<CRS>(
5783
3
                buildDerivedVerticalCRS(node));
5784
574
        } else {
5785
574
            return util::nn_static_pointer_cast<CRS>(buildVerticalCRS(node));
5786
574
        }
5787
577
    }
5788
5789
2.41k
    if (ci_equal(name, WKTConstants::COMPD_CS) ||
5790
2.13k
        ci_equal(name, WKTConstants::COMPOUNDCRS)) {
5791
281
        return util::nn_static_pointer_cast<CRS>(buildCompoundCRS(node));
5792
281
    }
5793
5794
2.13k
    if (ci_equal(name, WKTConstants::BOUNDCRS)) {
5795
15
        return util::nn_static_pointer_cast<CRS>(buildBoundCRS(node));
5796
15
    }
5797
5798
2.12k
    if (ci_equal(name, WKTConstants::TIMECRS)) {
5799
14
        if (!isNull(nodeP->lookForChild(WKTConstants::BASETIMECRS))) {
5800
2
            return util::nn_static_pointer_cast<CRS>(
5801
2
                buildDerivedTemporalCRS(node));
5802
12
        } else {
5803
12
            return util::nn_static_pointer_cast<CRS>(buildTemporalCRS(node));
5804
12
        }
5805
14
    }
5806
5807
2.10k
    if (ci_equal(name, WKTConstants::DERIVEDPROJCRS)) {
5808
2
        return util::nn_static_pointer_cast<CRS>(
5809
2
            buildDerivedProjectedCRS(node));
5810
2
    }
5811
5812
2.10k
    if (ci_equal(name, WKTConstants::ENGCRS) ||
5813
2.10k
        ci_equal(name, WKTConstants::ENGINEERINGCRS)) {
5814
3
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEENGCRS))) {
5815
0
            return util::nn_static_pointer_cast<CRS>(
5816
0
                buildDerivedEngineeringCRS(node));
5817
3
        } else {
5818
3
            return util::nn_static_pointer_cast<CRS>(buildEngineeringCRS(node));
5819
3
        }
5820
3
    }
5821
5822
2.10k
    if (ci_equal(name, WKTConstants::LOCAL_CS)) {
5823
363
        return util::nn_static_pointer_cast<CRS>(
5824
363
            buildEngineeringCRSFromLocalCS(node));
5825
363
    }
5826
5827
1.73k
    if (ci_equal(name, WKTConstants::PARAMETRICCRS)) {
5828
14
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEPARAMCRS))) {
5829
5
            return util::nn_static_pointer_cast<CRS>(
5830
5
                buildDerivedParametricCRS(node));
5831
9
        } else {
5832
9
            return util::nn_static_pointer_cast<CRS>(buildParametricCRS(node));
5833
9
        }
5834
14
    }
5835
5836
1.72k
    return nullptr;
5837
1.73k
}
5838
5839
// ---------------------------------------------------------------------------
5840
5841
2.23k
BaseObjectNNPtr WKTParser::Private::build(const WKTNodeNNPtr &node) {
5842
2.23k
    const auto *nodeP = node->GP();
5843
2.23k
    const std::string &name(nodeP->value());
5844
5845
2.23k
    auto crs = buildCRS(node);
5846
2.23k
    if (crs) {
5847
751
        return util::nn_static_pointer_cast<BaseObject>(NN_NO_CHECK(crs));
5848
751
    }
5849
5850
    // Datum handled by caller code WKTParser::createFromWKT()
5851
5852
1.48k
    if (ci_equal(name, WKTConstants::ENSEMBLE)) {
5853
9
        return util::nn_static_pointer_cast<BaseObject>(buildDatumEnsemble(
5854
9
            node, PrimeMeridian::GREENWICH,
5855
9
            !isNull(nodeP->lookForChild(WKTConstants::ELLIPSOID))));
5856
9
    }
5857
5858
1.47k
    if (ci_equal(name, WKTConstants::VDATUM) ||
5859
563
        ci_equal(name, WKTConstants::VERT_DATUM) ||
5860
562
        ci_equal(name, WKTConstants::VERTICALDATUM) ||
5861
562
        ci_equal(name, WKTConstants::VRF)) {
5862
137
        return util::nn_static_pointer_cast<BaseObject>(
5863
137
            buildVerticalReferenceFrame(node, null_node));
5864
137
    }
5865
5866
1.34k
    if (ci_equal(name, WKTConstants::TDATUM) ||
5867
416
        ci_equal(name, WKTConstants::TIMEDATUM)) {
5868
11
        return util::nn_static_pointer_cast<BaseObject>(
5869
11
            buildTemporalDatum(node));
5870
11
    }
5871
5872
1.33k
    if (ci_equal(name, WKTConstants::EDATUM) ||
5873
409
        ci_equal(name, WKTConstants::ENGINEERINGDATUM)) {
5874
6
        return util::nn_static_pointer_cast<BaseObject>(
5875
6
            buildEngineeringDatum(node));
5876
6
    }
5877
5878
1.32k
    if (ci_equal(name, WKTConstants::PDATUM) ||
5879
404
        ci_equal(name, WKTConstants::PARAMETRICDATUM)) {
5880
5
        return util::nn_static_pointer_cast<BaseObject>(
5881
5
            buildParametricDatum(node));
5882
5
    }
5883
5884
1.31k
    if (ci_equal(name, WKTConstants::ELLIPSOID) ||
5885
404
        ci_equal(name, WKTConstants::SPHEROID)) {
5886
4
        return util::nn_static_pointer_cast<BaseObject>(buildEllipsoid(node));
5887
4
    }
5888
5889
1.31k
    if (ci_equal(name, WKTConstants::COORDINATEOPERATION)) {
5890
13
        auto transf = buildCoordinateOperation(node);
5891
5892
13
        const char *prefixes[] = {
5893
13
            "PROJ-based operation method: ",
5894
13
            "PROJ-based operation method (approximate): "};
5895
13
        for (const char *prefix : prefixes) {
5896
0
            if (starts_with(transf->method()->nameStr(), prefix)) {
5897
0
                auto projString =
5898
0
                    transf->method()->nameStr().substr(strlen(prefix));
5899
0
                return util::nn_static_pointer_cast<BaseObject>(
5900
0
                    PROJBasedOperation::create(
5901
0
                        PropertyMap(), projString, transf->sourceCRS(),
5902
0
                        transf->targetCRS(),
5903
0
                        transf->coordinateOperationAccuracies()));
5904
0
            }
5905
0
        }
5906
5907
13
        return util::nn_static_pointer_cast<BaseObject>(transf);
5908
13
    }
5909
5910
1.30k
    if (ci_equal(name, WKTConstants::CONVERSION)) {
5911
346
        auto conv =
5912
346
            buildConversion(node, UnitOfMeasure::METRE, UnitOfMeasure::DEGREE);
5913
5914
346
        if (starts_with(conv->method()->nameStr(),
5915
346
                        "PROJ-based operation method: ")) {
5916
1
            auto projString = conv->method()->nameStr().substr(
5917
1
                strlen("PROJ-based operation method: "));
5918
1
            return util::nn_static_pointer_cast<BaseObject>(
5919
1
                PROJBasedOperation::create(PropertyMap(), projString, nullptr,
5920
1
                                           nullptr, {}));
5921
1
        }
5922
5923
345
        return util::nn_static_pointer_cast<BaseObject>(conv);
5924
346
    }
5925
5926
956
    if (ci_equal(name, WKTConstants::CONCATENATEDOPERATION)) {
5927
5
        return util::nn_static_pointer_cast<BaseObject>(
5928
5
            buildConcatenatedOperation(node));
5929
5
    }
5930
5931
951
    if (ci_equal(name, WKTConstants::POINTMOTIONOPERATION)) {
5932
1
        return util::nn_static_pointer_cast<BaseObject>(
5933
1
            buildPointMotionOperation(node));
5934
1
    }
5935
5936
950
    if (ci_equal(name, WKTConstants::ID) ||
5937
28
        ci_equal(name, WKTConstants::AUTHORITY)) {
5938
28
        return util::nn_static_pointer_cast<BaseObject>(
5939
28
            NN_NO_CHECK(buildId(node, node, false, false)));
5940
28
    }
5941
5942
922
    if (ci_equal(name, WKTConstants::COORDINATEMETADATA)) {
5943
4
        return util::nn_static_pointer_cast<BaseObject>(
5944
4
            buildCoordinateMetadata(node));
5945
4
    }
5946
5947
918
    throw ParsingException(concat("unhandled keyword: ", name));
5948
922
}
5949
//! @endcond
5950
5951
// ---------------------------------------------------------------------------
5952
5953
//! @cond Doxygen_Suppress
5954
class JSONParser {
5955
    DatabaseContextPtr dbContext_{};
5956
    std::string deformationModelName_{};
5957
    PJ_CONTEXT *ctx_ = nullptr;
5958
5959
    static std::string getString(const json &j, const char *key);
5960
    static json getObject(const json &j, const char *key);
5961
    static json getArray(const json &j, const char *key);
5962
    static int getInteger(const json &j, const char *key);
5963
    static double getNumber(const json &j, const char *key);
5964
    static UnitOfMeasure getUnit(const json &j, const char *key);
5965
    static std::string getName(const json &j);
5966
    static std::string getType(const json &j);
5967
    static Length getLength(const json &j, const char *key);
5968
    static Measure getMeasure(const json &j);
5969
5970
    IdentifierNNPtr buildId(const json &parentJ, const json &j,
5971
                            bool removeInverseOf);
5972
    static ObjectDomainPtr buildObjectDomain(const json &j);
5973
    PropertyMap buildProperties(const json &j, bool removeInverseOf = false,
5974
                                bool nameRequired = true);
5975
5976
    GeographicCRSNNPtr buildGeographicCRS(const json &j);
5977
    GeodeticCRSNNPtr buildGeodeticCRS(const json &j);
5978
    ProjectedCRSNNPtr buildProjectedCRS(const json &j);
5979
    ConversionNNPtr buildConversion(const json &j);
5980
    DatumEnsembleNNPtr buildDatumEnsemble(const json &j);
5981
    GeodeticReferenceFrameNNPtr buildGeodeticReferenceFrame(const json &j);
5982
    VerticalReferenceFrameNNPtr buildVerticalReferenceFrame(const json &j);
5983
    DynamicGeodeticReferenceFrameNNPtr
5984
    buildDynamicGeodeticReferenceFrame(const json &j);
5985
    DynamicVerticalReferenceFrameNNPtr
5986
    buildDynamicVerticalReferenceFrame(const json &j);
5987
    EllipsoidNNPtr buildEllipsoid(const json &j);
5988
    PrimeMeridianNNPtr buildPrimeMeridian(const json &j);
5989
    CoordinateSystemNNPtr buildCS(const json &j);
5990
    MeridianNNPtr buildMeridian(const json &j);
5991
    CoordinateSystemAxisNNPtr buildAxis(const json &j);
5992
    VerticalCRSNNPtr buildVerticalCRS(const json &j);
5993
    CRSNNPtr buildCRS(const json &j);
5994
    CompoundCRSNNPtr buildCompoundCRS(const json &j);
5995
    BoundCRSNNPtr buildBoundCRS(const json &j);
5996
    TransformationNNPtr buildTransformation(const json &j);
5997
    PointMotionOperationNNPtr buildPointMotionOperation(const json &j);
5998
    ConcatenatedOperationNNPtr buildConcatenatedOperation(const json &j);
5999
    CoordinateMetadataNNPtr buildCoordinateMetadata(const json &j);
6000
6001
    void buildGeodeticDatumOrDatumEnsemble(const json &j,
6002
                                           GeodeticReferenceFramePtr &datum,
6003
                                           DatumEnsemblePtr &datumEnsemble);
6004
6005
18
    static util::optional<std::string> getAnchor(const json &j) {
6006
18
        util::optional<std::string> anchor;
6007
18
        if (j.contains("anchor")) {
6008
0
            anchor = getString(j, "anchor");
6009
0
        }
6010
18
        return anchor;
6011
18
    }
6012
6013
0
    static util::optional<common::Measure> getAnchorEpoch(const json &j) {
6014
0
        if (j.contains("anchor_epoch")) {
6015
0
            return util::optional<common::Measure>(common::Measure(
6016
0
                getNumber(j, "anchor_epoch"), common::UnitOfMeasure::YEAR));
6017
0
        }
6018
0
        return util::optional<common::Measure>();
6019
0
    }
6020
6021
22
    EngineeringDatumNNPtr buildEngineeringDatum(const json &j) {
6022
22
        return EngineeringDatum::create(buildProperties(j), getAnchor(j));
6023
22
    }
6024
6025
0
    ParametricDatumNNPtr buildParametricDatum(const json &j) {
6026
0
        return ParametricDatum::create(buildProperties(j), getAnchor(j));
6027
0
    }
6028
6029
0
    TemporalDatumNNPtr buildTemporalDatum(const json &j) {
6030
0
        auto calendar = getString(j, "calendar");
6031
0
        auto origin = DateTime::create(j.contains("time_origin")
6032
0
                                           ? getString(j, "time_origin")
6033
0
                                           : std::string());
6034
0
        return TemporalDatum::create(buildProperties(j), origin, calendar);
6035
0
    }
6036
6037
    template <class TargetCRS, class DatumBuilderType,
6038
              class CSClass = CoordinateSystem>
6039
    util::nn<std::shared_ptr<TargetCRS>> buildCRS(const json &j,
6040
0
                                                  DatumBuilderType f) {
6041
0
        auto datum = (this->*f)(getObject(j, "datum"));
6042
0
        auto cs = buildCS(getObject(j, "coordinate_system"));
6043
0
        auto csCast = util::nn_dynamic_pointer_cast<CSClass>(cs);
6044
0
        if (!csCast) {
6045
0
            throw ParsingException("coordinate_system not of expected type");
6046
0
        }
6047
0
        return TargetCRS::create(buildProperties(j), datum,
6048
0
                                 NN_NO_CHECK(csCast));
6049
0
    }
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::EngineeringCRS> > osgeo::proj::io::JSONParser::buildCRS<osgeo::proj::crs::EngineeringCRS, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::EngineeringDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&), osgeo::proj::cs::CoordinateSystem>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::EngineeringDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&))
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::ParametricCRS> > osgeo::proj::io::JSONParser::buildCRS<osgeo::proj::crs::ParametricCRS, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::ParametricDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&), osgeo::proj::cs::ParametricCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::ParametricDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&))
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::TemporalCRS> > osgeo::proj::io::JSONParser::buildCRS<osgeo::proj::crs::TemporalCRS, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::TemporalDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&), osgeo::proj::cs::TemporalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::TemporalDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&))
6050
6051
    template <class TargetCRS, class BaseCRS, class CSClass = CoordinateSystem>
6052
0
    util::nn<std::shared_ptr<TargetCRS>> buildDerivedCRS(const json &j) {
6053
0
        auto baseCRSObj = create(getObject(j, "base_crs"));
6054
0
        auto baseCRS = util::nn_dynamic_pointer_cast<BaseCRS>(baseCRSObj);
6055
0
        if (!baseCRS) {
6056
0
            throw ParsingException("base_crs not of expected type");
6057
0
        }
6058
0
        auto cs = buildCS(getObject(j, "coordinate_system"));
6059
0
        auto csCast = util::nn_dynamic_pointer_cast<CSClass>(cs);
6060
0
        if (!csCast) {
6061
0
            throw ParsingException("coordinate_system not of expected type");
6062
0
        }
6063
0
        auto conv = buildConversion(getObject(j, "conversion"));
6064
0
        return TargetCRS::create(buildProperties(j), NN_NO_CHECK(baseCRS), conv,
6065
0
                                 NN_NO_CHECK(csCast));
6066
0
    }
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedGeographicCRS> > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedGeographicCRS, osgeo::proj::crs::GeodeticCRS, osgeo::proj::cs::EllipsoidalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedProjectedCRS> > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedProjectedCRS, osgeo::proj::crs::ProjectedCRS, osgeo::proj::cs::CoordinateSystem>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedVerticalCRS> > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedVerticalCRS, osgeo::proj::crs::VerticalCRS, osgeo::proj::cs::VerticalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedEngineeringCRSTraits> > > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedEngineeringCRSTraits>, osgeo::proj::crs::EngineeringCRS, osgeo::proj::cs::CoordinateSystem>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedParametricCRSTraits> > > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedParametricCRSTraits>, osgeo::proj::crs::ParametricCRS, osgeo::proj::cs::ParametricCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedTemporalCRSTraits> > > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedTemporalCRSTraits>, osgeo::proj::crs::TemporalCRS, osgeo::proj::cs::TemporalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
6067
6068
0
    void emitRecoverableWarning(const std::string &warningMsg) {
6069
0
        if (ctx_) {
6070
0
            proj_context_log_debug(ctx_, "PROJJSON parsing: %s",
6071
0
                                   warningMsg.c_str());
6072
0
        }
6073
0
    }
6074
6075
    JSONParser(const JSONParser &) = delete;
6076
    JSONParser &operator=(const JSONParser &) = delete;
6077
6078
  public:
6079
96
    JSONParser() = default;
6080
6081
96
    JSONParser &attachDatabaseContext(const DatabaseContextPtr &dbContext) {
6082
96
        dbContext_ = dbContext;
6083
96
        return *this;
6084
96
    }
6085
6086
96
    JSONParser &attachContext(PJ_CONTEXT *ctx) {
6087
96
        ctx_ = ctx;
6088
96
        return *this;
6089
96
    }
6090
6091
    BaseObjectNNPtr create(const json &j);
6092
};
6093
6094
// ---------------------------------------------------------------------------
6095
6096
142
std::string JSONParser::getString(const json &j, const char *key) {
6097
142
    if (!j.contains(key)) {
6098
22
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6099
22
    }
6100
120
    auto v = j[key];
6101
120
    if (!v.is_string()) {
6102
35
        throw ParsingException(std::string("The value of \"") + key +
6103
35
                               "\" should be a string");
6104
35
    }
6105
85
    return v.get<std::string>();
6106
120
}
6107
6108
// ---------------------------------------------------------------------------
6109
6110
25
json JSONParser::getObject(const json &j, const char *key) {
6111
25
    if (!j.contains(key)) {
6112
2
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6113
2
    }
6114
23
    auto v = j[key];
6115
23
    if (!v.is_object()) {
6116
0
        throw ParsingException(std::string("The value of \"") + key +
6117
0
                               "\" should be a object");
6118
0
    }
6119
23
    return v.get<json>();
6120
23
}
6121
6122
// ---------------------------------------------------------------------------
6123
6124
0
json JSONParser::getArray(const json &j, const char *key) {
6125
0
    if (!j.contains(key)) {
6126
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6127
0
    }
6128
0
    auto v = j[key];
6129
0
    if (!v.is_array()) {
6130
0
        throw ParsingException(std::string("The value of \"") + key +
6131
0
                               "\" should be a array");
6132
0
    }
6133
0
    return v.get<json>();
6134
0
}
6135
6136
// ---------------------------------------------------------------------------
6137
6138
0
int JSONParser::getInteger(const json &j, const char *key) {
6139
0
    if (!j.contains(key)) {
6140
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6141
0
    }
6142
0
    auto v = j[key];
6143
0
    if (!v.is_number()) {
6144
0
        throw ParsingException(std::string("The value of \"") + key +
6145
0
                               "\" should be an integer");
6146
0
    }
6147
0
    const double dbl = v.get<double>();
6148
0
    if (!(dbl >= std::numeric_limits<int>::min() &&
6149
0
          dbl <= std::numeric_limits<int>::max() &&
6150
0
          static_cast<int>(dbl) == dbl)) {
6151
0
        throw ParsingException(std::string("The value of \"") + key +
6152
0
                               "\" should be an integer");
6153
0
    }
6154
0
    return static_cast<int>(dbl);
6155
0
}
6156
6157
// ---------------------------------------------------------------------------
6158
6159
0
double JSONParser::getNumber(const json &j, const char *key) {
6160
0
    if (!j.contains(key)) {
6161
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6162
0
    }
6163
0
    auto v = j[key];
6164
0
    if (!v.is_number()) {
6165
0
        throw ParsingException(std::string("The value of \"") + key +
6166
0
                               "\" should be a number");
6167
0
    }
6168
0
    return v.get<double>();
6169
0
}
6170
6171
// ---------------------------------------------------------------------------
6172
6173
0
UnitOfMeasure JSONParser::getUnit(const json &j, const char *key) {
6174
0
    if (!j.contains(key)) {
6175
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6176
0
    }
6177
0
    auto v = j[key];
6178
0
    if (v.is_string()) {
6179
0
        auto vStr = v.get<std::string>();
6180
0
        for (const auto &unit : {UnitOfMeasure::METRE, UnitOfMeasure::DEGREE,
6181
0
                                 UnitOfMeasure::SCALE_UNITY}) {
6182
0
            if (vStr == unit.name())
6183
0
                return unit;
6184
0
        }
6185
0
        throw ParsingException("Unknown unit name: " + vStr);
6186
0
    }
6187
0
    if (!v.is_object()) {
6188
0
        throw ParsingException(std::string("The value of \"") + key +
6189
0
                               "\" should be a string or an object");
6190
0
    }
6191
0
    auto typeStr = getType(v);
6192
0
    UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN;
6193
0
    if (typeStr == "LinearUnit") {
6194
0
        type = UnitOfMeasure::Type::LINEAR;
6195
0
    } else if (typeStr == "AngularUnit") {
6196
0
        type = UnitOfMeasure::Type::ANGULAR;
6197
0
    } else if (typeStr == "ScaleUnit") {
6198
0
        type = UnitOfMeasure::Type::SCALE;
6199
0
    } else if (typeStr == "TimeUnit") {
6200
0
        type = UnitOfMeasure::Type::TIME;
6201
0
    } else if (typeStr == "ParametricUnit") {
6202
0
        type = UnitOfMeasure::Type::PARAMETRIC;
6203
0
    } else if (typeStr == "Unit") {
6204
0
        type = UnitOfMeasure::Type::UNKNOWN;
6205
0
    } else {
6206
0
        throw ParsingException("Unsupported value of \"type\"");
6207
0
    }
6208
0
    auto nameStr = getName(v);
6209
0
    auto convFactor = getNumber(v, "conversion_factor");
6210
0
    std::string authorityStr;
6211
0
    std::string codeStr;
6212
0
    if (v.contains("authority") && v.contains("code")) {
6213
0
        authorityStr = getString(v, "authority");
6214
0
        auto code = v["code"];
6215
0
        if (code.is_string()) {
6216
0
            codeStr = code.get<std::string>();
6217
0
        } else if (code.is_number_integer()) {
6218
0
            codeStr = internal::toString(code.get<int>());
6219
0
        } else {
6220
0
            throw ParsingException("Unexpected type for value of \"code\"");
6221
0
        }
6222
0
    }
6223
0
    return UnitOfMeasure(nameStr, convFactor, type, authorityStr, codeStr);
6224
0
}
6225
6226
// ---------------------------------------------------------------------------
6227
6228
23
std::string JSONParser::getName(const json &j) { return getString(j, "name"); }
6229
6230
// ---------------------------------------------------------------------------
6231
6232
0
std::string JSONParser::getType(const json &j) { return getString(j, "type"); }
6233
6234
// ---------------------------------------------------------------------------
6235
6236
0
Length JSONParser::getLength(const json &j, const char *key) {
6237
0
    if (!j.contains(key)) {
6238
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6239
0
    }
6240
0
    auto v = j[key];
6241
0
    if (v.is_number()) {
6242
0
        return Length(v.get<double>(), UnitOfMeasure::METRE);
6243
0
    }
6244
0
    if (v.is_object()) {
6245
0
        return Length(getMeasure(v));
6246
0
    }
6247
0
    throw ParsingException(std::string("The value of \"") + key +
6248
0
                           "\" should be a number or an object");
6249
0
}
6250
6251
// ---------------------------------------------------------------------------
6252
6253
0
Measure JSONParser::getMeasure(const json &j) {
6254
0
    return Measure(getNumber(j, "value"), getUnit(j, "unit"));
6255
0
}
6256
6257
// ---------------------------------------------------------------------------
6258
6259
18
ObjectDomainPtr JSONParser::buildObjectDomain(const json &j) {
6260
18
    optional<std::string> scope;
6261
18
    if (j.contains("scope")) {
6262
0
        scope = getString(j, "scope");
6263
0
    }
6264
18
    std::string area;
6265
18
    if (j.contains("area")) {
6266
0
        area = getString(j, "area");
6267
0
    }
6268
18
    std::vector<GeographicExtentNNPtr> geogExtent;
6269
18
    if (j.contains("bbox")) {
6270
0
        auto bbox = getObject(j, "bbox");
6271
0
        double south = getNumber(bbox, "south_latitude");
6272
0
        double west = getNumber(bbox, "west_longitude");
6273
0
        double north = getNumber(bbox, "north_latitude");
6274
0
        double east = getNumber(bbox, "east_longitude");
6275
0
        try {
6276
0
            geogExtent.emplace_back(
6277
0
                GeographicBoundingBox::create(west, south, east, north));
6278
0
        } catch (const std::exception &e) {
6279
0
            throw ParsingException(
6280
0
                std::string("Invalid bbox node: ").append(e.what()));
6281
0
        }
6282
0
    }
6283
6284
18
    std::vector<VerticalExtentNNPtr> verticalExtent;
6285
18
    if (j.contains("vertical_extent")) {
6286
0
        const auto vertical_extent = getObject(j, "vertical_extent");
6287
0
        const auto min = getNumber(vertical_extent, "minimum");
6288
0
        const auto max = getNumber(vertical_extent, "maximum");
6289
0
        const auto unit = vertical_extent.contains("unit")
6290
0
                              ? getUnit(vertical_extent, "unit")
6291
0
                              : UnitOfMeasure::METRE;
6292
0
        verticalExtent.emplace_back(VerticalExtent::create(
6293
0
            min, max, util::nn_make_shared<UnitOfMeasure>(unit)));
6294
0
    }
6295
6296
18
    std::vector<TemporalExtentNNPtr> temporalExtent;
6297
18
    if (j.contains("temporal_extent")) {
6298
0
        const auto temporal_extent = getObject(j, "temporal_extent");
6299
0
        const auto start = getString(temporal_extent, "start");
6300
0
        const auto end = getString(temporal_extent, "end");
6301
0
        temporalExtent.emplace_back(TemporalExtent::create(start, end));
6302
0
    }
6303
6304
18
    if (scope.has_value() || !area.empty() || !geogExtent.empty() ||
6305
18
        !verticalExtent.empty() || !temporalExtent.empty()) {
6306
0
        util::optional<std::string> description;
6307
0
        if (!area.empty())
6308
0
            description = area;
6309
0
        ExtentPtr extent;
6310
0
        if (description.has_value() || !geogExtent.empty() ||
6311
0
            !verticalExtent.empty() || !temporalExtent.empty()) {
6312
0
            extent = Extent::create(description, geogExtent, verticalExtent,
6313
0
                                    temporalExtent)
6314
0
                         .as_nullable();
6315
0
        }
6316
0
        return ObjectDomain::create(scope, extent).as_nullable();
6317
0
    }
6318
18
    return nullptr;
6319
18
}
6320
6321
// ---------------------------------------------------------------------------
6322
6323
IdentifierNNPtr JSONParser::buildId(const json &parentJ, const json &j,
6324
0
                                    bool removeInverseOf) {
6325
6326
0
    PropertyMap propertiesId;
6327
0
    auto codeSpace(getString(j, "authority"));
6328
0
    if (removeInverseOf && starts_with(codeSpace, "INVERSE(") &&
6329
0
        codeSpace.back() == ')') {
6330
0
        codeSpace = codeSpace.substr(strlen("INVERSE("));
6331
0
        codeSpace.resize(codeSpace.size() - 1);
6332
0
    }
6333
6334
0
    std::string version;
6335
0
    if (j.contains("version")) {
6336
0
        auto versionJ = j["version"];
6337
0
        if (versionJ.is_string()) {
6338
0
            version = versionJ.get<std::string>();
6339
0
        } else if (versionJ.is_number()) {
6340
0
            const double dblVersion = versionJ.get<double>();
6341
0
            if (dblVersion >= std::numeric_limits<int>::min() &&
6342
0
                dblVersion <= std::numeric_limits<int>::max() &&
6343
0
                static_cast<int>(dblVersion) == dblVersion) {
6344
0
                version = internal::toString(static_cast<int>(dblVersion));
6345
0
            } else {
6346
0
                version = internal::toString(dblVersion, /*precision=*/15);
6347
0
            }
6348
0
        } else {
6349
0
            throw ParsingException("Unexpected type for value of \"version\"");
6350
0
        }
6351
0
    }
6352
6353
    // IAU + 2015 -> IAU_2015
6354
0
    if (dbContext_ && !version.empty()) {
6355
0
        std::string codeSpaceOut;
6356
0
        if (dbContext_->getVersionedAuthority(codeSpace, version,
6357
0
                                              codeSpaceOut)) {
6358
0
            codeSpace = std::move(codeSpaceOut);
6359
0
            version.clear();
6360
0
        }
6361
0
    }
6362
6363
0
    propertiesId.set(metadata::Identifier::CODESPACE_KEY, codeSpace);
6364
0
    propertiesId.set(metadata::Identifier::AUTHORITY_KEY, codeSpace);
6365
0
    if (!j.contains("code")) {
6366
0
        throw ParsingException("Missing \"code\" key");
6367
0
    }
6368
0
    std::string code;
6369
0
    auto codeJ = j["code"];
6370
0
    if (codeJ.is_string()) {
6371
0
        code = codeJ.get<std::string>();
6372
0
    } else if (codeJ.is_number_integer()) {
6373
0
        code = internal::toString(codeJ.get<int>());
6374
0
    } else {
6375
0
        throw ParsingException("Unexpected type for value of \"code\"");
6376
0
    }
6377
6378
    // Prior to PROJ 9.5, when synthetizing an ID for a CONVERSION UTM Zone
6379
    // south, we generated a wrong value. Auto-fix that
6380
0
    if (parentJ.contains("type") && getType(parentJ) == "Conversion" &&
6381
0
        codeSpace == Identifier::EPSG && parentJ.contains("name")) {
6382
0
        const auto parentNodeName(getName(parentJ));
6383
0
        if (ci_starts_with(parentNodeName, "UTM Zone ") &&
6384
0
            parentNodeName.find('S') != std::string::npos) {
6385
0
            const int nZone =
6386
0
                atoi(parentNodeName.c_str() + strlen("UTM Zone "));
6387
0
            if (nZone >= 1 && nZone <= 60) {
6388
0
                code = internal::toString(16100 + nZone);
6389
0
            }
6390
0
        }
6391
0
    }
6392
6393
0
    if (!version.empty()) {
6394
0
        propertiesId.set(Identifier::VERSION_KEY, version);
6395
0
    }
6396
6397
0
    if (j.contains("authority_citation")) {
6398
0
        propertiesId.set(Identifier::AUTHORITY_KEY,
6399
0
                         getString(j, "authority_citation"));
6400
0
    }
6401
6402
0
    if (j.contains("uri")) {
6403
0
        propertiesId.set(Identifier::URI_KEY, getString(j, "uri"));
6404
0
    }
6405
6406
0
    return Identifier::create(code, propertiesId);
6407
0
}
6408
6409
// ---------------------------------------------------------------------------
6410
6411
PropertyMap JSONParser::buildProperties(const json &j, bool removeInverseOf,
6412
23
                                        bool nameRequired) {
6413
23
    PropertyMap map;
6414
6415
23
    if (j.contains("name") || nameRequired) {
6416
23
        std::string name(getName(j));
6417
23
        if (removeInverseOf && starts_with(name, "Inverse of ")) {
6418
0
            name = name.substr(strlen("Inverse of "));
6419
0
        }
6420
23
        map.set(IdentifiedObject::NAME_KEY, name);
6421
23
    }
6422
6423
23
    if (j.contains("ids")) {
6424
0
        auto idsJ = getArray(j, "ids");
6425
0
        auto identifiers = ArrayOfBaseObject::create();
6426
0
        for (const auto &idJ : idsJ) {
6427
0
            if (!idJ.is_object()) {
6428
0
                throw ParsingException(
6429
0
                    "Unexpected type for value of \"ids\" child");
6430
0
            }
6431
0
            identifiers->add(buildId(j, idJ, removeInverseOf));
6432
0
        }
6433
0
        map.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
6434
23
    } else if (j.contains("id")) {
6435
0
        auto idJ = getObject(j, "id");
6436
0
        auto identifiers = ArrayOfBaseObject::create();
6437
0
        identifiers->add(buildId(j, idJ, removeInverseOf));
6438
0
        map.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
6439
0
    }
6440
6441
23
    if (j.contains("remarks")) {
6442
0
        map.set(IdentifiedObject::REMARKS_KEY, getString(j, "remarks"));
6443
0
    }
6444
6445
23
    if (j.contains("usages")) {
6446
0
        ArrayOfBaseObjectNNPtr array = ArrayOfBaseObject::create();
6447
0
        auto usages = j["usages"];
6448
0
        if (!usages.is_array()) {
6449
0
            throw ParsingException("Unexpected type for value of \"usages\"");
6450
0
        }
6451
0
        for (const auto &usage : usages) {
6452
0
            if (!usage.is_object()) {
6453
0
                throw ParsingException(
6454
0
                    "Unexpected type for value of \"usages\" child");
6455
0
            }
6456
0
            auto objectDomain = buildObjectDomain(usage);
6457
0
            if (!objectDomain) {
6458
0
                throw ParsingException("missing children in \"usages\" child");
6459
0
            }
6460
0
            array->add(NN_NO_CHECK(objectDomain));
6461
0
        }
6462
0
        if (!array->empty()) {
6463
0
            map.set(ObjectUsage::OBJECT_DOMAIN_KEY, array);
6464
0
        }
6465
23
    } else {
6466
23
        auto objectDomain = buildObjectDomain(j);
6467
23
        if (objectDomain) {
6468
0
            map.set(ObjectUsage::OBJECT_DOMAIN_KEY, NN_NO_CHECK(objectDomain));
6469
0
        }
6470
23
    }
6471
6472
23
    return map;
6473
23
}
6474
6475
// ---------------------------------------------------------------------------
6476
6477
BaseObjectNNPtr JSONParser::create(const json &j)
6478
6479
119
{
6480
119
    if (!j.is_object()) {
6481
0
        throw ParsingException("JSON object expected");
6482
0
    }
6483
119
    auto type = getString(j, "type");
6484
119
    if (type == "GeographicCRS") {
6485
25
        return buildGeographicCRS(j);
6486
25
    }
6487
94
    if (type == "GeodeticCRS") {
6488
0
        return buildGeodeticCRS(j);
6489
0
    }
6490
94
    if (type == "ProjectedCRS") {
6491
0
        return buildProjectedCRS(j);
6492
0
    }
6493
94
    if (type == "VerticalCRS") {
6494
0
        return buildVerticalCRS(j);
6495
0
    }
6496
94
    if (type == "CompoundCRS") {
6497
0
        return buildCompoundCRS(j);
6498
0
    }
6499
94
    if (type == "BoundCRS") {
6500
0
        return buildBoundCRS(j);
6501
0
    }
6502
94
    if (type == "EngineeringCRS") {
6503
0
        return buildCRS<EngineeringCRS>(j, &JSONParser::buildEngineeringDatum);
6504
0
    }
6505
94
    if (type == "ParametricCRS") {
6506
0
        return buildCRS<ParametricCRS,
6507
0
                        decltype(&JSONParser::buildParametricDatum),
6508
0
                        ParametricCS>(j, &JSONParser::buildParametricDatum);
6509
0
    }
6510
94
    if (type == "TemporalCRS") {
6511
0
        return buildCRS<TemporalCRS, decltype(&JSONParser::buildTemporalDatum),
6512
0
                        TemporalCS>(j, &JSONParser::buildTemporalDatum);
6513
0
    }
6514
94
    if (type == "DerivedGeodeticCRS") {
6515
0
        auto baseCRSObj = create(getObject(j, "base_crs"));
6516
0
        auto baseCRS = util::nn_dynamic_pointer_cast<GeodeticCRS>(baseCRSObj);
6517
0
        if (!baseCRS) {
6518
0
            throw ParsingException("base_crs not of expected type");
6519
0
        }
6520
0
        auto cs = buildCS(getObject(j, "coordinate_system"));
6521
0
        auto conv = buildConversion(getObject(j, "conversion"));
6522
0
        auto csCartesian = util::nn_dynamic_pointer_cast<CartesianCS>(cs);
6523
0
        if (csCartesian)
6524
0
            return DerivedGeodeticCRS::create(buildProperties(j),
6525
0
                                              NN_NO_CHECK(baseCRS), conv,
6526
0
                                              NN_NO_CHECK(csCartesian));
6527
0
        auto csSpherical = util::nn_dynamic_pointer_cast<SphericalCS>(cs);
6528
0
        if (csSpherical)
6529
0
            return DerivedGeodeticCRS::create(buildProperties(j),
6530
0
                                              NN_NO_CHECK(baseCRS), conv,
6531
0
                                              NN_NO_CHECK(csSpherical));
6532
0
        throw ParsingException("coordinate_system not of expected type");
6533
0
    }
6534
94
    if (type == "DerivedGeographicCRS") {
6535
0
        return buildDerivedCRS<DerivedGeographicCRS, GeodeticCRS,
6536
0
                               EllipsoidalCS>(j);
6537
0
    }
6538
94
    if (type == "DerivedProjectedCRS") {
6539
0
        return buildDerivedCRS<DerivedProjectedCRS, ProjectedCRS>(j);
6540
0
    }
6541
94
    if (type == "DerivedVerticalCRS") {
6542
0
        return buildDerivedCRS<DerivedVerticalCRS, VerticalCRS, VerticalCS>(j);
6543
0
    }
6544
94
    if (type == "DerivedEngineeringCRS") {
6545
0
        return buildDerivedCRS<DerivedEngineeringCRS, EngineeringCRS>(j);
6546
0
    }
6547
94
    if (type == "DerivedParametricCRS") {
6548
0
        return buildDerivedCRS<DerivedParametricCRS, ParametricCRS,
6549
0
                               ParametricCS>(j);
6550
0
    }
6551
94
    if (type == "DerivedTemporalCRS") {
6552
0
        return buildDerivedCRS<DerivedTemporalCRS, TemporalCRS, TemporalCS>(j);
6553
0
    }
6554
94
    if (type == "DatumEnsemble") {
6555
0
        return buildDatumEnsemble(j);
6556
0
    }
6557
94
    if (type == "GeodeticReferenceFrame") {
6558
0
        return buildGeodeticReferenceFrame(j);
6559
0
    }
6560
94
    if (type == "VerticalReferenceFrame") {
6561
1
        return buildVerticalReferenceFrame(j);
6562
1
    }
6563
93
    if (type == "DynamicGeodeticReferenceFrame") {
6564
0
        return buildDynamicGeodeticReferenceFrame(j);
6565
0
    }
6566
93
    if (type == "DynamicVerticalReferenceFrame") {
6567
0
        return buildDynamicVerticalReferenceFrame(j);
6568
0
    }
6569
93
    if (type == "EngineeringDatum") {
6570
22
        return buildEngineeringDatum(j);
6571
22
    }
6572
71
    if (type == "ParametricDatum") {
6573
0
        return buildParametricDatum(j);
6574
0
    }
6575
71
    if (type == "TemporalDatum") {
6576
0
        return buildTemporalDatum(j);
6577
0
    }
6578
71
    if (type == "Ellipsoid") {
6579
0
        return buildEllipsoid(j);
6580
0
    }
6581
71
    if (type == "PrimeMeridian") {
6582
0
        return buildPrimeMeridian(j);
6583
0
    }
6584
71
    if (type == "CoordinateSystem") {
6585
0
        return buildCS(j);
6586
0
    }
6587
71
    if (type == "Conversion") {
6588
0
        return buildConversion(j);
6589
0
    }
6590
71
    if (type == "Transformation") {
6591
0
        return buildTransformation(j);
6592
0
    }
6593
71
    if (type == "PointMotionOperation") {
6594
0
        return buildPointMotionOperation(j);
6595
0
    }
6596
71
    if (type == "ConcatenatedOperation") {
6597
0
        return buildConcatenatedOperation(j);
6598
0
    }
6599
71
    if (type == "CoordinateMetadata") {
6600
0
        return buildCoordinateMetadata(j);
6601
0
    }
6602
71
    if (type == "Axis") {
6603
0
        return buildAxis(j);
6604
0
    }
6605
71
    throw ParsingException("Unsupported value of \"type\"");
6606
71
}
6607
6608
// ---------------------------------------------------------------------------
6609
6610
void JSONParser::buildGeodeticDatumOrDatumEnsemble(
6611
    const json &j, GeodeticReferenceFramePtr &datum,
6612
25
    DatumEnsemblePtr &datumEnsemble) {
6613
25
    if (j.contains("datum")) {
6614
23
        auto datumJ = getObject(j, "datum");
6615
6616
23
        if (j.contains("deformation_models")) {
6617
0
            auto deformationModelsJ = getArray(j, "deformation_models");
6618
0
            if (!deformationModelsJ.empty()) {
6619
0
                const auto &deformationModelJ = deformationModelsJ[0];
6620
0
                deformationModelName_ = getString(deformationModelJ, "name");
6621
                // We can handle only one for now
6622
0
            }
6623
0
        }
6624
6625
23
        datum = util::nn_dynamic_pointer_cast<GeodeticReferenceFrame>(
6626
23
            create(datumJ));
6627
23
        if (!datum) {
6628
0
            throw ParsingException("datum of wrong type");
6629
0
        }
6630
6631
23
        deformationModelName_.clear();
6632
23
    } else {
6633
2
        datumEnsemble =
6634
2
            buildDatumEnsemble(getObject(j, "datum_ensemble")).as_nullable();
6635
2
    }
6636
25
}
6637
6638
// ---------------------------------------------------------------------------
6639
6640
25
GeographicCRSNNPtr JSONParser::buildGeographicCRS(const json &j) {
6641
25
    GeodeticReferenceFramePtr datum;
6642
25
    DatumEnsemblePtr datumEnsemble;
6643
25
    buildGeodeticDatumOrDatumEnsemble(j, datum, datumEnsemble);
6644
25
    auto csJ = getObject(j, "coordinate_system");
6645
25
    auto ellipsoidalCS =
6646
25
        util::nn_dynamic_pointer_cast<EllipsoidalCS>(buildCS(csJ));
6647
25
    if (!ellipsoidalCS) {
6648
0
        throw ParsingException("expected an ellipsoidal CS");
6649
0
    }
6650
25
    return GeographicCRS::create(buildProperties(j), datum, datumEnsemble,
6651
25
                                 NN_NO_CHECK(ellipsoidalCS));
6652
25
}
6653
6654
// ---------------------------------------------------------------------------
6655
6656
0
GeodeticCRSNNPtr JSONParser::buildGeodeticCRS(const json &j) {
6657
0
    GeodeticReferenceFramePtr datum;
6658
0
    DatumEnsemblePtr datumEnsemble;
6659
0
    buildGeodeticDatumOrDatumEnsemble(j, datum, datumEnsemble);
6660
0
    auto csJ = getObject(j, "coordinate_system");
6661
0
    auto cs = buildCS(csJ);
6662
0
    auto props = buildProperties(j);
6663
0
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
6664
0
    if (cartesianCS) {
6665
0
        if (cartesianCS->axisList().size() != 3) {
6666
0
            throw ParsingException(
6667
0
                "Cartesian CS for a GeodeticCRS should have 3 axis");
6668
0
        }
6669
0
        try {
6670
0
            return GeodeticCRS::create(props, datum, datumEnsemble,
6671
0
                                       NN_NO_CHECK(cartesianCS));
6672
0
        } catch (const util::Exception &e) {
6673
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
6674
0
                                   e.what());
6675
0
        }
6676
0
    }
6677
6678
0
    auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs);
6679
0
    if (sphericalCS) {
6680
0
        try {
6681
0
            return GeodeticCRS::create(props, datum, datumEnsemble,
6682
0
                                       NN_NO_CHECK(sphericalCS));
6683
0
        } catch (const util::Exception &e) {
6684
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
6685
0
                                   e.what());
6686
0
        }
6687
0
    }
6688
0
    throw ParsingException("expected a Cartesian or spherical CS");
6689
0
}
6690
6691
// ---------------------------------------------------------------------------
6692
6693
0
ProjectedCRSNNPtr JSONParser::buildProjectedCRS(const json &j) {
6694
0
    auto jBaseCRS = getObject(j, "base_crs");
6695
0
    auto jBaseCS = getObject(jBaseCRS, "coordinate_system");
6696
0
    auto baseCS = buildCS(jBaseCS);
6697
0
    auto baseCRS = dynamic_cast<EllipsoidalCS *>(baseCS.get()) != nullptr
6698
0
                       ? util::nn_static_pointer_cast<GeodeticCRS>(
6699
0
                             buildGeographicCRS(jBaseCRS))
6700
0
                       : buildGeodeticCRS(jBaseCRS);
6701
0
    auto csJ = getObject(j, "coordinate_system");
6702
0
    auto cartesianCS = util::nn_dynamic_pointer_cast<CartesianCS>(buildCS(csJ));
6703
0
    if (!cartesianCS) {
6704
0
        throw ParsingException("expected a Cartesian CS");
6705
0
    }
6706
0
    auto conv = buildConversion(getObject(j, "conversion"));
6707
0
    return ProjectedCRS::create(buildProperties(j), baseCRS, conv,
6708
0
                                NN_NO_CHECK(cartesianCS));
6709
0
}
6710
6711
// ---------------------------------------------------------------------------
6712
6713
0
VerticalCRSNNPtr JSONParser::buildVerticalCRS(const json &j) {
6714
0
    VerticalReferenceFramePtr datum;
6715
0
    DatumEnsemblePtr datumEnsemble;
6716
0
    if (j.contains("datum")) {
6717
0
        auto datumJ = getObject(j, "datum");
6718
6719
0
        if (j.contains("deformation_models")) {
6720
0
            auto deformationModelsJ = getArray(j, "deformation_models");
6721
0
            if (!deformationModelsJ.empty()) {
6722
0
                const auto &deformationModelJ = deformationModelsJ[0];
6723
0
                deformationModelName_ = getString(deformationModelJ, "name");
6724
                // We can handle only one for now
6725
0
            }
6726
0
        }
6727
6728
0
        datum = util::nn_dynamic_pointer_cast<VerticalReferenceFrame>(
6729
0
            create(datumJ));
6730
0
        if (!datum) {
6731
0
            throw ParsingException("datum of wrong type");
6732
0
        }
6733
0
    } else {
6734
0
        datumEnsemble =
6735
0
            buildDatumEnsemble(getObject(j, "datum_ensemble")).as_nullable();
6736
0
    }
6737
0
    auto csJ = getObject(j, "coordinate_system");
6738
0
    auto verticalCS = util::nn_dynamic_pointer_cast<VerticalCS>(buildCS(csJ));
6739
0
    if (!verticalCS) {
6740
0
        throw ParsingException("expected a vertical CS");
6741
0
    }
6742
6743
0
    const auto buildGeoidModel = [this, &datum, &datumEnsemble,
6744
0
                                  &verticalCS](const json &geoidModelJ) {
6745
0
        auto propsModel = buildProperties(geoidModelJ);
6746
0
        const auto dummyCRS = VerticalCRS::create(
6747
0
            PropertyMap(), datum, datumEnsemble, NN_NO_CHECK(verticalCS));
6748
0
        CRSPtr interpolationCRS;
6749
0
        if (geoidModelJ.contains("interpolation_crs")) {
6750
0
            auto interpolationCRSJ =
6751
0
                getObject(geoidModelJ, "interpolation_crs");
6752
0
            interpolationCRS = buildCRS(interpolationCRSJ).as_nullable();
6753
0
        }
6754
0
        return Transformation::create(
6755
0
            propsModel, dummyCRS,
6756
0
            GeographicCRS::EPSG_4979, // arbitrarily chosen. Ignored,
6757
0
            interpolationCRS,
6758
0
            OperationMethod::create(PropertyMap(),
6759
0
                                    std::vector<OperationParameterNNPtr>()),
6760
0
            {}, {});
6761
0
    };
6762
6763
0
    auto props = buildProperties(j);
6764
0
    if (j.contains("geoid_model")) {
6765
0
        auto geoidModelJ = getObject(j, "geoid_model");
6766
0
        props.set("GEOID_MODEL", buildGeoidModel(geoidModelJ));
6767
0
    } else if (j.contains("geoid_models")) {
6768
0
        auto geoidModelsJ = getArray(j, "geoid_models");
6769
0
        auto geoidModels = ArrayOfBaseObject::create();
6770
0
        for (const auto &geoidModelJ : geoidModelsJ) {
6771
0
            geoidModels->add(buildGeoidModel(geoidModelJ));
6772
0
        }
6773
0
        props.set("GEOID_MODEL", geoidModels);
6774
0
    }
6775
6776
0
    return VerticalCRS::create(props, datum, datumEnsemble,
6777
0
                               NN_NO_CHECK(verticalCS));
6778
0
}
6779
6780
// ---------------------------------------------------------------------------
6781
6782
0
CRSNNPtr JSONParser::buildCRS(const json &j) {
6783
0
    auto crs = util::nn_dynamic_pointer_cast<CRS>(create(j));
6784
0
    if (crs) {
6785
0
        return NN_NO_CHECK(crs);
6786
0
    }
6787
0
    throw ParsingException("Object is not a CRS");
6788
0
}
6789
6790
// ---------------------------------------------------------------------------
6791
6792
0
CompoundCRSNNPtr JSONParser::buildCompoundCRS(const json &j) {
6793
0
    auto componentsJ = getArray(j, "components");
6794
0
    std::vector<CRSNNPtr> components;
6795
0
    for (const auto &componentJ : componentsJ) {
6796
0
        if (!componentJ.is_object()) {
6797
0
            throw ParsingException(
6798
0
                "Unexpected type for a \"components\" child");
6799
0
        }
6800
0
        components.push_back(buildCRS(componentJ));
6801
0
    }
6802
0
    return CompoundCRS::create(buildProperties(j), components);
6803
0
}
6804
6805
// ---------------------------------------------------------------------------
6806
6807
0
ConversionNNPtr JSONParser::buildConversion(const json &j) {
6808
0
    auto methodJ = getObject(j, "method");
6809
0
    auto convProps = buildProperties(j);
6810
0
    auto methodProps = buildProperties(methodJ);
6811
0
    if (!j.contains("parameters")) {
6812
0
        return Conversion::create(convProps, methodProps, {}, {});
6813
0
    }
6814
6815
0
    auto parametersJ = getArray(j, "parameters");
6816
0
    std::vector<OperationParameterNNPtr> parameters;
6817
0
    std::vector<ParameterValueNNPtr> values;
6818
0
    for (const auto &param : parametersJ) {
6819
0
        if (!param.is_object()) {
6820
0
            throw ParsingException(
6821
0
                "Unexpected type for a \"parameters\" child");
6822
0
        }
6823
0
        parameters.emplace_back(
6824
0
            OperationParameter::create(buildProperties(param)));
6825
0
        if (isIntegerParameter(parameters.back())) {
6826
0
            values.emplace_back(
6827
0
                ParameterValue::create(getInteger(param, "value")));
6828
0
        } else {
6829
0
            values.emplace_back(ParameterValue::create(getMeasure(param)));
6830
0
        }
6831
0
    }
6832
6833
0
    auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
6834
0
        dbContext_, parameters, values);
6835
6836
0
    std::string convName;
6837
0
    std::string methodName;
6838
0
    if (convProps.getStringValue(IdentifiedObject::NAME_KEY, convName) &&
6839
0
        methodProps.getStringValue(IdentifiedObject::NAME_KEY, methodName) &&
6840
0
        starts_with(convName, "Inverse of ") &&
6841
0
        starts_with(methodName, "Inverse of ")) {
6842
6843
0
        auto invConvProps = buildProperties(j, true);
6844
0
        auto invMethodProps = buildProperties(methodJ, true);
6845
0
        auto conv = NN_NO_CHECK(util::nn_dynamic_pointer_cast<Conversion>(
6846
0
            Conversion::create(invConvProps, invMethodProps, parameters, values)
6847
0
                ->inverse()));
6848
0
        if (interpolationCRS)
6849
0
            conv->setInterpolationCRS(interpolationCRS);
6850
0
        return conv;
6851
0
    }
6852
0
    auto conv = Conversion::create(convProps, methodProps, parameters, values);
6853
0
    if (interpolationCRS)
6854
0
        conv->setInterpolationCRS(interpolationCRS);
6855
0
    return conv;
6856
0
}
6857
6858
// ---------------------------------------------------------------------------
6859
6860
0
BoundCRSNNPtr JSONParser::buildBoundCRS(const json &j) {
6861
6862
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
6863
0
    auto targetCRS = buildCRS(getObject(j, "target_crs"));
6864
0
    auto transformationJ = getObject(j, "transformation");
6865
0
    auto methodJ = getObject(transformationJ, "method");
6866
0
    auto parametersJ = getArray(transformationJ, "parameters");
6867
0
    std::vector<OperationParameterNNPtr> parameters;
6868
0
    std::vector<ParameterValueNNPtr> values;
6869
0
    for (const auto &param : parametersJ) {
6870
0
        if (!param.is_object()) {
6871
0
            throw ParsingException(
6872
0
                "Unexpected type for a \"parameters\" child");
6873
0
        }
6874
0
        parameters.emplace_back(
6875
0
            OperationParameter::create(buildProperties(param)));
6876
0
        if (param.contains("value")) {
6877
0
            auto v = param["value"];
6878
0
            if (v.is_string()) {
6879
0
                values.emplace_back(
6880
0
                    ParameterValue::createFilename(v.get<std::string>()));
6881
0
                continue;
6882
0
            }
6883
0
        }
6884
0
        values.emplace_back(ParameterValue::create(getMeasure(param)));
6885
0
    }
6886
6887
0
    const auto transformation = [&]() {
6888
        // Unofficial extension / mostly for testing purposes.
6889
        // Allow to explicitly specify the source_crs of the transformation of
6890
        // the boundCRS if it is not the source_crs of the BoundCRS. Cf
6891
        // https://github.com/OSGeo/PROJ/issues/3428 use case
6892
0
        if (transformationJ.contains("source_crs")) {
6893
0
            auto sourceTransformationCRS =
6894
0
                buildCRS(getObject(transformationJ, "source_crs"));
6895
0
            auto interpolationCRS =
6896
0
                dealWithEPSGCodeForInterpolationCRSParameter(
6897
0
                    dbContext_, parameters, values);
6898
0
            return Transformation::create(
6899
0
                buildProperties(transformationJ), sourceTransformationCRS,
6900
0
                targetCRS, interpolationCRS, buildProperties(methodJ),
6901
0
                parameters, values, std::vector<PositionalAccuracyNNPtr>());
6902
0
        }
6903
6904
0
        return buildTransformationForBoundCRS(
6905
0
            dbContext_, buildProperties(transformationJ),
6906
0
            buildProperties(methodJ), sourceCRS, targetCRS, parameters, values);
6907
0
    }();
6908
6909
0
    return BoundCRS::create(buildProperties(j,
6910
0
                                            /* removeInverseOf= */ false,
6911
0
                                            /* nameRequired=*/false),
6912
0
                            sourceCRS, targetCRS, transformation);
6913
0
}
6914
6915
// ---------------------------------------------------------------------------
6916
6917
0
TransformationNNPtr JSONParser::buildTransformation(const json &j) {
6918
6919
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
6920
0
    auto targetCRS = buildCRS(getObject(j, "target_crs"));
6921
0
    auto methodJ = getObject(j, "method");
6922
0
    auto parametersJ = getArray(j, "parameters");
6923
0
    std::vector<OperationParameterNNPtr> parameters;
6924
0
    std::vector<ParameterValueNNPtr> values;
6925
0
    for (const auto &param : parametersJ) {
6926
0
        if (!param.is_object()) {
6927
0
            throw ParsingException(
6928
0
                "Unexpected type for a \"parameters\" child");
6929
0
        }
6930
0
        parameters.emplace_back(
6931
0
            OperationParameter::create(buildProperties(param)));
6932
0
        if (param.contains("value")) {
6933
0
            auto v = param["value"];
6934
0
            if (v.is_string()) {
6935
0
                values.emplace_back(
6936
0
                    ParameterValue::createFilename(v.get<std::string>()));
6937
0
                continue;
6938
0
            }
6939
0
        }
6940
0
        values.emplace_back(ParameterValue::create(getMeasure(param)));
6941
0
    }
6942
0
    CRSPtr interpolationCRS;
6943
0
    if (j.contains("interpolation_crs")) {
6944
0
        interpolationCRS =
6945
0
            buildCRS(getObject(j, "interpolation_crs")).as_nullable();
6946
0
    }
6947
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
6948
0
    if (j.contains("accuracy")) {
6949
0
        accuracies.push_back(
6950
0
            PositionalAccuracy::create(getString(j, "accuracy")));
6951
0
    }
6952
6953
0
    return Transformation::create(buildProperties(j), sourceCRS, targetCRS,
6954
0
                                  interpolationCRS, buildProperties(methodJ),
6955
0
                                  parameters, values, accuracies);
6956
0
}
6957
6958
// ---------------------------------------------------------------------------
6959
6960
0
PointMotionOperationNNPtr JSONParser::buildPointMotionOperation(const json &j) {
6961
6962
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
6963
0
    auto methodJ = getObject(j, "method");
6964
0
    auto parametersJ = getArray(j, "parameters");
6965
0
    std::vector<OperationParameterNNPtr> parameters;
6966
0
    std::vector<ParameterValueNNPtr> values;
6967
0
    for (const auto &param : parametersJ) {
6968
0
        if (!param.is_object()) {
6969
0
            throw ParsingException(
6970
0
                "Unexpected type for a \"parameters\" child");
6971
0
        }
6972
0
        parameters.emplace_back(
6973
0
            OperationParameter::create(buildProperties(param)));
6974
0
        if (param.contains("value")) {
6975
0
            auto v = param["value"];
6976
0
            if (v.is_string()) {
6977
0
                values.emplace_back(
6978
0
                    ParameterValue::createFilename(v.get<std::string>()));
6979
0
                continue;
6980
0
            }
6981
0
        }
6982
0
        values.emplace_back(ParameterValue::create(getMeasure(param)));
6983
0
    }
6984
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
6985
0
    if (j.contains("accuracy")) {
6986
0
        accuracies.push_back(
6987
0
            PositionalAccuracy::create(getString(j, "accuracy")));
6988
0
    }
6989
6990
0
    return PointMotionOperation::create(buildProperties(j), sourceCRS,
6991
0
                                        buildProperties(methodJ), parameters,
6992
0
                                        values, accuracies);
6993
0
}
6994
6995
// ---------------------------------------------------------------------------
6996
6997
ConcatenatedOperationNNPtr
6998
0
JSONParser::buildConcatenatedOperation(const json &j) {
6999
7000
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
7001
0
    auto targetCRS = buildCRS(getObject(j, "target_crs"));
7002
0
    auto stepsJ = getArray(j, "steps");
7003
0
    std::vector<CoordinateOperationNNPtr> operations;
7004
0
    for (const auto &stepJ : stepsJ) {
7005
0
        if (!stepJ.is_object()) {
7006
0
            throw ParsingException("Unexpected type for a \"steps\" child");
7007
0
        }
7008
0
        auto op = nn_dynamic_pointer_cast<CoordinateOperation>(create(stepJ));
7009
0
        if (!op) {
7010
0
            throw ParsingException("Invalid content in a \"steps\" child");
7011
0
        }
7012
0
        operations.emplace_back(NN_NO_CHECK(op));
7013
0
    }
7014
7015
0
    ConcatenatedOperation::fixSteps(sourceCRS, targetCRS, operations,
7016
0
                                    dbContext_,
7017
0
                                    /* fixDirectionAllowed = */ true);
7018
7019
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
7020
0
    if (j.contains("accuracy")) {
7021
0
        accuracies.push_back(
7022
0
            PositionalAccuracy::create(getString(j, "accuracy")));
7023
0
    }
7024
7025
0
    try {
7026
0
        return ConcatenatedOperation::create(buildProperties(j), operations,
7027
0
                                             accuracies);
7028
0
    } catch (const InvalidOperation &e) {
7029
0
        throw ParsingException(
7030
0
            std::string("Cannot build concatenated operation: ") + e.what());
7031
0
    }
7032
0
}
7033
7034
// ---------------------------------------------------------------------------
7035
7036
0
CoordinateMetadataNNPtr JSONParser::buildCoordinateMetadata(const json &j) {
7037
7038
0
    auto crs = buildCRS(getObject(j, "crs"));
7039
0
    if (j.contains("coordinateEpoch")) {
7040
0
        auto jCoordinateEpoch = j["coordinateEpoch"];
7041
0
        if (jCoordinateEpoch.is_number()) {
7042
0
            return CoordinateMetadata::create(
7043
0
                crs, jCoordinateEpoch.get<double>(), dbContext_);
7044
0
        }
7045
0
        throw ParsingException(
7046
0
            "Unexpected type for value of \"coordinateEpoch\"");
7047
0
    }
7048
0
    return CoordinateMetadata::create(crs);
7049
0
}
7050
7051
// ---------------------------------------------------------------------------
7052
7053
0
MeridianNNPtr JSONParser::buildMeridian(const json &j) {
7054
0
    if (!j.contains("longitude")) {
7055
0
        throw ParsingException("Missing \"longitude\" key");
7056
0
    }
7057
0
    auto longitude = j["longitude"];
7058
0
    if (longitude.is_number()) {
7059
0
        return Meridian::create(
7060
0
            Angle(longitude.get<double>(), UnitOfMeasure::DEGREE));
7061
0
    } else if (longitude.is_object()) {
7062
0
        return Meridian::create(Angle(getMeasure(longitude)));
7063
0
    }
7064
0
    throw ParsingException("Unexpected type for value of \"longitude\"");
7065
0
}
7066
7067
// ---------------------------------------------------------------------------
7068
7069
0
CoordinateSystemAxisNNPtr JSONParser::buildAxis(const json &j) {
7070
0
    auto dirString = getString(j, "direction");
7071
0
    auto abbreviation = getString(j, "abbreviation");
7072
0
    const UnitOfMeasure unit(
7073
0
        j.contains("unit")
7074
0
            ? getUnit(j, "unit")
7075
0
            : UnitOfMeasure(std::string(), 1.0, UnitOfMeasure::Type::NONE));
7076
0
    auto direction = AxisDirection::valueOf(dirString);
7077
0
    if (!direction) {
7078
0
        throw ParsingException(concat("unhandled axis direction: ", dirString));
7079
0
    }
7080
0
    auto meridian = j.contains("meridian")
7081
0
                        ? buildMeridian(getObject(j, "meridian")).as_nullable()
7082
0
                        : nullptr;
7083
7084
0
    util::optional<double> minVal;
7085
0
    if (j.contains("minimum_value")) {
7086
0
        minVal = getNumber(j, "minimum_value");
7087
0
    }
7088
7089
0
    util::optional<double> maxVal;
7090
0
    if (j.contains("maximum_value")) {
7091
0
        maxVal = getNumber(j, "maximum_value");
7092
0
    }
7093
7094
0
    util::optional<RangeMeaning> rangeMeaning;
7095
0
    if (j.contains("range_meaning")) {
7096
0
        const auto val = getString(j, "range_meaning");
7097
0
        const RangeMeaning *meaning = RangeMeaning::valueOf(val);
7098
0
        if (meaning == nullptr) {
7099
0
            throw ParsingException(
7100
0
                concat("buildAxis: invalid range_meaning value: ", val));
7101
0
        }
7102
0
        rangeMeaning = util::optional<RangeMeaning>(*meaning);
7103
0
    }
7104
7105
0
    return CoordinateSystemAxis::create(buildProperties(j), abbreviation,
7106
0
                                        *direction, unit, minVal, maxVal,
7107
0
                                        rangeMeaning, meridian);
7108
0
}
7109
7110
// ---------------------------------------------------------------------------
7111
7112
0
CoordinateSystemNNPtr JSONParser::buildCS(const json &j) {
7113
0
    auto subtype = getString(j, "subtype");
7114
0
    if (!j.contains("axis")) {
7115
0
        throw ParsingException("Missing \"axis\" key");
7116
0
    }
7117
0
    auto jAxisList = j["axis"];
7118
0
    if (!jAxisList.is_array()) {
7119
0
        throw ParsingException("Unexpected type for value of \"axis\"");
7120
0
    }
7121
0
    std::vector<CoordinateSystemAxisNNPtr> axisList;
7122
0
    for (const auto &axis : jAxisList) {
7123
0
        if (!axis.is_object()) {
7124
0
            throw ParsingException(
7125
0
                "Unexpected type for value of a \"axis\" member");
7126
0
        }
7127
0
        axisList.emplace_back(buildAxis(axis));
7128
0
    }
7129
0
    const PropertyMap &csMap = emptyPropertyMap;
7130
0
    const auto axisCount = axisList.size();
7131
0
    if (subtype == EllipsoidalCS::WKT2_TYPE) {
7132
0
        if (axisCount == 2) {
7133
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1]);
7134
0
        }
7135
0
        if (axisCount == 3) {
7136
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1],
7137
0
                                         axisList[2]);
7138
0
        }
7139
0
        throw ParsingException("Expected 2 or 3 axis");
7140
0
    }
7141
0
    if (subtype == CartesianCS::WKT2_TYPE) {
7142
0
        if (axisCount == 2) {
7143
0
            if (axisList[0]->unit() != axisList[1]->unit()) {
7144
0
                emitRecoverableWarning(
7145
0
                    "All axis of a CartesianCS must have the same unit");
7146
0
            }
7147
0
            return CartesianCS::create(csMap, axisList[0], axisList[1],
7148
0
                                       /* enforceSameUnit = */ false);
7149
0
        }
7150
0
        if (axisCount == 3) {
7151
0
            if (axisList[0]->unit() != axisList[1]->unit() ||
7152
0
                axisList[0]->unit() != axisList[2]->unit()) {
7153
0
                emitRecoverableWarning(
7154
0
                    "All axis of a CartesianCS must have the same unit");
7155
0
            }
7156
0
            return CartesianCS::create(csMap, axisList[0], axisList[1],
7157
0
                                       axisList[2],
7158
0
                                       /* enforceSameUnit = */ false);
7159
0
        }
7160
0
        throw ParsingException("Expected 2 or 3 axis");
7161
0
    }
7162
0
    if (subtype == AffineCS::WKT2_TYPE) {
7163
0
        if (axisCount == 2) {
7164
0
            return AffineCS::create(csMap, axisList[0], axisList[1]);
7165
0
        }
7166
0
        if (axisCount == 3) {
7167
0
            return AffineCS::create(csMap, axisList[0], axisList[1],
7168
0
                                    axisList[2]);
7169
0
        }
7170
0
        throw ParsingException("Expected 2 or 3 axis");
7171
0
    }
7172
0
    if (subtype == VerticalCS::WKT2_TYPE) {
7173
0
        if (axisCount == 1) {
7174
0
            return VerticalCS::create(csMap, axisList[0]);
7175
0
        }
7176
0
        throw ParsingException("Expected 1 axis");
7177
0
    }
7178
0
    if (subtype == SphericalCS::WKT2_TYPE) {
7179
0
        if (axisCount == 2) {
7180
            // Extension to ISO19111 to support (planet)-ocentric CS with
7181
            // geocentric latitude
7182
0
            return SphericalCS::create(csMap, axisList[0], axisList[1]);
7183
0
        } else if (axisCount == 3) {
7184
0
            return SphericalCS::create(csMap, axisList[0], axisList[1],
7185
0
                                       axisList[2]);
7186
0
        }
7187
0
        throw ParsingException("Expected 2 or 3 axis");
7188
0
    }
7189
0
    if (subtype == OrdinalCS::WKT2_TYPE) {
7190
0
        return OrdinalCS::create(csMap, axisList);
7191
0
    }
7192
0
    if (subtype == ParametricCS::WKT2_TYPE) {
7193
0
        if (axisCount == 1) {
7194
0
            return ParametricCS::create(csMap, axisList[0]);
7195
0
        }
7196
0
        throw ParsingException("Expected 1 axis");
7197
0
    }
7198
0
    if (subtype == DateTimeTemporalCS::WKT2_2019_TYPE) {
7199
0
        if (axisCount == 1) {
7200
0
            return DateTimeTemporalCS::create(csMap, axisList[0]);
7201
0
        }
7202
0
        throw ParsingException("Expected 1 axis");
7203
0
    }
7204
0
    if (subtype == TemporalCountCS::WKT2_2019_TYPE) {
7205
0
        if (axisCount == 1) {
7206
0
            return TemporalCountCS::create(csMap, axisList[0]);
7207
0
        }
7208
0
        throw ParsingException("Expected 1 axis");
7209
0
    }
7210
0
    if (subtype == TemporalMeasureCS::WKT2_2019_TYPE) {
7211
0
        if (axisCount == 1) {
7212
0
            return TemporalMeasureCS::create(csMap, axisList[0]);
7213
0
        }
7214
0
        throw ParsingException("Expected 1 axis");
7215
0
    }
7216
0
    throw ParsingException("Unhandled value for subtype");
7217
0
}
7218
7219
// ---------------------------------------------------------------------------
7220
7221
0
DatumEnsembleNNPtr JSONParser::buildDatumEnsemble(const json &j) {
7222
0
    std::vector<DatumNNPtr> datums;
7223
0
    if (j.contains("members")) {
7224
0
        auto membersJ = getArray(j, "members");
7225
0
        const bool hasEllipsoid(j.contains("ellipsoid"));
7226
0
        for (const auto &memberJ : membersJ) {
7227
0
            if (!memberJ.is_object()) {
7228
0
                throw ParsingException(
7229
0
                    "Unexpected type for value of a \"members\" member");
7230
0
            }
7231
0
            auto datumName(getName(memberJ));
7232
0
            bool datumAdded = false;
7233
0
            if (dbContext_ && memberJ.contains("id")) {
7234
0
                auto id = getObject(memberJ, "id");
7235
0
                auto authority = getString(id, "authority");
7236
0
                auto authFactory = AuthorityFactory::create(
7237
0
                    NN_NO_CHECK(dbContext_), authority);
7238
0
                auto code = id["code"];
7239
0
                std::string codeStr;
7240
0
                if (code.is_string()) {
7241
0
                    codeStr = code.get<std::string>();
7242
0
                } else if (code.is_number_integer()) {
7243
0
                    codeStr = internal::toString(code.get<int>());
7244
0
                } else {
7245
0
                    throw ParsingException(
7246
0
                        "Unexpected type for value of \"code\"");
7247
0
                }
7248
0
                try {
7249
0
                    datums.push_back(authFactory->createDatum(codeStr));
7250
0
                    datumAdded = true;
7251
0
                } catch (const std::exception &) {
7252
                    // Silently ignore, as this isn't necessary an error.
7253
                    // If an older PROJ version parses a DatumEnsemble object of
7254
                    // a more recent PROJ version where the datum ensemble got
7255
                    // a new member, it might be unknown from the older PROJ.
7256
0
                }
7257
0
            }
7258
7259
0
            if (dbContext_ && !datumAdded) {
7260
0
                auto authFactory = AuthorityFactory::create(
7261
0
                    NN_NO_CHECK(dbContext_), std::string());
7262
0
                auto list = authFactory->createObjectsFromName(
7263
0
                    datumName, {AuthorityFactory::ObjectType::DATUM},
7264
0
                    false /* approximate=false*/);
7265
0
                if (!list.empty()) {
7266
0
                    auto datum =
7267
0
                        util::nn_dynamic_pointer_cast<Datum>(list.front());
7268
0
                    if (!datum)
7269
0
                        throw ParsingException(
7270
0
                            "DatumEnsemble member is not a datum");
7271
0
                    datums.push_back(NN_NO_CHECK(datum));
7272
0
                    datumAdded = true;
7273
0
                }
7274
0
            }
7275
7276
0
            if (!datumAdded) {
7277
                // Fallback if no db match
7278
0
                if (hasEllipsoid) {
7279
0
                    datums.emplace_back(GeodeticReferenceFrame::create(
7280
0
                        buildProperties(memberJ),
7281
0
                        buildEllipsoid(getObject(j, "ellipsoid")),
7282
0
                        optional<std::string>(), PrimeMeridian::GREENWICH));
7283
0
                } else {
7284
0
                    datums.emplace_back(VerticalReferenceFrame::create(
7285
0
                        buildProperties(memberJ)));
7286
0
                }
7287
0
            }
7288
0
        }
7289
0
    } else {
7290
0
        auto name = getString(j, "name");
7291
0
        if (dbContext_) {
7292
0
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
7293
0
                                                        std::string());
7294
0
            auto res = authFactory->createObjectsFromName(
7295
0
                name, {AuthorityFactory::ObjectType::DATUM_ENSEMBLE}, true, 1);
7296
0
            if (res.size() == 1) {
7297
0
                auto datumEnsemble =
7298
0
                    dynamic_cast<const DatumEnsemble *>(res.front().get());
7299
0
                if (datumEnsemble) {
7300
0
                    datums = datumEnsemble->datums();
7301
0
                }
7302
0
            } else {
7303
0
                throw ParsingException(
7304
0
                    "No entry for datum ensemble '" + name +
7305
0
                    "' in database, and no explicit member specified");
7306
0
            }
7307
0
        } else {
7308
0
            throw ParsingException("Datum ensemble '" + name +
7309
0
                                   "' has no explicit member specified and no "
7310
0
                                   "connection to database");
7311
0
        }
7312
0
    }
7313
7314
0
    return DatumEnsemble::create(
7315
0
        buildProperties(j), datums,
7316
0
        PositionalAccuracy::create(getString(j, "accuracy")));
7317
0
}
7318
7319
// ---------------------------------------------------------------------------
7320
7321
GeodeticReferenceFrameNNPtr
7322
0
JSONParser::buildGeodeticReferenceFrame(const json &j) {
7323
0
    auto ellipsoidJ = getObject(j, "ellipsoid");
7324
0
    auto pm = j.contains("prime_meridian")
7325
0
                  ? buildPrimeMeridian(getObject(j, "prime_meridian"))
7326
0
                  : PrimeMeridian::GREENWICH;
7327
0
    return GeodeticReferenceFrame::create(buildProperties(j),
7328
0
                                          buildEllipsoid(ellipsoidJ),
7329
0
                                          getAnchor(j), getAnchorEpoch(j), pm);
7330
0
}
7331
7332
// ---------------------------------------------------------------------------
7333
7334
DynamicGeodeticReferenceFrameNNPtr
7335
0
JSONParser::buildDynamicGeodeticReferenceFrame(const json &j) {
7336
0
    auto ellipsoidJ = getObject(j, "ellipsoid");
7337
0
    auto pm = j.contains("prime_meridian")
7338
0
                  ? buildPrimeMeridian(getObject(j, "prime_meridian"))
7339
0
                  : PrimeMeridian::GREENWICH;
7340
0
    Measure frameReferenceEpoch(getNumber(j, "frame_reference_epoch"),
7341
0
                                UnitOfMeasure::YEAR);
7342
0
    optional<std::string> deformationModel;
7343
0
    if (j.contains("deformation_model")) {
7344
        // Before PROJJSON v0.5 / PROJ 9.1
7345
0
        deformationModel = getString(j, "deformation_model");
7346
0
    } else if (!deformationModelName_.empty()) {
7347
0
        deformationModel = deformationModelName_;
7348
0
    }
7349
0
    return DynamicGeodeticReferenceFrame::create(
7350
0
        buildProperties(j), buildEllipsoid(ellipsoidJ), getAnchor(j), pm,
7351
0
        frameReferenceEpoch, deformationModel);
7352
0
}
7353
7354
// ---------------------------------------------------------------------------
7355
7356
VerticalReferenceFrameNNPtr
7357
1
JSONParser::buildVerticalReferenceFrame(const json &j) {
7358
1
    return VerticalReferenceFrame::create(buildProperties(j), getAnchor(j),
7359
1
                                          getAnchorEpoch(j));
7360
1
}
7361
7362
// ---------------------------------------------------------------------------
7363
7364
DynamicVerticalReferenceFrameNNPtr
7365
0
JSONParser::buildDynamicVerticalReferenceFrame(const json &j) {
7366
0
    Measure frameReferenceEpoch(getNumber(j, "frame_reference_epoch"),
7367
0
                                UnitOfMeasure::YEAR);
7368
0
    optional<std::string> deformationModel;
7369
0
    if (j.contains("deformation_model")) {
7370
        // Before PROJJSON v0.5 / PROJ 9.1
7371
0
        deformationModel = getString(j, "deformation_model");
7372
0
    } else if (!deformationModelName_.empty()) {
7373
0
        deformationModel = deformationModelName_;
7374
0
    }
7375
0
    return DynamicVerticalReferenceFrame::create(
7376
0
        buildProperties(j), getAnchor(j), util::optional<RealizationMethod>(),
7377
0
        frameReferenceEpoch, deformationModel);
7378
0
}
7379
7380
// ---------------------------------------------------------------------------
7381
7382
0
PrimeMeridianNNPtr JSONParser::buildPrimeMeridian(const json &j) {
7383
0
    if (!j.contains("longitude")) {
7384
0
        throw ParsingException("Missing \"longitude\" key");
7385
0
    }
7386
0
    auto longitude = j["longitude"];
7387
0
    if (longitude.is_number()) {
7388
0
        return PrimeMeridian::create(
7389
0
            buildProperties(j),
7390
0
            Angle(longitude.get<double>(), UnitOfMeasure::DEGREE));
7391
0
    } else if (longitude.is_object()) {
7392
0
        return PrimeMeridian::create(buildProperties(j),
7393
0
                                     Angle(getMeasure(longitude)));
7394
0
    }
7395
0
    throw ParsingException("Unexpected type for value of \"longitude\"");
7396
0
}
7397
7398
// ---------------------------------------------------------------------------
7399
7400
0
EllipsoidNNPtr JSONParser::buildEllipsoid(const json &j) {
7401
0
    if (j.contains("semi_major_axis")) {
7402
0
        auto semiMajorAxis = getLength(j, "semi_major_axis");
7403
0
        const auto ellpsProperties = buildProperties(j);
7404
0
        std::string ellpsName;
7405
0
        ellpsProperties.getStringValue(IdentifiedObject::NAME_KEY, ellpsName);
7406
0
        const auto celestialBody(Ellipsoid::guessBodyName(
7407
0
            dbContext_, semiMajorAxis.getSIValue(), ellpsName));
7408
0
        if (j.contains("semi_minor_axis")) {
7409
0
            return Ellipsoid::createTwoAxis(ellpsProperties, semiMajorAxis,
7410
0
                                            getLength(j, "semi_minor_axis"),
7411
0
                                            celestialBody);
7412
0
        } else if (j.contains("inverse_flattening")) {
7413
0
            return Ellipsoid::createFlattenedSphere(
7414
0
                ellpsProperties, semiMajorAxis,
7415
0
                Scale(getNumber(j, "inverse_flattening")), celestialBody);
7416
0
        } else {
7417
0
            throw ParsingException(
7418
0
                "Missing semi_minor_axis or inverse_flattening");
7419
0
        }
7420
0
    } else if (j.contains("radius")) {
7421
0
        auto radius = getLength(j, "radius");
7422
0
        const auto celestialBody(
7423
0
            Ellipsoid::guessBodyName(dbContext_, radius.getSIValue()));
7424
0
        return Ellipsoid::createSphere(buildProperties(j), radius,
7425
0
                                       celestialBody);
7426
0
    }
7427
0
    throw ParsingException("Missing semi_major_axis or radius");
7428
0
}
7429
7430
//! @endcond
7431
7432
// ---------------------------------------------------------------------------
7433
7434
//! @cond Doxygen_Suppress
7435
7436
// import a CRS encoded as OGC Best Practice document 11-135.
7437
7438
static const char *const crsURLPrefixes[] = {
7439
    "http://opengis.net/def/crs",     "https://opengis.net/def/crs",
7440
    "http://www.opengis.net/def/crs", "https://www.opengis.net/def/crs",
7441
    "www.opengis.net/def/crs",
7442
};
7443
7444
3.02k
static bool isCRSURL(const std::string &text) {
7445
15.0k
    for (const auto crsURLPrefix : crsURLPrefixes) {
7446
15.0k
        if (starts_with(text, crsURLPrefix)) {
7447
56
            return true;
7448
56
        }
7449
15.0k
    }
7450
2.96k
    return false;
7451
3.02k
}
7452
7453
static CRSNNPtr importFromCRSURL(const std::string &text,
7454
53
                                 const DatabaseContextNNPtr &dbContext) {
7455
    // e.g http://www.opengis.net/def/crs/EPSG/0/4326
7456
53
    std::vector<std::string> parts;
7457
191
    for (const auto crsURLPrefix : crsURLPrefixes) {
7458
191
        if (starts_with(text, crsURLPrefix)) {
7459
53
            parts = split(text.substr(strlen(crsURLPrefix)), '/');
7460
53
            break;
7461
53
        }
7462
191
    }
7463
7464
    // e.g
7465
    // "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/3855"
7466
53
    if (!parts.empty() && starts_with(parts[0], "-compound?")) {
7467
17
        parts = split(text.substr(text.find('?') + 1), '&');
7468
17
        std::map<int, std::string> mapParts;
7469
17
        for (const auto &part : parts) {
7470
17
            const auto queryParam = split(part, '=');
7471
17
            if (queryParam.size() != 2) {
7472
12
                throw ParsingException("invalid OGC CRS URL");
7473
12
            }
7474
5
            try {
7475
5
                mapParts[std::stoi(queryParam[0])] = queryParam[1];
7476
5
            } catch (const std::exception &) {
7477
5
                throw ParsingException("invalid OGC CRS URL");
7478
5
            }
7479
5
        }
7480
0
        std::vector<CRSNNPtr> components;
7481
0
        std::string name;
7482
0
        for (size_t i = 1; i <= mapParts.size(); ++i) {
7483
0
            const auto iter = mapParts.find(static_cast<int>(i));
7484
0
            if (iter == mapParts.end()) {
7485
0
                throw ParsingException("invalid OGC CRS URL");
7486
0
            }
7487
0
            components.emplace_back(importFromCRSURL(iter->second, dbContext));
7488
0
            if (!name.empty()) {
7489
0
                name += " + ";
7490
0
            }
7491
0
            name += components.back()->nameStr();
7492
0
        }
7493
0
        return CompoundCRS::create(
7494
0
            util::PropertyMap().set(IdentifiedObject::NAME_KEY, name),
7495
0
            components);
7496
0
    }
7497
7498
36
    if (parts.size() < 4) {
7499
25
        throw ParsingException("invalid OGC CRS URL");
7500
25
    }
7501
7502
11
    const auto &auth_name = parts[1];
7503
11
    const auto &code = parts[3];
7504
11
    try {
7505
11
        auto factoryCRS = AuthorityFactory::create(dbContext, auth_name);
7506
11
        return factoryCRS->createCoordinateReferenceSystem(code, true);
7507
11
    } catch (...) {
7508
11
        const auto &version = parts[2];
7509
11
        if (version.empty() || version == "0") {
7510
3
            const auto authoritiesFromAuthName =
7511
3
                dbContext->getVersionedAuthoritiesFromName(auth_name);
7512
3
            for (const auto &authNameVersioned : authoritiesFromAuthName) {
7513
0
                try {
7514
0
                    auto factoryCRS =
7515
0
                        AuthorityFactory::create(dbContext, authNameVersioned);
7516
0
                    return factoryCRS->createCoordinateReferenceSystem(code,
7517
0
                                                                       true);
7518
0
                } catch (...) {
7519
0
                }
7520
0
            }
7521
3
            throw;
7522
3
        }
7523
8
        std::string authNameWithVersion;
7524
8
        if (!dbContext->getVersionedAuthority(auth_name, version,
7525
8
                                              authNameWithVersion)) {
7526
8
            throw;
7527
8
        }
7528
0
        auto factoryCRS =
7529
0
            AuthorityFactory::create(dbContext, authNameWithVersion);
7530
0
        return factoryCRS->createCoordinateReferenceSystem(code, true);
7531
8
    }
7532
11
}
7533
7534
// ---------------------------------------------------------------------------
7535
7536
/* Import a CRS encoded as WMSAUTO string.
7537
 *
7538
 * Note that the WMS 1.3 specification does not include the
7539
 * units code, while apparently earlier specs do.  We try to
7540
 * guess around this.
7541
 *
7542
 * (code derived from GDAL's importFromWMSAUTO())
7543
 */
7544
7545
192
static CRSNNPtr importFromWMSAUTO(const std::string &text) {
7546
7547
192
    int nUnitsId = 9001;
7548
192
    double dfRefLong;
7549
192
    double dfRefLat = 0.0;
7550
7551
192
    assert(ci_starts_with(text, "AUTO:"));
7552
192
    const auto parts = split(text.substr(strlen("AUTO:")), ',');
7553
7554
192
    try {
7555
192
        constexpr int AUTO_MOLLWEIDE = 42005;
7556
192
        if (parts.size() == 4) {
7557
4
            nUnitsId = std::stoi(parts[1]);
7558
4
            dfRefLong = c_locale_stod(parts[2]);
7559
4
            dfRefLat = c_locale_stod(parts[3]);
7560
188
        } else if (parts.size() == 3 && std::stoi(parts[0]) == AUTO_MOLLWEIDE) {
7561
3
            nUnitsId = std::stoi(parts[1]);
7562
3
            dfRefLong = c_locale_stod(parts[2]);
7563
185
        } else if (parts.size() == 3) {
7564
118
            dfRefLong = c_locale_stod(parts[1]);
7565
118
            dfRefLat = c_locale_stod(parts[2]);
7566
118
        } else if (parts.size() == 2 && std::stoi(parts[0]) == AUTO_MOLLWEIDE) {
7567
34
            dfRefLong = c_locale_stod(parts[1]);
7568
34
        } else {
7569
33
            throw ParsingException("invalid WMS AUTO CRS definition");
7570
33
        }
7571
7572
159
        const auto getConversion = [dfRefLong, dfRefLat, &parts]() {
7573
88
            const int nProjId = std::stoi(parts[0]);
7574
88
            switch (nProjId) {
7575
5
            case 42001: // Auto UTM
7576
5
                if (!(dfRefLong >= -180 && dfRefLong < 180)) {
7577
0
                    throw ParsingException("invalid WMS AUTO CRS definition: "
7578
0
                                           "invalid longitude");
7579
0
                }
7580
5
                return Conversion::createUTM(
7581
5
                    util::PropertyMap(),
7582
5
                    static_cast<int>(floor((dfRefLong + 180.0) / 6.0)) + 1,
7583
5
                    dfRefLat >= 0.0);
7584
7585
7
            case 42002: // Auto TM (strangely very UTM-like).
7586
7
                return Conversion::createTransverseMercator(
7587
7
                    util::PropertyMap(), common::Angle(0),
7588
7
                    common::Angle(dfRefLong), common::Scale(0.9996),
7589
7
                    common::Length(500000),
7590
7
                    common::Length((dfRefLat >= 0.0) ? 0.0 : 10000000.0));
7591
7592
24
            case 42003: // Auto Orthographic.
7593
24
                return Conversion::createOrthographic(
7594
24
                    util::PropertyMap(), common::Angle(dfRefLat),
7595
24
                    common::Angle(dfRefLong), common::Length(0),
7596
24
                    common::Length(0));
7597
7598
14
            case 42004: // Auto Equirectangular
7599
14
                return Conversion::createEquidistantCylindrical(
7600
14
                    util::PropertyMap(), common::Angle(dfRefLat),
7601
14
                    common::Angle(dfRefLong), common::Length(0),
7602
14
                    common::Length(0));
7603
7604
18
            case 42005: // MSVC 2015 thinks that AUTO_MOLLWEIDE is not constant
7605
18
                return Conversion::createMollweide(
7606
18
                    util::PropertyMap(), common::Angle(dfRefLong),
7607
18
                    common::Length(0), common::Length(0));
7608
7609
20
            default:
7610
20
                throw ParsingException("invalid WMS AUTO CRS definition: "
7611
20
                                       "unsupported projection id");
7612
88
            }
7613
88
        };
7614
7615
159
        const auto getUnits = [nUnitsId]() -> const UnitOfMeasure & {
7616
68
            switch (nUnitsId) {
7617
67
            case 9001:
7618
67
                return UnitOfMeasure::METRE;
7619
7620
0
            case 9002:
7621
0
                return UnitOfMeasure::FOOT;
7622
7623
0
            case 9003:
7624
0
                return UnitOfMeasure::US_FOOT;
7625
7626
1
            default:
7627
1
                throw ParsingException("invalid WMS AUTO CRS definition: "
7628
1
                                       "unsupported units code");
7629
68
            }
7630
68
        };
7631
7632
159
        return crs::ProjectedCRS::create(
7633
159
            util::PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
7634
159
            crs::GeographicCRS::EPSG_4326, getConversion(),
7635
159
            cs::CartesianCS::createEastingNorthing(getUnits()));
7636
7637
192
    } catch (const std::exception &) {
7638
125
        throw ParsingException("invalid WMS AUTO CRS definition");
7639
125
    }
7640
192
}
7641
7642
// ---------------------------------------------------------------------------
7643
7644
static BaseObjectNNPtr createFromURNPart(const DatabaseContextPtr &dbContext,
7645
                                         const std::string &type,
7646
                                         const std::string &authName,
7647
                                         const std::string &version,
7648
48
                                         const std::string &code) {
7649
48
    if (!dbContext) {
7650
4
        throw ParsingException("no database context specified");
7651
4
    }
7652
44
    try {
7653
44
        auto factory =
7654
44
            AuthorityFactory::create(NN_NO_CHECK(dbContext), authName);
7655
44
        if (type == "crs") {
7656
0
            return factory->createCoordinateReferenceSystem(code);
7657
0
        }
7658
44
        if (type == "coordinateOperation") {
7659
1
            return factory->createCoordinateOperation(code, true);
7660
1
        }
7661
43
        if (type == "datum") {
7662
0
            return factory->createDatum(code);
7663
0
        }
7664
43
        if (type == "ensemble") {
7665
0
            return factory->createDatumEnsemble(code);
7666
0
        }
7667
43
        if (type == "ellipsoid") {
7668
0
            return factory->createEllipsoid(code);
7669
0
        }
7670
43
        if (type == "meridian") {
7671
0
            return factory->createPrimeMeridian(code);
7672
0
        }
7673
        // Extension of OGC URN syntax to CoordinateMetadata
7674
43
        if (type == "coordinateMetadata") {
7675
0
            return factory->createCoordinateMetadata(code);
7676
0
        }
7677
43
        throw ParsingException(concat("unhandled object type: ", type));
7678
44
    } catch (...) {
7679
44
        if (version.empty()) {
7680
8
            const auto authoritiesFromAuthName =
7681
8
                dbContext->getVersionedAuthoritiesFromName(authName);
7682
8
            for (const auto &authNameVersioned : authoritiesFromAuthName) {
7683
0
                try {
7684
0
                    return createFromURNPart(dbContext, type, authNameVersioned,
7685
0
                                             std::string(), code);
7686
0
                } catch (...) {
7687
0
                }
7688
0
            }
7689
8
            throw;
7690
8
        }
7691
36
        std::string authNameWithVersion;
7692
36
        if (!dbContext->getVersionedAuthority(authName, version,
7693
36
                                              authNameWithVersion)) {
7694
36
            throw;
7695
36
        }
7696
0
        return createFromURNPart(dbContext, type, authNameWithVersion,
7697
0
                                 std::string(), code);
7698
36
    }
7699
44
}
7700
7701
// ---------------------------------------------------------------------------
7702
7703
static BaseObjectNNPtr createFromUserInput(const std::string &text,
7704
                                           const DatabaseContextPtr &dbContext,
7705
                                           bool usePROJ4InitRules,
7706
                                           PJ_CONTEXT *ctx,
7707
24.0k
                                           bool ignoreCoordinateEpoch) {
7708
24.0k
    std::size_t idxFirstCharNotSpace = text.find_first_not_of(" \t\r\n");
7709
24.0k
    if (idxFirstCharNotSpace > 0 && idxFirstCharNotSpace != std::string::npos) {
7710
396
        return createFromUserInput(text.substr(idxFirstCharNotSpace), dbContext,
7711
396
                                   usePROJ4InitRules, ctx,
7712
396
                                   ignoreCoordinateEpoch);
7713
396
    }
7714
7715
    // Parse strings like "ITRF2014 @ 2025.0"
7716
23.6k
    const auto posAt = text.find('@');
7717
23.6k
    if (!ignoreCoordinateEpoch && posAt != std::string::npos) {
7718
7719
        // Try first as if belonged to the name
7720
4.50k
        try {
7721
4.50k
            return createFromUserInput(text, dbContext, usePROJ4InitRules, ctx,
7722
4.50k
                                       /* ignoreCoordinateEpoch = */ true);
7723
4.50k
        } catch (...) {
7724
2.35k
        }
7725
7726
2.35k
        std::string leftPart = text.substr(0, posAt);
7727
2.57k
        while (!leftPart.empty() && leftPart.back() == ' ')
7728
213
            leftPart.resize(leftPart.size() - 1);
7729
2.35k
        const auto nonSpacePos = text.find_first_not_of(' ', posAt + 1);
7730
2.35k
        if (nonSpacePos != std::string::npos) {
7731
1.91k
            auto obj =
7732
1.91k
                createFromUserInput(leftPart, dbContext, usePROJ4InitRules, ctx,
7733
1.91k
                                    /* ignoreCoordinateEpoch = */ true);
7734
1.91k
            auto crs = nn_dynamic_pointer_cast<CRS>(obj);
7735
1.91k
            if (crs) {
7736
141
                double epoch;
7737
141
                try {
7738
141
                    epoch = c_locale_stod(text.substr(nonSpacePos));
7739
141
                } catch (const std::exception &) {
7740
56
                    throw ParsingException("non-numeric value after @");
7741
56
                }
7742
85
                try {
7743
85
                    return CoordinateMetadata::create(NN_NO_CHECK(crs), epoch,
7744
85
                                                      dbContext);
7745
85
                } catch (const std::exception &e) {
7746
11
                    throw ParsingException(
7747
11
                        std::string(
7748
11
                            "CoordinateMetadata::create() failed with: ") +
7749
11
                        e.what());
7750
11
                }
7751
85
            }
7752
1.91k
        }
7753
2.35k
    }
7754
7755
21.3k
    if (!text.empty() && text[0] == '{') {
7756
1.64k
        json j;
7757
1.64k
        try {
7758
17.5k
            j = json::parse(text, [](int depth, json::parse_event_t, json &) {
7759
17.5k
                if (depth >= 128)
7760
6
                    throw ParsingException("Too deep nesting in JSON content");
7761
17.5k
                return true;
7762
17.5k
            });
7763
1.64k
        } catch (const std::exception &e) {
7764
1.55k
            throw ParsingException(e.what());
7765
1.55k
        }
7766
96
        return JSONParser()
7767
96
            .attachContext(ctx)
7768
96
            .attachDatabaseContext(dbContext)
7769
96
            .create(j);
7770
1.64k
    }
7771
7772
19.7k
    if (!ci_starts_with(text, "step proj=") &&
7773
18.3k
        !ci_starts_with(text, "step +proj=")) {
7774
1.68M
        for (const auto &wktConstant : WKTConstants::constants()) {
7775
1.68M
            if (ci_starts_with(text, wktConstant)) {
7776
3.23k
                for (auto wkt = text.c_str() + wktConstant.size(); *wkt != '\0';
7777
3.23k
                     ++wkt) {
7778
3.23k
                    if (isspace(static_cast<unsigned char>(*wkt)))
7779
232
                        continue;
7780
2.99k
                    if (*wkt == '[') {
7781
2.89k
                        return WKTParser()
7782
2.89k
                            .attachDatabaseContext(dbContext)
7783
2.89k
                            .setStrict(false)
7784
2.89k
                            .createFromWKT(text);
7785
2.89k
                    }
7786
108
                    break;
7787
2.99k
                }
7788
3.00k
            }
7789
1.68M
        }
7790
18.3k
    }
7791
7792
16.8k
    const char *textWithoutPlusPrefix = text.c_str();
7793
16.8k
    if (textWithoutPlusPrefix[0] == '+')
7794
1.84k
        textWithoutPlusPrefix++;
7795
7796
16.8k
    if (strncmp(textWithoutPlusPrefix, "proj=", strlen("proj=")) == 0 ||
7797
6.61k
        text.find(" +proj=") != std::string::npos ||
7798
6.09k
        text.find(" proj=") != std::string::npos ||
7799
3.44k
        strncmp(textWithoutPlusPrefix, "init=", strlen("init=")) == 0 ||
7800
3.13k
        text.find(" +init=") != std::string::npos ||
7801
3.10k
        text.find(" init=") != std::string::npos ||
7802
12.3k
        strncmp(textWithoutPlusPrefix, "title=", strlen("title=")) == 0) {
7803
12.3k
        return PROJStringParser()
7804
12.3k
            .attachDatabaseContext(dbContext)
7805
12.3k
            .attachContext(ctx)
7806
12.3k
            .setUsePROJ4InitRules(ctx != nullptr
7807
12.3k
                                      ? (proj_context_get_use_proj4_init_rules(
7808
12.3k
                                             ctx, false) == TRUE)
7809
12.3k
                                      : usePROJ4InitRules)
7810
12.3k
            .createFromPROJString(text);
7811
12.3k
    }
7812
7813
4.44k
    if (isCRSURL(text) && dbContext) {
7814
53
        return importFromCRSURL(text, NN_NO_CHECK(dbContext));
7815
53
    }
7816
7817
4.39k
    if (ci_starts_with(text, "AUTO:")) {
7818
137
        return importFromWMSAUTO(text);
7819
137
    }
7820
7821
4.25k
    std::vector<std::string> tokens;
7822
4.25k
    if (text.find(' ') == std::string::npos)
7823
2.27k
        tokens = split(text, ':');
7824
4.25k
    if (tokens.size() == 2) {
7825
84
        if (!dbContext) {
7826
4
            throw ParsingException("no database context specified");
7827
4
        }
7828
80
        DatabaseContextNNPtr dbContextNNPtr(NN_NO_CHECK(dbContext));
7829
80
        const auto &authName = tokens[0];
7830
80
        const auto &code = tokens[1];
7831
80
        auto factory = AuthorityFactory::create(dbContextNNPtr, authName);
7832
80
        try {
7833
80
            return factory->createCoordinateReferenceSystem(code);
7834
80
        } catch (...) {
7835
7836
            // Convenience for well-known misused code
7837
            // See https://github.com/OSGeo/PROJ/issues/1730
7838
80
            if (ci_equal(authName, "EPSG") && code == "102100") {
7839
0
                factory = AuthorityFactory::create(dbContextNNPtr, "ESRI");
7840
0
                return factory->createCoordinateReferenceSystem(code);
7841
0
            }
7842
7843
80
            const auto authoritiesFromAuthName =
7844
80
                dbContextNNPtr->getVersionedAuthoritiesFromName(authName);
7845
80
            for (const auto &authNameVersioned : authoritiesFromAuthName) {
7846
3
                factory =
7847
3
                    AuthorityFactory::create(dbContextNNPtr, authNameVersioned);
7848
3
                try {
7849
3
                    return factory->createCoordinateReferenceSystem(code);
7850
3
                } catch (...) {
7851
3
                }
7852
3
            }
7853
7854
80
            const auto allAuthorities = dbContextNNPtr->getAuthorities();
7855
576
            for (const auto &authCandidate : allAuthorities) {
7856
576
                if (ci_equal(authCandidate, authName)) {
7857
22
                    factory =
7858
22
                        AuthorityFactory::create(dbContextNNPtr, authCandidate);
7859
22
                    try {
7860
22
                        return factory->createCoordinateReferenceSystem(code);
7861
22
                    } catch (...) {
7862
                        // EPSG:4326+3855
7863
22
                        auto tokensCode = split(code, '+');
7864
22
                        if (tokensCode.size() == 2) {
7865
5
                            auto crs1(factory->createCoordinateReferenceSystem(
7866
5
                                tokensCode[0], false));
7867
5
                            auto crs2(factory->createCoordinateReferenceSystem(
7868
5
                                tokensCode[1], false));
7869
5
                            return CompoundCRS::createLax(
7870
5
                                util::PropertyMap().set(
7871
5
                                    IdentifiedObject::NAME_KEY,
7872
5
                                    crs1->nameStr() + " + " + crs2->nameStr()),
7873
5
                                {crs1, crs2}, dbContext);
7874
5
                        }
7875
17
                        throw;
7876
22
                    }
7877
22
                }
7878
576
            }
7879
58
            throw;
7880
80
        }
7881
4.17k
    } else if (tokens.size() == 3) {
7882
        // ESRI:103668+EPSG:5703 ... compound
7883
22
        auto tokensCenter = split(tokens[1], '+');
7884
22
        if (tokensCenter.size() == 2) {
7885
4
            if (!dbContext) {
7886
2
                throw ParsingException("no database context specified");
7887
2
            }
7888
2
            DatabaseContextNNPtr dbContextNNPtr(NN_NO_CHECK(dbContext));
7889
7890
2
            const auto &authName1 = tokens[0];
7891
2
            const auto &code1 = tokensCenter[0];
7892
2
            const auto &authName2 = tokensCenter[1];
7893
2
            const auto &code2 = tokens[2];
7894
7895
2
            auto factory1 = AuthorityFactory::create(dbContextNNPtr, authName1);
7896
2
            auto crs1 = factory1->createCoordinateReferenceSystem(code1, false);
7897
2
            auto factory2 = AuthorityFactory::create(dbContextNNPtr, authName2);
7898
2
            auto crs2 = factory2->createCoordinateReferenceSystem(code2, false);
7899
2
            return CompoundCRS::createLax(
7900
2
                util::PropertyMap().set(IdentifiedObject::NAME_KEY,
7901
2
                                        crs1->nameStr() + " + " +
7902
2
                                            crs2->nameStr()),
7903
2
                {crs1, crs2}, dbContext);
7904
4
        }
7905
22
    }
7906
7907
4.17k
    if (starts_with(text, "urn:ogc:def:crs,")) {
7908
9
        if (!dbContext) {
7909
0
            throw ParsingException("no database context specified");
7910
0
        }
7911
9
        auto tokensComma = split(text, ',');
7912
9
        if (tokensComma.size() == 4 && starts_with(tokensComma[1], "crs:") &&
7913
0
            starts_with(tokensComma[2], "cs:") &&
7914
0
            starts_with(tokensComma[3], "coordinateOperation:")) {
7915
            // OGC 07-092r2: para 7.5.4
7916
            // URN combined references for projected or derived CRSs
7917
0
            const auto &crsPart = tokensComma[1];
7918
0
            const auto tokensCRS = split(crsPart, ':');
7919
0
            if (tokensCRS.size() != 4) {
7920
0
                throw ParsingException(
7921
0
                    concat("invalid crs component: ", crsPart));
7922
0
            }
7923
0
            auto factoryCRS =
7924
0
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensCRS[1]);
7925
0
            auto baseCRS =
7926
0
                factoryCRS->createCoordinateReferenceSystem(tokensCRS[3], true);
7927
7928
0
            const auto &csPart = tokensComma[2];
7929
0
            auto tokensCS = split(csPart, ':');
7930
0
            if (tokensCS.size() != 4) {
7931
0
                throw ParsingException(
7932
0
                    concat("invalid cs component: ", csPart));
7933
0
            }
7934
0
            auto factoryCS =
7935
0
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensCS[1]);
7936
0
            auto cs = factoryCS->createCoordinateSystem(tokensCS[3]);
7937
7938
0
            const auto &opPart = tokensComma[3];
7939
0
            auto tokensOp = split(opPart, ':');
7940
0
            if (tokensOp.size() != 4) {
7941
0
                throw ParsingException(
7942
0
                    concat("invalid coordinateOperation component: ", opPart));
7943
0
            }
7944
0
            auto factoryOp =
7945
0
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensOp[1]);
7946
0
            auto op = factoryOp->createCoordinateOperation(tokensOp[3], true);
7947
7948
0
            const auto &baseName = baseCRS->nameStr();
7949
0
            std::string name(baseName);
7950
0
            auto geogCRS =
7951
0
                util::nn_dynamic_pointer_cast<GeographicCRS>(baseCRS);
7952
0
            if (geogCRS &&
7953
0
                geogCRS->coordinateSystem()->axisList().size() == 3 &&
7954
0
                baseName.find("3D") == std::string::npos) {
7955
0
                name += " (3D)";
7956
0
            }
7957
0
            name += " / ";
7958
0
            name += op->nameStr();
7959
0
            auto props =
7960
0
                util::PropertyMap().set(IdentifiedObject::NAME_KEY, name);
7961
7962
0
            if (auto conv = util::nn_dynamic_pointer_cast<Conversion>(op)) {
7963
0
                auto convNN = NN_NO_CHECK(conv);
7964
0
                if (geogCRS != nullptr) {
7965
0
                    auto geogCRSNN = NN_NO_CHECK(geogCRS);
7966
0
                    if (CartesianCSPtr ccs =
7967
0
                            util::nn_dynamic_pointer_cast<CartesianCS>(cs)) {
7968
0
                        return ProjectedCRS::create(props, geogCRSNN, convNN,
7969
0
                                                    NN_NO_CHECK(ccs));
7970
0
                    }
7971
0
                    if (EllipsoidalCSPtr ecs =
7972
0
                            util::nn_dynamic_pointer_cast<EllipsoidalCS>(cs)) {
7973
0
                        return DerivedGeographicCRS::create(
7974
0
                            props, geogCRSNN, convNN, NN_NO_CHECK(ecs));
7975
0
                    }
7976
0
                } else if (dynamic_cast<GeodeticCRS *>(baseCRS.get()) &&
7977
0
                           dynamic_cast<CartesianCS *>(cs.get())) {
7978
0
                    return DerivedGeodeticCRS::create(
7979
0
                        props,
7980
0
                        NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>(
7981
0
                            baseCRS)),
7982
0
                        convNN,
7983
0
                        NN_NO_CHECK(
7984
0
                            util::nn_dynamic_pointer_cast<CartesianCS>(cs)));
7985
0
                } else if (auto pcrs =
7986
0
                               util::nn_dynamic_pointer_cast<ProjectedCRS>(
7987
0
                                   baseCRS)) {
7988
0
                    return DerivedProjectedCRS::create(props, NN_NO_CHECK(pcrs),
7989
0
                                                       convNN, cs);
7990
0
                } else if (auto vertBaseCRS =
7991
0
                               util::nn_dynamic_pointer_cast<VerticalCRS>(
7992
0
                                   baseCRS)) {
7993
0
                    if (auto vertCS =
7994
0
                            util::nn_dynamic_pointer_cast<VerticalCS>(cs)) {
7995
0
                        const int methodCode = convNN->method()->getEPSGCode();
7996
0
                        std::string newName(baseName);
7997
0
                        std::string unitNameSuffix;
7998
0
                        for (const char *suffix : {" (ft)", " (ftUS)"}) {
7999
0
                            if (ends_with(newName, suffix)) {
8000
0
                                unitNameSuffix = suffix;
8001
0
                                newName.resize(newName.size() - strlen(suffix));
8002
0
                                break;
8003
0
                            }
8004
0
                        }
8005
0
                        bool newNameOk = false;
8006
0
                        if (methodCode ==
8007
0
                                EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR ||
8008
0
                            methodCode ==
8009
0
                                EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT) {
8010
0
                            const auto &unitName =
8011
0
                                vertCS->axisList()[0]->unit().name();
8012
0
                            if (unitName == UnitOfMeasure::METRE.name()) {
8013
0
                                newNameOk = true;
8014
0
                            } else if (unitName == UnitOfMeasure::FOOT.name()) {
8015
0
                                newName += " (ft)";
8016
0
                                newNameOk = true;
8017
0
                            } else if (unitName ==
8018
0
                                       UnitOfMeasure::US_FOOT.name()) {
8019
0
                                newName += " (ftUS)";
8020
0
                                newNameOk = true;
8021
0
                            }
8022
0
                        } else if (methodCode ==
8023
0
                                   EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) {
8024
0
                            if (ends_with(newName, " height")) {
8025
0
                                newName.resize(newName.size() -
8026
0
                                               strlen(" height"));
8027
0
                                newName += " depth";
8028
0
                                newName += unitNameSuffix;
8029
0
                                newNameOk = true;
8030
0
                            } else if (ends_with(newName, " depth")) {
8031
0
                                newName.resize(newName.size() -
8032
0
                                               strlen(" depth"));
8033
0
                                newName += " height";
8034
0
                                newName += unitNameSuffix;
8035
0
                                newNameOk = true;
8036
0
                            }
8037
0
                        }
8038
0
                        if (newNameOk) {
8039
0
                            props.set(IdentifiedObject::NAME_KEY, newName);
8040
0
                        }
8041
0
                        return DerivedVerticalCRS::create(
8042
0
                            props, NN_NO_CHECK(vertBaseCRS), convNN,
8043
0
                            NN_NO_CHECK(vertCS));
8044
0
                    }
8045
0
                }
8046
0
            }
8047
8048
0
            throw ParsingException("unsupported combination of baseCRS, CS "
8049
0
                                   "and coordinateOperation for a "
8050
0
                                   "DerivedCRS");
8051
0
        }
8052
8053
        // OGC 07-092r2: para 7.5.2
8054
        // URN combined references for compound coordinate reference systems
8055
9
        std::vector<CRSNNPtr> components;
8056
9
        std::string name;
8057
9
        for (size_t i = 1; i < tokensComma.size(); i++) {
8058
9
            tokens = split(tokensComma[i], ':');
8059
9
            if (tokens.size() != 4) {
8060
6
                throw ParsingException(
8061
6
                    concat("invalid crs component: ", tokensComma[i]));
8062
6
            }
8063
3
            const auto &type = tokens[0];
8064
3
            auto factory =
8065
3
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokens[1]);
8066
3
            const auto &code = tokens[3];
8067
3
            if (type == "crs") {
8068
0
                auto crs(factory->createCoordinateReferenceSystem(code, false));
8069
0
                components.emplace_back(crs);
8070
0
                if (!name.empty()) {
8071
0
                    name += " + ";
8072
0
                }
8073
0
                name += crs->nameStr();
8074
3
            } else {
8075
3
                throw ParsingException(
8076
3
                    concat("unexpected object type: ", type));
8077
3
            }
8078
3
        }
8079
0
        return CompoundCRS::create(
8080
0
            util::PropertyMap().set(IdentifiedObject::NAME_KEY, name),
8081
0
            components);
8082
9
    }
8083
8084
    // OGC 07-092r2: para 7.5.3
8085
    // 7.5.3 URN combined references for concatenated operations
8086
4.16k
    if (starts_with(text, "urn:ogc:def:coordinateOperation,")) {
8087
9
        if (!dbContext) {
8088
3
            throw ParsingException("no database context specified");
8089
3
        }
8090
6
        auto tokensComma = split(text, ',');
8091
6
        std::vector<CoordinateOperationNNPtr> components;
8092
6
        for (size_t i = 1; i < tokensComma.size(); i++) {
8093
6
            tokens = split(tokensComma[i], ':');
8094
6
            if (tokens.size() != 4) {
8095
3
                throw ParsingException(concat(
8096
3
                    "invalid coordinateOperation component: ", tokensComma[i]));
8097
3
            }
8098
3
            const auto &type = tokens[0];
8099
3
            auto factory =
8100
3
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokens[1]);
8101
3
            const auto &code = tokens[3];
8102
3
            if (type == "coordinateOperation") {
8103
0
                auto op(factory->createCoordinateOperation(code, false));
8104
0
                components.emplace_back(op);
8105
3
            } else {
8106
3
                throw ParsingException(
8107
3
                    concat("unexpected object type: ", type));
8108
3
            }
8109
3
        }
8110
0
        return ConcatenatedOperation::createComputeMetadata(components, true);
8111
6
    }
8112
8113
    // urn:ogc:def:crs:EPSG::4326
8114
4.15k
    if (tokens.size() == 7 && tolower(tokens[0]) == "urn") {
8115
8116
15
        const std::string type(tokens[3] == "CRS" ? "crs" : tokens[3]);
8117
15
        const auto &authName = tokens[4];
8118
15
        const auto &version = tokens[5];
8119
15
        const auto &code = tokens[6];
8120
15
        return createFromURNPart(dbContext, type, authName, version, code);
8121
15
    }
8122
8123
    // urn:ogc:def:crs:OGC::AUTO42001:-117:33
8124
4.13k
    if (tokens.size() > 7 && tokens[0] == "urn" && tokens[4] == "OGC" &&
8125
58
        ci_starts_with(tokens[6], "AUTO")) {
8126
55
        const auto textAUTO = text.substr(text.find(":AUTO") + 5);
8127
55
        return importFromWMSAUTO("AUTO:" + replaceAll(textAUTO, ":", ","));
8128
55
    }
8129
8130
    // Legacy urn:opengis:crs:EPSG:0:4326 (note the missing def: compared to
8131
    // above)
8132
4.08k
    if (tokens.size() == 6 && tokens[0] == "urn" && tokens[2] != "def") {
8133
26
        const auto &type = tokens[2];
8134
26
        const auto &authName = tokens[3];
8135
26
        const auto &version = tokens[4];
8136
26
        const auto &code = tokens[5];
8137
26
        return createFromURNPart(dbContext, type, authName, version, code);
8138
26
    }
8139
8140
    // Legacy urn:x-ogc:def:crs:EPSG:4326 (note the missing version)
8141
4.05k
    if (tokens.size() == 6 && tokens[0] == "urn") {
8142
7
        const auto &type = tokens[3];
8143
7
        const auto &authName = tokens[4];
8144
7
        const auto &code = tokens[5];
8145
7
        return createFromURNPart(dbContext, type, authName, std::string(),
8146
7
                                 code);
8147
7
    }
8148
8149
4.04k
    if (dbContext) {
8150
2.56k
        auto factory =
8151
2.56k
            AuthorityFactory::create(NN_NO_CHECK(dbContext), std::string());
8152
8153
2.56k
        const auto searchObject =
8154
2.56k
            [&factory](
8155
2.56k
                const std::string &objectName, bool approximateMatch,
8156
2.56k
                const std::vector<AuthorityFactory::ObjectType> &objectTypes)
8157
7.63k
            -> IdentifiedObjectPtr {
8158
7.63k
            constexpr size_t limitResultCount = 10;
8159
7.63k
            auto res = factory->createObjectsFromName(
8160
7.63k
                objectName, objectTypes, approximateMatch, limitResultCount);
8161
7.63k
            if (res.size() == 1) {
8162
139
                return res.front().as_nullable();
8163
139
            }
8164
7.49k
            if (res.size() > 1) {
8165
1.26k
                if (objectTypes.size() == 1 &&
8166
999
                    objectTypes[0] == AuthorityFactory::ObjectType::CRS) {
8167
1.27k
                    for (size_t ndim = 2; ndim <= 3; ndim++) {
8168
4.22k
                        for (const auto &obj : res) {
8169
4.22k
                            auto crs =
8170
4.22k
                                dynamic_cast<crs::GeographicCRS *>(obj.get());
8171
4.22k
                            if (crs &&
8172
1.49k
                                crs->coordinateSystem()->axisList().size() ==
8173
1.49k
                                    ndim) {
8174
872
                                return obj.as_nullable();
8175
872
                            }
8176
4.22k
                        }
8177
1.14k
                    }
8178
999
                }
8179
8180
                // If there's exactly only one object whose name is equivalent
8181
                // to the user input, return it.
8182
1.15k
                for (int pass = 0; pass <= 1; ++pass) {
8183
776
                    IdentifiedObjectPtr identifiedObj;
8184
6.10k
                    for (const auto &obj : res) {
8185
6.10k
                        if (Identifier::isEquivalentName(
8186
6.10k
                                obj->nameStr().c_str(), objectName.c_str(),
8187
6.10k
                                /* biggerDifferencesAllowed = */ pass == 1)) {
8188
7
                            if (identifiedObj == nullptr) {
8189
7
                                identifiedObj = obj.as_nullable();
8190
7
                            } else {
8191
0
                                identifiedObj = nullptr;
8192
0
                                break;
8193
0
                            }
8194
7
                        }
8195
6.10k
                    }
8196
776
                    if (identifiedObj) {
8197
7
                        return identifiedObj;
8198
7
                    }
8199
776
                }
8200
8201
382
                std::string msg("several objects matching this name: ");
8202
382
                bool first = true;
8203
2.56k
                for (const auto &obj : res) {
8204
2.56k
                    if (msg.size() > 200) {
8205
234
                        msg += ", ...";
8206
234
                        break;
8207
234
                    }
8208
2.33k
                    if (!first) {
8209
1.95k
                        msg += ", ";
8210
1.95k
                    }
8211
2.33k
                    first = false;
8212
2.33k
                    msg += obj->nameStr();
8213
2.33k
                }
8214
382
                throw ParsingException(msg);
8215
389
            }
8216
6.23k
            return nullptr;
8217
7.49k
        };
8218
8219
2.56k
        const auto searchCRS = [&searchObject](const std::string &objectName) {
8220
63
            const auto objectTypes = std::vector<AuthorityFactory::ObjectType>{
8221
63
                AuthorityFactory::ObjectType::CRS};
8222
63
            {
8223
63
                constexpr bool approximateMatch = false;
8224
63
                auto ret =
8225
63
                    searchObject(objectName, approximateMatch, objectTypes);
8226
63
                if (ret)
8227
1
                    return ret;
8228
63
            }
8229
8230
62
            constexpr bool approximateMatch = true;
8231
62
            return searchObject(objectName, approximateMatch, objectTypes);
8232
63
        };
8233
8234
        // strings like "WGS 84 + EGM96 height"
8235
2.56k
        CompoundCRSPtr compoundCRS;
8236
2.56k
        try {
8237
2.56k
            const auto tokensCompound = split(text, " + ");
8238
2.56k
            if (tokensCompound.size() == 2) {
8239
33
                auto obj1 = searchCRS(tokensCompound[0]);
8240
33
                auto obj2 = searchCRS(tokensCompound[1]);
8241
33
                auto crs1 = std::dynamic_pointer_cast<CRS>(obj1);
8242
33
                auto crs2 = std::dynamic_pointer_cast<CRS>(obj2);
8243
33
                if (crs1 && crs2) {
8244
4
                    compoundCRS =
8245
4
                        CompoundCRS::create(
8246
4
                            util::PropertyMap().set(IdentifiedObject::NAME_KEY,
8247
4
                                                    crs1->nameStr() + " + " +
8248
4
                                                        crs2->nameStr()),
8249
4
                            {NN_NO_CHECK(crs1), NN_NO_CHECK(crs2)})
8250
4
                            .as_nullable();
8251
4
                }
8252
33
            }
8253
2.56k
        } catch (const std::exception &) {
8254
7
        }
8255
8256
        // First pass: exact match on CRS objects
8257
        // Second pass: exact match on other objects
8258
        // Third pass: approximate match on CRS objects
8259
        // Fourth pass: approximate match on other objects
8260
        // But only allow approximate matching if the size of the text is
8261
        // large enough (>= 5), otherwise we get a lot of false positives:
8262
        // "foo" -> "Amersfoort", "bar" -> "Barbados 1938"
8263
        // Also only accept approximate matching if the ratio between the
8264
        // input and match size is not too small, so that "omerc" doesn't match
8265
        // with "WGS 84 / Pseudo-Mercator"
8266
2.56k
        const int maxNumberPasses = text.size() <= 4 ? 2 : 4;
8267
9.31k
        for (int pass = 0; pass < maxNumberPasses; ++pass) {
8268
7.50k
            const bool approximateMatch = (pass >= 2);
8269
7.50k
            auto ret = searchObject(
8270
7.50k
                text, approximateMatch,
8271
7.50k
                (pass == 0 || pass == 2)
8272
7.50k
                    ? std::vector<
8273
4.17k
                          AuthorityFactory::ObjectType>{AuthorityFactory::
8274
4.17k
                                                            ObjectType::CRS}
8275
7.50k
                    : std::vector<AuthorityFactory::ObjectType>{
8276
3.33k
                          AuthorityFactory::ObjectType::ELLIPSOID,
8277
3.33k
                          AuthorityFactory::ObjectType::DATUM,
8278
3.33k
                          AuthorityFactory::ObjectType::DATUM_ENSEMBLE,
8279
3.33k
                          AuthorityFactory::ObjectType::COORDINATE_OPERATION});
8280
7.50k
            if (ret) {
8281
993
                if (!approximateMatch ||
8282
950
                    ret->nameStr().size() < 2 * text.size())
8283
757
                    return NN_NO_CHECK(ret);
8284
993
            }
8285
6.74k
            if (compoundCRS) {
8286
0
                if (!approximateMatch ||
8287
0
                    compoundCRS->nameStr().size() < 2 * text.size())
8288
0
                    return NN_NO_CHECK(compoundCRS);
8289
0
            }
8290
6.74k
        }
8291
2.56k
    }
8292
8293
3.29k
    throw ParsingException("unrecognized format / unknown name");
8294
4.04k
}
8295
//! @endcond
8296
8297
// ---------------------------------------------------------------------------
8298
8299
/** \brief Instantiate a sub-class of BaseObject from a user specified text.
8300
 *
8301
 * The text can be a:
8302
 * <ul>
8303
 * <li>WKT string</li>
8304
 * <li>PROJ string</li>
8305
 * <li>database code, prefixed by its authority. e.g. "EPSG:4326"</li>
8306
 * <li>OGC URN. e.g. "urn:ogc:def:crs:EPSG::4326",
8307
 *     "urn:ogc:def:coordinateOperation:EPSG::1671",
8308
 *     "urn:ogc:def:ellipsoid:EPSG::7001"
8309
 *     or "urn:ogc:def:datum:EPSG::6326"</li>
8310
 * <li> OGC URN combining references for compound coordinate reference systems
8311
 *      e.g. "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717"
8312
 *      We also accept a custom abbreviated syntax EPSG:2393+5717
8313
 *      or ESRI:103668+EPSG:5703
8314
 * </li>
8315
 * <li> OGC URN combining references for references for projected or derived
8316
 * CRSs
8317
 *      e.g. for Projected 3D CRS "UTM zone 31N / WGS 84 (3D)"
8318
 *      "urn:ogc:def:crs,crs:EPSG::4979,cs:PROJ::ENh,coordinateOperation:EPSG::16031"
8319
 * </li>
8320
 * <li>Extension of OGC URN for CoordinateMetadata.
8321
 *     e.g.
8322
 * "urn:ogc:def:coordinateMetadata:NRCAN::NAD83_CSRS_1997_MTM11_HT2_1997"</li>
8323
 * <li> OGC URN combining references for concatenated operations
8324
 *      e.g.
8325
 * "urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618"</li>
8326
 * <li>OGC URL for a single CRS. e.g.
8327
 * "http://www.opengis.net/def/crs/EPSG/0/4326"</li>
8328
 * <li>OGC URL for a compound
8329
 * CRS. e.g
8330
 * "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/3855"</li>
8331
 * <li>an Object name. e.g "WGS 84", "WGS 84 / UTM zone 31N". In that case as
8332
 *     uniqueness is not guaranteed, the function may apply heuristics to
8333
 *     determine the appropriate best match.</li>
8334
 * <li>a CRS name and a coordinate epoch, separated with '@'. For example
8335
 *     "ITRF2014@2025.0". (added in PROJ 9.2)</li>
8336
 * <li>a compound CRS made from two object names separated with " + ".
8337
 *     e.g. "WGS 84 + EGM96 height"</li>
8338
 * <li>PROJJSON string</li>
8339
 * </ul>
8340
 *
8341
 * @param text One of the above mentioned text format
8342
 * @param dbContext Database context, or nullptr (in which case database
8343
 * lookups will not work)
8344
 * @param usePROJ4InitRules When set to true,
8345
 * init=epsg:XXXX syntax will be allowed and will be interpreted according to
8346
 * PROJ.4 and PROJ.5 rules, that is geodeticCRS will have longitude, latitude
8347
 * order and will expect/output coordinates in radians. ProjectedCRS will have
8348
 * easting, northing axis order (except the ones with Transverse Mercator South
8349
 * Orientated projection). In that mode, the epsg:XXXX syntax will be also
8350
 * interpreted the same way.
8351
 * @throw ParsingException if the string cannot be parsed.
8352
 */
8353
BaseObjectNNPtr createFromUserInput(const std::string &text,
8354
                                    const DatabaseContextPtr &dbContext,
8355
330
                                    bool usePROJ4InitRules) {
8356
330
    return createFromUserInput(text, dbContext, usePROJ4InitRules, nullptr,
8357
330
                               /* ignoreCoordinateEpoch = */ false);
8358
330
}
8359
8360
// ---------------------------------------------------------------------------
8361
8362
/** \brief Instantiate a sub-class of BaseObject from a user specified text.
8363
 *
8364
 * The text can be a:
8365
 * <ul>
8366
 * <li>WKT string</li>
8367
 * <li>PROJ string</li>
8368
 * <li>database code, prefixed by its authority. e.g. "EPSG:4326"</li>
8369
 * <li>OGC URN. e.g. "urn:ogc:def:crs:EPSG::4326",
8370
 *     "urn:ogc:def:coordinateOperation:EPSG::1671",
8371
 *     "urn:ogc:def:ellipsoid:EPSG::7001"
8372
 *     or "urn:ogc:def:datum:EPSG::6326"</li>
8373
 * <li> OGC URN combining references for compound coordinate reference systems
8374
 *      e.g. "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717"
8375
 *      We also accept a custom abbreviated syntax EPSG:2393+5717
8376
 * </li>
8377
 * <li> OGC URN combining references for references for projected or derived
8378
 * CRSs
8379
 *      e.g. for Projected 3D CRS "UTM zone 31N / WGS 84 (3D)"
8380
 *      "urn:ogc:def:crs,crs:EPSG::4979,cs:PROJ::ENh,coordinateOperation:EPSG::16031"
8381
 * </li>
8382
 * <li>Extension of OGC URN for CoordinateMetadata.
8383
 *     e.g.
8384
 * "urn:ogc:def:coordinateMetadata:NRCAN::NAD83_CSRS_1997_MTM11_HT2_1997"</li>
8385
 * <li> OGC URN combining references for concatenated operations
8386
 *      e.g.
8387
 * "urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618"</li>
8388
 * <li>an Object name. e.g "WGS 84", "WGS 84 / UTM zone 31N". In that case as
8389
 *     uniqueness is not guaranteed, the function may apply heuristics to
8390
 *     determine the appropriate best match.</li>
8391
 * <li>a compound CRS made from two object names separated with " + ".
8392
 *     e.g. "WGS 84 + EGM96 height"</li>
8393
 * <li>PROJJSON string</li>
8394
 * </ul>
8395
 *
8396
 * @param text One of the above mentioned text format
8397
 * @param ctx PROJ context
8398
 * @throw ParsingException if the string cannot be parsed.
8399
 */
8400
16.9k
BaseObjectNNPtr createFromUserInput(const std::string &text, PJ_CONTEXT *ctx) {
8401
16.9k
    DatabaseContextPtr dbContext;
8402
16.9k
    try {
8403
16.9k
        if (ctx != nullptr) {
8404
            // Only connect to proj.db if needed
8405
16.9k
            if (text.find("proj=") == std::string::npos ||
8406
11.2k
                text.find("init=") != std::string::npos) {
8407
6.15k
                dbContext =
8408
6.15k
                    ctx->get_cpp_context()->getDatabaseContext().as_nullable();
8409
6.15k
            }
8410
16.9k
        }
8411
16.9k
    } catch (const std::exception &) {
8412
0
    }
8413
16.9k
    return createFromUserInput(text, dbContext, false, ctx,
8414
16.9k
                               /* ignoreCoordinateEpoch = */ false);
8415
16.9k
}
8416
8417
// ---------------------------------------------------------------------------
8418
8419
/** \brief Instantiate a sub-class of BaseObject from a WKT string.
8420
 *
8421
 * By default, validation is strict (to the extent of the checks that are
8422
 * actually implemented. Currently only WKT1 strict grammar is checked), and
8423
 * any issue detected will cause an exception to be thrown, unless
8424
 * setStrict(false) is called priorly.
8425
 *
8426
 * In non-strict mode, non-fatal issues will be recovered and simply listed
8427
 * in warningList(). This does not prevent more severe errors to cause an
8428
 * exception to be thrown.
8429
 *
8430
 * @throw ParsingException if the string cannot be parsed.
8431
 */
8432
2.89k
BaseObjectNNPtr WKTParser::createFromWKT(const std::string &wkt) {
8433
8434
2.89k
    const auto dialect = guessDialect(wkt);
8435
2.89k
    d->maybeEsriStyle_ = (dialect == WKTGuessedDialect::WKT1_ESRI);
8436
2.89k
    if (d->maybeEsriStyle_) {
8437
1.69k
        if (wkt.find("PARAMETER[\"X_Scale\",") != std::string::npos) {
8438
55
            d->esriStyle_ = true;
8439
55
            d->maybeEsriStyle_ = false;
8440
55
        }
8441
1.69k
    }
8442
8443
2.89k
    const auto build = [this, &wkt]() -> BaseObjectNNPtr {
8444
2.89k
        size_t indexEnd;
8445
2.89k
        WKTNodeNNPtr root = WKTNode::createFrom(wkt, 0, 0, indexEnd);
8446
2.89k
        const std::string &name(root->GP()->value());
8447
2.89k
        if (ci_equal(name, WKTConstants::DATUM) ||
8448
2.50k
            ci_equal(name, WKTConstants::GEODETICDATUM) ||
8449
2.50k
            ci_equal(name, WKTConstants::TRF)) {
8450
8451
101
            auto primeMeridian = PrimeMeridian::GREENWICH;
8452
101
            if (indexEnd < wkt.size()) {
8453
90
                indexEnd = skipSpace(wkt, indexEnd);
8454
90
                if (indexEnd < wkt.size() && wkt[indexEnd] == ',') {
8455
69
                    ++indexEnd;
8456
69
                    indexEnd = skipSpace(wkt, indexEnd);
8457
69
                    if (indexEnd < wkt.size() &&
8458
64
                        ci_starts_with(wkt.c_str() + indexEnd,
8459
64
                                       WKTConstants::PRIMEM.c_str())) {
8460
29
                        primeMeridian = d->buildPrimeMeridian(
8461
29
                            WKTNode::createFrom(wkt, indexEnd, 0, indexEnd),
8462
29
                            UnitOfMeasure::DEGREE);
8463
29
                    }
8464
69
                }
8465
90
            }
8466
101
            return d->buildGeodeticReferenceFrame(root, primeMeridian,
8467
101
                                                  null_node);
8468
2.79k
        } else if (ci_equal(name, WKTConstants::GEOGCS) ||
8469
2.01k
                   ci_equal(name, WKTConstants::PROJCS)) {
8470
            // Parse implicit compoundCRS from ESRI that is
8471
            // "PROJCS[...],VERTCS[...]" or "GEOGCS[...],VERTCS[...]"
8472
1.24k
            if (indexEnd < wkt.size()) {
8473
890
                indexEnd = skipSpace(wkt, indexEnd);
8474
890
                if (indexEnd < wkt.size() && wkt[indexEnd] == ',') {
8475
333
                    ++indexEnd;
8476
333
                    indexEnd = skipSpace(wkt, indexEnd);
8477
333
                    if (indexEnd < wkt.size() &&
8478
328
                        ci_starts_with(wkt.c_str() + indexEnd,
8479
328
                                       WKTConstants::VERTCS.c_str())) {
8480
238
                        auto horizCRS = d->buildCRS(root);
8481
238
                        if (horizCRS) {
8482
211
                            auto vertCRS =
8483
211
                                d->buildVerticalCRS(WKTNode::createFrom(
8484
211
                                    wkt, indexEnd, 0, indexEnd));
8485
211
                            return CompoundCRS::createLax(
8486
211
                                util::PropertyMap().set(
8487
211
                                    IdentifiedObject::NAME_KEY,
8488
211
                                    horizCRS->nameStr() + " + " +
8489
211
                                        vertCRS->nameStr()),
8490
211
                                {NN_NO_CHECK(horizCRS), vertCRS},
8491
211
                                d->dbContext_);
8492
211
                        }
8493
238
                    }
8494
333
                }
8495
890
            }
8496
1.24k
        }
8497
2.57k
        return d->build(root);
8498
2.89k
    };
8499
8500
2.89k
    auto obj = build();
8501
8502
2.89k
    if (dialect == WKTGuessedDialect::WKT1_GDAL ||
8503
1.32k
        dialect == WKTGuessedDialect::WKT1_ESRI) {
8504
885
        auto errorMsg = pj_wkt1_parse(wkt);
8505
885
        if (!errorMsg.empty()) {
8506
546
            d->emitGrammarError(errorMsg);
8507
546
        }
8508
2.00k
    } else if (dialect == WKTGuessedDialect::WKT2_2015 ||
8509
513
               dialect == WKTGuessedDialect::WKT2_2019) {
8510
513
        auto errorMsg = pj_wkt2_parse(wkt);
8511
513
        if (!errorMsg.empty()) {
8512
457
            d->emitGrammarError(errorMsg);
8513
457
        }
8514
513
    }
8515
8516
2.89k
    return obj;
8517
2.89k
}
8518
8519
// ---------------------------------------------------------------------------
8520
8521
/** \brief Attach a database context, to allow queries in it if needed.
8522
 */
8523
WKTParser &
8524
2.89k
WKTParser::attachDatabaseContext(const DatabaseContextPtr &dbContext) {
8525
2.89k
    d->dbContext_ = dbContext;
8526
2.89k
    return *this;
8527
2.89k
}
8528
8529
// ---------------------------------------------------------------------------
8530
8531
/** \brief Guess the "dialect" of the WKT string.
8532
 */
8533
WKTParser::WKTGuessedDialect
8534
2.89k
WKTParser::guessDialect(const std::string &inputWkt) noexcept {
8535
8536
    // cppcheck complains (rightly) that the method could be static
8537
2.89k
    (void)this;
8538
8539
2.89k
    std::string wkt = inputWkt;
8540
2.89k
    std::size_t idxFirstCharNotSpace = wkt.find_first_not_of(" \t\r\n");
8541
2.89k
    if (idxFirstCharNotSpace > 0 && idxFirstCharNotSpace != std::string::npos) {
8542
0
        wkt = wkt.substr(idxFirstCharNotSpace);
8543
0
    }
8544
2.89k
    if (ci_starts_with(wkt, WKTConstants::VERTCS)) {
8545
174
        return WKTGuessedDialect::WKT1_ESRI;
8546
174
    }
8547
2.71k
    const std::string *const wkt1_keywords[] = {
8548
2.71k
        &WKTConstants::GEOCCS, &WKTConstants::GEOGCS,  &WKTConstants::COMPD_CS,
8549
2.71k
        &WKTConstants::PROJCS, &WKTConstants::VERT_CS, &WKTConstants::LOCAL_CS};
8550
11.3k
    for (const auto &pointerKeyword : wkt1_keywords) {
8551
11.3k
        if (ci_starts_with(wkt, *pointerKeyword)) {
8552
8553
1.82k
            if ((ci_find(wkt, "GEOGCS[\"GCS_") != std::string::npos ||
8554
1.48k
                 (!ci_starts_with(wkt, WKTConstants::LOCAL_CS) &&
8555
1.34k
                  ci_find(wkt, "AXIS[") == std::string::npos &&
8556
1.24k
                  ci_find(wkt, "AUTHORITY[") == std::string::npos)) &&
8557
                // WKT1:GDAL and WKT1:ESRI have both a
8558
                // Hotine_Oblique_Mercator_Azimuth_Center If providing a
8559
                // WKT1:GDAL without AXIS, we may wrongly detect it as WKT1:ESRI
8560
                // and skip the rectified_grid_angle parameter cf
8561
                // https://github.com/OSGeo/PROJ/issues/3279
8562
1.52k
                ci_find(wkt, "PARAMETER[\"rectified_grid_angle") ==
8563
1.52k
                    std::string::npos) {
8564
1.52k
                return WKTGuessedDialect::WKT1_ESRI;
8565
1.52k
            }
8566
8567
298
            return WKTGuessedDialect::WKT1_GDAL;
8568
1.82k
        }
8569
11.3k
    }
8570
8571
897
    const std::string *const wkt2_2019_only_keywords[] = {
8572
897
        &WKTConstants::GEOGCRS,
8573
        // contained in previous one
8574
        // &WKTConstants::BASEGEOGCRS,
8575
897
        &WKTConstants::CONCATENATEDOPERATION, &WKTConstants::USAGE,
8576
897
        &WKTConstants::DYNAMIC, &WKTConstants::FRAMEEPOCH, &WKTConstants::MODEL,
8577
897
        &WKTConstants::VELOCITYGRID, &WKTConstants::ENSEMBLE,
8578
897
        &WKTConstants::DERIVEDPROJCRS, &WKTConstants::BASEPROJCRS,
8579
897
        &WKTConstants::GEOGRAPHICCRS, &WKTConstants::TRF, &WKTConstants::VRF,
8580
897
        &WKTConstants::POINTMOTIONOPERATION};
8581
8582
12.0k
    for (const auto &pointerKeyword : wkt2_2019_only_keywords) {
8583
12.0k
        auto pos = ci_find(wkt, *pointerKeyword);
8584
12.0k
        if (pos != std::string::npos &&
8585
295
            wkt[pos + pointerKeyword->size()] == '[') {
8586
232
            return WKTGuessedDialect::WKT2_2019;
8587
232
        }
8588
12.0k
    }
8589
665
    static const char *const wkt2_2019_only_substrings[] = {
8590
665
        "CS[TemporalDateTime,",
8591
665
        "CS[TemporalCount,",
8592
665
        "CS[TemporalMeasure,",
8593
665
    };
8594
1.98k
    for (const auto &substrings : wkt2_2019_only_substrings) {
8595
1.98k
        if (ci_find(wkt, substrings) != std::string::npos) {
8596
15
            return WKTGuessedDialect::WKT2_2019;
8597
15
        }
8598
1.98k
    }
8599
8600
23.4k
    for (const auto &wktConstant : WKTConstants::constants()) {
8601
23.4k
        if (ci_starts_with(wkt, wktConstant)) {
8602
651
            for (auto wktPtr = wkt.c_str() + wktConstant.size();
8603
856
                 *wktPtr != '\0'; ++wktPtr) {
8604
856
                if (isspace(static_cast<unsigned char>(*wktPtr)))
8605
205
                    continue;
8606
651
                if (*wktPtr == '[') {
8607
650
                    return WKTGuessedDialect::WKT2_2015;
8608
650
                }
8609
1
                break;
8610
651
            }
8611
651
        }
8612
23.4k
    }
8613
8614
0
    return WKTGuessedDialect::NOT_WKT;
8615
650
}
8616
8617
// ---------------------------------------------------------------------------
8618
8619
//! @cond Doxygen_Suppress
8620
FormattingException::FormattingException(const char *message)
8621
15
    : Exception(message) {}
8622
8623
// ---------------------------------------------------------------------------
8624
8625
FormattingException::FormattingException(const std::string &message)
8626
619
    : Exception(message) {}
8627
8628
// ---------------------------------------------------------------------------
8629
8630
0
FormattingException::FormattingException(const FormattingException &) = default;
8631
8632
// ---------------------------------------------------------------------------
8633
8634
634
FormattingException::~FormattingException() = default;
8635
8636
// ---------------------------------------------------------------------------
8637
8638
4
void FormattingException::Throw(const char *msg) {
8639
4
    throw FormattingException(msg);
8640
4
}
8641
8642
// ---------------------------------------------------------------------------
8643
8644
0
void FormattingException::Throw(const std::string &msg) {
8645
0
    throw FormattingException(msg);
8646
0
}
8647
8648
// ---------------------------------------------------------------------------
8649
8650
4.26k
ParsingException::ParsingException(const char *message) : Exception(message) {}
8651
8652
// ---------------------------------------------------------------------------
8653
8654
ParsingException::ParsingException(const std::string &message)
8655
3.32k
    : Exception(message) {}
8656
8657
// ---------------------------------------------------------------------------
8658
8659
0
ParsingException::ParsingException(const ParsingException &) = default;
8660
8661
// ---------------------------------------------------------------------------
8662
8663
7.58k
ParsingException::~ParsingException() = default;
8664
8665
// ---------------------------------------------------------------------------
8666
8667
1.25M
IPROJStringExportable::~IPROJStringExportable() = default;
8668
8669
// ---------------------------------------------------------------------------
8670
8671
std::string IPROJStringExportable::exportToPROJString(
8672
122k
    PROJStringFormatter *formatter) const {
8673
122k
    const bool bIsCRS = dynamic_cast<const crs::CRS *>(this) != nullptr;
8674
122k
    if (bIsCRS) {
8675
0
        formatter->setCRSExport(true);
8676
0
    }
8677
122k
    _exportToPROJString(formatter);
8678
122k
    if (formatter->getAddNoDefs() && bIsCRS) {
8679
0
        if (!formatter->hasParam("no_defs")) {
8680
0
            formatter->addParam("no_defs");
8681
0
        }
8682
0
    }
8683
122k
    if (bIsCRS) {
8684
0
        if (!formatter->hasParam("type")) {
8685
0
            formatter->addParam("type", "crs");
8686
0
        }
8687
0
        formatter->setCRSExport(false);
8688
0
    }
8689
122k
    return formatter->toString();
8690
122k
}
8691
//! @endcond
8692
8693
// ---------------------------------------------------------------------------
8694
8695
//! @cond Doxygen_Suppress
8696
8697
struct Step {
8698
    std::string name{};
8699
    bool isInit = false;
8700
    bool inverted{false};
8701
8702
    struct KeyValue {
8703
        std::string key{};
8704
        std::string value{};
8705
        bool usedByParser = false; // only for PROJStringParser used
8706
8707
3.20M
        explicit KeyValue(const std::string &keyIn) : key(keyIn) {}
8708
8709
        KeyValue(const char *keyIn, const std::string &valueIn);
8710
8711
        KeyValue(const std::string &keyIn, const std::string &valueIn)
8712
7.65M
            : key(keyIn), value(valueIn) {}
8713
8714
        // cppcheck-suppress functionStatic
8715
5.93M
        bool keyEquals(const char *otherKey) const noexcept {
8716
5.93M
            return key == otherKey;
8717
5.93M
        }
8718
8719
        // cppcheck-suppress functionStatic
8720
1.98M
        bool equals(const char *otherKey, const char *otherVal) const noexcept {
8721
1.98M
            return key == otherKey && value == otherVal;
8722
1.98M
        }
8723
8724
549
        bool operator==(const KeyValue &other) const noexcept {
8725
549
            return key == other.key && value == other.value;
8726
549
        }
8727
8728
104k
        bool operator!=(const KeyValue &other) const noexcept {
8729
104k
            return key != other.key || value != other.value;
8730
104k
        }
8731
    };
8732
8733
    std::vector<KeyValue> paramValues{};
8734
8735
54.2k
    bool hasKey(const char *keyName) const {
8736
564k
        for (const auto &kv : paramValues) {
8737
564k
            if (kv.key == keyName) {
8738
41
                return true;
8739
41
            }
8740
564k
        }
8741
54.2k
        return false;
8742
54.2k
    }
8743
};
8744
8745
Step::KeyValue::KeyValue(const char *keyIn, const std::string &valueIn)
8746
77.1k
    : key(keyIn), value(valueIn) {}
8747
8748
struct PROJStringFormatter::Private {
8749
    PROJStringFormatter::Convention convention_ =
8750
        PROJStringFormatter::Convention::PROJ_5;
8751
    std::vector<double> toWGS84Parameters_{};
8752
    std::string vDatumExtension_{};
8753
    std::string geoidCRSValue_{};
8754
    std::string hDatumExtension_{};
8755
    crs::GeographicCRSPtr geogCRSOfCompoundCRS_{};
8756
8757
    std::list<Step> steps_{};
8758
    std::vector<Step::KeyValue> globalParamValues_{};
8759
8760
    struct InversionStackElt {
8761
        std::list<Step>::iterator startIter{};
8762
        bool iterValid = false;
8763
        bool currentInversionState = false;
8764
    };
8765
    std::vector<InversionStackElt> inversionStack_{InversionStackElt()};
8766
    bool omitProjLongLatIfPossible_ = false;
8767
    std::vector<bool> omitZUnitConversion_{false};
8768
    std::vector<bool> omitHorizontalConversionInVertTransformation_{false};
8769
    DatabaseContextPtr dbContext_{};
8770
    bool useApproxTMerc_ = false;
8771
    bool addNoDefs_ = true;
8772
    bool coordOperationOptimizations_ = false;
8773
    bool crsExport_ = false;
8774
    bool legacyCRSToCRSContext_ = false;
8775
    bool multiLine_ = false;
8776
    bool normalizeOutput_ = false;
8777
    int indentWidth_ = 2;
8778
    int indentLevel_ = 0;
8779
    int maxLineLength_ = 80;
8780
8781
    std::string result_{};
8782
8783
    // cppcheck-suppress functionStatic
8784
    void appendToResult(const char *str);
8785
8786
    // cppcheck-suppress functionStatic
8787
    void addStep();
8788
};
8789
8790
//! @endcond
8791
8792
// ---------------------------------------------------------------------------
8793
8794
//! @cond Doxygen_Suppress
8795
PROJStringFormatter::PROJStringFormatter(Convention conventionIn,
8796
                                         const DatabaseContextPtr &dbContext)
8797
358k
    : d(std::make_unique<Private>()) {
8798
358k
    d->convention_ = conventionIn;
8799
358k
    d->dbContext_ = dbContext;
8800
358k
}
8801
//! @endcond
8802
8803
// ---------------------------------------------------------------------------
8804
8805
//! @cond Doxygen_Suppress
8806
358k
PROJStringFormatter::~PROJStringFormatter() = default;
8807
//! @endcond
8808
8809
// ---------------------------------------------------------------------------
8810
8811
/** \brief Constructs a new formatter.
8812
 *
8813
 * A formatter can be used only once (its internal state is mutated)
8814
 *
8815
 * Its default behavior can be adjusted with the different setters.
8816
 *
8817
 * @param conventionIn PROJ string flavor. Defaults to Convention::PROJ_5
8818
 * @param dbContext Database context (can help to find alternative grid names).
8819
 * May be nullptr
8820
 * @return new formatter.
8821
 */
8822
PROJStringFormatterNNPtr
8823
PROJStringFormatter::create(Convention conventionIn,
8824
358k
                            DatabaseContextPtr dbContext) {
8825
358k
    return NN_NO_CHECK(PROJStringFormatter::make_unique<PROJStringFormatter>(
8826
358k
        conventionIn, dbContext));
8827
358k
}
8828
8829
// ---------------------------------------------------------------------------
8830
8831
/** \brief Set whether approximate Transverse Mercator or UTM should be used */
8832
0
void PROJStringFormatter::setUseApproxTMerc(bool flag) {
8833
0
    d->useApproxTMerc_ = flag;
8834
0
}
8835
8836
// ---------------------------------------------------------------------------
8837
8838
/** \brief Whether to use multi line output or not. */
8839
PROJStringFormatter &
8840
0
PROJStringFormatter::setMultiLine(bool multiLine) noexcept {
8841
0
    d->multiLine_ = multiLine;
8842
0
    return *this;
8843
0
}
8844
8845
// ---------------------------------------------------------------------------
8846
8847
/** \brief Set number of spaces for each indentation level (defaults to 2).
8848
 */
8849
PROJStringFormatter &
8850
0
PROJStringFormatter::setIndentationWidth(int width) noexcept {
8851
0
    d->indentWidth_ = width;
8852
0
    return *this;
8853
0
}
8854
8855
// ---------------------------------------------------------------------------
8856
8857
/** \brief Set the maximum size of a line (when multiline output is enable).
8858
 * Can be set to 0 for unlimited length.
8859
 */
8860
PROJStringFormatter &
8861
0
PROJStringFormatter::setMaxLineLength(int maxLineLength) noexcept {
8862
0
    d->maxLineLength_ = maxLineLength;
8863
0
    return *this;
8864
0
}
8865
8866
// ---------------------------------------------------------------------------
8867
8868
/** \brief Returns the PROJ string. */
8869
243k
const std::string &PROJStringFormatter::toString() const {
8870
8871
243k
    assert(d->inversionStack_.size() == 1);
8872
8873
243k
    d->result_.clear();
8874
8875
243k
    auto &steps = d->steps_;
8876
8877
243k
    if (d->normalizeOutput_) {
8878
        // Sort +key=value options of each step in lexicographic order.
8879
13.6k
        for (auto &step : steps) {
8880
11.9k
            std::sort(step.paramValues.begin(), step.paramValues.end(),
8881
4.64M
                      [](const Step::KeyValue &a, const Step::KeyValue &b) {
8882
4.64M
                          return a.key < b.key;
8883
4.64M
                      });
8884
11.9k
        }
8885
13.6k
    }
8886
8887
3.59M
    for (auto iter = steps.begin(); iter != steps.end();) {
8888
        // Remove no-op helmert
8889
3.35M
        auto &step = *iter;
8890
3.35M
        const auto paramCount = step.paramValues.size();
8891
3.35M
        if (step.name == "helmert" && (paramCount == 3 || paramCount == 8) &&
8892
154k
            step.paramValues[0].equals("x", "0") &&
8893
27.0k
            step.paramValues[1].equals("y", "0") &&
8894
17.6k
            step.paramValues[2].equals("z", "0") &&
8895
17.4k
            (paramCount == 3 ||
8896
436
             (step.paramValues[3].equals("rx", "0") &&
8897
149
              step.paramValues[4].equals("ry", "0") &&
8898
147
              step.paramValues[5].equals("rz", "0") &&
8899
99
              step.paramValues[6].equals("s", "0") &&
8900
17.0k
              step.paramValues[7].keyEquals("convention")))) {
8901
17.0k
            iter = steps.erase(iter);
8902
3.33M
        } else if (d->coordOperationOptimizations_ &&
8903
2.93M
                   step.name == "unitconvert" && paramCount == 2 &&
8904
828k
                   step.paramValues[0].keyEquals("xy_in") &&
8905
818k
                   step.paramValues[1].keyEquals("xy_out") &&
8906
817k
                   step.paramValues[0].value == step.paramValues[1].value) {
8907
44
            iter = steps.erase(iter);
8908
3.33M
        } else if (step.name == "push" && step.inverted) {
8909
28.4k
            step.name = "pop";
8910
28.4k
            step.inverted = false;
8911
28.4k
            ++iter;
8912
3.30M
        } else if (step.name == "pop" && step.inverted) {
8913
35.2k
            step.name = "push";
8914
35.2k
            step.inverted = false;
8915
35.2k
            ++iter;
8916
3.27M
        } else if (step.name == "noop" && steps.size() > 1) {
8917
1.75k
            iter = steps.erase(iter);
8918
3.27M
        } else {
8919
3.27M
            ++iter;
8920
3.27M
        }
8921
3.35M
    }
8922
8923
3.33M
    for (auto &step : steps) {
8924
3.33M
        if (!step.inverted) {
8925
1.86M
            continue;
8926
1.86M
        }
8927
8928
1.46M
        const auto paramCount = step.paramValues.size();
8929
8930
        // axisswap order=2,1 (or 1,-2) is its own inverse
8931
1.46M
        if (step.name == "axisswap" && paramCount == 1 &&
8932
325k
            (step.paramValues[0].equals("order", "2,1") ||
8933
319k
             step.paramValues[0].equals("order", "1,-2"))) {
8934
319k
            step.inverted = false;
8935
319k
            continue;
8936
319k
        }
8937
8938
        // axisswap inv order=2,-1 ==> axisswap order -2,1
8939
1.14M
        if (step.name == "axisswap" && paramCount == 1 &&
8940
6.27k
            step.paramValues[0].equals("order", "2,-1")) {
8941
611
            step.inverted = false;
8942
611
            step.paramValues[0] = Step::KeyValue("order", "-2,1");
8943
611
            continue;
8944
611
        }
8945
8946
        // axisswap order=1,2,-3 is its own inverse
8947
1.14M
        if (step.name == "axisswap" && paramCount == 1 &&
8948
5.66k
            step.paramValues[0].equals("order", "1,2,-3")) {
8949
0
            step.inverted = false;
8950
0
            continue;
8951
0
        }
8952
8953
        // handle unitconvert inverse
8954
1.14M
        if (step.name == "unitconvert" && paramCount == 2 &&
8955
445k
            step.paramValues[0].keyEquals("xy_in") &&
8956
436k
            step.paramValues[1].keyEquals("xy_out")) {
8957
436k
            std::swap(step.paramValues[0].value, step.paramValues[1].value);
8958
436k
            step.inverted = false;
8959
436k
            continue;
8960
436k
        }
8961
8962
709k
        if (step.name == "unitconvert" && paramCount == 2 &&
8963
8.59k
            step.paramValues[0].keyEquals("z_in") &&
8964
7.16k
            step.paramValues[1].keyEquals("z_out")) {
8965
6.32k
            std::swap(step.paramValues[0].value, step.paramValues[1].value);
8966
6.32k
            step.inverted = false;
8967
6.32k
            continue;
8968
6.32k
        }
8969
8970
703k
        if (step.name == "unitconvert" && paramCount == 4 &&
8971
33.4k
            step.paramValues[0].keyEquals("xy_in") &&
8972
32.7k
            step.paramValues[1].keyEquals("z_in") &&
8973
32.3k
            step.paramValues[2].keyEquals("xy_out") &&
8974
32.1k
            step.paramValues[3].keyEquals("z_out")) {
8975
32.0k
            std::swap(step.paramValues[0].value, step.paramValues[2].value);
8976
32.0k
            std::swap(step.paramValues[1].value, step.paramValues[3].value);
8977
32.0k
            step.inverted = false;
8978
32.0k
            continue;
8979
32.0k
        }
8980
8981
        // set does the same in forward and inverse paths
8982
671k
        if (step.name == "set") {
8983
4.38k
            step.inverted = false;
8984
4.38k
        }
8985
671k
    }
8986
8987
243k
    {
8988
243k
        auto iterCur = steps.begin();
8989
243k
        if (iterCur != steps.end()) {
8990
236k
            ++iterCur;
8991
236k
        }
8992
3.87M
        while (iterCur != steps.end()) {
8993
8994
3.63M
            assert(iterCur != steps.begin());
8995
3.63M
            auto iterPrev = std::prev(iterCur);
8996
3.63M
            auto &prevStep = *iterPrev;
8997
3.63M
            auto &curStep = *iterCur;
8998
8999
3.63M
            const auto curStepParamCount = curStep.paramValues.size();
9000
3.63M
            const auto prevStepParamCount = prevStep.paramValues.size();
9001
9002
3.63M
            const auto deletePrevAndCurIter = [&steps, &iterPrev, &iterCur]() {
9003
729k
                iterCur = steps.erase(iterPrev, std::next(iterCur));
9004
729k
                if (iterCur != steps.begin())
9005
654k
                    iterCur = std::prev(iterCur);
9006
729k
                if (iterCur == steps.begin() && iterCur != steps.end())
9007
149k
                    ++iterCur;
9008
729k
            };
9009
9010
            // longlat (or its inverse) with ellipsoid only is a no-op
9011
            // do that only for an internal step
9012
3.63M
            if (std::next(iterCur) != steps.end() &&
9013
3.40M
                curStep.name == "longlat" && curStepParamCount == 1 &&
9014
363k
                curStep.paramValues[0].keyEquals("ellps")) {
9015
342k
                iterCur = steps.erase(iterCur);
9016
342k
                continue;
9017
342k
            }
9018
9019
            // push v_x followed by pop v_x is a no-op.
9020
3.28M
            if (curStep.name == "pop" && prevStep.name == "push" &&
9021
12.1k
                !curStep.inverted && !prevStep.inverted &&
9022
12.1k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9023
11.3k
                curStep.paramValues[0].key == prevStep.paramValues[0].key) {
9024
11.1k
                deletePrevAndCurIter();
9025
11.1k
                continue;
9026
11.1k
            }
9027
9028
            // pop v_x followed by push v_x is, almost, a no-op. For our
9029
            // purposes,
9030
            // we consider it as a no-op for better pipeline optimizations.
9031
3.27M
            if (curStep.name == "push" && prevStep.name == "pop" &&
9032
6.50k
                !curStep.inverted && !prevStep.inverted &&
9033
6.50k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9034
5.18k
                curStep.paramValues[0].key == prevStep.paramValues[0].key) {
9035
4.85k
                deletePrevAndCurIter();
9036
4.85k
                continue;
9037
4.85k
            }
9038
9039
            // unitconvert (xy) followed by its inverse is a no-op
9040
3.27M
            if (curStep.name == "unitconvert" &&
9041
1.19M
                prevStep.name == "unitconvert" && !curStep.inverted &&
9042
375k
                !prevStep.inverted && curStepParamCount == 2 &&
9043
342k
                prevStepParamCount == 2 &&
9044
314k
                curStep.paramValues[0].keyEquals("xy_in") &&
9045
310k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9046
304k
                curStep.paramValues[1].keyEquals("xy_out") &&
9047
304k
                prevStep.paramValues[1].keyEquals("xy_out") &&
9048
304k
                curStep.paramValues[0].value == prevStep.paramValues[1].value &&
9049
304k
                curStep.paramValues[1].value == prevStep.paramValues[0].value) {
9050
304k
                deletePrevAndCurIter();
9051
304k
                continue;
9052
304k
            }
9053
9054
            // unitconvert (z) followed by its inverse is a no-op
9055
2.96M
            if (curStep.name == "unitconvert" &&
9056
892k
                prevStep.name == "unitconvert" && !curStep.inverted &&
9057
71.0k
                !prevStep.inverted && curStepParamCount == 2 &&
9058
38.0k
                prevStepParamCount == 2 &&
9059
10.4k
                curStep.paramValues[0].keyEquals("z_in") &&
9060
3.49k
                prevStep.paramValues[0].keyEquals("z_in") &&
9061
1.34k
                curStep.paramValues[1].keyEquals("z_out") &&
9062
1.19k
                prevStep.paramValues[1].keyEquals("z_out") &&
9063
1.13k
                curStep.paramValues[0].value == prevStep.paramValues[1].value &&
9064
1.01k
                curStep.paramValues[1].value == prevStep.paramValues[0].value) {
9065
884
                deletePrevAndCurIter();
9066
884
                continue;
9067
884
            }
9068
9069
            // unitconvert (xyz) followed by its inverse is a no-op
9070
2.96M
            if (curStep.name == "unitconvert" &&
9071
891k
                prevStep.name == "unitconvert" && !curStep.inverted &&
9072
70.1k
                !prevStep.inverted && curStepParamCount == 4 &&
9073
30.5k
                prevStepParamCount == 4 &&
9074
16.8k
                curStep.paramValues[0].keyEquals("xy_in") &&
9075
16.5k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9076
16.3k
                curStep.paramValues[1].keyEquals("z_in") &&
9077
16.1k
                prevStep.paramValues[1].keyEquals("z_in") &&
9078
16.0k
                curStep.paramValues[2].keyEquals("xy_out") &&
9079
16.0k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9080
15.9k
                curStep.paramValues[3].keyEquals("z_out") &&
9081
15.9k
                prevStep.paramValues[3].keyEquals("z_out") &&
9082
15.9k
                curStep.paramValues[0].value == prevStep.paramValues[2].value &&
9083
15.4k
                curStep.paramValues[1].value == prevStep.paramValues[3].value &&
9084
15.1k
                curStep.paramValues[2].value == prevStep.paramValues[0].value &&
9085
15.0k
                curStep.paramValues[3].value == prevStep.paramValues[1].value) {
9086
13.6k
                deletePrevAndCurIter();
9087
13.6k
                continue;
9088
13.6k
            }
9089
9090
2.95M
            const auto deletePrevIter = [&steps, &iterPrev, &iterCur]() {
9091
16.9k
                steps.erase(iterPrev, iterCur);
9092
16.9k
                if (iterCur != steps.begin())
9093
14.2k
                    iterCur = std::prev(iterCur);
9094
16.9k
                if (iterCur == steps.begin())
9095
4.22k
                    ++iterCur;
9096
16.9k
            };
9097
9098
            // combine unitconvert (xy) and unitconvert (z)
9099
2.95M
            bool changeDone = false;
9100
8.84M
            for (int k = 0; k < 2; ++k) {
9101
5.90M
                auto &first = (k == 0) ? curStep : prevStep;
9102
5.90M
                auto &second = (k == 0) ? prevStep : curStep;
9103
5.90M
                if (first.name == "unitconvert" &&
9104
1.45M
                    second.name == "unitconvert" && !first.inverted &&
9105
110k
                    !second.inverted && first.paramValues.size() == 2 &&
9106
58.7k
                    second.paramValues.size() == 2 &&
9107
17.1k
                    second.paramValues[0].keyEquals("xy_in") &&
9108
9.16k
                    second.paramValues[1].keyEquals("xy_out") &&
9109
8.71k
                    first.paramValues[0].keyEquals("z_in") &&
9110
7.90k
                    first.paramValues[1].keyEquals("z_out")) {
9111
9112
7.59k
                    const std::string xy_in(second.paramValues[0].value);
9113
7.59k
                    const std::string xy_out(second.paramValues[1].value);
9114
7.59k
                    const std::string z_in(first.paramValues[0].value);
9115
7.59k
                    const std::string z_out(first.paramValues[1].value);
9116
9117
7.59k
                    iterCur->paramValues.clear();
9118
7.59k
                    iterCur->paramValues.emplace_back(
9119
7.59k
                        Step::KeyValue("xy_in", xy_in));
9120
7.59k
                    iterCur->paramValues.emplace_back(
9121
7.59k
                        Step::KeyValue("z_in", z_in));
9122
7.59k
                    iterCur->paramValues.emplace_back(
9123
7.59k
                        Step::KeyValue("xy_out", xy_out));
9124
7.59k
                    iterCur->paramValues.emplace_back(
9125
7.59k
                        Step::KeyValue("z_out", z_out));
9126
9127
7.59k
                    deletePrevIter();
9128
7.59k
                    changeDone = true;
9129
7.59k
                    break;
9130
7.59k
                }
9131
5.90M
            }
9132
2.95M
            if (changeDone) {
9133
7.59k
                continue;
9134
7.59k
            }
9135
9136
            // +step +proj=unitconvert +xy_in=X1 +xy_out=X2
9137
            //  +step +proj=unitconvert +xy_in=X2 +z_in=Z1 +xy_out=X1 +z_out=Z2
9138
            // ==> step +proj=unitconvert +z_in=Z1 +z_out=Z2
9139
8.78M
            for (int k = 0; k < 2; ++k) {
9140
5.87M
                auto &first = (k == 0) ? curStep : prevStep;
9141
5.87M
                auto &second = (k == 0) ? prevStep : curStep;
9142
5.87M
                if (first.name == "unitconvert" &&
9143
1.43M
                    second.name == "unitconvert" && !first.inverted &&
9144
85.3k
                    !second.inverted && first.paramValues.size() == 4 &&
9145
47.5k
                    second.paramValues.size() == 2 &&
9146
41.0k
                    first.paramValues[0].keyEquals("xy_in") &&
9147
40.5k
                    first.paramValues[1].keyEquals("z_in") &&
9148
40.3k
                    first.paramValues[2].keyEquals("xy_out") &&
9149
40.2k
                    first.paramValues[3].keyEquals("z_out") &&
9150
40.0k
                    second.paramValues[0].keyEquals("xy_in") &&
9151
38.8k
                    second.paramValues[1].keyEquals("xy_out") &&
9152
38.7k
                    first.paramValues[0].value == second.paramValues[1].value &&
9153
38.2k
                    first.paramValues[2].value == second.paramValues[0].value) {
9154
38.2k
                    const std::string z_in(first.paramValues[1].value);
9155
38.2k
                    const std::string z_out(first.paramValues[3].value);
9156
38.2k
                    if (z_in != z_out) {
9157
6.97k
                        iterCur->paramValues.clear();
9158
6.97k
                        iterCur->paramValues.emplace_back(
9159
6.97k
                            Step::KeyValue("z_in", z_in));
9160
6.97k
                        iterCur->paramValues.emplace_back(
9161
6.97k
                            Step::KeyValue("z_out", z_out));
9162
6.97k
                        deletePrevIter();
9163
31.2k
                    } else {
9164
31.2k
                        deletePrevAndCurIter();
9165
31.2k
                    }
9166
38.2k
                    changeDone = true;
9167
38.2k
                    break;
9168
38.2k
                }
9169
5.87M
            }
9170
2.94M
            if (changeDone) {
9171
38.2k
                continue;
9172
38.2k
            }
9173
9174
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2
9175
            // +step +proj=unitconvert +z_in=Z2 +z_out=Z3
9176
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2
9177
            // +z_out=Z3
9178
2.90M
            if (prevStep.name == "unitconvert" &&
9179
534k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9180
10.4k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9181
4.60k
                curStep.paramValues.size() == 2 &&
9182
1.40k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9183
1.17k
                prevStep.paramValues[1].keyEquals("z_in") &&
9184
1.08k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9185
972
                prevStep.paramValues[3].keyEquals("z_out") &&
9186
918
                curStep.paramValues[0].keyEquals("z_in") &&
9187
583
                curStep.paramValues[1].keyEquals("z_out") &&
9188
498
                prevStep.paramValues[3].value == curStep.paramValues[0].value) {
9189
426
                const std::string xy_in(prevStep.paramValues[0].value);
9190
426
                const std::string z_in(prevStep.paramValues[1].value);
9191
426
                const std::string xy_out(prevStep.paramValues[2].value);
9192
426
                const std::string z_out(curStep.paramValues[1].value);
9193
9194
426
                iterCur->paramValues.clear();
9195
426
                iterCur->paramValues.emplace_back(
9196
426
                    Step::KeyValue("xy_in", xy_in));
9197
426
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9198
426
                iterCur->paramValues.emplace_back(
9199
426
                    Step::KeyValue("xy_out", xy_out));
9200
426
                iterCur->paramValues.emplace_back(
9201
426
                    Step::KeyValue("z_out", z_out));
9202
9203
426
                deletePrevIter();
9204
426
                continue;
9205
426
            }
9206
9207
            // +step +proj=unitconvert +z_in=Z1 +z_out=Z2
9208
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X2 +z_out=Z3
9209
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2
9210
            // +z_out=Z3
9211
2.90M
            if (prevStep.name == "unitconvert" &&
9212
534k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9213
9.98k
                !curStep.inverted && prevStep.paramValues.size() == 2 &&
9214
3.75k
                curStep.paramValues.size() == 4 &&
9215
1.46k
                prevStep.paramValues[0].keyEquals("z_in") &&
9216
593
                prevStep.paramValues[1].keyEquals("z_out") &&
9217
514
                curStep.paramValues[0].keyEquals("xy_in") &&
9218
477
                curStep.paramValues[1].keyEquals("z_in") &&
9219
461
                curStep.paramValues[2].keyEquals("xy_out") &&
9220
450
                curStep.paramValues[3].keyEquals("z_out") &&
9221
450
                prevStep.paramValues[1].value == curStep.paramValues[1].value) {
9222
112
                const std::string xy_in(curStep.paramValues[0].value);
9223
112
                const std::string z_in(prevStep.paramValues[0].value);
9224
112
                const std::string xy_out(curStep.paramValues[2].value);
9225
112
                const std::string z_out(curStep.paramValues[3].value);
9226
9227
112
                iterCur->paramValues.clear();
9228
112
                iterCur->paramValues.emplace_back(
9229
112
                    Step::KeyValue("xy_in", xy_in));
9230
112
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9231
112
                iterCur->paramValues.emplace_back(
9232
112
                    Step::KeyValue("xy_out", xy_out));
9233
112
                iterCur->paramValues.emplace_back(
9234
112
                    Step::KeyValue("z_out", z_out));
9235
9236
112
                deletePrevIter();
9237
112
                continue;
9238
112
            }
9239
9240
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2
9241
            // +step +proj=unitconvert +xy_in=X2 +xy_out=X3
9242
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3
9243
            // +z_out=Z2
9244
2.90M
            if (prevStep.name == "unitconvert" &&
9245
534k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9246
9.87k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9247
4.17k
                curStep.paramValues.size() == 2 &&
9248
982
                prevStep.paramValues[0].keyEquals("xy_in") &&
9249
745
                prevStep.paramValues[1].keyEquals("z_in") &&
9250
659
                prevStep.paramValues[2].keyEquals("xy_out") &&
9251
546
                prevStep.paramValues[3].keyEquals("z_out") &&
9252
492
                curStep.paramValues[0].keyEquals("xy_in") &&
9253
251
                curStep.paramValues[1].keyEquals("xy_out") &&
9254
203
                prevStep.paramValues[2].value == curStep.paramValues[0].value) {
9255
19
                const std::string xy_in(prevStep.paramValues[0].value);
9256
19
                const std::string z_in(prevStep.paramValues[1].value);
9257
19
                const std::string xy_out(curStep.paramValues[1].value);
9258
19
                const std::string z_out(prevStep.paramValues[3].value);
9259
9260
19
                iterCur->paramValues.clear();
9261
19
                iterCur->paramValues.emplace_back(
9262
19
                    Step::KeyValue("xy_in", xy_in));
9263
19
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9264
19
                iterCur->paramValues.emplace_back(
9265
19
                    Step::KeyValue("xy_out", xy_out));
9266
19
                iterCur->paramValues.emplace_back(
9267
19
                    Step::KeyValue("z_out", z_out));
9268
9269
19
                deletePrevIter();
9270
19
                continue;
9271
19
            }
9272
9273
            // clang-format off
9274
            // A bit odd. Used to simplify geog3d_feet -> EPSG:6318+6360
9275
            // of https://github.com/OSGeo/PROJ/issues/3938
9276
            // where we get originally
9277
            // +step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=us-ft
9278
            // +step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m
9279
            // and want it simplified as:
9280
            // +step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=deg +z_out=us-ft
9281
            //
9282
            // More generally:
9283
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2
9284
            // +step +proj=unitconvert +xy_in=X2 +z_in=Z3 +xy_out=X3 +z_out=Z3
9285
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3 +z_out=Z2
9286
            // clang-format on
9287
2.90M
            if (prevStep.name == "unitconvert" &&
9288
534k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9289
9.85k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9290
4.16k
                curStep.paramValues.size() == 4 &&
9291
3.15k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9292
2.89k
                prevStep.paramValues[1].keyEquals("z_in") &&
9293
2.66k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9294
2.58k
                prevStep.paramValues[3].keyEquals("z_out") &&
9295
2.44k
                curStep.paramValues[0].keyEquals("xy_in") &&
9296
2.30k
                curStep.paramValues[1].keyEquals("z_in") &&
9297
2.27k
                curStep.paramValues[2].keyEquals("xy_out") &&
9298
2.23k
                curStep.paramValues[3].keyEquals("z_out") &&
9299
2.23k
                prevStep.paramValues[2].value == curStep.paramValues[0].value &&
9300
1.72k
                curStep.paramValues[1].value == curStep.paramValues[3].value) {
9301
829
                const std::string xy_in(prevStep.paramValues[0].value);
9302
829
                const std::string z_in(prevStep.paramValues[1].value);
9303
829
                const std::string xy_out(curStep.paramValues[2].value);
9304
829
                const std::string z_out(prevStep.paramValues[3].value);
9305
9306
829
                iterCur->paramValues.clear();
9307
829
                iterCur->paramValues.emplace_back(
9308
829
                    Step::KeyValue("xy_in", xy_in));
9309
829
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9310
829
                iterCur->paramValues.emplace_back(
9311
829
                    Step::KeyValue("xy_out", xy_out));
9312
829
                iterCur->paramValues.emplace_back(
9313
829
                    Step::KeyValue("z_out", z_out));
9314
9315
829
                deletePrevIter();
9316
829
                continue;
9317
829
            }
9318
9319
            // clang-format off
9320
            // Variant of above
9321
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z1
9322
            // +step +proj=unitconvert +xy_in=X2 +z_in=Z2 +xy_out=X3 +z_out=Z3
9323
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X3 +z_out=Z3
9324
            // clang-format on
9325
2.90M
            if (prevStep.name == "unitconvert" &&
9326
533k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9327
9.02k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9328
3.33k
                curStep.paramValues.size() == 4 &&
9329
2.32k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9330
2.06k
                prevStep.paramValues[1].keyEquals("z_in") &&
9331
1.84k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9332
1.75k
                prevStep.paramValues[3].keyEquals("z_out") &&
9333
1.62k
                curStep.paramValues[0].keyEquals("xy_in") &&
9334
1.47k
                curStep.paramValues[1].keyEquals("z_in") &&
9335
1.44k
                curStep.paramValues[2].keyEquals("xy_out") &&
9336
1.40k
                curStep.paramValues[3].keyEquals("z_out") &&
9337
1.40k
                prevStep.paramValues[1].value ==
9338
1.40k
                    prevStep.paramValues[3].value &&
9339
1.23k
                curStep.paramValues[0].value == prevStep.paramValues[2].value) {
9340
776
                const std::string xy_in(prevStep.paramValues[0].value);
9341
776
                const std::string z_in(curStep.paramValues[1].value);
9342
776
                const std::string xy_out(curStep.paramValues[2].value);
9343
776
                const std::string z_out(curStep.paramValues[3].value);
9344
9345
776
                iterCur->paramValues.clear();
9346
776
                iterCur->paramValues.emplace_back(
9347
776
                    Step::KeyValue("xy_in", xy_in));
9348
776
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9349
776
                iterCur->paramValues.emplace_back(
9350
776
                    Step::KeyValue("xy_out", xy_out));
9351
776
                iterCur->paramValues.emplace_back(
9352
776
                    Step::KeyValue("z_out", z_out));
9353
9354
776
                deletePrevIter();
9355
776
                continue;
9356
776
            }
9357
9358
            // unitconvert (1), axisswap order=2,1, unitconvert(2)  ==>
9359
            // axisswap order=2,1, unitconvert (1), unitconvert(2) which
9360
            // will get further optimized by previous case
9361
2.90M
            if (std::next(iterCur) != steps.end() &&
9362
2.67M
                prevStep.name == "unitconvert" && curStep.name == "axisswap" &&
9363
283k
                curStepParamCount == 1 &&
9364
282k
                curStep.paramValues[0].equals("order", "2,1")) {
9365
277k
                auto iterNext = std::next(iterCur);
9366
277k
                auto &nextStep = *iterNext;
9367
277k
                if (nextStep.name == "unitconvert") {
9368
1.87k
                    std::swap(*iterPrev, *iterCur);
9369
1.87k
                    ++iterCur;
9370
1.87k
                    continue;
9371
1.87k
                }
9372
277k
            }
9373
9374
            // axisswap order=2,1 followed by itself is a no-op
9375
2.90M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9376
321k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9377
321k
                curStep.paramValues[0].equals("order", "2,1") &&
9378
319k
                prevStep.paramValues[0].equals("order", "2,1")) {
9379
319k
                deletePrevAndCurIter();
9380
319k
                continue;
9381
319k
            }
9382
9383
            // axisswap order=2,-1 followed by axisswap order=-2,1 is a no-op
9384
2.58M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9385
2.45k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9386
2.10k
                !prevStep.inverted &&
9387
1.96k
                prevStep.paramValues[0].equals("order", "2,-1") &&
9388
264
                !curStep.inverted &&
9389
264
                curStep.paramValues[0].equals("order", "-2,1")) {
9390
264
                deletePrevAndCurIter();
9391
264
                continue;
9392
264
            }
9393
9394
            // axisswap order=2,-1 followed by axisswap order=1,-2 is
9395
            // equivalent to axisswap order=2,1
9396
2.58M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9397
2.19k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9398
1.84k
                !prevStep.inverted &&
9399
1.70k
                prevStep.paramValues[0].equals("order", "2,-1") &&
9400
0
                !curStep.inverted &&
9401
0
                curStep.paramValues[0].equals("order", "1,-2")) {
9402
0
                prevStep.inverted = false;
9403
0
                prevStep.paramValues[0] = Step::KeyValue("order", "2,1");
9404
                // Delete this iter
9405
0
                iterCur = steps.erase(iterCur);
9406
0
                continue;
9407
0
            }
9408
9409
            // axisswap order=2,1 followed by axisswap order=2,-1 is
9410
            // equivalent to axisswap order=1,-2
9411
            // Same for axisswap order=-2,1 followed by axisswap order=2,1
9412
2.58M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9413
2.19k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9414
1.84k
                ((prevStep.paramValues[0].equals("order", "2,1") &&
9415
17
                  !curStep.inverted &&
9416
17
                  curStep.paramValues[0].equals("order", "2,-1")) ||
9417
1.83k
                 (prevStep.paramValues[0].equals("order", "-2,1") &&
9418
184
                  !prevStep.inverted &&
9419
182
                  curStep.paramValues[0].equals("order", "2,1")))) {
9420
9421
25
                prevStep.inverted = false;
9422
25
                prevStep.paramValues[0] = Step::KeyValue("order", "1,-2");
9423
                // Delete this iter
9424
25
                iterCur = steps.erase(iterCur);
9425
25
                continue;
9426
25
            }
9427
9428
            // axisswap order=2,1, unitconvert, axisswap order=2,1 -> can
9429
            // suppress axisswap
9430
2.58M
            if (std::next(iterCur) != steps.end() &&
9431
2.37M
                prevStep.name == "axisswap" && curStep.name == "unitconvert" &&
9432
72.5k
                prevStepParamCount == 1 &&
9433
71.9k
                prevStep.paramValues[0].equals("order", "2,1")) {
9434
63.7k
                auto iterNext = std::next(iterCur);
9435
63.7k
                auto &nextStep = *iterNext;
9436
63.7k
                if (nextStep.name == "axisswap" &&
9437
1.23k
                    nextStep.paramValues.size() == 1 &&
9438
1.23k
                    nextStep.paramValues[0].equals("order", "2,1")) {
9439
1.23k
                    steps.erase(iterPrev);
9440
1.23k
                    steps.erase(iterNext);
9441
                    // Coverity complains about invalid usage of iterCur
9442
                    // due to the above erase(iterNext). To the best of our
9443
                    // understanding, this is a false-positive.
9444
                    // coverity[use_iterator]
9445
1.23k
                    if (iterCur != steps.begin())
9446
1.13k
                        iterCur = std::prev(iterCur);
9447
1.23k
                    if (iterCur == steps.begin())
9448
100
                        ++iterCur;
9449
1.23k
                    continue;
9450
1.23k
                }
9451
63.7k
            }
9452
9453
            // "+proj=set +v_4=X" followed by "+proj=set +v_4=X +omit_fwd"
9454
            // can be optimized as "+proj=set +v_4=X"
9455
2.58M
            if (curStep.name == "set" && prevStep.name == "set" &&
9456
4.11k
                !curStep.inverted && !prevStep.inverted &&
9457
4.11k
                curStepParamCount == 2 && prevStepParamCount == 1 &&
9458
0
                curStep.paramValues[0].keyEquals("v_4") &&
9459
0
                prevStep.paramValues[0].keyEquals("v_4") &&
9460
0
                curStep.paramValues[1].keyEquals("omit_fwd") &&
9461
0
                curStep.paramValues[0].value == prevStep.paramValues[0].value) {
9462
9463
0
                iterCur = steps.erase(iterCur);
9464
0
                continue;
9465
0
            }
9466
9467
            // "+proj=set +v_4=X +omit_inv" followed by "+proj=set +v_4=X"
9468
            // can be optimized as "+proj=set +v_4=X"
9469
2.58M
            if (curStep.name == "set" && prevStep.name == "set" &&
9470
4.11k
                !curStep.inverted && !prevStep.inverted &&
9471
4.11k
                curStepParamCount == 1 && prevStepParamCount == 2 &&
9472
0
                curStep.paramValues[0].keyEquals("v_4") &&
9473
0
                prevStep.paramValues[0].keyEquals("v_4") &&
9474
0
                prevStep.paramValues[1].keyEquals("omit_inv") &&
9475
0
                curStep.paramValues[0].value == prevStep.paramValues[0].value) {
9476
9477
0
                deletePrevIter();
9478
0
                continue;
9479
0
            }
9480
9481
            // for practical purposes WGS84 and GRS80 ellipsoids are
9482
            // equivalents (cartesian transform between both lead to differences
9483
            // of the order of 1e-14 deg..).
9484
            // No need to do a cart roundtrip for that...
9485
            // and actually IGNF uses the GRS80 definition for the WGS84 datum
9486
2.58M
            if (curStep.name == "cart" && prevStep.name == "cart" &&
9487
34.5k
                curStep.inverted == !prevStep.inverted &&
9488
34.5k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9489
34.1k
                ((curStep.paramValues[0].equals("ellps", "WGS84") &&
9490
16.3k
                  prevStep.paramValues[0].equals("ellps", "GRS80")) ||
9491
25.1k
                 (curStep.paramValues[0].equals("ellps", "GRS80") &&
9492
10.0k
                  prevStep.paramValues[0].equals("ellps", "WGS84")))) {
9493
10.0k
                deletePrevAndCurIter();
9494
10.0k
                continue;
9495
10.0k
            }
9496
9497
2.57M
            if (curStep.name == "helmert" && prevStep.name == "helmert" &&
9498
13.3k
                curStepParamCount == 3 &&
9499
10.5k
                curStepParamCount == prevStepParamCount) {
9500
9.68k
                std::map<std::string, double> leftParamsMap;
9501
9.68k
                std::map<std::string, double> rightParamsMap;
9502
9.68k
                try {
9503
28.6k
                    for (const auto &kv : prevStep.paramValues) {
9504
28.6k
                        leftParamsMap[kv.key] = c_locale_stod(kv.value);
9505
28.6k
                    }
9506
28.2k
                    for (const auto &kv : curStep.paramValues) {
9507
28.2k
                        rightParamsMap[kv.key] = c_locale_stod(kv.value);
9508
28.2k
                    }
9509
9.68k
                } catch (const std::invalid_argument &) {
9510
293
                    break;
9511
293
                }
9512
9.38k
                const std::string x("x");
9513
9.38k
                const std::string y("y");
9514
9.38k
                const std::string z("z");
9515
9.38k
                if (leftParamsMap.find(x) != leftParamsMap.end() &&
9516
9.26k
                    leftParamsMap.find(y) != leftParamsMap.end() &&
9517
9.18k
                    leftParamsMap.find(z) != leftParamsMap.end() &&
9518
8.82k
                    rightParamsMap.find(x) != rightParamsMap.end() &&
9519
8.76k
                    rightParamsMap.find(y) != rightParamsMap.end() &&
9520
8.65k
                    rightParamsMap.find(z) != rightParamsMap.end()) {
9521
9522
8.62k
                    const double signLeft = prevStep.inverted ? -1 : 1;
9523
8.62k
                    const double signRight = curStep.inverted ? -1 : 1;
9524
8.62k
                    const double xSum = signLeft * leftParamsMap[x] +
9525
8.62k
                                        signRight * rightParamsMap[x];
9526
8.62k
                    const double ySum = signLeft * leftParamsMap[y] +
9527
8.62k
                                        signRight * rightParamsMap[y];
9528
8.62k
                    const double zSum = signLeft * leftParamsMap[z] +
9529
8.62k
                                        signRight * rightParamsMap[z];
9530
8.62k
                    if (xSum == 0.0 && ySum == 0.0 && zSum == 0.0) {
9531
870
                        deletePrevAndCurIter();
9532
7.75k
                    } else {
9533
7.75k
                        prevStep.inverted = false;
9534
7.75k
                        prevStep.paramValues[0] =
9535
7.75k
                            Step::KeyValue("x", internal::toString(xSum));
9536
7.75k
                        prevStep.paramValues[1] =
9537
7.75k
                            Step::KeyValue("y", internal::toString(ySum));
9538
7.75k
                        prevStep.paramValues[2] =
9539
7.75k
                            Step::KeyValue("z", internal::toString(zSum));
9540
9541
                        // Delete this iter
9542
7.75k
                        iterCur = steps.erase(iterCur);
9543
7.75k
                    }
9544
8.62k
                    continue;
9545
8.62k
                }
9546
9.38k
            }
9547
9548
            // Helmert followed by its inverse is a no-op
9549
2.56M
            if (curStep.name == "helmert" && prevStep.name == "helmert" &&
9550
4.41k
                (curStep.inverted == prevStep.inverted) &&
9551
2.73k
                curStepParamCount == prevStepParamCount) {
9552
1.16k
                std::set<std::string> leftParamsSet;
9553
1.16k
                std::set<std::string> rightParamsSet;
9554
1.16k
                std::map<std::string, std::string> leftParamsMap;
9555
1.16k
                std::map<std::string, std::string> rightParamsMap;
9556
4.51k
                for (const auto &kv : prevStep.paramValues) {
9557
4.51k
                    leftParamsSet.insert(kv.key);
9558
4.51k
                    leftParamsMap[kv.key] = kv.value;
9559
4.51k
                }
9560
4.51k
                for (const auto &kv : curStep.paramValues) {
9561
4.51k
                    rightParamsSet.insert(kv.key);
9562
4.51k
                    rightParamsMap[kv.key] = kv.value;
9563
4.51k
                }
9564
1.16k
                if (leftParamsSet == rightParamsSet) {
9565
324
                    bool doErase = true;
9566
324
                    try {
9567
688
                        for (const auto &param : leftParamsSet) {
9568
688
                            if (param == "convention" || param == "t_epoch" ||
9569
536
                                param == "t_obs") {
9570
152
                                if (leftParamsMap[param] !=
9571
152
                                    rightParamsMap[param]) {
9572
115
                                    doErase = false;
9573
115
                                    break;
9574
115
                                }
9575
536
                            } else if (c_locale_stod(leftParamsMap[param]) !=
9576
536
                                       -c_locale_stod(rightParamsMap[param])) {
9577
154
                                doErase = false;
9578
154
                                break;
9579
154
                            }
9580
688
                        }
9581
324
                    } catch (const std::invalid_argument &) {
9582
42
                        break;
9583
42
                    }
9584
282
                    if (doErase) {
9585
13
                        deletePrevAndCurIter();
9586
13
                        continue;
9587
13
                    }
9588
282
                }
9589
1.16k
            }
9590
9591
            // The following should be optimized as a no-op
9592
            // +step +proj=helmert +x=25 +y=-141 +z=-78.5 +rx=0 +ry=-0.35
9593
            // +rz=-0.736 +s=0 +convention=coordinate_frame
9594
            // +step +inv +proj=helmert +x=25 +y=-141 +z=-78.5 +rx=0 +ry=0.35
9595
            // +rz=0.736 +s=0 +convention=position_vector
9596
2.56M
            if (curStep.name == "helmert" && prevStep.name == "helmert" &&
9597
4.36k
                ((curStep.inverted && !prevStep.inverted) ||
9598
3.41k
                 (!curStep.inverted && prevStep.inverted)) &&
9599
1.67k
                curStepParamCount == prevStepParamCount) {
9600
913
                std::set<std::string> leftParamsSet;
9601
913
                std::set<std::string> rightParamsSet;
9602
913
                std::map<std::string, std::string> leftParamsMap;
9603
913
                std::map<std::string, std::string> rightParamsMap;
9604
11.1k
                for (const auto &kv : prevStep.paramValues) {
9605
11.1k
                    leftParamsSet.insert(kv.key);
9606
11.1k
                    leftParamsMap[kv.key] = kv.value;
9607
11.1k
                }
9608
11.1k
                for (const auto &kv : curStep.paramValues) {
9609
11.1k
                    rightParamsSet.insert(kv.key);
9610
11.1k
                    rightParamsMap[kv.key] = kv.value;
9611
11.1k
                }
9612
913
                if (leftParamsSet == rightParamsSet) {
9613
684
                    bool doErase = true;
9614
684
                    try {
9615
3.17k
                        for (const auto &param : leftParamsSet) {
9616
3.17k
                            if (param == "convention") {
9617
                                // Convention must be different
9618
417
                                if (leftParamsMap[param] ==
9619
417
                                    rightParamsMap[param]) {
9620
399
                                    doErase = false;
9621
399
                                    break;
9622
399
                                }
9623
2.75k
                            } else if (param == "rx" || param == "ry" ||
9624
2.56k
                                       param == "rz" || param == "drx" ||
9625
2.56k
                                       param == "dry" || param == "drz") {
9626
                                // Rotational parameters should have opposite
9627
                                // value
9628
190
                                if (c_locale_stod(leftParamsMap[param]) !=
9629
190
                                    -c_locale_stod(rightParamsMap[param])) {
9630
73
                                    doErase = false;
9631
73
                                    break;
9632
73
                                }
9633
2.56k
                            } else {
9634
                                // Non rotational parameters should have the
9635
                                // same value
9636
2.56k
                                if (leftParamsMap[param] !=
9637
2.56k
                                    rightParamsMap[param]) {
9638
54
                                    doErase = false;
9639
54
                                    break;
9640
54
                                }
9641
2.56k
                            }
9642
3.17k
                        }
9643
684
                    } catch (const std::invalid_argument &) {
9644
76
                        break;
9645
76
                    }
9646
608
                    if (doErase) {
9647
82
                        deletePrevAndCurIter();
9648
82
                        continue;
9649
82
                    }
9650
608
                }
9651
913
            }
9652
9653
            // Optimize patterns like Krovak (South West) to Krovak East North
9654
            // (also applies to Modified Krovak)
9655
            //   +step +inv +proj=krovak +axis=swu +lat_0=49.5
9656
            //   +lon_0=24.8333333333333
9657
            //     +alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel
9658
            //   +step +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333
9659
            //     +alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel
9660
            // as:
9661
            //   +step +proj=axisswap +order=-2,-1
9662
            // Also applies for the symmetrical case where +axis=swu is on the
9663
            // second step.
9664
2.56M
            if (curStep.inverted != prevStep.inverted &&
9665
1.09M
                curStep.name == prevStep.name &&
9666
72.1k
                ((curStepParamCount + 1 == prevStepParamCount &&
9667
1.11k
                  prevStep.paramValues[0].equals("axis", "swu")) ||
9668
72.0k
                 (prevStepParamCount + 1 == curStepParamCount &&
9669
1.33k
                  curStep.paramValues[0].equals("axis", "swu")))) {
9670
305
                const auto &swStep = (curStepParamCount < prevStepParamCount)
9671
305
                                         ? prevStep
9672
305
                                         : curStep;
9673
305
                const auto &enStep = (curStepParamCount < prevStepParamCount)
9674
305
                                         ? curStep
9675
305
                                         : prevStep;
9676
                // Check if all remaining parameters (except leading axis=swu
9677
                // in swStep) are identical.
9678
305
                bool allSame = true;
9679
305
                for (size_t j = 0;
9680
345
                     j < std::min(curStepParamCount, prevStepParamCount); j++) {
9681
173
                    if (enStep.paramValues[j] != swStep.paramValues[j + 1]) {
9682
133
                        allSame = false;
9683
133
                        break;
9684
133
                    }
9685
173
                }
9686
305
                if (allSame) {
9687
172
                    iterCur->inverted = false;
9688
172
                    iterCur->name = "axisswap";
9689
172
                    iterCur->paramValues.clear();
9690
172
                    iterCur->paramValues.emplace_back(
9691
172
                        Step::KeyValue("order", "-2,-1"));
9692
9693
172
                    deletePrevIter();
9694
172
                    continue;
9695
172
                }
9696
305
            }
9697
9698
            // detect a step and its inverse
9699
2.56M
            if (curStep.inverted != prevStep.inverted &&
9700
1.09M
                curStep.name == prevStep.name &&
9701
72.0k
                curStepParamCount == prevStepParamCount) {
9702
64.4k
                bool allSame = true;
9703
117k
                for (size_t j = 0; j < curStepParamCount; j++) {
9704
85.1k
                    if (curStep.paramValues[j] != prevStep.paramValues[j]) {
9705
31.7k
                        allSame = false;
9706
31.7k
                        break;
9707
31.7k
                    }
9708
85.1k
                }
9709
64.4k
                if (allSame) {
9710
32.6k
                    deletePrevAndCurIter();
9711
32.6k
                    continue;
9712
32.6k
                }
9713
64.4k
            }
9714
9715
2.53M
            ++iterCur;
9716
2.53M
        }
9717
243k
    }
9718
9719
243k
    {
9720
243k
        auto iterCur = steps.begin();
9721
243k
        if (iterCur != steps.end()) {
9722
233k
            ++iterCur;
9723
233k
        }
9724
1.51M
        while (iterCur != steps.end()) {
9725
9726
1.27M
            assert(iterCur != steps.begin());
9727
1.27M
            auto iterPrev = std::prev(iterCur);
9728
1.27M
            auto &prevStep = *iterPrev;
9729
1.27M
            auto &curStep = *iterCur;
9730
9731
1.27M
            const auto curStepParamCount = curStep.paramValues.size();
9732
1.27M
            const auto prevStepParamCount = prevStep.paramValues.size();
9733
9734
            // +step +proj=hgridshift +grids=grid_A
9735
            // +step +proj=vgridshift [...] <== curStep
9736
            // +step +inv +proj=hgridshift +grids=grid_A
9737
            // ==>
9738
            // +step +proj=push +v_1 +v_2
9739
            // +step +proj=hgridshift +grids=grid_A +omit_inv
9740
            // +step +proj=vgridshift [...]
9741
            // +step +inv +proj=hgridshift +grids=grid_A +omit_fwd
9742
            // +step +proj=pop +v_1 +v_2
9743
1.27M
            if (std::next(iterCur) != steps.end() &&
9744
1.06M
                prevStep.name == "hgridshift" && prevStepParamCount == 1 &&
9745
9.61k
                curStep.name == "vgridshift") {
9746
3.17k
                auto iterNext = std::next(iterCur);
9747
3.17k
                auto &nextStep = *iterNext;
9748
3.17k
                if (nextStep.name == "hgridshift" &&
9749
615
                    nextStep.inverted != prevStep.inverted &&
9750
575
                    nextStep.paramValues.size() == 1 &&
9751
549
                    prevStep.paramValues[0] == nextStep.paramValues[0]) {
9752
383
                    Step pushStep;
9753
383
                    pushStep.name = "push";
9754
383
                    pushStep.paramValues.emplace_back("v_1");
9755
383
                    pushStep.paramValues.emplace_back("v_2");
9756
383
                    steps.insert(iterPrev, pushStep);
9757
9758
383
                    prevStep.paramValues.emplace_back("omit_inv");
9759
9760
383
                    nextStep.paramValues.emplace_back("omit_fwd");
9761
9762
383
                    Step popStep;
9763
383
                    popStep.name = "pop";
9764
383
                    popStep.paramValues.emplace_back("v_1");
9765
383
                    popStep.paramValues.emplace_back("v_2");
9766
383
                    steps.insert(std::next(iterNext), popStep);
9767
9768
383
                    continue;
9769
383
                }
9770
3.17k
            }
9771
9772
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9773
            // +step +proj=axisswap +order=2,1
9774
            // +step +proj=push +v_1 +v_2
9775
            // +step +proj=axisswap +order=2,1
9776
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9777
            // +step +proj=vgridshift ...
9778
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9779
            // +step +proj=axisswap +order=2,1
9780
            // +step +proj=pop +v_1 +v_2
9781
            // ==>
9782
            // +step +proj=vgridshift ...
9783
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9784
            // +step +proj=axisswap +order=2,1
9785
1.27M
            if (prevStep.name == "unitconvert" && prevStepParamCount == 2 &&
9786
173k
                prevStep.paramValues[0].equals("xy_in", "rad") &&
9787
38.3k
                prevStep.paramValues[1].equals("xy_out", "deg") &&
9788
38.3k
                curStep.name == "axisswap" && curStepParamCount == 1 &&
9789
25.2k
                curStep.paramValues[0].equals("order", "2,1")) {
9790
20.2k
                auto iterNext = std::next(iterCur);
9791
20.2k
                bool ok = false;
9792
20.2k
                if (iterNext != steps.end()) {
9793
1.82k
                    auto &nextStep = *iterNext;
9794
1.82k
                    if (nextStep.name == "push" &&
9795
204
                        nextStep.paramValues.size() == 2 &&
9796
0
                        nextStep.paramValues[0].keyEquals("v_1") &&
9797
0
                        nextStep.paramValues[1].keyEquals("v_2")) {
9798
0
                        ok = true;
9799
0
                        iterNext = std::next(iterNext);
9800
0
                    }
9801
1.82k
                }
9802
20.2k
                ok &= iterNext != steps.end();
9803
20.2k
                if (ok) {
9804
0
                    ok = false;
9805
0
                    auto &nextStep = *iterNext;
9806
0
                    if (nextStep.name == "axisswap" &&
9807
0
                        nextStep.paramValues.size() == 1 &&
9808
0
                        nextStep.paramValues[0].equals("order", "2,1")) {
9809
0
                        ok = true;
9810
0
                        iterNext = std::next(iterNext);
9811
0
                    }
9812
0
                }
9813
20.2k
                ok &= iterNext != steps.end();
9814
20.2k
                if (ok) {
9815
0
                    ok = false;
9816
0
                    auto &nextStep = *iterNext;
9817
0
                    if (nextStep.name == "unitconvert" &&
9818
0
                        nextStep.paramValues.size() == 2 &&
9819
0
                        nextStep.paramValues[0].equals("xy_in", "deg") &&
9820
0
                        nextStep.paramValues[1].equals("xy_out", "rad")) {
9821
0
                        ok = true;
9822
0
                        iterNext = std::next(iterNext);
9823
0
                    }
9824
0
                }
9825
20.2k
                auto iterVgridshift = iterNext;
9826
20.2k
                ok &= iterNext != steps.end();
9827
20.2k
                if (ok) {
9828
0
                    ok = false;
9829
0
                    auto &nextStep = *iterNext;
9830
0
                    if (nextStep.name == "vgridshift") {
9831
0
                        ok = true;
9832
0
                        iterNext = std::next(iterNext);
9833
0
                    }
9834
0
                }
9835
20.2k
                ok &= iterNext != steps.end();
9836
20.2k
                if (ok) {
9837
0
                    ok = false;
9838
0
                    auto &nextStep = *iterNext;
9839
0
                    if (nextStep.name == "unitconvert" &&
9840
0
                        nextStep.paramValues.size() == 2 &&
9841
0
                        nextStep.paramValues[0].equals("xy_in", "rad") &&
9842
0
                        nextStep.paramValues[1].equals("xy_out", "deg")) {
9843
0
                        ok = true;
9844
0
                        iterNext = std::next(iterNext);
9845
0
                    }
9846
0
                }
9847
20.2k
                ok &= iterNext != steps.end();
9848
20.2k
                if (ok) {
9849
0
                    ok = false;
9850
0
                    auto &nextStep = *iterNext;
9851
0
                    if (nextStep.name == "axisswap" &&
9852
0
                        nextStep.paramValues.size() == 1 &&
9853
0
                        nextStep.paramValues[0].equals("order", "2,1")) {
9854
0
                        ok = true;
9855
0
                        iterNext = std::next(iterNext);
9856
0
                    }
9857
0
                }
9858
20.2k
                ok &= iterNext != steps.end();
9859
20.2k
                if (ok) {
9860
0
                    ok = false;
9861
0
                    auto &nextStep = *iterNext;
9862
0
                    if (nextStep.name == "pop" &&
9863
0
                        nextStep.paramValues.size() == 2 &&
9864
0
                        nextStep.paramValues[0].keyEquals("v_1") &&
9865
0
                        nextStep.paramValues[1].keyEquals("v_2")) {
9866
0
                        ok = true;
9867
                        // iterNext = std::next(iterNext);
9868
0
                    }
9869
0
                }
9870
20.2k
                if (ok) {
9871
0
                    steps.erase(iterPrev, iterVgridshift);
9872
0
                    steps.erase(iterNext, std::next(iterNext));
9873
0
                    iterPrev = std::prev(iterVgridshift);
9874
0
                    iterCur = iterVgridshift;
9875
0
                    continue;
9876
0
                }
9877
20.2k
            }
9878
9879
            // +step +proj=axisswap +order=2,1
9880
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9881
            // +step +proj=vgridshift ...
9882
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9883
            // +step +proj=axisswap +order=2,1
9884
            // +step +proj=push +v_1 +v_2
9885
            // +step +proj=axisswap +order=2,1
9886
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9887
            // ==>
9888
            // +step +proj=push +v_1 +v_2
9889
            // +step +proj=axisswap +order=2,1
9890
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9891
            // +step +proj=vgridshift ...
9892
9893
1.27M
            if (prevStep.name == "axisswap" && prevStepParamCount == 1 &&
9894
47.7k
                prevStep.paramValues[0].equals("order", "2,1") &&
9895
37.6k
                curStep.name == "unitconvert" && curStepParamCount == 2 &&
9896
33.1k
                !curStep.inverted &&
9897
33.1k
                curStep.paramValues[0].equals("xy_in", "deg") &&
9898
32.6k
                curStep.paramValues[1].equals("xy_out", "rad")) {
9899
32.5k
                auto iterNext = std::next(iterCur);
9900
32.5k
                bool ok = false;
9901
32.5k
                auto iterVgridshift = iterNext;
9902
32.5k
                if (iterNext != steps.end()) {
9903
32.5k
                    auto &nextStep = *iterNext;
9904
32.5k
                    if (nextStep.name == "vgridshift") {
9905
5.45k
                        ok = true;
9906
5.45k
                        iterNext = std::next(iterNext);
9907
5.45k
                    }
9908
32.5k
                }
9909
32.5k
                ok &= iterNext != steps.end();
9910
32.5k
                if (ok) {
9911
5.45k
                    ok = false;
9912
5.45k
                    auto &nextStep = *iterNext;
9913
5.45k
                    if (nextStep.name == "unitconvert" && !nextStep.inverted &&
9914
1.31k
                        nextStep.paramValues.size() == 2 &&
9915
1.26k
                        nextStep.paramValues[0].equals("xy_in", "rad") &&
9916
943
                        nextStep.paramValues[1].equals("xy_out", "deg")) {
9917
943
                        ok = true;
9918
943
                        iterNext = std::next(iterNext);
9919
943
                    }
9920
5.45k
                }
9921
32.5k
                ok &= iterNext != steps.end();
9922
32.5k
                if (ok) {
9923
165
                    ok = false;
9924
165
                    auto &nextStep = *iterNext;
9925
165
                    if (nextStep.name == "axisswap" &&
9926
151
                        nextStep.paramValues.size() == 1 &&
9927
151
                        nextStep.paramValues[0].equals("order", "2,1")) {
9928
141
                        ok = true;
9929
141
                        iterNext = std::next(iterNext);
9930
141
                    }
9931
165
                }
9932
32.5k
                auto iterPush = iterNext;
9933
32.5k
                ok &= iterNext != steps.end();
9934
32.5k
                if (ok) {
9935
86
                    ok = false;
9936
86
                    auto &nextStep = *iterNext;
9937
86
                    if (nextStep.name == "push" &&
9938
0
                        nextStep.paramValues.size() == 2 &&
9939
0
                        nextStep.paramValues[0].keyEquals("v_1") &&
9940
0
                        nextStep.paramValues[1].keyEquals("v_2")) {
9941
0
                        ok = true;
9942
0
                        iterNext = std::next(iterNext);
9943
0
                    }
9944
86
                }
9945
32.5k
                ok &= iterNext != steps.end();
9946
32.5k
                if (ok) {
9947
0
                    ok = false;
9948
0
                    auto &nextStep = *iterNext;
9949
0
                    if (nextStep.name == "axisswap" &&
9950
0
                        nextStep.paramValues.size() == 1 &&
9951
0
                        nextStep.paramValues[0].equals("order", "2,1")) {
9952
0
                        ok = true;
9953
0
                        iterNext = std::next(iterNext);
9954
0
                    }
9955
0
                }
9956
32.5k
                ok &= iterNext != steps.end();
9957
32.5k
                if (ok) {
9958
0
                    ok = false;
9959
0
                    auto &nextStep = *iterNext;
9960
0
                    if (nextStep.name == "unitconvert" &&
9961
0
                        nextStep.paramValues.size() == 2 &&
9962
0
                        !nextStep.inverted &&
9963
0
                        nextStep.paramValues[0].equals("xy_in", "deg") &&
9964
0
                        nextStep.paramValues[1].equals("xy_out", "rad")) {
9965
0
                        ok = true;
9966
                        // iterNext = std::next(iterNext);
9967
0
                    }
9968
0
                }
9969
9970
32.5k
                if (ok) {
9971
0
                    Step stepVgridshift(*iterVgridshift);
9972
0
                    steps.erase(iterPrev, iterPush);
9973
0
                    steps.insert(std::next(iterNext),
9974
0
                                 std::move(stepVgridshift));
9975
0
                    iterPrev = iterPush;
9976
0
                    iterCur = std::next(iterPush);
9977
0
                    continue;
9978
0
                }
9979
32.5k
            }
9980
9981
1.27M
            ++iterCur;
9982
1.27M
        }
9983
243k
    }
9984
9985
243k
    {
9986
243k
        auto iterCur = steps.begin();
9987
243k
        if (iterCur != steps.end()) {
9988
233k
            ++iterCur;
9989
233k
        }
9990
1.51M
        while (iterCur != steps.end()) {
9991
9992
1.27M
            assert(iterCur != steps.begin());
9993
1.27M
            auto iterPrev = std::prev(iterCur);
9994
1.27M
            auto &prevStep = *iterPrev;
9995
1.27M
            auto &curStep = *iterCur;
9996
9997
1.27M
            const auto curStepParamCount = curStep.paramValues.size();
9998
1.27M
            const auto prevStepParamCount = prevStep.paramValues.size();
9999
10000
1.27M
            const auto deletePrevAndCurIter = [&steps, &iterPrev, &iterCur]() {
10001
241
                iterCur = steps.erase(iterPrev, std::next(iterCur));
10002
241
                if (iterCur != steps.begin())
10003
241
                    iterCur = std::prev(iterCur);
10004
241
                if (iterCur == steps.begin() && iterCur != steps.end())
10005
64
                    ++iterCur;
10006
241
            };
10007
10008
            // axisswap order=2,1 followed by itself is a no-op
10009
1.27M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
10010
718
                curStepParamCount == 1 && prevStepParamCount == 1 &&
10011
389
                curStep.paramValues[0].equals("order", "2,1") &&
10012
53
                prevStep.paramValues[0].equals("order", "2,1")) {
10013
33
                deletePrevAndCurIter();
10014
33
                continue;
10015
33
            }
10016
10017
            // detect a step and its inverse
10018
1.27M
            if (curStep.inverted != prevStep.inverted &&
10019
554k
                curStep.name == prevStep.name &&
10020
21.8k
                curStepParamCount == prevStepParamCount) {
10021
15.8k
                bool allSame = true;
10022
19.3k
                for (size_t j = 0; j < curStepParamCount; j++) {
10023
19.1k
                    if (curStep.paramValues[j] != prevStep.paramValues[j]) {
10024
15.6k
                        allSame = false;
10025
15.6k
                        break;
10026
15.6k
                    }
10027
19.1k
                }
10028
15.8k
                if (allSame) {
10029
208
                    deletePrevAndCurIter();
10030
208
                    continue;
10031
208
                }
10032
15.8k
            }
10033
10034
1.27M
            ++iterCur;
10035
1.27M
        }
10036
243k
    }
10037
10038
243k
    if (steps.size() > 1 ||
10039
38.4k
        (steps.size() == 1 &&
10040
29.2k
         (steps.front().inverted || steps.front().hasKey("omit_inv") ||
10041
27.1k
          steps.front().hasKey("omit_fwd") ||
10042
207k
          !d->globalParamValues_.empty()))) {
10043
207k
        d->appendToResult("+proj=pipeline");
10044
10045
655k
        for (const auto &paramValue : d->globalParamValues_) {
10046
655k
            d->appendToResult("+");
10047
655k
            d->result_ += paramValue.key;
10048
655k
            if (!paramValue.value.empty()) {
10049
359k
                d->result_ += '=';
10050
359k
                d->result_ +=
10051
359k
                    pj_double_quote_string_param_if_needed(paramValue.value);
10052
359k
            }
10053
655k
        }
10054
10055
207k
        if (d->multiLine_) {
10056
0
            d->indentLevel_++;
10057
0
        }
10058
207k
    }
10059
10060
1.50M
    for (const auto &step : steps) {
10061
1.50M
        std::string curLine;
10062
1.50M
        if (!d->result_.empty()) {
10063
1.48M
            if (d->multiLine_) {
10064
0
                curLine = std::string(static_cast<size_t>(d->indentLevel_) *
10065
0
                                          d->indentWidth_,
10066
0
                                      ' ');
10067
0
                curLine += "+step";
10068
1.48M
            } else {
10069
1.48M
                curLine = " +step";
10070
1.48M
            }
10071
1.48M
        }
10072
1.50M
        if (step.inverted) {
10073
456k
            curLine += " +inv";
10074
456k
        }
10075
1.50M
        if (!step.name.empty()) {
10076
1.49M
            if (!curLine.empty())
10077
1.46M
                curLine += ' ';
10078
1.49M
            curLine += step.isInit ? "+init=" : "+proj=";
10079
1.49M
            curLine += step.name;
10080
1.49M
        }
10081
4.64M
        for (const auto &paramValue : step.paramValues) {
10082
4.64M
            std::string newKV = "+";
10083
4.64M
            newKV += paramValue.key;
10084
4.64M
            if (!paramValue.value.empty()) {
10085
2.90M
                newKV += '=';
10086
2.90M
                newKV +=
10087
2.90M
                    pj_double_quote_string_param_if_needed(paramValue.value);
10088
2.90M
            }
10089
4.64M
            if (d->maxLineLength_ > 0 && d->multiLine_ &&
10090
0
                curLine.size() + newKV.size() >
10091
0
                    static_cast<size_t>(d->maxLineLength_)) {
10092
0
                if (!d->result_.empty())
10093
0
                    d->result_ += '\n';
10094
0
                d->result_ += curLine;
10095
0
                curLine = std::string(static_cast<size_t>(d->indentLevel_) *
10096
0
                                              d->indentWidth_ +
10097
0
                                          strlen("+step "),
10098
0
                                      ' ');
10099
4.64M
            } else {
10100
4.64M
                if (!curLine.empty())
10101
4.64M
                    curLine += ' ';
10102
4.64M
            }
10103
4.64M
            curLine += newKV;
10104
4.64M
        }
10105
1.50M
        if (d->multiLine_ && !d->result_.empty())
10106
0
            d->result_ += '\n';
10107
1.50M
        d->result_ += curLine;
10108
1.50M
    }
10109
10110
243k
    if (d->result_.empty()) {
10111
9.17k
        d->appendToResult("+proj=noop");
10112
9.17k
    }
10113
10114
243k
    return d->result_;
10115
243k
}
10116
10117
// ---------------------------------------------------------------------------
10118
10119
//! @cond Doxygen_Suppress
10120
10121
571k
PROJStringFormatter::Convention PROJStringFormatter::convention() const {
10122
571k
    return d->convention_;
10123
571k
}
10124
10125
// ---------------------------------------------------------------------------
10126
10127
// Return the number of steps in the pipeline.
10128
// Note: this value will change after calling toString() that will run
10129
// optimizations.
10130
36.7k
size_t PROJStringFormatter::getStepCount() const { return d->steps_.size(); }
10131
10132
// ---------------------------------------------------------------------------
10133
10134
9.23k
bool PROJStringFormatter::getUseApproxTMerc() const {
10135
9.23k
    return d->useApproxTMerc_;
10136
9.23k
}
10137
10138
// ---------------------------------------------------------------------------
10139
10140
359k
void PROJStringFormatter::setCoordinateOperationOptimizations(bool enable) {
10141
359k
    d->coordOperationOptimizations_ = enable;
10142
359k
}
10143
10144
// ---------------------------------------------------------------------------
10145
10146
871k
void PROJStringFormatter::Private::appendToResult(const char *str) {
10147
871k
    if (!result_.empty()) {
10148
655k
        result_ += ' ';
10149
655k
    }
10150
871k
    result_ += str;
10151
871k
}
10152
10153
// ---------------------------------------------------------------------------
10154
10155
static void
10156
PROJStringSyntaxParser(const std::string &projString, std::vector<Step> &steps,
10157
                       std::vector<Step::KeyValue> &globalParamValues,
10158
284k
                       std::string &title) {
10159
284k
    std::vector<std::string> tokens;
10160
10161
284k
    bool hasProj = false;
10162
284k
    bool hasInit = false;
10163
284k
    bool hasPipeline = false;
10164
10165
284k
    std::string projStringModified(projString);
10166
10167
    // Special case for "+title=several words +foo=bar"
10168
284k
    if (starts_with(projStringModified, "+title=") &&
10169
173
        projStringModified.size() > 7 && projStringModified[7] != '"') {
10170
169
        const auto plusPos = projStringModified.find(" +", 1);
10171
169
        const auto spacePos = projStringModified.find(' ');
10172
169
        if (plusPos != std::string::npos && spacePos != std::string::npos &&
10173
127
            spacePos < plusPos) {
10174
91
            std::string tmp("+title=");
10175
91
            tmp += pj_double_quote_string_param_if_needed(
10176
91
                projStringModified.substr(7, plusPos - 7));
10177
91
            tmp += projStringModified.substr(plusPos);
10178
91
            projStringModified = std::move(tmp);
10179
91
        }
10180
169
    }
10181
10182
284k
    size_t argc = pj_trim_argc(&projStringModified[0]);
10183
284k
    char **argv = pj_trim_argv(argc, &projStringModified[0]);
10184
9.28M
    for (size_t i = 0; i < argc; i++) {
10185
8.99M
        std::string token(argv[i]);
10186
8.99M
        if (!hasPipeline && token == "proj=pipeline") {
10187
232k
            hasPipeline = true;
10188
8.76M
        } else if (!hasProj && starts_with(token, "proj=")) {
10189
276k
            hasProj = true;
10190
8.48M
        } else if (!hasInit && starts_with(token, "init=")) {
10191
6.45k
            hasInit = true;
10192
6.45k
        }
10193
8.99M
        tokens.emplace_back(token);
10194
8.99M
    }
10195
284k
    free(argv);
10196
10197
284k
    if (!hasPipeline) {
10198
52.3k
        if (hasProj || hasInit) {
10199
45.3k
            steps.push_back(Step());
10200
45.3k
        }
10201
10202
602k
        for (auto &word : tokens) {
10203
602k
            if (starts_with(word, "proj=") && !hasInit &&
10204
63.2k
                steps.back().name.empty()) {
10205
44.1k
                assert(hasProj);
10206
44.1k
                auto stepName = word.substr(strlen("proj="));
10207
44.1k
                steps.back().name = std::move(stepName);
10208
558k
            } else if (starts_with(word, "init=")) {
10209
1.40k
                assert(hasInit);
10210
1.40k
                auto initName = word.substr(strlen("init="));
10211
1.40k
                steps.back().name = std::move(initName);
10212
1.40k
                steps.back().isInit = true;
10213
556k
            } else if (word == "inv") {
10214
2.89k
                if (!steps.empty()) {
10215
2.88k
                    steps.back().inverted = true;
10216
2.88k
                }
10217
554k
            } else if (starts_with(word, "title=")) {
10218
1.11k
                title = word.substr(strlen("title="));
10219
552k
            } else if (word != "step") {
10220
545k
                const auto pos = word.find('=');
10221
545k
                const auto key = word.substr(0, pos);
10222
10223
545k
                Step::KeyValue pair(
10224
545k
                    (pos != std::string::npos)
10225
545k
                        ? Step::KeyValue(key, word.substr(pos + 1))
10226
545k
                        : Step::KeyValue(key));
10227
545k
                if (steps.empty()) {
10228
419
                    globalParamValues.push_back(std::move(pair));
10229
544k
                } else {
10230
544k
                    steps.back().paramValues.push_back(std::move(pair));
10231
544k
                }
10232
545k
            }
10233
602k
        }
10234
52.3k
        return;
10235
52.3k
    }
10236
10237
232k
    bool inPipeline = false;
10238
232k
    bool invGlobal = false;
10239
8.39M
    for (auto &word : tokens) {
10240
8.39M
        if (word == "proj=pipeline") {
10241
232k
            if (inPipeline) {
10242
48
                throw ParsingException("nested pipeline not supported");
10243
48
            }
10244
232k
            inPipeline = true;
10245
8.16M
        } else if (word == "step") {
10246
1.17M
            if (!inPipeline) {
10247
6
                throw ParsingException("+step found outside pipeline");
10248
6
            }
10249
1.17M
            steps.push_back(Step());
10250
6.98M
        } else if (word == "inv") {
10251
345k
            if (steps.empty()) {
10252
3.44k
                invGlobal = true;
10253
341k
            } else {
10254
341k
                steps.back().inverted = true;
10255
341k
            }
10256
6.64M
        } else if (inPipeline && !steps.empty() && starts_with(word, "proj=") &&
10257
1.28M
                   steps.back().name.empty()) {
10258
1.14M
            auto stepName = word.substr(strlen("proj="));
10259
1.14M
            steps.back().name = std::move(stepName);
10260
5.49M
        } else if (inPipeline && !steps.empty() && starts_with(word, "init=") &&
10261
3.96k
                   steps.back().name.empty()) {
10262
578
            auto initName = word.substr(strlen("init="));
10263
578
            steps.back().name = std::move(initName);
10264
578
            steps.back().isInit = true;
10265
5.49M
        } else if (!inPipeline && starts_with(word, "title=")) {
10266
295
            title = word.substr(strlen("title="));
10267
5.49M
        } else {
10268
5.49M
            const auto pos = word.find('=');
10269
5.49M
            auto key = word.substr(0, pos);
10270
5.49M
            Step::KeyValue pair((pos != std::string::npos)
10271
5.49M
                                    ? Step::KeyValue(key, word.substr(pos + 1))
10272
5.49M
                                    : Step::KeyValue(key));
10273
5.49M
            if (steps.empty()) {
10274
1.08M
                globalParamValues.emplace_back(std::move(pair));
10275
4.41M
            } else {
10276
4.41M
                steps.back().paramValues.emplace_back(std::move(pair));
10277
4.41M
            }
10278
5.49M
        }
10279
8.39M
    }
10280
232k
    if (invGlobal && !steps.empty()) {
10281
29.5k
        for (auto &step : steps) {
10282
29.5k
            step.inverted = !step.inverted;
10283
29.5k
        }
10284
3.01k
        std::reverse(steps.begin(), steps.end());
10285
3.01k
    }
10286
232k
}
10287
10288
// ---------------------------------------------------------------------------
10289
10290
void PROJStringFormatter::ingestPROJString(
10291
    const std::string &str) // throw ParsingException
10292
271k
{
10293
271k
    std::vector<Step> steps;
10294
271k
    std::string title;
10295
271k
    PROJStringSyntaxParser(str, steps, d->globalParamValues_, title);
10296
271k
    d->steps_.insert(d->steps_.end(), steps.begin(), steps.end());
10297
271k
}
10298
10299
// ---------------------------------------------------------------------------
10300
10301
13.9k
void PROJStringFormatter::setCRSExport(bool b) { d->crsExport_ = b; }
10302
10303
// ---------------------------------------------------------------------------
10304
10305
2.01M
bool PROJStringFormatter::getCRSExport() const { return d->crsExport_; }
10306
10307
// ---------------------------------------------------------------------------
10308
10309
648k
void PROJStringFormatter::startInversion() {
10310
648k
    PROJStringFormatter::Private::InversionStackElt elt;
10311
648k
    elt.startIter = d->steps_.end();
10312
648k
    if (elt.startIter != d->steps_.begin()) {
10313
440k
        elt.iterValid = true;
10314
440k
        --elt.startIter; // point to the last valid element
10315
440k
    } else {
10316
207k
        elt.iterValid = false;
10317
207k
    }
10318
648k
    elt.currentInversionState =
10319
648k
        !d->inversionStack_.back().currentInversionState;
10320
648k
    d->inversionStack_.push_back(elt);
10321
648k
}
10322
10323
// ---------------------------------------------------------------------------
10324
10325
647k
void PROJStringFormatter::stopInversion() {
10326
647k
    assert(!d->inversionStack_.empty());
10327
647k
    auto startIter = d->inversionStack_.back().startIter;
10328
647k
    if (!d->inversionStack_.back().iterValid) {
10329
207k
        startIter = d->steps_.begin();
10330
439k
    } else {
10331
439k
        ++startIter; // advance after the last valid element we marked above
10332
439k
    }
10333
    // Invert the inversion status of the steps between the start point and
10334
    // the current end of steps
10335
2.80M
    for (auto iter = startIter; iter != d->steps_.end(); ++iter) {
10336
2.15M
        iter->inverted = !iter->inverted;
10337
4.30M
        for (auto &paramValue : iter->paramValues) {
10338
4.30M
            if (paramValue.key == "omit_fwd")
10339
241
                paramValue.key = "omit_inv";
10340
4.30M
            else if (paramValue.key == "omit_inv")
10341
160
                paramValue.key = "omit_fwd";
10342
4.30M
        }
10343
2.15M
    }
10344
    // And reverse the order of steps in that range as well.
10345
647k
    std::reverse(startIter, d->steps_.end());
10346
647k
    d->inversionStack_.pop_back();
10347
647k
}
10348
10349
// ---------------------------------------------------------------------------
10350
10351
0
bool PROJStringFormatter::isInverted() const {
10352
0
    return d->inversionStack_.back().currentInversionState;
10353
0
}
10354
10355
// ---------------------------------------------------------------------------
10356
10357
2.83M
void PROJStringFormatter::Private::addStep() { steps_.emplace_back(Step()); }
10358
10359
// ---------------------------------------------------------------------------
10360
10361
2.79M
void PROJStringFormatter::addStep(const char *stepName) {
10362
2.79M
    d->addStep();
10363
2.79M
    d->steps_.back().name.assign(stepName);
10364
2.79M
}
10365
10366
// ---------------------------------------------------------------------------
10367
10368
42.7k
void PROJStringFormatter::addStep(const std::string &stepName) {
10369
42.7k
    d->addStep();
10370
42.7k
    d->steps_.back().name = stepName;
10371
42.7k
}
10372
10373
// ---------------------------------------------------------------------------
10374
10375
147k
void PROJStringFormatter::setCurrentStepInverted(bool inverted) {
10376
147k
    assert(!d->steps_.empty());
10377
147k
    d->steps_.back().inverted = inverted;
10378
147k
}
10379
10380
// ---------------------------------------------------------------------------
10381
10382
0
bool PROJStringFormatter::hasParam(const char *paramName) const {
10383
0
    if (!d->steps_.empty()) {
10384
0
        for (const auto &paramValue : d->steps_.back().paramValues) {
10385
0
            if (paramValue.keyEquals(paramName)) {
10386
0
                return true;
10387
0
            }
10388
0
        }
10389
0
    }
10390
0
    return false;
10391
0
}
10392
10393
// ---------------------------------------------------------------------------
10394
10395
26.0k
void PROJStringFormatter::addNoDefs(bool b) { d->addNoDefs_ = b; }
10396
10397
// ---------------------------------------------------------------------------
10398
10399
122k
bool PROJStringFormatter::getAddNoDefs() const { return d->addNoDefs_; }
10400
10401
// ---------------------------------------------------------------------------
10402
10403
345k
void PROJStringFormatter::addParam(const std::string &paramName) {
10404
345k
    if (d->steps_.empty()) {
10405
0
        d->addStep();
10406
0
    }
10407
345k
    d->steps_.back().paramValues.push_back(Step::KeyValue(paramName));
10408
345k
}
10409
10410
// ---------------------------------------------------------------------------
10411
10412
23
void PROJStringFormatter::addParam(const char *paramName, int val) {
10413
23
    addParam(std::string(paramName), val);
10414
23
}
10415
10416
23
void PROJStringFormatter::addParam(const std::string &paramName, int val) {
10417
23
    addParam(paramName, internal::toString(val));
10418
23
}
10419
10420
// ---------------------------------------------------------------------------
10421
10422
922k
static std::string formatToString(double val, double precision) {
10423
922k
    if (std::abs(val * 10 - std::round(val * 10)) < precision) {
10424
        // For the purpose of
10425
        // https://www.epsg-registry.org/export.htm?wkt=urn:ogc:def:crs:EPSG::27561
10426
        // Latitude of natural of origin to be properly rounded from 55 grad
10427
        // to
10428
        // 49.5 deg
10429
752k
        val = std::round(val * 10) / 10;
10430
752k
    }
10431
922k
    return normalizeSerializedString(internal::toString(val));
10432
922k
}
10433
10434
// ---------------------------------------------------------------------------
10435
10436
902k
void PROJStringFormatter::addParam(const char *paramName, double val) {
10437
902k
    addParam(std::string(paramName), val);
10438
902k
}
10439
10440
922k
void PROJStringFormatter::addParam(const std::string &paramName, double val) {
10441
922k
    if (paramName == "dt") {
10442
0
        addParam(paramName,
10443
0
                 normalizeSerializedString(internal::toString(val, 7)));
10444
922k
    } else {
10445
922k
        addParam(paramName, formatToString(val, 1e-8));
10446
922k
    }
10447
922k
}
10448
10449
// ---------------------------------------------------------------------------
10450
10451
void PROJStringFormatter::addParam(const char *paramName,
10452
41
                                   const std::vector<double> &vals) {
10453
41
    std::string paramValue;
10454
328
    for (size_t i = 0; i < vals.size(); ++i) {
10455
287
        if (i > 0) {
10456
246
            paramValue += ',';
10457
246
        }
10458
287
        paramValue += formatToString(vals[i], 1e-8);
10459
287
    }
10460
41
    addParam(paramName, paramValue);
10461
41
}
10462
10463
// ---------------------------------------------------------------------------
10464
10465
1.66M
void PROJStringFormatter::addParam(const char *paramName, const char *val) {
10466
1.66M
    addParam(std::string(paramName), val);
10467
1.66M
}
10468
10469
void PROJStringFormatter::addParam(const char *paramName,
10470
1.81M
                                   const std::string &val) {
10471
1.81M
    addParam(std::string(paramName), val);
10472
1.81M
}
10473
10474
void PROJStringFormatter::addParam(const std::string &paramName,
10475
1.66M
                                   const char *val) {
10476
1.66M
    addParam(paramName, std::string(val));
10477
1.66M
}
10478
10479
// ---------------------------------------------------------------------------
10480
10481
void PROJStringFormatter::addParam(const std::string &paramName,
10482
4.46M
                                   const std::string &val) {
10483
4.46M
    if (d->steps_.empty()) {
10484
623
        d->addStep();
10485
623
    }
10486
4.46M
    d->steps_.back().paramValues.push_back(Step::KeyValue(paramName, val));
10487
4.46M
}
10488
10489
// ---------------------------------------------------------------------------
10490
10491
void PROJStringFormatter::setTOWGS84Parameters(
10492
607
    const std::vector<double> &params) {
10493
607
    d->toWGS84Parameters_ = params;
10494
607
}
10495
10496
// ---------------------------------------------------------------------------
10497
10498
475k
const std::vector<double> &PROJStringFormatter::getTOWGS84Parameters() const {
10499
475k
    return d->toWGS84Parameters_;
10500
475k
}
10501
10502
// ---------------------------------------------------------------------------
10503
10504
29.6k
std::set<std::string> PROJStringFormatter::getUsedGridNames() const {
10505
29.6k
    std::set<std::string> res;
10506
184k
    for (const auto &step : d->steps_) {
10507
504k
        for (const auto &param : step.paramValues) {
10508
504k
            if (param.keyEquals("grids") || param.keyEquals("file")) {
10509
19.8k
                const auto gridNames = split(param.value, ",");
10510
57.0k
                for (const auto &gridName : gridNames) {
10511
57.0k
                    res.insert(gridName);
10512
57.0k
                }
10513
19.8k
            }
10514
504k
        }
10515
184k
    }
10516
29.6k
    return res;
10517
29.6k
}
10518
10519
// ---------------------------------------------------------------------------
10520
10521
117k
bool PROJStringFormatter::requiresPerCoordinateInputTime() const {
10522
661k
    for (const auto &step : d->steps_) {
10523
661k
        if (step.name == "set" && !step.inverted) {
10524
40.4k
            for (const auto &param : step.paramValues) {
10525
40.4k
                if (param.keyEquals("v_4")) {
10526
1
                    return false;
10527
1
                }
10528
40.4k
            }
10529
651k
        } else if (step.name == "helmert") {
10530
143k
            for (const auto &param : step.paramValues) {
10531
143k
                if (param.keyEquals("t_epoch")) {
10532
47
                    return true;
10533
47
                }
10534
143k
            }
10535
611k
        } else if (step.name == "deformation") {
10536
13.1k
            for (const auto &param : step.paramValues) {
10537
13.1k
                if (param.keyEquals("t_epoch")) {
10538
908
                    return true;
10539
908
                }
10540
13.1k
            }
10541
607k
        } else if (step.name == "defmodel") {
10542
0
            return true;
10543
0
        }
10544
661k
    }
10545
116k
    return false;
10546
117k
}
10547
10548
// ---------------------------------------------------------------------------
10549
10550
void PROJStringFormatter::setVDatumExtension(const std::string &filename,
10551
942
                                             const std::string &geoidCRSValue) {
10552
942
    d->vDatumExtension_ = filename;
10553
942
    d->geoidCRSValue_ = geoidCRSValue;
10554
942
}
10555
10556
// ---------------------------------------------------------------------------
10557
10558
819
const std::string &PROJStringFormatter::getVDatumExtension() const {
10559
819
    return d->vDatumExtension_;
10560
819
}
10561
10562
// ---------------------------------------------------------------------------
10563
10564
819
const std::string &PROJStringFormatter::getGeoidCRSValue() const {
10565
819
    return d->geoidCRSValue_;
10566
819
}
10567
10568
// ---------------------------------------------------------------------------
10569
10570
409
void PROJStringFormatter::setHDatumExtension(const std::string &filename) {
10571
409
    d->hDatumExtension_ = filename;
10572
409
}
10573
10574
// ---------------------------------------------------------------------------
10575
10576
475k
const std::string &PROJStringFormatter::getHDatumExtension() const {
10577
475k
    return d->hDatumExtension_;
10578
475k
}
10579
10580
// ---------------------------------------------------------------------------
10581
10582
void PROJStringFormatter::setGeogCRSOfCompoundCRS(
10583
371
    const crs::GeographicCRSPtr &crs) {
10584
371
    d->geogCRSOfCompoundCRS_ = crs;
10585
371
}
10586
10587
// ---------------------------------------------------------------------------
10588
10589
const crs::GeographicCRSPtr &
10590
1.14k
PROJStringFormatter::getGeogCRSOfCompoundCRS() const {
10591
1.14k
    return d->geogCRSOfCompoundCRS_;
10592
1.14k
}
10593
10594
// ---------------------------------------------------------------------------
10595
10596
207k
void PROJStringFormatter::setOmitProjLongLatIfPossible(bool omit) {
10597
207k
    assert(d->omitProjLongLatIfPossible_ ^ omit);
10598
207k
    d->omitProjLongLatIfPossible_ = omit;
10599
207k
}
10600
10601
// ---------------------------------------------------------------------------
10602
10603
426k
bool PROJStringFormatter::omitProjLongLatIfPossible() const {
10604
426k
    return d->omitProjLongLatIfPossible_;
10605
426k
}
10606
10607
// ---------------------------------------------------------------------------
10608
10609
246k
void PROJStringFormatter::pushOmitZUnitConversion() {
10610
246k
    d->omitZUnitConversion_.push_back(true);
10611
246k
}
10612
10613
// ---------------------------------------------------------------------------
10614
10615
246k
void PROJStringFormatter::popOmitZUnitConversion() {
10616
246k
    assert(d->omitZUnitConversion_.size() > 1);
10617
246k
    d->omitZUnitConversion_.pop_back();
10618
246k
}
10619
10620
// ---------------------------------------------------------------------------
10621
10622
524k
bool PROJStringFormatter::omitZUnitConversion() const {
10623
524k
    return d->omitZUnitConversion_.back();
10624
524k
}
10625
10626
// ---------------------------------------------------------------------------
10627
10628
92.5k
void PROJStringFormatter::pushOmitHorizontalConversionInVertTransformation() {
10629
92.5k
    d->omitHorizontalConversionInVertTransformation_.push_back(true);
10630
92.5k
}
10631
10632
// ---------------------------------------------------------------------------
10633
10634
92.5k
void PROJStringFormatter::popOmitHorizontalConversionInVertTransformation() {
10635
92.5k
    assert(d->omitHorizontalConversionInVertTransformation_.size() > 1);
10636
92.5k
    d->omitHorizontalConversionInVertTransformation_.pop_back();
10637
92.5k
}
10638
10639
// ---------------------------------------------------------------------------
10640
10641
218k
bool PROJStringFormatter::omitHorizontalConversionInVertTransformation() const {
10642
218k
    return d->omitHorizontalConversionInVertTransformation_.back();
10643
218k
}
10644
10645
// ---------------------------------------------------------------------------
10646
10647
13.9k
void PROJStringFormatter::setLegacyCRSToCRSContext(bool legacyContext) {
10648
13.9k
    d->legacyCRSToCRSContext_ = legacyContext;
10649
13.9k
}
10650
10651
// ---------------------------------------------------------------------------
10652
10653
358k
bool PROJStringFormatter::getLegacyCRSToCRSContext() const {
10654
358k
    return d->legacyCRSToCRSContext_;
10655
358k
}
10656
10657
// ---------------------------------------------------------------------------
10658
10659
/** Asks for a "normalized" output during toString(), aimed at comparing two
10660
 * strings for equivalence.
10661
 *
10662
 * This consists for now in sorting the +key=value option in lexicographic
10663
 * order.
10664
 */
10665
13.6k
PROJStringFormatter &PROJStringFormatter::setNormalizeOutput() {
10666
13.6k
    d->normalizeOutput_ = true;
10667
13.6k
    return *this;
10668
13.6k
}
10669
10670
// ---------------------------------------------------------------------------
10671
10672
552k
const DatabaseContextPtr &PROJStringFormatter::databaseContext() const {
10673
552k
    return d->dbContext_;
10674
552k
}
10675
10676
//! @endcond
10677
10678
// ---------------------------------------------------------------------------
10679
10680
//! @cond Doxygen_Suppress
10681
10682
struct PROJStringParser::Private {
10683
    DatabaseContextPtr dbContext_{};
10684
    PJ_CONTEXT *ctx_{};
10685
    bool usePROJ4InitRules_ = false;
10686
    std::vector<std::string> warningList_{};
10687
10688
    std::string projString_{};
10689
10690
    std::vector<Step> steps_{};
10691
    std::vector<Step::KeyValue> globalParamValues_{};
10692
    std::string title_{};
10693
10694
    bool ignoreNadgrids_ = false;
10695
10696
    template <class T>
10697
    // cppcheck-suppress functionStatic
10698
87.6k
    bool hasParamValue(Step &step, const T key) {
10699
161k
        for (auto &pair : globalParamValues_) {
10700
161k
            if (ci_equal(pair.key, key)) {
10701
1.47k
                pair.usedByParser = true;
10702
1.47k
                return true;
10703
1.47k
            }
10704
161k
        }
10705
206k
        for (auto &pair : step.paramValues) {
10706
206k
            if (ci_equal(pair.key, key)) {
10707
7.48k
                pair.usedByParser = true;
10708
7.48k
                return true;
10709
7.48k
            }
10710
206k
        }
10711
78.7k
        return false;
10712
86.2k
    }
10713
10714
    template <class T>
10715
    // cppcheck-suppress functionStatic
10716
2.13k
    const std::string &getGlobalParamValue(T key) {
10717
13.4k
        for (auto &pair : globalParamValues_) {
10718
13.4k
            if (ci_equal(pair.key, key)) {
10719
1.31k
                pair.usedByParser = true;
10720
1.31k
                return pair.value;
10721
1.31k
            }
10722
13.4k
        }
10723
814
        return emptyString;
10724
2.13k
    }
10725
10726
    template <class T>
10727
    // cppcheck-suppress functionStatic
10728
423k
    const std::string &getParamValue(Step &step, const T key) {
10729
619k
        for (auto &pair : globalParamValues_) {
10730
619k
            if (ci_equal(pair.key, key)) {
10731
7.24k
                pair.usedByParser = true;
10732
7.24k
                return pair.value;
10733
7.24k
            }
10734
619k
        }
10735
918k
        for (auto &pair : step.paramValues) {
10736
918k
            if (ci_equal(pair.key, key)) {
10737
38.6k
                pair.usedByParser = true;
10738
38.6k
                return pair.value;
10739
38.6k
            }
10740
918k
        }
10741
378k
        return emptyString;
10742
416k
    }
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const& osgeo::proj::io::PROJStringParser::Private::getParamValue<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(osgeo::proj::io::Step&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
Line
Count
Source
10728
89.4k
    const std::string &getParamValue(Step &step, const T key) {
10729
141k
        for (auto &pair : globalParamValues_) {
10730
141k
            if (ci_equal(pair.key, key)) {
10731
262
                pair.usedByParser = true;
10732
262
                return pair.value;
10733
262
            }
10734
141k
        }
10735
224k
        for (auto &pair : step.paramValues) {
10736
224k
            if (ci_equal(pair.key, key)) {
10737
2.98k
                pair.usedByParser = true;
10738
2.98k
                return pair.value;
10739
2.98k
            }
10740
224k
        }
10741
86.1k
        return emptyString;
10742
89.1k
    }
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const& osgeo::proj::io::PROJStringParser::Private::getParamValue<char const*>(osgeo::proj::io::Step&, char const*)
Line
Count
Source
10728
334k
    const std::string &getParamValue(Step &step, const T key) {
10729
478k
        for (auto &pair : globalParamValues_) {
10730
478k
            if (ci_equal(pair.key, key)) {
10731
6.98k
                pair.usedByParser = true;
10732
6.98k
                return pair.value;
10733
6.98k
            }
10734
478k
        }
10735
693k
        for (auto &pair : step.paramValues) {
10736
693k
            if (ci_equal(pair.key, key)) {
10737
35.6k
                pair.usedByParser = true;
10738
35.6k
                return pair.value;
10739
35.6k
            }
10740
693k
        }
10741
291k
        return emptyString;
10742
327k
    }
10743
10744
2.07k
    static const std::string &getParamValueK(Step &step) {
10745
4.20k
        for (auto &pair : step.paramValues) {
10746
4.20k
            if (ci_equal(pair.key, "k") || ci_equal(pair.key, "k_0")) {
10747
76
                pair.usedByParser = true;
10748
76
                return pair.value;
10749
76
            }
10750
4.20k
        }
10751
1.99k
        return emptyString;
10752
2.07k
    }
10753
10754
    // cppcheck-suppress functionStatic
10755
17.6k
    bool hasUnusedParameters(const Step &step) const {
10756
17.6k
        if (steps_.size() == 1) {
10757
15.5k
            for (const auto &pair : step.paramValues) {
10758
15.5k
                if (pair.key != "no_defs" && !pair.usedByParser) {
10759
4.51k
                    return true;
10760
4.51k
                }
10761
15.5k
            }
10762
14.8k
        }
10763
13.1k
        return false;
10764
17.6k
    }
10765
10766
    // cppcheck-suppress functionStatic
10767
    std::string guessBodyName(double a);
10768
10769
    PrimeMeridianNNPtr buildPrimeMeridian(Step &step);
10770
    GeodeticReferenceFrameNNPtr buildDatum(Step &step,
10771
                                           const std::string &title);
10772
    GeodeticCRSNNPtr buildGeodeticCRS(int iStep, int iUnitConvert,
10773
                                      int iAxisSwap, bool ignorePROJAxis);
10774
    GeodeticCRSNNPtr buildGeocentricCRS(int iStep, int iUnitConvert);
10775
    CRSNNPtr buildProjectedCRS(int iStep, const GeodeticCRSNNPtr &geogCRS,
10776
                               int iUnitConvert, int iAxisSwap);
10777
    CRSNNPtr buildBoundOrCompoundCRSIfNeeded(int iStep, CRSNNPtr crs);
10778
    UnitOfMeasure buildUnit(Step &step, const std::string &unitsParamName,
10779
                            const std::string &toMeterParamName);
10780
10781
    enum class AxisType { REGULAR, NORTH_POLE, SOUTH_POLE };
10782
10783
    std::vector<CoordinateSystemAxisNNPtr>
10784
    processAxisSwap(Step &step, const UnitOfMeasure &unit, int iAxisSwap,
10785
                    AxisType axisType, bool ignorePROJAxis);
10786
10787
    EllipsoidalCSNNPtr buildEllipsoidalCS(int iStep, int iUnitConvert,
10788
                                          int iAxisSwap, bool ignorePROJAxis);
10789
10790
    SphericalCSNNPtr buildSphericalCS(int iStep, int iUnitConvert,
10791
                                      int iAxisSwap, bool ignorePROJAxis);
10792
};
10793
10794
//! @endcond
10795
10796
// ---------------------------------------------------------------------------
10797
10798
12.5k
PROJStringParser::PROJStringParser() : d(std::make_unique<Private>()) {}
10799
10800
// ---------------------------------------------------------------------------
10801
10802
//! @cond Doxygen_Suppress
10803
12.5k
PROJStringParser::~PROJStringParser() = default;
10804
//! @endcond
10805
10806
// ---------------------------------------------------------------------------
10807
10808
/** \brief Attach a database context, to allow queries in it if needed.
10809
 */
10810
PROJStringParser &
10811
12.3k
PROJStringParser::attachDatabaseContext(const DatabaseContextPtr &dbContext) {
10812
12.3k
    d->dbContext_ = dbContext;
10813
12.3k
    return *this;
10814
12.3k
}
10815
10816
// ---------------------------------------------------------------------------
10817
10818
//! @cond Doxygen_Suppress
10819
12.3k
PROJStringParser &PROJStringParser::attachContext(PJ_CONTEXT *ctx) {
10820
12.3k
    d->ctx_ = ctx;
10821
12.3k
    return *this;
10822
12.3k
}
10823
//! @endcond
10824
10825
// ---------------------------------------------------------------------------
10826
10827
/** \brief Set how init=epsg:XXXX syntax should be interpreted.
10828
 *
10829
 * @param enable When set to true,
10830
 * init=epsg:XXXX syntax will be allowed and will be interpreted according to
10831
 * PROJ.4 and PROJ.5 rules, that is geodeticCRS will have longitude, latitude
10832
 * order and will expect/output coordinates in radians. ProjectedCRS will have
10833
 * easting, northing axis order (except the ones with Transverse Mercator South
10834
 * Orientated projection).
10835
 */
10836
12.3k
PROJStringParser &PROJStringParser::setUsePROJ4InitRules(bool enable) {
10837
12.3k
    d->usePROJ4InitRules_ = enable;
10838
12.3k
    return *this;
10839
12.3k
}
10840
10841
// ---------------------------------------------------------------------------
10842
10843
/** \brief Return the list of warnings found during parsing.
10844
 */
10845
0
std::vector<std::string> PROJStringParser::warningList() const {
10846
0
    return d->warningList_;
10847
0
}
10848
10849
// ---------------------------------------------------------------------------
10850
10851
//! @cond Doxygen_Suppress
10852
10853
// ---------------------------------------------------------------------------
10854
10855
static const struct LinearUnitDesc {
10856
    const char *projName;
10857
    const char *convToMeter;
10858
    const char *name;
10859
    int epsgCode;
10860
} linearUnitDescs[] = {
10861
    {"mm", "0.001", "millimetre", 1025},
10862
    {"cm", "0.01", "centimetre", 1033},
10863
    {"m", "1.0", "metre", 9001},
10864
    {"meter", "1.0", "metre", 9001}, // alternative
10865
    {"metre", "1.0", "metre", 9001}, // alternative
10866
    {"ft", "0.3048", "foot", 9002},
10867
    {"us-ft", "0.3048006096012192", "US survey foot", 9003},
10868
    {"fath", "1.8288", "fathom", 9014},
10869
    {"kmi", "1852", "nautical mile", 9030},
10870
    {"us-ch", "20.11684023368047", "US survey chain", 9033},
10871
    {"us-mi", "1609.347218694437", "US survey mile", 9035},
10872
    {"km", "1000.0", "kilometre", 9036},
10873
    {"ind-ft", "0.30479841", "Indian foot (1937)", 9081},
10874
    {"ind-yd", "0.91439523", "Indian yard (1937)", 9085},
10875
    {"mi", "1609.344", "Statute mile", 9093},
10876
    {"yd", "0.9144", "yard", 9096},
10877
    {"ch", "20.1168", "chain", 9097},
10878
    {"link", "0.201168", "link", 9098},
10879
    {"dm", "0.1", "decimetre", 0},                       // no EPSG equivalent
10880
    {"in", "0.0254", "inch", 0},                         // no EPSG equivalent
10881
    {"us-in", "0.025400050800101", "US survey inch", 0}, // no EPSG equivalent
10882
    {"us-yd", "0.914401828803658", "US survey yard", 0}, // no EPSG equivalent
10883
    {"ind-ch", "20.11669506", "Indian chain", 0},        // no EPSG equivalent
10884
};
10885
10886
2.49k
static const LinearUnitDesc *getLinearUnits(const std::string &projName) {
10887
12.8k
    for (const auto &desc : linearUnitDescs) {
10888
12.8k
        if (desc.projName == projName)
10889
2.46k
            return &desc;
10890
12.8k
    }
10891
27
    return nullptr;
10892
2.49k
}
10893
10894
212
static const LinearUnitDesc *getLinearUnits(double toMeter) {
10895
4.67k
    for (const auto &desc : linearUnitDescs) {
10896
4.67k
        if (std::fabs(c_locale_stod(desc.convToMeter) - toMeter) <
10897
4.67k
            1e-10 * toMeter) {
10898
10
            return &desc;
10899
10
        }
10900
4.67k
    }
10901
202
    return nullptr;
10902
212
}
10903
10904
// ---------------------------------------------------------------------------
10905
10906
2.47k
static UnitOfMeasure _buildUnit(const LinearUnitDesc *unitsMatch) {
10907
2.47k
    std::string unitsCode;
10908
2.47k
    if (unitsMatch->epsgCode) {
10909
2.45k
        std::ostringstream buffer;
10910
2.45k
        buffer.imbue(std::locale::classic());
10911
2.45k
        buffer << unitsMatch->epsgCode;
10912
2.45k
        unitsCode = buffer.str();
10913
2.45k
    }
10914
2.47k
    return UnitOfMeasure(
10915
2.47k
        unitsMatch->name, c_locale_stod(unitsMatch->convToMeter),
10916
2.47k
        UnitOfMeasure::Type::LINEAR,
10917
2.47k
        unitsMatch->epsgCode ? Identifier::EPSG : std::string(), unitsCode);
10918
2.47k
}
10919
10920
// ---------------------------------------------------------------------------
10921
10922
202
static UnitOfMeasure _buildUnit(double to_meter_value) {
10923
    // TODO: look-up in EPSG catalog
10924
202
    if (to_meter_value == 0) {
10925
1
        throw ParsingException("invalid unit value");
10926
1
    }
10927
201
    return UnitOfMeasure("unknown", to_meter_value,
10928
201
                         UnitOfMeasure::Type::LINEAR);
10929
202
}
10930
10931
// ---------------------------------------------------------------------------
10932
10933
UnitOfMeasure
10934
PROJStringParser::Private::buildUnit(Step &step,
10935
                                     const std::string &unitsParamName,
10936
35.4k
                                     const std::string &toMeterParamName) {
10937
35.4k
    UnitOfMeasure unit = UnitOfMeasure::METRE;
10938
35.4k
    const LinearUnitDesc *unitsMatch = nullptr;
10939
35.4k
    const auto &projUnits = getParamValue(step, unitsParamName);
10940
35.4k
    if (!projUnits.empty()) {
10941
2.49k
        unitsMatch = getLinearUnits(projUnits);
10942
2.49k
        if (unitsMatch == nullptr) {
10943
22
            throw ParsingException("unhandled " + unitsParamName + "=" +
10944
22
                                   projUnits);
10945
22
        }
10946
2.49k
    }
10947
10948
35.4k
    const auto &toMeter = getParamValue(step, toMeterParamName);
10949
35.4k
    if (!toMeter.empty()) {
10950
222
        double to_meter_value;
10951
222
        try {
10952
222
            to_meter_value = c_locale_stod(toMeter);
10953
222
        } catch (const std::invalid_argument &) {
10954
10
            throw ParsingException("invalid value for " + toMeterParamName);
10955
10
        }
10956
212
        unitsMatch = getLinearUnits(to_meter_value);
10957
212
        if (unitsMatch == nullptr) {
10958
202
            unit = _buildUnit(to_meter_value);
10959
202
        }
10960
212
    }
10961
10962
35.4k
    if (unitsMatch) {
10963
2.47k
        unit = _buildUnit(unitsMatch);
10964
2.47k
    }
10965
10966
35.4k
    return unit;
10967
35.4k
}
10968
10969
// ---------------------------------------------------------------------------
10970
10971
static const struct DatumDesc {
10972
    const char *projName;
10973
    const char *gcsName;
10974
    int gcsCode;
10975
    const char *datumName;
10976
    int datumCode;
10977
    const char *ellipsoidName;
10978
    int ellipsoidCode;
10979
    double a;
10980
    double rf;
10981
} datumDescs[] = {
10982
    {"GGRS87", "GGRS87", 4121, "Greek Geodetic Reference System 1987", 6121,
10983
     "GRS 1980", 7019, 6378137, 298.257222101},
10984
    {"potsdam", "DHDN", 4314, "Deutsches Hauptdreiecksnetz", 6314,
10985
     "Bessel 1841", 7004, 6377397.155, 299.1528128},
10986
    {"carthage", "Carthage", 4223, "Carthage", 6223, "Clarke 1880 (IGN)", 7011,
10987
     6378249.2, 293.4660213},
10988
    {"hermannskogel", "MGI", 4312, "Militar-Geographische Institut", 6312,
10989
     "Bessel 1841", 7004, 6377397.155, 299.1528128},
10990
    {"ire65", "TM65", 4299, "TM65", 6299, "Airy Modified 1849", 7002,
10991
     6377340.189, 299.3249646},
10992
    {"nzgd49", "NZGD49", 4272, "New Zealand Geodetic Datum 1949", 6272,
10993
     "International 1924", 7022, 6378388, 297},
10994
    {"OSGB36", "OSGB 1936", 4277, "OSGB 1936", 6277, "Airy 1830", 7001,
10995
     6377563.396, 299.3249646},
10996
};
10997
10998
// ---------------------------------------------------------------------------
10999
11000
29.2k
static bool isGeographicStep(const std::string &name) {
11001
29.2k
    return name == "longlat" || name == "lonlat" || name == "latlong" ||
11002
18.2k
           name == "latlon";
11003
29.2k
}
11004
11005
// ---------------------------------------------------------------------------
11006
11007
8.92k
static bool isGeocentricStep(const std::string &name) {
11008
8.92k
    return name == "geocent" || name == "cart";
11009
8.92k
}
11010
11011
// ---------------------------------------------------------------------------
11012
11013
19.3k
static bool isTopocentricStep(const std::string &name) {
11014
19.3k
    return name == "topocentric";
11015
19.3k
}
11016
11017
// ---------------------------------------------------------------------------
11018
11019
9.61k
static bool isProjectedStep(const std::string &name) {
11020
9.61k
    if (name == "etmerc" || name == "utm" ||
11021
9.52k
        !getMappingsFromPROJName(name).empty()) {
11022
3.04k
        return true;
11023
3.04k
    }
11024
    // IMPROVE ME: have a better way of distinguishing projections from
11025
    // other
11026
    // transformations.
11027
6.56k
    if (name == "pipeline" || name == "geoc" || name == "deformation" ||
11028
6.54k
        name == "helmert" || name == "hgridshift" || name == "molodensky" ||
11029
6.41k
        name == "vgridshift") {
11030
218
        return false;
11031
218
    }
11032
6.35k
    const auto *operations = proj_list_operations();
11033
578k
    for (int i = 0; operations[i].id != nullptr; ++i) {
11034
578k
        if (name == operations[i].id) {
11035
5.96k
            return true;
11036
5.96k
        }
11037
578k
    }
11038
389
    return false;
11039
6.35k
}
11040
11041
// ---------------------------------------------------------------------------
11042
11043
32.9k
static PropertyMap createMapWithUnknownName() {
11044
32.9k
    return PropertyMap().set(common::IdentifiedObject::NAME_KEY, "unknown");
11045
32.9k
}
11046
11047
// ---------------------------------------------------------------------------
11048
11049
27.9k
PrimeMeridianNNPtr PROJStringParser::Private::buildPrimeMeridian(Step &step) {
11050
11051
27.9k
    PrimeMeridianNNPtr pm = PrimeMeridian::GREENWICH;
11052
27.9k
    const auto &pmStr = getParamValue(step, "pm");
11053
27.9k
    if (!pmStr.empty()) {
11054
2.94k
        char *end;
11055
2.94k
        double pmValue = dmstor(pmStr.c_str(), &end) * RAD_TO_DEG;
11056
2.94k
        if (pmValue != HUGE_VAL && *end == '\0') {
11057
2.82k
            pm = PrimeMeridian::create(createMapWithUnknownName(),
11058
2.82k
                                       Angle(pmValue));
11059
2.82k
        } else {
11060
114
            bool found = false;
11061
114
            if (pmStr == "paris") {
11062
35
                found = true;
11063
35
                pm = PrimeMeridian::PARIS;
11064
35
            }
11065
114
            auto proj_prime_meridians = proj_list_prime_meridians();
11066
972
            for (int i = 0; !found && proj_prime_meridians[i].id != nullptr;
11067
932
                 i++) {
11068
932
                if (pmStr == proj_prime_meridians[i].id) {
11069
74
                    found = true;
11070
74
                    std::string name = static_cast<char>(::toupper(pmStr[0])) +
11071
74
                                       pmStr.substr(1);
11072
74
                    pmValue = dmstor(proj_prime_meridians[i].defn, nullptr) *
11073
74
                              RAD_TO_DEG;
11074
74
                    pm = PrimeMeridian::create(
11075
74
                        PropertyMap().set(IdentifiedObject::NAME_KEY, name),
11076
74
                        Angle(pmValue));
11077
74
                    break;
11078
74
                }
11079
932
            }
11080
114
            if (!found) {
11081
5
                throw ParsingException("unknown pm " + pmStr);
11082
5
            }
11083
114
        }
11084
2.94k
    }
11085
27.9k
    return pm;
11086
27.9k
}
11087
11088
// ---------------------------------------------------------------------------
11089
11090
856
std::string PROJStringParser::Private::guessBodyName(double a) {
11091
11092
856
    auto ret = Ellipsoid::guessBodyName(dbContext_, a);
11093
856
    if (ret == NON_EARTH_BODY && dbContext_ == nullptr && ctx_ != nullptr) {
11094
76
        dbContext_ =
11095
76
            ctx_->get_cpp_context()->getDatabaseContext().as_nullable();
11096
76
        if (dbContext_) {
11097
76
            ret = Ellipsoid::guessBodyName(dbContext_, a);
11098
76
        }
11099
76
    }
11100
856
    return ret;
11101
856
}
11102
11103
// ---------------------------------------------------------------------------
11104
11105
GeodeticReferenceFrameNNPtr
11106
17.7k
PROJStringParser::Private::buildDatum(Step &step, const std::string &title) {
11107
11108
17.7k
    std::string ellpsStr = getParamValue(step, "ellps");
11109
17.7k
    const auto &datumStr = getParamValue(step, "datum");
11110
17.7k
    const auto &RStr = getParamValue(step, "R");
11111
17.7k
    const auto &aStr = getParamValue(step, "a");
11112
17.7k
    const auto &bStr = getParamValue(step, "b");
11113
17.7k
    const auto &rfStr = getParamValue(step, "rf");
11114
17.7k
    const auto &fStr = getParamValue(step, "f");
11115
17.7k
    const auto &esStr = getParamValue(step, "es");
11116
17.7k
    const auto &eStr = getParamValue(step, "e");
11117
17.7k
    double a = -1.0;
11118
17.7k
    double b = -1.0;
11119
17.7k
    double rf = -1.0;
11120
17.7k
    const util::optional<std::string> optionalEmptyString{};
11121
17.7k
    const bool numericParamPresent =
11122
17.7k
        !RStr.empty() || !aStr.empty() || !bStr.empty() || !rfStr.empty() ||
11123
17.1k
        !fStr.empty() || !esStr.empty() || !eStr.empty();
11124
11125
17.7k
    if (!numericParamPresent && ellpsStr.empty() && datumStr.empty() &&
11126
14.0k
        (step.name == "krovak" || step.name == "mod_krovak")) {
11127
733
        ellpsStr = "bessel";
11128
733
    }
11129
11130
17.7k
    PrimeMeridianNNPtr pm(buildPrimeMeridian(step));
11131
17.7k
    PropertyMap grfMap;
11132
11133
17.7k
    const auto &nadgrids = getParamValue(step, "nadgrids");
11134
17.7k
    const auto &towgs84 = getParamValue(step, "towgs84");
11135
17.7k
    std::string datumNameSuffix;
11136
17.7k
    if (!nadgrids.empty()) {
11137
1.57k
        datumNameSuffix = " using nadgrids=" + nadgrids;
11138
16.2k
    } else if (!towgs84.empty()) {
11139
1.20k
        datumNameSuffix = " using towgs84=" + towgs84;
11140
1.20k
    }
11141
11142
    // It is arguable that we allow the prime meridian of a datum defined by
11143
    // its name to be overridden, but this is found at least in a regression
11144
    // test
11145
    // of GDAL. So let's keep the ellipsoid part of the datum in that case and
11146
    // use the specified prime meridian.
11147
17.7k
    const auto overridePmIfNeeded =
11148
17.7k
        [&pm, &datumNameSuffix](const GeodeticReferenceFrameNNPtr &grf) {
11149
14.7k
            if (pm->_isEquivalentTo(PrimeMeridian::GREENWICH.get())) {
11150
13.6k
                return grf;
11151
13.6k
            } else {
11152
1.07k
                return GeodeticReferenceFrame::create(
11153
1.07k
                    PropertyMap().set(IdentifiedObject::NAME_KEY,
11154
1.07k
                                      UNKNOWN_BASED_ON +
11155
1.07k
                                          grf->ellipsoid()->nameStr() +
11156
1.07k
                                          " ellipsoid" + datumNameSuffix),
11157
1.07k
                    grf->ellipsoid(), grf->anchorDefinition(), pm);
11158
1.07k
            }
11159
14.7k
        };
11160
11161
    // R take precedence
11162
17.7k
    if (!RStr.empty()) {
11163
118
        double R;
11164
118
        try {
11165
118
            R = c_locale_stod(RStr);
11166
118
        } catch (const std::invalid_argument &) {
11167
22
            throw ParsingException("Invalid R value");
11168
22
        }
11169
96
        auto ellipsoid = Ellipsoid::createSphere(createMapWithUnknownName(),
11170
96
                                                 Length(R), guessBodyName(R));
11171
96
        return GeodeticReferenceFrame::create(
11172
96
            grfMap.set(IdentifiedObject::NAME_KEY,
11173
96
                       title.empty() ? "unknown" + datumNameSuffix : title),
11174
96
            ellipsoid, optionalEmptyString, fixupPrimeMeridan(ellipsoid, pm));
11175
118
    }
11176
11177
17.6k
    if (!datumStr.empty()) {
11178
2.47k
        auto l_datum = [&datumStr, &overridePmIfNeeded, &grfMap,
11179
2.47k
                        &optionalEmptyString, &pm]() {
11180
2.47k
            if (datumStr == "WGS84") {
11181
1
                return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6326);
11182
2.47k
            } else if (datumStr == "NAD83") {
11183
528
                return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6269);
11184
1.95k
            } else if (datumStr == "NAD27") {
11185
850
                return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6267);
11186
1.10k
            } else {
11187
11188
6.00k
                for (const auto &datumDesc : datumDescs) {
11189
6.00k
                    if (datumStr == datumDesc.projName) {
11190
1.08k
                        (void)datumDesc.gcsName; // to please cppcheck
11191
1.08k
                        (void)datumDesc.gcsCode; // to please cppcheck
11192
1.08k
                        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11193
1.08k
                            grfMap
11194
1.08k
                                .set(IdentifiedObject::NAME_KEY,
11195
1.08k
                                     datumDesc.ellipsoidName)
11196
1.08k
                                .set(Identifier::CODESPACE_KEY,
11197
1.08k
                                     Identifier::EPSG)
11198
1.08k
                                .set(Identifier::CODE_KEY,
11199
1.08k
                                     datumDesc.ellipsoidCode),
11200
1.08k
                            Length(datumDesc.a), Scale(datumDesc.rf));
11201
1.08k
                        return GeodeticReferenceFrame::create(
11202
1.08k
                            grfMap
11203
1.08k
                                .set(IdentifiedObject::NAME_KEY,
11204
1.08k
                                     datumDesc.datumName)
11205
1.08k
                                .set(Identifier::CODESPACE_KEY,
11206
1.08k
                                     Identifier::EPSG)
11207
1.08k
                                .set(Identifier::CODE_KEY, datumDesc.datumCode),
11208
1.08k
                            ellipsoid, optionalEmptyString, pm);
11209
1.08k
                    }
11210
6.00k
                }
11211
1.10k
            }
11212
17
            throw ParsingException("unknown datum " + datumStr);
11213
2.47k
        }();
11214
2.47k
        if (!numericParamPresent) {
11215
2.05k
            return l_datum;
11216
2.05k
        }
11217
421
        a = l_datum->ellipsoid()->semiMajorAxis().getSIValue();
11218
421
        rf = l_datum->ellipsoid()->computedInverseFlattening();
11219
421
    }
11220
11221
15.2k
    else if (!ellpsStr.empty()) {
11222
1.47k
        auto l_datum = [&ellpsStr, &title, &grfMap, &optionalEmptyString, &pm,
11223
1.47k
                        &datumNameSuffix]() {
11224
1.47k
            if (ellpsStr == "WGS84") {
11225
23
                return GeodeticReferenceFrame::create(
11226
23
                    grfMap.set(IdentifiedObject::NAME_KEY,
11227
23
                               title.empty() ? std::string(UNKNOWN_BASED_ON)
11228
21
                                                   .append("WGS 84 ellipsoid")
11229
21
                                                   .append(datumNameSuffix)
11230
23
                                             : title),
11231
23
                    Ellipsoid::WGS84, optionalEmptyString, pm);
11232
1.45k
            } else if (ellpsStr == "GRS80") {
11233
29
                return GeodeticReferenceFrame::create(
11234
29
                    grfMap.set(IdentifiedObject::NAME_KEY,
11235
29
                               title.empty() ? std::string(UNKNOWN_BASED_ON)
11236
10
                                                   .append("GRS 1980 ellipsoid")
11237
10
                                                   .append(datumNameSuffix)
11238
29
                                             : title),
11239
29
                    Ellipsoid::GRS1980, optionalEmptyString, pm);
11240
1.42k
            } else {
11241
1.42k
                auto proj_ellps = proj_list_ellps();
11242
20.7k
                for (int i = 0; proj_ellps[i].id != nullptr; i++) {
11243
20.7k
                    if (ellpsStr == proj_ellps[i].id) {
11244
1.40k
                        assert(strncmp(proj_ellps[i].major, "a=", 2) == 0);
11245
1.40k
                        const double a_iter =
11246
1.40k
                            c_locale_stod(proj_ellps[i].major + 2);
11247
1.40k
                        EllipsoidPtr ellipsoid;
11248
1.40k
                        PropertyMap ellpsMap;
11249
1.40k
                        if (strncmp(proj_ellps[i].ell, "b=", 2) == 0) {
11250
49
                            const double b_iter =
11251
49
                                c_locale_stod(proj_ellps[i].ell + 2);
11252
49
                            ellipsoid =
11253
49
                                Ellipsoid::createTwoAxis(
11254
49
                                    ellpsMap.set(IdentifiedObject::NAME_KEY,
11255
49
                                                 proj_ellps[i].name),
11256
49
                                    Length(a_iter), Length(b_iter))
11257
49
                                    .as_nullable();
11258
1.36k
                        } else {
11259
1.36k
                            assert(strncmp(proj_ellps[i].ell, "rf=", 3) == 0);
11260
1.36k
                            const double rf_iter =
11261
1.36k
                                c_locale_stod(proj_ellps[i].ell + 3);
11262
1.36k
                            ellipsoid =
11263
1.36k
                                Ellipsoid::createFlattenedSphere(
11264
1.36k
                                    ellpsMap.set(IdentifiedObject::NAME_KEY,
11265
1.36k
                                                 proj_ellps[i].name),
11266
1.36k
                                    Length(a_iter), Scale(rf_iter))
11267
1.36k
                                    .as_nullable();
11268
1.36k
                        }
11269
1.40k
                        return GeodeticReferenceFrame::create(
11270
1.40k
                            grfMap.set(IdentifiedObject::NAME_KEY,
11271
1.40k
                                       title.empty()
11272
1.40k
                                           ? std::string(UNKNOWN_BASED_ON)
11273
1.22k
                                                 .append(proj_ellps[i].name)
11274
1.22k
                                                 .append(" ellipsoid")
11275
1.22k
                                                 .append(datumNameSuffix)
11276
1.40k
                                           : title),
11277
1.40k
                            NN_NO_CHECK(ellipsoid), optionalEmptyString, pm);
11278
1.40k
                    }
11279
20.7k
                }
11280
17
                throw ParsingException("unknown ellipsoid " + ellpsStr);
11281
1.42k
            }
11282
1.47k
        }();
11283
1.47k
        if (!numericParamPresent) {
11284
1.38k
            return l_datum;
11285
1.38k
        }
11286
92
        a = l_datum->ellipsoid()->semiMajorAxis().getSIValue();
11287
92
        if (l_datum->ellipsoid()->semiMinorAxis().has_value()) {
11288
21
            b = l_datum->ellipsoid()->semiMinorAxis()->getSIValue();
11289
71
        } else {
11290
71
            rf = l_datum->ellipsoid()->computedInverseFlattening();
11291
71
        }
11292
92
    }
11293
11294
14.2k
    if (!aStr.empty()) {
11295
540
        try {
11296
540
            a = c_locale_stod(aStr);
11297
540
        } catch (const std::invalid_argument &) {
11298
35
            throw ParsingException("Invalid a value");
11299
35
        }
11300
540
    }
11301
11302
14.2k
    const auto createGRF = [&grfMap, &title, &optionalEmptyString,
11303
14.2k
                            &datumNameSuffix,
11304
14.2k
                            &pm](const EllipsoidNNPtr &ellipsoid) {
11305
760
        std::string datumName(title);
11306
760
        if (title.empty()) {
11307
617
            if (ellipsoid->nameStr() != "unknown") {
11308
107
                datumName = UNKNOWN_BASED_ON;
11309
107
                datumName += ellipsoid->nameStr();
11310
107
                datumName += " ellipsoid";
11311
510
            } else {
11312
510
                datumName = "unknown";
11313
510
            }
11314
617
            datumName += datumNameSuffix;
11315
617
        }
11316
760
        return GeodeticReferenceFrame::create(
11317
760
            grfMap.set(IdentifiedObject::NAME_KEY, datumName), ellipsoid,
11318
760
            optionalEmptyString, fixupPrimeMeridan(ellipsoid, pm));
11319
760
    };
11320
11321
14.2k
    if (a > 0 && (b > 0 || !bStr.empty())) {
11322
148
        if (!bStr.empty()) {
11323
127
            try {
11324
127
                b = c_locale_stod(bStr);
11325
127
            } catch (const std::invalid_argument &) {
11326
6
                throw ParsingException("Invalid b value");
11327
6
            }
11328
127
        }
11329
142
        auto ellipsoid =
11330
142
            Ellipsoid::createTwoAxis(createMapWithUnknownName(), Length(a),
11331
142
                                     Length(b), guessBodyName(a))
11332
142
                ->identify();
11333
142
        return createGRF(ellipsoid);
11334
148
    }
11335
11336
14.0k
    else if (a > 0 && (rf >= 0 || !rfStr.empty())) {
11337
433
        if (!rfStr.empty()) {
11338
10
            try {
11339
10
                rf = c_locale_stod(rfStr);
11340
10
            } catch (const std::invalid_argument &) {
11341
8
                throw ParsingException("Invalid rf value");
11342
8
            }
11343
10
        }
11344
425
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11345
425
                             createMapWithUnknownName(), Length(a), Scale(rf),
11346
425
                             guessBodyName(a))
11347
425
                             ->identify();
11348
425
        return createGRF(ellipsoid);
11349
433
    }
11350
11351
13.6k
    else if (a > 0 && !fStr.empty()) {
11352
10
        double f;
11353
10
        try {
11354
10
            f = c_locale_stod(fStr);
11355
10
        } catch (const std::invalid_argument &) {
11356
3
            throw ParsingException("Invalid f value");
11357
3
        }
11358
7
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11359
7
                             createMapWithUnknownName(), Length(a),
11360
7
                             Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a))
11361
7
                             ->identify();
11362
7
        return createGRF(ellipsoid);
11363
10
    }
11364
11365
13.6k
    else if (a > 0 && !eStr.empty()) {
11366
12
        double e;
11367
12
        try {
11368
12
            e = c_locale_stod(eStr);
11369
12
        } catch (const std::invalid_argument &) {
11370
8
            throw ParsingException("Invalid e value");
11371
8
        }
11372
4
        double alpha = asin(e);    /* angular eccentricity */
11373
4
        double f = 1 - cos(alpha); /* = 1 - sqrt (1 - es); */
11374
4
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11375
4
                             createMapWithUnknownName(), Length(a),
11376
4
                             Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a))
11377
4
                             ->identify();
11378
4
        return createGRF(ellipsoid);
11379
12
    }
11380
11381
13.5k
    else if (a > 0 && !esStr.empty()) {
11382
0
        double es;
11383
0
        try {
11384
0
            es = c_locale_stod(esStr);
11385
0
        } catch (const std::invalid_argument &) {
11386
0
            throw ParsingException("Invalid es value");
11387
0
        }
11388
0
        double f = 1 - sqrt(1 - es);
11389
0
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11390
0
                             createMapWithUnknownName(), Length(a),
11391
0
                             Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a))
11392
0
                             ->identify();
11393
0
        return createGRF(ellipsoid);
11394
0
    }
11395
11396
    // If only a is specified, create a sphere
11397
13.5k
    if (a > 0 && bStr.empty() && rfStr.empty() && eStr.empty() &&
11398
182
        esStr.empty()) {
11399
182
        auto ellipsoid = Ellipsoid::createSphere(createMapWithUnknownName(),
11400
182
                                                 Length(a), guessBodyName(a));
11401
182
        return createGRF(ellipsoid);
11402
182
    }
11403
11404
13.4k
    if (!bStr.empty() && aStr.empty()) {
11405
3
        throw ParsingException("b found, but a missing");
11406
3
    }
11407
11408
13.4k
    if (!rfStr.empty() && aStr.empty()) {
11409
3
        throw ParsingException("rf found, but a missing");
11410
3
    }
11411
11412
13.4k
    if (!fStr.empty() && aStr.empty()) {
11413
4
        throw ParsingException("f found, but a missing");
11414
4
    }
11415
11416
13.4k
    if (!eStr.empty() && aStr.empty()) {
11417
5
        throw ParsingException("e found, but a missing");
11418
5
    }
11419
11420
13.4k
    if (!esStr.empty() && aStr.empty()) {
11421
4
        throw ParsingException("es found, but a missing");
11422
4
    }
11423
11424
13.3k
    return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6326);
11425
13.4k
}
11426
11427
// ---------------------------------------------------------------------------
11428
11429
static const MeridianPtr nullMeridian{};
11430
11431
static CoordinateSystemAxisNNPtr
11432
createAxis(const std::string &name, const std::string &abbreviation,
11433
           const AxisDirection &direction, const common::UnitOfMeasure &unit,
11434
100k
           const MeridianPtr &meridian = nullMeridian) {
11435
100k
    return CoordinateSystemAxis::create(
11436
100k
        PropertyMap().set(IdentifiedObject::NAME_KEY, name), abbreviation,
11437
100k
        direction, unit, meridian);
11438
100k
}
11439
11440
std::vector<CoordinateSystemAxisNNPtr>
11441
PROJStringParser::Private::processAxisSwap(Step &step,
11442
                                           const UnitOfMeasure &unit,
11443
                                           int iAxisSwap, AxisType axisType,
11444
25.1k
                                           bool ignorePROJAxis) {
11445
25.1k
    assert(iAxisSwap < 0 || ci_equal(steps_[iAxisSwap].name, "axisswap"));
11446
11447
25.1k
    const bool isGeographic = unit.type() == UnitOfMeasure::Type::ANGULAR;
11448
25.1k
    const bool isSpherical = isGeographic && hasParamValue(step, "geoc");
11449
25.1k
    const auto &eastName = isSpherical    ? "Planetocentric longitude"
11450
25.1k
                           : isGeographic ? AxisName::Longitude
11451
24.8k
                                          : AxisName::Easting;
11452
25.1k
    const auto &eastAbbev = isSpherical    ? "V"
11453
25.1k
                            : isGeographic ? AxisAbbreviation::lon
11454
24.8k
                                           : AxisAbbreviation::E;
11455
25.1k
    const auto &eastDir =
11456
25.1k
        isGeographic                         ? AxisDirection::EAST
11457
25.1k
        : (axisType == AxisType::NORTH_POLE) ? AxisDirection::SOUTH
11458
8.36k
        : (axisType == AxisType::SOUTH_POLE) ? AxisDirection::NORTH
11459
8.33k
                                             : AxisDirection::EAST;
11460
25.1k
    CoordinateSystemAxisNNPtr east = createAxis(
11461
25.1k
        eastName, eastAbbev, eastDir, unit,
11462
25.1k
        (!isGeographic &&
11463
8.36k
         (axisType == AxisType::NORTH_POLE || axisType == AxisType::SOUTH_POLE))
11464
25.1k
            ? Meridian::create(Angle(90, UnitOfMeasure::DEGREE)).as_nullable()
11465
25.1k
            : nullMeridian);
11466
11467
25.1k
    const auto &northName = isSpherical    ? "Planetocentric latitude"
11468
25.1k
                            : isGeographic ? AxisName::Latitude
11469
24.8k
                                           : AxisName::Northing;
11470
25.1k
    const auto &northAbbev = isSpherical    ? "U"
11471
25.1k
                             : isGeographic ? AxisAbbreviation::lat
11472
24.8k
                                            : AxisAbbreviation::N;
11473
25.1k
    const auto &northDir = isGeographic ? AxisDirection::NORTH
11474
25.1k
                           : (axisType == AxisType::NORTH_POLE)
11475
8.36k
                               ? AxisDirection::SOUTH
11476
                               /*: (axisType == AxisType::SOUTH_POLE)
11477
                                     ? AxisDirection::NORTH*/
11478
8.36k
                               : AxisDirection::NORTH;
11479
25.1k
    const CoordinateSystemAxisNNPtr north = createAxis(
11480
25.1k
        northName, northAbbev, northDir, unit,
11481
25.1k
        isGeographic ? nullMeridian
11482
25.1k
        : (axisType == AxisType::NORTH_POLE)
11483
8.36k
            ? Meridian::create(Angle(180, UnitOfMeasure::DEGREE)).as_nullable()
11484
8.36k
        : (axisType == AxisType::SOUTH_POLE)
11485
8.33k
            ? Meridian::create(Angle(0, UnitOfMeasure::DEGREE)).as_nullable()
11486
8.33k
            : nullMeridian);
11487
11488
25.1k
    CoordinateSystemAxisNNPtr west =
11489
25.1k
        createAxis(isSpherical    ? "Planetocentric longitude"
11490
25.1k
                   : isGeographic ? AxisName::Longitude
11491
24.8k
                                  : AxisName::Westing,
11492
25.1k
                   isSpherical    ? "V"
11493
25.1k
                   : isGeographic ? AxisAbbreviation::lon
11494
24.8k
                                  : std::string(),
11495
25.1k
                   AxisDirection::WEST, unit);
11496
11497
25.1k
    CoordinateSystemAxisNNPtr south =
11498
25.1k
        createAxis(isSpherical    ? "Planetocentric latitude"
11499
25.1k
                   : isGeographic ? AxisName::Latitude
11500
24.8k
                                  : AxisName::Southing,
11501
25.1k
                   isSpherical    ? "U"
11502
25.1k
                   : isGeographic ? AxisAbbreviation::lat
11503
24.8k
                                  : std::string(),
11504
25.1k
                   AxisDirection::SOUTH, unit);
11505
11506
25.1k
    std::vector<CoordinateSystemAxisNNPtr> axis{east, north};
11507
11508
25.1k
    const auto &axisStr = getParamValue(step, "axis");
11509
25.1k
    if (!ignorePROJAxis && !axisStr.empty()) {
11510
389
        if (axisStr.size() == 3) {
11511
1.14k
            for (int i = 0; i < 2; i++) {
11512
777
                if (axisStr[i] == 'n') {
11513
183
                    axis[i] = north;
11514
594
                } else if (axisStr[i] == 's') {
11515
193
                    axis[i] = south;
11516
401
                } else if (axisStr[i] == 'e') {
11517
159
                    axis[i] = east;
11518
242
                } else if (axisStr[i] == 'w') {
11519
220
                    axis[i] = west;
11520
220
                } else {
11521
22
                    throw ParsingException("Unhandled axis=" + axisStr);
11522
22
                }
11523
777
            }
11524
389
        } else {
11525
0
            throw ParsingException("Unhandled axis=" + axisStr);
11526
0
        }
11527
24.7k
    } else if (iAxisSwap >= 0) {
11528
76
        auto &stepAxisSwap = steps_[iAxisSwap];
11529
76
        const auto &orderStr = getParamValue(stepAxisSwap, "order");
11530
76
        auto orderTab = split(orderStr, ',');
11531
76
        if (orderTab.size() != 2) {
11532
18
            throw ParsingException("Unhandled order=" + orderStr);
11533
18
        }
11534
58
        if (stepAxisSwap.inverted) {
11535
0
            throw ParsingException("Unhandled +inv for +proj=axisswap");
11536
0
        }
11537
11538
153
        for (size_t i = 0; i < 2; i++) {
11539
113
            if (orderTab[i] == "1") {
11540
8
                axis[i] = east;
11541
105
            } else if (orderTab[i] == "-1") {
11542
42
                axis[i] = west;
11543
63
            } else if (orderTab[i] == "2") {
11544
8
                axis[i] = north;
11545
55
            } else if (orderTab[i] == "-2") {
11546
37
                axis[i] = south;
11547
37
            } else {
11548
18
                throw ParsingException("Unhandled order=" + orderStr);
11549
18
            }
11550
113
        }
11551
24.6k
    } else if ((step.name == "krovak" || step.name == "mod_krovak") &&
11552
1.84k
               hasParamValue(step, "czech")) {
11553
94
        axis[0] = std::move(west);
11554
94
        axis[1] = std::move(south);
11555
94
    }
11556
25.0k
    return axis;
11557
25.1k
}
11558
11559
// ---------------------------------------------------------------------------
11560
11561
EllipsoidalCSNNPtr PROJStringParser::Private::buildEllipsoidalCS(
11562
16.5k
    int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) {
11563
16.5k
    auto &step = steps_[iStep];
11564
16.5k
    assert(iUnitConvert < 0 ||
11565
16.5k
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11566
11567
16.5k
    UnitOfMeasure angularUnit = UnitOfMeasure::DEGREE;
11568
16.5k
    if (iUnitConvert >= 0) {
11569
54
        auto &stepUnitConvert = steps_[iUnitConvert];
11570
54
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
11571
54
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
11572
54
        if (stepUnitConvert.inverted) {
11573
0
            std::swap(xy_in, xy_out);
11574
0
        }
11575
54
        if (iUnitConvert < iStep) {
11576
37
            std::swap(xy_in, xy_out);
11577
37
        }
11578
54
        if (xy_in->empty() || xy_out->empty() || *xy_in != "rad" ||
11579
44
            (*xy_out != "rad" && *xy_out != "deg" && *xy_out != "grad")) {
11580
44
            throw ParsingException("unhandled values for xy_in and/or xy_out");
11581
44
        }
11582
10
        if (*xy_out == "rad") {
11583
8
            angularUnit = UnitOfMeasure::RADIAN;
11584
8
        } else if (*xy_out == "grad") {
11585
2
            angularUnit = UnitOfMeasure::GRAD;
11586
2
        }
11587
10
    }
11588
11589
16.5k
    std::vector<CoordinateSystemAxisNNPtr> axis = processAxisSwap(
11590
16.5k
        step, angularUnit, iAxisSwap, AxisType::REGULAR, ignorePROJAxis);
11591
16.5k
    CoordinateSystemAxisNNPtr up = CoordinateSystemAxis::create(
11592
16.5k
        util::PropertyMap().set(IdentifiedObject::NAME_KEY,
11593
16.5k
                                AxisName::Ellipsoidal_height),
11594
16.5k
        AxisAbbreviation::h, AxisDirection::UP,
11595
16.5k
        buildUnit(step, "vunits", "vto_meter"));
11596
11597
16.5k
    return (!hasParamValue(step, "geoidgrids") &&
11598
9.91k
            (hasParamValue(step, "vunits") || hasParamValue(step, "vto_meter")))
11599
16.5k
               ? EllipsoidalCS::create(emptyPropertyMap, axis[0], axis[1], up)
11600
16.5k
               : EllipsoidalCS::create(emptyPropertyMap, axis[0], axis[1]);
11601
16.5k
}
11602
11603
// ---------------------------------------------------------------------------
11604
11605
SphericalCSNNPtr PROJStringParser::Private::buildSphericalCS(
11606
236
    int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) {
11607
236
    auto &step = steps_[iStep];
11608
236
    assert(iUnitConvert < 0 ||
11609
236
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11610
11611
236
    UnitOfMeasure angularUnit = UnitOfMeasure::DEGREE;
11612
236
    if (iUnitConvert >= 0) {
11613
24
        auto &stepUnitConvert = steps_[iUnitConvert];
11614
24
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
11615
24
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
11616
24
        if (stepUnitConvert.inverted) {
11617
0
            std::swap(xy_in, xy_out);
11618
0
        }
11619
24
        if (iUnitConvert < iStep) {
11620
21
            std::swap(xy_in, xy_out);
11621
21
        }
11622
24
        if (xy_in->empty() || xy_out->empty() || *xy_in != "rad" ||
11623
21
            (*xy_out != "rad" && *xy_out != "deg" && *xy_out != "grad")) {
11624
21
            throw ParsingException("unhandled values for xy_in and/or xy_out");
11625
21
        }
11626
3
        if (*xy_out == "rad") {
11627
0
            angularUnit = UnitOfMeasure::RADIAN;
11628
3
        } else if (*xy_out == "grad") {
11629
3
            angularUnit = UnitOfMeasure::GRAD;
11630
3
        }
11631
3
    }
11632
11633
215
    std::vector<CoordinateSystemAxisNNPtr> axis = processAxisSwap(
11634
215
        step, angularUnit, iAxisSwap, AxisType::REGULAR, ignorePROJAxis);
11635
11636
215
    return SphericalCS::create(emptyPropertyMap, axis[0], axis[1]);
11637
236
}
11638
11639
// ---------------------------------------------------------------------------
11640
11641
static double getNumericValue(const std::string &paramValue,
11642
4.23k
                              bool *pHasError = nullptr) {
11643
4.23k
    bool success;
11644
4.23k
    double value = c_locale_stod(paramValue, success);
11645
4.23k
    if (pHasError)
11646
415
        *pHasError = !success;
11647
4.23k
    return value;
11648
4.23k
}
11649
11650
// ---------------------------------------------------------------------------
11651
namespace {
11652
15.3k
template <class T> inline void ignoreRetVal(T) {}
11653
} // namespace
11654
11655
GeodeticCRSNNPtr PROJStringParser::Private::buildGeodeticCRS(
11656
15.3k
    int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) {
11657
15.3k
    auto &step = steps_[iStep];
11658
11659
15.3k
    const bool l_isGeographicStep = isGeographicStep(step.name);
11660
15.3k
    const auto &title = l_isGeographicStep ? title_ : emptyString;
11661
11662
    // units=m is often found in the wild.
11663
    // No need to create a extension string for this
11664
15.3k
    ignoreRetVal(hasParamValue(step, "units"));
11665
11666
15.3k
    auto datum = buildDatum(step, title);
11667
11668
15.3k
    auto props = PropertyMap().set(IdentifiedObject::NAME_KEY,
11669
15.3k
                                   title.empty() ? "unknown" : title);
11670
11671
15.3k
    if (l_isGeographicStep &&
11672
6.99k
        (hasUnusedParameters(step) ||
11673
4.83k
         getNumericValue(getParamValue(step, "lon_0")) != 0.0)) {
11674
4.83k
        props.set("EXTENSION_PROJ4", projString_);
11675
4.83k
    }
11676
15.3k
    props.set("IMPLICIT_CS", true);
11677
11678
15.3k
    if (!hasParamValue(step, "geoc")) {
11679
15.0k
        auto cs =
11680
15.0k
            buildEllipsoidalCS(iStep, iUnitConvert, iAxisSwap, ignorePROJAxis);
11681
11682
15.0k
        return GeographicCRS::create(props, datum, cs);
11683
15.0k
    } else {
11684
369
        auto cs =
11685
369
            buildSphericalCS(iStep, iUnitConvert, iAxisSwap, ignorePROJAxis);
11686
11687
369
        return GeodeticCRS::create(props, datum, cs);
11688
369
    }
11689
15.3k
}
11690
11691
// ---------------------------------------------------------------------------
11692
11693
GeodeticCRSNNPtr
11694
2.40k
PROJStringParser::Private::buildGeocentricCRS(int iStep, int iUnitConvert) {
11695
2.40k
    auto &step = steps_[iStep];
11696
11697
2.40k
    assert(isGeocentricStep(step.name) || isTopocentricStep(step.name));
11698
2.40k
    assert(iUnitConvert < 0 ||
11699
2.40k
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11700
11701
2.40k
    const auto &title = title_;
11702
11703
2.40k
    auto datum = buildDatum(step, title);
11704
11705
2.40k
    UnitOfMeasure unit = buildUnit(step, "units", "");
11706
2.40k
    if (iUnitConvert >= 0) {
11707
29
        auto &stepUnitConvert = steps_[iUnitConvert];
11708
29
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
11709
29
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
11710
29
        const std::string *z_in = &getParamValue(stepUnitConvert, "z_in");
11711
29
        const std::string *z_out = &getParamValue(stepUnitConvert, "z_out");
11712
29
        if (stepUnitConvert.inverted) {
11713
0
            std::swap(xy_in, xy_out);
11714
0
            std::swap(z_in, z_out);
11715
0
        }
11716
29
        if (xy_in->empty() || xy_out->empty() || *xy_in != "m" ||
11717
29
            *z_in != "m" || *xy_out != *z_out) {
11718
29
            throw ParsingException(
11719
29
                "unhandled values for xy_in, z_in, xy_out or z_out");
11720
29
        }
11721
11722
0
        const LinearUnitDesc *unitsMatch = nullptr;
11723
0
        try {
11724
0
            double to_meter_value = c_locale_stod(*xy_out);
11725
0
            unitsMatch = getLinearUnits(to_meter_value);
11726
0
            if (unitsMatch == nullptr) {
11727
0
                unit = _buildUnit(to_meter_value);
11728
0
            }
11729
0
        } catch (const std::invalid_argument &) {
11730
0
            unitsMatch = getLinearUnits(*xy_out);
11731
0
            if (!unitsMatch) {
11732
0
                throw ParsingException(
11733
0
                    "unhandled values for xy_in, z_in, xy_out or z_out");
11734
0
            }
11735
0
            unit = _buildUnit(unitsMatch);
11736
0
        }
11737
0
    }
11738
11739
2.37k
    auto props = PropertyMap().set(IdentifiedObject::NAME_KEY,
11740
2.37k
                                   title.empty() ? "unknown" : title);
11741
2.37k
    auto cs = CartesianCS::createGeocentric(unit);
11742
11743
2.37k
    if (hasUnusedParameters(step)) {
11744
73
        props.set("EXTENSION_PROJ4", projString_);
11745
73
    }
11746
11747
2.37k
    return GeodeticCRS::create(props, datum, cs);
11748
2.40k
}
11749
11750
// ---------------------------------------------------------------------------
11751
11752
CRSNNPtr
11753
PROJStringParser::Private::buildBoundOrCompoundCRSIfNeeded(int iStep,
11754
17.2k
                                                           CRSNNPtr crs) {
11755
17.2k
    auto &step = steps_[iStep];
11756
17.2k
    const auto &nadgrids = getParamValue(step, "nadgrids");
11757
17.2k
    const auto &towgs84 = getParamValue(step, "towgs84");
11758
    // nadgrids has the priority over towgs84
11759
17.2k
    if (!ignoreNadgrids_ && !nadgrids.empty()) {
11760
1.63k
        crs = BoundCRS::createFromNadgrids(crs, nadgrids);
11761
15.6k
    } else if (!towgs84.empty()) {
11762
1.14k
        std::vector<double> towgs84Values;
11763
1.14k
        const auto tokens = split(towgs84, ',');
11764
3.65k
        for (const auto &str : tokens) {
11765
3.65k
            try {
11766
3.65k
                towgs84Values.push_back(c_locale_stod(str));
11767
3.65k
            } catch (const std::invalid_argument &) {
11768
118
                throw ParsingException("Non numerical value in towgs84 clause");
11769
118
            }
11770
3.65k
        }
11771
11772
1.02k
        if (towgs84Values.size() == 7 && dbContext_) {
11773
2
            if (dbContext_->toWGS84AutocorrectWrongValues(
11774
2
                    towgs84Values[0], towgs84Values[1], towgs84Values[2],
11775
2
                    towgs84Values[3], towgs84Values[4], towgs84Values[5],
11776
2
                    towgs84Values[6])) {
11777
0
                for (auto &pair : step.paramValues) {
11778
0
                    if (ci_equal(pair.key, "towgs84")) {
11779
0
                        pair.value.clear();
11780
0
                        for (int i = 0; i < 7; ++i) {
11781
0
                            if (i > 0)
11782
0
                                pair.value += ',';
11783
0
                            pair.value += internal::toString(towgs84Values[i]);
11784
0
                        }
11785
0
                        break;
11786
0
                    }
11787
0
                }
11788
0
            }
11789
2
        }
11790
11791
1.02k
        crs = BoundCRS::createFromTOWGS84(crs, towgs84Values);
11792
1.02k
    }
11793
11794
17.1k
    const auto &geoidgrids = getParamValue(step, "geoidgrids");
11795
17.1k
    if (!geoidgrids.empty()) {
11796
6.33k
        auto vdatum = VerticalReferenceFrame::create(
11797
6.33k
            PropertyMap().set(common::IdentifiedObject::NAME_KEY,
11798
6.33k
                              "unknown using geoidgrids=" + geoidgrids));
11799
11800
6.33k
        const UnitOfMeasure unit = buildUnit(step, "vunits", "vto_meter");
11801
11802
6.33k
        auto vcrs =
11803
6.33k
            VerticalCRS::create(createMapWithUnknownName(), vdatum,
11804
6.33k
                                VerticalCS::createGravityRelatedHeight(unit));
11805
11806
6.33k
        CRSNNPtr geogCRS = GeographicCRS::EPSG_4979; // default
11807
6.33k
        const auto &geoid_crs = getParamValue(step, "geoid_crs");
11808
6.33k
        if (!geoid_crs.empty()) {
11809
1.97k
            if (geoid_crs == "WGS84") {
11810
                // nothing to do
11811
1.97k
            } else if (geoid_crs == "horizontal_crs") {
11812
1.93k
                auto geogCRSOfCompoundCRS = crs->extractGeographicCRS();
11813
1.93k
                if (geogCRSOfCompoundCRS &&
11814
1.93k
                    geogCRSOfCompoundCRS->primeMeridian()
11815
1.93k
                            ->longitude()
11816
1.93k
                            .getSIValue() == 0 &&
11817
1.87k
                    geogCRSOfCompoundCRS->coordinateSystem()
11818
1.87k
                            ->axisList()[0]
11819
1.87k
                            ->unit() == UnitOfMeasure::DEGREE) {
11820
1.87k
                    geogCRS = geogCRSOfCompoundCRS->promoteTo3D(std::string(),
11821
1.87k
                                                                nullptr);
11822
1.87k
                } else if (geogCRSOfCompoundCRS) {
11823
60
                    auto geogCRSOfCompoundCRSDatum =
11824
60
                        geogCRSOfCompoundCRS->datumNonNull(nullptr);
11825
60
                    geogCRS = GeographicCRS::create(
11826
60
                        createMapWithUnknownName(),
11827
60
                        datum::GeodeticReferenceFrame::create(
11828
60
                            util::PropertyMap().set(
11829
60
                                common::IdentifiedObject::NAME_KEY,
11830
60
                                geogCRSOfCompoundCRSDatum->nameStr() +
11831
60
                                    " (with Greenwich prime meridian)"),
11832
60
                            geogCRSOfCompoundCRSDatum->ellipsoid(),
11833
60
                            util::optional<std::string>(),
11834
60
                            datum::PrimeMeridian::GREENWICH),
11835
60
                        EllipsoidalCS::createLongitudeLatitudeEllipsoidalHeight(
11836
60
                            UnitOfMeasure::DEGREE, UnitOfMeasure::METRE));
11837
60
                }
11838
1.93k
            } else {
11839
39
                throw ParsingException("Unsupported value for geoid_crs: "
11840
39
                                       "should be 'WGS84' or 'horizontal_crs'");
11841
39
            }
11842
1.97k
        }
11843
6.29k
        auto transformation =
11844
6.29k
            Transformation::createGravityRelatedHeightToGeographic3D(
11845
6.29k
                PropertyMap().set(IdentifiedObject::NAME_KEY,
11846
6.29k
                                  "unknown to " + geogCRS->nameStr() +
11847
6.29k
                                      " ellipsoidal height"),
11848
6.29k
                VerticalCRS::create(createMapWithUnknownName(), vdatum,
11849
6.29k
                                    VerticalCS::createGravityRelatedHeight(
11850
6.29k
                                        common::UnitOfMeasure::METRE)),
11851
6.29k
                geogCRS, nullptr, geoidgrids,
11852
6.29k
                std::vector<PositionalAccuracyNNPtr>());
11853
6.29k
        auto boundvcrs = BoundCRS::create(vcrs, geogCRS, transformation);
11854
11855
6.29k
        crs = CompoundCRS::create(createMapWithUnknownName(),
11856
6.29k
                                  std::vector<CRSNNPtr>{crs, boundvcrs});
11857
6.29k
    }
11858
11859
17.0k
    return crs;
11860
17.1k
}
11861
11862
// ---------------------------------------------------------------------------
11863
11864
static double getAngularValue(const std::string &paramValue,
11865
2.97k
                              bool *pHasError = nullptr) {
11866
2.97k
    char *endptr = nullptr;
11867
2.97k
    double value = dmstor(paramValue.c_str(), &endptr) * RAD_TO_DEG;
11868
2.97k
    if (value == HUGE_VAL || endptr != paramValue.c_str() + paramValue.size()) {
11869
191
        if (pHasError)
11870
157
            *pHasError = true;
11871
191
        return 0.0;
11872
191
    }
11873
2.78k
    if (pHasError)
11874
2.64k
        *pHasError = false;
11875
2.78k
    return value;
11876
2.97k
}
11877
11878
// ---------------------------------------------------------------------------
11879
11880
29.7k
static bool is_in_stringlist(const std::string &str, const char *stringlist) {
11881
29.7k
    if (str.empty())
11882
757
        return false;
11883
29.0k
    const char *haystack = stringlist;
11884
303k
    while (true) {
11885
303k
        const char *res = strstr(haystack, str.c_str());
11886
303k
        if (res == nullptr)
11887
25.3k
            return false;
11888
278k
        if ((res == stringlist || res[-1] == ',') &&
11889
98.1k
            (res[str.size()] == ',' || res[str.size()] == '\0'))
11890
3.67k
            return true;
11891
274k
        haystack += str.size();
11892
274k
    }
11893
29.0k
}
11894
11895
// ---------------------------------------------------------------------------
11896
11897
CRSNNPtr
11898
PROJStringParser::Private::buildProjectedCRS(int iStep,
11899
                                             const GeodeticCRSNNPtr &geodCRS,
11900
10.1k
                                             int iUnitConvert, int iAxisSwap) {
11901
10.1k
    auto &step = steps_[iStep];
11902
10.1k
    const auto mappings = getMappingsFromPROJName(step.name);
11903
10.1k
    const MethodMapping *mapping = mappings.empty() ? nullptr : mappings[0];
11904
11905
10.1k
    bool foundStrictlyMatchingMapping = false;
11906
10.1k
    if (mappings.size() >= 2) {
11907
        // To distinguish for example +ortho from +ortho +f=0
11908
2.40k
        bool allMappingsHaveAuxParam = true;
11909
5.96k
        for (const auto *mappingIter : mappings) {
11910
5.96k
            if (mappingIter->proj_name_aux == nullptr) {
11911
3.85k
                allMappingsHaveAuxParam = false;
11912
3.85k
            }
11913
5.96k
            if (mappingIter->proj_name_aux != nullptr &&
11914
2.11k
                strchr(mappingIter->proj_name_aux, '=') == nullptr &&
11915
625
                hasParamValue(step, mappingIter->proj_name_aux)) {
11916
31
                foundStrictlyMatchingMapping = true;
11917
31
                mapping = mappingIter;
11918
31
                break;
11919
5.93k
            } else if (mappingIter->proj_name_aux != nullptr &&
11920
2.07k
                       strchr(mappingIter->proj_name_aux, '=') != nullptr) {
11921
1.48k
                const auto tokens = split(mappingIter->proj_name_aux, '=');
11922
1.48k
                if (tokens.size() == 2 &&
11923
1.48k
                    getParamValue(step, tokens[0]) == tokens[1]) {
11924
55
                    foundStrictlyMatchingMapping = true;
11925
55
                    mapping = mappingIter;
11926
55
                    break;
11927
55
                }
11928
1.48k
            }
11929
5.96k
        }
11930
2.40k
        if (allMappingsHaveAuxParam && !foundStrictlyMatchingMapping) {
11931
52
            mapping = nullptr;
11932
52
        }
11933
2.40k
    }
11934
11935
10.1k
    if (mapping && !foundStrictlyMatchingMapping) {
11936
4.06k
        mapping = selectSphericalOrEllipsoidal(mapping, geodCRS);
11937
4.06k
    }
11938
11939
10.1k
    assert(isProjectedStep(step.name));
11940
10.1k
    assert(iUnitConvert < 0 ||
11941
10.1k
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11942
11943
10.1k
    const auto &title = title_;
11944
11945
10.1k
    if (!buildPrimeMeridian(step)->longitude()._isEquivalentTo(
11946
10.1k
            geodCRS->primeMeridian()->longitude(),
11947
10.1k
            util::IComparable::Criterion::EQUIVALENT)) {
11948
3
        throw ParsingException("inconsistent pm values between projectedCRS "
11949
3
                               "and its base geographicalCRS");
11950
3
    }
11951
11952
10.1k
    auto axisType = AxisType::REGULAR;
11953
10.1k
    bool bWebMercator = false;
11954
10.1k
    std::string webMercatorName("WGS 84 / Pseudo-Mercator");
11955
11956
10.1k
    if (step.name == "tmerc" &&
11957
345
        ((getParamValue(step, "axis") == "wsu" && iAxisSwap < 0) ||
11958
334
         (iAxisSwap > 0 &&
11959
71
          getParamValue(steps_[iAxisSwap], "order") == "-1,-2"))) {
11960
24
        mapping =
11961
24
            getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED);
11962
10.1k
    } else if (step.name == "etmerc") {
11963
4
        mapping = getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR);
11964
10.1k
    } else if (step.name == "lcc") {
11965
82
        const auto &lat_0 = getParamValue(step, "lat_0");
11966
82
        const auto &lat_1 = getParamValue(step, "lat_1");
11967
82
        const auto &lat_2 = getParamValue(step, "lat_2");
11968
82
        const auto &k = getParamValueK(step);
11969
82
        if (lat_2.empty() && !lat_0.empty() && !lat_1.empty()) {
11970
7
            if (lat_0 == lat_1 ||
11971
                // For some reason with gcc 5.3.1-14ubuntu2 32bit, the following
11972
                // comparison returns false even if lat_0 == lat_1. Smells like
11973
                // a compiler bug
11974
7
                getAngularValue(lat_0) == getAngularValue(lat_1)) {
11975
2
                mapping =
11976
2
                    getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP);
11977
5
            } else {
11978
5
                mapping = getMapping(
11979
5
                    EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B);
11980
5
            }
11981
75
        } else if (!k.empty() && getNumericValue(k) != 1.0) {
11982
4
            mapping = getMapping(
11983
4
                EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN);
11984
71
        } else {
11985
71
            mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP);
11986
71
        }
11987
10.0k
    } else if (step.name == "aeqd" && hasParamValue(step, "guam")) {
11988
7
        mapping = getMapping(EPSG_CODE_METHOD_GUAM_PROJECTION);
11989
10.0k
    } else if (step.name == "geos" && getParamValue(step, "sweep") == "x") {
11990
16
        mapping =
11991
16
            getMapping(PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X);
11992
10.0k
    } else if (step.name == "geos") {
11993
8
        mapping =
11994
8
            getMapping(PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y);
11995
10.0k
    } else if (step.name == "omerc") {
11996
59
        if (hasParamValue(step, "no_rot")) {
11997
0
            mapping = nullptr;
11998
59
        } else if (hasParamValue(step, "no_uoff") ||
11999
59
                   hasParamValue(step, "no_off")) {
12000
5
            mapping =
12001
5
                getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A);
12002
54
        } else if (hasParamValue(step, "lat_1") &&
12003
46
                   hasParamValue(step, "lon_1") &&
12004
16
                   hasParamValue(step, "lat_2") &&
12005
5
                   hasParamValue(step, "lon_2")) {
12006
0
            mapping = getMapping(
12007
0
                PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN);
12008
54
        } else {
12009
54
            mapping =
12010
54
                getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B);
12011
54
        }
12012
9.98k
    } else if (step.name == "somerc") {
12013
34
        mapping =
12014
34
            getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B);
12015
34
        if (!hasParamValue(step, "alpha") && !hasParamValue(step, "gamma") &&
12016
19
            !hasParamValue(step, "lonc")) {
12017
19
            step.paramValues.emplace_back(Step::KeyValue("alpha", "90"));
12018
19
            step.paramValues.emplace_back(Step::KeyValue("gamma", "90"));
12019
19
            step.paramValues.emplace_back(
12020
19
                Step::KeyValue("lonc", getParamValue(step, "lon_0")));
12021
19
        }
12022
9.94k
    } else if (step.name == "krovak" &&
12023
822
               ((iAxisSwap < 0 && getParamValue(step, "axis") == "swu" &&
12024
12
                 !hasParamValue(step, "czech")) ||
12025
810
                (iAxisSwap > 0 &&
12026
0
                 getParamValue(steps_[iAxisSwap], "order") == "-2,-1" &&
12027
12
                 !hasParamValue(step, "czech")))) {
12028
12
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK);
12029
9.93k
    } else if (step.name == "krovak" && iAxisSwap < 0 &&
12030
810
               hasParamValue(step, "czech") && !hasParamValue(step, "axis")) {
12031
6
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK);
12032
9.93k
    } else if (step.name == "mod_krovak" &&
12033
123
               ((iAxisSwap < 0 && getParamValue(step, "axis") == "swu" &&
12034
0
                 !hasParamValue(step, "czech")) ||
12035
123
                (iAxisSwap > 0 &&
12036
0
                 getParamValue(steps_[iAxisSwap], "order") == "-2,-1" &&
12037
0
                 !hasParamValue(step, "czech")))) {
12038
0
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK_MODIFIED);
12039
9.93k
    } else if (step.name == "mod_krovak" && iAxisSwap < 0 &&
12040
123
               hasParamValue(step, "czech") && !hasParamValue(step, "axis")) {
12041
40
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK_MODIFIED);
12042
9.89k
    } else if (step.name == "merc") {
12043
162
        if (hasParamValue(step, "a") && hasParamValue(step, "b") &&
12044
4
            getParamValue(step, "a") == getParamValue(step, "b") &&
12045
2
            (!hasParamValue(step, "lat_ts") ||
12046
0
             getAngularValue(getParamValue(step, "lat_ts")) == 0.0) &&
12047
2
            getNumericValue(getParamValueK(step)) == 1.0 &&
12048
0
            getParamValue(step, "nadgrids") == "@null") {
12049
0
            mapping = getMapping(
12050
0
                EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR);
12051
0
            for (size_t i = 0; i < step.paramValues.size(); ++i) {
12052
0
                if (ci_equal(step.paramValues[i].key, "nadgrids")) {
12053
0
                    ignoreNadgrids_ = true;
12054
0
                    break;
12055
0
                }
12056
0
            }
12057
0
            if (getNumericValue(getParamValue(step, "a")) == 6378137 &&
12058
0
                getAngularValue(getParamValue(step, "lon_0")) == 0.0 &&
12059
0
                getAngularValue(getParamValue(step, "lat_0")) == 0.0 &&
12060
0
                getAngularValue(getParamValue(step, "x_0")) == 0.0 &&
12061
0
                getAngularValue(getParamValue(step, "y_0")) == 0.0) {
12062
0
                bWebMercator = true;
12063
0
                if (hasParamValue(step, "units") &&
12064
0
                    getParamValue(step, "units") != "m") {
12065
0
                    webMercatorName +=
12066
0
                        " (unit " + getParamValue(step, "units") + ')';
12067
0
                }
12068
0
            }
12069
162
        } else if (hasParamValue(step, "lat_ts")) {
12070
23
            if (hasParamValue(step, "R_C") &&
12071
2
                !geodCRS->ellipsoid()->isSphere() &&
12072
2
                getAngularValue(getParamValue(step, "lat_ts")) != 0) {
12073
0
                throw ParsingException("lat_ts != 0 not supported for "
12074
0
                                       "spherical Mercator on an ellipsoid");
12075
0
            }
12076
23
            mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_B);
12077
139
        } else if (hasParamValue(step, "R_C")) {
12078
15
            const auto &k = getParamValueK(step);
12079
15
            if (!k.empty() && getNumericValue(k) != 1.0) {
12080
3
                if (geodCRS->ellipsoid()->isSphere()) {
12081
0
                    mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_A);
12082
3
                } else {
12083
3
                    throw ParsingException(
12084
3
                        "k_0 != 1 not supported for spherical Mercator on an "
12085
3
                        "ellipsoid");
12086
3
                }
12087
12
            } else {
12088
12
                mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_SPHERICAL);
12089
12
            }
12090
124
        } else {
12091
124
            mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_A);
12092
124
        }
12093
9.72k
    } else if (step.name == "stere") {
12094
230
        if (hasParamValue(step, "lat_0") &&
12095
64
            std::fabs(std::fabs(getAngularValue(getParamValue(step, "lat_0"))) -
12096
64
                      90.0) < 1e-10) {
12097
47
            const double lat_0 = getAngularValue(getParamValue(step, "lat_0"));
12098
47
            if (lat_0 > 0) {
12099
45
                axisType = AxisType::NORTH_POLE;
12100
45
            } else {
12101
2
                axisType = AxisType::SOUTH_POLE;
12102
2
            }
12103
47
            const auto &lat_ts = getParamValue(step, "lat_ts");
12104
47
            const auto &k = getParamValueK(step);
12105
47
            if (!lat_ts.empty() &&
12106
30
                std::fabs(getAngularValue(lat_ts) - lat_0) > 1e-10 &&
12107
26
                !k.empty() && std::fabs(getNumericValue(k) - 1) > 1e-10) {
12108
6
                throw ParsingException("lat_ts != lat_0 and k != 1 not "
12109
6
                                       "supported for Polar Stereographic");
12110
6
            }
12111
41
            if (!lat_ts.empty() &&
12112
24
                (k.empty() || std::fabs(getNumericValue(k) - 1) < 1e-10)) {
12113
20
                mapping =
12114
20
                    getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B);
12115
21
            } else {
12116
21
                mapping =
12117
21
                    getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A);
12118
21
            }
12119
183
        } else {
12120
183
            mapping = getMapping(PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC);
12121
183
        }
12122
9.49k
    } else if (step.name == "laea") {
12123
179
        if (hasParamValue(step, "lat_0") &&
12124
8
            std::fabs(std::fabs(getAngularValue(getParamValue(step, "lat_0"))) -
12125
8
                      90.0) < 1e-10) {
12126
4
            const double lat_0 = getAngularValue(getParamValue(step, "lat_0"));
12127
4
            if (lat_0 > 0) {
12128
4
                axisType = AxisType::NORTH_POLE;
12129
4
            } else {
12130
0
                axisType = AxisType::SOUTH_POLE;
12131
0
            }
12132
4
        }
12133
9.32k
    } else if (step.name == "ortho") {
12134
35
        const std::string &k = getParamValueK(step);
12135
35
        if ((!k.empty() && getNumericValue(k) != 1.0) ||
12136
35
            (hasParamValue(step, "alpha") &&
12137
8
             getNumericValue(getParamValue(step, "alpha")) != 0.0)) {
12138
6
            mapping = getMapping(EPSG_CODE_METHOD_LOCAL_ORTHOGRAPHIC);
12139
6
        }
12140
35
    }
12141
12142
10.1k
    UnitOfMeasure unit = buildUnit(step, "units", "to_meter");
12143
10.1k
    if (iUnitConvert >= 0) {
12144
27
        auto &stepUnitConvert = steps_[iUnitConvert];
12145
27
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
12146
27
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
12147
27
        if (stepUnitConvert.inverted) {
12148
2
            std::swap(xy_in, xy_out);
12149
2
        }
12150
27
        if (xy_in->empty() || xy_out->empty() || *xy_in != "m") {
12151
27
            if (step.name != "ob_tran") {
12152
22
                throw ParsingException(
12153
22
                    "unhandled values for xy_in and/or xy_out");
12154
22
            }
12155
27
        }
12156
12157
5
        const LinearUnitDesc *unitsMatch = nullptr;
12158
5
        try {
12159
5
            double to_meter_value = c_locale_stod(*xy_out);
12160
5
            unitsMatch = getLinearUnits(to_meter_value);
12161
5
            if (unitsMatch == nullptr) {
12162
0
                unit = _buildUnit(to_meter_value);
12163
0
            }
12164
5
        } catch (const std::invalid_argument &) {
12165
5
            unitsMatch = getLinearUnits(*xy_out);
12166
5
            if (!unitsMatch) {
12167
5
                if (step.name != "ob_tran") {
12168
0
                    throw ParsingException(
12169
0
                        "unhandled values for xy_in and/or xy_out");
12170
0
                }
12171
5
            } else {
12172
0
                unit = _buildUnit(unitsMatch);
12173
0
            }
12174
5
        }
12175
5
    }
12176
12177
10.1k
    ConversionPtr conv;
12178
12179
10.1k
    auto mapWithUnknownName = createMapWithUnknownName();
12180
12181
10.1k
    if (step.name == "utm") {
12182
57
        const int zone = std::atoi(getParamValue(step, "zone").c_str());
12183
57
        const bool north = !hasParamValue(step, "south");
12184
57
        conv =
12185
57
            Conversion::createUTM(emptyPropertyMap, zone, north).as_nullable();
12186
10.0k
    } else if (mapping) {
12187
12188
4.16k
        auto methodMap =
12189
4.16k
            PropertyMap().set(IdentifiedObject::NAME_KEY, mapping->wkt2_name);
12190
4.16k
        if (mapping->epsg_code) {
12191
2.21k
            methodMap.set(Identifier::CODESPACE_KEY, Identifier::EPSG)
12192
2.21k
                .set(Identifier::CODE_KEY, mapping->epsg_code);
12193
2.21k
        }
12194
4.16k
        std::vector<OperationParameterNNPtr> parameters;
12195
4.16k
        std::vector<ParameterValueNNPtr> values;
12196
23.8k
        for (int i = 0; mapping->params[i] != nullptr; i++) {
12197
19.8k
            const auto *param = mapping->params[i];
12198
19.8k
            std::string proj_name(param->proj_name ? param->proj_name : "");
12199
19.8k
            const std::string *paramValue =
12200
19.8k
                (proj_name == "k" || proj_name == "k_0") ? &getParamValueK(step)
12201
19.8k
                : !proj_name.empty() ? &getParamValue(step, proj_name)
12202
18.0k
                                     : &emptyString;
12203
19.8k
            double value = 0;
12204
19.8k
            if (!paramValue->empty()) {
12205
390
                bool hasError = false;
12206
390
                if (param->unit_type == UnitOfMeasure::Type::ANGULAR) {
12207
294
                    value = getAngularValue(*paramValue, &hasError);
12208
294
                } else {
12209
96
                    value = getNumericValue(*paramValue, &hasError);
12210
96
                }
12211
390
                if (hasError) {
12212
82
                    throw ParsingException("invalid value for " + proj_name);
12213
82
                }
12214
390
            }
12215
            // For omerc, if gamma is missing, the default value is
12216
            // alpha
12217
19.4k
            else if (step.name == "omerc" && proj_name == "gamma") {
12218
56
                paramValue = &getParamValue(step, "alpha");
12219
56
                if (!paramValue->empty()) {
12220
0
                    value = getAngularValue(*paramValue);
12221
0
                }
12222
19.3k
            } else if (step.name == "krovak" || step.name == "mod_krovak") {
12223
                // Keep it in sync with defaults of krovak.cpp
12224
6.55k
                if (param->epsg_code ==
12225
6.55k
                    EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE) {
12226
941
                    value = 49.5;
12227
5.61k
                } else if (param->epsg_code ==
12228
5.61k
                           EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN) {
12229
934
                    value = 24.833333333333333333;
12230
4.67k
                } else if (param->epsg_code ==
12231
4.67k
                           EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS) {
12232
939
                    value = 30.28813975277777776;
12233
3.73k
                } else if (
12234
3.73k
                    param->epsg_code ==
12235
3.73k
                    EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL) {
12236
939
                    value = 78.5;
12237
2.80k
                } else if (
12238
2.80k
                    param->epsg_code ==
12239
2.80k
                    EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL) {
12240
936
                    value = 0.9999;
12241
936
                }
12242
12.8k
            } else if (step.name == "cea" && proj_name == "lat_ts") {
12243
120
                paramValue = &getParamValueK(step);
12244
120
                if (!paramValue->empty()) {
12245
11
                    bool hasError = false;
12246
11
                    const double k = getNumericValue(*paramValue, &hasError);
12247
11
                    if (hasError) {
12248
3
                        throw ParsingException("invalid value for k/k_0");
12249
3
                    }
12250
8
                    if (k >= 0 && k <= 1) {
12251
5
                        const double es =
12252
5
                            geodCRS->ellipsoid()->squaredEccentricity();
12253
5
                        if (es < 0 || es == 1) {
12254
0
                            throw ParsingException("Invalid flattening");
12255
0
                        }
12256
5
                        value =
12257
5
                            Angle(acos(k * sqrt((1 - es) / (1 - k * k * es))),
12258
5
                                  UnitOfMeasure::RADIAN)
12259
5
                                .convertToUnit(UnitOfMeasure::DEGREE);
12260
5
                    } else {
12261
3
                        throw ParsingException("k/k_0 should be in [0,1]");
12262
3
                    }
12263
8
                }
12264
12.6k
            } else if (param->unit_type == UnitOfMeasure::Type::SCALE) {
12265
792
                value = 1;
12266
11.9k
            } else if (step.name == "peirce_q" && proj_name == "lat_0") {
12267
16
                value = 90;
12268
16
            }
12269
12270
19.7k
            PropertyMap propertiesParameter;
12271
19.7k
            propertiesParameter.set(IdentifiedObject::NAME_KEY,
12272
19.7k
                                    param->wkt2_name);
12273
19.7k
            if (param->epsg_code) {
12274
19.1k
                propertiesParameter.set(Identifier::CODE_KEY, param->epsg_code);
12275
19.1k
                propertiesParameter.set(Identifier::CODESPACE_KEY,
12276
19.1k
                                        Identifier::EPSG);
12277
19.1k
            }
12278
19.7k
            parameters.push_back(
12279
19.7k
                OperationParameter::create(propertiesParameter));
12280
            // In PROJ convention, angular parameters are always in degree
12281
            // and linear parameters always in metre.
12282
19.7k
            double valRounded =
12283
19.7k
                param->unit_type == UnitOfMeasure::Type::LINEAR
12284
19.7k
                    ? Length(value, UnitOfMeasure::METRE).convertToUnit(unit)
12285
19.7k
                    : value;
12286
19.7k
            if (std::fabs(valRounded - std::round(valRounded)) < 1e-8) {
12287
15.0k
                valRounded = std::round(valRounded);
12288
15.0k
            }
12289
19.7k
            values.push_back(ParameterValue::create(
12290
19.7k
                Measure(valRounded,
12291
19.7k
                        param->unit_type == UnitOfMeasure::Type::ANGULAR
12292
19.7k
                            ? UnitOfMeasure::DEGREE
12293
19.7k
                        : param->unit_type == UnitOfMeasure::Type::LINEAR ? unit
12294
9.95k
                        : param->unit_type == UnitOfMeasure::Type::SCALE
12295
1.75k
                            ? UnitOfMeasure::SCALE_UNITY
12296
1.75k
                            : UnitOfMeasure::NONE)));
12297
19.7k
        }
12298
12299
4.07k
        if (step.name == "tmerc" && hasParamValue(step, "approx")) {
12300
0
            methodMap.set("proj_method", "tmerc approx");
12301
4.07k
        } else if (step.name == "utm" && hasParamValue(step, "approx")) {
12302
0
            methodMap.set("proj_method", "utm approx");
12303
0
        }
12304
12305
4.07k
        conv = Conversion::create(mapWithUnknownName, methodMap, parameters,
12306
4.07k
                                  values)
12307
4.07k
                   .as_nullable();
12308
5.93k
    } else {
12309
5.93k
        std::vector<OperationParameterNNPtr> parameters;
12310
5.93k
        std::vector<ParameterValueNNPtr> values;
12311
5.93k
        std::string methodName = "PROJ " + step.name;
12312
24.2k
        for (const auto &param : step.paramValues) {
12313
24.2k
            if (is_in_stringlist(param.key,
12314
24.2k
                                 "wktext,no_defs,datum,ellps,a,b,R,f,rf,"
12315
24.2k
                                 "towgs84,nadgrids,geoidgrids,"
12316
24.2k
                                 "units,to_meter,vunits,vto_meter,type")) {
12317
3.36k
                continue;
12318
3.36k
            }
12319
20.8k
            if (param.value.empty()) {
12320
10.2k
                methodName += " " + param.key;
12321
10.6k
            } else if (isalpha(param.value[0]) || param.key == "gores") {
12322
                // The value of gores can be a string or a number.
12323
                // See interrupted.cpp for more info.
12324
7.84k
                methodName += " " + param.key + "=" + param.value;
12325
7.84k
            } else {
12326
2.81k
                parameters.push_back(OperationParameter::create(
12327
2.81k
                    PropertyMap().set(IdentifiedObject::NAME_KEY, param.key)));
12328
2.81k
                bool hasError = false;
12329
2.81k
                if (is_in_stringlist(param.key, "x_0,y_0,h,h_0")) {
12330
90
                    double value = getNumericValue(param.value, &hasError);
12331
90
                    values.push_back(ParameterValue::create(
12332
90
                        Measure(value, UnitOfMeasure::METRE)));
12333
2.72k
                } else if (is_in_stringlist(
12334
2.72k
                               param.key,
12335
2.72k
                               "k,k_0,"
12336
2.72k
                               "north_square,south_square," // rhealpix
12337
2.72k
                               "n,m,"                       // sinu
12338
2.72k
                               "q,"                         // urm5
12339
2.72k
                               "path,lsat,"                 // lsat
12340
2.72k
                               "W,M,"                       // hammer
12341
2.72k
                               )) {
12342
218
                    double value = getNumericValue(param.value, &hasError);
12343
218
                    values.push_back(ParameterValue::create(
12344
218
                        Measure(value, UnitOfMeasure::SCALE_UNITY)));
12345
2.50k
                } else {
12346
2.50k
                    double value = getAngularValue(param.value, &hasError);
12347
2.50k
                    values.push_back(ParameterValue::create(
12348
2.50k
                        Measure(value, UnitOfMeasure::DEGREE)));
12349
2.50k
                }
12350
2.81k
                if (hasError) {
12351
118
                    throw ParsingException("invalid value for " + param.key);
12352
118
                }
12353
2.81k
            }
12354
20.8k
        }
12355
5.81k
        conv = Conversion::create(
12356
5.81k
                   mapWithUnknownName,
12357
5.81k
                   PropertyMap().set(IdentifiedObject::NAME_KEY, methodName),
12358
5.81k
                   parameters, values)
12359
5.81k
                   .as_nullable();
12360
12361
5.81k
        for (const char *substr :
12362
5.81k
             {"PROJ ob_tran o_proj=longlat", "PROJ ob_tran o_proj=lonlat",
12363
20.0k
              "PROJ ob_tran o_proj=latlon", "PROJ ob_tran o_proj=latlong"}) {
12364
20.0k
            if (starts_with(methodName, substr)) {
12365
1.55k
                auto geogCRS =
12366
1.55k
                    util::nn_dynamic_pointer_cast<GeographicCRS>(geodCRS);
12367
1.55k
                if (geogCRS) {
12368
1.54k
                    return DerivedGeographicCRS::create(
12369
1.54k
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
12370
1.54k
                                          "unnamed"),
12371
1.54k
                        NN_NO_CHECK(geogCRS), NN_NO_CHECK(conv),
12372
1.54k
                        buildEllipsoidalCS(iStep, iUnitConvert, iAxisSwap,
12373
1.54k
                                           false));
12374
1.54k
                }
12375
1.55k
            }
12376
20.0k
        }
12377
5.81k
    }
12378
12379
8.39k
    std::vector<CoordinateSystemAxisNNPtr> axis =
12380
8.39k
        processAxisSwap(step, unit, iAxisSwap, axisType, false);
12381
12382
8.39k
    auto csGeodCRS = geodCRS->coordinateSystem();
12383
8.39k
    auto cs = csGeodCRS->axisList().size() == 2
12384
8.39k
                  ? CartesianCS::create(emptyPropertyMap, axis[0], axis[1],
12385
7.23k
                                        /* enforceSameUnit = */ false)
12386
8.39k
                  : CartesianCS::create(emptyPropertyMap, axis[0], axis[1],
12387
1.16k
                                        csGeodCRS->axisList()[2],
12388
1.16k
                                        /* enforceSameUnit = */ false);
12389
8.39k
    if (isTopocentricStep(step.name)) {
12390
23
        cs = CartesianCS::create(
12391
23
            emptyPropertyMap,
12392
23
            createAxis("topocentric East", "U", AxisDirection::EAST, unit),
12393
23
            createAxis("topocentric North", "V", AxisDirection::NORTH, unit),
12394
23
            createAxis("topocentric Up", "W", AxisDirection::UP, unit));
12395
23
    }
12396
12397
8.39k
    auto props = PropertyMap().set(IdentifiedObject::NAME_KEY,
12398
8.39k
                                   title.empty() ? "unknown" : title);
12399
8.39k
    if (hasUnusedParameters(step)) {
12400
1.23k
        props.set("EXTENSION_PROJ4", projString_);
12401
1.23k
    }
12402
12403
8.39k
    props.set("IMPLICIT_CS", true);
12404
12405
8.39k
    CRSNNPtr crs =
12406
8.39k
        bWebMercator
12407
8.39k
            ? createPseudoMercator(
12408
0
                  props.set(IdentifiedObject::NAME_KEY, webMercatorName), cs)
12409
8.39k
            : ProjectedCRS::create(props, geodCRS, NN_NO_CHECK(conv), cs);
12410
12411
8.39k
    return crs;
12412
10.1k
}
12413
12414
//! @endcond
12415
12416
// ---------------------------------------------------------------------------
12417
12418
//! @cond Doxygen_Suppress
12419
static const metadata::ExtentPtr nullExtent{};
12420
12421
0
static const metadata::ExtentPtr &getExtent(const crs::CRS *crs) {
12422
0
    const auto &domains = crs->domains();
12423
0
    if (!domains.empty()) {
12424
0
        return domains[0]->domainOfValidity();
12425
0
    }
12426
0
    return nullExtent;
12427
0
}
12428
12429
//! @endcond
12430
12431
namespace {
12432
struct PJContextHolder {
12433
    PJ_CONTEXT *ctx_;
12434
    bool bFree_;
12435
12436
556
    PJContextHolder(PJ_CONTEXT *ctx, bool bFree) : ctx_(ctx), bFree_(bFree) {}
12437
556
    ~PJContextHolder() {
12438
556
        if (bFree_)
12439
4
            proj_context_destroy(ctx_);
12440
556
    }
12441
    PJContextHolder(const PJContextHolder &) = delete;
12442
    PJContextHolder &operator=(const PJContextHolder &) = delete;
12443
};
12444
} // namespace
12445
12446
// ---------------------------------------------------------------------------
12447
12448
/** \brief Instantiate a sub-class of BaseObject from a PROJ string.
12449
 *
12450
 * The projString must contain +type=crs for the object to be detected as a
12451
 * CRS instead of a CoordinateOperation.
12452
 *
12453
 * @throw ParsingException if the string cannot be parsed.
12454
 */
12455
BaseObjectNNPtr
12456
12.9k
PROJStringParser::createFromPROJString(const std::string &projString) {
12457
12458
    // In some abnormal situations involving init=epsg:XXXX syntax, we could
12459
    // have infinite loop
12460
12.9k
    if (d->ctx_ &&
12461
12.8k
        d->ctx_->projStringParserCreateFromPROJStringRecursionCounter == 2) {
12462
0
        throw ParsingException(
12463
0
            "Infinite recursion in PROJStringParser::createFromPROJString()");
12464
0
    }
12465
12466
12.9k
    d->steps_.clear();
12467
12.9k
    d->title_.clear();
12468
12.9k
    d->globalParamValues_.clear();
12469
12.9k
    d->projString_ = projString;
12470
12.9k
    PROJStringSyntaxParser(projString, d->steps_, d->globalParamValues_,
12471
12.9k
                           d->title_);
12472
12473
12.9k
    if (d->steps_.empty()) {
12474
228
        const auto &vunits = d->getGlobalParamValue("vunits");
12475
228
        const auto &vto_meter = d->getGlobalParamValue("vto_meter");
12476
228
        if (!vunits.empty() || !vto_meter.empty()) {
12477
51
            Step fakeStep;
12478
51
            if (!vunits.empty()) {
12479
46
                fakeStep.paramValues.emplace_back(
12480
46
                    Step::KeyValue("vunits", vunits));
12481
46
            }
12482
51
            if (!vto_meter.empty()) {
12483
5
                fakeStep.paramValues.emplace_back(
12484
5
                    Step::KeyValue("vto_meter", vto_meter));
12485
5
            }
12486
51
            auto vdatum =
12487
51
                VerticalReferenceFrame::create(createMapWithUnknownName());
12488
51
            auto vcrs = VerticalCRS::create(
12489
51
                createMapWithUnknownName(), vdatum,
12490
51
                VerticalCS::createGravityRelatedHeight(
12491
51
                    d->buildUnit(fakeStep, "vunits", "vto_meter")));
12492
51
            return vcrs;
12493
51
        }
12494
228
    }
12495
12496
12.9k
    const bool isGeocentricCRS =
12497
12.9k
        ((d->steps_.size() == 1 &&
12498
11.0k
          d->getParamValue(d->steps_[0], "type") == "crs") ||
12499
3.98k
         (d->steps_.size() == 2 && d->steps_[1].name == "unitconvert")) &&
12500
8.98k
        !d->steps_[0].inverted && isGeocentricStep(d->steps_[0].name);
12501
12502
12.9k
    const bool isTopocentricCRS =
12503
12.9k
        (d->steps_.size() == 1 && isTopocentricStep(d->steps_[0].name) &&
12504
39
         d->getParamValue(d->steps_[0], "type") == "crs");
12505
12506
    // +init=xxxx:yyyy syntax
12507
12.9k
    if (d->steps_.size() == 1 && d->steps_[0].isInit &&
12508
573
        !d->steps_[0].inverted) {
12509
12510
556
        auto ctx = d->ctx_ ? d->ctx_ : proj_context_create();
12511
556
        if (!ctx) {
12512
0
            throw ParsingException("out of memory");
12513
0
        }
12514
556
        PJContextHolder contextHolder(ctx, ctx != d->ctx_);
12515
12516
        // Those used to come from a text init file
12517
        // We only support them in compatibility mode
12518
556
        const std::string &stepName = d->steps_[0].name;
12519
556
        if (ci_starts_with(stepName, "epsg:") ||
12520
556
            ci_starts_with(stepName, "IGNF:")) {
12521
12522
5
            struct BackupContextErrno {
12523
5
                PJ_CONTEXT *m_ctxt = nullptr;
12524
5
                int m_last_errno = 0;
12525
12526
5
                explicit BackupContextErrno(PJ_CONTEXT *ctxtIn)
12527
5
                    : m_ctxt(ctxtIn), m_last_errno(m_ctxt->last_errno) {
12528
5
                    m_ctxt->debug_level = PJ_LOG_ERROR;
12529
5
                }
12530
12531
5
                ~BackupContextErrno() { m_ctxt->last_errno = m_last_errno; }
12532
12533
5
                BackupContextErrno(const BackupContextErrno &) = delete;
12534
5
                BackupContextErrno &
12535
5
                operator=(const BackupContextErrno &) = delete;
12536
5
            };
12537
12538
5
            BackupContextErrno backupContextErrno(ctx);
12539
12540
5
            bool usePROJ4InitRules = d->usePROJ4InitRules_;
12541
5
            if (!usePROJ4InitRules) {
12542
5
                usePROJ4InitRules =
12543
5
                    proj_context_get_use_proj4_init_rules(ctx, FALSE) == TRUE;
12544
5
            }
12545
5
            if (!usePROJ4InitRules) {
12546
5
                throw ParsingException("init=epsg:/init=IGNF: syntax not "
12547
5
                                       "supported in non-PROJ4 emulation mode");
12548
5
            }
12549
12550
0
            char unused[256];
12551
0
            std::string initname(stepName);
12552
0
            initname.resize(initname.find(':'));
12553
0
            int file_found =
12554
0
                pj_find_file(ctx, initname.c_str(), unused, sizeof(unused),
12555
0
                             /* disable_network = */ true);
12556
12557
0
            if (!file_found) {
12558
0
                auto obj = createFromUserInput(stepName, d->dbContext_, true);
12559
0
                auto crs = dynamic_cast<CRS *>(obj.get());
12560
12561
0
                bool hasSignificantParamValues = false;
12562
0
                bool hasOver = false;
12563
0
                for (const auto &kv : d->steps_[0].paramValues) {
12564
0
                    if (kv.key == "over") {
12565
0
                        hasOver = true;
12566
0
                    } else if (!((kv.key == "type" && kv.value == "crs") ||
12567
0
                                 kv.key == "wktext" || kv.key == "no_defs")) {
12568
0
                        hasSignificantParamValues = true;
12569
0
                        break;
12570
0
                    }
12571
0
                }
12572
12573
0
                if (crs && !hasSignificantParamValues) {
12574
0
                    PropertyMap properties;
12575
0
                    properties.set(IdentifiedObject::NAME_KEY,
12576
0
                                   d->title_.empty() ? crs->nameStr()
12577
0
                                                     : d->title_);
12578
0
                    if (hasOver) {
12579
0
                        properties.set("OVER", true);
12580
0
                    }
12581
0
                    const auto &extent = getExtent(crs);
12582
0
                    if (extent) {
12583
0
                        properties.set(
12584
0
                            common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY,
12585
0
                            NN_NO_CHECK(extent));
12586
0
                    }
12587
0
                    auto geogCRS = dynamic_cast<GeographicCRS *>(crs);
12588
0
                    if (geogCRS) {
12589
0
                        const auto &cs = geogCRS->coordinateSystem();
12590
                        // Override with longitude latitude in degrees
12591
0
                        return GeographicCRS::create(
12592
0
                            properties, geogCRS->datum(),
12593
0
                            geogCRS->datumEnsemble(),
12594
0
                            cs->axisList().size() == 2
12595
0
                                ? EllipsoidalCS::createLongitudeLatitude(
12596
0
                                      UnitOfMeasure::DEGREE)
12597
0
                                : EllipsoidalCS::
12598
0
                                      createLongitudeLatitudeEllipsoidalHeight(
12599
0
                                          UnitOfMeasure::DEGREE,
12600
0
                                          cs->axisList()[2]->unit()));
12601
0
                    }
12602
0
                    auto projCRS = dynamic_cast<ProjectedCRS *>(crs);
12603
0
                    if (projCRS) {
12604
                        // Override with easting northing order
12605
0
                        const auto conv = projCRS->derivingConversion();
12606
0
                        if (conv->method()->getEPSGCode() !=
12607
0
                            EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED) {
12608
0
                            return ProjectedCRS::create(
12609
0
                                properties, projCRS->baseCRS(), conv,
12610
0
                                CartesianCS::createEastingNorthing(
12611
0
                                    projCRS->coordinateSystem()
12612
0
                                        ->axisList()[0]
12613
0
                                        ->unit()));
12614
0
                        }
12615
0
                    }
12616
0
                    return obj;
12617
0
                }
12618
0
                auto projStringExportable =
12619
0
                    dynamic_cast<IPROJStringExportable *>(crs);
12620
0
                if (projStringExportable) {
12621
0
                    std::string expanded;
12622
0
                    if (!d->title_.empty()) {
12623
0
                        expanded = "title=";
12624
0
                        expanded +=
12625
0
                            pj_double_quote_string_param_if_needed(d->title_);
12626
0
                    }
12627
0
                    for (const auto &pair : d->steps_[0].paramValues) {
12628
0
                        if (!expanded.empty())
12629
0
                            expanded += ' ';
12630
0
                        expanded += '+';
12631
0
                        expanded += pair.key;
12632
0
                        if (!pair.value.empty()) {
12633
0
                            expanded += '=';
12634
0
                            expanded += pj_double_quote_string_param_if_needed(
12635
0
                                pair.value);
12636
0
                        }
12637
0
                    }
12638
0
                    expanded += ' ';
12639
0
                    expanded += projStringExportable->exportToPROJString(
12640
0
                        PROJStringFormatter::create().get());
12641
0
                    return createFromPROJString(expanded);
12642
0
                }
12643
0
            }
12644
0
        }
12645
12646
551
        paralist *init = pj_mkparam(("init=" + d->steps_[0].name).c_str());
12647
551
        if (!init) {
12648
0
            throw ParsingException("out of memory");
12649
0
        }
12650
551
        ctx->projStringParserCreateFromPROJStringRecursionCounter++;
12651
551
        paralist *list = pj_expand_init(ctx, init);
12652
551
        ctx->projStringParserCreateFromPROJStringRecursionCounter--;
12653
551
        if (!list) {
12654
127
            free(init);
12655
127
            throw ParsingException("cannot expand " + projString);
12656
127
        }
12657
424
        std::string expanded;
12658
424
        if (!d->title_.empty()) {
12659
141
            expanded =
12660
141
                "title=" + pj_double_quote_string_param_if_needed(d->title_);
12661
141
        }
12662
424
        bool first = true;
12663
424
        bool has_init_term = false;
12664
3.40k
        for (auto t = list; t;) {
12665
2.97k
            if (!expanded.empty()) {
12666
2.41k
                expanded += ' ';
12667
2.41k
            }
12668
2.97k
            if (first) {
12669
                // first parameter is the init= itself
12670
424
                first = false;
12671
2.55k
            } else if (starts_with(t->param, "init=")) {
12672
0
                has_init_term = true;
12673
2.55k
            } else {
12674
2.55k
                expanded += t->param;
12675
2.55k
            }
12676
12677
2.97k
            auto n = t->next;
12678
2.97k
            free(t);
12679
2.97k
            t = n;
12680
2.97k
        }
12681
7.48k
        for (const auto &pair : d->steps_[0].paramValues) {
12682
7.48k
            expanded += " +";
12683
7.48k
            expanded += pair.key;
12684
7.48k
            if (!pair.value.empty()) {
12685
5.05k
                expanded += '=';
12686
5.05k
                expanded += pj_double_quote_string_param_if_needed(pair.value);
12687
5.05k
            }
12688
7.48k
        }
12689
12690
424
        if (!has_init_term) {
12691
424
            return createFromPROJString(expanded);
12692
424
        }
12693
424
    }
12694
12695
12.3k
    int iFirstGeogStep = -1;
12696
12.3k
    int iSecondGeogStep = -1;
12697
12.3k
    int iProjStep = -1;
12698
12.3k
    int iFirstUnitConvert = -1;
12699
12.3k
    int iSecondUnitConvert = -1;
12700
12.3k
    int iFirstAxisSwap = -1;
12701
12.3k
    int iSecondAxisSwap = -1;
12702
12.3k
    bool unexpectedStructure = d->steps_.empty();
12703
25.3k
    for (int i = 0; i < static_cast<int>(d->steps_.size()); i++) {
12704
13.8k
        const auto &stepName = d->steps_[i].name;
12705
13.8k
        if (isGeographicStep(stepName)) {
12706
3.88k
            if (iFirstGeogStep < 0) {
12707
3.86k
                iFirstGeogStep = i;
12708
3.86k
            } else if (iSecondGeogStep < 0) {
12709
18
                iSecondGeogStep = i;
12710
18
            } else {
12711
2
                unexpectedStructure = true;
12712
2
                break;
12713
2
            }
12714
9.91k
        } else if (ci_equal(stepName, "unitconvert")) {
12715
191
            if (iFirstUnitConvert < 0) {
12716
159
                iFirstUnitConvert = i;
12717
159
            } else if (iSecondUnitConvert < 0) {
12718
31
                iSecondUnitConvert = i;
12719
31
            } else {
12720
1
                unexpectedStructure = true;
12721
1
                break;
12722
1
            }
12723
9.72k
        } else if (ci_equal(stepName, "axisswap")) {
12724
110
            if (iFirstAxisSwap < 0) {
12725
104
                iFirstAxisSwap = i;
12726
104
            } else if (iSecondAxisSwap < 0) {
12727
4
                iSecondAxisSwap = i;
12728
4
            } else {
12729
2
                unexpectedStructure = true;
12730
2
                break;
12731
2
            }
12732
9.61k
        } else if (isProjectedStep(stepName)) {
12733
9.00k
            if (iProjStep >= 0) {
12734
254
                unexpectedStructure = true;
12735
254
                break;
12736
254
            }
12737
8.75k
            iProjStep = i;
12738
8.75k
        } else {
12739
607
            unexpectedStructure = true;
12740
607
            break;
12741
607
        }
12742
13.8k
    }
12743
12744
12.3k
    if (!d->steps_.empty()) {
12745
        // CRS candidate
12746
12.1k
        if ((d->steps_.size() == 1 &&
12747
10.5k
             d->getParamValue(d->steps_[0], "type") != "crs") ||
12748
10.3k
            (d->steps_.size() > 1 && d->getGlobalParamValue("type") != "crs")) {
12749
2.31k
            unexpectedStructure = true;
12750
2.31k
        }
12751
12.1k
    }
12752
12753
12.3k
    struct Logger {
12754
12.3k
        std::string msg{};
12755
12756
        // cppcheck-suppress functionStatic
12757
12.3k
        void setMessage(const char *msgIn) noexcept {
12758
2.25k
            try {
12759
2.25k
                msg = msgIn;
12760
2.25k
            } catch (const std::exception &) {
12761
0
            }
12762
2.25k
        }
12763
12764
12.3k
        static void log(void *user_data, int level, const char *msg) {
12765
2.25k
            if (level == PJ_LOG_ERROR) {
12766
2.25k
                static_cast<Logger *>(user_data)->setMessage(msg);
12767
2.25k
            }
12768
2.25k
        }
12769
12.3k
    };
12770
12771
    // If the structure is not recognized, then try to instantiate the
12772
    // pipeline, and if successful, wrap it in a PROJBasedOperation
12773
12.3k
    Logger logger;
12774
12.3k
    bool valid;
12775
12776
12.3k
    auto pj_context = d->ctx_ ? d->ctx_ : proj_context_create();
12777
12.3k
    if (!pj_context) {
12778
0
        throw ParsingException("out of memory");
12779
0
    }
12780
12781
    // Backup error logger and level, and install temporary handler
12782
12.3k
    auto old_logger = pj_context->logger;
12783
12.3k
    auto old_logger_app_data = pj_context->logger_app_data;
12784
12.3k
    auto log_level = proj_log_level(pj_context, PJ_LOG_ERROR);
12785
12.3k
    proj_log_func(pj_context, &logger, Logger::log);
12786
12787
12.3k
    if (pj_context != d->ctx_) {
12788
142
        proj_context_use_proj4_init_rules(pj_context, d->usePROJ4InitRules_);
12789
142
    }
12790
12.3k
    pj_context->projStringParserCreateFromPROJStringRecursionCounter++;
12791
12.3k
    auto pj = pj_create_internal(
12792
12.3k
        pj_context, (projString.find("type=crs") != std::string::npos
12793
12.3k
                         ? projString + " +disable_grid_presence_check"
12794
12.3k
                         : projString)
12795
12.3k
                        .c_str());
12796
12.3k
    pj_context->projStringParserCreateFromPROJStringRecursionCounter--;
12797
12.3k
    valid = pj != nullptr;
12798
12799
    // Restore initial error logger and level
12800
12.3k
    proj_log_level(pj_context, log_level);
12801
12.3k
    pj_context->logger = old_logger;
12802
12.3k
    pj_context->logger_app_data = old_logger_app_data;
12803
12804
    // Remove parameters not understood by PROJ.
12805
12.3k
    if (valid && d->steps_.size() == 1) {
12806
9.46k
        std::vector<Step::KeyValue> newParamValues{};
12807
9.46k
        std::set<std::string> foundKeys;
12808
9.46k
        auto &step = d->steps_[0];
12809
12810
53.6k
        for (auto &kv : step.paramValues) {
12811
53.6k
            bool recognizedByPROJ = false;
12812
53.6k
            if (foundKeys.find(kv.key) != foundKeys.end()) {
12813
3.72k
                continue;
12814
3.72k
            }
12815
49.9k
            foundKeys.insert(kv.key);
12816
49.9k
            if ((step.name == "krovak" || step.name == "mod_krovak") &&
12817
3.33k
                kv.key == "alpha") {
12818
                // We recognize it in our CRS parsing code
12819
4
                recognizedByPROJ = true;
12820
49.9k
            } else {
12821
392k
                for (auto cur = pj->params; cur; cur = cur->next) {
12822
392k
                    const char *equal = strchr(cur->param, '=');
12823
392k
                    if (equal && static_cast<size_t>(equal - cur->param) ==
12824
202k
                                     kv.key.size()) {
12825
50.2k
                        if (memcmp(cur->param, kv.key.c_str(), kv.key.size()) ==
12826
50.2k
                            0) {
12827
28.5k
                            recognizedByPROJ = (cur->used == 1);
12828
28.5k
                            break;
12829
28.5k
                        }
12830
342k
                    } else if (strcmp(cur->param, kv.key.c_str()) == 0) {
12831
21.3k
                        recognizedByPROJ = (cur->used == 1);
12832
21.3k
                        break;
12833
21.3k
                    }
12834
392k
                }
12835
49.9k
            }
12836
49.9k
            if (!recognizedByPROJ && kv.key == "geoid_crs") {
12837
3.71k
                for (auto &pair : step.paramValues) {
12838
3.71k
                    if (ci_equal(pair.key, "geoidgrids")) {
12839
628
                        recognizedByPROJ = true;
12840
628
                        break;
12841
628
                    }
12842
3.71k
                }
12843
718
            }
12844
49.9k
            if (recognizedByPROJ) {
12845
15.1k
                newParamValues.emplace_back(kv);
12846
15.1k
            }
12847
49.9k
        }
12848
9.46k
        step.paramValues = std::move(newParamValues);
12849
12850
9.46k
        d->projString_.clear();
12851
9.46k
        if (!step.name.empty()) {
12852
9.45k
            d->projString_ += step.isInit ? "+init=" : "+proj=";
12853
9.45k
            d->projString_ += step.name;
12854
9.45k
        }
12855
15.1k
        for (const auto &paramValue : step.paramValues) {
12856
15.1k
            if (!d->projString_.empty()) {
12857
15.1k
                d->projString_ += ' ';
12858
15.1k
            }
12859
15.1k
            d->projString_ += '+';
12860
15.1k
            d->projString_ += paramValue.key;
12861
15.1k
            if (!paramValue.value.empty()) {
12862
12.6k
                d->projString_ += '=';
12863
12.6k
                d->projString_ +=
12864
12.6k
                    pj_double_quote_string_param_if_needed(paramValue.value);
12865
12.6k
            }
12866
15.1k
        }
12867
9.46k
    }
12868
12869
12.3k
    proj_destroy(pj);
12870
12871
12.3k
    if (!valid) {
12872
1.47k
        const int l_errno = proj_context_errno(pj_context);
12873
1.47k
        std::string msg("Error " + toString(l_errno) + " (" +
12874
1.47k
                        proj_errno_string(l_errno) + ")");
12875
1.47k
        if (!logger.msg.empty()) {
12876
1.41k
            msg += ": ";
12877
1.41k
            msg += logger.msg;
12878
1.41k
        }
12879
1.47k
        logger.msg = std::move(msg);
12880
1.47k
    }
12881
12882
12.3k
    if (pj_context != d->ctx_) {
12883
142
        proj_context_destroy(pj_context);
12884
142
    }
12885
12886
12.3k
    if (!valid) {
12887
1.47k
        throw ParsingException(logger.msg);
12888
1.47k
    }
12889
12890
10.8k
    if (isGeocentricCRS) {
12891
        // First run is dry run to mark all recognized/unrecognized tokens
12892
2.45k
        for (int iter = 0; iter < 2; iter++) {
12893
2.37k
            auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12894
2.37k
                0, d->buildGeocentricCRS(0, (d->steps_.size() == 2 &&
12895
29
                                             d->steps_[1].name == "unitconvert")
12896
2.37k
                                                ? 1
12897
2.37k
                                                : -1));
12898
2.37k
            if (iter == 1) {
12899
1.15k
                return nn_static_pointer_cast<BaseObject>(obj);
12900
1.15k
            }
12901
2.37k
        }
12902
1.22k
    }
12903
12904
9.74k
    if (isTopocentricCRS) {
12905
        // First run is dry run to mark all recognized/unrecognized tokens
12906
28
        for (int iter = 0; iter < 2; iter++) {
12907
23
            auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12908
23
                0,
12909
23
                d->buildProjectedCRS(0, d->buildGeocentricCRS(0, -1), -1, -1));
12910
23
            if (iter == 1) {
12911
9
                return nn_static_pointer_cast<BaseObject>(obj);
12912
9
            }
12913
23
        }
12914
14
    }
12915
12916
9.73k
    if (!unexpectedStructure) {
12917
8.10k
        if (iFirstGeogStep == 0 && !d->steps_[iFirstGeogStep].inverted &&
12918
3.60k
            iSecondGeogStep < 0 && iProjStep < 0 &&
12919
2.60k
            (iFirstUnitConvert < 0 || iSecondUnitConvert < 0) &&
12920
2.60k
            (iFirstAxisSwap < 0 || iSecondAxisSwap < 0)) {
12921
            // First run is dry run to mark all recognized/unrecognized tokens
12922
5.20k
            for (int iter = 0; iter < 2; iter++) {
12923
5.08k
                auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12924
5.08k
                    0, d->buildGeodeticCRS(iFirstGeogStep, iFirstUnitConvert,
12925
5.08k
                                           iFirstAxisSwap, false));
12926
5.08k
                if (iter == 1) {
12927
2.48k
                    return nn_static_pointer_cast<BaseObject>(obj);
12928
2.48k
                }
12929
5.08k
            }
12930
2.60k
        }
12931
5.61k
        if (iProjStep >= 0 && !d->steps_[iProjStep].inverted &&
12932
5.44k
            (iFirstGeogStep < 0 || iFirstGeogStep + 1 == iProjStep) &&
12933
5.44k
            iSecondGeogStep < 0) {
12934
5.44k
            if (iFirstGeogStep < 0)
12935
4.44k
                iFirstGeogStep = iProjStep;
12936
            // First run is dry run to mark all recognized/unrecognized tokens
12937
10.8k
            for (int iter = 0; iter < 2; iter++) {
12938
10.3k
                auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12939
10.3k
                    iProjStep,
12940
10.3k
                    d->buildProjectedCRS(
12941
10.3k
                        iProjStep,
12942
10.3k
                        d->buildGeodeticCRS(iFirstGeogStep,
12943
10.3k
                                            iFirstUnitConvert < iFirstGeogStep
12944
10.3k
                                                ? iFirstUnitConvert
12945
10.3k
                                                : -1,
12946
10.3k
                                            iFirstAxisSwap < iFirstGeogStep
12947
10.3k
                                                ? iFirstAxisSwap
12948
10.3k
                                                : -1,
12949
10.3k
                                            true),
12950
10.3k
                        iFirstUnitConvert < iFirstGeogStep ? iSecondUnitConvert
12951
10.3k
                                                           : iFirstUnitConvert,
12952
10.3k
                        iFirstAxisSwap < iFirstGeogStep ? iSecondAxisSwap
12953
10.3k
                                                        : iFirstAxisSwap));
12954
10.3k
                if (iter == 1) {
12955
4.87k
                    return nn_static_pointer_cast<BaseObject>(obj);
12956
4.87k
                }
12957
10.3k
            }
12958
5.44k
        }
12959
5.61k
    }
12960
12961
2.37k
    auto props = PropertyMap();
12962
2.37k
    if (!d->title_.empty()) {
12963
54
        props.set(IdentifiedObject::NAME_KEY, d->title_);
12964
54
    }
12965
2.37k
    return operation::SingleOperation::createPROJBased(props, projString,
12966
2.37k
                                                       nullptr, nullptr, {});
12967
9.73k
}
12968
12969
// ---------------------------------------------------------------------------
12970
12971
//! @cond Doxygen_Suppress
12972
struct JSONFormatter::Private {
12973
    CPLJSonStreamingWriter writer_{nullptr, nullptr};
12974
    DatabaseContextPtr dbContext_{};
12975
12976
    std::vector<bool> stackHasId_{false};
12977
    std::vector<bool> outputIdStack_{true};
12978
    bool allowIDInImmediateChild_ = false;
12979
    bool omitTypeInImmediateChild_ = false;
12980
    bool abridgedTransformation_ = false;
12981
    bool abridgedTransformationWriteSourceCRS_ = false;
12982
    std::string schema_ = PROJJSON_DEFAULT_VERSION;
12983
12984
    // cppcheck-suppress functionStatic
12985
0
    void pushOutputId(bool outputIdIn) { outputIdStack_.push_back(outputIdIn); }
12986
12987
    // cppcheck-suppress functionStatic
12988
0
    void popOutputId() { outputIdStack_.pop_back(); }
12989
};
12990
//! @endcond
12991
12992
// ---------------------------------------------------------------------------
12993
12994
/** \brief Constructs a new formatter.
12995
 *
12996
 * A formatter can be used only once (its internal state is mutated)
12997
 *
12998
 * @return new formatter.
12999
 */
13000
JSONFormatterNNPtr JSONFormatter::create( // cppcheck-suppress passedByValue
13001
0
    DatabaseContextPtr dbContext) {
13002
0
    auto ret = NN_NO_CHECK(JSONFormatter::make_unique<JSONFormatter>());
13003
0
    ret->d->dbContext_ = std::move(dbContext);
13004
0
    return ret;
13005
0
}
13006
13007
// ---------------------------------------------------------------------------
13008
13009
/** \brief Whether to use multi line output or not. */
13010
0
JSONFormatter &JSONFormatter::setMultiLine(bool multiLine) noexcept {
13011
0
    d->writer_.SetPrettyFormatting(multiLine);
13012
0
    return *this;
13013
0
}
13014
13015
// ---------------------------------------------------------------------------
13016
13017
/** \brief Set number of spaces for each indentation level (defaults to 4).
13018
 */
13019
0
JSONFormatter &JSONFormatter::setIndentationWidth(int width) noexcept {
13020
0
    d->writer_.SetIndentationSize(width);
13021
0
    return *this;
13022
0
}
13023
13024
// ---------------------------------------------------------------------------
13025
13026
/** \brief Set the value of the "$schema" key in the top level object.
13027
 *
13028
 * If set to empty string, it will not be written.
13029
 */
13030
0
JSONFormatter &JSONFormatter::setSchema(const std::string &schema) noexcept {
13031
0
    d->schema_ = schema;
13032
0
    return *this;
13033
0
}
13034
13035
// ---------------------------------------------------------------------------
13036
13037
//! @cond Doxygen_Suppress
13038
13039
0
JSONFormatter::JSONFormatter() : d(std::make_unique<Private>()) {}
13040
13041
// ---------------------------------------------------------------------------
13042
13043
0
JSONFormatter::~JSONFormatter() = default;
13044
13045
// ---------------------------------------------------------------------------
13046
13047
0
CPLJSonStreamingWriter *JSONFormatter::writer() const { return &(d->writer_); }
13048
13049
// ---------------------------------------------------------------------------
13050
13051
0
const DatabaseContextPtr &JSONFormatter::databaseContext() const {
13052
0
    return d->dbContext_;
13053
0
}
13054
13055
// ---------------------------------------------------------------------------
13056
13057
0
bool JSONFormatter::outputId() const { return d->outputIdStack_.back(); }
13058
13059
// ---------------------------------------------------------------------------
13060
13061
0
bool JSONFormatter::outputUsage(bool calledBeforeObjectContext) const {
13062
0
    return outputId() &&
13063
0
           d->outputIdStack_.size() == (calledBeforeObjectContext ? 1U : 2U);
13064
0
}
13065
13066
// ---------------------------------------------------------------------------
13067
13068
0
void JSONFormatter::setAllowIDInImmediateChild() {
13069
0
    d->allowIDInImmediateChild_ = true;
13070
0
}
13071
13072
// ---------------------------------------------------------------------------
13073
13074
0
void JSONFormatter::setOmitTypeInImmediateChild() {
13075
0
    d->omitTypeInImmediateChild_ = true;
13076
0
}
13077
13078
// ---------------------------------------------------------------------------
13079
13080
JSONFormatter::ObjectContext::ObjectContext(JSONFormatter &formatter,
13081
                                            const char *objectType, bool hasId)
13082
0
    : m_formatter(formatter) {
13083
0
    m_formatter.d->writer_.StartObj();
13084
0
    if (m_formatter.d->outputIdStack_.size() == 1 &&
13085
0
        !m_formatter.d->schema_.empty()) {
13086
0
        m_formatter.d->writer_.AddObjKey("$schema");
13087
0
        m_formatter.d->writer_.Add(m_formatter.d->schema_);
13088
0
    }
13089
0
    if (objectType && !m_formatter.d->omitTypeInImmediateChild_) {
13090
0
        m_formatter.d->writer_.AddObjKey("type");
13091
0
        m_formatter.d->writer_.Add(objectType);
13092
0
    }
13093
0
    m_formatter.d->omitTypeInImmediateChild_ = false;
13094
    // All intermediate nodes shouldn't have ID if a parent has an ID
13095
    // unless explicitly enabled.
13096
0
    if (m_formatter.d->allowIDInImmediateChild_) {
13097
0
        m_formatter.d->pushOutputId(m_formatter.d->outputIdStack_[0]);
13098
0
        m_formatter.d->allowIDInImmediateChild_ = false;
13099
0
    } else {
13100
0
        m_formatter.d->pushOutputId(m_formatter.d->outputIdStack_[0] &&
13101
0
                                    !m_formatter.d->stackHasId_.back());
13102
0
    }
13103
13104
0
    m_formatter.d->stackHasId_.push_back(hasId ||
13105
0
                                         m_formatter.d->stackHasId_.back());
13106
0
}
13107
13108
// ---------------------------------------------------------------------------
13109
13110
0
JSONFormatter::ObjectContext::~ObjectContext() {
13111
0
    m_formatter.d->writer_.EndObj();
13112
0
    m_formatter.d->stackHasId_.pop_back();
13113
0
    m_formatter.d->popOutputId();
13114
0
}
13115
13116
// ---------------------------------------------------------------------------
13117
13118
0
void JSONFormatter::setAbridgedTransformation(bool outputIn) {
13119
0
    d->abridgedTransformation_ = outputIn;
13120
0
}
13121
13122
// ---------------------------------------------------------------------------
13123
13124
0
bool JSONFormatter::abridgedTransformation() const {
13125
0
    return d->abridgedTransformation_;
13126
0
}
13127
13128
// ---------------------------------------------------------------------------
13129
13130
0
void JSONFormatter::setAbridgedTransformationWriteSourceCRS(bool writeCRS) {
13131
0
    d->abridgedTransformationWriteSourceCRS_ = writeCRS;
13132
0
}
13133
13134
// ---------------------------------------------------------------------------
13135
13136
0
bool JSONFormatter::abridgedTransformationWriteSourceCRS() const {
13137
0
    return d->abridgedTransformationWriteSourceCRS_;
13138
0
}
13139
13140
//! @endcond
13141
13142
// ---------------------------------------------------------------------------
13143
13144
/** \brief Return the serialized JSON.
13145
 */
13146
0
const std::string &JSONFormatter::toString() const {
13147
0
    return d->writer_.GetString();
13148
0
}
13149
13150
// ---------------------------------------------------------------------------
13151
13152
//! @cond Doxygen_Suppress
13153
12.1M
IJSONExportable::~IJSONExportable() = default;
13154
13155
// ---------------------------------------------------------------------------
13156
13157
0
std::string IJSONExportable::exportToJSON(JSONFormatter *formatter) const {
13158
0
    _exportToJSON(formatter);
13159
0
    return formatter->toString();
13160
0
}
13161
13162
//! @endcond
13163
13164
} // namespace io
13165
NS_PROJ_END