LCOV - code coverage report
Current view: top level - ogr - ogrspatialreference.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 3475 4264 81.5 %
Date: 2026-11-13 18:19:58 Functions: 300 377 79.6 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  OpenGIS Simple Features Reference Implementation
       4             :  * Purpose:  The OGRSpatialReference class.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1999,  Les Technologies SoftMap Inc.
       9             :  * Copyright (c) 2008-2018, Even Rouault <even.rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "cpl_port.h"
      15             : #include "ogr_spatialref.h"
      16             : 
      17             : #include <cmath>
      18             : #include <cstddef>
      19             : #include <cstdio>
      20             : #include <cstdlib>
      21             : #include <cstring>
      22             : #include <limits>
      23             : #include <string>
      24             : #include <mutex>
      25             : #include <set>
      26             : #include <vector>
      27             : 
      28             : #include "cpl_atomic_ops.h"
      29             : #include "cpl_conv.h"
      30             : #include "cpl_csv.h"
      31             : #include "cpl_error.h"
      32             : #include "cpl_error_internal.h"
      33             : #include "cpl_http.h"
      34             : #include "cpl_json.h"
      35             : #include "cpl_multiproc.h"
      36             : #include "cpl_string.h"
      37             : #include "cpl_vsi.h"
      38             : #include "ogr_core.h"
      39             : #include "ogr_p.h"
      40             : #include "ogr_proj_p.h"
      41             : #include "ogr_srs_api.h"
      42             : #include "ogrmitabspatialref.h"
      43             : 
      44             : #include "proj.h"
      45             : #include "proj_experimental.h"
      46             : #include "proj_constants.h"
      47             : 
      48             : bool GDALThreadLocalDatasetCacheIsInDestruction();
      49             : 
      50             : // Exists since 8.0.1
      51             : #ifndef PROJ_AT_LEAST_VERSION
      52             : #define PROJ_COMPUTE_VERSION(maj, min, patch)                                  \
      53             :     ((maj) * 10000 + (min) * 100 + (patch))
      54             : #define PROJ_VERSION_NUMBER                                                    \
      55             :     PROJ_COMPUTE_VERSION(PROJ_VERSION_MAJOR, PROJ_VERSION_MINOR,               \
      56             :                          PROJ_VERSION_PATCH)
      57             : #define PROJ_AT_LEAST_VERSION(maj, min, patch)                                 \
      58             :     (PROJ_VERSION_NUMBER >= PROJ_COMPUTE_VERSION(maj, min, patch))
      59             : #endif
      60             : 
      61             : #define STRINGIFY(s) #s
      62             : #define XSTRINGIFY(s) STRINGIFY(s)
      63             : 
      64             : struct OGRSpatialReference::Private
      65             : {
      66             :     struct Listener final : public OGR_SRSNode::Listener
      67             :     {
      68             :         OGRSpatialReference::Private *m_poObj = nullptr;
      69             : 
      70      283360 :         explicit Listener(OGRSpatialReference::Private *poObj) : m_poObj(poObj)
      71             :         {
      72      283360 :         }
      73             : 
      74             :         Listener(const Listener &) = delete;
      75             :         Listener &operator=(const Listener &) = delete;
      76             : 
      77             :         void notifyChange(OGR_SRSNode *) override;
      78             :     };
      79             : 
      80             :     OGRSpatialReference *m_poSelf = nullptr;
      81             :     PJ *m_pj_crs = nullptr;
      82             : 
      83             :     // Temporary state used for object construction
      84             :     PJ_TYPE m_pjType = PJ_TYPE_UNKNOWN;
      85             :     CPLString m_osPrimeMeridianName{};
      86             :     CPLString m_osAngularUnits{};
      87             :     CPLString m_osLinearUnits{};
      88             :     CPLString m_osAxisName[3]{};
      89             : 
      90             :     std::vector<std::string> m_wktImportWarnings{};
      91             :     std::vector<std::string> m_wktImportErrors{};
      92             :     CPLString m_osAreaName{};
      93             :     CPLString m_celestialBodyName{};
      94             : 
      95             :     bool m_bIsThreadSafe = false;
      96             :     bool m_bNodesChanged = false;
      97             :     bool m_bNodesWKT2 = false;
      98             :     OGR_SRSNode *m_poRoot = nullptr;
      99             : 
     100             :     double dfFromGreenwich = 0.0;
     101             :     double dfToMeter = 0.0;
     102             :     double dfToDegrees = 0.0;
     103             :     double m_dfAngularUnitToRadian = 0.0;
     104             : 
     105             :     int nRefCount = 1;
     106             :     int bNormInfoSet = FALSE;
     107             : 
     108             :     PJ *m_pj_geod_base_crs_temp = nullptr;
     109             :     PJ *m_pj_proj_crs_cs_temp = nullptr;
     110             : 
     111             :     bool m_pj_crs_modified_during_demote = false;
     112             :     PJ *m_pj_bound_crs_target = nullptr;
     113             :     PJ *m_pj_bound_crs_co = nullptr;
     114             :     PJ *m_pj_crs_backup = nullptr;
     115             :     OGR_SRSNode *m_poRootBackup = nullptr;
     116             : 
     117             :     bool m_bMorphToESRI = false;
     118             :     bool m_bHasCenterLong = false;
     119             : 
     120             :     std::shared_ptr<Listener> m_poListener{};
     121             : 
     122             :     std::recursive_mutex m_mutex{};
     123             : 
     124             :     OSRAxisMappingStrategy m_axisMappingStrategy = OAMS_AUTHORITY_COMPLIANT;
     125             :     std::vector<int> m_axisMapping{1, 2, 3};
     126             : 
     127             :     double m_coordinateEpoch = 0;  // as decimal year
     128             : 
     129             :     explicit Private(OGRSpatialReference *poSelf);
     130             :     ~Private();
     131             :     Private(const Private &) = delete;
     132             :     Private &operator=(const Private &) = delete;
     133             : 
     134           2 :     void SetThreadSafe()
     135             :     {
     136           2 :         m_bIsThreadSafe = true;
     137           2 :     }
     138             : 
     139             :     void clear();
     140             :     void setPjCRS(PJ *pj_crsIn, bool doRefreshAxisMapping = true);
     141             :     void setRoot(OGR_SRSNode *poRoot);
     142             :     void refreshProjObj();
     143             :     void nodesChanged();
     144             :     void refreshRootFromProjObj(bool bForceWKT2);
     145             :     void invalidateNodes();
     146             : 
     147             :     void setMorphToESRI(bool b);
     148             : 
     149             :     PJ *getGeodBaseCRS();
     150             :     PJ *getProjCRSCoordSys();
     151             : 
     152             :     const char *getProjCRSName();
     153             :     OGRErr replaceConversionAndUnref(PJ *conv);
     154             : 
     155             :     void demoteFromBoundCRS();
     156             :     void undoDemoteFromBoundCRS();
     157             : 
     158     1305770 :     PJ_CONTEXT *getPROJContext()
     159             :     {
     160     1305770 :         return OSRGetProjTLSContext();
     161             :     }
     162             : 
     163             :     const char *nullifyTargetKeyIfPossible(const char *pszTargetKey);
     164             : 
     165             :     void refreshAxisMapping();
     166             : 
     167             :     // This structures enables locking during calls to OGRSpatialReference
     168             :     // public methods. Locking is only needed for instances of
     169             :     // OGRSpatialReference that have been asked to be thread-safe at
     170             :     // construction.
     171             :     // The lock is not just for a single call to OGRSpatialReference::Private,
     172             :     // but for the series of calls done by a OGRSpatialReference method.
     173             :     // We need a recursive mutex, because some OGRSpatialReference methods
     174             :     // may call other ones.
     175             :     struct OptionalLockGuard
     176             :     {
     177             :         Private &m_private;
     178             : 
     179    24538200 :         explicit OptionalLockGuard(Private *p) : m_private(*p)
     180             :         {
     181    24538200 :             if (m_private.m_bIsThreadSafe)
     182        3798 :                 m_private.m_mutex.lock();
     183    24538200 :         }
     184             : 
     185    24538200 :         ~OptionalLockGuard()
     186    24538200 :         {
     187    24538200 :             if (m_private.m_bIsThreadSafe)
     188        3798 :                 m_private.m_mutex.unlock();
     189    24538200 :         }
     190             :     };
     191             : 
     192    24538200 :     inline OptionalLockGuard GetOptionalLockGuard()
     193             :     {
     194    24538200 :         return OptionalLockGuard(this);
     195             :     }
     196             : };
     197             : 
     198     2447740 : void OGRSpatialReference::Private::Listener::notifyChange(OGR_SRSNode *)
     199             : {
     200     2447740 :     m_poObj->nodesChanged();
     201     2447740 : }
     202             : 
     203             : #define TAKE_OPTIONAL_LOCK()                                                   \
     204             :     auto lock = d->GetOptionalLockGuard();                                     \
     205             :     CPL_IGNORE_RET_VAL(lock)
     206             : 
     207      283360 : static OSRAxisMappingStrategy GetDefaultAxisMappingStrategy()
     208             : {
     209             :     const char *pszDefaultAMS =
     210      283360 :         CPLGetConfigOption("OSR_DEFAULT_AXIS_MAPPING_STRATEGY", nullptr);
     211      283360 :     if (pszDefaultAMS)
     212             :     {
     213           1 :         if (EQUAL(pszDefaultAMS, "AUTHORITY_COMPLIANT"))
     214           0 :             return OAMS_AUTHORITY_COMPLIANT;
     215           1 :         else if (EQUAL(pszDefaultAMS, "TRADITIONAL_GIS_ORDER"))
     216           1 :             return OAMS_TRADITIONAL_GIS_ORDER;
     217             :         else
     218             :         {
     219           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     220             :                      "Illegal value for OSR_DEFAULT_AXIS_MAPPING_STRATEGY = %s",
     221             :                      pszDefaultAMS);
     222             :         }
     223             :     }
     224      283359 :     return OAMS_AUTHORITY_COMPLIANT;
     225             : }
     226             : 
     227      283360 : OGRSpatialReference::Private::Private(OGRSpatialReference *poSelf)
     228      283360 :     : m_poSelf(poSelf), m_poListener(std::make_shared<Listener>(this))
     229             : {
     230             :     // Get the default value for m_axisMappingStrategy from the
     231             :     // OSR_DEFAULT_AXIS_MAPPING_STRATEGY configuration option, if set.
     232      283360 :     m_axisMappingStrategy = GetDefaultAxisMappingStrategy();
     233      283360 : }
     234             : 
     235     1129480 : OGRSpatialReference::Private::~Private()
     236             : {
     237             :     // In case we destroy the object not in the thread that created it,
     238             :     // we need to reassign the PROJ context. Having the context bundled inside
     239             :     // PJ* deeply sucks...
     240      282370 :     PJ_CONTEXT *pj_context_to_destroy = nullptr;
     241             :     PJ_CONTEXT *ctxt;
     242      282370 :     if (GDALThreadLocalDatasetCacheIsInDestruction())
     243             :     {
     244         183 :         pj_context_to_destroy = proj_context_create();
     245         183 :         ctxt = pj_context_to_destroy;
     246             :     }
     247             :     else
     248             :     {
     249      282187 :         ctxt = getPROJContext();
     250             :     }
     251             : 
     252      282370 :     proj_assign_context(m_pj_crs, ctxt);
     253      282370 :     proj_destroy(m_pj_crs);
     254             : 
     255      282370 :     proj_assign_context(m_pj_geod_base_crs_temp, ctxt);
     256      282370 :     proj_destroy(m_pj_geod_base_crs_temp);
     257             : 
     258      282370 :     proj_assign_context(m_pj_proj_crs_cs_temp, ctxt);
     259      282370 :     proj_destroy(m_pj_proj_crs_cs_temp);
     260             : 
     261      282370 :     proj_assign_context(m_pj_bound_crs_target, ctxt);
     262      282370 :     proj_destroy(m_pj_bound_crs_target);
     263             : 
     264      282370 :     proj_assign_context(m_pj_bound_crs_co, ctxt);
     265      282370 :     proj_destroy(m_pj_bound_crs_co);
     266             : 
     267      282370 :     proj_assign_context(m_pj_crs_backup, ctxt);
     268      282370 :     proj_destroy(m_pj_crs_backup);
     269             : 
     270      282370 :     delete m_poRootBackup;
     271      282370 :     delete m_poRoot;
     272      282370 :     proj_context_destroy(pj_context_to_destroy);
     273      282370 : }
     274             : 
     275      137135 : void OGRSpatialReference::Private::clear()
     276             : {
     277      137135 :     proj_assign_context(m_pj_crs, getPROJContext());
     278      137135 :     proj_destroy(m_pj_crs);
     279      137135 :     m_pj_crs = nullptr;
     280             : 
     281      137135 :     delete m_poRoot;
     282      137135 :     m_poRoot = nullptr;
     283      137135 :     m_bNodesChanged = false;
     284             : 
     285      137135 :     m_wktImportWarnings.clear();
     286      137135 :     m_wktImportErrors.clear();
     287             : 
     288      137135 :     m_pj_crs_modified_during_demote = false;
     289      137135 :     m_pjType = PJ_TYPE_UNKNOWN;
     290      137135 :     m_osPrimeMeridianName.clear();
     291      137135 :     m_osAngularUnits.clear();
     292      137135 :     m_osLinearUnits.clear();
     293             : 
     294      137135 :     bNormInfoSet = FALSE;
     295      137135 :     dfFromGreenwich = 1.0;
     296      137135 :     dfToMeter = 1.0;
     297      137135 :     dfToDegrees = 1.0;
     298      137135 :     m_dfAngularUnitToRadian = 0.0;
     299             : 
     300      137135 :     m_bMorphToESRI = false;
     301      137135 :     m_bHasCenterLong = false;
     302             : 
     303      137135 :     m_coordinateEpoch = 0.0;
     304      137135 : }
     305             : 
     306       30454 : void OGRSpatialReference::Private::setRoot(OGR_SRSNode *poRoot)
     307             : {
     308       30454 :     m_poRoot = poRoot;
     309       30454 :     if (m_poRoot)
     310             :     {
     311       30454 :         m_poRoot->RegisterListener(m_poListener);
     312             :     }
     313       30454 :     nodesChanged();
     314       30454 : }
     315             : 
     316      201303 : void OGRSpatialReference::Private::setPjCRS(PJ *pj_crsIn,
     317             :                                             bool doRefreshAxisMapping)
     318             : {
     319      201303 :     auto ctxt = getPROJContext();
     320             : 
     321             : #if PROJ_AT_LEAST_VERSION(9, 2, 0)
     322             :     if (proj_get_type(pj_crsIn) == PJ_TYPE_COORDINATE_METADATA)
     323             :     {
     324             :         const double dfEpoch =
     325             :             proj_coordinate_metadata_get_epoch(ctxt, pj_crsIn);
     326             :         if (!std::isnan(dfEpoch))
     327             :         {
     328             :             m_poSelf->SetCoordinateEpoch(dfEpoch);
     329             :         }
     330             :         auto crs = proj_get_source_crs(ctxt, pj_crsIn);
     331             :         proj_destroy(pj_crsIn);
     332             :         pj_crsIn = crs;
     333             :     }
     334             : #endif
     335             : 
     336      201303 :     proj_assign_context(m_pj_crs, ctxt);
     337      201303 :     proj_destroy(m_pj_crs);
     338      201303 :     m_pj_crs = pj_crsIn;
     339      201303 :     if (m_pj_crs)
     340             :     {
     341      201250 :         m_pjType = proj_get_type(m_pj_crs);
     342             :     }
     343      201303 :     if (m_pj_crs_backup)
     344             :     {
     345          21 :         m_pj_crs_modified_during_demote = true;
     346             :     }
     347      201303 :     invalidateNodes();
     348      201303 :     if (doRefreshAxisMapping)
     349             :     {
     350      201283 :         refreshAxisMapping();
     351             :     }
     352      201303 : }
     353             : 
     354      815907 : void OGRSpatialReference::Private::refreshProjObj()
     355             : {
     356      815907 :     if (m_bNodesChanged && m_poRoot)
     357             :     {
     358        8926 :         char *pszWKT = nullptr;
     359        8926 :         m_poRoot->exportToWkt(&pszWKT);
     360        8926 :         auto poRootBackup = m_poRoot;
     361        8926 :         m_poRoot = nullptr;
     362        8926 :         const double dfCoordinateEpochBackup = m_coordinateEpoch;
     363        8926 :         clear();
     364        8926 :         m_coordinateEpoch = dfCoordinateEpochBackup;
     365        8926 :         m_bHasCenterLong = strstr(pszWKT, "CENTER_LONG") != nullptr;
     366             : 
     367        8926 :         const char *const options[] = {
     368             :             "STRICT=NO",
     369             : #if PROJ_AT_LEAST_VERSION(9, 1, 0)
     370             :             "UNSET_IDENTIFIERS_IF_INCOMPATIBLE_DEF=NO",
     371             : #endif
     372             :             nullptr};
     373        8926 :         PROJ_STRING_LIST warnings = nullptr;
     374        8926 :         PROJ_STRING_LIST errors = nullptr;
     375        8926 :         setPjCRS(proj_create_from_wkt(getPROJContext(), pszWKT, options,
     376             :                                       &warnings, &errors));
     377       17456 :         for (auto iter = warnings; iter && *iter; ++iter)
     378             :         {
     379        8530 :             m_wktImportWarnings.push_back(*iter);
     380             :         }
     381        9137 :         for (auto iter = errors; iter && *iter; ++iter)
     382             :         {
     383         211 :             m_wktImportErrors.push_back(*iter);
     384             :         }
     385        8926 :         proj_string_list_destroy(warnings);
     386        8926 :         proj_string_list_destroy(errors);
     387             : 
     388        8926 :         CPLFree(pszWKT);
     389             : 
     390        8926 :         m_poRoot = poRootBackup;
     391        8926 :         m_bNodesChanged = false;
     392             :     }
     393      815907 : }
     394             : 
     395       32586 : void OGRSpatialReference::Private::refreshRootFromProjObj(bool bForceWKT2)
     396             : {
     397       32586 :     CPLAssert(m_poRoot == nullptr);
     398             : 
     399       32586 :     if (m_pj_crs)
     400             :     {
     401       60818 :         CPLStringList aosOptions;
     402       30409 :         if (!m_bMorphToESRI)
     403             :         {
     404       30405 :             aosOptions.SetNameValue("OUTPUT_AXIS", "YES");
     405       30405 :             aosOptions.SetNameValue("MULTILINE", "NO");
     406             :         }
     407       30409 :         aosOptions.SetNameValue("STRICT", "NO");
     408             : 
     409       30409 :         const char *pszWKT = nullptr;
     410       30409 :         if (!bForceWKT2)
     411             :         {
     412       30391 :             CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
     413       30391 :             pszWKT = proj_as_wkt(getPROJContext(), m_pj_crs,
     414       30391 :                                  m_bMorphToESRI ? PJ_WKT1_ESRI : PJ_WKT1_GDAL,
     415       30391 :                                  aosOptions.List());
     416       30391 :             m_bNodesWKT2 = false;
     417             :         }
     418       30409 :         if (!m_bMorphToESRI && pszWKT == nullptr)
     419             :         {
     420         114 :             pszWKT = proj_as_wkt(getPROJContext(), m_pj_crs, PJ_WKT2_2018,
     421         114 :                                  aosOptions.List());
     422         114 :             m_bNodesWKT2 = true;
     423             :         }
     424       30409 :         if (pszWKT)
     425             :         {
     426       30409 :             auto root = new OGR_SRSNode();
     427       30409 :             setRoot(root);
     428       30409 :             root->importFromWkt(&pszWKT);
     429       30409 :             m_bNodesChanged = false;
     430             :         }
     431             :     }
     432       32586 : }
     433             : 
     434      235483 : static bool isNorthEastAxisOrder(PJ_CONTEXT *ctx, PJ *cs)
     435             : {
     436      235483 :     const char *pszName1 = nullptr;
     437      235483 :     const char *pszDirection1 = nullptr;
     438      235483 :     proj_cs_get_axis_info(ctx, cs, 0, &pszName1, nullptr, &pszDirection1,
     439             :                           nullptr, nullptr, nullptr, nullptr);
     440      235483 :     const char *pszName2 = nullptr;
     441      235483 :     const char *pszDirection2 = nullptr;
     442      235483 :     proj_cs_get_axis_info(ctx, cs, 1, &pszName2, nullptr, &pszDirection2,
     443             :                           nullptr, nullptr, nullptr, nullptr);
     444      235483 :     if (pszDirection1 && EQUAL(pszDirection1, "north") && pszDirection2 &&
     445      105023 :         EQUAL(pszDirection2, "east"))
     446             :     {
     447      103345 :         return true;
     448             :     }
     449      132138 :     if (pszDirection1 && pszDirection2 &&
     450      132138 :         ((EQUAL(pszDirection1, "north") && EQUAL(pszDirection2, "north")) ||
     451      130477 :          (EQUAL(pszDirection1, "south") && EQUAL(pszDirection2, "south"))) &&
     452        3458 :         pszName1 && STARTS_WITH_CI(pszName1, "northing") && pszName2 &&
     453        1413 :         STARTS_WITH_CI(pszName2, "easting"))
     454             :     {
     455        1413 :         return true;
     456             :     }
     457      130725 :     return false;
     458             : }
     459             : 
     460      296726 : void OGRSpatialReference::Private::refreshAxisMapping()
     461             : {
     462      296726 :     if (!m_pj_crs || m_axisMappingStrategy == OAMS_CUSTOM)
     463       61823 :         return;
     464             : 
     465      234903 :     bool doUndoDemote = false;
     466      234903 :     if (m_pj_crs_backup == nullptr)
     467             :     {
     468      234882 :         doUndoDemote = true;
     469      234882 :         demoteFromBoundCRS();
     470             :     }
     471      234903 :     const auto ctxt = getPROJContext();
     472      234903 :     PJ *horizCRS = nullptr;
     473      234903 :     int axisCount = 0;
     474      234903 :     if (m_pjType == PJ_TYPE_VERTICAL_CRS)
     475             :     {
     476         311 :         axisCount = 1;
     477             :     }
     478      234592 :     else if (m_pjType == PJ_TYPE_COMPOUND_CRS)
     479             :     {
     480        1272 :         horizCRS = proj_crs_get_sub_crs(ctxt, m_pj_crs, 0);
     481        1272 :         if (horizCRS && proj_get_type(horizCRS) == PJ_TYPE_BOUND_CRS)
     482             :         {
     483         222 :             auto baseCRS = proj_get_source_crs(ctxt, horizCRS);
     484         222 :             if (baseCRS)
     485             :             {
     486         222 :                 proj_destroy(horizCRS);
     487         222 :                 horizCRS = baseCRS;
     488             :             }
     489             :         }
     490             : 
     491        1272 :         auto vertCRS = proj_crs_get_sub_crs(ctxt, m_pj_crs, 1);
     492        1272 :         if (vertCRS)
     493             :         {
     494        1269 :             if (proj_get_type(vertCRS) == PJ_TYPE_BOUND_CRS)
     495             :             {
     496         398 :                 auto baseCRS = proj_get_source_crs(ctxt, vertCRS);
     497         398 :                 if (baseCRS)
     498             :                 {
     499         398 :                     proj_destroy(vertCRS);
     500         398 :                     vertCRS = baseCRS;
     501             :                 }
     502             :             }
     503             : 
     504        1269 :             auto cs = proj_crs_get_coordinate_system(ctxt, vertCRS);
     505        1269 :             if (cs)
     506             :             {
     507        1269 :                 axisCount += proj_cs_get_axis_count(ctxt, cs);
     508        1269 :                 proj_destroy(cs);
     509             :             }
     510        1269 :             proj_destroy(vertCRS);
     511             :         }
     512             :     }
     513             :     else
     514             :     {
     515      233320 :         horizCRS = m_pj_crs;
     516             :     }
     517             : 
     518      234903 :     bool bSwitchForGisFriendlyOrder = false;
     519      234903 :     if (horizCRS)
     520             :     {
     521      234589 :         auto cs = proj_crs_get_coordinate_system(ctxt, horizCRS);
     522      234589 :         if (cs)
     523             :         {
     524      234589 :             int nHorizCSAxisCount = proj_cs_get_axis_count(ctxt, cs);
     525      234589 :             axisCount += nHorizCSAxisCount;
     526      234589 :             if (nHorizCSAxisCount >= 2)
     527             :             {
     528      234579 :                 bSwitchForGisFriendlyOrder = isNorthEastAxisOrder(ctxt, cs);
     529             :             }
     530      234589 :             proj_destroy(cs);
     531             :         }
     532             :     }
     533      234903 :     if (horizCRS != m_pj_crs)
     534             :     {
     535        1583 :         proj_destroy(horizCRS);
     536             :     }
     537      234903 :     if (doUndoDemote)
     538             :     {
     539      234882 :         undoDemoteFromBoundCRS();
     540             :     }
     541             : 
     542      234903 :     m_axisMapping.resize(axisCount);
     543      234903 :     if (m_axisMappingStrategy == OAMS_AUTHORITY_COMPLIANT ||
     544       70196 :         !bSwitchForGisFriendlyOrder)
     545             :     {
     546      608257 :         for (int i = 0; i < axisCount; i++)
     547             :         {
     548      406017 :             m_axisMapping[i] = i + 1;
     549      202240 :         }
     550             :     }
     551             :     else
     552             :     {
     553       32663 :         m_axisMapping[0] = 2;
     554       32663 :         m_axisMapping[1] = 1;
     555       32663 :         if (axisCount == 3)
     556             :         {
     557         511 :             m_axisMapping[2] = 3;
     558             :         }
     559             :     }
     560             : }
     561             : 
     562     2478200 : void OGRSpatialReference::Private::nodesChanged()
     563             : {
     564     2478200 :     m_bNodesChanged = true;
     565     2478200 : }
     566             : 
     567      201578 : void OGRSpatialReference::Private::invalidateNodes()
     568             : {
     569      201578 :     delete m_poRoot;
     570      201578 :     m_poRoot = nullptr;
     571      201578 :     m_bNodesChanged = false;
     572      201578 : }
     573             : 
     574         257 : void OGRSpatialReference::Private::setMorphToESRI(bool b)
     575             : {
     576         257 :     invalidateNodes();
     577         257 :     m_bMorphToESRI = b;
     578         257 : }
     579             : 
     580      689736 : void OGRSpatialReference::Private::demoteFromBoundCRS()
     581             : {
     582      689736 :     CPLAssert(m_pj_bound_crs_target == nullptr);
     583      689736 :     CPLAssert(m_pj_bound_crs_co == nullptr);
     584      689736 :     CPLAssert(m_poRootBackup == nullptr);
     585      689736 :     CPLAssert(m_pj_crs_backup == nullptr);
     586             : 
     587      689736 :     m_pj_crs_modified_during_demote = false;
     588             : 
     589      689736 :     if (m_pjType == PJ_TYPE_BOUND_CRS)
     590             :     {
     591        2751 :         auto baseCRS = proj_get_source_crs(getPROJContext(), m_pj_crs);
     592        2751 :         m_pj_bound_crs_target = proj_get_target_crs(getPROJContext(), m_pj_crs);
     593        2751 :         m_pj_bound_crs_co =
     594        2751 :             proj_crs_get_coordoperation(getPROJContext(), m_pj_crs);
     595             : 
     596        2751 :         m_poRootBackup = m_poRoot;
     597        2751 :         m_poRoot = nullptr;
     598        2751 :         m_pj_crs_backup = m_pj_crs;
     599        2751 :         m_pj_crs = baseCRS;
     600        2751 :         m_pjType = proj_get_type(m_pj_crs);
     601             :     }
     602      689736 : }
     603             : 
     604      689736 : void OGRSpatialReference::Private::undoDemoteFromBoundCRS()
     605             : {
     606      689736 :     if (m_pj_bound_crs_target)
     607             :     {
     608        2751 :         CPLAssert(m_poRoot == nullptr);
     609        2751 :         CPLAssert(m_pj_crs);
     610        2751 :         if (!m_pj_crs_modified_during_demote)
     611             :         {
     612        2731 :             proj_destroy(m_pj_crs);
     613        2731 :             m_pj_crs = m_pj_crs_backup;
     614        2731 :             m_pjType = proj_get_type(m_pj_crs);
     615        2731 :             m_poRoot = m_poRootBackup;
     616             :         }
     617             :         else
     618             :         {
     619          20 :             delete m_poRootBackup;
     620          20 :             m_poRootBackup = nullptr;
     621          20 :             proj_destroy(m_pj_crs_backup);
     622          20 :             m_pj_crs_backup = nullptr;
     623          20 :             setPjCRS(proj_crs_create_bound_crs(getPROJContext(), m_pj_crs,
     624          20 :                                                m_pj_bound_crs_target,
     625          20 :                                                m_pj_bound_crs_co),
     626             :                      false);
     627             :         }
     628             :     }
     629             : 
     630      689736 :     m_poRootBackup = nullptr;
     631      689736 :     m_pj_crs_backup = nullptr;
     632      689736 :     proj_destroy(m_pj_bound_crs_target);
     633      689736 :     m_pj_bound_crs_target = nullptr;
     634      689736 :     proj_destroy(m_pj_bound_crs_co);
     635      689736 :     m_pj_bound_crs_co = nullptr;
     636      689736 :     m_pj_crs_modified_during_demote = false;
     637      689736 : }
     638             : 
     639      175541 : const char *OGRSpatialReference::Private::nullifyTargetKeyIfPossible(
     640             :     const char *pszTargetKey)
     641             : {
     642      175541 :     if (pszTargetKey)
     643             :     {
     644       62549 :         demoteFromBoundCRS();
     645       62549 :         if ((m_pjType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
     646       32839 :              m_pjType == PJ_TYPE_GEOGRAPHIC_3D_CRS) &&
     647       29788 :             EQUAL(pszTargetKey, "GEOGCS"))
     648             :         {
     649        7200 :             pszTargetKey = nullptr;
     650             :         }
     651       55349 :         else if (m_pjType == PJ_TYPE_GEOCENTRIC_CRS &&
     652          20 :                  EQUAL(pszTargetKey, "GEOCCS"))
     653             :         {
     654           0 :             pszTargetKey = nullptr;
     655             :         }
     656       55349 :         else if (m_pjType == PJ_TYPE_PROJECTED_CRS &&
     657       31449 :                  EQUAL(pszTargetKey, "PROJCS"))
     658             :         {
     659        4434 :             pszTargetKey = nullptr;
     660             :         }
     661       50915 :         else if (m_pjType == PJ_TYPE_VERTICAL_CRS &&
     662           4 :                  EQUAL(pszTargetKey, "VERT_CS"))
     663             :         {
     664           2 :             pszTargetKey = nullptr;
     665             :         }
     666       62549 :         undoDemoteFromBoundCRS();
     667             :     }
     668      175541 :     return pszTargetKey;
     669             : }
     670             : 
     671        9946 : PJ *OGRSpatialReference::Private::getGeodBaseCRS()
     672             : {
     673        9946 :     if (m_pjType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
     674        9891 :         m_pjType == PJ_TYPE_GEOGRAPHIC_3D_CRS)
     675             :     {
     676          55 :         return m_pj_crs;
     677             :     }
     678             : 
     679        9891 :     auto ctxt = getPROJContext();
     680        9891 :     if (m_pjType == PJ_TYPE_PROJECTED_CRS)
     681             :     {
     682        4561 :         proj_assign_context(m_pj_geod_base_crs_temp, ctxt);
     683        4561 :         proj_destroy(m_pj_geod_base_crs_temp);
     684        4561 :         m_pj_geod_base_crs_temp = proj_crs_get_geodetic_crs(ctxt, m_pj_crs);
     685        4561 :         return m_pj_geod_base_crs_temp;
     686             :     }
     687             : 
     688        5330 :     proj_assign_context(m_pj_geod_base_crs_temp, ctxt);
     689        5330 :     proj_destroy(m_pj_geod_base_crs_temp);
     690        5330 :     auto cs = proj_create_ellipsoidal_2D_cs(ctxt, PJ_ELLPS2D_LATITUDE_LONGITUDE,
     691             :                                             nullptr, 0);
     692        5330 :     m_pj_geod_base_crs_temp = proj_create_geographic_crs(
     693             :         ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84",
     694             :         SRS_WGS84_SEMIMAJOR, SRS_WGS84_INVFLATTENING, SRS_PM_GREENWICH, 0.0,
     695             :         SRS_UA_DEGREE, CPLAtof(SRS_UA_DEGREE_CONV), cs);
     696        5330 :     proj_destroy(cs);
     697             : 
     698        5330 :     return m_pj_geod_base_crs_temp;
     699             : }
     700             : 
     701        5533 : PJ *OGRSpatialReference::Private::getProjCRSCoordSys()
     702             : {
     703        5533 :     auto ctxt = getPROJContext();
     704        5533 :     if (m_pjType == PJ_TYPE_PROJECTED_CRS)
     705             :     {
     706        4547 :         proj_assign_context(m_pj_proj_crs_cs_temp, ctxt);
     707        4547 :         proj_destroy(m_pj_proj_crs_cs_temp);
     708        4547 :         m_pj_proj_crs_cs_temp =
     709        4547 :             proj_crs_get_coordinate_system(getPROJContext(), m_pj_crs);
     710        4547 :         return m_pj_proj_crs_cs_temp;
     711             :     }
     712             : 
     713         986 :     proj_assign_context(m_pj_proj_crs_cs_temp, ctxt);
     714         986 :     proj_destroy(m_pj_proj_crs_cs_temp);
     715         986 :     m_pj_proj_crs_cs_temp = proj_create_cartesian_2D_cs(
     716             :         ctxt, PJ_CART2D_EASTING_NORTHING, nullptr, 0);
     717         986 :     return m_pj_proj_crs_cs_temp;
     718             : }
     719             : 
     720        5585 : const char *OGRSpatialReference::Private::getProjCRSName()
     721             : {
     722        5585 :     if (m_pjType == PJ_TYPE_PROJECTED_CRS)
     723             :     {
     724        4562 :         return proj_get_name(m_pj_crs);
     725             :     }
     726             : 
     727        1023 :     return "unnamed";
     728             : }
     729             : 
     730        1387 : OGRErr OGRSpatialReference::Private::replaceConversionAndUnref(PJ *conv)
     731             : {
     732        1387 :     refreshProjObj();
     733             : 
     734        1387 :     demoteFromBoundCRS();
     735             : 
     736             :     auto projCRS =
     737        1387 :         proj_create_projected_crs(getPROJContext(), getProjCRSName(),
     738        1387 :                                   getGeodBaseCRS(), conv, getProjCRSCoordSys());
     739        1387 :     proj_destroy(conv);
     740             : 
     741        1387 :     setPjCRS(projCRS);
     742             : 
     743        1387 :     undoDemoteFromBoundCRS();
     744        1387 :     return OGRERR_NONE;
     745             : }
     746             : 
     747             : /************************************************************************/
     748             : /*                             ToPointer()                              */
     749             : /************************************************************************/
     750             : 
     751       27804 : static inline OGRSpatialReference *ToPointer(OGRSpatialReferenceH hSRS)
     752             : {
     753       27804 :     return OGRSpatialReference::FromHandle(hSRS);
     754             : }
     755             : 
     756             : /************************************************************************/
     757             : /*                              ToHandle()                              */
     758             : /************************************************************************/
     759             : 
     760        5018 : static inline OGRSpatialReferenceH ToHandle(OGRSpatialReference *poSRS)
     761             : {
     762        5018 :     return OGRSpatialReference::ToHandle(poSRS);
     763             : }
     764             : 
     765             : /************************************************************************/
     766             : /*                          OGRsnPrintDouble()                          */
     767             : /************************************************************************/
     768             : 
     769             : void OGRsnPrintDouble(char *pszStrBuf, size_t size, double dfValue);
     770             : 
     771         121 : void OGRsnPrintDouble(char *pszStrBuf, size_t size, double dfValue)
     772             : 
     773             : {
     774         121 :     CPLsnprintf(pszStrBuf, size, "%.16g", dfValue);
     775             : 
     776         121 :     const size_t nLen = strlen(pszStrBuf);
     777             : 
     778             :     // The following hack is intended to truncate some "precision" in cases
     779             :     // that appear to be roundoff error.
     780         121 :     if (nLen > 15 && (strcmp(pszStrBuf + nLen - 6, "999999") == 0 ||
     781           7 :                       strcmp(pszStrBuf + nLen - 6, "000001") == 0))
     782             :     {
     783           0 :         CPLsnprintf(pszStrBuf, size, "%.15g", dfValue);
     784             :     }
     785             : 
     786             :     // Force to user periods regardless of locale.
     787         121 :     if (strchr(pszStrBuf, ',') != nullptr)
     788             :     {
     789           0 :         char *const pszDelim = strchr(pszStrBuf, ',');
     790           0 :         *pszDelim = '.';
     791             :     }
     792         121 : }
     793             : 
     794             : /************************************************************************/
     795             : /*                        OGRSpatialReference()                         */
     796             : /************************************************************************/
     797             : 
     798             : /**
     799             :  * \brief Constructor.
     800             :  *
     801             :  * This constructor takes an optional string argument which if passed
     802             :  * should be a WKT representation of an SRS.  Passing this is equivalent
     803             :  * to not passing it, and then calling importFromWkt() with the WKT string.
     804             :  *
     805             :  * Note that newly created objects are given a reference count of one.
     806             :  *
     807             :  * Starting with GDAL 3.0, coordinates associated with a OGRSpatialReference
     808             :  * object are assumed to be in the order of the axis of the CRS definition
     809             :  (which
     810             :  * for example means latitude first, longitude second for geographic CRS
     811             :  belonging
     812             :  * to the EPSG authority). It is possible to define a data axis to CRS axis
     813             :  * mapping strategy with the SetAxisMappingStrategy() method.
     814             :  *
     815             :  * Starting with GDAL 3.5, the OSR_DEFAULT_AXIS_MAPPING_STRATEGY configuration
     816             :  * option can be set to "TRADITIONAL_GIS_ORDER" / "AUTHORITY_COMPLIANT" (the
     817             :  later
     818             :  * being the default value when the option is not set) to control the value of
     819             :  the
     820             :  * data axis to CRS axis mapping strategy when a OSRSpatialReference object is
     821             :  * created. Calling SetAxisMappingStrategy() will override this default value.
     822             : 
     823             :  * The C function OSRNewSpatialReference() does the same thing as this
     824             :  * constructor.
     825             :  *
     826             :  * @param pszWKT well known text definition to which the object should
     827             :  * be initialized, or NULL (the default).
     828             :  */
     829             : 
     830      280659 : OGRSpatialReference::OGRSpatialReference(const char *pszWKT)
     831      280659 :     : d(new Private(this))
     832             : {
     833      280659 :     if (pszWKT != nullptr)
     834        1280 :         importFromWkt(pszWKT);
     835      280659 : }
     836             : 
     837             : /************************************************************************/
     838             : /*                       OSRNewSpatialReference()                       */
     839             : /************************************************************************/
     840             : 
     841             : /**
     842             :  * \brief Constructor.
     843             :  *
     844             :  * Starting with GDAL 3.0, coordinates associated with a OGRSpatialReference
     845             :  * object are assumed to be in the order of the axis of the CRS definition
     846             :  * (which for example means latitude first, longitude second for geographic CRS
     847             :  * belonging to the EPSG authority). It is possible to define a data axis to CRS
     848             :  * axis mapping strategy with the SetAxisMappingStrategy() method.
     849             :  *
     850             :  * Starting with GDAL 3.5, the OSR_DEFAULT_AXIS_MAPPING_STRATEGY configuration
     851             :  * option can be set to "TRADITIONAL_GIS_ORDER" / "AUTHORITY_COMPLIANT" (the
     852             :  * later being the default value when the option is not set) to control the
     853             :  * value of the data axis to CRS axis mapping strategy when a
     854             :  * OSRSpatialReference object is created. Calling SetAxisMappingStrategy() will
     855             :  * override this default value.
     856             :  *
     857             :  * This function is the same as OGRSpatialReference::OGRSpatialReference()
     858             :  */
     859        3489 : OGRSpatialReferenceH CPL_STDCALL OSRNewSpatialReference(const char *pszWKT)
     860             : 
     861             : {
     862        3489 :     OGRSpatialReference *poSRS = new OGRSpatialReference();
     863             : 
     864        3489 :     if (pszWKT != nullptr && strlen(pszWKT) > 0)
     865             :     {
     866          66 :         if (poSRS->importFromWkt(pszWKT) != OGRERR_NONE)
     867             :         {
     868           0 :             delete poSRS;
     869           0 :             poSRS = nullptr;
     870             :         }
     871             :     }
     872             : 
     873        3489 :     return ToHandle(poSRS);
     874             : }
     875             : 
     876             : /************************************************************************/
     877             : /*                        OGRSpatialReference()                         */
     878             : /************************************************************************/
     879             : 
     880             : /** Copy constructor. See also Clone().
     881             :  * @param oOther other spatial reference
     882             :  */
     883        2701 : OGRSpatialReference::OGRSpatialReference(const OGRSpatialReference &oOther)
     884        2701 :     : d(new Private(this))
     885             : {
     886        2701 :     *this = oOther;
     887        2701 : }
     888             : 
     889             : /************************************************************************/
     890             : /*                        OGRSpatialReference()                         */
     891             : /************************************************************************/
     892             : 
     893             : /** Move constructor.
     894             :  * @param oOther other spatial reference
     895             :  */
     896           1 : OGRSpatialReference::OGRSpatialReference(OGRSpatialReference &&oOther)
     897           1 :     : d(std::move(oOther.d))
     898             : {
     899           1 : }
     900             : 
     901             : /************************************************************************/
     902             : /*                        ~OGRSpatialReference()                        */
     903             : /************************************************************************/
     904             : 
     905             : /**
     906             :  * \brief OGRSpatialReference destructor.
     907             :  *
     908             :  * The C function OSRDestroySpatialReference() does the same thing as this
     909             :  * method. Preferred C++ method : OGRSpatialReference::DestroySpatialReference()
     910             :  *
     911             :  * @deprecated
     912             :  */
     913             : 
     914      343408 : OGRSpatialReference::~OGRSpatialReference()
     915             : 
     916             : {
     917      343408 : }
     918             : 
     919             : /************************************************************************/
     920             : /*                      DestroySpatialReference()                       */
     921             : /************************************************************************/
     922             : 
     923             : /**
     924             :  * \brief OGRSpatialReference destructor.
     925             :  *
     926             :  * This static method will destroy a OGRSpatialReference.  It is
     927             :  * equivalent to calling delete on the object, but it ensures that the
     928             :  * deallocation is properly executed within the OGR libraries heap on
     929             :  * platforms where this can matter (win32).
     930             :  *
     931             :  * This function is the same as OSRDestroySpatialReference()
     932             :  *
     933             :  * @param poSRS the object to delete
     934             :  *
     935             :  */
     936             : 
     937           0 : void OGRSpatialReference::DestroySpatialReference(OGRSpatialReference *poSRS)
     938             : {
     939           0 :     delete poSRS;
     940           0 : }
     941             : 
     942             : /************************************************************************/
     943             : /*                     OSRDestroySpatialReference()                     */
     944             : /************************************************************************/
     945             : 
     946             : /**
     947             :  * \brief OGRSpatialReference destructor.
     948             :  *
     949             :  * This function is the same as OGRSpatialReference::~OGRSpatialReference()
     950             :  * and OGRSpatialReference::DestroySpatialReference()
     951             :  *
     952             :  * @param hSRS the object to delete
     953             :  */
     954        9746 : void CPL_STDCALL OSRDestroySpatialReference(OGRSpatialReferenceH hSRS)
     955             : 
     956             : {
     957        9746 :     delete ToPointer(hSRS);
     958        9746 : }
     959             : 
     960             : /************************************************************************/
     961             : /*                               Clear()                                */
     962             : /************************************************************************/
     963             : 
     964             : /**
     965             :  * \brief Wipe current definition.
     966             :  *
     967             :  * Returns OGRSpatialReference to a state with no definition, as it
     968             :  * exists when first created.  It does not affect reference counts.
     969             :  */
     970             : 
     971      128209 : void OGRSpatialReference::Clear()
     972             : 
     973             : {
     974      128209 :     d->clear();
     975      128209 : }
     976             : 
     977             : /************************************************************************/
     978             : /*                             operator=()                              */
     979             : /************************************************************************/
     980             : 
     981             : /** Assignment operator.
     982             :  * @param oSource SRS to assign to *this
     983             :  * @return *this
     984             :  */
     985             : OGRSpatialReference &
     986       28442 : OGRSpatialReference::operator=(const OGRSpatialReference &oSource)
     987             : 
     988             : {
     989       28442 :     if (&oSource != this)
     990             :     {
     991       28441 :         Clear();
     992             : #ifdef CPPCHECK
     993             :         // Otherwise cppcheck would protest that nRefCount isn't modified
     994             :         d->nRefCount = (d->nRefCount + 1) - 1;
     995             : #endif
     996             : 
     997       28441 :         oSource.d->refreshProjObj();
     998       28441 :         if (oSource.d->m_pj_crs)
     999       27981 :             d->setPjCRS(proj_clone(d->getPROJContext(), oSource.d->m_pj_crs));
    1000       28441 :         if (oSource.d->m_axisMappingStrategy == OAMS_TRADITIONAL_GIS_ORDER)
    1001       13452 :             SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    1002       14989 :         else if (oSource.d->m_axisMappingStrategy == OAMS_CUSTOM)
    1003         139 :             SetDataAxisToSRSAxisMapping(oSource.d->m_axisMapping);
    1004             : 
    1005       28441 :         d->m_coordinateEpoch = oSource.d->m_coordinateEpoch;
    1006             :     }
    1007             : 
    1008       28442 :     return *this;
    1009             : }
    1010             : 
    1011             : /************************************************************************/
    1012             : /*                             operator=()                              */
    1013             : /************************************************************************/
    1014             : 
    1015             : /** Move assignment operator.
    1016             :  * @param oSource SRS to assign to *this
    1017             :  * @return *this
    1018             :  */
    1019             : OGRSpatialReference &
    1020        5301 : OGRSpatialReference::operator=(OGRSpatialReference &&oSource)
    1021             : 
    1022             : {
    1023        5301 :     if (&oSource != this)
    1024             :     {
    1025        5300 :         d = std::move(oSource.d);
    1026             :     }
    1027             : 
    1028        5301 :     return *this;
    1029             : }
    1030             : 
    1031             : /************************************************************************/
    1032             : /*                       AssignAndSetThreadSafe()                       */
    1033             : /************************************************************************/
    1034             : 
    1035             : /** Assignment method, with thread-safety.
    1036             :  *
    1037             :  * Same as an assignment operator, but asking also that the *this instance
    1038             :  * becomes thread-safe.
    1039             :  *
    1040             :  * @param oSource SRS to assign to *this
    1041             :  * @return *this
    1042             :  * @since 3.10
    1043             :  */
    1044             : 
    1045             : OGRSpatialReference &
    1046           2 : OGRSpatialReference::AssignAndSetThreadSafe(const OGRSpatialReference &oSource)
    1047             : {
    1048           2 :     *this = oSource;
    1049           2 :     d->SetThreadSafe();
    1050           2 :     return *this;
    1051             : }
    1052             : 
    1053             : /************************************************************************/
    1054             : /*                             Reference()                              */
    1055             : /************************************************************************/
    1056             : 
    1057             : /**
    1058             :  * \brief Increments the reference count by one.
    1059             :  *
    1060             :  * The reference count is used keep track of the number of OGRGeometry objects
    1061             :  * referencing this SRS.
    1062             :  *
    1063             :  * The method does the same thing as the C function OSRReference().
    1064             :  *
    1065             :  * @return the updated reference count.
    1066             :  */
    1067             : 
    1068     3734690 : int OGRSpatialReference::Reference()
    1069             : 
    1070             : {
    1071     3734690 :     return CPLAtomicInc(&d->nRefCount);
    1072             : }
    1073             : 
    1074             : /************************************************************************/
    1075             : /*                            OSRReference()                            */
    1076             : /************************************************************************/
    1077             : 
    1078             : /**
    1079             :  * \brief Increments the reference count by one.
    1080             :  *
    1081             :  * This function is the same as OGRSpatialReference::Reference()
    1082             :  */
    1083        1103 : int OSRReference(OGRSpatialReferenceH hSRS)
    1084             : 
    1085             : {
    1086        1103 :     VALIDATE_POINTER1(hSRS, "OSRReference", 0);
    1087             : 
    1088        1103 :     return ToPointer(hSRS)->Reference();
    1089             : }
    1090             : 
    1091             : /************************************************************************/
    1092             : /*                            Dereference()                             */
    1093             : /************************************************************************/
    1094             : 
    1095             : /**
    1096             :  * \brief Decrements the reference count by one.
    1097             :  *
    1098             :  * The method does the same thing as the C function OSRDereference().
    1099             :  *
    1100             :  * @return the updated reference count.
    1101             :  */
    1102             : 
    1103     3778400 : int OGRSpatialReference::Dereference()
    1104             : 
    1105             : {
    1106     3778400 :     if (d->nRefCount <= 0)
    1107           0 :         CPLDebug("OSR",
    1108             :                  "Dereference() called on an object with refcount %d,"
    1109             :                  "likely already destroyed!",
    1110           0 :                  d->nRefCount);
    1111     3778400 :     return CPLAtomicDec(&d->nRefCount);
    1112             : }
    1113             : 
    1114             : /************************************************************************/
    1115             : /*                           OSRDereference()                           */
    1116             : /************************************************************************/
    1117             : 
    1118             : /**
    1119             :  * \brief Decrements the reference count by one.
    1120             :  *
    1121             :  * This function is the same as OGRSpatialReference::Dereference()
    1122             :  */
    1123           0 : int OSRDereference(OGRSpatialReferenceH hSRS)
    1124             : 
    1125             : {
    1126           0 :     VALIDATE_POINTER1(hSRS, "OSRDereference", 0);
    1127             : 
    1128           0 :     return ToPointer(hSRS)->Dereference();
    1129             : }
    1130             : 
    1131             : /************************************************************************/
    1132             : /*                         GetReferenceCount()                          */
    1133             : /************************************************************************/
    1134             : 
    1135             : /**
    1136             :  * \brief Fetch current reference count.
    1137             :  *
    1138             :  * @return the current reference count.
    1139             :  */
    1140         180 : int OGRSpatialReference::GetReferenceCount() const
    1141             : {
    1142         180 :     return d->nRefCount;
    1143             : }
    1144             : 
    1145             : /************************************************************************/
    1146             : /*                              Release()                               */
    1147             : /************************************************************************/
    1148             : 
    1149             : /**
    1150             :  * \brief Decrements the reference count by one, and destroy if zero.
    1151             :  *
    1152             :  * The method does the same thing as the C function OSRRelease().
    1153             :  */
    1154             : 
    1155     3778140 : void OGRSpatialReference::Release()
    1156             : 
    1157             : {
    1158     3778140 :     if (Dereference() <= 0)
    1159       43649 :         delete this;
    1160     3778140 : }
    1161             : 
    1162             : /************************************************************************/
    1163             : /*                             OSRRelease()                             */
    1164             : /************************************************************************/
    1165             : 
    1166             : /**
    1167             :  * \brief Decrements the reference count by one, and destroy if zero.
    1168             :  *
    1169             :  * This function is the same as OGRSpatialReference::Release()
    1170             :  */
    1171        6998 : void OSRRelease(OGRSpatialReferenceH hSRS)
    1172             : 
    1173             : {
    1174        6998 :     VALIDATE_POINTER0(hSRS, "OSRRelease");
    1175             : 
    1176        6998 :     ToPointer(hSRS)->Release();
    1177             : }
    1178             : 
    1179       96148 : OGR_SRSNode *OGRSpatialReference::GetRoot()
    1180             : {
    1181       96148 :     TAKE_OPTIONAL_LOCK();
    1182             : 
    1183       96148 :     if (!d->m_poRoot)
    1184             :     {
    1185       29148 :         d->refreshRootFromProjObj(false);
    1186             :     }
    1187      192296 :     return d->m_poRoot;
    1188             : }
    1189             : 
    1190        8820 : const OGR_SRSNode *OGRSpatialReference::GetRoot() const
    1191             : {
    1192        8820 :     TAKE_OPTIONAL_LOCK();
    1193             : 
    1194        8820 :     if (!d->m_poRoot)
    1195             :     {
    1196        3420 :         d->refreshRootFromProjObj(false);
    1197             :     }
    1198       17640 :     return d->m_poRoot;
    1199             : }
    1200             : 
    1201             : /************************************************************************/
    1202             : /*                              SetRoot()                               */
    1203             : /************************************************************************/
    1204             : 
    1205             : /**
    1206             :  * \brief Set the root SRS node.
    1207             :  *
    1208             :  * If the object has an existing tree of OGR_SRSNodes, they are destroyed
    1209             :  * as part of assigning the new root.  Ownership of the passed OGR_SRSNode is
    1210             :  * is assumed by the OGRSpatialReference.
    1211             :  *
    1212             :  * @param poNewRoot object to assign as root.
    1213             :  */
    1214             : 
    1215          45 : void OGRSpatialReference::SetRoot(OGR_SRSNode *poNewRoot)
    1216             : 
    1217             : {
    1218          45 :     if (d->m_poRoot != poNewRoot)
    1219             :     {
    1220          45 :         delete d->m_poRoot;
    1221          45 :         d->setRoot(poNewRoot);
    1222             :     }
    1223          45 : }
    1224             : 
    1225             : /************************************************************************/
    1226             : /*                            GetAttrNode()                             */
    1227             : /************************************************************************/
    1228             : 
    1229             : /**
    1230             :  * \brief Find named node in tree.
    1231             :  *
    1232             :  * This method does a pre-order traversal of the node tree searching for
    1233             :  * a node with this exact value (case insensitive), and returns it.  Leaf
    1234             :  * nodes are not considered, under the assumption that they are just
    1235             :  * attribute value nodes.
    1236             :  *
    1237             :  * If a node appears more than once in the tree (such as UNIT for instance),
    1238             :  * the first encountered will be returned.  Use GetNode() on a subtree to be
    1239             :  * more specific.
    1240             :  *
    1241             :  * @param pszNodePath the name of the node to search for.  May contain multiple
    1242             :  * components such as "GEOGCS|UNIT".
    1243             :  *
    1244             :  * @return a pointer to the node found, or NULL if none.
    1245             :  */
    1246             : 
    1247       93011 : OGR_SRSNode *OGRSpatialReference::GetAttrNode(const char *pszNodePath)
    1248             : 
    1249             : {
    1250       93011 :     if (strstr(pszNodePath, "CONVERSION") && !d->m_bNodesWKT2)
    1251             :     {
    1252          18 :         d->invalidateNodes();
    1253          18 :         d->refreshRootFromProjObj(/* bForceWKT2 = */ true);
    1254             :     }
    1255             : 
    1256       93011 :     if (strchr(pszNodePath, '|') == nullptr)
    1257             :     {
    1258             :         // Fast path
    1259       51465 :         OGR_SRSNode *poNode = GetRoot();
    1260       51465 :         if (poNode)
    1261       50253 :             poNode = poNode->GetNode(pszNodePath);
    1262       51465 :         return poNode;
    1263             :     }
    1264             : 
    1265             :     char **papszPathTokens =
    1266       41546 :         CSLTokenizeStringComplex(pszNodePath, "|", TRUE, FALSE);
    1267             : 
    1268       41546 :     if (CSLCount(papszPathTokens) < 1)
    1269             :     {
    1270           0 :         CSLDestroy(papszPathTokens);
    1271           0 :         return nullptr;
    1272             :     }
    1273             : 
    1274       41546 :     OGR_SRSNode *poNode = GetRoot();
    1275      126552 :     for (int i = 0; poNode != nullptr && papszPathTokens[i] != nullptr; i++)
    1276             :     {
    1277       85006 :         poNode = poNode->GetNode(papszPathTokens[i]);
    1278             :     }
    1279             : 
    1280       41546 :     CSLDestroy(papszPathTokens);
    1281             : 
    1282       41546 :     return poNode;
    1283             : }
    1284             : 
    1285             : /**
    1286             :  * \brief Find named node in tree.
    1287             :  *
    1288             :  * This method does a pre-order traversal of the node tree searching for
    1289             :  * a node with this exact value (case insensitive), and returns it.  Leaf
    1290             :  * nodes are not considered, under the assumption that they are just
    1291             :  * attribute value nodes.
    1292             :  *
    1293             :  * If a node appears more than once in the tree (such as UNIT for instance),
    1294             :  * the first encountered will be returned.  Use GetNode() on a subtree to be
    1295             :  * more specific.
    1296             :  *
    1297             :  * @param pszNodePath the name of the node to search for.  May contain multiple
    1298             :  * components such as "GEOGCS|UNIT".
    1299             :  *
    1300             :  * @return a pointer to the node found, or NULL if none.
    1301             :  */
    1302             : 
    1303             : const OGR_SRSNode *
    1304       84332 : OGRSpatialReference::GetAttrNode(const char *pszNodePath) const
    1305             : 
    1306             : {
    1307             :     OGR_SRSNode *poNode =
    1308       84332 :         const_cast<OGRSpatialReference *>(this)->GetAttrNode(pszNodePath);
    1309             : 
    1310       84332 :     return poNode;
    1311             : }
    1312             : 
    1313             : /************************************************************************/
    1314             : /*                            GetAttrValue()                            */
    1315             : /************************************************************************/
    1316             : 
    1317             : /**
    1318             :  * \brief Fetch indicated attribute of named node.
    1319             :  *
    1320             :  * This method uses GetAttrNode() to find the named node, and then extracts
    1321             :  * the value of the indicated child.  Thus a call to GetAttrValue("UNIT",1)
    1322             :  * would return the second child of the UNIT node, which is normally the
    1323             :  * length of the linear unit in meters.
    1324             :  *
    1325             :  * This method does the same thing as the C function OSRGetAttrValue().
    1326             :  *
    1327             :  * @param pszNodeName the tree node to look for (case insensitive).
    1328             :  * @param iAttr the child of the node to fetch (zero based).
    1329             :  *
    1330             :  * @return the requested value, or NULL if it fails for any reason.
    1331             :  */
    1332             : 
    1333       25078 : const char *OGRSpatialReference::GetAttrValue(const char *pszNodeName,
    1334             :                                               int iAttr) const
    1335             : 
    1336             : {
    1337       25078 :     const OGR_SRSNode *poNode = GetAttrNode(pszNodeName);
    1338       25078 :     if (poNode == nullptr)
    1339             :     {
    1340       10801 :         if (d->m_bNodesWKT2 && EQUAL(pszNodeName, "PROJECTION"))
    1341             :         {
    1342          14 :             return GetAttrValue("METHOD", iAttr);
    1343             :         }
    1344       10787 :         else if (d->m_bNodesWKT2 && EQUAL(pszNodeName, "PROJCS|PROJECTION"))
    1345             :         {
    1346           0 :             return GetAttrValue("PROJCRS|METHOD", iAttr);
    1347             :         }
    1348       10787 :         else if (d->m_bNodesWKT2 && EQUAL(pszNodeName, "PROJCS"))
    1349             :         {
    1350           1 :             return GetAttrValue("PROJCRS", iAttr);
    1351             :         }
    1352       10786 :         return nullptr;
    1353             :     }
    1354             : 
    1355       14277 :     if (iAttr < 0 || iAttr >= poNode->GetChildCount())
    1356           0 :         return nullptr;
    1357             : 
    1358       14277 :     return poNode->GetChild(iAttr)->GetValue();
    1359             : }
    1360             : 
    1361             : /************************************************************************/
    1362             : /*                          OSRGetAttrValue()                           */
    1363             : /************************************************************************/
    1364             : 
    1365             : /**
    1366             :  * \brief Fetch indicated attribute of named node.
    1367             :  *
    1368             :  * This function is the same as OGRSpatialReference::GetAttrValue()
    1369             :  */
    1370          36 : const char *CPL_STDCALL OSRGetAttrValue(OGRSpatialReferenceH hSRS,
    1371             :                                         const char *pszKey, int iChild)
    1372             : 
    1373             : {
    1374          36 :     VALIDATE_POINTER1(hSRS, "OSRGetAttrValue", nullptr);
    1375             : 
    1376          36 :     return ToPointer(hSRS)->GetAttrValue(pszKey, iChild);
    1377             : }
    1378             : 
    1379             : /************************************************************************/
    1380             : /*                              GetName()                               */
    1381             : /************************************************************************/
    1382             : 
    1383             : /**
    1384             :  * \brief Return the CRS name.
    1385             :  *
    1386             :  * The returned value is only short lived and should not be used after other
    1387             :  * calls to methods on this object.
    1388             :  *
    1389             :  * @since GDAL 3.0
    1390             :  */
    1391             : 
    1392        9109 : const char *OGRSpatialReference::GetName() const
    1393             : {
    1394       18218 :     TAKE_OPTIONAL_LOCK();
    1395             : 
    1396        9109 :     d->refreshProjObj();
    1397        9109 :     if (!d->m_pj_crs)
    1398         113 :         return nullptr;
    1399        8996 :     const char *pszName = proj_get_name(d->m_pj_crs);
    1400             : #if PROJ_VERSION_NUMBER == PROJ_COMPUTE_VERSION(8, 2, 0)
    1401             :     if (d->m_pjType == PJ_TYPE_BOUND_CRS && EQUAL(pszName, "SOURCECRS"))
    1402             :     {
    1403             :         // Work around a bug of PROJ 8.2.0 (fixed in 8.2.1)
    1404             :         PJ *baseCRS = proj_get_source_crs(d->getPROJContext(), d->m_pj_crs);
    1405             :         if (baseCRS)
    1406             :         {
    1407             :             pszName = proj_get_name(baseCRS);
    1408             :             // pszName still remains valid after proj_destroy(), since
    1409             :             // d->m_pj_crs keeps a reference to the base CRS C++ object.
    1410             :             proj_destroy(baseCRS);
    1411             :         }
    1412             :     }
    1413             : #endif
    1414        8996 :     return pszName;
    1415             : }
    1416             : 
    1417             : /************************************************************************/
    1418             : /*                             OSRGetName()                             */
    1419             : /************************************************************************/
    1420             : 
    1421             : /**
    1422             :  * \brief Return the CRS name.
    1423             :  *
    1424             :  * The returned value is only short lived and should not be used after other
    1425             :  * calls to methods on this object.
    1426             :  *
    1427             :  * @since GDAL 3.0
    1428             :  */
    1429          47 : const char *OSRGetName(OGRSpatialReferenceH hSRS)
    1430             : 
    1431             : {
    1432          47 :     VALIDATE_POINTER1(hSRS, "OSRGetName", nullptr);
    1433             : 
    1434          47 :     return ToPointer(hSRS)->GetName();
    1435             : }
    1436             : 
    1437             : /************************************************************************/
    1438             : /*                        GetCelestialBodyName()                        */
    1439             : /************************************************************************/
    1440             : 
    1441             : /**
    1442             :  * \brief Return the name of the celestial body of this CRS.
    1443             :  *
    1444             :  * e.g. "Earth" for an Earth CRS
    1445             :  *
    1446             :  * The returned value is only short lived and should not be used after other
    1447             :  * calls to methods on this object.
    1448             :  *
    1449             :  * @since GDAL 3.12 and PROJ 8.1
    1450             :  */
    1451             : 
    1452           4 : const char *OGRSpatialReference::GetCelestialBodyName() const
    1453             : {
    1454             : #if PROJ_AT_LEAST_VERSION(8, 1, 0)
    1455             : 
    1456             :     TAKE_OPTIONAL_LOCK();
    1457             : 
    1458             :     d->refreshProjObj();
    1459             :     if (!d->m_pj_crs)
    1460             :         return nullptr;
    1461             :     d->demoteFromBoundCRS();
    1462             :     const char *name =
    1463             :         proj_get_celestial_body_name(d->getPROJContext(), d->m_pj_crs);
    1464             :     if (name)
    1465             :     {
    1466             :         d->m_celestialBodyName = name;
    1467             :     }
    1468             :     d->undoDemoteFromBoundCRS();
    1469             :     return d->m_celestialBodyName.c_str();
    1470             : #else
    1471           4 :     if (std::fabs(GetSemiMajor(nullptr) - SRS_WGS84_SEMIMAJOR) <=
    1472             :         0.05 * SRS_WGS84_SEMIMAJOR)
    1473           4 :         return "Earth";
    1474           0 :     const char *pszAuthName = GetAuthorityName();
    1475           0 :     if (pszAuthName && EQUAL(pszAuthName, "EPSG"))
    1476           0 :         return "Earth";
    1477           0 :     return nullptr;
    1478             : #endif
    1479             : }
    1480             : 
    1481             : /************************************************************************/
    1482             : /*                      OSRGetCelestialBodyName()                       */
    1483             : /************************************************************************/
    1484             : 
    1485             : /**
    1486             :  * \brief Return the name of the celestial body of this CRS.
    1487             :  *
    1488             :  * e.g. "Earth" for an Earth CRS
    1489             :  *
    1490             :  * The returned value is only short lived and should not be used after other
    1491             :  * calls to methods on this object.
    1492             :  *
    1493             :  * @since GDAL 3.12 and PROJ 8.1
    1494             :  */
    1495             : 
    1496           1 : const char *OSRGetCelestialBodyName(OGRSpatialReferenceH hSRS)
    1497             : 
    1498             : {
    1499           1 :     VALIDATE_POINTER1(hSRS, "GetCelestialBodyName", nullptr);
    1500             : 
    1501           1 :     return ToPointer(hSRS)->GetCelestialBodyName();
    1502             : }
    1503             : 
    1504             : /************************************************************************/
    1505             : /*                               Clone()                                */
    1506             : /************************************************************************/
    1507             : 
    1508             : /**
    1509             :  * \brief Make a duplicate of this OGRSpatialReference.
    1510             :  *
    1511             :  * This method is the same as the C function OSRClone().
    1512             :  *
    1513             :  * @return a new SRS, which becomes the responsibility of the caller.
    1514             :  */
    1515             : 
    1516       32862 : OGRSpatialReference *OGRSpatialReference::Clone() const
    1517             : 
    1518             : {
    1519       32862 :     OGRSpatialReference *poNewRef = new OGRSpatialReference();
    1520             : 
    1521       32862 :     TAKE_OPTIONAL_LOCK();
    1522             : 
    1523       32862 :     d->refreshProjObj();
    1524       32862 :     if (d->m_pj_crs != nullptr)
    1525       32818 :         poNewRef->d->setPjCRS(proj_clone(d->getPROJContext(), d->m_pj_crs));
    1526       32862 :     if (d->m_bHasCenterLong && d->m_poRoot)
    1527             :     {
    1528           0 :         poNewRef->d->setRoot(d->m_poRoot->Clone());
    1529             :     }
    1530       32862 :     poNewRef->d->m_axisMapping = d->m_axisMapping;
    1531       32862 :     poNewRef->d->m_axisMappingStrategy = d->m_axisMappingStrategy;
    1532       32862 :     poNewRef->d->m_coordinateEpoch = d->m_coordinateEpoch;
    1533       65724 :     return poNewRef;
    1534             : }
    1535             : 
    1536             : /************************************************************************/
    1537             : /*                              OSRClone()                              */
    1538             : /************************************************************************/
    1539             : 
    1540             : /**
    1541             :  * \brief Make a duplicate of this OGRSpatialReference.
    1542             :  *
    1543             :  * This function is the same as OGRSpatialReference::Clone()
    1544             :  */
    1545        1372 : OGRSpatialReferenceH CPL_STDCALL OSRClone(OGRSpatialReferenceH hSRS)
    1546             : 
    1547             : {
    1548        1372 :     VALIDATE_POINTER1(hSRS, "OSRClone", nullptr);
    1549             : 
    1550        1372 :     return ToHandle(ToPointer(hSRS)->Clone());
    1551             : }
    1552             : 
    1553             : /************************************************************************/
    1554             : /*                            dumpReadable()                            */
    1555             : /************************************************************************/
    1556             : 
    1557             : /** Dump pretty wkt to stdout, mostly for debugging.
    1558             :  */
    1559           0 : void OGRSpatialReference::dumpReadable()
    1560             : 
    1561             : {
    1562           0 :     char *pszPrettyWkt = nullptr;
    1563             : 
    1564           0 :     const char *const apszOptions[] = {"FORMAT=WKT2", "MULTILINE=YES", nullptr};
    1565           0 :     exportToWkt(&pszPrettyWkt, apszOptions);
    1566           0 :     printf("%s\n", pszPrettyWkt); /*ok*/
    1567           0 :     CPLFree(pszPrettyWkt);
    1568           0 : }
    1569             : 
    1570             : /************************************************************************/
    1571             : /*                         exportToPrettyWkt()                          */
    1572             : /************************************************************************/
    1573             : 
    1574             : /**
    1575             :  * Convert this SRS into a nicely formatted WKT 1 string for display to a
    1576             :  * person.
    1577             :  *
    1578             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    1579             :  * Issues</a> page for implementation details of WKT 1 in OGR.
    1580             :  *
    1581             :  * Note that the returned WKT string should be freed with
    1582             :  * CPLFree() when no longer needed.  It is the responsibility of the caller.
    1583             :  *
    1584             :  * The WKT version can be overridden by using the OSR_WKT_FORMAT configuration
    1585             :  * option. Valid values are the one of the FORMAT option of
    1586             :  * exportToWkt( char ** ppszResult, const char* const* papszOptions ) const
    1587             :  *
    1588             :  * This method is the same as the C function OSRExportToPrettyWkt().
    1589             :  *
    1590             :  * @param ppszResult the resulting string is returned in this pointer.
    1591             :  * @param bSimplify TRUE if the AXIS, AUTHORITY and EXTENSION nodes should be
    1592             :  *   stripped off.
    1593             :  *
    1594             :  * @return OGRERR_NONE if successful.
    1595             :  */
    1596             : 
    1597          58 : OGRErr OGRSpatialReference::exportToPrettyWkt(char **ppszResult,
    1598             :                                               int bSimplify) const
    1599             : 
    1600             : {
    1601         116 :     CPLStringList aosOptions;
    1602          58 :     aosOptions.SetNameValue("MULTILINE", "YES");
    1603          58 :     if (bSimplify)
    1604             :     {
    1605           0 :         aosOptions.SetNameValue("FORMAT", "WKT1_SIMPLE");
    1606             :     }
    1607         116 :     return exportToWkt(ppszResult, aosOptions.List());
    1608             : }
    1609             : 
    1610             : /************************************************************************/
    1611             : /*                        OSRExportToPrettyWkt()                        */
    1612             : /************************************************************************/
    1613             : 
    1614             : /**
    1615             :  * \brief Convert this SRS into a nicely formatted WKT 1 string for display to a
    1616             :  * person.
    1617             :  *
    1618             :  * The WKT version can be overridden by using the OSR_WKT_FORMAT configuration
    1619             :  * option. Valid values are the one of the FORMAT option of
    1620             :  * exportToWkt( char ** ppszResult, const char* const* papszOptions ) const
    1621             :  *
    1622             :  * This function is the same as OGRSpatialReference::exportToPrettyWkt().
    1623             :  */
    1624             : 
    1625          56 : OGRErr CPL_STDCALL OSRExportToPrettyWkt(OGRSpatialReferenceH hSRS,
    1626             :                                         char **ppszReturn, int bSimplify)
    1627             : 
    1628             : {
    1629          56 :     VALIDATE_POINTER1(hSRS, "OSRExportToPrettyWkt", OGRERR_FAILURE);
    1630             : 
    1631          56 :     *ppszReturn = nullptr;
    1632             : 
    1633          56 :     return ToPointer(hSRS)->exportToPrettyWkt(ppszReturn, bSimplify);
    1634             : }
    1635             : 
    1636             : /************************************************************************/
    1637             : /*                            exportToWkt()                             */
    1638             : /************************************************************************/
    1639             : 
    1640             : /**
    1641             :  * \brief Convert this SRS into WKT 1 format.
    1642             :  *
    1643             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    1644             :  * Issues</a> page for implementation details of WKT 1 in OGR.
    1645             :  *
    1646             :  * Note that the returned WKT string should be freed with
    1647             :  * CPLFree() when no longer needed.  It is the responsibility of the caller.
    1648             :  *
    1649             :  * The WKT version can be overridden by using the OSR_WKT_FORMAT configuration
    1650             :  * option. Valid values are the one of the FORMAT option of
    1651             :  * exportToWkt( char ** ppszResult, const char* const* papszOptions ) const
    1652             :  *
    1653             :  * This method is the same as the C function OSRExportToWkt().
    1654             :  *
    1655             :  * @param ppszResult the resulting string is returned in this pointer.
    1656             :  *
    1657             :  * @return OGRERR_NONE if successful.
    1658             :  */
    1659             : 
    1660       12204 : OGRErr OGRSpatialReference::exportToWkt(char **ppszResult) const
    1661             : 
    1662             : {
    1663       12204 :     return exportToWkt(ppszResult, nullptr);
    1664             : }
    1665             : 
    1666             : /************************************************************************/
    1667             : /*              GDAL_proj_crs_create_bound_crs_to_WGS84()               */
    1668             : /************************************************************************/
    1669             : 
    1670         570 : static PJ *GDAL_proj_crs_create_bound_crs_to_WGS84(PJ_CONTEXT *ctx, PJ *pj,
    1671             :                                                    bool onlyIfEPSGCode,
    1672             :                                                    bool canModifyHorizPart)
    1673             : {
    1674         570 :     PJ *ret = nullptr;
    1675         570 :     if (proj_get_type(pj) == PJ_TYPE_COMPOUND_CRS)
    1676             :     {
    1677          13 :         auto horizCRS = proj_crs_get_sub_crs(ctx, pj, 0);
    1678          13 :         auto vertCRS = proj_crs_get_sub_crs(ctx, pj, 1);
    1679          13 :         if (horizCRS && proj_get_type(horizCRS) != PJ_TYPE_BOUND_CRS &&
    1680          26 :             vertCRS &&
    1681          10 :             (!onlyIfEPSGCode || proj_get_id_auth_name(horizCRS, 0) != nullptr))
    1682             :         {
    1683             :             auto boundHoriz =
    1684             :                 canModifyHorizPart
    1685           3 :                     ? proj_crs_create_bound_crs_to_WGS84(ctx, horizCRS, nullptr)
    1686           3 :                     : proj_clone(ctx, horizCRS);
    1687             :             auto boundVert =
    1688           3 :                 proj_crs_create_bound_crs_to_WGS84(ctx, vertCRS, nullptr);
    1689           3 :             if (boundHoriz && boundVert)
    1690             :             {
    1691           3 :                 ret = proj_create_compound_crs(ctx, proj_get_name(pj),
    1692             :                                                boundHoriz, boundVert);
    1693             :             }
    1694           3 :             proj_destroy(boundHoriz);
    1695           3 :             proj_destroy(boundVert);
    1696             :         }
    1697          13 :         proj_destroy(horizCRS);
    1698          13 :         proj_destroy(vertCRS);
    1699             :     }
    1700        1074 :     else if (proj_get_type(pj) != PJ_TYPE_BOUND_CRS &&
    1701         517 :              (!onlyIfEPSGCode || proj_get_id_auth_name(pj, 0) != nullptr))
    1702             :     {
    1703         195 :         ret = proj_crs_create_bound_crs_to_WGS84(ctx, pj, nullptr);
    1704             :     }
    1705         570 :     return ret;
    1706             : }
    1707             : 
    1708             : /************************************************************************/
    1709             : /*                            exportToWkt()                             */
    1710             : /************************************************************************/
    1711             : 
    1712             : /**
    1713             :  * Convert this SRS into a WKT string.
    1714             :  *
    1715             :  * Note that the returned WKT string should be freed with
    1716             :  * CPLFree() when no longer needed.  It is the responsibility of the caller.
    1717             :  *
    1718             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    1719             :  * Issues</a> page for implementation details of WKT 1 in OGR.
    1720             :  *
    1721             :  * @param ppszResult the resulting string is returned in this pointer.
    1722             :  * @param papszOptions NULL terminated list of options, or NULL. Currently
    1723             :  * supported options are
    1724             :  * <ul>
    1725             :  * <li>MULTILINE=YES/NO. Defaults to NO.</li>
    1726             :  * <li>FORMAT=SFSQL/WKT1_SIMPLE/WKT1/WKT1_GDAL/WKT1_ESRI/WKT2_2015/WKT2_2018/WKT2/DEFAULT.
    1727             :  *     If SFSQL, a WKT1 string without AXIS, TOWGS84, AUTHORITY or EXTENSION
    1728             :  *     node is returned.
    1729             :  *     If WKT1_SIMPLE, a WKT1 string without AXIS, AUTHORITY or EXTENSION
    1730             :  *     node is returned.
    1731             :  *     WKT1 is an alias of WKT1_GDAL.
    1732             :  *     WKT2 will default to the latest revision implemented (currently
    1733             :  *     WKT2_2018) WKT2_2019 can be used as an alias of WKT2_2018 since GDAL 3.2
    1734             :  * </li>
    1735             :  * <li>ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS=YES/NO. Default is NO. If set
    1736             :  * to YES and FORMAT=WKT1_GDAL, a Geographic 3D CRS or a Projected 3D CRS will
    1737             :  * be exported as a compound CRS whose vertical part represents an ellipsoidal
    1738             :  * height (for example for use with LAS 1.4 WKT1).
    1739             :  * Requires PROJ 7.2.1 and GDAL 3.2.1.</li>
    1740             :  * </ul>
    1741             :  *
    1742             :  * Starting with GDAL 3.0.3, if the OSR_ADD_TOWGS84_ON_EXPORT_TO_WKT1
    1743             :  * configuration option is set to YES, when exporting to WKT1_GDAL, this method
    1744             :  * will try to add a TOWGS84[] node, if there's none attached yet to the SRS and
    1745             :  * if the SRS has a EPSG code. See the AddGuessedTOWGS84() method for how this
    1746             :  * TOWGS84[] node may be added.
    1747             :  *
    1748             :  * @return OGRERR_NONE if successful.
    1749             :  * @since GDAL 3.0
    1750             :  */
    1751             : 
    1752       17293 : OGRErr OGRSpatialReference::exportToWkt(char **ppszResult,
    1753             :                                         const char *const *papszOptions) const
    1754             : {
    1755             :     // In the past calling this method was thread-safe, even if we never
    1756             :     // guaranteed it. Now proj_as_wkt() will cache the result internally,
    1757             :     // so this is no longer thread-safe.
    1758       34586 :     std::lock_guard oLock(d->m_mutex);
    1759             : 
    1760       17293 :     d->refreshProjObj();
    1761       17293 :     if (!d->m_pj_crs)
    1762             :     {
    1763          22 :         *ppszResult = CPLStrdup("");
    1764          22 :         return OGRERR_FAILURE;
    1765             :     }
    1766             : 
    1767       17271 :     if (d->m_bHasCenterLong && d->m_poRoot && !d->m_bMorphToESRI)
    1768             :     {
    1769           0 :         return d->m_poRoot->exportToWkt(ppszResult);
    1770             :     }
    1771             : 
    1772       17271 :     auto ctxt = d->getPROJContext();
    1773       17271 :     auto wktFormat = PJ_WKT1_GDAL;
    1774             :     const char *pszFormat =
    1775       17271 :         CSLFetchNameValueDef(papszOptions, "FORMAT",
    1776             :                              CPLGetConfigOption("OSR_WKT_FORMAT", "DEFAULT"));
    1777       17271 :     if (EQUAL(pszFormat, "DEFAULT"))
    1778       14426 :         pszFormat = "";
    1779             : 
    1780       17271 :     if (EQUAL(pszFormat, "WKT1_ESRI") || d->m_bMorphToESRI)
    1781             :     {
    1782         682 :         wktFormat = PJ_WKT1_ESRI;
    1783             :     }
    1784       16589 :     else if (EQUAL(pszFormat, "WKT1") || EQUAL(pszFormat, "WKT1_GDAL") ||
    1785       15859 :              EQUAL(pszFormat, "WKT1_SIMPLE") || EQUAL(pszFormat, "SFSQL"))
    1786             :     {
    1787         735 :         wktFormat = PJ_WKT1_GDAL;
    1788             :     }
    1789       15854 :     else if (EQUAL(pszFormat, "WKT2_2015"))
    1790             :     {
    1791         365 :         wktFormat = PJ_WKT2_2015;
    1792             :     }
    1793       15489 :     else if (EQUAL(pszFormat, "WKT2") || EQUAL(pszFormat, "WKT2_2018") ||
    1794       15172 :              EQUAL(pszFormat, "WKT2_2019"))
    1795             :     {
    1796        1293 :         wktFormat = PJ_WKT2_2018;
    1797             :     }
    1798       14196 :     else if (pszFormat[0] == '\0')
    1799             :     {
    1800             :         // cppcheck-suppress knownConditionTrueFalse
    1801       14196 :         if (IsDerivedGeographic())
    1802             :         {
    1803           2 :             wktFormat = PJ_WKT2_2018;
    1804             :         }
    1805       27754 :         else if ((IsGeographic() || IsProjected()) && !IsCompound() &&
    1806       13560 :                  GetAxesCount() == 3)
    1807             :         {
    1808          80 :             wktFormat = PJ_WKT2_2018;
    1809             :         }
    1810             :     }
    1811             :     else
    1812             :     {
    1813           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unsupported value for FORMAT");
    1814           0 :         *ppszResult = CPLStrdup("");
    1815           0 :         return OGRERR_FAILURE;
    1816             :     }
    1817             : 
    1818       34542 :     CPLStringList aosOptions;
    1819       17271 :     if (wktFormat != PJ_WKT1_ESRI)
    1820             :     {
    1821       16589 :         aosOptions.SetNameValue("OUTPUT_AXIS", "YES");
    1822             :     }
    1823             :     aosOptions.SetNameValue(
    1824       17271 :         "MULTILINE", CSLFetchNameValueDef(papszOptions, "MULTILINE", "NO"));
    1825             : 
    1826       17271 :     const char *pszAllowEllpsHeightAsVertCS = CSLFetchNameValue(
    1827             :         papszOptions, "ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS");
    1828       17271 :     if (pszAllowEllpsHeightAsVertCS)
    1829             :     {
    1830             :         aosOptions.SetNameValue("ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS",
    1831           0 :                                 pszAllowEllpsHeightAsVertCS);
    1832             :     }
    1833             : 
    1834       17271 :     PJ *boundCRS = nullptr;
    1835       32120 :     if (wktFormat == PJ_WKT1_GDAL &&
    1836       14849 :         CPLTestBool(CSLFetchNameValueDef(
    1837             :             papszOptions, "ADD_TOWGS84_ON_EXPORT_TO_WKT1",
    1838             :             CPLGetConfigOption("OSR_ADD_TOWGS84_ON_EXPORT_TO_WKT1", "NO"))))
    1839             :     {
    1840           0 :         boundCRS = GDAL_proj_crs_create_bound_crs_to_WGS84(
    1841           0 :             d->getPROJContext(), d->m_pj_crs, true, true);
    1842             :     }
    1843             : 
    1844       34542 :     CPLErrorAccumulator oErrorAccumulator;
    1845             :     const char *pszWKT;
    1846             :     {
    1847       17271 :         auto oAccumulator = oErrorAccumulator.InstallForCurrentScope();
    1848       17271 :         CPL_IGNORE_RET_VAL(oAccumulator);
    1849       17271 :         pszWKT = proj_as_wkt(ctxt, boundCRS ? boundCRS : d->m_pj_crs, wktFormat,
    1850       17271 :                              aosOptions.List());
    1851             :     }
    1852       17273 :     for (const auto &oError : oErrorAccumulator.GetErrors())
    1853             :     {
    1854          32 :         if (pszFormat[0] == '\0' &&
    1855          14 :             (oError.msg.find("Unsupported conversion method") !=
    1856           2 :                  std::string::npos ||
    1857           2 :              oError.msg.find("can only be exported to WKT2") !=
    1858           0 :                  std::string::npos ||
    1859           0 :              oError.msg.find("can only be exported since WKT2:2019") !=
    1860             :                  std::string::npos))
    1861             :         {
    1862          14 :             CPLErrorReset();
    1863             :             // If we cannot export in the default mode (WKT1), retry with WKT2
    1864          14 :             pszWKT = proj_as_wkt(ctxt, boundCRS ? boundCRS : d->m_pj_crs,
    1865          14 :                                  PJ_WKT2_2018, aosOptions.List());
    1866          14 :             break;
    1867             :         }
    1868           2 :         CPLError(oError.type, oError.no, "%s", oError.msg.c_str());
    1869             :     }
    1870             : 
    1871       17271 :     if (!pszWKT)
    1872             :     {
    1873           2 :         *ppszResult = CPLStrdup("");
    1874           2 :         proj_destroy(boundCRS);
    1875           2 :         return OGRERR_FAILURE;
    1876             :     }
    1877             : 
    1878       17269 :     if (EQUAL(pszFormat, "SFSQL") || EQUAL(pszFormat, "WKT1_SIMPLE"))
    1879             :     {
    1880           5 :         OGR_SRSNode oRoot;
    1881           5 :         oRoot.importFromWkt(&pszWKT);
    1882           5 :         oRoot.StripNodes("AXIS");
    1883           5 :         if (EQUAL(pszFormat, "SFSQL"))
    1884             :         {
    1885           3 :             oRoot.StripNodes("TOWGS84");
    1886             :         }
    1887           5 :         oRoot.StripNodes("AUTHORITY");
    1888           5 :         oRoot.StripNodes("EXTENSION");
    1889             :         OGRErr eErr;
    1890           5 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "MULTILINE", "NO")))
    1891           2 :             eErr = oRoot.exportToPrettyWkt(ppszResult, 1);
    1892             :         else
    1893           3 :             eErr = oRoot.exportToWkt(ppszResult);
    1894           5 :         proj_destroy(boundCRS);
    1895           5 :         return eErr;
    1896             :     }
    1897             : 
    1898       17264 :     *ppszResult = CPLStrdup(pszWKT);
    1899             : 
    1900             : #if !(PROJ_AT_LEAST_VERSION(9, 5, 0))
    1901       17264 :     if (wktFormat == PJ_WKT2_2018)
    1902             :     {
    1903             :         // Works around bug fixed per https://github.com/OSGeo/PROJ/pull/4166
    1904             :         // related to a wrong EPSG code assigned to UTM South conversions
    1905        1375 :         char *pszPtr = strstr(*ppszResult, "CONVERSION[\"UTM zone ");
    1906        1375 :         if (pszPtr)
    1907             :         {
    1908         353 :             pszPtr += strlen("CONVERSION[\"UTM zone ");
    1909         353 :             const int nZone = atoi(pszPtr);
    1910        1058 :             while (*pszPtr >= '0' && *pszPtr <= '9')
    1911         705 :                 ++pszPtr;
    1912         353 :             if (nZone >= 1 && nZone <= 60 && *pszPtr == 'S' &&
    1913           1 :                 pszPtr[1] == '"' && pszPtr[2] == ',')
    1914             :             {
    1915           1 :                 pszPtr += 3;
    1916           1 :                 int nLevel = 0;
    1917           1 :                 bool bInString = false;
    1918             :                 // Find the ID node corresponding to this CONVERSION node
    1919         480 :                 while (*pszPtr)
    1920             :                 {
    1921         480 :                     if (bInString)
    1922             :                     {
    1923         197 :                         if (*pszPtr == '"' && pszPtr[1] == '"')
    1924             :                         {
    1925           0 :                             ++pszPtr;
    1926             :                         }
    1927         197 :                         else if (*pszPtr == '"')
    1928             :                         {
    1929          17 :                             bInString = false;
    1930             :                         }
    1931             :                     }
    1932         283 :                     else if (nLevel == 0 && STARTS_WITH_CI(pszPtr, "ID["))
    1933             :                     {
    1934           1 :                         if (STARTS_WITH_CI(pszPtr, CPLSPrintf("ID[\"EPSG\",%d]",
    1935             :                                                               17000 + nZone)))
    1936             :                         {
    1937           1 :                             CPLAssert(pszPtr[11] == '7');
    1938           1 :                             CPLAssert(pszPtr[12] == '0');
    1939           1 :                             pszPtr[11] = '6';
    1940           1 :                             pszPtr[12] = '1';
    1941             :                         }
    1942           1 :                         break;
    1943             :                     }
    1944         282 :                     else if (*pszPtr == '"')
    1945             :                     {
    1946          17 :                         bInString = true;
    1947             :                     }
    1948         265 :                     else if (*pszPtr == '[')
    1949             :                     {
    1950          17 :                         ++nLevel;
    1951             :                     }
    1952         248 :                     else if (*pszPtr == ']')
    1953             :                     {
    1954          17 :                         --nLevel;
    1955             :                     }
    1956             : 
    1957         479 :                     ++pszPtr;
    1958             :                 }
    1959             :             }
    1960             :         }
    1961             :     }
    1962             : #endif
    1963             : 
    1964       17264 :     proj_destroy(boundCRS);
    1965       17264 :     return OGRERR_NONE;
    1966             : }
    1967             : 
    1968             : /************************************************************************/
    1969             : /*                            exportToWkt()                             */
    1970             : /************************************************************************/
    1971             : 
    1972             : /**
    1973             :  * Convert this SRS into a WKT string.
    1974             :  *
    1975             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    1976             :  * Issues</a> page for implementation details of WKT 1 in OGR.
    1977             :  *
    1978             :  * @param papszOptions NULL terminated list of options, or NULL. Currently
    1979             :  * supported options are
    1980             :  * <ul>
    1981             :  * <li>MULTILINE=YES/NO. Defaults to NO.</li>
    1982             :  * <li>FORMAT=SFSQL/WKT1_SIMPLE/WKT1/WKT1_GDAL/WKT1_ESRI/WKT2_2015/WKT2_2018/WKT2/DEFAULT.
    1983             :  *     If SFSQL, a WKT1 string without AXIS, TOWGS84, AUTHORITY or EXTENSION
    1984             :  *     node is returned.
    1985             :  *     If WKT1_SIMPLE, a WKT1 string without AXIS, AUTHORITY or EXTENSION
    1986             :  *     node is returned.
    1987             :  *     WKT1 is an alias of WKT1_GDAL.
    1988             :  *     WKT2 will default to the latest revision implemented (currently
    1989             :  *     WKT2_2019)
    1990             :  * </li>
    1991             :  * <li>ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS=YES/NO. Default is NO. If set
    1992             :  * to YES and FORMAT=WKT1_GDAL, a Geographic 3D CRS or a Projected 3D CRS will
    1993             :  * be exported as a compound CRS whose vertical part represents an ellipsoidal
    1994             :  * height (for example for use with LAS 1.4 WKT1).
    1995             :  * Requires PROJ 7.2.1.</li>
    1996             :  * </ul>
    1997             :  *
    1998             :  * If the OSR_ADD_TOWGS84_ON_EXPORT_TO_WKT1
    1999             :  * configuration option is set to YES, when exporting to WKT1_GDAL, this method
    2000             :  * will try to add a TOWGS84[] node, if there's none attached yet to the SRS and
    2001             :  * if the SRS has a EPSG code. See the AddGuessedTOWGS84() method for how this
    2002             :  * TOWGS84[] node may be added.
    2003             :  *
    2004             :  * @return a non-empty string if successful.
    2005             :  * @since GDAL 3.9
    2006             :  */
    2007             : 
    2008             : std::string
    2009         774 : OGRSpatialReference::exportToWkt(const char *const *papszOptions) const
    2010             : {
    2011         774 :     std::string osWKT;
    2012         774 :     char *pszWKT = nullptr;
    2013         774 :     if (exportToWkt(&pszWKT, papszOptions) == OGRERR_NONE)
    2014         760 :         osWKT = pszWKT;
    2015         774 :     CPLFree(pszWKT);
    2016        1548 :     return osWKT;
    2017             : }
    2018             : 
    2019             : /************************************************************************/
    2020             : /*                           OSRExportToWkt()                           */
    2021             : /************************************************************************/
    2022             : 
    2023             : /**
    2024             :  * \brief Convert this SRS into WKT 1 format.
    2025             :  *
    2026             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    2027             :  * Issues</a> page for implementation details of WKT in OGR.
    2028             :  *
    2029             :  * The WKT version can be overridden by using the OSR_WKT_FORMAT configuration
    2030             :  * option. Valid values are the one of the FORMAT option of
    2031             :  * exportToWkt( char ** ppszResult, const char* const* papszOptions ) const
    2032             :  *
    2033             :  * This function is the same as OGRSpatialReference::exportToWkt().
    2034             :  */
    2035             : 
    2036        1081 : OGRErr CPL_STDCALL OSRExportToWkt(OGRSpatialReferenceH hSRS, char **ppszReturn)
    2037             : 
    2038             : {
    2039        1081 :     VALIDATE_POINTER1(hSRS, "OSRExportToWkt", OGRERR_FAILURE);
    2040             : 
    2041        1081 :     *ppszReturn = nullptr;
    2042             : 
    2043        1081 :     return ToPointer(hSRS)->exportToWkt(ppszReturn);
    2044             : }
    2045             : 
    2046             : /************************************************************************/
    2047             : /*                          OSRExportToWktEx()                          */
    2048             : /************************************************************************/
    2049             : 
    2050             : /**
    2051             :  * \brief Convert this SRS into WKT format.
    2052             :  *
    2053             :  * This function is the same as OGRSpatialReference::exportToWkt(char **
    2054             :  * ppszResult,const char* const* papszOptions ) const
    2055             :  *
    2056             :  * @since GDAL 3.0
    2057             :  */
    2058             : 
    2059        1307 : OGRErr OSRExportToWktEx(OGRSpatialReferenceH hSRS, char **ppszReturn,
    2060             :                         const char *const *papszOptions)
    2061             : {
    2062        1307 :     VALIDATE_POINTER1(hSRS, "OSRExportToWktEx", OGRERR_FAILURE);
    2063             : 
    2064        1307 :     *ppszReturn = nullptr;
    2065             : 
    2066        1307 :     return ToPointer(hSRS)->exportToWkt(ppszReturn, papszOptions);
    2067             : }
    2068             : 
    2069             : /************************************************************************/
    2070             : /*                          exportToPROJJSON()                          */
    2071             : /************************************************************************/
    2072             : 
    2073             : /**
    2074             :  * Convert this SRS into a PROJJSON string.
    2075             :  *
    2076             :  * Note that the returned JSON string should be freed with
    2077             :  * CPLFree() when no longer needed.  It is the responsibility of the caller.
    2078             :  *
    2079             :  * @param ppszResult the resulting string is returned in this pointer.
    2080             :  * @param papszOptions NULL terminated list of options, or NULL. Currently
    2081             :  * supported options are
    2082             :  * <ul>
    2083             :  * <li>MULTILINE=YES/NO. Defaults to YES</li>
    2084             :  * <li>INDENTATION_WIDTH=number. Defaults to 2 (when multiline output is
    2085             :  * on).</li>
    2086             :  * <li>SCHEMA=string. URL to PROJJSON schema. Can be set to empty string to
    2087             :  * disable it.</li>
    2088             :  * </ul>
    2089             :  *
    2090             :  * @return OGRERR_NONE if successful.
    2091             :  * @since GDAL 3.1 and PROJ 6.2
    2092             :  */
    2093             : 
    2094        3012 : OGRErr OGRSpatialReference::exportToPROJJSON(
    2095             :     char **ppszResult, CPL_UNUSED const char *const *papszOptions) const
    2096             : {
    2097        6024 :     TAKE_OPTIONAL_LOCK();
    2098             : 
    2099        3012 :     d->refreshProjObj();
    2100        3012 :     if (!d->m_pj_crs)
    2101             :     {
    2102           1 :         *ppszResult = nullptr;
    2103           1 :         return OGRERR_FAILURE;
    2104             :     }
    2105             : 
    2106             :     const char *pszPROJJSON =
    2107        3011 :         proj_as_projjson(d->getPROJContext(), d->m_pj_crs, papszOptions);
    2108             : 
    2109        3011 :     if (!pszPROJJSON)
    2110             :     {
    2111           0 :         *ppszResult = CPLStrdup("");
    2112           0 :         return OGRERR_FAILURE;
    2113             :     }
    2114             : 
    2115        3011 :     *ppszResult = CPLStrdup(pszPROJJSON);
    2116             : 
    2117             : #if !(PROJ_AT_LEAST_VERSION(9, 5, 0))
    2118             :     {
    2119             :         // Works around bug fixed per https://github.com/OSGeo/PROJ/pull/4166
    2120             :         // related to a wrong EPSG code assigned to UTM South conversions
    2121        3011 :         char *pszPtr = strstr(*ppszResult, "\"name\": \"UTM zone ");
    2122        3011 :         if (pszPtr)
    2123             :         {
    2124         261 :             pszPtr += strlen("\"name\": \"UTM zone ");
    2125         261 :             const int nZone = atoi(pszPtr);
    2126         782 :             while (*pszPtr >= '0' && *pszPtr <= '9')
    2127         521 :                 ++pszPtr;
    2128         261 :             if (nZone >= 1 && nZone <= 60 && *pszPtr == 'S' && pszPtr[1] == '"')
    2129             :             {
    2130           4 :                 pszPtr += 2;
    2131           4 :                 int nLevel = 0;
    2132           4 :                 bool bInString = false;
    2133             :                 // Find the id node corresponding to this conversion node
    2134        5299 :                 while (*pszPtr)
    2135             :                 {
    2136        5299 :                     if (bInString)
    2137             :                     {
    2138        1950 :                         if (*pszPtr == '\\')
    2139             :                         {
    2140           0 :                             ++pszPtr;
    2141             :                         }
    2142        1950 :                         else if (*pszPtr == '"')
    2143             :                         {
    2144         244 :                             bInString = false;
    2145             :                         }
    2146             :                     }
    2147        3349 :                     else if (nLevel == 0 && STARTS_WITH(pszPtr, "\"id\": {"))
    2148             :                     {
    2149           4 :                         const char *pszNextEndCurl = strchr(pszPtr, '}');
    2150             :                         const char *pszAuthEPSG =
    2151           4 :                             strstr(pszPtr, "\"authority\": \"EPSG\"");
    2152           4 :                         char *pszCode = strstr(
    2153             :                             pszPtr, CPLSPrintf("\"code\": %d", 17000 + nZone));
    2154           4 :                         if (pszAuthEPSG && pszCode && pszNextEndCurl &&
    2155           4 :                             pszNextEndCurl - pszAuthEPSG > 0 &&
    2156           4 :                             pszNextEndCurl - pszCode > 0)
    2157             :                         {
    2158           4 :                             CPLAssert(pszCode[9] == '7');
    2159           4 :                             CPLAssert(pszCode[10] == '0');
    2160           4 :                             pszCode[9] = '6';
    2161           4 :                             pszCode[10] = '1';
    2162             :                         }
    2163           4 :                         break;
    2164             :                     }
    2165        3345 :                     else if (*pszPtr == '"')
    2166             :                     {
    2167         244 :                         bInString = true;
    2168             :                     }
    2169        3101 :                     else if (*pszPtr == '{' || *pszPtr == '[')
    2170             :                     {
    2171          60 :                         ++nLevel;
    2172             :                     }
    2173        3041 :                     else if (*pszPtr == '}' || *pszPtr == ']')
    2174             :                     {
    2175          60 :                         --nLevel;
    2176             :                     }
    2177             : 
    2178        5295 :                     ++pszPtr;
    2179             :                 }
    2180             :             }
    2181             :         }
    2182             :     }
    2183             : #endif
    2184             : 
    2185        3011 :     return OGRERR_NONE;
    2186             : }
    2187             : 
    2188             : /************************************************************************/
    2189             : /*                        OSRExportToPROJJSON()                         */
    2190             : /************************************************************************/
    2191             : 
    2192             : /**
    2193             :  * \brief Convert this SRS into PROJJSON format.
    2194             :  *
    2195             :  * This function is the same as OGRSpatialReference::exportToPROJJSON() const
    2196             :  *
    2197             :  * @since GDAL 3.1 and PROJ 6.2
    2198             :  */
    2199             : 
    2200           2 : OGRErr OSRExportToPROJJSON(OGRSpatialReferenceH hSRS, char **ppszReturn,
    2201             :                            const char *const *papszOptions)
    2202             : {
    2203           2 :     VALIDATE_POINTER1(hSRS, "OSRExportToPROJJSON", OGRERR_FAILURE);
    2204             : 
    2205           2 :     *ppszReturn = nullptr;
    2206             : 
    2207           2 :     return ToPointer(hSRS)->exportToPROJJSON(ppszReturn, papszOptions);
    2208             : }
    2209             : 
    2210             : /************************************************************************/
    2211             : /*                           importFromWkt()                            */
    2212             : /************************************************************************/
    2213             : 
    2214             : /**
    2215             :  * \brief Import from WKT string.
    2216             :  *
    2217             :  * This method will wipe the existing SRS definition, and
    2218             :  * reassign it based on the contents of the passed WKT string.  Only as
    2219             :  * much of the input string as needed to construct this SRS is consumed from
    2220             :  * the input string, and the input string pointer
    2221             :  * is then updated to point to the remaining (unused) input.
    2222             :  *
    2223             :  * Starting with PROJ 9.2, if invoked on a COORDINATEMETADATA[] construct,
    2224             :  * the CRS contained in it will be used to fill the OGRSpatialReference object,
    2225             :  * and the coordinate epoch potentially present used as the coordinate epoch
    2226             :  * property of the OGRSpatialReference object.
    2227             :  *
    2228             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    2229             :  * Issues</a> page for implementation details of WKT in OGR.
    2230             :  *
    2231             :  * This method is the same as the C function OSRImportFromWkt().
    2232             :  *
    2233             :  * @param ppszInput Pointer to pointer to input.  The pointer is updated to
    2234             :  * point to remaining unused input text.
    2235             :  *
    2236             :  * @return OGRERR_NONE if import succeeds, or OGRERR_CORRUPT_DATA if it
    2237             :  * fails for any reason.
    2238             :  */
    2239             : 
    2240       20930 : OGRErr OGRSpatialReference::importFromWkt(const char **ppszInput)
    2241             : 
    2242             : {
    2243       20930 :     return importFromWkt(ppszInput, nullptr);
    2244             : }
    2245             : 
    2246             : /************************************************************************/
    2247             : /*                           importFromWkt()                            */
    2248             : /************************************************************************/
    2249             : 
    2250             : /*! @cond Doxygen_Suppress */
    2251             : 
    2252          21 : OGRErr OGRSpatialReference::importFromWkt(const char *pszInput,
    2253             :                                           CSLConstList papszOptions)
    2254             : 
    2255             : {
    2256          21 :     return importFromWkt(&pszInput, papszOptions);
    2257             : }
    2258             : 
    2259       20951 : OGRErr OGRSpatialReference::importFromWkt(const char **ppszInput,
    2260             :                                           CSLConstList papszOptions)
    2261             : 
    2262             : {
    2263       41902 :     TAKE_OPTIONAL_LOCK();
    2264             : 
    2265       20951 :     if (!ppszInput || !*ppszInput)
    2266           0 :         return OGRERR_FAILURE;
    2267             : 
    2268       20951 :     if (strlen(*ppszInput) > 100 * 1000 &&
    2269           0 :         CPLTestBool(CPLGetConfigOption("OSR_IMPORT_FROM_WKT_LIMIT", "YES")))
    2270             :     {
    2271           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2272             :                  "Suspiciously large input for importFromWkt(). Rejecting it. "
    2273             :                  "You can remove this limitation by definition the "
    2274             :                  "OSR_IMPORT_FROM_WKT_LIMIT configuration option to NO.");
    2275           0 :         return OGRERR_FAILURE;
    2276             :     }
    2277             : 
    2278       20951 :     Clear();
    2279             : 
    2280       20951 :     bool canCache = false;
    2281       20951 :     auto tlsCache = OSRGetProjTLSCache();
    2282       41902 :     std::string osWkt;
    2283       20951 :     if (**ppszInput)
    2284             :     {
    2285       20396 :         osWkt = *ppszInput;
    2286       20396 :         auto cachedObj = tlsCache->GetPJForWKT(osWkt);
    2287       20396 :         if (cachedObj)
    2288             :         {
    2289       18452 :             d->setPjCRS(cachedObj);
    2290             :         }
    2291             :         else
    2292             :         {
    2293        3888 :             CPLStringList aosOptions(papszOptions);
    2294        1944 :             if (aosOptions.FetchNameValue("STRICT") == nullptr)
    2295        1944 :                 aosOptions.SetNameValue("STRICT", "NO");
    2296        1944 :             PROJ_STRING_LIST warnings = nullptr;
    2297        1944 :             PROJ_STRING_LIST errors = nullptr;
    2298        1944 :             auto ctxt = d->getPROJContext();
    2299        1944 :             auto pj = proj_create_from_wkt(ctxt, *ppszInput, aosOptions.List(),
    2300             :                                            &warnings, &errors);
    2301        1944 :             d->setPjCRS(pj);
    2302             : 
    2303        1998 :             for (auto iter = warnings; iter && *iter; ++iter)
    2304             :             {
    2305          54 :                 d->m_wktImportWarnings.push_back(*iter);
    2306             :             }
    2307        2181 :             for (auto iter = errors; iter && *iter; ++iter)
    2308             :             {
    2309         237 :                 d->m_wktImportErrors.push_back(*iter);
    2310         237 :                 if (!d->m_pj_crs)
    2311             :                 {
    2312          34 :                     CPLError(CE_Failure, CPLE_AppDefined, "%s", *iter);
    2313             :                 }
    2314             :             }
    2315        1944 :             if (warnings == nullptr && errors == nullptr)
    2316             :             {
    2317        1662 :                 canCache = true;
    2318             :             }
    2319        1944 :             proj_string_list_destroy(warnings);
    2320        1944 :             proj_string_list_destroy(errors);
    2321             :         }
    2322             :     }
    2323       20951 :     if (!d->m_pj_crs)
    2324         589 :         return OGRERR_CORRUPT_DATA;
    2325             : 
    2326             :     // Only accept CRS objects
    2327       20362 :     if (!proj_is_crs(d->m_pj_crs))
    2328             :     {
    2329           0 :         Clear();
    2330           0 :         return OGRERR_CORRUPT_DATA;
    2331             :     }
    2332             : 
    2333       20362 :     if (canCache)
    2334             :     {
    2335        1662 :         tlsCache->CachePJForWKT(osWkt, d->m_pj_crs);
    2336             :     }
    2337             : 
    2338       20362 :     if (strstr(*ppszInput, "CENTER_LONG"))
    2339             :     {
    2340           0 :         auto poRoot = new OGR_SRSNode();
    2341           0 :         d->setRoot(poRoot);
    2342           0 :         const char *pszTmp = *ppszInput;
    2343           0 :         poRoot->importFromWkt(&pszTmp);
    2344           0 :         d->m_bHasCenterLong = true;
    2345             :     }
    2346             : 
    2347             :     // TODO? we don't really update correctly since we assume that the
    2348             :     // passed string is only WKT.
    2349       20362 :     *ppszInput += strlen(*ppszInput);
    2350       20362 :     return OGRERR_NONE;
    2351             : 
    2352             : #if no_longer_implemented_for_now
    2353             :     /* -------------------------------------------------------------------- */
    2354             :     /*      The following seems to try and detect and unconsumed            */
    2355             :     /*      VERTCS[] coordinate system definition (ESRI style) and to       */
    2356             :     /*      import and attach it to the existing root.  Likely we will      */
    2357             :     /*      need to extend this somewhat to bring it into an acceptable     */
    2358             :     /*      OGRSpatialReference organization at some point.                 */
    2359             :     /* -------------------------------------------------------------------- */
    2360             :     if (strlen(*ppszInput) > 0 && strstr(*ppszInput, "VERTCS"))
    2361             :     {
    2362             :         if (((*ppszInput)[0]) == ',')
    2363             :             (*ppszInput)++;
    2364             :         OGR_SRSNode *poNewChild = new OGR_SRSNode();
    2365             :         poRoot->AddChild(poNewChild);
    2366             :         return poNewChild->importFromWkt(ppszInput);
    2367             :     }
    2368             : #endif
    2369             : }
    2370             : 
    2371             : /*! @endcond */
    2372             : 
    2373             : /**
    2374             :  * \brief Import from WKT string.
    2375             :  *
    2376             :  * This method will wipe the existing SRS definition, and
    2377             :  * reassign it based on the contents of the passed WKT string.  Only as
    2378             :  * much of the input string as needed to construct this SRS is consumed from
    2379             :  * the input string, and the input string pointer
    2380             :  * is then updated to point to the remaining (unused) input.
    2381             :  *
    2382             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    2383             :  * Issues</a> page for implementation details of WKT in OGR.
    2384             :  *
    2385             :  * This method is the same as the C function OSRImportFromWkt().
    2386             :  *
    2387             :  * @param ppszInput Pointer to pointer to input.  The pointer is updated to
    2388             :  * point to remaining unused input text.
    2389             :  *
    2390             :  * @return OGRERR_NONE if import succeeds, or OGRERR_CORRUPT_DATA if it
    2391             :  * fails for any reason.
    2392             :  * @deprecated Use importFromWkt(const char**) or importFromWkt(const
    2393             :  * char*)
    2394             :  */
    2395             : 
    2396           0 : OGRErr OGRSpatialReference::importFromWkt(char **ppszInput)
    2397             : 
    2398             : {
    2399           0 :     return importFromWkt(const_cast<const char **>(ppszInput));
    2400             : }
    2401             : 
    2402             : /**
    2403             :  * \brief Import from WKT string.
    2404             :  *
    2405             :  * This method will wipe the existing SRS definition, and
    2406             :  * reassign it based on the contents of the passed WKT string.  Only as
    2407             :  * much of the input string as needed to construct this SRS is consumed from
    2408             :  * the input string, and the input string pointer
    2409             :  * is then updated to point to the remaining (unused) input.
    2410             :  *
    2411             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    2412             :  * Issues</a> page for implementation details of WKT in OGR.
    2413             :  *
    2414             :  * @param pszInput Input WKT
    2415             :  *
    2416             :  * @return OGRERR_NONE if import succeeds, or OGRERR_CORRUPT_DATA if it
    2417             :  * fails for any reason.
    2418             :  */
    2419             : 
    2420       20667 : OGRErr OGRSpatialReference::importFromWkt(const char *pszInput)
    2421             : {
    2422       20667 :     return importFromWkt(&pszInput);
    2423             : }
    2424             : 
    2425             : /************************************************************************/
    2426             : /*                              Validate()                              */
    2427             : /************************************************************************/
    2428             : 
    2429             : /**
    2430             :  * \brief Validate CRS imported with importFromWkt() or with modified with
    2431             :  * direct node manipulations. Otherwise the CRS should be always valid.
    2432             :  *
    2433             :  * This method attempts to verify that the spatial reference system is
    2434             :  * well formed, and consists of known tokens.  The validation is not
    2435             :  * comprehensive.
    2436             :  *
    2437             :  * This method is the same as the C function OSRValidate().
    2438             :  *
    2439             :  * @return OGRERR_NONE if all is fine, OGRERR_CORRUPT_DATA if the SRS is
    2440             :  * not well formed, and OGRERR_UNSUPPORTED_SRS if the SRS is well formed,
    2441             :  * but contains non-standard PROJECTION[] values.
    2442             :  */
    2443             : 
    2444         116 : OGRErr OGRSpatialReference::Validate() const
    2445             : 
    2446             : {
    2447         232 :     TAKE_OPTIONAL_LOCK();
    2448             : 
    2449         154 :     for (const auto &str : d->m_wktImportErrors)
    2450             :     {
    2451          38 :         CPLDebug("OGRSpatialReference::Validate", "%s", str.c_str());
    2452             :     }
    2453         116 :     for (const auto &str : d->m_wktImportWarnings)
    2454             :     {
    2455           0 :         CPLDebug("OGRSpatialReference::Validate", "%s", str.c_str());
    2456             :     }
    2457         116 :     if (!d->m_pj_crs || !d->m_wktImportErrors.empty())
    2458             :     {
    2459          37 :         return OGRERR_CORRUPT_DATA;
    2460             :     }
    2461          79 :     if (!d->m_wktImportWarnings.empty())
    2462             :     {
    2463           0 :         return OGRERR_UNSUPPORTED_SRS;
    2464             :     }
    2465          79 :     return OGRERR_NONE;
    2466             : }
    2467             : 
    2468             : /************************************************************************/
    2469             : /*                            OSRValidate()                             */
    2470             : /************************************************************************/
    2471             : /**
    2472             :  * \brief Validate SRS tokens.
    2473             :  *
    2474             :  * This function is the same as the C++ method OGRSpatialReference::Validate().
    2475             :  */
    2476         114 : OGRErr OSRValidate(OGRSpatialReferenceH hSRS)
    2477             : 
    2478             : {
    2479         114 :     VALIDATE_POINTER1(hSRS, "OSRValidate", OGRERR_FAILURE);
    2480             : 
    2481         114 :     return OGRSpatialReference::FromHandle(hSRS)->Validate();
    2482             : }
    2483             : 
    2484             : /************************************************************************/
    2485             : /*                          OSRImportFromWkt()                          */
    2486             : /************************************************************************/
    2487             : 
    2488             : /**
    2489             :  * \brief Import from WKT string.
    2490             :  *
    2491             :  * Consult also the <a href="wktproblems.html">OGC WKT Coordinate System
    2492             :  * Issues</a> page for implementation details of WKT in OGR.
    2493             :  *
    2494             :  * This function is the same as OGRSpatialReference::importFromWkt().
    2495             :  */
    2496             : 
    2497         263 : OGRErr OSRImportFromWkt(OGRSpatialReferenceH hSRS, char **ppszInput)
    2498             : 
    2499             : {
    2500         263 :     VALIDATE_POINTER1(hSRS, "OSRImportFromWkt", OGRERR_FAILURE);
    2501             : 
    2502         263 :     return ToPointer(hSRS)->importFromWkt(const_cast<const char **>(ppszInput));
    2503             : }
    2504             : 
    2505             : /************************************************************************/
    2506             : /*                              SetNode()                               */
    2507             : /************************************************************************/
    2508             : 
    2509             : /**
    2510             :  * \brief Set attribute value in spatial reference.
    2511             :  *
    2512             :  * Missing intermediate nodes in the path will be created if not already
    2513             :  * in existence.  If the attribute has no children one will be created and
    2514             :  * assigned the value otherwise the zeroth child will be assigned the value.
    2515             :  *
    2516             :  * This method does the same as the C function OSRSetAttrValue().
    2517             :  *
    2518             :  * @param pszNodePath full path to attribute to be set.  For instance
    2519             :  * "PROJCS|GEOGCS|UNIT".
    2520             :  *
    2521             :  * @param pszNewNodeValue value to be assigned to node, such as "meter".
    2522             :  * This may be NULL if you just want to force creation of the intermediate
    2523             :  * path.
    2524             :  *
    2525             :  * @return OGRERR_NONE on success.
    2526             :  */
    2527             : 
    2528         583 : OGRErr OGRSpatialReference::SetNode(const char *pszNodePath,
    2529             :                                     const char *pszNewNodeValue)
    2530             : 
    2531             : {
    2532        1166 :     TAKE_OPTIONAL_LOCK();
    2533             : 
    2534             :     char **papszPathTokens =
    2535         583 :         CSLTokenizeStringComplex(pszNodePath, "|", TRUE, FALSE);
    2536             : 
    2537         583 :     if (CSLCount(papszPathTokens) < 1)
    2538             :     {
    2539           0 :         CSLDestroy(papszPathTokens);
    2540           0 :         return OGRERR_FAILURE;
    2541             :     }
    2542             : 
    2543        1017 :     if (GetRoot() == nullptr ||
    2544         434 :         !EQUAL(papszPathTokens[0], GetRoot()->GetValue()))
    2545             :     {
    2546         269 :         if (EQUAL(papszPathTokens[0], "PROJCS") &&
    2547         116 :             CSLCount(papszPathTokens) == 1)
    2548             :         {
    2549         116 :             CSLDestroy(papszPathTokens);
    2550         116 :             return SetProjCS(pszNewNodeValue);
    2551             :         }
    2552             :         else
    2553             :         {
    2554          37 :             SetRoot(new OGR_SRSNode(papszPathTokens[0]));
    2555             :         }
    2556             :     }
    2557             : 
    2558         467 :     OGR_SRSNode *poNode = GetRoot();
    2559         724 :     for (int i = 1; papszPathTokens[i] != nullptr; i++)
    2560             :     {
    2561         257 :         int j = 0;  // Used after for.
    2562             : 
    2563         642 :         for (; j < poNode->GetChildCount(); j++)
    2564             :         {
    2565         582 :             if (EQUAL(poNode->GetChild(j)->GetValue(), papszPathTokens[i]))
    2566             :             {
    2567         197 :                 poNode = poNode->GetChild(j);
    2568         197 :                 j = -1;
    2569         197 :                 break;
    2570             :             }
    2571             :         }
    2572             : 
    2573         257 :         if (j != -1)
    2574             :         {
    2575          60 :             OGR_SRSNode *poNewNode = new OGR_SRSNode(papszPathTokens[i]);
    2576          60 :             poNode->AddChild(poNewNode);
    2577          60 :             poNode = poNewNode;
    2578             :         }
    2579             :     }
    2580             : 
    2581         467 :     CSLDestroy(papszPathTokens);
    2582             : 
    2583         467 :     if (pszNewNodeValue != nullptr)
    2584             :     {
    2585         467 :         if (poNode->GetChildCount() > 0)
    2586         370 :             poNode->GetChild(0)->SetValue(pszNewNodeValue);
    2587             :         else
    2588          97 :             poNode->AddChild(new OGR_SRSNode(pszNewNodeValue));
    2589             :     };
    2590         467 :     return OGRERR_NONE;
    2591             : }
    2592             : 
    2593             : /************************************************************************/
    2594             : /*                          OSRSetAttrValue()                           */
    2595             : /************************************************************************/
    2596             : 
    2597             : /**
    2598             :  * \brief Set attribute value in spatial reference.
    2599             :  *
    2600             :  * This function is the same as OGRSpatialReference::SetNode()
    2601             :  */
    2602           1 : OGRErr CPL_STDCALL OSRSetAttrValue(OGRSpatialReferenceH hSRS,
    2603             :                                    const char *pszPath, const char *pszValue)
    2604             : 
    2605             : {
    2606           1 :     VALIDATE_POINTER1(hSRS, "OSRSetAttrValue", OGRERR_FAILURE);
    2607             : 
    2608           1 :     return ToPointer(hSRS)->SetNode(pszPath, pszValue);
    2609             : }
    2610             : 
    2611             : /************************************************************************/
    2612             : /*                              SetNode()                               */
    2613             : /************************************************************************/
    2614             : 
    2615             : /**
    2616             :  * \brief Set attribute value in spatial reference.
    2617             :  *
    2618             :  * Missing intermediate nodes in the path will be created if not already
    2619             :  * in existence.  If the attribute has no children one will be created and
    2620             :  * assigned the value otherwise the zeroth child will be assigned the value.
    2621             :  *
    2622             :  * This method does the same as the C function OSRSetAttrValue().
    2623             :  *
    2624             :  * @param pszNodePath full path to attribute to be set.  For instance
    2625             :  * "PROJCS|GEOGCS|UNIT".
    2626             :  *
    2627             :  * @param dfValue value to be assigned to node.
    2628             :  *
    2629             :  * @return OGRERR_NONE on success.
    2630             :  */
    2631             : 
    2632           0 : OGRErr OGRSpatialReference::SetNode(const char *pszNodePath, double dfValue)
    2633             : 
    2634             : {
    2635           0 :     char szValue[64] = {'\0'};
    2636             : 
    2637           0 :     if (std::abs(dfValue - static_cast<int>(dfValue)) == 0.0)
    2638           0 :         snprintf(szValue, sizeof(szValue), "%d", static_cast<int>(dfValue));
    2639             :     else
    2640           0 :         OGRsnPrintDouble(szValue, sizeof(szValue), dfValue);
    2641             : 
    2642           0 :     return SetNode(pszNodePath, szValue);
    2643             : }
    2644             : 
    2645             : /************************************************************************/
    2646             : /*                          SetAngularUnits()                           */
    2647             : /************************************************************************/
    2648             : 
    2649             : /**
    2650             :  * \brief Set the angular units for the geographic coordinate system.
    2651             :  *
    2652             :  * This method creates a UNIT subnode with the specified values as a
    2653             :  * child of the GEOGCS node.
    2654             :  *
    2655             :  * This method does the same as the C function OSRSetAngularUnits().
    2656             :  *
    2657             :  * @param pszUnitsName the units name to be used.  Some preferred units
    2658             :  * names can be found in ogr_srs_api.h such as SRS_UA_DEGREE.
    2659             :  *
    2660             :  * @param dfInRadians the value to multiple by an angle in the indicated
    2661             :  * units to transform to radians.  Some standard conversion factors can
    2662             :  * be found in ogr_srs_api.h.
    2663             :  *
    2664             :  * @return OGRERR_NONE on success.
    2665             :  */
    2666             : 
    2667        1610 : OGRErr OGRSpatialReference::SetAngularUnits(const char *pszUnitsName,
    2668             :                                             double dfInRadians)
    2669             : 
    2670             : {
    2671        3220 :     TAKE_OPTIONAL_LOCK();
    2672             : 
    2673        1610 :     d->bNormInfoSet = FALSE;
    2674             : 
    2675        1610 :     d->refreshProjObj();
    2676        1610 :     if (!d->m_pj_crs)
    2677           0 :         return OGRERR_FAILURE;
    2678        1610 :     auto geodCRS = proj_crs_get_geodetic_crs(d->getPROJContext(), d->m_pj_crs);
    2679        1610 :     if (!geodCRS)
    2680           0 :         return OGRERR_FAILURE;
    2681        1610 :     proj_destroy(geodCRS);
    2682        1610 :     d->demoteFromBoundCRS();
    2683        1610 :     d->setPjCRS(proj_crs_alter_cs_angular_unit(d->getPROJContext(), d->m_pj_crs,
    2684             :                                                pszUnitsName, dfInRadians,
    2685             :                                                nullptr, nullptr));
    2686        1610 :     d->undoDemoteFromBoundCRS();
    2687             : 
    2688        1610 :     d->m_osAngularUnits = pszUnitsName;
    2689        1610 :     d->m_dfAngularUnitToRadian = dfInRadians;
    2690             : 
    2691        1610 :     return OGRERR_NONE;
    2692             : }
    2693             : 
    2694             : /************************************************************************/
    2695             : /*                         OSRSetAngularUnits()                         */
    2696             : /************************************************************************/
    2697             : 
    2698             : /**
    2699             :  * \brief Set the angular units for the geographic coordinate system.
    2700             :  *
    2701             :  * This function is the same as OGRSpatialReference::SetAngularUnits()
    2702             :  */
    2703          51 : OGRErr OSRSetAngularUnits(OGRSpatialReferenceH hSRS, const char *pszUnits,
    2704             :                           double dfInRadians)
    2705             : 
    2706             : {
    2707          51 :     VALIDATE_POINTER1(hSRS, "OSRSetAngularUnits", OGRERR_FAILURE);
    2708             : 
    2709          51 :     return ToPointer(hSRS)->SetAngularUnits(pszUnits, dfInRadians);
    2710             : }
    2711             : 
    2712             : /************************************************************************/
    2713             : /*                          GetAngularUnits()                           */
    2714             : /************************************************************************/
    2715             : 
    2716             : /**
    2717             :  * \brief Fetch angular geographic coordinate system units.
    2718             :  *
    2719             :  * If no units are available, a value of "degree" and SRS_UA_DEGREE_CONV
    2720             :  * will be assumed.  This method only checks directly under the GEOGCS node
    2721             :  * for units.
    2722             :  *
    2723             :  * This method does the same thing as the C function OSRGetAngularUnits().
    2724             :  *
    2725             :  * @param ppszName a pointer to be updated with the pointer to the units name.
    2726             :  * The returned value remains internal to the OGRSpatialReference and should
    2727             :  * not be freed, or modified.  It may be invalidated on the next
    2728             :  * OGRSpatialReference call.
    2729             :  *
    2730             :  * @return the value to multiply by angular distances to transform them to
    2731             :  * radians.
    2732             :  */
    2733             : 
    2734        8899 : double OGRSpatialReference::GetAngularUnits(const char **ppszName) const
    2735             : 
    2736             : {
    2737       17798 :     TAKE_OPTIONAL_LOCK();
    2738             : 
    2739        8899 :     d->refreshProjObj();
    2740             : 
    2741        8899 :     if (!d->m_osAngularUnits.empty())
    2742             :     {
    2743        2442 :         if (ppszName != nullptr)
    2744         185 :             *ppszName = d->m_osAngularUnits.c_str();
    2745        2442 :         return d->m_dfAngularUnitToRadian;
    2746             :     }
    2747             : 
    2748             :     do
    2749             :     {
    2750        6457 :         if (d->m_pj_crs == nullptr || d->m_pjType == PJ_TYPE_ENGINEERING_CRS)
    2751             :         {
    2752         113 :             break;
    2753             :         }
    2754             : 
    2755             :         auto geodCRS =
    2756        6346 :             proj_crs_get_geodetic_crs(d->getPROJContext(), d->m_pj_crs);
    2757        6346 :         if (!geodCRS)
    2758             :         {
    2759           0 :             break;
    2760             :         }
    2761             :         auto coordSys =
    2762        6346 :             proj_crs_get_coordinate_system(d->getPROJContext(), geodCRS);
    2763        6346 :         proj_destroy(geodCRS);
    2764        6346 :         if (!coordSys)
    2765             :         {
    2766           0 :             break;
    2767             :         }
    2768        6346 :         if (proj_cs_get_type(d->getPROJContext(), coordSys) !=
    2769             :             PJ_CS_TYPE_ELLIPSOIDAL)
    2770             :         {
    2771           2 :             proj_destroy(coordSys);
    2772           2 :             break;
    2773             :         }
    2774             : 
    2775        6344 :         double dfConvFactor = 0.0;
    2776        6344 :         const char *pszUnitName = nullptr;
    2777        6344 :         if (!proj_cs_get_axis_info(d->getPROJContext(), coordSys, 0, nullptr,
    2778             :                                    nullptr, nullptr, &dfConvFactor,
    2779             :                                    &pszUnitName, nullptr, nullptr))
    2780             :         {
    2781           0 :             proj_destroy(coordSys);
    2782           0 :             break;
    2783             :         }
    2784             : 
    2785        6344 :         d->m_osAngularUnits = pszUnitName;
    2786             : 
    2787        6344 :         proj_destroy(coordSys);
    2788        6344 :         d->m_dfAngularUnitToRadian = dfConvFactor;
    2789             :     } while (false);
    2790             : 
    2791        6457 :     if (d->m_osAngularUnits.empty())
    2792             :     {
    2793         113 :         d->m_osAngularUnits = "degree";
    2794         113 :         d->m_dfAngularUnitToRadian = CPLAtof(SRS_UA_DEGREE_CONV);
    2795             :     }
    2796             : 
    2797        6457 :     if (ppszName != nullptr)
    2798        3308 :         *ppszName = d->m_osAngularUnits.c_str();
    2799        6457 :     return d->m_dfAngularUnitToRadian;
    2800             : }
    2801             : 
    2802             : /**
    2803             :  * \brief Fetch angular geographic coordinate system units.
    2804             :  *
    2805             :  * If no units are available, a value of "degree" and SRS_UA_DEGREE_CONV
    2806             :  * will be assumed.  This method only checks directly under the GEOGCS node
    2807             :  * for units.
    2808             :  *
    2809             :  * This method does the same thing as the C function OSRGetAngularUnits().
    2810             :  *
    2811             :  * @param ppszName a pointer to be updated with the pointer to the units name.
    2812             :  * The returned value remains internal to the OGRSpatialReference and should
    2813             :  * not be freed, or modified.  It may be invalidated on the next
    2814             :  * OGRSpatialReference call.
    2815             :  *
    2816             :  * @return the value to multiply by angular distances to transform them to
    2817             :  * radians.
    2818             :  * @deprecated Use GetAngularUnits(const char**) const.
    2819             :  */
    2820             : 
    2821           0 : double OGRSpatialReference::GetAngularUnits(char **ppszName) const
    2822             : 
    2823             : {
    2824           0 :     return GetAngularUnits(const_cast<const char **>(ppszName));
    2825             : }
    2826             : 
    2827             : /************************************************************************/
    2828             : /*                         OSRGetAngularUnits()                         */
    2829             : /************************************************************************/
    2830             : 
    2831             : /**
    2832             :  * \brief Fetch angular geographic coordinate system units.
    2833             :  *
    2834             :  * This function is the same as OGRSpatialReference::GetAngularUnits()
    2835             :  */
    2836           1 : double OSRGetAngularUnits(OGRSpatialReferenceH hSRS, char **ppszName)
    2837             : 
    2838             : {
    2839           1 :     VALIDATE_POINTER1(hSRS, "OSRGetAngularUnits", 0);
    2840             : 
    2841           1 :     return ToPointer(hSRS)->GetAngularUnits(
    2842           1 :         const_cast<const char **>(ppszName));
    2843             : }
    2844             : 
    2845             : /************************************************************************/
    2846             : /*                 SetLinearUnitsAndUpdateParameters()                  */
    2847             : /************************************************************************/
    2848             : 
    2849             : /**
    2850             :  * \brief Set the linear units for the projection.
    2851             :  *
    2852             :  * This method creates a UNIT subnode with the specified values as a
    2853             :  * child of the PROJCS or LOCAL_CS node.   It works the same as the
    2854             :  * SetLinearUnits() method, but it also updates all existing linear
    2855             :  * projection parameter values from the old units to the new units.
    2856             :  *
    2857             :  * @param pszName the units name to be used.  Some preferred units
    2858             :  * names can be found in ogr_srs_api.h such as SRS_UL_METER, SRS_UL_FOOT
    2859             :  * and SRS_UL_US_FOOT.
    2860             :  *
    2861             :  * @param dfInMeters the value to multiple by a length in the indicated
    2862             :  * units to transform to meters.  Some standard conversion factors can
    2863             :  * be found in ogr_srs_api.h.
    2864             :  *
    2865             :  * @param pszUnitAuthority Unit authority name. Or nullptr
    2866             :  *
    2867             :  * @param pszUnitCode Unit code. Or nullptr
    2868             :  *
    2869             :  * @return OGRERR_NONE on success.
    2870             :  */
    2871             : 
    2872          39 : OGRErr OGRSpatialReference::SetLinearUnitsAndUpdateParameters(
    2873             :     const char *pszName, double dfInMeters, const char *pszUnitAuthority,
    2874             :     const char *pszUnitCode)
    2875             : 
    2876             : {
    2877          78 :     TAKE_OPTIONAL_LOCK();
    2878             : 
    2879          39 :     if (dfInMeters <= 0.0)
    2880           0 :         return OGRERR_FAILURE;
    2881             : 
    2882          39 :     d->refreshProjObj();
    2883          39 :     if (!d->m_pj_crs)
    2884           0 :         return OGRERR_FAILURE;
    2885             : 
    2886          39 :     d->demoteFromBoundCRS();
    2887          39 :     if (d->m_pjType == PJ_TYPE_PROJECTED_CRS)
    2888             :     {
    2889          78 :         d->setPjCRS(proj_crs_alter_parameters_linear_unit(
    2890          39 :             d->getPROJContext(), d->m_pj_crs, pszName, dfInMeters,
    2891             :             pszUnitAuthority, pszUnitCode, true));
    2892             :     }
    2893          39 :     d->setPjCRS(proj_crs_alter_cs_linear_unit(d->getPROJContext(), d->m_pj_crs,
    2894             :                                               pszName, dfInMeters,
    2895             :                                               pszUnitAuthority, pszUnitCode));
    2896          39 :     d->undoDemoteFromBoundCRS();
    2897             : 
    2898          39 :     d->m_osLinearUnits = pszName;
    2899          39 :     d->dfToMeter = dfInMeters;
    2900             : 
    2901          39 :     return OGRERR_NONE;
    2902             : }
    2903             : 
    2904             : /************************************************************************/
    2905             : /*                OSRSetLinearUnitsAndUpdateParameters()                */
    2906             : /************************************************************************/
    2907             : 
    2908             : /**
    2909             :  * \brief Set the linear units for the projection.
    2910             :  *
    2911             :  * This function is the same as
    2912             :  *   OGRSpatialReference::SetLinearUnitsAndUpdateParameters()
    2913             :  */
    2914           1 : OGRErr OSRSetLinearUnitsAndUpdateParameters(OGRSpatialReferenceH hSRS,
    2915             :                                             const char *pszUnits,
    2916             :                                             double dfInMeters)
    2917             : 
    2918             : {
    2919           1 :     VALIDATE_POINTER1(hSRS, "OSRSetLinearUnitsAndUpdateParameters",
    2920             :                       OGRERR_FAILURE);
    2921             : 
    2922           1 :     return ToPointer(hSRS)->SetLinearUnitsAndUpdateParameters(pszUnits,
    2923           1 :                                                               dfInMeters);
    2924             : }
    2925             : 
    2926             : /************************************************************************/
    2927             : /*                           SetLinearUnits()                           */
    2928             : /************************************************************************/
    2929             : 
    2930             : /**
    2931             :  * \brief Set the linear units for the projection.
    2932             :  *
    2933             :  * This method creates a UNIT subnode with the specified values as a
    2934             :  * child of the PROJCS, GEOCCS, GEOGCS or LOCAL_CS node. When called on a
    2935             :  * Geographic 3D CRS the vertical axis units will be set.
    2936             :  *
    2937             :  * This method does the same as the C function OSRSetLinearUnits().
    2938             :  *
    2939             :  * @param pszUnitsName the units name to be used.  Some preferred units
    2940             :  * names can be found in ogr_srs_api.h such as SRS_UL_METER, SRS_UL_FOOT
    2941             :  * and SRS_UL_US_FOOT.
    2942             :  *
    2943             :  * @param dfInMeters the value to multiple by a length in the indicated
    2944             :  * units to transform to meters.  Some standard conversion factors can
    2945             :  * be found in ogr_srs_api.h.
    2946             :  *
    2947             :  * @return OGRERR_NONE on success.
    2948             :  */
    2949             : 
    2950        7436 : OGRErr OGRSpatialReference::SetLinearUnits(const char *pszUnitsName,
    2951             :                                            double dfInMeters)
    2952             : 
    2953             : {
    2954        7436 :     return SetTargetLinearUnits(nullptr, pszUnitsName, dfInMeters);
    2955             : }
    2956             : 
    2957             : /************************************************************************/
    2958             : /*                         OSRSetLinearUnits()                          */
    2959             : /************************************************************************/
    2960             : 
    2961             : /**
    2962             :  * \brief Set the linear units for the projection.
    2963             :  *
    2964             :  * This function is the same as OGRSpatialReference::SetLinearUnits()
    2965             :  */
    2966           7 : OGRErr OSRSetLinearUnits(OGRSpatialReferenceH hSRS, const char *pszUnits,
    2967             :                          double dfInMeters)
    2968             : 
    2969             : {
    2970           7 :     VALIDATE_POINTER1(hSRS, "OSRSetLinearUnits", OGRERR_FAILURE);
    2971             : 
    2972           7 :     return ToPointer(hSRS)->SetLinearUnits(pszUnits, dfInMeters);
    2973             : }
    2974             : 
    2975             : /************************************************************************/
    2976             : /*                        SetTargetLinearUnits()                        */
    2977             : /************************************************************************/
    2978             : 
    2979             : /**
    2980             :  * \brief Set the linear units for the projection.
    2981             :  *
    2982             :  * This method creates a UNIT subnode with the specified values as a
    2983             :  * child of the target node.
    2984             :  *
    2985             :  * This method does the same as the C function OSRSetTargetLinearUnits().
    2986             :  *
    2987             :  * @param pszTargetKey the keyword to set the linear units for.
    2988             :  * i.e. "PROJCS" or "VERT_CS"
    2989             :  *
    2990             :  * @param pszUnitsName the units name to be used.  Some preferred units
    2991             :  * names can be found in ogr_srs_api.h such as SRS_UL_METER, SRS_UL_FOOT
    2992             :  * and SRS_UL_US_FOOT.
    2993             :  *
    2994             :  * @param dfInMeters the value to multiple by a length in the indicated
    2995             :  * units to transform to meters.  Some standard conversion factors can
    2996             :  * be found in ogr_srs_api.h.
    2997             :  *
    2998             :  * @param pszUnitAuthority Unit authority name. Or nullptr
    2999             :  *
    3000             :  * @param pszUnitCode Unit code. Or nullptr
    3001             :  *
    3002             :  * @return OGRERR_NONE on success.
    3003             :  *
    3004             :  */
    3005             : 
    3006       11926 : OGRErr OGRSpatialReference::SetTargetLinearUnits(const char *pszTargetKey,
    3007             :                                                  const char *pszUnitsName,
    3008             :                                                  double dfInMeters,
    3009             :                                                  const char *pszUnitAuthority,
    3010             :                                                  const char *pszUnitCode)
    3011             : 
    3012             : {
    3013       23852 :     TAKE_OPTIONAL_LOCK();
    3014             : 
    3015       11926 :     if (dfInMeters <= 0.0)
    3016           0 :         return OGRERR_FAILURE;
    3017             : 
    3018       11926 :     d->refreshProjObj();
    3019       11926 :     pszTargetKey = d->nullifyTargetKeyIfPossible(pszTargetKey);
    3020       11926 :     if (pszTargetKey == nullptr)
    3021             :     {
    3022       11926 :         if (!d->m_pj_crs)
    3023           0 :             return OGRERR_FAILURE;
    3024             : 
    3025       11926 :         d->demoteFromBoundCRS();
    3026       11926 :         if (d->m_pjType == PJ_TYPE_PROJECTED_CRS)
    3027             :         {
    3028       18048 :             d->setPjCRS(proj_crs_alter_parameters_linear_unit(
    3029        9024 :                 d->getPROJContext(), d->m_pj_crs, pszUnitsName, dfInMeters,
    3030             :                 pszUnitAuthority, pszUnitCode, false));
    3031             :         }
    3032       23852 :         d->setPjCRS(proj_crs_alter_cs_linear_unit(
    3033       11926 :             d->getPROJContext(), d->m_pj_crs, pszUnitsName, dfInMeters,
    3034             :             pszUnitAuthority, pszUnitCode));
    3035       11926 :         d->undoDemoteFromBoundCRS();
    3036             : 
    3037       11926 :         d->m_osLinearUnits = pszUnitsName;
    3038       11926 :         d->dfToMeter = dfInMeters;
    3039             : 
    3040       11926 :         return OGRERR_NONE;
    3041             :     }
    3042             : 
    3043           0 :     OGR_SRSNode *poCS = GetAttrNode(pszTargetKey);
    3044             : 
    3045           0 :     if (poCS == nullptr)
    3046           0 :         return OGRERR_FAILURE;
    3047             : 
    3048           0 :     char szValue[128] = {'\0'};
    3049           0 :     if (dfInMeters < std::numeric_limits<int>::max() &&
    3050           0 :         dfInMeters > std::numeric_limits<int>::min() &&
    3051           0 :         dfInMeters == static_cast<int>(dfInMeters))
    3052           0 :         snprintf(szValue, sizeof(szValue), "%d", static_cast<int>(dfInMeters));
    3053             :     else
    3054           0 :         OGRsnPrintDouble(szValue, sizeof(szValue), dfInMeters);
    3055             : 
    3056           0 :     OGR_SRSNode *poUnits = nullptr;
    3057           0 :     if (poCS->FindChild("UNIT") >= 0)
    3058             :     {
    3059           0 :         poUnits = poCS->GetChild(poCS->FindChild("UNIT"));
    3060           0 :         if (poUnits->GetChildCount() < 2)
    3061           0 :             return OGRERR_FAILURE;
    3062           0 :         poUnits->GetChild(0)->SetValue(pszUnitsName);
    3063           0 :         poUnits->GetChild(1)->SetValue(szValue);
    3064           0 :         if (poUnits->FindChild("AUTHORITY") != -1)
    3065           0 :             poUnits->DestroyChild(poUnits->FindChild("AUTHORITY"));
    3066             :     }
    3067             :     else
    3068             :     {
    3069           0 :         poUnits = new OGR_SRSNode("UNIT");
    3070           0 :         poUnits->AddChild(new OGR_SRSNode(pszUnitsName));
    3071           0 :         poUnits->AddChild(new OGR_SRSNode(szValue));
    3072             : 
    3073           0 :         poCS->AddChild(poUnits);
    3074             :     }
    3075             : 
    3076           0 :     return OGRERR_NONE;
    3077             : }
    3078             : 
    3079             : /************************************************************************/
    3080             : /*                         OSRSetLinearUnits()                          */
    3081             : /************************************************************************/
    3082             : 
    3083             : /**
    3084             :  * \brief Set the linear units for the target node.
    3085             :  *
    3086             :  * This function is the same as OGRSpatialReference::SetTargetLinearUnits()
    3087             :  *
    3088             :  */
    3089           1 : OGRErr OSRSetTargetLinearUnits(OGRSpatialReferenceH hSRS,
    3090             :                                const char *pszTargetKey, const char *pszUnits,
    3091             :                                double dfInMeters)
    3092             : 
    3093             : {
    3094           1 :     VALIDATE_POINTER1(hSRS, "OSRSetTargetLinearUnits", OGRERR_FAILURE);
    3095             : 
    3096           1 :     return ToPointer(hSRS)->SetTargetLinearUnits(pszTargetKey, pszUnits,
    3097           1 :                                                  dfInMeters);
    3098             : }
    3099             : 
    3100             : /************************************************************************/
    3101             : /*                           GetLinearUnits()                           */
    3102             : /************************************************************************/
    3103             : 
    3104             : /**
    3105             :  * \brief Fetch linear projection units.
    3106             :  *
    3107             :  * If no units are available, a value of "Meters" and 1.0 will be assumed.
    3108             :  * This method only checks directly under the PROJCS, GEOCCS, GEOGCS or
    3109             :  * LOCAL_CS node for units. When called on a Geographic 3D CRS the vertical
    3110             :  * axis units will be returned.
    3111             :  *
    3112             :  * This method does the same thing as the C function OSRGetLinearUnits()
    3113             :  *
    3114             :  * @param ppszName a pointer to be updated with the pointer to the units name.
    3115             :  * The returned value remains internal to the OGRSpatialReference and should
    3116             :  * not be freed, or modified.  It may be invalidated on the next
    3117             :  * OGRSpatialReference call.
    3118             :  *
    3119             :  * @return the value to multiply by linear distances to transform them to
    3120             :  * meters.
    3121             :  * @deprecated Use GetLinearUnits(const char**) const.
    3122             :  */
    3123             : 
    3124           0 : double OGRSpatialReference::GetLinearUnits(char **ppszName) const
    3125             : 
    3126             : {
    3127           0 :     return GetTargetLinearUnits(nullptr, const_cast<const char **>(ppszName));
    3128             : }
    3129             : 
    3130             : /**
    3131             :  * \brief Fetch linear projection units.
    3132             :  *
    3133             :  * If no units are available, a value of "Meters" and 1.0 will be assumed.
    3134             :  * This method only checks directly under the PROJCS, GEOCCS or LOCAL_CS node
    3135             :  * for units.
    3136             :  *
    3137             :  * This method does the same thing as the C function OSRGetLinearUnits()
    3138             :  *
    3139             :  * @param ppszName a pointer to be updated with the pointer to the units name.
    3140             :  * The returned value remains internal to the OGRSpatialReference and should
    3141             :  * not be freed, or modified.  It may be invalidated on the next
    3142             :  * OGRSpatialReference call.
    3143             :  *
    3144             :  * @return the value to multiply by linear distances to transform them to
    3145             :  * meters.
    3146             :  */
    3147             : 
    3148       21829 : double OGRSpatialReference::GetLinearUnits(const char **ppszName) const
    3149             : 
    3150             : {
    3151       21829 :     return GetTargetLinearUnits(nullptr, ppszName);
    3152             : }
    3153             : 
    3154             : /************************************************************************/
    3155             : /*                         OSRGetLinearUnits()                          */
    3156             : /************************************************************************/
    3157             : 
    3158             : /**
    3159             :  * \brief Fetch linear projection units.
    3160             :  *
    3161             :  * This function is the same as OGRSpatialReference::GetLinearUnits()
    3162             :  */
    3163         255 : double OSRGetLinearUnits(OGRSpatialReferenceH hSRS, char **ppszName)
    3164             : 
    3165             : {
    3166         255 :     VALIDATE_POINTER1(hSRS, "OSRGetLinearUnits", 0);
    3167             : 
    3168         255 :     return ToPointer(hSRS)->GetLinearUnits(const_cast<const char **>(ppszName));
    3169             : }
    3170             : 
    3171             : /************************************************************************/
    3172             : /*                        GetTargetLinearUnits()                        */
    3173             : /************************************************************************/
    3174             : 
    3175             : /**
    3176             :  * \brief Fetch linear units for target.
    3177             :  *
    3178             :  * If no units are available, a value of "Meters" and 1.0 will be assumed.
    3179             :  *
    3180             :  * This method does the same thing as the C function OSRGetTargetLinearUnits()
    3181             :  *
    3182             :  * @param pszTargetKey the key to look on. i.e. "PROJCS" or "VERT_CS". Might be
    3183             :  * NULL, in which case PROJCS will be implied (and if not found, LOCAL_CS,
    3184             :  * GEOCCS, GEOGCS and VERT_CS are looked up)
    3185             :  * @param ppszName a pointer to be updated with the pointer to the units name.
    3186             :  * The returned value remains internal to the OGRSpatialReference and should not
    3187             :  * be freed, or modified.  It may be invalidated on the next
    3188             :  * OGRSpatialReference call. ppszName can be set to NULL.
    3189             :  *
    3190             :  * @return the value to multiply by linear distances to transform them to
    3191             :  * meters.
    3192             :  *
    3193             :  * @deprecated Use GetTargetLinearUnits(const char*, const char**)
    3194             :  * const.
    3195             :  */
    3196             : 
    3197       21982 : double OGRSpatialReference::GetTargetLinearUnits(const char *pszTargetKey,
    3198             :                                                  const char **ppszName) const
    3199             : 
    3200             : {
    3201       43964 :     TAKE_OPTIONAL_LOCK();
    3202             : 
    3203       21982 :     d->refreshProjObj();
    3204             : 
    3205       21982 :     pszTargetKey = d->nullifyTargetKeyIfPossible(pszTargetKey);
    3206       21982 :     if (pszTargetKey == nullptr)
    3207             :     {
    3208             :         // Use cached result if available
    3209       21890 :         if (!d->m_osLinearUnits.empty())
    3210             :         {
    3211        9213 :             if (ppszName)
    3212        8327 :                 *ppszName = d->m_osLinearUnits.c_str();
    3213        9213 :             return d->dfToMeter;
    3214             :         }
    3215             : 
    3216             :         while (true)
    3217             :         {
    3218       12677 :             if (d->m_pj_crs == nullptr)
    3219             :             {
    3220         243 :                 break;
    3221             :             }
    3222             : 
    3223       12434 :             d->demoteFromBoundCRS();
    3224       12434 :             PJ *coordSys = nullptr;
    3225       12434 :             if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    3226             :             {
    3227          37 :                 for (int iComponent = 0; iComponent < 2; iComponent++)
    3228             :                 {
    3229          37 :                     auto subCRS = proj_crs_get_sub_crs(d->getPROJContext(),
    3230          37 :                                                        d->m_pj_crs, iComponent);
    3231          37 :                     if (subCRS && proj_get_type(subCRS) == PJ_TYPE_BOUND_CRS)
    3232             :                     {
    3233             :                         auto temp =
    3234           0 :                             proj_get_source_crs(d->getPROJContext(), subCRS);
    3235           0 :                         proj_destroy(subCRS);
    3236           0 :                         subCRS = temp;
    3237             :                     }
    3238          74 :                     if (subCRS &&
    3239          37 :                         (proj_get_type(subCRS) == PJ_TYPE_PROJECTED_CRS ||
    3240          16 :                          proj_get_type(subCRS) == PJ_TYPE_ENGINEERING_CRS ||
    3241          12 :                          proj_get_type(subCRS) == PJ_TYPE_VERTICAL_CRS))
    3242             :                     {
    3243          31 :                         coordSys = proj_crs_get_coordinate_system(
    3244             :                             d->getPROJContext(), subCRS);
    3245          31 :                         proj_destroy(subCRS);
    3246          31 :                         break;
    3247             :                     }
    3248           6 :                     else if (subCRS)
    3249             :                     {
    3250           6 :                         proj_destroy(subCRS);
    3251             :                     }
    3252             :                 }
    3253          31 :                 if (coordSys == nullptr)
    3254             :                 {
    3255           0 :                     d->undoDemoteFromBoundCRS();
    3256           0 :                     break;
    3257             :                 }
    3258             :             }
    3259             :             else
    3260             :             {
    3261       12403 :                 coordSys = proj_crs_get_coordinate_system(d->getPROJContext(),
    3262       12403 :                                                           d->m_pj_crs);
    3263             :             }
    3264             : 
    3265       12434 :             d->undoDemoteFromBoundCRS();
    3266       12434 :             if (!coordSys)
    3267             :             {
    3268           0 :                 break;
    3269             :             }
    3270       12434 :             auto csType = proj_cs_get_type(d->getPROJContext(), coordSys);
    3271             : 
    3272       12434 :             if (csType != PJ_CS_TYPE_CARTESIAN &&
    3273        2303 :                 csType != PJ_CS_TYPE_VERTICAL &&
    3274           0 :                 csType != PJ_CS_TYPE_ELLIPSOIDAL &&
    3275             :                 csType != PJ_CS_TYPE_SPHERICAL)
    3276             :             {
    3277           0 :                 proj_destroy(coordSys);
    3278           0 :                 break;
    3279             :             }
    3280             : 
    3281       12434 :             int axis = 0;
    3282             : 
    3283       12434 :             if (csType == PJ_CS_TYPE_ELLIPSOIDAL ||
    3284             :                 csType == PJ_CS_TYPE_SPHERICAL)
    3285             :             {
    3286             :                 const int axisCount =
    3287        2303 :                     proj_cs_get_axis_count(d->getPROJContext(), coordSys);
    3288             : 
    3289        2303 :                 if (axisCount == 3)
    3290             :                 {
    3291           4 :                     axis = 2;
    3292             :                 }
    3293             :                 else
    3294             :                 {
    3295        2299 :                     proj_destroy(coordSys);
    3296        2299 :                     break;
    3297             :                 }
    3298             :             }
    3299             : 
    3300       10135 :             double dfConvFactor = 0.0;
    3301       10135 :             const char *pszUnitName = nullptr;
    3302       10135 :             if (!proj_cs_get_axis_info(d->getPROJContext(), coordSys, axis,
    3303             :                                        nullptr, nullptr, nullptr, &dfConvFactor,
    3304             :                                        &pszUnitName, nullptr, nullptr))
    3305             :             {
    3306           0 :                 proj_destroy(coordSys);
    3307           0 :                 break;
    3308             :             }
    3309             : 
    3310       10135 :             d->m_osLinearUnits = pszUnitName;
    3311       10135 :             d->dfToMeter = dfConvFactor;
    3312       10135 :             if (ppszName)
    3313        1318 :                 *ppszName = d->m_osLinearUnits.c_str();
    3314             : 
    3315       10135 :             proj_destroy(coordSys);
    3316       10135 :             return dfConvFactor;
    3317             :         }
    3318             : 
    3319        2542 :         d->m_osLinearUnits = "unknown";
    3320        2542 :         d->dfToMeter = 1.0;
    3321             : 
    3322        2542 :         if (ppszName != nullptr)
    3323        2353 :             *ppszName = d->m_osLinearUnits.c_str();
    3324        2542 :         return 1.0;
    3325             :     }
    3326             : 
    3327          92 :     const OGR_SRSNode *poCS = GetAttrNode(pszTargetKey);
    3328             : 
    3329          92 :     if (ppszName != nullptr)
    3330          38 :         *ppszName = "unknown";
    3331             : 
    3332          92 :     if (poCS == nullptr)
    3333          53 :         return 1.0;
    3334             : 
    3335         117 :     for (int iChild = 0; iChild < poCS->GetChildCount(); iChild++)
    3336             :     {
    3337         117 :         const OGR_SRSNode *poChild = poCS->GetChild(iChild);
    3338             : 
    3339         117 :         if (EQUAL(poChild->GetValue(), "UNIT") && poChild->GetChildCount() >= 2)
    3340             :         {
    3341          39 :             if (ppszName != nullptr)
    3342          38 :                 *ppszName = poChild->GetChild(0)->GetValue();
    3343             : 
    3344          39 :             return CPLAtof(poChild->GetChild(1)->GetValue());
    3345             :         }
    3346             :     }
    3347             : 
    3348           0 :     return 1.0;
    3349             : }
    3350             : 
    3351             : /**
    3352             :  * \brief Fetch linear units for target.
    3353             :  *
    3354             :  * If no units are available, a value of "Meters" and 1.0 will be assumed.
    3355             :  *
    3356             :  * This method does the same thing as the C function OSRGetTargetLinearUnits()
    3357             :  *
    3358             :  * @param pszTargetKey the key to look on. i.e. "PROJCS" or "VERT_CS". Might be
    3359             :  * NULL, in which case PROJCS will be implied (and if not found, LOCAL_CS,
    3360             :  * GEOCCS and VERT_CS are looked up)
    3361             :  * @param ppszName a pointer to be updated with the pointer to the units name.
    3362             :  * The returned value remains internal to the OGRSpatialReference and should not
    3363             :  * be freed, or modified.  It may be invalidated on the next
    3364             :  * OGRSpatialReference call. ppszName can be set to NULL.
    3365             :  *
    3366             :  * @return the value to multiply by linear distances to transform them to
    3367             :  * meters.
    3368             :  *
    3369             :  */
    3370             : 
    3371           0 : double OGRSpatialReference::GetTargetLinearUnits(const char *pszTargetKey,
    3372             :                                                  char **ppszName) const
    3373             : 
    3374             : {
    3375           0 :     return GetTargetLinearUnits(pszTargetKey,
    3376           0 :                                 const_cast<const char **>(ppszName));
    3377             : }
    3378             : 
    3379             : /************************************************************************/
    3380             : /*                      OSRGetTargetLinearUnits()                       */
    3381             : /************************************************************************/
    3382             : 
    3383             : /**
    3384             :  * \brief Fetch linear projection units.
    3385             :  *
    3386             :  * This function is the same as OGRSpatialReference::GetTargetLinearUnits()
    3387             :  *
    3388             :  */
    3389           4 : double OSRGetTargetLinearUnits(OGRSpatialReferenceH hSRS,
    3390             :                                const char *pszTargetKey, char **ppszName)
    3391             : 
    3392             : {
    3393           4 :     VALIDATE_POINTER1(hSRS, "OSRGetTargetLinearUnits", 0);
    3394             : 
    3395           4 :     return ToPointer(hSRS)->GetTargetLinearUnits(
    3396           4 :         pszTargetKey, const_cast<const char **>(ppszName));
    3397             : }
    3398             : 
    3399             : /************************************************************************/
    3400             : /*                          GetPrimeMeridian()                          */
    3401             : /************************************************************************/
    3402             : 
    3403             : /**
    3404             :  * \brief Fetch prime meridian info.
    3405             :  *
    3406             :  * Returns the offset of the prime meridian from greenwich in degrees,
    3407             :  * and the prime meridian name (if requested).   If no PRIMEM value exists
    3408             :  * in the coordinate system definition a value of "Greenwich" and an
    3409             :  * offset of 0.0 is assumed.
    3410             :  *
    3411             :  * If the prime meridian name is returned, the pointer is to an internal
    3412             :  * copy of the name. It should not be freed, altered or depended on after
    3413             :  * the next OGR call.
    3414             :  *
    3415             :  * This method is the same as the C function OSRGetPrimeMeridian().
    3416             :  *
    3417             :  * @param ppszName return location for prime meridian name.  If NULL, name
    3418             :  * is not returned.
    3419             :  *
    3420             :  * @return the offset to the GEOGCS prime meridian from greenwich in decimal
    3421             :  * degrees.
    3422             :  * @deprecated Use GetPrimeMeridian(const char**) const.
    3423             :  */
    3424             : 
    3425        1514 : double OGRSpatialReference::GetPrimeMeridian(const char **ppszName) const
    3426             : 
    3427             : {
    3428        3028 :     TAKE_OPTIONAL_LOCK();
    3429             : 
    3430        1514 :     d->refreshProjObj();
    3431             : 
    3432        1514 :     if (!d->m_osPrimeMeridianName.empty())
    3433             :     {
    3434          87 :         if (ppszName != nullptr)
    3435          11 :             *ppszName = d->m_osPrimeMeridianName.c_str();
    3436          87 :         return d->dfFromGreenwich;
    3437             :     }
    3438             : 
    3439             :     while (true)
    3440             :     {
    3441        1427 :         if (!d->m_pj_crs)
    3442           0 :             break;
    3443             : 
    3444        1427 :         auto pm = proj_get_prime_meridian(d->getPROJContext(), d->m_pj_crs);
    3445        1427 :         if (!pm)
    3446           0 :             break;
    3447             : 
    3448        1427 :         d->m_osPrimeMeridianName = proj_get_name(pm);
    3449        1427 :         if (ppszName)
    3450          19 :             *ppszName = d->m_osPrimeMeridianName.c_str();
    3451        1427 :         double dfLongitude = 0.0;
    3452        1427 :         double dfConvFactor = 0.0;
    3453        1427 :         proj_prime_meridian_get_parameters(
    3454             :             d->getPROJContext(), pm, &dfLongitude, &dfConvFactor, nullptr);
    3455        1427 :         proj_destroy(pm);
    3456        2854 :         d->dfFromGreenwich =
    3457        1427 :             dfLongitude * dfConvFactor / CPLAtof(SRS_UA_DEGREE_CONV);
    3458        1427 :         return d->dfFromGreenwich;
    3459             :     }
    3460             : 
    3461           0 :     d->m_osPrimeMeridianName = SRS_PM_GREENWICH;
    3462           0 :     d->dfFromGreenwich = 0.0;
    3463           0 :     if (ppszName != nullptr)
    3464           0 :         *ppszName = d->m_osPrimeMeridianName.c_str();
    3465           0 :     return d->dfFromGreenwich;
    3466             : }
    3467             : 
    3468             : /**
    3469             :  * \brief Fetch prime meridian info.
    3470             :  *
    3471             :  * Returns the offset of the prime meridian from greenwich in degrees,
    3472             :  * and the prime meridian name (if requested).   If no PRIMEM value exists
    3473             :  * in the coordinate system definition a value of "Greenwich" and an
    3474             :  * offset of 0.0 is assumed.
    3475             :  *
    3476             :  * If the prime meridian name is returned, the pointer is to an internal
    3477             :  * copy of the name. It should not be freed, altered or depended on after
    3478             :  * the next OGR call.
    3479             :  *
    3480             :  * This method is the same as the C function OSRGetPrimeMeridian().
    3481             :  *
    3482             :  * @param ppszName return location for prime meridian name.  If NULL, name
    3483             :  * is not returned.
    3484             :  *
    3485             :  * @return the offset to the GEOGCS prime meridian from greenwich in decimal
    3486             :  * degrees.
    3487             :  */
    3488             : 
    3489           0 : double OGRSpatialReference::GetPrimeMeridian(char **ppszName) const
    3490             : 
    3491             : {
    3492           0 :     return GetPrimeMeridian(const_cast<const char **>(ppszName));
    3493             : }
    3494             : 
    3495             : /************************************************************************/
    3496             : /*                        OSRGetPrimeMeridian()                         */
    3497             : /************************************************************************/
    3498             : 
    3499             : /**
    3500             :  * \brief Fetch prime meridian info.
    3501             :  *
    3502             :  * This function is the same as OGRSpatialReference::GetPrimeMeridian()
    3503             :  */
    3504           0 : double OSRGetPrimeMeridian(OGRSpatialReferenceH hSRS, char **ppszName)
    3505             : 
    3506             : {
    3507           0 :     VALIDATE_POINTER1(hSRS, "OSRGetPrimeMeridian", 0);
    3508             : 
    3509           0 :     return ToPointer(hSRS)->GetPrimeMeridian(
    3510           0 :         const_cast<const char **>(ppszName));
    3511             : }
    3512             : 
    3513             : /************************************************************************/
    3514             : /*                             SetGeogCS()                              */
    3515             : /************************************************************************/
    3516             : 
    3517             : /**
    3518             :  * \brief Set geographic coordinate system.
    3519             :  *
    3520             :  * This method is used to set the datum, ellipsoid, prime meridian and
    3521             :  * angular units for a geographic coordinate system.  It can be used on its
    3522             :  * own to establish a geographic spatial reference, or applied to a
    3523             :  * projected coordinate system to establish the underlying geographic
    3524             :  * coordinate system.
    3525             :  *
    3526             :  * This method does the same as the C function OSRSetGeogCS().
    3527             :  *
    3528             :  * @param pszGeogName user visible name for the geographic coordinate system
    3529             :  * (not to serve as a key).
    3530             :  *
    3531             :  * @param pszDatumName key name for this datum.  The OpenGIS specification
    3532             :  * lists some known values, and otherwise EPSG datum names with a standard
    3533             :  * transformation are considered legal keys.
    3534             :  *
    3535             :  * @param pszSpheroidName user visible spheroid name (not to serve as a key)
    3536             :  *
    3537             :  * @param dfSemiMajor the semi major axis of the spheroid.
    3538             :  *
    3539             :  * @param dfInvFlattening the inverse flattening for the spheroid.
    3540             :  * This can be computed from the semi minor axis as
    3541             :  * 1/f = 1.0 / (1.0 - semiminor/semimajor).
    3542             :  *
    3543             :  * @param pszPMName the name of the prime meridian (not to serve as a key)
    3544             :  * If this is NULL a default value of "Greenwich" will be used.
    3545             :  *
    3546             :  * @param dfPMOffset the longitude of Greenwich relative to this prime
    3547             :  * meridian. Always in Degrees
    3548             :  *
    3549             :  * @param pszAngularUnits the angular units name (see ogr_srs_api.h for some
    3550             :  * standard names).  If NULL a value of "degrees" will be assumed.
    3551             :  *
    3552             :  * @param dfConvertToRadians value to multiply angular units by to transform
    3553             :  * them to radians.  A value of SRS_UA_DEGREE_CONV will be used if
    3554             :  * pszAngularUnits is NULL.
    3555             :  *
    3556             :  * @return OGRERR_NONE on success.
    3557             :  */
    3558             : 
    3559        9762 : OGRErr OGRSpatialReference::SetGeogCS(
    3560             :     const char *pszGeogName, const char *pszDatumName,
    3561             :     const char *pszSpheroidName, double dfSemiMajor, double dfInvFlattening,
    3562             :     const char *pszPMName, double dfPMOffset, const char *pszAngularUnits,
    3563             :     double dfConvertToRadians)
    3564             : 
    3565             : {
    3566       19524 :     TAKE_OPTIONAL_LOCK();
    3567             : 
    3568        9762 :     d->bNormInfoSet = FALSE;
    3569        9762 :     d->m_osAngularUnits.clear();
    3570        9762 :     d->m_dfAngularUnitToRadian = 0.0;
    3571        9762 :     d->m_osPrimeMeridianName.clear();
    3572        9762 :     d->dfFromGreenwich = 0.0;
    3573             : 
    3574             :     /* -------------------------------------------------------------------- */
    3575             :     /*      For a geocentric coordinate system we want to set the datum     */
    3576             :     /*      and ellipsoid based on the GEOGCS.  Create the GEOGCS in a      */
    3577             :     /*      temporary srs and use the copy method which has special         */
    3578             :     /*      handling for GEOCCS.                                            */
    3579             :     /* -------------------------------------------------------------------- */
    3580        9762 :     if (IsGeocentric())
    3581             :     {
    3582           4 :         OGRSpatialReference oGCS;
    3583             : 
    3584           2 :         oGCS.SetGeogCS(pszGeogName, pszDatumName, pszSpheroidName, dfSemiMajor,
    3585             :                        dfInvFlattening, pszPMName, dfPMOffset, pszAngularUnits,
    3586             :                        dfConvertToRadians);
    3587           2 :         return CopyGeogCSFrom(&oGCS);
    3588             :     }
    3589             : 
    3590        9760 :     auto cs = proj_create_ellipsoidal_2D_cs(
    3591             :         d->getPROJContext(), PJ_ELLPS2D_LATITUDE_LONGITUDE, pszAngularUnits,
    3592             :         dfConvertToRadians);
    3593             :     // Prime meridian expressed in Degree
    3594        9760 :     auto obj = proj_create_geographic_crs(
    3595             :         d->getPROJContext(), pszGeogName, pszDatumName, pszSpheroidName,
    3596             :         dfSemiMajor, dfInvFlattening, pszPMName, dfPMOffset, nullptr, 0.0, cs);
    3597        9760 :     proj_destroy(cs);
    3598             : 
    3599       14802 :     if (d->m_pj_crs == nullptr || d->m_pjType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
    3600        5042 :         d->m_pjType == PJ_TYPE_GEOGRAPHIC_3D_CRS)
    3601             :     {
    3602        4718 :         d->setPjCRS(obj);
    3603             :     }
    3604        5042 :     else if (d->m_pjType == PJ_TYPE_PROJECTED_CRS)
    3605             :     {
    3606       10084 :         d->setPjCRS(
    3607        5042 :             proj_crs_alter_geodetic_crs(d->getPROJContext(), d->m_pj_crs, obj));
    3608        5042 :         proj_destroy(obj);
    3609             :     }
    3610             :     else
    3611             :     {
    3612           0 :         proj_destroy(obj);
    3613             :     }
    3614             : 
    3615        9760 :     return OGRERR_NONE;
    3616             : }
    3617             : 
    3618             : /************************************************************************/
    3619             : /*                            OSRSetGeogCS()                            */
    3620             : /************************************************************************/
    3621             : 
    3622             : /**
    3623             :  * \brief Set geographic coordinate system.
    3624             :  *
    3625             :  * This function is the same as OGRSpatialReference::SetGeogCS()
    3626             :  */
    3627          18 : OGRErr OSRSetGeogCS(OGRSpatialReferenceH hSRS, const char *pszGeogName,
    3628             :                     const char *pszDatumName, const char *pszSpheroidName,
    3629             :                     double dfSemiMajor, double dfInvFlattening,
    3630             :                     const char *pszPMName, double dfPMOffset,
    3631             :                     const char *pszAngularUnits, double dfConvertToRadians)
    3632             : 
    3633             : {
    3634          18 :     VALIDATE_POINTER1(hSRS, "OSRSetGeogCS", OGRERR_FAILURE);
    3635             : 
    3636          18 :     return ToPointer(hSRS)->SetGeogCS(pszGeogName, pszDatumName,
    3637             :                                       pszSpheroidName, dfSemiMajor,
    3638             :                                       dfInvFlattening, pszPMName, dfPMOffset,
    3639          18 :                                       pszAngularUnits, dfConvertToRadians);
    3640             : }
    3641             : 
    3642             : /************************************************************************/
    3643             : /*                         SetWellKnownGeogCS()                         */
    3644             : /************************************************************************/
    3645             : 
    3646             : /**
    3647             :  * \brief Set a GeogCS based on well known name.
    3648             :  *
    3649             :  * This may be called on an empty OGRSpatialReference to make a geographic
    3650             :  * coordinate system, or on something with an existing PROJCS node to
    3651             :  * set the underlying geographic coordinate system of a projected coordinate
    3652             :  * system.
    3653             :  *
    3654             :  * The following well known text values are currently supported,
    3655             :  * Except for "EPSG:n", the others are without dependency on EPSG data files:
    3656             :  * <ul>
    3657             :  * <li> "EPSG:n": where n is the code a Geographic coordinate reference system.
    3658             :  * <li> "WGS84": same as "EPSG:4326" (axis order lat/long).
    3659             :  * <li> "WGS72": same as "EPSG:4322" (axis order lat/long).
    3660             :  * <li> "NAD83": same as "EPSG:4269" (axis order lat/long).
    3661             :  * <li> "NAD27": same as "EPSG:4267" (axis order lat/long).
    3662             :  * <li> "CRS84", "CRS:84": same as "WGS84" but with axis order long/lat.
    3663             :  * <li> "CRS72", "CRS:72": same as "WGS72" but with axis order long/lat.
    3664             :  * <li> "CRS27", "CRS:27": same as "NAD27" but with axis order long/lat.
    3665             :  * </ul>
    3666             :  *
    3667             :  * @param pszName name of well known geographic coordinate system.
    3668             :  * @return OGRERR_NONE on success, or OGRERR_FAILURE if the name isn't
    3669             :  * recognised, the target object is already initialized, or an EPSG value
    3670             :  * can't be successfully looked up.
    3671             :  */
    3672             : 
    3673        5028 : OGRErr OGRSpatialReference::SetWellKnownGeogCS(const char *pszName)
    3674             : 
    3675             : {
    3676       10056 :     TAKE_OPTIONAL_LOCK();
    3677             : 
    3678             :     /* -------------------------------------------------------------------- */
    3679             :     /*      Check for EPSG authority numbers.                               */
    3680             :     /* -------------------------------------------------------------------- */
    3681        5028 :     if (STARTS_WITH_CI(pszName, "EPSG:") || STARTS_WITH_CI(pszName, "EPSGA:"))
    3682             :     {
    3683          86 :         OGRSpatialReference oSRS2;
    3684          43 :         const OGRErr eErr = oSRS2.importFromEPSG(atoi(pszName + 5));
    3685          43 :         if (eErr != OGRERR_NONE)
    3686           0 :             return eErr;
    3687             : 
    3688          43 :         if (!oSRS2.IsGeographic())
    3689           0 :             return OGRERR_FAILURE;
    3690             : 
    3691          43 :         return CopyGeogCSFrom(&oSRS2);
    3692             :     }
    3693             : 
    3694             :     /* -------------------------------------------------------------------- */
    3695             :     /*      Check for simple names.                                         */
    3696             :     /* -------------------------------------------------------------------- */
    3697        4985 :     const char *pszWKT = nullptr;
    3698             : 
    3699        4985 :     if (EQUAL(pszName, "WGS84"))
    3700             :     {
    3701        2838 :         pszWKT = SRS_WKT_WGS84_LAT_LONG;
    3702             :     }
    3703        2147 :     else if (EQUAL(pszName, "CRS84") || EQUAL(pszName, "CRS:84"))
    3704             :     {
    3705        1207 :         pszWKT =
    3706             :             "GEOGCRS[\"WGS 84 (CRS84)\",DATUM[\"World Geodetic System 1984\","
    3707             :             "ELLIPSOID[\"WGS "
    3708             :             "84\",6378137,298.257223563,LENGTHUNIT[\"metre\",1]]],"
    3709             :             "PRIMEM[\"Greenwich\",0,ANGLEUNIT[\"degree\",0.0174532925199433]],"
    3710             :             "CS[ellipsoidal,2],AXIS[\"geodetic longitude (Lon)\",east,ORDER[1],"
    3711             :             "ANGLEUNIT[\"degree\",0.0174532925199433]],"
    3712             :             "AXIS[\"geodetic latitude (Lat)\",north,ORDER[2],"
    3713             :             "ANGLEUNIT[\"degree\",0.0174532925199433]],"
    3714             :             "USAGE[SCOPE[\"unknown\"],AREA[\"World\"],BBOX[-90,-180,90,180]],"
    3715             :             "ID[\"OGC\",\"CRS84\"]]";
    3716             :     }
    3717         940 :     else if (EQUAL(pszName, "WGS72"))
    3718          19 :         pszWKT =
    3719             :             "GEOGCS[\"WGS 72\",DATUM[\"WGS_1972\","
    3720             :             "SPHEROID[\"WGS 72\",6378135,298.26,AUTHORITY[\"EPSG\",\"7043\"]],"
    3721             :             "AUTHORITY[\"EPSG\",\"6322\"]],"
    3722             :             "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],"
    3723             :             "UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],"
    3724             :             "AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\",EAST],"
    3725             :             "AUTHORITY[\"EPSG\",\"4322\"]]";
    3726             : 
    3727         921 :     else if (EQUAL(pszName, "NAD27"))
    3728         133 :         pszWKT =
    3729             :             "GEOGCS[\"NAD27\",DATUM[\"North_American_Datum_1927\","
    3730             :             "SPHEROID[\"Clarke 1866\",6378206.4,294.9786982138982,"
    3731             :             "AUTHORITY[\"EPSG\",\"7008\"]],AUTHORITY[\"EPSG\",\"6267\"]],"
    3732             :             "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],"
    3733             :             "UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],"
    3734             :             "AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\",EAST],"
    3735             :             "AUTHORITY[\"EPSG\",\"4267\"]]";
    3736             : 
    3737         788 :     else if (EQUAL(pszName, "CRS27") || EQUAL(pszName, "CRS:27"))
    3738           0 :         pszWKT =
    3739             :             "GEOGCS[\"NAD27\",DATUM[\"North_American_Datum_1927\","
    3740             :             "SPHEROID[\"Clarke 1866\",6378206.4,294.9786982138982,"
    3741             :             "AUTHORITY[\"EPSG\",\"7008\"]],AUTHORITY[\"EPSG\",\"6267\"]],"
    3742             :             "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],"
    3743             :             "UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],"
    3744             :             "AXIS[\"Longitude\",EAST],AXIS[\"Latitude\",NORTH]]";
    3745             : 
    3746         788 :     else if (EQUAL(pszName, "NAD83"))
    3747         784 :         pszWKT =
    3748             :             "GEOGCS[\"NAD83\",DATUM[\"North_American_Datum_1983\","
    3749             :             "SPHEROID[\"GRS 1980\",6378137,298.257222101,"
    3750             :             "AUTHORITY[\"EPSG\",\"7019\"]],"
    3751             :             "AUTHORITY[\"EPSG\",\"6269\"]],"
    3752             :             "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],"
    3753             :             "UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],"
    3754             :             "AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\",EAST],AUTHORITY["
    3755             :             "\"EPSG\",\"4269\"]]";
    3756             : 
    3757           4 :     else if (EQUAL(pszName, "CRS83") || EQUAL(pszName, "CRS:83"))
    3758           0 :         pszWKT =
    3759             :             "GEOGCS[\"NAD83\",DATUM[\"North_American_Datum_1983\","
    3760             :             "SPHEROID[\"GRS 1980\",6378137,298.257222101,"
    3761             :             "AUTHORITY[\"EPSG\",\"7019\"]],"
    3762             :             "AUTHORITY[\"EPSG\",\"6269\"]],"
    3763             :             "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],"
    3764             :             "UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],"
    3765             :             "AXIS[\"Longitude\",EAST],AXIS[\"Latitude\",NORTH]]";
    3766             : 
    3767             :     else
    3768           4 :         return OGRERR_FAILURE;
    3769             : 
    3770             :     /* -------------------------------------------------------------------- */
    3771             :     /*      Import the WKT                                                  */
    3772             :     /* -------------------------------------------------------------------- */
    3773        9962 :     OGRSpatialReference oSRS2;
    3774        4981 :     const OGRErr eErr = oSRS2.importFromWkt(pszWKT);
    3775        4981 :     if (eErr != OGRERR_NONE)
    3776           0 :         return eErr;
    3777             : 
    3778             :     /* -------------------------------------------------------------------- */
    3779             :     /*      Copy over.                                                      */
    3780             :     /* -------------------------------------------------------------------- */
    3781        4981 :     return CopyGeogCSFrom(&oSRS2);
    3782             : }
    3783             : 
    3784             : /************************************************************************/
    3785             : /*                       OSRSetWellKnownGeogCS()                        */
    3786             : /************************************************************************/
    3787             : 
    3788             : /**
    3789             :  * \brief Set a GeogCS based on well known name.
    3790             :  *
    3791             :  * This function is the same as OGRSpatialReference::SetWellKnownGeogCS()
    3792             :  */
    3793         161 : OGRErr OSRSetWellKnownGeogCS(OGRSpatialReferenceH hSRS, const char *pszName)
    3794             : 
    3795             : {
    3796         161 :     VALIDATE_POINTER1(hSRS, "OSRSetWellKnownGeogCS", OGRERR_FAILURE);
    3797             : 
    3798         161 :     return ToPointer(hSRS)->SetWellKnownGeogCS(pszName);
    3799             : }
    3800             : 
    3801             : /************************************************************************/
    3802             : /*                           CopyGeogCSFrom()                           */
    3803             : /************************************************************************/
    3804             : 
    3805             : /**
    3806             :  * \brief Copy GEOGCS from another OGRSpatialReference.
    3807             :  *
    3808             :  * The GEOGCS information is copied into this OGRSpatialReference from another.
    3809             :  * If this object has a PROJCS root already, the GEOGCS is installed within
    3810             :  * it, otherwise it is installed as the root.
    3811             :  *
    3812             :  * @param poSrcSRS the spatial reference to copy the GEOGCS information from.
    3813             :  *
    3814             :  * @return OGRERR_NONE on success or an error code.
    3815             :  */
    3816        5494 : OGRErr OGRSpatialReference::CopyGeogCSFrom(const OGRSpatialReference *poSrcSRS)
    3817             : 
    3818             : {
    3819        5494 :     return CopyGeogCSFrom(poSrcSRS, false);
    3820             : }
    3821             : 
    3822             : /**
    3823             :  * \brief Copy GEOGCS from another OGRSpatialReference.
    3824             :  *
    3825             :  * The GEOGCS information is copied into this OGRSpatialReference from another.
    3826             :  * If this object has a PROJCS root already, the GEOGCS is installed within
    3827             :  * it, otherwise it is installed as the root.
    3828             :  *
    3829             :  * @param poSrcSRS the spatial reference to copy the GEOGCS information from.
    3830             :  * @param bInnerMostGeogCRS Whether the inner-most geographic CRS must be used.
    3831             :  *                          This setting makes a difference if this CRS is a
    3832             :  *                          derived geographic CRS. Setting bInnerMostGeogCRS
    3833             :  *                          to true will then extract its base CRS.
    3834             :  *
    3835             :  * @return OGRERR_NONE on success or an error code.
    3836             :  * @since 3.13.2
    3837             :  */
    3838        5640 : OGRErr OGRSpatialReference::CopyGeogCSFrom(const OGRSpatialReference *poSrcSRS,
    3839             :                                            bool bInnerMostGeogCRS)
    3840             : 
    3841             : {
    3842       11280 :     TAKE_OPTIONAL_LOCK();
    3843             : 
    3844        5640 :     d->bNormInfoSet = FALSE;
    3845        5640 :     d->m_osAngularUnits.clear();
    3846        5640 :     d->m_dfAngularUnitToRadian = 0.0;
    3847        5640 :     d->m_osPrimeMeridianName.clear();
    3848        5640 :     d->dfFromGreenwich = 0.0;
    3849             : 
    3850        5640 :     d->refreshProjObj();
    3851        5640 :     poSrcSRS->d->refreshProjObj();
    3852        5640 :     if (!poSrcSRS->d->m_pj_crs)
    3853             :     {
    3854           1 :         return OGRERR_FAILURE;
    3855             :     }
    3856             :     auto geodCRS =
    3857        5639 :         proj_crs_get_geodetic_crs(d->getPROJContext(), poSrcSRS->d->m_pj_crs);
    3858        5639 :     if (!geodCRS)
    3859             :     {
    3860           0 :         return OGRERR_FAILURE;
    3861             :     }
    3862             : 
    3863        5639 :     if (bInnerMostGeogCRS && poSrcSRS->IsDerivedGeographic())
    3864             :     {
    3865           0 :         auto baseCRS = proj_get_source_crs(d->getPROJContext(), geodCRS);
    3866           0 :         if (!baseCRS)
    3867           0 :             return OGRERR_FAILURE;
    3868           0 :         proj_destroy(geodCRS);
    3869           0 :         geodCRS = baseCRS;
    3870             :     }
    3871             : 
    3872             :     /* -------------------------------------------------------------------- */
    3873             :     /*      Handle geocentric coordinate systems specially.  We just        */
    3874             :     /*      want to copy the DATUM.                                         */
    3875             :     /* -------------------------------------------------------------------- */
    3876        5639 :     if (d->m_pjType == PJ_TYPE_GEOCENTRIC_CRS)
    3877             :     {
    3878           3 :         auto datum = proj_crs_get_datum(d->getPROJContext(), geodCRS);
    3879             : #if PROJ_VERSION_MAJOR > 7 ||                                                  \
    3880             :     (PROJ_VERSION_MAJOR == 7 && PROJ_VERSION_MINOR >= 2)
    3881             :         if (datum == nullptr)
    3882             :         {
    3883             :             datum = proj_crs_get_datum_ensemble(d->getPROJContext(), geodCRS);
    3884             :         }
    3885             : #endif
    3886           3 :         if (datum == nullptr)
    3887             :         {
    3888           0 :             proj_destroy(geodCRS);
    3889           0 :             return OGRERR_FAILURE;
    3890             :         }
    3891             : 
    3892           3 :         const char *pszUnitName = nullptr;
    3893           3 :         double unitConvFactor = GetLinearUnits(&pszUnitName);
    3894             : 
    3895           3 :         auto pj_crs = proj_create_geocentric_crs_from_datum(
    3896           3 :             d->getPROJContext(), proj_get_name(d->m_pj_crs), datum, pszUnitName,
    3897             :             unitConvFactor);
    3898           3 :         proj_destroy(datum);
    3899             : 
    3900           3 :         d->setPjCRS(pj_crs);
    3901             :     }
    3902             : 
    3903        5636 :     else if (d->m_pjType == PJ_TYPE_PROJECTED_CRS)
    3904             :     {
    3905         313 :         auto pj_crs = proj_crs_alter_geodetic_crs(d->getPROJContext(),
    3906         313 :                                                   d->m_pj_crs, geodCRS);
    3907         313 :         d->setPjCRS(pj_crs);
    3908             :     }
    3909             : 
    3910             :     else
    3911             :     {
    3912        5323 :         d->setPjCRS(proj_clone(d->getPROJContext(), geodCRS));
    3913             :     }
    3914             : 
    3915             :     // Apply TOWGS84 of source CRS
    3916        5639 :     if (poSrcSRS->d->m_pjType == PJ_TYPE_BOUND_CRS)
    3917             :     {
    3918             :         auto target =
    3919           1 :             proj_get_target_crs(d->getPROJContext(), poSrcSRS->d->m_pj_crs);
    3920           1 :         auto co = proj_crs_get_coordoperation(d->getPROJContext(),
    3921           1 :                                               poSrcSRS->d->m_pj_crs);
    3922           1 :         d->setPjCRS(proj_crs_create_bound_crs(d->getPROJContext(), d->m_pj_crs,
    3923             :                                               target, co));
    3924           1 :         proj_destroy(target);
    3925           1 :         proj_destroy(co);
    3926             :     }
    3927             : 
    3928        5639 :     proj_destroy(geodCRS);
    3929             : 
    3930        5639 :     return OGRERR_NONE;
    3931             : }
    3932             : 
    3933             : /************************************************************************/
    3934             : /*                         OSRCopyGeogCSFrom()                          */
    3935             : /************************************************************************/
    3936             : 
    3937             : /**
    3938             :  * \brief Copy GEOGCS from another OGRSpatialReference.
    3939             :  *
    3940             :  * This function is the same as OGRSpatialReference::CopyGeogCSFrom()
    3941             :  */
    3942           1 : OGRErr OSRCopyGeogCSFrom(OGRSpatialReferenceH hSRS,
    3943             :                          const OGRSpatialReferenceH hSrcSRS)
    3944             : 
    3945             : {
    3946           1 :     VALIDATE_POINTER1(hSRS, "OSRCopyGeogCSFrom", OGRERR_FAILURE);
    3947           1 :     VALIDATE_POINTER1(hSrcSRS, "OSRCopyGeogCSFrom", OGRERR_FAILURE);
    3948             : 
    3949           1 :     return ToPointer(hSRS)->CopyGeogCSFrom(ToPointer(hSrcSRS));
    3950             : }
    3951             : 
    3952             : /************************************************************************/
    3953             : /*                SET_FROM_USER_INPUT_LIMITATIONS_get()                 */
    3954             : /************************************************************************/
    3955             : 
    3956             : /** Limitations for OGRSpatialReference::SetFromUserInput().
    3957             :  *
    3958             :  * Currently ALLOW_NETWORK_ACCESS=NO and ALLOW_FILE_ACCESS=NO.
    3959             :  */
    3960             : const char *const OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS[] = {
    3961             :     "ALLOW_NETWORK_ACCESS=NO", "ALLOW_FILE_ACCESS=NO", nullptr};
    3962             : 
    3963             : /**
    3964             :  * \brief Return OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS
    3965             :  */
    3966        2699 : CSLConstList OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()
    3967             : {
    3968        2699 :     return SET_FROM_USER_INPUT_LIMITATIONS;
    3969             : }
    3970             : 
    3971             : /************************************************************************/
    3972             : /*                   RemoveIDFromMemberOfEnsembles()                    */
    3973             : /************************************************************************/
    3974             : 
    3975             : // cppcheck-suppress constParameterReference
    3976         243 : static void RemoveIDFromMemberOfEnsembles(CPLJSONObject &obj)
    3977             : {
    3978             :     // Remove "id" from members of datum ensembles for compatibility with
    3979             :     // older PROJ versions
    3980             :     // Cf https://github.com/opengeospatial/geoparquet/discussions/110
    3981             :     // and https://github.com/OSGeo/PROJ/pull/3221
    3982         243 :     if (obj.GetType() == CPLJSONObject::Type::Object)
    3983             :     {
    3984         300 :         for (auto &subObj : obj.GetChildren())
    3985             :         {
    3986         235 :             RemoveIDFromMemberOfEnsembles(subObj);
    3987             :         }
    3988             :     }
    3989         198 :     else if (obj.GetType() == CPLJSONObject::Type::Array &&
    3990         198 :              obj.GetName() == "members")
    3991             :     {
    3992          60 :         for (auto &subObj : obj.ToArray())
    3993             :         {
    3994          52 :             if (subObj.GetType() == CPLJSONObject::Type::Object)
    3995             :             {
    3996          51 :                 subObj.Delete("id");
    3997             :             }
    3998             :         }
    3999             :     }
    4000         243 : }
    4001             : 
    4002             : /************************************************************************/
    4003             : /*                          SetFromUserInput()                          */
    4004             : /************************************************************************/
    4005             : 
    4006             : /**
    4007             :  * \brief Set spatial reference from various text formats.
    4008             :  *
    4009             :  * This method will examine the provided input, and try to deduce the
    4010             :  * format, and then use it to initialize the spatial reference system.  It
    4011             :  * may take the following forms:
    4012             :  *
    4013             :  * <ol>
    4014             :  * <li> Well Known Text definition - passed on to importFromWkt().
    4015             :  * <li> "EPSG:n" - number passed on to importFromEPSG().
    4016             :  * <li> "EPSGA:n" - number passed on to importFromEPSGA().
    4017             :  * <li> "AUTO:proj_id,unit_id,lon0,lat0" - WMS auto projections.
    4018             :  * <li> "urn:ogc:def:crs:EPSG::n" - ogc urns
    4019             :  * <li> PROJ.4 definitions - passed on to importFromProj4().
    4020             :  * <li> filename - file read for WKT, XML or PROJ.4 definition.
    4021             :  * <li> well known name accepted by SetWellKnownGeogCS(), such as NAD27, NAD83,
    4022             :  * WGS84 or WGS72.
    4023             :  * <li> "IGNF:xxxx", "ESRI:xxxx", etc. from definitions from the PROJ database;
    4024             :  * <li> PROJJSON (PROJ &gt;= 6.2)
    4025             :  * </ol>
    4026             :  *
    4027             :  * It is expected that this method will be extended in the future to support
    4028             :  * XML and perhaps a simplified "minilanguage" for indicating common UTM and
    4029             :  * State Plane definitions.
    4030             :  *
    4031             :  * This method is intended to be flexible, but by its nature it is
    4032             :  * imprecise as it must guess information about the format intended.  When
    4033             :  * possible applications should call the specific method appropriate if the
    4034             :  * input is known to be in a particular format.
    4035             :  *
    4036             :  * This method does the same thing as the OSRSetFromUserInput() function.
    4037             :  *
    4038             :  * @param pszDefinition text definition to try to deduce SRS from.
    4039             :  *
    4040             :  * @return OGRERR_NONE on success, or an error code if the name isn't
    4041             :  * recognised, the definition is corrupt, or an EPSG value can't be
    4042             :  * successfully looked up.
    4043             :  */
    4044             : 
    4045       23768 : OGRErr OGRSpatialReference::SetFromUserInput(const char *pszDefinition)
    4046             : {
    4047       23768 :     return SetFromUserInput(pszDefinition, nullptr);
    4048             : }
    4049             : 
    4050             : /**
    4051             :  * \brief Set spatial reference from various text formats.
    4052             :  *
    4053             :  * This method will examine the provided input, and try to deduce the
    4054             :  * format, and then use it to initialize the spatial reference system.  It
    4055             :  * may take the following forms:
    4056             :  *
    4057             :  * <ol>
    4058             :  * <li> Well Known Text definition - passed on to importFromWkt().
    4059             :  * <li> "EPSG:n" - number passed on to importFromEPSG().
    4060             :  * <li> "EPSGA:n" - number passed on to importFromEPSGA().
    4061             :  * <li> "AUTO:proj_id,unit_id,lon0,lat0" - WMS auto projections.
    4062             :  * <li> "urn:ogc:def:crs:EPSG::n" - ogc urns
    4063             :  * <li> PROJ.4 definitions - passed on to importFromProj4().
    4064             :  * <li> filename - file read for WKT, XML or PROJ.4 definition.
    4065             :  * <li> well known name accepted by SetWellKnownGeogCS(), such as NAD27, NAD83,
    4066             :  * WGS84 or WGS72.
    4067             :  * <li> "IGNF:xxxx", "ESRI:xxxx", etc. from definitions from the PROJ database;
    4068             :  * <li> PROJJSON (PROJ &gt;= 6.2)
    4069             :  * </ol>
    4070             :  *
    4071             :  * It is expected that this method will be extended in the future to support
    4072             :  * XML and perhaps a simplified "minilanguage" for indicating common UTM and
    4073             :  * State Plane definitions.
    4074             :  *
    4075             :  * This method is intended to be flexible, but by its nature it is
    4076             :  * imprecise as it must guess information about the format intended.  When
    4077             :  * possible applications should call the specific method appropriate if the
    4078             :  * input is known to be in a particular format.
    4079             :  *
    4080             :  * This method does the same thing as the OSRSetFromUserInput() and
    4081             :  * OSRSetFromUserInputEx() functions.
    4082             :  *
    4083             :  * @param pszDefinition text definition to try to deduce SRS from.
    4084             :  *
    4085             :  * @param papszOptions NULL terminated list of options, or NULL.
    4086             :  * <ol>
    4087             :  * <li> ALLOW_NETWORK_ACCESS=YES/NO.
    4088             :  *      Whether http:// or https:// access is allowed. Defaults to YES.
    4089             :  * <li> ALLOW_FILE_ACCESS=YES/NO.
    4090             :  *      Whether reading a file using the Virtual File System layer is allowed
    4091             :  *      (can also involve network access). Defaults to YES.
    4092             :  * </ol>
    4093             :  *
    4094             :  * @return OGRERR_NONE on success, or an error code if the name isn't
    4095             :  * recognised, the definition is corrupt, or an EPSG value can't be
    4096             :  * successfully looked up.
    4097             :  */
    4098             : 
    4099       31413 : OGRErr OGRSpatialReference::SetFromUserInput(const char *pszDefinition,
    4100             :                                              CSLConstList papszOptions)
    4101             : {
    4102       62826 :     TAKE_OPTIONAL_LOCK();
    4103             : 
    4104             :     // Skip leading white space
    4105       31415 :     while (isspace(static_cast<unsigned char>(*pszDefinition)))
    4106           2 :         pszDefinition++;
    4107             : 
    4108       31413 :     if (STARTS_WITH_CI(pszDefinition, "ESRI::"))
    4109             :     {
    4110           1 :         pszDefinition += 6;
    4111             :     }
    4112             : 
    4113             :     /* -------------------------------------------------------------------- */
    4114             :     /*      Is it a recognised syntax?                                      */
    4115             :     /* -------------------------------------------------------------------- */
    4116       31413 :     const char *const wktKeywords[] = {
    4117             :         // WKT1
    4118             :         "GEOGCS", "GEOCCS", "PROJCS", "VERT_CS", "COMPD_CS", "LOCAL_CS",
    4119             :         // WKT2"
    4120             :         "GEODCRS", "GEOGCRS", "GEODETICCRS", "GEOGRAPHICCRS", "PROJCRS",
    4121             :         "PROJECTEDCRS", "VERTCRS", "VERTICALCRS", "COMPOUNDCRS", "ENGCRS",
    4122             :         "ENGINEERINGCRS", "BOUNDCRS", "DERIVEDPROJCRS", "COORDINATEMETADATA"};
    4123      493248 :     for (const char *keyword : wktKeywords)
    4124             :     {
    4125      470859 :         if (STARTS_WITH_CI(pszDefinition, keyword))
    4126             :         {
    4127        9024 :             return importFromWkt(pszDefinition);
    4128             :         }
    4129             :     }
    4130             : 
    4131       22389 :     const bool bStartsWithEPSG = STARTS_WITH_CI(pszDefinition, "EPSG:");
    4132       22389 :     if (bStartsWithEPSG || STARTS_WITH_CI(pszDefinition, "EPSGA:"))
    4133             :     {
    4134       12551 :         OGRErr eStatus = OGRERR_NONE;
    4135             : 
    4136       12551 :         if (strchr(pszDefinition, '+') || strchr(pszDefinition, '@'))
    4137             :         {
    4138             :             // Use proj_create() as it allows things like EPSG:3157+4617
    4139             :             // that are not normally supported by the below code that
    4140             :             // builds manually a compound CRS
    4141          69 :             PJ *pj = proj_create(d->getPROJContext(), pszDefinition);
    4142          69 :             if (!pj)
    4143             :             {
    4144           1 :                 return OGRERR_FAILURE;
    4145             :             }
    4146          68 :             Clear();
    4147          68 :             d->setPjCRS(pj);
    4148          68 :             return OGRERR_NONE;
    4149             :         }
    4150             :         else
    4151             :         {
    4152             :             eStatus =
    4153       12482 :                 importFromEPSG(atoi(pszDefinition + (bStartsWithEPSG ? 5 : 6)));
    4154             :         }
    4155             : 
    4156       12482 :         return eStatus;
    4157             :     }
    4158             : 
    4159        9838 :     if (STARTS_WITH_CI(pszDefinition, "urn:ogc:def:crs:") ||
    4160        9109 :         STARTS_WITH_CI(pszDefinition, "urn:ogc:def:crs,crs:") ||
    4161        9108 :         STARTS_WITH_CI(pszDefinition, "urn:x-ogc:def:crs:") ||
    4162        9050 :         STARTS_WITH_CI(pszDefinition, "urn:opengis:crs:") ||
    4163        9050 :         STARTS_WITH_CI(pszDefinition, "urn:opengis:def:crs:") ||
    4164        9050 :         STARTS_WITH_CI(pszDefinition, "urn:ogc:def:coordinateMetadata:"))
    4165         788 :         return importFromURN(pszDefinition);
    4166             : 
    4167        9050 :     if (STARTS_WITH_CI(pszDefinition, "http://opengis.net/def/crs") ||
    4168        9048 :         STARTS_WITH_CI(pszDefinition, "https://opengis.net/def/crs") ||
    4169        9047 :         STARTS_WITH_CI(pszDefinition, "http://www.opengis.net/def/crs") ||
    4170        1726 :         STARTS_WITH_CI(pszDefinition, "https://www.opengis.net/def/crs") ||
    4171        1725 :         STARTS_WITH_CI(pszDefinition, "www.opengis.net/def/crs"))
    4172        7325 :         return importFromCRSURL(pszDefinition);
    4173             : 
    4174        1725 :     if (STARTS_WITH_CI(pszDefinition, "AUTO:"))
    4175           1 :         return importFromWMSAUTO(pszDefinition);
    4176             : 
    4177             :     // WMS/WCS OGC codes like OGC:CRS84.
    4178        1724 :     if (EQUAL(pszDefinition, "OGC:CRS84"))
    4179          79 :         return SetWellKnownGeogCS(pszDefinition + 4);
    4180             : 
    4181        1645 :     if (STARTS_WITH_CI(pszDefinition, "CRS:"))
    4182           1 :         return SetWellKnownGeogCS(pszDefinition);
    4183             : 
    4184        1644 :     if (STARTS_WITH_CI(pszDefinition, "DICT:") && strstr(pszDefinition, ","))
    4185             :     {
    4186           0 :         char *pszFile = CPLStrdup(pszDefinition + 5);
    4187           0 :         char *pszCode = strstr(pszFile, ",") + 1;
    4188             : 
    4189           0 :         pszCode[-1] = '\0';
    4190             : 
    4191           0 :         OGRErr err = importFromDict(pszFile, pszCode);
    4192           0 :         CPLFree(pszFile);
    4193             : 
    4194           0 :         return err;
    4195             :     }
    4196             : 
    4197        1644 :     if (EQUAL(pszDefinition, "NAD27") || EQUAL(pszDefinition, "NAD83") ||
    4198        1639 :         EQUAL(pszDefinition, "WGS84") || EQUAL(pszDefinition, "WGS72"))
    4199             :     {
    4200         593 :         Clear();
    4201         593 :         return SetWellKnownGeogCS(pszDefinition);
    4202             :     }
    4203             : 
    4204             :     // PROJJSON
    4205        1051 :     if (pszDefinition[0] == '{' && strstr(pszDefinition, "\"type\"") &&
    4206         179 :         (strstr(pszDefinition, "GeodeticCRS") ||
    4207         179 :          strstr(pszDefinition, "GeographicCRS") ||
    4208         129 :          strstr(pszDefinition, "ProjectedCRS") ||
    4209           0 :          strstr(pszDefinition, "VerticalCRS") ||
    4210           0 :          strstr(pszDefinition, "BoundCRS") ||
    4211           0 :          strstr(pszDefinition, "CompoundCRS") ||
    4212           0 :          strstr(pszDefinition, "DerivedGeodeticCRS") ||
    4213           0 :          strstr(pszDefinition, "DerivedGeographicCRS") ||
    4214           0 :          strstr(pszDefinition, "DerivedProjectedCRS") ||
    4215           0 :          strstr(pszDefinition, "DerivedVerticalCRS") ||
    4216           0 :          strstr(pszDefinition, "EngineeringCRS") ||
    4217           0 :          strstr(pszDefinition, "DerivedEngineeringCRS") ||
    4218           0 :          strstr(pszDefinition, "ParametricCRS") ||
    4219           0 :          strstr(pszDefinition, "DerivedParametricCRS") ||
    4220           0 :          strstr(pszDefinition, "TemporalCRS") ||
    4221           0 :          strstr(pszDefinition, "DerivedTemporalCRS")))
    4222             :     {
    4223             :         PJ *pj;
    4224         179 :         if (strstr(pszDefinition, "datum_ensemble") != nullptr)
    4225             :         {
    4226             :             // PROJ < 9.0.1 doesn't like a datum_ensemble whose member have
    4227             :             // an unknown id.
    4228           8 :             CPLJSONDocument oCRSDoc;
    4229           8 :             if (!oCRSDoc.LoadMemory(pszDefinition))
    4230           0 :                 return OGRERR_CORRUPT_DATA;
    4231           8 :             CPLJSONObject oCRSRoot = oCRSDoc.GetRoot();
    4232           8 :             RemoveIDFromMemberOfEnsembles(oCRSRoot);
    4233           8 :             pj = proj_create(d->getPROJContext(), oCRSRoot.ToString().c_str());
    4234             :         }
    4235             :         else
    4236             :         {
    4237         171 :             pj = proj_create(d->getPROJContext(), pszDefinition);
    4238             :         }
    4239         179 :         if (!pj)
    4240             :         {
    4241           2 :             return OGRERR_FAILURE;
    4242             :         }
    4243         177 :         Clear();
    4244         177 :         d->setPjCRS(pj);
    4245         177 :         return OGRERR_NONE;
    4246             :     }
    4247             : 
    4248         872 :     if (strstr(pszDefinition, "+proj") != nullptr ||
    4249         412 :         strstr(pszDefinition, "+init") != nullptr)
    4250         460 :         return importFromProj4(pszDefinition);
    4251             : 
    4252         412 :     if (STARTS_WITH_CI(pszDefinition, "http://") ||
    4253         387 :         STARTS_WITH_CI(pszDefinition, "https://"))
    4254             :     {
    4255          26 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions,
    4256             :                                              "ALLOW_NETWORK_ACCESS", "YES")))
    4257           0 :             return importFromUrl(pszDefinition);
    4258             : 
    4259          26 :         CPLError(CE_Failure, CPLE_AppDefined,
    4260             :                  "Cannot import %s due to ALLOW_NETWORK_ACCESS=NO",
    4261             :                  pszDefinition);
    4262          26 :         return OGRERR_FAILURE;
    4263             :     }
    4264             : 
    4265         386 :     if (EQUAL(pszDefinition, "osgb:BNG"))
    4266             :     {
    4267           8 :         return importFromEPSG(27700);
    4268             :     }
    4269             : 
    4270             :     // Used by German CityGML files
    4271         378 :     if (EQUAL(pszDefinition, "urn:adv:crs:ETRS89_UTM32*DE_DHHN92_NH"))
    4272             :     {
    4273             :         // "ETRS89 / UTM Zone 32N + DHHN92 height"
    4274           0 :         return SetFromUserInput("EPSG:25832+5783");
    4275             :     }
    4276         378 :     else if (EQUAL(pszDefinition, "urn:adv:crs:ETRS89_UTM32*DE_DHHN2016_NH"))
    4277             :     {
    4278             :         // "ETRS89 / UTM Zone 32N + DHHN2016 height"
    4279           3 :         return SetFromUserInput("EPSG:25832+7837");
    4280             :     }
    4281             : 
    4282             :     // Used by  Japan's Fundamental Geospatial Data (FGD) GML
    4283         375 :     if (EQUAL(pszDefinition, "fguuid:jgd2001.bl"))
    4284           0 :         return importFromEPSG(4612);  // JGD2000 (slight difference in years)
    4285         375 :     else if (EQUAL(pszDefinition, "fguuid:jgd2011.bl"))
    4286           8 :         return importFromEPSG(6668);  // JGD2011
    4287         367 :     else if (EQUAL(pszDefinition, "fguuid:jgd2024.bl"))
    4288             :     {
    4289             :         // FIXME when EPSG attributes a CRS code
    4290           3 :         return importFromWkt(
    4291             :             "GEOGCRS[\"JGD2024\",\n"
    4292             :             "    DATUM[\"Japanese Geodetic Datum 2024\",\n"
    4293             :             "        ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n"
    4294             :             "            LENGTHUNIT[\"metre\",1]]],\n"
    4295             :             "    PRIMEM[\"Greenwich\",0,\n"
    4296             :             "        ANGLEUNIT[\"degree\",0.0174532925199433]],\n"
    4297             :             "    CS[ellipsoidal,2],\n"
    4298             :             "        AXIS[\"geodetic latitude (Lat)\",north,\n"
    4299             :             "            ORDER[1],\n"
    4300             :             "            ANGLEUNIT[\"degree\",0.0174532925199433]],\n"
    4301             :             "        AXIS[\"geodetic longitude (Lon)\",east,\n"
    4302             :             "            ORDER[2],\n"
    4303             :             "            ANGLEUNIT[\"degree\",0.0174532925199433]],\n"
    4304             :             "    USAGE[\n"
    4305             :             "        SCOPE[\"Horizontal component of 3D system.\"],\n"
    4306             :             "        AREA[\"Japan - onshore and offshore.\"],\n"
    4307           3 :             "        BBOX[17.09,122.38,46.05,157.65]]]");
    4308             :     }
    4309             : 
    4310             :     // Deal with IGNF:xxx, ESRI:xxx, etc from the PROJ database
    4311         364 :     const char *pszDot = strrchr(pszDefinition, ':');
    4312         364 :     if (pszDot)
    4313             :     {
    4314         125 :         CPLString osPrefix(pszDefinition, pszDot - pszDefinition);
    4315             :         auto authorities =
    4316         125 :             proj_get_authorities_from_database(d->getPROJContext());
    4317         125 :         if (authorities)
    4318             :         {
    4319         125 :             std::set<std::string> aosCandidateAuthorities;
    4320         290 :             for (auto iter = authorities; *iter; ++iter)
    4321             :             {
    4322         288 :                 if (*iter == osPrefix)
    4323             :                 {
    4324         123 :                     aosCandidateAuthorities.clear();
    4325         123 :                     aosCandidateAuthorities.insert(*iter);
    4326         123 :                     break;
    4327             :                 }
    4328             :                 // Deal with "IAU_2015" as authority in the list and input
    4329             :                 // "IAU:code"
    4330         165 :                 else if (strncmp(*iter, osPrefix.c_str(), osPrefix.size()) ==
    4331         165 :                              0 &&
    4332           0 :                          (*iter)[osPrefix.size()] == '_')
    4333             :                 {
    4334           0 :                     aosCandidateAuthorities.insert(*iter);
    4335             :                 }
    4336             :                 // Deal with "IAU_2015" as authority in the list and input
    4337             :                 // "IAU:2015:code"
    4338         330 :                 else if (osPrefix.find(':') != std::string::npos &&
    4339         165 :                          osPrefix.size() == strlen(*iter) &&
    4340         165 :                          CPLString(osPrefix).replaceAll(':', '_') == *iter)
    4341             :                 {
    4342           0 :                     aosCandidateAuthorities.clear();
    4343           0 :                     aosCandidateAuthorities.insert(*iter);
    4344           0 :                     break;
    4345             :                 }
    4346             :             }
    4347             : 
    4348         125 :             proj_string_list_destroy(authorities);
    4349             : 
    4350         125 :             if (!aosCandidateAuthorities.empty())
    4351             :             {
    4352         123 :                 auto obj = proj_create_from_database(
    4353             :                     d->getPROJContext(),
    4354         123 :                     aosCandidateAuthorities.rbegin()->c_str(), pszDot + 1,
    4355             :                     PJ_CATEGORY_CRS, false, nullptr);
    4356         123 :                 if (!obj)
    4357             :                 {
    4358          16 :                     return OGRERR_FAILURE;
    4359             :                 }
    4360         107 :                 Clear();
    4361         107 :                 d->setPjCRS(obj);
    4362         107 :                 return OGRERR_NONE;
    4363             :             }
    4364             :         }
    4365             :     }
    4366             : 
    4367             :     /* -------------------------------------------------------------------- */
    4368             :     /*      Try to open it as a file, if allowed.                           */
    4369             :     /* -------------------------------------------------------------------- */
    4370         241 :     if (!CPLTestBool(
    4371             :             CSLFetchNameValueDef(papszOptions, "ALLOW_FILE_ACCESS", "YES")))
    4372             :     {
    4373          22 :         return OGRERR_CORRUPT_DATA;
    4374             :     }
    4375             : 
    4376         438 :     CPLConfigOptionSetter oSetter("CPL_ALLOW_VSISTDIN", "NO", true);
    4377         219 :     VSILFILE *const fp = VSIFOpenL(pszDefinition, "rt");
    4378         219 :     if (fp == nullptr)
    4379         215 :         return OGRERR_CORRUPT_DATA;
    4380             : 
    4381           4 :     const size_t nBufMax = 100000;
    4382           4 :     char *const pszBuffer = static_cast<char *>(CPLMalloc(nBufMax));
    4383           4 :     const size_t nBytes = VSIFReadL(pszBuffer, 1, nBufMax - 1, fp);
    4384           4 :     VSIFCloseL(fp);
    4385             : 
    4386           4 :     if (nBytes == nBufMax - 1)
    4387             :     {
    4388           0 :         CPLDebug("OGR",
    4389             :                  "OGRSpatialReference::SetFromUserInput(%s), opened file "
    4390             :                  "but it is to large for our generous buffer.  Is it really "
    4391             :                  "just a WKT definition?",
    4392             :                  pszDefinition);
    4393           0 :         CPLFree(pszBuffer);
    4394           0 :         return OGRERR_FAILURE;
    4395             :     }
    4396             : 
    4397           4 :     pszBuffer[nBytes] = '\0';
    4398             : 
    4399           4 :     char *pszBufPtr = pszBuffer;
    4400           4 :     while (pszBufPtr[0] == ' ' || pszBufPtr[0] == '\n')
    4401           0 :         pszBufPtr++;
    4402             : 
    4403           4 :     OGRErr err = OGRERR_NONE;
    4404           4 :     if (pszBufPtr[0] == '<')
    4405           0 :         err = importFromXML(pszBufPtr);
    4406           4 :     else if ((strstr(pszBuffer, "+proj") != nullptr ||
    4407           4 :               strstr(pszBuffer, "+init") != nullptr) &&
    4408           0 :              (strstr(pszBuffer, "EXTENSION") == nullptr &&
    4409           0 :               strstr(pszBuffer, "extension") == nullptr))
    4410           0 :         err = importFromProj4(pszBufPtr);
    4411             :     else
    4412             :     {
    4413           4 :         if (STARTS_WITH_CI(pszBufPtr, "ESRI::"))
    4414             :         {
    4415           0 :             pszBufPtr += 6;
    4416             :         }
    4417             : 
    4418             :         // coverity[tainted_data]
    4419           4 :         err = importFromWkt(pszBufPtr);
    4420             :     }
    4421             : 
    4422           4 :     CPLFree(pszBuffer);
    4423             : 
    4424           4 :     return err;
    4425             : }
    4426             : 
    4427             : /************************************************************************/
    4428             : /*                        OSRSetFromUserInput()                         */
    4429             : /************************************************************************/
    4430             : 
    4431             : /**
    4432             :  * \brief Set spatial reference from various text formats.
    4433             :  *
    4434             :  * This function is the same as OGRSpatialReference::SetFromUserInput()
    4435             :  *
    4436             :  * \see OSRSetFromUserInputEx() for a variant allowing to pass options.
    4437             :  */
    4438         385 : OGRErr CPL_STDCALL OSRSetFromUserInput(OGRSpatialReferenceH hSRS,
    4439             :                                        const char *pszDef)
    4440             : 
    4441             : {
    4442         385 :     VALIDATE_POINTER1(hSRS, "OSRSetFromUserInput", OGRERR_FAILURE);
    4443             : 
    4444         385 :     return ToPointer(hSRS)->SetFromUserInput(pszDef);
    4445             : }
    4446             : 
    4447             : /************************************************************************/
    4448             : /*                       OSRSetFromUserInputEx()                        */
    4449             : /************************************************************************/
    4450             : 
    4451             : /**
    4452             :  * \brief Set spatial reference from various text formats.
    4453             :  *
    4454             :  * This function is the same as OGRSpatialReference::SetFromUserInput().
    4455             :  *
    4456             :  * @since GDAL 3.9
    4457             :  */
    4458        1302 : OGRErr OSRSetFromUserInputEx(OGRSpatialReferenceH hSRS, const char *pszDef,
    4459             :                              CSLConstList papszOptions)
    4460             : 
    4461             : {
    4462        1302 :     VALIDATE_POINTER1(hSRS, "OSRSetFromUserInputEx", OGRERR_FAILURE);
    4463             : 
    4464        1302 :     return ToPointer(hSRS)->SetFromUserInput(pszDef, papszOptions);
    4465             : }
    4466             : 
    4467             : /************************************************************************/
    4468             : /*                           ImportFromUrl()                            */
    4469             : /************************************************************************/
    4470             : 
    4471             : /**
    4472             :  * \brief Set spatial reference from a URL.
    4473             :  *
    4474             :  * This method will download the spatial reference at a given URL and
    4475             :  * feed it into SetFromUserInput for you.
    4476             :  *
    4477             :  * This method does the same thing as the OSRImportFromUrl() function.
    4478             :  *
    4479             :  * @param pszUrl text definition to try to deduce SRS from.
    4480             :  *
    4481             :  * @return OGRERR_NONE on success, or an error code with the curl
    4482             :  * error message if it is unable to download data.
    4483             :  */
    4484             : 
    4485           5 : OGRErr OGRSpatialReference::importFromUrl(const char *pszUrl)
    4486             : 
    4487             : {
    4488          10 :     TAKE_OPTIONAL_LOCK();
    4489             : 
    4490           5 :     if (!STARTS_WITH_CI(pszUrl, "http://") &&
    4491           3 :         !STARTS_WITH_CI(pszUrl, "https://"))
    4492             :     {
    4493           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    4494             :                  "The given string is not recognized as a URL"
    4495             :                  "starting with 'http://' -- %s",
    4496             :                  pszUrl);
    4497           2 :         return OGRERR_FAILURE;
    4498             :     }
    4499             : 
    4500             :     /* -------------------------------------------------------------------- */
    4501             :     /*      Fetch the result.                                               */
    4502             :     /* -------------------------------------------------------------------- */
    4503           3 :     CPLErrorReset();
    4504             : 
    4505           6 :     std::string osUrl(pszUrl);
    4506             :     // We have historically supported "http://spatialreference.org/ref/AUTHNAME/CODE/"
    4507             :     // as a valid URL since we used a "Accept: application/x-ogcwkt" header
    4508             :     // to query WKT. To allow a static server to be used, rather append a
    4509             :     // "ogcwkt/" suffix.
    4510           2 :     for (const char *pszPrefix : {"https://spatialreference.org/ref/",
    4511           5 :                                   "http://spatialreference.org/ref/"})
    4512             :     {
    4513           5 :         if (STARTS_WITH(pszUrl, pszPrefix))
    4514             :         {
    4515             :             const CPLStringList aosTokens(
    4516           6 :                 CSLTokenizeString2(pszUrl + strlen(pszPrefix), "/", 0));
    4517           3 :             if (aosTokens.size() == 2)
    4518             :             {
    4519           2 :                 osUrl = "https://spatialreference.org/ref/";
    4520           2 :                 osUrl += aosTokens[0];  // authority
    4521           2 :                 osUrl += '/';
    4522           2 :                 osUrl += aosTokens[1];  // code
    4523           2 :                 osUrl += "/ogcwkt/";
    4524             :             }
    4525           3 :             break;
    4526             :         }
    4527             :     }
    4528             : 
    4529           3 :     const char *pszTimeout = "TIMEOUT=10";
    4530           3 :     char *apszOptions[] = {const_cast<char *>(pszTimeout), nullptr};
    4531             : 
    4532           3 :     CPLHTTPResult *psResult = CPLHTTPFetch(osUrl.c_str(), apszOptions);
    4533             : 
    4534             :     /* -------------------------------------------------------------------- */
    4535             :     /*      Try to handle errors.                                           */
    4536             :     /* -------------------------------------------------------------------- */
    4537             : 
    4538           3 :     if (psResult == nullptr)
    4539           0 :         return OGRERR_FAILURE;
    4540           6 :     if (psResult->nDataLen == 0 || CPLGetLastErrorNo() != 0 ||
    4541           3 :         psResult->pabyData == nullptr)
    4542             :     {
    4543           0 :         if (CPLGetLastErrorNo() == 0)
    4544             :         {
    4545           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4546             :                      "No data was returned from the given URL");
    4547             :         }
    4548           0 :         CPLHTTPDestroyResult(psResult);
    4549           0 :         return OGRERR_FAILURE;
    4550             :     }
    4551             : 
    4552           3 :     if (psResult->nStatus != 0)
    4553             :     {
    4554           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Curl reports error: %d: %s",
    4555             :                  psResult->nStatus, psResult->pszErrBuf);
    4556           0 :         CPLHTTPDestroyResult(psResult);
    4557           0 :         return OGRERR_FAILURE;
    4558             :     }
    4559             : 
    4560           3 :     const char *pszData = reinterpret_cast<const char *>(psResult->pabyData);
    4561           3 :     if (STARTS_WITH_CI(pszData, "http://") ||
    4562           3 :         STARTS_WITH_CI(pszData, "https://"))
    4563             :     {
    4564           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    4565             :                  "The data that was downloaded also starts with 'http://' "
    4566             :                  "and cannot be passed into SetFromUserInput.  Is this "
    4567             :                  "really a spatial reference definition? ");
    4568           0 :         CPLHTTPDestroyResult(psResult);
    4569           0 :         return OGRERR_FAILURE;
    4570             :     }
    4571           3 :     if (OGRERR_NONE != SetFromUserInput(pszData))
    4572             :     {
    4573           0 :         CPLHTTPDestroyResult(psResult);
    4574           0 :         return OGRERR_FAILURE;
    4575             :     }
    4576             : 
    4577           3 :     CPLHTTPDestroyResult(psResult);
    4578           3 :     return OGRERR_NONE;
    4579             : }
    4580             : 
    4581             : /************************************************************************/
    4582             : /*                          OSRimportFromUrl()                          */
    4583             : /************************************************************************/
    4584             : 
    4585             : /**
    4586             :  * \brief Set spatial reference from a URL.
    4587             :  *
    4588             :  * This function is the same as OGRSpatialReference::importFromUrl()
    4589             :  */
    4590           3 : OGRErr OSRImportFromUrl(OGRSpatialReferenceH hSRS, const char *pszUrl)
    4591             : 
    4592             : {
    4593           3 :     VALIDATE_POINTER1(hSRS, "OSRImportFromUrl", OGRERR_FAILURE);
    4594             : 
    4595           3 :     return ToPointer(hSRS)->importFromUrl(pszUrl);
    4596             : }
    4597             : 
    4598             : /************************************************************************/
    4599             : /*                         importFromURNPart()                          */
    4600             : /************************************************************************/
    4601        7536 : OGRErr OGRSpatialReference::importFromURNPart(const char *pszAuthority,
    4602             :                                               const char *pszCode,
    4603             :                                               const char *pszURN)
    4604             : {
    4605             : #if PROJ_AT_LEAST_VERSION(8, 1, 0)
    4606             :     (void)this;
    4607             :     (void)pszAuthority;
    4608             :     (void)pszCode;
    4609             :     (void)pszURN;
    4610             :     return OGRERR_FAILURE;
    4611             : #else
    4612             :     /* -------------------------------------------------------------------- */
    4613             :     /*      Is this an EPSG code? Note that we import it with EPSG          */
    4614             :     /*      preferred axis ordering for geographic coordinate systems.      */
    4615             :     /* -------------------------------------------------------------------- */
    4616        7536 :     if (STARTS_WITH_CI(pszAuthority, "EPSG"))
    4617        6406 :         return importFromEPSGA(atoi(pszCode));
    4618             : 
    4619             :     /* -------------------------------------------------------------------- */
    4620             :     /*      Is this an IAU code?  Lets try for the IAU2000 dictionary.      */
    4621             :     /* -------------------------------------------------------------------- */
    4622        1130 :     if (STARTS_WITH_CI(pszAuthority, "IAU"))
    4623           0 :         return importFromDict("IAU2000.wkt", pszCode);
    4624             : 
    4625             :     /* -------------------------------------------------------------------- */
    4626             :     /*      Is this an OGC code?                                            */
    4627             :     /* -------------------------------------------------------------------- */
    4628        1130 :     if (!STARTS_WITH_CI(pszAuthority, "OGC"))
    4629             :     {
    4630           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    4631             :                  "URN %s has unrecognized authority.", pszURN);
    4632           1 :         return OGRERR_FAILURE;
    4633             :     }
    4634             : 
    4635        1129 :     if (STARTS_WITH_CI(pszCode, "CRS84"))
    4636        1117 :         return SetWellKnownGeogCS(pszCode);
    4637          12 :     else if (STARTS_WITH_CI(pszCode, "CRS83"))
    4638           0 :         return SetWellKnownGeogCS(pszCode);
    4639          12 :     else if (STARTS_WITH_CI(pszCode, "CRS27"))
    4640           0 :         return SetWellKnownGeogCS(pszCode);
    4641          12 :     else if (STARTS_WITH_CI(pszCode, "84"))  // urn:ogc:def:crs:OGC:2:84
    4642          10 :         return SetWellKnownGeogCS("CRS84");
    4643             : 
    4644             :     /* -------------------------------------------------------------------- */
    4645             :     /*      Handle auto codes.  We need to convert from format              */
    4646             :     /*      AUTO42001:99:8888 to format AUTO:42001,99,8888.                 */
    4647             :     /* -------------------------------------------------------------------- */
    4648           2 :     else if (STARTS_WITH_CI(pszCode, "AUTO"))
    4649             :     {
    4650           2 :         char szWMSAuto[100] = {'\0'};
    4651             : 
    4652           2 :         if (strlen(pszCode) > sizeof(szWMSAuto) - 2)
    4653           0 :             return OGRERR_FAILURE;
    4654             : 
    4655           2 :         snprintf(szWMSAuto, sizeof(szWMSAuto), "AUTO:%s", pszCode + 4);
    4656          28 :         for (int i = 5; szWMSAuto[i] != '\0'; i++)
    4657             :         {
    4658          26 :             if (szWMSAuto[i] == ':')
    4659           4 :                 szWMSAuto[i] = ',';
    4660             :         }
    4661             : 
    4662           2 :         return importFromWMSAUTO(szWMSAuto);
    4663             :     }
    4664             : 
    4665             :     /* -------------------------------------------------------------------- */
    4666             :     /*      Not a recognise OGC item.                                       */
    4667             :     /* -------------------------------------------------------------------- */
    4668           0 :     CPLError(CE_Failure, CPLE_AppDefined, "URN %s value not supported.",
    4669             :              pszURN);
    4670             : 
    4671           0 :     return OGRERR_FAILURE;
    4672             : #endif
    4673             : }
    4674             : 
    4675             : /************************************************************************/
    4676             : /*                           importFromURN()                            */
    4677             : /*                                                                      */
    4678             : /*      See OGC recommendation paper 06-023r1 or later for details.     */
    4679             : /************************************************************************/
    4680             : 
    4681             : /**
    4682             :  * \brief Initialize from OGC URN.
    4683             :  *
    4684             :  * Initializes this spatial reference from a coordinate system defined
    4685             :  * by an OGC URN prefixed with "urn:ogc:def:crs:" per recommendation
    4686             :  * paper 06-023r1.  Currently EPSG and OGC authority values are supported,
    4687             :  * including OGC auto codes, but not including CRS1 or CRS88 (NAVD88).
    4688             :  *
    4689             :  * This method is also support through SetFromUserInput() which can
    4690             :  * normally be used for URNs.
    4691             :  *
    4692             :  * @param pszURN the urn string.
    4693             :  *
    4694             :  * @return OGRERR_NONE on success or an error code.
    4695             :  */
    4696             : 
    4697         849 : OGRErr OGRSpatialReference::importFromURN(const char *pszURN)
    4698             : 
    4699             : {
    4700         849 :     constexpr const char *EPSG_URN_CRS_PREFIX = "urn:ogc:def:crs:EPSG::";
    4701        1613 :     if (STARTS_WITH(pszURN, EPSG_URN_CRS_PREFIX) &&
    4702         764 :         CPLGetValueType(pszURN + strlen(EPSG_URN_CRS_PREFIX)) ==
    4703             :             CPL_VALUE_INTEGER)
    4704             :     {
    4705         761 :         return importFromEPSG(atoi(pszURN + strlen(EPSG_URN_CRS_PREFIX)));
    4706             :     }
    4707             : 
    4708         176 :     TAKE_OPTIONAL_LOCK();
    4709             : 
    4710             : #if PROJ_AT_LEAST_VERSION(8, 1, 0)
    4711             : 
    4712             :     // PROJ 8.2.0 has support for IAU codes now.
    4713             : #if !PROJ_AT_LEAST_VERSION(8, 2, 0)
    4714             :     /* -------------------------------------------------------------------- */
    4715             :     /*      Is this an IAU code?  Lets try for the IAU2000 dictionary.      */
    4716             :     /* -------------------------------------------------------------------- */
    4717             :     const char *pszIAU = strstr(pszURN, "IAU");
    4718             :     if (pszIAU)
    4719             :     {
    4720             :         const char *pszCode = strchr(pszIAU, ':');
    4721             :         if (pszCode)
    4722             :         {
    4723             :             ++pszCode;
    4724             :             if (*pszCode == ':')
    4725             :                 ++pszCode;
    4726             :             return importFromDict("IAU2000.wkt", pszCode);
    4727             :         }
    4728             :     }
    4729             : #endif
    4730             : 
    4731             :     if (strlen(pszURN) >= 1000)
    4732             :     {
    4733             :         CPLError(CE_Failure, CPLE_AppDefined, "Too long input string");
    4734             :         return OGRERR_CORRUPT_DATA;
    4735             :     }
    4736             :     auto obj = proj_create(d->getPROJContext(), pszURN);
    4737             :     if (!obj)
    4738             :     {
    4739             :         return OGRERR_FAILURE;
    4740             :     }
    4741             :     Clear();
    4742             :     d->setPjCRS(obj);
    4743             :     return OGRERR_NONE;
    4744             : #else
    4745          88 :     const char *pszCur = nullptr;
    4746             : 
    4747          88 :     if (STARTS_WITH_CI(pszURN, "urn:ogc:def:crs:"))
    4748          23 :         pszCur = pszURN + 16;
    4749          65 :     else if (STARTS_WITH_CI(pszURN, "urn:ogc:def:crs,crs:"))
    4750           1 :         pszCur = pszURN + 20;
    4751          64 :     else if (STARTS_WITH_CI(pszURN, "urn:x-ogc:def:crs:"))
    4752          62 :         pszCur = pszURN + 18;
    4753           2 :     else if (STARTS_WITH_CI(pszURN, "urn:opengis:crs:"))
    4754           0 :         pszCur = pszURN + 16;
    4755           2 :     else if (STARTS_WITH_CI(pszURN, "urn:opengis:def:crs:"))
    4756           0 :         pszCur = pszURN + 20;
    4757             :     else
    4758             :     {
    4759           2 :         CPLError(CE_Failure, CPLE_AppDefined, "URN %s not a supported format.",
    4760             :                  pszURN);
    4761           2 :         return OGRERR_FAILURE;
    4762             :     }
    4763             : 
    4764             :     /* -------------------------------------------------------------------- */
    4765             :     /*      Clear any existing definition.                                  */
    4766             :     /* -------------------------------------------------------------------- */
    4767          86 :     Clear();
    4768             : 
    4769             :     /* -------------------------------------------------------------------- */
    4770             :     /*      Find code (ignoring version) out of string like:                */
    4771             :     /*                                                                      */
    4772             :     /*      authority:[version]:code                                        */
    4773             :     /* -------------------------------------------------------------------- */
    4774          86 :     const char *pszAuthority = pszCur;
    4775             : 
    4776             :     // skip authority
    4777         414 :     while (*pszCur != ':' && *pszCur)
    4778         328 :         pszCur++;
    4779          86 :     if (*pszCur == ':')
    4780          86 :         pszCur++;
    4781             : 
    4782             :     // skip version
    4783          86 :     const char *pszBeforeVersion = pszCur;
    4784         387 :     while (*pszCur != ':' && *pszCur)
    4785         301 :         pszCur++;
    4786          86 :     if (*pszCur == ':')
    4787          58 :         pszCur++;
    4788             :     else
    4789             :         // We come here in the case, the content to parse is authority:code
    4790             :         // (instead of authority::code) which is probably illegal according to
    4791             :         // http://www.opengeospatial.org/ogcUrnPolicy but such content is found
    4792             :         // for example in what is returned by GeoServer.
    4793          28 :         pszCur = pszBeforeVersion;
    4794             : 
    4795          86 :     const char *pszCode = pszCur;
    4796             : 
    4797          86 :     const char *pszComma = strchr(pszCur, ',');
    4798          86 :     if (pszComma == nullptr)
    4799          85 :         return importFromURNPart(pszAuthority, pszCode, pszURN);
    4800             : 
    4801             :     // There's a second part with the vertical SRS.
    4802           1 :     pszCur = pszComma + 1;
    4803           1 :     if (!STARTS_WITH(pszCur, "crs:"))
    4804             :     {
    4805           0 :         CPLError(CE_Failure, CPLE_AppDefined, "URN %s not a supported format.",
    4806             :                  pszURN);
    4807           0 :         return OGRERR_FAILURE;
    4808             :     }
    4809             : 
    4810           1 :     pszCur += 4;
    4811             : 
    4812           1 :     char *pszFirstCode = CPLStrdup(pszCode);
    4813           1 :     pszFirstCode[pszComma - pszCode] = '\0';
    4814           1 :     OGRErr eStatus = importFromURNPart(pszAuthority, pszFirstCode, pszURN);
    4815           1 :     CPLFree(pszFirstCode);
    4816             : 
    4817             :     // Do we want to turn this into a compound definition
    4818             :     // with a vertical datum?
    4819           1 :     if (eStatus != OGRERR_NONE)
    4820           0 :         return eStatus;
    4821             : 
    4822             :     /* -------------------------------------------------------------------- */
    4823             :     /*      Find code (ignoring version) out of string like:                */
    4824             :     /*                                                                      */
    4825             :     /*      authority:[version]:code                                        */
    4826             :     /* -------------------------------------------------------------------- */
    4827           1 :     pszAuthority = pszCur;
    4828             : 
    4829             :     // skip authority
    4830           5 :     while (*pszCur != ':' && *pszCur)
    4831           4 :         pszCur++;
    4832           1 :     if (*pszCur == ':')
    4833           1 :         pszCur++;
    4834             : 
    4835             :     // skip version
    4836           1 :     pszBeforeVersion = pszCur;
    4837           1 :     while (*pszCur != ':' && *pszCur)
    4838           0 :         pszCur++;
    4839           1 :     if (*pszCur == ':')
    4840           1 :         pszCur++;
    4841             :     else
    4842           0 :         pszCur = pszBeforeVersion;
    4843             : 
    4844           1 :     pszCode = pszCur;
    4845             : 
    4846           2 :     OGRSpatialReference oVertSRS;
    4847           1 :     eStatus = oVertSRS.importFromURNPart(pszAuthority, pszCode, pszURN);
    4848           1 :     if (eStatus == OGRERR_NONE)
    4849             :     {
    4850           1 :         OGRSpatialReference oHorizSRS(*this);
    4851             : 
    4852           1 :         Clear();
    4853             : 
    4854           1 :         oHorizSRS.d->refreshProjObj();
    4855           1 :         oVertSRS.d->refreshProjObj();
    4856           1 :         if (!oHorizSRS.d->m_pj_crs || !oVertSRS.d->m_pj_crs)
    4857           0 :             return OGRERR_FAILURE;
    4858             : 
    4859           1 :         const char *pszHorizName = proj_get_name(oHorizSRS.d->m_pj_crs);
    4860           1 :         const char *pszVertName = proj_get_name(oVertSRS.d->m_pj_crs);
    4861             : 
    4862           2 :         CPLString osName = pszHorizName ? pszHorizName : "";
    4863           1 :         osName += " + ";
    4864           1 :         osName += pszVertName ? pszVertName : "";
    4865             : 
    4866           1 :         SetCompoundCS(osName, &oHorizSRS, &oVertSRS);
    4867             :     }
    4868             : 
    4869           1 :     return eStatus;
    4870             : #endif
    4871             : }
    4872             : 
    4873             : /************************************************************************/
    4874             : /*                           importFromCRSURL()                         */
    4875             : /*                                                                      */
    4876             : /*      See OGC Best Practice document 11-135 for details.              */
    4877             : /************************************************************************/
    4878             : 
    4879             : /**
    4880             :  * \brief Initialize from OGC URL.
    4881             :  *
    4882             :  * Initializes this spatial reference from a coordinate system defined
    4883             :  * by an OGC URL prefixed with "http://opengis.net/def/crs" per best practice
    4884             :  * paper 11-135.  Currently EPSG and OGC authority values are supported,
    4885             :  * including OGC auto codes, but not including CRS1 or CRS88 (NAVD88).
    4886             :  *
    4887             :  * This method is also supported through SetFromUserInput() which can
    4888             :  * normally be used for URLs.
    4889             :  *
    4890             :  * @param pszURL the URL string.
    4891             :  *
    4892             :  * @return OGRERR_NONE on success or an error code.
    4893             :  */
    4894             : 
    4895        7462 : OGRErr OGRSpatialReference::importFromCRSURL(const char *pszURL)
    4896             : 
    4897             : {
    4898       14924 :     TAKE_OPTIONAL_LOCK();
    4899             : 
    4900             : #if !PROJ_AT_LEAST_VERSION(9, 1, 0)
    4901        7462 :     if (strcmp(pszURL, "http://www.opengis.net/def/crs/OGC/0/CRS84h") == 0)
    4902             :     {
    4903          12 :         PJ *obj = proj_create(
    4904             :             d->getPROJContext(),
    4905             :             "GEOGCRS[\"WGS 84 longitude-latitude-height\",\n"
    4906             :             "    ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n"
    4907             :             "        MEMBER[\"World Geodetic System 1984 (Transit)\"],\n"
    4908             :             "        MEMBER[\"World Geodetic System 1984 (G730)\"],\n"
    4909             :             "        MEMBER[\"World Geodetic System 1984 (G873)\"],\n"
    4910             :             "        MEMBER[\"World Geodetic System 1984 (G1150)\"],\n"
    4911             :             "        MEMBER[\"World Geodetic System 1984 (G1674)\"],\n"
    4912             :             "        MEMBER[\"World Geodetic System 1984 (G1762)\"],\n"
    4913             :             "        MEMBER[\"World Geodetic System 1984 (G2139)\"],\n"
    4914             :             "        MEMBER[\"World Geodetic System 1984 (G2296)\"],\n"
    4915             :             "        ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n"
    4916             :             "            LENGTHUNIT[\"metre\",1]],\n"
    4917             :             "        ENSEMBLEACCURACY[2.0]],\n"
    4918             :             "    PRIMEM[\"Greenwich\",0,\n"
    4919             :             "        ANGLEUNIT[\"degree\",0.0174532925199433]],\n"
    4920             :             "    CS[ellipsoidal,3],\n"
    4921             :             "        AXIS[\"geodetic longitude (Lon)\",east,\n"
    4922             :             "            ORDER[1],\n"
    4923             :             "            ANGLEUNIT[\"degree\",0.0174532925199433]],\n"
    4924             :             "        AXIS[\"geodetic latitude (Lat)\",north,\n"
    4925             :             "            ORDER[2],\n"
    4926             :             "            ANGLEUNIT[\"degree\",0.0174532925199433]],\n"
    4927             :             "        AXIS[\"ellipsoidal height (h)\",up,\n"
    4928             :             "            ORDER[3],\n"
    4929             :             "            LENGTHUNIT[\"metre\",1]],\n"
    4930             :             "    USAGE[\n"
    4931             :             "        SCOPE[\"3D system frequently used in GIS, Web APIs and "
    4932             :             "Web applications\"],\n"
    4933             :             "        AREA[\"World.\"],\n"
    4934             :             "        BBOX[-90,-180,90,180]],\n"
    4935             :             "    ID[\"OGC\",\"CRS84h\"]]");
    4936          12 :         if (!obj)
    4937             :         {
    4938           0 :             return OGRERR_FAILURE;
    4939             :         }
    4940          12 :         Clear();
    4941          12 :         d->setPjCRS(obj);
    4942          12 :         return OGRERR_NONE;
    4943             :     }
    4944             : #endif
    4945             : 
    4946             : #if PROJ_AT_LEAST_VERSION(8, 1, 0)
    4947             :     if (strlen(pszURL) >= 10000)
    4948             :     {
    4949             :         CPLError(CE_Failure, CPLE_AppDefined, "Too long input string");
    4950             :         return OGRERR_CORRUPT_DATA;
    4951             :     }
    4952             : 
    4953             :     PJ *obj;
    4954             : #if !PROJ_AT_LEAST_VERSION(9, 2, 0)
    4955             :     if (STARTS_WITH(pszURL, "http://www.opengis.net/def/crs/IAU/0/"))
    4956             :     {
    4957             :         obj = proj_create(
    4958             :             d->getPROJContext(),
    4959             :             CPLSPrintf("IAU:%s",
    4960             :                        pszURL +
    4961             :                            strlen("http://www.opengis.net/def/crs/IAU/0/")));
    4962             :     }
    4963             :     else
    4964             : #endif
    4965             :     {
    4966             :         obj = proj_create(d->getPROJContext(), pszURL);
    4967             :     }
    4968             :     if (!obj)
    4969             :     {
    4970             :         return OGRERR_FAILURE;
    4971             :     }
    4972             :     Clear();
    4973             :     d->setPjCRS(obj);
    4974             :     return OGRERR_NONE;
    4975             : #else
    4976        7450 :     const char *pszCur = nullptr;
    4977             : 
    4978        7450 :     if (STARTS_WITH_CI(pszURL, "http://opengis.net/def/crs"))
    4979           2 :         pszCur = pszURL + 26;
    4980        7448 :     else if (STARTS_WITH_CI(pszURL, "https://opengis.net/def/crs"))
    4981           1 :         pszCur = pszURL + 27;
    4982        7447 :     else if (STARTS_WITH_CI(pszURL, "http://www.opengis.net/def/crs"))
    4983        7446 :         pszCur = pszURL + 30;
    4984           1 :     else if (STARTS_WITH_CI(pszURL, "https://www.opengis.net/def/crs"))
    4985           1 :         pszCur = pszURL + 31;
    4986           0 :     else if (STARTS_WITH_CI(pszURL, "www.opengis.net/def/crs"))
    4987           0 :         pszCur = pszURL + 23;
    4988             :     else
    4989             :     {
    4990           0 :         CPLError(CE_Failure, CPLE_AppDefined, "URL %s not a supported format.",
    4991             :                  pszURL);
    4992           0 :         return OGRERR_FAILURE;
    4993             :     }
    4994             : 
    4995        7450 :     if (*pszCur == '\0')
    4996             :     {
    4997           0 :         CPLError(CE_Failure, CPLE_AppDefined, "URL %s malformed.", pszURL);
    4998           0 :         return OGRERR_FAILURE;
    4999             :     }
    5000             : 
    5001             :     /* -------------------------------------------------------------------- */
    5002             :     /*      Clear any existing definition.                                  */
    5003             :     /* -------------------------------------------------------------------- */
    5004        7450 :     Clear();
    5005             : 
    5006        7450 :     if (STARTS_WITH_CI(pszCur, "-compound?1="))
    5007             :     {
    5008             :         /* --------------------------------------------------------------------
    5009             :          */
    5010             :         /*      It's a compound CRS, of the form: */
    5011             :         /*                                                                      */
    5012             :         /*      http://opengis.net/def/crs-compound?1=URL1&2=URL2&3=URL3&.. */
    5013             :         /* --------------------------------------------------------------------
    5014             :          */
    5015           1 :         pszCur += 12;
    5016             : 
    5017             :         // Extract each component CRS URL.
    5018           1 :         int iComponentUrl = 2;
    5019             : 
    5020           2 :         CPLString osName = "";
    5021           1 :         Clear();
    5022             : 
    5023           3 :         while (iComponentUrl != -1)
    5024             :         {
    5025           2 :             char searchStr[15] = {};
    5026           2 :             snprintf(searchStr, sizeof(searchStr), "&%d=", iComponentUrl);
    5027             : 
    5028           2 :             const char *pszUrlEnd = strstr(pszCur, searchStr);
    5029             : 
    5030             :             // Figure out the next component URL.
    5031           2 :             char *pszComponentUrl = nullptr;
    5032             : 
    5033           2 :             if (pszUrlEnd)
    5034             :             {
    5035           1 :                 size_t nLen = pszUrlEnd - pszCur;
    5036           1 :                 pszComponentUrl = static_cast<char *>(CPLMalloc(nLen + 1));
    5037           1 :                 strncpy(pszComponentUrl, pszCur, nLen);
    5038           1 :                 pszComponentUrl[nLen] = '\0';
    5039             : 
    5040           1 :                 ++iComponentUrl;
    5041           1 :                 pszCur += nLen + strlen(searchStr);
    5042             :             }
    5043             :             else
    5044             :             {
    5045           1 :                 if (iComponentUrl == 2)
    5046             :                 {
    5047           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5048             :                              "Compound CRS URLs must have at least two "
    5049             :                              "component CRSs.");
    5050           0 :                     return OGRERR_FAILURE;
    5051             :                 }
    5052             :                 else
    5053             :                 {
    5054           1 :                     pszComponentUrl = CPLStrdup(pszCur);
    5055             :                     // no more components
    5056           1 :                     iComponentUrl = -1;
    5057             :                 }
    5058             :             }
    5059             : 
    5060           2 :             OGRSpatialReference oComponentSRS;
    5061           2 :             OGRErr eStatus = oComponentSRS.importFromCRSURL(pszComponentUrl);
    5062             : 
    5063           2 :             CPLFree(pszComponentUrl);
    5064           2 :             pszComponentUrl = nullptr;
    5065             : 
    5066           2 :             if (eStatus == OGRERR_NONE)
    5067             :             {
    5068           2 :                 if (osName.length() != 0)
    5069             :                 {
    5070           1 :                     osName += " + ";
    5071             :                 }
    5072           2 :                 osName += oComponentSRS.GetRoot()->GetValue();
    5073           2 :                 SetNode("COMPD_CS", osName);
    5074           2 :                 GetRoot()->AddChild(oComponentSRS.GetRoot()->Clone());
    5075             :             }
    5076             :             else
    5077           0 :                 return eStatus;
    5078             :         }
    5079             : 
    5080           1 :         return OGRERR_NONE;
    5081             :     }
    5082             : 
    5083             :     /* -------------------------------------------------------------------- */
    5084             :     /*      It's a normal CRS URL, of the form:                             */
    5085             :     /*                                                                      */
    5086             :     /*      http://opengis.net/def/crs/AUTHORITY/VERSION/CODE               */
    5087             :     /* -------------------------------------------------------------------- */
    5088        7449 :     ++pszCur;
    5089        7449 :     const char *pszAuthority = pszCur;
    5090             : 
    5091             :     // skip authority
    5092      136128 :     while (*pszCur != '/' && *pszCur)
    5093      128679 :         pszCur++;
    5094        7449 :     if (*pszCur == '/')
    5095        7448 :         pszCur++;
    5096             : 
    5097             :     // skip version
    5098       17095 :     while (*pszCur != '/' && *pszCur)
    5099        9646 :         pszCur++;
    5100        7449 :     if (*pszCur == '/')
    5101        7448 :         pszCur++;
    5102             : 
    5103        7449 :     const char *pszCode = pszCur;
    5104             : 
    5105        7449 :     return importFromURNPart(pszAuthority, pszCode, pszURL);
    5106             : #endif
    5107             : }
    5108             : 
    5109             : /************************************************************************/
    5110             : /*                         importFromWMSAUTO()                          */
    5111             : /************************************************************************/
    5112             : 
    5113             : /**
    5114             :  * \brief Initialize from WMSAUTO string.
    5115             :  *
    5116             :  * Note that the WMS 1.3 specification does not include the
    5117             :  * units code, while apparently earlier specs do.  We try to
    5118             :  * guess around this.
    5119             :  *
    5120             :  * @param pszDefinition the WMSAUTO string
    5121             :  *
    5122             :  * @return OGRERR_NONE on success or an error code.
    5123             :  */
    5124           3 : OGRErr OGRSpatialReference::importFromWMSAUTO(const char *pszDefinition)
    5125             : 
    5126             : {
    5127           6 :     TAKE_OPTIONAL_LOCK();
    5128             : 
    5129             : #if PROJ_AT_LEAST_VERSION(8, 1, 0)
    5130             :     if (strlen(pszDefinition) >= 10000)
    5131             :     {
    5132             :         CPLError(CE_Failure, CPLE_AppDefined, "Too long input string");
    5133             :         return OGRERR_CORRUPT_DATA;
    5134             :     }
    5135             : 
    5136             :     auto obj = proj_create(d->getPROJContext(), pszDefinition);
    5137             :     if (!obj)
    5138             :     {
    5139             :         return OGRERR_FAILURE;
    5140             :     }
    5141             :     Clear();
    5142             :     d->setPjCRS(obj);
    5143             :     return OGRERR_NONE;
    5144             : #else
    5145             :     int nProjId, nUnitsId;
    5146           3 :     double dfRefLong, dfRefLat = 0.0;
    5147             : 
    5148             :     /* -------------------------------------------------------------------- */
    5149             :     /*      Tokenize                                                        */
    5150             :     /* -------------------------------------------------------------------- */
    5151           3 :     if (STARTS_WITH_CI(pszDefinition, "AUTO:"))
    5152           3 :         pszDefinition += 5;
    5153             : 
    5154             :     char **papszTokens =
    5155           3 :         CSLTokenizeStringComplex(pszDefinition, ",", FALSE, TRUE);
    5156             : 
    5157           3 :     if (CSLCount(papszTokens) == 4)
    5158             :     {
    5159           0 :         nProjId = atoi(papszTokens[0]);
    5160           0 :         nUnitsId = atoi(papszTokens[1]);
    5161           0 :         dfRefLong = CPLAtof(papszTokens[2]);
    5162           0 :         dfRefLat = CPLAtof(papszTokens[3]);
    5163             :     }
    5164           3 :     else if (CSLCount(papszTokens) == 3 && atoi(papszTokens[0]) == 42005)
    5165             :     {
    5166           0 :         nProjId = atoi(papszTokens[0]);
    5167           0 :         nUnitsId = atoi(papszTokens[1]);
    5168           0 :         dfRefLong = CPLAtof(papszTokens[2]);
    5169           0 :         dfRefLat = 0.0;
    5170             :     }
    5171           3 :     else if (CSLCount(papszTokens) == 3)
    5172             :     {
    5173           2 :         nProjId = atoi(papszTokens[0]);
    5174           2 :         nUnitsId = 9001;
    5175           2 :         dfRefLong = CPLAtof(papszTokens[1]);
    5176           2 :         dfRefLat = CPLAtof(papszTokens[2]);
    5177             :     }
    5178           1 :     else if (CSLCount(papszTokens) == 2 && atoi(papszTokens[0]) == 42005)
    5179             :     {
    5180           0 :         nProjId = atoi(papszTokens[0]);
    5181           0 :         nUnitsId = 9001;
    5182           0 :         dfRefLong = CPLAtof(papszTokens[1]);
    5183             :     }
    5184             :     else
    5185             :     {
    5186           1 :         CSLDestroy(papszTokens);
    5187           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    5188             :                  "AUTO projection has wrong number of arguments, expected\n"
    5189             :                  "AUTO:proj_id,units_id,ref_long,ref_lat or"
    5190             :                  "AUTO:proj_id,ref_long,ref_lat");
    5191           1 :         return OGRERR_FAILURE;
    5192             :     }
    5193             : 
    5194           2 :     CSLDestroy(papszTokens);
    5195           2 :     papszTokens = nullptr;
    5196             : 
    5197             :     /* -------------------------------------------------------------------- */
    5198             :     /*      Build coordsys.                                                 */
    5199             :     /* -------------------------------------------------------------------- */
    5200           2 :     Clear();
    5201             : 
    5202             :     /* -------------------------------------------------------------------- */
    5203             :     /*      Set WGS84.                                                      */
    5204             :     /* -------------------------------------------------------------------- */
    5205           2 :     SetWellKnownGeogCS("WGS84");
    5206             : 
    5207           2 :     switch (nProjId)
    5208             :     {
    5209           2 :         case 42001:  // Auto UTM
    5210           2 :             SetUTM(static_cast<int>(floor((dfRefLong + 180.0) / 6.0)) + 1,
    5211             :                    dfRefLat >= 0.0);
    5212           2 :             break;
    5213             : 
    5214           0 :         case 42002:  // Auto TM (strangely very UTM-like).
    5215           0 :             SetTM(0, dfRefLong, 0.9996, 500000.0,
    5216             :                   (dfRefLat >= 0.0) ? 0.0 : 10000000.0);
    5217           0 :             break;
    5218             : 
    5219           0 :         case 42003:  // Auto Orthographic.
    5220           0 :             SetOrthographic(dfRefLat, dfRefLong, 0.0, 0.0);
    5221           0 :             break;
    5222             : 
    5223           0 :         case 42004:  // Auto Equirectangular
    5224           0 :             SetEquirectangular(dfRefLat, dfRefLong, 0.0, 0.0);
    5225           0 :             break;
    5226             : 
    5227           0 :         case 42005:
    5228           0 :             SetMollweide(dfRefLong, 0.0, 0.0);
    5229           0 :             break;
    5230             : 
    5231           0 :         default:
    5232           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5233             :                      "Unsupported projection id in importFromWMSAUTO(): %d",
    5234             :                      nProjId);
    5235           0 :             return OGRERR_FAILURE;
    5236             :     }
    5237             : 
    5238             :     /* -------------------------------------------------------------------- */
    5239             :     /*      Set units.                                                      */
    5240             :     /* -------------------------------------------------------------------- */
    5241             : 
    5242           2 :     switch (nUnitsId)
    5243             :     {
    5244           2 :         case 9001:
    5245           2 :             SetTargetLinearUnits(nullptr, SRS_UL_METER, 1.0, "EPSG", "9001");
    5246           2 :             break;
    5247             : 
    5248           0 :         case 9002:
    5249           0 :             SetTargetLinearUnits(nullptr, "Foot", 0.3048, "EPSG", "9002");
    5250           0 :             break;
    5251             : 
    5252           0 :         case 9003:
    5253           0 :             SetTargetLinearUnits(nullptr, "US survey foot",
    5254             :                                  CPLAtof(SRS_UL_US_FOOT_CONV), "EPSG", "9003");
    5255           0 :             break;
    5256             : 
    5257           0 :         default:
    5258           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5259             :                      "Unsupported units code (%d).", nUnitsId);
    5260           0 :             return OGRERR_FAILURE;
    5261             :             break;
    5262             :     }
    5263             : 
    5264           2 :     return OGRERR_NONE;
    5265             : #endif
    5266             : }
    5267             : 
    5268             : /************************************************************************/
    5269             : /*                            GetSemiMajor()                            */
    5270             : /************************************************************************/
    5271             : 
    5272             : /**
    5273             :  * \brief Get spheroid semi major axis (in metres starting with GDAL 3.0)
    5274             :  *
    5275             :  * This method does the same thing as the C function OSRGetSemiMajor().
    5276             :  *
    5277             :  * @param pnErr if non-NULL set to OGRERR_FAILURE if semi major axis
    5278             :  * can be found.
    5279             :  *
    5280             :  * @return semi-major axis, or SRS_WGS84_SEMIMAJOR if it can't be found.
    5281             :  */
    5282             : 
    5283        6980 : double OGRSpatialReference::GetSemiMajor(OGRErr *pnErr) const
    5284             : 
    5285             : {
    5286       13960 :     TAKE_OPTIONAL_LOCK();
    5287             : 
    5288        6980 :     if (pnErr != nullptr)
    5289        3652 :         *pnErr = OGRERR_FAILURE;
    5290             : 
    5291        6980 :     d->refreshProjObj();
    5292        6980 :     if (!d->m_pj_crs)
    5293         111 :         return SRS_WGS84_SEMIMAJOR;
    5294             : 
    5295        6869 :     auto ellps = proj_get_ellipsoid(d->getPROJContext(), d->m_pj_crs);
    5296        6869 :     if (!ellps)
    5297           5 :         return SRS_WGS84_SEMIMAJOR;
    5298             : 
    5299        6864 :     double dfSemiMajor = 0.0;
    5300        6864 :     proj_ellipsoid_get_parameters(d->getPROJContext(), ellps, &dfSemiMajor,
    5301             :                                   nullptr, nullptr, nullptr);
    5302        6864 :     proj_destroy(ellps);
    5303             : 
    5304        6864 :     if (dfSemiMajor > 0)
    5305             :     {
    5306        6864 :         if (pnErr != nullptr)
    5307        3538 :             *pnErr = OGRERR_NONE;
    5308        6864 :         return dfSemiMajor;
    5309             :     }
    5310             : 
    5311           0 :     return SRS_WGS84_SEMIMAJOR;
    5312             : }
    5313             : 
    5314             : /************************************************************************/
    5315             : /*                          OSRGetSemiMajor()                           */
    5316             : /************************************************************************/
    5317             : 
    5318             : /**
    5319             :  * \brief Get spheroid semi major axis.
    5320             :  *
    5321             :  * This function is the same as OGRSpatialReference::GetSemiMajor()
    5322             :  */
    5323          90 : double OSRGetSemiMajor(OGRSpatialReferenceH hSRS, OGRErr *pnErr)
    5324             : 
    5325             : {
    5326          90 :     VALIDATE_POINTER1(hSRS, "OSRGetSemiMajor", 0);
    5327             : 
    5328          90 :     return ToPointer(hSRS)->GetSemiMajor(pnErr);
    5329             : }
    5330             : 
    5331             : /************************************************************************/
    5332             : /*                          GetInvFlattening()                          */
    5333             : /************************************************************************/
    5334             : 
    5335             : /**
    5336             :  * \brief Get spheroid inverse flattening.
    5337             :  *
    5338             :  * This method does the same thing as the C function OSRGetInvFlattening().
    5339             :  *
    5340             :  * @param pnErr if non-NULL set to OGRERR_FAILURE if no inverse flattening
    5341             :  * can be found.
    5342             :  *
    5343             :  * @return inverse flattening, or SRS_WGS84_INVFLATTENING if it can't be found.
    5344             :  */
    5345             : 
    5346        4585 : double OGRSpatialReference::GetInvFlattening(OGRErr *pnErr) const
    5347             : 
    5348             : {
    5349        9170 :     TAKE_OPTIONAL_LOCK();
    5350             : 
    5351        4585 :     if (pnErr != nullptr)
    5352        3541 :         *pnErr = OGRERR_FAILURE;
    5353             : 
    5354        4585 :     d->refreshProjObj();
    5355        4585 :     if (!d->m_pj_crs)
    5356         111 :         return SRS_WGS84_INVFLATTENING;
    5357             : 
    5358        4474 :     auto ellps = proj_get_ellipsoid(d->getPROJContext(), d->m_pj_crs);
    5359        4474 :     if (!ellps)
    5360           2 :         return SRS_WGS84_INVFLATTENING;
    5361             : 
    5362        4472 :     double dfInvFlattening = -1.0;
    5363        4472 :     proj_ellipsoid_get_parameters(d->getPROJContext(), ellps, nullptr, nullptr,
    5364             :                                   nullptr, &dfInvFlattening);
    5365        4472 :     proj_destroy(ellps);
    5366             : 
    5367        4472 :     if (dfInvFlattening >= 0.0)
    5368             :     {
    5369        4472 :         if (pnErr != nullptr)
    5370        3430 :             *pnErr = OGRERR_NONE;
    5371        4472 :         return dfInvFlattening;
    5372             :     }
    5373             : 
    5374           0 :     return SRS_WGS84_INVFLATTENING;
    5375             : }
    5376             : 
    5377             : /************************************************************************/
    5378             : /*                        OSRGetInvFlattening()                         */
    5379             : /************************************************************************/
    5380             : 
    5381             : /**
    5382             :  * \brief Get spheroid inverse flattening.
    5383             :  *
    5384             :  * This function is the same as OGRSpatialReference::GetInvFlattening()
    5385             :  */
    5386          10 : double OSRGetInvFlattening(OGRSpatialReferenceH hSRS, OGRErr *pnErr)
    5387             : 
    5388             : {
    5389          10 :     VALIDATE_POINTER1(hSRS, "OSRGetInvFlattening", 0);
    5390             : 
    5391          10 :     return ToPointer(hSRS)->GetInvFlattening(pnErr);
    5392             : }
    5393             : 
    5394             : /************************************************************************/
    5395             : /*                          GetEccentricity()                           */
    5396             : /************************************************************************/
    5397             : 
    5398             : /**
    5399             :  * \brief Get spheroid eccentricity
    5400             :  *
    5401             :  * @return eccentricity (or -1 in case of error)
    5402             :  */
    5403             : 
    5404           0 : double OGRSpatialReference::GetEccentricity() const
    5405             : 
    5406             : {
    5407           0 :     OGRErr eErr = OGRERR_NONE;
    5408           0 :     const double dfInvFlattening = GetInvFlattening(&eErr);
    5409           0 :     if (eErr != OGRERR_NONE)
    5410             :     {
    5411           0 :         return -1.0;
    5412             :     }
    5413           0 :     if (dfInvFlattening == 0.0)
    5414           0 :         return 0.0;
    5415           0 :     if (dfInvFlattening < 0.5)
    5416           0 :         return -1.0;
    5417           0 :     return sqrt(2.0 / dfInvFlattening -
    5418           0 :                 1.0 / (dfInvFlattening * dfInvFlattening));
    5419             : }
    5420             : 
    5421             : /************************************************************************/
    5422             : /*                       GetSquaredEccentricity()                       */
    5423             : /************************************************************************/
    5424             : 
    5425             : /**
    5426             :  * \brief Get spheroid squared eccentricity
    5427             :  *
    5428             :  * @return squared eccentricity (or -1 in case of error)
    5429             :  */
    5430             : 
    5431           0 : double OGRSpatialReference::GetSquaredEccentricity() const
    5432             : 
    5433             : {
    5434           0 :     OGRErr eErr = OGRERR_NONE;
    5435           0 :     const double dfInvFlattening = GetInvFlattening(&eErr);
    5436           0 :     if (eErr != OGRERR_NONE)
    5437             :     {
    5438           0 :         return -1.0;
    5439             :     }
    5440           0 :     if (dfInvFlattening == 0.0)
    5441           0 :         return 0.0;
    5442           0 :     if (dfInvFlattening < 0.5)
    5443           0 :         return -1.0;
    5444           0 :     return 2.0 / dfInvFlattening - 1.0 / (dfInvFlattening * dfInvFlattening);
    5445             : }
    5446             : 
    5447             : /************************************************************************/
    5448             : /*                            GetSemiMinor()                            */
    5449             : /************************************************************************/
    5450             : 
    5451             : /**
    5452             :  * \brief Get spheroid semi minor axis.
    5453             :  *
    5454             :  * This method does the same thing as the C function OSRGetSemiMinor().
    5455             :  *
    5456             :  * @param pnErr if non-NULL set to OGRERR_FAILURE if semi minor axis
    5457             :  * can be found.
    5458             :  *
    5459             :  * @return semi-minor axis, or WGS84 semi minor if it can't be found.
    5460             :  */
    5461             : 
    5462         638 : double OGRSpatialReference::GetSemiMinor(OGRErr *pnErr) const
    5463             : 
    5464             : {
    5465         638 :     const double dfSemiMajor = GetSemiMajor(pnErr);
    5466         638 :     const double dfInvFlattening = GetInvFlattening(pnErr);
    5467             : 
    5468         638 :     return OSRCalcSemiMinorFromInvFlattening(dfSemiMajor, dfInvFlattening);
    5469             : }
    5470             : 
    5471             : /************************************************************************/
    5472             : /*                          OSRGetSemiMinor()                           */
    5473             : /************************************************************************/
    5474             : 
    5475             : /**
    5476             :  * \brief Get spheroid semi minor axis.
    5477             :  *
    5478             :  * This function is the same as OGRSpatialReference::GetSemiMinor()
    5479             :  */
    5480           4 : double OSRGetSemiMinor(OGRSpatialReferenceH hSRS, OGRErr *pnErr)
    5481             : 
    5482             : {
    5483           4 :     VALIDATE_POINTER1(hSRS, "OSRGetSemiMinor", 0);
    5484             : 
    5485           4 :     return ToPointer(hSRS)->GetSemiMinor(pnErr);
    5486             : }
    5487             : 
    5488             : /************************************************************************/
    5489             : /*                             SetLocalCS()                             */
    5490             : /************************************************************************/
    5491             : 
    5492             : /**
    5493             :  * \brief Set the user visible LOCAL_CS name.
    5494             :  *
    5495             :  * This method is the same as the C function OSRSetLocalCS().
    5496             :  *
    5497             :  * This method will ensure a LOCAL_CS node is created as the root,
    5498             :  * and set the provided name on it.  It must be used before SetLinearUnits().
    5499             :  *
    5500             :  * @param pszName the user visible name to assign.  Not used as a key.
    5501             :  *
    5502             :  * @return OGRERR_NONE on success.
    5503             :  */
    5504             : 
    5505        2901 : OGRErr OGRSpatialReference::SetLocalCS(const char *pszName)
    5506             : 
    5507             : {
    5508        5802 :     TAKE_OPTIONAL_LOCK();
    5509             : 
    5510        2901 :     if (d->m_pjType == PJ_TYPE_UNKNOWN ||
    5511           0 :         d->m_pjType == PJ_TYPE_ENGINEERING_CRS)
    5512             :     {
    5513        2901 :         d->setPjCRS(proj_create_engineering_crs(d->getPROJContext(), pszName));
    5514             :     }
    5515             :     else
    5516             :     {
    5517           0 :         CPLDebug("OGR",
    5518             :                  "OGRSpatialReference::SetLocalCS(%s) failed.  "
    5519             :                  "It appears an incompatible object already exists.",
    5520             :                  pszName);
    5521           0 :         return OGRERR_FAILURE;
    5522             :     }
    5523             : 
    5524        2901 :     return OGRERR_NONE;
    5525             : }
    5526             : 
    5527             : /************************************************************************/
    5528             : /*                           OSRSetLocalCS()                            */
    5529             : /************************************************************************/
    5530             : 
    5531             : /**
    5532             :  * \brief Set the user visible LOCAL_CS name.
    5533             :  *
    5534             :  * This function is the same as OGRSpatialReference::SetLocalCS()
    5535             :  */
    5536           1 : OGRErr OSRSetLocalCS(OGRSpatialReferenceH hSRS, const char *pszName)
    5537             : 
    5538             : {
    5539           1 :     VALIDATE_POINTER1(hSRS, "OSRSetLocalCS", OGRERR_FAILURE);
    5540             : 
    5541           1 :     return ToPointer(hSRS)->SetLocalCS(pszName);
    5542             : }
    5543             : 
    5544             : /************************************************************************/
    5545             : /*                             SetGeocCS()                              */
    5546             : /************************************************************************/
    5547             : 
    5548             : /**
    5549             :  * \brief Set the user visible GEOCCS name.
    5550             :  *
    5551             :  * This method is the same as the C function OSRSetGeocCS().
    5552             : 
    5553             :  * This method will ensure a GEOCCS node is created as the root,
    5554             :  * and set the provided name on it.  If used on a GEOGCS coordinate system,
    5555             :  * the DATUM and PRIMEM nodes from the GEOGCS will be transferred over to
    5556             :  * the GEOGCS.
    5557             :  *
    5558             :  * @param pszName the user visible name to assign.  Not used as a key.
    5559             :  *
    5560             :  * @return OGRERR_NONE on success.
    5561             :  *
    5562             :  */
    5563             : 
    5564           6 : OGRErr OGRSpatialReference::SetGeocCS(const char *pszName)
    5565             : 
    5566             : {
    5567          12 :     TAKE_OPTIONAL_LOCK();
    5568             : 
    5569           6 :     OGRErr eErr = OGRERR_NONE;
    5570           6 :     d->refreshProjObj();
    5571           6 :     d->demoteFromBoundCRS();
    5572           6 :     if (d->m_pjType == PJ_TYPE_UNKNOWN)
    5573             :     {
    5574           3 :         d->setPjCRS(proj_create_geocentric_crs(
    5575             :             d->getPROJContext(), pszName, "World Geodetic System 1984",
    5576             :             "WGS 84", SRS_WGS84_SEMIMAJOR, SRS_WGS84_INVFLATTENING,
    5577             :             SRS_PM_GREENWICH, 0.0, SRS_UA_DEGREE, CPLAtof(SRS_UA_DEGREE_CONV),
    5578             :             "Metre", 1.0));
    5579             :     }
    5580           3 :     else if (d->m_pjType == PJ_TYPE_GEOCENTRIC_CRS)
    5581             :     {
    5582           1 :         d->setPjCRS(proj_alter_name(d->getPROJContext(), d->m_pj_crs, pszName));
    5583             :     }
    5584           3 :     else if (d->m_pjType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
    5585           1 :              d->m_pjType == PJ_TYPE_GEOGRAPHIC_3D_CRS)
    5586             :     {
    5587           1 :         auto datum = proj_crs_get_datum(d->getPROJContext(), d->m_pj_crs);
    5588             : #if PROJ_VERSION_MAJOR > 7 ||                                                  \
    5589             :     (PROJ_VERSION_MAJOR == 7 && PROJ_VERSION_MINOR >= 2)
    5590             :         if (datum == nullptr)
    5591             :         {
    5592             :             datum =
    5593             :                 proj_crs_get_datum_ensemble(d->getPROJContext(), d->m_pj_crs);
    5594             :         }
    5595             : #endif
    5596           1 :         if (datum == nullptr)
    5597             :         {
    5598           0 :             d->undoDemoteFromBoundCRS();
    5599           0 :             return OGRERR_FAILURE;
    5600             :         }
    5601             : 
    5602           1 :         auto pj_crs = proj_create_geocentric_crs_from_datum(
    5603           1 :             d->getPROJContext(), proj_get_name(d->m_pj_crs), datum, nullptr,
    5604             :             0.0);
    5605           1 :         d->setPjCRS(pj_crs);
    5606             : 
    5607           1 :         proj_destroy(datum);
    5608             :     }
    5609             :     else
    5610             :     {
    5611           1 :         CPLDebug("OGR",
    5612             :                  "OGRSpatialReference::SetGeocCS(%s) failed.  "
    5613             :                  "It appears an incompatible object already exists.",
    5614             :                  pszName);
    5615           1 :         eErr = OGRERR_FAILURE;
    5616             :     }
    5617           6 :     d->undoDemoteFromBoundCRS();
    5618             : 
    5619           6 :     return eErr;
    5620             : }
    5621             : 
    5622             : /************************************************************************/
    5623             : /*                            OSRSetGeocCS()                            */
    5624             : /************************************************************************/
    5625             : 
    5626             : /**
    5627             :  * \brief Set the user visible PROJCS name.
    5628             :  *
    5629             :  * This function is the same as OGRSpatialReference::SetGeocCS()
    5630             :  *
    5631             :  */
    5632           4 : OGRErr OSRSetGeocCS(OGRSpatialReferenceH hSRS, const char *pszName)
    5633             : 
    5634             : {
    5635           4 :     VALIDATE_POINTER1(hSRS, "OSRSetGeocCS", OGRERR_FAILURE);
    5636             : 
    5637           4 :     return ToPointer(hSRS)->SetGeocCS(pszName);
    5638             : }
    5639             : 
    5640             : /************************************************************************/
    5641             : /*                             SetVertCS()                              */
    5642             : /************************************************************************/
    5643             : 
    5644             : /**
    5645             :  * \brief Set the user visible VERT_CS name.
    5646             :  *
    5647             :  * This method is the same as the C function OSRSetVertCS().
    5648             : 
    5649             :  * This method will ensure a VERT_CS node is created if needed.  If the
    5650             :  * existing coordinate system is GEOGCS or PROJCS rooted, then it will be
    5651             :  * turned into a COMPD_CS.
    5652             :  *
    5653             :  * @param pszVertCSName the user visible name of the vertical coordinate
    5654             :  * system. Not used as a key.
    5655             :  *
    5656             :  * @param pszVertDatumName the user visible name of the vertical datum.  It
    5657             :  * is helpful if this matches the EPSG name.
    5658             :  *
    5659             :  * @param nVertDatumType the OGC vertical datum type. Ignored
    5660             :  *
    5661             :  * @return OGRERR_NONE on success.
    5662             :  *
    5663             :  */
    5664             : 
    5665           1 : OGRErr OGRSpatialReference::SetVertCS(const char *pszVertCSName,
    5666             :                                       const char *pszVertDatumName,
    5667             :                                       int nVertDatumType)
    5668             : 
    5669             : {
    5670           1 :     TAKE_OPTIONAL_LOCK();
    5671             : 
    5672           1 :     CPL_IGNORE_RET_VAL(nVertDatumType);
    5673             : 
    5674           1 :     d->refreshProjObj();
    5675             : 
    5676           1 :     auto vertCRS = proj_create_vertical_crs(d->getPROJContext(), pszVertCSName,
    5677             :                                             pszVertDatumName, nullptr, 0.0);
    5678             : 
    5679             :     /* -------------------------------------------------------------------- */
    5680             :     /*      Handle the case where we want to make a compound coordinate     */
    5681             :     /*      system.                                                         */
    5682             :     /* -------------------------------------------------------------------- */
    5683           1 :     if (IsProjected() || IsGeographic())
    5684             :     {
    5685           1 :         auto compoundCRS = proj_create_compound_crs(
    5686           1 :             d->getPROJContext(), nullptr, d->m_pj_crs, vertCRS);
    5687           1 :         proj_destroy(vertCRS);
    5688           1 :         d->setPjCRS(compoundCRS);
    5689             :     }
    5690             :     else
    5691             :     {
    5692           0 :         d->setPjCRS(vertCRS);
    5693             :     }
    5694           2 :     return OGRERR_NONE;
    5695             : }
    5696             : 
    5697             : /************************************************************************/
    5698             : /*                            OSRSetVertCS()                            */
    5699             : /************************************************************************/
    5700             : 
    5701             : /**
    5702             :  * \brief Setup the vertical coordinate system.
    5703             :  *
    5704             :  * This function is the same as OGRSpatialReference::SetVertCS()
    5705             :  *
    5706             :  */
    5707           0 : OGRErr OSRSetVertCS(OGRSpatialReferenceH hSRS, const char *pszVertCSName,
    5708             :                     const char *pszVertDatumName, int nVertDatumType)
    5709             : 
    5710             : {
    5711           0 :     VALIDATE_POINTER1(hSRS, "OSRSetVertCS", OGRERR_FAILURE);
    5712             : 
    5713           0 :     return ToPointer(hSRS)->SetVertCS(pszVertCSName, pszVertDatumName,
    5714           0 :                                       nVertDatumType);
    5715             : }
    5716             : 
    5717             : /************************************************************************/
    5718             : /*                           SetCompoundCS()                            */
    5719             : /************************************************************************/
    5720             : 
    5721             : /**
    5722             :  * \brief Setup a compound coordinate system.
    5723             :  *
    5724             :  * This method is the same as the C function OSRSetCompoundCS().
    5725             : 
    5726             :  * This method is replace the current SRS with a COMPD_CS coordinate system
    5727             :  * consisting of the passed in horizontal and vertical coordinate systems.
    5728             :  *
    5729             :  * @param pszName the name of the compound coordinate system.
    5730             :  *
    5731             :  * @param poHorizSRS the horizontal SRS (PROJCS or GEOGCS).
    5732             :  *
    5733             :  * @param poVertSRS the vertical SRS (VERT_CS).
    5734             :  *
    5735             :  * @return OGRERR_NONE on success.
    5736             :  */
    5737             : 
    5738         183 : OGRErr OGRSpatialReference::SetCompoundCS(const char *pszName,
    5739             :                                           const OGRSpatialReference *poHorizSRS,
    5740             :                                           const OGRSpatialReference *poVertSRS)
    5741             : 
    5742             : {
    5743         366 :     TAKE_OPTIONAL_LOCK();
    5744             : 
    5745             :     /* -------------------------------------------------------------------- */
    5746             :     /*      Verify these are legal horizontal and vertical coordinate       */
    5747             :     /*      systems.                                                        */
    5748             :     /* -------------------------------------------------------------------- */
    5749         183 :     if (!poVertSRS->IsVertical())
    5750             :     {
    5751           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5752             :                  "SetCompoundCS() fails, vertical component is not VERT_CS.");
    5753           0 :         return OGRERR_FAILURE;
    5754             :     }
    5755         183 :     if (!poHorizSRS->IsProjected() && !poHorizSRS->IsGeographic())
    5756             :     {
    5757           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5758             :                  "SetCompoundCS() fails, horizontal component is not PROJCS or "
    5759             :                  "GEOGCS.");
    5760           0 :         return OGRERR_FAILURE;
    5761             :     }
    5762             : 
    5763             :     /* -------------------------------------------------------------------- */
    5764             :     /*      Replace with compound srs.                                      */
    5765             :     /* -------------------------------------------------------------------- */
    5766         183 :     Clear();
    5767             : 
    5768         183 :     auto compoundCRS = proj_create_compound_crs(d->getPROJContext(), pszName,
    5769         183 :                                                 poHorizSRS->d->m_pj_crs,
    5770         183 :                                                 poVertSRS->d->m_pj_crs);
    5771         183 :     d->setPjCRS(compoundCRS);
    5772             : 
    5773         183 :     return OGRERR_NONE;
    5774             : }
    5775             : 
    5776             : /************************************************************************/
    5777             : /*                          OSRSetCompoundCS()                          */
    5778             : /************************************************************************/
    5779             : 
    5780             : /**
    5781             :  * \brief Setup a compound coordinate system.
    5782             :  *
    5783             :  * This function is the same as OGRSpatialReference::SetCompoundCS()
    5784             :  */
    5785           8 : OGRErr OSRSetCompoundCS(OGRSpatialReferenceH hSRS, const char *pszName,
    5786             :                         OGRSpatialReferenceH hHorizSRS,
    5787             :                         OGRSpatialReferenceH hVertSRS)
    5788             : 
    5789             : {
    5790           8 :     VALIDATE_POINTER1(hSRS, "OSRSetCompoundCS", OGRERR_FAILURE);
    5791           8 :     VALIDATE_POINTER1(hHorizSRS, "OSRSetCompoundCS", OGRERR_FAILURE);
    5792           8 :     VALIDATE_POINTER1(hVertSRS, "OSRSetCompoundCS", OGRERR_FAILURE);
    5793             : 
    5794          16 :     return ToPointer(hSRS)->SetCompoundCS(pszName, ToPointer(hHorizSRS),
    5795          16 :                                           ToPointer(hVertSRS));
    5796             : }
    5797             : 
    5798             : /************************************************************************/
    5799             : /*                        GetCompoundComponent()                        */
    5800             : /************************************************************************/
    5801             : 
    5802             : /**
    5803             :  * \brief Get a CRS component from a CompoundCRS
    5804             :  *
    5805             :  * @param iComponent Index of the CRS component (typically 0 = horizontal, 1 =
    5806             :  * vertical)
    5807             :  * @return new OGRSpatialReference object, or NULL in case of error.
    5808             :  *
    5809             :  * @since 3.14
    5810             :  */
    5811             : 
    5812             : std::unique_ptr<OGRSpatialReference>
    5813           0 : OGRSpatialReference::GetCompoundComponent(int iComponent) const
    5814             : {
    5815           0 :     std::unique_ptr<OGRSpatialReference> poSRS;
    5816           0 :     d->refreshProjObj();
    5817           0 :     d->demoteFromBoundCRS();
    5818           0 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    5819             :     {
    5820             :         auto subCrs =
    5821           0 :             proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, iComponent);
    5822           0 :         if (subCrs)
    5823             :         {
    5824           0 :             poSRS = std::make_unique<OGRSpatialReference>();
    5825           0 :             poSRS->d->setPjCRS(subCrs);
    5826             :         }
    5827             :     }
    5828           0 :     d->undoDemoteFromBoundCRS();
    5829           0 :     return poSRS;
    5830             : }
    5831             : 
    5832             : /************************************************************************/
    5833             : /*                             SetProjCS()                              */
    5834             : /************************************************************************/
    5835             : 
    5836             : /**
    5837             :  * \brief Set the user visible PROJCS name.
    5838             :  *
    5839             :  * This method is the same as the C function OSRSetProjCS().
    5840             :  *
    5841             :  * This method will ensure a PROJCS node is created as the root,
    5842             :  * and set the provided name on it.  If used on a GEOGCS coordinate system,
    5843             :  * the GEOGCS node will be demoted to be a child of the new PROJCS root.
    5844             :  *
    5845             :  * @param pszName the user visible name to assign.  Not used as a key.
    5846             :  *
    5847             :  * @return OGRERR_NONE on success.
    5848             :  */
    5849             : 
    5850        4854 : OGRErr OGRSpatialReference::SetProjCS(const char *pszName)
    5851             : 
    5852             : {
    5853        4854 :     TAKE_OPTIONAL_LOCK();
    5854             : 
    5855        4854 :     d->refreshProjObj();
    5856        4854 :     d->demoteFromBoundCRS();
    5857        4854 :     if (d->m_pjType == PJ_TYPE_PROJECTED_CRS)
    5858             :     {
    5859         492 :         d->setPjCRS(proj_alter_name(d->getPROJContext(), d->m_pj_crs, pszName));
    5860             :     }
    5861             :     else
    5862             :     {
    5863        4362 :         auto dummyConv = proj_create_conversion(d->getPROJContext(), nullptr,
    5864             :                                                 nullptr, nullptr, nullptr,
    5865             :                                                 nullptr, nullptr, 0, nullptr);
    5866        4362 :         auto cs = proj_create_cartesian_2D_cs(
    5867             :             d->getPROJContext(), PJ_CART2D_EASTING_NORTHING, nullptr, 0);
    5868             : 
    5869        4362 :         auto projCRS = proj_create_projected_crs(
    5870        4362 :             d->getPROJContext(), pszName, d->getGeodBaseCRS(), dummyConv, cs);
    5871        4362 :         proj_destroy(dummyConv);
    5872        4362 :         proj_destroy(cs);
    5873             : 
    5874        4362 :         d->setPjCRS(projCRS);
    5875             :     }
    5876        4854 :     d->undoDemoteFromBoundCRS();
    5877        9708 :     return OGRERR_NONE;
    5878             : }
    5879             : 
    5880             : /************************************************************************/
    5881             : /*                            OSRSetProjCS()                            */
    5882             : /************************************************************************/
    5883             : 
    5884             : /**
    5885             :  * \brief Set the user visible PROJCS name.
    5886             :  *
    5887             :  * This function is the same as OGRSpatialReference::SetProjCS()
    5888             :  */
    5889           1 : OGRErr OSRSetProjCS(OGRSpatialReferenceH hSRS, const char *pszName)
    5890             : 
    5891             : {
    5892           1 :     VALIDATE_POINTER1(hSRS, "OSRSetProjCS", OGRERR_FAILURE);
    5893             : 
    5894           1 :     return ToPointer(hSRS)->SetProjCS(pszName);
    5895             : }
    5896             : 
    5897             : /************************************************************************/
    5898             : /*                           SetProjection()                            */
    5899             : /************************************************************************/
    5900             : 
    5901             : /**
    5902             :  * \brief Set a projection name.
    5903             :  *
    5904             :  * This method is the same as the C function OSRSetProjection().
    5905             :  *
    5906             :  * @param pszProjection the projection name, which should be selected from
    5907             :  * the macros in ogr_srs_api.h, such as SRS_PT_TRANSVERSE_MERCATOR.
    5908             :  *
    5909             :  * @return OGRERR_NONE on success.
    5910             :  */
    5911             : 
    5912          22 : OGRErr OGRSpatialReference::SetProjection(const char *pszProjection)
    5913             : 
    5914             : {
    5915          44 :     TAKE_OPTIONAL_LOCK();
    5916             : 
    5917          22 :     OGR_SRSNode *poGeogCS = nullptr;
    5918             : 
    5919          22 :     if (GetRoot() != nullptr && EQUAL(d->m_poRoot->GetValue(), "GEOGCS"))
    5920             :     {
    5921           4 :         poGeogCS = d->m_poRoot;
    5922           4 :         d->m_poRoot = nullptr;
    5923             :     }
    5924             : 
    5925          22 :     if (!GetAttrNode("PROJCS"))
    5926             :     {
    5927          11 :         SetNode("PROJCS", "unnamed");
    5928             :     }
    5929             : 
    5930          22 :     const OGRErr eErr = SetNode("PROJCS|PROJECTION", pszProjection);
    5931          22 :     if (eErr != OGRERR_NONE)
    5932           0 :         return eErr;
    5933             : 
    5934          22 :     if (poGeogCS != nullptr)
    5935           4 :         d->m_poRoot->InsertChild(poGeogCS, 1);
    5936             : 
    5937          22 :     return OGRERR_NONE;
    5938             : }
    5939             : 
    5940             : /************************************************************************/
    5941             : /*                          OSRSetProjection()                          */
    5942             : /************************************************************************/
    5943             : 
    5944             : /**
    5945             :  * \brief Set a projection name.
    5946             :  *
    5947             :  * This function is the same as OGRSpatialReference::SetProjection()
    5948             :  */
    5949           0 : OGRErr OSRSetProjection(OGRSpatialReferenceH hSRS, const char *pszProjection)
    5950             : 
    5951             : {
    5952           0 :     VALIDATE_POINTER1(hSRS, "OSRSetProjection", OGRERR_FAILURE);
    5953             : 
    5954           0 :     return ToPointer(hSRS)->SetProjection(pszProjection);
    5955             : }
    5956             : 
    5957             : /************************************************************************/
    5958             : /*                      GetWKT2ProjectionMethod()                       */
    5959             : /************************************************************************/
    5960             : 
    5961             : /**
    5962             :  * \brief Returns info on the projection method, based on WKT2 naming
    5963             :  * conventions.
    5964             :  *
    5965             :  * The returned strings are short lived and should be considered to be
    5966             :  * invalidated by any further call to the GDAL API.
    5967             :  *
    5968             :  * @param[out] ppszMethodName Pointer to a string that will receive the
    5969             :  * projection method name.
    5970             :  * @param[out] ppszMethodAuthName null pointer, or pointer to a string that will
    5971             :  * receive the name of the authority that defines the projection method.
    5972             :  * *ppszMethodAuthName may be nullptr if the projection method is not linked to
    5973             :  * an authority.
    5974             :  * @param[out] ppszMethodCode null pointer, or pointer to a string that will
    5975             :  * receive the code that defines the projection method.
    5976             :  * *ppszMethodCode may be nullptr if the projection method is not linked to
    5977             :  * an authority.
    5978             :  *
    5979             :  * @return OGRERR_NONE on success.
    5980             :  */
    5981             : OGRErr
    5982           1 : OGRSpatialReference::GetWKT2ProjectionMethod(const char **ppszMethodName,
    5983             :                                              const char **ppszMethodAuthName,
    5984             :                                              const char **ppszMethodCode) const
    5985             : {
    5986           2 :     TAKE_OPTIONAL_LOCK();
    5987             : 
    5988           1 :     auto conv = proj_crs_get_coordoperation(d->getPROJContext(), d->m_pj_crs);
    5989           1 :     if (!conv)
    5990           0 :         return OGRERR_FAILURE;
    5991           1 :     const char *pszTmpMethodName = "";
    5992           1 :     const char *pszTmpMethodAuthName = "";
    5993           1 :     const char *pszTmpMethodCode = "";
    5994           1 :     int ret = proj_coordoperation_get_method_info(
    5995             :         d->getPROJContext(), conv, &pszTmpMethodName, &pszTmpMethodAuthName,
    5996             :         &pszTmpMethodCode);
    5997             :     // "Internalize" temporary strings returned by PROJ
    5998           1 :     CPLAssert(pszTmpMethodName);
    5999           1 :     if (ppszMethodName)
    6000           1 :         *ppszMethodName = CPLSPrintf("%s", pszTmpMethodName);
    6001           1 :     if (ppszMethodAuthName)
    6002           0 :         *ppszMethodAuthName = pszTmpMethodAuthName
    6003           0 :                                   ? CPLSPrintf("%s", pszTmpMethodAuthName)
    6004           0 :                                   : nullptr;
    6005           1 :     if (ppszMethodCode)
    6006           0 :         *ppszMethodCode =
    6007           0 :             pszTmpMethodCode ? CPLSPrintf("%s", pszTmpMethodCode) : nullptr;
    6008           1 :     proj_destroy(conv);
    6009           1 :     return ret ? OGRERR_NONE : OGRERR_FAILURE;
    6010             : }
    6011             : 
    6012             : /************************************************************************/
    6013             : /*                            SetProjParm()                             */
    6014             : /************************************************************************/
    6015             : 
    6016             : /**
    6017             :  * \brief Set a projection parameter value.
    6018             :  *
    6019             :  * Adds a new PARAMETER under the PROJCS with the indicated name and value.
    6020             :  *
    6021             :  * This method is the same as the C function OSRSetProjParm().
    6022             :  *
    6023             :  * Please check https://gdal.org/proj_list pages for
    6024             :  * legal parameter names for specific projections.
    6025             :  *
    6026             :  *
    6027             :  * @param pszParamName the parameter name, which should be selected from
    6028             :  * the macros in ogr_srs_api.h, such as SRS_PP_CENTRAL_MERIDIAN.
    6029             :  *
    6030             :  * @param dfValue value to assign.
    6031             :  *
    6032             :  * @return OGRERR_NONE on success.
    6033             :  */
    6034             : 
    6035         124 : OGRErr OGRSpatialReference::SetProjParm(const char *pszParamName,
    6036             :                                         double dfValue)
    6037             : 
    6038             : {
    6039         248 :     TAKE_OPTIONAL_LOCK();
    6040             : 
    6041         124 :     OGR_SRSNode *poPROJCS = GetAttrNode("PROJCS");
    6042             : 
    6043         124 :     if (poPROJCS == nullptr)
    6044           3 :         return OGRERR_FAILURE;
    6045             : 
    6046         121 :     char szValue[64] = {'\0'};
    6047         121 :     OGRsnPrintDouble(szValue, sizeof(szValue), dfValue);
    6048             : 
    6049             :     /* -------------------------------------------------------------------- */
    6050             :     /*      Try to find existing parameter with this name.                  */
    6051             :     /* -------------------------------------------------------------------- */
    6052         985 :     for (int iChild = 0; iChild < poPROJCS->GetChildCount(); iChild++)
    6053             :     {
    6054         903 :         OGR_SRSNode *poParam = poPROJCS->GetChild(iChild);
    6055             : 
    6056        1192 :         if (EQUAL(poParam->GetValue(), "PARAMETER") &&
    6057        1192 :             poParam->GetChildCount() == 2 &&
    6058         289 :             EQUAL(poParam->GetChild(0)->GetValue(), pszParamName))
    6059             :         {
    6060          39 :             poParam->GetChild(1)->SetValue(szValue);
    6061          39 :             return OGRERR_NONE;
    6062             :         }
    6063             :     }
    6064             : 
    6065             :     /* -------------------------------------------------------------------- */
    6066             :     /*      Otherwise create a new parameter and append.                    */
    6067             :     /* -------------------------------------------------------------------- */
    6068          82 :     OGR_SRSNode *poParam = new OGR_SRSNode("PARAMETER");
    6069          82 :     poParam->AddChild(new OGR_SRSNode(pszParamName));
    6070          82 :     poParam->AddChild(new OGR_SRSNode(szValue));
    6071             : 
    6072          82 :     poPROJCS->AddChild(poParam);
    6073             : 
    6074          82 :     return OGRERR_NONE;
    6075             : }
    6076             : 
    6077             : /************************************************************************/
    6078             : /*                           OSRSetProjParm()                           */
    6079             : /************************************************************************/
    6080             : 
    6081             : /**
    6082             :  * \brief Set a projection parameter value.
    6083             :  *
    6084             :  * This function is the same as OGRSpatialReference::SetProjParm()
    6085             :  */
    6086           0 : OGRErr OSRSetProjParm(OGRSpatialReferenceH hSRS, const char *pszParamName,
    6087             :                       double dfValue)
    6088             : 
    6089             : {
    6090           0 :     VALIDATE_POINTER1(hSRS, "OSRSetProjParm", OGRERR_FAILURE);
    6091             : 
    6092           0 :     return ToPointer(hSRS)->SetProjParm(pszParamName, dfValue);
    6093             : }
    6094             : 
    6095             : /************************************************************************/
    6096             : /*                            FindProjParm()                            */
    6097             : /************************************************************************/
    6098             : 
    6099             : /**
    6100             :  * \brief Return the child index of the named projection parameter on
    6101             :  * its parent PROJCS node.
    6102             :  *
    6103             :  * @param pszParameter projection parameter to look for
    6104             :  * @param poPROJCS projection CS node to look in. If NULL is passed,
    6105             :  *        the PROJCS node of the SpatialReference object will be searched.
    6106             :  *
    6107             :  * @return the child index of the named projection parameter. -1 on failure
    6108             :  */
    6109        5184 : int OGRSpatialReference::FindProjParm(const char *pszParameter,
    6110             :                                       const OGR_SRSNode *poPROJCS) const
    6111             : 
    6112             : {
    6113       10368 :     TAKE_OPTIONAL_LOCK();
    6114             : 
    6115        5184 :     if (poPROJCS == nullptr)
    6116           0 :         poPROJCS = GetAttrNode("PROJCS");
    6117             : 
    6118        5184 :     if (poPROJCS == nullptr)
    6119           0 :         return -1;
    6120             : 
    6121             :     /* -------------------------------------------------------------------- */
    6122             :     /*      Search for requested parameter.                                 */
    6123             :     /* -------------------------------------------------------------------- */
    6124        5184 :     bool bIsWKT2 = false;
    6125       34212 :     for (int iChild = 0; iChild < poPROJCS->GetChildCount(); iChild++)
    6126             :     {
    6127       33513 :         const OGR_SRSNode *poParameter = poPROJCS->GetChild(iChild);
    6128             : 
    6129       33513 :         if (poParameter->GetChildCount() >= 2)
    6130             :         {
    6131       23186 :             const char *pszValue = poParameter->GetValue();
    6132       38175 :             if (EQUAL(pszValue, "PARAMETER") &&
    6133       14989 :                 EQUAL(poPROJCS->GetChild(iChild)->GetChild(0)->GetValue(),
    6134             :                       pszParameter))
    6135             :             {
    6136        4485 :                 return iChild;
    6137             :             }
    6138       18701 :             else if (EQUAL(pszValue, "METHOD"))
    6139             :             {
    6140          41 :                 bIsWKT2 = true;
    6141             :             }
    6142             :         }
    6143             :     }
    6144             : 
    6145             :     /* -------------------------------------------------------------------- */
    6146             :     /*      Try similar names, for selected parameters.                     */
    6147             :     /* -------------------------------------------------------------------- */
    6148         699 :     if (EQUAL(pszParameter, SRS_PP_LATITUDE_OF_ORIGIN))
    6149             :     {
    6150         328 :         if (bIsWKT2)
    6151             :         {
    6152           8 :             int iChild = FindProjParm(
    6153             :                 EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, poPROJCS);
    6154           8 :             if (iChild == -1)
    6155           3 :                 iChild = FindProjParm(
    6156             :                     EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, poPROJCS);
    6157           8 :             return iChild;
    6158             :         }
    6159         320 :         return FindProjParm(SRS_PP_LATITUDE_OF_CENTER, poPROJCS);
    6160             :     }
    6161             : 
    6162         371 :     if (EQUAL(pszParameter, SRS_PP_CENTRAL_MERIDIAN))
    6163             :     {
    6164          38 :         if (bIsWKT2)
    6165             :         {
    6166           9 :             int iChild = FindProjParm(
    6167             :                 EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, poPROJCS);
    6168           9 :             if (iChild == -1)
    6169           0 :                 iChild = FindProjParm(
    6170             :                     EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, poPROJCS);
    6171           9 :             return iChild;
    6172             :         }
    6173          29 :         int iChild = FindProjParm(SRS_PP_LONGITUDE_OF_CENTER, poPROJCS);
    6174          29 :         if (iChild == -1)
    6175           0 :             iChild = FindProjParm(SRS_PP_LONGITUDE_OF_ORIGIN, poPROJCS);
    6176          29 :         return iChild;
    6177             :     }
    6178             : 
    6179         333 :     return -1;
    6180             : }
    6181             : 
    6182             : /************************************************************************/
    6183             : /*                            GetProjParm()                             */
    6184             : /************************************************************************/
    6185             : 
    6186             : /**
    6187             :  * \brief Fetch a projection parameter value.
    6188             :  *
    6189             :  * NOTE: This code should be modified to translate non degree angles into
    6190             :  * degrees based on the GEOGCS unit.  This has not yet been done.
    6191             :  *
    6192             :  * This method is the same as the C function OSRGetProjParm().
    6193             :  *
    6194             :  * @param pszName the name of the parameter to fetch, from the set of
    6195             :  * SRS_PP codes in ogr_srs_api.h.
    6196             :  *
    6197             :  * @param dfDefaultValue the value to return if this parameter doesn't exist.
    6198             :  *
    6199             :  * @param pnErr place to put error code on failure.  Ignored if NULL.
    6200             :  *
    6201             :  * @return value of parameter.
    6202             :  */
    6203             : 
    6204        5079 : double OGRSpatialReference::GetProjParm(const char *pszName,
    6205             :                                         double dfDefaultValue,
    6206             :                                         OGRErr *pnErr) const
    6207             : 
    6208             : {
    6209       10158 :     TAKE_OPTIONAL_LOCK();
    6210             : 
    6211        5079 :     d->refreshProjObj();
    6212        5079 :     GetRoot();  // force update of d->m_bNodesWKT2
    6213             : 
    6214        5079 :     if (pnErr != nullptr)
    6215        4083 :         *pnErr = OGRERR_NONE;
    6216             : 
    6217             :     /* -------------------------------------------------------------------- */
    6218             :     /*      Find the desired parameter.                                     */
    6219             :     /* -------------------------------------------------------------------- */
    6220             :     const OGR_SRSNode *poPROJCS =
    6221        5079 :         GetAttrNode(d->m_bNodesWKT2 ? "CONVERSION" : "PROJCS");
    6222        5079 :     if (poPROJCS == nullptr)
    6223             :     {
    6224         264 :         if (pnErr != nullptr)
    6225         264 :             *pnErr = OGRERR_FAILURE;
    6226         264 :         return dfDefaultValue;
    6227             :     }
    6228             : 
    6229        4815 :     const int iChild = FindProjParm(pszName, poPROJCS);
    6230        4815 :     if (iChild == -1)
    6231             :     {
    6232         330 :         if (IsProjected() && GetAxesCount() == 3)
    6233             :         {
    6234           3 :             OGRSpatialReference *poSRSTmp = Clone();
    6235           3 :             poSRSTmp->DemoteTo2D(nullptr);
    6236             :             const double dfRet =
    6237           3 :                 poSRSTmp->GetProjParm(pszName, dfDefaultValue, pnErr);
    6238           3 :             delete poSRSTmp;
    6239           3 :             return dfRet;
    6240             :         }
    6241             : 
    6242         327 :         if (pnErr != nullptr)
    6243         305 :             *pnErr = OGRERR_FAILURE;
    6244         327 :         return dfDefaultValue;
    6245             :     }
    6246             : 
    6247        4485 :     const OGR_SRSNode *poParameter = poPROJCS->GetChild(iChild);
    6248        4485 :     return CPLAtof(poParameter->GetChild(1)->GetValue());
    6249             : }
    6250             : 
    6251             : /************************************************************************/
    6252             : /*                           OSRGetProjParm()                           */
    6253             : /************************************************************************/
    6254             : 
    6255             : /**
    6256             :  * \brief Fetch a projection parameter value.
    6257             :  *
    6258             :  * This function is the same as OGRSpatialReference::GetProjParm()
    6259             :  */
    6260          90 : double OSRGetProjParm(OGRSpatialReferenceH hSRS, const char *pszName,
    6261             :                       double dfDefaultValue, OGRErr *pnErr)
    6262             : 
    6263             : {
    6264          90 :     VALIDATE_POINTER1(hSRS, "OSRGetProjParm", 0);
    6265             : 
    6266          90 :     return ToPointer(hSRS)->GetProjParm(pszName, dfDefaultValue, pnErr);
    6267             : }
    6268             : 
    6269             : /************************************************************************/
    6270             : /*                          GetNormProjParm()                           */
    6271             : /************************************************************************/
    6272             : 
    6273             : /**
    6274             :  * \brief Fetch a normalized projection parameter value.
    6275             :  *
    6276             :  * This method is the same as GetProjParm() except that the value of
    6277             :  * the parameter is "normalized" into degrees or meters depending on
    6278             :  * whether it is linear or angular.
    6279             :  *
    6280             :  * This method is the same as the C function OSRGetNormProjParm().
    6281             :  *
    6282             :  * @param pszName the name of the parameter to fetch, from the set of
    6283             :  * SRS_PP codes in ogr_srs_api.h.
    6284             :  *
    6285             :  * @param dfDefaultValue the value to return if this parameter doesn't exist.
    6286             :  *
    6287             :  * @param pnErr place to put error code on failure.  Ignored if NULL.
    6288             :  *
    6289             :  * @return value of parameter.
    6290             :  */
    6291             : 
    6292        4058 : double OGRSpatialReference::GetNormProjParm(const char *pszName,
    6293             :                                             double dfDefaultValue,
    6294             :                                             OGRErr *pnErr) const
    6295             : 
    6296             : {
    6297        8116 :     TAKE_OPTIONAL_LOCK();
    6298             : 
    6299        4058 :     GetNormInfo();
    6300             : 
    6301        4058 :     OGRErr nError = OGRERR_NONE;
    6302        4058 :     double dfRawResult = GetProjParm(pszName, dfDefaultValue, &nError);
    6303        4058 :     if (pnErr != nullptr)
    6304           0 :         *pnErr = nError;
    6305             : 
    6306             :     // If we got the default just return it unadjusted.
    6307        4058 :     if (nError != OGRERR_NONE)
    6308         569 :         return dfRawResult;
    6309             : 
    6310        3489 :     if (d->dfToDegrees != 1.0 && IsAngularParameter(pszName))
    6311           8 :         dfRawResult *= d->dfToDegrees;
    6312             : 
    6313        3489 :     if (d->dfToMeter != 1.0 && IsLinearParameter(pszName))
    6314           5 :         return dfRawResult * d->dfToMeter;
    6315             : 
    6316        3484 :     return dfRawResult;
    6317             : }
    6318             : 
    6319             : /************************************************************************/
    6320             : /*                         OSRGetNormProjParm()                         */
    6321             : /************************************************************************/
    6322             : 
    6323             : /**
    6324             :  * \brief This function is the same as OGRSpatialReference::
    6325             :  *
    6326             :  * This function is the same as OGRSpatialReference::GetNormProjParm()
    6327             :  */
    6328           1 : double OSRGetNormProjParm(OGRSpatialReferenceH hSRS, const char *pszName,
    6329             :                           double dfDefaultValue, OGRErr *pnErr)
    6330             : 
    6331             : {
    6332           1 :     VALIDATE_POINTER1(hSRS, "OSRGetNormProjParm", 0);
    6333             : 
    6334           1 :     return ToPointer(hSRS)->GetNormProjParm(pszName, dfDefaultValue, pnErr);
    6335             : }
    6336             : 
    6337             : /************************************************************************/
    6338             : /*                          SetNormProjParm()                           */
    6339             : /************************************************************************/
    6340             : 
    6341             : /**
    6342             :  * \brief Set a projection parameter with a normalized value.
    6343             :  *
    6344             :  * This method is the same as SetProjParm() except that the value of
    6345             :  * the parameter passed in is assumed to be in "normalized" form (decimal
    6346             :  * degrees for angular values, meters for linear values.  The values are
    6347             :  * converted in a form suitable for the GEOGCS and linear units in effect.
    6348             :  *
    6349             :  * This method is the same as the C function OSRSetNormProjParm().
    6350             :  *
    6351             :  * @param pszName the parameter name, which should be selected from
    6352             :  * the macros in ogr_srs_api.h, such as SRS_PP_CENTRAL_MERIDIAN.
    6353             :  *
    6354             :  * @param dfValue value to assign.
    6355             :  *
    6356             :  * @return OGRERR_NONE on success.
    6357             :  */
    6358             : 
    6359          86 : OGRErr OGRSpatialReference::SetNormProjParm(const char *pszName, double dfValue)
    6360             : 
    6361             : {
    6362         172 :     TAKE_OPTIONAL_LOCK();
    6363             : 
    6364          86 :     GetNormInfo();
    6365             : 
    6366          86 :     if (d->dfToDegrees != 0.0 &&
    6367          86 :         (d->dfToDegrees != 1.0 || d->dfFromGreenwich != 0.0) &&
    6368           0 :         IsAngularParameter(pszName))
    6369             :     {
    6370           0 :         dfValue /= d->dfToDegrees;
    6371             :     }
    6372          90 :     else if (d->dfToMeter != 1.0 && d->dfToMeter != 0.0 &&
    6373           4 :              IsLinearParameter(pszName))
    6374           4 :         dfValue /= d->dfToMeter;
    6375             : 
    6376         172 :     return SetProjParm(pszName, dfValue);
    6377             : }
    6378             : 
    6379             : /************************************************************************/
    6380             : /*                         OSRSetNormProjParm()                         */
    6381             : /************************************************************************/
    6382             : 
    6383             : /**
    6384             :  * \brief Set a projection parameter with a normalized value.
    6385             :  *
    6386             :  * This function is the same as OGRSpatialReference::SetNormProjParm()
    6387             :  */
    6388           0 : OGRErr OSRSetNormProjParm(OGRSpatialReferenceH hSRS, const char *pszParamName,
    6389             :                           double dfValue)
    6390             : 
    6391             : {
    6392           0 :     VALIDATE_POINTER1(hSRS, "OSRSetNormProjParm", OGRERR_FAILURE);
    6393             : 
    6394           0 :     return ToPointer(hSRS)->SetNormProjParm(pszParamName, dfValue);
    6395             : }
    6396             : 
    6397             : /************************************************************************/
    6398             : /*                               SetTM()                                */
    6399             : /************************************************************************/
    6400             : 
    6401         443 : OGRErr OGRSpatialReference::SetTM(double dfCenterLat, double dfCenterLong,
    6402             :                                   double dfScale, double dfFalseEasting,
    6403             :                                   double dfFalseNorthing)
    6404             : 
    6405             : {
    6406         886 :     TAKE_OPTIONAL_LOCK();
    6407             : 
    6408         443 :     return d->replaceConversionAndUnref(
    6409             :         proj_create_conversion_transverse_mercator(
    6410             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfScale,
    6411         886 :             dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6412             : }
    6413             : 
    6414             : /************************************************************************/
    6415             : /*                              OSRSetTM()                              */
    6416             : /************************************************************************/
    6417             : 
    6418           1 : OGRErr OSRSetTM(OGRSpatialReferenceH hSRS, double dfCenterLat,
    6419             :                 double dfCenterLong, double dfScale, double dfFalseEasting,
    6420             :                 double dfFalseNorthing)
    6421             : 
    6422             : {
    6423           1 :     VALIDATE_POINTER1(hSRS, "OSRSetTM", OGRERR_FAILURE);
    6424             : 
    6425           1 :     return ToPointer(hSRS)->SetTM(dfCenterLat, dfCenterLong, dfScale,
    6426           1 :                                   dfFalseEasting, dfFalseNorthing);
    6427             : }
    6428             : 
    6429             : /************************************************************************/
    6430             : /*                            SetTMVariant()                            */
    6431             : /************************************************************************/
    6432             : 
    6433           0 : OGRErr OGRSpatialReference::SetTMVariant(const char *pszVariantName,
    6434             :                                          double dfCenterLat,
    6435             :                                          double dfCenterLong, double dfScale,
    6436             :                                          double dfFalseEasting,
    6437             :                                          double dfFalseNorthing)
    6438             : 
    6439             : {
    6440           0 :     TAKE_OPTIONAL_LOCK();
    6441             : 
    6442           0 :     SetProjection(pszVariantName);
    6443           0 :     SetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, dfCenterLat);
    6444           0 :     SetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, dfCenterLong);
    6445           0 :     SetNormProjParm(SRS_PP_SCALE_FACTOR, dfScale);
    6446           0 :     SetNormProjParm(SRS_PP_FALSE_EASTING, dfFalseEasting);
    6447           0 :     SetNormProjParm(SRS_PP_FALSE_NORTHING, dfFalseNorthing);
    6448             : 
    6449           0 :     return OGRERR_NONE;
    6450             : }
    6451             : 
    6452             : /************************************************************************/
    6453             : /*                          OSRSetTMVariant()                           */
    6454             : /************************************************************************/
    6455             : 
    6456           0 : OGRErr OSRSetTMVariant(OGRSpatialReferenceH hSRS, const char *pszVariantName,
    6457             :                        double dfCenterLat, double dfCenterLong, double dfScale,
    6458             :                        double dfFalseEasting, double dfFalseNorthing)
    6459             : 
    6460             : {
    6461           0 :     VALIDATE_POINTER1(hSRS, "OSRSetTMVariant", OGRERR_FAILURE);
    6462             : 
    6463           0 :     return ToPointer(hSRS)->SetTMVariant(pszVariantName, dfCenterLat,
    6464             :                                          dfCenterLong, dfScale, dfFalseEasting,
    6465           0 :                                          dfFalseNorthing);
    6466             : }
    6467             : 
    6468             : /************************************************************************/
    6469             : /*                              SetTMSO()                               */
    6470             : /************************************************************************/
    6471             : 
    6472           2 : OGRErr OGRSpatialReference::SetTMSO(double dfCenterLat, double dfCenterLong,
    6473             :                                     double dfScale, double dfFalseEasting,
    6474             :                                     double dfFalseNorthing)
    6475             : 
    6476             : {
    6477           4 :     TAKE_OPTIONAL_LOCK();
    6478             : 
    6479           2 :     auto conv = proj_create_conversion_transverse_mercator_south_oriented(
    6480             :         d->getPROJContext(), dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
    6481             :         dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    6482             : 
    6483           2 :     const char *pszName = nullptr;
    6484           2 :     double dfConvFactor = GetTargetLinearUnits(nullptr, &pszName);
    6485           2 :     CPLString osName = pszName ? pszName : "";
    6486             : 
    6487           2 :     d->refreshProjObj();
    6488             : 
    6489           2 :     d->demoteFromBoundCRS();
    6490             : 
    6491           2 :     auto cs = proj_create_cartesian_2D_cs(
    6492             :         d->getPROJContext(), PJ_CART2D_WESTING_SOUTHING,
    6493           2 :         !osName.empty() ? osName.c_str() : nullptr, dfConvFactor);
    6494             :     auto projCRS =
    6495           2 :         proj_create_projected_crs(d->getPROJContext(), d->getProjCRSName(),
    6496           2 :                                   d->getGeodBaseCRS(), conv, cs);
    6497           2 :     proj_destroy(conv);
    6498           2 :     proj_destroy(cs);
    6499             : 
    6500           2 :     d->setPjCRS(projCRS);
    6501             : 
    6502           2 :     d->undoDemoteFromBoundCRS();
    6503             : 
    6504           4 :     return OGRERR_NONE;
    6505             : }
    6506             : 
    6507             : /************************************************************************/
    6508             : /*                             OSRSetTMSO()                             */
    6509             : /************************************************************************/
    6510             : 
    6511           0 : OGRErr OSRSetTMSO(OGRSpatialReferenceH hSRS, double dfCenterLat,
    6512             :                   double dfCenterLong, double dfScale, double dfFalseEasting,
    6513             :                   double dfFalseNorthing)
    6514             : 
    6515             : {
    6516           0 :     VALIDATE_POINTER1(hSRS, "OSRSetTMSO", OGRERR_FAILURE);
    6517             : 
    6518           0 :     return ToPointer(hSRS)->SetTMSO(dfCenterLat, dfCenterLong, dfScale,
    6519           0 :                                     dfFalseEasting, dfFalseNorthing);
    6520             : }
    6521             : 
    6522             : /************************************************************************/
    6523             : /*                              SetTPED()                               */
    6524             : /************************************************************************/
    6525             : 
    6526           1 : OGRErr OGRSpatialReference::SetTPED(double dfLat1, double dfLong1,
    6527             :                                     double dfLat2, double dfLong2,
    6528             :                                     double dfFalseEasting,
    6529             :                                     double dfFalseNorthing)
    6530             : 
    6531             : {
    6532           2 :     TAKE_OPTIONAL_LOCK();
    6533             : 
    6534           1 :     return d->replaceConversionAndUnref(
    6535             :         proj_create_conversion_two_point_equidistant(
    6536             :             d->getPROJContext(), dfLat1, dfLong1, dfLat2, dfLong2,
    6537           2 :             dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6538             : }
    6539             : 
    6540             : /************************************************************************/
    6541             : /*                             OSRSetTPED()                             */
    6542             : /************************************************************************/
    6543             : 
    6544           0 : OGRErr OSRSetTPED(OGRSpatialReferenceH hSRS, double dfLat1, double dfLong1,
    6545             :                   double dfLat2, double dfLong2, double dfFalseEasting,
    6546             :                   double dfFalseNorthing)
    6547             : 
    6548             : {
    6549           0 :     VALIDATE_POINTER1(hSRS, "OSRSetTPED", OGRERR_FAILURE);
    6550             : 
    6551           0 :     return ToPointer(hSRS)->SetTPED(dfLat1, dfLong1, dfLat2, dfLong2,
    6552           0 :                                     dfFalseEasting, dfFalseNorthing);
    6553             : }
    6554             : 
    6555             : /************************************************************************/
    6556             : /*                               SetTMG()                               */
    6557             : /************************************************************************/
    6558             : 
    6559           0 : OGRErr OGRSpatialReference::SetTMG(double dfCenterLat, double dfCenterLong,
    6560             :                                    double dfFalseEasting,
    6561             :                                    double dfFalseNorthing)
    6562             : 
    6563             : {
    6564           0 :     TAKE_OPTIONAL_LOCK();
    6565             : 
    6566           0 :     return d->replaceConversionAndUnref(
    6567             :         proj_create_conversion_tunisia_mapping_grid(
    6568             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    6569           0 :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6570             : }
    6571             : 
    6572             : /************************************************************************/
    6573             : /*                             OSRSetTMG()                              */
    6574             : /************************************************************************/
    6575             : 
    6576           0 : OGRErr OSRSetTMG(OGRSpatialReferenceH hSRS, double dfCenterLat,
    6577             :                  double dfCenterLong, double dfFalseEasting,
    6578             :                  double dfFalseNorthing)
    6579             : 
    6580             : {
    6581           0 :     VALIDATE_POINTER1(hSRS, "OSRSetTMG", OGRERR_FAILURE);
    6582             : 
    6583           0 :     return ToPointer(hSRS)->SetTMG(dfCenterLat, dfCenterLong, dfFalseEasting,
    6584           0 :                                    dfFalseNorthing);
    6585             : }
    6586             : 
    6587             : /************************************************************************/
    6588             : /*                              SetACEA()                               */
    6589             : /************************************************************************/
    6590             : 
    6591          39 : OGRErr OGRSpatialReference::SetACEA(double dfStdP1, double dfStdP2,
    6592             :                                     double dfCenterLat, double dfCenterLong,
    6593             :                                     double dfFalseEasting,
    6594             :                                     double dfFalseNorthing)
    6595             : 
    6596             : {
    6597          78 :     TAKE_OPTIONAL_LOCK();
    6598             : 
    6599             :     // Note different order of parameters. The one in PROJ is conformant with
    6600             :     // EPSG
    6601          39 :     return d->replaceConversionAndUnref(
    6602             :         proj_create_conversion_albers_equal_area(
    6603             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfStdP1, dfStdP2,
    6604          78 :             dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6605             : }
    6606             : 
    6607             : /************************************************************************/
    6608             : /*                             OSRSetACEA()                             */
    6609             : /************************************************************************/
    6610             : 
    6611           0 : OGRErr OSRSetACEA(OGRSpatialReferenceH hSRS, double dfStdP1, double dfStdP2,
    6612             :                   double dfCenterLat, double dfCenterLong,
    6613             :                   double dfFalseEasting, double dfFalseNorthing)
    6614             : 
    6615             : {
    6616           0 :     VALIDATE_POINTER1(hSRS, "OSRSetACEA", OGRERR_FAILURE);
    6617             : 
    6618           0 :     return ToPointer(hSRS)->SetACEA(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
    6619           0 :                                     dfFalseEasting, dfFalseNorthing);
    6620             : }
    6621             : 
    6622             : /************************************************************************/
    6623             : /*                               SetAE()                                */
    6624             : /************************************************************************/
    6625             : 
    6626          21 : OGRErr OGRSpatialReference::SetAE(double dfCenterLat, double dfCenterLong,
    6627             :                                   double dfFalseEasting, double dfFalseNorthing)
    6628             : 
    6629             : {
    6630          42 :     TAKE_OPTIONAL_LOCK();
    6631             : 
    6632          21 :     return d->replaceConversionAndUnref(
    6633             :         proj_create_conversion_azimuthal_equidistant(
    6634             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    6635          42 :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6636             : }
    6637             : 
    6638             : /************************************************************************/
    6639             : /*                              OSRSetAE()                              */
    6640             : /************************************************************************/
    6641             : 
    6642           0 : OGRErr OSRSetAE(OGRSpatialReferenceH hSRS, double dfCenterLat,
    6643             :                 double dfCenterLong, double dfFalseEasting,
    6644             :                 double dfFalseNorthing)
    6645             : 
    6646             : {
    6647           0 :     VALIDATE_POINTER1(hSRS, "OSRSetACEA", OGRERR_FAILURE);
    6648             : 
    6649           0 :     return ToPointer(hSRS)->SetAE(dfCenterLat, dfCenterLong, dfFalseEasting,
    6650           0 :                                   dfFalseNorthing);
    6651             : }
    6652             : 
    6653             : /************************************************************************/
    6654             : /*                              SetBonne()                              */
    6655             : /************************************************************************/
    6656             : 
    6657           1 : OGRErr OGRSpatialReference::SetBonne(double dfStdP1, double dfCentralMeridian,
    6658             :                                      double dfFalseEasting,
    6659             :                                      double dfFalseNorthing)
    6660             : 
    6661             : {
    6662           2 :     TAKE_OPTIONAL_LOCK();
    6663             : 
    6664           1 :     return d->replaceConversionAndUnref(proj_create_conversion_bonne(
    6665             :         d->getPROJContext(), dfStdP1, dfCentralMeridian, dfFalseEasting,
    6666           2 :         dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6667             : }
    6668             : 
    6669             : /************************************************************************/
    6670             : /*                            OSRSetBonne()                             */
    6671             : /************************************************************************/
    6672             : 
    6673           0 : OGRErr OSRSetBonne(OGRSpatialReferenceH hSRS, double dfStdP1,
    6674             :                    double dfCentralMeridian, double dfFalseEasting,
    6675             :                    double dfFalseNorthing)
    6676             : 
    6677             : {
    6678           0 :     VALIDATE_POINTER1(hSRS, "OSRSetBonne", OGRERR_FAILURE);
    6679             : 
    6680           0 :     return ToPointer(hSRS)->SetBonne(dfStdP1, dfCentralMeridian, dfFalseEasting,
    6681           0 :                                      dfFalseNorthing);
    6682             : }
    6683             : 
    6684             : /************************************************************************/
    6685             : /*                               SetCEA()                               */
    6686             : /************************************************************************/
    6687             : 
    6688           4 : OGRErr OGRSpatialReference::SetCEA(double dfStdP1, double dfCentralMeridian,
    6689             :                                    double dfFalseEasting,
    6690             :                                    double dfFalseNorthing)
    6691             : 
    6692             : {
    6693           8 :     TAKE_OPTIONAL_LOCK();
    6694             : 
    6695           4 :     return d->replaceConversionAndUnref(
    6696             :         proj_create_conversion_lambert_cylindrical_equal_area(
    6697             :             d->getPROJContext(), dfStdP1, dfCentralMeridian, dfFalseEasting,
    6698           8 :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6699             : }
    6700             : 
    6701             : /************************************************************************/
    6702             : /*                             OSRSetCEA()                              */
    6703             : /************************************************************************/
    6704             : 
    6705           0 : OGRErr OSRSetCEA(OGRSpatialReferenceH hSRS, double dfStdP1,
    6706             :                  double dfCentralMeridian, double dfFalseEasting,
    6707             :                  double dfFalseNorthing)
    6708             : 
    6709             : {
    6710           0 :     VALIDATE_POINTER1(hSRS, "OSRSetCEA", OGRERR_FAILURE);
    6711             : 
    6712           0 :     return ToPointer(hSRS)->SetCEA(dfStdP1, dfCentralMeridian, dfFalseEasting,
    6713           0 :                                    dfFalseNorthing);
    6714             : }
    6715             : 
    6716             : /************************************************************************/
    6717             : /*                               SetCS()                                */
    6718             : /************************************************************************/
    6719             : 
    6720           5 : OGRErr OGRSpatialReference::SetCS(double dfCenterLat, double dfCenterLong,
    6721             :                                   double dfFalseEasting, double dfFalseNorthing)
    6722             : 
    6723             : {
    6724          10 :     TAKE_OPTIONAL_LOCK();
    6725             : 
    6726           5 :     return d->replaceConversionAndUnref(proj_create_conversion_cassini_soldner(
    6727             :         d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    6728          10 :         dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6729             : }
    6730             : 
    6731             : /************************************************************************/
    6732             : /*                              OSRSetCS()                              */
    6733             : /************************************************************************/
    6734             : 
    6735           0 : OGRErr OSRSetCS(OGRSpatialReferenceH hSRS, double dfCenterLat,
    6736             :                 double dfCenterLong, double dfFalseEasting,
    6737             :                 double dfFalseNorthing)
    6738             : 
    6739             : {
    6740           0 :     VALIDATE_POINTER1(hSRS, "OSRSetCS", OGRERR_FAILURE);
    6741             : 
    6742           0 :     return ToPointer(hSRS)->SetCS(dfCenterLat, dfCenterLong, dfFalseEasting,
    6743           0 :                                   dfFalseNorthing);
    6744             : }
    6745             : 
    6746             : /************************************************************************/
    6747             : /*                               SetEC()                                */
    6748             : /************************************************************************/
    6749             : 
    6750           7 : OGRErr OGRSpatialReference::SetEC(double dfStdP1, double dfStdP2,
    6751             :                                   double dfCenterLat, double dfCenterLong,
    6752             :                                   double dfFalseEasting, double dfFalseNorthing)
    6753             : 
    6754             : {
    6755          14 :     TAKE_OPTIONAL_LOCK();
    6756             : 
    6757             :     // Note: different order of arguments
    6758           7 :     return d->replaceConversionAndUnref(
    6759             :         proj_create_conversion_equidistant_conic(
    6760             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfStdP1, dfStdP2,
    6761          14 :             dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6762             : }
    6763             : 
    6764             : /************************************************************************/
    6765             : /*                              OSRSetEC()                              */
    6766             : /************************************************************************/
    6767             : 
    6768           0 : OGRErr OSRSetEC(OGRSpatialReferenceH hSRS, double dfStdP1, double dfStdP2,
    6769             :                 double dfCenterLat, double dfCenterLong, double dfFalseEasting,
    6770             :                 double dfFalseNorthing)
    6771             : 
    6772             : {
    6773           0 :     VALIDATE_POINTER1(hSRS, "OSRSetEC", OGRERR_FAILURE);
    6774             : 
    6775           0 :     return ToPointer(hSRS)->SetEC(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
    6776           0 :                                   dfFalseEasting, dfFalseNorthing);
    6777             : }
    6778             : 
    6779             : /************************************************************************/
    6780             : /*                             SetEckert()                              */
    6781             : /************************************************************************/
    6782             : 
    6783          10 : OGRErr OGRSpatialReference::SetEckert(int nVariation,  // 1-6.
    6784             :                                       double dfCentralMeridian,
    6785             :                                       double dfFalseEasting,
    6786             :                                       double dfFalseNorthing)
    6787             : 
    6788             : {
    6789          20 :     TAKE_OPTIONAL_LOCK();
    6790             : 
    6791             :     PJ *conv;
    6792          10 :     if (nVariation == 1)
    6793             :     {
    6794           1 :         conv = proj_create_conversion_eckert_i(
    6795             :             d->getPROJContext(), dfCentralMeridian, dfFalseEasting,
    6796             :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    6797             :     }
    6798           9 :     else if (nVariation == 2)
    6799             :     {
    6800           1 :         conv = proj_create_conversion_eckert_ii(
    6801             :             d->getPROJContext(), dfCentralMeridian, dfFalseEasting,
    6802             :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    6803             :     }
    6804           8 :     else if (nVariation == 3)
    6805             :     {
    6806           1 :         conv = proj_create_conversion_eckert_iii(
    6807             :             d->getPROJContext(), dfCentralMeridian, dfFalseEasting,
    6808             :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    6809             :     }
    6810           7 :     else if (nVariation == 4)
    6811             :     {
    6812           3 :         conv = proj_create_conversion_eckert_iv(
    6813             :             d->getPROJContext(), dfCentralMeridian, dfFalseEasting,
    6814             :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    6815             :     }
    6816           4 :     else if (nVariation == 5)
    6817             :     {
    6818           1 :         conv = proj_create_conversion_eckert_v(
    6819             :             d->getPROJContext(), dfCentralMeridian, dfFalseEasting,
    6820             :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    6821             :     }
    6822           3 :     else if (nVariation == 6)
    6823             :     {
    6824           3 :         conv = proj_create_conversion_eckert_vi(
    6825             :             d->getPROJContext(), dfCentralMeridian, dfFalseEasting,
    6826             :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    6827             :     }
    6828             :     else
    6829             :     {
    6830           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6831             :                  "Unsupported Eckert variation (%d).", nVariation);
    6832           0 :         return OGRERR_UNSUPPORTED_SRS;
    6833             :     }
    6834             : 
    6835          10 :     return d->replaceConversionAndUnref(conv);
    6836             : }
    6837             : 
    6838             : /************************************************************************/
    6839             : /*                            OSRSetEckert()                            */
    6840             : /************************************************************************/
    6841             : 
    6842           0 : OGRErr OSRSetEckert(OGRSpatialReferenceH hSRS, int nVariation,
    6843             :                     double dfCentralMeridian, double dfFalseEasting,
    6844             :                     double dfFalseNorthing)
    6845             : 
    6846             : {
    6847           0 :     VALIDATE_POINTER1(hSRS, "OSRSetEckert", OGRERR_FAILURE);
    6848             : 
    6849           0 :     return ToPointer(hSRS)->SetEckert(nVariation, dfCentralMeridian,
    6850           0 :                                       dfFalseEasting, dfFalseNorthing);
    6851             : }
    6852             : 
    6853             : /************************************************************************/
    6854             : /*                            SetEckertIV()                             */
    6855             : /*                                                                      */
    6856             : /*      Deprecated                                                      */
    6857             : /************************************************************************/
    6858             : 
    6859           2 : OGRErr OGRSpatialReference::SetEckertIV(double dfCentralMeridian,
    6860             :                                         double dfFalseEasting,
    6861             :                                         double dfFalseNorthing)
    6862             : 
    6863             : {
    6864           2 :     return SetEckert(4, dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
    6865             : }
    6866             : 
    6867             : /************************************************************************/
    6868             : /*                           OSRSetEckertIV()                           */
    6869             : /************************************************************************/
    6870             : 
    6871           0 : OGRErr OSRSetEckertIV(OGRSpatialReferenceH hSRS, double dfCentralMeridian,
    6872             :                       double dfFalseEasting, double dfFalseNorthing)
    6873             : 
    6874             : {
    6875           0 :     VALIDATE_POINTER1(hSRS, "OSRSetEckertIV", OGRERR_FAILURE);
    6876             : 
    6877           0 :     return ToPointer(hSRS)->SetEckertIV(dfCentralMeridian, dfFalseEasting,
    6878           0 :                                         dfFalseNorthing);
    6879             : }
    6880             : 
    6881             : /************************************************************************/
    6882             : /*                            SetEckertVI()                             */
    6883             : /*                                                                      */
    6884             : /*      Deprecated                                                      */
    6885             : /************************************************************************/
    6886             : 
    6887           2 : OGRErr OGRSpatialReference::SetEckertVI(double dfCentralMeridian,
    6888             :                                         double dfFalseEasting,
    6889             :                                         double dfFalseNorthing)
    6890             : 
    6891             : {
    6892           2 :     return SetEckert(6, dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
    6893             : }
    6894             : 
    6895             : /************************************************************************/
    6896             : /*                           OSRSetEckertVI()                           */
    6897             : /************************************************************************/
    6898             : 
    6899           0 : OGRErr OSRSetEckertVI(OGRSpatialReferenceH hSRS, double dfCentralMeridian,
    6900             :                       double dfFalseEasting, double dfFalseNorthing)
    6901             : 
    6902             : {
    6903           0 :     VALIDATE_POINTER1(hSRS, "OSRSetEckertVI", OGRERR_FAILURE);
    6904             : 
    6905           0 :     return ToPointer(hSRS)->SetEckertVI(dfCentralMeridian, dfFalseEasting,
    6906           0 :                                         dfFalseNorthing);
    6907             : }
    6908             : 
    6909             : /************************************************************************/
    6910             : /*                         SetEquirectangular()                         */
    6911             : /************************************************************************/
    6912             : 
    6913           2 : OGRErr OGRSpatialReference::SetEquirectangular(double dfCenterLat,
    6914             :                                                double dfCenterLong,
    6915             :                                                double dfFalseEasting,
    6916             :                                                double dfFalseNorthing)
    6917             : 
    6918             : {
    6919           4 :     TAKE_OPTIONAL_LOCK();
    6920             : 
    6921           2 :     if (dfCenterLat == 0.0)
    6922             :     {
    6923           0 :         return d->replaceConversionAndUnref(
    6924             :             proj_create_conversion_equidistant_cylindrical(
    6925             :                 d->getPROJContext(), 0.0, dfCenterLong, dfFalseEasting,
    6926           0 :                 dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6927             :     }
    6928             : 
    6929             :     // Non-standard extension with non-zero latitude of origin
    6930           2 :     SetProjection(SRS_PT_EQUIRECTANGULAR);
    6931           2 :     SetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, dfCenterLat);
    6932           2 :     SetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, dfCenterLong);
    6933           2 :     SetNormProjParm(SRS_PP_FALSE_EASTING, dfFalseEasting);
    6934           2 :     SetNormProjParm(SRS_PP_FALSE_NORTHING, dfFalseNorthing);
    6935             : 
    6936           2 :     return OGRERR_NONE;
    6937             : }
    6938             : 
    6939             : /************************************************************************/
    6940             : /*                       OSRSetEquirectangular()                        */
    6941             : /************************************************************************/
    6942             : 
    6943           0 : OGRErr OSRSetEquirectangular(OGRSpatialReferenceH hSRS, double dfCenterLat,
    6944             :                              double dfCenterLong, double dfFalseEasting,
    6945             :                              double dfFalseNorthing)
    6946             : 
    6947             : {
    6948           0 :     VALIDATE_POINTER1(hSRS, "OSRSetEquirectangular", OGRERR_FAILURE);
    6949             : 
    6950           0 :     return ToPointer(hSRS)->SetEquirectangular(dfCenterLat, dfCenterLong,
    6951           0 :                                                dfFalseEasting, dfFalseNorthing);
    6952             : }
    6953             : 
    6954             : /************************************************************************/
    6955             : /*                         SetEquirectangular2()                        */
    6956             : /* Generalized form                                                     */
    6957             : /************************************************************************/
    6958             : 
    6959         182 : OGRErr OGRSpatialReference::SetEquirectangular2(double dfCenterLat,
    6960             :                                                 double dfCenterLong,
    6961             :                                                 double dfStdParallel1,
    6962             :                                                 double dfFalseEasting,
    6963             :                                                 double dfFalseNorthing)
    6964             : 
    6965             : {
    6966         364 :     TAKE_OPTIONAL_LOCK();
    6967             : 
    6968         182 :     if (dfCenterLat == 0.0)
    6969             :     {
    6970         178 :         return d->replaceConversionAndUnref(
    6971             :             proj_create_conversion_equidistant_cylindrical(
    6972             :                 d->getPROJContext(), dfStdParallel1, dfCenterLong,
    6973         178 :                 dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    6974             :     }
    6975             : 
    6976             :     // Non-standard extension with non-zero latitude of origin
    6977           4 :     SetProjection(SRS_PT_EQUIRECTANGULAR);
    6978           4 :     SetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, dfCenterLat);
    6979           4 :     SetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, dfCenterLong);
    6980           4 :     SetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, dfStdParallel1);
    6981           4 :     SetNormProjParm(SRS_PP_FALSE_EASTING, dfFalseEasting);
    6982           4 :     SetNormProjParm(SRS_PP_FALSE_NORTHING, dfFalseNorthing);
    6983             : 
    6984           4 :     return OGRERR_NONE;
    6985             : }
    6986             : 
    6987             : /************************************************************************/
    6988             : /*                       OSRSetEquirectangular2()                       */
    6989             : /************************************************************************/
    6990             : 
    6991           3 : OGRErr OSRSetEquirectangular2(OGRSpatialReferenceH hSRS, double dfCenterLat,
    6992             :                               double dfCenterLong, double dfStdParallel1,
    6993             :                               double dfFalseEasting, double dfFalseNorthing)
    6994             : 
    6995             : {
    6996           3 :     VALIDATE_POINTER1(hSRS, "OSRSetEquirectangular2", OGRERR_FAILURE);
    6997             : 
    6998           3 :     return ToPointer(hSRS)->SetEquirectangular2(dfCenterLat, dfCenterLong,
    6999             :                                                 dfStdParallel1, dfFalseEasting,
    7000           3 :                                                 dfFalseNorthing);
    7001             : }
    7002             : 
    7003             : /************************************************************************/
    7004             : /*                               SetGS()                                */
    7005             : /************************************************************************/
    7006             : 
    7007           5 : OGRErr OGRSpatialReference::SetGS(double dfCentralMeridian,
    7008             :                                   double dfFalseEasting, double dfFalseNorthing)
    7009             : 
    7010             : {
    7011           5 :     return d->replaceConversionAndUnref(proj_create_conversion_gall(
    7012             :         d->getPROJContext(), dfCentralMeridian, dfFalseEasting, dfFalseNorthing,
    7013           5 :         nullptr, 0.0, nullptr, 0.0));
    7014             : }
    7015             : 
    7016             : /************************************************************************/
    7017             : /*                              OSRSetGS()                              */
    7018             : /************************************************************************/
    7019             : 
    7020           2 : OGRErr OSRSetGS(OGRSpatialReferenceH hSRS, double dfCentralMeridian,
    7021             :                 double dfFalseEasting, double dfFalseNorthing)
    7022             : 
    7023             : {
    7024           2 :     VALIDATE_POINTER1(hSRS, "OSRSetGS", OGRERR_FAILURE);
    7025             : 
    7026           2 :     return ToPointer(hSRS)->SetGS(dfCentralMeridian, dfFalseEasting,
    7027           2 :                                   dfFalseNorthing);
    7028             : }
    7029             : 
    7030             : /************************************************************************/
    7031             : /*                               SetGH()                                */
    7032             : /************************************************************************/
    7033             : 
    7034           0 : OGRErr OGRSpatialReference::SetGH(double dfCentralMeridian,
    7035             :                                   double dfFalseEasting, double dfFalseNorthing)
    7036             : 
    7037             : {
    7038           0 :     TAKE_OPTIONAL_LOCK();
    7039             : 
    7040           0 :     return d->replaceConversionAndUnref(proj_create_conversion_goode_homolosine(
    7041             :         d->getPROJContext(), dfCentralMeridian, dfFalseEasting, dfFalseNorthing,
    7042           0 :         nullptr, 0.0, nullptr, 0.0));
    7043             : }
    7044             : 
    7045             : /************************************************************************/
    7046             : /*                              OSRSetGH()                              */
    7047             : /************************************************************************/
    7048             : 
    7049           0 : OGRErr OSRSetGH(OGRSpatialReferenceH hSRS, double dfCentralMeridian,
    7050             :                 double dfFalseEasting, double dfFalseNorthing)
    7051             : 
    7052             : {
    7053           0 :     VALIDATE_POINTER1(hSRS, "OSRSetGH", OGRERR_FAILURE);
    7054             : 
    7055           0 :     return ToPointer(hSRS)->SetGH(dfCentralMeridian, dfFalseEasting,
    7056           0 :                                   dfFalseNorthing);
    7057             : }
    7058             : 
    7059             : /************************************************************************/
    7060             : /*                               SetIGH()                               */
    7061             : /************************************************************************/
    7062             : 
    7063           0 : OGRErr OGRSpatialReference::SetIGH()
    7064             : 
    7065             : {
    7066           0 :     TAKE_OPTIONAL_LOCK();
    7067             : 
    7068           0 :     return d->replaceConversionAndUnref(
    7069             :         proj_create_conversion_interrupted_goode_homolosine(
    7070           0 :             d->getPROJContext(), 0.0, 0.0, 0.0, nullptr, 0.0, nullptr, 0.0));
    7071             : }
    7072             : 
    7073             : /************************************************************************/
    7074             : /*                             OSRSetIGH()                              */
    7075             : /************************************************************************/
    7076             : 
    7077           0 : OGRErr OSRSetIGH(OGRSpatialReferenceH hSRS)
    7078             : 
    7079             : {
    7080           0 :     VALIDATE_POINTER1(hSRS, "OSRSetIGH", OGRERR_FAILURE);
    7081             : 
    7082           0 :     return ToPointer(hSRS)->SetIGH();
    7083             : }
    7084             : 
    7085             : /************************************************************************/
    7086             : /*                              SetGEOS()                               */
    7087             : /************************************************************************/
    7088             : 
    7089           3 : OGRErr OGRSpatialReference::SetGEOS(double dfCentralMeridian,
    7090             :                                     double dfSatelliteHeight,
    7091             :                                     double dfFalseEasting,
    7092             :                                     double dfFalseNorthing)
    7093             : 
    7094             : {
    7095           6 :     TAKE_OPTIONAL_LOCK();
    7096             : 
    7097           3 :     return d->replaceConversionAndUnref(
    7098             :         proj_create_conversion_geostationary_satellite_sweep_y(
    7099             :             d->getPROJContext(), dfCentralMeridian, dfSatelliteHeight,
    7100           6 :             dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    7101             : }
    7102             : 
    7103             : /************************************************************************/
    7104             : /*                             OSRSetGEOS()                             */
    7105             : /************************************************************************/
    7106             : 
    7107           0 : OGRErr OSRSetGEOS(OGRSpatialReferenceH hSRS, double dfCentralMeridian,
    7108             :                   double dfSatelliteHeight, double dfFalseEasting,
    7109             :                   double dfFalseNorthing)
    7110             : 
    7111             : {
    7112           0 :     VALIDATE_POINTER1(hSRS, "OSRSetGEOS", OGRERR_FAILURE);
    7113             : 
    7114           0 :     return ToPointer(hSRS)->SetGEOS(dfCentralMeridian, dfSatelliteHeight,
    7115           0 :                                     dfFalseEasting, dfFalseNorthing);
    7116             : }
    7117             : 
    7118             : /************************************************************************/
    7119             : /*                     SetGaussSchreiberTMercator()                     */
    7120             : /************************************************************************/
    7121             : 
    7122           0 : OGRErr OGRSpatialReference::SetGaussSchreiberTMercator(double dfCenterLat,
    7123             :                                                        double dfCenterLong,
    7124             :                                                        double dfScale,
    7125             :                                                        double dfFalseEasting,
    7126             :                                                        double dfFalseNorthing)
    7127             : 
    7128             : {
    7129           0 :     TAKE_OPTIONAL_LOCK();
    7130             : 
    7131           0 :     return d->replaceConversionAndUnref(
    7132             :         proj_create_conversion_gauss_schreiber_transverse_mercator(
    7133             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfScale,
    7134           0 :             dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    7135             : }
    7136             : 
    7137             : /************************************************************************/
    7138             : /*                   OSRSetGaussSchreiberTMercator()                    */
    7139             : /************************************************************************/
    7140             : 
    7141           0 : OGRErr OSRSetGaussSchreiberTMercator(OGRSpatialReferenceH hSRS,
    7142             :                                      double dfCenterLat, double dfCenterLong,
    7143             :                                      double dfScale, double dfFalseEasting,
    7144             :                                      double dfFalseNorthing)
    7145             : 
    7146             : {
    7147           0 :     VALIDATE_POINTER1(hSRS, "OSRSetGaussSchreiberTMercator", OGRERR_FAILURE);
    7148             : 
    7149           0 :     return ToPointer(hSRS)->SetGaussSchreiberTMercator(
    7150           0 :         dfCenterLat, dfCenterLong, dfScale, dfFalseEasting, dfFalseNorthing);
    7151             : }
    7152             : 
    7153             : /************************************************************************/
    7154             : /*                            SetGnomonic()                             */
    7155             : /************************************************************************/
    7156             : 
    7157           2 : OGRErr OGRSpatialReference::SetGnomonic(double dfCenterLat, double dfCenterLong,
    7158             :                                         double dfFalseEasting,
    7159             :                                         double dfFalseNorthing)
    7160             : 
    7161             : {
    7162           4 :     TAKE_OPTIONAL_LOCK();
    7163             : 
    7164           2 :     return d->replaceConversionAndUnref(proj_create_conversion_gnomonic(
    7165             :         d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    7166           4 :         dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    7167             : }
    7168             : 
    7169             : /************************************************************************/
    7170             : /*                           OSRSetGnomonic()                           */
    7171             : /************************************************************************/
    7172             : 
    7173           0 : OGRErr OSRSetGnomonic(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7174             :                       double dfCenterLong, double dfFalseEasting,
    7175             :                       double dfFalseNorthing)
    7176             : 
    7177             : {
    7178           0 :     VALIDATE_POINTER1(hSRS, "OSRSetGnomonic", OGRERR_FAILURE);
    7179             : 
    7180           0 :     return ToPointer(hSRS)->SetGnomonic(dfCenterLat, dfCenterLong,
    7181           0 :                                         dfFalseEasting, dfFalseNorthing);
    7182             : }
    7183             : 
    7184             : /************************************************************************/
    7185             : /*                              SetHOMAC()                              */
    7186             : /************************************************************************/
    7187             : 
    7188             : /**
    7189             :  * \brief Set an Hotine Oblique Mercator Azimuth Center projection using
    7190             :  * azimuth angle.
    7191             :  *
    7192             :  * This projection corresponds to EPSG projection method 9815, also
    7193             :  * sometimes known as hotine oblique mercator (variant B).
    7194             :  *
    7195             :  * This method does the same thing as the C function OSRSetHOMAC().
    7196             :  *
    7197             :  * @param dfCenterLat Latitude of the projection origin.
    7198             :  * @param dfCenterLong Longitude of the projection origin.
    7199             :  * @param dfAzimuth Azimuth, measured clockwise from North, of the projection
    7200             :  * centerline.
    7201             :  * @param dfRectToSkew Angle from Rectified to Skew Grid
    7202             :  * @param dfScale Scale factor applies to the projection origin.
    7203             :  * @param dfFalseEasting False easting.
    7204             :  * @param dfFalseNorthing False northing.
    7205             :  *
    7206             :  * @return OGRERR_NONE on success.
    7207             :  */
    7208             : 
    7209           4 : OGRErr OGRSpatialReference::SetHOMAC(double dfCenterLat, double dfCenterLong,
    7210             :                                      double dfAzimuth, double dfRectToSkew,
    7211             :                                      double dfScale, double dfFalseEasting,
    7212             :                                      double dfFalseNorthing)
    7213             : 
    7214             : {
    7215           8 :     TAKE_OPTIONAL_LOCK();
    7216             : 
    7217           4 :     return d->replaceConversionAndUnref(
    7218             :         proj_create_conversion_hotine_oblique_mercator_variant_b(
    7219             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfAzimuth,
    7220             :             dfRectToSkew, dfScale, dfFalseEasting, dfFalseNorthing, nullptr,
    7221           8 :             0.0, nullptr, 0.0));
    7222             : }
    7223             : 
    7224             : /************************************************************************/
    7225             : /*                            OSRSetHOMAC()                             */
    7226             : /************************************************************************/
    7227             : 
    7228             : /**
    7229             :  * \brief Set an Oblique Mercator projection using azimuth angle.
    7230             :  *
    7231             :  * This is the same as the C++ method OGRSpatialReference::SetHOMAC()
    7232             :  */
    7233           0 : OGRErr OSRSetHOMAC(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7234             :                    double dfCenterLong, double dfAzimuth, double dfRectToSkew,
    7235             :                    double dfScale, double dfFalseEasting,
    7236             :                    double dfFalseNorthing)
    7237             : 
    7238             : {
    7239           0 :     VALIDATE_POINTER1(hSRS, "OSRSetHOMAC", OGRERR_FAILURE);
    7240             : 
    7241           0 :     return ToPointer(hSRS)->SetHOMAC(dfCenterLat, dfCenterLong, dfAzimuth,
    7242             :                                      dfRectToSkew, dfScale, dfFalseEasting,
    7243           0 :                                      dfFalseNorthing);
    7244             : }
    7245             : 
    7246             : /************************************************************************/
    7247             : /*                               SetHOM()                               */
    7248             : /************************************************************************/
    7249             : 
    7250             : /**
    7251             :  * \brief Set a Hotine Oblique Mercator projection using azimuth angle.
    7252             :  *
    7253             :  * This projection corresponds to EPSG projection method 9812, also
    7254             :  * sometimes known as hotine oblique mercator (variant A)..
    7255             :  *
    7256             :  * This method does the same thing as the C function OSRSetHOM().
    7257             :  *
    7258             :  * @param dfCenterLat Latitude of the projection origin.
    7259             :  * @param dfCenterLong Longitude of the projection origin.
    7260             :  * @param dfAzimuth Azimuth, measured clockwise from North, of the projection
    7261             :  * centerline.
    7262             :  * @param dfRectToSkew Angle from Rectified to Skew Grid
    7263             :  * @param dfScale Scale factor applies to the projection origin.
    7264             :  * @param dfFalseEasting False easting.
    7265             :  * @param dfFalseNorthing False northing.
    7266             :  *
    7267             :  * @return OGRERR_NONE on success.
    7268             :  */
    7269             : 
    7270          12 : OGRErr OGRSpatialReference::SetHOM(double dfCenterLat, double dfCenterLong,
    7271             :                                    double dfAzimuth, double dfRectToSkew,
    7272             :                                    double dfScale, double dfFalseEasting,
    7273             :                                    double dfFalseNorthing)
    7274             : 
    7275             : {
    7276          24 :     TAKE_OPTIONAL_LOCK();
    7277             : 
    7278          12 :     return d->replaceConversionAndUnref(
    7279             :         proj_create_conversion_hotine_oblique_mercator_variant_a(
    7280             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfAzimuth,
    7281             :             dfRectToSkew, dfScale, dfFalseEasting, dfFalseNorthing, nullptr,
    7282          24 :             0.0, nullptr, 0.0));
    7283             : }
    7284             : 
    7285             : /************************************************************************/
    7286             : /*                             OSRSetHOM()                              */
    7287             : /************************************************************************/
    7288             : /**
    7289             :  * \brief Set a Hotine Oblique Mercator projection using azimuth angle.
    7290             :  *
    7291             :  * This is the same as the C++ method OGRSpatialReference::SetHOM()
    7292             :  */
    7293           0 : OGRErr OSRSetHOM(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7294             :                  double dfCenterLong, double dfAzimuth, double dfRectToSkew,
    7295             :                  double dfScale, double dfFalseEasting, double dfFalseNorthing)
    7296             : 
    7297             : {
    7298           0 :     VALIDATE_POINTER1(hSRS, "OSRSetHOM", OGRERR_FAILURE);
    7299             : 
    7300           0 :     return ToPointer(hSRS)->SetHOM(dfCenterLat, dfCenterLong, dfAzimuth,
    7301             :                                    dfRectToSkew, dfScale, dfFalseEasting,
    7302           0 :                                    dfFalseNorthing);
    7303             : }
    7304             : 
    7305             : /************************************************************************/
    7306             : /*                             SetHOM2PNO()                             */
    7307             : /************************************************************************/
    7308             : 
    7309             : /**
    7310             :  * \brief Set a Hotine Oblique Mercator projection using two points on
    7311             :  * projection centerline.
    7312             :  *
    7313             :  * This method does the same thing as the C function OSRSetHOM2PNO().
    7314             :  *
    7315             :  * @param dfCenterLat Latitude of the projection origin.
    7316             :  * @param dfLat1 Latitude of the first point on center line.
    7317             :  * @param dfLong1 Longitude of the first point on center line.
    7318             :  * @param dfLat2 Latitude of the second point on center line.
    7319             :  * @param dfLong2 Longitude of the second point on center line.
    7320             :  * @param dfScale Scale factor applies to the projection origin.
    7321             :  * @param dfFalseEasting False easting.
    7322             :  * @param dfFalseNorthing False northing.
    7323             :  *
    7324             :  * @return OGRERR_NONE on success.
    7325             :  */
    7326             : 
    7327           3 : OGRErr OGRSpatialReference::SetHOM2PNO(double dfCenterLat, double dfLat1,
    7328             :                                        double dfLong1, double dfLat2,
    7329             :                                        double dfLong2, double dfScale,
    7330             :                                        double dfFalseEasting,
    7331             :                                        double dfFalseNorthing)
    7332             : 
    7333             : {
    7334           6 :     TAKE_OPTIONAL_LOCK();
    7335             : 
    7336           3 :     return d->replaceConversionAndUnref(
    7337             :         proj_create_conversion_hotine_oblique_mercator_two_point_natural_origin(
    7338             :             d->getPROJContext(), dfCenterLat, dfLat1, dfLong1, dfLat2, dfLong2,
    7339             :             dfScale, dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr,
    7340           6 :             0.0));
    7341             : }
    7342             : 
    7343             : /************************************************************************/
    7344             : /*                           OSRSetHOM2PNO()                            */
    7345             : /************************************************************************/
    7346             : /**
    7347             :  * \brief Set a Hotine Oblique Mercator projection using two points on
    7348             :  *  projection centerline.
    7349             :  *
    7350             :  * This is the same as the C++ method OGRSpatialReference::SetHOM2PNO()
    7351             :  */
    7352           0 : OGRErr OSRSetHOM2PNO(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7353             :                      double dfLat1, double dfLong1, double dfLat2,
    7354             :                      double dfLong2, double dfScale, double dfFalseEasting,
    7355             :                      double dfFalseNorthing)
    7356             : 
    7357             : {
    7358           0 :     VALIDATE_POINTER1(hSRS, "OSRSetHOM2PNO", OGRERR_FAILURE);
    7359             : 
    7360           0 :     return ToPointer(hSRS)->SetHOM2PNO(dfCenterLat, dfLat1, dfLong1, dfLat2,
    7361             :                                        dfLong2, dfScale, dfFalseEasting,
    7362           0 :                                        dfFalseNorthing);
    7363             : }
    7364             : 
    7365             : /************************************************************************/
    7366             : /*                               SetLOM()                               */
    7367             : /************************************************************************/
    7368             : 
    7369             : /**
    7370             :  * \brief Set a Laborde Oblique Mercator projection.
    7371             :  *
    7372             :  * @param dfCenterLat Latitude of the projection origin.
    7373             :  * @param dfCenterLong Longitude of the projection origin.
    7374             :  * @param dfAzimuth Azimuth, measured clockwise from North, of the projection
    7375             :  * centerline.
    7376             :  * @param dfScale Scale factor on the initial line
    7377             :  * @param dfFalseEasting False easting.
    7378             :  * @param dfFalseNorthing False northing.
    7379             :  *
    7380             :  * @return OGRERR_NONE on success.
    7381             :  */
    7382             : 
    7383           0 : OGRErr OGRSpatialReference::SetLOM(double dfCenterLat, double dfCenterLong,
    7384             :                                    double dfAzimuth, double dfScale,
    7385             :                                    double dfFalseEasting,
    7386             :                                    double dfFalseNorthing)
    7387             : 
    7388             : {
    7389           0 :     TAKE_OPTIONAL_LOCK();
    7390             : 
    7391           0 :     return d->replaceConversionAndUnref(
    7392             :         proj_create_conversion_laborde_oblique_mercator(
    7393             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfAzimuth, dfScale,
    7394           0 :             dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    7395             : }
    7396             : 
    7397             : /************************************************************************/
    7398             : /*                          SetIWMPolyconic()                           */
    7399             : /************************************************************************/
    7400             : 
    7401           0 : OGRErr OGRSpatialReference::SetIWMPolyconic(double dfLat1, double dfLat2,
    7402             :                                             double dfCenterLong,
    7403             :                                             double dfFalseEasting,
    7404             :                                             double dfFalseNorthing)
    7405             : 
    7406             : {
    7407           0 :     TAKE_OPTIONAL_LOCK();
    7408             : 
    7409           0 :     return d->replaceConversionAndUnref(
    7410             :         proj_create_conversion_international_map_world_polyconic(
    7411             :             d->getPROJContext(), dfCenterLong, dfLat1, dfLat2, dfFalseEasting,
    7412           0 :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0));
    7413             : }
    7414             : 
    7415             : /************************************************************************/
    7416             : /*                         OSRSetIWMPolyconic()                         */
    7417             : /************************************************************************/
    7418             : 
    7419           0 : OGRErr OSRSetIWMPolyconic(OGRSpatialReferenceH hSRS, double dfLat1,
    7420             :                           double dfLat2, double dfCenterLong,
    7421             :                           double dfFalseEasting, double dfFalseNorthing)
    7422             : 
    7423             : {
    7424           0 :     VALIDATE_POINTER1(hSRS, "OSRSetIWMPolyconic", OGRERR_FAILURE);
    7425             : 
    7426           0 :     return ToPointer(hSRS)->SetIWMPolyconic(dfLat1, dfLat2, dfCenterLong,
    7427           0 :                                             dfFalseEasting, dfFalseNorthing);
    7428             : }
    7429             : 
    7430             : /************************************************************************/
    7431             : /*                             SetKrovak()                              */
    7432             : /************************************************************************/
    7433             : 
    7434             : /** Krovak east-north projection.
    7435             :  *
    7436             :  * Note that dfAzimuth and dfPseudoStdParallel1 are ignored when exporting
    7437             :  * to PROJ and should be respectively set to 30.28813972222222 and 78.5
    7438             :  */
    7439           3 : OGRErr OGRSpatialReference::SetKrovak(double dfCenterLat, double dfCenterLong,
    7440             :                                       double dfAzimuth,
    7441             :                                       double dfPseudoStdParallel1,
    7442             :                                       double dfScale, double dfFalseEasting,
    7443             :                                       double dfFalseNorthing)
    7444             : 
    7445             : {
    7446           6 :     TAKE_OPTIONAL_LOCK();
    7447             : 
    7448           3 :     return d->replaceConversionAndUnref(
    7449             :         proj_create_conversion_krovak_north_oriented(
    7450             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfAzimuth,
    7451             :             dfPseudoStdParallel1, dfScale, dfFalseEasting, dfFalseNorthing,
    7452           6 :             nullptr, 0.0, nullptr, 0.0));
    7453             : }
    7454             : 
    7455             : /************************************************************************/
    7456             : /*                            OSRSetKrovak()                            */
    7457             : /************************************************************************/
    7458             : 
    7459           0 : OGRErr OSRSetKrovak(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7460             :                     double dfCenterLong, double dfAzimuth,
    7461             :                     double dfPseudoStdParallel1, double dfScale,
    7462             :                     double dfFalseEasting, double dfFalseNorthing)
    7463             : 
    7464             : {
    7465           0 :     VALIDATE_POINTER1(hSRS, "OSRSetKrovak", OGRERR_FAILURE);
    7466             : 
    7467           0 :     return ToPointer(hSRS)->SetKrovak(dfCenterLat, dfCenterLong, dfAzimuth,
    7468             :                                       dfPseudoStdParallel1, dfScale,
    7469           0 :                                       dfFalseEasting, dfFalseNorthing);
    7470             : }
    7471             : 
    7472             : /************************************************************************/
    7473             : /*                              SetLAEA()                               */
    7474             : /************************************************************************/
    7475             : 
    7476          17 : OGRErr OGRSpatialReference::SetLAEA(double dfCenterLat, double dfCenterLong,
    7477             :                                     double dfFalseEasting,
    7478             :                                     double dfFalseNorthing)
    7479             : 
    7480             : {
    7481          34 :     TAKE_OPTIONAL_LOCK();
    7482             : 
    7483          17 :     auto conv = proj_create_conversion_lambert_azimuthal_equal_area(
    7484             :         d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    7485             :         dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    7486             : 
    7487          17 :     const char *pszName = nullptr;
    7488          17 :     double dfConvFactor = GetTargetLinearUnits(nullptr, &pszName);
    7489          17 :     CPLString osName = pszName ? pszName : "";
    7490             : 
    7491          17 :     d->refreshProjObj();
    7492             : 
    7493          17 :     d->demoteFromBoundCRS();
    7494             : 
    7495          17 :     auto cs = proj_create_cartesian_2D_cs(
    7496             :         d->getPROJContext(),
    7497          17 :         std::fabs(dfCenterLat - 90) < 1e-10 && dfCenterLong == 0
    7498             :             ? PJ_CART2D_NORTH_POLE_EASTING_SOUTH_NORTHING_SOUTH
    7499           0 :         : std::fabs(dfCenterLat - -90) < 1e-10 && dfCenterLong == 0
    7500          14 :             ? PJ_CART2D_SOUTH_POLE_EASTING_NORTH_NORTHING_NORTH
    7501             :             : PJ_CART2D_EASTING_NORTHING,
    7502          17 :         !osName.empty() ? osName.c_str() : nullptr, dfConvFactor);
    7503             :     auto projCRS =
    7504          17 :         proj_create_projected_crs(d->getPROJContext(), d->getProjCRSName(),
    7505          17 :                                   d->getGeodBaseCRS(), conv, cs);
    7506          17 :     proj_destroy(conv);
    7507          17 :     proj_destroy(cs);
    7508             : 
    7509          17 :     d->setPjCRS(projCRS);
    7510             : 
    7511          17 :     d->undoDemoteFromBoundCRS();
    7512             : 
    7513          34 :     return OGRERR_NONE;
    7514             : }
    7515             : 
    7516             : /************************************************************************/
    7517             : /*                             OSRSetLAEA()                             */
    7518             : /************************************************************************/
    7519             : 
    7520           0 : OGRErr OSRSetLAEA(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7521             :                   double dfCenterLong, double dfFalseEasting,
    7522             :                   double dfFalseNorthing)
    7523             : 
    7524             : {
    7525           0 :     VALIDATE_POINTER1(hSRS, "OSRSetLAEA", OGRERR_FAILURE);
    7526             : 
    7527           0 :     return ToPointer(hSRS)->SetLAEA(dfCenterLat, dfCenterLong, dfFalseEasting,
    7528           0 :                                     dfFalseNorthing);
    7529             : }
    7530             : 
    7531             : /************************************************************************/
    7532             : /*                               SetLCC()                               */
    7533             : /************************************************************************/
    7534             : 
    7535         147 : OGRErr OGRSpatialReference::SetLCC(double dfStdP1, double dfStdP2,
    7536             :                                    double dfCenterLat, double dfCenterLong,
    7537             :                                    double dfFalseEasting,
    7538             :                                    double dfFalseNorthing)
    7539             : 
    7540             : {
    7541         294 :     TAKE_OPTIONAL_LOCK();
    7542             : 
    7543         147 :     return d->replaceConversionAndUnref(
    7544             :         proj_create_conversion_lambert_conic_conformal_2sp(
    7545             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfStdP1, dfStdP2,
    7546         294 :             dfFalseEasting, dfFalseNorthing, nullptr, 0, nullptr, 0));
    7547             : }
    7548             : 
    7549             : /************************************************************************/
    7550             : /*                             OSRSetLCC()                              */
    7551             : /************************************************************************/
    7552             : 
    7553           1 : OGRErr OSRSetLCC(OGRSpatialReferenceH hSRS, double dfStdP1, double dfStdP2,
    7554             :                  double dfCenterLat, double dfCenterLong, double dfFalseEasting,
    7555             :                  double dfFalseNorthing)
    7556             : 
    7557             : {
    7558           1 :     VALIDATE_POINTER1(hSRS, "OSRSetLCC", OGRERR_FAILURE);
    7559             : 
    7560           1 :     return ToPointer(hSRS)->SetLCC(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
    7561           1 :                                    dfFalseEasting, dfFalseNorthing);
    7562             : }
    7563             : 
    7564             : /************************************************************************/
    7565             : /*                             SetLCC1SP()                              */
    7566             : /************************************************************************/
    7567             : 
    7568          10 : OGRErr OGRSpatialReference::SetLCC1SP(double dfCenterLat, double dfCenterLong,
    7569             :                                       double dfScale, double dfFalseEasting,
    7570             :                                       double dfFalseNorthing)
    7571             : 
    7572             : {
    7573          20 :     TAKE_OPTIONAL_LOCK();
    7574             : 
    7575          10 :     return d->replaceConversionAndUnref(
    7576             :         proj_create_conversion_lambert_conic_conformal_1sp(
    7577             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfScale,
    7578          20 :             dfFalseEasting, dfFalseNorthing, nullptr, 0, nullptr, 0));
    7579             : }
    7580             : 
    7581             : /************************************************************************/
    7582             : /*                            OSRSetLCC1SP()                            */
    7583             : /************************************************************************/
    7584             : 
    7585           0 : OGRErr OSRSetLCC1SP(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7586             :                     double dfCenterLong, double dfScale, double dfFalseEasting,
    7587             :                     double dfFalseNorthing)
    7588             : 
    7589             : {
    7590           0 :     VALIDATE_POINTER1(hSRS, "OSRSetLCC1SP", OGRERR_FAILURE);
    7591             : 
    7592           0 :     return ToPointer(hSRS)->SetLCC1SP(dfCenterLat, dfCenterLong, dfScale,
    7593           0 :                                       dfFalseEasting, dfFalseNorthing);
    7594             : }
    7595             : 
    7596             : /************************************************************************/
    7597             : /*                              SetLCCB()                               */
    7598             : /************************************************************************/
    7599             : 
    7600           2 : OGRErr OGRSpatialReference::SetLCCB(double dfStdP1, double dfStdP2,
    7601             :                                     double dfCenterLat, double dfCenterLong,
    7602             :                                     double dfFalseEasting,
    7603             :                                     double dfFalseNorthing)
    7604             : 
    7605             : {
    7606           4 :     TAKE_OPTIONAL_LOCK();
    7607             : 
    7608           2 :     return d->replaceConversionAndUnref(
    7609             :         proj_create_conversion_lambert_conic_conformal_2sp_belgium(
    7610             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfStdP1, dfStdP2,
    7611           4 :             dfFalseEasting, dfFalseNorthing, nullptr, 0, nullptr, 0));
    7612             : }
    7613             : 
    7614             : /************************************************************************/
    7615             : /*                             OSRSetLCCB()                             */
    7616             : /************************************************************************/
    7617             : 
    7618           0 : OGRErr OSRSetLCCB(OGRSpatialReferenceH hSRS, double dfStdP1, double dfStdP2,
    7619             :                   double dfCenterLat, double dfCenterLong,
    7620             :                   double dfFalseEasting, double dfFalseNorthing)
    7621             : 
    7622             : {
    7623           0 :     VALIDATE_POINTER1(hSRS, "OSRSetLCCB", OGRERR_FAILURE);
    7624             : 
    7625           0 :     return ToPointer(hSRS)->SetLCCB(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
    7626           0 :                                     dfFalseEasting, dfFalseNorthing);
    7627             : }
    7628             : 
    7629             : /************************************************************************/
    7630             : /*                               SetMC()                                */
    7631             : /************************************************************************/
    7632             : 
    7633           4 : OGRErr OGRSpatialReference::SetMC(double dfCenterLat, double dfCenterLong,
    7634             :                                   double dfFalseEasting, double dfFalseNorthing)
    7635             : 
    7636             : {
    7637           8 :     TAKE_OPTIONAL_LOCK();
    7638             : 
    7639             :     (void)dfCenterLat;  // ignored
    7640             : 
    7641           4 :     return d->replaceConversionAndUnref(
    7642             :         proj_create_conversion_miller_cylindrical(
    7643             :             d->getPROJContext(), dfCenterLong, dfFalseEasting, dfFalseNorthing,
    7644           8 :             nullptr, 0, nullptr, 0));
    7645             : }
    7646             : 
    7647             : /************************************************************************/
    7648             : /*                              OSRSetMC()                              */
    7649             : /************************************************************************/
    7650             : 
    7651           0 : OGRErr OSRSetMC(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7652             :                 double dfCenterLong, double dfFalseEasting,
    7653             :                 double dfFalseNorthing)
    7654             : 
    7655             : {
    7656           0 :     VALIDATE_POINTER1(hSRS, "OSRSetMC", OGRERR_FAILURE);
    7657             : 
    7658           0 :     return ToPointer(hSRS)->SetMC(dfCenterLat, dfCenterLong, dfFalseEasting,
    7659           0 :                                   dfFalseNorthing);
    7660             : }
    7661             : 
    7662             : /************************************************************************/
    7663             : /*                            SetMercator()                             */
    7664             : /************************************************************************/
    7665             : 
    7666          60 : OGRErr OGRSpatialReference::SetMercator(double dfCenterLat, double dfCenterLong,
    7667             :                                         double dfScale, double dfFalseEasting,
    7668             :                                         double dfFalseNorthing)
    7669             : 
    7670             : {
    7671         120 :     TAKE_OPTIONAL_LOCK();
    7672             : 
    7673          60 :     if (dfCenterLat != 0.0 && dfScale == 1.0)
    7674             :     {
    7675             :         // Not sure this is correct, but this is how it has been used
    7676             :         // historically
    7677           0 :         return SetMercator2SP(dfCenterLat, 0.0, dfCenterLong, dfFalseEasting,
    7678           0 :                               dfFalseNorthing);
    7679             :     }
    7680          60 :     return d->replaceConversionAndUnref(
    7681             :         proj_create_conversion_mercator_variant_a(
    7682             :             d->getPROJContext(),
    7683             :             dfCenterLat,  // should be zero
    7684             :             dfCenterLong, dfScale, dfFalseEasting, dfFalseNorthing, nullptr, 0,
    7685          60 :             nullptr, 0));
    7686             : }
    7687             : 
    7688             : /************************************************************************/
    7689             : /*                           OSRSetMercator()                           */
    7690             : /************************************************************************/
    7691             : 
    7692           2 : OGRErr OSRSetMercator(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7693             :                       double dfCenterLong, double dfScale,
    7694             :                       double dfFalseEasting, double dfFalseNorthing)
    7695             : 
    7696             : {
    7697           2 :     VALIDATE_POINTER1(hSRS, "OSRSetMercator", OGRERR_FAILURE);
    7698             : 
    7699           2 :     return ToPointer(hSRS)->SetMercator(dfCenterLat, dfCenterLong, dfScale,
    7700           2 :                                         dfFalseEasting, dfFalseNorthing);
    7701             : }
    7702             : 
    7703             : /************************************************************************/
    7704             : /*                           SetMercator2SP()                           */
    7705             : /************************************************************************/
    7706             : 
    7707          30 : OGRErr OGRSpatialReference::SetMercator2SP(double dfStdP1, double dfCenterLat,
    7708             :                                            double dfCenterLong,
    7709             :                                            double dfFalseEasting,
    7710             :                                            double dfFalseNorthing)
    7711             : 
    7712             : {
    7713          30 :     if (dfCenterLat == 0.0)
    7714             :     {
    7715          29 :         return d->replaceConversionAndUnref(
    7716             :             proj_create_conversion_mercator_variant_b(
    7717             :                 d->getPROJContext(), dfStdP1, dfCenterLong, dfFalseEasting,
    7718          29 :                 dfFalseNorthing, nullptr, 0, nullptr, 0));
    7719             :     }
    7720             : 
    7721           1 :     TAKE_OPTIONAL_LOCK();
    7722             : 
    7723           1 :     SetProjection(SRS_PT_MERCATOR_2SP);
    7724             : 
    7725           1 :     SetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, dfStdP1);
    7726           1 :     SetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, dfCenterLat);
    7727           1 :     SetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, dfCenterLong);
    7728           1 :     SetNormProjParm(SRS_PP_FALSE_EASTING, dfFalseEasting);
    7729           1 :     SetNormProjParm(SRS_PP_FALSE_NORTHING, dfFalseNorthing);
    7730             : 
    7731           1 :     return OGRERR_NONE;
    7732             : }
    7733             : 
    7734             : /************************************************************************/
    7735             : /*                         OSRSetMercator2SP()                          */
    7736             : /************************************************************************/
    7737             : 
    7738           1 : OGRErr OSRSetMercator2SP(OGRSpatialReferenceH hSRS, double dfStdP1,
    7739             :                          double dfCenterLat, double dfCenterLong,
    7740             :                          double dfFalseEasting, double dfFalseNorthing)
    7741             : 
    7742             : {
    7743           1 :     VALIDATE_POINTER1(hSRS, "OSRSetMercator2SP", OGRERR_FAILURE);
    7744             : 
    7745           1 :     return ToPointer(hSRS)->SetMercator2SP(dfStdP1, dfCenterLat, dfCenterLong,
    7746           1 :                                            dfFalseEasting, dfFalseNorthing);
    7747             : }
    7748             : 
    7749             : /************************************************************************/
    7750             : /*                            SetMollweide()                            */
    7751             : /************************************************************************/
    7752             : 
    7753           3 : OGRErr OGRSpatialReference::SetMollweide(double dfCentralMeridian,
    7754             :                                          double dfFalseEasting,
    7755             :                                          double dfFalseNorthing)
    7756             : 
    7757             : {
    7758           6 :     TAKE_OPTIONAL_LOCK();
    7759             : 
    7760           3 :     return d->replaceConversionAndUnref(proj_create_conversion_mollweide(
    7761             :         d->getPROJContext(), dfCentralMeridian, dfFalseEasting, dfFalseNorthing,
    7762           6 :         nullptr, 0, nullptr, 0));
    7763             : }
    7764             : 
    7765             : /************************************************************************/
    7766             : /*                          OSRSetMollweide()                           */
    7767             : /************************************************************************/
    7768             : 
    7769           0 : OGRErr OSRSetMollweide(OGRSpatialReferenceH hSRS, double dfCentralMeridian,
    7770             :                        double dfFalseEasting, double dfFalseNorthing)
    7771             : 
    7772             : {
    7773           0 :     VALIDATE_POINTER1(hSRS, "OSRSetMollweide", OGRERR_FAILURE);
    7774             : 
    7775           0 :     return ToPointer(hSRS)->SetMollweide(dfCentralMeridian, dfFalseEasting,
    7776           0 :                                          dfFalseNorthing);
    7777             : }
    7778             : 
    7779             : /************************************************************************/
    7780             : /*                              SetNZMG()                               */
    7781             : /************************************************************************/
    7782             : 
    7783           8 : OGRErr OGRSpatialReference::SetNZMG(double dfCenterLat, double dfCenterLong,
    7784             :                                     double dfFalseEasting,
    7785             :                                     double dfFalseNorthing)
    7786             : 
    7787             : {
    7788          16 :     TAKE_OPTIONAL_LOCK();
    7789             : 
    7790           8 :     return d->replaceConversionAndUnref(
    7791             :         proj_create_conversion_new_zealand_mapping_grid(
    7792             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    7793          16 :             dfFalseNorthing, nullptr, 0, nullptr, 0));
    7794             : }
    7795             : 
    7796             : /************************************************************************/
    7797             : /*                             OSRSetNZMG()                             */
    7798             : /************************************************************************/
    7799             : 
    7800           0 : OGRErr OSRSetNZMG(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7801             :                   double dfCenterLong, double dfFalseEasting,
    7802             :                   double dfFalseNorthing)
    7803             : 
    7804             : {
    7805           0 :     VALIDATE_POINTER1(hSRS, "OSRSetNZMG", OGRERR_FAILURE);
    7806             : 
    7807           0 :     return ToPointer(hSRS)->SetNZMG(dfCenterLat, dfCenterLong, dfFalseEasting,
    7808           0 :                                     dfFalseNorthing);
    7809             : }
    7810             : 
    7811             : /************************************************************************/
    7812             : /*                               SetOS()                                */
    7813             : /************************************************************************/
    7814             : 
    7815           6 : OGRErr OGRSpatialReference::SetOS(double dfOriginLat, double dfCMeridian,
    7816             :                                   double dfScale, double dfFalseEasting,
    7817             :                                   double dfFalseNorthing)
    7818             : 
    7819             : {
    7820          12 :     TAKE_OPTIONAL_LOCK();
    7821             : 
    7822           6 :     return d->replaceConversionAndUnref(
    7823             :         proj_create_conversion_oblique_stereographic(
    7824             :             d->getPROJContext(), dfOriginLat, dfCMeridian, dfScale,
    7825          12 :             dfFalseEasting, dfFalseNorthing, nullptr, 0, nullptr, 0));
    7826             : }
    7827             : 
    7828             : /************************************************************************/
    7829             : /*                              OSRSetOS()                              */
    7830             : /************************************************************************/
    7831             : 
    7832           0 : OGRErr OSRSetOS(OGRSpatialReferenceH hSRS, double dfOriginLat,
    7833             :                 double dfCMeridian, double dfScale, double dfFalseEasting,
    7834             :                 double dfFalseNorthing)
    7835             : 
    7836             : {
    7837           0 :     VALIDATE_POINTER1(hSRS, "OSRSetOS", OGRERR_FAILURE);
    7838             : 
    7839           0 :     return ToPointer(hSRS)->SetOS(dfOriginLat, dfCMeridian, dfScale,
    7840           0 :                                   dfFalseEasting, dfFalseNorthing);
    7841             : }
    7842             : 
    7843             : /************************************************************************/
    7844             : /*                          SetOrthographic()                           */
    7845             : /************************************************************************/
    7846             : 
    7847           8 : OGRErr OGRSpatialReference::SetOrthographic(double dfCenterLat,
    7848             :                                             double dfCenterLong,
    7849             :                                             double dfFalseEasting,
    7850             :                                             double dfFalseNorthing)
    7851             : 
    7852             : {
    7853          16 :     TAKE_OPTIONAL_LOCK();
    7854             : 
    7855           8 :     return d->replaceConversionAndUnref(proj_create_conversion_orthographic(
    7856             :         d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    7857          16 :         dfFalseNorthing, nullptr, 0, nullptr, 0));
    7858             : }
    7859             : 
    7860             : /************************************************************************/
    7861             : /*                         OSRSetOrthographic()                         */
    7862             : /************************************************************************/
    7863             : 
    7864           1 : OGRErr OSRSetOrthographic(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7865             :                           double dfCenterLong, double dfFalseEasting,
    7866             :                           double dfFalseNorthing)
    7867             : 
    7868             : {
    7869           1 :     VALIDATE_POINTER1(hSRS, "OSRSetOrthographic", OGRERR_FAILURE);
    7870             : 
    7871           1 :     return ToPointer(hSRS)->SetOrthographic(dfCenterLat, dfCenterLong,
    7872           1 :                                             dfFalseEasting, dfFalseNorthing);
    7873             : }
    7874             : 
    7875             : /************************************************************************/
    7876             : /*                            SetPolyconic()                            */
    7877             : /************************************************************************/
    7878             : 
    7879           7 : OGRErr OGRSpatialReference::SetPolyconic(double dfCenterLat,
    7880             :                                          double dfCenterLong,
    7881             :                                          double dfFalseEasting,
    7882             :                                          double dfFalseNorthing)
    7883             : 
    7884             : {
    7885          14 :     TAKE_OPTIONAL_LOCK();
    7886             : 
    7887             :     // note: it seems that by some definitions this should include a
    7888             :     //       scale_factor parameter.
    7889           7 :     return d->replaceConversionAndUnref(
    7890             :         proj_create_conversion_american_polyconic(
    7891             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    7892          14 :             dfFalseNorthing, nullptr, 0, nullptr, 0));
    7893             : }
    7894             : 
    7895             : /************************************************************************/
    7896             : /*                          OSRSetPolyconic()                           */
    7897             : /************************************************************************/
    7898             : 
    7899           0 : OGRErr OSRSetPolyconic(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7900             :                        double dfCenterLong, double dfFalseEasting,
    7901             :                        double dfFalseNorthing)
    7902             : 
    7903             : {
    7904           0 :     VALIDATE_POINTER1(hSRS, "OSRSetPolyconic", OGRERR_FAILURE);
    7905             : 
    7906           0 :     return ToPointer(hSRS)->SetPolyconic(dfCenterLat, dfCenterLong,
    7907           0 :                                          dfFalseEasting, dfFalseNorthing);
    7908             : }
    7909             : 
    7910             : /************************************************************************/
    7911             : /*                               SetPS()                                */
    7912             : /************************************************************************/
    7913             : 
    7914             : /** Sets a Polar Stereographic projection.
    7915             :  *
    7916             :  * Two variants are possible:
    7917             :  * - Polar Stereographic Variant A: dfCenterLat must be +/- 90° and is
    7918             :  *   interpreted as the latitude of origin, combined with the scale factor
    7919             :  * - Polar Stereographic Variant B: dfCenterLat is different from +/- 90° and
    7920             :  *   is interpreted as the latitude of true scale. In that situation, dfScale
    7921             :  *   must be set to 1 (it is ignored in the projection parameters)
    7922             :  */
    7923          32 : OGRErr OGRSpatialReference::SetPS(double dfCenterLat, double dfCenterLong,
    7924             :                                   double dfScale, double dfFalseEasting,
    7925             :                                   double dfFalseNorthing)
    7926             : 
    7927             : {
    7928          64 :     TAKE_OPTIONAL_LOCK();
    7929             : 
    7930             :     PJ *conv;
    7931          32 :     if (dfScale == 1.0 && std::abs(std::abs(dfCenterLat) - 90) > 1e-8)
    7932             :     {
    7933          21 :         conv = proj_create_conversion_polar_stereographic_variant_b(
    7934             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfFalseEasting,
    7935             :             dfFalseNorthing, nullptr, 0, nullptr, 0);
    7936             :     }
    7937             :     else
    7938             :     {
    7939          11 :         conv = proj_create_conversion_polar_stereographic_variant_a(
    7940             :             d->getPROJContext(), dfCenterLat, dfCenterLong, dfScale,
    7941             :             dfFalseEasting, dfFalseNorthing, nullptr, 0, nullptr, 0);
    7942             :     }
    7943             : 
    7944          32 :     const char *pszName = nullptr;
    7945          32 :     double dfConvFactor = GetTargetLinearUnits(nullptr, &pszName);
    7946          32 :     CPLString osName = pszName ? pszName : "";
    7947             : 
    7948          32 :     d->refreshProjObj();
    7949             : 
    7950          32 :     d->demoteFromBoundCRS();
    7951             : 
    7952          32 :     auto cs = proj_create_cartesian_2D_cs(
    7953             :         d->getPROJContext(),
    7954             :         dfCenterLat > 0 ? PJ_CART2D_NORTH_POLE_EASTING_SOUTH_NORTHING_SOUTH
    7955             :                         : PJ_CART2D_SOUTH_POLE_EASTING_NORTH_NORTHING_NORTH,
    7956          32 :         !osName.empty() ? osName.c_str() : nullptr, dfConvFactor);
    7957             :     auto projCRS =
    7958          32 :         proj_create_projected_crs(d->getPROJContext(), d->getProjCRSName(),
    7959          32 :                                   d->getGeodBaseCRS(), conv, cs);
    7960          32 :     proj_destroy(conv);
    7961          32 :     proj_destroy(cs);
    7962             : 
    7963          32 :     d->setPjCRS(projCRS);
    7964             : 
    7965          32 :     d->undoDemoteFromBoundCRS();
    7966             : 
    7967          64 :     return OGRERR_NONE;
    7968             : }
    7969             : 
    7970             : /************************************************************************/
    7971             : /*                              OSRSetPS()                              */
    7972             : /************************************************************************/
    7973             : 
    7974           1 : OGRErr OSRSetPS(OGRSpatialReferenceH hSRS, double dfCenterLat,
    7975             :                 double dfCenterLong, double dfScale, double dfFalseEasting,
    7976             :                 double dfFalseNorthing)
    7977             : 
    7978             : {
    7979           1 :     VALIDATE_POINTER1(hSRS, "OSRSetPS", OGRERR_FAILURE);
    7980             : 
    7981           1 :     return ToPointer(hSRS)->SetPS(dfCenterLat, dfCenterLong, dfScale,
    7982           1 :                                   dfFalseEasting, dfFalseNorthing);
    7983             : }
    7984             : 
    7985             : /************************************************************************/
    7986             : /*                            SetRobinson()                             */
    7987             : /************************************************************************/
    7988             : 
    7989           4 : OGRErr OGRSpatialReference::SetRobinson(double dfCenterLong,
    7990             :                                         double dfFalseEasting,
    7991             :                                         double dfFalseNorthing)
    7992             : 
    7993             : {
    7994           8 :     TAKE_OPTIONAL_LOCK();
    7995             : 
    7996           4 :     return d->replaceConversionAndUnref(proj_create_conversion_robinson(
    7997             :         d->getPROJContext(), dfCenterLong, dfFalseEasting, dfFalseNorthing,
    7998           8 :         nullptr, 0, nullptr, 0));
    7999             : }
    8000             : 
    8001             : /************************************************************************/
    8002             : /*                           OSRSetRobinson()                           */
    8003             : /************************************************************************/
    8004             : 
    8005           0 : OGRErr OSRSetRobinson(OGRSpatialReferenceH hSRS, double dfCenterLong,
    8006             :                       double dfFalseEasting, double dfFalseNorthing)
    8007             : 
    8008             : {
    8009           0 :     VALIDATE_POINTER1(hSRS, "OSRSetRobinson", OGRERR_FAILURE);
    8010             : 
    8011           0 :     return ToPointer(hSRS)->SetRobinson(dfCenterLong, dfFalseEasting,
    8012           0 :                                         dfFalseNorthing);
    8013             : }
    8014             : 
    8015             : /************************************************************************/
    8016             : /*                           SetSinusoidal()                            */
    8017             : /************************************************************************/
    8018             : 
    8019          37 : OGRErr OGRSpatialReference::SetSinusoidal(double dfCenterLong,
    8020             :                                           double dfFalseEasting,
    8021             :                                           double dfFalseNorthing)
    8022             : 
    8023             : {
    8024          74 :     TAKE_OPTIONAL_LOCK();
    8025             : 
    8026          37 :     return d->replaceConversionAndUnref(proj_create_conversion_sinusoidal(
    8027             :         d->getPROJContext(), dfCenterLong, dfFalseEasting, dfFalseNorthing,
    8028          74 :         nullptr, 0, nullptr, 0));
    8029             : }
    8030             : 
    8031             : /************************************************************************/
    8032             : /*                          OSRSetSinusoidal()                          */
    8033             : /************************************************************************/
    8034             : 
    8035           1 : OGRErr OSRSetSinusoidal(OGRSpatialReferenceH hSRS, double dfCenterLong,
    8036             :                         double dfFalseEasting, double dfFalseNorthing)
    8037             : 
    8038             : {
    8039           1 :     VALIDATE_POINTER1(hSRS, "OSRSetSinusoidal", OGRERR_FAILURE);
    8040             : 
    8041           1 :     return ToPointer(hSRS)->SetSinusoidal(dfCenterLong, dfFalseEasting,
    8042           1 :                                           dfFalseNorthing);
    8043             : }
    8044             : 
    8045             : /************************************************************************/
    8046             : /*                          SetStereographic()                          */
    8047             : /************************************************************************/
    8048             : 
    8049           2 : OGRErr OGRSpatialReference::SetStereographic(double dfOriginLat,
    8050             :                                              double dfCMeridian, double dfScale,
    8051             :                                              double dfFalseEasting,
    8052             :                                              double dfFalseNorthing)
    8053             : 
    8054             : {
    8055           4 :     TAKE_OPTIONAL_LOCK();
    8056             : 
    8057           2 :     return d->replaceConversionAndUnref(proj_create_conversion_stereographic(
    8058             :         d->getPROJContext(), dfOriginLat, dfCMeridian, dfScale, dfFalseEasting,
    8059           4 :         dfFalseNorthing, nullptr, 0, nullptr, 0));
    8060             : }
    8061             : 
    8062             : /************************************************************************/
    8063             : /*                        OSRSetStereographic()                         */
    8064             : /************************************************************************/
    8065             : 
    8066           0 : OGRErr OSRSetStereographic(OGRSpatialReferenceH hSRS, double dfOriginLat,
    8067             :                            double dfCMeridian, double dfScale,
    8068             :                            double dfFalseEasting, double dfFalseNorthing)
    8069             : 
    8070             : {
    8071           0 :     VALIDATE_POINTER1(hSRS, "OSRSetStereographic", OGRERR_FAILURE);
    8072             : 
    8073           0 :     return ToPointer(hSRS)->SetStereographic(dfOriginLat, dfCMeridian, dfScale,
    8074           0 :                                              dfFalseEasting, dfFalseNorthing);
    8075             : }
    8076             : 
    8077             : /************************************************************************/
    8078             : /*                               SetSOC()                               */
    8079             : /*                                                                      */
    8080             : /*      NOTE: This definition isn't really used in practice any more    */
    8081             : /*      and should be considered deprecated.  It seems that swiss       */
    8082             : /*      oblique mercator is now define as Hotine_Oblique_Mercator       */
    8083             : /*      with an azimuth of 90 and a rectified_grid_angle of 90.  See    */
    8084             : /*      EPSG:2056 and Bug 423.                                          */
    8085             : /************************************************************************/
    8086             : 
    8087           2 : OGRErr OGRSpatialReference::SetSOC(double dfLatitudeOfOrigin,
    8088             :                                    double dfCentralMeridian,
    8089             :                                    double dfFalseEasting,
    8090             :                                    double dfFalseNorthing)
    8091             : 
    8092             : {
    8093           4 :     TAKE_OPTIONAL_LOCK();
    8094             : 
    8095           2 :     return d->replaceConversionAndUnref(
    8096             :         proj_create_conversion_hotine_oblique_mercator_variant_b(
    8097             :             d->getPROJContext(), dfLatitudeOfOrigin, dfCentralMeridian, 90.0,
    8098             :             90.0, 1.0, dfFalseEasting, dfFalseNorthing, nullptr, 0.0, nullptr,
    8099           4 :             0.0));
    8100             : #if 0
    8101             :     SetProjection( SRS_PT_SWISS_OBLIQUE_CYLINDRICAL );
    8102             :     SetNormProjParm( SRS_PP_LATITUDE_OF_CENTER, dfLatitudeOfOrigin );
    8103             :     SetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, dfCentralMeridian );
    8104             :     SetNormProjParm( SRS_PP_FALSE_EASTING, dfFalseEasting );
    8105             :     SetNormProjParm( SRS_PP_FALSE_NORTHING, dfFalseNorthing );
    8106             : 
    8107             :     return OGRERR_NONE;
    8108             : #endif
    8109             : }
    8110             : 
    8111             : /************************************************************************/
    8112             : /*                             OSRSetSOC()                              */
    8113             : /************************************************************************/
    8114             : 
    8115           0 : OGRErr OSRSetSOC(OGRSpatialReferenceH hSRS, double dfLatitudeOfOrigin,
    8116             :                  double dfCentralMeridian, double dfFalseEasting,
    8117             :                  double dfFalseNorthing)
    8118             : 
    8119             : {
    8120           0 :     VALIDATE_POINTER1(hSRS, "OSRSetSOC", OGRERR_FAILURE);
    8121             : 
    8122           0 :     return ToPointer(hSRS)->SetSOC(dfLatitudeOfOrigin, dfCentralMeridian,
    8123           0 :                                    dfFalseEasting, dfFalseNorthing);
    8124             : }
    8125             : 
    8126             : /************************************************************************/
    8127             : /*                               SetVDG()                               */
    8128             : /************************************************************************/
    8129             : 
    8130           2 : OGRErr OGRSpatialReference::SetVDG(double dfCMeridian, double dfFalseEasting,
    8131             :                                    double dfFalseNorthing)
    8132             : 
    8133             : {
    8134           4 :     TAKE_OPTIONAL_LOCK();
    8135             : 
    8136           2 :     return d->replaceConversionAndUnref(proj_create_conversion_van_der_grinten(
    8137             :         d->getPROJContext(), dfCMeridian, dfFalseEasting, dfFalseNorthing,
    8138           4 :         nullptr, 0, nullptr, 0));
    8139             : }
    8140             : 
    8141             : /************************************************************************/
    8142             : /*                             OSRSetVDG()                              */
    8143             : /************************************************************************/
    8144             : 
    8145           0 : OGRErr OSRSetVDG(OGRSpatialReferenceH hSRS, double dfCentralMeridian,
    8146             :                  double dfFalseEasting, double dfFalseNorthing)
    8147             : 
    8148             : {
    8149           0 :     VALIDATE_POINTER1(hSRS, "OSRSetVDG", OGRERR_FAILURE);
    8150             : 
    8151           0 :     return ToPointer(hSRS)->SetVDG(dfCentralMeridian, dfFalseEasting,
    8152           0 :                                    dfFalseNorthing);
    8153             : }
    8154             : 
    8155             : /************************************************************************/
    8156             : /*                               SetUTM()                               */
    8157             : /************************************************************************/
    8158             : 
    8159             : /**
    8160             :  * \brief Set UTM projection definition.
    8161             :  *
    8162             :  * This will generate a projection definition with the full set of
    8163             :  * transverse mercator projection parameters for the given UTM zone.
    8164             :  * If no PROJCS[] description is set yet, one will be set to look
    8165             :  * like "UTM Zone %d, {Northern, Southern} Hemisphere".
    8166             :  *
    8167             :  * This method is the same as the C function OSRSetUTM().
    8168             :  *
    8169             :  * @param nZone UTM zone.
    8170             :  *
    8171             :  * @param bNorth TRUE for northern hemisphere, or FALSE for southern
    8172             :  * hemisphere.
    8173             :  *
    8174             :  * @return OGRERR_NONE on success.
    8175             :  */
    8176             : 
    8177         311 : OGRErr OGRSpatialReference::SetUTM(int nZone, int bNorth)
    8178             : 
    8179             : {
    8180         622 :     TAKE_OPTIONAL_LOCK();
    8181             : 
    8182         311 :     if (nZone < 0 || nZone > 60)
    8183             :     {
    8184           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid zone: %d", nZone);
    8185           0 :         return OGRERR_FAILURE;
    8186             :     }
    8187             : 
    8188         311 :     return d->replaceConversionAndUnref(
    8189         311 :         proj_create_conversion_utm(d->getPROJContext(), nZone, bNorth));
    8190             : }
    8191             : 
    8192             : /************************************************************************/
    8193             : /*                             OSRSetUTM()                              */
    8194             : /************************************************************************/
    8195             : 
    8196             : /**
    8197             :  * \brief Set UTM projection definition.
    8198             :  *
    8199             :  * This is the same as the C++ method OGRSpatialReference::SetUTM()
    8200             :  */
    8201          19 : OGRErr OSRSetUTM(OGRSpatialReferenceH hSRS, int nZone, int bNorth)
    8202             : 
    8203             : {
    8204          19 :     VALIDATE_POINTER1(hSRS, "OSRSetUTM", OGRERR_FAILURE);
    8205             : 
    8206          19 :     return ToPointer(hSRS)->SetUTM(nZone, bNorth);
    8207             : }
    8208             : 
    8209             : /************************************************************************/
    8210             : /*                             GetUTMZone()                             */
    8211             : /*                                                                      */
    8212             : /*      Returns zero if it isn't UTM.                                   */
    8213             : /************************************************************************/
    8214             : 
    8215             : /**
    8216             :  * \brief Get utm zone information.
    8217             :  *
    8218             :  * This is the same as the C function OSRGetUTMZone().
    8219             :  *
    8220             :  * In SWIG bindings (Python, Java, etc) the GetUTMZone() method returns a
    8221             :  * zone which is negative in the southern hemisphere instead of having the
    8222             :  * pbNorth flag used in the C and C++ interface.
    8223             :  *
    8224             :  * @param pbNorth pointer to in to set to TRUE if northern hemisphere, or
    8225             :  * FALSE if southern.
    8226             :  *
    8227             :  * @return UTM zone number or zero if this isn't a UTM definition.
    8228             :  */
    8229             : 
    8230         603 : int OGRSpatialReference::GetUTMZone(int *pbNorth) const
    8231             : 
    8232             : {
    8233        1206 :     TAKE_OPTIONAL_LOCK();
    8234             : 
    8235         603 :     if (IsProjected() && GetAxesCount() == 3)
    8236             :     {
    8237           1 :         OGRSpatialReference *poSRSTmp = Clone();
    8238           1 :         poSRSTmp->DemoteTo2D(nullptr);
    8239           1 :         const int nZone = poSRSTmp->GetUTMZone(pbNorth);
    8240           1 :         delete poSRSTmp;
    8241           1 :         return nZone;
    8242             :     }
    8243             : 
    8244         602 :     const char *pszProjection = GetAttrValue("PROJECTION");
    8245             : 
    8246         602 :     if (pszProjection == nullptr ||
    8247         523 :         !EQUAL(pszProjection, SRS_PT_TRANSVERSE_MERCATOR))
    8248         274 :         return 0;
    8249             : 
    8250         328 :     if (GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) != 0.0)
    8251           5 :         return 0;
    8252             : 
    8253         323 :     if (GetProjParm(SRS_PP_SCALE_FACTOR, 1.0) != 0.9996)
    8254          15 :         return 0;
    8255             : 
    8256         308 :     if (fabs(GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0) - 500000.0) > 0.001)
    8257           6 :         return 0;
    8258             : 
    8259         302 :     const double dfFalseNorthing = GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0);
    8260             : 
    8261         302 :     if (dfFalseNorthing != 0.0 && fabs(dfFalseNorthing - 10000000.0) > 0.001)
    8262           0 :         return 0;
    8263             : 
    8264         302 :     if (pbNorth != nullptr)
    8265         236 :         *pbNorth = (dfFalseNorthing == 0);
    8266             : 
    8267             :     const double dfCentralMeridian =
    8268         302 :         GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0);
    8269         302 :     const double dfZone = (dfCentralMeridian + 186.0) / 6.0;
    8270             : 
    8271         604 :     if (dfCentralMeridian < -177.00001 || dfCentralMeridian > 177.000001 ||
    8272         906 :         std::isnan(dfZone) ||
    8273         302 :         std::abs(dfZone - static_cast<int>(dfZone) - 0.5) > 0.00001)
    8274           0 :         return 0;
    8275             : 
    8276         302 :     return static_cast<int>(dfZone);
    8277             : }
    8278             : 
    8279             : /************************************************************************/
    8280             : /*                           OSRGetUTMZone()                            */
    8281             : /************************************************************************/
    8282             : 
    8283             : /**
    8284             :  * \brief Get utm zone information.
    8285             :  *
    8286             :  * This is the same as the C++ method OGRSpatialReference::GetUTMZone()
    8287             :  */
    8288           6 : int OSRGetUTMZone(OGRSpatialReferenceH hSRS, int *pbNorth)
    8289             : 
    8290             : {
    8291           6 :     VALIDATE_POINTER1(hSRS, "OSRGetUTMZone", 0);
    8292             : 
    8293           6 :     return ToPointer(hSRS)->GetUTMZone(pbNorth);
    8294             : }
    8295             : 
    8296             : /************************************************************************/
    8297             : /*                             SetWagner()                              */
    8298             : /************************************************************************/
    8299             : 
    8300           0 : OGRErr OGRSpatialReference::SetWagner(int nVariation,  // 1--7.
    8301             :                                       double dfCenterLat, double dfFalseEasting,
    8302             :                                       double dfFalseNorthing)
    8303             : 
    8304             : {
    8305           0 :     TAKE_OPTIONAL_LOCK();
    8306             : 
    8307             :     PJ *conv;
    8308           0 :     if (nVariation == 1)
    8309             :     {
    8310           0 :         conv = proj_create_conversion_wagner_i(d->getPROJContext(), 0.0,
    8311             :                                                dfFalseEasting, dfFalseNorthing,
    8312             :                                                nullptr, 0.0, nullptr, 0.0);
    8313             :     }
    8314           0 :     else if (nVariation == 2)
    8315             :     {
    8316           0 :         conv = proj_create_conversion_wagner_ii(d->getPROJContext(), 0.0,
    8317             :                                                 dfFalseEasting, dfFalseNorthing,
    8318             :                                                 nullptr, 0.0, nullptr, 0.0);
    8319             :     }
    8320           0 :     else if (nVariation == 3)
    8321             :     {
    8322           0 :         conv = proj_create_conversion_wagner_iii(
    8323             :             d->getPROJContext(), dfCenterLat, 0.0, dfFalseEasting,
    8324             :             dfFalseNorthing, nullptr, 0.0, nullptr, 0.0);
    8325             :     }
    8326           0 :     else if (nVariation == 4)
    8327             :     {
    8328           0 :         conv = proj_create_conversion_wagner_iv(d->getPROJContext(), 0.0,
    8329             :                                                 dfFalseEasting, dfFalseNorthing,
    8330             :                                                 nullptr, 0.0, nullptr, 0.0);
    8331             :     }
    8332           0 :     else if (nVariation == 5)
    8333             :     {
    8334           0 :         conv = proj_create_conversion_wagner_v(d->getPROJContext(), 0.0,
    8335             :                                                dfFalseEasting, dfFalseNorthing,
    8336             :                                                nullptr, 0.0, nullptr, 0.0);
    8337             :     }
    8338           0 :     else if (nVariation == 6)
    8339             :     {
    8340           0 :         conv = proj_create_conversion_wagner_vi(d->getPROJContext(), 0.0,
    8341             :                                                 dfFalseEasting, dfFalseNorthing,
    8342             :                                                 nullptr, 0.0, nullptr, 0.0);
    8343             :     }
    8344           0 :     else if (nVariation == 7)
    8345             :     {
    8346           0 :         conv = proj_create_conversion_wagner_vii(
    8347             :             d->getPROJContext(), 0.0, dfFalseEasting, dfFalseNorthing, nullptr,
    8348             :             0.0, nullptr, 0.0);
    8349             :     }
    8350             :     else
    8351             :     {
    8352           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    8353             :                  "Unsupported Wagner variation (%d).", nVariation);
    8354           0 :         return OGRERR_UNSUPPORTED_SRS;
    8355             :     }
    8356             : 
    8357           0 :     return d->replaceConversionAndUnref(conv);
    8358             : }
    8359             : 
    8360             : /************************************************************************/
    8361             : /*                            OSRSetWagner()                            */
    8362             : /************************************************************************/
    8363             : 
    8364           0 : OGRErr OSRSetWagner(OGRSpatialReferenceH hSRS, int nVariation,
    8365             :                     double dfCenterLat, double dfFalseEasting,
    8366             :                     double dfFalseNorthing)
    8367             : 
    8368             : {
    8369           0 :     VALIDATE_POINTER1(hSRS, "OSRSetWagner", OGRERR_FAILURE);
    8370             : 
    8371           0 :     return ToPointer(hSRS)->SetWagner(nVariation, dfCenterLat, dfFalseEasting,
    8372           0 :                                       dfFalseNorthing);
    8373             : }
    8374             : 
    8375             : /************************************************************************/
    8376             : /*                               SetQSC()                               */
    8377             : /************************************************************************/
    8378             : 
    8379           0 : OGRErr OGRSpatialReference::SetQSC(double dfCenterLat, double dfCenterLong)
    8380             : {
    8381           0 :     TAKE_OPTIONAL_LOCK();
    8382             : 
    8383           0 :     return d->replaceConversionAndUnref(
    8384             :         proj_create_conversion_quadrilateralized_spherical_cube(
    8385             :             d->getPROJContext(), dfCenterLat, dfCenterLong, 0.0, 0.0, nullptr,
    8386           0 :             0, nullptr, 0));
    8387             : }
    8388             : 
    8389             : /************************************************************************/
    8390             : /*                             OSRSetQSC()                              */
    8391             : /************************************************************************/
    8392             : 
    8393           0 : OGRErr OSRSetQSC(OGRSpatialReferenceH hSRS, double dfCenterLat,
    8394             :                  double dfCenterLong)
    8395             : 
    8396             : {
    8397           0 :     VALIDATE_POINTER1(hSRS, "OSRSetQSC", OGRERR_FAILURE);
    8398             : 
    8399           0 :     return ToPointer(hSRS)->SetQSC(dfCenterLat, dfCenterLong);
    8400             : }
    8401             : 
    8402             : /************************************************************************/
    8403             : /*                               SetSCH()                               */
    8404             : /************************************************************************/
    8405             : 
    8406           0 : OGRErr OGRSpatialReference::SetSCH(double dfPegLat, double dfPegLong,
    8407             :                                    double dfPegHeading, double dfPegHgt)
    8408             : 
    8409             : {
    8410           0 :     TAKE_OPTIONAL_LOCK();
    8411             : 
    8412           0 :     return d->replaceConversionAndUnref(
    8413             :         proj_create_conversion_spherical_cross_track_height(
    8414             :             d->getPROJContext(), dfPegLat, dfPegLong, dfPegHeading, dfPegHgt,
    8415           0 :             nullptr, 0, nullptr, 0));
    8416             : }
    8417             : 
    8418             : /************************************************************************/
    8419             : /*                             OSRSetSCH()                              */
    8420             : /************************************************************************/
    8421             : 
    8422           0 : OGRErr OSRSetSCH(OGRSpatialReferenceH hSRS, double dfPegLat, double dfPegLong,
    8423             :                  double dfPegHeading, double dfPegHgt)
    8424             : 
    8425             : {
    8426           0 :     VALIDATE_POINTER1(hSRS, "OSRSetSCH", OGRERR_FAILURE);
    8427             : 
    8428           0 :     return ToPointer(hSRS)->SetSCH(dfPegLat, dfPegLong, dfPegHeading, dfPegHgt);
    8429             : }
    8430             : 
    8431             : /************************************************************************/
    8432             : /*                       SetVerticalPerspective()                       */
    8433             : /************************************************************************/
    8434             : 
    8435           4 : OGRErr OGRSpatialReference::SetVerticalPerspective(
    8436             :     double dfTopoOriginLat, double dfTopoOriginLon, double dfTopoOriginHeight,
    8437             :     double dfViewPointHeight, double dfFalseEasting, double dfFalseNorthing)
    8438             : {
    8439           8 :     TAKE_OPTIONAL_LOCK();
    8440             : 
    8441           4 :     return d->replaceConversionAndUnref(
    8442             :         proj_create_conversion_vertical_perspective(
    8443             :             d->getPROJContext(), dfTopoOriginLat, dfTopoOriginLon,
    8444             :             dfTopoOriginHeight, dfViewPointHeight, dfFalseEasting,
    8445           8 :             dfFalseNorthing, nullptr, 0, nullptr, 0));
    8446             : }
    8447             : 
    8448             : /************************************************************************/
    8449             : /*                     OSRSetVerticalPerspective()                      */
    8450             : /************************************************************************/
    8451             : 
    8452           1 : OGRErr OSRSetVerticalPerspective(OGRSpatialReferenceH hSRS,
    8453             :                                  double dfTopoOriginLat, double dfTopoOriginLon,
    8454             :                                  double dfTopoOriginHeight,
    8455             :                                  double dfViewPointHeight,
    8456             :                                  double dfFalseEasting, double dfFalseNorthing)
    8457             : 
    8458             : {
    8459           1 :     VALIDATE_POINTER1(hSRS, "OSRSetVerticalPerspective", OGRERR_FAILURE);
    8460             : 
    8461           1 :     return ToPointer(hSRS)->SetVerticalPerspective(
    8462             :         dfTopoOriginLat, dfTopoOriginLon, dfTopoOriginHeight, dfViewPointHeight,
    8463           1 :         dfFalseEasting, dfFalseNorthing);
    8464             : }
    8465             : 
    8466             : /************************************************************************/
    8467             : /*          SetDerivedGeogCRSWithPoleRotationGRIBConvention()           */
    8468             : /************************************************************************/
    8469             : 
    8470           2 : OGRErr OGRSpatialReference::SetDerivedGeogCRSWithPoleRotationGRIBConvention(
    8471             :     const char *pszCRSName, double dfSouthPoleLat, double dfSouthPoleLon,
    8472             :     double dfAxisRotation)
    8473             : {
    8474           4 :     TAKE_OPTIONAL_LOCK();
    8475             : 
    8476           2 :     d->refreshProjObj();
    8477           2 :     if (!d->m_pj_crs)
    8478           0 :         return OGRERR_FAILURE;
    8479           2 :     if (d->m_pjType != PJ_TYPE_GEOGRAPHIC_2D_CRS)
    8480           0 :         return OGRERR_FAILURE;
    8481           2 :     auto ctxt = d->getPROJContext();
    8482           2 :     auto conv = proj_create_conversion_pole_rotation_grib_convention(
    8483             :         ctxt, dfSouthPoleLat, dfSouthPoleLon, dfAxisRotation, nullptr, 0);
    8484           2 :     auto cs = proj_crs_get_coordinate_system(ctxt, d->m_pj_crs);
    8485           4 :     d->setPjCRS(proj_create_derived_geographic_crs(ctxt, pszCRSName,
    8486           2 :                                                    d->m_pj_crs, conv, cs));
    8487           2 :     proj_destroy(conv);
    8488           2 :     proj_destroy(cs);
    8489           2 :     return OGRERR_NONE;
    8490             : }
    8491             : 
    8492             : /************************************************************************/
    8493             : /*        SetDerivedGeogCRSWithPoleRotationNetCDFCFConvention()         */
    8494             : /************************************************************************/
    8495             : 
    8496           3 : OGRErr OGRSpatialReference::SetDerivedGeogCRSWithPoleRotationNetCDFCFConvention(
    8497             :     const char *pszCRSName, double dfGridNorthPoleLat,
    8498             :     double dfGridNorthPoleLon, double dfNorthPoleGridLon)
    8499             : {
    8500           3 :     TAKE_OPTIONAL_LOCK();
    8501             : 
    8502             : #if PROJ_VERSION_MAJOR > 8 ||                                                  \
    8503             :     (PROJ_VERSION_MAJOR == 8 && PROJ_VERSION_MINOR >= 2)
    8504             :     d->refreshProjObj();
    8505             :     if (!d->m_pj_crs)
    8506             :         return OGRERR_FAILURE;
    8507             :     if (d->m_pjType != PJ_TYPE_GEOGRAPHIC_2D_CRS)
    8508             :         return OGRERR_FAILURE;
    8509             :     auto ctxt = d->getPROJContext();
    8510             :     auto conv = proj_create_conversion_pole_rotation_netcdf_cf_convention(
    8511             :         ctxt, dfGridNorthPoleLat, dfGridNorthPoleLon, dfNorthPoleGridLon,
    8512             :         nullptr, 0);
    8513             :     auto cs = proj_crs_get_coordinate_system(ctxt, d->m_pj_crs);
    8514             :     d->setPjCRS(proj_create_derived_geographic_crs(ctxt, pszCRSName,
    8515             :                                                    d->m_pj_crs, conv, cs));
    8516             :     proj_destroy(conv);
    8517             :     proj_destroy(cs);
    8518             :     return OGRERR_NONE;
    8519             : #else
    8520             :     (void)pszCRSName;
    8521           3 :     SetProjection("Rotated_pole");
    8522           3 :     SetExtension(
    8523             :         "PROJCS", "PROJ4",
    8524             :         CPLSPrintf("+proj=ob_tran +o_proj=longlat +lon_0=%.17g +o_lon_p=%.17g "
    8525             :                    "+o_lat_p=%.17g +a=%.17g +b=%.17g "
    8526             :                    "+to_meter=0.0174532925199433 "
    8527             :                    "+wktext",
    8528             :                    180.0 + dfGridNorthPoleLon, dfNorthPoleGridLon,
    8529             :                    dfGridNorthPoleLat, GetSemiMajor(nullptr),
    8530             :                    GetSemiMinor(nullptr)));
    8531           6 :     return OGRERR_NONE;
    8532             : #endif
    8533             : }
    8534             : 
    8535             : /************************************************************************/
    8536             : /*                            SetAuthority()                            */
    8537             : /************************************************************************/
    8538             : 
    8539             : /**
    8540             :  * \brief Set the authority for a node.
    8541             :  *
    8542             :  * This method is the same as the C function OSRSetAuthority().
    8543             :  *
    8544             :  * @param pszTargetKey the partial or complete path to the node to
    8545             :  * set an authority on.  i.e. "PROJCS", "GEOGCS" or "GEOGCS|UNIT".
    8546             :  *
    8547             :  * @param pszAuthority authority name, such as "EPSG".
    8548             :  *
    8549             :  * @param nCode code for value with this authority.
    8550             :  *
    8551             :  * @return OGRERR_NONE on success.
    8552             :  */
    8553             : 
    8554       12801 : OGRErr OGRSpatialReference::SetAuthority(const char *pszTargetKey,
    8555             :                                          const char *pszAuthority, int nCode)
    8556             : 
    8557             : {
    8558       25602 :     TAKE_OPTIONAL_LOCK();
    8559             : 
    8560       12801 :     d->refreshProjObj();
    8561       12801 :     pszTargetKey = d->nullifyTargetKeyIfPossible(pszTargetKey);
    8562             : 
    8563       12801 :     if (pszTargetKey == nullptr)
    8564             :     {
    8565         260 :         if (!d->m_pj_crs)
    8566           0 :             return OGRERR_FAILURE;
    8567         260 :         CPLString osCode;
    8568         260 :         osCode.Printf("%d", nCode);
    8569         260 :         d->demoteFromBoundCRS();
    8570         260 :         d->setPjCRS(proj_alter_id(d->getPROJContext(), d->m_pj_crs,
    8571             :                                   pszAuthority, osCode.c_str()));
    8572         260 :         d->undoDemoteFromBoundCRS();
    8573         260 :         return OGRERR_NONE;
    8574             :     }
    8575             : 
    8576       12541 :     d->demoteFromBoundCRS();
    8577       12541 :     if (d->m_pjType == PJ_TYPE_PROJECTED_CRS && EQUAL(pszTargetKey, "GEOGCS"))
    8578             :     {
    8579        4146 :         CPLString osCode;
    8580        4146 :         osCode.Printf("%d", nCode);
    8581             :         auto newGeogCRS =
    8582        4146 :             proj_alter_id(d->getPROJContext(), d->getGeodBaseCRS(),
    8583             :                           pszAuthority, osCode.c_str());
    8584             : 
    8585             :         auto conv =
    8586        4146 :             proj_crs_get_coordoperation(d->getPROJContext(), d->m_pj_crs);
    8587             : 
    8588        4146 :         auto projCRS = proj_create_projected_crs(
    8589             :             d->getPROJContext(), d->getProjCRSName(), newGeogCRS, conv,
    8590        4146 :             d->getProjCRSCoordSys());
    8591             : 
    8592             :         // Preserve existing id on the PROJCRS
    8593        4146 :         const char *pszProjCRSAuthName = proj_get_id_auth_name(d->m_pj_crs, 0);
    8594        4146 :         const char *pszProjCRSCode = proj_get_id_code(d->m_pj_crs, 0);
    8595        4146 :         if (pszProjCRSAuthName && pszProjCRSCode)
    8596             :         {
    8597             :             auto projCRSWithId =
    8598           0 :                 proj_alter_id(d->getPROJContext(), projCRS, pszProjCRSAuthName,
    8599             :                               pszProjCRSCode);
    8600           0 :             proj_destroy(projCRS);
    8601           0 :             projCRS = projCRSWithId;
    8602             :         }
    8603             : 
    8604        4146 :         proj_destroy(newGeogCRS);
    8605        4146 :         proj_destroy(conv);
    8606             : 
    8607        4146 :         d->setPjCRS(projCRS);
    8608        4146 :         d->undoDemoteFromBoundCRS();
    8609        4146 :         return OGRERR_NONE;
    8610             :     }
    8611        8395 :     d->undoDemoteFromBoundCRS();
    8612             : 
    8613             :     /* -------------------------------------------------------------------- */
    8614             :     /*      Find the node below which the authority should be put.          */
    8615             :     /* -------------------------------------------------------------------- */
    8616        8395 :     OGR_SRSNode *poNode = GetAttrNode(pszTargetKey);
    8617             : 
    8618        8395 :     if (poNode == nullptr)
    8619           0 :         return OGRERR_FAILURE;
    8620             : 
    8621             :     /* -------------------------------------------------------------------- */
    8622             :     /*      If there is an existing AUTHORITY child blow it away before     */
    8623             :     /*      trying to set a new one.                                        */
    8624             :     /* -------------------------------------------------------------------- */
    8625        8395 :     int iOldChild = poNode->FindChild("AUTHORITY");
    8626        8395 :     if (iOldChild != -1)
    8627           5 :         poNode->DestroyChild(iOldChild);
    8628             : 
    8629             :     /* -------------------------------------------------------------------- */
    8630             :     /*      Create a new authority node.                                    */
    8631             :     /* -------------------------------------------------------------------- */
    8632        8395 :     char szCode[32] = {};
    8633             : 
    8634        8395 :     snprintf(szCode, sizeof(szCode), "%d", nCode);
    8635             : 
    8636        8395 :     OGR_SRSNode *poAuthNode = new OGR_SRSNode("AUTHORITY");
    8637        8395 :     poAuthNode->AddChild(new OGR_SRSNode(pszAuthority));
    8638        8395 :     poAuthNode->AddChild(new OGR_SRSNode(szCode));
    8639             : 
    8640        8395 :     poNode->AddChild(poAuthNode);
    8641             : 
    8642        8395 :     return OGRERR_NONE;
    8643             : }
    8644             : 
    8645             : /************************************************************************/
    8646             : /*                          OSRSetAuthority()                           */
    8647             : /************************************************************************/
    8648             : 
    8649             : /**
    8650             :  * \brief Set the authority for a node.
    8651             :  *
    8652             :  * This function is the same as OGRSpatialReference::SetAuthority().
    8653             :  */
    8654           0 : OGRErr OSRSetAuthority(OGRSpatialReferenceH hSRS, const char *pszTargetKey,
    8655             :                        const char *pszAuthority, int nCode)
    8656             : 
    8657             : {
    8658           0 :     VALIDATE_POINTER1(hSRS, "OSRSetAuthority", OGRERR_FAILURE);
    8659             : 
    8660           0 :     return ToPointer(hSRS)->SetAuthority(pszTargetKey, pszAuthority, nCode);
    8661             : }
    8662             : 
    8663             : /************************************************************************/
    8664             : /*                          GetAuthorityCode()                          */
    8665             : /************************************************************************/
    8666             : 
    8667             : /**
    8668             :  * \brief Get the authority code for a node.
    8669             :  *
    8670             :  * This method is used to query an AUTHORITY[] node from within the
    8671             :  * WKT tree, and fetch the code value.
    8672             :  *
    8673             :  * While in theory values may be non-numeric, for the EPSG authority all
    8674             :  * code values should be integral.
    8675             :  *
    8676             :  * This method is the same as the C function OSRGetAuthorityCode().
    8677             :  *
    8678             :  * @param pszTargetKey the partial or complete path to the node to
    8679             :  * get an authority from.  i.e. "PROJCS", "GEOGCS", "GEOGCS|UNIT" or NULL to
    8680             :  * search for an authority node on the root element.
    8681             :  *
    8682             :  * @return value code from authority node, or NULL on failure.  The value
    8683             :  * returned is internal and should not be freed or modified.
    8684             :  */
    8685             : 
    8686             : const char *
    8687       52744 : OGRSpatialReference::GetAuthorityCode(const char *pszTargetKey) const
    8688             : 
    8689             : {
    8690      105488 :     TAKE_OPTIONAL_LOCK();
    8691             : 
    8692       52744 :     d->refreshProjObj();
    8693       52744 :     const char *pszInputTargetKey = pszTargetKey;
    8694       52744 :     pszTargetKey = d->nullifyTargetKeyIfPossible(pszTargetKey);
    8695       52744 :     if (pszTargetKey == nullptr)
    8696             :     {
    8697       44161 :         if (!d->m_pj_crs)
    8698             :         {
    8699          17 :             return nullptr;
    8700             :         }
    8701       44144 :         d->demoteFromBoundCRS();
    8702       44144 :         auto ret = proj_get_id_code(d->m_pj_crs, 0);
    8703       44144 :         if (ret == nullptr && d->m_pjType == PJ_TYPE_PROJECTED_CRS)
    8704             :         {
    8705        1378 :             auto ctxt = d->getPROJContext();
    8706        1378 :             auto cs = proj_crs_get_coordinate_system(ctxt, d->m_pj_crs);
    8707        1378 :             if (cs)
    8708             :             {
    8709        1378 :                 const int axisCount = proj_cs_get_axis_count(ctxt, cs);
    8710        1378 :                 proj_destroy(cs);
    8711        1378 :                 if (axisCount == 3)
    8712             :                 {
    8713             :                     // This might come from a COMPD_CS with a VERT_DATUM type =
    8714             :                     // 2002 in which case, using the WKT1 representation will
    8715             :                     // enable us to recover the EPSG code.
    8716          14 :                     pszTargetKey = pszInputTargetKey;
    8717             :                 }
    8718             :             }
    8719             :         }
    8720       44144 :         d->undoDemoteFromBoundCRS();
    8721       44144 :         if (ret != nullptr || pszTargetKey == nullptr)
    8722             :         {
    8723       44144 :             return ret;
    8724             :         }
    8725             :     }
    8726             : 
    8727             :     // Special key for that context
    8728        8587 :     else if (EQUAL(pszTargetKey, "HORIZCRS") &&
    8729           4 :              d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    8730             :     {
    8731           4 :         auto ctxt = d->getPROJContext();
    8732           4 :         auto crs = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 0);
    8733           4 :         if (crs)
    8734             :         {
    8735           4 :             const char *ret = proj_get_id_code(crs, 0);
    8736           4 :             if (ret)
    8737           4 :                 ret = CPLSPrintf("%s", ret);
    8738           4 :             proj_destroy(crs);
    8739           4 :             return ret;
    8740             :         }
    8741             :     }
    8742        8583 :     else if (EQUAL(pszTargetKey, "VERTCRS") &&
    8743           4 :              d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    8744             :     {
    8745           4 :         auto ctxt = d->getPROJContext();
    8746           4 :         auto crs = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 1);
    8747           4 :         if (crs)
    8748             :         {
    8749           4 :             const char *ret = proj_get_id_code(crs, 0);
    8750           4 :             if (ret)
    8751           4 :                 ret = CPLSPrintf("%s", ret);
    8752           4 :             proj_destroy(crs);
    8753           4 :             return ret;
    8754             :         }
    8755             :     }
    8756             : 
    8757             :     /* -------------------------------------------------------------------- */
    8758             :     /*      Find the node below which the authority should be put.          */
    8759             :     /* -------------------------------------------------------------------- */
    8760        8575 :     const OGR_SRSNode *poNode = GetAttrNode(pszTargetKey);
    8761             : 
    8762        8575 :     if (poNode == nullptr)
    8763         106 :         return nullptr;
    8764             : 
    8765             :     /* -------------------------------------------------------------------- */
    8766             :     /*      Fetch AUTHORITY child if there is one.                          */
    8767             :     /* -------------------------------------------------------------------- */
    8768        8469 :     if (poNode->FindChild("AUTHORITY") == -1)
    8769         196 :         return nullptr;
    8770             : 
    8771        8273 :     poNode = poNode->GetChild(poNode->FindChild("AUTHORITY"));
    8772             : 
    8773             :     /* -------------------------------------------------------------------- */
    8774             :     /*      Create a new authority node.                                    */
    8775             :     /* -------------------------------------------------------------------- */
    8776        8273 :     if (poNode->GetChildCount() < 2)
    8777           0 :         return nullptr;
    8778             : 
    8779        8273 :     return poNode->GetChild(1)->GetValue();
    8780             : }
    8781             : 
    8782             : /************************************************************************/
    8783             : /*                        OSRGetAuthorityCode()                         */
    8784             : /************************************************************************/
    8785             : 
    8786             : /**
    8787             :  * \brief Get the authority code for a node.
    8788             :  *
    8789             :  * This function is the same as OGRSpatialReference::GetAuthorityCode().
    8790             :  */
    8791         839 : const char *OSRGetAuthorityCode(OGRSpatialReferenceH hSRS,
    8792             :                                 const char *pszTargetKey)
    8793             : 
    8794             : {
    8795         839 :     VALIDATE_POINTER1(hSRS, "OSRGetAuthorityCode", nullptr);
    8796             : 
    8797         839 :     return ToPointer(hSRS)->GetAuthorityCode(pszTargetKey);
    8798             : }
    8799             : 
    8800             : /************************************************************************/
    8801             : /*                          GetAuthorityName()                          */
    8802             : /************************************************************************/
    8803             : 
    8804             : /**
    8805             :  * \brief Get the authority name for a node.
    8806             :  *
    8807             :  * This method is used to query an AUTHORITY[] node from within the
    8808             :  * WKT tree, and fetch the authority name value.
    8809             :  *
    8810             :  * The most common authority is "EPSG".
    8811             :  *
    8812             :  * This method is the same as the C function OSRGetAuthorityName().
    8813             :  *
    8814             :  * @param pszTargetKey the partial or complete path to the node to
    8815             :  * get an authority from.  i.e. "PROJCS", "GEOGCS", "GEOGCS|UNIT" or NULL to
    8816             :  * search for an authority node on the root element.
    8817             :  *
    8818             :  * @return value code from authority node, or NULL on failure. The value
    8819             :  * returned is internal and should not be freed or modified.
    8820             :  */
    8821             : 
    8822             : const char *
    8823       66987 : OGRSpatialReference::GetAuthorityName(const char *pszTargetKey) const
    8824             : 
    8825             : {
    8826      133974 :     TAKE_OPTIONAL_LOCK();
    8827             : 
    8828       66987 :     d->refreshProjObj();
    8829       66987 :     const char *pszInputTargetKey = pszTargetKey;
    8830       66987 :     pszTargetKey = d->nullifyTargetKeyIfPossible(pszTargetKey);
    8831       66987 :     if (pszTargetKey == nullptr)
    8832             :     {
    8833       37290 :         if (!d->m_pj_crs)
    8834             :         {
    8835          18 :             return nullptr;
    8836             :         }
    8837       37272 :         d->demoteFromBoundCRS();
    8838       37272 :         auto ret = proj_get_id_auth_name(d->m_pj_crs, 0);
    8839       37272 :         if (ret == nullptr && d->m_pjType == PJ_TYPE_PROJECTED_CRS)
    8840             :         {
    8841        1012 :             auto ctxt = d->getPROJContext();
    8842        1012 :             auto cs = proj_crs_get_coordinate_system(ctxt, d->m_pj_crs);
    8843        1012 :             if (cs)
    8844             :             {
    8845        1012 :                 const int axisCount = proj_cs_get_axis_count(ctxt, cs);
    8846        1012 :                 proj_destroy(cs);
    8847        1012 :                 if (axisCount == 3)
    8848             :                 {
    8849             :                     // This might come from a COMPD_CS with a VERT_DATUM type =
    8850             :                     // 2002 in which case, using the WKT1 representation will
    8851             :                     // enable us to recover the EPSG code.
    8852          14 :                     pszTargetKey = pszInputTargetKey;
    8853             :                 }
    8854             :             }
    8855             :         }
    8856       37272 :         d->undoDemoteFromBoundCRS();
    8857       37272 :         if (ret != nullptr || pszTargetKey == nullptr)
    8858             :         {
    8859       37272 :             return ret;
    8860             :         }
    8861             :     }
    8862             : 
    8863             :     // Special key for that context
    8864       29701 :     else if (EQUAL(pszTargetKey, "HORIZCRS") &&
    8865           4 :              d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    8866             :     {
    8867           4 :         auto ctxt = d->getPROJContext();
    8868           4 :         auto crs = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 0);
    8869           4 :         if (crs)
    8870             :         {
    8871           4 :             const char *ret = proj_get_id_auth_name(crs, 0);
    8872           4 :             if (ret)
    8873           4 :                 ret = CPLSPrintf("%s", ret);
    8874           4 :             proj_destroy(crs);
    8875           4 :             return ret;
    8876             :         }
    8877             :     }
    8878       29697 :     else if (EQUAL(pszTargetKey, "VERTCRS") &&
    8879           4 :              d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    8880             :     {
    8881           4 :         auto ctxt = d->getPROJContext();
    8882           4 :         auto crs = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 1);
    8883           4 :         if (crs)
    8884             :         {
    8885           4 :             const char *ret = proj_get_id_auth_name(crs, 0);
    8886           4 :             if (ret)
    8887           4 :                 ret = CPLSPrintf("%s", ret);
    8888           4 :             proj_destroy(crs);
    8889           4 :             return ret;
    8890             :         }
    8891             :     }
    8892             : 
    8893             :     /* -------------------------------------------------------------------- */
    8894             :     /*      Find the node below which the authority should be put.          */
    8895             :     /* -------------------------------------------------------------------- */
    8896       29689 :     const OGR_SRSNode *poNode = GetAttrNode(pszTargetKey);
    8897             : 
    8898       29689 :     if (poNode == nullptr)
    8899       12159 :         return nullptr;
    8900             : 
    8901             :     /* -------------------------------------------------------------------- */
    8902             :     /*      Fetch AUTHORITY child if there is one.                          */
    8903             :     /* -------------------------------------------------------------------- */
    8904       17530 :     if (poNode->FindChild("AUTHORITY") == -1)
    8905        1596 :         return nullptr;
    8906             : 
    8907       15934 :     poNode = poNode->GetChild(poNode->FindChild("AUTHORITY"));
    8908             : 
    8909             :     /* -------------------------------------------------------------------- */
    8910             :     /*      Create a new authority node.                                    */
    8911             :     /* -------------------------------------------------------------------- */
    8912       15934 :     if (poNode->GetChildCount() < 2)
    8913           0 :         return nullptr;
    8914             : 
    8915       15934 :     return poNode->GetChild(0)->GetValue();
    8916             : }
    8917             : 
    8918             : /************************************************************************/
    8919             : /*                        OSRGetAuthorityName()                         */
    8920             : /************************************************************************/
    8921             : 
    8922             : /**
    8923             :  * \brief Get the authority name for a node.
    8924             :  *
    8925             :  * This function is the same as OGRSpatialReference::GetAuthorityName().
    8926             :  */
    8927          95 : const char *OSRGetAuthorityName(OGRSpatialReferenceH hSRS,
    8928             :                                 const char *pszTargetKey)
    8929             : 
    8930             : {
    8931          95 :     VALIDATE_POINTER1(hSRS, "OSRGetAuthorityName", nullptr);
    8932             : 
    8933          95 :     return ToPointer(hSRS)->GetAuthorityName(pszTargetKey);
    8934             : }
    8935             : 
    8936             : /************************************************************************/
    8937             : /*                             GetOGCURN()                              */
    8938             : /************************************************************************/
    8939             : 
    8940             : /**
    8941             :  * \brief Get a OGC URN string describing the CRS, when possible
    8942             :  *
    8943             :  * This method assumes that the CRS has a top-level identifier, or is
    8944             :  * a compound CRS whose horizontal and vertical parts have a top-level
    8945             :  * identifier.
    8946             :  *
    8947             :  * @return a string to free with CPLFree(), or nullptr when no result can be
    8948             :  * generated
    8949             :  *
    8950             :  * @since GDAL 3.5
    8951             :  */
    8952             : 
    8953          68 : char *OGRSpatialReference::GetOGCURN() const
    8954             : 
    8955             : {
    8956         136 :     TAKE_OPTIONAL_LOCK();
    8957             : 
    8958          68 :     const char *pszAuthName = GetAuthorityName();
    8959          68 :     const char *pszAuthCode = GetAuthorityCode();
    8960          68 :     if (pszAuthName && pszAuthCode)
    8961          65 :         return CPLStrdup(
    8962          65 :             CPLSPrintf("urn:ogc:def:crs:%s::%s", pszAuthName, pszAuthCode));
    8963           3 :     if (d->m_pjType != PJ_TYPE_COMPOUND_CRS)
    8964           2 :         return nullptr;
    8965           1 :     auto horizCRS = proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, 0);
    8966           1 :     auto vertCRS = proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, 1);
    8967           1 :     char *pszRet = nullptr;
    8968           1 :     if (horizCRS && vertCRS)
    8969             :     {
    8970           1 :         auto horizAuthName = proj_get_id_auth_name(horizCRS, 0);
    8971           1 :         auto horizAuthCode = proj_get_id_code(horizCRS, 0);
    8972           1 :         auto vertAuthName = proj_get_id_auth_name(vertCRS, 0);
    8973           1 :         auto vertAuthCode = proj_get_id_code(vertCRS, 0);
    8974           1 :         if (horizAuthName && horizAuthCode && vertAuthName && vertAuthCode)
    8975             :         {
    8976           1 :             pszRet = CPLStrdup(CPLSPrintf(
    8977             :                 "urn:ogc:def:crs,crs:%s::%s,crs:%s::%s", horizAuthName,
    8978             :                 horizAuthCode, vertAuthName, vertAuthCode));
    8979             :         }
    8980             :     }
    8981           1 :     proj_destroy(horizCRS);
    8982           1 :     proj_destroy(vertCRS);
    8983           1 :     return pszRet;
    8984             : }
    8985             : 
    8986             : /************************************************************************/
    8987             : /*                           StripVertical()                            */
    8988             : /************************************************************************/
    8989             : 
    8990             : /**
    8991             :  * \brief Convert a compound cs into a horizontal CS.
    8992             :  *
    8993             :  * If this SRS is of type COMPD_CS[] then the vertical CS and the root COMPD_CS
    8994             :  * nodes are stripped resulting and only the horizontal coordinate system
    8995             :  * portion remains (normally PROJCS, GEOGCS or LOCAL_CS).
    8996             :  *
    8997             :  * If this is not a compound coordinate system then nothing is changed.
    8998             :  *
    8999             :  * This method is the same as the C function OSRStripVertical().
    9000             :  *
    9001             :  */
    9002             : 
    9003          47 : OGRErr OGRSpatialReference::StripVertical()
    9004             : 
    9005             : {
    9006          94 :     TAKE_OPTIONAL_LOCK();
    9007             : 
    9008          47 :     d->refreshProjObj();
    9009          47 :     d->demoteFromBoundCRS();
    9010          47 :     if (!d->m_pj_crs || d->m_pjType != PJ_TYPE_COMPOUND_CRS)
    9011             :     {
    9012           0 :         d->undoDemoteFromBoundCRS();
    9013           0 :         return OGRERR_NONE;
    9014             :     }
    9015          47 :     auto horizCRS = proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, 0);
    9016          47 :     if (!horizCRS)
    9017             :     {
    9018           0 :         d->undoDemoteFromBoundCRS();
    9019           0 :         return OGRERR_FAILURE;
    9020             :     }
    9021             : 
    9022          47 :     bool reuseExistingBoundCRS = false;
    9023          47 :     if (d->m_pj_bound_crs_target)
    9024             :     {
    9025           4 :         auto type = proj_get_type(d->m_pj_bound_crs_target);
    9026           8 :         reuseExistingBoundCRS = type == PJ_TYPE_GEOCENTRIC_CRS ||
    9027           8 :                                 type == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
    9028             :                                 type == PJ_TYPE_GEOGRAPHIC_3D_CRS;
    9029             :     }
    9030             : 
    9031          47 :     if (reuseExistingBoundCRS)
    9032             :     {
    9033           4 :         auto newBoundCRS = proj_crs_create_bound_crs(
    9034           4 :             d->getPROJContext(), horizCRS, d->m_pj_bound_crs_target,
    9035           4 :             d->m_pj_bound_crs_co);
    9036           4 :         proj_destroy(horizCRS);
    9037           4 :         d->undoDemoteFromBoundCRS();
    9038           4 :         d->setPjCRS(newBoundCRS);
    9039             :     }
    9040             :     else
    9041             :     {
    9042          43 :         d->undoDemoteFromBoundCRS();
    9043          43 :         d->setPjCRS(horizCRS);
    9044             :     }
    9045             : 
    9046          47 :     return OGRERR_NONE;
    9047             : }
    9048             : 
    9049             : /************************************************************************/
    9050             : /*                          OSRStripVertical()                          */
    9051             : /************************************************************************/
    9052             : /**
    9053             :  * \brief Convert a compound cs into a horizontal CS.
    9054             :  *
    9055             :  * This function is the same as the C++ method
    9056             :  * OGRSpatialReference::StripVertical().
    9057             :  */
    9058           1 : OGRErr OSRStripVertical(OGRSpatialReferenceH hSRS)
    9059             : 
    9060             : {
    9061           1 :     VALIDATE_POINTER1(hSRS, "OSRStripVertical", OGRERR_FAILURE);
    9062             : 
    9063           1 :     return OGRSpatialReference::FromHandle(hSRS)->StripVertical();
    9064             : }
    9065             : 
    9066             : /************************************************************************/
    9067             : /*                 StripTOWGS84IfKnownDatumAndAllowed()                 */
    9068             : /************************************************************************/
    9069             : 
    9070             : /**
    9071             :  * \brief Remove TOWGS84 information if the CRS has a known horizontal datum
    9072             :  *        and this is allowed by the user.
    9073             :  *
    9074             :  * The default behavior is to remove TOWGS84 information if the CRS has a
    9075             :  * known horizontal datum. This can be disabled by setting the
    9076             :  * OSR_STRIP_TOWGS84 configuration option to NO.
    9077             :  *
    9078             :  * @return true if TOWGS84 has been removed.
    9079             :  * @since OGR 3.1.0
    9080             :  */
    9081             : 
    9082        9577 : bool OGRSpatialReference::StripTOWGS84IfKnownDatumAndAllowed()
    9083             : {
    9084        9577 :     if (CPLTestBool(CPLGetConfigOption("OSR_STRIP_TOWGS84", "YES")))
    9085             :     {
    9086        9574 :         if (StripTOWGS84IfKnownDatum())
    9087             :         {
    9088          71 :             CPLDebug("OSR", "TOWGS84 information has been removed. "
    9089             :                             "It can be kept by setting the OSR_STRIP_TOWGS84 "
    9090             :                             "configuration option to NO");
    9091          71 :             return true;
    9092             :         }
    9093             :     }
    9094        9506 :     return false;
    9095             : }
    9096             : 
    9097             : /************************************************************************/
    9098             : /*                      StripTOWGS84IfKnownDatum()                      */
    9099             : /************************************************************************/
    9100             : 
    9101             : /**
    9102             :  * \brief Remove TOWGS84 information if the CRS has a known horizontal datum
    9103             :  *
    9104             :  * @return true if TOWGS84 has been removed.
    9105             :  * @since OGR 3.1.0
    9106             :  */
    9107             : 
    9108        9580 : bool OGRSpatialReference::StripTOWGS84IfKnownDatum()
    9109             : 
    9110             : {
    9111       19160 :     TAKE_OPTIONAL_LOCK();
    9112             : 
    9113        9580 :     d->refreshProjObj();
    9114        9580 :     if (!d->m_pj_crs || d->m_pjType != PJ_TYPE_BOUND_CRS)
    9115             :     {
    9116        9489 :         return false;
    9117             :     }
    9118          91 :     auto ctxt = d->getPROJContext();
    9119          91 :     auto baseCRS = proj_get_source_crs(ctxt, d->m_pj_crs);
    9120          91 :     if (proj_get_type(baseCRS) == PJ_TYPE_COMPOUND_CRS)
    9121             :     {
    9122           3 :         proj_destroy(baseCRS);
    9123           3 :         return false;
    9124             :     }
    9125             : 
    9126             :     // Known base CRS code ? Return base CRS
    9127          88 :     const char *pszCode = proj_get_id_code(baseCRS, 0);
    9128          88 :     if (pszCode)
    9129             :     {
    9130           2 :         d->setPjCRS(baseCRS);
    9131           2 :         return true;
    9132             :     }
    9133             : 
    9134          86 :     auto datum = proj_crs_get_datum(ctxt, baseCRS);
    9135             : #if PROJ_VERSION_MAJOR > 7 ||                                                  \
    9136             :     (PROJ_VERSION_MAJOR == 7 && PROJ_VERSION_MINOR >= 2)
    9137             :     if (datum == nullptr)
    9138             :     {
    9139             :         datum = proj_crs_get_datum_ensemble(ctxt, baseCRS);
    9140             :     }
    9141             : #endif
    9142          86 :     if (!datum)
    9143             :     {
    9144           0 :         proj_destroy(baseCRS);
    9145           0 :         return false;
    9146             :     }
    9147             : 
    9148             :     // Known datum code ? Return base CRS
    9149          86 :     pszCode = proj_get_id_code(datum, 0);
    9150          86 :     if (pszCode)
    9151             :     {
    9152           3 :         proj_destroy(datum);
    9153           3 :         d->setPjCRS(baseCRS);
    9154           3 :         return true;
    9155             :     }
    9156             : 
    9157          83 :     const char *name = proj_get_name(datum);
    9158          83 :     if (EQUAL(name, "unknown"))
    9159             :     {
    9160           1 :         proj_destroy(datum);
    9161           1 :         proj_destroy(baseCRS);
    9162           1 :         return false;
    9163             :     }
    9164          82 :     const PJ_TYPE type = PJ_TYPE_GEODETIC_REFERENCE_FRAME;
    9165             :     PJ_OBJ_LIST *list =
    9166          82 :         proj_create_from_name(ctxt, nullptr, name, &type, 1, false, 1, nullptr);
    9167             : 
    9168          82 :     bool knownDatumName = false;
    9169          82 :     if (list)
    9170             :     {
    9171          82 :         if (proj_list_get_count(list) == 1)
    9172             :         {
    9173          69 :             knownDatumName = true;
    9174             :         }
    9175          82 :         proj_list_destroy(list);
    9176             :     }
    9177             : 
    9178          82 :     proj_destroy(datum);
    9179          82 :     if (knownDatumName)
    9180             :     {
    9181          69 :         d->setPjCRS(baseCRS);
    9182          69 :         return true;
    9183             :     }
    9184          13 :     proj_destroy(baseCRS);
    9185          13 :     return false;
    9186             : }
    9187             : 
    9188             : /************************************************************************/
    9189             : /*                             IsCompound()                             */
    9190             : /************************************************************************/
    9191             : 
    9192             : /**
    9193             :  * \brief Check if coordinate system is compound.
    9194             :  *
    9195             :  * This method is the same as the C function OSRIsCompound().
    9196             :  *
    9197             :  * @return TRUE if this is rooted with a COMPD_CS node.
    9198             :  */
    9199             : 
    9200       43155 : int OGRSpatialReference::IsCompound() const
    9201             : 
    9202             : {
    9203       43155 :     TAKE_OPTIONAL_LOCK();
    9204             : 
    9205       43155 :     d->refreshProjObj();
    9206       43155 :     d->demoteFromBoundCRS();
    9207       43155 :     bool isCompound = d->m_pjType == PJ_TYPE_COMPOUND_CRS;
    9208       43155 :     d->undoDemoteFromBoundCRS();
    9209       86310 :     return isCompound;
    9210             : }
    9211             : 
    9212             : /************************************************************************/
    9213             : /*                           OSRIsCompound()                            */
    9214             : /************************************************************************/
    9215             : 
    9216             : /**
    9217             :  * \brief Check if the coordinate system is compound.
    9218             :  *
    9219             :  * This function is the same as OGRSpatialReference::IsCompound().
    9220             :  */
    9221           5 : int OSRIsCompound(OGRSpatialReferenceH hSRS)
    9222             : 
    9223             : {
    9224           5 :     VALIDATE_POINTER1(hSRS, "OSRIsCompound", 0);
    9225             : 
    9226           5 :     return ToPointer(hSRS)->IsCompound();
    9227             : }
    9228             : 
    9229             : /************************************************************************/
    9230             : /*                            IsProjected()                             */
    9231             : /************************************************************************/
    9232             : 
    9233             : /**
    9234             :  * \brief Check if projected coordinate system.
    9235             :  *
    9236             :  * This method is the same as the C function OSRIsProjected().
    9237             :  *
    9238             :  * @return TRUE if this contains a PROJCS node indicating a it is a
    9239             :  * projected coordinate system. Also if it is a CompoundCRS made of a
    9240             :  * ProjectedCRS
    9241             :  */
    9242             : 
    9243       46272 : int OGRSpatialReference::IsProjected() const
    9244             : 
    9245             : {
    9246       46272 :     TAKE_OPTIONAL_LOCK();
    9247             : 
    9248       46272 :     d->refreshProjObj();
    9249       46272 :     d->demoteFromBoundCRS();
    9250       46272 :     bool isProjected = d->m_pjType == PJ_TYPE_PROJECTED_CRS;
    9251       46272 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    9252             :     {
    9253             :         auto horizCRS =
    9254         152 :             proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, 0);
    9255         152 :         if (horizCRS)
    9256             :         {
    9257         152 :             auto horizCRSType = proj_get_type(horizCRS);
    9258         152 :             isProjected = horizCRSType == PJ_TYPE_PROJECTED_CRS;
    9259         152 :             if (horizCRSType == PJ_TYPE_BOUND_CRS)
    9260             :             {
    9261           6 :                 auto base = proj_get_source_crs(d->getPROJContext(), horizCRS);
    9262           6 :                 if (base)
    9263             :                 {
    9264           6 :                     isProjected = proj_get_type(base) == PJ_TYPE_PROJECTED_CRS;
    9265           6 :                     proj_destroy(base);
    9266             :                 }
    9267             :             }
    9268         152 :             proj_destroy(horizCRS);
    9269             :         }
    9270             :     }
    9271       46272 :     d->undoDemoteFromBoundCRS();
    9272       92544 :     return isProjected;
    9273             : }
    9274             : 
    9275             : /************************************************************************/
    9276             : /*                           OSRIsProjected()                           */
    9277             : /************************************************************************/
    9278             : /**
    9279             :  * \brief Check if projected coordinate system.
    9280             :  *
    9281             :  * This function is the same as OGRSpatialReference::IsProjected().
    9282             :  */
    9283         452 : int OSRIsProjected(OGRSpatialReferenceH hSRS)
    9284             : 
    9285             : {
    9286         452 :     VALIDATE_POINTER1(hSRS, "OSRIsProjected", 0);
    9287             : 
    9288         452 :     return ToPointer(hSRS)->IsProjected();
    9289             : }
    9290             : 
    9291             : /************************************************************************/
    9292             : /*                            IsGeocentric()                            */
    9293             : /************************************************************************/
    9294             : 
    9295             : /**
    9296             :  * \brief Check if geocentric coordinate system.
    9297             :  *
    9298             :  * This method is the same as the C function OSRIsGeocentric().
    9299             :  *
    9300             :  * @return TRUE if this contains a GEOCCS node indicating a it is a
    9301             :  * geocentric coordinate system.
    9302             :  *
    9303             :  */
    9304             : 
    9305       17993 : int OGRSpatialReference::IsGeocentric() const
    9306             : 
    9307             : {
    9308       17993 :     TAKE_OPTIONAL_LOCK();
    9309             : 
    9310       17993 :     d->refreshProjObj();
    9311       17993 :     d->demoteFromBoundCRS();
    9312       17993 :     bool isGeocentric = d->m_pjType == PJ_TYPE_GEOCENTRIC_CRS;
    9313       17993 :     d->undoDemoteFromBoundCRS();
    9314       35986 :     return isGeocentric;
    9315             : }
    9316             : 
    9317             : /************************************************************************/
    9318             : /*                          OSRIsGeocentric()                           */
    9319             : /************************************************************************/
    9320             : /**
    9321             :  * \brief Check if geocentric coordinate system.
    9322             :  *
    9323             :  * This function is the same as OGRSpatialReference::IsGeocentric().
    9324             :  *
    9325             :  */
    9326           2 : int OSRIsGeocentric(OGRSpatialReferenceH hSRS)
    9327             : 
    9328             : {
    9329           2 :     VALIDATE_POINTER1(hSRS, "OSRIsGeocentric", 0);
    9330             : 
    9331           2 :     return ToPointer(hSRS)->IsGeocentric();
    9332             : }
    9333             : 
    9334             : /************************************************************************/
    9335             : /*                              IsEmpty()                               */
    9336             : /************************************************************************/
    9337             : 
    9338             : /**
    9339             :  * \brief Return if the SRS is not set.
    9340             :  */
    9341             : 
    9342      121533 : bool OGRSpatialReference::IsEmpty() const
    9343             : {
    9344      121533 :     TAKE_OPTIONAL_LOCK();
    9345             : 
    9346      121533 :     d->refreshProjObj();
    9347      243066 :     return d->m_pj_crs == nullptr;
    9348             : }
    9349             : 
    9350             : /************************************************************************/
    9351             : /*                            IsGeographic()                            */
    9352             : /************************************************************************/
    9353             : 
    9354             : /**
    9355             :  * \brief Check if geographic coordinate system.
    9356             :  *
    9357             :  * This method is the same as the C function OSRIsGeographic().
    9358             :  *
    9359             :  * @return TRUE if this spatial reference is geographic ... that is the
    9360             :  * root is a GEOGCS node. Also if it is a CompoundCRS made of a
    9361             :  * GeographicCRS
    9362             :  */
    9363             : 
    9364       65136 : int OGRSpatialReference::IsGeographic() const
    9365             : 
    9366             : {
    9367       65136 :     TAKE_OPTIONAL_LOCK();
    9368             : 
    9369       65136 :     d->refreshProjObj();
    9370       65136 :     d->demoteFromBoundCRS();
    9371       92066 :     bool isGeog = d->m_pjType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
    9372       26930 :                   d->m_pjType == PJ_TYPE_GEOGRAPHIC_3D_CRS;
    9373       65136 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    9374             :     {
    9375             :         auto horizCRS =
    9376         329 :             proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, 0);
    9377         329 :         if (horizCRS)
    9378             :         {
    9379         329 :             auto horizCRSType = proj_get_type(horizCRS);
    9380         329 :             isGeog = horizCRSType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
    9381             :                      horizCRSType == PJ_TYPE_GEOGRAPHIC_3D_CRS;
    9382         329 :             if (horizCRSType == PJ_TYPE_BOUND_CRS)
    9383             :             {
    9384          13 :                 auto base = proj_get_source_crs(d->getPROJContext(), horizCRS);
    9385          13 :                 if (base)
    9386             :                 {
    9387          13 :                     horizCRSType = proj_get_type(base);
    9388          13 :                     isGeog = horizCRSType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
    9389             :                              horizCRSType == PJ_TYPE_GEOGRAPHIC_3D_CRS;
    9390          13 :                     proj_destroy(base);
    9391             :                 }
    9392             :             }
    9393         329 :             proj_destroy(horizCRS);
    9394             :         }
    9395             :     }
    9396       65136 :     d->undoDemoteFromBoundCRS();
    9397      130272 :     return isGeog;
    9398             : }
    9399             : 
    9400             : /************************************************************************/
    9401             : /*                          OSRIsGeographic()                           */
    9402             : /************************************************************************/
    9403             : /**
    9404             :  * \brief Check if geographic coordinate system.
    9405             :  *
    9406             :  * This function is the same as OGRSpatialReference::IsGeographic().
    9407             :  */
    9408         285 : int OSRIsGeographic(OGRSpatialReferenceH hSRS)
    9409             : 
    9410             : {
    9411         285 :     VALIDATE_POINTER1(hSRS, "OSRIsGeographic", 0);
    9412             : 
    9413         285 :     return ToPointer(hSRS)->IsGeographic();
    9414             : }
    9415             : 
    9416             : /************************************************************************/
    9417             : /*                        IsDerivedGeographic()                         */
    9418             : /************************************************************************/
    9419             : 
    9420             : /**
    9421             :  * \brief Check if the CRS is a derived geographic coordinate system.
    9422             :  * (for example a rotated long/lat grid)
    9423             :  *
    9424             :  * This method is the same as the C function OSRIsDerivedGeographic().
    9425             :  *
    9426             :  * @since GDAL 3.1.0 and PROJ 6.3.0
    9427             :  */
    9428             : 
    9429       15480 : int OGRSpatialReference::IsDerivedGeographic() const
    9430             : 
    9431             : {
    9432       15480 :     TAKE_OPTIONAL_LOCK();
    9433             : 
    9434       15480 :     d->refreshProjObj();
    9435       15480 :     d->demoteFromBoundCRS();
    9436       25523 :     const bool isGeog = d->m_pjType == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
    9437       10043 :                         d->m_pjType == PJ_TYPE_GEOGRAPHIC_3D_CRS;
    9438             :     const bool isDerivedGeographic =
    9439       15480 :         isGeog && proj_is_derived_crs(d->getPROJContext(), d->m_pj_crs);
    9440       15480 :     d->undoDemoteFromBoundCRS();
    9441       30960 :     return isDerivedGeographic ? TRUE : FALSE;
    9442             : }
    9443             : 
    9444             : /************************************************************************/
    9445             : /*                       OSRIsDerivedGeographic()                       */
    9446             : /************************************************************************/
    9447             : /**
    9448             :  * \brief Check if the CRS is a derived geographic coordinate system.
    9449             :  * (for example a rotated long/lat grid)
    9450             :  *
    9451             :  * This function is the same as OGRSpatialReference::IsDerivedGeographic().
    9452             :  */
    9453           1 : int OSRIsDerivedGeographic(OGRSpatialReferenceH hSRS)
    9454             : 
    9455             : {
    9456           1 :     VALIDATE_POINTER1(hSRS, "OSRIsDerivedGeographic", 0);
    9457             : 
    9458           1 :     return ToPointer(hSRS)->IsDerivedGeographic();
    9459             : }
    9460             : 
    9461             : /************************************************************************/
    9462             : /*                         IsDerivedProjected()                         */
    9463             : /************************************************************************/
    9464             : 
    9465             : /**
    9466             :  * \brief Check if the CRS is a derived projected coordinate system.
    9467             :  *
    9468             :  * This method is the same as the C function OSRIsDerivedGeographic().
    9469             :  *
    9470             :  * @since GDAL 3.9.0 (and may only return non-zero starting with PROJ 9.2.0)
    9471             :  */
    9472             : 
    9473           0 : int OGRSpatialReference::IsDerivedProjected() const
    9474             : 
    9475             : {
    9476             : #if PROJ_AT_LEAST_VERSION(9, 2, 0)
    9477             :     TAKE_OPTIONAL_LOCK();
    9478             :     d->refreshProjObj();
    9479             :     d->demoteFromBoundCRS();
    9480             :     const bool isDerivedProjected =
    9481             :         d->m_pjType == PJ_TYPE_DERIVED_PROJECTED_CRS;
    9482             :     d->undoDemoteFromBoundCRS();
    9483             :     return isDerivedProjected ? TRUE : FALSE;
    9484             : #else
    9485           0 :     return FALSE;
    9486             : #endif
    9487             : }
    9488             : 
    9489             : /************************************************************************/
    9490             : /*                       OSRIsDerivedProjected()                        */
    9491             : /************************************************************************/
    9492             : /**
    9493             :  * \brief Check if the CRS is a derived projected coordinate system.
    9494             :  *
    9495             :  * This function is the same as OGRSpatialReference::IsDerivedProjected().
    9496             :  *
    9497             :  * @since GDAL 3.9.0 (and may only return non-zero starting with PROJ 9.2.0)
    9498             :  */
    9499           0 : int OSRIsDerivedProjected(OGRSpatialReferenceH hSRS)
    9500             : 
    9501             : {
    9502           0 :     VALIDATE_POINTER1(hSRS, "OSRIsDerivedProjected", 0);
    9503             : 
    9504           0 :     return ToPointer(hSRS)->IsDerivedProjected();
    9505             : }
    9506             : 
    9507             : /************************************************************************/
    9508             : /*                              IsLocal()                               */
    9509             : /************************************************************************/
    9510             : 
    9511             : /**
    9512             :  * \brief Check if local coordinate system.
    9513             :  *
    9514             :  * This method is the same as the C function OSRIsLocal().
    9515             :  *
    9516             :  * @return TRUE if this spatial reference is local ... that is the
    9517             :  * root is a LOCAL_CS node.
    9518             :  */
    9519             : 
    9520        8332 : int OGRSpatialReference::IsLocal() const
    9521             : 
    9522             : {
    9523        8332 :     TAKE_OPTIONAL_LOCK();
    9524        8332 :     d->refreshProjObj();
    9525       16664 :     return d->m_pjType == PJ_TYPE_ENGINEERING_CRS;
    9526             : }
    9527             : 
    9528             : /************************************************************************/
    9529             : /*                             OSRIsLocal()                             */
    9530             : /************************************************************************/
    9531             : /**
    9532             :  * \brief Check if local coordinate system.
    9533             :  *
    9534             :  * This function is the same as OGRSpatialReference::IsLocal().
    9535             :  */
    9536           8 : int OSRIsLocal(OGRSpatialReferenceH hSRS)
    9537             : 
    9538             : {
    9539           8 :     VALIDATE_POINTER1(hSRS, "OSRIsLocal", 0);
    9540             : 
    9541           8 :     return ToPointer(hSRS)->IsLocal();
    9542             : }
    9543             : 
    9544             : /************************************************************************/
    9545             : /*                             IsVertical()                             */
    9546             : /************************************************************************/
    9547             : 
    9548             : /**
    9549             :  * \brief Check if vertical coordinate system.
    9550             :  *
    9551             :  * This method is the same as the C function OSRIsVertical().
    9552             :  *
    9553             :  * @return TRUE if this contains a VERT_CS node indicating a it is a
    9554             :  * vertical coordinate system. Also if it is a CompoundCRS made of a
    9555             :  * VerticalCRS
    9556             :  *
    9557             :  */
    9558             : 
    9559        9374 : int OGRSpatialReference::IsVertical() const
    9560             : 
    9561             : {
    9562        9374 :     TAKE_OPTIONAL_LOCK();
    9563        9374 :     d->refreshProjObj();
    9564        9374 :     d->demoteFromBoundCRS();
    9565        9374 :     bool isVertical = d->m_pjType == PJ_TYPE_VERTICAL_CRS;
    9566        9374 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    9567             :     {
    9568             :         auto vertCRS =
    9569          34 :             proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, 1);
    9570          34 :         if (vertCRS)
    9571             :         {
    9572          34 :             const auto vertCRSType = proj_get_type(vertCRS);
    9573          34 :             isVertical = vertCRSType == PJ_TYPE_VERTICAL_CRS;
    9574          34 :             if (vertCRSType == PJ_TYPE_BOUND_CRS)
    9575             :             {
    9576           0 :                 auto base = proj_get_source_crs(d->getPROJContext(), vertCRS);
    9577           0 :                 if (base)
    9578             :                 {
    9579           0 :                     isVertical = proj_get_type(base) == PJ_TYPE_VERTICAL_CRS;
    9580           0 :                     proj_destroy(base);
    9581             :                 }
    9582             :             }
    9583          34 :             proj_destroy(vertCRS);
    9584             :         }
    9585             :     }
    9586        9374 :     d->undoDemoteFromBoundCRS();
    9587       18748 :     return isVertical;
    9588             : }
    9589             : 
    9590             : /************************************************************************/
    9591             : /*                           OSRIsVertical()                            */
    9592             : /************************************************************************/
    9593             : /**
    9594             :  * \brief Check if vertical coordinate system.
    9595             :  *
    9596             :  * This function is the same as OGRSpatialReference::IsVertical().
    9597             :  *
    9598             :  */
    9599           0 : int OSRIsVertical(OGRSpatialReferenceH hSRS)
    9600             : 
    9601             : {
    9602           0 :     VALIDATE_POINTER1(hSRS, "OSRIsVertical", 0);
    9603             : 
    9604           0 :     return ToPointer(hSRS)->IsVertical();
    9605             : }
    9606             : 
    9607             : /************************************************************************/
    9608             : /*                             IsDynamic()                              */
    9609             : /************************************************************************/
    9610             : 
    9611             : /**
    9612             :  * \brief Check if a CRS is a dynamic CRS.
    9613             :  *
    9614             :  * A dynamic CRS relies on a dynamic datum, that is a datum that is not
    9615             :  * plate-fixed.
    9616             :  *
    9617             :  * This method is the same as the C function OSRIsDynamic().
    9618             :  *
    9619             :  * @return true if the CRS is dynamic
    9620             :  *
    9621             :  * @since OGR 3.4.0
    9622             :  *
    9623             :  * @see HasPointMotionOperation()
    9624             :  */
    9625             : 
    9626       17207 : bool OGRSpatialReference::IsDynamic() const
    9627             : 
    9628             : {
    9629       17207 :     TAKE_OPTIONAL_LOCK();
    9630       17207 :     bool isDynamic = false;
    9631       17207 :     d->refreshProjObj();
    9632       17207 :     d->demoteFromBoundCRS();
    9633       17207 :     auto ctxt = d->getPROJContext();
    9634       17207 :     PJ *horiz = nullptr;
    9635       17207 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
    9636             :     {
    9637          99 :         horiz = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 0);
    9638             :     }
    9639       17108 :     else if (d->m_pj_crs)
    9640             :     {
    9641       16914 :         horiz = proj_clone(ctxt, d->m_pj_crs);
    9642             :     }
    9643       17207 :     if (horiz && proj_get_type(horiz) == PJ_TYPE_BOUND_CRS)
    9644             :     {
    9645           6 :         auto baseCRS = proj_get_source_crs(ctxt, horiz);
    9646           6 :         if (baseCRS)
    9647             :         {
    9648           6 :             proj_destroy(horiz);
    9649           6 :             horiz = baseCRS;
    9650             :         }
    9651             :     }
    9652       17207 :     auto datum = horiz ? proj_crs_get_datum(ctxt, horiz) : nullptr;
    9653       17207 :     if (datum)
    9654             :     {
    9655       16978 :         const auto type = proj_get_type(datum);
    9656       16978 :         isDynamic = type == PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME ||
    9657             :                     type == PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME;
    9658       16978 :         if (!isDynamic)
    9659             :         {
    9660       16978 :             const char *auth_name = proj_get_id_auth_name(datum, 0);
    9661       16978 :             const char *code = proj_get_id_code(datum, 0);
    9662       16978 :             if (auth_name && code && EQUAL(auth_name, "EPSG") &&
    9663       16452 :                 EQUAL(code, "6326"))
    9664             :             {
    9665       10726 :                 isDynamic = true;
    9666             :             }
    9667             :         }
    9668       16978 :         proj_destroy(datum);
    9669             :     }
    9670             : #if PROJ_VERSION_MAJOR > 7 ||                                                  \
    9671             :     (PROJ_VERSION_MAJOR == 7 && PROJ_VERSION_MINOR >= 2)
    9672             :     else
    9673             :     {
    9674             :         auto ensemble =
    9675             :             horiz ? proj_crs_get_datum_ensemble(ctxt, horiz) : nullptr;
    9676             :         if (ensemble)
    9677             :         {
    9678             :             auto member = proj_datum_ensemble_get_member(ctxt, ensemble, 0);
    9679             :             if (member)
    9680             :             {
    9681             :                 const auto type = proj_get_type(member);
    9682             :                 isDynamic = type == PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME ||
    9683             :                             type == PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME;
    9684             :                 proj_destroy(member);
    9685             :             }
    9686             :             proj_destroy(ensemble);
    9687             :         }
    9688             :     }
    9689             : #endif
    9690       17207 :     proj_destroy(horiz);
    9691       17207 :     d->undoDemoteFromBoundCRS();
    9692       34414 :     return isDynamic;
    9693             : }
    9694             : 
    9695             : /************************************************************************/
    9696             : /*                            OSRIsDynamic()                            */
    9697             : /************************************************************************/
    9698             : /**
    9699             :  * \brief Check if a CRS is a dynamic CRS.
    9700             :  *
    9701             :  * A dynamic CRS relies on a dynamic datum, that is a datum that is not
    9702             :  * plate-fixed.
    9703             :  *
    9704             :  * This function is the same as OGRSpatialReference::IsDynamic().
    9705             :  *
    9706             :  * @since OGR 3.4.0
    9707             :  */
    9708           0 : int OSRIsDynamic(OGRSpatialReferenceH hSRS)
    9709             : 
    9710             : {
    9711           0 :     VALIDATE_POINTER1(hSRS, "OSRIsDynamic", 0);
    9712             : 
    9713           0 :     return ToPointer(hSRS)->IsDynamic();
    9714             : }
    9715             : 
    9716             : /************************************************************************/
    9717             : /*                      HasPointMotionOperation()                       */
    9718             : /************************************************************************/
    9719             : 
    9720             : /**
    9721             :  * \brief Check if a CRS has at least an associated point motion operation.
    9722             :  *
    9723             :  * Some CRS are not formally declared as dynamic, but may behave as such
    9724             :  * in practice due to the presence of point motion operation, to perform
    9725             :  * coordinate epoch changes within the CRS. Typically NAD83(CSRS)v7
    9726             :  *
    9727             :  * @return true if the CRS has at least an associated point motion operation.
    9728             :  *
    9729             :  * @since OGR 3.8.0 and PROJ 9.4.0
    9730             :  *
    9731             :  * @see IsDynamic()
    9732             :  */
    9733             : 
    9734           5 : bool OGRSpatialReference::HasPointMotionOperation() const
    9735             : 
    9736             : {
    9737             : #if PROJ_VERSION_MAJOR > 9 ||                                                  \
    9738             :     (PROJ_VERSION_MAJOR == 9 && PROJ_VERSION_MINOR >= 4)
    9739             :     TAKE_OPTIONAL_LOCK();
    9740             :     d->refreshProjObj();
    9741             :     d->demoteFromBoundCRS();
    9742             :     auto ctxt = d->getPROJContext();
    9743             :     auto res =
    9744             :         CPL_TO_BOOL(proj_crs_has_point_motion_operation(ctxt, d->m_pj_crs));
    9745             :     d->undoDemoteFromBoundCRS();
    9746             :     return res;
    9747             : #else
    9748           5 :     return false;
    9749             : #endif
    9750             : }
    9751             : 
    9752             : /************************************************************************/
    9753             : /*                     OSRHasPointMotionOperation()                     */
    9754             : /************************************************************************/
    9755             : 
    9756             : /**
    9757             :  * \brief Check if a CRS has at least an associated point motion operation.
    9758             :  *
    9759             :  * Some CRS are not formally declared as dynamic, but may behave as such
    9760             :  * in practice due to the presence of point motion operation, to perform
    9761             :  * coordinate epoch changes within the CRS. Typically NAD83(CSRS)v7
    9762             :  *
    9763             :  * This function is the same as OGRSpatialReference::HasPointMotionOperation().
    9764             :  *
    9765             :  * @since OGR 3.8.0 and PROJ 9.4.0
    9766             :  */
    9767           0 : int OSRHasPointMotionOperation(OGRSpatialReferenceH hSRS)
    9768             : 
    9769             : {
    9770           0 :     VALIDATE_POINTER1(hSRS, "OSRHasPointMotionOperation", 0);
    9771             : 
    9772           0 :     return ToPointer(hSRS)->HasPointMotionOperation();
    9773             : }
    9774             : 
    9775             : /************************************************************************/
    9776             : /*                            CloneGeogCS()                             */
    9777             : /************************************************************************/
    9778             : 
    9779             : /**
    9780             :  * \brief Make a duplicate of the GEOGCS node of this OGRSpatialReference
    9781             :  * object.
    9782             :  *
    9783             :  * @return a new SRS, which becomes the responsibility of the caller.
    9784             :  */
    9785        4700 : OGRSpatialReference *OGRSpatialReference::CloneGeogCS() const
    9786             : 
    9787             : {
    9788        9400 :     TAKE_OPTIONAL_LOCK();
    9789        4700 :     d->refreshProjObj();
    9790        4700 :     if (d->m_pj_crs)
    9791             :     {
    9792        4700 :         if (d->m_pjType == PJ_TYPE_ENGINEERING_CRS)
    9793           0 :             return nullptr;
    9794             : 
    9795             :         auto geodCRS =
    9796        4700 :             proj_crs_get_geodetic_crs(d->getPROJContext(), d->m_pj_crs);
    9797        4700 :         if (geodCRS)
    9798             :         {
    9799        4700 :             OGRSpatialReference *poNewSRS = new OGRSpatialReference();
    9800        4700 :             if (d->m_pjType == PJ_TYPE_BOUND_CRS)
    9801             :             {
    9802             :                 PJ *hub_crs =
    9803          13 :                     proj_get_target_crs(d->getPROJContext(), d->m_pj_crs);
    9804          13 :                 PJ *co = proj_crs_get_coordoperation(d->getPROJContext(),
    9805          13 :                                                      d->m_pj_crs);
    9806          13 :                 auto temp = proj_crs_create_bound_crs(d->getPROJContext(),
    9807             :                                                       geodCRS, hub_crs, co);
    9808          13 :                 proj_destroy(geodCRS);
    9809          13 :                 geodCRS = temp;
    9810          13 :                 proj_destroy(hub_crs);
    9811          13 :                 proj_destroy(co);
    9812             :             }
    9813             : 
    9814             :             /* --------------------------------------------------------------------
    9815             :              */
    9816             :             /*      We have to reconstruct the GEOGCS node for geocentric */
    9817             :             /*      coordinate systems. */
    9818             :             /* --------------------------------------------------------------------
    9819             :              */
    9820        4700 :             if (proj_get_type(geodCRS) == PJ_TYPE_GEOCENTRIC_CRS)
    9821             :             {
    9822           0 :                 auto datum = proj_crs_get_datum(d->getPROJContext(), geodCRS);
    9823             : #if PROJ_VERSION_MAJOR > 7 ||                                                  \
    9824             :     (PROJ_VERSION_MAJOR == 7 && PROJ_VERSION_MINOR >= 2)
    9825             :                 if (datum == nullptr)
    9826             :                 {
    9827             :                     datum = proj_crs_get_datum_ensemble(d->getPROJContext(),
    9828             :                                                         geodCRS);
    9829             :                 }
    9830             : #endif
    9831           0 :                 if (datum)
    9832             :                 {
    9833           0 :                     auto cs = proj_create_ellipsoidal_2D_cs(
    9834             :                         d->getPROJContext(), PJ_ELLPS2D_LATITUDE_LONGITUDE,
    9835             :                         nullptr, 0);
    9836           0 :                     auto temp = proj_create_geographic_crs_from_datum(
    9837             :                         d->getPROJContext(), "unnamed", datum, cs);
    9838           0 :                     proj_destroy(datum);
    9839           0 :                     proj_destroy(cs);
    9840           0 :                     proj_destroy(geodCRS);
    9841           0 :                     geodCRS = temp;
    9842             :                 }
    9843             :             }
    9844             : 
    9845        4700 :             poNewSRS->d->setPjCRS(geodCRS);
    9846        4700 :             if (d->m_axisMappingStrategy == OAMS_TRADITIONAL_GIS_ORDER)
    9847        3062 :                 poNewSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    9848        4700 :             return poNewSRS;
    9849             :         }
    9850             :     }
    9851           0 :     return nullptr;
    9852             : }
    9853             : 
    9854             : /************************************************************************/
    9855             : /*                           OSRCloneGeogCS()                           */
    9856             : /************************************************************************/
    9857             : /**
    9858             :  * \brief Make a duplicate of the GEOGCS node of this OGRSpatialReference
    9859             :  * object.
    9860             :  *
    9861             :  * This function is the same as OGRSpatialReference::CloneGeogCS().
    9862             :  */
    9863         129 : OGRSpatialReferenceH CPL_STDCALL OSRCloneGeogCS(OGRSpatialReferenceH hSource)
    9864             : 
    9865             : {
    9866         129 :     VALIDATE_POINTER1(hSource, "OSRCloneGeogCS", nullptr);
    9867             : 
    9868         129 :     return ToHandle(ToPointer(hSource)->CloneGeogCS());
    9869             : }
    9870             : 
    9871             : /************************************************************************/
    9872             : /*                            IsSameGeogCS()                            */
    9873             : /************************************************************************/
    9874             : 
    9875             : /**
    9876             :  * \brief Do the GeogCS'es match?
    9877             :  *
    9878             :  * This method is the same as the C function OSRIsSameGeogCS().
    9879             :  *
    9880             :  * @param poOther the SRS being compared against.
    9881             :  *
    9882             :  * @return TRUE if they are the same or FALSE otherwise.
    9883             :  */
    9884             : 
    9885        8776 : int OGRSpatialReference::IsSameGeogCS(const OGRSpatialReference *poOther) const
    9886             : 
    9887             : {
    9888        8776 :     return IsSameGeogCS(poOther, nullptr);
    9889             : }
    9890             : 
    9891             : /**
    9892             :  * \brief Do the GeogCS'es match?
    9893             :  *
    9894             :  * This method is the same as the C function OSRIsSameGeogCS().
    9895             :  *
    9896             :  * @param poOther the SRS being compared against.
    9897             :  * @param papszOptions options. ignored
    9898             :  *
    9899             :  * @return TRUE if they are the same or FALSE otherwise.
    9900             :  */
    9901             : 
    9902        8776 : int OGRSpatialReference::IsSameGeogCS(const OGRSpatialReference *poOther,
    9903             :                                       const char *const *papszOptions) const
    9904             : 
    9905             : {
    9906       17552 :     TAKE_OPTIONAL_LOCK();
    9907             : 
    9908        8776 :     CPL_IGNORE_RET_VAL(papszOptions);
    9909             : 
    9910        8776 :     d->refreshProjObj();
    9911        8776 :     poOther->d->refreshProjObj();
    9912        8776 :     if (!d->m_pj_crs || !poOther->d->m_pj_crs)
    9913           0 :         return FALSE;
    9914        8776 :     if (d->m_pjType == PJ_TYPE_ENGINEERING_CRS ||
    9915        8776 :         d->m_pjType == PJ_TYPE_VERTICAL_CRS ||
    9916       26328 :         poOther->d->m_pjType == PJ_TYPE_ENGINEERING_CRS ||
    9917        8776 :         poOther->d->m_pjType == PJ_TYPE_VERTICAL_CRS)
    9918             :     {
    9919           0 :         return FALSE;
    9920             :     }
    9921             : 
    9922        8776 :     auto geodCRS = proj_crs_get_geodetic_crs(d->getPROJContext(), d->m_pj_crs);
    9923             :     auto otherGeodCRS =
    9924        8776 :         proj_crs_get_geodetic_crs(d->getPROJContext(), poOther->d->m_pj_crs);
    9925        8776 :     if (!geodCRS || !otherGeodCRS)
    9926             :     {
    9927           0 :         proj_destroy(geodCRS);
    9928           0 :         proj_destroy(otherGeodCRS);
    9929           0 :         return FALSE;
    9930             :     }
    9931             : 
    9932        8776 :     int ret = proj_is_equivalent_to(
    9933             :         geodCRS, otherGeodCRS, PJ_COMP_EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS);
    9934             : 
    9935        8776 :     proj_destroy(geodCRS);
    9936        8776 :     proj_destroy(otherGeodCRS);
    9937        8776 :     return ret;
    9938             : }
    9939             : 
    9940             : /************************************************************************/
    9941             : /*                          OSRIsSameGeogCS()                           */
    9942             : /************************************************************************/
    9943             : 
    9944             : /**
    9945             :  * \brief Do the GeogCS'es match?
    9946             :  *
    9947             :  * This function is the same as OGRSpatialReference::IsSameGeogCS().
    9948             :  */
    9949           0 : int OSRIsSameGeogCS(OGRSpatialReferenceH hSRS1, OGRSpatialReferenceH hSRS2)
    9950             : 
    9951             : {
    9952           0 :     VALIDATE_POINTER1(hSRS1, "OSRIsSameGeogCS", 0);
    9953           0 :     VALIDATE_POINTER1(hSRS2, "OSRIsSameGeogCS", 0);
    9954             : 
    9955           0 :     return ToPointer(hSRS1)->IsSameGeogCS(ToPointer(hSRS2));
    9956             : }
    9957             : 
    9958             : /************************************************************************/
    9959             : /*                            IsSameVertCS()                            */
    9960             : /************************************************************************/
    9961             : 
    9962             : /**
    9963             :  * \brief Do the VertCS'es match?
    9964             :  *
    9965             :  * This method is the same as the C function OSRIsSameVertCS().
    9966             :  *
    9967             :  * @param poOther the SRS being compared against.
    9968             :  *
    9969             :  * @return TRUE if they are the same or FALSE otherwise.
    9970             :  */
    9971             : 
    9972           0 : int OGRSpatialReference::IsSameVertCS(const OGRSpatialReference *poOther) const
    9973             : 
    9974             : {
    9975           0 :     TAKE_OPTIONAL_LOCK();
    9976             : 
    9977             :     /* -------------------------------------------------------------------- */
    9978             :     /*      Does the datum name match?                                      */
    9979             :     /* -------------------------------------------------------------------- */
    9980           0 :     const char *pszThisValue = this->GetAttrValue("VERT_DATUM");
    9981           0 :     const char *pszOtherValue = poOther->GetAttrValue("VERT_DATUM");
    9982             : 
    9983           0 :     if (pszThisValue == nullptr || pszOtherValue == nullptr ||
    9984           0 :         !EQUAL(pszThisValue, pszOtherValue))
    9985           0 :         return FALSE;
    9986             : 
    9987             :     /* -------------------------------------------------------------------- */
    9988             :     /*      Do the units match?                                             */
    9989             :     /* -------------------------------------------------------------------- */
    9990           0 :     pszThisValue = this->GetAttrValue("VERT_CS|UNIT", 1);
    9991           0 :     if (pszThisValue == nullptr)
    9992           0 :         pszThisValue = "1.0";
    9993             : 
    9994           0 :     pszOtherValue = poOther->GetAttrValue("VERT_CS|UNIT", 1);
    9995           0 :     if (pszOtherValue == nullptr)
    9996           0 :         pszOtherValue = "1.0";
    9997             : 
    9998           0 :     if (std::abs(CPLAtof(pszOtherValue) - CPLAtof(pszThisValue)) > 0.00000001)
    9999           0 :         return FALSE;
   10000             : 
   10001           0 :     return TRUE;
   10002             : }
   10003             : 
   10004             : /************************************************************************/
   10005             : /*                          OSRIsSameVertCS()                           */
   10006             : /************************************************************************/
   10007             : 
   10008             : /**
   10009             :  * \brief Do the VertCS'es match?
   10010             :  *
   10011             :  * This function is the same as OGRSpatialReference::IsSameVertCS().
   10012             :  */
   10013           0 : int OSRIsSameVertCS(OGRSpatialReferenceH hSRS1, OGRSpatialReferenceH hSRS2)
   10014             : 
   10015             : {
   10016           0 :     VALIDATE_POINTER1(hSRS1, "OSRIsSameVertCS", 0);
   10017           0 :     VALIDATE_POINTER1(hSRS2, "OSRIsSameVertCS", 0);
   10018             : 
   10019           0 :     return ToPointer(hSRS1)->IsSameVertCS(ToPointer(hSRS2));
   10020             : }
   10021             : 
   10022             : /************************************************************************/
   10023             : /*                               IsSame()                               */
   10024             : /************************************************************************/
   10025             : 
   10026             : /**
   10027             :  * \brief Do these two spatial references describe the same system ?
   10028             :  *
   10029             :  * @param poOtherSRS the SRS being compared to.
   10030             :  *
   10031             :  * @return TRUE if equivalent or FALSE otherwise.
   10032             :  */
   10033             : 
   10034       24960 : int OGRSpatialReference::IsSame(const OGRSpatialReference *poOtherSRS) const
   10035             : 
   10036             : {
   10037       24960 :     return IsSame(poOtherSRS, nullptr);
   10038             : }
   10039             : 
   10040             : /**
   10041             :  * \brief Do these two spatial references describe the same system ?
   10042             :  *
   10043             :  * This also takes into account the data axis to CRS axis mapping by default
   10044             :  *
   10045             :  * @param poOtherSRS the SRS being compared to.
   10046             :  * @param papszOptions options. NULL or NULL terminated list of options.
   10047             :  * Currently supported options are:
   10048             :  * <ul>
   10049             :  * <li>IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES/NO. Defaults to NO</li>
   10050             :  * <li>CRITERION=STRICT/EQUIVALENT/EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS.
   10051             :  *     Defaults to EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS.</li>
   10052             :  * <li>IGNORE_COORDINATE_EPOCH=YES/NO. Defaults to NO</li>
   10053             :  * </ul>
   10054             :  *
   10055             :  * @return TRUE if equivalent or FALSE otherwise.
   10056             :  */
   10057             : 
   10058       39032 : int OGRSpatialReference::IsSame(const OGRSpatialReference *poOtherSRS,
   10059             :                                 const char *const *papszOptions) const
   10060             : 
   10061             : {
   10062       78064 :     TAKE_OPTIONAL_LOCK();
   10063             : 
   10064       39032 :     d->refreshProjObj();
   10065       39032 :     poOtherSRS->d->refreshProjObj();
   10066       39032 :     if (!d->m_pj_crs || !poOtherSRS->d->m_pj_crs)
   10067          50 :         return d->m_pj_crs == poOtherSRS->d->m_pj_crs;
   10068       38982 :     if (!CPLTestBool(CSLFetchNameValueDef(
   10069             :             papszOptions, "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING", "NO")))
   10070             :     {
   10071       38218 :         if (d->m_axisMapping != poOtherSRS->d->m_axisMapping)
   10072        3753 :             return false;
   10073             :     }
   10074             : 
   10075       35229 :     if (!CPLTestBool(CSLFetchNameValueDef(papszOptions,
   10076             :                                           "IGNORE_COORDINATE_EPOCH", "NO")))
   10077             :     {
   10078       34735 :         if (d->m_coordinateEpoch != poOtherSRS->d->m_coordinateEpoch)
   10079          27 :             return false;
   10080             :     }
   10081             : 
   10082       35202 :     bool reboundSelf = false;
   10083       35202 :     bool reboundOther = false;
   10084       35254 :     if (d->m_pjType == PJ_TYPE_BOUND_CRS &&
   10085          52 :         poOtherSRS->d->m_pjType != PJ_TYPE_BOUND_CRS)
   10086             :     {
   10087          14 :         d->demoteFromBoundCRS();
   10088          14 :         reboundSelf = true;
   10089             :     }
   10090       70338 :     else if (d->m_pjType != PJ_TYPE_BOUND_CRS &&
   10091       35150 :              poOtherSRS->d->m_pjType == PJ_TYPE_BOUND_CRS)
   10092             :     {
   10093          28 :         poOtherSRS->d->demoteFromBoundCRS();
   10094          28 :         reboundOther = true;
   10095             :     }
   10096             : 
   10097       35202 :     PJ_COMPARISON_CRITERION criterion =
   10098             :         PJ_COMP_EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS;
   10099       35202 :     const char *pszCriterion = CSLFetchNameValueDef(
   10100             :         papszOptions, "CRITERION", "EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS");
   10101       35202 :     if (EQUAL(pszCriterion, "STRICT"))
   10102           0 :         criterion = PJ_COMP_STRICT;
   10103       35202 :     else if (EQUAL(pszCriterion, "EQUIVALENT"))
   10104       10493 :         criterion = PJ_COMP_EQUIVALENT;
   10105       24709 :     else if (!EQUAL(pszCriterion, "EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS"))
   10106             :     {
   10107           0 :         CPLError(CE_Warning, CPLE_NotSupported,
   10108             :                  "Unsupported value for CRITERION: %s", pszCriterion);
   10109             :     }
   10110             :     int ret =
   10111       35202 :         proj_is_equivalent_to(d->m_pj_crs, poOtherSRS->d->m_pj_crs, criterion);
   10112       35202 :     if (reboundSelf)
   10113          14 :         d->undoDemoteFromBoundCRS();
   10114       35202 :     if (reboundOther)
   10115          28 :         poOtherSRS->d->undoDemoteFromBoundCRS();
   10116             : 
   10117       35202 :     return ret;
   10118             : }
   10119             : 
   10120             : /************************************************************************/
   10121             : /*                             OSRIsSame()                              */
   10122             : /************************************************************************/
   10123             : 
   10124             : /**
   10125             :  * \brief Do these two spatial references describe the same system ?
   10126             :  *
   10127             :  * This function is the same as OGRSpatialReference::IsSame().
   10128             :  */
   10129          41 : int OSRIsSame(OGRSpatialReferenceH hSRS1, OGRSpatialReferenceH hSRS2)
   10130             : 
   10131             : {
   10132          41 :     VALIDATE_POINTER1(hSRS1, "OSRIsSame", 0);
   10133          41 :     VALIDATE_POINTER1(hSRS2, "OSRIsSame", 0);
   10134             : 
   10135          41 :     return ToPointer(hSRS1)->IsSame(ToPointer(hSRS2));
   10136             : }
   10137             : 
   10138             : /************************************************************************/
   10139             : /*                            OSRIsSameEx()                             */
   10140             : /************************************************************************/
   10141             : 
   10142             : /**
   10143             :  * \brief Do these two spatial references describe the same system ?
   10144             :  *
   10145             :  * This function is the same as OGRSpatialReference::IsSame().
   10146             :  */
   10147         680 : int OSRIsSameEx(OGRSpatialReferenceH hSRS1, OGRSpatialReferenceH hSRS2,
   10148             :                 const char *const *papszOptions)
   10149             : {
   10150         680 :     VALIDATE_POINTER1(hSRS1, "OSRIsSame", 0);
   10151         680 :     VALIDATE_POINTER1(hSRS2, "OSRIsSame", 0);
   10152             : 
   10153         680 :     return ToPointer(hSRS1)->IsSame(ToPointer(hSRS2), papszOptions);
   10154             : }
   10155             : 
   10156             : /************************************************************************/
   10157             : /*                      convertToOtherProjection()                      */
   10158             : /************************************************************************/
   10159             : 
   10160             : /**
   10161             :  * \brief Convert to another equivalent projection
   10162             :  *
   10163             :  * Currently implemented:
   10164             :  * <ul>
   10165             :  * <li>SRS_PT_MERCATOR_1SP to SRS_PT_MERCATOR_2SP</li>
   10166             :  * <li>SRS_PT_MERCATOR_2SP to SRS_PT_MERCATOR_1SP</li>
   10167             :  * <li>SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP to
   10168             :  * SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP</li>
   10169             :  * <li>SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP to
   10170             :  * SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP</li>
   10171             :  * </ul>
   10172             :  *
   10173             :  * @param pszTargetProjection target projection.
   10174             :  * @param papszOptions lists of options. None supported currently.
   10175             :  * @return a new SRS, or NULL in case of error.
   10176             :  *
   10177             :  */
   10178          91 : OGRSpatialReference *OGRSpatialReference::convertToOtherProjection(
   10179             :     const char *pszTargetProjection,
   10180             :     CPL_UNUSED const char *const *papszOptions) const
   10181             : {
   10182         182 :     TAKE_OPTIONAL_LOCK();
   10183             : 
   10184          91 :     if (pszTargetProjection == nullptr)
   10185           1 :         return nullptr;
   10186             :     int new_code;
   10187          90 :     if (EQUAL(pszTargetProjection, SRS_PT_MERCATOR_1SP))
   10188             :     {
   10189           6 :         new_code = EPSG_CODE_METHOD_MERCATOR_VARIANT_A;
   10190             :     }
   10191          84 :     else if (EQUAL(pszTargetProjection, SRS_PT_MERCATOR_2SP))
   10192             :     {
   10193           7 :         new_code = EPSG_CODE_METHOD_MERCATOR_VARIANT_B;
   10194             :     }
   10195          77 :     else if (EQUAL(pszTargetProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP))
   10196             :     {
   10197          65 :         new_code = EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP;
   10198             :     }
   10199          12 :     else if (EQUAL(pszTargetProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP))
   10200             :     {
   10201          11 :         new_code = EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP;
   10202             :     }
   10203             :     else
   10204             :     {
   10205           1 :         return nullptr;
   10206             :     }
   10207             : 
   10208          89 :     d->refreshProjObj();
   10209          89 :     d->demoteFromBoundCRS();
   10210          89 :     OGRSpatialReference *poNewSRS = nullptr;
   10211          89 :     if (d->m_pjType == PJ_TYPE_PROJECTED_CRS)
   10212             :     {
   10213             :         auto conv =
   10214          88 :             proj_crs_get_coordoperation(d->getPROJContext(), d->m_pj_crs);
   10215          88 :         auto new_conv = proj_convert_conversion_to_other_method(
   10216             :             d->getPROJContext(), conv, new_code, nullptr);
   10217          88 :         proj_destroy(conv);
   10218          88 :         if (new_conv)
   10219             :         {
   10220             :             auto geodCRS =
   10221          74 :                 proj_crs_get_geodetic_crs(d->getPROJContext(), d->m_pj_crs);
   10222          74 :             auto cs = proj_crs_get_coordinate_system(d->getPROJContext(),
   10223          74 :                                                      d->m_pj_crs);
   10224          74 :             if (geodCRS && cs)
   10225             :             {
   10226          74 :                 auto new_proj_crs = proj_create_projected_crs(
   10227          74 :                     d->getPROJContext(), proj_get_name(d->m_pj_crs), geodCRS,
   10228             :                     new_conv, cs);
   10229          74 :                 proj_destroy(new_conv);
   10230          74 :                 if (new_proj_crs)
   10231             :                 {
   10232          74 :                     poNewSRS = new OGRSpatialReference();
   10233             : 
   10234          74 :                     if (d->m_pj_bound_crs_target && d->m_pj_bound_crs_co)
   10235             :                     {
   10236           9 :                         auto boundCRS = proj_crs_create_bound_crs(
   10237             :                             d->getPROJContext(), new_proj_crs,
   10238           9 :                             d->m_pj_bound_crs_target, d->m_pj_bound_crs_co);
   10239           9 :                         if (boundCRS)
   10240             :                         {
   10241           9 :                             proj_destroy(new_proj_crs);
   10242           9 :                             new_proj_crs = boundCRS;
   10243             :                         }
   10244             :                     }
   10245             : 
   10246          74 :                     poNewSRS->d->setPjCRS(new_proj_crs);
   10247             :                 }
   10248             :             }
   10249          74 :             proj_destroy(geodCRS);
   10250          74 :             proj_destroy(cs);
   10251             :         }
   10252             :     }
   10253          89 :     d->undoDemoteFromBoundCRS();
   10254          89 :     return poNewSRS;
   10255             : }
   10256             : 
   10257             : /************************************************************************/
   10258             : /*                    OSRConvertToOtherProjection()                     */
   10259             : /************************************************************************/
   10260             : 
   10261             : /**
   10262             :  * \brief Convert to another equivalent projection
   10263             :  *
   10264             :  * Currently implemented:
   10265             :  * <ul>
   10266             :  * <li>SRS_PT_MERCATOR_1SP to SRS_PT_MERCATOR_2SP</li>
   10267             :  * <li>SRS_PT_MERCATOR_2SP to SRS_PT_MERCATOR_1SP</li>
   10268             :  * <li>SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP to
   10269             :  * SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP</li>
   10270             :  * <li>SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP to
   10271             :  * SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP</li>
   10272             :  * </ul>
   10273             :  *
   10274             :  * @param hSRS source SRS
   10275             :  * @param pszTargetProjection target projection.
   10276             :  * @param papszOptions lists of options. None supported currently.
   10277             :  * @return a new SRS, or NULL in case of error.
   10278             :  *
   10279             :  */
   10280             : OGRSpatialReferenceH
   10281          28 : OSRConvertToOtherProjection(OGRSpatialReferenceH hSRS,
   10282             :                             const char *pszTargetProjection,
   10283             :                             const char *const *papszOptions)
   10284             : {
   10285          28 :     VALIDATE_POINTER1(hSRS, "OSRConvertToOtherProjection", nullptr);
   10286          28 :     return ToHandle(ToPointer(hSRS)->convertToOtherProjection(
   10287          28 :         pszTargetProjection, papszOptions));
   10288             : }
   10289             : 
   10290             : /************************************************************************/
   10291             : /*                           OSRFindMatches()                           */
   10292             : /************************************************************************/
   10293             : 
   10294             : /**
   10295             :  * \brief Try to identify a match between the passed SRS and a related SRS
   10296             :  * in a catalog.
   10297             :  *
   10298             :  * Matching may be partial, or may fail.
   10299             :  * Returned entries will be sorted by decreasing match confidence (first
   10300             :  * entry has the highest match confidence).
   10301             :  *
   10302             :  * The exact way matching is done may change in future versions. Starting with
   10303             :  * GDAL 3.0, it relies on PROJ' proj_identify() function.
   10304             :  *
   10305             :  * This function is the same as OGRSpatialReference::FindMatches().
   10306             :  *
   10307             :  * @param hSRS SRS to match
   10308             :  * @param papszOptions NULL terminated list of options or NULL
   10309             :  * @param pnEntries Output parameter. Number of values in the returned array.
   10310             :  * @param ppanMatchConfidence Output parameter (or NULL). *ppanMatchConfidence
   10311             :  * will be allocated to an array of *pnEntries whose values between 0 and 100
   10312             :  * indicate the confidence in the match. 100 is the highest confidence level.
   10313             :  * The array must be freed with CPLFree().
   10314             :  *
   10315             :  * @return an array of SRS that match the passed SRS, or NULL. Must be freed
   10316             :  * with OSRFreeSRSArray()
   10317             :  *
   10318             :  */
   10319           9 : OGRSpatialReferenceH *OSRFindMatches(OGRSpatialReferenceH hSRS,
   10320             :                                      CSLConstList papszOptions, int *pnEntries,
   10321             :                                      int **ppanMatchConfidence)
   10322             : {
   10323           9 :     if (pnEntries)
   10324           9 :         *pnEntries = 0;
   10325           9 :     if (ppanMatchConfidence)
   10326           9 :         *ppanMatchConfidence = nullptr;
   10327           9 :     VALIDATE_POINTER1(hSRS, "OSRFindMatches", nullptr);
   10328             : 
   10329           9 :     OGRSpatialReference *poSRS = ToPointer(hSRS);
   10330           9 :     return poSRS->FindMatches(papszOptions, pnEntries, ppanMatchConfidence);
   10331             : }
   10332             : 
   10333             : /************************************************************************/
   10334             : /*                          OSRFreeSRSArray()                           */
   10335             : /************************************************************************/
   10336             : 
   10337             : /**
   10338             :  * \brief Free return of OSRIdentifyMatches()
   10339             :  *
   10340             :  * @param pahSRS array of SRS (must be NULL terminated)
   10341             :  */
   10342         193 : void OSRFreeSRSArray(OGRSpatialReferenceH *pahSRS)
   10343             : {
   10344         193 :     if (pahSRS != nullptr)
   10345             :     {
   10346        1734 :         for (int i = 0; pahSRS[i] != nullptr; ++i)
   10347             :         {
   10348        1559 :             OSRRelease(pahSRS[i]);
   10349             :         }
   10350         175 :         CPLFree(pahSRS);
   10351             :     }
   10352         193 : }
   10353             : 
   10354             : /************************************************************************/
   10355             : /*                           FindBestMatch()                            */
   10356             : /************************************************************************/
   10357             : 
   10358             : /**
   10359             :  * \brief Try to identify the best match between the passed SRS and a related
   10360             :  * SRS in a catalog.
   10361             :  *
   10362             :  * This is a wrapper over OGRSpatialReference::FindMatches() that takes care
   10363             :  * of filtering its output.
   10364             :  * Only matches whose confidence is greater or equal to nMinimumMatchConfidence
   10365             :  * will be considered. If there is a single match, it is returned.
   10366             :  * If there are several matches, only return the one under the
   10367             :  * pszPreferredAuthority, if there is a single one under that authority.
   10368             :  *
   10369             :  * @param nMinimumMatchConfidence Minimum match confidence (value between 0 and
   10370             :  * 100). If set to 0, 90 is used.
   10371             :  * @param pszPreferredAuthority Preferred CRS authority. If set to nullptr,
   10372             :  * "EPSG" is used.
   10373             :  * @param papszOptions NULL terminated list of options or NULL. No option is
   10374             :  * defined at time of writing.
   10375             :  *
   10376             :  * @return a new OGRSpatialReference* object to free with Release(), or nullptr
   10377             :  *
   10378             :  * @since GDAL 3.6
   10379             :  * @see OGRSpatialReference::FindMatches()
   10380             :  */
   10381             : OGRSpatialReference *
   10382        1585 : OGRSpatialReference::FindBestMatch(int nMinimumMatchConfidence,
   10383             :                                    const char *pszPreferredAuthority,
   10384             :                                    CSLConstList papszOptions) const
   10385             : {
   10386        3170 :     TAKE_OPTIONAL_LOCK();
   10387             : 
   10388        1585 :     CPL_IGNORE_RET_VAL(papszOptions);  // ignored for now.
   10389             : 
   10390        1585 :     if (nMinimumMatchConfidence == 0)
   10391           0 :         nMinimumMatchConfidence = 90;
   10392        1585 :     if (pszPreferredAuthority == nullptr)
   10393         194 :         pszPreferredAuthority = "EPSG";
   10394             : 
   10395             :     // Try to identify the CRS with the database
   10396        1585 :     int nEntries = 0;
   10397        1585 :     int *panConfidence = nullptr;
   10398             :     OGRSpatialReferenceH *pahSRS =
   10399        1585 :         FindMatches(nullptr, &nEntries, &panConfidence);
   10400        1585 :     if (nEntries == 1 && panConfidence[0] >= nMinimumMatchConfidence)
   10401             :     {
   10402        2852 :         std::vector<double> adfTOWGS84(7);
   10403        1426 :         if (GetTOWGS84(&adfTOWGS84[0], 7) != OGRERR_NONE)
   10404             :         {
   10405        1425 :             adfTOWGS84.clear();
   10406             :         }
   10407             : 
   10408        1426 :         auto poSRS = OGRSpatialReference::FromHandle(pahSRS[0]);
   10409             : 
   10410             :         auto poBaseGeogCRS =
   10411        1426 :             std::unique_ptr<OGRSpatialReference>(poSRS->CloneGeogCS());
   10412        1426 :         if (poBaseGeogCRS)
   10413             :         {
   10414             :             // If the base geographic SRS of the SRS is EPSG:4326
   10415             :             // with TOWGS84[0,0,0,0,0,0], then just use the official
   10416             :             // SRS code
   10417             :             // Same with EPSG:4258 (ETRS89), since it's the only known
   10418             :             // TOWGS84[] style transformation to WGS 84, and given the
   10419             :             // "fuzzy" nature of both ETRS89 and WGS 84, there's little
   10420             :             // chance that a non-NULL TOWGS84[] will emerge.
   10421        1426 :             const char *pszAuthorityName = nullptr;
   10422        1426 :             const char *pszAuthorityCode = nullptr;
   10423        1426 :             const char *pszBaseAuthorityName = nullptr;
   10424        1426 :             const char *pszBaseAuthorityCode = nullptr;
   10425        1426 :             const char *pszBaseName = poBaseGeogCRS->GetName();
   10426        2852 :             if (adfTOWGS84 == std::vector<double>(7) &&
   10427           1 :                 (pszAuthorityName = poSRS->GetAuthorityName()) != nullptr &&
   10428           1 :                 EQUAL(pszAuthorityName, "EPSG") &&
   10429           1 :                 (pszAuthorityCode = poSRS->GetAuthorityCode()) != nullptr &&
   10430           1 :                 (pszBaseAuthorityName = poBaseGeogCRS->GetAuthorityName()) !=
   10431           1 :                     nullptr &&
   10432           1 :                 EQUAL(pszBaseAuthorityName, "EPSG") &&
   10433           1 :                 (pszBaseAuthorityCode = poBaseGeogCRS->GetAuthorityCode()) !=
   10434        2853 :                     nullptr &&
   10435           1 :                 (EQUAL(pszBaseAuthorityCode, "4326") ||
   10436           1 :                  EQUAL(pszBaseAuthorityCode, "4258") ||
   10437             :                  // For ETRS89-XXX [...] new CRS added in EPSG 12.033+
   10438           0 :                  (pszBaseName && STARTS_WITH(pszBaseName, "ETRS89"))))
   10439             :             {
   10440           1 :                 poSRS->importFromEPSG(atoi(pszAuthorityCode));
   10441             :             }
   10442             :         }
   10443             : 
   10444        1426 :         CPLFree(pahSRS);
   10445        1426 :         CPLFree(panConfidence);
   10446             : 
   10447        1426 :         return poSRS;
   10448             :     }
   10449             :     else
   10450             :     {
   10451             :         // If there are several matches >= nMinimumMatchConfidence, take the
   10452             :         // only one that is under pszPreferredAuthority
   10453         159 :         int iBestEntry = -1;
   10454        1667 :         for (int i = 0; i < nEntries; i++)
   10455             :         {
   10456        1508 :             if (panConfidence[i] >= nMinimumMatchConfidence)
   10457             :             {
   10458             :                 const char *pszAuthName =
   10459           3 :                     OGRSpatialReference::FromHandle(pahSRS[i])
   10460           3 :                         ->GetAuthorityName();
   10461           3 :                 if (pszAuthName != nullptr &&
   10462           3 :                     EQUAL(pszAuthName, pszPreferredAuthority))
   10463             :                 {
   10464           3 :                     if (iBestEntry < 0)
   10465           3 :                         iBestEntry = i;
   10466             :                     else
   10467             :                     {
   10468           0 :                         iBestEntry = -1;
   10469           0 :                         break;
   10470             :                     }
   10471             :                 }
   10472             :             }
   10473             :         }
   10474         159 :         if (iBestEntry >= 0)
   10475             :         {
   10476           3 :             auto poRet = OGRSpatialReference::FromHandle(pahSRS[0])->Clone();
   10477           3 :             OSRFreeSRSArray(pahSRS);
   10478           3 :             CPLFree(panConfidence);
   10479           3 :             return poRet;
   10480             :         }
   10481             :     }
   10482         156 :     OSRFreeSRSArray(pahSRS);
   10483         156 :     CPLFree(panConfidence);
   10484         156 :     return nullptr;
   10485             : }
   10486             : 
   10487             : /************************************************************************/
   10488             : /*                             SetTOWGS84()                             */
   10489             : /************************************************************************/
   10490             : 
   10491             : /**
   10492             :  * \brief Set the Bursa-Wolf conversion to WGS84.
   10493             :  *
   10494             :  * This will create the TOWGS84 node as a child of the DATUM.  It will fail
   10495             :  * if there is no existing DATUM node. It will replace
   10496             :  * an existing TOWGS84 node if there is one.
   10497             :  *
   10498             :  * The parameters have the same meaning as EPSG transformation 9606
   10499             :  * (Position Vector 7-param. transformation).
   10500             :  *
   10501             :  * This method is the same as the C function OSRSetTOWGS84().
   10502             :  *
   10503             :  * @param dfDX X child in meters.
   10504             :  * @param dfDY Y child in meters.
   10505             :  * @param dfDZ Z child in meters.
   10506             :  * @param dfEX X rotation in arc seconds (optional, defaults to zero).
   10507             :  * @param dfEY Y rotation in arc seconds (optional, defaults to zero).
   10508             :  * @param dfEZ Z rotation in arc seconds (optional, defaults to zero).
   10509             :  * @param dfPPM scaling factor (parts per million).
   10510             :  *
   10511             :  * @return OGRERR_NONE on success.
   10512             :  */
   10513             : 
   10514         102 : OGRErr OGRSpatialReference::SetTOWGS84(double dfDX, double dfDY, double dfDZ,
   10515             :                                        double dfEX, double dfEY, double dfEZ,
   10516             :                                        double dfPPM)
   10517             : 
   10518             : {
   10519         204 :     TAKE_OPTIONAL_LOCK();
   10520             : 
   10521         102 :     d->refreshProjObj();
   10522         102 :     if (d->m_pj_crs == nullptr)
   10523             :     {
   10524           0 :         return OGRERR_FAILURE;
   10525             :     }
   10526             : 
   10527             :     // Remove existing BoundCRS
   10528         102 :     if (d->m_pjType == PJ_TYPE_BOUND_CRS)
   10529             :     {
   10530           0 :         auto baseCRS = proj_get_source_crs(d->getPROJContext(), d->m_pj_crs);
   10531           0 :         if (!baseCRS)
   10532           0 :             return OGRERR_FAILURE;
   10533           0 :         d->setPjCRS(baseCRS);
   10534             :     }
   10535             : 
   10536             :     PJ_PARAM_DESCRIPTION params[7];
   10537             : 
   10538         102 :     params[0].name = EPSG_NAME_PARAMETER_X_AXIS_TRANSLATION;
   10539         102 :     params[0].auth_name = "EPSG";
   10540         102 :     params[0].code = XSTRINGIFY(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION);
   10541         102 :     params[0].value = dfDX;
   10542         102 :     params[0].unit_name = "metre";
   10543         102 :     params[0].unit_conv_factor = 1.0;
   10544         102 :     params[0].unit_type = PJ_UT_LINEAR;
   10545             : 
   10546         102 :     params[1].name = EPSG_NAME_PARAMETER_Y_AXIS_TRANSLATION;
   10547         102 :     params[1].auth_name = "EPSG";
   10548         102 :     params[1].code = XSTRINGIFY(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION);
   10549         102 :     params[1].value = dfDY;
   10550         102 :     params[1].unit_name = "metre";
   10551         102 :     params[1].unit_conv_factor = 1.0;
   10552         102 :     params[1].unit_type = PJ_UT_LINEAR;
   10553             : 
   10554         102 :     params[2].name = EPSG_NAME_PARAMETER_Z_AXIS_TRANSLATION;
   10555         102 :     params[2].auth_name = "EPSG";
   10556         102 :     params[2].code = XSTRINGIFY(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION);
   10557         102 :     params[2].value = dfDZ;
   10558         102 :     params[2].unit_name = "metre";
   10559         102 :     params[2].unit_conv_factor = 1.0;
   10560         102 :     params[2].unit_type = PJ_UT_LINEAR;
   10561             : 
   10562         102 :     params[3].name = EPSG_NAME_PARAMETER_X_AXIS_ROTATION;
   10563         102 :     params[3].auth_name = "EPSG";
   10564         102 :     params[3].code = XSTRINGIFY(EPSG_CODE_PARAMETER_X_AXIS_ROTATION);
   10565         102 :     params[3].value = dfEX;
   10566         102 :     params[3].unit_name = "arc-second";
   10567         102 :     params[3].unit_conv_factor = 1. / 3600 * M_PI / 180;
   10568         102 :     params[3].unit_type = PJ_UT_ANGULAR;
   10569             : 
   10570         102 :     params[4].name = EPSG_NAME_PARAMETER_Y_AXIS_ROTATION;
   10571         102 :     params[4].auth_name = "EPSG";
   10572         102 :     params[4].code = XSTRINGIFY(EPSG_CODE_PARAMETER_Y_AXIS_ROTATION);
   10573         102 :     params[4].value = dfEY;
   10574         102 :     params[4].unit_name = "arc-second";
   10575         102 :     params[4].unit_conv_factor = 1. / 3600 * M_PI / 180;
   10576         102 :     params[4].unit_type = PJ_UT_ANGULAR;
   10577             : 
   10578         102 :     params[5].name = EPSG_NAME_PARAMETER_Z_AXIS_ROTATION;
   10579         102 :     params[5].auth_name = "EPSG";
   10580         102 :     params[5].code = XSTRINGIFY(EPSG_CODE_PARAMETER_Z_AXIS_ROTATION);
   10581         102 :     params[5].value = dfEZ;
   10582         102 :     params[5].unit_name = "arc-second";
   10583         102 :     params[5].unit_conv_factor = 1. / 3600 * M_PI / 180;
   10584         102 :     params[5].unit_type = PJ_UT_ANGULAR;
   10585             : 
   10586         102 :     params[6].name = EPSG_NAME_PARAMETER_SCALE_DIFFERENCE;
   10587         102 :     params[6].auth_name = "EPSG";
   10588         102 :     params[6].code = XSTRINGIFY(EPSG_CODE_PARAMETER_SCALE_DIFFERENCE);
   10589         102 :     params[6].value = dfPPM;
   10590         102 :     params[6].unit_name = "parts per million";
   10591         102 :     params[6].unit_conv_factor = 1e-6;
   10592         102 :     params[6].unit_type = PJ_UT_SCALE;
   10593             : 
   10594             :     auto sourceCRS =
   10595         102 :         proj_crs_get_geodetic_crs(d->getPROJContext(), d->m_pj_crs);
   10596         102 :     if (!sourceCRS)
   10597             :     {
   10598           0 :         return OGRERR_FAILURE;
   10599             :     }
   10600             : 
   10601         102 :     const auto sourceType = proj_get_type(sourceCRS);
   10602             : 
   10603         102 :     auto targetCRS = proj_create_from_database(
   10604             :         d->getPROJContext(), "EPSG",
   10605             :         sourceType == PJ_TYPE_GEOGRAPHIC_2D_CRS   ? "4326"
   10606             :         : sourceType == PJ_TYPE_GEOGRAPHIC_3D_CRS ? "4979"
   10607             :                                                   : "4978",
   10608             :         PJ_CATEGORY_CRS, false, nullptr);
   10609         102 :     if (!targetCRS)
   10610             :     {
   10611           0 :         proj_destroy(sourceCRS);
   10612           0 :         return OGRERR_FAILURE;
   10613             :     }
   10614             : 
   10615         204 :     CPLString osMethodCode;
   10616             :     osMethodCode.Printf("%d",
   10617             :                         sourceType == PJ_TYPE_GEOGRAPHIC_2D_CRS
   10618             :                             ? EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D
   10619             :                         : sourceType == PJ_TYPE_GEOGRAPHIC_3D_CRS
   10620           0 :                             ? EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D
   10621         102 :                             : EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC);
   10622             : 
   10623         102 :     auto transf = proj_create_transformation(
   10624             :         d->getPROJContext(), "Transformation to WGS84", nullptr, nullptr,
   10625             :         sourceCRS, targetCRS, nullptr,
   10626             :         sourceType == PJ_TYPE_GEOGRAPHIC_2D_CRS
   10627             :             ? EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D
   10628             :         : sourceType == PJ_TYPE_GEOGRAPHIC_3D_CRS
   10629           0 :             ? EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D
   10630             :             : EPSG_NAME_METHOD_POSITION_VECTOR_GEOCENTRIC,
   10631             :         "EPSG", osMethodCode.c_str(), 7, params, -1);
   10632         102 :     proj_destroy(sourceCRS);
   10633         102 :     if (!transf)
   10634             :     {
   10635           0 :         proj_destroy(targetCRS);
   10636           0 :         return OGRERR_FAILURE;
   10637             :     }
   10638             : 
   10639         102 :     auto newBoundCRS = proj_crs_create_bound_crs(
   10640         102 :         d->getPROJContext(), d->m_pj_crs, targetCRS, transf);
   10641         102 :     proj_destroy(transf);
   10642         102 :     proj_destroy(targetCRS);
   10643         102 :     if (!newBoundCRS)
   10644             :     {
   10645           0 :         return OGRERR_FAILURE;
   10646             :     }
   10647             : 
   10648         102 :     d->setPjCRS(newBoundCRS);
   10649         102 :     return OGRERR_NONE;
   10650             : }
   10651             : 
   10652             : /************************************************************************/
   10653             : /*                           OSRSetTOWGS84()                            */
   10654             : /************************************************************************/
   10655             : 
   10656             : /**
   10657             :  * \brief Set the Bursa-Wolf conversion to WGS84.
   10658             :  *
   10659             :  * This function is the same as OGRSpatialReference::SetTOWGS84().
   10660             :  */
   10661           4 : OGRErr OSRSetTOWGS84(OGRSpatialReferenceH hSRS, double dfDX, double dfDY,
   10662             :                      double dfDZ, double dfEX, double dfEY, double dfEZ,
   10663             :                      double dfPPM)
   10664             : 
   10665             : {
   10666           4 :     VALIDATE_POINTER1(hSRS, "OSRSetTOWGS84", OGRERR_FAILURE);
   10667             : 
   10668           4 :     return ToPointer(hSRS)->SetTOWGS84(dfDX, dfDY, dfDZ, dfEX, dfEY, dfEZ,
   10669           4 :                                        dfPPM);
   10670             : }
   10671             : 
   10672             : /************************************************************************/
   10673             : /*                             GetTOWGS84()                             */
   10674             : /************************************************************************/
   10675             : 
   10676             : /**
   10677             :  * \brief Fetch TOWGS84 parameters, if available.
   10678             :  *
   10679             :  * The parameters have the same meaning as EPSG transformation 9606
   10680             :  * (Position Vector 7-param. transformation).
   10681             :  *
   10682             :  * @param padfCoeff array into which up to 7 coefficients are placed.
   10683             :  * @param nCoeffCount size of padfCoeff - defaults to 7.
   10684             :  *
   10685             :  * @return OGRERR_NONE on success, or OGRERR_FAILURE if there is no
   10686             :  * TOWGS84 node available.
   10687             :  */
   10688             : 
   10689        5094 : OGRErr OGRSpatialReference::GetTOWGS84(double *padfCoeff, int nCoeffCount) const
   10690             : 
   10691             : {
   10692       10188 :     TAKE_OPTIONAL_LOCK();
   10693             : 
   10694        5094 :     d->refreshProjObj();
   10695        5094 :     if (d->m_pjType != PJ_TYPE_BOUND_CRS)
   10696        5046 :         return OGRERR_FAILURE;
   10697             : 
   10698          48 :     memset(padfCoeff, 0, sizeof(double) * nCoeffCount);
   10699             : 
   10700          48 :     auto transf = proj_crs_get_coordoperation(d->getPROJContext(), d->m_pj_crs);
   10701          48 :     int success = proj_coordoperation_get_towgs84_values(
   10702             :         d->getPROJContext(), transf, padfCoeff, nCoeffCount, false);
   10703          48 :     proj_destroy(transf);
   10704             : 
   10705          48 :     return success ? OGRERR_NONE : OGRERR_FAILURE;
   10706             : }
   10707             : 
   10708             : /************************************************************************/
   10709             : /*                           OSRGetTOWGS84()                            */
   10710             : /************************************************************************/
   10711             : 
   10712             : /**
   10713             :  * \brief Fetch TOWGS84 parameters, if available.
   10714             :  *
   10715             :  * This function is the same as OGRSpatialReference::GetTOWGS84().
   10716             :  */
   10717          10 : OGRErr OSRGetTOWGS84(OGRSpatialReferenceH hSRS, double *padfCoeff,
   10718             :                      int nCoeffCount)
   10719             : 
   10720             : {
   10721          10 :     VALIDATE_POINTER1(hSRS, "OSRGetTOWGS84", OGRERR_FAILURE);
   10722             : 
   10723          10 :     return ToPointer(hSRS)->GetTOWGS84(padfCoeff, nCoeffCount);
   10724             : }
   10725             : 
   10726             : /************************************************************************/
   10727             : /*                         IsAngularParameter()                         */
   10728             : /************************************************************************/
   10729             : 
   10730             : /** Is the passed projection parameter an angular one?
   10731             :  *
   10732             :  * @return TRUE or FALSE
   10733             :  */
   10734             : 
   10735             : /* static */
   10736          10 : int OGRSpatialReference::IsAngularParameter(const char *pszParameterName)
   10737             : 
   10738             : {
   10739          10 :     if (STARTS_WITH_CI(pszParameterName, "long") ||
   10740          10 :         STARTS_WITH_CI(pszParameterName, "lati") ||
   10741           7 :         EQUAL(pszParameterName, SRS_PP_CENTRAL_MERIDIAN) ||
   10742           4 :         STARTS_WITH_CI(pszParameterName, "standard_parallel") ||
   10743           2 :         EQUAL(pszParameterName, SRS_PP_AZIMUTH) ||
   10744           2 :         EQUAL(pszParameterName, SRS_PP_RECTIFIED_GRID_ANGLE))
   10745           8 :         return TRUE;
   10746             : 
   10747           2 :     return FALSE;
   10748             : }
   10749             : 
   10750             : /************************************************************************/
   10751             : /*                        IsLongitudeParameter()                        */
   10752             : /************************************************************************/
   10753             : 
   10754             : /** Is the passed projection parameter an angular longitude
   10755             :  * (relative to a prime meridian)?
   10756             :  *
   10757             :  * @return TRUE or FALSE
   10758             :  */
   10759             : 
   10760             : /* static */
   10761           0 : int OGRSpatialReference::IsLongitudeParameter(const char *pszParameterName)
   10762             : 
   10763             : {
   10764           0 :     if (STARTS_WITH_CI(pszParameterName, "long") ||
   10765           0 :         EQUAL(pszParameterName, SRS_PP_CENTRAL_MERIDIAN))
   10766           0 :         return TRUE;
   10767             : 
   10768           0 :     return FALSE;
   10769             : }
   10770             : 
   10771             : /************************************************************************/
   10772             : /*                         IsLinearParameter()                          */
   10773             : /************************************************************************/
   10774             : 
   10775             : /** Is the passed projection parameter an linear one measured in meters or
   10776             :  * some similar linear measure.
   10777             :  *
   10778             :  * @return TRUE or FALSE
   10779             :  */
   10780             : 
   10781             : /* static */
   10782          43 : int OGRSpatialReference::IsLinearParameter(const char *pszParameterName)
   10783             : 
   10784             : {
   10785          43 :     if (STARTS_WITH_CI(pszParameterName, "false_") ||
   10786          34 :         EQUAL(pszParameterName, SRS_PP_SATELLITE_HEIGHT))
   10787           9 :         return TRUE;
   10788             : 
   10789          34 :     return FALSE;
   10790             : }
   10791             : 
   10792             : /************************************************************************/
   10793             : /*                            GetNormInfo()                             */
   10794             : /************************************************************************/
   10795             : 
   10796             : /**
   10797             :  * \brief Set the internal information for normalizing linear, and angular
   10798             :  * values.
   10799             :  */
   10800        4144 : void OGRSpatialReference::GetNormInfo() const
   10801             : 
   10802             : {
   10803        4144 :     TAKE_OPTIONAL_LOCK();
   10804             : 
   10805        4144 :     if (d->bNormInfoSet)
   10806        2962 :         return;
   10807             : 
   10808             :     /* -------------------------------------------------------------------- */
   10809             :     /*      Initialize values.                                              */
   10810             :     /* -------------------------------------------------------------------- */
   10811        1182 :     d->bNormInfoSet = TRUE;
   10812             : 
   10813        1182 :     d->dfFromGreenwich = GetPrimeMeridian(nullptr);
   10814        1182 :     d->dfToMeter = GetLinearUnits(nullptr);
   10815        1182 :     d->dfToDegrees = GetAngularUnits(nullptr) / CPLAtof(SRS_UA_DEGREE_CONV);
   10816        1182 :     if (fabs(d->dfToDegrees - 1.0) < 0.000000001)
   10817        1179 :         d->dfToDegrees = 1.0;
   10818             : }
   10819             : 
   10820             : /************************************************************************/
   10821             : /*                            GetExtension()                            */
   10822             : /************************************************************************/
   10823             : 
   10824             : /**
   10825             :  * \brief Fetch extension value.
   10826             :  *
   10827             :  * Fetch the value of the named EXTENSION item for the identified
   10828             :  * target node.
   10829             :  *
   10830             :  * @param pszTargetKey the name or path to the parent node of the EXTENSION.
   10831             :  * @param pszName the name of the extension being fetched.
   10832             :  * @param pszDefault the value to return if the extension is not found.
   10833             :  *
   10834             :  * @return node value if successful or pszDefault on failure.
   10835             :  */
   10836             : 
   10837       13666 : const char *OGRSpatialReference::GetExtension(const char *pszTargetKey,
   10838             :                                               const char *pszName,
   10839             :                                               const char *pszDefault) const
   10840             : 
   10841             : {
   10842       27332 :     TAKE_OPTIONAL_LOCK();
   10843             : 
   10844             :     /* -------------------------------------------------------------------- */
   10845             :     /*      Find the target node.                                           */
   10846             :     /* -------------------------------------------------------------------- */
   10847             :     const OGR_SRSNode *poNode =
   10848       13666 :         pszTargetKey == nullptr ? GetRoot() : GetAttrNode(pszTargetKey);
   10849             : 
   10850       13666 :     if (poNode == nullptr)
   10851        2411 :         return nullptr;
   10852             : 
   10853             :     /* -------------------------------------------------------------------- */
   10854             :     /*      Fetch matching EXTENSION if there is one.                       */
   10855             :     /* -------------------------------------------------------------------- */
   10856       82874 :     for (int i = poNode->GetChildCount() - 1; i >= 0; i--)
   10857             :     {
   10858       71643 :         const OGR_SRSNode *poChild = poNode->GetChild(i);
   10859             : 
   10860       71669 :         if (EQUAL(poChild->GetValue(), "EXTENSION") &&
   10861          26 :             poChild->GetChildCount() >= 2)
   10862             :         {
   10863          26 :             if (EQUAL(poChild->GetChild(0)->GetValue(), pszName))
   10864          24 :                 return poChild->GetChild(1)->GetValue();
   10865             :         }
   10866             :     }
   10867             : 
   10868       11231 :     return pszDefault;
   10869             : }
   10870             : 
   10871             : /************************************************************************/
   10872             : /*                            SetExtension()                            */
   10873             : /************************************************************************/
   10874             : /**
   10875             :  * \brief Set extension value.
   10876             :  *
   10877             :  * Set the value of the named EXTENSION item for the identified
   10878             :  * target node.
   10879             :  *
   10880             :  * @param pszTargetKey the name or path to the parent node of the EXTENSION.
   10881             :  * @param pszName the name of the extension being fetched.
   10882             :  * @param pszValue the value to set
   10883             :  *
   10884             :  * @return OGRERR_NONE on success
   10885             :  */
   10886             : 
   10887          20 : OGRErr OGRSpatialReference::SetExtension(const char *pszTargetKey,
   10888             :                                          const char *pszName,
   10889             :                                          const char *pszValue)
   10890             : 
   10891             : {
   10892          40 :     TAKE_OPTIONAL_LOCK();
   10893             : 
   10894             :     /* -------------------------------------------------------------------- */
   10895             :     /*      Find the target node.                                           */
   10896             :     /* -------------------------------------------------------------------- */
   10897          20 :     OGR_SRSNode *poNode = nullptr;
   10898             : 
   10899          20 :     if (pszTargetKey == nullptr)
   10900           0 :         poNode = GetRoot();
   10901             :     else
   10902          20 :         poNode = GetAttrNode(pszTargetKey);
   10903             : 
   10904          20 :     if (poNode == nullptr)
   10905           0 :         return OGRERR_FAILURE;
   10906             : 
   10907             :     /* -------------------------------------------------------------------- */
   10908             :     /*      Fetch matching EXTENSION if there is one.                       */
   10909             :     /* -------------------------------------------------------------------- */
   10910         151 :     for (int i = poNode->GetChildCount() - 1; i >= 0; i--)
   10911             :     {
   10912         137 :         OGR_SRSNode *poChild = poNode->GetChild(i);
   10913             : 
   10914         143 :         if (EQUAL(poChild->GetValue(), "EXTENSION") &&
   10915           6 :             poChild->GetChildCount() >= 2)
   10916             :         {
   10917           6 :             if (EQUAL(poChild->GetChild(0)->GetValue(), pszName))
   10918             :             {
   10919           6 :                 poChild->GetChild(1)->SetValue(pszValue);
   10920           6 :                 return OGRERR_NONE;
   10921             :             }
   10922             :         }
   10923             :     }
   10924             : 
   10925             :     /* -------------------------------------------------------------------- */
   10926             :     /*      Create a new EXTENSION node.                                    */
   10927             :     /* -------------------------------------------------------------------- */
   10928          14 :     OGR_SRSNode *poAuthNode = new OGR_SRSNode("EXTENSION");
   10929          14 :     poAuthNode->AddChild(new OGR_SRSNode(pszName));
   10930          14 :     poAuthNode->AddChild(new OGR_SRSNode(pszValue));
   10931             : 
   10932          14 :     poNode->AddChild(poAuthNode);
   10933             : 
   10934          14 :     return OGRERR_NONE;
   10935             : }
   10936             : 
   10937             : /************************************************************************/
   10938             : /*                             OSRCleanup()                             */
   10939             : /************************************************************************/
   10940             : 
   10941             : static void CleanupSRSWGS84Mutex();
   10942             : 
   10943             : /**
   10944             :  * \brief Cleanup cached SRS related memory.
   10945             :  *
   10946             :  * This function will attempt to cleanup any cache spatial reference
   10947             :  * related information, such as cached tables of coordinate systems.
   10948             :  *
   10949             :  * This function should not be called concurrently with any other GDAL/OGR
   10950             :  * function. It is meant at being called once before process termination
   10951             :  * (typically from the main thread). CPLCleanupTLS() might be used to clean
   10952             :  * thread-specific resources before thread termination.
   10953             :  */
   10954        1232 : void OSRCleanup(void)
   10955             : 
   10956             : {
   10957        1232 :     OGRCTDumpStatistics();
   10958        1232 :     CSVDeaccess(nullptr);
   10959        1232 :     CleanupSRSWGS84Mutex();
   10960        1232 :     OSRCTCleanCache();
   10961        1232 :     OSRCleanupTLSContext();
   10962        1232 : }
   10963             : 
   10964             : /************************************************************************/
   10965             : /*                            GetAxesCount()                            */
   10966             : /************************************************************************/
   10967             : 
   10968             : /**
   10969             :  * \brief Return the number of axis of the coordinate system of the CRS.
   10970             :  *
   10971             :  * @since GDAL 3.0
   10972             :  */
   10973       40121 : int OGRSpatialReference::GetAxesCount() const
   10974             : {
   10975       80242 :     TAKE_OPTIONAL_LOCK();
   10976             : 
   10977       40121 :     int axisCount = 0;
   10978       40121 :     d->refreshProjObj();
   10979       40121 :     if (d->m_pj_crs == nullptr)
   10980             :     {
   10981           0 :         return 0;
   10982             :     }
   10983       40121 :     d->demoteFromBoundCRS();
   10984       40121 :     auto ctxt = d->getPROJContext();
   10985       40121 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
   10986             :     {
   10987          96 :         for (int i = 0;; i++)
   10988             :         {
   10989         288 :             auto subCRS = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, i);
   10990         288 :             if (!subCRS)
   10991          96 :                 break;
   10992         192 :             if (proj_get_type(subCRS) == PJ_TYPE_BOUND_CRS)
   10993             :             {
   10994          18 :                 auto baseCRS = proj_get_source_crs(ctxt, subCRS);
   10995          18 :                 if (baseCRS)
   10996             :                 {
   10997          18 :                     proj_destroy(subCRS);
   10998          18 :                     subCRS = baseCRS;
   10999             :                 }
   11000             :             }
   11001         192 :             auto cs = proj_crs_get_coordinate_system(ctxt, subCRS);
   11002         192 :             if (cs)
   11003             :             {
   11004         192 :                 axisCount += proj_cs_get_axis_count(ctxt, cs);
   11005         192 :                 proj_destroy(cs);
   11006             :             }
   11007         192 :             proj_destroy(subCRS);
   11008         192 :         }
   11009             :     }
   11010             :     else
   11011             :     {
   11012       40025 :         auto cs = proj_crs_get_coordinate_system(ctxt, d->m_pj_crs);
   11013       40025 :         if (cs)
   11014             :         {
   11015       40025 :             axisCount = proj_cs_get_axis_count(ctxt, cs);
   11016       40025 :             proj_destroy(cs);
   11017             :         }
   11018             :     }
   11019       40121 :     d->undoDemoteFromBoundCRS();
   11020       40121 :     return axisCount;
   11021             : }
   11022             : 
   11023             : /************************************************************************/
   11024             : /*                          OSRGetAxesCount()                           */
   11025             : /************************************************************************/
   11026             : 
   11027             : /**
   11028             :  * \brief Return the number of axis of the coordinate system of the CRS.
   11029             :  *
   11030             :  * This method is the equivalent of the C++ method
   11031             :  * OGRSpatialReference::GetAxesCount()
   11032             :  *
   11033             :  * @since GDAL 3.1
   11034             :  */
   11035           6 : int OSRGetAxesCount(OGRSpatialReferenceH hSRS)
   11036             : 
   11037             : {
   11038           6 :     VALIDATE_POINTER1(hSRS, "OSRGetAxesCount", 0);
   11039             : 
   11040           6 :     return ToPointer(hSRS)->GetAxesCount();
   11041             : }
   11042             : 
   11043             : /************************************************************************/
   11044             : /*                              GetAxis()                               */
   11045             : /************************************************************************/
   11046             : 
   11047             : /**
   11048             :  * \brief Fetch the orientation of one axis.
   11049             :  *
   11050             :  * Fetches the request axis (iAxis - zero based) from the
   11051             :  * indicated portion of the coordinate system (pszTargetKey) which
   11052             :  * should be either "GEOGCS" or "PROJCS".
   11053             :  *
   11054             :  * No CPLError is issued on routine failures (such as not finding the AXIS).
   11055             :  *
   11056             :  * This method is equivalent to the C function OSRGetAxis().
   11057             :  *
   11058             :  * @param pszTargetKey the coordinate system part to query ("PROJCS" or
   11059             :  * "GEOGCS").
   11060             :  * @param iAxis the axis to query (0 for first, 1 for second, 2 for third).
   11061             :  * @param peOrientation location into which to place the fetch orientation, may
   11062             :  * be NULL.
   11063             :  * @param pdfConvUnit (GDAL >= 3.4) Location into which to place axis conversion
   11064             :  * factor. May be NULL. Only set if pszTargetKey == NULL
   11065             :  *
   11066             :  * @return the name of the axis or NULL on failure.
   11067             :  */
   11068             : 
   11069        9104 : const char *OGRSpatialReference::GetAxis(const char *pszTargetKey, int iAxis,
   11070             :                                          OGRAxisOrientation *peOrientation,
   11071             :                                          double *pdfConvUnit) const
   11072             : 
   11073             : {
   11074       18208 :     TAKE_OPTIONAL_LOCK();
   11075             : 
   11076        9104 :     if (peOrientation != nullptr)
   11077        8993 :         *peOrientation = OAO_Other;
   11078        9104 :     if (pdfConvUnit != nullptr)
   11079         103 :         *pdfConvUnit = 0;
   11080             : 
   11081        9104 :     d->refreshProjObj();
   11082        9104 :     if (d->m_pj_crs == nullptr)
   11083             :     {
   11084           3 :         return nullptr;
   11085             :     }
   11086             : 
   11087        9101 :     pszTargetKey = d->nullifyTargetKeyIfPossible(pszTargetKey);
   11088        9101 :     if (pszTargetKey == nullptr && iAxis <= 2)
   11089             :     {
   11090        9101 :         auto ctxt = d->getPROJContext();
   11091             : 
   11092        9101 :         int iAxisModified = iAxis;
   11093             : 
   11094        9101 :         d->demoteFromBoundCRS();
   11095             : 
   11096        9101 :         PJ *cs = nullptr;
   11097        9101 :         if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
   11098             :         {
   11099         138 :             auto horizCRS = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 0);
   11100         138 :             if (horizCRS)
   11101             :             {
   11102         138 :                 if (proj_get_type(horizCRS) == PJ_TYPE_BOUND_CRS)
   11103             :                 {
   11104           6 :                     auto baseCRS = proj_get_source_crs(ctxt, horizCRS);
   11105           6 :                     if (baseCRS)
   11106             :                     {
   11107           6 :                         proj_destroy(horizCRS);
   11108           6 :                         horizCRS = baseCRS;
   11109             :                     }
   11110             :                 }
   11111         138 :                 cs = proj_crs_get_coordinate_system(ctxt, horizCRS);
   11112         138 :                 proj_destroy(horizCRS);
   11113         138 :                 if (cs)
   11114             :                 {
   11115         138 :                     if (iAxisModified >= proj_cs_get_axis_count(ctxt, cs))
   11116             :                     {
   11117          45 :                         iAxisModified -= proj_cs_get_axis_count(ctxt, cs);
   11118          45 :                         proj_destroy(cs);
   11119          45 :                         cs = nullptr;
   11120             :                     }
   11121             :                 }
   11122             :             }
   11123             : 
   11124         138 :             if (cs == nullptr)
   11125             :             {
   11126          45 :                 auto vertCRS = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 1);
   11127          45 :                 if (vertCRS)
   11128             :                 {
   11129          45 :                     if (proj_get_type(vertCRS) == PJ_TYPE_BOUND_CRS)
   11130             :                     {
   11131          30 :                         auto baseCRS = proj_get_source_crs(ctxt, vertCRS);
   11132          30 :                         if (baseCRS)
   11133             :                         {
   11134          30 :                             proj_destroy(vertCRS);
   11135          30 :                             vertCRS = baseCRS;
   11136             :                         }
   11137             :                     }
   11138             : 
   11139          45 :                     cs = proj_crs_get_coordinate_system(ctxt, vertCRS);
   11140          45 :                     proj_destroy(vertCRS);
   11141             :                 }
   11142             :             }
   11143             :         }
   11144             :         else
   11145             :         {
   11146        8963 :             cs = proj_crs_get_coordinate_system(ctxt, d->m_pj_crs);
   11147             :         }
   11148             : 
   11149        9101 :         if (cs)
   11150             :         {
   11151        9101 :             const char *pszName = nullptr;
   11152        9101 :             const char *pszOrientation = nullptr;
   11153        9101 :             double dfConvFactor = 0.0;
   11154        9101 :             proj_cs_get_axis_info(ctxt, cs, iAxisModified, &pszName, nullptr,
   11155             :                                   &pszOrientation, &dfConvFactor, nullptr,
   11156             :                                   nullptr, nullptr);
   11157             : 
   11158        9101 :             if (pdfConvUnit != nullptr)
   11159             :             {
   11160         103 :                 *pdfConvUnit = dfConvFactor;
   11161             :             }
   11162             : 
   11163        9101 :             if (pszName && pszOrientation)
   11164             :             {
   11165        9101 :                 d->m_osAxisName[iAxis] = pszName;
   11166        9101 :                 if (peOrientation)
   11167             :                 {
   11168        8990 :                     if (EQUAL(pszOrientation, "NORTH"))
   11169        5673 :                         *peOrientation = OAO_North;
   11170        3317 :                     else if (EQUAL(pszOrientation, "EAST"))
   11171        3244 :                         *peOrientation = OAO_East;
   11172          73 :                     else if (EQUAL(pszOrientation, "SOUTH"))
   11173          65 :                         *peOrientation = OAO_South;
   11174           8 :                     else if (EQUAL(pszOrientation, "WEST"))
   11175           0 :                         *peOrientation = OAO_West;
   11176           8 :                     else if (EQUAL(pszOrientation, "UP"))
   11177           1 :                         *peOrientation = OAO_Up;
   11178           7 :                     else if (EQUAL(pszOrientation, "DOWN"))
   11179           0 :                         *peOrientation = OAO_Down;
   11180             :                 }
   11181        9101 :                 proj_destroy(cs);
   11182        9101 :                 d->undoDemoteFromBoundCRS();
   11183        9101 :                 return d->m_osAxisName[iAxis].c_str();
   11184             :             }
   11185           0 :             proj_destroy(cs);
   11186             :         }
   11187           0 :         d->undoDemoteFromBoundCRS();
   11188             :     }
   11189             : 
   11190             :     /* -------------------------------------------------------------------- */
   11191             :     /*      Find the target node.                                           */
   11192             :     /* -------------------------------------------------------------------- */
   11193           0 :     const OGR_SRSNode *poNode = nullptr;
   11194             : 
   11195           0 :     if (pszTargetKey == nullptr)
   11196           0 :         poNode = GetRoot();
   11197             :     else
   11198           0 :         poNode = GetAttrNode(pszTargetKey);
   11199             : 
   11200           0 :     if (poNode == nullptr)
   11201           0 :         return nullptr;
   11202             : 
   11203             :     /* -------------------------------------------------------------------- */
   11204             :     /*      Find desired child AXIS.                                        */
   11205             :     /* -------------------------------------------------------------------- */
   11206           0 :     const OGR_SRSNode *poAxis = nullptr;
   11207           0 :     const int nChildCount = poNode->GetChildCount();
   11208             : 
   11209           0 :     for (int iChild = 0; iChild < nChildCount; iChild++)
   11210             :     {
   11211           0 :         const OGR_SRSNode *poChild = poNode->GetChild(iChild);
   11212             : 
   11213           0 :         if (!EQUAL(poChild->GetValue(), "AXIS"))
   11214           0 :             continue;
   11215             : 
   11216           0 :         if (iAxis == 0)
   11217             :         {
   11218           0 :             poAxis = poChild;
   11219           0 :             break;
   11220             :         }
   11221           0 :         iAxis--;
   11222             :     }
   11223             : 
   11224           0 :     if (poAxis == nullptr)
   11225           0 :         return nullptr;
   11226             : 
   11227           0 :     if (poAxis->GetChildCount() < 2)
   11228           0 :         return nullptr;
   11229             : 
   11230             :     /* -------------------------------------------------------------------- */
   11231             :     /*      Extract name and orientation if possible.                       */
   11232             :     /* -------------------------------------------------------------------- */
   11233           0 :     if (peOrientation != nullptr)
   11234             :     {
   11235           0 :         const char *pszOrientation = poAxis->GetChild(1)->GetValue();
   11236             : 
   11237           0 :         if (EQUAL(pszOrientation, "NORTH"))
   11238           0 :             *peOrientation = OAO_North;
   11239           0 :         else if (EQUAL(pszOrientation, "EAST"))
   11240           0 :             *peOrientation = OAO_East;
   11241           0 :         else if (EQUAL(pszOrientation, "SOUTH"))
   11242           0 :             *peOrientation = OAO_South;
   11243           0 :         else if (EQUAL(pszOrientation, "WEST"))
   11244           0 :             *peOrientation = OAO_West;
   11245           0 :         else if (EQUAL(pszOrientation, "UP"))
   11246           0 :             *peOrientation = OAO_Up;
   11247           0 :         else if (EQUAL(pszOrientation, "DOWN"))
   11248           0 :             *peOrientation = OAO_Down;
   11249           0 :         else if (EQUAL(pszOrientation, "OTHER"))
   11250           0 :             *peOrientation = OAO_Other;
   11251             :         else
   11252             :         {
   11253           0 :             CPLDebug("OSR", "Unrecognized orientation value '%s'.",
   11254             :                      pszOrientation);
   11255             :         }
   11256             :     }
   11257             : 
   11258           0 :     return poAxis->GetChild(0)->GetValue();
   11259             : }
   11260             : 
   11261             : /************************************************************************/
   11262             : /*                             OSRGetAxis()                             */
   11263             : /************************************************************************/
   11264             : 
   11265             : /**
   11266             :  * \brief Fetch the orientation of one axis.
   11267             :  *
   11268             :  * This method is the equivalent of the C++ method OGRSpatialReference::GetAxis
   11269             :  */
   11270          13 : const char *OSRGetAxis(OGRSpatialReferenceH hSRS, const char *pszTargetKey,
   11271             :                        int iAxis, OGRAxisOrientation *peOrientation)
   11272             : 
   11273             : {
   11274          13 :     VALIDATE_POINTER1(hSRS, "OSRGetAxis", nullptr);
   11275             : 
   11276          13 :     return ToPointer(hSRS)->GetAxis(pszTargetKey, iAxis, peOrientation);
   11277             : }
   11278             : 
   11279             : /************************************************************************/
   11280             : /*                         OSRAxisEnumToName()                          */
   11281             : /************************************************************************/
   11282             : 
   11283             : /**
   11284             :  * \brief Return the string representation for the OGRAxisOrientation
   11285             :  * enumeration.
   11286             :  *
   11287             :  * For example "NORTH" for OAO_North.
   11288             :  *
   11289             :  * @return an internal string
   11290             :  */
   11291         400 : const char *OSRAxisEnumToName(OGRAxisOrientation eOrientation)
   11292             : 
   11293             : {
   11294         400 :     if (eOrientation == OAO_North)
   11295         200 :         return "NORTH";
   11296         200 :     if (eOrientation == OAO_East)
   11297         200 :         return "EAST";
   11298           0 :     if (eOrientation == OAO_South)
   11299           0 :         return "SOUTH";
   11300           0 :     if (eOrientation == OAO_West)
   11301           0 :         return "WEST";
   11302           0 :     if (eOrientation == OAO_Up)
   11303           0 :         return "UP";
   11304           0 :     if (eOrientation == OAO_Down)
   11305           0 :         return "DOWN";
   11306           0 :     if (eOrientation == OAO_Other)
   11307           0 :         return "OTHER";
   11308             : 
   11309           0 :     return "UNKNOWN";
   11310             : }
   11311             : 
   11312             : /************************************************************************/
   11313             : /*                              SetAxes()                               */
   11314             : /************************************************************************/
   11315             : 
   11316             : /**
   11317             :  * \brief Set the axes for a coordinate system.
   11318             :  *
   11319             :  * Set the names, and orientations of the axes for either a projected
   11320             :  * (PROJCS) or geographic (GEOGCS) coordinate system.
   11321             :  *
   11322             :  * This method is equivalent to the C function OSRSetAxes().
   11323             :  *
   11324             :  * @param pszTargetKey either "PROJCS" or "GEOGCS", must already exist in SRS.
   11325             :  * @param pszXAxisName name of first axis, normally "Long" or "Easting".
   11326             :  * @param eXAxisOrientation normally OAO_East.
   11327             :  * @param pszYAxisName name of second axis, normally "Lat" or "Northing".
   11328             :  * @param eYAxisOrientation normally OAO_North.
   11329             :  *
   11330             :  * @return OGRERR_NONE on success or an error code.
   11331             :  */
   11332             : 
   11333         200 : OGRErr OGRSpatialReference::SetAxes(const char *pszTargetKey,
   11334             :                                     const char *pszXAxisName,
   11335             :                                     OGRAxisOrientation eXAxisOrientation,
   11336             :                                     const char *pszYAxisName,
   11337             :                                     OGRAxisOrientation eYAxisOrientation)
   11338             : 
   11339             : {
   11340         400 :     TAKE_OPTIONAL_LOCK();
   11341             : 
   11342             :     /* -------------------------------------------------------------------- */
   11343             :     /*      Find the target node.                                           */
   11344             :     /* -------------------------------------------------------------------- */
   11345         200 :     OGR_SRSNode *poNode = nullptr;
   11346             : 
   11347         200 :     if (pszTargetKey == nullptr)
   11348         200 :         poNode = GetRoot();
   11349             :     else
   11350           0 :         poNode = GetAttrNode(pszTargetKey);
   11351             : 
   11352         200 :     if (poNode == nullptr)
   11353           0 :         return OGRERR_FAILURE;
   11354             : 
   11355             :     /* -------------------------------------------------------------------- */
   11356             :     /*      Strip any existing AXIS children.                               */
   11357             :     /* -------------------------------------------------------------------- */
   11358         600 :     while (poNode->FindChild("AXIS") >= 0)
   11359         400 :         poNode->DestroyChild(poNode->FindChild("AXIS"));
   11360             : 
   11361             :     /* -------------------------------------------------------------------- */
   11362             :     /*      Insert desired axes                                             */
   11363             :     /* -------------------------------------------------------------------- */
   11364         200 :     OGR_SRSNode *poAxis = new OGR_SRSNode("AXIS");
   11365             : 
   11366         200 :     poAxis->AddChild(new OGR_SRSNode(pszXAxisName));
   11367         200 :     poAxis->AddChild(new OGR_SRSNode(OSRAxisEnumToName(eXAxisOrientation)));
   11368             : 
   11369         200 :     poNode->AddChild(poAxis);
   11370             : 
   11371         200 :     poAxis = new OGR_SRSNode("AXIS");
   11372             : 
   11373         200 :     poAxis->AddChild(new OGR_SRSNode(pszYAxisName));
   11374         200 :     poAxis->AddChild(new OGR_SRSNode(OSRAxisEnumToName(eYAxisOrientation)));
   11375             : 
   11376         200 :     poNode->AddChild(poAxis);
   11377             : 
   11378         200 :     return OGRERR_NONE;
   11379             : }
   11380             : 
   11381             : /************************************************************************/
   11382             : /*                             OSRSetAxes()                             */
   11383             : /************************************************************************/
   11384             : /**
   11385             :  * \brief Set the axes for a coordinate system.
   11386             :  *
   11387             :  * This method is the equivalent of the C++ method OGRSpatialReference::SetAxes
   11388             :  */
   11389           0 : OGRErr OSRSetAxes(OGRSpatialReferenceH hSRS, const char *pszTargetKey,
   11390             :                   const char *pszXAxisName,
   11391             :                   OGRAxisOrientation eXAxisOrientation,
   11392             :                   const char *pszYAxisName,
   11393             :                   OGRAxisOrientation eYAxisOrientation)
   11394             : {
   11395           0 :     VALIDATE_POINTER1(hSRS, "OSRSetAxes", OGRERR_FAILURE);
   11396             : 
   11397           0 :     return ToPointer(hSRS)->SetAxes(pszTargetKey, pszXAxisName,
   11398             :                                     eXAxisOrientation, pszYAxisName,
   11399           0 :                                     eYAxisOrientation);
   11400             : }
   11401             : 
   11402             : /************************************************************************/
   11403             : /*                       OSRExportToMICoordSys()                        */
   11404             : /************************************************************************/
   11405             : /**
   11406             :  * \brief Export coordinate system in Mapinfo style CoordSys format.
   11407             :  *
   11408             :  * This method is the equivalent of the C++ method
   11409             :  * OGRSpatialReference::exportToMICoordSys
   11410             :  */
   11411           5 : OGRErr OSRExportToMICoordSys(OGRSpatialReferenceH hSRS, char **ppszReturn)
   11412             : 
   11413             : {
   11414           5 :     VALIDATE_POINTER1(hSRS, "OSRExportToMICoordSys", OGRERR_FAILURE);
   11415             : 
   11416           5 :     *ppszReturn = nullptr;
   11417             : 
   11418           5 :     return ToPointer(hSRS)->exportToMICoordSys(ppszReturn);
   11419             : }
   11420             : 
   11421             : /************************************************************************/
   11422             : /*                         exportToMICoordSys()                         */
   11423             : /************************************************************************/
   11424             : 
   11425             : /**
   11426             :  * \brief Export coordinate system in Mapinfo style CoordSys format.
   11427             :  *
   11428             :  * Note that the returned WKT string should be freed with
   11429             :  * CPLFree() when no longer needed.  It is the responsibility of the caller.
   11430             :  *
   11431             :  * This method is the same as the C function OSRExportToMICoordSys().
   11432             :  *
   11433             :  * @param ppszResult pointer to which dynamically allocated Mapinfo CoordSys
   11434             :  * definition will be assigned.
   11435             :  *
   11436             :  * @return OGRERR_NONE on success, OGRERR_FAILURE on failure,
   11437             :  * OGRERR_UNSUPPORTED_OPERATION if MITAB library was not linked in.
   11438             :  */
   11439             : 
   11440           7 : OGRErr OGRSpatialReference::exportToMICoordSys(char **ppszResult) const
   11441             : 
   11442             : {
   11443           7 :     *ppszResult = MITABSpatialRef2CoordSys(this);
   11444           7 :     if (*ppszResult != nullptr && strlen(*ppszResult) > 0)
   11445           7 :         return OGRERR_NONE;
   11446             : 
   11447           0 :     return OGRERR_FAILURE;
   11448             : }
   11449             : 
   11450             : /************************************************************************/
   11451             : /*                      OSRImportFromMICoordSys()                       */
   11452             : /************************************************************************/
   11453             : /**
   11454             :  * \brief Import Mapinfo style CoordSys definition.
   11455             :  *
   11456             :  * This method is the equivalent of the C++ method
   11457             :  * OGRSpatialReference::importFromMICoordSys
   11458             :  */
   11459             : 
   11460           3 : OGRErr OSRImportFromMICoordSys(OGRSpatialReferenceH hSRS,
   11461             :                                const char *pszCoordSys)
   11462             : 
   11463             : {
   11464           3 :     VALIDATE_POINTER1(hSRS, "OSRImportFromMICoordSys", OGRERR_FAILURE);
   11465             : 
   11466           3 :     return ToPointer(hSRS)->importFromMICoordSys(pszCoordSys);
   11467             : }
   11468             : 
   11469             : /************************************************************************/
   11470             : /*                        importFromMICoordSys()                        */
   11471             : /************************************************************************/
   11472             : 
   11473             : /**
   11474             :  * \brief Import Mapinfo style CoordSys definition.
   11475             :  *
   11476             :  * The OGRSpatialReference is initialized from the passed Mapinfo style CoordSys
   11477             :  * definition string.
   11478             :  *
   11479             :  * This method is the equivalent of the C function OSRImportFromMICoordSys().
   11480             :  *
   11481             :  * @param pszCoordSys Mapinfo style CoordSys definition string.
   11482             :  *
   11483             :  * @return OGRERR_NONE on success, OGRERR_FAILURE on failure,
   11484             :  * OGRERR_UNSUPPORTED_OPERATION if MITAB library was not linked in.
   11485             :  */
   11486             : 
   11487          17 : OGRErr OGRSpatialReference::importFromMICoordSys(const char *pszCoordSys)
   11488             : 
   11489             : {
   11490          17 :     OGRSpatialReference *poResult = MITABCoordSys2SpatialRef(pszCoordSys);
   11491             : 
   11492          17 :     if (poResult == nullptr)
   11493           0 :         return OGRERR_FAILURE;
   11494             : 
   11495          17 :     *this = *poResult;
   11496          17 :     delete poResult;
   11497             : 
   11498          17 :     return OGRERR_NONE;
   11499             : }
   11500             : 
   11501             : /************************************************************************/
   11502             : /*                        OSRCalcInvFlattening()                        */
   11503             : /************************************************************************/
   11504             : 
   11505             : /**
   11506             :  * \brief Compute inverse flattening from semi-major and semi-minor axis
   11507             :  *
   11508             :  * @param dfSemiMajor Semi-major axis length.
   11509             :  * @param dfSemiMinor Semi-minor axis length.
   11510             :  *
   11511             :  * @return inverse flattening, or 0 if both axis are equal.
   11512             :  */
   11513             : 
   11514        8842 : double OSRCalcInvFlattening(double dfSemiMajor, double dfSemiMinor)
   11515             : {
   11516        8842 :     if (fabs(dfSemiMajor - dfSemiMinor) < 1e-1)
   11517          27 :         return 0;
   11518        8815 :     if (dfSemiMajor <= 0 || dfSemiMinor <= 0 || dfSemiMinor > dfSemiMajor)
   11519             :     {
   11520           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
   11521             :                  "OSRCalcInvFlattening(): Wrong input values");
   11522           0 :         return 0;
   11523             :     }
   11524             : 
   11525        8815 :     return dfSemiMajor / (dfSemiMajor - dfSemiMinor);
   11526             : }
   11527             : 
   11528             : /************************************************************************/
   11529             : /*                        OSRCalcInvFlattening()                        */
   11530             : /************************************************************************/
   11531             : 
   11532             : /**
   11533             :  * \brief Compute semi-minor axis from semi-major axis and inverse flattening.
   11534             :  *
   11535             :  * @param dfSemiMajor Semi-major axis length.
   11536             :  * @param dfInvFlattening Inverse flattening or 0 for sphere.
   11537             :  *
   11538             :  * @return semi-minor axis
   11539             :  */
   11540             : 
   11541         642 : double OSRCalcSemiMinorFromInvFlattening(double dfSemiMajor,
   11542             :                                          double dfInvFlattening)
   11543             : {
   11544         642 :     if (fabs(dfInvFlattening) < 0.000000000001)
   11545         103 :         return dfSemiMajor;
   11546         539 :     if (dfSemiMajor <= 0.0 || dfInvFlattening <= 1.0)
   11547             :     {
   11548           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
   11549             :                  "OSRCalcSemiMinorFromInvFlattening(): Wrong input values");
   11550           0 :         return dfSemiMajor;
   11551             :     }
   11552             : 
   11553         539 :     return dfSemiMajor * (1.0 - 1.0 / dfInvFlattening);
   11554             : }
   11555             : 
   11556             : /************************************************************************/
   11557             : /*                            GetWGS84SRS()                             */
   11558             : /************************************************************************/
   11559             : 
   11560             : static OGRSpatialReference *poSRSWGS84 = nullptr;
   11561             : static CPLMutex *hMutex = nullptr;
   11562             : 
   11563             : /**
   11564             :  * \brief Returns an instance of a SRS object with WGS84 WKT.
   11565             :  *
   11566             :  * Note: the instance will have
   11567             :  * SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER)
   11568             :  *
   11569             :  * The reference counter of the returned object is not increased by this
   11570             :  * operation.
   11571             :  *
   11572             :  * @return instance.
   11573             :  */
   11574             : 
   11575        1005 : OGRSpatialReference *OGRSpatialReference::GetWGS84SRS()
   11576             : {
   11577        1005 :     CPLMutexHolderD(&hMutex);
   11578        1005 :     if (poSRSWGS84 == nullptr)
   11579             :     {
   11580           5 :         poSRSWGS84 = new OGRSpatialReference(SRS_WKT_WGS84_LAT_LONG);
   11581           5 :         poSRSWGS84->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
   11582             :     }
   11583        2010 :     return poSRSWGS84;
   11584             : }
   11585             : 
   11586             : /************************************************************************/
   11587             : /*                        CleanupSRSWGS84Mutex()                        */
   11588             : /************************************************************************/
   11589             : 
   11590        1232 : static void CleanupSRSWGS84Mutex()
   11591             : {
   11592        1232 :     if (hMutex != nullptr)
   11593             :     {
   11594           3 :         poSRSWGS84->Release();
   11595           3 :         poSRSWGS84 = nullptr;
   11596           3 :         CPLDestroyMutex(hMutex);
   11597           3 :         hMutex = nullptr;
   11598             :     }
   11599        1232 : }
   11600             : 
   11601             : /************************************************************************/
   11602             : /*                         OSRImportFromProj4()                         */
   11603             : /************************************************************************/
   11604             : /**
   11605             :  * \brief Import PROJ coordinate string.
   11606             :  *
   11607             :  * This function is the same as OGRSpatialReference::importFromProj4().
   11608             :  */
   11609         218 : OGRErr OSRImportFromProj4(OGRSpatialReferenceH hSRS, const char *pszProj4)
   11610             : 
   11611             : {
   11612         218 :     VALIDATE_POINTER1(hSRS, "OSRImportFromProj4", OGRERR_FAILURE);
   11613             : 
   11614         218 :     return OGRSpatialReference::FromHandle(hSRS)->importFromProj4(pszProj4);
   11615             : }
   11616             : 
   11617             : /************************************************************************/
   11618             : /*                          importFromProj4()                           */
   11619             : /************************************************************************/
   11620             : 
   11621             : /**
   11622             :  * \brief Import PROJ coordinate string.
   11623             :  *
   11624             :  * The OGRSpatialReference is initialized from the passed PROJs style
   11625             :  * coordinate system string.
   11626             :  *
   11627             :  * Example:
   11628             :  *   pszProj4 = "+proj=utm +zone=11 +datum=WGS84"
   11629             :  *
   11630             :  * It is also possible to import "+init=epsg:n" style definitions. Those are
   11631             :  * a legacy syntax that should be avoided in the future. In particular they will
   11632             :  * result in CRS objects whose axis order might not correspond to the official
   11633             :  * EPSG axis order.
   11634             :  *
   11635             :  * This method is the equivalent of the C function OSRImportFromProj4().
   11636             :  *
   11637             :  * @param pszProj4 the PROJ style string.
   11638             :  *
   11639             :  * @return OGRERR_NONE on success or OGRERR_CORRUPT_DATA on failure.
   11640             :  */
   11641             : 
   11642         777 : OGRErr OGRSpatialReference::importFromProj4(const char *pszProj4)
   11643             : 
   11644             : {
   11645        1554 :     TAKE_OPTIONAL_LOCK();
   11646             : 
   11647         777 :     if (strlen(pszProj4) >= 10000)
   11648             :     {
   11649           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Too long PROJ string");
   11650           1 :         return OGRERR_CORRUPT_DATA;
   11651             :     }
   11652             : 
   11653             :     /* -------------------------------------------------------------------- */
   11654             :     /*      Clear any existing definition.                                  */
   11655             :     /* -------------------------------------------------------------------- */
   11656         776 :     Clear();
   11657             : 
   11658         776 :     CPLString osProj4(pszProj4);
   11659         776 :     if (osProj4.find("type=crs") == std::string::npos)
   11660             :     {
   11661         764 :         osProj4 += " +type=crs";
   11662             :     }
   11663             : 
   11664         778 :     if (osProj4.find("+init=epsg:") != std::string::npos &&
   11665           2 :         getenv("PROJ_USE_PROJ4_INIT_RULES") == nullptr)
   11666             :     {
   11667           2 :         CPLErrorOnce(CE_Warning, CPLE_AppDefined,
   11668             :                      "+init=epsg:XXXX syntax is deprecated. It might return "
   11669             :                      "a CRS with a non-EPSG compliant axis order.");
   11670             :     }
   11671         776 :     proj_context_use_proj4_init_rules(d->getPROJContext(), true);
   11672         776 :     d->setPjCRS(proj_create(d->getPROJContext(), osProj4.c_str()));
   11673         776 :     proj_context_use_proj4_init_rules(d->getPROJContext(), false);
   11674         776 :     return d->m_pj_crs ? OGRERR_NONE : OGRERR_CORRUPT_DATA;
   11675             : }
   11676             : 
   11677             : /************************************************************************/
   11678             : /*                          OSRExportToProj4()                          */
   11679             : /************************************************************************/
   11680             : /**
   11681             :  * \brief Export coordinate system in PROJ.4 legacy format.
   11682             :  *
   11683             :  * \warning Use of this function is discouraged. Its behavior in GDAL &gt;= 3 /
   11684             :  * PROJ &gt;= 6 is significantly different from earlier versions. In particular
   11685             :  * +datum will only encode WGS84, NAD27 and NAD83, and +towgs84/+nadgrids terms
   11686             :  * will be missing most of the time. PROJ strings to encode CRS should be
   11687             :  * considered as a legacy solution. Using a AUTHORITY:CODE or WKT representation
   11688             :  * is the recommended way.
   11689             :  *
   11690             :  * This function is the same as OGRSpatialReference::exportToProj4().
   11691             :  */
   11692         325 : OGRErr CPL_STDCALL OSRExportToProj4(OGRSpatialReferenceH hSRS,
   11693             :                                     char **ppszReturn)
   11694             : 
   11695             : {
   11696         325 :     VALIDATE_POINTER1(hSRS, "OSRExportToProj4", OGRERR_FAILURE);
   11697             : 
   11698         325 :     *ppszReturn = nullptr;
   11699             : 
   11700         325 :     return OGRSpatialReference::FromHandle(hSRS)->exportToProj4(ppszReturn);
   11701             : }
   11702             : 
   11703             : /************************************************************************/
   11704             : /*                           exportToProj4()                            */
   11705             : /************************************************************************/
   11706             : 
   11707             : /**
   11708             :  * \brief Export coordinate system in PROJ.4 legacy format.
   11709             :  *
   11710             :  * \warning Use of this function is discouraged. Its behavior in GDAL &gt;= 3 /
   11711             :  * PROJ &gt;= 6 is significantly different from earlier versions. In particular
   11712             :  * +datum will only encode WGS84, NAD27 and NAD83, and +towgs84/+nadgrids terms
   11713             :  * will be missing most of the time. PROJ strings to encode CRS should be
   11714             :  * considered as a a legacy solution. Using a AUTHORITY:CODE or WKT
   11715             :  * representation is the recommended way.
   11716             :  *
   11717             :  * Converts the loaded coordinate reference system into PROJ format
   11718             :  * to the extent possible.  The string returned in ppszProj4 should be
   11719             :  * deallocated by the caller with CPLFree() when no longer needed.
   11720             :  *
   11721             :  * LOCAL_CS coordinate systems are not translatable.  An empty string
   11722             :  * will be returned along with OGRERR_NONE.
   11723             :  *
   11724             :  * Special processing for Transverse Mercator:
   11725             :  * Starting with GDAL 3.0, if the OSR_USE_APPROX_TMERC configuration option is
   11726             :  * set to YES, the PROJ definition built from the SRS will use the +approx flag
   11727             :  * for the tmerc and utm projection methods, rather than the more accurate
   11728             :  * method.
   11729             :  *
   11730             :  * Starting with GDAL 3.0.3, this method will try to add a +towgs84 parameter,
   11731             :  * if there's none attached yet to the SRS and if the SRS has a EPSG code.
   11732             :  * See the AddGuessedTOWGS84() method for how this +towgs84 parameter may be
   11733             :  * added. This automatic addition may be disabled by setting the
   11734             :  * OSR_ADD_TOWGS84_ON_EXPORT_TO_PROJ4 configuration option to NO.
   11735             :  *
   11736             :  * This method is the equivalent of the C function OSRExportToProj4().
   11737             :  *
   11738             :  * @param ppszProj4 pointer to which dynamically allocated PROJ definition
   11739             :  * will be assigned.
   11740             :  *
   11741             :  * @return OGRERR_NONE on success or an error code on failure.
   11742             :  */
   11743             : 
   11744        1474 : OGRErr OGRSpatialReference::exportToProj4(char **ppszProj4) const
   11745             : 
   11746             : {
   11747             :     // In the past calling this method was thread-safe, even if we never
   11748             :     // guaranteed it. Now proj_as_proj_string() will cache the result
   11749             :     // internally, so this is no longer thread-safe.
   11750        2948 :     std::lock_guard oLock(d->m_mutex);
   11751             : 
   11752        1474 :     d->refreshProjObj();
   11753        1474 :     if (d->m_pj_crs == nullptr || d->m_pjType == PJ_TYPE_ENGINEERING_CRS)
   11754             :     {
   11755           4 :         *ppszProj4 = CPLStrdup("");
   11756           4 :         return OGRERR_FAILURE;
   11757             :     }
   11758             : 
   11759             :     // OSR_USE_ETMERC is here just for legacy
   11760        1470 :     bool bForceApproxTMerc = false;
   11761        1470 :     const char *pszUseETMERC = CPLGetConfigOption("OSR_USE_ETMERC", nullptr);
   11762        1470 :     if (pszUseETMERC && pszUseETMERC[0])
   11763             :     {
   11764           0 :         CPLErrorOnce(CE_Warning, CPLE_AppDefined,
   11765             :                      "OSR_USE_ETMERC is a legacy configuration option, which "
   11766             :                      "now has only effect when set to NO (YES is the default). "
   11767             :                      "Use OSR_USE_APPROX_TMERC=YES instead");
   11768           0 :         bForceApproxTMerc = !CPLTestBool(pszUseETMERC);
   11769             :     }
   11770             :     else
   11771             :     {
   11772             :         const char *pszUseApproxTMERC =
   11773        1470 :             CPLGetConfigOption("OSR_USE_APPROX_TMERC", nullptr);
   11774        1470 :         if (pszUseApproxTMERC && pszUseApproxTMERC[0])
   11775             :         {
   11776           2 :             bForceApproxTMerc = CPLTestBool(pszUseApproxTMERC);
   11777             :         }
   11778             :     }
   11779        1470 :     const char *options[] = {
   11780        1470 :         bForceApproxTMerc ? "USE_APPROX_TMERC=YES" : nullptr, nullptr};
   11781             : 
   11782        1470 :     const char *projString = proj_as_proj_string(
   11783        1470 :         d->getPROJContext(), d->m_pj_crs, PJ_PROJ_4, options);
   11784             : 
   11785        1470 :     PJ *boundCRS = nullptr;
   11786        2936 :     if (projString &&
   11787        1466 :         (strstr(projString, "+datum=") == nullptr ||
   11788        2946 :          d->m_pjType == PJ_TYPE_COMPOUND_CRS) &&
   11789         552 :         CPLTestBool(
   11790             :             CPLGetConfigOption("OSR_ADD_TOWGS84_ON_EXPORT_TO_PROJ4", "YES")))
   11791             :     {
   11792         552 :         boundCRS = GDAL_proj_crs_create_bound_crs_to_WGS84(
   11793         552 :             d->getPROJContext(), d->m_pj_crs, true,
   11794         552 :             strstr(projString, "+datum=") == nullptr);
   11795         552 :         if (boundCRS)
   11796             :         {
   11797         180 :             projString = proj_as_proj_string(d->getPROJContext(), boundCRS,
   11798             :                                              PJ_PROJ_4, options);
   11799             :         }
   11800             :     }
   11801             : 
   11802        1470 :     if (projString == nullptr)
   11803             :     {
   11804           4 :         *ppszProj4 = CPLStrdup("");
   11805           4 :         proj_destroy(boundCRS);
   11806           4 :         return OGRERR_FAILURE;
   11807             :     }
   11808        1466 :     *ppszProj4 = CPLStrdup(projString);
   11809        1466 :     proj_destroy(boundCRS);
   11810        1466 :     char *pszTypeCrs = strstr(*ppszProj4, " +type=crs");
   11811        1466 :     if (pszTypeCrs)
   11812        1466 :         *pszTypeCrs = '\0';
   11813        1466 :     return OGRERR_NONE;
   11814             : }
   11815             : 
   11816             : /************************************************************************/
   11817             : /*                            morphToESRI()                             */
   11818             : /************************************************************************/
   11819             : /**
   11820             :  * \brief Convert in place to ESRI WKT format.
   11821             :  *
   11822             :  * The value nodes of this coordinate system are modified in various manners
   11823             :  * more closely map onto the ESRI concept of WKT format.  This includes
   11824             :  * renaming a variety of projections and arguments, and stripping out
   11825             :  * nodes note recognised by ESRI (like AUTHORITY and AXIS).
   11826             :  *
   11827             :  * \note Since GDAL 3.0, this function has only user-visible effects at
   11828             :  * exportToWkt() time. It is recommended to use instead exportToWkt(char**,
   11829             :  * const char* const char*) const with options having FORMAT=WKT1_ESRI.
   11830             :  *
   11831             :  * This does the same as the C function OSRMorphToESRI().
   11832             :  *
   11833             :  * @return OGRERR_NONE unless something goes badly wrong.
   11834             :  * @deprecated
   11835             :  */
   11836             : 
   11837         236 : OGRErr OGRSpatialReference::morphToESRI()
   11838             : 
   11839             : {
   11840         236 :     TAKE_OPTIONAL_LOCK();
   11841             : 
   11842         236 :     d->refreshProjObj();
   11843         236 :     d->setMorphToESRI(true);
   11844             : 
   11845         472 :     return OGRERR_NONE;
   11846             : }
   11847             : 
   11848             : /************************************************************************/
   11849             : /*                           OSRMorphToESRI()                           */
   11850             : /************************************************************************/
   11851             : 
   11852             : /**
   11853             :  * \brief Convert in place to ESRI WKT format.
   11854             :  *
   11855             :  * This function is the same as the C++ method
   11856             :  * OGRSpatialReference::morphToESRI().
   11857             :  */
   11858          71 : OGRErr OSRMorphToESRI(OGRSpatialReferenceH hSRS)
   11859             : 
   11860             : {
   11861          71 :     VALIDATE_POINTER1(hSRS, "OSRMorphToESRI", OGRERR_FAILURE);
   11862             : 
   11863          71 :     return OGRSpatialReference::FromHandle(hSRS)->morphToESRI();
   11864             : }
   11865             : 
   11866             : /************************************************************************/
   11867             : /*                           morphFromESRI()                            */
   11868             : /************************************************************************/
   11869             : 
   11870             : /**
   11871             :  * \brief Convert in place from ESRI WKT format.
   11872             :  *
   11873             :  * The value notes of this coordinate system are modified in various manners
   11874             :  * to adhere more closely to the WKT standard.  This mostly involves
   11875             :  * translating a variety of ESRI names for projections, arguments and
   11876             :  * datums to "standard" names, as defined by Adam Gawne-Cain's reference
   11877             :  * translation of EPSG to WKT for the CT specification.
   11878             :  *
   11879             :  * \note Since GDAL 3.0, this function is essentially a no-operation, since
   11880             :  * morphing from ESRI is automatically done by importFromWkt(). Its only
   11881             :  * effect is to undo the effect of a potential prior call to morphToESRI().
   11882             :  *
   11883             :  * This does the same as the C function OSRMorphFromESRI().
   11884             :  *
   11885             :  * @return OGRERR_NONE unless something goes badly wrong.
   11886             :  * @deprecated
   11887             :  */
   11888             : 
   11889          21 : OGRErr OGRSpatialReference::morphFromESRI()
   11890             : 
   11891             : {
   11892          21 :     TAKE_OPTIONAL_LOCK();
   11893             : 
   11894          21 :     d->refreshProjObj();
   11895          21 :     d->setMorphToESRI(false);
   11896             : 
   11897          42 :     return OGRERR_NONE;
   11898             : }
   11899             : 
   11900             : /************************************************************************/
   11901             : /*                          OSRMorphFromESRI()                          */
   11902             : /************************************************************************/
   11903             : 
   11904             : /**
   11905             :  * \brief Convert in place from ESRI WKT format.
   11906             :  *
   11907             :  * This function is the same as the C++ method
   11908             :  * OGRSpatialReference::morphFromESRI().
   11909             :  */
   11910          20 : OGRErr OSRMorphFromESRI(OGRSpatialReferenceH hSRS)
   11911             : 
   11912             : {
   11913          20 :     VALIDATE_POINTER1(hSRS, "OSRMorphFromESRI", OGRERR_FAILURE);
   11914             : 
   11915          20 :     return OGRSpatialReference::FromHandle(hSRS)->morphFromESRI();
   11916             : }
   11917             : 
   11918             : /************************************************************************/
   11919             : /*                            FindMatches()                             */
   11920             : /************************************************************************/
   11921             : 
   11922             : /**
   11923             :  * \brief Try to identify a match between the passed SRS and a related SRS
   11924             :  * in a catalog.
   11925             :  *
   11926             :  * Matching may be partial, or may fail.
   11927             :  * Returned entries will be sorted by decreasing match confidence (first
   11928             :  * entry has the highest match confidence).
   11929             :  *
   11930             :  * The exact way matching is done may change in future versions. Starting with
   11931             :  * GDAL 3.0, it relies on PROJ' proj_identify() function.
   11932             :  *
   11933             :  * This method is the same as OSRFindMatches().
   11934             :  *
   11935             :  * @param papszOptions NULL terminated list of options or NULL
   11936             :  * @param pnEntries Output parameter. Number of values in the returned array.
   11937             :  * @param ppanMatchConfidence Output parameter (or NULL). *ppanMatchConfidence
   11938             :  * will be allocated to an array of *pnEntries whose values between 0 and 100
   11939             :  * indicate the confidence in the match. 100 is the highest confidence level.
   11940             :  * The array must be freed with CPLFree().
   11941             :  *
   11942             :  * @return an array of SRS that match the passed SRS, or NULL. Must be freed
   11943             :  * with OSRFreeSRSArray()
   11944             :  *
   11945             :  *
   11946             :  * @see OGRSpatialReference::FindBestMatch()
   11947             :  */
   11948             : OGRSpatialReferenceH *
   11949        1601 : OGRSpatialReference::FindMatches(CSLConstList papszOptions, int *pnEntries,
   11950             :                                  int **ppanMatchConfidence) const
   11951             : {
   11952        3202 :     TAKE_OPTIONAL_LOCK();
   11953             : 
   11954        1601 :     CPL_IGNORE_RET_VAL(papszOptions);
   11955             : 
   11956        1601 :     if (pnEntries)
   11957        1601 :         *pnEntries = 0;
   11958        1601 :     if (ppanMatchConfidence)
   11959        1601 :         *ppanMatchConfidence = nullptr;
   11960             : 
   11961        1601 :     d->refreshProjObj();
   11962        1601 :     if (!d->m_pj_crs)
   11963           0 :         return nullptr;
   11964             : 
   11965        1601 :     int *panConfidence = nullptr;
   11966        1601 :     auto ctxt = d->getPROJContext();
   11967             :     auto list =
   11968        1601 :         proj_identify(ctxt, d->m_pj_crs, nullptr, nullptr, &panConfidence);
   11969        1601 :     if (!list)
   11970           0 :         return nullptr;
   11971             : 
   11972        1601 :     const int nMatches = proj_list_get_count(list);
   11973             : 
   11974        1601 :     if (pnEntries)
   11975        1601 :         *pnEntries = static_cast<int>(nMatches);
   11976             :     OGRSpatialReferenceH *pahRet = static_cast<OGRSpatialReferenceH *>(
   11977        1601 :         CPLCalloc(sizeof(OGRSpatialReferenceH), nMatches + 1));
   11978        1601 :     if (ppanMatchConfidence)
   11979             :     {
   11980        1601 :         *ppanMatchConfidence =
   11981        1601 :             static_cast<int *>(CPLMalloc(sizeof(int) * (nMatches + 1)));
   11982             :     }
   11983             : 
   11984        1601 :     bool bSortAgain = false;
   11985             : 
   11986        4585 :     for (int i = 0; i < nMatches; i++)
   11987             :     {
   11988        2984 :         PJ *obj = proj_list_get(ctxt, list, i);
   11989        2984 :         CPLAssert(obj);
   11990        2984 :         OGRSpatialReference *poSRS = new OGRSpatialReference();
   11991        2984 :         poSRS->d->setPjCRS(obj);
   11992        2984 :         pahRet[i] = ToHandle(poSRS);
   11993             : 
   11994             :         // Identify matches that only differ by axis order
   11995           9 :         if (panConfidence[i] == 50 && GetAxesCount() == 2 &&
   11996        3002 :             poSRS->GetAxesCount() == 2 &&
   11997        2993 :             GetDataAxisToSRSAxisMapping() == std::vector<int>{1, 2})
   11998             :         {
   11999           9 :             OGRAxisOrientation eThisAxis0 = OAO_Other;
   12000           9 :             OGRAxisOrientation eThisAxis1 = OAO_Other;
   12001           9 :             OGRAxisOrientation eSRSAxis0 = OAO_Other;
   12002           9 :             OGRAxisOrientation eSRSAxis1 = OAO_Other;
   12003           9 :             GetAxis(nullptr, 0, &eThisAxis0);
   12004           9 :             GetAxis(nullptr, 1, &eThisAxis1);
   12005           9 :             poSRS->GetAxis(nullptr, 0, &eSRSAxis0);
   12006           9 :             poSRS->GetAxis(nullptr, 1, &eSRSAxis1);
   12007           9 :             if (eThisAxis0 == OAO_East && eThisAxis1 == OAO_North &&
   12008           9 :                 eSRSAxis0 == OAO_North && eSRSAxis1 == OAO_East)
   12009             :             {
   12010             :                 auto pj_crs_normalized =
   12011           9 :                     proj_normalize_for_visualization(ctxt, poSRS->d->m_pj_crs);
   12012           9 :                 if (pj_crs_normalized)
   12013             :                 {
   12014           9 :                     if (proj_is_equivalent_to(d->m_pj_crs, pj_crs_normalized,
   12015           9 :                                               PJ_COMP_EQUIVALENT))
   12016             :                     {
   12017           3 :                         bSortAgain = true;
   12018           3 :                         panConfidence[i] = 90;
   12019           3 :                         poSRS->SetDataAxisToSRSAxisMapping({2, 1});
   12020             :                     }
   12021           9 :                     proj_destroy(pj_crs_normalized);
   12022             :                 }
   12023             :             }
   12024             :         }
   12025             : 
   12026        2984 :         if (ppanMatchConfidence)
   12027        2984 :             (*ppanMatchConfidence)[i] = panConfidence[i];
   12028             :     }
   12029             : 
   12030        1601 :     if (bSortAgain)
   12031             :     {
   12032           3 :         std::vector<int> anIndices;
   12033          12 :         for (int i = 0; i < nMatches; ++i)
   12034           9 :             anIndices.push_back(i);
   12035             : 
   12036           3 :         std::stable_sort(anIndices.begin(), anIndices.end(),
   12037           9 :                          [&panConfidence](int i, int j)
   12038           9 :                          { return panConfidence[i] > panConfidence[j]; });
   12039             : 
   12040             :         OGRSpatialReferenceH *pahRetSorted =
   12041             :             static_cast<OGRSpatialReferenceH *>(
   12042           3 :                 CPLCalloc(sizeof(OGRSpatialReferenceH), nMatches + 1));
   12043          12 :         for (int i = 0; i < nMatches; ++i)
   12044             :         {
   12045           9 :             pahRetSorted[i] = pahRet[anIndices[i]];
   12046           9 :             if (ppanMatchConfidence)
   12047           9 :                 (*ppanMatchConfidence)[i] = panConfidence[anIndices[i]];
   12048             :         }
   12049           3 :         CPLFree(pahRet);
   12050           3 :         pahRet = pahRetSorted;
   12051             :     }
   12052             : 
   12053        1601 :     pahRet[nMatches] = nullptr;
   12054        1601 :     proj_list_destroy(list);
   12055        1601 :     proj_int_list_destroy(panConfidence);
   12056             : 
   12057        1601 :     return pahRet;
   12058             : }
   12059             : 
   12060             : /************************************************************************/
   12061             : /*                          importFromEPSGA()                           */
   12062             : /************************************************************************/
   12063             : 
   12064             : /**
   12065             :  * \brief  Initialize SRS based on EPSG geographic, projected or vertical CRS
   12066             :  * code.
   12067             :  *
   12068             :  * This method will initialize the spatial reference based on the
   12069             :  * passed in EPSG CRS code found in the PROJ database.
   12070             :  *
   12071             :  * Since GDAL 3.0, this method is identical to importFromEPSG().
   12072             :  *
   12073             :  * Before GDAL 3.0.3, this method would try to attach a 3-parameter or
   12074             :  * 7-parameter Helmert transformation to WGS84 when there is one and only one
   12075             :  * such method available for the CRS. This behavior might not always be
   12076             :  * desirable, so starting with GDAL 3.0.3, this is no longer done unless
   12077             :  * the OSR_ADD_TOWGS84_ON_IMPORT_FROM_EPSG configuration option is set to YES.
   12078             :  * The AddGuessedTOWGS84() method can also be used for that purpose.
   12079             :  *
   12080             :  * The method will also by default substitute a deprecated EPSG code by its
   12081             :  * non-deprecated replacement. If this behavior is not desired, the
   12082             :  * OSR_USE_NON_DEPRECATED configuration option can be set to NO.
   12083             :  *
   12084             :  * This method is the same as the C function OSRImportFromEPSGA().
   12085             :  *
   12086             :  * @param nCode a CRS code.
   12087             :  *
   12088             :  * @return OGRERR_NONE on success, or an error code on failure.
   12089             :  */
   12090             : 
   12091       50126 : OGRErr OGRSpatialReference::importFromEPSGA(int nCode)
   12092             : 
   12093             : {
   12094      100252 :     TAKE_OPTIONAL_LOCK();
   12095             : 
   12096       50126 :     Clear();
   12097             : 
   12098             :     const char *pszUseNonDeprecated =
   12099       50126 :         CPLGetConfigOption("OSR_USE_NON_DEPRECATED", nullptr);
   12100             :     const bool bUseNonDeprecated =
   12101       50126 :         CPLTestBool(pszUseNonDeprecated ? pszUseNonDeprecated : "YES");
   12102       50126 :     const bool bAddTOWGS84 = CPLTestBool(
   12103             :         CPLGetConfigOption("OSR_ADD_TOWGS84_ON_IMPORT_FROM_EPSG", "NO"));
   12104       50126 :     auto tlsCache = OSRGetProjTLSCache();
   12105       50126 :     if (tlsCache)
   12106             :     {
   12107             :         auto cachedObj =
   12108       50126 :             tlsCache->GetPJForEPSGCode(nCode, bUseNonDeprecated, bAddTOWGS84);
   12109       50126 :         if (cachedObj)
   12110             :         {
   12111       39725 :             d->setPjCRS(cachedObj);
   12112       39725 :             return OGRERR_NONE;
   12113             :         }
   12114             :     }
   12115             : 
   12116       20802 :     CPLString osCode;
   12117       10401 :     osCode.Printf("%d", nCode);
   12118             :     PJ *obj;
   12119       10401 :     constexpr int FIRST_NON_DEPRECATED_ESRI_CODE = 53001;
   12120       10401 :     if (nCode < FIRST_NON_DEPRECATED_ESRI_CODE)
   12121             :     {
   12122       10396 :         obj = proj_create_from_database(d->getPROJContext(), "EPSG",
   12123             :                                         osCode.c_str(), PJ_CATEGORY_CRS, true,
   12124             :                                         nullptr);
   12125       10396 :         if (!obj)
   12126             :         {
   12127          25 :             return OGRERR_FAILURE;
   12128             :         }
   12129             :     }
   12130             :     else
   12131             :     {
   12132             :         // Likely to be an ESRI CRS...
   12133           5 :         CPLErr eLastErrorType = CE_None;
   12134           5 :         CPLErrorNum eLastErrorNum = CPLE_None;
   12135           5 :         std::string osLastErrorMsg;
   12136           5 :         bool bIsESRI = false;
   12137             :         {
   12138          10 :             CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
   12139           5 :             CPLErrorReset();
   12140           5 :             obj = proj_create_from_database(d->getPROJContext(), "EPSG",
   12141             :                                             osCode.c_str(), PJ_CATEGORY_CRS,
   12142             :                                             true, nullptr);
   12143           5 :             if (!obj)
   12144             :             {
   12145           2 :                 eLastErrorType = CPLGetLastErrorType();
   12146           2 :                 eLastErrorNum = CPLGetLastErrorNo();
   12147           2 :                 osLastErrorMsg = CPLGetLastErrorMsg();
   12148           2 :                 obj = proj_create_from_database(d->getPROJContext(), "ESRI",
   12149             :                                                 osCode.c_str(), PJ_CATEGORY_CRS,
   12150             :                                                 true, nullptr);
   12151           2 :                 if (obj)
   12152           1 :                     bIsESRI = true;
   12153             :             }
   12154             :         }
   12155           5 :         if (!obj)
   12156             :         {
   12157           1 :             if (eLastErrorType != CE_None)
   12158           1 :                 CPLError(eLastErrorType, eLastErrorNum, "%s",
   12159             :                          osLastErrorMsg.c_str());
   12160           1 :             return OGRERR_FAILURE;
   12161             :         }
   12162           4 :         if (bIsESRI)
   12163             :         {
   12164           1 :             CPLError(CE_Warning, CPLE_AppDefined,
   12165             :                      "EPSG:%d is not a valid CRS code, but ESRI:%d is. "
   12166             :                      "Assuming ESRI:%d was meant",
   12167             :                      nCode, nCode, nCode);
   12168             :         }
   12169             :     }
   12170             : 
   12171       10375 :     if (bUseNonDeprecated && proj_is_deprecated(obj))
   12172             :     {
   12173         410 :         auto list = proj_get_non_deprecated(d->getPROJContext(), obj);
   12174         410 :         if (list)
   12175             :         {
   12176         410 :             const auto count = proj_list_get_count(list);
   12177         410 :             if (count == 1)
   12178             :             {
   12179             :                 auto nonDeprecated =
   12180         359 :                     proj_list_get(d->getPROJContext(), list, 0);
   12181         359 :                 if (nonDeprecated)
   12182             :                 {
   12183         359 :                     if (pszUseNonDeprecated == nullptr)
   12184             :                     {
   12185             :                         const char *pszNewAuth =
   12186         359 :                             proj_get_id_auth_name(nonDeprecated, 0);
   12187             :                         const char *pszNewCode =
   12188         359 :                             proj_get_id_code(nonDeprecated, 0);
   12189         359 :                         CPLError(CE_Warning, CPLE_AppDefined,
   12190             :                                  "CRS EPSG:%d is deprecated. "
   12191             :                                  "Its non-deprecated replacement %s:%s "
   12192             :                                  "will be used instead. "
   12193             :                                  "To use the original CRS, set the "
   12194             :                                  "OSR_USE_NON_DEPRECATED "
   12195             :                                  "configuration option to NO.",
   12196             :                                  nCode, pszNewAuth ? pszNewAuth : "(null)",
   12197             :                                  pszNewCode ? pszNewCode : "(null)");
   12198             :                     }
   12199         359 :                     proj_destroy(obj);
   12200         359 :                     obj = nonDeprecated;
   12201             :                 }
   12202             :             }
   12203             :         }
   12204         410 :         proj_list_destroy(list);
   12205             :     }
   12206             : 
   12207       10375 :     if (bAddTOWGS84)
   12208             :     {
   12209           1 :         auto boundCRS = proj_crs_create_bound_crs_to_WGS84(d->getPROJContext(),
   12210             :                                                            obj, nullptr);
   12211           1 :         if (boundCRS)
   12212             :         {
   12213           1 :             proj_destroy(obj);
   12214           1 :             obj = boundCRS;
   12215             :         }
   12216             :     }
   12217             : 
   12218       10375 :     d->setPjCRS(obj);
   12219             : 
   12220       10375 :     if (tlsCache)
   12221             :     {
   12222       10375 :         tlsCache->CachePJForEPSGCode(nCode, bUseNonDeprecated, bAddTOWGS84,
   12223             :                                      obj);
   12224             :     }
   12225             : 
   12226       10375 :     return OGRERR_NONE;
   12227             : }
   12228             : 
   12229             : /************************************************************************/
   12230             : /*                         AddGuessedTOWGS84()                          */
   12231             : /************************************************************************/
   12232             : 
   12233             : /**
   12234             :  * \brief  Try to add a a 3-parameter or 7-parameter Helmert transformation
   12235             :  * to WGS84.
   12236             :  *
   12237             :  * This method try to attach a 3-parameter or 7-parameter Helmert transformation
   12238             :  * to WGS84 when there is one and only one such method available for the CRS.
   12239             :  * Note: this is more restrictive to how GDAL < 3 worked.
   12240             :  *
   12241             :  * This method is the same as the C function OSRAddGuessedTOWGS84().
   12242             :  *
   12243             :  * @return OGRERR_NONE on success, or an error code on failure (the CRS has
   12244             :  * already a transformation to WGS84 or none matching could be found).
   12245             :  *
   12246             :  * @since GDAL 3.0.3
   12247             :  */
   12248          18 : OGRErr OGRSpatialReference::AddGuessedTOWGS84()
   12249             : {
   12250          36 :     TAKE_OPTIONAL_LOCK();
   12251             : 
   12252          18 :     d->refreshProjObj();
   12253          18 :     if (!d->m_pj_crs)
   12254           0 :         return OGRERR_FAILURE;
   12255          18 :     auto boundCRS = GDAL_proj_crs_create_bound_crs_to_WGS84(
   12256          18 :         d->getPROJContext(), d->m_pj_crs, false, true);
   12257          18 :     if (!boundCRS)
   12258             :     {
   12259           0 :         return OGRERR_FAILURE;
   12260             :     }
   12261          18 :     d->setPjCRS(boundCRS);
   12262          18 :     return OGRERR_NONE;
   12263             : }
   12264             : 
   12265             : /************************************************************************/
   12266             : /*                         OSRImportFromEPSGA()                         */
   12267             : /************************************************************************/
   12268             : 
   12269             : /**
   12270             :  * \brief  Try to add a a 3-parameter or 7-parameter Helmert transformation
   12271             :  * to WGS84.
   12272             :  *
   12273             :  * This function is the same as OGRSpatialReference::AddGuessedTOWGS84().
   12274             :  *
   12275             :  * @since GDAL 3.0.3
   12276             :  */
   12277             : 
   12278           2 : OGRErr OSRAddGuessedTOWGS84(OGRSpatialReferenceH hSRS)
   12279             : 
   12280             : {
   12281           2 :     VALIDATE_POINTER1(hSRS, "OSRAddGuessedTOWGS84", OGRERR_FAILURE);
   12282             : 
   12283           2 :     return OGRSpatialReference::FromHandle(hSRS)->AddGuessedTOWGS84();
   12284             : }
   12285             : 
   12286             : /************************************************************************/
   12287             : /*                         OSRImportFromEPSGA()                         */
   12288             : /************************************************************************/
   12289             : 
   12290             : /**
   12291             :  * \brief  Initialize SRS based on EPSG geographic, projected or vertical CRS
   12292             :  * code.
   12293             :  *
   12294             :  * This function is the same as OGRSpatialReference::importFromEPSGA().
   12295             :  */
   12296             : 
   12297           3 : OGRErr CPL_STDCALL OSRImportFromEPSGA(OGRSpatialReferenceH hSRS, int nCode)
   12298             : 
   12299             : {
   12300           3 :     VALIDATE_POINTER1(hSRS, "OSRImportFromEPSGA", OGRERR_FAILURE);
   12301             : 
   12302           3 :     return OGRSpatialReference::FromHandle(hSRS)->importFromEPSGA(nCode);
   12303             : }
   12304             : 
   12305             : /************************************************************************/
   12306             : /*                           importFromEPSG()                           */
   12307             : /************************************************************************/
   12308             : 
   12309             : /**
   12310             :  * \brief  Initialize SRS based on EPSG geographic, projected or vertical CRS
   12311             :  * code.
   12312             :  *
   12313             :  * This method will initialize the spatial reference based on the
   12314             :  * passed in EPSG CRS code found in the PROJ database.
   12315             :  *
   12316             :  * This method is the same as the C function OSRImportFromEPSG().
   12317             :  *
   12318             :  * Before GDAL 3.0.3, this method would try to attach a 3-parameter or
   12319             :  * 7-parameter Helmert transformation to WGS84 when there is one and only one
   12320             :  * such method available for the CRS. This behavior might not always be
   12321             :  * desirable, so starting with GDAL 3.0.3, this is no longer done unless
   12322             :  * the OSR_ADD_TOWGS84_ON_IMPORT_FROM_EPSG configuration option is set to YES.
   12323             :  *
   12324             :  * @param nCode a GCS or PCS code from the horizontal coordinate system table.
   12325             :  *
   12326             :  * @return OGRERR_NONE on success, or an error code on failure.
   12327             :  */
   12328             : 
   12329       43685 : OGRErr OGRSpatialReference::importFromEPSG(int nCode)
   12330             : 
   12331             : {
   12332       43685 :     return importFromEPSGA(nCode);
   12333             : }
   12334             : 
   12335             : /************************************************************************/
   12336             : /*                         OSRImportFromEPSG()                          */
   12337             : /************************************************************************/
   12338             : 
   12339             : /**
   12340             :  * \brief  Initialize SRS based on EPSG geographic, projected or vertical CRS
   12341             :  * code.
   12342             :  *
   12343             :  * This function is the same as OGRSpatialReference::importFromEPSG().
   12344             :  */
   12345             : 
   12346        1532 : OGRErr CPL_STDCALL OSRImportFromEPSG(OGRSpatialReferenceH hSRS, int nCode)
   12347             : 
   12348             : {
   12349        1532 :     VALIDATE_POINTER1(hSRS, "OSRImportFromEPSG", OGRERR_FAILURE);
   12350             : 
   12351        1532 :     return OGRSpatialReference::FromHandle(hSRS)->importFromEPSG(nCode);
   12352             : }
   12353             : 
   12354             : /************************************************************************/
   12355             : /*                        EPSGTreatsAsLatLong()                         */
   12356             : /************************************************************************/
   12357             : 
   12358             : /**
   12359             :  * \brief This method returns TRUE if this geographic coordinate
   12360             :  * system should be treated as having lat/long coordinate ordering.
   12361             :  *
   12362             :  * Currently this returns TRUE for all geographic coordinate systems
   12363             :  * with axes set defining it as lat, long (prior to GDAL 3.10, it
   12364             :  * also checked that the CRS had belonged to EPSG authority, but this check
   12365             :  * has now been removed).
   12366             :  *
   12367             :  * \note Important change of behavior since GDAL 3.0. In previous versions,
   12368             :  * geographic CRS imported with importFromEPSG() would cause this method to
   12369             :  * return FALSE on them, whereas now it returns TRUE, since importFromEPSG()
   12370             :  * is now equivalent to importFromEPSGA().
   12371             :  *
   12372             :  * FALSE will be returned for all coordinate systems that are not geographic,
   12373             :  * or whose axes ordering is not latitude, longitude.
   12374             :  *
   12375             :  * This method is the same as the C function OSREPSGTreatsAsLatLong().
   12376             :  *
   12377             :  * @return TRUE or FALSE.
   12378             :  */
   12379             : 
   12380        1302 : int OGRSpatialReference::EPSGTreatsAsLatLong() const
   12381             : 
   12382             : {
   12383        2604 :     TAKE_OPTIONAL_LOCK();
   12384             : 
   12385        1302 :     if (!IsGeographic())
   12386         866 :         return FALSE;
   12387             : 
   12388         436 :     d->demoteFromBoundCRS();
   12389             : 
   12390         436 :     bool ret = false;
   12391         436 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
   12392             :     {
   12393             :         auto horizCRS =
   12394          17 :             proj_crs_get_sub_crs(d->getPROJContext(), d->m_pj_crs, 0);
   12395          17 :         if (horizCRS)
   12396             :         {
   12397             :             auto cs =
   12398          17 :                 proj_crs_get_coordinate_system(d->getPROJContext(), horizCRS);
   12399          17 :             if (cs)
   12400             :             {
   12401          17 :                 const char *pszDirection = nullptr;
   12402          17 :                 if (proj_cs_get_axis_info(d->getPROJContext(), cs, 0, nullptr,
   12403             :                                           nullptr, &pszDirection, nullptr,
   12404          17 :                                           nullptr, nullptr, nullptr))
   12405             :                 {
   12406          17 :                     if (EQUAL(pszDirection, "north"))
   12407             :                     {
   12408          17 :                         ret = true;
   12409             :                     }
   12410             :                 }
   12411             : 
   12412          17 :                 proj_destroy(cs);
   12413             :             }
   12414             : 
   12415          17 :             proj_destroy(horizCRS);
   12416             :         }
   12417             :     }
   12418             :     else
   12419             :     {
   12420             :         auto cs =
   12421         419 :             proj_crs_get_coordinate_system(d->getPROJContext(), d->m_pj_crs);
   12422         419 :         if (cs)
   12423             :         {
   12424         419 :             const char *pszDirection = nullptr;
   12425         419 :             if (proj_cs_get_axis_info(d->getPROJContext(), cs, 0, nullptr,
   12426             :                                       nullptr, &pszDirection, nullptr, nullptr,
   12427         419 :                                       nullptr, nullptr))
   12428             :             {
   12429         419 :                 if (EQUAL(pszDirection, "north"))
   12430             :                 {
   12431         372 :                     ret = true;
   12432             :                 }
   12433             :             }
   12434             : 
   12435         419 :             proj_destroy(cs);
   12436             :         }
   12437             :     }
   12438         436 :     d->undoDemoteFromBoundCRS();
   12439             : 
   12440         436 :     return ret;
   12441             : }
   12442             : 
   12443             : /************************************************************************/
   12444             : /*                       OSREPSGTreatsAsLatLong()                       */
   12445             : /************************************************************************/
   12446             : 
   12447             : /**
   12448             :  * \brief This function returns TRUE if this geographic coordinate
   12449             :  * system should be treated as having lat/long coordinate ordering.
   12450             :  *
   12451             :  * This function is the same as OGRSpatialReference::OSREPSGTreatsAsLatLong().
   12452             :  */
   12453             : 
   12454         208 : int OSREPSGTreatsAsLatLong(OGRSpatialReferenceH hSRS)
   12455             : 
   12456             : {
   12457         208 :     VALIDATE_POINTER1(hSRS, "OSREPSGTreatsAsLatLong", OGRERR_FAILURE);
   12458             : 
   12459         208 :     return OGRSpatialReference::FromHandle(hSRS)->EPSGTreatsAsLatLong();
   12460             : }
   12461             : 
   12462             : /************************************************************************/
   12463             : /*                    EPSGTreatsAsNorthingEasting()                     */
   12464             : /************************************************************************/
   12465             : 
   12466             : /**
   12467             :  * \brief This method returns TRUE if this projected coordinate
   12468             :  * system should be treated as having northing/easting coordinate ordering.
   12469             :  *
   12470             :  * Currently this returns TRUE for all projected coordinate systems
   12471             :  * with axes set defining it as northing, easting (prior to GDAL 3.10, it
   12472             :  * also checked that the CRS had belonged to EPSG authority, but this check
   12473             :  * has now been removed).
   12474             :  *
   12475             :  * \note Important change of behavior since GDAL 3.0. In previous versions,
   12476             :  * projected CRS with northing, easting axis order imported with
   12477             :  * importFromEPSG() would cause this method to
   12478             :  * return FALSE on them, whereas now it returns TRUE, since importFromEPSG()
   12479             :  * is now equivalent to importFromEPSGA().
   12480             :  *
   12481             :  * FALSE will be returned for all coordinate systems that are not projected,
   12482             :  * or whose axes ordering is not northing, easting.
   12483             :  *
   12484             :  * This method is the same as the C function EPSGTreatsAsNorthingEasting().
   12485             :  *
   12486             :  * @return TRUE or FALSE.
   12487             :  *
   12488             :  */
   12489             : 
   12490         953 : int OGRSpatialReference::EPSGTreatsAsNorthingEasting() const
   12491             : 
   12492             : {
   12493        1906 :     TAKE_OPTIONAL_LOCK();
   12494             : 
   12495         953 :     if (!IsProjected())
   12496          49 :         return FALSE;
   12497             : 
   12498         904 :     d->demoteFromBoundCRS();
   12499             :     PJ *projCRS;
   12500         904 :     const auto ctxt = d->getPROJContext();
   12501         904 :     if (d->m_pjType == PJ_TYPE_COMPOUND_CRS)
   12502             :     {
   12503           4 :         projCRS = proj_crs_get_sub_crs(ctxt, d->m_pj_crs, 0);
   12504           4 :         if (!projCRS || proj_get_type(projCRS) != PJ_TYPE_PROJECTED_CRS)
   12505             :         {
   12506           0 :             d->undoDemoteFromBoundCRS();
   12507           0 :             proj_destroy(projCRS);
   12508           0 :             return FALSE;
   12509             :         }
   12510             :     }
   12511             :     else
   12512             :     {
   12513         900 :         projCRS = proj_clone(ctxt, d->m_pj_crs);
   12514             :     }
   12515             : 
   12516         904 :     bool ret = false;
   12517         904 :     auto cs = proj_crs_get_coordinate_system(ctxt, projCRS);
   12518         904 :     proj_destroy(projCRS);
   12519         904 :     d->undoDemoteFromBoundCRS();
   12520             : 
   12521         904 :     if (cs)
   12522             :     {
   12523         904 :         ret = isNorthEastAxisOrder(ctxt, cs);
   12524         904 :         proj_destroy(cs);
   12525             :     }
   12526             : 
   12527         904 :     return ret;
   12528             : }
   12529             : 
   12530             : /************************************************************************/
   12531             : /*                   OSREPSGTreatsAsNorthingEasting()                   */
   12532             : /************************************************************************/
   12533             : 
   12534             : /**
   12535             :  * \brief This function returns TRUE if this projected coordinate
   12536             :  * system should be treated as having northing/easting coordinate ordering.
   12537             :  *
   12538             :  * This function is the same as
   12539             :  * OGRSpatialReference::EPSGTreatsAsNorthingEasting().
   12540             :  *
   12541             :  */
   12542             : 
   12543         215 : int OSREPSGTreatsAsNorthingEasting(OGRSpatialReferenceH hSRS)
   12544             : 
   12545             : {
   12546         215 :     VALIDATE_POINTER1(hSRS, "OSREPSGTreatsAsNorthingEasting", OGRERR_FAILURE);
   12547             : 
   12548         215 :     return OGRSpatialReference::FromHandle(hSRS)->EPSGTreatsAsNorthingEasting();
   12549             : }
   12550             : 
   12551             : /************************************************************************/
   12552             : /*                     ImportFromESRIWisconsinWKT()                     */
   12553             : /*                                                                      */
   12554             : /*      Search a ESRI State Plane WKT and import it.                    */
   12555             : /************************************************************************/
   12556             : 
   12557             : // This is only used by the HFA driver and somewhat dubious we really need that
   12558             : // Coming from an old ESRI merge
   12559             : 
   12560           1 : OGRErr OGRSpatialReference::ImportFromESRIWisconsinWKT(const char *prjName,
   12561             :                                                        double centralMeridian,
   12562             :                                                        double latOfOrigin,
   12563             :                                                        const char *unitsName,
   12564             :                                                        const char *crsName)
   12565             : {
   12566           2 :     TAKE_OPTIONAL_LOCK();
   12567             : 
   12568           1 :     if (centralMeridian < -93 || centralMeridian > -87)
   12569           0 :         return OGRERR_FAILURE;
   12570           1 :     if (latOfOrigin < 40 || latOfOrigin > 47)
   12571           0 :         return OGRERR_FAILURE;
   12572             : 
   12573             :     // If the CS name is known.
   12574           1 :     if (!prjName && !unitsName && crsName)
   12575             :     {
   12576           0 :         const PJ_TYPE type = PJ_TYPE_PROJECTED_CRS;
   12577           0 :         PJ_OBJ_LIST *list = proj_create_from_name(
   12578             :             d->getPROJContext(), "ESRI", crsName, &type, 1, false, 1, nullptr);
   12579           0 :         if (list)
   12580             :         {
   12581           0 :             if (proj_list_get_count(list) == 1)
   12582             :             {
   12583           0 :                 auto crs = proj_list_get(d->getPROJContext(), list, 0);
   12584           0 :                 if (crs)
   12585             :                 {
   12586           0 :                     Clear();
   12587           0 :                     d->setPjCRS(crs);
   12588           0 :                     proj_list_destroy(list);
   12589           0 :                     return OGRERR_NONE;
   12590             :                 }
   12591             :             }
   12592           0 :             proj_list_destroy(list);
   12593             :         }
   12594           0 :         return OGRERR_FAILURE;
   12595             :     }
   12596             : 
   12597           1 :     if (prjName == nullptr || unitsName == nullptr)
   12598             :     {
   12599           0 :         return OGRERR_FAILURE;
   12600             :     }
   12601             : 
   12602           1 :     const PJ_TYPE type = PJ_TYPE_PROJECTED_CRS;
   12603           1 :     PJ_OBJ_LIST *list = proj_create_from_name(d->getPROJContext(), "ESRI",
   12604             :                                               "NAD_1983_HARN_WISCRS_", &type, 1,
   12605             :                                               true, 0, nullptr);
   12606           1 :     if (list)
   12607             :     {
   12608           1 :         const auto listSize = proj_list_get_count(list);
   12609           8 :         for (int i = 0; i < listSize; i++)
   12610             :         {
   12611           8 :             auto crs = proj_list_get(d->getPROJContext(), list, i);
   12612           8 :             if (!crs)
   12613             :             {
   12614           7 :                 continue;
   12615             :             }
   12616             : 
   12617           8 :             auto conv = proj_crs_get_coordoperation(d->getPROJContext(), crs);
   12618           8 :             if (!conv)
   12619             :             {
   12620           0 :                 proj_destroy(crs);
   12621           0 :                 continue;
   12622             :             }
   12623           8 :             const char *pszMethodCode = nullptr;
   12624           8 :             proj_coordoperation_get_method_info(
   12625             :                 d->getPROJContext(), conv, nullptr, nullptr, &pszMethodCode);
   12626           8 :             const int nMethodCode = atoi(pszMethodCode ? pszMethodCode : "0");
   12627           8 :             if (!((EQUAL(prjName, SRS_PT_TRANSVERSE_MERCATOR) &&
   12628             :                    nMethodCode == EPSG_CODE_METHOD_TRANSVERSE_MERCATOR) ||
   12629           3 :                   (EQUAL(prjName, "Lambert_Conformal_Conic") &&
   12630             :                    nMethodCode ==
   12631             :                        EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP)))
   12632             :             {
   12633           3 :                 proj_destroy(crs);
   12634           3 :                 proj_destroy(conv);
   12635           3 :                 continue;
   12636             :             }
   12637             : 
   12638             :             auto coordSys =
   12639           5 :                 proj_crs_get_coordinate_system(d->getPROJContext(), crs);
   12640           5 :             if (!coordSys)
   12641             :             {
   12642           0 :                 proj_destroy(crs);
   12643           0 :                 proj_destroy(conv);
   12644           0 :                 continue;
   12645             :             }
   12646             : 
   12647           5 :             double dfConvFactor = 0.0;
   12648           5 :             proj_cs_get_axis_info(d->getPROJContext(), coordSys, 0, nullptr,
   12649             :                                   nullptr, nullptr, &dfConvFactor, nullptr,
   12650             :                                   nullptr, nullptr);
   12651           5 :             proj_destroy(coordSys);
   12652             : 
   12653           6 :             if ((EQUAL(unitsName, "meters") && dfConvFactor != 1.0) ||
   12654           1 :                 (!EQUAL(unitsName, "meters") &&
   12655           0 :                  std::fabs(dfConvFactor - CPLAtof(SRS_UL_US_FOOT_CONV)) >
   12656             :                      1e-10))
   12657             :             {
   12658           4 :                 proj_destroy(crs);
   12659           4 :                 proj_destroy(conv);
   12660           4 :                 continue;
   12661             :             }
   12662             : 
   12663           1 :             int idx_lat = proj_coordoperation_get_param_index(
   12664             :                 d->getPROJContext(), conv,
   12665             :                 EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN);
   12666           1 :             double valueLat = -1000;
   12667           1 :             proj_coordoperation_get_param(d->getPROJContext(), conv, idx_lat,
   12668             :                                           nullptr, nullptr, nullptr, &valueLat,
   12669             :                                           nullptr, nullptr, nullptr, nullptr,
   12670             :                                           nullptr, nullptr);
   12671           1 :             int idx_lon = proj_coordoperation_get_param_index(
   12672             :                 d->getPROJContext(), conv,
   12673             :                 EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN);
   12674           1 :             double valueLong = -1000;
   12675           1 :             proj_coordoperation_get_param(d->getPROJContext(), conv, idx_lon,
   12676             :                                           nullptr, nullptr, nullptr, &valueLong,
   12677             :                                           nullptr, nullptr, nullptr, nullptr,
   12678             :                                           nullptr, nullptr);
   12679           1 :             if (std::fabs(centralMeridian - valueLong) <= 1e-10 &&
   12680           1 :                 std::fabs(latOfOrigin - valueLat) <= 1e-10)
   12681             :             {
   12682           1 :                 Clear();
   12683           1 :                 d->setPjCRS(crs);
   12684           1 :                 proj_list_destroy(list);
   12685           1 :                 proj_destroy(conv);
   12686           1 :                 return OGRERR_NONE;
   12687             :             }
   12688             : 
   12689           0 :             proj_destroy(crs);
   12690           0 :             proj_destroy(conv);
   12691             :         }
   12692           0 :         proj_list_destroy(list);
   12693             :     }
   12694             : 
   12695           0 :     return OGRERR_FAILURE;
   12696             : }
   12697             : 
   12698             : /************************************************************************/
   12699             : /*                       GetAxisMappingStrategy()                       */
   12700             : /************************************************************************/
   12701             : 
   12702             : /** \brief Return the data axis to CRS axis mapping strategy.
   12703             :  *
   12704             :  * <ul>
   12705             :  * <li>OAMS_TRADITIONAL_GIS_ORDER means that for geographic CRS with
   12706             :  *     lat/long order, the data will still be long/lat ordered. Similarly for
   12707             :  *     a projected CRS with northing/easting order, the data will still be
   12708             :  *     easting/northing ordered.
   12709             :  * <li>OAMS_AUTHORITY_COMPLIANT means that the data axis will be identical to
   12710             :  *     the CRS axis.
   12711             :  * <li>OAMS_CUSTOM means that the data axis are customly defined with
   12712             :  *     SetDataAxisToSRSAxisMapping()
   12713             :  * </ul>
   12714             :  * @return the data axis to CRS axis mapping strategy.
   12715             :  * @since GDAL 3.0
   12716             :  */
   12717          95 : OSRAxisMappingStrategy OGRSpatialReference::GetAxisMappingStrategy() const
   12718             : {
   12719          95 :     TAKE_OPTIONAL_LOCK();
   12720             : 
   12721         190 :     return d->m_axisMappingStrategy;
   12722             : }
   12723             : 
   12724             : /************************************************************************/
   12725             : /*                     OSRGetAxisMappingStrategy()                      */
   12726             : /************************************************************************/
   12727             : 
   12728             : /** \brief Return the data axis to CRS axis mapping strategy.
   12729             :  *
   12730             :  * See OGRSpatialReference::GetAxisMappingStrategy()
   12731             :  * @since GDAL 3.0
   12732             :  */
   12733          37 : OSRAxisMappingStrategy OSRGetAxisMappingStrategy(OGRSpatialReferenceH hSRS)
   12734             : {
   12735          37 :     VALIDATE_POINTER1(hSRS, "OSRGetAxisMappingStrategy", OAMS_CUSTOM);
   12736             : 
   12737          37 :     return OGRSpatialReference::FromHandle(hSRS)->GetAxisMappingStrategy();
   12738             : }
   12739             : 
   12740             : /************************************************************************/
   12741             : /*                       SetAxisMappingStrategy()                       */
   12742             : /************************************************************************/
   12743             : 
   12744             : /** \brief Set the data axis to CRS axis mapping strategy.
   12745             :  *
   12746             :  * Starting with GDAL 3.5, the OSR_DEFAULT_AXIS_MAPPING_STRATEGY configuration
   12747             :  * option can be set to "TRADITIONAL_GIS_ORDER" / "AUTHORITY_COMPLIANT" (the
   12748             :  * later being the default value when the option is not set) to control the
   12749             :  * value of the data axis to CRS axis mapping strategy when a
   12750             :  * OSRSpatialReference object is created. Calling SetAxisMappingStrategy() will
   12751             :  * override this default value.
   12752             :  *
   12753             :  * See OGRSpatialReference::GetAxisMappingStrategy()
   12754             :  * @since GDAL 3.0
   12755             :  */
   12756       95443 : void OGRSpatialReference::SetAxisMappingStrategy(
   12757             :     OSRAxisMappingStrategy strategy)
   12758             : {
   12759      190886 :     TAKE_OPTIONAL_LOCK();
   12760             : 
   12761       95443 :     d->m_axisMappingStrategy = strategy;
   12762       95443 :     d->refreshAxisMapping();
   12763       95443 : }
   12764             : 
   12765             : /************************************************************************/
   12766             : /*                     OSRSetAxisMappingStrategy()                      */
   12767             : /************************************************************************/
   12768             : 
   12769             : /** \brief Set the data axis to CRS axis mapping strategy.
   12770             :  *
   12771             :  * See OGRSpatialReference::SetAxisMappingStrategy()
   12772             :  * @since GDAL 3.0
   12773             :  */
   12774         827 : void OSRSetAxisMappingStrategy(OGRSpatialReferenceH hSRS,
   12775             :                                OSRAxisMappingStrategy strategy)
   12776             : {
   12777         827 :     VALIDATE_POINTER0(hSRS, "OSRSetAxisMappingStrategy");
   12778             : 
   12779         827 :     OGRSpatialReference::FromHandle(hSRS)->SetAxisMappingStrategy(strategy);
   12780             : }
   12781             : 
   12782             : /************************************************************************/
   12783             : /*                    GetDataAxisToSRSAxisMapping()                     */
   12784             : /************************************************************************/
   12785             : 
   12786             : /** \brief Return the data axis to SRS axis mapping.
   12787             :  *
   12788             :  * The number of elements of the vector will be the number of axis of the CRS.
   12789             :  * Values start at 1.
   12790             :  *
   12791             :  * If m = GetDataAxisToSRSAxisMapping(), then m[0] is the data axis number
   12792             :  * for the first axis of the CRS.
   12793             :  *
   12794             :  * @since GDAL 3.0
   12795             :  */
   12796    23450100 : const std::vector<int> &OGRSpatialReference::GetDataAxisToSRSAxisMapping() const
   12797             : {
   12798    23450100 :     TAKE_OPTIONAL_LOCK();
   12799             : 
   12800    46900300 :     return d->m_axisMapping;
   12801             : }
   12802             : 
   12803             : /************************************************************************/
   12804             : /*                   OSRGetDataAxisToSRSAxisMapping()                   */
   12805             : /************************************************************************/
   12806             : 
   12807             : /** \brief Return the data axis to SRS axis mapping.
   12808             :  *
   12809             :  * See OGRSpatialReference::GetDataAxisToSRSAxisMapping()
   12810             :  *
   12811             :  * @since GDAL 3.0
   12812             :  */
   12813         105 : const int *OSRGetDataAxisToSRSAxisMapping(OGRSpatialReferenceH hSRS,
   12814             :                                           int *pnCount)
   12815             : {
   12816         105 :     VALIDATE_POINTER1(hSRS, "OSRGetDataAxisToSRSAxisMapping", nullptr);
   12817         105 :     VALIDATE_POINTER1(pnCount, "OSRGetDataAxisToSRSAxisMapping", nullptr);
   12818             : 
   12819             :     const auto &v =
   12820         105 :         OGRSpatialReference::FromHandle(hSRS)->GetDataAxisToSRSAxisMapping();
   12821         105 :     *pnCount = static_cast<int>(v.size());
   12822         105 :     return v.data();
   12823             : }
   12824             : 
   12825             : /************************************************************************/
   12826             : /*                    SetDataAxisToSRSAxisMapping()                     */
   12827             : /************************************************************************/
   12828             : 
   12829             : /** \brief Set a custom data axis to CRS axis mapping.
   12830             :  *
   12831             :  * The number of elements of the mapping vector should be the number of axis
   12832             :  * of the CRS (as returned by GetAxesCount()) (although this method does not
   12833             :  * check that, beyond checking there are at least 2 elements, so that this
   12834             :  * method and setting the CRS can be done in any order).
   12835             :  * This is taken into account by OGRCoordinateTransformation to transform the
   12836             :  * order of coordinates to the order expected by the CRS before
   12837             :  * transformation, and back to the data order after transformation.
   12838             :  *
   12839             :  * The mapping[i] value (one based) represents the data axis number for the i(th)
   12840             :  * axis of the CRS. A negative value can also be used to ask for a sign
   12841             :  * reversal during coordinate transformation (to deal with northing vs southing,
   12842             :  * easting vs westing, heights vs depths).
   12843             :  *
   12844             :  * When used with OGRCoordinateTransformation,
   12845             :  * - the only valid values for mapping[0] (data axis number for the first axis
   12846             :  *   of the CRS) are 1, 2, -1, -2.
   12847             :  * - the only valid values for mapping[1] (data axis number for the second axis
   12848             :  *   of the CRS) are 1, 2, -1, -2.
   12849             :  *  - the only valid values mapping[2] are 3 or -3.
   12850             :  * Note: this method does not validate the values of mapping[].
   12851             :  *
   12852             :  * mapping=[2,1] typically expresses the inversion of axis between the data
   12853             :  * axis and the CRS axis for a 2D CRS.
   12854             :  *
   12855             :  * Automatically implies SetAxisMappingStrategy(OAMS_CUSTOM)
   12856             :  *
   12857             :  * This is the same as the C function OSRSetDataAxisToSRSAxisMapping().
   12858             :  *
   12859             :  * @param mapping The new data axis to CRS axis mapping.
   12860             :  *
   12861             :  * @since GDAL 3.0
   12862             :  * @see OGRSpatialReference::GetDataAxisToSRSAxisMapping()
   12863             :  */
   12864       10535 : OGRErr OGRSpatialReference::SetDataAxisToSRSAxisMapping(
   12865             :     const std::vector<int> &mapping)
   12866             : {
   12867       21070 :     TAKE_OPTIONAL_LOCK();
   12868             : 
   12869       10535 :     if (mapping.size() < 2)
   12870           0 :         return OGRERR_FAILURE;
   12871       10535 :     d->m_axisMappingStrategy = OAMS_CUSTOM;
   12872       10535 :     d->m_axisMapping = mapping;
   12873       10535 :     return OGRERR_NONE;
   12874             : }
   12875             : 
   12876             : /************************************************************************/
   12877             : /*                   OSRSetDataAxisToSRSAxisMapping()                   */
   12878             : /************************************************************************/
   12879             : 
   12880             : /** \brief Set a custom data axis to CRS axis mapping.
   12881             :  *
   12882             :  * Automatically implies SetAxisMappingStrategy(OAMS_CUSTOM)
   12883             :  *
   12884             :  * This is the same as the C++ method
   12885             :  * OGRSpatialReference::SetDataAxisToSRSAxisMapping()
   12886             :  *
   12887             :  * @since GDAL 3.1
   12888             :  */
   12889          16 : OGRErr OSRSetDataAxisToSRSAxisMapping(OGRSpatialReferenceH hSRS,
   12890             :                                       int nMappingSize, const int *panMapping)
   12891             : {
   12892          16 :     VALIDATE_POINTER1(hSRS, "OSRSetDataAxisToSRSAxisMapping", OGRERR_FAILURE);
   12893          16 :     VALIDATE_POINTER1(panMapping, "OSRSetDataAxisToSRSAxisMapping",
   12894             :                       OGRERR_FAILURE);
   12895             : 
   12896          16 :     if (nMappingSize < 0)
   12897           0 :         return OGRERR_FAILURE;
   12898             : 
   12899          32 :     std::vector<int> mapping(nMappingSize);
   12900          16 :     if (nMappingSize)
   12901          16 :         memcpy(&mapping[0], panMapping, nMappingSize * sizeof(int));
   12902          16 :     return OGRSpatialReference::FromHandle(hSRS)->SetDataAxisToSRSAxisMapping(
   12903          16 :         mapping);
   12904             : }
   12905             : 
   12906             : /************************************************************************/
   12907             : /*                            GetAreaOfUse()                            */
   12908             : /************************************************************************/
   12909             : 
   12910             : /** \brief Return the area of use of the CRS.
   12911             :  *
   12912             :  * This method is the same as the OSRGetAreaOfUse() function.
   12913             :  *
   12914             :  * @param pdfWestLongitudeDeg Pointer to a double to receive the western-most
   12915             :  * longitude, expressed in degree. Might be NULL. If the returned value is
   12916             :  * -1000, the bounding box is unknown.
   12917             :  * @param pdfSouthLatitudeDeg Pointer to a double to receive the southern-most
   12918             :  * latitude, expressed in degree. Might be NULL. If the returned value is -1000,
   12919             :  * the bounding box is unknown.
   12920             :  * @param pdfEastLongitudeDeg Pointer to a double to receive the eastern-most
   12921             :  * longitude, expressed in degree. Might be NULL. If the returned value is
   12922             :  * -1000, the bounding box is unknown.
   12923             :  * @param pdfNorthLatitudeDeg Pointer to a double to receive the northern-most
   12924             :  * latitude, expressed in degree. Might be NULL. If the returned value is -1000,
   12925             :  * the bounding box is unknown.
   12926             :  * @param ppszAreaName Pointer to a string to receive the name of the area of
   12927             :  * use. Might be NULL. Note that *ppszAreaName is short-lived and might be
   12928             :  * invalidated by further calls.
   12929             :  * @return true in case of success
   12930             :  * @since GDAL 3.0
   12931             :  */
   12932          82 : bool OGRSpatialReference::GetAreaOfUse(double *pdfWestLongitudeDeg,
   12933             :                                        double *pdfSouthLatitudeDeg,
   12934             :                                        double *pdfEastLongitudeDeg,
   12935             :                                        double *pdfNorthLatitudeDeg,
   12936             :                                        const char **ppszAreaName) const
   12937             : {
   12938         164 :     TAKE_OPTIONAL_LOCK();
   12939             : 
   12940          82 :     d->refreshProjObj();
   12941          82 :     if (!d->m_pj_crs)
   12942             :     {
   12943           0 :         return false;
   12944             :     }
   12945          82 :     d->demoteFromBoundCRS();
   12946          82 :     const char *pszAreaName = nullptr;
   12947          82 :     int bSuccess = proj_get_area_of_use(
   12948          82 :         d->getPROJContext(), d->m_pj_crs, pdfWestLongitudeDeg,
   12949             :         pdfSouthLatitudeDeg, pdfEastLongitudeDeg, pdfNorthLatitudeDeg,
   12950             :         &pszAreaName);
   12951          82 :     d->undoDemoteFromBoundCRS();
   12952          82 :     d->m_osAreaName = pszAreaName ? pszAreaName : "";
   12953          82 :     if (ppszAreaName)
   12954          28 :         *ppszAreaName = d->m_osAreaName.c_str();
   12955          82 :     return CPL_TO_BOOL(bSuccess);
   12956             : }
   12957             : 
   12958             : /************************************************************************/
   12959             : /*                            GetAreaOfUse()                            */
   12960             : /************************************************************************/
   12961             : 
   12962             : /** \brief Return the area of use of the CRS.
   12963             :  *
   12964             :  * This function is the same as the OGRSpatialReference::GetAreaOfUse() method.
   12965             :  *
   12966             :  * @since GDAL 3.0
   12967             :  */
   12968           1 : int OSRGetAreaOfUse(OGRSpatialReferenceH hSRS, double *pdfWestLongitudeDeg,
   12969             :                     double *pdfSouthLatitudeDeg, double *pdfEastLongitudeDeg,
   12970             :                     double *pdfNorthLatitudeDeg, const char **ppszAreaName)
   12971             : {
   12972           1 :     VALIDATE_POINTER1(hSRS, "OSRGetAreaOfUse", FALSE);
   12973             : 
   12974           1 :     return OGRSpatialReference::FromHandle(hSRS)->GetAreaOfUse(
   12975             :         pdfWestLongitudeDeg, pdfSouthLatitudeDeg, pdfEastLongitudeDeg,
   12976           1 :         pdfNorthLatitudeDeg, ppszAreaName);
   12977             : }
   12978             : 
   12979             : /************************************************************************/
   12980             : /*                   OSRGetCRSInfoListFromDatabase()                    */
   12981             : /************************************************************************/
   12982             : 
   12983             : /** \brief Enumerate CRS objects from the database.
   12984             :  *
   12985             :  * The returned object is an array of OSRCRSInfo* pointers, whose last
   12986             :  * entry is NULL. This array should be freed with OSRDestroyCRSInfoList()
   12987             :  *
   12988             :  * @param pszAuthName Authority name, used to restrict the search.
   12989             :  * Or NULL for all authorities.
   12990             :  * @param params Additional criteria. Must be set to NULL for now.
   12991             :  * @param pnOutResultCount Output parameter pointing to an integer to receive
   12992             :  * the size of the result list. Might be NULL
   12993             :  * @return an array of OSRCRSInfo* pointers to be freed with
   12994             :  * OSRDestroyCRSInfoList(), or NULL in case of error.
   12995             :  *
   12996             :  * @since GDAL 3.0
   12997             :  */
   12998             : OSRCRSInfo **
   12999          28 : OSRGetCRSInfoListFromDatabase(const char *pszAuthName,
   13000             :                               CPL_UNUSED const OSRCRSListParameters *params,
   13001             :                               int *pnOutResultCount)
   13002             : {
   13003          28 :     int nResultCount = 0;
   13004          28 :     auto projList = proj_get_crs_info_list_from_database(
   13005             :         OSRGetProjTLSContext(), pszAuthName, nullptr, &nResultCount);
   13006          28 :     if (pnOutResultCount)
   13007          28 :         *pnOutResultCount = nResultCount;
   13008          28 :     if (!projList)
   13009             :     {
   13010           0 :         return nullptr;
   13011             :     }
   13012          28 :     auto res = new OSRCRSInfo *[nResultCount + 1];
   13013       92468 :     for (int i = 0; i < nResultCount; i++)
   13014             :     {
   13015       92440 :         res[i] = new OSRCRSInfo;
   13016      184880 :         res[i]->pszAuthName = projList[i]->auth_name
   13017       92440 :                                   ? CPLStrdup(projList[i]->auth_name)
   13018             :                                   : nullptr;
   13019       92440 :         res[i]->pszCode =
   13020       92440 :             projList[i]->code ? CPLStrdup(projList[i]->code) : nullptr;
   13021       92440 :         res[i]->pszName =
   13022       92440 :             projList[i]->name ? CPLStrdup(projList[i]->name) : nullptr;
   13023       92440 :         res[i]->eType = OSR_CRS_TYPE_OTHER;
   13024       92440 :         switch (projList[i]->type)
   13025             :         {
   13026        9272 :             case PJ_TYPE_GEOGRAPHIC_2D_CRS:
   13027        9272 :                 res[i]->eType = OSR_CRS_TYPE_GEOGRAPHIC_2D;
   13028        9272 :                 break;
   13029        2864 :             case PJ_TYPE_GEOGRAPHIC_3D_CRS:
   13030        2864 :                 res[i]->eType = OSR_CRS_TYPE_GEOGRAPHIC_3D;
   13031        2864 :                 break;
   13032        3200 :             case PJ_TYPE_GEOCENTRIC_CRS:
   13033        3200 :                 res[i]->eType = OSR_CRS_TYPE_GEOCENTRIC;
   13034        3200 :                 break;
   13035       70012 :             case PJ_TYPE_PROJECTED_CRS:
   13036       70012 :                 res[i]->eType = OSR_CRS_TYPE_PROJECTED;
   13037       70012 :                 break;
   13038        2860 :             case PJ_TYPE_VERTICAL_CRS:
   13039        2860 :                 res[i]->eType = OSR_CRS_TYPE_VERTICAL;
   13040        2860 :                 break;
   13041        4232 :             case PJ_TYPE_COMPOUND_CRS:
   13042        4232 :                 res[i]->eType = OSR_CRS_TYPE_COMPOUND;
   13043        4232 :                 break;
   13044           0 :             default:
   13045           0 :                 break;
   13046             :         }
   13047       92440 :         res[i]->bDeprecated = projList[i]->deprecated;
   13048       92440 :         res[i]->bBboxValid = projList[i]->bbox_valid;
   13049       92440 :         res[i]->dfWestLongitudeDeg = projList[i]->west_lon_degree;
   13050       92440 :         res[i]->dfSouthLatitudeDeg = projList[i]->south_lat_degree;
   13051       92440 :         res[i]->dfEastLongitudeDeg = projList[i]->east_lon_degree;
   13052       92440 :         res[i]->dfNorthLatitudeDeg = projList[i]->north_lat_degree;
   13053      184880 :         res[i]->pszAreaName = projList[i]->area_name
   13054       92440 :                                   ? CPLStrdup(projList[i]->area_name)
   13055             :                                   : nullptr;
   13056       92440 :         res[i]->pszProjectionMethod =
   13057       92440 :             projList[i]->projection_method_name
   13058       92440 :                 ? CPLStrdup(projList[i]->projection_method_name)
   13059             :                 : nullptr;
   13060             : #if PROJ_AT_LEAST_VERSION(8, 1, 0)
   13061             :         res[i]->pszCelestialBodyName =
   13062             :             projList[i]->celestial_body_name
   13063             :                 ? CPLStrdup(projList[i]->celestial_body_name)
   13064             :                 : nullptr;
   13065             : #else
   13066       92440 :         res[i]->pszCelestialBodyName =
   13067       92440 :             res[i]->pszAuthName && EQUAL(res[i]->pszAuthName, "EPSG")
   13068      184880 :                 ? CPLStrdup("Earth")
   13069             :                 : nullptr;
   13070             : #endif
   13071             :     }
   13072          28 :     res[nResultCount] = nullptr;
   13073          28 :     proj_crs_info_list_destroy(projList);
   13074          28 :     return res;
   13075             : }
   13076             : 
   13077             : /************************************************************************/
   13078             : /*                       OSRDestroyCRSInfoList()                        */
   13079             : /************************************************************************/
   13080             : 
   13081             : /** \brief Destroy the result returned by
   13082             :  * OSRGetCRSInfoListFromDatabase().
   13083             :  *
   13084             :  * @since GDAL 3.0
   13085             :  */
   13086          28 : void OSRDestroyCRSInfoList(OSRCRSInfo **list)
   13087             : {
   13088          28 :     if (list)
   13089             :     {
   13090       92468 :         for (int i = 0; list[i] != nullptr; i++)
   13091             :         {
   13092       92440 :             CPLFree(list[i]->pszAuthName);
   13093       92440 :             CPLFree(list[i]->pszCode);
   13094       92440 :             CPLFree(list[i]->pszName);
   13095       92440 :             CPLFree(list[i]->pszAreaName);
   13096       92440 :             CPLFree(list[i]->pszProjectionMethod);
   13097       92440 :             CPLFree(list[i]->pszCelestialBodyName);
   13098       92440 :             delete list[i];
   13099             :         }
   13100          28 :         delete[] list;
   13101             :     }
   13102          28 : }
   13103             : 
   13104             : /************************************************************************/
   13105             : /*                  OSRGetAuthorityListFromDatabase()                   */
   13106             : /************************************************************************/
   13107             : 
   13108             : /** \brief Return the list of CRS authorities used in the PROJ database.
   13109             :  *
   13110             :  * Such as "EPSG", "ESRI", "PROJ", "IGNF", "IAU_2015", etc.
   13111             :  *
   13112             :  * This is a direct mapping of https://proj.org/en/latest/development/reference/functions.html#c.proj_get_authorities_from_database
   13113             :  *
   13114             :  * @return nullptr in case of error, or a NULL terminated list of strings to
   13115             :  * free with CSLDestroy()
   13116             :  * @since GDAL 3.10
   13117             :  */
   13118           5 : char **OSRGetAuthorityListFromDatabase()
   13119             : {
   13120             :     PROJ_STRING_LIST list =
   13121           5 :         proj_get_authorities_from_database(OSRGetProjTLSContext());
   13122           5 :     if (!list)
   13123             :     {
   13124           0 :         return nullptr;
   13125             :     }
   13126           5 :     int count = 0;
   13127          30 :     while (list[count])
   13128          25 :         ++count;
   13129           5 :     char **res = static_cast<char **>(CPLCalloc(count + 1, sizeof(char *)));
   13130          30 :     for (int i = 0; i < count; ++i)
   13131          25 :         res[i] = CPLStrdup(list[i]);
   13132           5 :     proj_string_list_destroy(list);
   13133           5 :     return res;
   13134             : }
   13135             : 
   13136             : /************************************************************************/
   13137             : /*                 UpdateCoordinateSystemFromGeogCRS()                  */
   13138             : /************************************************************************/
   13139             : 
   13140             : /*! @cond Doxygen_Suppress */
   13141             : /** \brief Used by gt_wkt_srs.cpp to create projected 3D CRS. Internal use only
   13142             :  *
   13143             :  * @since GDAL 3.1
   13144             :  */
   13145           1 : void OGRSpatialReference::UpdateCoordinateSystemFromGeogCRS()
   13146             : {
   13147           1 :     TAKE_OPTIONAL_LOCK();
   13148             : 
   13149           1 :     d->refreshProjObj();
   13150           1 :     if (!d->m_pj_crs)
   13151           0 :         return;
   13152           1 :     if (d->m_pjType != PJ_TYPE_PROJECTED_CRS)
   13153           0 :         return;
   13154           1 :     if (GetAxesCount() == 3)
   13155           0 :         return;
   13156           1 :     auto ctxt = d->getPROJContext();
   13157           1 :     auto baseCRS = proj_crs_get_geodetic_crs(ctxt, d->m_pj_crs);
   13158           1 :     if (!baseCRS)
   13159           0 :         return;
   13160           1 :     auto baseCRSCS = proj_crs_get_coordinate_system(ctxt, baseCRS);
   13161           1 :     if (!baseCRSCS)
   13162             :     {
   13163           0 :         proj_destroy(baseCRS);
   13164           0 :         return;
   13165             :     }
   13166           1 :     if (proj_cs_get_axis_count(ctxt, baseCRSCS) != 3)
   13167             :     {
   13168           0 :         proj_destroy(baseCRSCS);
   13169           0 :         proj_destroy(baseCRS);
   13170           0 :         return;
   13171             :     }
   13172           1 :     auto projCS = proj_crs_get_coordinate_system(ctxt, d->m_pj_crs);
   13173           1 :     if (!projCS || proj_cs_get_axis_count(ctxt, projCS) != 2)
   13174             :     {
   13175           0 :         proj_destroy(baseCRSCS);
   13176           0 :         proj_destroy(baseCRS);
   13177           0 :         proj_destroy(projCS);
   13178           0 :         return;
   13179             :     }
   13180             : 
   13181             :     PJ_AXIS_DESCRIPTION axis[3];
   13182           4 :     for (int i = 0; i < 3; i++)
   13183             :     {
   13184           3 :         const char *name = nullptr;
   13185           3 :         const char *abbreviation = nullptr;
   13186           3 :         const char *direction = nullptr;
   13187           3 :         double unit_conv_factor = 0;
   13188           3 :         const char *unit_name = nullptr;
   13189           3 :         proj_cs_get_axis_info(ctxt, i < 2 ? projCS : baseCRSCS, i, &name,
   13190             :                               &abbreviation, &direction, &unit_conv_factor,
   13191             :                               &unit_name, nullptr, nullptr);
   13192           3 :         axis[i].name = CPLStrdup(name);
   13193           3 :         axis[i].abbreviation = CPLStrdup(abbreviation);
   13194           3 :         axis[i].direction = CPLStrdup(direction);
   13195           3 :         axis[i].unit_name = CPLStrdup(unit_name);
   13196           3 :         axis[i].unit_conv_factor = unit_conv_factor;
   13197           3 :         axis[i].unit_type = PJ_UT_LINEAR;
   13198             :     }
   13199           1 :     proj_destroy(baseCRSCS);
   13200           1 :     proj_destroy(projCS);
   13201           1 :     auto cs = proj_create_cs(ctxt, PJ_CS_TYPE_CARTESIAN, 3, axis);
   13202           4 :     for (int i = 0; i < 3; i++)
   13203             :     {
   13204           3 :         CPLFree(axis[i].name);
   13205           3 :         CPLFree(axis[i].abbreviation);
   13206           3 :         CPLFree(axis[i].direction);
   13207           3 :         CPLFree(axis[i].unit_name);
   13208             :     }
   13209           1 :     if (!cs)
   13210             :     {
   13211           0 :         proj_destroy(baseCRS);
   13212           0 :         return;
   13213             :     }
   13214           1 :     auto conversion = proj_crs_get_coordoperation(ctxt, d->m_pj_crs);
   13215           1 :     auto crs = proj_create_projected_crs(ctxt, d->getProjCRSName(), baseCRS,
   13216             :                                          conversion, cs);
   13217           1 :     proj_destroy(baseCRS);
   13218           1 :     proj_destroy(conversion);
   13219           1 :     proj_destroy(cs);
   13220           1 :     d->setPjCRS(crs);
   13221             : }
   13222             : 
   13223             : /*! @endcond */
   13224             : 
   13225             : /************************************************************************/
   13226             : /*                            PromoteTo3D()                             */
   13227             : /************************************************************************/
   13228             : 
   13229             : /** \brief "Promotes" a 2D CRS to a 3D CRS one.
   13230             :  *
   13231             :  * The new axis will be ellipsoidal height, oriented upwards, and with metre
   13232             :  * units.
   13233             :  *
   13234             :  * @param pszName New name for the CRS. If set to NULL, the previous name will
   13235             :  * be used.
   13236             :  * @return OGRERR_NONE if no error occurred.
   13237             :  * @since GDAL 3.1 and PROJ 6.3
   13238             :  */
   13239          44 : OGRErr OGRSpatialReference::PromoteTo3D(const char *pszName)
   13240             : {
   13241          88 :     TAKE_OPTIONAL_LOCK();
   13242             : 
   13243          44 :     d->refreshProjObj();
   13244          44 :     if (!d->m_pj_crs)
   13245           0 :         return OGRERR_FAILURE;
   13246             :     auto newPj =
   13247          44 :         proj_crs_promote_to_3D(d->getPROJContext(), pszName, d->m_pj_crs);
   13248          44 :     if (!newPj)
   13249           0 :         return OGRERR_FAILURE;
   13250          44 :     d->setPjCRS(newPj);
   13251          44 :     return OGRERR_NONE;
   13252             : }
   13253             : 
   13254             : /************************************************************************/
   13255             : /*                           OSRPromoteTo3D()                           */
   13256             : /************************************************************************/
   13257             : 
   13258             : /** \brief "Promotes" a 2D CRS to a 3D CRS one.
   13259             :  *
   13260             :  * See OGRSpatialReference::PromoteTo3D()
   13261             :  *
   13262             :  * @since GDAL 3.1 and PROJ 6.3
   13263             :  */
   13264           3 : OGRErr OSRPromoteTo3D(OGRSpatialReferenceH hSRS, const char *pszName)
   13265             : {
   13266           3 :     VALIDATE_POINTER1(hSRS, "OSRPromoteTo3D", OGRERR_FAILURE);
   13267             : 
   13268           3 :     return OGRSpatialReference::FromHandle(hSRS)->PromoteTo3D(pszName);
   13269             : }
   13270             : 
   13271             : /************************************************************************/
   13272             : /*                             DemoteTo2D()                             */
   13273             : /************************************************************************/
   13274             : 
   13275             : /** \brief "Demote" a 3D CRS to a 2D CRS one.
   13276             :  *
   13277             :  * @param pszName New name for the CRS. If set to NULL, the previous name will
   13278             :  * be used.
   13279             :  * @return OGRERR_NONE if no error occurred.
   13280             :  * @since GDAL 3.2 and PROJ 6.3
   13281             :  */
   13282          49 : OGRErr OGRSpatialReference::DemoteTo2D(const char *pszName)
   13283             : {
   13284          98 :     TAKE_OPTIONAL_LOCK();
   13285             : 
   13286          49 :     d->refreshProjObj();
   13287          49 :     if (!d->m_pj_crs)
   13288           0 :         return OGRERR_FAILURE;
   13289             :     auto newPj =
   13290          49 :         proj_crs_demote_to_2D(d->getPROJContext(), pszName, d->m_pj_crs);
   13291          49 :     if (!newPj)
   13292           0 :         return OGRERR_FAILURE;
   13293          49 :     d->setPjCRS(newPj);
   13294          49 :     return OGRERR_NONE;
   13295             : }
   13296             : 
   13297             : /************************************************************************/
   13298             : /*                           OSRDemoteTo2D()                            */
   13299             : /************************************************************************/
   13300             : 
   13301             : /** \brief "Demote" a 3D CRS to a 2D CRS one.
   13302             :  *
   13303             :  * See OGRSpatialReference::DemoteTo2D()
   13304             :  *
   13305             :  * @since GDAL 3.2 and PROJ 6.3
   13306             :  */
   13307           1 : OGRErr OSRDemoteTo2D(OGRSpatialReferenceH hSRS, const char *pszName)
   13308             : {
   13309           1 :     VALIDATE_POINTER1(hSRS, "OSRDemoteTo2D", OGRERR_FAILURE);
   13310             : 
   13311           1 :     return OGRSpatialReference::FromHandle(hSRS)->DemoteTo2D(pszName);
   13312             : }
   13313             : 
   13314             : /************************************************************************/
   13315             : /*                           GetEPSGGeogCS()                            */
   13316             : /************************************************************************/
   13317             : 
   13318             : /** Try to establish what the EPSG code for this coordinate systems
   13319             :  * GEOGCS might be.  Returns -1 if no reasonable guess can be made.
   13320             :  *
   13321             :  * @return EPSG code
   13322             :  */
   13323             : 
   13324         342 : int OGRSpatialReference::GetEPSGGeogCS() const
   13325             : 
   13326             : {
   13327         684 :     TAKE_OPTIONAL_LOCK();
   13328             : 
   13329             :     /* -------------------------------------------------------------------- */
   13330             :     /*      Check axis order.                                               */
   13331             :     /* -------------------------------------------------------------------- */
   13332         684 :     auto poGeogCRS = std::unique_ptr<OGRSpatialReference>(CloneGeogCS());
   13333         342 :     if (!poGeogCRS)
   13334           0 :         return -1;
   13335             : 
   13336         342 :     bool ret = false;
   13337         342 :     poGeogCRS->d->demoteFromBoundCRS();
   13338         342 :     auto cs = proj_crs_get_coordinate_system(d->getPROJContext(),
   13339         342 :                                              poGeogCRS->d->m_pj_crs);
   13340         342 :     poGeogCRS->d->undoDemoteFromBoundCRS();
   13341         342 :     if (cs)
   13342             :     {
   13343         342 :         const char *pszDirection = nullptr;
   13344         342 :         if (proj_cs_get_axis_info(d->getPROJContext(), cs, 0, nullptr, nullptr,
   13345             :                                   &pszDirection, nullptr, nullptr, nullptr,
   13346         342 :                                   nullptr))
   13347             :         {
   13348         342 :             if (EQUAL(pszDirection, "north"))
   13349             :             {
   13350         143 :                 ret = true;
   13351             :             }
   13352             :         }
   13353             : 
   13354         342 :         proj_destroy(cs);
   13355             :     }
   13356         342 :     if (!ret)
   13357         199 :         return -1;
   13358             : 
   13359             :     /* -------------------------------------------------------------------- */
   13360             :     /*      Do we already have it?                                          */
   13361             :     /* -------------------------------------------------------------------- */
   13362         143 :     const char *pszAuthName = GetAuthorityName("GEOGCS");
   13363         143 :     if (pszAuthName != nullptr && EQUAL(pszAuthName, "epsg"))
   13364          67 :         return atoi(GetAuthorityCode("GEOGCS"));
   13365             : 
   13366             :     /* -------------------------------------------------------------------- */
   13367             :     /*      Get the datum and geogcs names.                                 */
   13368             :     /* -------------------------------------------------------------------- */
   13369             : 
   13370          76 :     const char *pszGEOGCS = GetAttrValue("GEOGCS");
   13371          76 :     const char *pszDatum = GetAttrValue("DATUM");
   13372             : 
   13373             :     // We can only operate on coordinate systems with a geogcs.
   13374         152 :     OGRSpatialReference oSRSTmp;
   13375          76 :     if (pszGEOGCS == nullptr || pszDatum == nullptr)
   13376             :     {
   13377             :         // Calling GetAttrValue("GEOGCS") will fail on a CRS that can't be
   13378             :         // export to WKT1, so try to extract the geographic CRS through PROJ
   13379             :         // API with CopyGeogCSFrom() and get the nodes' values from it.
   13380           1 :         oSRSTmp.CopyGeogCSFrom(this);
   13381           1 :         pszGEOGCS = oSRSTmp.GetAttrValue("GEOGCS");
   13382           1 :         pszDatum = oSRSTmp.GetAttrValue("DATUM");
   13383           1 :         if (pszGEOGCS == nullptr || pszDatum == nullptr)
   13384             :         {
   13385           0 :             return -1;
   13386             :         }
   13387             :     }
   13388             : 
   13389             :     // Lookup geographic CRS name
   13390          76 :     const PJ_TYPE type = PJ_TYPE_GEOGRAPHIC_2D_CRS;
   13391          76 :     PJ_OBJ_LIST *list = proj_create_from_name(
   13392             :         d->getPROJContext(), nullptr, pszGEOGCS, &type, 1, false, 1, nullptr);
   13393          76 :     if (list)
   13394             :     {
   13395          76 :         const auto listSize = proj_list_get_count(list);
   13396          76 :         if (listSize == 1)
   13397             :         {
   13398          48 :             auto crs = proj_list_get(d->getPROJContext(), list, 0);
   13399          48 :             if (crs)
   13400             :             {
   13401          48 :                 pszAuthName = proj_get_id_auth_name(crs, 0);
   13402          48 :                 const char *pszCode = proj_get_id_code(crs, 0);
   13403          48 :                 if (pszAuthName && pszCode && EQUAL(pszAuthName, "EPSG"))
   13404             :                 {
   13405          46 :                     const int nCode = atoi(pszCode);
   13406          46 :                     proj_destroy(crs);
   13407          46 :                     proj_list_destroy(list);
   13408          46 :                     return nCode;
   13409             :                 }
   13410           2 :                 proj_destroy(crs);
   13411             :             }
   13412             :         }
   13413          30 :         proj_list_destroy(list);
   13414             :     }
   13415             : 
   13416             :     /* -------------------------------------------------------------------- */
   13417             :     /*      Is this a "well known" geographic coordinate system?            */
   13418             :     /* -------------------------------------------------------------------- */
   13419          90 :     const bool bWGS = strstr(pszGEOGCS, "WGS") != nullptr ||
   13420          30 :                       strstr(pszDatum, "WGS") ||
   13421          30 :                       strstr(pszGEOGCS, "World Geodetic System") ||
   13422          30 :                       strstr(pszGEOGCS, "World_Geodetic_System") ||
   13423          90 :                       strstr(pszDatum, "World Geodetic System") ||
   13424          30 :                       strstr(pszDatum, "World_Geodetic_System");
   13425             : 
   13426          90 :     const bool bNAD = strstr(pszGEOGCS, "NAD") != nullptr ||
   13427          30 :                       strstr(pszDatum, "NAD") ||
   13428          30 :                       strstr(pszGEOGCS, "North American") ||
   13429          30 :                       strstr(pszGEOGCS, "North_American") ||
   13430          90 :                       strstr(pszDatum, "North American") ||
   13431          30 :                       strstr(pszDatum, "North_American");
   13432             : 
   13433          30 :     if (bWGS && (strstr(pszGEOGCS, "84") || strstr(pszDatum, "84")))
   13434           0 :         return 4326;
   13435             : 
   13436          30 :     if (bWGS && (strstr(pszGEOGCS, "72") || strstr(pszDatum, "72")))
   13437           0 :         return 4322;
   13438             : 
   13439             :     // This is questionable as there are several 'flavors' of NAD83 that
   13440             :     // are not the same as 4269
   13441          30 :     if (bNAD && (strstr(pszGEOGCS, "83") || strstr(pszDatum, "83")))
   13442           0 :         return 4269;
   13443             : 
   13444          30 :     if (bNAD && (strstr(pszGEOGCS, "27") || strstr(pszDatum, "27")))
   13445           0 :         return 4267;
   13446             : 
   13447             :     /* -------------------------------------------------------------------- */
   13448             :     /*      If we know the datum, associate the most likely GCS with        */
   13449             :     /*      it.                                                             */
   13450             :     /* -------------------------------------------------------------------- */
   13451          30 :     const OGRSpatialReference &oActiveObj = oSRSTmp.IsEmpty() ? *this : oSRSTmp;
   13452          30 :     pszAuthName = oActiveObj.GetAuthorityName("GEOGCS|DATUM");
   13453          30 :     if (pszAuthName != nullptr && EQUAL(pszAuthName, "epsg") &&
   13454           0 :         GetPrimeMeridian() == 0.0)
   13455             :     {
   13456           0 :         const int nDatum = atoi(oActiveObj.GetAuthorityCode("GEOGCS|DATUM"));
   13457             : 
   13458           0 :         if (nDatum >= 6000 && nDatum <= 6999)
   13459           0 :             return nDatum - 2000;
   13460             :     }
   13461             : 
   13462          30 :     return -1;
   13463             : }
   13464             : 
   13465             : /************************************************************************/
   13466             : /*                         SetCoordinateEpoch()                         */
   13467             : /************************************************************************/
   13468             : 
   13469             : /** Set the coordinate epoch, as decimal year.
   13470             :  *
   13471             :  * In a dynamic CRS, coordinates of a point on the surface of the Earth may
   13472             :  * change with time. To be unambiguous the coordinates must always be qualified
   13473             :  * with the epoch at which they are valid. The coordinate epoch is not
   13474             :  * necessarily the epoch at which the observation was collected.
   13475             :  *
   13476             :  * Pedantically the coordinate epoch of an observation belongs to the
   13477             :  * observation, and not to the CRS, however it is often more practical to
   13478             :  * bind it to the CRS. The coordinate epoch should be specified for dynamic
   13479             :  * CRS (see IsDynamic())
   13480             :  *
   13481             :  * This method is the same as the OSRSetCoordinateEpoch() function.
   13482             :  *
   13483             :  * @param dfCoordinateEpoch Coordinate epoch as decimal year (e.g. 2021.3)
   13484             :  * @since OGR 3.4
   13485             :  */
   13486             : 
   13487         960 : void OGRSpatialReference::SetCoordinateEpoch(double dfCoordinateEpoch)
   13488             : {
   13489         960 :     d->m_coordinateEpoch = dfCoordinateEpoch;
   13490         960 : }
   13491             : 
   13492             : /************************************************************************/
   13493             : /*                       OSRSetCoordinateEpoch()                        */
   13494             : /************************************************************************/
   13495             : 
   13496             : /** \brief Set the coordinate epoch, as decimal year.
   13497             :  *
   13498             :  * See OGRSpatialReference::SetCoordinateEpoch()
   13499             :  *
   13500             :  * @since OGR 3.4
   13501             :  */
   13502          31 : void OSRSetCoordinateEpoch(OGRSpatialReferenceH hSRS, double dfCoordinateEpoch)
   13503             : {
   13504          31 :     VALIDATE_POINTER0(hSRS, "OSRSetCoordinateEpoch");
   13505             : 
   13506          31 :     return OGRSpatialReference::FromHandle(hSRS)->SetCoordinateEpoch(
   13507          31 :         dfCoordinateEpoch);
   13508             : }
   13509             : 
   13510             : /************************************************************************/
   13511             : /*                         GetCoordinateEpoch()                         */
   13512             : /************************************************************************/
   13513             : 
   13514             : /** Return the coordinate epoch, as decimal year.
   13515             :  *
   13516             :  * In a dynamic CRS, coordinates of a point on the surface of the Earth may
   13517             :  * change with time. To be unambiguous the coordinates must always be qualified
   13518             :  * with the epoch at which they are valid. The coordinate epoch is not
   13519             :  * necessarily the epoch at which the observation was collected.
   13520             :  *
   13521             :  * Pedantically the coordinate epoch of an observation belongs to the
   13522             :  * observation, and not to the CRS, however it is often more practical to
   13523             :  * bind it to the CRS. The coordinate epoch should be specified for dynamic
   13524             :  * CRS (see IsDynamic())
   13525             :  *
   13526             :  * This method is the same as the OSRGetCoordinateEpoch() function.
   13527             :  *
   13528             :  * @return coordinateEpoch Coordinate epoch as decimal year (e.g. 2021.3), or 0
   13529             :  *                         if not set, or relevant.
   13530             :  * @since OGR 3.4
   13531             :  */
   13532             : 
   13533       15030 : double OGRSpatialReference::GetCoordinateEpoch() const
   13534             : {
   13535       15030 :     return d->m_coordinateEpoch;
   13536             : }
   13537             : 
   13538             : /************************************************************************/
   13539             : /*                       OSRGetCoordinateEpoch()                        */
   13540             : /************************************************************************/
   13541             : 
   13542             : /** \brief Get the coordinate epoch, as decimal year.
   13543             :  *
   13544             :  * See OGRSpatialReference::GetCoordinateEpoch()
   13545             :  *
   13546             :  * @since OGR 3.4
   13547             :  */
   13548         611 : double OSRGetCoordinateEpoch(OGRSpatialReferenceH hSRS)
   13549             : {
   13550         611 :     VALIDATE_POINTER1(hSRS, "OSRGetCoordinateEpoch", 0);
   13551             : 
   13552         611 :     return OGRSpatialReference::FromHandle(hSRS)->GetCoordinateEpoch();
   13553             : }

Generated by: LCOV version 1.14