repo_name
stringclasses
10 values
file_path
stringlengths
29
222
content
stringlengths
24
926k
extention
stringclasses
5 values
PROJ
data/projects/PROJ/src/conversions/unitconvert.cpp
/*********************************************************************** Unit conversion pseudo-projection for use with transformation pipelines. Kristian Evers, 2017-05-16 ************************************************************************ A pseudo-projection that can be used to convert units of input and output data. Primarily useful in pipelines. Unit conversion is performed by means of a pivot unit. The pivot unit for distance units are the meter and for time we use the modified julian date. A time unit conversion is performed like Unit A -> Modified Julian date -> Unit B distance units are converted in the same manner, with meter being the central unit. The modified Julian date is chosen as the pivot unit since it has a fairly high precision, goes sufficiently long backwards in time, has no danger of hitting the upper limit in the near future and it is a fairly common time unit in astronomy and geodesy. Note that we are using the Julian date and not day. The difference being that the latter is defined as an integer and is thus limited to days in resolution. This approach has been extended wherever it makes sense, e.g. the GPS week unit also has a fractional part that makes it possible to determine the day, hour and minute of an observation. In- and output units are controlled with the parameters +xy_in, +xy_out, +z_in, +z_out, +t_in and +t_out where xy denotes horizontal units, z vertical units and t time units. ************************************************************************ Kristian Evers, [email protected], 2017-05-09 Last update: 2017-05-16 ************************************************************************ * Copyright (c) 2017, Kristian Evers / SDFE * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * ***********************************************************************/ #include <errno.h> #include <math.h> #include <string.h> #include <time.h> #include "proj_internal.h" #include <math.h> PROJ_HEAD(unitconvert, "Unit conversion"); typedef double (*tconvert)(double); namespace { // anonymous namespace struct TIME_UNITS { const char *id; /* units keyword */ tconvert t_in; /* unit -> mod. julian date function pointer */ tconvert t_out; /* mod. julian date > unit function pointer */ const char *name; /* comments */ }; } // anonymous namespace namespace { // anonymous namespace struct pj_opaque_unitconvert { int t_in_id; /* time unit id for the time input unit */ int t_out_id; /* time unit id for the time output unit */ double xy_factor; /* unit conversion factor for horizontal components */ double z_factor; /* unit conversion factor for vertical components */ }; } // anonymous namespace /***********************************************************************/ static int is_leap_year(long year) { /***********************************************************************/ return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } /***********************************************************************/ static int days_in_year(long year) { /***********************************************************************/ return is_leap_year(year) ? 366 : 365; } /***********************************************************************/ static unsigned int days_in_month(unsigned long year, unsigned long month) { /***********************************************************************/ const unsigned int month_table[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; unsigned int days; if (month > 12) month = 12; if (month == 0) month = 1; days = month_table[month - 1]; if (is_leap_year(year) && month == 2) days++; return days; } /***********************************************************************/ static int daynumber_in_year(unsigned long year, unsigned long month, unsigned long day) { /***********************************************************************/ unsigned int daynumber = 0, i; if (month > 12) month = 12; if (month == 0) month = 1; if (day > days_in_month(year, month)) day = days_in_month(year, month); for (i = 1; i < month; i++) daynumber += days_in_month(year, i); daynumber += day; return daynumber; } /***********************************************************************/ static double mjd_to_mjd(double mjd) { /*********************************************************************** Modified julian date no-op function. The Julian date is defined as (fractional) days since midnight on 16th of November in 1858. ************************************************************************/ return mjd; } /***********************************************************************/ static double decimalyear_to_mjd(double decimalyear) { /*********************************************************************** Epoch of modified julian date is 1858-11-16 00:00 ************************************************************************/ long year; double fractional_year; double mjd; // Written this way to deal with NaN input if (!(decimalyear >= -10000 && decimalyear <= 10000)) return 0; year = lround(floor(decimalyear)); fractional_year = decimalyear - year; mjd = (year - 1859) * 365 + 14 + 31; mjd += (double)fractional_year * (double)days_in_year(year); /* take care of leap days */ year--; for (; year > 1858; year--) if (is_leap_year(year)) mjd++; return mjd; } /***********************************************************************/ static double mjd_to_decimalyear(double mjd) { /*********************************************************************** Epoch of modified julian date is 1858-11-16 00:00 ************************************************************************/ double decimalyear = mjd; double mjd_iter = 14 + 31; int year = 1859; /* a smarter brain than mine could probably to do this more elegantly - I'll just brute-force my way out of this... */ for (; mjd >= mjd_iter; year++) { mjd_iter += days_in_year(year); } year--; mjd_iter -= days_in_year(year); decimalyear = year + (mjd - mjd_iter) / days_in_year(year); return decimalyear; } /***********************************************************************/ static double gps_week_to_mjd(double gps_week) { /*********************************************************************** GPS weeks are defined as the number of weeks since January the 6th 1980. Epoch of gps weeks is 1980-01-06 00:00, which in modified Julian date is 44244. ************************************************************************/ return 44244.0 + gps_week * 7.0; } /***********************************************************************/ static double mjd_to_gps_week(double mjd) { /*********************************************************************** GPS weeks are defined as the number of weeks since January the 6th 1980. Epoch of gps weeks is 1980-01-06 00:00, which in modified Julian date is 44244. ************************************************************************/ return (mjd - 44244.0) / 7.0; } /***********************************************************************/ static double yyyymmdd_to_mjd(double yyyymmdd) { /************************************************************************ Date given in YYYY-MM-DD format. ************************************************************************/ long year = lround(floor(yyyymmdd / 10000)); long month = lround(floor((yyyymmdd - year * 10000) / 100)); long day = lround(floor(yyyymmdd - year * 10000 - month * 100)); double mjd = daynumber_in_year(year, month, day); for (year -= 1; year > 1858; year--) mjd += days_in_year(year); return mjd + 13 + 31; } /***********************************************************************/ static double mjd_to_yyyymmdd(double mjd) { /************************************************************************ Date returned in YYYY-MM-DD format. ************************************************************************/ unsigned int date_iter = 14 + 31; unsigned int year = 1859, month = 0, day = 0; unsigned int date = (int)lround(mjd); for (; date >= date_iter; year++) { date_iter += days_in_year(year); } year--; date_iter -= days_in_year(year); for (month = 1; date_iter + days_in_month(year, month) <= date; month++) date_iter += days_in_month(year, month); day = date - date_iter + 1; return year * 10000.0 + month * 100.0 + day; } static const struct TIME_UNITS time_units[] = { {"mjd", mjd_to_mjd, mjd_to_mjd, "Modified julian date"}, {"decimalyear", decimalyear_to_mjd, mjd_to_decimalyear, "Decimal year"}, {"gps_week", gps_week_to_mjd, mjd_to_gps_week, "GPS Week"}, {"yyyymmdd", yyyymmdd_to_mjd, mjd_to_yyyymmdd, "YYYYMMDD date"}, {nullptr, nullptr, nullptr, nullptr}}; /***********************************************************************/ static PJ_XY forward_2d(PJ_LP lp, PJ *P) { /************************************************************************ Forward unit conversions in the plane ************************************************************************/ struct pj_opaque_unitconvert *Q = (struct pj_opaque_unitconvert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; point.lp = lp; point.xy.x *= Q->xy_factor; point.xy.y *= Q->xy_factor; return point.xy; } /***********************************************************************/ static PJ_LP reverse_2d(PJ_XY xy, PJ *P) { /************************************************************************ Reverse unit conversions in the plane ************************************************************************/ struct pj_opaque_unitconvert *Q = (struct pj_opaque_unitconvert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; point.xy = xy; point.xy.x /= Q->xy_factor; point.xy.y /= Q->xy_factor; return point.lp; } /***********************************************************************/ static PJ_XYZ forward_3d(PJ_LPZ lpz, PJ *P) { /************************************************************************ Forward unit conversions the vertical component ************************************************************************/ struct pj_opaque_unitconvert *Q = (struct pj_opaque_unitconvert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; point.lpz = lpz; /* take care of the horizontal components in the 2D function */ // Assigning in 2 steps avoids cppcheck warning // "Overlapping read/write of union is undefined behavior" // Cf https://github.com/OSGeo/PROJ/pull/3527#pullrequestreview-1233332710 const auto xy = forward_2d(point.lp, P); point.xy = xy; point.xyz.z *= Q->z_factor; return point.xyz; } /***********************************************************************/ static PJ_LPZ reverse_3d(PJ_XYZ xyz, PJ *P) { /************************************************************************ Reverse unit conversions the vertical component ************************************************************************/ struct pj_opaque_unitconvert *Q = (struct pj_opaque_unitconvert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; point.xyz = xyz; /* take care of the horizontal components in the 2D function */ // Assigning in 2 steps avoids cppcheck warning // "Overlapping read/write of union is undefined behavior" // Cf https://github.com/OSGeo/PROJ/pull/3527#pullrequestreview-1233332710 const auto lp = reverse_2d(point.xy, P); point.lp = lp; point.xyz.z /= Q->z_factor; return point.lpz; } /***********************************************************************/ static void forward_4d(PJ_COORD &coo, PJ *P) { /************************************************************************ Forward conversion of time units ************************************************************************/ struct pj_opaque_unitconvert *Q = (struct pj_opaque_unitconvert *)P->opaque; /* delegate unit conversion of physical dimensions to the 3D function */ // Assigning in 2 steps avoids cppcheck warning // "Overlapping read/write of union is undefined behavior" // Cf https://github.com/OSGeo/PROJ/pull/3527#pullrequestreview-1233332710 const auto xyz = forward_3d(coo.lpz, P); coo.xyz = xyz; if (Q->t_in_id >= 0) coo.xyzt.t = time_units[Q->t_in_id].t_in(coo.xyzt.t); if (Q->t_out_id >= 0) coo.xyzt.t = time_units[Q->t_out_id].t_out(coo.xyzt.t); } /***********************************************************************/ static void reverse_4d(PJ_COORD &coo, PJ *P) { /************************************************************************ Reverse conversion of time units ************************************************************************/ struct pj_opaque_unitconvert *Q = (struct pj_opaque_unitconvert *)P->opaque; /* delegate unit conversion of physical dimensions to the 3D function */ // Assigning in 2 steps avoids cppcheck warning // "Overlapping read/write of union is undefined behavior" // Cf https://github.com/OSGeo/PROJ/pull/3527#pullrequestreview-1233332710 const auto lpz = reverse_3d(coo.xyz, P); coo.lpz = lpz; if (Q->t_out_id >= 0) coo.xyzt.t = time_units[Q->t_out_id].t_in(coo.xyzt.t); if (Q->t_in_id >= 0) coo.xyzt.t = time_units[Q->t_in_id].t_out(coo.xyzt.t); } /***********************************************************************/ static double get_unit_conversion_factor(const char *name, int *p_is_linear, const char **p_normalized_name) { /***********************************************************************/ int i; const char *s; const PJ_UNITS *units = pj_list_linear_units(); /* Try first with linear units */ for (i = 0; (s = units[i].id); ++i) { if (strcmp(s, name) == 0) { if (p_normalized_name) { *p_normalized_name = units[i].name; } if (p_is_linear) { *p_is_linear = 1; } return units[i].factor; } } /* And then angular units */ units = pj_list_angular_units(); for (i = 0; (s = units[i].id); ++i) { if (strcmp(s, name) == 0) { if (p_normalized_name) { *p_normalized_name = units[i].name; } if (p_is_linear) { *p_is_linear = 0; } return units[i].factor; } } if (p_normalized_name) { *p_normalized_name = nullptr; } if (p_is_linear) { *p_is_linear = -1; } return 0.0; } /***********************************************************************/ PJ *PJ_CONVERSION(unitconvert, 0) { /***********************************************************************/ struct pj_opaque_unitconvert *Q = static_cast<struct pj_opaque_unitconvert *>( calloc(1, sizeof(struct pj_opaque_unitconvert))); const char *s, *name; int i; double f; int xy_in_is_linear = -1; /* unknown */ int xy_out_is_linear = -1; /* unknown */ int z_in_is_linear = -1; /* unknown */ int z_out_is_linear = -1; /* unknown */ if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = (void *)Q; P->fwd4d = forward_4d; P->inv4d = reverse_4d; P->fwd3d = forward_3d; P->inv3d = reverse_3d; P->fwd = forward_2d; P->inv = reverse_2d; P->left = PJ_IO_UNITS_WHATEVER; P->right = PJ_IO_UNITS_WHATEVER; P->skip_fwd_prepare = 1; P->skip_inv_prepare = 1; /* if no time input/output unit is specified we can skip them */ Q->t_in_id = -1; Q->t_out_id = -1; Q->xy_factor = 1.0; Q->z_factor = 1.0; if ((name = pj_param(P->ctx, P->params, "sxy_in").s) != nullptr) { const char *normalized_name = nullptr; f = get_unit_conversion_factor(name, &xy_in_is_linear, &normalized_name); if (f != 0.0) { proj_log_trace(P, "xy_in unit: %s", normalized_name); } else { f = pj_param(P->ctx, P->params, "dxy_in").f; if (f == 0.0 || 1.0 / f == 0.0) { proj_log_error(P, _("unknown xy_in unit")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } Q->xy_factor = f; if (normalized_name != nullptr) { if (strcmp(normalized_name, "Radian") == 0) P->left = PJ_IO_UNITS_RADIANS; if (strcmp(normalized_name, "Degree") == 0) P->left = PJ_IO_UNITS_DEGREES; } } if ((name = pj_param(P->ctx, P->params, "sxy_out").s) != nullptr) { const char *normalized_name = nullptr; f = get_unit_conversion_factor(name, &xy_out_is_linear, &normalized_name); if (f != 0.0) { proj_log_trace(P, "xy_out unit: %s", normalized_name); } else { f = pj_param(P->ctx, P->params, "dxy_out").f; if (f == 0.0 || 1.0 / f == 0.0) { proj_log_error(P, _("unknown xy_out unit")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } Q->xy_factor /= f; if (normalized_name != nullptr) { if (strcmp(normalized_name, "Radian") == 0) P->right = PJ_IO_UNITS_RADIANS; if (strcmp(normalized_name, "Degree") == 0) P->right = PJ_IO_UNITS_DEGREES; } } if (xy_in_is_linear >= 0 && xy_out_is_linear >= 0 && xy_in_is_linear != xy_out_is_linear) { proj_log_error(P, _("inconsistent unit type between xy_in and xy_out")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if ((name = pj_param(P->ctx, P->params, "sz_in").s) != nullptr) { const char *normalized_name = nullptr; f = get_unit_conversion_factor(name, &z_in_is_linear, &normalized_name); if (f != 0.0) { proj_log_trace(P, "z_in unit: %s", normalized_name); } else { f = pj_param(P->ctx, P->params, "dz_in").f; if (f == 0.0 || 1.0 / f == 0.0) { proj_log_error(P, _("unknown z_in unit")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } Q->z_factor = f; } if ((name = pj_param(P->ctx, P->params, "sz_out").s) != nullptr) { const char *normalized_name = nullptr; f = get_unit_conversion_factor(name, &z_out_is_linear, &normalized_name); if (f != 0.0) { proj_log_trace(P, "z_out unit: %s", normalized_name); } else { f = pj_param(P->ctx, P->params, "dz_out").f; if (f == 0.0 || 1.0 / f == 0.0) { proj_log_error(P, _("unknown z_out unit")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } Q->z_factor /= f; } if (z_in_is_linear >= 0 && z_out_is_linear >= 0 && z_in_is_linear != z_out_is_linear) { proj_log_error(P, _("inconsistent unit type between z_in and z_out")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if ((name = pj_param(P->ctx, P->params, "st_in").s) != nullptr) { for (i = 0; (s = time_units[i].id) && strcmp(name, s); ++i) ; if (!s) { proj_log_error(P, _("unknown t_in unit")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->t_in_id = i; proj_log_trace(P, "t_in unit: %s", time_units[i].name); } s = nullptr; if ((name = pj_param(P->ctx, P->params, "st_out").s) != nullptr) { for (i = 0; (s = time_units[i].id) && strcmp(name, s); ++i) ; if (!s) { proj_log_error(P, _("unknown t_out unit")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->t_out_id = i; proj_log_trace(P, "t_out unit: %s", time_units[i].name); } return P; }
cpp
PROJ
data/projects/PROJ/src/iso19111/metadata.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/metadata.hpp" #include "proj/common.hpp" #include "proj/io.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj_json_streaming_writer.hpp" #include <algorithm> #include <cmath> #include <limits> #include <memory> #include <string> #include <vector> using namespace NS_PROJ::internal; using namespace NS_PROJ::io; using namespace NS_PROJ::util; #if 0 namespace dropbox{ namespace oxygen { template<> nn<std::shared_ptr<NS_PROJ::metadata::Citation>>::~nn() = default; template<> nn<NS_PROJ::metadata::ExtentPtr>::~nn() = default; template<> nn<NS_PROJ::metadata::GeographicBoundingBoxPtr>::~nn() = default; template<> nn<NS_PROJ::metadata::GeographicExtentPtr>::~nn() = default; template<> nn<NS_PROJ::metadata::VerticalExtentPtr>::~nn() = default; template<> nn<NS_PROJ::metadata::TemporalExtentPtr>::~nn() = default; template<> nn<NS_PROJ::metadata::IdentifierPtr>::~nn() = default; template<> nn<NS_PROJ::metadata::PositionalAccuracyPtr>::~nn() = default; }} #endif NS_PROJ_START namespace metadata { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Citation::Private { optional<std::string> title{}; }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Citation::Citation() : d(internal::make_unique<Private>()) {} //! @endcond // --------------------------------------------------------------------------- /** \brief Constructs a citation by its title. */ Citation::Citation(const std::string &titleIn) : d(internal::make_unique<Private>()) { d->title = titleIn; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Citation::Citation(const Citation &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- Citation::~Citation() = default; // --------------------------------------------------------------------------- Citation &Citation::operator=(const Citation &other) { if (this != &other) { *d = *other.d; } return *this; } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns the name by which the cited resource is known. */ const optional<std::string> &Citation::title() PROJ_PURE_DEFN { return d->title; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GeographicExtent::Private {}; //! @endcond // --------------------------------------------------------------------------- GeographicExtent::GeographicExtent() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeographicExtent::~GeographicExtent() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GeographicBoundingBox::Private { double west_{}; double south_{}; double east_{}; double north_{}; Private(double west, double south, double east, double north) : west_(west), south_(south), east_(east), north_(north) {} bool intersects(const Private &other) const; std::unique_ptr<Private> intersection(const Private &other) const; }; //! @endcond // --------------------------------------------------------------------------- GeographicBoundingBox::GeographicBoundingBox(double west, double south, double east, double north) : GeographicExtent(), d(internal::make_unique<Private>(west, south, east, north)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeographicBoundingBox::~GeographicBoundingBox() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Returns the western-most coordinate of the limit of the dataset * extent. * * The unit is degrees. * * If eastBoundLongitude < westBoundLongitude(), then the bounding box crosses * the anti-meridian. */ double GeographicBoundingBox::westBoundLongitude() PROJ_PURE_DEFN { return d->west_; } // --------------------------------------------------------------------------- /** \brief Returns the southern-most coordinate of the limit of the dataset * extent. * * The unit is degrees. */ double GeographicBoundingBox::southBoundLatitude() PROJ_PURE_DEFN { return d->south_; } // --------------------------------------------------------------------------- /** \brief Returns the eastern-most coordinate of the limit of the dataset * extent. * * The unit is degrees. * * If eastBoundLongitude < westBoundLongitude(), then the bounding box crosses * the anti-meridian. */ double GeographicBoundingBox::eastBoundLongitude() PROJ_PURE_DEFN { return d->east_; } // --------------------------------------------------------------------------- /** \brief Returns the northern-most coordinate of the limit of the dataset * extent. * * The unit is degrees. */ double GeographicBoundingBox::northBoundLatitude() PROJ_PURE_DEFN { return d->north_; } // --------------------------------------------------------------------------- /** \brief Instantiate a GeographicBoundingBox. * * If east < west, then the bounding box crosses the anti-meridian. * * @param west Western-most coordinate of the limit of the dataset extent (in * degrees). * @param south Southern-most coordinate of the limit of the dataset extent (in * degrees). * @param east Eastern-most coordinate of the limit of the dataset extent (in * degrees). * @param north Northern-most coordinate of the limit of the dataset extent (in * degrees). * @return a new GeographicBoundingBox. */ GeographicBoundingBoxNNPtr GeographicBoundingBox::create(double west, double south, double east, double north) { if (std::isnan(west) || std::isnan(south) || std::isnan(east) || std::isnan(north)) { throw InvalidValueTypeException( "GeographicBoundingBox::create() does not accept NaN values"); } return GeographicBoundingBox::nn_make_shared<GeographicBoundingBox>( west, south, east, north); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool GeographicBoundingBox::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion, const io::DatabaseContextPtr &) const { auto otherExtent = dynamic_cast<const GeographicBoundingBox *>(other); if (!otherExtent) return false; return d->west_ == otherExtent->d->west_ && d->south_ == otherExtent->d->south_ && d->east_ == otherExtent->d->east_ && d->north_ == otherExtent->d->north_; } //! @endcond // --------------------------------------------------------------------------- bool GeographicBoundingBox::contains(const GeographicExtentNNPtr &other) const { auto otherExtent = dynamic_cast<const GeographicBoundingBox *>(other.get()); if (!otherExtent) { return false; } const double W = d->west_; const double E = d->east_; const double N = d->north_; const double S = d->south_; const double oW = otherExtent->d->west_; const double oE = otherExtent->d->east_; const double oN = otherExtent->d->north_; const double oS = otherExtent->d->south_; if (!(S <= oS && N >= oN)) { return false; } if (W == -180.0 && E == 180.0) { return oW != oE; } if (oW == -180.0 && oE == 180.0) { return false; } // Normal bounding box ? if (W < E) { if (oW < oE) { return W <= oW && E >= oE; } else { return false; } // No: crossing antimerian } else { if (oW < oE) { if (oW >= W) { return true; } else if (oE <= E) { return true; } else { return false; } } else { return W <= oW && E >= oE; } } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool GeographicBoundingBox::Private::intersects(const Private &other) const { const double W = west_; const double E = east_; const double N = north_; const double S = south_; const double oW = other.west_; const double oE = other.east_; const double oN = other.north_; const double oS = other.south_; if (N < oS || S > oN) { return false; } if (W == -180.0 && E == 180.0 && oW > oE) { return true; } if (oW == -180.0 && oE == 180.0 && W > E) { return true; } // Normal bounding box ? if (W <= E) { if (oW <= oE) { if (std::max(W, oW) < std::min(E, oE)) { return true; } return false; } // Bail out on longitudes not in [-180,180]. We could probably make // some sense of them, but this check at least avoid potential infinite // recursion. if (oW > 180 || oE < -180) { return false; } return intersects(Private(oW, oS, 180.0, oN)) || intersects(Private(-180.0, oS, oE, oN)); // No: crossing antimerian } else { if (oW <= oE) { return other.intersects(*this); } return true; } } //! @endcond bool GeographicBoundingBox::intersects( const GeographicExtentNNPtr &other) const { auto otherExtent = dynamic_cast<const GeographicBoundingBox *>(other.get()); if (!otherExtent) { return false; } return d->intersects(*(otherExtent->d)); } // --------------------------------------------------------------------------- GeographicExtentPtr GeographicBoundingBox::intersection(const GeographicExtentNNPtr &other) const { auto otherExtent = dynamic_cast<const GeographicBoundingBox *>(other.get()); if (!otherExtent) { return nullptr; } auto ret = d->intersection(*(otherExtent->d)); if (ret) { auto bbox = GeographicBoundingBox::create(ret->west_, ret->south_, ret->east_, ret->north_); return bbox.as_nullable(); } return nullptr; } //! @cond Doxygen_Suppress std::unique_ptr<GeographicBoundingBox::Private> GeographicBoundingBox::Private::intersection(const Private &otherExtent) const { const double W = west_; const double E = east_; const double N = north_; const double S = south_; const double oW = otherExtent.west_; const double oE = otherExtent.east_; const double oN = otherExtent.north_; const double oS = otherExtent.south_; if (N < oS || S > oN) { return nullptr; } if (W == -180.0 && E == 180.0 && oW > oE) { return internal::make_unique<Private>(oW, std::max(S, oS), oE, std::min(N, oN)); } if (oW == -180.0 && oE == 180.0 && W > E) { return internal::make_unique<Private>(W, std::max(S, oS), E, std::min(N, oN)); } // Normal bounding box ? if (W <= E) { if (oW <= oE) { const double resW = std::max(W, oW); const double resE = std::min(E, oE); if (resW < resE) { return internal::make_unique<Private>(resW, std::max(S, oS), resE, std::min(N, oN)); } return nullptr; } // Bail out on longitudes not in [-180,180]. We could probably make // some sense of them, but this check at least avoid potential infinite // recursion. if (oW > 180 || oE < -180) { return nullptr; } // Return larger of two parts of the multipolygon auto inter1 = intersection(Private(oW, oS, 180.0, oN)); auto inter2 = intersection(Private(-180.0, oS, oE, oN)); if (!inter1) { return inter2; } if (!inter2) { return inter1; } if (inter1->east_ - inter1->west_ > inter2->east_ - inter2->west_) { return inter1; } return inter2; // No: crossing antimerian } else { if (oW <= oE) { return otherExtent.intersection(*this); } return internal::make_unique<Private>(std::max(W, oW), std::max(S, oS), std::min(E, oE), std::min(N, oN)); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct VerticalExtent::Private { double minimum_{}; double maximum_{}; common::UnitOfMeasureNNPtr unit_; Private(double minimum, double maximum, const common::UnitOfMeasureNNPtr &unit) : minimum_(minimum), maximum_(maximum), unit_(unit) {} }; //! @endcond // --------------------------------------------------------------------------- VerticalExtent::VerticalExtent(double minimumIn, double maximumIn, const common::UnitOfMeasureNNPtr &unitIn) : d(internal::make_unique<Private>(minimumIn, maximumIn, unitIn)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress VerticalExtent::~VerticalExtent() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Returns the minimum of the vertical extent. */ double VerticalExtent::minimumValue() PROJ_PURE_DEFN { return d->minimum_; } // --------------------------------------------------------------------------- /** \brief Returns the maximum of the vertical extent. */ double VerticalExtent::maximumValue() PROJ_PURE_DEFN { return d->maximum_; } // --------------------------------------------------------------------------- /** \brief Returns the unit of the vertical extent. */ common::UnitOfMeasureNNPtr &VerticalExtent::unit() PROJ_PURE_DEFN { return d->unit_; } // --------------------------------------------------------------------------- /** \brief Instantiate a VerticalExtent. * * @param minimumIn minimum. * @param maximumIn maximum. * @param unitIn unit. * @return a new VerticalExtent. */ VerticalExtentNNPtr VerticalExtent::create(double minimumIn, double maximumIn, const common::UnitOfMeasureNNPtr &unitIn) { return VerticalExtent::nn_make_shared<VerticalExtent>(minimumIn, maximumIn, unitIn); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool VerticalExtent::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion, const io::DatabaseContextPtr &) const { auto otherExtent = dynamic_cast<const VerticalExtent *>(other); if (!otherExtent) return false; return d->minimum_ == otherExtent->d->minimum_ && d->maximum_ == otherExtent->d->maximum_ && d->unit_ == otherExtent->d->unit_; } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns whether this extent contains the other one. */ bool VerticalExtent::contains(const VerticalExtentNNPtr &other) const { const double thisUnitToSI = d->unit_->conversionToSI(); const double otherUnitToSI = other->d->unit_->conversionToSI(); return d->minimum_ * thisUnitToSI <= other->d->minimum_ * otherUnitToSI && d->maximum_ * thisUnitToSI >= other->d->maximum_ * otherUnitToSI; } // --------------------------------------------------------------------------- /** \brief Returns whether this extent intersects the other one. */ bool VerticalExtent::intersects(const VerticalExtentNNPtr &other) const { const double thisUnitToSI = d->unit_->conversionToSI(); const double otherUnitToSI = other->d->unit_->conversionToSI(); return d->minimum_ * thisUnitToSI <= other->d->maximum_ * otherUnitToSI && d->maximum_ * thisUnitToSI >= other->d->minimum_ * otherUnitToSI; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct TemporalExtent::Private { std::string start_{}; std::string stop_{}; Private(const std::string &start, const std::string &stop) : start_(start), stop_(stop) {} }; //! @endcond // --------------------------------------------------------------------------- TemporalExtent::TemporalExtent(const std::string &startIn, const std::string &stopIn) : d(internal::make_unique<Private>(startIn, stopIn)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TemporalExtent::~TemporalExtent() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Returns the start of the temporal extent. */ const std::string &TemporalExtent::start() PROJ_PURE_DEFN { return d->start_; } // --------------------------------------------------------------------------- /** \brief Returns the end of the temporal extent. */ const std::string &TemporalExtent::stop() PROJ_PURE_DEFN { return d->stop_; } // --------------------------------------------------------------------------- /** \brief Instantiate a TemporalExtent. * * @param start start. * @param stop stop. * @return a new TemporalExtent. */ TemporalExtentNNPtr TemporalExtent::create(const std::string &start, const std::string &stop) { return TemporalExtent::nn_make_shared<TemporalExtent>(start, stop); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool TemporalExtent::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion, const io::DatabaseContextPtr &) const { auto otherExtent = dynamic_cast<const TemporalExtent *>(other); if (!otherExtent) return false; return start() == otherExtent->start() && stop() == otherExtent->stop(); } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns whether this extent contains the other one. */ bool TemporalExtent::contains(const TemporalExtentNNPtr &other) const { return start() <= other->start() && stop() >= other->stop(); } // --------------------------------------------------------------------------- /** \brief Returns whether this extent intersects the other one. */ bool TemporalExtent::intersects(const TemporalExtentNNPtr &other) const { return start() <= other->stop() && stop() >= other->start(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Extent::Private { optional<std::string> description_{}; std::vector<GeographicExtentNNPtr> geographicElements_{}; std::vector<VerticalExtentNNPtr> verticalElements_{}; std::vector<TemporalExtentNNPtr> temporalElements_{}; }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Extent::Extent() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- Extent::Extent(const Extent &other) : d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- Extent::~Extent() = default; //! @endcond // --------------------------------------------------------------------------- /** Return a textual description of the extent. * * @return the description, or empty. */ const optional<std::string> &Extent::description() PROJ_PURE_DEFN { return d->description_; } // --------------------------------------------------------------------------- /** Return the geographic element(s) of the extent * * @return the geographic element(s), or empty. */ const std::vector<GeographicExtentNNPtr> & Extent::geographicElements() PROJ_PURE_DEFN { return d->geographicElements_; } // --------------------------------------------------------------------------- /** Return the vertical element(s) of the extent * * @return the vertical element(s), or empty. */ const std::vector<VerticalExtentNNPtr> & Extent::verticalElements() PROJ_PURE_DEFN { return d->verticalElements_; } // --------------------------------------------------------------------------- /** Return the temporal element(s) of the extent * * @return the temporal element(s), or empty. */ const std::vector<TemporalExtentNNPtr> & Extent::temporalElements() PROJ_PURE_DEFN { return d->temporalElements_; } // --------------------------------------------------------------------------- /** \brief Instantiate a Extent. * * @param descriptionIn Textual description, or empty. * @param geographicElementsIn Geographic element(s), or empty. * @param verticalElementsIn Vertical element(s), or empty. * @param temporalElementsIn Temporal element(s), or empty. * @return a new Extent. */ ExtentNNPtr Extent::create(const optional<std::string> &descriptionIn, const std::vector<GeographicExtentNNPtr> &geographicElementsIn, const std::vector<VerticalExtentNNPtr> &verticalElementsIn, const std::vector<TemporalExtentNNPtr> &temporalElementsIn) { auto extent = Extent::nn_make_shared<Extent>(); extent->assignSelf(extent); extent->d->description_ = descriptionIn; extent->d->geographicElements_ = geographicElementsIn; extent->d->verticalElements_ = verticalElementsIn; extent->d->temporalElements_ = temporalElementsIn; return extent; } // --------------------------------------------------------------------------- /** \brief Instantiate a Extent from a bounding box * * @param west Western-most coordinate of the limit of the dataset extent (in * degrees). * @param south Southern-most coordinate of the limit of the dataset extent (in * degrees). * @param east Eastern-most coordinate of the limit of the dataset extent (in * degrees). * @param north Northern-most coordinate of the limit of the dataset extent (in * degrees). * @param descriptionIn Textual description, or empty. * @return a new Extent. */ ExtentNNPtr Extent::createFromBBOX(double west, double south, double east, double north, const util::optional<std::string> &descriptionIn) { return create( descriptionIn, std::vector<GeographicExtentNNPtr>{ nn_static_pointer_cast<GeographicExtent>( GeographicBoundingBox::create(west, south, east, north))}, std::vector<VerticalExtentNNPtr>(), std::vector<TemporalExtentNNPtr>()); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool Extent::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherExtent = dynamic_cast<const Extent *>(other); bool ret = (otherExtent && description().has_value() == otherExtent->description().has_value() && *description() == *otherExtent->description() && d->geographicElements_.size() == otherExtent->d->geographicElements_.size() && d->verticalElements_.size() == otherExtent->d->verticalElements_.size() && d->temporalElements_.size() == otherExtent->d->temporalElements_.size()); if (ret) { for (size_t i = 0; ret && i < d->geographicElements_.size(); ++i) { ret = d->geographicElements_[i]->_isEquivalentTo( otherExtent->d->geographicElements_[i].get(), criterion, dbContext); } for (size_t i = 0; ret && i < d->verticalElements_.size(); ++i) { ret = d->verticalElements_[i]->_isEquivalentTo( otherExtent->d->verticalElements_[i].get(), criterion, dbContext); } for (size_t i = 0; ret && i < d->temporalElements_.size(); ++i) { ret = d->temporalElements_[i]->_isEquivalentTo( otherExtent->d->temporalElements_[i].get(), criterion, dbContext); } } return ret; } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns whether this extent contains the other one. * * Behavior only well specified if each sub-extent category as at most * one element. */ bool Extent::contains(const ExtentNNPtr &other) const { bool res = true; if (d->geographicElements_.size() == 1 && other->d->geographicElements_.size() == 1) { res = d->geographicElements_[0]->contains( other->d->geographicElements_[0]); } if (res && d->verticalElements_.size() == 1 && other->d->verticalElements_.size() == 1) { res = d->verticalElements_[0]->contains(other->d->verticalElements_[0]); } if (res && d->temporalElements_.size() == 1 && other->d->temporalElements_.size() == 1) { res = d->temporalElements_[0]->contains(other->d->temporalElements_[0]); } return res; } // --------------------------------------------------------------------------- /** \brief Returns whether this extent intersects the other one. * * Behavior only well specified if each sub-extent category as at most * one element. */ bool Extent::intersects(const ExtentNNPtr &other) const { bool res = true; if (d->geographicElements_.size() == 1 && other->d->geographicElements_.size() == 1) { res = d->geographicElements_[0]->intersects( other->d->geographicElements_[0]); } if (res && d->verticalElements_.size() == 1 && other->d->verticalElements_.size() == 1) { res = d->verticalElements_[0]->intersects(other->d->verticalElements_[0]); } if (res && d->temporalElements_.size() == 1 && other->d->temporalElements_.size() == 1) { res = d->temporalElements_[0]->intersects(other->d->temporalElements_[0]); } return res; } // --------------------------------------------------------------------------- /** \brief Returns the intersection of this extent with another one. * * Behavior only well specified if there is one single GeographicExtent * in each object. * Returns nullptr otherwise. */ ExtentPtr Extent::intersection(const ExtentNNPtr &other) const { if (d->geographicElements_.size() == 1 && other->d->geographicElements_.size() == 1) { if (contains(other)) { return other.as_nullable(); } auto self = util::nn_static_pointer_cast<Extent>(shared_from_this()); if (other->contains(self)) { return self.as_nullable(); } auto geogIntersection = d->geographicElements_[0]->intersection( other->d->geographicElements_[0]); if (geogIntersection) { return create(util::optional<std::string>(), std::vector<GeographicExtentNNPtr>{ NN_NO_CHECK(geogIntersection)}, std::vector<VerticalExtentNNPtr>{}, std::vector<TemporalExtentNNPtr>{}); } } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Identifier::Private { optional<Citation> authority_{}; std::string code_{}; optional<std::string> codeSpace_{}; optional<std::string> version_{}; optional<std::string> description_{}; optional<std::string> uri_{}; Private() = default; Private(const std::string &codeIn, const PropertyMap &properties) : code_(codeIn) { setProperties(properties); } private: // cppcheck-suppress functionStatic void setProperties(const PropertyMap &properties); }; // --------------------------------------------------------------------------- void Identifier::Private::setProperties( const PropertyMap &properties) // throw(InvalidValueTypeException) { { const auto pVal = properties.get(AUTHORITY_KEY); if (pVal) { if (auto genVal = dynamic_cast<const BoxedValue *>(pVal->get())) { if (genVal->type() == BoxedValue::Type::STRING) { authority_ = Citation(genVal->stringValue()); } else { throw InvalidValueTypeException("Invalid value type for " + AUTHORITY_KEY); } } else { if (auto citation = dynamic_cast<const Citation *>(pVal->get())) { authority_ = *citation; } else { throw InvalidValueTypeException("Invalid value type for " + AUTHORITY_KEY); } } } } { const auto pVal = properties.get(CODE_KEY); if (pVal) { if (auto genVal = dynamic_cast<const BoxedValue *>(pVal->get())) { if (genVal->type() == BoxedValue::Type::INTEGER) { code_ = toString(genVal->integerValue()); } else if (genVal->type() == BoxedValue::Type::STRING) { code_ = genVal->stringValue(); } else { throw InvalidValueTypeException("Invalid value type for " + CODE_KEY); } } else { throw InvalidValueTypeException("Invalid value type for " + CODE_KEY); } } } properties.getStringValue(CODESPACE_KEY, codeSpace_); properties.getStringValue(VERSION_KEY, version_); properties.getStringValue(DESCRIPTION_KEY, description_); properties.getStringValue(URI_KEY, uri_); } //! @endcond // --------------------------------------------------------------------------- Identifier::Identifier(const std::string &codeIn, const util::PropertyMap &properties) : d(internal::make_unique<Private>(codeIn, properties)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- Identifier::Identifier() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- Identifier::Identifier(const Identifier &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- Identifier::~Identifier() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a Identifier. * * @param codeIn Alphanumeric value identifying an instance in the codespace * @param properties See \ref general_properties. * Generally, the Identifier::CODESPACE_KEY should be set. * @return a new Identifier. */ IdentifierNNPtr Identifier::create(const std::string &codeIn, const PropertyMap &properties) { return Identifier::nn_make_shared<Identifier>(codeIn, properties); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress IdentifierNNPtr Identifier::createFromDescription(const std::string &descriptionIn) { auto id = Identifier::nn_make_shared<Identifier>(); id->d->description_ = descriptionIn; return id; } //! @endcond // --------------------------------------------------------------------------- /** \brief Return a citation for the organization responsible for definition and * maintenance of the code. * * @return the citation for the authority, or empty. */ const optional<Citation> &Identifier::authority() PROJ_PURE_DEFN { return d->authority_; } // --------------------------------------------------------------------------- /** \brief Return the alphanumeric value identifying an instance in the * codespace. * * e.g. "4326" (for EPSG:4326 WGS 84 GeographicCRS) * * @return the code. */ const std::string &Identifier::code() PROJ_PURE_DEFN { return d->code_; } // --------------------------------------------------------------------------- /** \brief Return the organization responsible for definition and maintenance of * the code. * * e.g "EPSG" * * @return the authority codespace, or empty. */ const optional<std::string> &Identifier::codeSpace() PROJ_PURE_DEFN { return d->codeSpace_; } // --------------------------------------------------------------------------- /** \brief Return the version identifier for the namespace. * * When appropriate, the edition is identified by the effective date, coded * using ISO 8601 date format. * * @return the version or empty. */ const optional<std::string> &Identifier::version() PROJ_PURE_DEFN { return d->version_; } // --------------------------------------------------------------------------- /** \brief Return the natural language description of the meaning of the code * value. * * @return the description or empty. */ const optional<std::string> &Identifier::description() PROJ_PURE_DEFN { return d->description_; } // --------------------------------------------------------------------------- /** \brief Return the URI of the identifier. * * @return the URI or empty. */ const optional<std::string> &Identifier::uri() PROJ_PURE_DEFN { return d->uri_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Identifier::_exportToWKT(WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == WKTFormatter::Version::WKT2; const std::string &l_code = code(); std::string l_codeSpace = *codeSpace(); std::string l_version = *version(); const auto &dbContext = formatter->databaseContext(); if (dbContext) { dbContext->getAuthorityAndVersion(*codeSpace(), l_codeSpace, l_version); } if (!l_codeSpace.empty() && !l_code.empty()) { if (isWKT2) { formatter->startNode(WKTConstants::ID, false); formatter->addQuotedString(l_codeSpace); try { (void)std::stoi(l_code); formatter->add(l_code); } catch (const std::exception &) { formatter->addQuotedString(l_code); } if (!l_version.empty()) { bool isDouble = false; (void)c_locale_stod(l_version, isDouble); if (isDouble) { formatter->add(l_version); } else { formatter->addQuotedString(l_version); } } if (authority().has_value() && *(authority()->title()) != *codeSpace()) { formatter->startNode(WKTConstants::CITATION, false); formatter->addQuotedString(*(authority()->title())); formatter->endNode(); } if (uri().has_value()) { formatter->startNode(WKTConstants::URI, false); formatter->addQuotedString(*(uri())); formatter->endNode(); } formatter->endNode(); } else { formatter->startNode(WKTConstants::AUTHORITY, false); formatter->addQuotedString(l_codeSpace); formatter->addQuotedString(l_code); formatter->endNode(); } } } // --------------------------------------------------------------------------- void Identifier::_exportToJSON(JSONFormatter *formatter) const { const std::string &l_code = code(); std::string l_codeSpace = *codeSpace(); std::string l_version = *version(); const auto &dbContext = formatter->databaseContext(); if (dbContext) { dbContext->getAuthorityAndVersion(*codeSpace(), l_codeSpace, l_version); } if (!l_codeSpace.empty() && !l_code.empty()) { auto writer = formatter->writer(); auto objContext(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("authority"); writer->Add(l_codeSpace); writer->AddObjKey("code"); try { writer->Add(std::stoi(l_code)); } catch (const std::exception &) { writer->Add(l_code); } if (!l_version.empty()) { writer->AddObjKey("version"); bool isDouble = false; (void)c_locale_stod(l_version, isDouble); if (isDouble) { writer->AddUnquoted(l_version.c_str()); } else { writer->Add(l_version); } } if (authority().has_value() && *(authority()->title()) != *codeSpace()) { writer->AddObjKey("authority_citation"); writer->Add(*(authority()->title())); } if (uri().has_value()) { writer->AddObjKey("uri"); writer->Add(*(uri())); } } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool isIgnoredChar(char ch) { return ch == ' ' || ch == '_' || ch == '-' || ch == '/' || ch == '(' || ch == ')' || ch == '.' || ch == '&' || ch == ','; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const struct utf8_to_lower { const char *utf8; char ascii; } map_utf8_to_lower[] = { {"\xc3\xa1", 'a'}, // a acute {"\xc3\xa4", 'a'}, // a tremma {"\xc4\x9b", 'e'}, // e reverse circumflex {"\xc3\xa8", 'e'}, // e grave {"\xc3\xa9", 'e'}, // e acute {"\xc3\xab", 'e'}, // e tremma {"\xc3\xad", 'i'}, // i grave {"\xc3\xb4", 'o'}, // o circumflex {"\xc3\xb6", 'o'}, // o tremma {"\xc3\xa7", 'c'}, // c cedilla }; static const struct utf8_to_lower *get_ascii_replacement(const char *c_str) { for (const auto &pair : map_utf8_to_lower) { if (*c_str == pair.utf8[0] && strncmp(c_str, pair.utf8, strlen(pair.utf8)) == 0) { return &pair; } } return nullptr; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::string Identifier::canonicalizeName(const std::string &str) { std::string res; const char *c_str = str.c_str(); for (size_t i = 0; c_str[i] != 0; ++i) { const auto ch = c_str[i]; if (ch == ' ' && c_str[i + 1] == '+' && c_str[i + 2] == ' ') { i += 2; continue; } if (ch == '1' && !res.empty() && !(res.back() >= '0' && res.back() <= '9') && c_str[i + 1] == '9' && c_str[i + 2] >= '0' && c_str[i + 2] <= '9') { ++i; continue; } if (static_cast<unsigned char>(ch) > 127) { const auto *replacement = get_ascii_replacement(c_str + i); if (replacement) { res.push_back(replacement->ascii); i += strlen(replacement->utf8) - 1; continue; } } if (!isIgnoredChar(ch)) { res.push_back(static_cast<char>(::tolower(ch))); } } return res; } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns whether two names are considered equivalent. * * Two names are equivalent by removing any space, underscore, dash, slash, * { or } character from them, and comparing in a case insensitive way. */ bool Identifier::isEquivalentName(const char *a, const char *b) noexcept { size_t i = 0; size_t j = 0; char lastValidA = 0; char lastValidB = 0; while (a[i] != 0 || b[j] != 0) { char aCh = a[i]; char bCh = b[j]; if (aCh == ' ' && a[i + 1] == '+' && a[i + 2] == ' ' && a[i + 3] != 0) { i += 3; continue; } if (bCh == ' ' && b[j + 1] == '+' && b[j + 2] == ' ' && b[j + 3] != 0) { j += 3; continue; } if (isIgnoredChar(aCh)) { ++i; continue; } if (isIgnoredChar(bCh)) { ++j; continue; } if (aCh == '1' && !(lastValidA >= '0' && lastValidA <= '9') && a[i + 1] == '9' && a[i + 2] >= '0' && a[i + 2] <= '9') { i += 2; lastValidA = '9'; continue; } if (bCh == '1' && !(lastValidB >= '0' && lastValidB <= '9') && b[j + 1] == '9' && b[j + 2] >= '0' && b[j + 2] <= '9') { j += 2; lastValidB = '9'; continue; } if (static_cast<unsigned char>(aCh) > 127) { const auto *replacement = get_ascii_replacement(a + i); if (replacement) { aCh = replacement->ascii; i += strlen(replacement->utf8) - 1; } } if (static_cast<unsigned char>(bCh) > 127) { const auto *replacement = get_ascii_replacement(b + j); if (replacement) { bCh = replacement->ascii; j += strlen(replacement->utf8) - 1; } } if ((aCh == 0 && bCh != 0) || (aCh != 0 && bCh == 0) || ::tolower(aCh) != ::tolower(bCh)) { return false; } lastValidA = aCh; lastValidB = bCh; if (aCh != 0) ++i; if (bCh != 0) ++j; } return true; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PositionalAccuracy::Private { std::string value_{}; }; //! @endcond // --------------------------------------------------------------------------- PositionalAccuracy::PositionalAccuracy(const std::string &valueIn) : d(internal::make_unique<Private>()) { d->value_ = valueIn; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PositionalAccuracy::~PositionalAccuracy() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the value of the positional accuracy. */ const std::string &PositionalAccuracy::value() PROJ_PURE_DEFN { return d->value_; } // --------------------------------------------------------------------------- /** \brief Instantiate a PositionalAccuracy. * * @param valueIn positional accuracy value. * @return a new PositionalAccuracy. */ PositionalAccuracyNNPtr PositionalAccuracy::create(const std::string &valueIn) { return PositionalAccuracy::nn_make_shared<PositionalAccuracy>(valueIn); } } // namespace metadata NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/datum.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/datum.hpp" #include "proj/common.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/datum_internal.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // clang-format on #include "proj_json_streaming_writer.hpp" #include <cmath> #include <cstdlib> #include <memory> #include <string> using namespace NS_PROJ::internal; #if 0 namespace dropbox{ namespace oxygen { template<> nn<NS_PROJ::datum::DatumPtr>::~nn() = default; template<> nn<NS_PROJ::datum::DatumEnsemblePtr>::~nn() = default; template<> nn<NS_PROJ::datum::PrimeMeridianPtr>::~nn() = default; template<> nn<NS_PROJ::datum::EllipsoidPtr>::~nn() = default; template<> nn<NS_PROJ::datum::GeodeticReferenceFramePtr>::~nn() = default; template<> nn<NS_PROJ::datum::DynamicGeodeticReferenceFramePtr>::~nn() = default; template<> nn<NS_PROJ::datum::VerticalReferenceFramePtr>::~nn() = default; template<> nn<NS_PROJ::datum::DynamicVerticalReferenceFramePtr>::~nn() = default; template<> nn<NS_PROJ::datum::EngineeringDatumPtr>::~nn() = default; template<> nn<NS_PROJ::datum::TemporalDatumPtr>::~nn() = default; template<> nn<NS_PROJ::datum::ParametricDatumPtr>::~nn() = default; }} #endif NS_PROJ_START namespace datum { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static util::PropertyMap createMapNameEPSGCode(const char *name, int code) { return util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, code); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Datum::Private { util::optional<std::string> anchorDefinition{}; std::shared_ptr<util::optional<common::Measure>> anchorEpoch = std::make_shared<util::optional<common::Measure>>(); util::optional<common::DateTime> publicationDate{}; common::IdentifiedObjectPtr conventionalRS{}; // cppcheck-suppress functionStatic void exportAnchorDefinition(io::WKTFormatter *formatter) const; // cppcheck-suppress functionStatic void exportAnchorEpoch(io::WKTFormatter *formatter) const; // cppcheck-suppress functionStatic void exportAnchorDefinition(io::JSONFormatter *formatter) const; // cppcheck-suppress functionStatic void exportAnchorEpoch(io::JSONFormatter *formatter) const; }; // --------------------------------------------------------------------------- void Datum::Private::exportAnchorDefinition(io::WKTFormatter *formatter) const { if (anchorDefinition) { formatter->startNode(io::WKTConstants::ANCHOR, false); formatter->addQuotedString(*anchorDefinition); formatter->endNode(); } } // --------------------------------------------------------------------------- void Datum::Private::exportAnchorEpoch(io::WKTFormatter *formatter) const { if (anchorEpoch->has_value()) { formatter->startNode(io::WKTConstants::ANCHOREPOCH, false); const double year = (*anchorEpoch)->convertToUnit(common::UnitOfMeasure::YEAR); formatter->add(getRoundedEpochInDecimalYear(year)); formatter->endNode(); } } // --------------------------------------------------------------------------- void Datum::Private::exportAnchorDefinition( io::JSONFormatter *formatter) const { if (anchorDefinition) { auto writer = formatter->writer(); writer->AddObjKey("anchor"); writer->Add(*anchorDefinition); } } // --------------------------------------------------------------------------- void Datum::Private::exportAnchorEpoch(io::JSONFormatter *formatter) const { if (anchorEpoch->has_value()) { auto writer = formatter->writer(); writer->AddObjKey("anchor_epoch"); const double year = (*anchorEpoch)->convertToUnit(common::UnitOfMeasure::YEAR); writer->Add(getRoundedEpochInDecimalYear(year)); } } //! @endcond // --------------------------------------------------------------------------- Datum::Datum() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- #ifdef notdef Datum::Datum(const Datum &other) : ObjectUsage(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Datum::~Datum() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the anchor definition. * * A description - possibly including coordinates of an identified point or * points - of the relationship used to anchor a coordinate system to the * Earth or alternate object. * <ul> * <li>For modern geodetic reference frames the anchor may be a set of station * coordinates; if the reference frame is dynamic it will also include * coordinate velocities. For a traditional geodetic datum, this anchor may be * a point known as the fundamental point, which is traditionally the point * where the relationship between geoid and ellipsoid is defined, together * with a direction from that point.</li> * <li>For a vertical reference frame the anchor may be the zero level at one * or more defined locations or a conventionally defined surface.</li> * <li>For an engineering datum, the anchor may be an identified physical point * with the orientation defined relative to the object.</li> * </ul> * * @return the anchor definition, or empty. */ const util::optional<std::string> &Datum::anchorDefinition() const { return d->anchorDefinition; } // --------------------------------------------------------------------------- /** \brief Return the anchor epoch. * * Epoch at which a static reference frame matches a dynamic reference frame * from which it has been derived. * * Note: Not to be confused with the frame reference epoch of dynamic geodetic * and dynamic vertical reference frames. Nor with the epoch at which a * reference frame is defined to be aligned with another reference frame; * this information should be included in the datum anchor definition. * * @return the anchor epoch, or empty. * @since 9.2 */ const util::optional<common::Measure> &Datum::anchorEpoch() const { return *(d->anchorEpoch); } // --------------------------------------------------------------------------- /** \brief Return the date on which the datum definition was published. * * \note Departure from \ref ISO_19111_2019 : we return a DateTime instead of * a Citation::Date. * * @return the publication date, or empty. */ const util::optional<common::DateTime> &Datum::publicationDate() const { return d->publicationDate; } // --------------------------------------------------------------------------- /** \brief Return the conventional reference system. * * This is the name, identifier, alias and remarks for the terrestrial * reference system or vertical reference system realized by this reference * frame, for example "ITRS" for ITRF88 through ITRF2008 and ITRF2014, or * "EVRS" for EVRF2000 and EVRF2007. * * @return the conventional reference system, or nullptr. */ const common::IdentifiedObjectPtr &Datum::conventionalRS() const { return d->conventionalRS; } // --------------------------------------------------------------------------- void Datum::setAnchor(const util::optional<std::string> &anchor) { d->anchorDefinition = anchor; } // --------------------------------------------------------------------------- void Datum::setAnchorEpoch(const util::optional<common::Measure> &anchorEpoch) { d->anchorEpoch = std::make_shared<util::optional<common::Measure>>(anchorEpoch); } // --------------------------------------------------------------------------- void Datum::setProperties( const util::PropertyMap &properties) // throw(InvalidValueTypeException) { std::string publicationDateResult; properties.getStringValue("PUBLICATION_DATE", publicationDateResult); if (!publicationDateResult.empty()) { d->publicationDate = common::DateTime::create(publicationDateResult); } std::string anchorEpoch; properties.getStringValue("ANCHOR_EPOCH", anchorEpoch); if (!anchorEpoch.empty()) { bool success = false; const double anchorEpochYear = c_locale_stod(anchorEpoch, success); if (success) { setAnchorEpoch(util::optional<common::Measure>( common::Measure(anchorEpochYear, common::UnitOfMeasure::YEAR))); } } ObjectUsage::setProperties(properties); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool Datum::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDatum = dynamic_cast<const Datum *>(other); if (otherDatum == nullptr || !ObjectUsage::_isEquivalentTo(other, criterion, dbContext)) { return false; } if (criterion == util::IComparable::Criterion::STRICT) { if ((anchorDefinition().has_value() ^ otherDatum->anchorDefinition().has_value())) { return false; } if (anchorDefinition().has_value() && otherDatum->anchorDefinition().has_value() && *anchorDefinition() != *otherDatum->anchorDefinition()) { return false; } if ((publicationDate().has_value() ^ otherDatum->publicationDate().has_value())) { return false; } if (publicationDate().has_value() && otherDatum->publicationDate().has_value() && publicationDate()->toString() != otherDatum->publicationDate()->toString()) { return false; } if (((conventionalRS() != nullptr) ^ (otherDatum->conventionalRS() != nullptr))) { return false; } if (conventionalRS() && otherDatum->conventionalRS() && conventionalRS()->_isEquivalentTo( otherDatum->conventionalRS().get(), criterion, dbContext)) { return false; } } return true; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PrimeMeridian::Private { common::Angle longitude_{}; explicit Private(const common::Angle &longitude) : longitude_(longitude) {} }; //! @endcond // --------------------------------------------------------------------------- PrimeMeridian::PrimeMeridian(const common::Angle &longitudeIn) : d(internal::make_unique<Private>(longitudeIn)) {} // --------------------------------------------------------------------------- #ifdef notdef PrimeMeridian::PrimeMeridian(const PrimeMeridian &other) : common::IdentifiedObject(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PrimeMeridian::~PrimeMeridian() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the longitude of the prime meridian. * * It is measured from the internationally-recognised reference meridian * ('Greenwich meridian'), positive eastward. * The default value is 0 degrees. * * @return the longitude of the prime meridian. */ const common::Angle &PrimeMeridian::longitude() PROJ_PURE_DEFN { return d->longitude_; } // --------------------------------------------------------------------------- /** \brief Instantiate a PrimeMeridian. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param longitudeIn the longitude of the prime meridian. * @return new PrimeMeridian. */ PrimeMeridianNNPtr PrimeMeridian::create(const util::PropertyMap &properties, const common::Angle &longitudeIn) { auto pm(PrimeMeridian::nn_make_shared<PrimeMeridian>(longitudeIn)); pm->setProperties(properties); return pm; } // --------------------------------------------------------------------------- const PrimeMeridianNNPtr PrimeMeridian::createGREENWICH() { return create(createMapNameEPSGCode("Greenwich", 8901), common::Angle(0)); } // --------------------------------------------------------------------------- const PrimeMeridianNNPtr PrimeMeridian::createREFERENCE_MERIDIAN() { return create(util::PropertyMap().set(IdentifiedObject::NAME_KEY, "Reference meridian"), common::Angle(0)); } // --------------------------------------------------------------------------- const PrimeMeridianNNPtr PrimeMeridian::createPARIS() { return create(createMapNameEPSGCode("Paris", 8903), common::Angle(2.5969213, common::UnitOfMeasure::GRAD)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void PrimeMeridian::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; std::string l_name(name()->description().has_value() ? nameStr() : "Greenwich"); if (!(isWKT2 && formatter->primeMeridianOmittedIfGreenwich() && l_name == "Greenwich")) { formatter->startNode(io::WKTConstants::PRIMEM, !identifiers().empty()); if (formatter->useESRIDialect()) { bool aliasFound = false; const auto &dbContext = formatter->databaseContext(); if (dbContext) { auto l_alias = dbContext->getAliasFromOfficialName( l_name, "prime_meridian", "ESRI"); if (!l_alias.empty()) { l_name = std::move(l_alias); aliasFound = true; } } if (!aliasFound && dbContext) { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), "ESRI"); aliasFound = authFactory ->createObjectsFromName( l_name, {io::AuthorityFactory::ObjectType::PRIME_MERIDIAN}, false // approximateMatch ) .size() == 1; } if (!aliasFound) { l_name = io::WKTFormatter::morphNameToESRI(l_name); } } formatter->addQuotedString(l_name); const auto &l_long = longitude(); if (formatter->primeMeridianInDegree()) { formatter->add(l_long.convertToUnit(common::UnitOfMeasure::DEGREE)); } else { formatter->add(l_long.value()); } const auto &unit = l_long.unit(); if (isWKT2) { if (!(formatter ->primeMeridianOrParameterUnitOmittedIfSameAsAxis() && unit == *(formatter->axisAngularUnit()))) { unit._exportToWKT(formatter, io::WKTConstants::ANGLEUNIT); } } else if (!formatter->primeMeridianInDegree()) { unit._exportToWKT(formatter); } if (formatter->outputId()) { formatID(formatter); } formatter->endNode(); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void PrimeMeridian::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("PrimeMeridian", !identifiers().empty())); writer->AddObjKey("name"); std::string l_name = name()->description().has_value() ? nameStr() : "Greenwich"; writer->Add(l_name); const auto &l_long = longitude(); writer->AddObjKey("longitude"); const auto &unit = l_long.unit(); if (unit == common::UnitOfMeasure::DEGREE) { writer->Add(l_long.value(), 15); } else { auto longitudeContext(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("value"); writer->Add(l_long.value(), 15); writer->AddObjKey("unit"); unit._exportToJSON(formatter); } if (formatter->outputId()) { formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::string PrimeMeridian::getPROJStringWellKnownName(const common::Angle &angle) { const double valRad = angle.getSIValue(); std::string projPMName; PJ_CONTEXT *ctxt = proj_context_create(); auto proj_pm = proj_list_prime_meridians(); for (int i = 0; proj_pm[i].id != nullptr; ++i) { double valRefRad = dmstor_ctx(ctxt, proj_pm[i].defn, nullptr); if (::fabs(valRad - valRefRad) < 1e-10) { projPMName = proj_pm[i].id; break; } } proj_context_destroy(ctxt); return projPMName; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void PrimeMeridian::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(FormattingException) { if (longitude().getSIValue() != 0) { std::string projPMName(getPROJStringWellKnownName(longitude())); if (!projPMName.empty()) { formatter->addParam("pm", projPMName); } else { const double valDeg = longitude().convertToUnit(common::UnitOfMeasure::DEGREE); formatter->addParam("pm", valDeg); } } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool PrimeMeridian::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherPM = dynamic_cast<const PrimeMeridian *>(other); if (otherPM == nullptr || !IdentifiedObject::_isEquivalentTo(other, criterion, dbContext)) { return false; } // In MapInfo, the Paris prime meridian is returned as 2.3372291666667 // instead of the official value of 2.33722917, which is a relative // error in the 1e-9 range. return longitude()._isEquivalentTo(otherPM->longitude(), criterion, 1e-8); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Ellipsoid::Private { common::Length semiMajorAxis_{}; util::optional<common::Scale> inverseFlattening_{}; util::optional<common::Length> semiMinorAxis_{}; util::optional<common::Length> semiMedianAxis_{}; std::string celestialBody_{}; explicit Private(const common::Length &radius, const std::string &celestialBody) : semiMajorAxis_(radius), celestialBody_(celestialBody) {} Private(const common::Length &semiMajorAxisIn, const common::Scale &invFlattening, const std::string &celestialBody) : semiMajorAxis_(semiMajorAxisIn), inverseFlattening_(invFlattening), celestialBody_(celestialBody) {} Private(const common::Length &semiMajorAxisIn, const common::Length &semiMinorAxisIn, const std::string &celestialBody) : semiMajorAxis_(semiMajorAxisIn), semiMinorAxis_(semiMinorAxisIn), celestialBody_(celestialBody) {} }; //! @endcond // --------------------------------------------------------------------------- Ellipsoid::Ellipsoid(const common::Length &radius, const std::string &celestialBodyIn) : d(internal::make_unique<Private>(radius, celestialBodyIn)) {} // --------------------------------------------------------------------------- Ellipsoid::Ellipsoid(const common::Length &semiMajorAxisIn, const common::Scale &invFlattening, const std::string &celestialBodyIn) : d(internal::make_unique<Private>(semiMajorAxisIn, invFlattening, celestialBodyIn)) {} // --------------------------------------------------------------------------- Ellipsoid::Ellipsoid(const common::Length &semiMajorAxisIn, const common::Length &semiMinorAxisIn, const std::string &celestialBodyIn) : d(internal::make_unique<Private>(semiMajorAxisIn, semiMinorAxisIn, celestialBodyIn)) {} // --------------------------------------------------------------------------- #ifdef notdef Ellipsoid::Ellipsoid(const Ellipsoid &other) : common::IdentifiedObject(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Ellipsoid::~Ellipsoid() = default; Ellipsoid::Ellipsoid(const Ellipsoid &other) : IdentifiedObject(other), d(internal::make_unique<Private>(*(other.d))) {} //! @endcond // --------------------------------------------------------------------------- /** \brief Return the length of the semi-major axis of the ellipsoid. * * @return the semi-major axis. */ const common::Length &Ellipsoid::semiMajorAxis() PROJ_PURE_DEFN { return d->semiMajorAxis_; } // --------------------------------------------------------------------------- /** \brief Return the inverse flattening value of the ellipsoid, if the * ellipsoid * has been defined with this value. * * @see computeInverseFlattening() that will always return a valid value of the * inverse flattening, whether the ellipsoid has been defined through inverse * flattening or semi-minor axis. * * @return the inverse flattening value of the ellipsoid, or empty. */ const util::optional<common::Scale> & Ellipsoid::inverseFlattening() PROJ_PURE_DEFN { return d->inverseFlattening_; } // --------------------------------------------------------------------------- /** \brief Return the length of the semi-minor axis of the ellipsoid, if the * ellipsoid * has been defined with this value. * * @see computeSemiMinorAxis() that will always return a valid value of the * semi-minor axis, whether the ellipsoid has been defined through inverse * flattening or semi-minor axis. * * @return the semi-minor axis of the ellipsoid, or empty. */ const util::optional<common::Length> & Ellipsoid::semiMinorAxis() PROJ_PURE_DEFN { return d->semiMinorAxis_; } // --------------------------------------------------------------------------- /** \brief Return whether the ellipsoid is spherical. * * That is to say is semiMajorAxis() == computeSemiMinorAxis(). * * A sphere is completely defined by the semi-major axis, which is the radius * of the sphere. * * @return true if the ellipsoid is spherical. */ bool Ellipsoid::isSphere() PROJ_PURE_DEFN { if (d->inverseFlattening_.has_value()) { return d->inverseFlattening_->value() == 0; } if (semiMinorAxis().has_value()) { return semiMajorAxis() == *semiMinorAxis(); } return true; } // --------------------------------------------------------------------------- /** \brief Return the length of the semi-median axis of a triaxial ellipsoid * * This parameter is not required for a biaxial ellipsoid. * * @return the semi-median axis of the ellipsoid, or empty. */ const util::optional<common::Length> & Ellipsoid::semiMedianAxis() PROJ_PURE_DEFN { return d->semiMedianAxis_; } // --------------------------------------------------------------------------- /** \brief Return or compute the inverse flattening value of the ellipsoid. * * If computed, the inverse flattening is the result of a / (a - b), * where a is the semi-major axis and b the semi-minor axis. * * @return the inverse flattening value of the ellipsoid, or 0 for a sphere. */ double Ellipsoid::computedInverseFlattening() PROJ_PURE_DEFN { if (d->inverseFlattening_.has_value()) { return d->inverseFlattening_->getSIValue(); } if (d->semiMinorAxis_.has_value()) { const double a = d->semiMajorAxis_.getSIValue(); const double b = d->semiMinorAxis_->getSIValue(); return (a == b) ? 0.0 : a / (a - b); } return 0.0; } // --------------------------------------------------------------------------- /** \brief Return the squared eccentricity of the ellipsoid. * * @return the squared eccentricity, or a negative value if invalid. */ double Ellipsoid::squaredEccentricity() PROJ_PURE_DEFN { const double rf = computedInverseFlattening(); const double f = rf != 0.0 ? 1. / rf : 0.0; const double e2 = f * (2 - f); return e2; } // --------------------------------------------------------------------------- /** \brief Return or compute the length of the semi-minor axis of the ellipsoid. * * If computed, the semi-minor axis is the result of a * (1 - 1 / rf) * where a is the semi-major axis and rf the reverse/inverse flattening. * @return the semi-minor axis of the ellipsoid. */ common::Length Ellipsoid::computeSemiMinorAxis() const { if (d->semiMinorAxis_.has_value()) { return *d->semiMinorAxis_; } if (inverseFlattening().has_value()) { return common::Length( (1.0 - 1.0 / d->inverseFlattening_->getSIValue()) * d->semiMajorAxis_.value(), d->semiMajorAxis_.unit()); } return d->semiMajorAxis_; } // --------------------------------------------------------------------------- /** \brief Return the name of the celestial body on which the ellipsoid refers * to. */ const std::string &Ellipsoid::celestialBody() PROJ_PURE_DEFN { return d->celestialBody_; } // --------------------------------------------------------------------------- /** \brief Instantiate a Ellipsoid as a sphere. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param radius the sphere radius (semi-major axis). * @param celestialBody Name of the celestial body on which the ellipsoid refers * to. * @return new Ellipsoid. */ EllipsoidNNPtr Ellipsoid::createSphere(const util::PropertyMap &properties, const common::Length &radius, const std::string &celestialBody) { auto ellipsoid(Ellipsoid::nn_make_shared<Ellipsoid>(radius, celestialBody)); ellipsoid->setProperties(properties); return ellipsoid; } // --------------------------------------------------------------------------- /** \brief Instantiate a Ellipsoid from its inverse/reverse flattening. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param semiMajorAxisIn the semi-major axis. * @param invFlattening the inverse/reverse flattening. If set to 0, this will * be considered as a sphere. * @param celestialBody Name of the celestial body on which the ellipsoid refers * to. * @return new Ellipsoid. */ EllipsoidNNPtr Ellipsoid::createFlattenedSphere( const util::PropertyMap &properties, const common::Length &semiMajorAxisIn, const common::Scale &invFlattening, const std::string &celestialBody) { auto ellipsoid(invFlattening.value() == 0 ? Ellipsoid::nn_make_shared<Ellipsoid>(semiMajorAxisIn, celestialBody) : Ellipsoid::nn_make_shared<Ellipsoid>( semiMajorAxisIn, invFlattening, celestialBody)); ellipsoid->setProperties(properties); return ellipsoid; } // --------------------------------------------------------------------------- /** \brief Instantiate a Ellipsoid from the value of its two semi axis. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param semiMajorAxisIn the semi-major axis. * @param semiMinorAxisIn the semi-minor axis. * @param celestialBody Name of the celestial body on which the ellipsoid refers * to. * @return new Ellipsoid. */ EllipsoidNNPtr Ellipsoid::createTwoAxis(const util::PropertyMap &properties, const common::Length &semiMajorAxisIn, const common::Length &semiMinorAxisIn, const std::string &celestialBody) { auto ellipsoid(Ellipsoid::nn_make_shared<Ellipsoid>( semiMajorAxisIn, semiMinorAxisIn, celestialBody)); ellipsoid->setProperties(properties); return ellipsoid; } // --------------------------------------------------------------------------- const EllipsoidNNPtr Ellipsoid::createCLARKE_1866() { return createTwoAxis(createMapNameEPSGCode("Clarke 1866", 7008), common::Length(6378206.4), common::Length(6356583.8)); } // --------------------------------------------------------------------------- const EllipsoidNNPtr Ellipsoid::createWGS84() { return createFlattenedSphere(createMapNameEPSGCode("WGS 84", 7030), common::Length(6378137), common::Scale(298.257223563)); } // --------------------------------------------------------------------------- const EllipsoidNNPtr Ellipsoid::createGRS1980() { return createFlattenedSphere(createMapNameEPSGCode("GRS 1980", 7019), common::Length(6378137), common::Scale(298.257222101)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Ellipsoid::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; formatter->startNode(isWKT2 ? io::WKTConstants::ELLIPSOID : io::WKTConstants::SPHEROID, !identifiers().empty()); { std::string l_name(nameStr()); if (l_name.empty()) { formatter->addQuotedString("unnamed"); } else { if (formatter->useESRIDialect()) { if (l_name == "WGS 84") { l_name = "WGS_1984"; } else { bool aliasFound = false; const auto &dbContext = formatter->databaseContext(); if (dbContext) { auto l_alias = dbContext->getAliasFromOfficialName( l_name, "ellipsoid", "ESRI"); if (!l_alias.empty()) { l_name = std::move(l_alias); aliasFound = true; } } if (!aliasFound && dbContext) { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), "ESRI"); aliasFound = authFactory ->createObjectsFromName( l_name, {io::AuthorityFactory::ObjectType:: ELLIPSOID}, false // approximateMatch ) .size() == 1; } if (!aliasFound) { l_name = io::WKTFormatter::morphNameToESRI(l_name); } } } formatter->addQuotedString(l_name); } const auto &semiMajor = semiMajorAxis(); if (isWKT2) { formatter->add(semiMajor.value()); } else { formatter->add(semiMajor.getSIValue()); } formatter->add(computedInverseFlattening()); const auto &unit = semiMajor.unit(); if (isWKT2 && !(formatter->ellipsoidUnitOmittedIfMetre() && unit == common::UnitOfMeasure::METRE)) { unit._exportToWKT(formatter, io::WKTConstants::LENGTHUNIT); } if (formatter->outputId()) { formatID(formatter); } } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Ellipsoid::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("Ellipsoid", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } const auto &semiMajor = semiMajorAxis(); const auto &semiMajorUnit = semiMajor.unit(); writer->AddObjKey(isSphere() ? "radius" : "semi_major_axis"); if (semiMajorUnit == common::UnitOfMeasure::METRE) { writer->Add(semiMajor.value(), 15); } else { auto objContext(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("value"); writer->Add(semiMajor.value(), 15); writer->AddObjKey("unit"); semiMajorUnit._exportToJSON(formatter); } if (!isSphere()) { const auto &l_inverseFlattening = inverseFlattening(); if (l_inverseFlattening.has_value()) { writer->AddObjKey("inverse_flattening"); writer->Add(l_inverseFlattening->getSIValue(), 15); } else { writer->AddObjKey("semi_minor_axis"); const auto &l_semiMinorAxis(semiMinorAxis()); const auto &semiMinorAxisUnit(l_semiMinorAxis->unit()); if (semiMinorAxisUnit == common::UnitOfMeasure::METRE) { writer->Add(l_semiMinorAxis->value(), 15); } else { auto objContext(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("value"); writer->Add(l_semiMinorAxis->value(), 15); writer->AddObjKey("unit"); semiMinorAxisUnit._exportToJSON(formatter); } } } if (formatter->outputId()) { formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- bool Ellipsoid::lookForProjWellKnownEllps(std::string &projEllpsName, std::string &ellpsName) const { const double a = semiMajorAxis().getSIValue(); const double b = computeSemiMinorAxis().getSIValue(); const double rf = computedInverseFlattening(); auto proj_ellps = proj_list_ellps(); for (int i = 0; proj_ellps[i].id != nullptr; i++) { assert(strncmp(proj_ellps[i].major, "a=", 2) == 0); const double a_iter = c_locale_stod(proj_ellps[i].major + 2); if (::fabs(a - a_iter) < 1e-10 * a_iter) { if (strncmp(proj_ellps[i].ell, "b=", 2) == 0) { const double b_iter = c_locale_stod(proj_ellps[i].ell + 2); if (::fabs(b - b_iter) < 1e-10 * b_iter) { projEllpsName = proj_ellps[i].id; ellpsName = proj_ellps[i].name; if (starts_with(ellpsName, "GRS 1980")) { ellpsName = "GRS 1980"; } return true; } } else { assert(strncmp(proj_ellps[i].ell, "rf=", 3) == 0); const double rf_iter = c_locale_stod(proj_ellps[i].ell + 3); if (::fabs(rf - rf_iter) < 1e-10 * rf_iter) { projEllpsName = proj_ellps[i].id; ellpsName = proj_ellps[i].name; if (starts_with(ellpsName, "GRS 1980")) { ellpsName = "GRS 1980"; } return true; } } } } return false; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Ellipsoid::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(FormattingException) { const double a = semiMajorAxis().getSIValue(); std::string projEllpsName; std::string ellpsName; if (lookForProjWellKnownEllps(projEllpsName, ellpsName)) { formatter->addParam("ellps", projEllpsName); return; } if (isSphere()) { formatter->addParam("R", a); } else { formatter->addParam("a", a); if (inverseFlattening().has_value()) { const double rf = computedInverseFlattening(); formatter->addParam("rf", rf); } else { const double b = computeSemiMinorAxis().getSIValue(); formatter->addParam("b", b); } } } //! @endcond // --------------------------------------------------------------------------- /** \brief Return a Ellipsoid object where some parameters are better * identified. * * @return a new Ellipsoid. */ EllipsoidNNPtr Ellipsoid::identify() const { auto newEllipsoid = Ellipsoid::nn_make_shared<Ellipsoid>(*this); newEllipsoid->assignSelf( util::nn_static_pointer_cast<util::BaseObject>(newEllipsoid)); if (name()->description()->empty() || nameStr() == "unknown") { std::string projEllpsName; std::string ellpsName; if (lookForProjWellKnownEllps(projEllpsName, ellpsName)) { newEllipsoid->setProperties( util::PropertyMap().set(IdentifiedObject::NAME_KEY, ellpsName)); } } return newEllipsoid; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool Ellipsoid::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherEllipsoid = dynamic_cast<const Ellipsoid *>(other); if (otherEllipsoid == nullptr || (criterion == util::IComparable::Criterion::STRICT && !IdentifiedObject::_isEquivalentTo(other, criterion, dbContext))) { return false; } // PROJ "clrk80" name is "Clarke 1880 mod." and GDAL tends to // export to it a number of Clarke 1880 variants, so be lax if (criterion != util::IComparable::Criterion::STRICT && (nameStr() == "Clarke 1880 mod." || otherEllipsoid->nameStr() == "Clarke 1880 mod.")) { return std::fabs(semiMajorAxis().getSIValue() - otherEllipsoid->semiMajorAxis().getSIValue()) < 1e-8 * semiMajorAxis().getSIValue() && std::fabs(computedInverseFlattening() - otherEllipsoid->computedInverseFlattening()) < 1e-5 * computedInverseFlattening(); } if (!semiMajorAxis()._isEquivalentTo(otherEllipsoid->semiMajorAxis(), criterion)) { return false; } const auto &l_semiMinorAxis = semiMinorAxis(); const auto &l_other_semiMinorAxis = otherEllipsoid->semiMinorAxis(); if (l_semiMinorAxis.has_value() && l_other_semiMinorAxis.has_value()) { if (!l_semiMinorAxis->_isEquivalentTo(*l_other_semiMinorAxis, criterion)) { return false; } } const auto &l_inverseFlattening = inverseFlattening(); const auto &l_other_sinverseFlattening = otherEllipsoid->inverseFlattening(); if (l_inverseFlattening.has_value() && l_other_sinverseFlattening.has_value()) { if (!l_inverseFlattening->_isEquivalentTo(*l_other_sinverseFlattening, criterion)) { return false; } } if (criterion == util::IComparable::Criterion::STRICT) { if ((l_semiMinorAxis.has_value() ^ l_other_semiMinorAxis.has_value())) { return false; } if ((l_inverseFlattening.has_value() ^ l_other_sinverseFlattening.has_value())) { return false; } } else { if (!computeSemiMinorAxis()._isEquivalentTo( otherEllipsoid->computeSemiMinorAxis(), criterion)) { return false; } } const auto &l_semiMedianAxis = semiMedianAxis(); const auto &l_other_semiMedianAxis = otherEllipsoid->semiMedianAxis(); if ((l_semiMedianAxis.has_value() ^ l_other_semiMedianAxis.has_value())) { return false; } if (l_semiMedianAxis.has_value() && l_other_semiMedianAxis.has_value()) { if (!l_semiMedianAxis->_isEquivalentTo(*l_other_semiMedianAxis, criterion)) { return false; } } return true; } //! @endcond // --------------------------------------------------------------------------- std::string Ellipsoid::guessBodyName(const io::DatabaseContextPtr &dbContext, double a) { // Mars (2015) - Sphere uses R=3396190 // and Mars polar radius (as used by HIRISE JPEG2000) is 3376200m // which is a 0.59% relative difference. constexpr double relError = 0.007; constexpr double earthMeanRadius = 6375000.0; if (std::fabs(a - earthMeanRadius) < relError * earthMeanRadius) { return Ellipsoid::EARTH; } if (dbContext) { try { auto factory = io::AuthorityFactory::create(NN_NO_CHECK(dbContext), std::string()); return factory->identifyBodyFromSemiMajorAxis(a, relError); } catch (const std::exception &) { } } return "Non-Earth body"; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GeodeticReferenceFrame::Private { PrimeMeridianNNPtr primeMeridian_; EllipsoidNNPtr ellipsoid_; Private(const EllipsoidNNPtr &ellipsoidIn, const PrimeMeridianNNPtr &primeMeridianIn) : primeMeridian_(primeMeridianIn), ellipsoid_(ellipsoidIn) {} }; //! @endcond // --------------------------------------------------------------------------- GeodeticReferenceFrame::GeodeticReferenceFrame( const EllipsoidNNPtr &ellipsoidIn, const PrimeMeridianNNPtr &primeMeridianIn) : d(internal::make_unique<Private>(ellipsoidIn, primeMeridianIn)) {} // --------------------------------------------------------------------------- #ifdef notdef GeodeticReferenceFrame::GeodeticReferenceFrame( const GeodeticReferenceFrame &other) : Datum(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeodeticReferenceFrame::~GeodeticReferenceFrame() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the PrimeMeridian associated with a GeodeticReferenceFrame. * * @return the PrimeMeridian. */ const PrimeMeridianNNPtr & GeodeticReferenceFrame::primeMeridian() PROJ_PURE_DEFN { return d->primeMeridian_; } // --------------------------------------------------------------------------- /** \brief Return the Ellipsoid associated with a GeodeticReferenceFrame. * * \note The \ref ISO_19111_2019 modelling allows (but discourages) a * GeodeticReferenceFrame * to not be associated with a Ellipsoid in the case where it is used by a * geocentric crs::GeodeticCRS. We have made the choice of making the ellipsoid * specification compulsory. * * @return the Ellipsoid. */ const EllipsoidNNPtr &GeodeticReferenceFrame::ellipsoid() PROJ_PURE_DEFN { return d->ellipsoid_; } // --------------------------------------------------------------------------- /** \brief Instantiate a GeodeticReferenceFrame * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param ellipsoid the Ellipsoid. * @param anchor the anchor definition, or empty. * @param primeMeridian the PrimeMeridian. * @return new GeodeticReferenceFrame. */ GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::create(const util::PropertyMap &properties, const EllipsoidNNPtr &ellipsoid, const util::optional<std::string> &anchor, const PrimeMeridianNNPtr &primeMeridian) { GeodeticReferenceFrameNNPtr grf( GeodeticReferenceFrame::nn_make_shared<GeodeticReferenceFrame>( ellipsoid, primeMeridian)); grf->setAnchor(anchor); grf->setProperties(properties); return grf; } // --------------------------------------------------------------------------- /** \brief Instantiate a GeodeticReferenceFrame * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param ellipsoid the Ellipsoid. * @param anchor the anchor definition, or empty. * @param anchorEpoch the anchor epoch, or empty. * @param primeMeridian the PrimeMeridian. * @return new GeodeticReferenceFrame. * @since 9.2 */ GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::create( const util::PropertyMap &properties, const EllipsoidNNPtr &ellipsoid, const util::optional<std::string> &anchor, const util::optional<common::Measure> &anchorEpoch, const PrimeMeridianNNPtr &primeMeridian) { GeodeticReferenceFrameNNPtr grf( GeodeticReferenceFrame::nn_make_shared<GeodeticReferenceFrame>( ellipsoid, primeMeridian)); grf->setAnchor(anchor); grf->setAnchorEpoch(anchorEpoch); grf->setProperties(properties); return grf; } // --------------------------------------------------------------------------- const GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::createEPSG_6267() { return create(createMapNameEPSGCode("North American Datum 1927", 6267), Ellipsoid::CLARKE_1866, util::optional<std::string>(), PrimeMeridian::GREENWICH); } // --------------------------------------------------------------------------- const GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::createEPSG_6269() { return create(createMapNameEPSGCode("North American Datum 1983", 6269), Ellipsoid::GRS1980, util::optional<std::string>(), PrimeMeridian::GREENWICH); } // --------------------------------------------------------------------------- const GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::createEPSG_6326() { return create(createMapNameEPSGCode("World Geodetic System 1984", 6326), Ellipsoid::WGS84, util::optional<std::string>(), PrimeMeridian::GREENWICH); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticReferenceFrame::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; const auto &ids = identifiers(); formatter->startNode(io::WKTConstants::DATUM, !ids.empty()); std::string l_name(nameStr()); if (l_name.empty()) { l_name = "unnamed"; } if (!isWKT2) { if (formatter->useESRIDialect()) { if (l_name == "World Geodetic System 1984") { l_name = "D_WGS_1984"; } else { bool aliasFound = false; const auto &dbContext = formatter->databaseContext(); if (dbContext) { auto l_alias = dbContext->getAliasFromOfficialName( l_name, "geodetic_datum", "ESRI"); size_t pos; if (!l_alias.empty()) { l_name = std::move(l_alias); aliasFound = true; } else if ((pos = l_name.find(" (")) != std::string::npos) { l_alias = dbContext->getAliasFromOfficialName( l_name.substr(0, pos), "geodetic_datum", "ESRI"); if (!l_alias.empty()) { l_name = std::move(l_alias); aliasFound = true; } } } if (!aliasFound && dbContext) { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), "ESRI"); aliasFound = authFactory ->createObjectsFromName( l_name, {io::AuthorityFactory::ObjectType:: GEODETIC_REFERENCE_FRAME}, false // approximateMatch ) .size() == 1; } if (!aliasFound) { l_name = io::WKTFormatter::morphNameToESRI(l_name); if (!starts_with(l_name, "D_")) { l_name = "D_" + l_name; } } } } else { // Replace spaces by underscore for datum names coming from EPSG // so as to emulate GDAL < 3 importFromEPSG() if (ids.size() == 1 && *(ids.front()->codeSpace()) == "EPSG") { l_name = io::WKTFormatter::morphNameToESRI(l_name); } else if (ids.empty()) { const auto &dbContext = formatter->databaseContext(); if (dbContext) { auto factory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), std::string()); // We use anonymous authority and approximate matching, so // as to trigger the caching done in createObjectsFromName() // in that case. auto matches = factory->createObjectsFromName( l_name, {io::AuthorityFactory::ObjectType:: GEODETIC_REFERENCE_FRAME}, true, 2); if (matches.size() == 1) { const auto &match = matches.front(); const auto &matchId = match->identifiers(); if (matchId.size() == 1 && *(matchId.front()->codeSpace()) == "EPSG" && metadata::Identifier::isEquivalentName( l_name.c_str(), match->nameStr().c_str())) { l_name = io::WKTFormatter::morphNameToESRI(l_name); } } } } if (l_name == "World_Geodetic_System_1984") { l_name = "WGS_1984"; } } } formatter->addQuotedString(l_name); ellipsoid()->_exportToWKT(formatter); if (isWKT2) { Datum::getPrivate()->exportAnchorDefinition(formatter); if (formatter->use2019Keywords()) { Datum::getPrivate()->exportAnchorEpoch(formatter); } } else { const auto &TOWGS84Params = formatter->getTOWGS84Parameters(); if (TOWGS84Params.size() == 7) { formatter->startNode(io::WKTConstants::TOWGS84, false); for (const auto &val : TOWGS84Params) { formatter->add(val, 12); } formatter->endNode(); } std::string extension = formatter->getHDatumExtension(); if (!extension.empty()) { formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4_GRIDS"); formatter->addQuotedString(extension); formatter->endNode(); } } if (formatter->outputId()) { formatID(formatter); } // the PRIMEM is exported as a child of the CRS formatter->endNode(); if (formatter->isAtTopLevel()) { const auto &l_primeMeridian(primeMeridian()); if (l_primeMeridian->nameStr() != "Greenwich") { l_primeMeridian->_exportToWKT(formatter); } } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticReferenceFrame::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto dynamicGRF = dynamic_cast<const DynamicGeodeticReferenceFrame *>(this); auto objectContext(formatter->MakeObjectContext( dynamicGRF ? "DynamicGeodeticReferenceFrame" : "GeodeticReferenceFrame", !identifiers().empty())); auto writer = formatter->writer(); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } Datum::getPrivate()->exportAnchorDefinition(formatter); Datum::getPrivate()->exportAnchorEpoch(formatter); if (dynamicGRF) { writer->AddObjKey("frame_reference_epoch"); writer->Add(dynamicGRF->frameReferenceEpoch().value()); } writer->AddObjKey("ellipsoid"); formatter->setOmitTypeInImmediateChild(); ellipsoid()->_exportToJSON(formatter); const auto &l_primeMeridian(primeMeridian()); if (l_primeMeridian->nameStr() != "Greenwich") { writer->AddObjKey("prime_meridian"); formatter->setOmitTypeInImmediateChild(); primeMeridian()->_exportToJSON(formatter); } ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool GeodeticReferenceFrame::isEquivalentToNoExactTypeCheck( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherGRF = dynamic_cast<const GeodeticReferenceFrame *>(other); if (otherGRF == nullptr || !Datum::_isEquivalentTo(other, criterion, dbContext)) { return false; } return primeMeridian()->_isEquivalentTo(otherGRF->primeMeridian().get(), criterion, dbContext) && ellipsoid()->_isEquivalentTo(otherGRF->ellipsoid().get(), criterion, dbContext); } // --------------------------------------------------------------------------- bool GeodeticReferenceFrame::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { if (criterion == Criterion::STRICT && !util::isOfExactType<GeodeticReferenceFrame>(*other)) { return false; } return isEquivalentToNoExactTypeCheck(other, criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- bool GeodeticReferenceFrame::hasEquivalentNameToUsingAlias( const IdentifiedObject *other, const io::DatabaseContextPtr &dbContext) const { if (nameStr() == "unknown" || other->nameStr() == "unknown") { return true; } if (dbContext) { if (!identifiers().empty()) { const auto &id = identifiers().front(); const std::string officialNameFromId = dbContext->getName( "geodetic_datum", *(id->codeSpace()), id->code()); const auto aliasesResult = dbContext->getAliases(*(id->codeSpace()), id->code(), nameStr(), "geodetic_datum", std::string()); const auto isNameMatching = [&aliasesResult, &officialNameFromId](const std::string &name) { const char *nameCstr = name.c_str(); if (metadata::Identifier::isEquivalentName( nameCstr, officialNameFromId.c_str())) { return true; } else { for (const auto &aliasResult : aliasesResult) { if (metadata::Identifier::isEquivalentName( nameCstr, aliasResult.c_str())) { return true; } } } return false; }; return isNameMatching(nameStr()) && isNameMatching(other->nameStr()); } else if (!other->identifiers().empty()) { auto otherGRF = dynamic_cast<const GeodeticReferenceFrame *>(other); if (otherGRF) { return otherGRF->hasEquivalentNameToUsingAlias(this, dbContext); } return false; } auto aliasesResult = dbContext->getAliases(std::string(), std::string(), nameStr(), "geodetic_datum", std::string()); const char *otherName = other->nameStr().c_str(); for (const auto &aliasResult : aliasesResult) { if (metadata::Identifier::isEquivalentName(otherName, aliasResult.c_str())) { return true; } } } return false; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DynamicGeodeticReferenceFrame::Private { common::Measure frameReferenceEpoch{}; util::optional<std::string> deformationModelName{}; explicit Private(const common::Measure &frameReferenceEpochIn) : frameReferenceEpoch(frameReferenceEpochIn) {} }; //! @endcond // --------------------------------------------------------------------------- DynamicGeodeticReferenceFrame::DynamicGeodeticReferenceFrame( const EllipsoidNNPtr &ellipsoidIn, const PrimeMeridianNNPtr &primeMeridianIn, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn) : GeodeticReferenceFrame(ellipsoidIn, primeMeridianIn), d(internal::make_unique<Private>(frameReferenceEpochIn)) { d->deformationModelName = deformationModelNameIn; } // --------------------------------------------------------------------------- #ifdef notdef DynamicGeodeticReferenceFrame::DynamicGeodeticReferenceFrame( const DynamicGeodeticReferenceFrame &other) : GeodeticReferenceFrame(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DynamicGeodeticReferenceFrame::~DynamicGeodeticReferenceFrame() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the epoch to which the coordinates of stations defining the * dynamic geodetic reference frame are referenced. * * Usually given as a decimal year e.g. 2016.47. * * @return the frame reference epoch. */ const common::Measure & DynamicGeodeticReferenceFrame::frameReferenceEpoch() const { return d->frameReferenceEpoch; } // --------------------------------------------------------------------------- /** \brief Return the name of the deformation model. * * @note This is an extension to the \ref ISO_19111_2019 modeling, to * hold the content of the DYNAMIC.MODEL WKT2 node. * * @return the name of the deformation model. */ const util::optional<std::string> & DynamicGeodeticReferenceFrame::deformationModelName() const { return d->deformationModelName; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool DynamicGeodeticReferenceFrame::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { if (criterion == Criterion::STRICT && !util::isOfExactType<DynamicGeodeticReferenceFrame>(*other)) { return false; } if (!GeodeticReferenceFrame::isEquivalentToNoExactTypeCheck( other, criterion, dbContext)) { return false; } auto otherDGRF = dynamic_cast<const DynamicGeodeticReferenceFrame *>(other); if (otherDGRF == nullptr) { // we can go here only if criterion != Criterion::STRICT, and thus // given the above check we can consider the objects equivalent. return true; } return frameReferenceEpoch()._isEquivalentTo( otherDGRF->frameReferenceEpoch(), criterion) && metadata::Identifier::isEquivalentName( deformationModelName()->c_str(), otherDGRF->deformationModelName()->c_str()); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DynamicGeodeticReferenceFrame::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (isWKT2 && formatter->use2019Keywords()) { formatter->startNode(io::WKTConstants::DYNAMIC, false); formatter->startNode(io::WKTConstants::FRAMEEPOCH, false); formatter->add( frameReferenceEpoch().convertToUnit(common::UnitOfMeasure::YEAR)); formatter->endNode(); if (deformationModelName().has_value() && !deformationModelName()->empty()) { formatter->startNode(io::WKTConstants::MODEL, false); formatter->addQuotedString(*deformationModelName()); formatter->endNode(); } formatter->endNode(); } GeodeticReferenceFrame::_exportToWKT(formatter); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a DynamicGeodeticReferenceFrame * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param ellipsoid the Ellipsoid. * @param anchor the anchor definition, or empty. * @param primeMeridian the PrimeMeridian. * @param frameReferenceEpochIn the frame reference epoch. * @param deformationModelNameIn deformation model name, or empty * @return new DynamicGeodeticReferenceFrame. */ DynamicGeodeticReferenceFrameNNPtr DynamicGeodeticReferenceFrame::create( const util::PropertyMap &properties, const EllipsoidNNPtr &ellipsoid, const util::optional<std::string> &anchor, const PrimeMeridianNNPtr &primeMeridian, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn) { DynamicGeodeticReferenceFrameNNPtr grf( DynamicGeodeticReferenceFrame::nn_make_shared< DynamicGeodeticReferenceFrame>(ellipsoid, primeMeridian, frameReferenceEpochIn, deformationModelNameIn)); grf->setAnchor(anchor); grf->setProperties(properties); return grf; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DatumEnsemble::Private { std::vector<DatumNNPtr> datums{}; metadata::PositionalAccuracyNNPtr positionalAccuracy; Private(const std::vector<DatumNNPtr> &datumsIn, const metadata::PositionalAccuracyNNPtr &accuracy) : datums(datumsIn), positionalAccuracy(accuracy) {} }; //! @endcond // --------------------------------------------------------------------------- DatumEnsemble::DatumEnsemble(const std::vector<DatumNNPtr> &datumsIn, const metadata::PositionalAccuracyNNPtr &accuracy) : d(internal::make_unique<Private>(datumsIn, accuracy)) {} // --------------------------------------------------------------------------- #ifdef notdef DatumEnsemble::DatumEnsemble(const DatumEnsemble &other) : common::ObjectUsage(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DatumEnsemble::~DatumEnsemble() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the set of datums which may be considered to be * insignificantly different from each other. * * @return the set of datums of the DatumEnsemble. */ const std::vector<DatumNNPtr> &DatumEnsemble::datums() const { return d->datums; } // --------------------------------------------------------------------------- /** \brief Return the inaccuracy introduced through use of this collection of * datums. * * It is an indication of the differences in coordinate values at all points * between the various realizations that have been grouped into this datum * ensemble. * * @return the accuracy. */ const metadata::PositionalAccuracyNNPtr & DatumEnsemble::positionalAccuracy() const { return d->positionalAccuracy; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DatumNNPtr DatumEnsemble::asDatum(const io::DatabaseContextPtr &dbContext) const { const auto &l_datums = datums(); auto *grf = dynamic_cast<const GeodeticReferenceFrame *>(l_datums[0].get()); const auto &l_identifiers = identifiers(); if (dbContext) { if (!l_identifiers.empty()) { const auto &id = l_identifiers[0]; try { auto factory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), *(id->codeSpace())); if (grf) { return factory->createGeodeticDatum(id->code()); } else { return factory->createVerticalDatum(id->code()); } } catch (const std::exception &) { } } } std::string l_name(nameStr()); if (grf) { // Remap to traditional datum names if (l_name == "World Geodetic System 1984 ensemble") { l_name = "World Geodetic System 1984"; } else if (l_name == "European Terrestrial Reference System 1989 ensemble") { l_name = "European Terrestrial Reference System 1989"; } } auto props = util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, l_name); if (isDeprecated()) { props.set(common::IdentifiedObject::DEPRECATED_KEY, true); } if (!l_identifiers.empty()) { const auto &id = l_identifiers[0]; props.set(metadata::Identifier::CODESPACE_KEY, *(id->codeSpace())) .set(metadata::Identifier::CODE_KEY, id->code()); } const auto &l_usages = domains(); if (!l_usages.empty()) { auto array(util::ArrayOfBaseObject::create()); for (const auto &usage : l_usages) { array->add(usage); } props.set(common::ObjectUsage::OBJECT_DOMAIN_KEY, util::nn_static_pointer_cast<util::BaseObject>(array)); } const auto anchor = util::optional<std::string>(); if (grf) { return GeodeticReferenceFrame::create(props, grf->ellipsoid(), anchor, grf->primeMeridian()); } else { assert(dynamic_cast<VerticalReferenceFrame *>(l_datums[0].get())); return datum::VerticalReferenceFrame::create(props, anchor); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DatumEnsemble::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2 || !formatter->use2019Keywords()) { return asDatum(formatter->databaseContext())->_exportToWKT(formatter); } const auto &l_datums = datums(); assert(!l_datums.empty()); formatter->startNode(io::WKTConstants::ENSEMBLE, false); const auto &l_name = nameStr(); if (!l_name.empty()) { formatter->addQuotedString(l_name); } else { formatter->addQuotedString("unnamed"); } for (const auto &datum : l_datums) { formatter->startNode(io::WKTConstants::MEMBER, !datum->identifiers().empty()); const auto &l_datum_name = datum->nameStr(); if (!l_datum_name.empty()) { formatter->addQuotedString(l_datum_name); } else { formatter->addQuotedString("unnamed"); } if (formatter->outputId()) { datum->formatID(formatter); } formatter->endNode(); } auto grfFirst = std::dynamic_pointer_cast<GeodeticReferenceFrame>( l_datums[0].as_nullable()); if (grfFirst) { grfFirst->ellipsoid()->_exportToWKT(formatter); } formatter->startNode(io::WKTConstants::ENSEMBLEACCURACY, false); formatter->add(positionalAccuracy()->value()); formatter->endNode(); // In theory, we should do the following, but currently the WKT grammar // doesn't allow this // ObjectUsage::baseExportToWKT(formatter); if (formatter->outputId()) { formatID(formatter); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DatumEnsemble::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto objectContext( formatter->MakeObjectContext("DatumEnsemble", !identifiers().empty())); auto writer = formatter->writer(); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } const auto &l_datums = datums(); writer->AddObjKey("members"); { auto membersContext(writer->MakeArrayContext(false)); for (const auto &datum : l_datums) { auto memberContext(writer->MakeObjectContext()); writer->AddObjKey("name"); const auto &l_datum_name = datum->nameStr(); if (!l_datum_name.empty()) { writer->Add(l_datum_name); } else { writer->Add("unnamed"); } datum->formatID(formatter); } } auto grfFirst = std::dynamic_pointer_cast<GeodeticReferenceFrame>( l_datums[0].as_nullable()); if (grfFirst) { writer->AddObjKey("ellipsoid"); formatter->setOmitTypeInImmediateChild(); grfFirst->ellipsoid()->_exportToJSON(formatter); } writer->AddObjKey("accuracy"); writer->Add(positionalAccuracy()->value()); formatID(formatter); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a DatumEnsemble. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datumsIn Array of at least 2 datums. * @param accuracy Accuracy of the datum ensemble * @return new DatumEnsemble. * @throw util::Exception */ DatumEnsembleNNPtr DatumEnsemble::create( const util::PropertyMap &properties, const std::vector<DatumNNPtr> &datumsIn, const metadata::PositionalAccuracyNNPtr &accuracy) // throw(Exception) { if (datumsIn.size() < 2) { throw util::Exception("ensemble should have at least 2 datums"); } if (auto grfFirst = dynamic_cast<const GeodeticReferenceFrame *>(datumsIn[0].get())) { for (size_t i = 1; i < datumsIn.size(); i++) { auto grf = dynamic_cast<const GeodeticReferenceFrame *>(datumsIn[i].get()); if (!grf) { throw util::Exception( "ensemble should have consistent datum types"); } if (!grfFirst->ellipsoid()->_isEquivalentTo( grf->ellipsoid().get())) { throw util::Exception( "ensemble should have datums with identical ellipsoid"); } if (!grfFirst->primeMeridian()->_isEquivalentTo( grf->primeMeridian().get())) { throw util::Exception( "ensemble should have datums with identical " "prime meridian"); } } } else if (dynamic_cast<VerticalReferenceFrame *>(datumsIn[0].get())) { for (size_t i = 1; i < datumsIn.size(); i++) { if (!dynamic_cast<VerticalReferenceFrame *>(datumsIn[i].get())) { throw util::Exception( "ensemble should have consistent datum types"); } } } auto ensemble( DatumEnsemble::nn_make_shared<DatumEnsemble>(datumsIn, accuracy)); ensemble->setProperties(properties); return ensemble; } // --------------------------------------------------------------------------- RealizationMethod::RealizationMethod(const std::string &nameIn) : CodeList(nameIn) {} // --------------------------------------------------------------------------- RealizationMethod & RealizationMethod::operator=(const RealizationMethod &other) { CodeList::operator=(other); return *this; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct VerticalReferenceFrame::Private { util::optional<RealizationMethod> realizationMethod_{}; // 2005 = CS_VD_GeoidModelDerived from OGC 01-009 std::string wkt1DatumType_{"2005"}; }; //! @endcond // --------------------------------------------------------------------------- VerticalReferenceFrame::VerticalReferenceFrame( const util::optional<RealizationMethod> &realizationMethodIn) : d(internal::make_unique<Private>()) { if (!realizationMethodIn->toString().empty()) { d->realizationMethod_ = *realizationMethodIn; } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress VerticalReferenceFrame::~VerticalReferenceFrame() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the method through which this vertical reference frame is * realized. * * @return the realization method. */ const util::optional<RealizationMethod> & VerticalReferenceFrame::realizationMethod() const { return d->realizationMethod_; } // --------------------------------------------------------------------------- /** \brief Instantiate a VerticalReferenceFrame * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param anchor the anchor definition, or empty. * @param realizationMethodIn the realization method, or empty. * @return new VerticalReferenceFrame. */ VerticalReferenceFrameNNPtr VerticalReferenceFrame::create( const util::PropertyMap &properties, const util::optional<std::string> &anchor, const util::optional<RealizationMethod> &realizationMethodIn) { auto rf(VerticalReferenceFrame::nn_make_shared<VerticalReferenceFrame>( realizationMethodIn)); rf->setAnchor(anchor); rf->setProperties(properties); properties.getStringValue("VERT_DATUM_TYPE", rf->d->wkt1DatumType_); return rf; } // --------------------------------------------------------------------------- /** \brief Instantiate a VerticalReferenceFrame * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param anchor the anchor definition, or empty. * @param anchorEpoch the anchor epoch, or empty. * @param realizationMethodIn the realization method, or empty. * @return new VerticalReferenceFrame. * @since 9.2 */ VerticalReferenceFrameNNPtr VerticalReferenceFrame::create( const util::PropertyMap &properties, const util::optional<std::string> &anchor, const util::optional<common::Measure> &anchorEpoch, const util::optional<RealizationMethod> &realizationMethodIn) { auto rf(VerticalReferenceFrame::nn_make_shared<VerticalReferenceFrame>( realizationMethodIn)); rf->setAnchor(anchor); rf->setAnchorEpoch(anchorEpoch); rf->setProperties(properties); properties.getStringValue("VERT_DATUM_TYPE", rf->d->wkt1DatumType_); return rf; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const std::string &VerticalReferenceFrame::getWKT1DatumType() const { return d->wkt1DatumType_; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void VerticalReferenceFrame::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; formatter->startNode(isWKT2 ? io::WKTConstants::VDATUM : formatter->useESRIDialect() ? io::WKTConstants::VDATUM : io::WKTConstants::VERT_DATUM, !identifiers().empty()); std::string l_name(nameStr()); if (!l_name.empty()) { if (!isWKT2 && formatter->useESRIDialect()) { bool aliasFound = false; const auto &dbContext = formatter->databaseContext(); if (dbContext) { auto l_alias = dbContext->getAliasFromOfficialName( l_name, "vertical_datum", "ESRI"); if (!l_alias.empty()) { l_name = std::move(l_alias); aliasFound = true; } } if (!aliasFound && dbContext) { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), "ESRI"); aliasFound = authFactory ->createObjectsFromName( l_name, {io::AuthorityFactory::ObjectType:: VERTICAL_REFERENCE_FRAME}, false // approximateMatch ) .size() == 1; } if (!aliasFound) { l_name = io::WKTFormatter::morphNameToESRI(l_name); } } formatter->addQuotedString(l_name); } else { formatter->addQuotedString("unnamed"); } if (isWKT2) { Datum::getPrivate()->exportAnchorDefinition(formatter); if (formatter->use2019Keywords()) { Datum::getPrivate()->exportAnchorEpoch(formatter); } } else if (!formatter->useESRIDialect()) { formatter->add(d->wkt1DatumType_); const auto &extension = formatter->getVDatumExtension(); if (!extension.empty()) { formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4_GRIDS"); formatter->addQuotedString(extension); formatter->endNode(); } } if (formatter->outputId()) { formatID(formatter); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void VerticalReferenceFrame::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto dynamicGRF = dynamic_cast<const DynamicVerticalReferenceFrame *>(this); auto objectContext(formatter->MakeObjectContext( dynamicGRF ? "DynamicVerticalReferenceFrame" : "VerticalReferenceFrame", !identifiers().empty())); auto writer = formatter->writer(); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } Datum::getPrivate()->exportAnchorDefinition(formatter); Datum::getPrivate()->exportAnchorEpoch(formatter); if (dynamicGRF) { writer->AddObjKey("frame_reference_epoch"); writer->Add(dynamicGRF->frameReferenceEpoch().value()); } ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool VerticalReferenceFrame::isEquivalentToNoExactTypeCheck( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherVRF = dynamic_cast<const VerticalReferenceFrame *>(other); if (otherVRF == nullptr || !Datum::_isEquivalentTo(other, criterion, dbContext)) { return false; } if ((realizationMethod().has_value() ^ otherVRF->realizationMethod().has_value())) { return false; } if (realizationMethod().has_value() && otherVRF->realizationMethod().has_value()) { if (*(realizationMethod()) != *(otherVRF->realizationMethod())) { return false; } } return true; } // --------------------------------------------------------------------------- bool VerticalReferenceFrame::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { if (criterion == Criterion::STRICT && !util::isOfExactType<VerticalReferenceFrame>(*other)) { return false; } return isEquivalentToNoExactTypeCheck(other, criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DynamicVerticalReferenceFrame::Private { common::Measure frameReferenceEpoch{}; util::optional<std::string> deformationModelName{}; explicit Private(const common::Measure &frameReferenceEpochIn) : frameReferenceEpoch(frameReferenceEpochIn) {} }; //! @endcond // --------------------------------------------------------------------------- DynamicVerticalReferenceFrame::DynamicVerticalReferenceFrame( const util::optional<RealizationMethod> &realizationMethodIn, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn) : VerticalReferenceFrame(realizationMethodIn), d(internal::make_unique<Private>(frameReferenceEpochIn)) { d->deformationModelName = deformationModelNameIn; } // --------------------------------------------------------------------------- #ifdef notdef DynamicVerticalReferenceFrame::DynamicVerticalReferenceFrame( const DynamicVerticalReferenceFrame &other) : VerticalReferenceFrame(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DynamicVerticalReferenceFrame::~DynamicVerticalReferenceFrame() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the epoch to which the coordinates of stations defining the * dynamic geodetic reference frame are referenced. * * Usually given as a decimal year e.g. 2016.47. * * @return the frame reference epoch. */ const common::Measure & DynamicVerticalReferenceFrame::frameReferenceEpoch() const { return d->frameReferenceEpoch; } // --------------------------------------------------------------------------- /** \brief Return the name of the deformation model. * * @note This is an extension to the \ref ISO_19111_2019 modeling, to * hold the content of the DYNAMIC.MODEL WKT2 node. * * @return the name of the deformation model. */ const util::optional<std::string> & DynamicVerticalReferenceFrame::deformationModelName() const { return d->deformationModelName; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool DynamicVerticalReferenceFrame::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { if (criterion == Criterion::STRICT && !util::isOfExactType<DynamicVerticalReferenceFrame>(*other)) { return false; } if (!VerticalReferenceFrame::isEquivalentToNoExactTypeCheck( other, criterion, dbContext)) { return false; } auto otherDGRF = dynamic_cast<const DynamicVerticalReferenceFrame *>(other); if (otherDGRF == nullptr) { // we can go here only if criterion != Criterion::STRICT, and thus // given the above check we can consider the objects equivalent. return true; } return frameReferenceEpoch()._isEquivalentTo( otherDGRF->frameReferenceEpoch(), criterion) && metadata::Identifier::isEquivalentName( deformationModelName()->c_str(), otherDGRF->deformationModelName()->c_str()); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DynamicVerticalReferenceFrame::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (isWKT2 && formatter->use2019Keywords()) { formatter->startNode(io::WKTConstants::DYNAMIC, false); formatter->startNode(io::WKTConstants::FRAMEEPOCH, false); formatter->add( frameReferenceEpoch().convertToUnit(common::UnitOfMeasure::YEAR)); formatter->endNode(); if (!deformationModelName()->empty()) { formatter->startNode(io::WKTConstants::MODEL, false); formatter->addQuotedString(*deformationModelName()); formatter->endNode(); } formatter->endNode(); } VerticalReferenceFrame::_exportToWKT(formatter); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a DynamicVerticalReferenceFrame * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param anchor the anchor definition, or empty. * @param realizationMethodIn the realization method, or empty. * @param frameReferenceEpochIn the frame reference epoch. * @param deformationModelNameIn deformation model name, or empty * @return new DynamicVerticalReferenceFrame. */ DynamicVerticalReferenceFrameNNPtr DynamicVerticalReferenceFrame::create( const util::PropertyMap &properties, const util::optional<std::string> &anchor, const util::optional<RealizationMethod> &realizationMethodIn, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn) { DynamicVerticalReferenceFrameNNPtr grf( DynamicVerticalReferenceFrame::nn_make_shared< DynamicVerticalReferenceFrame>(realizationMethodIn, frameReferenceEpochIn, deformationModelNameIn)); grf->setAnchor(anchor); grf->setProperties(properties); return grf; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct TemporalDatum::Private { common::DateTime temporalOrigin_; std::string calendar_; Private(const common::DateTime &temporalOriginIn, const std::string &calendarIn) : temporalOrigin_(temporalOriginIn), calendar_(calendarIn) {} }; //! @endcond // --------------------------------------------------------------------------- TemporalDatum::TemporalDatum(const common::DateTime &temporalOriginIn, const std::string &calendarIn) : d(internal::make_unique<Private>(temporalOriginIn, calendarIn)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TemporalDatum::~TemporalDatum() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the date and time to which temporal coordinates are * referenced, expressed in conformance with ISO 8601. * * @return the temporal origin. */ const common::DateTime &TemporalDatum::temporalOrigin() const { return d->temporalOrigin_; } // --------------------------------------------------------------------------- /** \brief Return the calendar to which the temporal origin is referenced * * Default value: TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN. * * @return the calendar. */ const std::string &TemporalDatum::calendar() const { return d->calendar_; } // --------------------------------------------------------------------------- /** \brief Instantiate a TemporalDatum * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param temporalOriginIn the temporal origin into which temporal coordinates * are referenced. * @param calendarIn the calendar (generally * TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN) * @return new TemporalDatum. */ TemporalDatumNNPtr TemporalDatum::create(const util::PropertyMap &properties, const common::DateTime &temporalOriginIn, const std::string &calendarIn) { auto datum(TemporalDatum::nn_make_shared<TemporalDatum>(temporalOriginIn, calendarIn)); datum->setProperties(properties); return datum; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void TemporalDatum::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { throw io::FormattingException( "TemporalDatum can only be exported to WKT2"); } formatter->startNode(io::WKTConstants::TDATUM, !identifiers().empty()); formatter->addQuotedString(nameStr()); if (formatter->use2019Keywords()) { formatter->startNode(io::WKTConstants::CALENDAR, false); formatter->addQuotedString(calendar()); formatter->endNode(); } const auto &timeOriginStr = temporalOrigin().toString(); if (!timeOriginStr.empty()) { formatter->startNode(io::WKTConstants::TIMEORIGIN, false); if (temporalOrigin().isISO_8601()) { formatter->add(timeOriginStr); } else { formatter->addQuotedString(timeOriginStr); } formatter->endNode(); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void TemporalDatum::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto objectContext( formatter->MakeObjectContext("TemporalDatum", !identifiers().empty())); auto writer = formatter->writer(); writer->AddObjKey("name"); writer->Add(nameStr()); writer->AddObjKey("calendar"); writer->Add(calendar()); const auto &timeOriginStr = temporalOrigin().toString(); if (!timeOriginStr.empty()) { writer->AddObjKey("time_origin"); writer->Add(timeOriginStr); } ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool TemporalDatum::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherTD = dynamic_cast<const TemporalDatum *>(other); if (otherTD == nullptr || !Datum::_isEquivalentTo(other, criterion, dbContext)) { return false; } return temporalOrigin().toString() == otherTD->temporalOrigin().toString() && calendar() == otherTD->calendar(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct EngineeringDatum::Private {}; //! @endcond // --------------------------------------------------------------------------- EngineeringDatum::EngineeringDatum() : d(nullptr) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress EngineeringDatum::~EngineeringDatum() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a EngineeringDatum * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param anchor the anchor definition, or empty. * @return new EngineeringDatum. */ EngineeringDatumNNPtr EngineeringDatum::create(const util::PropertyMap &properties, const util::optional<std::string> &anchor) { auto datum(EngineeringDatum::nn_make_shared<EngineeringDatum>()); datum->setAnchor(anchor); datum->setProperties(properties); return datum; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void EngineeringDatum::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; formatter->startNode(isWKT2 ? io::WKTConstants::EDATUM : io::WKTConstants::LOCAL_DATUM, !identifiers().empty()); formatter->addQuotedString(nameStr()); if (isWKT2) { Datum::getPrivate()->exportAnchorDefinition(formatter); } else { // Somewhat picked up arbitrarily from OGC 01-009: // CS_LD_Max (Attribute) : 32767 // Highest possible value for local datum types. formatter->add(32767); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void EngineeringDatum::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto objectContext(formatter->MakeObjectContext("EngineeringDatum", !identifiers().empty())); auto writer = formatter->writer(); writer->AddObjKey("name"); writer->Add(nameStr()); Datum::getPrivate()->exportAnchorDefinition(formatter); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool EngineeringDatum::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDatum = dynamic_cast<const EngineeringDatum *>(other); if (otherDatum == nullptr) { return false; } if (criterion != util::IComparable::Criterion::STRICT && (nameStr().empty() || nameStr() == UNKNOWN_ENGINEERING_DATUM) && (otherDatum->nameStr().empty() || otherDatum->nameStr() == UNKNOWN_ENGINEERING_DATUM)) { return true; } return Datum::_isEquivalentTo(other, criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ParametricDatum::Private {}; //! @endcond // --------------------------------------------------------------------------- ParametricDatum::ParametricDatum() : d(nullptr) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ParametricDatum::~ParametricDatum() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a ParametricDatum * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param anchor the anchor definition, or empty. * @return new ParametricDatum. */ ParametricDatumNNPtr ParametricDatum::create(const util::PropertyMap &properties, const util::optional<std::string> &anchor) { auto datum(ParametricDatum::nn_make_shared<ParametricDatum>()); datum->setAnchor(anchor); datum->setProperties(properties); return datum; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ParametricDatum::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { throw io::FormattingException( "ParametricDatum can only be exported to WKT2"); } formatter->startNode(io::WKTConstants::PDATUM, !identifiers().empty()); formatter->addQuotedString(nameStr()); Datum::getPrivate()->exportAnchorDefinition(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ParametricDatum::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto objectContext(formatter->MakeObjectContext("ParametricDatum", !identifiers().empty())); auto writer = formatter->writer(); writer->AddObjKey("name"); writer->Add(nameStr()); Datum::getPrivate()->exportAnchorDefinition(formatter); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool ParametricDatum::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherTD = dynamic_cast<const ParametricDatum *>(other); if (otherTD == nullptr || !Datum::_isEquivalentTo(other, criterion, dbContext)) { return false; } return true; } //! @endcond } // namespace datum NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/static.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "operation/oputils.hpp" #include "proj/internal/coordinatesystem_internal.hpp" #include "proj/internal/io_internal.hpp" #include <map> #include <set> #include <string> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // We put all static definitions in the same compilation unit, and in // increasing order of dependency, to avoid the "static initialization fiasco" // See https://isocpp.org/wiki/faq/ctors#static-init-order using namespace NS_PROJ::crs; using namespace NS_PROJ::datum; using namespace NS_PROJ::io; using namespace NS_PROJ::metadata; using namespace NS_PROJ::operation; using namespace NS_PROJ::util; NS_PROJ_START // --------------------------------------------------------------------------- const NameSpaceNNPtr NameSpace::GLOBAL(NameSpace::createGLOBAL()); // --------------------------------------------------------------------------- /** \brief Key to set the authority citation of a metadata::Identifier. * * The value is to be provided as a string or a metadata::Citation. */ const std::string Identifier::AUTHORITY_KEY("authority"); /** \brief Key to set the code of a metadata::Identifier. * * The value is to be provided as a integer or a string. */ const std::string Identifier::CODE_KEY("code"); /** \brief Key to set the organization responsible for definition and * maintenance of the code of a metadata::Identifier. * * The value is to be provided as a string. */ const std::string Identifier::CODESPACE_KEY("codespace"); /** \brief Key to set the version identifier for the namespace of a * metadata::Identifier. * * The value is to be provided as a string. */ const std::string Identifier::VERSION_KEY("version"); /** \brief Key to set the natural language description of the meaning of the * code value of a metadata::Identifier. * * The value is to be provided as a string. */ const std::string Identifier::DESCRIPTION_KEY("description"); /** \brief Key to set the URI of a metadata::Identifier. * * The value is to be provided as a string. */ const std::string Identifier::URI_KEY("uri"); /** \brief EPSG codespace. */ const std::string Identifier::EPSG("EPSG"); /** \brief OGC codespace. */ const std::string Identifier::OGC("OGC"); // --------------------------------------------------------------------------- /** \brief Key to set the name of a common::IdentifiedObject * * The value is to be provided as a string or metadata::IdentifierNNPtr. */ const std::string common::IdentifiedObject::NAME_KEY("name"); /** \brief Key to set the identifier(s) of a common::IdentifiedObject * * The value is to be provided as a common::IdentifierNNPtr or a * util::ArrayOfBaseObjectNNPtr * of common::IdentifierNNPtr. */ const std::string common::IdentifiedObject::IDENTIFIERS_KEY("identifiers"); /** \brief Key to set the alias(es) of a common::IdentifiedObject * * The value is to be provided as string, a util::GenericNameNNPtr or a * util::ArrayOfBaseObjectNNPtr * of util::GenericNameNNPtr. */ const std::string common::IdentifiedObject::ALIAS_KEY("alias"); /** \brief Key to set the remarks of a common::IdentifiedObject * * The value is to be provided as a string. */ const std::string common::IdentifiedObject::REMARKS_KEY("remarks"); /** \brief Key to set the deprecation flag of a common::IdentifiedObject * * The value is to be provided as a boolean. */ const std::string common::IdentifiedObject::DEPRECATED_KEY("deprecated"); // --------------------------------------------------------------------------- /** \brief Key to set the scope of a common::ObjectUsage * * The value is to be provided as a string. */ const std::string common::ObjectUsage::SCOPE_KEY("scope"); /** \brief Key to set the domain of validity of a common::ObjectUsage * * The value is to be provided as a common::ExtentNNPtr. */ const std::string common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY("domainOfValidity"); /** \brief Key to set the object domain(s) of a common::ObjectUsage * * The value is to be provided as a common::ObjectDomainNNPtr or a * util::ArrayOfBaseObjectNNPtr * of common::ObjectDomainNNPtr. */ const std::string common::ObjectUsage::OBJECT_DOMAIN_KEY("objectDomain"); // --------------------------------------------------------------------------- /** \brief World extent. */ const ExtentNNPtr Extent::WORLD(Extent::createFromBBOX(-180, -90, 180, 90, util::optional<std::string>("World"))); // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::vector<std::string> WKTConstants::constants_; const char *WKTConstants::createAndAddToConstantList(const char *text) { WKTConstants::constants_.push_back(text); return text; } #define DEFINE_WKT_CONSTANT(x) \ const std::string WKTConstants::x(createAndAddToConstantList(#x)) DEFINE_WKT_CONSTANT(GEOCCS); DEFINE_WKT_CONSTANT(GEOGCS); DEFINE_WKT_CONSTANT(DATUM); DEFINE_WKT_CONSTANT(UNIT); DEFINE_WKT_CONSTANT(SPHEROID); DEFINE_WKT_CONSTANT(AXIS); DEFINE_WKT_CONSTANT(PRIMEM); DEFINE_WKT_CONSTANT(AUTHORITY); DEFINE_WKT_CONSTANT(PROJCS); DEFINE_WKT_CONSTANT(PROJECTION); DEFINE_WKT_CONSTANT(PARAMETER); DEFINE_WKT_CONSTANT(VERT_CS); DEFINE_WKT_CONSTANT(VERTCS); DEFINE_WKT_CONSTANT(VERT_DATUM); DEFINE_WKT_CONSTANT(COMPD_CS); DEFINE_WKT_CONSTANT(TOWGS84); DEFINE_WKT_CONSTANT(EXTENSION); DEFINE_WKT_CONSTANT(LOCAL_CS); DEFINE_WKT_CONSTANT(LOCAL_DATUM); DEFINE_WKT_CONSTANT(LINUNIT); DEFINE_WKT_CONSTANT(GEODCRS); DEFINE_WKT_CONSTANT(LENGTHUNIT); DEFINE_WKT_CONSTANT(ANGLEUNIT); DEFINE_WKT_CONSTANT(SCALEUNIT); DEFINE_WKT_CONSTANT(TIMEUNIT); DEFINE_WKT_CONSTANT(ELLIPSOID); const std::string WKTConstants::CS_(createAndAddToConstantList("CS")); DEFINE_WKT_CONSTANT(ID); DEFINE_WKT_CONSTANT(PROJCRS); DEFINE_WKT_CONSTANT(BASEGEODCRS); DEFINE_WKT_CONSTANT(MERIDIAN); DEFINE_WKT_CONSTANT(ORDER); DEFINE_WKT_CONSTANT(ANCHOR); DEFINE_WKT_CONSTANT(ANCHOREPOCH); DEFINE_WKT_CONSTANT(CONVERSION); DEFINE_WKT_CONSTANT(METHOD); DEFINE_WKT_CONSTANT(REMARK); DEFINE_WKT_CONSTANT(GEOGCRS); DEFINE_WKT_CONSTANT(BASEGEOGCRS); DEFINE_WKT_CONSTANT(SCOPE); DEFINE_WKT_CONSTANT(AREA); DEFINE_WKT_CONSTANT(BBOX); DEFINE_WKT_CONSTANT(CITATION); DEFINE_WKT_CONSTANT(URI); DEFINE_WKT_CONSTANT(VERTCRS); DEFINE_WKT_CONSTANT(VDATUM); DEFINE_WKT_CONSTANT(COMPOUNDCRS); DEFINE_WKT_CONSTANT(PARAMETERFILE); DEFINE_WKT_CONSTANT(COORDINATEOPERATION); DEFINE_WKT_CONSTANT(SOURCECRS); DEFINE_WKT_CONSTANT(TARGETCRS); DEFINE_WKT_CONSTANT(INTERPOLATIONCRS); DEFINE_WKT_CONSTANT(OPERATIONACCURACY); DEFINE_WKT_CONSTANT(CONCATENATEDOPERATION); DEFINE_WKT_CONSTANT(STEP); DEFINE_WKT_CONSTANT(BOUNDCRS); DEFINE_WKT_CONSTANT(ABRIDGEDTRANSFORMATION); DEFINE_WKT_CONSTANT(DERIVINGCONVERSION); DEFINE_WKT_CONSTANT(TDATUM); DEFINE_WKT_CONSTANT(CALENDAR); DEFINE_WKT_CONSTANT(TIMEORIGIN); DEFINE_WKT_CONSTANT(TIMECRS); DEFINE_WKT_CONSTANT(VERTICALEXTENT); DEFINE_WKT_CONSTANT(TIMEEXTENT); DEFINE_WKT_CONSTANT(USAGE); DEFINE_WKT_CONSTANT(DYNAMIC); DEFINE_WKT_CONSTANT(FRAMEEPOCH); DEFINE_WKT_CONSTANT(MODEL); DEFINE_WKT_CONSTANT(VELOCITYGRID); DEFINE_WKT_CONSTANT(ENSEMBLE); DEFINE_WKT_CONSTANT(MEMBER); DEFINE_WKT_CONSTANT(ENSEMBLEACCURACY); DEFINE_WKT_CONSTANT(DERIVEDPROJCRS); DEFINE_WKT_CONSTANT(BASEPROJCRS); DEFINE_WKT_CONSTANT(EDATUM); DEFINE_WKT_CONSTANT(ENGCRS); DEFINE_WKT_CONSTANT(PDATUM); DEFINE_WKT_CONSTANT(PARAMETRICCRS); DEFINE_WKT_CONSTANT(PARAMETRICUNIT); DEFINE_WKT_CONSTANT(BASEVERTCRS); DEFINE_WKT_CONSTANT(BASEENGCRS); DEFINE_WKT_CONSTANT(BASEPARAMCRS); DEFINE_WKT_CONSTANT(BASETIMECRS); DEFINE_WKT_CONSTANT(VERSION); DEFINE_WKT_CONSTANT(GEOIDMODEL); DEFINE_WKT_CONSTANT(COORDINATEMETADATA); DEFINE_WKT_CONSTANT(EPOCH); DEFINE_WKT_CONSTANT(AXISMINVALUE); DEFINE_WKT_CONSTANT(AXISMAXVALUE); DEFINE_WKT_CONSTANT(RANGEMEANING); DEFINE_WKT_CONSTANT(POINTMOTIONOPERATION); DEFINE_WKT_CONSTANT(GEODETICCRS); DEFINE_WKT_CONSTANT(GEODETICDATUM); DEFINE_WKT_CONSTANT(PROJECTEDCRS); DEFINE_WKT_CONSTANT(PRIMEMERIDIAN); DEFINE_WKT_CONSTANT(GEOGRAPHICCRS); DEFINE_WKT_CONSTANT(TRF); DEFINE_WKT_CONSTANT(VERTICALCRS); DEFINE_WKT_CONSTANT(VERTICALDATUM); DEFINE_WKT_CONSTANT(VRF); DEFINE_WKT_CONSTANT(TIMEDATUM); DEFINE_WKT_CONSTANT(TEMPORALQUANTITY); DEFINE_WKT_CONSTANT(ENGINEERINGDATUM); DEFINE_WKT_CONSTANT(ENGINEERINGCRS); DEFINE_WKT_CONSTANT(PARAMETRICDATUM); //! @endcond // --------------------------------------------------------------------------- namespace common { /** \brief "Empty"/"None", unit of measure of type NONE. */ const UnitOfMeasure UnitOfMeasure::NONE("", 1.0, UnitOfMeasure::Type::NONE); /** \brief Scale unity, unit of measure of type SCALE. */ const UnitOfMeasure UnitOfMeasure::SCALE_UNITY("unity", 1.0, UnitOfMeasure::Type::SCALE, Identifier::EPSG, "9201"); /** \brief Parts-per-million, unit of measure of type SCALE. */ const UnitOfMeasure UnitOfMeasure::PARTS_PER_MILLION("parts per million", 1e-6, UnitOfMeasure::Type::SCALE, Identifier::EPSG, "9202"); /** \brief Metre, unit of measure of type LINEAR (SI unit). */ const UnitOfMeasure UnitOfMeasure::METRE("metre", 1.0, UnitOfMeasure::Type::LINEAR, Identifier::EPSG, "9001"); /** \brief Foot, unit of measure of type LINEAR. */ const UnitOfMeasure UnitOfMeasure::FOOT("foot", 0.3048, UnitOfMeasure::Type::LINEAR, Identifier::EPSG, "9002"); /** \brief US survey foot, unit of measure of type LINEAR. */ const UnitOfMeasure UnitOfMeasure::US_FOOT("US survey foot", 0.304800609601219241184, UnitOfMeasure::Type::LINEAR, Identifier::EPSG, "9003"); /** \brief Degree, unit of measure of type ANGULAR. */ const UnitOfMeasure UnitOfMeasure::DEGREE("degree", M_PI / 180., UnitOfMeasure::Type::ANGULAR, Identifier::EPSG, "9122"); /** \brief Arc-second, unit of measure of type ANGULAR. */ const UnitOfMeasure UnitOfMeasure::ARC_SECOND("arc-second", M_PI / 180. / 3600., UnitOfMeasure::Type::ANGULAR, Identifier::EPSG, "9104"); /** \brief Grad, unit of measure of type ANGULAR. */ const UnitOfMeasure UnitOfMeasure::GRAD("grad", M_PI / 200., UnitOfMeasure::Type::ANGULAR, Identifier::EPSG, "9105"); /** \brief Radian, unit of measure of type ANGULAR (SI unit). */ const UnitOfMeasure UnitOfMeasure::RADIAN("radian", 1.0, UnitOfMeasure::Type::ANGULAR, Identifier::EPSG, "9101"); /** \brief Microradian, unit of measure of type ANGULAR. */ const UnitOfMeasure UnitOfMeasure::MICRORADIAN("microradian", 1e-6, UnitOfMeasure::Type::ANGULAR, Identifier::EPSG, "9109"); /** \brief Second, unit of measure of type TIME (SI unit). */ const UnitOfMeasure UnitOfMeasure::SECOND("second", 1.0, UnitOfMeasure::Type::TIME, Identifier::EPSG, "1040"); /** \brief Year, unit of measure of type TIME */ const UnitOfMeasure UnitOfMeasure::YEAR("year", 31556925.445, UnitOfMeasure::Type::TIME, Identifier::EPSG, "1029"); /** \brief Metre per year, unit of measure of type LINEAR. */ const UnitOfMeasure UnitOfMeasure::METRE_PER_YEAR("metres per year", 1.0 / 31556925.445, UnitOfMeasure::Type::LINEAR, Identifier::EPSG, "1042"); /** \brief Arc-second per year, unit of measure of type ANGULAR. */ const UnitOfMeasure UnitOfMeasure::ARC_SECOND_PER_YEAR( "arc-seconds per year", M_PI / 180. / 3600. / 31556925.445, UnitOfMeasure::Type::ANGULAR, Identifier::EPSG, "1043"); /** \brief Parts-per-million per year, unit of measure of type SCALE. */ const UnitOfMeasure UnitOfMeasure::PPM_PER_YEAR("parts per million per year", 1e-6 / 31556925.445, UnitOfMeasure::Type::SCALE, Identifier::EPSG, "1036"); } // namespace common // --------------------------------------------------------------------------- namespace cs { std::map<std::string, const AxisDirection *> AxisDirection::registry; /** Axis positive direction is north. In a geodetic or projected CRS, north is * defined through the geodetic reference frame. In an engineering CRS, north * may be defined with respect to an engineering object rather than a * geographical direction. */ const AxisDirection AxisDirection::NORTH("north"); /** Axis positive direction is approximately north-north-east. */ const AxisDirection AxisDirection::NORTH_NORTH_EAST("northNorthEast"); /** Axis positive direction is approximately north-east. */ const AxisDirection AxisDirection::NORTH_EAST("northEast"); /** Axis positive direction is approximately east-north-east. */ const AxisDirection AxisDirection::EAST_NORTH_EAST("eastNorthEast"); /** Axis positive direction is 90deg clockwise from north. */ const AxisDirection AxisDirection::EAST("east"); /** Axis positive direction is approximately east-south-east. */ const AxisDirection AxisDirection::EAST_SOUTH_EAST("eastSouthEast"); /** Axis positive direction is approximately south-east. */ const AxisDirection AxisDirection::SOUTH_EAST("southEast"); /** Axis positive direction is approximately south-south-east. */ const AxisDirection AxisDirection::SOUTH_SOUTH_EAST("southSouthEast"); /** Axis positive direction is 180deg clockwise from north. */ const AxisDirection AxisDirection::SOUTH("south"); /** Axis positive direction is approximately south-south-west. */ const AxisDirection AxisDirection::SOUTH_SOUTH_WEST("southSouthWest"); /** Axis positive direction is approximately south-west. */ const AxisDirection AxisDirection::SOUTH_WEST("southWest"); /** Axis positive direction is approximately west-south-west. */ const AxisDirection AxisDirection::WEST_SOUTH_WEST("westSouthWest"); /** Axis positive direction is 270deg clockwise from north. */ const AxisDirection AxisDirection::WEST("west"); /** Axis positive direction is approximately west-north-west. */ const AxisDirection AxisDirection::WEST_NORTH_WEST("westNorthWest"); /** Axis positive direction is approximately north-west. */ const AxisDirection AxisDirection::NORTH_WEST("northWest"); /** Axis positive direction is approximately north-north-west. */ const AxisDirection AxisDirection::NORTH_NORTH_WEST("northNorthWest"); /** Axis positive direction is up relative to gravity. */ const AxisDirection AxisDirection::UP("up"); /** Axis positive direction is down relative to gravity. */ const AxisDirection AxisDirection::DOWN("down"); /** Axis positive direction is in the equatorial plane from the centre of the * modelled Earth towards the intersection of the equator with the prime * meridian. */ const AxisDirection AxisDirection::GEOCENTRIC_X("geocentricX"); /** Axis positive direction is in the equatorial plane from the centre of the * modelled Earth towards the intersection of the equator and the meridian 90deg * eastwards from the prime meridian. */ const AxisDirection AxisDirection::GEOCENTRIC_Y("geocentricY"); /** Axis positive direction is from the centre of the modelled Earth parallel to * its rotation axis and towards its north pole. */ const AxisDirection AxisDirection::GEOCENTRIC_Z("geocentricZ"); /** Axis positive direction is towards higher pixel column. */ const AxisDirection AxisDirection::COLUMN_POSITIVE("columnPositive"); /** Axis positive direction is towards lower pixel column. */ const AxisDirection AxisDirection::COLUMN_NEGATIVE("columnNegative"); /** Axis positive direction is towards higher pixel row. */ const AxisDirection AxisDirection::ROW_POSITIVE("rowPositive"); /** Axis positive direction is towards lower pixel row. */ const AxisDirection AxisDirection::ROW_NEGATIVE("rowNegative"); /** Axis positive direction is right in display. */ const AxisDirection AxisDirection::DISPLAY_RIGHT("displayRight"); /** Axis positive direction is left in display. */ const AxisDirection AxisDirection::DISPLAY_LEFT("displayLeft"); /** Axis positive direction is towards top of approximately vertical display * surface. */ const AxisDirection AxisDirection::DISPLAY_UP("displayUp"); /** Axis positive direction is towards bottom of approximately vertical display * surface. */ const AxisDirection AxisDirection::DISPLAY_DOWN("displayDown"); /** Axis positive direction is forward; for an observer at the centre of the * object this is will be towards its front, bow or nose. */ const AxisDirection AxisDirection::FORWARD("forward"); /** Axis positive direction is aft; for an observer at the centre of the object * this will be towards its back, stern or tail. */ const AxisDirection AxisDirection::AFT("aft"); /** Axis positive direction is port; for an observer at the centre of the object * this will be towards its left. */ const AxisDirection AxisDirection::PORT("port"); /** Axis positive direction is starboard; for an observer at the centre of the * object this will be towards its right. */ const AxisDirection AxisDirection::STARBOARD("starboard"); /** Axis positive direction is clockwise from a specified direction. */ const AxisDirection AxisDirection::CLOCKWISE("clockwise"); /** Axis positive direction is counter clockwise from a specified direction. */ const AxisDirection AxisDirection::COUNTER_CLOCKWISE("counterClockwise"); /** Axis positive direction is towards the object. */ const AxisDirection AxisDirection::TOWARDS("towards"); /** Axis positive direction is away from the object. */ const AxisDirection AxisDirection::AWAY_FROM("awayFrom"); /** Temporal axis positive direction is towards the future. */ const AxisDirection AxisDirection::FUTURE("future"); /** Temporal axis positive direction is towards the past. */ const AxisDirection AxisDirection::PAST("past"); /** Axis positive direction is unspecified. */ const AxisDirection AxisDirection::UNSPECIFIED("unspecified"); // --------------------------------------------------------------------------- std::map<std::string, const RangeMeaning *> RangeMeaning::registry; /** any value between and including minimumValue and maximumValue is valid. */ const RangeMeaning RangeMeaning::EXACT("exact"); /** Axis is continuous with values wrapping around at the minimumValue and * maximumValue */ const RangeMeaning RangeMeaning::WRAPAROUND("wraparound"); // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::map<std::string, const AxisDirectionWKT1 *> AxisDirectionWKT1::registry; const AxisDirectionWKT1 AxisDirectionWKT1::NORTH("NORTH"); const AxisDirectionWKT1 AxisDirectionWKT1::EAST("EAST"); const AxisDirectionWKT1 AxisDirectionWKT1::SOUTH("SOUTH"); const AxisDirectionWKT1 AxisDirectionWKT1::WEST("WEST"); const AxisDirectionWKT1 AxisDirectionWKT1::UP("UP"); const AxisDirectionWKT1 AxisDirectionWKT1::DOWN("DOWN"); const AxisDirectionWKT1 AxisDirectionWKT1::OTHER("OTHER"); //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const std::string AxisName::Longitude("Longitude"); const std::string AxisName::Latitude("Latitude"); const std::string AxisName::Easting("Easting"); const std::string AxisName::Northing("Northing"); const std::string AxisName::Westing("Westing"); const std::string AxisName::Southing("Southing"); const std::string AxisName::Ellipsoidal_height("Ellipsoidal height"); const std::string AxisName::Geocentric_X("Geocentric X"); const std::string AxisName::Geocentric_Y("Geocentric Y"); const std::string AxisName::Geocentric_Z("Geocentric Z"); //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const std::string AxisAbbreviation::lon("lon"); const std::string AxisAbbreviation::lat("lat"); const std::string AxisAbbreviation::E("E"); const std::string AxisAbbreviation::N("N"); const std::string AxisAbbreviation::h("h"); const std::string AxisAbbreviation::X("X"); const std::string AxisAbbreviation::Y("Y"); const std::string AxisAbbreviation::Z("Z"); //! @endcond } // namespace cs // --------------------------------------------------------------------------- /** \brief The realization is by adjustment of a levelling network fixed to one * or more tide gauges. */ const RealizationMethod RealizationMethod::LEVELLING("levelling"); /** \brief The realization is through a geoid height model or a height * correction model. This is applied to a specified geodetic CRS. */ const RealizationMethod RealizationMethod::GEOID("geoid"); /** \brief The realization is through a tidal model or by tidal predictions. */ const RealizationMethod RealizationMethod::TIDAL("tidal"); // --------------------------------------------------------------------------- /** \brief The Greenwich PrimeMeridian */ const PrimeMeridianNNPtr PrimeMeridian::GREENWICH(PrimeMeridian::createGREENWICH()); /** \brief The "Reference Meridian" PrimeMeridian. * * This is a meridian of longitude 0 to be used with non-Earth bodies. */ const PrimeMeridianNNPtr PrimeMeridian::REFERENCE_MERIDIAN( PrimeMeridian::createREFERENCE_MERIDIAN()); /** \brief The Paris PrimeMeridian */ const PrimeMeridianNNPtr PrimeMeridian::PARIS(PrimeMeridian::createPARIS()); // --------------------------------------------------------------------------- /** \brief Earth celestial body */ const std::string Ellipsoid::EARTH("Earth"); /** \brief The EPSG:7008 / "Clarke 1866" Ellipsoid */ const EllipsoidNNPtr Ellipsoid::CLARKE_1866(Ellipsoid::createCLARKE_1866()); /** \brief The EPSG:7030 / "WGS 84" Ellipsoid */ const EllipsoidNNPtr Ellipsoid::WGS84(Ellipsoid::createWGS84()); /** \brief The EPSG:7019 / "GRS 1980" Ellipsoid */ const EllipsoidNNPtr Ellipsoid::GRS1980(Ellipsoid::createGRS1980()); // --------------------------------------------------------------------------- /** \brief The EPSG:6267 / "North_American_Datum_1927" GeodeticReferenceFrame */ const GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::EPSG_6267( GeodeticReferenceFrame::createEPSG_6267()); /** \brief The EPSG:6269 / "North_American_Datum_1983" GeodeticReferenceFrame */ const GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::EPSG_6269( GeodeticReferenceFrame::createEPSG_6269()); /** \brief The EPSG:6326 / "WGS_1984" GeodeticReferenceFrame */ const GeodeticReferenceFrameNNPtr GeodeticReferenceFrame::EPSG_6326( GeodeticReferenceFrame::createEPSG_6326()); // --------------------------------------------------------------------------- /** \brief The proleptic Gregorian calendar. */ const std::string TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN("proleptic Gregorian"); // --------------------------------------------------------------------------- /** \brief EPSG:4978 / "WGS 84" Geocentric */ const GeodeticCRSNNPtr GeodeticCRS::EPSG_4978(GeodeticCRS::createEPSG_4978()); // --------------------------------------------------------------------------- /** \brief EPSG:4267 / "NAD27" 2D GeographicCRS */ const GeographicCRSNNPtr GeographicCRS::EPSG_4267(GeographicCRS::createEPSG_4267()); /** \brief EPSG:4269 / "NAD83" 2D GeographicCRS */ const GeographicCRSNNPtr GeographicCRS::EPSG_4269(GeographicCRS::createEPSG_4269()); /** \brief EPSG:4326 / "WGS 84" 2D GeographicCRS */ const GeographicCRSNNPtr GeographicCRS::EPSG_4326(GeographicCRS::createEPSG_4326()); /** \brief OGC:CRS84 / "CRS 84" 2D GeographicCRS (long, lat)*/ const GeographicCRSNNPtr GeographicCRS::OGC_CRS84(GeographicCRS::createOGC_CRS84()); /** \brief EPSG:4807 / "NTF (Paris)" 2D GeographicCRS */ const GeographicCRSNNPtr GeographicCRS::EPSG_4807(GeographicCRS::createEPSG_4807()); /** \brief EPSG:4979 / "WGS 84" 3D GeographicCRS */ const GeographicCRSNNPtr GeographicCRS::EPSG_4979(GeographicCRS::createEPSG_4979()); // --------------------------------------------------------------------------- /** \brief Key to set the operation version of a operation::CoordinateOperation * * The value is to be provided as a string. */ const std::string operation::CoordinateOperation::OPERATION_VERSION_KEY("operationVersion"); //! @cond Doxygen_Suppress const common::Measure operation::nullMeasure{}; const std::string operation::INVERSE_OF = "Inverse of "; const std::string operation::AXIS_ORDER_CHANGE_2D_NAME = "axis order change (2D)"; const std::string operation::AXIS_ORDER_CHANGE_3D_NAME = "axis order change (geographic3D horizontal)"; //! @endcond // --------------------------------------------------------------------------- NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/common.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj.h" #include "proj_internal.h" #include "proj_json_streaming_writer.hpp" #include <cmath> // M_PI #include <cstdlib> #include <memory> #include <string> #include <vector> using namespace NS_PROJ::internal; using namespace NS_PROJ::io; using namespace NS_PROJ::metadata; using namespace NS_PROJ::util; #if 0 namespace dropbox{ namespace oxygen { template<> nn<NS_PROJ::common::IdentifiedObjectPtr>::~nn() = default; template<> nn<NS_PROJ::common::ObjectDomainPtr>::~nn() = default; template<> nn<NS_PROJ::common::ObjectUsagePtr>::~nn() = default; template<> nn<NS_PROJ::common::UnitOfMeasurePtr>::~nn() = default; }} #endif NS_PROJ_START namespace common { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct UnitOfMeasure::Private { std::string name_{}; double toSI_ = 1.0; UnitOfMeasure::Type type_{UnitOfMeasure::Type::UNKNOWN}; std::string codeSpace_{}; std::string code_{}; Private(const std::string &nameIn, double toSIIn, UnitOfMeasure::Type typeIn, const std::string &codeSpaceIn, const std::string &codeIn) : name_(nameIn), toSI_(toSIIn), type_(typeIn), codeSpace_(codeSpaceIn), code_(codeIn) {} }; //! @endcond // --------------------------------------------------------------------------- /** \brief Creates a UnitOfMeasure. */ UnitOfMeasure::UnitOfMeasure(const std::string &nameIn, double toSIIn, UnitOfMeasure::Type typeIn, const std::string &codeSpaceIn, const std::string &codeIn) : d(internal::make_unique<Private>(nameIn, toSIIn, typeIn, codeSpaceIn, codeIn)) {} // --------------------------------------------------------------------------- UnitOfMeasure::UnitOfMeasure(const UnitOfMeasure &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress UnitOfMeasure::~UnitOfMeasure() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress UnitOfMeasure &UnitOfMeasure::operator=(const UnitOfMeasure &other) { if (this != &other) { *d = *(other.d); } return *this; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress UnitOfMeasure &UnitOfMeasure::operator=(UnitOfMeasure &&other) { *d = std::move(*(other.d)); other.d = nullptr; BaseObject::operator=(std::move(static_cast<BaseObject &&>(other))); return *this; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress UnitOfMeasureNNPtr UnitOfMeasure::create(const UnitOfMeasure &other) { return util::nn_make_shared<UnitOfMeasure>(other); } //! @endcond // --------------------------------------------------------------------------- /** \brief Return the name of the unit of measure. */ const std::string &UnitOfMeasure::name() PROJ_PURE_DEFN { return d->name_; } // --------------------------------------------------------------------------- /** \brief Return the conversion factor to the unit of the * International System of Units of the same Type. * * For example, for foot, this would be 0.3048 (metre) * * @return the conversion factor, or 0 if no conversion exists. */ double UnitOfMeasure::conversionToSI() PROJ_PURE_DEFN { return d->toSI_; } // --------------------------------------------------------------------------- /** \brief Return the type of the unit of measure. */ UnitOfMeasure::Type UnitOfMeasure::type() PROJ_PURE_DEFN { return d->type_; } // --------------------------------------------------------------------------- /** \brief Return the code space of the unit of measure. * * For example "EPSG" * * @return the code space, or empty string. */ const std::string &UnitOfMeasure::codeSpace() PROJ_PURE_DEFN { return d->codeSpace_; } // --------------------------------------------------------------------------- /** \brief Return the code of the unit of measure. * * @return the code, or empty string. */ const std::string &UnitOfMeasure::code() PROJ_PURE_DEFN { return d->code_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void UnitOfMeasure::_exportToWKT( WKTFormatter *formatter, const std::string &unitType) const // throw(FormattingException) { const bool isWKT2 = formatter->version() == WKTFormatter::Version::WKT2; const auto l_type = type(); if (!unitType.empty()) { formatter->startNode(unitType, !codeSpace().empty()); } else if (formatter->forceUNITKeyword() && l_type != Type::PARAMETRIC) { formatter->startNode(WKTConstants::UNIT, !codeSpace().empty()); } else { if (isWKT2 && l_type == Type::LINEAR) { formatter->startNode(WKTConstants::LENGTHUNIT, !codeSpace().empty()); } else if (isWKT2 && l_type == Type::ANGULAR) { formatter->startNode(WKTConstants::ANGLEUNIT, !codeSpace().empty()); } else if (isWKT2 && l_type == Type::SCALE) { formatter->startNode(WKTConstants::SCALEUNIT, !codeSpace().empty()); } else if (isWKT2 && l_type == Type::TIME) { formatter->startNode(WKTConstants::TIMEUNIT, !codeSpace().empty()); } else if (isWKT2 && l_type == Type::PARAMETRIC) { formatter->startNode(WKTConstants::PARAMETRICUNIT, !codeSpace().empty()); } else { formatter->startNode(WKTConstants::UNIT, !codeSpace().empty()); } } { const auto &l_name = name(); const bool esri = formatter->useESRIDialect(); if (esri) { if (ci_equal(l_name, "degree")) { formatter->addQuotedString("Degree"); } else if (ci_equal(l_name, "grad")) { formatter->addQuotedString("Grad"); } else if (ci_equal(l_name, "metre")) { formatter->addQuotedString("Meter"); } else { formatter->addQuotedString(l_name); } } else { formatter->addQuotedString(l_name); } const auto &factor = conversionToSI(); if (!isWKT2 || l_type != Type::TIME || factor != 0.0) { // Some TIMEUNIT do not have a conversion factor formatter->add(factor); } if (!codeSpace().empty() && formatter->outputId()) { formatter->startNode( isWKT2 ? WKTConstants::ID : WKTConstants::AUTHORITY, false); formatter->addQuotedString(codeSpace()); const auto &l_code = code(); if (isWKT2) { try { (void)std::stoi(l_code); formatter->add(l_code); } catch (const std::exception &) { formatter->addQuotedString(l_code); } } else { formatter->addQuotedString(l_code); } formatter->endNode(); } } formatter->endNode(); } // --------------------------------------------------------------------------- void UnitOfMeasure::_exportToJSON( JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); const auto &l_codeSpace = codeSpace(); auto objContext( formatter->MakeObjectContext(nullptr, !l_codeSpace.empty())); writer->AddObjKey("type"); const auto l_type = type(); if (l_type == Type::LINEAR) { writer->Add("LinearUnit"); } else if (l_type == Type::ANGULAR) { writer->Add("AngularUnit"); } else if (l_type == Type::SCALE) { writer->Add("ScaleUnit"); } else if (l_type == Type::TIME) { writer->Add("TimeUnit"); } else if (l_type == Type::PARAMETRIC) { writer->Add("ParametricUnit"); } else { writer->Add("Unit"); } writer->AddObjKey("name"); const auto &l_name = name(); writer->Add(l_name); const auto &factor = conversionToSI(); writer->AddObjKey("conversion_factor"); writer->Add(factor, 15); if (!l_codeSpace.empty() && formatter->outputId()) { writer->AddObjKey("id"); auto idContext(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("authority"); writer->Add(l_codeSpace); writer->AddObjKey("code"); const auto &l_code = code(); try { writer->Add(std::stoi(l_code)); } catch (const std::exception &) { writer->Add(l_code); } } } //! @endcond // --------------------------------------------------------------------------- /** Returns whether two units of measures are equal. * * The comparison is based on the name. */ bool UnitOfMeasure::operator==(const UnitOfMeasure &other) PROJ_PURE_DEFN { return name() == other.name(); } // --------------------------------------------------------------------------- /** Returns whether two units of measures are different. * * The comparison is based on the name. */ bool UnitOfMeasure::operator!=(const UnitOfMeasure &other) PROJ_PURE_DEFN { return name() != other.name(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::string UnitOfMeasure::exportToPROJString() const { if (type() == Type::LINEAR) { auto proj_units = pj_list_linear_units(); for (int i = 0; proj_units[i].id != nullptr; i++) { if (::fabs(proj_units[i].factor - conversionToSI()) < 1e-10 * conversionToSI()) { return proj_units[i].id; } } } else if (type() == Type::ANGULAR) { auto proj_angular_units = pj_list_angular_units(); for (int i = 0; proj_angular_units[i].id != nullptr; i++) { if (::fabs(proj_angular_units[i].factor - conversionToSI()) < 1e-10 * conversionToSI()) { return proj_angular_units[i].id; } } } return std::string(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool UnitOfMeasure::_isEquivalentTo( const UnitOfMeasure &other, util::IComparable::Criterion criterion) const { if (criterion == util::IComparable::Criterion::STRICT) { return operator==(other); } return std::fabs(conversionToSI() - other.conversionToSI()) <= 1e-10 * std::fabs(conversionToSI()); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Measure::Private { double value_ = 0.0; UnitOfMeasure unit_{}; Private(double valueIn, const UnitOfMeasure &unitIn) : value_(valueIn), unit_(unitIn) {} }; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a Measure. */ Measure::Measure(double valueIn, const UnitOfMeasure &unitIn) : d(internal::make_unique<Private>(valueIn, unitIn)) {} // --------------------------------------------------------------------------- Measure::Measure(const Measure &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Measure::~Measure() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the unit of the Measure. */ const UnitOfMeasure &Measure::unit() PROJ_PURE_DEFN { return d->unit_; } // --------------------------------------------------------------------------- /** \brief Return the value of the Measure, after conversion to the * corresponding * unit of the International System. */ double Measure::getSIValue() PROJ_PURE_DEFN { return d->value_ * d->unit_.conversionToSI(); } // --------------------------------------------------------------------------- /** \brief Return the value of the measure, expressed in the unit() */ double Measure::value() PROJ_PURE_DEFN { return d->value_; } // --------------------------------------------------------------------------- /** \brief Return the value of this measure expressed into the provided unit. */ double Measure::convertToUnit(const UnitOfMeasure &otherUnit) PROJ_PURE_DEFN { return getSIValue() / otherUnit.conversionToSI(); } // --------------------------------------------------------------------------- /** \brief Return whether two measures are equal. * * The comparison is done both on the value and the unit. */ bool Measure::operator==(const Measure &other) PROJ_PURE_DEFN { return d->value_ == other.d->value_ && d->unit_ == other.d->unit_; } // --------------------------------------------------------------------------- /** \brief Returns whether an object is equivalent to another one. * @param other other object to compare to * @param criterion comparison criterion. * @param maxRelativeError Maximum relative error allowed. * @return true if objects are equivalent. */ bool Measure::_isEquivalentTo(const Measure &other, util::IComparable::Criterion criterion, double maxRelativeError) const { if (criterion == util::IComparable::Criterion::STRICT) { return operator==(other); } const double SIValue = getSIValue(); const double otherSIValue = other.getSIValue(); // It is arguable that we have to deal with infinite values, but this // helps robustify some situations. if (std::isinf(SIValue) && std::isinf(otherSIValue)) return SIValue * otherSIValue > 0; return std::fabs(SIValue - otherSIValue) <= maxRelativeError * std::fabs(SIValue); } // --------------------------------------------------------------------------- /** \brief Instantiate a Scale. * * @param valueIn value */ Scale::Scale(double valueIn) : Measure(valueIn, UnitOfMeasure::SCALE_UNITY) {} // --------------------------------------------------------------------------- /** \brief Instantiate a Scale. * * @param valueIn value * @param unitIn unit. Constraint: unit.type() == UnitOfMeasure::Type::SCALE */ Scale::Scale(double valueIn, const UnitOfMeasure &unitIn) : Measure(valueIn, unitIn) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Scale::Scale(const Scale &) = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Scale::~Scale() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a Angle. * * @param valueIn value */ Angle::Angle(double valueIn) : Measure(valueIn, UnitOfMeasure::DEGREE) {} // --------------------------------------------------------------------------- /** \brief Instantiate a Angle. * * @param valueIn value * @param unitIn unit. Constraint: unit.type() == UnitOfMeasure::Type::ANGULAR */ Angle::Angle(double valueIn, const UnitOfMeasure &unitIn) : Measure(valueIn, unitIn) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Angle::Angle(const Angle &) = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Angle::~Angle() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a Length. * * @param valueIn value */ Length::Length(double valueIn) : Measure(valueIn, UnitOfMeasure::METRE) {} // --------------------------------------------------------------------------- /** \brief Instantiate a Length. * * @param valueIn value * @param unitIn unit. Constraint: unit.type() == UnitOfMeasure::Type::LINEAR */ Length::Length(double valueIn, const UnitOfMeasure &unitIn) : Measure(valueIn, unitIn) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Length::Length(const Length &) = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Length::~Length() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DateTime::Private { std::string str_{}; explicit Private(const std::string &str) : str_(str) {} }; //! @endcond // --------------------------------------------------------------------------- DateTime::DateTime() : d(internal::make_unique<Private>(std::string())) {} // --------------------------------------------------------------------------- DateTime::DateTime(const std::string &str) : d(internal::make_unique<Private>(str)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DateTime::DateTime(const DateTime &other) : d(internal::make_unique<Private>(*(other.d))) {} //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DateTime &DateTime::operator=(const DateTime &other) { d->str_ = other.d->str_; return *this; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DateTime::~DateTime() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a DateTime. */ DateTime DateTime::create(const std::string &str) { return DateTime(str); } // --------------------------------------------------------------------------- /** \brief Return whether the DateTime is ISO:8601 compliant. * * \remark The current implementation is really simplistic, and aimed at * detecting date-times that are not ISO:8601 compliant. */ bool DateTime::isISO_8601() const { return !d->str_.empty() && d->str_[0] >= '0' && d->str_[0] <= '9' && d->str_.find(' ') == std::string::npos; } // --------------------------------------------------------------------------- /** \brief Return the DateTime as a string. */ std::string DateTime::toString() const { return d->str_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // cppcheck-suppress copyCtorAndEqOperator struct IdentifiedObject::Private { IdentifierNNPtr name{Identifier::create()}; std::vector<IdentifierNNPtr> identifiers{}; std::vector<GenericNameNNPtr> aliases{}; std::string remarks{}; bool isDeprecated{}; void setIdentifiers(const PropertyMap &properties); void setName(const PropertyMap &properties); void setAliases(const PropertyMap &properties); }; //! @endcond // --------------------------------------------------------------------------- IdentifiedObject::IdentifiedObject() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- IdentifiedObject::IdentifiedObject(const IdentifiedObject &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress IdentifiedObject::~IdentifiedObject() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the name of the object. * * Generally, the only interesting field of the name will be * name()->description(). */ const IdentifierNNPtr &IdentifiedObject::name() PROJ_PURE_DEFN { return d->name; } // --------------------------------------------------------------------------- /** \brief Return the name of the object. * * Return *(name()->description()) */ const std::string &IdentifiedObject::nameStr() PROJ_PURE_DEFN { return *(d->name->description()); } // --------------------------------------------------------------------------- /** \brief Return the identifier(s) of the object * * Generally, those will have Identifier::code() and Identifier::codeSpace() * filled. */ const std::vector<IdentifierNNPtr> & IdentifiedObject::identifiers() PROJ_PURE_DEFN { return d->identifiers; } // --------------------------------------------------------------------------- /** \brief Return the alias(es) of the object. */ const std::vector<GenericNameNNPtr> & IdentifiedObject::aliases() PROJ_PURE_DEFN { return d->aliases; } // --------------------------------------------------------------------------- /** \brief Return the (first) alias of the object as a string. * * Shortcut for aliases()[0]->toFullyQualifiedName()->toString() */ std::string IdentifiedObject::alias() PROJ_PURE_DEFN { if (d->aliases.empty()) return std::string(); return d->aliases[0]->toFullyQualifiedName()->toString(); } // --------------------------------------------------------------------------- /** \brief Return the EPSG code. * @return code, or 0 if not found */ int IdentifiedObject::getEPSGCode() PROJ_PURE_DEFN { for (const auto &id : identifiers()) { if (ci_equal(*(id->codeSpace()), metadata::Identifier::EPSG)) { return ::atoi(id->code().c_str()); } } return 0; } // --------------------------------------------------------------------------- /** \brief Return the remarks. */ const std::string &IdentifiedObject::remarks() PROJ_PURE_DEFN { return d->remarks; } // --------------------------------------------------------------------------- /** \brief Return whether the object is deprecated. * * \remark Extension of \ref ISO_19111_2019 */ bool IdentifiedObject::isDeprecated() PROJ_PURE_DEFN { return d->isDeprecated; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void IdentifiedObject::Private::setName( const PropertyMap &properties) // throw(InvalidValueTypeException) { const auto pVal = properties.get(NAME_KEY); if (!pVal) { return; } if (const auto genVal = dynamic_cast<const BoxedValue *>(pVal->get())) { if (genVal->type() == BoxedValue::Type::STRING) { name = Identifier::createFromDescription(genVal->stringValue()); } else { throw InvalidValueTypeException("Invalid value type for " + NAME_KEY); } } else { if (auto identifier = util::nn_dynamic_pointer_cast<Identifier>(*pVal)) { name = NN_NO_CHECK(identifier); } else { throw InvalidValueTypeException("Invalid value type for " + NAME_KEY); } } } // --------------------------------------------------------------------------- void IdentifiedObject::Private::setIdentifiers( const PropertyMap &properties) // throw(InvalidValueTypeException) { auto pVal = properties.get(IDENTIFIERS_KEY); if (!pVal) { pVal = properties.get(Identifier::CODE_KEY); if (pVal) { identifiers.clear(); identifiers.push_back( Identifier::create(std::string(), properties)); } return; } if (auto identifier = util::nn_dynamic_pointer_cast<Identifier>(*pVal)) { identifiers.clear(); identifiers.push_back(NN_NO_CHECK(identifier)); } else { if (auto array = dynamic_cast<const ArrayOfBaseObject *>(pVal->get())) { identifiers.clear(); for (const auto &val : *array) { identifier = util::nn_dynamic_pointer_cast<Identifier>(val); if (identifier) { identifiers.push_back(NN_NO_CHECK(identifier)); } else { throw InvalidValueTypeException("Invalid value type for " + IDENTIFIERS_KEY); } } } else { throw InvalidValueTypeException("Invalid value type for " + IDENTIFIERS_KEY); } } } // --------------------------------------------------------------------------- void IdentifiedObject::Private::setAliases( const PropertyMap &properties) // throw(InvalidValueTypeException) { const auto pVal = properties.get(ALIAS_KEY); if (!pVal) { return; } if (auto l_name = util::nn_dynamic_pointer_cast<GenericName>(*pVal)) { aliases.clear(); aliases.push_back(NN_NO_CHECK(l_name)); } else { if (const auto array = dynamic_cast<const ArrayOfBaseObject *>(pVal->get())) { aliases.clear(); for (const auto &val : *array) { l_name = util::nn_dynamic_pointer_cast<GenericName>(val); if (l_name) { aliases.push_back(NN_NO_CHECK(l_name)); } else { if (auto genVal = dynamic_cast<const BoxedValue *>(val.get())) { if (genVal->type() == BoxedValue::Type::STRING) { aliases.push_back(NameFactory::createLocalName( nullptr, genVal->stringValue())); } else { throw InvalidValueTypeException( "Invalid value type for " + ALIAS_KEY); } } else { throw InvalidValueTypeException( "Invalid value type for " + ALIAS_KEY); } } } } else { std::string temp; if (properties.getStringValue(ALIAS_KEY, temp)) { aliases.clear(); aliases.push_back(NameFactory::createLocalName(nullptr, temp)); } else { throw InvalidValueTypeException("Invalid value type for " + ALIAS_KEY); } } } } //! @endcond // --------------------------------------------------------------------------- void IdentifiedObject::setProperties( const PropertyMap &properties) // throw(InvalidValueTypeException) { d->setName(properties); d->setIdentifiers(properties); d->setAliases(properties); properties.getStringValue(REMARKS_KEY, d->remarks); { const auto pVal = properties.get(DEPRECATED_KEY); if (pVal) { if (const auto genVal = dynamic_cast<const BoxedValue *>(pVal->get())) { if (genVal->type() == BoxedValue::Type::BOOLEAN) { d->isDeprecated = genVal->booleanValue(); } else { throw InvalidValueTypeException("Invalid value type for " + DEPRECATED_KEY); } } else { throw InvalidValueTypeException("Invalid value type for " + DEPRECATED_KEY); } } } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void IdentifiedObject::formatID(WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == WKTFormatter::Version::WKT2; for (const auto &id : identifiers()) { id->_exportToWKT(formatter); if (!isWKT2) { break; } } } // --------------------------------------------------------------------------- void IdentifiedObject::formatRemarks(WKTFormatter *formatter) const { if (!remarks().empty()) { formatter->startNode(WKTConstants::REMARK, false); formatter->addQuotedString(remarks()); formatter->endNode(); } } // --------------------------------------------------------------------------- void IdentifiedObject::formatID(JSONFormatter *formatter) const { const auto &ids(identifiers()); auto writer = formatter->writer(); if (ids.size() == 1) { writer->AddObjKey("id"); ids.front()->_exportToJSON(formatter); } else if (!ids.empty()) { writer->AddObjKey("ids"); auto arrayContext(writer->MakeArrayContext()); for (const auto &id : ids) { id->_exportToJSON(formatter); } } } // --------------------------------------------------------------------------- void IdentifiedObject::formatRemarks(JSONFormatter *formatter) const { if (!remarks().empty()) { auto writer = formatter->writer(); writer->AddObjKey("remarks"); writer->Add(remarks()); } } // --------------------------------------------------------------------------- bool IdentifiedObject::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherIdObj = dynamic_cast<const IdentifiedObject *>(other); if (!otherIdObj) return false; return _isEquivalentTo(otherIdObj, criterion, dbContext); } // --------------------------------------------------------------------------- bool IdentifiedObject::_isEquivalentTo( const IdentifiedObject *otherIdObj, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) PROJ_PURE_DEFN { if (criterion == util::IComparable::Criterion::STRICT) { if (!ci_equal(nameStr(), otherIdObj->nameStr())) { return false; } // TODO test id etc } else { if (!metadata::Identifier::isEquivalentName( nameStr().c_str(), otherIdObj->nameStr().c_str())) { return hasEquivalentNameToUsingAlias(otherIdObj, dbContext); } } return true; } // --------------------------------------------------------------------------- bool IdentifiedObject::hasEquivalentNameToUsingAlias( const IdentifiedObject *, const io::DatabaseContextPtr &) const { return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ObjectDomain::Private { optional<std::string> scope_{}; ExtentPtr domainOfValidity_{}; Private(const optional<std::string> &scopeIn, const ExtentPtr &extent) : scope_(scopeIn), domainOfValidity_(extent) {} }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ObjectDomain::ObjectDomain(const optional<std::string> &scopeIn, const ExtentPtr &extent) : d(internal::make_unique<Private>(scopeIn, extent)) {} //! @endcond // --------------------------------------------------------------------------- ObjectDomain::ObjectDomain(const ObjectDomain &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ObjectDomain::~ObjectDomain() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the scope. * * @return the scope, or empty. */ const optional<std::string> &ObjectDomain::scope() PROJ_PURE_DEFN { return d->scope_; } // --------------------------------------------------------------------------- /** \brief Return the domain of validity. * * @return the domain of validity, or nullptr. */ const ExtentPtr &ObjectDomain::domainOfValidity() PROJ_PURE_DEFN { return d->domainOfValidity_; } // --------------------------------------------------------------------------- /** \brief Instantiate a ObjectDomain. */ ObjectDomainNNPtr ObjectDomain::create(const optional<std::string> &scopeIn, const ExtentPtr &extent) { return ObjectDomain::nn_make_shared<ObjectDomain>(scopeIn, extent); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ObjectDomain::_exportToWKT(WKTFormatter *formatter) const { if (d->scope_.has_value()) { formatter->startNode(WKTConstants::SCOPE, false); formatter->addQuotedString(*(d->scope_)); formatter->endNode(); } else if (formatter->use2019Keywords()) { formatter->startNode(WKTConstants::SCOPE, false); formatter->addQuotedString("unknown"); formatter->endNode(); } if (d->domainOfValidity_) { if (d->domainOfValidity_->description().has_value()) { formatter->startNode(WKTConstants::AREA, false); formatter->addQuotedString(*(d->domainOfValidity_->description())); formatter->endNode(); } if (d->domainOfValidity_->geographicElements().size() == 1) { const auto bbox = dynamic_cast<const GeographicBoundingBox *>( d->domainOfValidity_->geographicElements()[0].get()); if (bbox) { formatter->startNode(WKTConstants::BBOX, false); formatter->add(bbox->southBoundLatitude()); formatter->add(bbox->westBoundLongitude()); formatter->add(bbox->northBoundLatitude()); formatter->add(bbox->eastBoundLongitude()); formatter->endNode(); } } if (d->domainOfValidity_->verticalElements().size() == 1) { auto extent = d->domainOfValidity_->verticalElements()[0]; formatter->startNode(WKTConstants::VERTICALEXTENT, false); formatter->add(extent->minimumValue()); formatter->add(extent->maximumValue()); extent->unit()->_exportToWKT(formatter); formatter->endNode(); } if (d->domainOfValidity_->temporalElements().size() == 1) { auto extent = d->domainOfValidity_->temporalElements()[0]; formatter->startNode(WKTConstants::TIMEEXTENT, false); if (DateTime::create(extent->start()).isISO_8601()) { formatter->add(extent->start()); } else { formatter->addQuotedString(extent->start()); } if (DateTime::create(extent->stop()).isISO_8601()) { formatter->add(extent->stop()); } else { formatter->addQuotedString(extent->stop()); } formatter->endNode(); } } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ObjectDomain::_exportToJSON(JSONFormatter *formatter) const { auto writer = formatter->writer(); if (d->scope_.has_value()) { writer->AddObjKey("scope"); writer->Add(*(d->scope_)); } if (d->domainOfValidity_) { if (d->domainOfValidity_->description().has_value()) { writer->AddObjKey("area"); writer->Add(*(d->domainOfValidity_->description())); } if (d->domainOfValidity_->geographicElements().size() == 1) { const auto bbox = dynamic_cast<const GeographicBoundingBox *>( d->domainOfValidity_->geographicElements()[0].get()); if (bbox) { writer->AddObjKey("bbox"); auto bboxContext(writer->MakeObjectContext()); writer->AddObjKey("south_latitude"); writer->Add(bbox->southBoundLatitude(), 15); writer->AddObjKey("west_longitude"); writer->Add(bbox->westBoundLongitude(), 15); writer->AddObjKey("north_latitude"); writer->Add(bbox->northBoundLatitude(), 15); writer->AddObjKey("east_longitude"); writer->Add(bbox->eastBoundLongitude(), 15); } } if (d->domainOfValidity_->verticalElements().size() == 1) { const auto &verticalExtent = d->domainOfValidity_->verticalElements().front(); writer->AddObjKey("vertical_extent"); auto bboxContext(writer->MakeObjectContext()); writer->AddObjKey("minimum"); writer->Add(verticalExtent->minimumValue(), 15); writer->AddObjKey("maximum"); writer->Add(verticalExtent->maximumValue(), 15); const auto &unit = verticalExtent->unit(); if (*unit != common::UnitOfMeasure::METRE) { writer->AddObjKey("unit"); unit->_exportToJSON(formatter); } } if (d->domainOfValidity_->temporalElements().size() == 1) { const auto &temporalExtent = d->domainOfValidity_->temporalElements().front(); writer->AddObjKey("temporal_extent"); auto bboxContext(writer->MakeObjectContext()); writer->AddObjKey("start"); writer->Add(temporalExtent->start()); writer->AddObjKey("end"); writer->Add(temporalExtent->stop()); } } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool ObjectDomain::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDomain = dynamic_cast<const ObjectDomain *>(other); if (!otherDomain) return false; if (scope().has_value() != otherDomain->scope().has_value()) return false; if (*scope() != *otherDomain->scope()) return false; if ((domainOfValidity().get() != nullptr) ^ (otherDomain->domainOfValidity().get() != nullptr)) return false; return domainOfValidity().get() == nullptr || domainOfValidity()->_isEquivalentTo( otherDomain->domainOfValidity().get(), criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ObjectUsage::Private { std::vector<ObjectDomainNNPtr> domains_{}; }; //! @endcond // --------------------------------------------------------------------------- ObjectUsage::ObjectUsage() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- ObjectUsage::ObjectUsage(const ObjectUsage &other) : IdentifiedObject(other), d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ObjectUsage::~ObjectUsage() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the domains of the object. */ const std::vector<ObjectDomainNNPtr> &ObjectUsage::domains() PROJ_PURE_DEFN { return d->domains_; } // --------------------------------------------------------------------------- void ObjectUsage::setProperties( const PropertyMap &properties) // throw(InvalidValueTypeException) { IdentifiedObject::setProperties(properties); optional<std::string> scope; properties.getStringValue(SCOPE_KEY, scope); ExtentPtr domainOfValidity; { const auto pVal = properties.get(DOMAIN_OF_VALIDITY_KEY); if (pVal) { domainOfValidity = util::nn_dynamic_pointer_cast<Extent>(*pVal); if (!domainOfValidity) { throw InvalidValueTypeException("Invalid value type for " + DOMAIN_OF_VALIDITY_KEY); } } } if (scope.has_value() || domainOfValidity) { d->domains_.emplace_back(ObjectDomain::create(scope, domainOfValidity)); } { const auto pVal = properties.get(OBJECT_DOMAIN_KEY); if (pVal) { if (auto objectDomain = util::nn_dynamic_pointer_cast<ObjectDomain>(*pVal)) { d->domains_.emplace_back(NN_NO_CHECK(objectDomain)); } else if (const auto array = dynamic_cast<const ArrayOfBaseObject *>( pVal->get())) { for (const auto &val : *array) { objectDomain = util::nn_dynamic_pointer_cast<ObjectDomain>(val); if (objectDomain) { d->domains_.emplace_back(NN_NO_CHECK(objectDomain)); } else { throw InvalidValueTypeException( "Invalid value type for " + OBJECT_DOMAIN_KEY); } } } else { throw InvalidValueTypeException("Invalid value type for " + OBJECT_DOMAIN_KEY); } } } } // --------------------------------------------------------------------------- void ObjectUsage::baseExportToWKT(WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == WKTFormatter::Version::WKT2; if (isWKT2 && formatter->outputUsage()) { auto l_domains = domains(); if (!l_domains.empty()) { if (formatter->use2019Keywords()) { for (const auto &domain : l_domains) { formatter->startNode(WKTConstants::USAGE, false); domain->_exportToWKT(formatter); formatter->endNode(); } } else { l_domains[0]->_exportToWKT(formatter); } } } if (formatter->outputId()) { formatID(formatter); } if (isWKT2) { formatRemarks(formatter); } } // --------------------------------------------------------------------------- void ObjectUsage::baseExportToJSON(JSONFormatter *formatter) const { auto writer = formatter->writer(); if (formatter->outputUsage()) { const auto &l_domains = domains(); if (l_domains.size() == 1) { l_domains[0]->_exportToJSON(formatter); } else if (!l_domains.empty()) { writer->AddObjKey("usages"); auto arrayContext(writer->MakeArrayContext(false)); for (const auto &domain : l_domains) { auto objContext(writer->MakeObjectContext()); domain->_exportToJSON(formatter); } } } if (formatter->outputId()) { formatID(formatter); } formatRemarks(formatter); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool ObjectUsage::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherObjUsage = dynamic_cast<const ObjectUsage *>(other); if (!otherObjUsage) return false; // TODO: incomplete return IdentifiedObject::_isEquivalentTo(other, criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DataEpoch::Private { Measure coordinateEpoch_{}; explicit Private(const Measure &coordinateEpochIn) : coordinateEpoch_(coordinateEpochIn) {} }; //! @endcond // --------------------------------------------------------------------------- DataEpoch::DataEpoch() : d(internal::make_unique<Private>(Measure())) {} // --------------------------------------------------------------------------- DataEpoch::DataEpoch(const Measure &coordinateEpochIn) : d(internal::make_unique<Private>(coordinateEpochIn)) {} // --------------------------------------------------------------------------- DataEpoch::DataEpoch(const DataEpoch &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DataEpoch::~DataEpoch() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the coordinate epoch, as a measure in decimal year. */ const Measure &DataEpoch::coordinateEpoch() const { return d->coordinateEpoch_; } } // namespace common NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/factory.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinates.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj/internal/lru_cache.hpp" #include "proj/internal/tracing.hpp" #include "operation/coordinateoperation_internal.hpp" #include "operation/parammappings.hpp" #include "filemanager.hpp" #include "sqlite3_utils.hpp" #include <algorithm> #include <cmath> #include <cstdlib> #include <cstring> #include <functional> #include <iomanip> #include <limits> #include <locale> #include <map> #include <memory> #include <mutex> #include <sstream> // std::ostringstream #include <stdexcept> #include <string> #include "proj_constants.h" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // clang-format on #include <sqlite3.h> // Custom SQLite VFS as our database is not supposed to be modified in // parallel. This is slightly faster #define ENABLE_CUSTOM_LOCKLESS_VFS #if defined(_WIN32) && defined(PROJ_HAS_PTHREADS) #undef PROJ_HAS_PTHREADS #endif /* SQLite3 might use seak()+read() or pread[64]() to read data */ /* The later allows the same SQLite handle to be safely used in forked */ /* children of a parent process, while the former doesn't. */ /* So we use pthread_atfork() to set a flag in forked children, to ask them */ /* to close and reopen their database handle. */ #if defined(PROJ_HAS_PTHREADS) && !defined(SQLITE_USE_PREAD) #include <pthread.h> #define REOPEN_SQLITE_DB_AFTER_FORK #endif using namespace NS_PROJ::internal; using namespace NS_PROJ::common; NS_PROJ_START namespace io { //! @cond Doxygen_Suppress // CRS subtypes #define GEOG_2D "geographic 2D" #define GEOG_3D "geographic 3D" #define GEOCENTRIC "geocentric" #define OTHER "other" #define PROJECTED "projected" #define VERTICAL "vertical" #define COMPOUND "compound" #define GEOG_2D_SINGLE_QUOTED "'geographic 2D'" #define GEOG_3D_SINGLE_QUOTED "'geographic 3D'" #define GEOCENTRIC_SINGLE_QUOTED "'geocentric'" // Coordinate system types constexpr const char *CS_TYPE_ELLIPSOIDAL = cs::EllipsoidalCS::WKT2_TYPE; constexpr const char *CS_TYPE_CARTESIAN = cs::CartesianCS::WKT2_TYPE; constexpr const char *CS_TYPE_SPHERICAL = cs::SphericalCS::WKT2_TYPE; constexpr const char *CS_TYPE_VERTICAL = cs::VerticalCS::WKT2_TYPE; constexpr const char *CS_TYPE_ORDINAL = cs::OrdinalCS::WKT2_TYPE; // See data/sql/metadata.sql for the semantics of those constants constexpr int DATABASE_LAYOUT_VERSION_MAJOR = 1; // If the code depends on the new additions, then DATABASE_LAYOUT_VERSION_MINOR // must be incremented. constexpr int DATABASE_LAYOUT_VERSION_MINOR = 3; constexpr size_t N_MAX_PARAMS = 7; // --------------------------------------------------------------------------- struct SQLValues { enum class Type { STRING, INT, DOUBLE }; // cppcheck-suppress noExplicitConstructor SQLValues(const std::string &value) : type_(Type::STRING), str_(value) {} // cppcheck-suppress noExplicitConstructor SQLValues(int value) : type_(Type::INT), int_(value) {} // cppcheck-suppress noExplicitConstructor SQLValues(double value) : type_(Type::DOUBLE), double_(value) {} const Type &type() const { return type_; } // cppcheck-suppress functionStatic const std::string &stringValue() const { return str_; } // cppcheck-suppress functionStatic int intValue() const { return int_; } // cppcheck-suppress functionStatic double doubleValue() const { return double_; } private: Type type_; std::string str_{}; int int_ = 0; double double_ = 0.0; }; // --------------------------------------------------------------------------- using SQLRow = std::vector<std::string>; using SQLResultSet = std::list<SQLRow>; using ListOfParams = std::list<SQLValues>; // --------------------------------------------------------------------------- static double PROJ_SQLITE_GetValAsDouble(sqlite3_value *val, bool &gotVal) { switch (sqlite3_value_type(val)) { case SQLITE_FLOAT: gotVal = true; return sqlite3_value_double(val); case SQLITE_INTEGER: gotVal = true; return static_cast<double>(sqlite3_value_int64(val)); default: gotVal = false; return 0.0; } } // --------------------------------------------------------------------------- static void PROJ_SQLITE_pseudo_area_from_swne(sqlite3_context *pContext, int /* argc */, sqlite3_value **argv) { bool b0, b1, b2, b3; double south_lat = PROJ_SQLITE_GetValAsDouble(argv[0], b0); double west_lon = PROJ_SQLITE_GetValAsDouble(argv[1], b1); double north_lat = PROJ_SQLITE_GetValAsDouble(argv[2], b2); double east_lon = PROJ_SQLITE_GetValAsDouble(argv[3], b3); if (!b0 || !b1 || !b2 || !b3) { sqlite3_result_null(pContext); return; } // Deal with area crossing antimeridian if (east_lon < west_lon) { east_lon += 360.0; } // Integrate cos(lat) between south_lat and north_lat double pseudo_area = (east_lon - west_lon) * (std::sin(common::Angle(north_lat).getSIValue()) - std::sin(common::Angle(south_lat).getSIValue())); sqlite3_result_double(pContext, pseudo_area); } // --------------------------------------------------------------------------- static void PROJ_SQLITE_intersects_bbox(sqlite3_context *pContext, int /* argc */, sqlite3_value **argv) { bool b0, b1, b2, b3, b4, b5, b6, b7; double south_lat1 = PROJ_SQLITE_GetValAsDouble(argv[0], b0); double west_lon1 = PROJ_SQLITE_GetValAsDouble(argv[1], b1); double north_lat1 = PROJ_SQLITE_GetValAsDouble(argv[2], b2); double east_lon1 = PROJ_SQLITE_GetValAsDouble(argv[3], b3); double south_lat2 = PROJ_SQLITE_GetValAsDouble(argv[4], b4); double west_lon2 = PROJ_SQLITE_GetValAsDouble(argv[5], b5); double north_lat2 = PROJ_SQLITE_GetValAsDouble(argv[6], b6); double east_lon2 = PROJ_SQLITE_GetValAsDouble(argv[7], b7); if (!b0 || !b1 || !b2 || !b3 || !b4 || !b5 || !b6 || !b7) { sqlite3_result_null(pContext); return; } auto bbox1 = metadata::GeographicBoundingBox::create(west_lon1, south_lat1, east_lon1, north_lat1); auto bbox2 = metadata::GeographicBoundingBox::create(west_lon2, south_lat2, east_lon2, north_lat2); sqlite3_result_int(pContext, bbox1->intersects(bbox2) ? 1 : 0); } // --------------------------------------------------------------------------- class SQLiteHandle { sqlite3 *sqlite_handle_ = nullptr; bool close_handle_ = true; #ifdef REOPEN_SQLITE_DB_AFTER_FORK bool is_valid_ = true; #endif int nLayoutVersionMajor_ = 0; int nLayoutVersionMinor_ = 0; #ifdef ENABLE_CUSTOM_LOCKLESS_VFS std::unique_ptr<SQLite3VFS> vfs_{}; #endif SQLiteHandle(const SQLiteHandle &) = delete; SQLiteHandle &operator=(const SQLiteHandle &) = delete; SQLiteHandle(sqlite3 *sqlite_handle, bool close_handle) : sqlite_handle_(sqlite_handle), close_handle_(close_handle) { assert(sqlite_handle_); } // cppcheck-suppress functionStatic void initialize(); SQLResultSet run(const std::string &sql, const ListOfParams &parameters = ListOfParams(), bool useMaxFloatPrecision = false); public: ~SQLiteHandle(); sqlite3 *handle() { return sqlite_handle_; } #ifdef REOPEN_SQLITE_DB_AFTER_FORK bool isValid() const { return is_valid_; } void invalidate() { is_valid_ = false; } #endif static std::shared_ptr<SQLiteHandle> open(PJ_CONTEXT *ctx, const std::string &path); // might not be shared between thread depending how the handle was opened! static std::shared_ptr<SQLiteHandle> initFromExisting(sqlite3 *sqlite_handle, bool close_handle, int nLayoutVersionMajor, int nLayoutVersionMinor); static std::unique_ptr<SQLiteHandle> initFromExistingUniquePtr(sqlite3 *sqlite_handle, bool close_handle); void checkDatabaseLayout(const std::string &mainDbPath, const std::string &path, const std::string &dbNamePrefix); SQLResultSet run(sqlite3_stmt *stmt, const std::string &sql, const ListOfParams &parameters = ListOfParams(), bool useMaxFloatPrecision = false); inline int getLayoutVersionMajor() const { return nLayoutVersionMajor_; } inline int getLayoutVersionMinor() const { return nLayoutVersionMinor_; } }; // --------------------------------------------------------------------------- SQLiteHandle::~SQLiteHandle() { if (close_handle_) { sqlite3_close(sqlite_handle_); } } // --------------------------------------------------------------------------- std::shared_ptr<SQLiteHandle> SQLiteHandle::open(PJ_CONTEXT *ctx, const std::string &path) { const int sqlite3VersionNumber = sqlite3_libversion_number(); // Minimum version for correct performance: 3.11 if (sqlite3VersionNumber < 3 * 1000000 + 11 * 1000) { pj_log(ctx, PJ_LOG_ERROR, "SQLite3 version is %s, whereas at least 3.11 should be used", sqlite3_libversion()); } std::string vfsName; #ifdef ENABLE_CUSTOM_LOCKLESS_VFS std::unique_ptr<SQLite3VFS> vfs; if (ctx->custom_sqlite3_vfs_name.empty()) { vfs = SQLite3VFS::create(false, true, true); if (vfs == nullptr) { throw FactoryException("Open of " + path + " failed"); } vfsName = vfs->name(); } else #endif { vfsName = ctx->custom_sqlite3_vfs_name; } sqlite3 *sqlite_handle = nullptr; // SQLITE_OPEN_FULLMUTEX as this will be used from concurrent threads if (sqlite3_open_v2( path.c_str(), &sqlite_handle, SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_URI, vfsName.empty() ? nullptr : vfsName.c_str()) != SQLITE_OK || !sqlite_handle) { if (sqlite_handle != nullptr) { sqlite3_close(sqlite_handle); } throw FactoryException("Open of " + path + " failed"); } auto handle = std::shared_ptr<SQLiteHandle>(new SQLiteHandle(sqlite_handle, true)); #ifdef ENABLE_CUSTOM_LOCKLESS_VFS handle->vfs_ = std::move(vfs); #endif handle->initialize(); handle->checkDatabaseLayout(path, path, std::string()); return handle; } // --------------------------------------------------------------------------- std::shared_ptr<SQLiteHandle> SQLiteHandle::initFromExisting(sqlite3 *sqlite_handle, bool close_handle, int nLayoutVersionMajor, int nLayoutVersionMinor) { auto handle = std::shared_ptr<SQLiteHandle>( new SQLiteHandle(sqlite_handle, close_handle)); handle->nLayoutVersionMajor_ = nLayoutVersionMajor; handle->nLayoutVersionMinor_ = nLayoutVersionMinor; handle->initialize(); return handle; } // --------------------------------------------------------------------------- std::unique_ptr<SQLiteHandle> SQLiteHandle::initFromExistingUniquePtr(sqlite3 *sqlite_handle, bool close_handle) { auto handle = std::unique_ptr<SQLiteHandle>( new SQLiteHandle(sqlite_handle, close_handle)); handle->initialize(); return handle; } // --------------------------------------------------------------------------- SQLResultSet SQLiteHandle::run(sqlite3_stmt *stmt, const std::string &sql, const ListOfParams &parameters, bool useMaxFloatPrecision) { int nBindField = 1; for (const auto &param : parameters) { const auto &paramType = param.type(); if (paramType == SQLValues::Type::STRING) { const auto &strValue = param.stringValue(); sqlite3_bind_text(stmt, nBindField, strValue.c_str(), static_cast<int>(strValue.size()), SQLITE_TRANSIENT); } else if (paramType == SQLValues::Type::INT) { sqlite3_bind_int(stmt, nBindField, param.intValue()); } else { assert(paramType == SQLValues::Type::DOUBLE); sqlite3_bind_double(stmt, nBindField, param.doubleValue()); } nBindField++; } #ifdef TRACE_DATABASE size_t nPos = 0; std::string sqlSubst(sql); for (const auto &param : parameters) { nPos = sqlSubst.find('?', nPos); assert(nPos != std::string::npos); std::string strValue; const auto paramType = param.type(); if (paramType == SQLValues::Type::STRING) { strValue = '\'' + param.stringValue() + '\''; } else if (paramType == SQLValues::Type::INT) { strValue = toString(param.intValue()); } else { strValue = toString(param.doubleValue()); } sqlSubst = sqlSubst.substr(0, nPos) + strValue + sqlSubst.substr(nPos + 1); nPos += strValue.size(); } logTrace(sqlSubst, "DATABASE"); #endif SQLResultSet result; const int column_count = sqlite3_column_count(stmt); while (true) { int ret = sqlite3_step(stmt); if (ret == SQLITE_ROW) { SQLRow row(column_count); for (int i = 0; i < column_count; i++) { if (useMaxFloatPrecision && sqlite3_column_type(stmt, i) == SQLITE_FLOAT) { // sqlite3_column_text() does not use maximum precision std::ostringstream buffer; buffer.imbue(std::locale::classic()); buffer << std::setprecision(18); buffer << sqlite3_column_double(stmt, i); row[i] = buffer.str(); } else { const char *txt = reinterpret_cast<const char *>( sqlite3_column_text(stmt, i)); if (txt) { row[i] = txt; } } } result.emplace_back(std::move(row)); } else if (ret == SQLITE_DONE) { break; } else { throw FactoryException("SQLite error on " + sql + ": " + sqlite3_errmsg(sqlite_handle_)); } } return result; } // --------------------------------------------------------------------------- SQLResultSet SQLiteHandle::run(const std::string &sql, const ListOfParams &parameters, bool useMaxFloatPrecision) { sqlite3_stmt *stmt = nullptr; try { if (sqlite3_prepare_v2(sqlite_handle_, sql.c_str(), static_cast<int>(sql.size()), &stmt, nullptr) != SQLITE_OK) { throw FactoryException("SQLite error on " + sql + ": " + sqlite3_errmsg(sqlite_handle_)); } auto ret = run(stmt, sql, parameters, useMaxFloatPrecision); sqlite3_finalize(stmt); return ret; } catch (const std::exception &) { if (stmt) sqlite3_finalize(stmt); throw; } } // --------------------------------------------------------------------------- void SQLiteHandle::checkDatabaseLayout(const std::string &mainDbPath, const std::string &path, const std::string &dbNamePrefix) { if (!dbNamePrefix.empty() && run("SELECT 1 FROM " + dbNamePrefix + "sqlite_master WHERE name = 'metadata'") .empty()) { // Accept auxiliary databases without metadata table (sparse DBs) return; } auto res = run("SELECT key, value FROM " + dbNamePrefix + "metadata WHERE key IN " "('DATABASE.LAYOUT.VERSION.MAJOR', " "'DATABASE.LAYOUT.VERSION.MINOR')"); if (res.empty() && !dbNamePrefix.empty()) { // Accept auxiliary databases without layout metadata. return; } if (res.size() != 2) { throw FactoryException( path + " lacks DATABASE.LAYOUT.VERSION.MAJOR / " "DATABASE.LAYOUT.VERSION.MINOR " "metadata. It comes from another PROJ installation."); } int major = 0; int minor = 0; for (const auto &row : res) { if (row[0] == "DATABASE.LAYOUT.VERSION.MAJOR") { major = atoi(row[1].c_str()); } else if (row[0] == "DATABASE.LAYOUT.VERSION.MINOR") { minor = atoi(row[1].c_str()); } } if (major != DATABASE_LAYOUT_VERSION_MAJOR) { throw FactoryException( path + " contains DATABASE.LAYOUT.VERSION.MAJOR = " + toString(major) + " whereas " + toString(DATABASE_LAYOUT_VERSION_MAJOR) + " is expected. " "It comes from another PROJ installation."); } if (minor < DATABASE_LAYOUT_VERSION_MINOR) { throw FactoryException( path + " contains DATABASE.LAYOUT.VERSION.MINOR = " + toString(minor) + " whereas a number >= " + toString(DATABASE_LAYOUT_VERSION_MINOR) + " is expected. " "It comes from another PROJ installation."); } if (dbNamePrefix.empty()) { nLayoutVersionMajor_ = major; nLayoutVersionMinor_ = minor; } else if (nLayoutVersionMajor_ != major || nLayoutVersionMinor_ != minor) { throw FactoryException( "Auxiliary database " + path + " contains a DATABASE.LAYOUT.VERSION = " + toString(major) + '.' + toString(minor) + " which is different from the one from the main database " + mainDbPath + " which is " + toString(nLayoutVersionMajor_) + '.' + toString(nLayoutVersionMinor_)); } } // --------------------------------------------------------------------------- #ifndef SQLITE_DETERMINISTIC #define SQLITE_DETERMINISTIC 0 #endif void SQLiteHandle::initialize() { // There is a bug in sqlite 3.38.0 with some complex queries. // Cf https://github.com/OSGeo/PROJ/issues/3077 // Disabling Bloom-filter pull-down optimization as suggested in // https://sqlite.org/forum/forumpost/7d3a75438c const int sqlite3VersionNumber = sqlite3_libversion_number(); if (sqlite3VersionNumber == 3 * 1000000 + 38 * 1000) { sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite_handle_, 0x100000); } sqlite3_create_function(sqlite_handle_, "pseudo_area_from_swne", 4, SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr, PROJ_SQLITE_pseudo_area_from_swne, nullptr, nullptr); sqlite3_create_function(sqlite_handle_, "intersects_bbox", 8, SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr, PROJ_SQLITE_intersects_bbox, nullptr, nullptr); } // --------------------------------------------------------------------------- class SQLiteHandleCache { #ifdef REOPEN_SQLITE_DB_AFTER_FORK bool firstTime_ = true; #endif std::mutex sMutex_{}; // Map dbname to SQLiteHandle lru11::Cache<std::string, std::shared_ptr<SQLiteHandle>> cache_{}; public: static SQLiteHandleCache &get(); std::shared_ptr<SQLiteHandle> getHandle(const std::string &path, PJ_CONTEXT *ctx); void clear(); #ifdef REOPEN_SQLITE_DB_AFTER_FORK void invalidateHandles(); #endif }; // --------------------------------------------------------------------------- SQLiteHandleCache &SQLiteHandleCache::get() { // Global cache static SQLiteHandleCache gSQLiteHandleCache; return gSQLiteHandleCache; } // --------------------------------------------------------------------------- void SQLiteHandleCache::clear() { std::lock_guard<std::mutex> lock(sMutex_); cache_.clear(); } // --------------------------------------------------------------------------- std::shared_ptr<SQLiteHandle> SQLiteHandleCache::getHandle(const std::string &path, PJ_CONTEXT *ctx) { std::lock_guard<std::mutex> lock(sMutex_); #ifdef REOPEN_SQLITE_DB_AFTER_FORK if (firstTime_) { firstTime_ = false; pthread_atfork(nullptr, nullptr, []() { SQLiteHandleCache::get().invalidateHandles(); }); } #endif std::shared_ptr<SQLiteHandle> handle; std::string key = path + ctx->custom_sqlite3_vfs_name; if (!cache_.tryGet(key, handle)) { handle = SQLiteHandle::open(ctx, path); cache_.insert(key, handle); } return handle; } #ifdef REOPEN_SQLITE_DB_AFTER_FORK // --------------------------------------------------------------------------- void SQLiteHandleCache::invalidateHandles() { std::lock_guard<std::mutex> lock(sMutex_); const auto lambda = [](const lru11::KeyValuePair<std::string, std::shared_ptr<SQLiteHandle>> &kvp) { kvp.value->invalidate(); }; cache_.cwalk(lambda); cache_.clear(); } #endif // --------------------------------------------------------------------------- struct DatabaseContext::Private { Private(); ~Private(); void open(const std::string &databasePath, PJ_CONTEXT *ctx); void setHandle(sqlite3 *sqlite_handle); const std::shared_ptr<SQLiteHandle> &handle(); PJ_CONTEXT *pjCtxt() const { return pjCtxt_; } void setPjCtxt(PJ_CONTEXT *ctxt) { pjCtxt_ = ctxt; } SQLResultSet run(const std::string &sql, const ListOfParams &parameters = ListOfParams(), bool useMaxFloatPrecision = false); std::vector<std::string> getDatabaseStructure(); // cppcheck-suppress functionStatic const std::string &getPath() const { return databasePath_; } void attachExtraDatabases( const std::vector<std::string> &auxiliaryDatabasePaths); // Mechanism to detect recursion in calls from // AuthorityFactory::createXXX() -> createFromUserInput() -> // AuthorityFactory::createXXX() struct RecursionDetector { explicit RecursionDetector(const DatabaseContextNNPtr &context) : dbContext_(context) { if (dbContext_->getPrivate()->recLevel_ == 2) { // Throw exception before incrementing, since the destructor // will not be called throw FactoryException("Too many recursive calls"); } ++dbContext_->getPrivate()->recLevel_; } ~RecursionDetector() { --dbContext_->getPrivate()->recLevel_; } private: DatabaseContextNNPtr dbContext_; }; std::map<std::string, std::list<SQLRow>> &getMapCanonicalizeGRFName() { return mapCanonicalizeGRFName_; } // cppcheck-suppress functionStatic common::UnitOfMeasurePtr getUOMFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const common::UnitOfMeasureNNPtr &uom); // cppcheck-suppress functionStatic crs::CRSPtr getCRSFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const crs::CRSNNPtr &crs); datum::GeodeticReferenceFramePtr // cppcheck-suppress functionStatic getGeodeticDatumFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const datum::GeodeticReferenceFrameNNPtr &datum); datum::DatumEnsemblePtr // cppcheck-suppress functionStatic getDatumEnsembleFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const datum::DatumEnsembleNNPtr &datumEnsemble); datum::EllipsoidPtr // cppcheck-suppress functionStatic getEllipsoidFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const datum::EllipsoidNNPtr &ellipsoid); datum::PrimeMeridianPtr // cppcheck-suppress functionStatic getPrimeMeridianFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const datum::PrimeMeridianNNPtr &pm); // cppcheck-suppress functionStatic cs::CoordinateSystemPtr getCoordinateSystemFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const cs::CoordinateSystemNNPtr &cs); // cppcheck-suppress functionStatic metadata::ExtentPtr getExtentFromCache(const std::string &code); // cppcheck-suppress functionStatic void cache(const std::string &code, const metadata::ExtentNNPtr &extent); // cppcheck-suppress functionStatic bool getCRSToCRSCoordOpFromCache( const std::string &code, std::vector<operation::CoordinateOperationNNPtr> &list); // cppcheck-suppress functionStatic void cache(const std::string &code, const std::vector<operation::CoordinateOperationNNPtr> &list); struct GridInfoCache { std::string fullFilename{}; std::string packageName{}; std::string url{}; bool found = false; bool directDownload = false; bool openLicense = false; bool gridAvailable = false; }; // cppcheck-suppress functionStatic bool getGridInfoFromCache(const std::string &code, GridInfoCache &info); // cppcheck-suppress functionStatic void cache(const std::string &code, const GridInfoCache &info); struct VersionedAuthName { std::string versionedAuthName{}; std::string authName{}; std::string version{}; int priority = 0; }; const std::vector<VersionedAuthName> &getCacheAuthNameWithVersion(); private: friend class DatabaseContext; // This is a manual implementation of std::enable_shared_from_this<> that // avoids publicly deriving from it. std::weak_ptr<DatabaseContext> self_{}; std::string databasePath_{}; std::vector<std::string> auxiliaryDatabasePaths_{}; std::shared_ptr<SQLiteHandle> sqlite_handle_{}; std::map<std::string, sqlite3_stmt *> mapSqlToStatement_{}; PJ_CONTEXT *pjCtxt_ = nullptr; int recLevel_ = 0; bool detach_ = false; std::string lastMetadataValue_{}; std::map<std::string, std::list<SQLRow>> mapCanonicalizeGRFName_{}; // Used by startInsertStatementsSession() and related functions std::string memoryDbForInsertPath_{}; std::unique_ptr<SQLiteHandle> memoryDbHandle_{}; using LRUCacheOfObjects = lru11::Cache<std::string, util::BaseObjectPtr>; static constexpr size_t CACHE_SIZE = 128; LRUCacheOfObjects cacheUOM_{CACHE_SIZE}; LRUCacheOfObjects cacheCRS_{CACHE_SIZE}; LRUCacheOfObjects cacheEllipsoid_{CACHE_SIZE}; LRUCacheOfObjects cacheGeodeticDatum_{CACHE_SIZE}; LRUCacheOfObjects cacheDatumEnsemble_{CACHE_SIZE}; LRUCacheOfObjects cachePrimeMeridian_{CACHE_SIZE}; LRUCacheOfObjects cacheCS_{CACHE_SIZE}; LRUCacheOfObjects cacheExtent_{CACHE_SIZE}; lru11::Cache<std::string, std::vector<operation::CoordinateOperationNNPtr>> cacheCRSToCrsCoordOp_{CACHE_SIZE}; lru11::Cache<std::string, GridInfoCache> cacheGridInfo_{CACHE_SIZE}; std::map<std::string, std::vector<std::string>> cacheAllowedAuthorities_{}; lru11::Cache<std::string, std::list<std::string>> cacheAliasNames_{ CACHE_SIZE}; std::vector<VersionedAuthName> cacheAuthNameWithVersion_{}; static void insertIntoCache(LRUCacheOfObjects &cache, const std::string &code, const util::BaseObjectPtr &obj); static void getFromCache(LRUCacheOfObjects &cache, const std::string &code, util::BaseObjectPtr &obj); void closeDB() noexcept; void clearCaches(); std::string findFreeCode(const std::string &tableName, const std::string &authName, const std::string &codePrototype); void identify(const DatabaseContextNNPtr &dbContext, const cs::CoordinateSystemNNPtr &obj, std::string &authName, std::string &code); void identifyOrInsert(const DatabaseContextNNPtr &dbContext, const cs::CoordinateSystemNNPtr &obj, const std::string &ownerType, const std::string &ownerAuthName, const std::string &ownerCode, std::string &authName, std::string &code, std::vector<std::string> &sqlStatements); void identify(const DatabaseContextNNPtr &dbContext, const common::UnitOfMeasure &obj, std::string &authName, std::string &code); void identifyOrInsert(const DatabaseContextNNPtr &dbContext, const common::UnitOfMeasure &unit, const std::string &ownerAuthName, std::string &authName, std::string &code, std::vector<std::string> &sqlStatements); void appendSql(std::vector<std::string> &sqlStatements, const std::string &sql); void identifyOrInsertUsages(const common::ObjectUsageNNPtr &obj, const std::string &tableName, const std::string &authName, const std::string &code, const std::vector<std::string> &allowedAuthorities, std::vector<std::string> &sqlStatements); std::vector<std::string> getInsertStatementsFor(const datum::PrimeMeridianNNPtr &pm, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const datum::EllipsoidNNPtr &ellipsoid, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const datum::GeodeticReferenceFrameNNPtr &datum, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const datum::DatumEnsembleNNPtr &ensemble, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const crs::GeodeticCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const crs::ProjectedCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const datum::VerticalReferenceFrameNNPtr &datum, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const crs::VerticalCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); std::vector<std::string> getInsertStatementsFor(const crs::CompoundCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities); Private(const Private &) = delete; Private &operator=(const Private &) = delete; }; // --------------------------------------------------------------------------- DatabaseContext::Private::Private() = default; // --------------------------------------------------------------------------- DatabaseContext::Private::~Private() { assert(recLevel_ == 0); closeDB(); } // --------------------------------------------------------------------------- void DatabaseContext::Private::closeDB() noexcept { if (detach_) { // Workaround a bug visible in SQLite 3.8.1 and 3.8.2 that causes // a crash in TEST(factory, attachExtraDatabases_auxiliary) // due to possible wrong caching of key info. // The bug is specific to using a memory file with shared cache as an // auxiliary DB. // The fix was likely in 3.8.8 // https://github.com/mackyle/sqlite/commit/d412d4b8731991ecbd8811874aa463d0821673eb // But just after 3.8.2, // https://github.com/mackyle/sqlite/commit/ccf328c4318eacedab9ed08c404bc4f402dcad19 // also seemed to hide the issue. // Detaching a database hides the issue, not sure if it is by chance... try { run("DETACH DATABASE db_0"); } catch (...) { } detach_ = false; } for (auto &pair : mapSqlToStatement_) { sqlite3_finalize(pair.second); } mapSqlToStatement_.clear(); sqlite_handle_.reset(); } // --------------------------------------------------------------------------- void DatabaseContext::Private::clearCaches() { cacheUOM_.clear(); cacheCRS_.clear(); cacheEllipsoid_.clear(); cacheGeodeticDatum_.clear(); cacheDatumEnsemble_.clear(); cachePrimeMeridian_.clear(); cacheCS_.clear(); cacheExtent_.clear(); cacheCRSToCrsCoordOp_.clear(); cacheGridInfo_.clear(); cacheAllowedAuthorities_.clear(); cacheAliasNames_.clear(); } // --------------------------------------------------------------------------- const std::shared_ptr<SQLiteHandle> &DatabaseContext::Private::handle() { #ifdef REOPEN_SQLITE_DB_AFTER_FORK if (sqlite_handle_ && !sqlite_handle_->isValid()) { closeDB(); open(databasePath_, pjCtxt_); if (!auxiliaryDatabasePaths_.empty()) { attachExtraDatabases(auxiliaryDatabasePaths_); } } #endif return sqlite_handle_; } // --------------------------------------------------------------------------- void DatabaseContext::Private::insertIntoCache(LRUCacheOfObjects &cache, const std::string &code, const util::BaseObjectPtr &obj) { cache.insert(code, obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::getFromCache(LRUCacheOfObjects &cache, const std::string &code, util::BaseObjectPtr &obj) { cache.tryGet(code, obj); } // --------------------------------------------------------------------------- bool DatabaseContext::Private::getCRSToCRSCoordOpFromCache( const std::string &code, std::vector<operation::CoordinateOperationNNPtr> &list) { return cacheCRSToCrsCoordOp_.tryGet(code, list); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache( const std::string &code, const std::vector<operation::CoordinateOperationNNPtr> &list) { cacheCRSToCrsCoordOp_.insert(code, list); } // --------------------------------------------------------------------------- crs::CRSPtr DatabaseContext::Private::getCRSFromCache(const std::string &code) { util::BaseObjectPtr obj; getFromCache(cacheCRS_, code, obj); return std::static_pointer_cast<crs::CRS>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache(const std::string &code, const crs::CRSNNPtr &crs) { insertIntoCache(cacheCRS_, code, crs.as_nullable()); } // --------------------------------------------------------------------------- common::UnitOfMeasurePtr DatabaseContext::Private::getUOMFromCache(const std::string &code) { util::BaseObjectPtr obj; getFromCache(cacheUOM_, code, obj); return std::static_pointer_cast<common::UnitOfMeasure>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache(const std::string &code, const common::UnitOfMeasureNNPtr &uom) { insertIntoCache(cacheUOM_, code, uom.as_nullable()); } // --------------------------------------------------------------------------- datum::GeodeticReferenceFramePtr DatabaseContext::Private::getGeodeticDatumFromCache(const std::string &code) { util::BaseObjectPtr obj; getFromCache(cacheGeodeticDatum_, code, obj); return std::static_pointer_cast<datum::GeodeticReferenceFrame>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache( const std::string &code, const datum::GeodeticReferenceFrameNNPtr &datum) { insertIntoCache(cacheGeodeticDatum_, code, datum.as_nullable()); } // --------------------------------------------------------------------------- datum::DatumEnsemblePtr DatabaseContext::Private::getDatumEnsembleFromCache(const std::string &code) { util::BaseObjectPtr obj; getFromCache(cacheDatumEnsemble_, code, obj); return std::static_pointer_cast<datum::DatumEnsemble>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache( const std::string &code, const datum::DatumEnsembleNNPtr &datumEnsemble) { insertIntoCache(cacheDatumEnsemble_, code, datumEnsemble.as_nullable()); } // --------------------------------------------------------------------------- datum::EllipsoidPtr DatabaseContext::Private::getEllipsoidFromCache(const std::string &code) { util::BaseObjectPtr obj; getFromCache(cacheEllipsoid_, code, obj); return std::static_pointer_cast<datum::Ellipsoid>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache(const std::string &code, const datum::EllipsoidNNPtr &ellps) { insertIntoCache(cacheEllipsoid_, code, ellps.as_nullable()); } // --------------------------------------------------------------------------- datum::PrimeMeridianPtr DatabaseContext::Private::getPrimeMeridianFromCache(const std::string &code) { util::BaseObjectPtr obj; getFromCache(cachePrimeMeridian_, code, obj); return std::static_pointer_cast<datum::PrimeMeridian>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache(const std::string &code, const datum::PrimeMeridianNNPtr &pm) { insertIntoCache(cachePrimeMeridian_, code, pm.as_nullable()); } // --------------------------------------------------------------------------- cs::CoordinateSystemPtr DatabaseContext::Private::getCoordinateSystemFromCache( const std::string &code) { util::BaseObjectPtr obj; getFromCache(cacheCS_, code, obj); return std::static_pointer_cast<cs::CoordinateSystem>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache(const std::string &code, const cs::CoordinateSystemNNPtr &cs) { insertIntoCache(cacheCS_, code, cs.as_nullable()); } // --------------------------------------------------------------------------- metadata::ExtentPtr DatabaseContext::Private::getExtentFromCache(const std::string &code) { util::BaseObjectPtr obj; getFromCache(cacheExtent_, code, obj); return std::static_pointer_cast<metadata::Extent>(obj); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache(const std::string &code, const metadata::ExtentNNPtr &extent) { insertIntoCache(cacheExtent_, code, extent.as_nullable()); } // --------------------------------------------------------------------------- bool DatabaseContext::Private::getGridInfoFromCache(const std::string &code, GridInfoCache &info) { return cacheGridInfo_.tryGet(code, info); } // --------------------------------------------------------------------------- void DatabaseContext::Private::cache(const std::string &code, const GridInfoCache &info) { cacheGridInfo_.insert(code, info); } // --------------------------------------------------------------------------- void DatabaseContext::Private::open(const std::string &databasePath, PJ_CONTEXT *ctx) { if (!ctx) { ctx = pj_get_default_ctx(); } setPjCtxt(ctx); std::string path(databasePath); if (path.empty()) { path.resize(2048); const bool found = pj_find_file(pjCtxt(), "proj.db", &path[0], path.size() - 1) != 0; path.resize(strlen(path.c_str())); if (!found) { throw FactoryException("Cannot find proj.db"); } } sqlite_handle_ = SQLiteHandleCache::get().getHandle(path, ctx); databasePath_ = std::move(path); } // --------------------------------------------------------------------------- void DatabaseContext::Private::setHandle(sqlite3 *sqlite_handle) { assert(sqlite_handle); assert(!sqlite_handle_); sqlite_handle_ = SQLiteHandle::initFromExisting(sqlite_handle, false, 0, 0); } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getDatabaseStructure() { const std::string dbNamePrefix(auxiliaryDatabasePaths_.empty() && memoryDbForInsertPath_.empty() ? "" : "db_0."); const auto sqlBegin("SELECT sql||';' FROM " + dbNamePrefix + "sqlite_master WHERE type = "); const char *tableType = "'table' AND name NOT LIKE 'sqlite_stat%'"; const char *const objectTypes[] = {tableType, "'view'", "'trigger'"}; std::vector<std::string> res; for (const auto &objectType : objectTypes) { const auto sqlRes = run(sqlBegin + objectType); for (const auto &row : sqlRes) { res.emplace_back(row[0]); } } if (sqlite_handle_->getLayoutVersionMajor() > 0) { res.emplace_back( "INSERT INTO metadata VALUES('DATABASE.LAYOUT.VERSION.MAJOR'," + toString(sqlite_handle_->getLayoutVersionMajor()) + ");"); res.emplace_back( "INSERT INTO metadata VALUES('DATABASE.LAYOUT.VERSION.MINOR'," + toString(sqlite_handle_->getLayoutVersionMinor()) + ");"); } return res; } // --------------------------------------------------------------------------- void DatabaseContext::Private::attachExtraDatabases( const std::vector<std::string> &auxiliaryDatabasePaths) { auto l_handle = handle(); assert(l_handle); auto tables = run("SELECT name FROM sqlite_master WHERE type IN ('table', 'view') " "AND name NOT LIKE 'sqlite_stat%'"); std::map<std::string, std::vector<std::string>> tableStructure; for (const auto &rowTable : tables) { const auto &tableName = rowTable[0]; auto tableInfo = run("PRAGMA table_info(\"" + replaceAll(tableName, "\"", "\"\"") + "\")"); for (const auto &rowCol : tableInfo) { const auto &colName = rowCol[1]; tableStructure[tableName].push_back(colName); } } const int nLayoutVersionMajor = l_handle->getLayoutVersionMajor(); const int nLayoutVersionMinor = l_handle->getLayoutVersionMinor(); closeDB(); if (auxiliaryDatabasePaths.empty()) { open(databasePath_, pjCtxt()); return; } sqlite3 *sqlite_handle = nullptr; sqlite3_open_v2( ":memory:", &sqlite_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_URI, nullptr); if (!sqlite_handle) { throw FactoryException("cannot create in memory database"); } sqlite_handle_ = SQLiteHandle::initFromExisting( sqlite_handle, true, nLayoutVersionMajor, nLayoutVersionMinor); l_handle = sqlite_handle_; run("ATTACH DATABASE ? AS db_0", {databasePath_}); detach_ = true; int count = 1; for (const auto &otherDbPath : auxiliaryDatabasePaths) { const auto attachedDbName("db_" + toString(static_cast<int>(count))); std::string sql = "ATTACH DATABASE ? AS "; sql += attachedDbName; count++; run(sql, {otherDbPath}); l_handle->checkDatabaseLayout(databasePath_, otherDbPath, attachedDbName + '.'); } for (const auto &pair : tableStructure) { std::string sql("CREATE TEMP VIEW "); sql += pair.first; sql += " AS "; for (size_t i = 0; i <= auxiliaryDatabasePaths.size(); ++i) { std::string selectFromAux("SELECT "); bool firstCol = true; for (const auto &colName : pair.second) { if (!firstCol) { selectFromAux += ", "; } firstCol = false; selectFromAux += colName; } selectFromAux += " FROM db_"; selectFromAux += toString(static_cast<int>(i)); selectFromAux += "."; selectFromAux += pair.first; try { // Check that the request will succeed. In case of 'sparse' // databases... run(selectFromAux + " LIMIT 0"); if (i > 0) { sql += " UNION ALL "; } sql += selectFromAux; } catch (const std::exception &) { } } run(sql); } } // --------------------------------------------------------------------------- SQLResultSet DatabaseContext::Private::run(const std::string &sql, const ListOfParams &parameters, bool useMaxFloatPrecision) { auto l_handle = handle(); assert(l_handle); sqlite3_stmt *stmt = nullptr; auto iter = mapSqlToStatement_.find(sql); if (iter != mapSqlToStatement_.end()) { stmt = iter->second; sqlite3_reset(stmt); } else { if (sqlite3_prepare_v2(l_handle->handle(), sql.c_str(), static_cast<int>(sql.size()), &stmt, nullptr) != SQLITE_OK) { throw FactoryException("SQLite error on " + sql + ": " + sqlite3_errmsg(l_handle->handle())); } mapSqlToStatement_.insert( std::pair<std::string, sqlite3_stmt *>(sql, stmt)); } return l_handle->run(stmt, sql, parameters, useMaxFloatPrecision); } // --------------------------------------------------------------------------- static std::string formatStatement(const char *fmt, ...) { std::string res; va_list args; va_start(args, fmt); for (int i = 0; fmt[i] != '\0'; ++i) { if (fmt[i] == '%') { if (fmt[i + 1] == '%') { res += '%'; } else if (fmt[i + 1] == 'q') { const char *arg = va_arg(args, const char *); for (int j = 0; arg[j] != '\0'; ++j) { if (arg[j] == '\'') res += arg[j]; res += arg[j]; } } else if (fmt[i + 1] == 'Q') { const char *arg = va_arg(args, const char *); if (arg == nullptr) res += "NULL"; else { res += '\''; for (int j = 0; arg[j] != '\0'; ++j) { if (arg[j] == '\'') res += arg[j]; res += arg[j]; } res += '\''; } } else if (fmt[i + 1] == 's') { const char *arg = va_arg(args, const char *); res += arg; } else if (fmt[i + 1] == 'f') { const double arg = va_arg(args, double); res += toString(arg); } else if (fmt[i + 1] == 'd') { const int arg = va_arg(args, int); res += toString(arg); } else { va_end(args); throw FactoryException( "Unsupported formatter in formatStatement()"); } ++i; } else { res += fmt[i]; } } va_end(args); return res; } // --------------------------------------------------------------------------- void DatabaseContext::Private::appendSql( std::vector<std::string> &sqlStatements, const std::string &sql) { sqlStatements.emplace_back(sql); char *errMsg = nullptr; if (sqlite3_exec(memoryDbHandle_->handle(), sql.c_str(), nullptr, nullptr, &errMsg) != SQLITE_OK) { std::string s("Cannot execute " + sql); if (errMsg) { s += " : "; s += errMsg; } sqlite3_free(errMsg); throw FactoryException(s); } sqlite3_free(errMsg); } // --------------------------------------------------------------------------- static void identifyFromNameOrCode( const DatabaseContextNNPtr &dbContext, const std::vector<std::string> &allowedAuthorities, const std::string &authNameParent, const common::IdentifiedObjectNNPtr &obj, std::function<std::shared_ptr<util::IComparable>( const AuthorityFactoryNNPtr &authFactory, const std::string &)> instantiateFunc, AuthorityFactory::ObjectType objType, std::string &authName, std::string &code) { auto allowedAuthoritiesTmp(allowedAuthorities); allowedAuthoritiesTmp.emplace_back(authNameParent); for (const auto &id : obj->identifiers()) { try { const auto &idAuthName = *(id->codeSpace()); if (std::find(allowedAuthoritiesTmp.begin(), allowedAuthoritiesTmp.end(), idAuthName) != allowedAuthoritiesTmp.end()) { const auto factory = AuthorityFactory::create(dbContext, idAuthName); if (instantiateFunc(factory, id->code()) ->isEquivalentTo( obj.get(), util::IComparable::Criterion::EQUIVALENT)) { authName = idAuthName; code = id->code(); return; } } } catch (const std::exception &) { } } for (const auto &allowedAuthority : allowedAuthoritiesTmp) { const auto factory = AuthorityFactory::create(dbContext, allowedAuthority); const auto candidates = factory->createObjectsFromName(obj->nameStr(), {objType}, false, 0); for (const auto &candidate : candidates) { const auto &ids = candidate->identifiers(); if (!ids.empty() && candidate->isEquivalentTo( obj.get(), util::IComparable::Criterion::EQUIVALENT)) { const auto &id = ids.front(); authName = *(id->codeSpace()); code = id->code(); return; } } } } // --------------------------------------------------------------------------- static void identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, const std::vector<std::string> &allowedAuthorities, const std::string &authNameParent, const datum::DatumEnsembleNNPtr &obj, std::string &authName, std::string &code) { const char *type = "geodetic_datum"; if (!obj->datums().empty() && dynamic_cast<const datum::VerticalReferenceFrame *>( obj->datums().front().get())) { type = "vertical_datum"; } const auto instantiateFunc = [&type](const AuthorityFactoryNNPtr &authFactory, const std::string &lCode) { return util::nn_static_pointer_cast<util::IComparable>( authFactory->createDatumEnsemble(lCode, type)); }; identifyFromNameOrCode( dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, AuthorityFactory::ObjectType::DATUM_ENSEMBLE, authName, code); } // --------------------------------------------------------------------------- static void identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, const std::vector<std::string> &allowedAuthorities, const std::string &authNameParent, const datum::GeodeticReferenceFrameNNPtr &obj, std::string &authName, std::string &code) { const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, const std::string &lCode) { return util::nn_static_pointer_cast<util::IComparable>( authFactory->createGeodeticDatum(lCode)); }; identifyFromNameOrCode( dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME, authName, code); } // --------------------------------------------------------------------------- static void identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, const std::vector<std::string> &allowedAuthorities, const std::string &authNameParent, const datum::EllipsoidNNPtr &obj, std::string &authName, std::string &code) { const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, const std::string &lCode) { return util::nn_static_pointer_cast<util::IComparable>( authFactory->createEllipsoid(lCode)); }; identifyFromNameOrCode( dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, AuthorityFactory::ObjectType::ELLIPSOID, authName, code); } // --------------------------------------------------------------------------- static void identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, const std::vector<std::string> &allowedAuthorities, const std::string &authNameParent, const datum::PrimeMeridianNNPtr &obj, std::string &authName, std::string &code) { const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, const std::string &lCode) { return util::nn_static_pointer_cast<util::IComparable>( authFactory->createPrimeMeridian(lCode)); }; identifyFromNameOrCode( dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, AuthorityFactory::ObjectType::PRIME_MERIDIAN, authName, code); } // --------------------------------------------------------------------------- static void identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, const std::vector<std::string> &allowedAuthorities, const std::string &authNameParent, const datum::VerticalReferenceFrameNNPtr &obj, std::string &authName, std::string &code) { const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, const std::string &lCode) { return util::nn_static_pointer_cast<util::IComparable>( authFactory->createVerticalDatum(lCode)); }; identifyFromNameOrCode( dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, AuthorityFactory::ObjectType::VERTICAL_REFERENCE_FRAME, authName, code); } // --------------------------------------------------------------------------- static void identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, const std::vector<std::string> &allowedAuthorities, const std::string &authNameParent, const datum::DatumNNPtr &obj, std::string &authName, std::string &code) { if (const auto geodeticDatum = util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>(obj)) { identifyFromNameOrCode(dbContext, allowedAuthorities, authNameParent, NN_NO_CHECK(geodeticDatum), authName, code); } else if (const auto verticalDatum = util::nn_dynamic_pointer_cast<datum::VerticalReferenceFrame>( obj)) { identifyFromNameOrCode(dbContext, allowedAuthorities, authNameParent, NN_NO_CHECK(verticalDatum), authName, code); } else { throw FactoryException("Unhandled type of datum"); } } // --------------------------------------------------------------------------- static const char *getCSDatabaseType(const cs::CoordinateSystemNNPtr &obj) { if (dynamic_cast<const cs::EllipsoidalCS *>(obj.get())) { return CS_TYPE_ELLIPSOIDAL; } else if (dynamic_cast<const cs::CartesianCS *>(obj.get())) { return CS_TYPE_CARTESIAN; } else if (dynamic_cast<const cs::VerticalCS *>(obj.get())) { return CS_TYPE_VERTICAL; } return nullptr; } // --------------------------------------------------------------------------- std::string DatabaseContext::Private::findFreeCode(const std::string &tableName, const std::string &authName, const std::string &codePrototype) { std::string code(codePrototype); if (run("SELECT 1 FROM " + tableName + " WHERE auth_name = ? AND code = ?", {authName, code}) .empty()) { return code; } for (int counter = 2; counter < 10; counter++) { code = codePrototype + '_' + toString(counter); if (run("SELECT 1 FROM " + tableName + " WHERE auth_name = ? AND code = ?", {authName, code}) .empty()) { return code; } } // shouldn't happen hopefully... throw FactoryException("Cannot insert " + tableName + ": too many similar codes"); } // --------------------------------------------------------------------------- static const char *getUnitDatabaseType(const common::UnitOfMeasure &unit) { switch (unit.type()) { case common::UnitOfMeasure::Type::LINEAR: return "length"; case common::UnitOfMeasure::Type::ANGULAR: return "angle"; case common::UnitOfMeasure::Type::SCALE: return "scale"; case common::UnitOfMeasure::Type::TIME: return "time"; default: break; } return nullptr; } // --------------------------------------------------------------------------- void DatabaseContext::Private::identify(const DatabaseContextNNPtr &dbContext, const common::UnitOfMeasure &obj, std::string &authName, std::string &code) { // Identify quickly a few well-known units const double convFactor = obj.conversionToSI(); switch (obj.type()) { case common::UnitOfMeasure::Type::LINEAR: { if (convFactor == 1.0) { authName = metadata::Identifier::EPSG; code = "9001"; return; } break; } case common::UnitOfMeasure::Type::ANGULAR: { constexpr double CONV_FACTOR_DEGREE = 1.74532925199432781271e-02; if (std::abs(convFactor - CONV_FACTOR_DEGREE) <= 1e-10 * CONV_FACTOR_DEGREE) { authName = metadata::Identifier::EPSG; code = "9102"; return; } break; } case common::UnitOfMeasure::Type::SCALE: { if (convFactor == 1.0) { authName = metadata::Identifier::EPSG; code = "9201"; return; } break; } default: break; } std::string sql("SELECT auth_name, code FROM unit_of_measure " "WHERE abs(conv_factor - ?) <= 1e-10 * conv_factor"); ListOfParams params{convFactor}; const char *type = getUnitDatabaseType(obj); if (type) { sql += " AND type = ?"; params.emplace_back(std::string(type)); } sql += " ORDER BY auth_name, code"; const auto res = run(sql, params); for (const auto &row : res) { const auto &rowAuthName = row[0]; const auto &rowCode = row[1]; const auto tmpAuthFactory = AuthorityFactory::create(dbContext, rowAuthName); try { tmpAuthFactory->createUnitOfMeasure(rowCode); authName = rowAuthName; code = rowCode; return; } catch (const std::exception &) { } } } // --------------------------------------------------------------------------- void DatabaseContext::Private::identifyOrInsert( const DatabaseContextNNPtr &dbContext, const common::UnitOfMeasure &unit, const std::string &ownerAuthName, std::string &authName, std::string &code, std::vector<std::string> &sqlStatements) { authName = unit.codeSpace(); code = unit.code(); if (authName.empty()) { identify(dbContext, unit, authName, code); } if (!authName.empty()) { return; } const char *type = getUnitDatabaseType(unit); if (type == nullptr) { throw FactoryException("Cannot insert this type of UnitOfMeasure"); } // Insert new record authName = ownerAuthName; const std::string codePrototype(replaceAll(toupper(unit.name()), " ", "_")); code = findFreeCode("unit_of_measure", authName, codePrototype); const auto sql = formatStatement( "INSERT INTO unit_of_measure VALUES('%q','%q','%q','%q',%f,NULL,0);", authName.c_str(), code.c_str(), unit.name().c_str(), type, unit.conversionToSI()); appendSql(sqlStatements, sql); } // --------------------------------------------------------------------------- void DatabaseContext::Private::identify(const DatabaseContextNNPtr &dbContext, const cs::CoordinateSystemNNPtr &obj, std::string &authName, std::string &code) { const auto &axisList = obj->axisList(); if (axisList.size() == 1U && axisList[0]->unit()._isEquivalentTo(UnitOfMeasure::METRE) && &(axisList[0]->direction()) == &cs::AxisDirection::UP && (axisList[0]->nameStr() == "Up" || axisList[0]->nameStr() == "Gravity-related height")) { // preferred coordinate system for gravity-related height authName = metadata::Identifier::EPSG; code = "6499"; return; } std::string sql( "SELECT auth_name, code FROM coordinate_system WHERE dimension = ?"); ListOfParams params{static_cast<int>(axisList.size())}; const char *type = getCSDatabaseType(obj); if (type) { sql += " AND type = ?"; params.emplace_back(std::string(type)); } sql += " ORDER BY auth_name, code"; const auto res = run(sql, params); for (const auto &row : res) { const auto &rowAuthName = row[0]; const auto &rowCode = row[1]; const auto tmpAuthFactory = AuthorityFactory::create(dbContext, rowAuthName); try { const auto cs = tmpAuthFactory->createCoordinateSystem(rowCode); if (cs->_isEquivalentTo(obj.get(), util::IComparable::Criterion::EQUIVALENT)) { authName = rowAuthName; code = rowCode; if (authName == metadata::Identifier::EPSG && code == "4400") { // preferred coordinate system for cartesian // Easting, Northing return; } if (authName == metadata::Identifier::EPSG && code == "6422") { // preferred coordinate system for geographic lat, long return; } if (authName == metadata::Identifier::EPSG && code == "6423") { // preferred coordinate system for geographic lat, long, h return; } } } catch (const std::exception &) { } } } // --------------------------------------------------------------------------- void DatabaseContext::Private::identifyOrInsert( const DatabaseContextNNPtr &dbContext, const cs::CoordinateSystemNNPtr &obj, const std::string &ownerType, const std::string &ownerAuthName, const std::string &ownerCode, std::string &authName, std::string &code, std::vector<std::string> &sqlStatements) { identify(dbContext, obj, authName, code); if (!authName.empty()) { return; } const char *type = getCSDatabaseType(obj); if (type == nullptr) { throw FactoryException("Cannot insert this type of CoordinateSystem"); } // Insert new record in coordinate_system authName = ownerAuthName; const std::string codePrototype("CS_" + ownerType + '_' + ownerCode); code = findFreeCode("coordinate_system", authName, codePrototype); const auto &axisList = obj->axisList(); { const auto sql = formatStatement( "INSERT INTO coordinate_system VALUES('%q','%q','%q',%d);", authName.c_str(), code.c_str(), type, static_cast<int>(axisList.size())); appendSql(sqlStatements, sql); } // Insert new records for the axis for (int i = 0; i < static_cast<int>(axisList.size()); ++i) { const auto &axis = axisList[i]; std::string uomAuthName; std::string uomCode; identifyOrInsert(dbContext, axis->unit(), ownerAuthName, uomAuthName, uomCode, sqlStatements); const auto sql = formatStatement( "INSERT INTO axis VALUES(" "'%q','%q','%q','%q','%q','%q','%q',%d,'%q','%q');", authName.c_str(), (code + "_AXIS_" + toString(i + 1)).c_str(), axis->nameStr().c_str(), axis->abbreviation().c_str(), axis->direction().toString().c_str(), authName.c_str(), code.c_str(), i + 1, uomAuthName.c_str(), uomCode.c_str()); appendSql(sqlStatements, sql); } } // --------------------------------------------------------------------------- static void addAllowedAuthoritiesCond(const std::vector<std::string> &allowedAuthorities, const std::string &authName, std::string &sql, ListOfParams &params) { sql += "auth_name IN (?"; params.emplace_back(authName); for (const auto &allowedAuthority : allowedAuthorities) { sql += ",?"; params.emplace_back(allowedAuthority); } sql += ')'; } // --------------------------------------------------------------------------- void DatabaseContext::Private::identifyOrInsertUsages( const common::ObjectUsageNNPtr &obj, const std::string &tableName, const std::string &authName, const std::string &code, const std::vector<std::string> &allowedAuthorities, std::vector<std::string> &sqlStatements) { std::string usageCode("USAGE_"); const std::string upperTableName(toupper(tableName)); if (!starts_with(code, upperTableName)) { usageCode += upperTableName; usageCode += '_'; } usageCode += code; const auto &domains = obj->domains(); if (domains.empty()) { const auto sql = formatStatement("INSERT INTO usage VALUES('%q','%q','%q','%q','%q'," "'PROJ','EXTENT_UNKNOWN','PROJ','SCOPE_UNKNOWN');", authName.c_str(), usageCode.c_str(), tableName.c_str(), authName.c_str(), code.c_str()); appendSql(sqlStatements, sql); return; } int usageCounter = 1; for (const auto &domain : domains) { std::string scopeAuthName; std::string scopeCode; const auto &scope = domain->scope(); if (scope.has_value()) { std::string sql = "SELECT auth_name, code, " "(CASE WHEN auth_name = 'EPSG' THEN 0 ELSE 1 END) " "AS order_idx " "FROM scope WHERE scope = ? AND deprecated = 0 AND "; ListOfParams params{*scope}; addAllowedAuthoritiesCond(allowedAuthorities, authName, sql, params); sql += " ORDER BY order_idx, auth_name, code"; const auto rows = run(sql, params); if (!rows.empty()) { const auto &row = rows.front(); scopeAuthName = row[0]; scopeCode = row[1]; } else { scopeAuthName = authName; scopeCode = "SCOPE_"; scopeCode += tableName; scopeCode += '_'; scopeCode += code; const auto sqlToInsert = formatStatement( "INSERT INTO scope VALUES('%q','%q','%q',0);", scopeAuthName.c_str(), scopeCode.c_str(), scope->c_str()); appendSql(sqlStatements, sqlToInsert); } } else { scopeAuthName = "PROJ"; scopeCode = "SCOPE_UNKNOWN"; } std::string extentAuthName("PROJ"); std::string extentCode("EXTENT_UNKNOWN"); const auto &extent = domain->domainOfValidity(); if (extent) { const auto &geogElts = extent->geographicElements(); if (!geogElts.empty()) { const auto bbox = dynamic_cast<const metadata::GeographicBoundingBox *>( geogElts.front().get()); if (bbox) { std::string sql = "SELECT auth_name, code, " "(CASE WHEN auth_name = 'EPSG' THEN 0 ELSE 1 END) " "AS order_idx " "FROM extent WHERE south_lat = ? AND north_lat = ? " "AND west_lon = ? AND east_lon = ? AND deprecated = 0 " "AND "; ListOfParams params{ bbox->southBoundLatitude(), bbox->northBoundLatitude(), bbox->westBoundLongitude(), bbox->eastBoundLongitude()}; addAllowedAuthoritiesCond(allowedAuthorities, authName, sql, params); sql += " ORDER BY order_idx, auth_name, code"; const auto rows = run(sql, params); if (!rows.empty()) { const auto &row = rows.front(); extentAuthName = row[0]; extentCode = row[1]; } else { extentAuthName = authName; extentCode = "EXTENT_"; extentCode += tableName; extentCode += '_'; extentCode += code; std::string description(*(extent->description())); if (description.empty()) { description = "unknown"; } const auto sqlToInsert = formatStatement( "INSERT INTO extent " "VALUES('%q','%q','%q','%q',%f,%f,%f,%f,0);", extentAuthName.c_str(), extentCode.c_str(), description.c_str(), description.c_str(), bbox->southBoundLatitude(), bbox->northBoundLatitude(), bbox->westBoundLongitude(), bbox->eastBoundLongitude()); appendSql(sqlStatements, sqlToInsert); } } } } if (domains.size() > 1) { usageCode += '_'; usageCode += toString(usageCounter); } const auto sql = formatStatement( "INSERT INTO usage VALUES('%q','%q','%q','%q','%q'," "'%q','%q','%q','%q');", authName.c_str(), usageCode.c_str(), tableName.c_str(), authName.c_str(), code.c_str(), extentAuthName.c_str(), extentCode.c_str(), scopeAuthName.c_str(), scopeCode.c_str()); appendSql(sqlStatements, sql); usageCounter++; } } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const datum::PrimeMeridianNNPtr &pm, const std::string &authName, const std::string &code, bool /*numericCode*/, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); // Check if the object is already known under that code std::string pmAuthName; std::string pmCode; identifyFromNameOrCode(self, allowedAuthorities, authName, pm, pmAuthName, pmCode); if (pmAuthName == authName && pmCode == code) { return {}; } std::vector<std::string> sqlStatements; // Insert new record in prime_meridian table std::string uomAuthName; std::string uomCode; identifyOrInsert(self, pm->longitude().unit(), authName, uomAuthName, uomCode, sqlStatements); const auto sql = formatStatement( "INSERT INTO prime_meridian VALUES(" "'%q','%q','%q',%f,'%q','%q',0);", authName.c_str(), code.c_str(), pm->nameStr().c_str(), pm->longitude().value(), uomAuthName.c_str(), uomCode.c_str()); appendSql(sqlStatements, sql); return sqlStatements; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const datum::EllipsoidNNPtr &ellipsoid, const std::string &authName, const std::string &code, bool /*numericCode*/, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); // Check if the object is already known under that code std::string ellipsoidAuthName; std::string ellipsoidCode; identifyFromNameOrCode(self, allowedAuthorities, authName, ellipsoid, ellipsoidAuthName, ellipsoidCode); if (ellipsoidAuthName == authName && ellipsoidCode == code) { return {}; } std::vector<std::string> sqlStatements; // Find or insert celestial body const auto &semiMajorAxis = ellipsoid->semiMajorAxis(); const double semiMajorAxisMetre = semiMajorAxis.getSIValue(); constexpr double tolerance = 0.005; std::string bodyAuthName; std::string bodyCode; auto res = run("SELECT auth_name, code, " "(ABS(semi_major_axis - ?) / semi_major_axis ) " "AS rel_error FROM celestial_body WHERE rel_error <= ?", {semiMajorAxisMetre, tolerance}); if (!res.empty()) { const auto &row = res.front(); bodyAuthName = row[0]; bodyCode = row[1]; } else { bodyAuthName = authName; bodyCode = "BODY_" + code; const auto bodyName = "Body of " + ellipsoid->nameStr(); const auto sql = formatStatement( "INSERT INTO celestial_body VALUES('%q','%q','%q',%f);", bodyAuthName.c_str(), bodyCode.c_str(), bodyName.c_str(), semiMajorAxisMetre); appendSql(sqlStatements, sql); } // Insert new record in ellipsoid table std::string uomAuthName; std::string uomCode; identifyOrInsert(self, semiMajorAxis.unit(), authName, uomAuthName, uomCode, sqlStatements); std::string invFlattening("NULL"); std::string semiMinorAxis("NULL"); if (ellipsoid->isSphere() || ellipsoid->semiMinorAxis().has_value()) { semiMinorAxis = toString(ellipsoid->computeSemiMinorAxis().value()); } else { invFlattening = toString(ellipsoid->computedInverseFlattening()); } const auto sql = formatStatement( "INSERT INTO ellipsoid VALUES(" "'%q','%q','%q','%q','%q','%q',%f,'%q','%q',%s,%s,0);", authName.c_str(), code.c_str(), ellipsoid->nameStr().c_str(), "", // description bodyAuthName.c_str(), bodyCode.c_str(), semiMajorAxis.value(), uomAuthName.c_str(), uomCode.c_str(), invFlattening.c_str(), semiMinorAxis.c_str()); appendSql(sqlStatements, sql); return sqlStatements; } // --------------------------------------------------------------------------- static std::string anchorEpochToStr(double val) { constexpr int BUF_SIZE = 16; char szBuffer[BUF_SIZE]; sqlite3_snprintf(BUF_SIZE, szBuffer, "%.3f", val); return szBuffer; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const datum::GeodeticReferenceFrameNNPtr &datum, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); // Check if the object is already known under that code std::string datumAuthName; std::string datumCode; identifyFromNameOrCode(self, allowedAuthorities, authName, datum, datumAuthName, datumCode); if (datumAuthName == authName && datumCode == code) { return {}; } std::vector<std::string> sqlStatements; // Find or insert ellipsoid std::string ellipsoidAuthName; std::string ellipsoidCode; const auto &ellipsoidOfDatum = datum->ellipsoid(); identifyFromNameOrCode(self, allowedAuthorities, authName, ellipsoidOfDatum, ellipsoidAuthName, ellipsoidCode); if (ellipsoidAuthName.empty()) { ellipsoidAuthName = authName; if (numericCode) { ellipsoidCode = self->suggestsCodeFor(ellipsoidOfDatum, ellipsoidAuthName, true); } else { ellipsoidCode = "ELLPS_" + code; } sqlStatements = self->getInsertStatementsFor( ellipsoidOfDatum, ellipsoidAuthName, ellipsoidCode, numericCode, allowedAuthorities); } // Find or insert prime meridian std::string pmAuthName; std::string pmCode; const auto &pmOfDatum = datum->primeMeridian(); identifyFromNameOrCode(self, allowedAuthorities, authName, pmOfDatum, pmAuthName, pmCode); if (pmAuthName.empty()) { pmAuthName = authName; if (numericCode) { pmCode = self->suggestsCodeFor(pmOfDatum, pmAuthName, true); } else { pmCode = "PM_" + code; } const auto sqlStatementsTmp = self->getInsertStatementsFor( pmOfDatum, pmAuthName, pmCode, numericCode, allowedAuthorities); sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(), sqlStatementsTmp.end()); } // Insert new record in geodetic_datum table std::string publicationDate("NULL"); if (datum->publicationDate().has_value()) { publicationDate = '\''; publicationDate += replaceAll(datum->publicationDate()->toString(), "'", "''"); publicationDate += '\''; } std::string frameReferenceEpoch("NULL"); const auto dynamicDatum = dynamic_cast<const datum::DynamicGeodeticReferenceFrame *>(datum.get()); if (dynamicDatum) { frameReferenceEpoch = toString(dynamicDatum->frameReferenceEpoch().value()); } const std::string anchor(*(datum->anchorDefinition())); const util::optional<common::Measure> &anchorEpoch = datum->anchorEpoch(); const auto sql = formatStatement( "INSERT INTO geodetic_datum VALUES(" "'%q','%q','%q','%q','%q','%q','%q','%q',%s,%s,NULL,%Q,%s,0);", authName.c_str(), code.c_str(), datum->nameStr().c_str(), "", // description ellipsoidAuthName.c_str(), ellipsoidCode.c_str(), pmAuthName.c_str(), pmCode.c_str(), publicationDate.c_str(), frameReferenceEpoch.c_str(), anchor.empty() ? nullptr : anchor.c_str(), anchorEpoch.has_value() ? anchorEpochToStr( anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) .c_str() : "NULL"); appendSql(sqlStatements, sql); identifyOrInsertUsages(datum, "geodetic_datum", authName, code, allowedAuthorities, sqlStatements); return sqlStatements; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const datum::DatumEnsembleNNPtr &ensemble, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); // Check if the object is already known under that code std::string datumAuthName; std::string datumCode; identifyFromNameOrCode(self, allowedAuthorities, authName, ensemble, datumAuthName, datumCode); if (datumAuthName == authName && datumCode == code) { return {}; } std::vector<std::string> sqlStatements; const auto &members = ensemble->datums(); assert(!members.empty()); int counter = 1; std::vector<std::pair<std::string, std::string>> membersId; for (const auto &member : members) { std::string memberAuthName; std::string memberCode; identifyFromNameOrCode(self, allowedAuthorities, authName, member, memberAuthName, memberCode); if (memberAuthName.empty()) { memberAuthName = authName; if (numericCode) { memberCode = self->suggestsCodeFor(member, memberAuthName, true); } else { memberCode = "MEMBER_" + toString(counter) + "_OF_" + code; } const auto sqlStatementsTmp = self->getInsertStatementsFor(member, memberAuthName, memberCode, numericCode, allowedAuthorities); sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(), sqlStatementsTmp.end()); } membersId.emplace_back( std::pair<std::string, std::string>(memberAuthName, memberCode)); ++counter; } const bool isGeodetic = util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>( members.front()) != nullptr; // Insert new record in geodetic_datum/vertical_datum table const double accuracy = c_locale_stod(ensemble->positionalAccuracy()->value()); if (isGeodetic) { const auto firstDatum = AuthorityFactory::create(self, membersId.front().first) ->createGeodeticDatum(membersId.front().second); const auto &ellipsoid = firstDatum->ellipsoid(); const auto &ellipsoidIds = ellipsoid->identifiers(); assert(!ellipsoidIds.empty()); const std::string &ellipsoidAuthName = *(ellipsoidIds.front()->codeSpace()); const std::string &ellipsoidCode = ellipsoidIds.front()->code(); const auto &pm = firstDatum->primeMeridian(); const auto &pmIds = pm->identifiers(); assert(!pmIds.empty()); const std::string &pmAuthName = *(pmIds.front()->codeSpace()); const std::string &pmCode = pmIds.front()->code(); const std::string anchor(*(firstDatum->anchorDefinition())); const util::optional<common::Measure> &anchorEpoch = firstDatum->anchorEpoch(); const auto sql = formatStatement( "INSERT INTO geodetic_datum VALUES(" "'%q','%q','%q','%q','%q','%q','%q','%q',NULL,NULL,%f,%Q,%s,0);", authName.c_str(), code.c_str(), ensemble->nameStr().c_str(), "", // description ellipsoidAuthName.c_str(), ellipsoidCode.c_str(), pmAuthName.c_str(), pmCode.c_str(), accuracy, anchor.empty() ? nullptr : anchor.c_str(), anchorEpoch.has_value() ? anchorEpochToStr( anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) .c_str() : "NULL"); appendSql(sqlStatements, sql); } else { const auto firstDatum = AuthorityFactory::create(self, membersId.front().first) ->createVerticalDatum(membersId.front().second); const std::string anchor(*(firstDatum->anchorDefinition())); const util::optional<common::Measure> &anchorEpoch = firstDatum->anchorEpoch(); const auto sql = formatStatement( "INSERT INTO vertical_datum VALUES(" "'%q','%q','%q','%q',NULL,NULL,%f,%Q,%s,0);", authName.c_str(), code.c_str(), ensemble->nameStr().c_str(), "", // description accuracy, anchor.empty() ? nullptr : anchor.c_str(), anchorEpoch.has_value() ? anchorEpochToStr( anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) .c_str() : "NULL"); appendSql(sqlStatements, sql); } identifyOrInsertUsages(ensemble, isGeodetic ? "geodetic_datum" : "vertical_datum", authName, code, allowedAuthorities, sqlStatements); const char *tableName = isGeodetic ? "geodetic_datum_ensemble_member" : "vertical_datum_ensemble_member"; counter = 1; for (const auto &authCodePair : membersId) { const auto sql = formatStatement( "INSERT INTO %s VALUES(" "'%q','%q','%q','%q',%d);", tableName, authName.c_str(), code.c_str(), authCodePair.first.c_str(), authCodePair.second.c_str(), counter); appendSql(sqlStatements, sql); ++counter; } return sqlStatements; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const crs::GeodeticCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); std::vector<std::string> sqlStatements; // Find or insert datum/datum ensemble std::string datumAuthName; std::string datumCode; const auto &ensemble = crs->datumEnsemble(); if (ensemble) { const auto ensembleNN = NN_NO_CHECK(ensemble); identifyFromNameOrCode(self, allowedAuthorities, authName, ensembleNN, datumAuthName, datumCode); if (datumAuthName.empty()) { datumAuthName = authName; if (numericCode) { datumCode = self->suggestsCodeFor(ensembleNN, datumAuthName, true); } else { datumCode = "GEODETIC_DATUM_" + code; } sqlStatements = self->getInsertStatementsFor( ensembleNN, datumAuthName, datumCode, numericCode, allowedAuthorities); } } else { const auto &datum = crs->datum(); assert(datum); const auto datumNN = NN_NO_CHECK(datum); identifyFromNameOrCode(self, allowedAuthorities, authName, datumNN, datumAuthName, datumCode); if (datumAuthName.empty()) { datumAuthName = authName; if (numericCode) { datumCode = self->suggestsCodeFor(datumNN, datumAuthName, true); } else { datumCode = "GEODETIC_DATUM_" + code; } sqlStatements = self->getInsertStatementsFor(datumNN, datumAuthName, datumCode, numericCode, allowedAuthorities); } } // Find or insert coordinate system const auto &coordinateSystem = crs->coordinateSystem(); std::string csAuthName; std::string csCode; identifyOrInsert(self, coordinateSystem, "GEODETIC_CRS", authName, code, csAuthName, csCode, sqlStatements); const char *type = GEOG_2D; if (coordinateSystem->axisList().size() == 3) { if (dynamic_cast<const crs::GeographicCRS *>(crs.get())) { type = GEOG_3D; } else { type = GEOCENTRIC; } } // Insert new record in geodetic_crs table const auto sql = formatStatement("INSERT INTO geodetic_crs VALUES(" "'%q','%q','%q','%q','%q','%q','%q','%q','%q',NULL,0);", authName.c_str(), code.c_str(), crs->nameStr().c_str(), "", // description type, csAuthName.c_str(), csCode.c_str(), datumAuthName.c_str(), datumCode.c_str()); appendSql(sqlStatements, sql); identifyOrInsertUsages(crs, "geodetic_crs", authName, code, allowedAuthorities, sqlStatements); return sqlStatements; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const crs::ProjectedCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); std::vector<std::string> sqlStatements; // Find or insert base geodetic CRS const auto &baseCRS = crs->baseCRS(); std::string geodAuthName; std::string geodCode; auto allowedAuthoritiesTmp(allowedAuthorities); allowedAuthoritiesTmp.emplace_back(authName); for (const auto &allowedAuthority : allowedAuthoritiesTmp) { const auto factory = AuthorityFactory::create(self, allowedAuthority); const auto candidates = baseCRS->identify(factory); for (const auto &candidate : candidates) { if (candidate.second == 100) { const auto &ids = candidate.first->identifiers(); if (!ids.empty()) { const auto &id = ids.front(); geodAuthName = *(id->codeSpace()); geodCode = id->code(); break; } } if (!geodAuthName.empty()) { break; } } } if (geodAuthName.empty()) { geodAuthName = authName; geodCode = "GEODETIC_CRS_" + code; sqlStatements = self->getInsertStatementsFor( baseCRS, geodAuthName, geodCode, numericCode, allowedAuthorities); } // Insert new record in conversion table const auto &conversion = crs->derivingConversionRef(); std::string convAuthName(authName); std::string convCode("CONVERSION_" + code); if (numericCode) { convCode = self->suggestsCodeFor(conversion, convAuthName, true); } { const auto &method = conversion->method(); const auto &methodIds = method->identifiers(); std::string methodAuthName; std::string methodCode; const operation::MethodMapping *methodMapping = nullptr; if (methodIds.empty()) { const int epsgCode = method->getEPSGCode(); if (epsgCode > 0) { methodAuthName = metadata::Identifier::EPSG; methodCode = toString(epsgCode); } else { const auto &methodName = method->nameStr(); size_t nProjectionMethodMappings = 0; const auto projectionMethodMappings = operation::getProjectionMethodMappings( nProjectionMethodMappings); for (size_t i = 0; i < nProjectionMethodMappings; ++i) { const auto &mapping = projectionMethodMappings[i]; if (metadata::Identifier::isEquivalentName( mapping.wkt2_name, methodName.c_str())) { methodMapping = &mapping; } } if (methodMapping == nullptr || methodMapping->proj_name_main == nullptr) { throw FactoryException("Cannot insert projection with " "method without identifier"); } methodAuthName = "PROJ"; methodCode = methodMapping->proj_name_main; if (methodMapping->proj_name_aux) { methodCode += ' '; methodCode += methodMapping->proj_name_aux; } } } else { const auto &methodId = methodIds.front(); methodAuthName = *(methodId->codeSpace()); methodCode = methodId->code(); } auto sql = formatStatement("INSERT INTO conversion VALUES(" "'%q','%q','%q','','%q','%q','%q'", convAuthName.c_str(), convCode.c_str(), conversion->nameStr().c_str(), methodAuthName.c_str(), methodCode.c_str(), method->nameStr().c_str()); const auto &srcValues = conversion->parameterValues(); if (srcValues.size() > N_MAX_PARAMS) { throw FactoryException("Cannot insert projection with more than " + toString(static_cast<int>(N_MAX_PARAMS)) + " parameters"); } std::vector<operation::GeneralParameterValueNNPtr> values; if (methodMapping == nullptr) { if (methodAuthName == metadata::Identifier::EPSG) { methodMapping = operation::getMapping(atoi(methodCode.c_str())); } else { methodMapping = operation::getMapping(method->nameStr().c_str()); } } if (methodMapping != nullptr) { // Re-order projection parameters in their reference order for (size_t j = 0; methodMapping->params[j] != nullptr; ++j) { for (size_t i = 0; i < srcValues.size(); ++i) { auto opParamValue = dynamic_cast< const operation::OperationParameterValue *>( srcValues[i].get()); if (!opParamValue) { throw FactoryException("Cannot insert projection with " "non-OperationParameterValue"); } if (methodMapping->params[j]->wkt2_name && opParamValue->parameter()->nameStr() == methodMapping->params[j]->wkt2_name) { values.emplace_back(srcValues[i]); } } } } if (values.size() != srcValues.size()) { values = srcValues; } for (const auto &genOpParamvalue : values) { auto opParamValue = dynamic_cast<const operation::OperationParameterValue *>( genOpParamvalue.get()); if (!opParamValue) { throw FactoryException("Cannot insert projection with " "non-OperationParameterValue"); } const auto &param = opParamValue->parameter(); const auto &paramIds = param->identifiers(); std::string paramAuthName; std::string paramCode; if (paramIds.empty()) { const int paramEPSGCode = param->getEPSGCode(); if (paramEPSGCode == 0) { throw FactoryException( "Cannot insert projection with method parameter " "without identifier"); } paramAuthName = metadata::Identifier::EPSG; paramCode = toString(paramEPSGCode); } else { const auto &paramId = paramIds.front(); paramAuthName = *(paramId->codeSpace()); paramCode = paramId->code(); } const auto &value = opParamValue->parameterValue()->value(); const auto &unit = value.unit(); std::string uomAuthName; std::string uomCode; identifyOrInsert(self, unit, authName, uomAuthName, uomCode, sqlStatements); sql += formatStatement(",'%q','%q','%q',%f,'%q','%q'", paramAuthName.c_str(), paramCode.c_str(), param->nameStr().c_str(), value.value(), uomAuthName.c_str(), uomCode.c_str()); } for (size_t i = values.size(); i < N_MAX_PARAMS; ++i) { sql += ",NULL,NULL,NULL,NULL,NULL,NULL"; } sql += ",0);"; appendSql(sqlStatements, sql); identifyOrInsertUsages(crs, "conversion", convAuthName, convCode, allowedAuthorities, sqlStatements); } // Find or insert coordinate system const auto &coordinateSystem = crs->coordinateSystem(); std::string csAuthName; std::string csCode; identifyOrInsert(self, coordinateSystem, "PROJECTED_CRS", authName, code, csAuthName, csCode, sqlStatements); // Insert new record in projected_crs table const auto sql = formatStatement( "INSERT INTO projected_crs VALUES(" "'%q','%q','%q','%q','%q','%q','%q','%q','%q','%q',NULL,0);", authName.c_str(), code.c_str(), crs->nameStr().c_str(), "", // description csAuthName.c_str(), csCode.c_str(), geodAuthName.c_str(), geodCode.c_str(), convAuthName.c_str(), convCode.c_str()); appendSql(sqlStatements, sql); identifyOrInsertUsages(crs, "projected_crs", authName, code, allowedAuthorities, sqlStatements); return sqlStatements; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const datum::VerticalReferenceFrameNNPtr &datum, const std::string &authName, const std::string &code, bool /* numericCode */, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); std::vector<std::string> sqlStatements; // Check if the object is already known under that code std::string datumAuthName; std::string datumCode; identifyFromNameOrCode(self, allowedAuthorities, authName, datum, datumAuthName, datumCode); if (datumAuthName == authName && datumCode == code) { return {}; } // Insert new record in vertical_datum table std::string publicationDate("NULL"); if (datum->publicationDate().has_value()) { publicationDate = '\''; publicationDate += replaceAll(datum->publicationDate()->toString(), "'", "''"); publicationDate += '\''; } std::string frameReferenceEpoch("NULL"); const auto dynamicDatum = dynamic_cast<const datum::DynamicVerticalReferenceFrame *>(datum.get()); if (dynamicDatum) { frameReferenceEpoch = toString(dynamicDatum->frameReferenceEpoch().value()); } const std::string anchor(*(datum->anchorDefinition())); const util::optional<common::Measure> &anchorEpoch = datum->anchorEpoch(); const auto sql = formatStatement( "INSERT INTO vertical_datum VALUES(" "'%q','%q','%q','%q',%s,%s,NULL,%Q,%s,0);", authName.c_str(), code.c_str(), datum->nameStr().c_str(), "", // description publicationDate.c_str(), frameReferenceEpoch.c_str(), anchor.empty() ? nullptr : anchor.c_str(), anchorEpoch.has_value() ? anchorEpochToStr( anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) .c_str() : "NULL"); appendSql(sqlStatements, sql); identifyOrInsertUsages(datum, "vertical_datum", authName, code, allowedAuthorities, sqlStatements); return sqlStatements; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const crs::VerticalCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); std::vector<std::string> sqlStatements; // Find or insert datum/datum ensemble std::string datumAuthName; std::string datumCode; const auto &ensemble = crs->datumEnsemble(); if (ensemble) { const auto ensembleNN = NN_NO_CHECK(ensemble); identifyFromNameOrCode(self, allowedAuthorities, authName, ensembleNN, datumAuthName, datumCode); if (datumAuthName.empty()) { datumAuthName = authName; if (numericCode) { datumCode = self->suggestsCodeFor(ensembleNN, datumAuthName, true); } else { datumCode = "VERTICAL_DATUM_" + code; } sqlStatements = self->getInsertStatementsFor( ensembleNN, datumAuthName, datumCode, numericCode, allowedAuthorities); } } else { const auto &datum = crs->datum(); assert(datum); const auto datumNN = NN_NO_CHECK(datum); identifyFromNameOrCode(self, allowedAuthorities, authName, datumNN, datumAuthName, datumCode); if (datumAuthName.empty()) { datumAuthName = authName; if (numericCode) { datumCode = self->suggestsCodeFor(datumNN, datumAuthName, true); } else { datumCode = "VERTICAL_DATUM_" + code; } sqlStatements = self->getInsertStatementsFor(datumNN, datumAuthName, datumCode, numericCode, allowedAuthorities); } } // Find or insert coordinate system const auto &coordinateSystem = crs->coordinateSystem(); std::string csAuthName; std::string csCode; identifyOrInsert(self, coordinateSystem, "VERTICAL_CRS", authName, code, csAuthName, csCode, sqlStatements); // Insert new record in vertical_crs table const auto sql = formatStatement("INSERT INTO vertical_crs VALUES(" "'%q','%q','%q','%q','%q','%q','%q','%q',0);", authName.c_str(), code.c_str(), crs->nameStr().c_str(), "", // description csAuthName.c_str(), csCode.c_str(), datumAuthName.c_str(), datumCode.c_str()); appendSql(sqlStatements, sql); identifyOrInsertUsages(crs, "vertical_crs", authName, code, allowedAuthorities, sqlStatements); return sqlStatements; } // --------------------------------------------------------------------------- std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( const crs::CompoundCRSNNPtr &crs, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities) { const auto self = NN_NO_CHECK(self_.lock()); std::vector<std::string> sqlStatements; int counter = 1; std::vector<std::pair<std::string, std::string>> componentsId; const auto &components = crs->componentReferenceSystems(); if (components.size() != 2) { throw FactoryException( "Cannot insert compound CRS with number of components != 2"); } auto allowedAuthoritiesTmp(allowedAuthorities); allowedAuthoritiesTmp.emplace_back(authName); for (const auto &component : components) { std::string compAuthName; std::string compCode; for (const auto &allowedAuthority : allowedAuthoritiesTmp) { const auto factory = AuthorityFactory::create(self, allowedAuthority); const auto candidates = component->identify(factory); for (const auto &candidate : candidates) { if (candidate.second == 100) { const auto &ids = candidate.first->identifiers(); if (!ids.empty()) { const auto &id = ids.front(); compAuthName = *(id->codeSpace()); compCode = id->code(); break; } } if (!compAuthName.empty()) { break; } } } if (compAuthName.empty()) { compAuthName = authName; if (numericCode) { compCode = self->suggestsCodeFor(component, compAuthName, true); } else { compCode = "COMPONENT_" + code + '_' + toString(counter); } const auto sqlStatementsTmp = self->getInsertStatementsFor(component, compAuthName, compCode, numericCode, allowedAuthorities); sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(), sqlStatementsTmp.end()); } componentsId.emplace_back( std::pair<std::string, std::string>(compAuthName, compCode)); ++counter; } // Insert new record in compound_crs table const auto sql = formatStatement( "INSERT INTO compound_crs VALUES(" "'%q','%q','%q','%q','%q','%q','%q','%q',0);", authName.c_str(), code.c_str(), crs->nameStr().c_str(), "", // description componentsId[0].first.c_str(), componentsId[0].second.c_str(), componentsId[1].first.c_str(), componentsId[1].second.c_str()); appendSql(sqlStatements, sql); identifyOrInsertUsages(crs, "compound_crs", authName, code, allowedAuthorities, sqlStatements); return sqlStatements; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DatabaseContext::~DatabaseContext() { try { stopInsertStatementsSession(); } catch (const std::exception &) { } } //! @endcond // --------------------------------------------------------------------------- DatabaseContext::DatabaseContext() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- /** \brief Instantiate a database context. * * This database context should be used only by one thread at a time. * * @param databasePath Path and filename of the database. Might be empty * string for the default rules to locate the default proj.db * @param auxiliaryDatabasePaths Path and filename of auxiliary databases. * Might be empty. * Starting with PROJ 8.1, if this parameter is an empty array, * the PROJ_AUX_DB environment variable will be used, if set. * It must contain one or several paths. If several paths are * provided, they must be separated by the colon (:) character on Unix, and * on Windows, by the semi-colon (;) character. * @param ctx Context used for file search. * @throw FactoryException */ DatabaseContextNNPtr DatabaseContext::create(const std::string &databasePath, const std::vector<std::string> &auxiliaryDatabasePaths, PJ_CONTEXT *ctx) { auto dbCtx = DatabaseContext::nn_make_shared<DatabaseContext>(); auto dbCtxPrivate = dbCtx->getPrivate(); dbCtxPrivate->open(databasePath, ctx); auto auxDbs(auxiliaryDatabasePaths); if (auxDbs.empty()) { const char *auxDbStr = getenv("PROJ_AUX_DB"); if (auxDbStr) { #ifdef _WIN32 const char *delim = ";"; #else const char *delim = ":"; #endif auxDbs = split(auxDbStr, delim); } } if (!auxDbs.empty()) { dbCtxPrivate->attachExtraDatabases(auxDbs); dbCtxPrivate->auxiliaryDatabasePaths_ = std::move(auxDbs); } dbCtxPrivate->self_ = dbCtx.as_nullable(); return dbCtx; } // --------------------------------------------------------------------------- /** \brief Return the list of authorities used in the database. */ std::set<std::string> DatabaseContext::getAuthorities() const { auto res = d->run("SELECT auth_name FROM authority_list"); std::set<std::string> list; for (const auto &row : res) { list.insert(row[0]); } return list; } // --------------------------------------------------------------------------- /** \brief Return the list of SQL commands (CREATE TABLE, CREATE TRIGGER, * CREATE VIEW) needed to initialize a new database. */ std::vector<std::string> DatabaseContext::getDatabaseStructure() const { return d->getDatabaseStructure(); } // --------------------------------------------------------------------------- /** \brief Return the path to the database. */ const std::string &DatabaseContext::getPath() const { return d->getPath(); } // --------------------------------------------------------------------------- /** \brief Return a metadata item. * * Value remains valid while this is alive and to the next call to getMetadata */ const char *DatabaseContext::getMetadata(const char *key) const { auto res = d->run("SELECT value FROM metadata WHERE key = ?", {std::string(key)}); if (res.empty()) { return nullptr; } d->lastMetadataValue_ = res.front()[0]; return d->lastMetadataValue_.c_str(); } // --------------------------------------------------------------------------- /** \brief Starts a session for getInsertStatementsFor() * * Starts a new session for one or several calls to getInsertStatementsFor(). * An insertion session guarantees that the inserted objects will not create * conflicting intermediate objects. * * The session must be stopped with stopInsertStatementsSession(). * * Only one session may be active at a time for a given database context. * * @throw FactoryException * @since 8.1 */ void DatabaseContext::startInsertStatementsSession() { if (d->memoryDbHandle_) { throw FactoryException( "startInsertStatementsSession() cannot be invoked until " "stopInsertStatementsSession() is."); } d->memoryDbForInsertPath_.clear(); const auto sqlStatements = getDatabaseStructure(); // Create a in-memory temporary sqlite3 database std::ostringstream buffer; buffer << "file:temp_db_for_insert_statements_"; buffer << this; buffer << ".db?mode=memory&cache=shared"; d->memoryDbForInsertPath_ = buffer.str(); sqlite3 *memoryDbHandle = nullptr; sqlite3_open_v2( d->memoryDbForInsertPath_.c_str(), &memoryDbHandle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, nullptr); if (memoryDbHandle == nullptr) { throw FactoryException("Cannot create in-memory database"); } d->memoryDbHandle_ = SQLiteHandle::initFromExistingUniquePtr(memoryDbHandle, true); // Fill the structure of this database for (const auto &sql : sqlStatements) { char *errmsg = nullptr; if (sqlite3_exec(d->memoryDbHandle_->handle(), sql.c_str(), nullptr, nullptr, &errmsg) != SQLITE_OK) { const auto sErrMsg = "Cannot execute " + sql + ": " + (errmsg ? errmsg : ""); sqlite3_free(errmsg); throw FactoryException(sErrMsg); } sqlite3_free(errmsg); } // Attach this database to the current one(s) auto auxiliaryDatabasePaths(d->auxiliaryDatabasePaths_); auxiliaryDatabasePaths.push_back(d->memoryDbForInsertPath_); d->attachExtraDatabases(auxiliaryDatabasePaths); } // --------------------------------------------------------------------------- /** \brief Suggests a database code for the passed object. * * Supported type of objects are PrimeMeridian, Ellipsoid, Datum, DatumEnsemble, * GeodeticCRS, ProjectedCRS, VerticalCRS, CompoundCRS, BoundCRS, Conversion. * * @param object Object for which to suggest a code. * @param authName Authority name into which the object will be inserted. * @param numericCode Whether the code should be numeric, or derived from the * object name. * @return the suggested code, that is guaranteed to not conflict with an * existing one. * * @throw FactoryException * @since 8.1 */ std::string DatabaseContext::suggestsCodeFor(const common::IdentifiedObjectNNPtr &object, const std::string &authName, bool numericCode) { const char *tableName = ""; if (dynamic_cast<const datum::PrimeMeridian *>(object.get())) { tableName = "prime_meridian"; } else if (dynamic_cast<const datum::Ellipsoid *>(object.get())) { tableName = "ellipsoid"; } else if (dynamic_cast<const datum::GeodeticReferenceFrame *>( object.get())) { tableName = "geodetic_datum"; } else if (dynamic_cast<const datum::VerticalReferenceFrame *>( object.get())) { tableName = "vertical_datum"; } else if (const auto ensemble = dynamic_cast<const datum::DatumEnsemble *>(object.get())) { const auto &datums = ensemble->datums(); if (!datums.empty() && dynamic_cast<const datum::GeodeticReferenceFrame *>( datums[0].get())) { tableName = "geodetic_datum"; } else { tableName = "vertical_datum"; } } else if (const auto boundCRS = dynamic_cast<const crs::BoundCRS *>(object.get())) { return suggestsCodeFor(boundCRS->baseCRS(), authName, numericCode); } else if (dynamic_cast<const crs::CRS *>(object.get())) { tableName = "crs_view"; } else if (dynamic_cast<const operation::Conversion *>(object.get())) { tableName = "conversion"; } else { throw FactoryException("suggestsCodeFor(): unhandled type of object"); } if (numericCode) { std::string sql("SELECT MAX(code) FROM "); sql += tableName; sql += " WHERE auth_name = ? AND code >= '1' AND code <= '999999999' " "AND upper(code) = lower(code)"; const auto res = d->run(sql, {authName}); if (res.empty()) { return "1"; } return toString(atoi(res.front()[0].c_str()) + 1); } std::string code; code.reserve(object->nameStr().size()); bool insertUnderscore = false; for (const auto ch : toupper(object->nameStr())) { if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z')) { if (insertUnderscore && code.back() != '_') code += '_'; code += ch; insertUnderscore = false; } else { insertUnderscore = true; } } return d->findFreeCode(tableName, authName, code); } // --------------------------------------------------------------------------- /** \brief Returns SQL statements needed to insert the passed object into the * database. * * startInsertStatementsSession() must have been called previously. * * @param object The object to insert into the database. Currently only * PrimeMeridian, Ellipsoid, Datum, GeodeticCRS, ProjectedCRS, * VerticalCRS, CompoundCRS or BoundCRS are supported. * @param authName Authority name into which the object will be inserted. * @param code Code with which the object will be inserted. * @param numericCode Whether intermediate objects that can be created should * use numeric codes (true), or may be alphanumeric (false) * @param allowedAuthorities Authorities to which intermediate objects are * allowed to refer to. authName will be implicitly * added to it. Note that unit, coordinate * systems, projection methods and parameters will in * any case be allowed to refer to EPSG. * @throw FactoryException * @since 8.1 */ std::vector<std::string> DatabaseContext::getInsertStatementsFor( const common::IdentifiedObjectNNPtr &object, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities) { if (d->memoryDbHandle_ == nullptr) { throw FactoryException( "startInsertStatementsSession() should be invoked first"); } const auto crs = util::nn_dynamic_pointer_cast<crs::CRS>(object); if (crs) { // Check if the object is already known under that code const auto self = NN_NO_CHECK(d->self_.lock()); auto allowedAuthoritiesTmp(allowedAuthorities); allowedAuthoritiesTmp.emplace_back(authName); for (const auto &allowedAuthority : allowedAuthoritiesTmp) { const auto factory = AuthorityFactory::create(self, allowedAuthority); const auto candidates = crs->identify(factory); for (const auto &candidate : candidates) { if (candidate.second == 100) { const auto &ids = candidate.first->identifiers(); for (const auto &id : ids) { if (*(id->codeSpace()) == authName && id->code() == code) { return {}; } } } } } } if (const auto pm = util::nn_dynamic_pointer_cast<datum::PrimeMeridian>(object)) { return d->getInsertStatementsFor(NN_NO_CHECK(pm), authName, code, numericCode, allowedAuthorities); } else if (const auto ellipsoid = util::nn_dynamic_pointer_cast<datum::Ellipsoid>(object)) { return d->getInsertStatementsFor(NN_NO_CHECK(ellipsoid), authName, code, numericCode, allowedAuthorities); } else if (const auto geodeticDatum = util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>( object)) { return d->getInsertStatementsFor(NN_NO_CHECK(geodeticDatum), authName, code, numericCode, allowedAuthorities); } else if (const auto ensemble = util::nn_dynamic_pointer_cast<datum::DatumEnsemble>(object)) { return d->getInsertStatementsFor(NN_NO_CHECK(ensemble), authName, code, numericCode, allowedAuthorities); } else if (const auto geodCRS = std::dynamic_pointer_cast<crs::GeodeticCRS>(crs)) { return d->getInsertStatementsFor(NN_NO_CHECK(geodCRS), authName, code, numericCode, allowedAuthorities); } else if (const auto projCRS = std::dynamic_pointer_cast<crs::ProjectedCRS>(crs)) { return d->getInsertStatementsFor(NN_NO_CHECK(projCRS), authName, code, numericCode, allowedAuthorities); } else if (const auto verticalDatum = util::nn_dynamic_pointer_cast<datum::VerticalReferenceFrame>( object)) { return d->getInsertStatementsFor(NN_NO_CHECK(verticalDatum), authName, code, numericCode, allowedAuthorities); } else if (const auto vertCRS = std::dynamic_pointer_cast<crs::VerticalCRS>(crs)) { return d->getInsertStatementsFor(NN_NO_CHECK(vertCRS), authName, code, numericCode, allowedAuthorities); } else if (const auto compoundCRS = std::dynamic_pointer_cast<crs::CompoundCRS>(crs)) { return d->getInsertStatementsFor(NN_NO_CHECK(compoundCRS), authName, code, numericCode, allowedAuthorities); } else if (const auto boundCRS = std::dynamic_pointer_cast<crs::BoundCRS>(crs)) { return getInsertStatementsFor(boundCRS->baseCRS(), authName, code, numericCode, allowedAuthorities); } else { throw FactoryException( "getInsertStatementsFor(): unhandled type of object"); } } // --------------------------------------------------------------------------- /** \brief Stops an insertion session started with * startInsertStatementsSession() * * @since 8.1 */ void DatabaseContext::stopInsertStatementsSession() { if (d->memoryDbHandle_) { d->clearCaches(); d->attachExtraDatabases(d->auxiliaryDatabasePaths_); d->memoryDbHandle_.reset(); d->memoryDbForInsertPath_.clear(); } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DatabaseContextNNPtr DatabaseContext::create(void *sqlite_handle) { auto ctxt = DatabaseContext::nn_make_shared<DatabaseContext>(); ctxt->getPrivate()->setHandle(static_cast<sqlite3 *>(sqlite_handle)); return ctxt; } // --------------------------------------------------------------------------- void *DatabaseContext::getSqliteHandle() const { return d->handle()->handle(); } // --------------------------------------------------------------------------- bool DatabaseContext::lookForGridAlternative(const std::string &officialName, std::string &projFilename, std::string &projFormat, bool &inverse) const { auto res = d->run( "SELECT proj_grid_name, proj_grid_format, inverse_direction FROM " "grid_alternatives WHERE original_grid_name = ? AND " "proj_grid_name <> ''", {officialName}); if (res.empty()) { return false; } const auto &row = res.front(); projFilename = row[0]; projFormat = row[1]; inverse = row[2] == "1"; return true; } // --------------------------------------------------------------------------- bool DatabaseContext::lookForGridInfo( const std::string &projFilename, bool considerKnownGridsAsAvailable, std::string &fullFilename, std::string &packageName, std::string &url, bool &directDownload, bool &openLicense, bool &gridAvailable) const { Private::GridInfoCache info; if (projFilename == "null") { // Special case for implicit "null" grid. fullFilename.clear(); packageName.clear(); url.clear(); directDownload = false; openLicense = true; gridAvailable = true; return true; } auto ctxt = d->pjCtxt(); if (ctxt == nullptr) { ctxt = pj_get_default_ctx(); d->setPjCtxt(ctxt); } std::string key(projFilename); key += proj_context_is_network_enabled(ctxt) ? "true" : "false"; key += considerKnownGridsAsAvailable ? "true" : "false"; if (d->getGridInfoFromCache(key, info)) { fullFilename = info.fullFilename; packageName = info.packageName; url = info.url; directDownload = info.directDownload; openLicense = info.openLicense; gridAvailable = info.gridAvailable; return info.found; } fullFilename.clear(); packageName.clear(); url.clear(); openLicense = false; directDownload = false; fullFilename.resize(2048); int errno_before = proj_context_errno(ctxt); gridAvailable = NS_PROJ::FileManager::open_resource_file( ctxt, projFilename.c_str(), &fullFilename[0], fullFilename.size() - 1) != nullptr; proj_context_errno_set(ctxt, errno_before); fullFilename.resize(strlen(fullFilename.c_str())); auto res = d->run("SELECT " "grid_packages.package_name, " "grid_alternatives.url, " "grid_packages.url AS package_url, " "grid_alternatives.open_license, " "grid_packages.open_license AS package_open_license, " "grid_alternatives.direct_download, " "grid_packages.direct_download AS package_direct_download, " "grid_alternatives.proj_grid_name, " "grid_alternatives.old_proj_grid_name " "FROM grid_alternatives " "LEFT JOIN grid_packages ON " "grid_alternatives.package_name = grid_packages.package_name " "WHERE proj_grid_name = ? OR old_proj_grid_name = ?", {projFilename, projFilename}); bool ret = !res.empty(); if (ret) { const auto &row = res.front(); packageName = std::move(row[0]); url = row[1].empty() ? std::move(row[2]) : std::move(row[1]); openLicense = (row[3].empty() ? row[4] : row[3]) == "1"; directDownload = (row[5].empty() ? row[6] : row[5]) == "1"; const auto &proj_grid_name = row[7]; const auto &old_proj_grid_name = row[8]; if (proj_grid_name != old_proj_grid_name && old_proj_grid_name == projFilename) { std::string fullFilenameNewName; fullFilenameNewName.resize(2048); errno_before = proj_context_errno(ctxt); bool gridAvailableWithNewName = pj_find_file(ctxt, proj_grid_name.c_str(), &fullFilenameNewName[0], fullFilenameNewName.size() - 1) != 0; proj_context_errno_set(ctxt, errno_before); fullFilenameNewName.resize(strlen(fullFilenameNewName.c_str())); if (gridAvailableWithNewName) { gridAvailable = true; fullFilename = std::move(fullFilenameNewName); } } if (considerKnownGridsAsAvailable && (!packageName.empty() || (!url.empty() && openLicense))) { gridAvailable = true; } info.packageName = packageName; std::string endpoint(proj_context_get_url_endpoint(d->pjCtxt())); if (!endpoint.empty() && starts_with(url, "https://cdn.proj.org/")) { if (endpoint.back() != '/') { endpoint += '/'; } url = endpoint + url.substr(strlen("https://cdn.proj.org/")); } info.directDownload = directDownload; info.openLicense = openLicense; } else { if (starts_with(fullFilename, "http://") || starts_with(fullFilename, "https://")) { url = fullFilename; fullFilename.clear(); } } info.fullFilename = fullFilename; info.url = url; info.gridAvailable = gridAvailable; info.found = ret; d->cache(key, info); return ret; } // --------------------------------------------------------------------------- bool DatabaseContext::isKnownName(const std::string &name, const std::string &tableName) const { std::string sql("SELECT 1 FROM \""); sql += replaceAll(tableName, "\"", "\"\""); sql += "\" WHERE name = ? LIMIT 1"; return !d->run(sql, {name}).empty(); } // --------------------------------------------------------------------------- std::string DatabaseContext::getProjGridName(const std::string &oldProjGridName) { auto res = d->run("SELECT proj_grid_name FROM grid_alternatives WHERE " "old_proj_grid_name = ?", {oldProjGridName}); if (res.empty()) { return std::string(); } return res.front()[0]; } // --------------------------------------------------------------------------- std::string DatabaseContext::getOldProjGridName(const std::string &gridName) { auto res = d->run("SELECT old_proj_grid_name FROM grid_alternatives WHERE " "proj_grid_name = ?", {gridName}); if (res.empty()) { return std::string(); } return res.front()[0]; } // --------------------------------------------------------------------------- // scripts/build_db_from_esri.py adds a second alias for // names that have '[' in them. See get_old_esri_name() // in scripts/build_db_from_esri.py // So if we only have two aliases detect that situation to get the official // new name static std::string getUniqueEsriAlias(const std::list<std::string> &l) { std::string first = l.front(); std::string second = *(std::next(l.begin())); if (second.find('[') != std::string::npos) std::swap(first, second); if (replaceAll(replaceAll(replaceAll(first, "[", ""), "]", ""), "-", "_") == second) { return first; } return std::string(); } // --------------------------------------------------------------------------- /** \brief Gets the alias name from an official name. * * @param officialName Official name. Mandatory * @param tableName Table name/category. Mandatory. * "geographic_2D_crs" and "geographic_3D_crs" are also * accepted as special names to add a constraint on the "type" * column of the "geodetic_crs" table. * @param source Source of the alias. Mandatory * @return Alias name (or empty if not found). * @throw FactoryException */ std::string DatabaseContext::getAliasFromOfficialName(const std::string &officialName, const std::string &tableName, const std::string &source) const { std::string sql("SELECT auth_name, code FROM \""); const auto genuineTableName = tableName == "geographic_2D_crs" || tableName == "geographic_3D_crs" ? "geodetic_crs" : tableName; sql += replaceAll(genuineTableName, "\"", "\"\""); sql += "\" WHERE name = ?"; if (tableName == "geodetic_crs" || tableName == "geographic_2D_crs") { sql += " AND type = " GEOG_2D_SINGLE_QUOTED; } else if (tableName == "geographic_3D_crs") { sql += " AND type = " GEOG_3D_SINGLE_QUOTED; } sql += " ORDER BY deprecated"; auto res = d->run(sql, {officialName}); // Sorry for the hack excluding NAD83 + geographic_3D_crs, but otherwise // EPSG has a weird alias from NAD83 to EPSG:4152 which happens to be // NAD83(HARN), and that's definitely not desirable. if (res.empty() && !(officialName == "NAD83" && tableName == "geographic_3D_crs")) { res = d->run( "SELECT auth_name, code FROM alias_name WHERE table_name = ? AND " "alt_name = ? AND source IN ('EPSG', 'PROJ')", {genuineTableName, officialName}); if (res.size() != 1) { return std::string(); } } for (const auto &row : res) { auto res2 = d->run("SELECT alt_name FROM alias_name WHERE table_name = ? AND " "auth_name = ? AND code = ? AND source = ?", {genuineTableName, row[0], row[1], source}); if (!res2.empty()) { if (res2.size() == 2 && source == "ESRI") { std::list<std::string> l; l.emplace_back(res2.front()[0]); l.emplace_back((*(std::next(res2.begin())))[0]); const auto uniqueEsriAlias = getUniqueEsriAlias(l); if (!uniqueEsriAlias.empty()) return uniqueEsriAlias; } return res2.front()[0]; } } return std::string(); } // --------------------------------------------------------------------------- /** \brief Gets the alias names for an object. * * Either authName + code or officialName must be non empty. * * @param authName Authority. * @param code Code. * @param officialName Official name. * @param tableName Table name/category. Mandatory. * "geographic_2D_crs" and "geographic_3D_crs" are also * accepted as special names to add a constraint on the "type" * column of the "geodetic_crs" table. * @param source Source of the alias. May be empty. * @return Aliases */ std::list<std::string> DatabaseContext::getAliases( const std::string &authName, const std::string &code, const std::string &officialName, const std::string &tableName, const std::string &source) const { std::list<std::string> res; const auto key(authName + code + officialName + tableName + source); if (d->cacheAliasNames_.tryGet(key, res)) { return res; } std::string resolvedAuthName(authName); std::string resolvedCode(code); const auto genuineTableName = tableName == "geographic_2D_crs" || tableName == "geographic_3D_crs" ? "geodetic_crs" : tableName; if (authName.empty() || code.empty()) { std::string sql("SELECT auth_name, code FROM \""); sql += replaceAll(genuineTableName, "\"", "\"\""); sql += "\" WHERE name = ?"; if (tableName == "geodetic_crs" || tableName == "geographic_2D_crs") { sql += " AND type = " GEOG_2D_SINGLE_QUOTED; } else if (tableName == "geographic_3D_crs") { sql += " AND type = " GEOG_3D_SINGLE_QUOTED; } sql += " ORDER BY deprecated"; auto resSql = d->run(sql, {officialName}); if (resSql.empty()) { resSql = d->run("SELECT auth_name, code FROM alias_name WHERE " "table_name = ? AND " "alt_name = ? AND source IN ('EPSG', 'PROJ')", {genuineTableName, officialName}); if (resSql.size() != 1) { d->cacheAliasNames_.insert(key, res); return res; } } const auto &row = resSql.front(); resolvedAuthName = row[0]; resolvedCode = row[1]; } std::string sql("SELECT alt_name FROM alias_name WHERE table_name = ? AND " "auth_name = ? AND code = ?"); ListOfParams params{genuineTableName, resolvedAuthName, resolvedCode}; if (!source.empty()) { sql += " AND source = ?"; params.emplace_back(source); } auto resSql = d->run(sql, params); for (const auto &row : resSql) { res.emplace_back(row[0]); } if (res.size() == 2 && source == "ESRI") { const auto uniqueEsriAlias = getUniqueEsriAlias(res); if (!uniqueEsriAlias.empty()) { res.clear(); res.emplace_back(uniqueEsriAlias); } } d->cacheAliasNames_.insert(key, res); return res; } // --------------------------------------------------------------------------- /** \brief Return the 'name' column of a table for an object * * @param tableName Table name/category. * @param authName Authority name of the object. * @param code Code of the object * @return Name (or empty) * @throw FactoryException */ std::string DatabaseContext::getName(const std::string &tableName, const std::string &authName, const std::string &code) const { std::string sql("SELECT name FROM \""); sql += replaceAll(tableName, "\"", "\"\""); sql += "\" WHERE auth_name = ? AND code = ?"; auto res = d->run(sql, {authName, code}); if (res.empty()) { return std::string(); } return res.front()[0]; } // --------------------------------------------------------------------------- /** \brief Return the 'text_definition' column of a table for an object * * @param tableName Table name/category. * @param authName Authority name of the object. * @param code Code of the object * @return Text definition (or empty) * @throw FactoryException */ std::string DatabaseContext::getTextDefinition(const std::string &tableName, const std::string &authName, const std::string &code) const { std::string sql("SELECT text_definition FROM \""); sql += replaceAll(tableName, "\"", "\"\""); sql += "\" WHERE auth_name = ? AND code = ?"; auto res = d->run(sql, {authName, code}); if (res.empty()) { return std::string(); } return res.front()[0]; } // --------------------------------------------------------------------------- /** \brief Return the allowed authorities when researching transformations * between different authorities. * * @throw FactoryException */ std::vector<std::string> DatabaseContext::getAllowedAuthorities( const std::string &sourceAuthName, const std::string &targetAuthName) const { const auto key(sourceAuthName + targetAuthName); auto hit = d->cacheAllowedAuthorities_.find(key); if (hit != d->cacheAllowedAuthorities_.end()) { return hit->second; } auto sqlRes = d->run( "SELECT allowed_authorities FROM authority_to_authority_preference " "WHERE source_auth_name = ? AND target_auth_name = ?", {sourceAuthName, targetAuthName}); if (sqlRes.empty()) { sqlRes = d->run( "SELECT allowed_authorities FROM authority_to_authority_preference " "WHERE source_auth_name = ? AND target_auth_name = 'any'", {sourceAuthName}); } if (sqlRes.empty()) { sqlRes = d->run( "SELECT allowed_authorities FROM authority_to_authority_preference " "WHERE source_auth_name = 'any' AND target_auth_name = ?", {targetAuthName}); } if (sqlRes.empty()) { sqlRes = d->run( "SELECT allowed_authorities FROM authority_to_authority_preference " "WHERE source_auth_name = 'any' AND target_auth_name = 'any'", {}); } if (sqlRes.empty()) { d->cacheAllowedAuthorities_[key] = std::vector<std::string>(); return std::vector<std::string>(); } auto res = split(sqlRes.front()[0], ','); d->cacheAllowedAuthorities_[key] = res; return res; } // --------------------------------------------------------------------------- std::list<std::pair<std::string, std::string>> DatabaseContext::getNonDeprecated(const std::string &tableName, const std::string &authName, const std::string &code) const { auto sqlRes = d->run("SELECT replacement_auth_name, replacement_code, source " "FROM deprecation " "WHERE table_name = ? AND deprecated_auth_name = ? " "AND deprecated_code = ?", {tableName, authName, code}); std::list<std::pair<std::string, std::string>> res; for (const auto &row : sqlRes) { const auto &source = row[2]; if (source == "PROJ") { const auto &replacement_auth_name = row[0]; const auto &replacement_code = row[1]; res.emplace_back(replacement_auth_name, replacement_code); } } if (!res.empty()) { return res; } for (const auto &row : sqlRes) { const auto &replacement_auth_name = row[0]; const auto &replacement_code = row[1]; res.emplace_back(replacement_auth_name, replacement_code); } return res; } // --------------------------------------------------------------------------- const std::vector<DatabaseContext::Private::VersionedAuthName> & DatabaseContext::Private::getCacheAuthNameWithVersion() { if (cacheAuthNameWithVersion_.empty()) { const auto sqlRes = run("SELECT versioned_auth_name, auth_name, version, priority " "FROM versioned_auth_name_mapping"); for (const auto &row : sqlRes) { VersionedAuthName van; van.versionedAuthName = row[0]; van.authName = row[1]; van.version = row[2]; van.priority = atoi(row[3].c_str()); cacheAuthNameWithVersion_.emplace_back(std::move(van)); } } return cacheAuthNameWithVersion_; } // --------------------------------------------------------------------------- // From IAU_2015 returns (IAU,2015) bool DatabaseContext::getAuthorityAndVersion( const std::string &versionedAuthName, std::string &authNameOut, std::string &versionOut) { for (const auto &van : d->getCacheAuthNameWithVersion()) { if (van.versionedAuthName == versionedAuthName) { authNameOut = van.authName; versionOut = van.version; return true; } } return false; } // --------------------------------------------------------------------------- // From IAU and 2015, returns IAU_2015 bool DatabaseContext::getVersionedAuthority(const std::string &authName, const std::string &version, std::string &versionedAuthNameOut) { for (const auto &van : d->getCacheAuthNameWithVersion()) { if (van.authName == authName && van.version == version) { versionedAuthNameOut = van.versionedAuthName; return true; } } return false; } // --------------------------------------------------------------------------- // From IAU returns IAU_latest, ... IAU_2015 std::vector<std::string> DatabaseContext::getVersionedAuthoritiesFromName(const std::string &authName) { typedef std::pair<std::string, int> VersionedAuthNamePriority; std::vector<VersionedAuthNamePriority> tmp; for (const auto &van : d->getCacheAuthNameWithVersion()) { if (van.authName == authName) { tmp.emplace_back( VersionedAuthNamePriority(van.versionedAuthName, van.priority)); } } std::vector<std::string> res; if (!tmp.empty()) { // Sort by decreasing priority std::sort(tmp.begin(), tmp.end(), [](const VersionedAuthNamePriority &a, const VersionedAuthNamePriority &b) { return b.second > a.second; }); for (const auto &pair : tmp) res.emplace_back(pair.first); } return res; } // --------------------------------------------------------------------------- std::vector<operation::CoordinateOperationNNPtr> DatabaseContext::getTransformationsForGridName( const DatabaseContextNNPtr &databaseContext, const std::string &gridName) { auto sqlRes = databaseContext->d->run( "SELECT auth_name, code FROM grid_transformation " "WHERE grid_name = ? OR grid_name IN " "(SELECT original_grid_name FROM grid_alternatives " "WHERE proj_grid_name = ?) ORDER BY auth_name, code", {gridName, gridName}); std::vector<operation::CoordinateOperationNNPtr> res; for (const auto &row : sqlRes) { res.emplace_back(AuthorityFactory::create(databaseContext, row[0]) ->createCoordinateOperation(row[1], true)); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct AuthorityFactory::Private { Private(const DatabaseContextNNPtr &contextIn, const std::string &authorityName) : context_(contextIn), authority_(authorityName) {} inline const std::string &authority() PROJ_PURE_DEFN { return authority_; } inline const DatabaseContextNNPtr &context() PROJ_PURE_DEFN { return context_; } // cppcheck-suppress functionStatic void setThis(AuthorityFactoryNNPtr factory) { thisFactory_ = factory.as_nullable(); } // cppcheck-suppress functionStatic AuthorityFactoryPtr getSharedFromThis() { return thisFactory_.lock(); } inline AuthorityFactoryNNPtr createFactory(const std::string &auth_name) { if (auth_name == authority_) { return NN_NO_CHECK(thisFactory_.lock()); } return AuthorityFactory::create(context_, auth_name); } bool rejectOpDueToMissingGrid(const operation::CoordinateOperationNNPtr &op, bool considerKnownGridsAsAvailable); UnitOfMeasure createUnitOfMeasure(const std::string &auth_name, const std::string &code); util::PropertyMap createProperties(const std::string &code, const std::string &name, bool deprecated, const std::vector<ObjectDomainNNPtr> &usages); util::PropertyMap createPropertiesSearchUsages(const std::string &table_name, const std::string &code, const std::string &name, bool deprecated); util::PropertyMap createPropertiesSearchUsages( const std::string &table_name, const std::string &code, const std::string &name, bool deprecated, const std::string &remarks); SQLResultSet run(const std::string &sql, const ListOfParams &parameters = ListOfParams()); SQLResultSet runWithCodeParam(const std::string &sql, const std::string &code); SQLResultSet runWithCodeParam(const char *sql, const std::string &code); bool hasAuthorityRestriction() const { return !authority_.empty() && authority_ != "any"; } SQLResultSet createProjectedCRSBegin(const std::string &code); crs::ProjectedCRSNNPtr createProjectedCRSEnd(const std::string &code, const SQLResultSet &res); private: DatabaseContextNNPtr context_; std::string authority_; std::weak_ptr<AuthorityFactory> thisFactory_{}; }; // --------------------------------------------------------------------------- SQLResultSet AuthorityFactory::Private::run(const std::string &sql, const ListOfParams &parameters) { return context()->getPrivate()->run(sql, parameters); } // --------------------------------------------------------------------------- SQLResultSet AuthorityFactory::Private::runWithCodeParam(const std::string &sql, const std::string &code) { return run(sql, {authority(), code}); } // --------------------------------------------------------------------------- SQLResultSet AuthorityFactory::Private::runWithCodeParam(const char *sql, const std::string &code) { return runWithCodeParam(std::string(sql), code); } // --------------------------------------------------------------------------- UnitOfMeasure AuthorityFactory::Private::createUnitOfMeasure(const std::string &auth_name, const std::string &code) { return *(createFactory(auth_name)->createUnitOfMeasure(code)); } // --------------------------------------------------------------------------- util::PropertyMap AuthorityFactory::Private::createProperties( const std::string &code, const std::string &name, bool deprecated, const std::vector<ObjectDomainNNPtr> &usages) { auto props = util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, authority()) .set(metadata::Identifier::CODE_KEY, code) .set(common::IdentifiedObject::NAME_KEY, name); if (deprecated) { props.set(common::IdentifiedObject::DEPRECATED_KEY, true); } if (!usages.empty()) { auto array(util::ArrayOfBaseObject::create()); for (const auto &usage : usages) { array->add(usage); } props.set(common::ObjectUsage::OBJECT_DOMAIN_KEY, util::nn_static_pointer_cast<util::BaseObject>(array)); } return props; } // --------------------------------------------------------------------------- util::PropertyMap AuthorityFactory::Private::createPropertiesSearchUsages( const std::string &table_name, const std::string &code, const std::string &name, bool deprecated) { SQLResultSet res; if (table_name == "geodetic_crs" && code == "4326" && authority() == "EPSG") { // EPSG v10.077 has changed the extent from 1262 to 2830, whose // description is super verbose. // Cf https://epsg.org/closed-change-request/browse/id/2022.086 // To avoid churn in our WKT2 output, hot patch to the usage of // 10.076 and earlier res = run("SELECT extent.description, extent.south_lat, " "extent.north_lat, extent.west_lon, extent.east_lon, " "scope.scope, 0 AS score FROM extent, scope WHERE " "extent.code = 1262 and scope.code = 1183"); } else { const std::string sql( "SELECT extent.description, extent.south_lat, " "extent.north_lat, extent.west_lon, extent.east_lon, " "scope.scope, " "(CASE WHEN scope.scope LIKE '%large scale%' THEN 0 ELSE 1 END) " "AS score " "FROM usage " "JOIN extent ON usage.extent_auth_name = extent.auth_name AND " "usage.extent_code = extent.code " "JOIN scope ON usage.scope_auth_name = scope.auth_name AND " "usage.scope_code = scope.code " "WHERE object_table_name = ? AND object_auth_name = ? AND " "object_code = ? AND " // We voluntary exclude extent and scope with a specific code "NOT (usage.extent_auth_name = 'PROJ' AND " "usage.extent_code = 'EXTENT_UNKNOWN') AND " "NOT (usage.scope_auth_name = 'PROJ' AND " "usage.scope_code = 'SCOPE_UNKNOWN') " "ORDER BY score, usage.auth_name, usage.code"); res = run(sql, {table_name, authority(), code}); } std::vector<ObjectDomainNNPtr> usages; for (const auto &row : res) { try { size_t idx = 0; const auto &extent_description = row[idx++]; const auto &south_lat_str = row[idx++]; const auto &north_lat_str = row[idx++]; const auto &west_lon_str = row[idx++]; const auto &east_lon_str = row[idx++]; const auto &scope = row[idx]; util::optional<std::string> scopeOpt; if (!scope.empty()) { scopeOpt = scope; } metadata::ExtentPtr extent; if (south_lat_str.empty()) { extent = metadata::Extent::create( util::optional<std::string>(extent_description), {}, {}, {}) .as_nullable(); } else { double south_lat = c_locale_stod(south_lat_str); double north_lat = c_locale_stod(north_lat_str); double west_lon = c_locale_stod(west_lon_str); double east_lon = c_locale_stod(east_lon_str); auto bbox = metadata::GeographicBoundingBox::create( west_lon, south_lat, east_lon, north_lat); extent = metadata::Extent::create( util::optional<std::string>(extent_description), std::vector<metadata::GeographicExtentNNPtr>{bbox}, std::vector<metadata::VerticalExtentNNPtr>(), std::vector<metadata::TemporalExtentNNPtr>()) .as_nullable(); } usages.emplace_back(ObjectDomain::create(scopeOpt, extent)); } catch (const std::exception &) { } } return createProperties(code, name, deprecated, std::move(usages)); } // --------------------------------------------------------------------------- util::PropertyMap AuthorityFactory::Private::createPropertiesSearchUsages( const std::string &table_name, const std::string &code, const std::string &name, bool deprecated, const std::string &remarks) { auto props = createPropertiesSearchUsages(table_name, code, name, deprecated); if (!remarks.empty()) props.set(common::IdentifiedObject::REMARKS_KEY, remarks); return props; } // --------------------------------------------------------------------------- bool AuthorityFactory::Private::rejectOpDueToMissingGrid( const operation::CoordinateOperationNNPtr &op, bool considerKnownGridsAsAvailable) { struct DisableNetwork { const DatabaseContextNNPtr &m_dbContext; bool m_old_network_enabled = false; explicit DisableNetwork(const DatabaseContextNNPtr &l_context) : m_dbContext(l_context) { auto ctxt = m_dbContext->d->pjCtxt(); if (ctxt == nullptr) { ctxt = pj_get_default_ctx(); m_dbContext->d->setPjCtxt(ctxt); } m_old_network_enabled = proj_context_is_network_enabled(ctxt) != FALSE; if (m_old_network_enabled) proj_context_set_enable_network(ctxt, false); } ~DisableNetwork() { if (m_old_network_enabled) { auto ctxt = m_dbContext->d->pjCtxt(); proj_context_set_enable_network(ctxt, true); } } }; auto &l_context = context(); // Temporarily disable networking as we are only interested in known grids DisableNetwork disabler(l_context); for (const auto &gridDesc : op->gridsNeeded(l_context, considerKnownGridsAsAvailable)) { if (!gridDesc.available) { return true; } } return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress AuthorityFactory::~AuthorityFactory() = default; //! @endcond // --------------------------------------------------------------------------- AuthorityFactory::AuthorityFactory(const DatabaseContextNNPtr &context, const std::string &authorityName) : d(internal::make_unique<Private>(context, authorityName)) {} // --------------------------------------------------------------------------- // clang-format off /** \brief Instantiate a AuthorityFactory. * * The authority name might be set to the empty string in the particular case * where createFromCoordinateReferenceSystemCodes(const std::string&,const std::string&,const std::string&,const std::string&) const * is called. * * @param context Context. * @param authorityName Authority name. * @return new AuthorityFactory. */ // clang-format on AuthorityFactoryNNPtr AuthorityFactory::create(const DatabaseContextNNPtr &context, const std::string &authorityName) { const auto getFactory = [&context, &authorityName]() { for (const auto &knownName : {metadata::Identifier::EPSG.c_str(), "ESRI", "PROJ"}) { if (ci_equal(authorityName, knownName)) { return AuthorityFactory::nn_make_shared<AuthorityFactory>( context, knownName); } } return AuthorityFactory::nn_make_shared<AuthorityFactory>( context, authorityName); }; auto factory = getFactory(); factory->d->setThis(factory); return factory; } // --------------------------------------------------------------------------- /** \brief Returns the database context. */ const DatabaseContextNNPtr &AuthorityFactory::databaseContext() const { return d->context(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress AuthorityFactory::CRSInfo::CRSInfo() : authName{}, code{}, name{}, type{ObjectType::CRS}, deprecated{}, bbox_valid{}, west_lon_degree{}, south_lat_degree{}, east_lon_degree{}, north_lat_degree{}, areaName{}, projectionMethodName{}, celestialBodyName{} {} //! @endcond // --------------------------------------------------------------------------- /** \brief Returns an arbitrary object from a code. * * The returned object will typically be an instance of Datum, * CoordinateSystem, ReferenceSystem or CoordinateOperation. If the type of * the object is know at compile time, it is recommended to invoke the most * precise method instead of this one (for example * createCoordinateReferenceSystem(code) instead of createObject(code) * if the caller know he is asking for a coordinate reference system). * * If there are several objects with the same code, a FactoryException is * thrown. * * @param code Object code allocated by authority. (e.g. "4326") * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ util::BaseObjectNNPtr AuthorityFactory::createObject(const std::string &code) const { auto res = d->runWithCodeParam("SELECT table_name, type FROM object_view " "WHERE auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("not found", d->authority(), code); } if (res.size() != 1) { std::string msg( "More than one object matching specified code. Objects found in "); bool first = true; for (const auto &row : res) { if (!first) msg += ", "; msg += row[0]; first = false; } throw FactoryException(msg); } const auto &first_row = res.front(); const auto &table_name = first_row[0]; const auto &type = first_row[1]; if (table_name == "extent") { return util::nn_static_pointer_cast<util::BaseObject>( createExtent(code)); } if (table_name == "unit_of_measure") { return util::nn_static_pointer_cast<util::BaseObject>( createUnitOfMeasure(code)); } if (table_name == "prime_meridian") { return util::nn_static_pointer_cast<util::BaseObject>( createPrimeMeridian(code)); } if (table_name == "ellipsoid") { return util::nn_static_pointer_cast<util::BaseObject>( createEllipsoid(code)); } if (table_name == "geodetic_datum") { if (type == "ensemble") { return util::nn_static_pointer_cast<util::BaseObject>( createDatumEnsemble(code, table_name)); } return util::nn_static_pointer_cast<util::BaseObject>( createGeodeticDatum(code)); } if (table_name == "vertical_datum") { if (type == "ensemble") { return util::nn_static_pointer_cast<util::BaseObject>( createDatumEnsemble(code, table_name)); } return util::nn_static_pointer_cast<util::BaseObject>( createVerticalDatum(code)); } if (table_name == "geodetic_crs") { return util::nn_static_pointer_cast<util::BaseObject>( createGeodeticCRS(code)); } if (table_name == "vertical_crs") { return util::nn_static_pointer_cast<util::BaseObject>( createVerticalCRS(code)); } if (table_name == "projected_crs") { return util::nn_static_pointer_cast<util::BaseObject>( createProjectedCRS(code)); } if (table_name == "compound_crs") { return util::nn_static_pointer_cast<util::BaseObject>( createCompoundCRS(code)); } if (table_name == "conversion") { return util::nn_static_pointer_cast<util::BaseObject>( createConversion(code)); } if (table_name == "helmert_transformation" || table_name == "grid_transformation" || table_name == "other_transformation" || table_name == "concatenated_operation") { return util::nn_static_pointer_cast<util::BaseObject>( createCoordinateOperation(code, false)); } throw FactoryException("unimplemented factory for " + res.front()[0]); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static FactoryException buildFactoryException(const char *type, const std::string &authName, const std::string &code, const std::exception &ex) { return FactoryException(std::string("cannot build ") + type + " " + authName + ":" + code + ": " + ex.what()); } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns a metadata::Extent from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ metadata::ExtentNNPtr AuthorityFactory::createExtent(const std::string &code) const { const auto cacheKey(d->authority() + code); { auto extent = d->context()->d->getExtentFromCache(cacheKey); if (extent) { return NN_NO_CHECK(extent); } } auto sql = "SELECT description, south_lat, north_lat, west_lon, east_lon, " "deprecated FROM extent WHERE auth_name = ? AND code = ?"; auto res = d->runWithCodeParam(sql, code); if (res.empty()) { throw NoSuchAuthorityCodeException("extent not found", d->authority(), code); } try { const auto &row = res.front(); const auto &description = row[0]; if (row[1].empty()) { auto extent = metadata::Extent::create( util::optional<std::string>(description), {}, {}, {}); d->context()->d->cache(cacheKey, extent); return extent; } double south_lat = c_locale_stod(row[1]); double north_lat = c_locale_stod(row[2]); double west_lon = c_locale_stod(row[3]); double east_lon = c_locale_stod(row[4]); auto bbox = metadata::GeographicBoundingBox::create( west_lon, south_lat, east_lon, north_lat); auto extent = metadata::Extent::create( util::optional<std::string>(description), std::vector<metadata::GeographicExtentNNPtr>{bbox}, std::vector<metadata::VerticalExtentNNPtr>(), std::vector<metadata::TemporalExtentNNPtr>()); d->context()->d->cache(cacheKey, extent); return extent; } catch (const std::exception &ex) { throw buildFactoryException("extent", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a common::UnitOfMeasure from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ UnitOfMeasureNNPtr AuthorityFactory::createUnitOfMeasure(const std::string &code) const { const auto cacheKey(d->authority() + code); { auto uom = d->context()->d->getUOMFromCache(cacheKey); if (uom) { return NN_NO_CHECK(uom); } } auto res = d->context()->d->run( "SELECT name, conv_factor, type, deprecated FROM unit_of_measure WHERE " "auth_name = ? AND code = ?", {d->authority(), code}, true); if (res.empty()) { throw NoSuchAuthorityCodeException("unit of measure not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = (row[0] == "degree (supplier to define representation)") ? UnitOfMeasure::DEGREE.name() : row[0]; double conv_factor = (code == "9107" || code == "9108") ? UnitOfMeasure::DEGREE.conversionToSI() : c_locale_stod(row[1]); constexpr double EPS = 1e-10; if (std::fabs(conv_factor - UnitOfMeasure::DEGREE.conversionToSI()) < EPS * UnitOfMeasure::DEGREE.conversionToSI()) { conv_factor = UnitOfMeasure::DEGREE.conversionToSI(); } if (std::fabs(conv_factor - UnitOfMeasure::ARC_SECOND.conversionToSI()) < EPS * UnitOfMeasure::ARC_SECOND.conversionToSI()) { conv_factor = UnitOfMeasure::ARC_SECOND.conversionToSI(); } const auto &type_str = row[2]; UnitOfMeasure::Type unitType = UnitOfMeasure::Type::UNKNOWN; if (type_str == "length") unitType = UnitOfMeasure::Type::LINEAR; else if (type_str == "angle") unitType = UnitOfMeasure::Type::ANGULAR; else if (type_str == "scale") unitType = UnitOfMeasure::Type::SCALE; else if (type_str == "time") unitType = UnitOfMeasure::Type::TIME; auto uom = util::nn_make_shared<UnitOfMeasure>( name, conv_factor, unitType, d->authority(), code); d->context()->d->cache(cacheKey, uom); return uom; } catch (const std::exception &ex) { throw buildFactoryException("unit of measure", d->authority(), code, ex); } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static double normalizeMeasure(const std::string &uom_code, const std::string &value, std::string &normalized_uom_code) { if (uom_code == "9110") // DDD.MMSSsss..... { double normalized_value = c_locale_stod(value); std::ostringstream buffer; buffer.imbue(std::locale::classic()); constexpr size_t precision = 12; buffer << std::fixed << std::setprecision(precision) << normalized_value; auto formatted = buffer.str(); size_t dotPos = formatted.find('.'); assert(dotPos + 1 + precision == formatted.size()); auto minutes = formatted.substr(dotPos + 1, 2); auto seconds = formatted.substr(dotPos + 3); assert(seconds.size() == precision - 2); normalized_value = (normalized_value < 0 ? -1.0 : 1.0) * (std::floor(std::fabs(normalized_value)) + c_locale_stod(minutes) / 60. + (c_locale_stod(seconds) / std::pow(10, seconds.size() - 2)) / 3600.); normalized_uom_code = common::UnitOfMeasure::DEGREE.code(); /* coverity[overflow_sink] */ return normalized_value; } else { normalized_uom_code = uom_code; return c_locale_stod(value); } } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns a datum::PrimeMeridian from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ datum::PrimeMeridianNNPtr AuthorityFactory::createPrimeMeridian(const std::string &code) const { const auto cacheKey(d->authority() + code); { auto pm = d->context()->d->getPrimeMeridianFromCache(cacheKey); if (pm) { return NN_NO_CHECK(pm); } } auto res = d->runWithCodeParam( "SELECT name, longitude, uom_auth_name, uom_code, deprecated FROM " "prime_meridian WHERE " "auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("prime meridian not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &longitude = row[1]; const auto &uom_auth_name = row[2]; const auto &uom_code = row[3]; const bool deprecated = row[4] == "1"; std::string normalized_uom_code(uom_code); const double normalized_value = normalizeMeasure(uom_code, longitude, normalized_uom_code); auto uom = d->createUnitOfMeasure(uom_auth_name, normalized_uom_code); auto props = d->createProperties(code, name, deprecated, {}); auto pm = datum::PrimeMeridian::create( props, common::Angle(normalized_value, uom)); d->context()->d->cache(cacheKey, pm); return pm; } catch (const std::exception &ex) { throw buildFactoryException("prime meridian", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Identify a celestial body from an approximate radius. * * @param semi_major_axis Approximate semi-major axis. * @param tolerance Relative error allowed. * @return celestial body name if one single match found. * @throw FactoryException */ std::string AuthorityFactory::identifyBodyFromSemiMajorAxis(double semi_major_axis, double tolerance) const { auto res = d->run("SELECT name, (ABS(semi_major_axis - ?) / semi_major_axis ) " "AS rel_error FROM celestial_body WHERE rel_error <= ?", {semi_major_axis, tolerance}); if (res.empty()) { throw FactoryException("no match found"); } if (res.size() > 1) { for (const auto &row : res) { if (row[0] != res.front()[0]) { throw FactoryException("more than one match found"); } } } return res.front()[0]; } // --------------------------------------------------------------------------- /** \brief Returns a datum::Ellipsoid from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ datum::EllipsoidNNPtr AuthorityFactory::createEllipsoid(const std::string &code) const { const auto cacheKey(d->authority() + code); { auto ellps = d->context()->d->getEllipsoidFromCache(cacheKey); if (ellps) { return NN_NO_CHECK(ellps); } } auto res = d->runWithCodeParam( "SELECT ellipsoid.name, ellipsoid.semi_major_axis, " "ellipsoid.uom_auth_name, ellipsoid.uom_code, " "ellipsoid.inv_flattening, ellipsoid.semi_minor_axis, " "celestial_body.name AS body_name, ellipsoid.deprecated FROM " "ellipsoid JOIN celestial_body " "ON ellipsoid.celestial_body_auth_name = celestial_body.auth_name AND " "ellipsoid.celestial_body_code = celestial_body.code WHERE " "ellipsoid.auth_name = ? AND ellipsoid.code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("ellipsoid not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &semi_major_axis_str = row[1]; double semi_major_axis = c_locale_stod(semi_major_axis_str); const auto &uom_auth_name = row[2]; const auto &uom_code = row[3]; const auto &inv_flattening_str = row[4]; const auto &semi_minor_axis_str = row[5]; const auto &body = row[6]; const bool deprecated = row[7] == "1"; auto uom = d->createUnitOfMeasure(uom_auth_name, uom_code); auto props = d->createProperties(code, name, deprecated, {}); if (!inv_flattening_str.empty()) { auto ellps = datum::Ellipsoid::createFlattenedSphere( props, common::Length(semi_major_axis, uom), common::Scale(c_locale_stod(inv_flattening_str)), body); d->context()->d->cache(cacheKey, ellps); return ellps; } else if (semi_major_axis_str == semi_minor_axis_str) { auto ellps = datum::Ellipsoid::createSphere( props, common::Length(semi_major_axis, uom), body); d->context()->d->cache(cacheKey, ellps); return ellps; } else { auto ellps = datum::Ellipsoid::createTwoAxis( props, common::Length(semi_major_axis, uom), common::Length(c_locale_stod(semi_minor_axis_str), uom), body); d->context()->d->cache(cacheKey, ellps); return ellps; } } catch (const std::exception &ex) { throw buildFactoryException("ellipsoid", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a datum::GeodeticReferenceFrame from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ datum::GeodeticReferenceFrameNNPtr AuthorityFactory::createGeodeticDatum(const std::string &code) const { datum::GeodeticReferenceFramePtr datum; datum::DatumEnsemblePtr datumEnsemble; constexpr bool turnEnsembleAsDatum = true; createGeodeticDatumOrEnsemble(code, datum, datumEnsemble, turnEnsembleAsDatum); return NN_NO_CHECK(datum); } // --------------------------------------------------------------------------- void AuthorityFactory::createGeodeticDatumOrEnsemble( const std::string &code, datum::GeodeticReferenceFramePtr &outDatum, datum::DatumEnsemblePtr &outDatumEnsemble, bool turnEnsembleAsDatum) const { const auto cacheKey(d->authority() + code); { outDatumEnsemble = d->context()->d->getDatumEnsembleFromCache(cacheKey); if (outDatumEnsemble) { if (!turnEnsembleAsDatum) return; outDatumEnsemble = nullptr; } outDatum = d->context()->d->getGeodeticDatumFromCache(cacheKey); if (outDatum) { return; } } auto res = d->runWithCodeParam( "SELECT name, ellipsoid_auth_name, ellipsoid_code, " "prime_meridian_auth_name, prime_meridian_code, " "publication_date, frame_reference_epoch, " "ensemble_accuracy, anchor, anchor_epoch, deprecated " "FROM geodetic_datum " "WHERE " "auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("geodetic datum not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &ellipsoid_auth_name = row[1]; const auto &ellipsoid_code = row[2]; const auto &prime_meridian_auth_name = row[3]; const auto &prime_meridian_code = row[4]; const auto &publication_date = row[5]; const auto &frame_reference_epoch = row[6]; const auto &ensemble_accuracy = row[7]; const auto &anchor = row[8]; const auto &anchor_epoch = row[9]; const bool deprecated = row[10] == "1"; std::string massagedName = name; if (turnEnsembleAsDatum) { if (name == "World Geodetic System 1984 ensemble") { massagedName = "World Geodetic System 1984"; } else if (name == "European Terrestrial Reference System 1989 ensemble") { massagedName = "European Terrestrial Reference System 1989"; } } auto props = d->createPropertiesSearchUsages("geodetic_datum", code, massagedName, deprecated); if (!turnEnsembleAsDatum && !ensemble_accuracy.empty()) { auto resMembers = d->run("SELECT member_auth_name, member_code FROM " "geodetic_datum_ensemble_member WHERE " "ensemble_auth_name = ? AND ensemble_code = ? " "ORDER BY sequence", {d->authority(), code}); std::vector<datum::DatumNNPtr> members; for (const auto &memberRow : resMembers) { members.push_back( d->createFactory(memberRow[0])->createDatum(memberRow[1])); } auto datumEnsemble = datum::DatumEnsemble::create( props, std::move(members), metadata::PositionalAccuracy::create(ensemble_accuracy)); d->context()->d->cache(cacheKey, datumEnsemble); outDatumEnsemble = datumEnsemble.as_nullable(); } else { auto ellipsoid = d->createFactory(ellipsoid_auth_name) ->createEllipsoid(ellipsoid_code); auto pm = d->createFactory(prime_meridian_auth_name) ->createPrimeMeridian(prime_meridian_code); auto anchorOpt = util::optional<std::string>(); if (!anchor.empty()) anchorOpt = anchor; if (!publication_date.empty()) { props.set("PUBLICATION_DATE", publication_date); } if (!anchor_epoch.empty()) { props.set("ANCHOR_EPOCH", anchor_epoch); } auto datum = frame_reference_epoch.empty() ? datum::GeodeticReferenceFrame::create( props, ellipsoid, anchorOpt, pm) : util::nn_static_pointer_cast< datum::GeodeticReferenceFrame>( datum::DynamicGeodeticReferenceFrame::create( props, ellipsoid, anchorOpt, pm, common::Measure( c_locale_stod(frame_reference_epoch), common::UnitOfMeasure::YEAR), util::optional<std::string>())); d->context()->d->cache(cacheKey, datum); outDatum = datum.as_nullable(); } } catch (const std::exception &ex) { throw buildFactoryException("geodetic reference frame", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a datum::VerticalReferenceFrame from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ datum::VerticalReferenceFrameNNPtr AuthorityFactory::createVerticalDatum(const std::string &code) const { datum::VerticalReferenceFramePtr datum; datum::DatumEnsemblePtr datumEnsemble; constexpr bool turnEnsembleAsDatum = true; createVerticalDatumOrEnsemble(code, datum, datumEnsemble, turnEnsembleAsDatum); return NN_NO_CHECK(datum); } // --------------------------------------------------------------------------- void AuthorityFactory::createVerticalDatumOrEnsemble( const std::string &code, datum::VerticalReferenceFramePtr &outDatum, datum::DatumEnsemblePtr &outDatumEnsemble, bool turnEnsembleAsDatum) const { auto res = d->runWithCodeParam("SELECT name, publication_date, " "frame_reference_epoch, ensemble_accuracy, anchor, " "anchor_epoch, deprecated FROM " "vertical_datum WHERE auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("vertical datum not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &publication_date = row[1]; const auto &frame_reference_epoch = row[2]; const auto &ensemble_accuracy = row[3]; const auto &anchor = row[4]; const auto &anchor_epoch = row[5]; const bool deprecated = row[6] == "1"; auto props = d->createPropertiesSearchUsages("vertical_datum", code, name, deprecated); if (!turnEnsembleAsDatum && !ensemble_accuracy.empty()) { auto resMembers = d->run("SELECT member_auth_name, member_code FROM " "vertical_datum_ensemble_member WHERE " "ensemble_auth_name = ? AND ensemble_code = ? " "ORDER BY sequence", {d->authority(), code}); std::vector<datum::DatumNNPtr> members; for (const auto &memberRow : resMembers) { members.push_back( d->createFactory(memberRow[0])->createDatum(memberRow[1])); } auto datumEnsemble = datum::DatumEnsemble::create( props, std::move(members), metadata::PositionalAccuracy::create(ensemble_accuracy)); outDatumEnsemble = datumEnsemble.as_nullable(); } else { if (!publication_date.empty()) { props.set("PUBLICATION_DATE", publication_date); } if (!anchor_epoch.empty()) { props.set("ANCHOR_EPOCH", anchor_epoch); } if (d->authority() == "ESRI" && starts_with(code, "from_geogdatum_")) { props.set("VERT_DATUM_TYPE", "2002"); } auto anchorOpt = util::optional<std::string>(); if (!anchor.empty()) anchorOpt = anchor; if (frame_reference_epoch.empty()) { outDatum = datum::VerticalReferenceFrame::create(props, anchorOpt) .as_nullable(); } else { outDatum = datum::DynamicVerticalReferenceFrame::create( props, anchorOpt, util::optional<datum::RealizationMethod>(), common::Measure(c_locale_stod(frame_reference_epoch), common::UnitOfMeasure::YEAR), util::optional<std::string>()) .as_nullable(); } } } catch (const std::exception &ex) { throw buildFactoryException("vertical reference frame", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a datum::DatumEnsemble from the specified code. * * @param code Object code allocated by authority. * @param type "geodetic_datum", "vertical_datum" or empty string if unknown * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ datum::DatumEnsembleNNPtr AuthorityFactory::createDatumEnsemble(const std::string &code, const std::string &type) const { auto res = d->run( "SELECT 'geodetic_datum', name, ensemble_accuracy, deprecated FROM " "geodetic_datum WHERE " "auth_name = ? AND code = ? AND ensemble_accuracy IS NOT NULL " "UNION ALL " "SELECT 'vertical_datum', name, ensemble_accuracy, deprecated FROM " "vertical_datum WHERE " "auth_name = ? AND code = ? AND ensemble_accuracy IS NOT NULL", {d->authority(), code, d->authority(), code}); if (res.empty()) { throw NoSuchAuthorityCodeException("datum ensemble not found", d->authority(), code); } for (const auto &row : res) { const std::string &gotType = row[0]; const std::string &name = row[1]; const std::string &ensembleAccuracy = row[2]; const bool deprecated = row[3] == "1"; if (type.empty() || type == gotType) { auto resMembers = d->run("SELECT member_auth_name, member_code FROM " + gotType + "_ensemble_member WHERE " "ensemble_auth_name = ? AND ensemble_code = ? " "ORDER BY sequence", {d->authority(), code}); std::vector<datum::DatumNNPtr> members; for (const auto &memberRow : resMembers) { members.push_back( d->createFactory(memberRow[0])->createDatum(memberRow[1])); } auto props = d->createPropertiesSearchUsages(gotType, code, name, deprecated); return datum::DatumEnsemble::create( props, std::move(members), metadata::PositionalAccuracy::create(ensembleAccuracy)); } } throw NoSuchAuthorityCodeException("datum ensemble not found", d->authority(), code); } // --------------------------------------------------------------------------- /** \brief Returns a datum::Datum from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ datum::DatumNNPtr AuthorityFactory::createDatum(const std::string &code) const { auto res = d->run("SELECT 'geodetic_datum' FROM geodetic_datum WHERE " "auth_name = ? AND code = ? " "UNION ALL SELECT 'vertical_datum' FROM vertical_datum WHERE " "auth_name = ? AND code = ?", {d->authority(), code, d->authority(), code}); if (res.empty()) { throw NoSuchAuthorityCodeException("datum not found", d->authority(), code); } if (res.front()[0] == "geodetic_datum") { return createGeodeticDatum(code); } return createVerticalDatum(code); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static cs::MeridianPtr createMeridian(const std::string &val) { try { const std::string degW(std::string("\xC2\xB0") + "W"); if (ends_with(val, degW)) { return cs::Meridian::create(common::Angle( -c_locale_stod(val.substr(0, val.size() - degW.size())))); } const std::string degE(std::string("\xC2\xB0") + "E"); if (ends_with(val, degE)) { return cs::Meridian::create(common::Angle( c_locale_stod(val.substr(0, val.size() - degE.size())))); } } catch (const std::exception &) { } return nullptr; } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns a cs::CoordinateSystem from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ cs::CoordinateSystemNNPtr AuthorityFactory::createCoordinateSystem(const std::string &code) const { const auto cacheKey(d->authority() + code); { auto cs = d->context()->d->getCoordinateSystemFromCache(cacheKey); if (cs) { return NN_NO_CHECK(cs); } } auto res = d->runWithCodeParam( "SELECT axis.name, abbrev, orientation, uom_auth_name, uom_code, " "cs.type FROM " "axis LEFT JOIN coordinate_system cs ON " "axis.coordinate_system_auth_name = cs.auth_name AND " "axis.coordinate_system_code = cs.code WHERE " "coordinate_system_auth_name = ? AND coordinate_system_code = ? ORDER " "BY coordinate_system_order", code); if (res.empty()) { throw NoSuchAuthorityCodeException("coordinate system not found", d->authority(), code); } const auto &csType = res.front()[5]; std::vector<cs::CoordinateSystemAxisNNPtr> axisList; for (const auto &row : res) { const auto &name = row[0]; const auto &abbrev = row[1]; const auto &orientation = row[2]; const auto &uom_auth_name = row[3]; const auto &uom_code = row[4]; if (uom_auth_name.empty() && csType != CS_TYPE_ORDINAL) { throw FactoryException("no unit of measure for an axis is only " "supported for ordinatal CS"); } auto uom = uom_auth_name.empty() ? common::UnitOfMeasure::NONE : d->createUnitOfMeasure(uom_auth_name, uom_code); auto props = util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, name); const cs::AxisDirection *direction = cs::AxisDirection::valueOf(orientation); cs::MeridianPtr meridian; if (direction == nullptr) { if (orientation == "Geocentre > equator/0" "\xC2\xB0" "E") { direction = &(cs::AxisDirection::GEOCENTRIC_X); } else if (orientation == "Geocentre > equator/90" "\xC2\xB0" "E") { direction = &(cs::AxisDirection::GEOCENTRIC_Y); } else if (orientation == "Geocentre > north pole") { direction = &(cs::AxisDirection::GEOCENTRIC_Z); } else if (starts_with(orientation, "North along ")) { direction = &(cs::AxisDirection::NORTH); meridian = createMeridian(orientation.substr(strlen("North along "))); } else if (starts_with(orientation, "South along ")) { direction = &(cs::AxisDirection::SOUTH); meridian = createMeridian(orientation.substr(strlen("South along "))); } else { throw FactoryException("unknown axis direction: " + orientation); } } axisList.emplace_back(cs::CoordinateSystemAxis::create( props, abbrev, *direction, uom, meridian)); } const auto cacheAndRet = [this, &cacheKey](const cs::CoordinateSystemNNPtr &cs) { d->context()->d->cache(cacheKey, cs); return cs; }; auto props = util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, d->authority()) .set(metadata::Identifier::CODE_KEY, code); if (csType == CS_TYPE_ELLIPSOIDAL) { if (axisList.size() == 2) { return cacheAndRet( cs::EllipsoidalCS::create(props, axisList[0], axisList[1])); } if (axisList.size() == 3) { return cacheAndRet(cs::EllipsoidalCS::create( props, axisList[0], axisList[1], axisList[2])); } throw FactoryException("invalid number of axis for EllipsoidalCS"); } if (csType == CS_TYPE_CARTESIAN) { if (axisList.size() == 2) { return cacheAndRet( cs::CartesianCS::create(props, axisList[0], axisList[1])); } if (axisList.size() == 3) { return cacheAndRet(cs::CartesianCS::create( props, axisList[0], axisList[1], axisList[2])); } throw FactoryException("invalid number of axis for CartesianCS"); } if (csType == CS_TYPE_SPHERICAL) { if (axisList.size() == 2) { return cacheAndRet( cs::SphericalCS::create(props, axisList[0], axisList[1])); } if (axisList.size() == 3) { return cacheAndRet(cs::SphericalCS::create( props, axisList[0], axisList[1], axisList[2])); } throw FactoryException("invalid number of axis for SphericalCS"); } if (csType == CS_TYPE_VERTICAL) { if (axisList.size() == 1) { return cacheAndRet(cs::VerticalCS::create(props, axisList[0])); } throw FactoryException("invalid number of axis for VerticalCS"); } if (csType == CS_TYPE_ORDINAL) { return cacheAndRet(cs::OrdinalCS::create(props, axisList)); } throw FactoryException("unhandled coordinate system type: " + csType); } // --------------------------------------------------------------------------- /** \brief Returns a crs::GeodeticCRS from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ crs::GeodeticCRSNNPtr AuthorityFactory::createGeodeticCRS(const std::string &code) const { return createGeodeticCRS(code, false); } // --------------------------------------------------------------------------- /** \brief Returns a crs::GeographicCRS from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ crs::GeographicCRSNNPtr AuthorityFactory::createGeographicCRS(const std::string &code) const { auto crs(util::nn_dynamic_pointer_cast<crs::GeographicCRS>( createGeodeticCRS(code, true))); if (!crs) { throw NoSuchAuthorityCodeException("geographicCRS not found", d->authority(), code); } return NN_NO_CHECK(crs); } // --------------------------------------------------------------------------- static crs::GeodeticCRSNNPtr cloneWithProps(const crs::GeodeticCRSNNPtr &geodCRS, const util::PropertyMap &props) { auto cs = geodCRS->coordinateSystem(); auto ellipsoidalCS = util::nn_dynamic_pointer_cast<cs::EllipsoidalCS>(cs); if (ellipsoidalCS) { return crs::GeographicCRS::create(props, geodCRS->datum(), geodCRS->datumEnsemble(), NN_NO_CHECK(ellipsoidalCS)); } auto geocentricCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>(cs); if (geocentricCS) { return crs::GeodeticCRS::create(props, geodCRS->datum(), geodCRS->datumEnsemble(), NN_NO_CHECK(geocentricCS)); } return geodCRS; } // --------------------------------------------------------------------------- crs::GeodeticCRSNNPtr AuthorityFactory::createGeodeticCRS(const std::string &code, bool geographicOnly) const { const auto cacheKey(d->authority() + code); auto crs = d->context()->d->getCRSFromCache(cacheKey); if (crs) { auto geogCRS = std::dynamic_pointer_cast<crs::GeodeticCRS>(crs); if (geogCRS) { return NN_NO_CHECK(geogCRS); } throw NoSuchAuthorityCodeException("geodeticCRS not found", d->authority(), code); } std::string sql("SELECT name, type, coordinate_system_auth_name, " "coordinate_system_code, datum_auth_name, datum_code, " "text_definition, deprecated, description FROM " "geodetic_crs WHERE auth_name = ? AND code = ?"); if (geographicOnly) { sql += " AND type in (" GEOG_2D_SINGLE_QUOTED "," GEOG_3D_SINGLE_QUOTED ")"; } auto res = d->runWithCodeParam(sql, code); if (res.empty()) { throw NoSuchAuthorityCodeException("geodeticCRS not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &type = row[1]; const auto &cs_auth_name = row[2]; const auto &cs_code = row[3]; const auto &datum_auth_name = row[4]; const auto &datum_code = row[5]; const auto &text_definition = row[6]; const bool deprecated = row[7] == "1"; const auto &remarks = row[8]; auto props = d->createPropertiesSearchUsages("geodetic_crs", code, name, deprecated, remarks); if (!text_definition.empty()) { DatabaseContext::Private::RecursionDetector detector(d->context()); auto obj = createFromUserInput( pj_add_type_crs_if_needed(text_definition), d->context()); auto geodCRS = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>(obj); if (geodCRS) { auto crsRet = cloneWithProps(NN_NO_CHECK(geodCRS), props); d->context()->d->cache(cacheKey, crsRet); return crsRet; } auto boundCRS = dynamic_cast<const crs::BoundCRS *>(obj.get()); if (boundCRS) { geodCRS = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( boundCRS->baseCRS()); if (geodCRS) { auto newBoundCRS = crs::BoundCRS::create( cloneWithProps(NN_NO_CHECK(geodCRS), props), boundCRS->hubCRS(), boundCRS->transformation()); return NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( newBoundCRS->baseCRSWithCanonicalBoundCRS())); } } throw FactoryException( "text_definition does not define a GeodeticCRS"); } auto cs = d->createFactory(cs_auth_name)->createCoordinateSystem(cs_code); datum::GeodeticReferenceFramePtr datum; datum::DatumEnsemblePtr datumEnsemble; constexpr bool turnEnsembleAsDatum = false; d->createFactory(datum_auth_name) ->createGeodeticDatumOrEnsemble(datum_code, datum, datumEnsemble, turnEnsembleAsDatum); auto ellipsoidalCS = util::nn_dynamic_pointer_cast<cs::EllipsoidalCS>(cs); if ((type == GEOG_2D || type == GEOG_3D) && ellipsoidalCS) { auto crsRet = crs::GeographicCRS::create( props, datum, datumEnsemble, NN_NO_CHECK(ellipsoidalCS)); d->context()->d->cache(cacheKey, crsRet); return crsRet; } auto geocentricCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>(cs); if (type == GEOCENTRIC && geocentricCS) { auto crsRet = crs::GeodeticCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(geocentricCS)); d->context()->d->cache(cacheKey, crsRet); return crsRet; } auto sphericalCS = util::nn_dynamic_pointer_cast<cs::SphericalCS>(cs); if (type == OTHER && sphericalCS) { auto crsRet = crs::GeodeticCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(sphericalCS)); d->context()->d->cache(cacheKey, crsRet); return crsRet; } throw FactoryException("unsupported (type, CS type) for geodeticCRS: " + type + ", " + cs->getWKT2Type(true)); } catch (const std::exception &ex) { throw buildFactoryException("geodeticCRS", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a crs::VerticalCRS from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ crs::VerticalCRSNNPtr AuthorityFactory::createVerticalCRS(const std::string &code) const { const auto cacheKey(d->authority() + code); auto crs = d->context()->d->getCRSFromCache(cacheKey); if (crs) { auto projCRS = std::dynamic_pointer_cast<crs::VerticalCRS>(crs); if (projCRS) { return NN_NO_CHECK(projCRS); } throw NoSuchAuthorityCodeException("verticalCRS not found", d->authority(), code); } auto res = d->runWithCodeParam( "SELECT name, coordinate_system_auth_name, " "coordinate_system_code, datum_auth_name, datum_code, " "deprecated FROM " "vertical_crs WHERE auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("verticalCRS not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &cs_auth_name = row[1]; const auto &cs_code = row[2]; const auto &datum_auth_name = row[3]; const auto &datum_code = row[4]; const bool deprecated = row[5] == "1"; auto cs = d->createFactory(cs_auth_name)->createCoordinateSystem(cs_code); datum::VerticalReferenceFramePtr datum; datum::DatumEnsemblePtr datumEnsemble; constexpr bool turnEnsembleAsDatum = false; d->createFactory(datum_auth_name) ->createVerticalDatumOrEnsemble(datum_code, datum, datumEnsemble, turnEnsembleAsDatum); auto props = d->createPropertiesSearchUsages("vertical_crs", code, name, deprecated); auto verticalCS = util::nn_dynamic_pointer_cast<cs::VerticalCS>(cs); if (verticalCS) { auto crsRet = crs::VerticalCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(verticalCS)); d->context()->d->cache(cacheKey, crsRet); return crsRet; } throw FactoryException("unsupported CS type for verticalCRS: " + cs->getWKT2Type(true)); } catch (const std::exception &ex) { throw buildFactoryException("verticalCRS", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a operation::Conversion from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ operation::ConversionNNPtr AuthorityFactory::createConversion(const std::string &code) const { static const char *sql = "SELECT name, description, " "method_auth_name, method_code, method_name, " "param1_auth_name, param1_code, param1_name, param1_value, " "param1_uom_auth_name, param1_uom_code, " "param2_auth_name, param2_code, param2_name, param2_value, " "param2_uom_auth_name, param2_uom_code, " "param3_auth_name, param3_code, param3_name, param3_value, " "param3_uom_auth_name, param3_uom_code, " "param4_auth_name, param4_code, param4_name, param4_value, " "param4_uom_auth_name, param4_uom_code, " "param5_auth_name, param5_code, param5_name, param5_value, " "param5_uom_auth_name, param5_uom_code, " "param6_auth_name, param6_code, param6_name, param6_value, " "param6_uom_auth_name, param6_uom_code, " "param7_auth_name, param7_code, param7_name, param7_value, " "param7_uom_auth_name, param7_uom_code, " "deprecated FROM conversion WHERE auth_name = ? AND code = ?"; auto res = d->runWithCodeParam(sql, code); if (res.empty()) { try { // Conversions using methods Change of Vertical Unit or // Height Depth Reversal are stored in other_transformation auto op = createCoordinateOperation( code, false /* allowConcatenated */, false /* usePROJAlternativeGridNames */, "other_transformation"); auto conv = util::nn_dynamic_pointer_cast<operation::Conversion>(op); if (conv) { return NN_NO_CHECK(conv); } } catch (const std::exception &) { } throw NoSuchAuthorityCodeException("conversion not found", d->authority(), code); } try { const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &description = row[idx++]; const auto &method_auth_name = row[idx++]; const auto &method_code = row[idx++]; const auto &method_name = row[idx++]; const size_t base_param_idx = idx; std::vector<operation::OperationParameterNNPtr> parameters; std::vector<operation::ParameterValueNNPtr> values; for (size_t i = 0; i < N_MAX_PARAMS; ++i) { const auto &param_auth_name = row[base_param_idx + i * 6 + 0]; if (param_auth_name.empty()) { break; } const auto &param_code = row[base_param_idx + i * 6 + 1]; const auto &param_name = row[base_param_idx + i * 6 + 2]; const auto &param_value = row[base_param_idx + i * 6 + 3]; const auto &param_uom_auth_name = row[base_param_idx + i * 6 + 4]; const auto &param_uom_code = row[base_param_idx + i * 6 + 5]; parameters.emplace_back(operation::OperationParameter::create( util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, param_auth_name) .set(metadata::Identifier::CODE_KEY, param_code) .set(common::IdentifiedObject::NAME_KEY, param_name))); std::string normalized_uom_code(param_uom_code); const double normalized_value = normalizeMeasure( param_uom_code, param_value, normalized_uom_code); auto uom = d->createUnitOfMeasure(param_uom_auth_name, normalized_uom_code); values.emplace_back(operation::ParameterValue::create( common::Measure(normalized_value, uom))); } const bool deprecated = row[base_param_idx + N_MAX_PARAMS * 6] == "1"; auto propConversion = d->createPropertiesSearchUsages( "conversion", code, name, deprecated); if (!description.empty()) propConversion.set(common::IdentifiedObject::REMARKS_KEY, description); auto propMethod = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, method_name); if (!method_auth_name.empty()) { propMethod .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) .set(metadata::Identifier::CODE_KEY, method_code); } return operation::Conversion::create(propConversion, propMethod, parameters, values); } catch (const std::exception &ex) { throw buildFactoryException("conversion", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a crs::ProjectedCRS from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ crs::ProjectedCRSNNPtr AuthorityFactory::createProjectedCRS(const std::string &code) const { const auto cacheKey(d->authority() + code); auto crs = d->context()->d->getCRSFromCache(cacheKey); if (crs) { auto projCRS = std::dynamic_pointer_cast<crs::ProjectedCRS>(crs); if (projCRS) { return NN_NO_CHECK(projCRS); } throw NoSuchAuthorityCodeException("projectedCRS not found", d->authority(), code); } return d->createProjectedCRSEnd(code, d->createProjectedCRSBegin(code)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** Returns the result of the SQL query needed by createProjectedCRSEnd * * The split in two functions is for createFromCoordinateReferenceSystemCodes() * convenience, to avoid throwing exceptions. */ SQLResultSet AuthorityFactory::Private::createProjectedCRSBegin(const std::string &code) { return runWithCodeParam( "SELECT name, coordinate_system_auth_name, " "coordinate_system_code, geodetic_crs_auth_name, geodetic_crs_code, " "conversion_auth_name, conversion_code, " "text_definition, " "deprecated FROM projected_crs WHERE auth_name = ? AND code = ?", code); } // --------------------------------------------------------------------------- /** Build a ProjectedCRS from the result of createProjectedCRSBegin() */ crs::ProjectedCRSNNPtr AuthorityFactory::Private::createProjectedCRSEnd(const std::string &code, const SQLResultSet &res) { const auto cacheKey(authority() + code); if (res.empty()) { throw NoSuchAuthorityCodeException("projectedCRS not found", authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &cs_auth_name = row[1]; const auto &cs_code = row[2]; const auto &geodetic_crs_auth_name = row[3]; const auto &geodetic_crs_code = row[4]; const auto &conversion_auth_name = row[5]; const auto &conversion_code = row[6]; const auto &text_definition = row[7]; const bool deprecated = row[8] == "1"; auto props = createPropertiesSearchUsages("projected_crs", code, name, deprecated); if (!text_definition.empty()) { DatabaseContext::Private::RecursionDetector detector(context()); auto obj = createFromUserInput( pj_add_type_crs_if_needed(text_definition), context()); auto projCRS = dynamic_cast<const crs::ProjectedCRS *>(obj.get()); if (projCRS) { const auto conv = projCRS->derivingConversion(); auto newConv = (conv->nameStr() == "unnamed") ? operation::Conversion::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, name), conv->method(), conv->parameterValues()) : conv; auto crsRet = crs::ProjectedCRS::create( props, projCRS->baseCRS(), newConv, projCRS->coordinateSystem()); context()->d->cache(cacheKey, crsRet); return crsRet; } auto boundCRS = dynamic_cast<const crs::BoundCRS *>(obj.get()); if (boundCRS) { projCRS = dynamic_cast<const crs::ProjectedCRS *>( boundCRS->baseCRS().get()); if (projCRS) { auto newBoundCRS = crs::BoundCRS::create( crs::ProjectedCRS::create(props, projCRS->baseCRS(), projCRS->derivingConversion(), projCRS->coordinateSystem()), boundCRS->hubCRS(), boundCRS->transformation()); return NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::ProjectedCRS>( newBoundCRS->baseCRSWithCanonicalBoundCRS())); } } throw FactoryException( "text_definition does not define a ProjectedCRS"); } auto cs = createFactory(cs_auth_name)->createCoordinateSystem(cs_code); auto baseCRS = createFactory(geodetic_crs_auth_name) ->createGeodeticCRS(geodetic_crs_code); auto conv = createFactory(conversion_auth_name) ->createConversion(conversion_code); if (conv->nameStr() == "unnamed") { conv = conv->shallowClone(); conv->setProperties(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, name)); } auto cartesianCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>(cs); if (cartesianCS) { auto crsRet = crs::ProjectedCRS::create(props, baseCRS, conv, NN_NO_CHECK(cartesianCS)); context()->d->cache(cacheKey, crsRet); return crsRet; } throw FactoryException("unsupported CS type for projectedCRS: " + cs->getWKT2Type(true)); } catch (const std::exception &ex) { throw buildFactoryException("projectedCRS", authority(), code, ex); } } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns a crs::CompoundCRS from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ crs::CompoundCRSNNPtr AuthorityFactory::createCompoundCRS(const std::string &code) const { auto res = d->runWithCodeParam("SELECT name, horiz_crs_auth_name, horiz_crs_code, " "vertical_crs_auth_name, vertical_crs_code, " "deprecated FROM " "compound_crs WHERE auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("compoundCRS not found", d->authority(), code); } try { const auto &row = res.front(); const auto &name = row[0]; const auto &horiz_crs_auth_name = row[1]; const auto &horiz_crs_code = row[2]; const auto &vertical_crs_auth_name = row[3]; const auto &vertical_crs_code = row[4]; const bool deprecated = row[5] == "1"; auto horizCRS = d->createFactory(horiz_crs_auth_name) ->createCoordinateReferenceSystem(horiz_crs_code, false); auto vertCRS = d->createFactory(vertical_crs_auth_name) ->createVerticalCRS(vertical_crs_code); auto props = d->createPropertiesSearchUsages("compound_crs", code, name, deprecated); return crs::CompoundCRS::create( props, std::vector<crs::CRSNNPtr>{std::move(horizCRS), std::move(vertCRS)}); } catch (const std::exception &ex) { throw buildFactoryException("compoundCRS", d->authority(), code, ex); } } // --------------------------------------------------------------------------- /** \brief Returns a crs::CRS from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ crs::CRSNNPtr AuthorityFactory::createCoordinateReferenceSystem( const std::string &code) const { return createCoordinateReferenceSystem(code, true); } //! @cond Doxygen_Suppress crs::CRSNNPtr AuthorityFactory::createCoordinateReferenceSystem(const std::string &code, bool allowCompound) const { const auto cacheKey(d->authority() + code); auto crs = d->context()->d->getCRSFromCache(cacheKey); if (crs) { return NN_NO_CHECK(crs); } if (d->authority() == metadata::Identifier::OGC) { if (code == "AnsiDate") { // Derived from http://www.opengis.net/def/crs/OGC/0/AnsiDate return crs::TemporalCRS::create( util::PropertyMap() // above URL indicates Julian Date" as name... likely wrong .set(common::IdentifiedObject::NAME_KEY, "Ansi Date") .set(metadata::Identifier::CODESPACE_KEY, d->authority()) .set(metadata::Identifier::CODE_KEY, code), datum::TemporalDatum::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "Epoch time for the ANSI date (1-Jan-1601, 00h00 UTC) " "as day 1."), common::DateTime::create("1600-12-31T00:00:00Z"), datum::TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN), cs::TemporalCountCS::create( util::PropertyMap(), cs::CoordinateSystemAxis::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "Time"), "T", cs::AxisDirection::FUTURE, common::UnitOfMeasure("day", 0, UnitOfMeasure::Type::TIME)))); } if (code == "JulianDate") { // Derived from http://www.opengis.net/def/crs/OGC/0/JulianDate return crs::TemporalCRS::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, "Julian Date") .set(metadata::Identifier::CODESPACE_KEY, d->authority()) .set(metadata::Identifier::CODE_KEY, code), datum::TemporalDatum::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "The beginning of the Julian period."), common::DateTime::create("-4714-11-24T12:00:00Z"), datum::TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN), cs::TemporalCountCS::create( util::PropertyMap(), cs::CoordinateSystemAxis::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "Time"), "T", cs::AxisDirection::FUTURE, common::UnitOfMeasure("day", 0, UnitOfMeasure::Type::TIME)))); } if (code == "UnixTime") { // Derived from http://www.opengis.net/def/crs/OGC/0/UnixTime return crs::TemporalCRS::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, "Unix Time") .set(metadata::Identifier::CODESPACE_KEY, d->authority()) .set(metadata::Identifier::CODE_KEY, code), datum::TemporalDatum::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, "Unix epoch"), common::DateTime::create("1970-01-01T00:00:00Z"), datum::TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN), cs::TemporalCountCS::create( util::PropertyMap(), cs::CoordinateSystemAxis::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "Time"), "T", cs::AxisDirection::FUTURE, common::UnitOfMeasure::SECOND))); } if (code == "84") { return createCoordinateReferenceSystem("CRS84", false); } } auto res = d->runWithCodeParam( "SELECT type FROM crs_view WHERE auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("crs not found", d->authority(), code); } const auto &type = res.front()[0]; if (type == GEOG_2D || type == GEOG_3D || type == GEOCENTRIC || type == OTHER) { return createGeodeticCRS(code); } if (type == VERTICAL) { return createVerticalCRS(code); } if (type == PROJECTED) { return createProjectedCRS(code); } if (allowCompound && type == COMPOUND) { return createCompoundCRS(code); } throw FactoryException("unhandled CRS type: " + type); } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns a coordinates::CoordinateMetadata from the specified code. * * @param code Object code allocated by authority. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException * @since 9.4 */ coordinates::CoordinateMetadataNNPtr AuthorityFactory::createCoordinateMetadata(const std::string &code) const { auto res = d->runWithCodeParam( "SELECT crs_auth_name, crs_code, crs_text_definition, coordinate_epoch " "FROM coordinate_metadata WHERE auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("coordinate_metadata not found", d->authority(), code); } try { const auto &row = res.front(); const auto &crs_auth_name = row[0]; const auto &crs_code = row[1]; const auto &crs_text_definition = row[2]; const auto &coordinate_epoch = row[3]; auto l_context = d->context(); DatabaseContext::Private::RecursionDetector detector(l_context); auto crs = !crs_auth_name.empty() ? d->createFactory(crs_auth_name) ->createCoordinateReferenceSystem(crs_code) .as_nullable() : util::nn_dynamic_pointer_cast<crs::CRS>( createFromUserInput(crs_text_definition, l_context)); if (!crs) { throw FactoryException( std::string("cannot build CoordinateMetadata ") + d->authority() + ":" + code + ": cannot build CRS"); } if (coordinate_epoch.empty()) { return coordinates::CoordinateMetadata::create(NN_NO_CHECK(crs)); } else { return coordinates::CoordinateMetadata::create( NN_NO_CHECK(crs), c_locale_stod(coordinate_epoch), l_context.as_nullable()); } } catch (const std::exception &ex) { throw buildFactoryException("CoordinateMetadata", d->authority(), code, ex); } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static util::PropertyMap createMapNameEPSGCode(const std::string &name, int code) { return util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, code); } // --------------------------------------------------------------------------- static operation::OperationParameterNNPtr createOpParamNameEPSGCode(int code) { const char *name = operation::OperationParameter::getNameForEPSGCode(code); assert(name); return operation::OperationParameter::create( createMapNameEPSGCode(name, code)); } static operation::ParameterValueNNPtr createLength(const std::string &value, const UnitOfMeasure &uom) { return operation::ParameterValue::create( common::Length(c_locale_stod(value), uom)); } static operation::ParameterValueNNPtr createAngle(const std::string &value, const UnitOfMeasure &uom) { return operation::ParameterValue::create( common::Angle(c_locale_stod(value), uom)); } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns a operation::CoordinateOperation from the specified code. * * @param code Object code allocated by authority. * @param usePROJAlternativeGridNames Whether PROJ alternative grid names * should be substituted to the official grid names. * @return object. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( const std::string &code, bool usePROJAlternativeGridNames) const { return createCoordinateOperation(code, true, usePROJAlternativeGridNames, std::string()); } operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( const std::string &code, bool allowConcatenated, bool usePROJAlternativeGridNames, const std::string &typeIn) const { std::string type(typeIn); if (type.empty()) { auto res = d->runWithCodeParam( "SELECT type FROM coordinate_operation_with_conversion_view " "WHERE auth_name = ? AND code = ?", code); if (res.empty()) { throw NoSuchAuthorityCodeException("coordinate operation not found", d->authority(), code); } type = res.front()[0]; } if (type == "conversion") { return createConversion(code); } if (type == "helmert_transformation") { auto res = d->runWithCodeParam( "SELECT name, description, " "method_auth_name, method_code, method_name, " "source_crs_auth_name, source_crs_code, target_crs_auth_name, " "target_crs_code, " "accuracy, tx, ty, tz, translation_uom_auth_name, " "translation_uom_code, rx, ry, rz, rotation_uom_auth_name, " "rotation_uom_code, scale_difference, " "scale_difference_uom_auth_name, scale_difference_uom_code, " "rate_tx, rate_ty, rate_tz, rate_translation_uom_auth_name, " "rate_translation_uom_code, rate_rx, rate_ry, rate_rz, " "rate_rotation_uom_auth_name, rate_rotation_uom_code, " "rate_scale_difference, rate_scale_difference_uom_auth_name, " "rate_scale_difference_uom_code, epoch, epoch_uom_auth_name, " "epoch_uom_code, px, py, pz, pivot_uom_auth_name, pivot_uom_code, " "operation_version, deprecated FROM " "helmert_transformation WHERE auth_name = ? AND code = ?", code); if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException( "helmert_transformation not found", d->authority(), code); } try { const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &description = row[idx++]; const auto &method_auth_name = row[idx++]; const auto &method_code = row[idx++]; const auto &method_name = row[idx++]; const auto &source_crs_auth_name = row[idx++]; const auto &source_crs_code = row[idx++]; const auto &target_crs_auth_name = row[idx++]; const auto &target_crs_code = row[idx++]; const auto &accuracy = row[idx++]; const auto &tx = row[idx++]; const auto &ty = row[idx++]; const auto &tz = row[idx++]; const auto &translation_uom_auth_name = row[idx++]; const auto &translation_uom_code = row[idx++]; const auto &rx = row[idx++]; const auto &ry = row[idx++]; const auto &rz = row[idx++]; const auto &rotation_uom_auth_name = row[idx++]; const auto &rotation_uom_code = row[idx++]; const auto &scale_difference = row[idx++]; const auto &scale_difference_uom_auth_name = row[idx++]; const auto &scale_difference_uom_code = row[idx++]; const auto &rate_tx = row[idx++]; const auto &rate_ty = row[idx++]; const auto &rate_tz = row[idx++]; const auto &rate_translation_uom_auth_name = row[idx++]; const auto &rate_translation_uom_code = row[idx++]; const auto &rate_rx = row[idx++]; const auto &rate_ry = row[idx++]; const auto &rate_rz = row[idx++]; const auto &rate_rotation_uom_auth_name = row[idx++]; const auto &rate_rotation_uom_code = row[idx++]; const auto &rate_scale_difference = row[idx++]; const auto &rate_scale_difference_uom_auth_name = row[idx++]; const auto &rate_scale_difference_uom_code = row[idx++]; const auto &epoch = row[idx++]; const auto &epoch_uom_auth_name = row[idx++]; const auto &epoch_uom_code = row[idx++]; const auto &px = row[idx++]; const auto &py = row[idx++]; const auto &pz = row[idx++]; const auto &pivot_uom_auth_name = row[idx++]; const auto &pivot_uom_code = row[idx++]; const auto &operation_version = row[idx++]; const auto &deprecated_str = row[idx++]; const bool deprecated = deprecated_str == "1"; assert(idx == row.size()); auto uom_translation = d->createUnitOfMeasure( translation_uom_auth_name, translation_uom_code); auto uom_epoch = epoch_uom_auth_name.empty() ? common::UnitOfMeasure::NONE : d->createUnitOfMeasure(epoch_uom_auth_name, epoch_uom_code); auto sourceCRS = d->createFactory(source_crs_auth_name) ->createCoordinateReferenceSystem(source_crs_code); auto targetCRS = d->createFactory(target_crs_auth_name) ->createCoordinateReferenceSystem(target_crs_code); std::vector<operation::OperationParameterNNPtr> parameters; std::vector<operation::ParameterValueNNPtr> values; parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION)); values.emplace_back(createLength(tx, uom_translation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION)); values.emplace_back(createLength(ty, uom_translation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION)); values.emplace_back(createLength(tz, uom_translation)); if (!rx.empty()) { // Helmert 7-, 8-, 10- or 15- parameter cases auto uom_rotation = d->createUnitOfMeasure( rotation_uom_auth_name, rotation_uom_code); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_X_AXIS_ROTATION)); values.emplace_back(createAngle(rx, uom_rotation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_Y_AXIS_ROTATION)); values.emplace_back(createAngle(ry, uom_rotation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_Z_AXIS_ROTATION)); values.emplace_back(createAngle(rz, uom_rotation)); auto uom_scale_difference = scale_difference_uom_auth_name.empty() ? common::UnitOfMeasure::NONE : d->createUnitOfMeasure(scale_difference_uom_auth_name, scale_difference_uom_code); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_SCALE_DIFFERENCE)); values.emplace_back(operation::ParameterValue::create( common::Scale(c_locale_stod(scale_difference), uom_scale_difference))); } if (!rate_tx.empty()) { // Helmert 15-parameter auto uom_rate_translation = d->createUnitOfMeasure( rate_translation_uom_auth_name, rate_translation_uom_code); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION)); values.emplace_back( createLength(rate_tx, uom_rate_translation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION)); values.emplace_back( createLength(rate_ty, uom_rate_translation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION)); values.emplace_back( createLength(rate_tz, uom_rate_translation)); auto uom_rate_rotation = d->createUnitOfMeasure( rate_rotation_uom_auth_name, rate_rotation_uom_code); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION)); values.emplace_back(createAngle(rate_rx, uom_rate_rotation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION)); values.emplace_back(createAngle(rate_ry, uom_rate_rotation)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION)); values.emplace_back(createAngle(rate_rz, uom_rate_rotation)); auto uom_rate_scale_difference = d->createUnitOfMeasure(rate_scale_difference_uom_auth_name, rate_scale_difference_uom_code); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE)); values.emplace_back(operation::ParameterValue::create( common::Scale(c_locale_stod(rate_scale_difference), uom_rate_scale_difference))); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_REFERENCE_EPOCH)); values.emplace_back(operation::ParameterValue::create( common::Measure(c_locale_stod(epoch), uom_epoch))); } else if (uom_epoch != common::UnitOfMeasure::NONE) { // Helmert 8-parameter parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_TRANSFORMATION_REFERENCE_EPOCH)); values.emplace_back(operation::ParameterValue::create( common::Measure(c_locale_stod(epoch), uom_epoch))); } else if (!px.empty()) { // Molodensky-Badekas case auto uom_pivot = d->createUnitOfMeasure(pivot_uom_auth_name, pivot_uom_code); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT)); values.emplace_back(createLength(px, uom_pivot)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT)); values.emplace_back(createLength(py, uom_pivot)); parameters.emplace_back(createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_ORDINATE_3_EVAL_POINT)); values.emplace_back(createLength(pz, uom_pivot)); } auto props = d->createPropertiesSearchUsages( type, code, name, deprecated, description); if (!operation_version.empty()) { props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, operation_version); } auto propsMethod = util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) .set(metadata::Identifier::CODE_KEY, method_code) .set(common::IdentifiedObject::NAME_KEY, method_name); std::vector<metadata::PositionalAccuracyNNPtr> accuracies; if (!accuracy.empty()) { accuracies.emplace_back( metadata::PositionalAccuracy::create(accuracy)); } return operation::Transformation::create( props, sourceCRS, targetCRS, nullptr, propsMethod, parameters, values, accuracies); } catch (const std::exception &ex) { throw buildFactoryException("transformation", d->authority(), code, ex); } } if (type == "grid_transformation") { auto res = d->runWithCodeParam( "SELECT name, description, " "method_auth_name, method_code, method_name, " "source_crs_auth_name, source_crs_code, target_crs_auth_name, " "target_crs_code, " "accuracy, grid_param_auth_name, grid_param_code, grid_param_name, " "grid_name, " "grid2_param_auth_name, grid2_param_code, grid2_param_name, " "grid2_name, " "interpolation_crs_auth_name, interpolation_crs_code, " "operation_version, deprecated FROM " "grid_transformation WHERE auth_name = ? AND code = ?", code); if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException("grid_transformation not found", d->authority(), code); } try { const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &description = row[idx++]; const auto &method_auth_name = row[idx++]; const auto &method_code = row[idx++]; const auto &method_name = row[idx++]; const auto &source_crs_auth_name = row[idx++]; const auto &source_crs_code = row[idx++]; const auto &target_crs_auth_name = row[idx++]; const auto &target_crs_code = row[idx++]; const auto &accuracy = row[idx++]; const auto &grid_param_auth_name = row[idx++]; const auto &grid_param_code = row[idx++]; const auto &grid_param_name = row[idx++]; const auto &grid_name = row[idx++]; const auto &grid2_param_auth_name = row[idx++]; const auto &grid2_param_code = row[idx++]; const auto &grid2_param_name = row[idx++]; const auto &grid2_name = row[idx++]; const auto &interpolation_crs_auth_name = row[idx++]; const auto &interpolation_crs_code = row[idx++]; const auto &operation_version = row[idx++]; const auto &deprecated_str = row[idx++]; const bool deprecated = deprecated_str == "1"; assert(idx == row.size()); auto sourceCRS = d->createFactory(source_crs_auth_name) ->createCoordinateReferenceSystem(source_crs_code); auto targetCRS = d->createFactory(target_crs_auth_name) ->createCoordinateReferenceSystem(target_crs_code); auto interpolationCRS = interpolation_crs_auth_name.empty() ? nullptr : d->createFactory(interpolation_crs_auth_name) ->createCoordinateReferenceSystem( interpolation_crs_code) .as_nullable(); std::vector<operation::OperationParameterNNPtr> parameters; std::vector<operation::ParameterValueNNPtr> values; parameters.emplace_back(operation::OperationParameter::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, grid_param_name) .set(metadata::Identifier::CODESPACE_KEY, grid_param_auth_name) .set(metadata::Identifier::CODE_KEY, grid_param_code))); values.emplace_back( operation::ParameterValue::createFilename(grid_name)); if (!grid2_name.empty()) { parameters.emplace_back(operation::OperationParameter::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, grid2_param_name) .set(metadata::Identifier::CODESPACE_KEY, grid2_param_auth_name) .set(metadata::Identifier::CODE_KEY, grid2_param_code))); values.emplace_back( operation::ParameterValue::createFilename(grid2_name)); } auto props = d->createPropertiesSearchUsages( type, code, name, deprecated, description); if (!operation_version.empty()) { props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, operation_version); } auto propsMethod = util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) .set(metadata::Identifier::CODE_KEY, method_code) .set(common::IdentifiedObject::NAME_KEY, method_name); std::vector<metadata::PositionalAccuracyNNPtr> accuracies; if (!accuracy.empty()) { accuracies.emplace_back( metadata::PositionalAccuracy::create(accuracy)); } // A bit fragile to detect the operation type with the method name, // but not worth changing the database model if (starts_with(method_name, "Point motion")) { if (!sourceCRS->isEquivalentTo(targetCRS.get())) { throw operation::InvalidOperation( "source_crs and target_crs should be the same for a " "PointMotionOperation"); } auto pmo = operation::PointMotionOperation::create( props, sourceCRS, propsMethod, parameters, values, accuracies); if (usePROJAlternativeGridNames) { return pmo->substitutePROJAlternativeGridNames( d->context()); } return pmo; } auto transf = operation::Transformation::create( props, sourceCRS, targetCRS, interpolationCRS, propsMethod, parameters, values, accuracies); if (usePROJAlternativeGridNames) { return transf->substitutePROJAlternativeGridNames(d->context()); } return transf; } catch (const std::exception &ex) { throw buildFactoryException("transformation", d->authority(), code, ex); } } if (type == "other_transformation") { std::ostringstream buffer; buffer.imbue(std::locale::classic()); buffer << "SELECT name, description, " "method_auth_name, method_code, method_name, " "source_crs_auth_name, source_crs_code, target_crs_auth_name, " "target_crs_code, " "interpolation_crs_auth_name, interpolation_crs_code, " "operation_version, accuracy, deprecated"; for (size_t i = 1; i <= N_MAX_PARAMS; ++i) { buffer << ", param" << i << "_auth_name"; buffer << ", param" << i << "_code"; buffer << ", param" << i << "_name"; buffer << ", param" << i << "_value"; buffer << ", param" << i << "_uom_auth_name"; buffer << ", param" << i << "_uom_code"; } buffer << " FROM other_transformation " "WHERE auth_name = ? AND code = ?"; auto res = d->runWithCodeParam(buffer.str(), code); if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException("other_transformation not found", d->authority(), code); } try { const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &description = row[idx++]; const auto &method_auth_name = row[idx++]; const auto &method_code = row[idx++]; const auto &method_name = row[idx++]; const auto &source_crs_auth_name = row[idx++]; const auto &source_crs_code = row[idx++]; const auto &target_crs_auth_name = row[idx++]; const auto &target_crs_code = row[idx++]; const auto &interpolation_crs_auth_name = row[idx++]; const auto &interpolation_crs_code = row[idx++]; const auto &operation_version = row[idx++]; const auto &accuracy = row[idx++]; const auto &deprecated_str = row[idx++]; const bool deprecated = deprecated_str == "1"; const size_t base_param_idx = idx; std::vector<operation::OperationParameterNNPtr> parameters; std::vector<operation::ParameterValueNNPtr> values; for (size_t i = 0; i < N_MAX_PARAMS; ++i) { const auto &param_auth_name = row[base_param_idx + i * 6 + 0]; if (param_auth_name.empty()) { break; } const auto &param_code = row[base_param_idx + i * 6 + 1]; const auto &param_name = row[base_param_idx + i * 6 + 2]; const auto &param_value = row[base_param_idx + i * 6 + 3]; const auto &param_uom_auth_name = row[base_param_idx + i * 6 + 4]; const auto &param_uom_code = row[base_param_idx + i * 6 + 5]; parameters.emplace_back(operation::OperationParameter::create( util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, param_auth_name) .set(metadata::Identifier::CODE_KEY, param_code) .set(common::IdentifiedObject::NAME_KEY, param_name))); std::string normalized_uom_code(param_uom_code); const double normalized_value = normalizeMeasure( param_uom_code, param_value, normalized_uom_code); auto uom = d->createUnitOfMeasure(param_uom_auth_name, normalized_uom_code); values.emplace_back(operation::ParameterValue::create( common::Measure(normalized_value, uom))); } idx = base_param_idx + 6 * N_MAX_PARAMS; (void)idx; assert(idx == row.size()); auto sourceCRS = d->createFactory(source_crs_auth_name) ->createCoordinateReferenceSystem(source_crs_code); auto targetCRS = d->createFactory(target_crs_auth_name) ->createCoordinateReferenceSystem(target_crs_code); auto interpolationCRS = interpolation_crs_auth_name.empty() ? nullptr : d->createFactory(interpolation_crs_auth_name) ->createCoordinateReferenceSystem( interpolation_crs_code) .as_nullable(); auto props = d->createPropertiesSearchUsages( type, code, name, deprecated, description); if (!operation_version.empty()) { props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, operation_version); } std::vector<metadata::PositionalAccuracyNNPtr> accuracies; if (!accuracy.empty()) { accuracies.emplace_back( metadata::PositionalAccuracy::create(accuracy)); } if (method_auth_name == "PROJ") { if (method_code == "PROJString") { auto op = operation::SingleOperation::createPROJBased( props, method_name, sourceCRS, targetCRS, accuracies); op->setCRSs(sourceCRS, targetCRS, interpolationCRS); return op; } else if (method_code == "WKT") { auto op = util::nn_dynamic_pointer_cast< operation::CoordinateOperation>( WKTParser().createFromWKT(method_name)); if (!op) { throw FactoryException("WKT string does not express a " "coordinate operation"); } op->setCRSs(sourceCRS, targetCRS, interpolationCRS); return NN_NO_CHECK(op); } } auto propsMethod = util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) .set(metadata::Identifier::CODE_KEY, method_code) .set(common::IdentifiedObject::NAME_KEY, method_name); if (method_auth_name == metadata::Identifier::EPSG) { int method_code_int = std::atoi(method_code.c_str()); if (operation::isAxisOrderReversal(method_code_int) || method_code_int == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT || method_code_int == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR || method_code_int == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { auto op = operation::Conversion::create(props, propsMethod, parameters, values); op->setCRSs(sourceCRS, targetCRS, interpolationCRS); return op; } } return operation::Transformation::create( props, sourceCRS, targetCRS, interpolationCRS, propsMethod, parameters, values, accuracies); } catch (const std::exception &ex) { throw buildFactoryException("transformation", d->authority(), code, ex); } } if (allowConcatenated && type == "concatenated_operation") { auto res = d->runWithCodeParam( "SELECT name, description, " "source_crs_auth_name, source_crs_code, " "target_crs_auth_name, target_crs_code, " "accuracy, " "operation_version, deprecated FROM " "concatenated_operation WHERE auth_name = ? AND code = ?", code); if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException( "concatenated_operation not found", d->authority(), code); } auto resSteps = d->runWithCodeParam( "SELECT step_auth_name, step_code FROM " "concatenated_operation_step WHERE operation_auth_name = ? " "AND operation_code = ? ORDER BY step_number", code); try { const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &description = row[idx++]; const auto &source_crs_auth_name = row[idx++]; const auto &source_crs_code = row[idx++]; const auto &target_crs_auth_name = row[idx++]; const auto &target_crs_code = row[idx++]; const auto &accuracy = row[idx++]; const auto &operation_version = row[idx++]; const auto &deprecated_str = row[idx++]; const bool deprecated = deprecated_str == "1"; std::vector<operation::CoordinateOperationNNPtr> operations; for (const auto &rowStep : resSteps) { const auto &step_auth_name = rowStep[0]; const auto &step_code = rowStep[1]; operations.push_back( d->createFactory(step_auth_name) ->createCoordinateOperation(step_code, false, usePROJAlternativeGridNames, std::string())); } operation::ConcatenatedOperation::fixStepsDirection( d->createFactory(source_crs_auth_name) ->createCoordinateReferenceSystem(source_crs_code), d->createFactory(target_crs_auth_name) ->createCoordinateReferenceSystem(target_crs_code), operations, d->context()); auto props = d->createPropertiesSearchUsages( type, code, name, deprecated, description); if (!operation_version.empty()) { props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, operation_version); } std::vector<metadata::PositionalAccuracyNNPtr> accuracies; if (!accuracy.empty()) { accuracies.emplace_back( metadata::PositionalAccuracy::create(accuracy)); } else { // Try to compute a reasonable accuracy from the members double totalAcc = -1; try { for (const auto &op : operations) { auto accs = op->coordinateOperationAccuracies(); if (accs.size() == 1) { double acc = c_locale_stod(accs[0]->value()); if (totalAcc < 0) { totalAcc = acc; } else { totalAcc += acc; } } else if (dynamic_cast<const operation::Conversion *>( op.get())) { // A conversion is perfectly accurate. if (totalAcc < 0) { totalAcc = 0; } } else { totalAcc = -1; break; } } if (totalAcc >= 0) { accuracies.emplace_back( metadata::PositionalAccuracy::create( toString(totalAcc))); } } catch (const std::exception &) { } } return operation::ConcatenatedOperation::create(props, operations, accuracies); } catch (const std::exception &ex) { throw buildFactoryException("transformation", d->authority(), code, ex); } } throw FactoryException("unhandled coordinate operation type: " + type); } // --------------------------------------------------------------------------- /** \brief Returns a list operation::CoordinateOperation between two CRS. * * The list is ordered with preferred operations first. No attempt is made * at inferring operations that are not explicitly in the database. * * Deprecated operations are rejected. * * @param sourceCRSCode Source CRS code allocated by authority. * @param targetCRSCode Source CRS code allocated by authority. * @return list of coordinate operations * @throw NoSuchAuthorityCodeException * @throw FactoryException */ std::vector<operation::CoordinateOperationNNPtr> AuthorityFactory::createFromCoordinateReferenceSystemCodes( const std::string &sourceCRSCode, const std::string &targetCRSCode) const { return createFromCoordinateReferenceSystemCodes( d->authority(), sourceCRSCode, d->authority(), targetCRSCode, false, false, false, false); } // --------------------------------------------------------------------------- /** \brief Returns a list of geoid models available for that crs * * The list includes the geoid models connected directly with the crs, * or via "Height Depth Reversal" or "Change of Vertical Unit" transformations * * @param code crs code allocated by authority. * @return list of geoid model names * @throw FactoryException */ std::list<std::string> AuthorityFactory::getGeoidModels(const std::string &code) const { ListOfParams params; std::string sql; sql += "SELECT DISTINCT GM0.name " " FROM geoid_model GM0 " "INNER JOIN grid_transformation GT0 " " ON GT0.code = GM0.operation_code " " AND GT0.auth_name = GM0.operation_auth_name " " AND GT0.target_crs_code = ? "; params.emplace_back(code); if (d->hasAuthorityRestriction()) { sql += " AND GT0.target_crs_auth_name = ? "; params.emplace_back(d->authority()); } /// The second part of the query is for CRSs that use that geoid model via /// Height Depth Reversal (EPSG:1068) or Change of Vertical Unit (EPSG:1069) sql += "UNION " "SELECT DISTINCT GM0.name " " FROM geoid_model GM0 " "INNER JOIN grid_transformation GT1 " " ON GT1.code = GM0.operation_code " " AND GT1.auth_name = GM0.operation_auth_name " "INNER JOIN other_transformation OT1 " " ON OT1.source_crs_code = GT1.target_crs_code " " AND OT1.source_crs_auth_name = GT1.target_crs_auth_name " " AND OT1.method_auth_name = 'EPSG' " " AND OT1.method_code IN (1068, 1069, 1104) " " AND OT1.target_crs_code = ? "; params.emplace_back(code); if (d->hasAuthorityRestriction()) { sql += " AND OT1.target_crs_auth_name = ? "; params.emplace_back(d->authority()); } /// The third part of the query is for CRSs that use that geoid model via /// other_transformation table twice, like transforming depth and feet sql += "UNION " "SELECT DISTINCT GM0.name " " FROM geoid_model GM0 " "INNER JOIN grid_transformation GT1 " " ON GT1.code = GM0.operation_code " " AND GT1.auth_name = GM0.operation_auth_name " "INNER JOIN other_transformation OT1 " " ON OT1.source_crs_code = GT1.target_crs_code " " AND OT1.source_crs_auth_name = GT1.target_crs_auth_name " " AND OT1.method_auth_name = 'EPSG' " " AND OT1.method_code IN (1068, 1069, 1104) " "INNER JOIN other_transformation OT2 " " ON OT2.source_crs_code = OT1.target_crs_code " " AND OT2.source_crs_auth_name = OT1.target_crs_auth_name " " AND OT2.method_code IN (1068, 1069, 1104) " " AND OT2.target_crs_code = ? "; params.emplace_back(code); if (d->hasAuthorityRestriction()) { sql += " AND OT2.target_crs_auth_name = ? "; params.emplace_back(d->authority()); } sql += " ORDER BY 1 "; auto sqlRes = d->run(sql, params); std::list<std::string> res; for (const auto &row : sqlRes) { res.push_back(row[0]); } return res; } // --------------------------------------------------------------------------- /** \brief Returns a list operation::CoordinateOperation between two CRS. * * The list is ordered with preferred operations first. No attempt is made * at inferring operations that are not explicitly in the database (see * createFromCRSCodesWithIntermediates() for that), and only * source -> target operations are searched (i.e. if target -> source is * present, you need to call this method with the arguments reversed, and apply * the reverse transformations). * * Deprecated operations are rejected. * * If getAuthority() returns empty, then coordinate operations from all * authorities are considered. * * @param sourceCRSAuthName Authority name of sourceCRSCode * @param sourceCRSCode Source CRS code allocated by authority * sourceCRSAuthName. * @param targetCRSAuthName Authority name of targetCRSCode * @param targetCRSCode Source CRS code allocated by authority * targetCRSAuthName. * @param usePROJAlternativeGridNames Whether PROJ alternative grid names * should be substituted to the official grid names. * @param discardIfMissingGrid Whether coordinate operations that reference * missing grids should be removed from the result set. * @param considerKnownGridsAsAvailable Whether known grids should be considered * as available (typically when network is enabled). * @param discardSuperseded Whether coordinate operations that are superseded * (but not deprecated) should be removed from the result set. * @param tryReverseOrder whether to search in the reverse order too (and thus * inverse results found that way) * @param reportOnlyIntersectingTransformations if intersectingExtent1 and * intersectingExtent2 should be honored in a strict way. * @param intersectingExtent1 Optional extent that the resulting operations * must intersect. * @param intersectingExtent2 Optional extent that the resulting operations * must intersect. * @return list of coordinate operations * @throw NoSuchAuthorityCodeException * @throw FactoryException */ std::vector<operation::CoordinateOperationNNPtr> AuthorityFactory::createFromCoordinateReferenceSystemCodes( const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, const std::string &targetCRSAuthName, const std::string &targetCRSCode, bool usePROJAlternativeGridNames, bool discardIfMissingGrid, bool considerKnownGridsAsAvailable, bool discardSuperseded, bool tryReverseOrder, bool reportOnlyIntersectingTransformations, const metadata::ExtentPtr &intersectingExtent1, const metadata::ExtentPtr &intersectingExtent2) const { auto cacheKey(d->authority()); cacheKey += sourceCRSAuthName.empty() ? "{empty}" : sourceCRSAuthName; cacheKey += sourceCRSCode; cacheKey += targetCRSAuthName.empty() ? "{empty}" : targetCRSAuthName; cacheKey += targetCRSCode; cacheKey += (usePROJAlternativeGridNames ? '1' : '0'); cacheKey += (discardIfMissingGrid ? '1' : '0'); cacheKey += (considerKnownGridsAsAvailable ? '1' : '0'); cacheKey += (discardSuperseded ? '1' : '0'); cacheKey += (tryReverseOrder ? '1' : '0'); cacheKey += (reportOnlyIntersectingTransformations ? '1' : '0'); for (const auto &extent : {intersectingExtent1, intersectingExtent2}) { if (extent) { const auto &geogExtent = extent->geographicElements(); if (geogExtent.size() == 1) { auto bbox = dynamic_cast<const metadata::GeographicBoundingBox *>( geogExtent[0].get()); if (bbox) { cacheKey += toString(bbox->southBoundLatitude()); cacheKey += toString(bbox->westBoundLongitude()); cacheKey += toString(bbox->northBoundLatitude()); cacheKey += toString(bbox->eastBoundLongitude()); } } } } std::vector<operation::CoordinateOperationNNPtr> list; if (d->context()->d->getCRSToCRSCoordOpFromCache(cacheKey, list)) { return list; } // Check if sourceCRS would be the base of a ProjectedCRS targetCRS // In which case use the conversion of the ProjectedCRS if (!targetCRSAuthName.empty()) { auto targetFactory = d->createFactory(targetCRSAuthName); const auto cacheKeyProjectedCRS(targetFactory->d->authority() + targetCRSCode); auto crs = targetFactory->d->context()->d->getCRSFromCache( cacheKeyProjectedCRS); crs::ProjectedCRSPtr targetProjCRS; if (crs) { targetProjCRS = std::dynamic_pointer_cast<crs::ProjectedCRS>(crs); } else { const auto sqlRes = targetFactory->d->createProjectedCRSBegin(targetCRSCode); if (!sqlRes.empty()) { try { targetProjCRS = targetFactory->d ->createProjectedCRSEnd(targetCRSCode, sqlRes) .as_nullable(); } catch (const std::exception &) { } } } if (targetProjCRS) { const auto &baseIds = targetProjCRS->baseCRS()->identifiers(); if (sourceCRSAuthName.empty() || (!baseIds.empty() && *(baseIds.front()->codeSpace()) == sourceCRSAuthName && baseIds.front()->code() == sourceCRSCode)) { bool ok = true; auto conv = targetProjCRS->derivingConversion(); if (d->hasAuthorityRestriction()) { ok = *(conv->identifiers().front()->codeSpace()) == d->authority(); } if (ok) { list.emplace_back(conv); d->context()->d->cache(cacheKey, list); return list; } } } } std::string sql; if (discardSuperseded) { sql = "SELECT cov.source_crs_auth_name, cov.source_crs_code, " "cov.target_crs_auth_name, cov.target_crs_code, " "cov.auth_name, cov.code, cov.table_name, " "extent.south_lat, extent.west_lon, extent.north_lat, " "extent.east_lon, " "ss.replacement_auth_name, ss.replacement_code, " "(gt.auth_name IS NOT NULL) AS replacement_is_grid_transform, " "(ga.proj_grid_name IS NOT NULL) AS replacement_is_known_grid " "FROM " "coordinate_operation_view cov " "JOIN usage ON " "usage.object_table_name = cov.table_name AND " "usage.object_auth_name = cov.auth_name AND " "usage.object_code = cov.code " "JOIN extent " "ON extent.auth_name = usage.extent_auth_name AND " "extent.code = usage.extent_code " "LEFT JOIN supersession ss ON " "ss.superseded_table_name = cov.table_name AND " "ss.superseded_auth_name = cov.auth_name AND " "ss.superseded_code = cov.code AND " "ss.superseded_table_name = ss.replacement_table_name AND " "ss.same_source_target_crs = 1 " "LEFT JOIN grid_transformation gt ON " "gt.auth_name = ss.replacement_auth_name AND " "gt.code = ss.replacement_code " "LEFT JOIN grid_alternatives ga ON " "ga.original_grid_name = gt.grid_name " "WHERE "; } else { sql = "SELECT source_crs_auth_name, source_crs_code, " "target_crs_auth_name, target_crs_code, " "cov.auth_name, cov.code, cov.table_name, " "extent.south_lat, extent.west_lon, extent.north_lat, " "extent.east_lon " "FROM " "coordinate_operation_view cov " "JOIN usage ON " "usage.object_table_name = cov.table_name AND " "usage.object_auth_name = cov.auth_name AND " "usage.object_code = cov.code " "JOIN extent " "ON extent.auth_name = usage.extent_auth_name AND " "extent.code = usage.extent_code " "WHERE "; } ListOfParams params; if (!sourceCRSAuthName.empty() && !targetCRSAuthName.empty()) { if (tryReverseOrder) { sql += "((cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " "AND " "cov.target_crs_auth_name = ? AND cov.target_crs_code = ?) " "OR " "(cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " "AND " "cov.target_crs_auth_name = ? AND cov.target_crs_code = ?)) " "AND "; params.emplace_back(sourceCRSAuthName); params.emplace_back(sourceCRSCode); params.emplace_back(targetCRSAuthName); params.emplace_back(targetCRSCode); params.emplace_back(targetCRSAuthName); params.emplace_back(targetCRSCode); params.emplace_back(sourceCRSAuthName); params.emplace_back(sourceCRSCode); } else { sql += "cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " "AND " "cov.target_crs_auth_name = ? AND cov.target_crs_code = ? " "AND "; params.emplace_back(sourceCRSAuthName); params.emplace_back(sourceCRSCode); params.emplace_back(targetCRSAuthName); params.emplace_back(targetCRSCode); } } else if (!sourceCRSAuthName.empty()) { if (tryReverseOrder) { sql += "((cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " ")OR " "(cov.target_crs_auth_name = ? AND cov.target_crs_code = ?))" " AND "; params.emplace_back(sourceCRSAuthName); params.emplace_back(sourceCRSCode); params.emplace_back(sourceCRSAuthName); params.emplace_back(sourceCRSCode); } else { sql += "cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " "AND "; params.emplace_back(sourceCRSAuthName); params.emplace_back(sourceCRSCode); } } else if (!targetCRSAuthName.empty()) { if (tryReverseOrder) { sql += "((cov.source_crs_auth_name = ? AND cov.source_crs_code = ?)" " OR " "(cov.target_crs_auth_name = ? AND cov.target_crs_code = ?))" " AND "; params.emplace_back(targetCRSAuthName); params.emplace_back(targetCRSCode); params.emplace_back(targetCRSAuthName); params.emplace_back(targetCRSCode); } else { sql += "cov.target_crs_auth_name = ? AND cov.target_crs_code = ? " "AND "; params.emplace_back(targetCRSAuthName); params.emplace_back(targetCRSCode); } } sql += "cov.deprecated = 0"; if (d->hasAuthorityRestriction()) { sql += " AND cov.auth_name = ?"; params.emplace_back(d->authority()); } sql += " ORDER BY pseudo_area_from_swne(south_lat, west_lon, north_lat, " "east_lon) DESC, " "(CASE WHEN cov.accuracy is NULL THEN 1 ELSE 0 END), cov.accuracy"; auto res = d->run(sql, params); std::set<std::pair<std::string, std::string>> setTransf; if (discardSuperseded) { for (const auto &row : res) { const auto &auth_name = row[4]; const auto &code = row[5]; setTransf.insert( std::pair<std::string, std::string>(auth_name, code)); } } // Do a pass to determine if there are transformations that intersect // intersectingExtent1 & intersectingExtent2 std::vector<bool> intersectingTransformations; intersectingTransformations.resize(res.size()); bool hasIntersectingTransformations = false; size_t i = 0; for (const auto &row : res) { size_t thisI = i; ++i; if (discardSuperseded) { const auto &replacement_auth_name = row[11]; const auto &replacement_code = row[12]; const bool replacement_is_grid_transform = row[13] == "1"; const bool replacement_is_known_grid = row[14] == "1"; if (!replacement_auth_name.empty() && // Ignore supersession if the replacement uses a unknown grid !(replacement_is_grid_transform && !replacement_is_known_grid) && setTransf.find(std::pair<std::string, std::string>( replacement_auth_name, replacement_code)) != setTransf.end()) { // Skip transformations that are superseded by others that got // returned in the result set. continue; } } bool intersecting = true; try { double south_lat = c_locale_stod(row[7]); double west_lon = c_locale_stod(row[8]); double north_lat = c_locale_stod(row[9]); double east_lon = c_locale_stod(row[10]); auto transf_extent = metadata::Extent::createFromBBOX( west_lon, south_lat, east_lon, north_lat); for (const auto &extent : {intersectingExtent1, intersectingExtent2}) { if (extent) { if (!transf_extent->intersects(NN_NO_CHECK(extent))) { intersecting = false; break; } } } } catch (const std::exception &) { } intersectingTransformations[thisI] = intersecting; if (intersecting) hasIntersectingTransformations = true; } // If there are intersecting transformations, then only report those ones // If there are no intersecting transformations, report all of them // This is for the "projinfo -s EPSG:32631 -t EPSG:2171" use case where we // still want to be able to use the Pulkovo datum shift if EPSG:32631 // coordinates are used i = 0; for (const auto &row : res) { size_t thisI = i; ++i; if ((hasIntersectingTransformations || reportOnlyIntersectingTransformations) && !intersectingTransformations[thisI]) { continue; } if (discardSuperseded) { const auto &replacement_auth_name = row[11]; const auto &replacement_code = row[12]; const bool replacement_is_grid_transform = row[13] == "1"; const bool replacement_is_known_grid = row[14] == "1"; if (!replacement_auth_name.empty() && // Ignore supersession if the replacement uses a unknown grid !(replacement_is_grid_transform && !replacement_is_known_grid) && setTransf.find(std::pair<std::string, std::string>( replacement_auth_name, replacement_code)) != setTransf.end()) { // Skip transformations that are superseded by others that got // returned in the result set. continue; } } const auto &source_crs_auth_name = row[0]; const auto &source_crs_code = row[1]; const auto &target_crs_auth_name = row[2]; const auto &target_crs_code = row[3]; const auto &auth_name = row[4]; const auto &code = row[5]; const auto &table_name = row[6]; try { auto op = d->createFactory(auth_name)->createCoordinateOperation( code, true, usePROJAlternativeGridNames, table_name); if (tryReverseOrder && (!sourceCRSAuthName.empty() ? (source_crs_auth_name != sourceCRSAuthName || source_crs_code != sourceCRSCode) : (target_crs_auth_name != targetCRSAuthName || target_crs_code != targetCRSCode))) { op = op->inverse(); } if (!discardIfMissingGrid || !d->rejectOpDueToMissingGrid(op, considerKnownGridsAsAvailable)) { list.emplace_back(op); } } catch (const std::exception &e) { // Mostly for debugging purposes when using an inconsistent // database if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); } else { throw; } } } d->context()->d->cache(cacheKey, list); return list; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool useIrrelevantPivot(const operation::CoordinateOperationNNPtr &op, const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, const std::string &targetCRSAuthName, const std::string &targetCRSCode) { auto concat = dynamic_cast<const operation::ConcatenatedOperation *>(op.get()); if (!concat) { return false; } auto ops = concat->operations(); for (size_t i = 0; i + 1 < ops.size(); i++) { auto targetCRS = ops[i]->targetCRS(); if (targetCRS) { const auto &ids = targetCRS->identifiers(); if (ids.size() == 1 && ((*ids[0]->codeSpace() == sourceCRSAuthName && ids[0]->code() == sourceCRSCode) || (*ids[0]->codeSpace() == targetCRSAuthName && ids[0]->code() == targetCRSCode))) { return true; } } } return false; } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns a list operation::CoordinateOperation between two CRS, * using intermediate codes. * * The list is ordered with preferred operations first. * * Deprecated operations are rejected. * * The method will take care of considering all potential combinations (i.e. * contrary to createFromCoordinateReferenceSystemCodes(), you do not need to * call it with sourceCRS and targetCRS switched) * * If getAuthority() returns empty, then coordinate operations from all * authorities are considered. * * @param sourceCRSAuthName Authority name of sourceCRSCode * @param sourceCRSCode Source CRS code allocated by authority * sourceCRSAuthName. * @param targetCRSAuthName Authority name of targetCRSCode * @param targetCRSCode Source CRS code allocated by authority * targetCRSAuthName. * @param usePROJAlternativeGridNames Whether PROJ alternative grid names * should be substituted to the official grid names. * @param discardIfMissingGrid Whether coordinate operations that reference * missing grids should be removed from the result set. * @param considerKnownGridsAsAvailable Whether known grids should be considered * as available (typically when network is enabled). * @param discardSuperseded Whether coordinate operations that are superseded * (but not deprecated) should be removed from the result set. * @param intermediateCRSAuthCodes List of (auth_name, code) of CRS that can be * used as potential intermediate CRS. If the list is empty, the database will * be used to find common CRS in operations involving both the source and * target CRS. * @param allowedIntermediateObjectType Restrict the type of the intermediate * object considered. * Only ObjectType::CRS and ObjectType::GEOGRAPHIC_CRS supported currently * @param allowedAuthorities One or several authority name allowed for the two * coordinate operations that are going to be searched. When this vector is * no empty, it overrides the authority of this object. This is useful for * example when the coordinate operations to chain belong to two different * allowed authorities. * @param intersectingExtent1 Optional extent that the resulting operations * must intersect. * @param intersectingExtent2 Optional extent that the resulting operations * must intersect. * @return list of coordinate operations * @throw NoSuchAuthorityCodeException * @throw FactoryException */ std::vector<operation::CoordinateOperationNNPtr> AuthorityFactory::createFromCRSCodesWithIntermediates( const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, const std::string &targetCRSAuthName, const std::string &targetCRSCode, bool usePROJAlternativeGridNames, bool discardIfMissingGrid, bool considerKnownGridsAsAvailable, bool discardSuperseded, const std::vector<std::pair<std::string, std::string>> &intermediateCRSAuthCodes, ObjectType allowedIntermediateObjectType, const std::vector<std::string> &allowedAuthorities, const metadata::ExtentPtr &intersectingExtent1, const metadata::ExtentPtr &intersectingExtent2) const { std::vector<operation::CoordinateOperationNNPtr> listTmp; if (sourceCRSAuthName == targetCRSAuthName && sourceCRSCode == targetCRSCode) { return listTmp; } const auto CheckIfHasOperations = [=](const std::string &auth_name, const std::string &code) { return !(d->run("SELECT 1 FROM coordinate_operation_view WHERE " "(source_crs_auth_name = ? AND source_crs_code = ?) OR " "(target_crs_auth_name = ? AND target_crs_code = ?)", {auth_name, code, auth_name, code}) .empty()); }; // If the source or target CRS are not the source or target of an operation, // do not run the next costly requests. if (!CheckIfHasOperations(sourceCRSAuthName, sourceCRSCode) || !CheckIfHasOperations(targetCRSAuthName, targetCRSCode)) { return listTmp; } const std::string sqlProlog( discardSuperseded ? "SELECT v1.table_name as table1, " "v1.auth_name AS auth_name1, v1.code AS code1, " "v1.accuracy AS accuracy1, " "v2.table_name as table2, " "v2.auth_name AS auth_name2, v2.code AS code2, " "v2.accuracy as accuracy2, " "a1.south_lat AS south_lat1, " "a1.west_lon AS west_lon1, " "a1.north_lat AS north_lat1, " "a1.east_lon AS east_lon1, " "a2.south_lat AS south_lat2, " "a2.west_lon AS west_lon2, " "a2.north_lat AS north_lat2, " "a2.east_lon AS east_lon2, " "ss1.replacement_auth_name AS replacement_auth_name1, " "ss1.replacement_code AS replacement_code1, " "ss2.replacement_auth_name AS replacement_auth_name2, " "ss2.replacement_code AS replacement_code2 " "FROM coordinate_operation_view v1 " "JOIN coordinate_operation_view v2 " : "SELECT v1.table_name as table1, " "v1.auth_name AS auth_name1, v1.code AS code1, " "v1.accuracy AS accuracy1, " "v2.table_name as table2, " "v2.auth_name AS auth_name2, v2.code AS code2, " "v2.accuracy as accuracy2, " "a1.south_lat AS south_lat1, " "a1.west_lon AS west_lon1, " "a1.north_lat AS north_lat1, " "a1.east_lon AS east_lon1, " "a2.south_lat AS south_lat2, " "a2.west_lon AS west_lon2, " "a2.north_lat AS north_lat2, " "a2.east_lon AS east_lon2 " "FROM coordinate_operation_view v1 " "JOIN coordinate_operation_view v2 "); const std::string joinSupersession( "LEFT JOIN supersession ss1 ON " "ss1.superseded_table_name = v1.table_name AND " "ss1.superseded_auth_name = v1.auth_name AND " "ss1.superseded_code = v1.code AND " "ss1.superseded_table_name = ss1.replacement_table_name AND " "ss1.same_source_target_crs = 1 " "LEFT JOIN supersession ss2 ON " "ss2.superseded_table_name = v2.table_name AND " "ss2.superseded_auth_name = v2.auth_name AND " "ss2.superseded_code = v2.code AND " "ss2.superseded_table_name = ss2.replacement_table_name AND " "ss2.same_source_target_crs = 1 "); const std::string joinArea( (discardSuperseded ? joinSupersession : std::string()) + "JOIN usage u1 ON " "u1.object_table_name = v1.table_name AND " "u1.object_auth_name = v1.auth_name AND " "u1.object_code = v1.code " "JOIN extent a1 " "ON a1.auth_name = u1.extent_auth_name AND " "a1.code = u1.extent_code " "JOIN usage u2 ON " "u2.object_table_name = v2.table_name AND " "u2.object_auth_name = v2.auth_name AND " "u2.object_code = v2.code " "JOIN extent a2 " "ON a2.auth_name = u2.extent_auth_name AND " "a2.code = u2.extent_code "); const std::string orderBy( "ORDER BY (CASE WHEN accuracy1 is NULL THEN 1 ELSE 0 END) + " "(CASE WHEN accuracy2 is NULL THEN 1 ELSE 0 END), " "accuracy1 + accuracy2"); // Case (source->intermediate) and (intermediate->target) std::string sql( sqlProlog + "ON v1.target_crs_auth_name = v2.source_crs_auth_name " "AND v1.target_crs_code = v2.source_crs_code " + joinArea + "WHERE v1.source_crs_auth_name = ? AND v1.source_crs_code = ? " "AND v2.target_crs_auth_name = ? AND v2.target_crs_code = ? "); std::string minDate; std::string criterionOnIntermediateCRS; if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { auto sourceCRS = d->createFactory(sourceCRSAuthName) ->createGeodeticCRS(sourceCRSCode); auto targetCRS = d->createFactory(targetCRSAuthName) ->createGeodeticCRS(targetCRSCode); const auto &sourceDatum = sourceCRS->datum(); const auto &targetDatum = targetCRS->datum(); if (sourceDatum && sourceDatum->publicationDate().has_value() && targetDatum && targetDatum->publicationDate().has_value()) { const auto sourceDate(sourceDatum->publicationDate()->toString()); const auto targetDate(targetDatum->publicationDate()->toString()); minDate = std::min(sourceDate, targetDate); // Check that the datum of the intermediateCRS has a publication // date most recent that the one of the source and the target CRS // Except when using the usual WGS84 pivot which happens to have a // NULL publication date. criterionOnIntermediateCRS = "AND EXISTS(SELECT 1 FROM geodetic_crs x " "JOIN geodetic_datum y " "ON " "y.auth_name = x.datum_auth_name AND " "y.code = x.datum_code " "WHERE " "x.auth_name = v1.target_crs_auth_name AND " "x.code = v1.target_crs_code AND " "x.type IN ('geographic 2D', 'geographic 3D') AND " "(y.publication_date IS NULL OR " "(y.publication_date >= '" + minDate + "'))) "; } else { criterionOnIntermediateCRS = "AND EXISTS(SELECT 1 FROM geodetic_crs x WHERE " "x.auth_name = v1.target_crs_auth_name AND " "x.code = v1.target_crs_code AND " "x.type IN ('geographic 2D', 'geographic 3D')) "; } sql += criterionOnIntermediateCRS; } auto params = ListOfParams{sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode}; std::string additionalWhere( "AND v1.deprecated = 0 AND v2.deprecated = 0 " "AND intersects_bbox(south_lat1, west_lon1, north_lat1, east_lon1, " "south_lat2, west_lon2, north_lat2, east_lon2) = 1 "); if (!allowedAuthorities.empty()) { additionalWhere += "AND v1.auth_name IN ("; for (size_t i = 0; i < allowedAuthorities.size(); i++) { if (i > 0) additionalWhere += ','; additionalWhere += '?'; } additionalWhere += ") AND v2.auth_name IN ("; for (size_t i = 0; i < allowedAuthorities.size(); i++) { if (i > 0) additionalWhere += ','; additionalWhere += '?'; } additionalWhere += ')'; for (const auto &allowedAuthority : allowedAuthorities) { params.emplace_back(allowedAuthority); } for (const auto &allowedAuthority : allowedAuthorities) { params.emplace_back(allowedAuthority); } } if (d->hasAuthorityRestriction()) { additionalWhere += "AND v1.auth_name = ? AND v2.auth_name = ? "; params.emplace_back(d->authority()); params.emplace_back(d->authority()); } for (const auto &extent : {intersectingExtent1, intersectingExtent2}) { if (extent) { const auto &geogExtent = extent->geographicElements(); if (geogExtent.size() == 1) { auto bbox = dynamic_cast<const metadata::GeographicBoundingBox *>( geogExtent[0].get()); if (bbox) { const double south_lat = bbox->southBoundLatitude(); const double west_lon = bbox->westBoundLongitude(); const double north_lat = bbox->northBoundLatitude(); const double east_lon = bbox->eastBoundLongitude(); if (south_lat != -90.0 || west_lon != -180.0 || north_lat != 90.0 || east_lon != 180.0) { additionalWhere += "AND intersects_bbox(south_lat1, " "west_lon1, north_lat1, east_lon1, ?, ?, ?, ?) AND " "intersects_bbox(south_lat2, west_lon2, " "north_lat2, east_lon2, ?, ?, ?, ?) "; params.emplace_back(south_lat); params.emplace_back(west_lon); params.emplace_back(north_lat); params.emplace_back(east_lon); params.emplace_back(south_lat); params.emplace_back(west_lon); params.emplace_back(north_lat); params.emplace_back(east_lon); } } } } } const auto buildIntermediateWhere = [&intermediateCRSAuthCodes](const std::string &first_field, const std::string &second_field) { if (intermediateCRSAuthCodes.empty()) { return std::string(); } std::string l_sql(" AND ("); for (size_t i = 0; i < intermediateCRSAuthCodes.size(); ++i) { if (i > 0) { l_sql += " OR"; } l_sql += "(v1." + first_field + "_crs_auth_name = ? AND "; l_sql += "v1." + first_field + "_crs_code = ? AND "; l_sql += "v2." + second_field + "_crs_auth_name = ? AND "; l_sql += "v2." + second_field + "_crs_code = ?) "; } l_sql += ')'; return l_sql; }; std::string intermediateWhere = buildIntermediateWhere("target", "source"); for (const auto &pair : intermediateCRSAuthCodes) { params.emplace_back(pair.first); params.emplace_back(pair.second); params.emplace_back(pair.first); params.emplace_back(pair.second); } auto res = d->run(sql + additionalWhere + intermediateWhere + orderBy, params); const auto filterOutSuperseded = [](SQLResultSet &&resultSet) { std::set<std::pair<std::string, std::string>> setTransf1; std::set<std::pair<std::string, std::string>> setTransf2; for (const auto &row : resultSet) { // table1 const auto &auth_name1 = row[1]; const auto &code1 = row[2]; // accuracy1 // table2 const auto &auth_name2 = row[5]; const auto &code2 = row[6]; setTransf1.insert( std::pair<std::string, std::string>(auth_name1, code1)); setTransf2.insert( std::pair<std::string, std::string>(auth_name2, code2)); } SQLResultSet filteredResultSet; for (const auto &row : resultSet) { const auto &replacement_auth_name1 = row[16]; const auto &replacement_code1 = row[17]; const auto &replacement_auth_name2 = row[18]; const auto &replacement_code2 = row[19]; if (!replacement_auth_name1.empty() && setTransf1.find(std::pair<std::string, std::string>( replacement_auth_name1, replacement_code1)) != setTransf1.end()) { // Skip transformations that are superseded by others that got // returned in the result set. continue; } if (!replacement_auth_name2.empty() && setTransf2.find(std::pair<std::string, std::string>( replacement_auth_name2, replacement_code2)) != setTransf2.end()) { // Skip transformations that are superseded by others that got // returned in the result set. continue; } filteredResultSet.emplace_back(row); } return filteredResultSet; }; if (discardSuperseded) { res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { const auto &table1 = row[0]; const auto &auth_name1 = row[1]; const auto &code1 = row[2]; // const auto &accuracy1 = row[3]; const auto &table2 = row[4]; const auto &auth_name2 = row[5]; const auto &code2 = row[6]; // const auto &accuracy2 = row[7]; try { auto op1 = d->createFactory(auth_name1) ->createCoordinateOperation( code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) ->createCoordinateOperation( code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } listTmp.emplace_back( operation::ConcatenatedOperation::createComputeMetadata( {std::move(op1), std::move(op2)}, false)); } catch (const std::exception &e) { // Mostly for debugging purposes when using an inconsistent // database if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); } else { throw; } } } // Case (source->intermediate) and (target->intermediate) sql = sqlProlog + "ON v1.target_crs_auth_name = v2.target_crs_auth_name " "AND v1.target_crs_code = v2.target_crs_code " + joinArea + "WHERE v1.source_crs_auth_name = ? AND v1.source_crs_code = ? " "AND v2.source_crs_auth_name = ? AND v2.source_crs_code = ? "; if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { sql += criterionOnIntermediateCRS; } intermediateWhere = buildIntermediateWhere("target", "target"); res = d->run(sql + additionalWhere + intermediateWhere + orderBy, params); if (discardSuperseded) { res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { const auto &table1 = row[0]; const auto &auth_name1 = row[1]; const auto &code1 = row[2]; // const auto &accuracy1 = row[3]; const auto &table2 = row[4]; const auto &auth_name2 = row[5]; const auto &code2 = row[6]; // const auto &accuracy2 = row[7]; try { auto op1 = d->createFactory(auth_name1) ->createCoordinateOperation( code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) ->createCoordinateOperation( code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } listTmp.emplace_back( operation::ConcatenatedOperation::createComputeMetadata( {std::move(op1), op2->inverse()}, false)); } catch (const std::exception &e) { // Mostly for debugging purposes when using an inconsistent // database if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); } else { throw; } } } // Case (intermediate->source) and (intermediate->target) sql = sqlProlog + "ON v1.source_crs_auth_name = v2.source_crs_auth_name " "AND v1.source_crs_code = v2.source_crs_code " + joinArea + "WHERE v1.target_crs_auth_name = ? AND v1.target_crs_code = ? " "AND v2.target_crs_auth_name = ? AND v2.target_crs_code = ? "; if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { if (!minDate.empty()) { criterionOnIntermediateCRS = "AND EXISTS(SELECT 1 FROM geodetic_crs x " "JOIN geodetic_datum y " "ON " "y.auth_name = x.datum_auth_name AND " "y.code = x.datum_code " "WHERE " "x.auth_name = v1.source_crs_auth_name AND " "x.code = v1.source_crs_code AND " "x.type IN ('geographic 2D', 'geographic 3D') AND " "(y.publication_date IS NULL OR " "(y.publication_date >= '" + minDate + "'))) "; } else { criterionOnIntermediateCRS = "AND EXISTS(SELECT 1 FROM geodetic_crs x WHERE " "x.auth_name = v1.source_crs_auth_name AND " "x.code = v1.source_crs_code AND " "x.type IN ('geographic 2D', 'geographic 3D')) "; } sql += criterionOnIntermediateCRS; } intermediateWhere = buildIntermediateWhere("source", "source"); res = d->run(sql + additionalWhere + intermediateWhere + orderBy, params); if (discardSuperseded) { res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { const auto &table1 = row[0]; const auto &auth_name1 = row[1]; const auto &code1 = row[2]; // const auto &accuracy1 = row[3]; const auto &table2 = row[4]; const auto &auth_name2 = row[5]; const auto &code2 = row[6]; // const auto &accuracy2 = row[7]; try { auto op1 = d->createFactory(auth_name1) ->createCoordinateOperation( code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) ->createCoordinateOperation( code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } listTmp.emplace_back( operation::ConcatenatedOperation::createComputeMetadata( {op1->inverse(), std::move(op2)}, false)); } catch (const std::exception &e) { // Mostly for debugging purposes when using an inconsistent // database if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); } else { throw; } } } // Case (intermediate->source) and (target->intermediate) sql = sqlProlog + "ON v1.source_crs_auth_name = v2.target_crs_auth_name " "AND v1.source_crs_code = v2.target_crs_code " + joinArea + "WHERE v1.target_crs_auth_name = ? AND v1.target_crs_code = ? " "AND v2.source_crs_auth_name = ? AND v2.source_crs_code = ? "; if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { sql += criterionOnIntermediateCRS; } intermediateWhere = buildIntermediateWhere("source", "target"); res = d->run(sql + additionalWhere + intermediateWhere + orderBy, params); if (discardSuperseded) { res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { const auto &table1 = row[0]; const auto &auth_name1 = row[1]; const auto &code1 = row[2]; // const auto &accuracy1 = row[3]; const auto &table2 = row[4]; const auto &auth_name2 = row[5]; const auto &code2 = row[6]; // const auto &accuracy2 = row[7]; try { auto op1 = d->createFactory(auth_name1) ->createCoordinateOperation( code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) ->createCoordinateOperation( code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } listTmp.emplace_back( operation::ConcatenatedOperation::createComputeMetadata( {op1->inverse(), op2->inverse()}, false)); } catch (const std::exception &e) { // Mostly for debugging purposes when using an inconsistent // database if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); } else { throw; } } } std::vector<operation::CoordinateOperationNNPtr> list; for (const auto &op : listTmp) { if (!discardIfMissingGrid || !d->rejectOpDueToMissingGrid(op, considerKnownGridsAsAvailable)) { list.emplace_back(op); } } return list; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct TrfmInfo { std::string situation{}; std::string table_name{}; std::string auth_name{}; std::string code{}; std::string name{}; double west = 0; double south = 0; double east = 0; double north = 0; }; // --------------------------------------------------------------------------- std::vector<operation::CoordinateOperationNNPtr> AuthorityFactory::createBetweenGeodeticCRSWithDatumBasedIntermediates( const crs::CRSNNPtr &sourceCRS, const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, const crs::CRSNNPtr &targetCRS, const std::string &targetCRSAuthName, const std::string &targetCRSCode, bool usePROJAlternativeGridNames, bool discardIfMissingGrid, bool considerKnownGridsAsAvailable, bool discardSuperseded, const std::vector<std::string> &allowedAuthorities, const metadata::ExtentPtr &intersectingExtent1, const metadata::ExtentPtr &intersectingExtent2) const { std::vector<operation::CoordinateOperationNNPtr> listTmp; if (sourceCRSAuthName == targetCRSAuthName && sourceCRSCode == targetCRSCode) { return listTmp; } const auto sourceGeodCRS = dynamic_cast<crs::GeodeticCRS *>(sourceCRS.get()); const auto targetGeodCRS = dynamic_cast<crs::GeodeticCRS *>(targetCRS.get()); if (!sourceGeodCRS || !targetGeodCRS) { return listTmp; } const auto GetListCRSWithSameDatum = [this](const crs::GeodeticCRS *crs, const std::string &crsAuthName, const std::string &crsCode) { // Find all geodetic CRS that share the same datum as the CRS SQLResultSet listCRS; const common::IdentifiedObject *obj = crs->datum().get(); if (obj == nullptr) obj = crs->datumEnsemble().get(); assert(obj != nullptr); const auto &ids = obj->identifiers(); std::string datumAuthName; std::string datumCode; if (!ids.empty()) { const auto &id = ids.front(); datumAuthName = *(id->codeSpace()); datumCode = id->code(); } else { const auto res = d->run("SELECT datum_auth_name, datum_code FROM " "geodetic_crs WHERE auth_name = ? AND code = ?", {crsAuthName, crsCode}); if (res.size() != 1) { return listCRS; } const auto &row = res.front(); datumAuthName = row[0]; datumCode = row[1]; } listCRS = d->run("SELECT auth_name, code FROM geodetic_crs WHERE " "datum_auth_name = ? AND datum_code = ? AND deprecated = 0", {datumAuthName, datumCode}); if (listCRS.empty()) { // Can happen if the CRS is deprecated listCRS.emplace_back(SQLRow{crsAuthName, crsCode}); } return listCRS; }; const SQLResultSet listSourceCRS = GetListCRSWithSameDatum( sourceGeodCRS, sourceCRSAuthName, sourceCRSCode); const SQLResultSet listTargetCRS = GetListCRSWithSameDatum( targetGeodCRS, targetCRSAuthName, targetCRSCode); if (listSourceCRS.empty() || listTargetCRS.empty()) { // would happen only if we had CRS objects in the database without a // link to a datum. return listTmp; } ListOfParams params; const auto BuildSQLPart = [this, &allowedAuthorities, &params, &listSourceCRS, &listTargetCRS](bool isSourceCRS, bool selectOnTarget) { std::string situation; if (isSourceCRS) situation = "src"; else situation = "tgt"; if (selectOnTarget) situation += "_is_tgt"; else situation += "_is_src"; const std::string prefix1(selectOnTarget ? "source" : "target"); const std::string prefix2(selectOnTarget ? "target" : "source"); std::string sql("SELECT '"); sql += situation; sql += "' as situation, v.table_name, v.auth_name, " "v.code, v.name, gcrs.datum_auth_name, gcrs.datum_code, " "a.west_lon, a.south_lat, a.east_lon, a.north_lat " "FROM coordinate_operation_view v " "JOIN geodetic_crs gcrs on gcrs.auth_name = "; sql += prefix1; sql += "_crs_auth_name AND gcrs.code = "; sql += prefix1; sql += "_crs_code " "LEFT JOIN usage u ON " "u.object_table_name = v.table_name AND " "u.object_auth_name = v.auth_name AND " "u.object_code = v.code " "LEFT JOIN extent a " "ON a.auth_name = u.extent_auth_name AND " "a.code = u.extent_code " "WHERE v.deprecated = 0 AND ("; std::string cond; const auto &list = isSourceCRS ? listSourceCRS : listTargetCRS; for (const auto &row : list) { if (!cond.empty()) cond += " OR "; cond += '('; cond += prefix2; cond += "_crs_auth_name = ? AND "; cond += prefix2; cond += "_crs_code = ?)"; params.emplace_back(row[0]); params.emplace_back(row[1]); } sql += cond; sql += ") "; if (!allowedAuthorities.empty()) { sql += "AND v.auth_name IN ("; for (size_t i = 0; i < allowedAuthorities.size(); i++) { if (i > 0) sql += ','; sql += '?'; } sql += ") "; for (const auto &allowedAuthority : allowedAuthorities) { params.emplace_back(allowedAuthority); } } if (d->hasAuthorityRestriction()) { sql += "AND v.auth_name = ? "; params.emplace_back(d->authority()); } return sql; }; std::string sql(BuildSQLPart(true, true)); sql += "UNION ALL "; sql += BuildSQLPart(false, true); sql += "UNION ALL "; sql += BuildSQLPart(true, false); sql += "UNION ALL "; sql += BuildSQLPart(false, false); // fprintf(stderr, "sql : %s\n", sql.c_str()); // Find all operations that have as source/target CRS a CRS that // share the same datum as the source or targetCRS const auto res = d->run(sql, params); std::map<std::string, std::list<TrfmInfo>> mapIntermDatumOfSource; std::map<std::string, std::list<TrfmInfo>> mapIntermDatumOfTarget; for (const auto &row : res) { try { TrfmInfo trfm; trfm.situation = row[0]; trfm.table_name = row[1]; trfm.auth_name = row[2]; trfm.code = row[3]; trfm.name = row[4]; const auto &datum_auth_name = row[5]; const auto &datum_code = row[6]; trfm.west = c_locale_stod(row[7]); trfm.south = c_locale_stod(row[8]); trfm.east = c_locale_stod(row[9]); trfm.north = c_locale_stod(row[10]); const std::string key = std::string(datum_auth_name).append(":").append(datum_code); if (trfm.situation == "src_is_tgt" || trfm.situation == "src_is_src") mapIntermDatumOfSource[key].emplace_back(std::move(trfm)); else mapIntermDatumOfTarget[key].emplace_back(std::move(trfm)); } catch (const std::exception &) { } } std::vector<const metadata::GeographicBoundingBox *> extraBbox; for (const auto &extent : {intersectingExtent1, intersectingExtent2}) { if (extent) { const auto &geogExtent = extent->geographicElements(); if (geogExtent.size() == 1) { auto bbox = dynamic_cast<const metadata::GeographicBoundingBox *>( geogExtent[0].get()); if (bbox) { const double south_lat = bbox->southBoundLatitude(); const double west_lon = bbox->westBoundLongitude(); const double north_lat = bbox->northBoundLatitude(); const double east_lon = bbox->eastBoundLongitude(); if (south_lat != -90.0 || west_lon != -180.0 || north_lat != 90.0 || east_lon != 180.0) { extraBbox.emplace_back(bbox); } } } } } std::map<std::string, operation::CoordinateOperationPtr> oMapTrfmKeyToOp; std::list<std::pair<TrfmInfo, TrfmInfo>> candidates; std::map<std::string, TrfmInfo> setOfTransformations; const auto MakeKey = [](const TrfmInfo &trfm) { return trfm.table_name + '_' + trfm.auth_name + '_' + trfm.code; }; // Find transformations that share a pivot datum, and do bbox filtering for (const auto &kvSource : mapIntermDatumOfSource) { const auto &listTrmfSource = kvSource.second; auto iter = mapIntermDatumOfTarget.find(kvSource.first); if (iter == mapIntermDatumOfTarget.end()) continue; const auto &listTrfmTarget = iter->second; for (const auto &trfmSource : listTrmfSource) { auto bbox1 = metadata::GeographicBoundingBox::create( trfmSource.west, trfmSource.south, trfmSource.east, trfmSource.north); bool okBbox1 = true; for (const auto bbox : extraBbox) okBbox1 &= bbox->intersects(bbox1); if (!okBbox1) continue; const std::string key1 = MakeKey(trfmSource); for (const auto &trfmTarget : listTrfmTarget) { auto bbox2 = metadata::GeographicBoundingBox::create( trfmTarget.west, trfmTarget.south, trfmTarget.east, trfmTarget.north); if (!bbox1->intersects(bbox2)) continue; bool okBbox2 = true; for (const auto bbox : extraBbox) okBbox2 &= bbox->intersects(bbox2); if (!okBbox2) continue; operation::CoordinateOperationPtr op1; if (oMapTrfmKeyToOp.find(key1) == oMapTrfmKeyToOp.end()) { auto op1NN = d->createFactory(trfmSource.auth_name) ->createCoordinateOperation( trfmSource.code, true, usePROJAlternativeGridNames, trfmSource.table_name); op1 = op1NN.as_nullable(); if (useIrrelevantPivot(op1NN, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { op1.reset(); } oMapTrfmKeyToOp[key1] = op1; } else { op1 = oMapTrfmKeyToOp[key1]; } if (op1 == nullptr) continue; const std::string key2 = MakeKey(trfmTarget); operation::CoordinateOperationPtr op2; if (oMapTrfmKeyToOp.find(key2) == oMapTrfmKeyToOp.end()) { auto op2NN = d->createFactory(trfmTarget.auth_name) ->createCoordinateOperation( trfmTarget.code, true, usePROJAlternativeGridNames, trfmTarget.table_name); op2 = op2NN.as_nullable(); if (useIrrelevantPivot(op2NN, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { op2.reset(); } oMapTrfmKeyToOp[key2] = op2; } else { op2 = oMapTrfmKeyToOp[key2]; } if (op2 == nullptr) continue; candidates.emplace_back( std::pair<TrfmInfo, TrfmInfo>(trfmSource, trfmTarget)); setOfTransformations[key1] = trfmSource; setOfTransformations[key2] = trfmTarget; } } } std::set<std::string> setSuperseded; if (discardSuperseded && !setOfTransformations.empty()) { std::string findSupersededSql( "SELECT superseded_table_name, " "superseded_auth_name, superseded_code, " "replacement_auth_name, replacement_code " "FROM supersession WHERE same_source_target_crs = 1 AND ("); bool findSupersededFirstWhere = true; ListOfParams findSupersededParams; const auto keyMapSupersession = [](const std::string &table_name, const std::string &auth_name, const std::string &code) { return table_name + auth_name + code; }; std::set<std::pair<std::string, std::string>> setTransf; for (const auto &kv : setOfTransformations) { const auto &table = kv.second.table_name; const auto &auth_name = kv.second.auth_name; const auto &code = kv.second.code; if (!findSupersededFirstWhere) findSupersededSql += " OR "; findSupersededFirstWhere = false; findSupersededSql += "(superseded_table_name = ? AND replacement_table_name = " "superseded_table_name AND superseded_auth_name = ? AND " "superseded_code = ?)"; findSupersededParams.push_back(table); findSupersededParams.push_back(auth_name); findSupersededParams.push_back(code); setTransf.insert( std::pair<std::string, std::string>(auth_name, code)); } findSupersededSql += ')'; std::map<std::string, std::vector<std::pair<std::string, std::string>>> mapSupersession; const auto resSuperseded = d->run(findSupersededSql, findSupersededParams); for (const auto &row : resSuperseded) { const auto &superseded_table_name = row[0]; const auto &superseded_auth_name = row[1]; const auto &superseded_code = row[2]; const auto &replacement_auth_name = row[3]; const auto &replacement_code = row[4]; mapSupersession[keyMapSupersession(superseded_table_name, superseded_auth_name, superseded_code)] .push_back(std::pair<std::string, std::string>( replacement_auth_name, replacement_code)); } for (const auto &kv : setOfTransformations) { const auto &table = kv.second.table_name; const auto &auth_name = kv.second.auth_name; const auto &code = kv.second.code; const auto iter = mapSupersession.find( keyMapSupersession(table, auth_name, code)); if (iter != mapSupersession.end()) { bool foundReplacement = false; for (const auto &replacement : iter->second) { const auto &replacement_auth_name = replacement.first; const auto &replacement_code = replacement.second; if (setTransf.find(std::pair<std::string, std::string>( replacement_auth_name, replacement_code)) != setTransf.end()) { // Skip transformations that are superseded by others // that got // returned in the result set. foundReplacement = true; break; } } if (foundReplacement) { setSuperseded.insert(kv.first); } } } } auto opFactory = operation::CoordinateOperationFactory::create(); for (const auto &pair : candidates) { const auto &trfmSource = pair.first; const auto &trfmTarget = pair.second; const std::string key1 = MakeKey(trfmSource); const std::string key2 = MakeKey(trfmTarget); if (setSuperseded.find(key1) != setSuperseded.end() || setSuperseded.find(key2) != setSuperseded.end()) { continue; } auto op1 = oMapTrfmKeyToOp[key1]; auto op2 = oMapTrfmKeyToOp[key2]; auto op1NN = NN_NO_CHECK(op1); auto op2NN = NN_NO_CHECK(op2); if (trfmSource.situation == "src_is_tgt") op1NN = op1NN->inverse(); if (trfmTarget.situation == "tgt_is_src") op2NN = op2NN->inverse(); const auto &op1Source = op1NN->sourceCRS(); const auto &op1Target = op1NN->targetCRS(); const auto &op2Source = op2NN->sourceCRS(); const auto &op2Target = op2NN->targetCRS(); if (!(op1Source && op1Target && op2Source && op2Target)) { continue; } std::vector<operation::CoordinateOperationNNPtr> steps; if (!sourceCRS->isEquivalentTo( op1Source.get(), util::IComparable::Criterion::EQUIVALENT)) { auto opFirst = opFactory->createOperation(sourceCRS, NN_NO_CHECK(op1Source)); assert(opFirst); steps.emplace_back(NN_NO_CHECK(opFirst)); } steps.emplace_back(op1NN); if (!op1Target->isEquivalentTo( op2Source.get(), util::IComparable::Criterion::EQUIVALENT)) { auto opMiddle = opFactory->createOperation(NN_NO_CHECK(op1Target), NN_NO_CHECK(op2Source)); assert(opMiddle); steps.emplace_back(NN_NO_CHECK(opMiddle)); } steps.emplace_back(op2NN); if (!op2Target->isEquivalentTo( targetCRS.get(), util::IComparable::Criterion::EQUIVALENT)) { auto opLast = opFactory->createOperation(NN_NO_CHECK(op2Target), targetCRS); assert(opLast); steps.emplace_back(NN_NO_CHECK(opLast)); } listTmp.emplace_back( operation::ConcatenatedOperation::createComputeMetadata(steps, false)); } std::vector<operation::CoordinateOperationNNPtr> list; for (const auto &op : listTmp) { if (!discardIfMissingGrid || !d->rejectOpDueToMissingGrid(op, considerKnownGridsAsAvailable)) { list.emplace_back(op); } } return list; } //! @endcond // --------------------------------------------------------------------------- /** \brief Returns the authority name associated to this factory. * @return name. */ const std::string &AuthorityFactory::getAuthority() PROJ_PURE_DEFN { return d->authority(); } // --------------------------------------------------------------------------- /** \brief Returns the set of authority codes of the given object type. * * @param type Object type. * @param allowDeprecated whether we should return deprecated objects as well. * @return the set of authority codes for spatial reference objects of the given * type * @throw FactoryException */ std::set<std::string> AuthorityFactory::getAuthorityCodes(const ObjectType &type, bool allowDeprecated) const { std::string sql; switch (type) { case ObjectType::PRIME_MERIDIAN: sql = "SELECT code FROM prime_meridian WHERE "; break; case ObjectType::ELLIPSOID: sql = "SELECT code FROM ellipsoid WHERE "; break; case ObjectType::DATUM: sql = "SELECT code FROM object_view WHERE table_name IN " "('geodetic_datum', 'vertical_datum') AND "; break; case ObjectType::GEODETIC_REFERENCE_FRAME: sql = "SELECT code FROM geodetic_datum WHERE "; break; case ObjectType::DYNAMIC_GEODETIC_REFERENCE_FRAME: sql = "SELECT code FROM geodetic_datum WHERE " "frame_reference_epoch IS NOT NULL AND "; break; case ObjectType::VERTICAL_REFERENCE_FRAME: sql = "SELECT code FROM vertical_datum WHERE "; break; case ObjectType::DYNAMIC_VERTICAL_REFERENCE_FRAME: sql = "SELECT code FROM vertical_datum WHERE " "frame_reference_epoch IS NOT NULL AND "; break; case ObjectType::CRS: sql = "SELECT code FROM crs_view WHERE "; break; case ObjectType::GEODETIC_CRS: sql = "SELECT code FROM geodetic_crs WHERE "; break; case ObjectType::GEOCENTRIC_CRS: sql = "SELECT code FROM geodetic_crs WHERE type " "= " GEOCENTRIC_SINGLE_QUOTED " AND "; break; case ObjectType::GEOGRAPHIC_CRS: sql = "SELECT code FROM geodetic_crs WHERE type IN " "(" GEOG_2D_SINGLE_QUOTED "," GEOG_3D_SINGLE_QUOTED ") AND "; break; case ObjectType::GEOGRAPHIC_2D_CRS: sql = "SELECT code FROM geodetic_crs WHERE type = " GEOG_2D_SINGLE_QUOTED " AND "; break; case ObjectType::GEOGRAPHIC_3D_CRS: sql = "SELECT code FROM geodetic_crs WHERE type = " GEOG_3D_SINGLE_QUOTED " AND "; break; case ObjectType::VERTICAL_CRS: sql = "SELECT code FROM vertical_crs WHERE "; break; case ObjectType::PROJECTED_CRS: sql = "SELECT code FROM projected_crs WHERE "; break; case ObjectType::COMPOUND_CRS: sql = "SELECT code FROM compound_crs WHERE "; break; case ObjectType::COORDINATE_OPERATION: sql = "SELECT code FROM coordinate_operation_with_conversion_view WHERE "; break; case ObjectType::CONVERSION: sql = "SELECT code FROM conversion WHERE "; break; case ObjectType::TRANSFORMATION: sql = "SELECT code FROM coordinate_operation_view WHERE table_name != " "'concatenated_operation' AND "; break; case ObjectType::CONCATENATED_OPERATION: sql = "SELECT code FROM concatenated_operation WHERE "; break; case ObjectType::DATUM_ENSEMBLE: sql = "SELECT code FROM object_view WHERE table_name IN " "('geodetic_datum', 'vertical_datum') AND " "type = 'ensemble' AND "; break; } sql += "auth_name = ?"; if (!allowDeprecated) { sql += " AND deprecated = 0"; } auto res = d->run(sql, {d->authority()}); std::set<std::string> set; for (const auto &row : res) { set.insert(row[0]); } return set; } // --------------------------------------------------------------------------- /** \brief Gets a description of the object corresponding to a code. * * \note In case of several objects of different types with the same code, * one of them will be arbitrarily selected. But if a CRS object is found, it * will be selected. * * @param code Object code allocated by authority. (e.g. "4326") * @return description. * @throw NoSuchAuthorityCodeException * @throw FactoryException */ std::string AuthorityFactory::getDescriptionText(const std::string &code) const { auto sql = "SELECT name, table_name FROM object_view WHERE auth_name = ? " "AND code = ? ORDER BY table_name"; auto sqlRes = d->runWithCodeParam(sql, code); if (sqlRes.empty()) { throw NoSuchAuthorityCodeException("object not found", d->authority(), code); } std::string text; for (const auto &row : sqlRes) { const auto &tableName = row[1]; if (tableName == "geodetic_crs" || tableName == "projected_crs" || tableName == "vertical_crs" || tableName == "compound_crs") { return row[0]; } else if (text.empty()) { text = row[0]; } } return text; } // --------------------------------------------------------------------------- /** \brief Return a list of information on CRS objects * * This is functionally equivalent of listing the codes from an authority, * instantiating * a CRS object for each of them and getting the information from this CRS * object, but this implementation has much less overhead. * * @throw FactoryException */ std::list<AuthorityFactory::CRSInfo> AuthorityFactory::getCRSInfoList() const { const auto getSqlArea = [](const char *table_name) { std::string sql("LEFT JOIN usage u ON u.object_table_name = '"); sql += table_name; sql += "' AND " "u.object_auth_name = c.auth_name AND " "u.object_code = c.code " "LEFT JOIN extent a " "ON a.auth_name = u.extent_auth_name AND " "a.code = u.extent_code "; return sql; }; const auto getJoinCelestialBody = [](const char *crs_alias) { std::string sql("LEFT JOIN geodetic_datum gd ON gd.auth_name = "); sql += crs_alias; sql += ".datum_auth_name AND gd.code = "; sql += crs_alias; sql += ".datum_code " "LEFT JOIN ellipsoid e ON e.auth_name = gd.ellipsoid_auth_name " "AND e.code = gd.ellipsoid_code " "LEFT JOIN celestial_body cb ON " "cb.auth_name = e.celestial_body_auth_name " "AND cb.code = e.celestial_body_code "; return sql; }; std::string sql = "SELECT * FROM (" "SELECT c.auth_name, c.code, c.name, c.type, " "c.deprecated, " "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " "a.description, NULL, cb.name FROM geodetic_crs c "; sql += getSqlArea("geodetic_crs"); sql += getJoinCelestialBody("c"); ListOfParams params; if (d->hasAuthorityRestriction()) { sql += "WHERE c.auth_name = ? "; params.emplace_back(d->authority()); } sql += "UNION ALL SELECT c.auth_name, c.code, c.name, 'projected', " "c.deprecated, " "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " "a.description, cm.name, cb.name AS conversion_method_name FROM " "projected_crs c " "LEFT JOIN conversion_table conv ON " "c.conversion_auth_name = conv.auth_name AND " "c.conversion_code = conv.code " "LEFT JOIN conversion_method cm ON " "conv.method_auth_name = cm.auth_name AND " "conv.method_code = cm.code " "LEFT JOIN geodetic_crs gcrs ON " "gcrs.auth_name = c.geodetic_crs_auth_name " "AND gcrs.code = c.geodetic_crs_code "; sql += getSqlArea("projected_crs"); sql += getJoinCelestialBody("gcrs"); if (d->hasAuthorityRestriction()) { sql += "WHERE c.auth_name = ? "; params.emplace_back(d->authority()); } // FIXME: we can't handle non-EARTH vertical CRS for now sql += "UNION ALL SELECT c.auth_name, c.code, c.name, 'vertical', " "c.deprecated, " "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " "a.description, NULL, 'Earth' FROM vertical_crs c "; sql += getSqlArea("vertical_crs"); if (d->hasAuthorityRestriction()) { sql += "WHERE c.auth_name = ? "; params.emplace_back(d->authority()); } // FIXME: we can't handle non-EARTH compound CRS for now sql += "UNION ALL SELECT c.auth_name, c.code, c.name, 'compound', " "c.deprecated, " "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " "a.description, NULL, 'Earth' FROM compound_crs c "; sql += getSqlArea("compound_crs"); if (d->hasAuthorityRestriction()) { sql += "WHERE c.auth_name = ? "; params.emplace_back(d->authority()); } sql += ") r ORDER BY auth_name, code"; auto sqlRes = d->run(sql, params); std::list<AuthorityFactory::CRSInfo> res; for (const auto &row : sqlRes) { AuthorityFactory::CRSInfo info; info.authName = row[0]; info.code = row[1]; info.name = row[2]; const auto &type = row[3]; if (type == GEOG_2D) { info.type = AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS; } else if (type == GEOG_3D) { info.type = AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS; } else if (type == GEOCENTRIC) { info.type = AuthorityFactory::ObjectType::GEOCENTRIC_CRS; } else if (type == OTHER) { info.type = AuthorityFactory::ObjectType::GEODETIC_CRS; } else if (type == PROJECTED) { info.type = AuthorityFactory::ObjectType::PROJECTED_CRS; } else if (type == VERTICAL) { info.type = AuthorityFactory::ObjectType::VERTICAL_CRS; } else if (type == COMPOUND) { info.type = AuthorityFactory::ObjectType::COMPOUND_CRS; } info.deprecated = row[4] == "1"; if (row[5].empty()) { info.bbox_valid = false; } else { info.bbox_valid = true; info.west_lon_degree = c_locale_stod(row[5]); info.south_lat_degree = c_locale_stod(row[6]); info.east_lon_degree = c_locale_stod(row[7]); info.north_lat_degree = c_locale_stod(row[8]); } info.areaName = row[9]; info.projectionMethodName = row[10]; info.celestialBodyName = row[11]; res.emplace_back(info); } return res; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress AuthorityFactory::UnitInfo::UnitInfo() : authName{}, code{}, name{}, category{}, convFactor{}, projShortName{}, deprecated{} {} //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress AuthorityFactory::CelestialBodyInfo::CelestialBodyInfo() : authName{}, name{} {} //! @endcond // --------------------------------------------------------------------------- /** \brief Return the list of units. * @throw FactoryException * * @since 7.1 */ std::list<AuthorityFactory::UnitInfo> AuthorityFactory::getUnitList() const { std::string sql = "SELECT auth_name, code, name, type, conv_factor, " "proj_short_name, deprecated FROM unit_of_measure"; ListOfParams params; if (d->hasAuthorityRestriction()) { sql += " WHERE auth_name = ?"; params.emplace_back(d->authority()); } sql += " ORDER BY auth_name, code"; auto sqlRes = d->run(sql, params); std::list<AuthorityFactory::UnitInfo> res; for (const auto &row : sqlRes) { AuthorityFactory::UnitInfo info; info.authName = row[0]; info.code = row[1]; info.name = row[2]; const std::string &raw_category(row[3]); if (raw_category == "length") { info.category = info.name.find(" per ") != std::string::npos ? "linear_per_time" : "linear"; } else if (raw_category == "angle") { info.category = info.name.find(" per ") != std::string::npos ? "angular_per_time" : "angular"; } else if (raw_category == "scale") { info.category = info.name.find(" per year") != std::string::npos || info.name.find(" per second") != std::string::npos ? "scale_per_time" : "scale"; } else { info.category = raw_category; } info.convFactor = row[4].empty() ? 0 : c_locale_stod(row[4]); info.projShortName = row[5]; info.deprecated = row[6] == "1"; res.emplace_back(info); } return res; } // --------------------------------------------------------------------------- /** \brief Return the list of celestial bodies. * @throw FactoryException * * @since 8.1 */ std::list<AuthorityFactory::CelestialBodyInfo> AuthorityFactory::getCelestialBodyList() const { std::string sql = "SELECT auth_name, name FROM celestial_body"; ListOfParams params; if (d->hasAuthorityRestriction()) { sql += " WHERE auth_name = ?"; params.emplace_back(d->authority()); } sql += " ORDER BY auth_name, name"; auto sqlRes = d->run(sql, params); std::list<AuthorityFactory::CelestialBodyInfo> res; for (const auto &row : sqlRes) { AuthorityFactory::CelestialBodyInfo info; info.authName = row[0]; info.name = row[1]; res.emplace_back(info); } return res; } // --------------------------------------------------------------------------- /** \brief Gets the official name from a possibly alias name. * * @param aliasedName Alias name. * @param tableName Table name/category. Can help in case of ambiguities. * Or empty otherwise. * @param source Source of the alias. Can help in case of ambiguities. * Or empty otherwise. * @param tryEquivalentNameSpelling whether the comparison of aliasedName with * the alt_name column of the alias_name table should be done with using * metadata::Identifier::isEquivalentName() rather than strict string * comparison; * @param outTableName Table name in which the official name has been found. * @param outAuthName Authority name of the official name that has been found. * @param outCode Code of the official name that has been found. * @return official name (or empty if not found). * @throw FactoryException */ std::string AuthorityFactory::getOfficialNameFromAlias( const std::string &aliasedName, const std::string &tableName, const std::string &source, bool tryEquivalentNameSpelling, std::string &outTableName, std::string &outAuthName, std::string &outCode) const { if (tryEquivalentNameSpelling) { std::string sql( "SELECT table_name, auth_name, code, alt_name FROM alias_name"); ListOfParams params; if (!tableName.empty()) { sql += " WHERE table_name = ?"; params.push_back(tableName); } if (!source.empty()) { if (!tableName.empty()) { sql += " AND "; } else { sql += " WHERE "; } sql += "source = ?"; params.push_back(source); } auto res = d->run(sql, params); if (res.empty()) { return std::string(); } for (const auto &row : res) { const auto &alt_name = row[3]; if (metadata::Identifier::isEquivalentName(alt_name.c_str(), aliasedName.c_str())) { outTableName = row[0]; outAuthName = row[1]; outCode = row[2]; sql = "SELECT name FROM \""; sql += replaceAll(outTableName, "\"", "\"\""); sql += "\" WHERE auth_name = ? AND code = ?"; res = d->run(sql, {outAuthName, outCode}); if (res.empty()) { // shouldn't happen normally return std::string(); } return res.front()[0]; } } return std::string(); } else { std::string sql( "SELECT table_name, auth_name, code FROM alias_name WHERE " "alt_name = ?"); ListOfParams params{aliasedName}; if (!tableName.empty()) { sql += " AND table_name = ?"; params.push_back(tableName); } if (!source.empty()) { sql += " AND source = ?"; params.push_back(source); } auto res = d->run(sql, params); if (res.empty()) { return std::string(); } params.clear(); sql.clear(); bool first = true; for (const auto &row : res) { if (!first) sql += " UNION ALL "; first = false; outTableName = row[0]; outAuthName = row[1]; outCode = row[2]; sql += "SELECT name, ? AS table_name, auth_name, code, deprecated " "FROM \""; sql += replaceAll(outTableName, "\"", "\"\""); sql += "\" WHERE auth_name = ? AND code = ?"; params.emplace_back(outTableName); params.emplace_back(outAuthName); params.emplace_back(outCode); } sql = "SELECT name, table_name, auth_name, code FROM (" + sql + ") x ORDER BY deprecated LIMIT 1"; res = d->run(sql, params); if (res.empty()) { // shouldn't happen normally return std::string(); } const auto &row = res.front(); outTableName = row[1]; outAuthName = row[2]; outCode = row[3]; return row[0]; } } // --------------------------------------------------------------------------- /** \brief Return a list of objects, identified by their name * * @param searchedName Searched name. Must be at least 2 character long. * @param allowedObjectTypes List of object types into which to search. If * empty, all object types will be searched. * @param approximateMatch Whether approximate name identification is allowed. * @param limitResultCount Maximum number of results to return. * Or 0 for unlimited. * @return list of matched objects. * @throw FactoryException */ std::list<common::IdentifiedObjectNNPtr> AuthorityFactory::createObjectsFromName( const std::string &searchedName, const std::vector<ObjectType> &allowedObjectTypes, bool approximateMatch, size_t limitResultCount) const { std::list<common::IdentifiedObjectNNPtr> res; const auto resTmp(createObjectsFromNameEx( searchedName, allowedObjectTypes, approximateMatch, limitResultCount)); for (const auto &pair : resTmp) { res.emplace_back(pair.first); } return res; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return a list of objects, identifier by their name, with the name * on which the match occurred. * * The name on which the match occurred might be different from the object name, * if the match has been done on an alias name of that object. * * @param searchedName Searched name. Must be at least 2 character long. * @param allowedObjectTypes List of object types into which to search. If * empty, all object types will be searched. * @param approximateMatch Whether approximate name identification is allowed. * @param limitResultCount Maximum number of results to return. * Or 0 for unlimited. * @return list of matched objects. * @throw FactoryException */ std::list<AuthorityFactory::PairObjectName> AuthorityFactory::createObjectsFromNameEx( const std::string &searchedName, const std::vector<ObjectType> &allowedObjectTypes, bool approximateMatch, size_t limitResultCount) const { std::string searchedNameWithoutDeprecated(searchedName); bool deprecated = false; if (ends_with(searchedNameWithoutDeprecated, " (deprecated)")) { deprecated = true; searchedNameWithoutDeprecated.resize( searchedNameWithoutDeprecated.size() - strlen(" (deprecated)")); } const std::string canonicalizedSearchedName( metadata::Identifier::canonicalizeName(searchedNameWithoutDeprecated)); if (canonicalizedSearchedName.size() <= 1) { return {}; } std::string sql( "SELECT table_name, auth_name, code, name, deprecated, is_alias " "FROM ("); const auto getTableAndTypeConstraints = [&allowedObjectTypes, &searchedName]() { typedef std::pair<std::string, std::string> TableType; std::list<TableType> res; // Hide ESRI D_ vertical datums const bool startsWithDUnderscore = starts_with(searchedName, "D_"); if (allowedObjectTypes.empty()) { for (const auto &tableName : {"prime_meridian", "ellipsoid", "geodetic_datum", "vertical_datum", "geodetic_crs", "projected_crs", "vertical_crs", "compound_crs", "conversion", "helmert_transformation", "grid_transformation", "other_transformation", "concatenated_operation"}) { if (!(startsWithDUnderscore && strcmp(tableName, "vertical_datum") == 0)) { res.emplace_back(TableType(tableName, std::string())); } } } else { for (const auto type : allowedObjectTypes) { switch (type) { case ObjectType::PRIME_MERIDIAN: res.emplace_back( TableType("prime_meridian", std::string())); break; case ObjectType::ELLIPSOID: res.emplace_back(TableType("ellipsoid", std::string())); break; case ObjectType::DATUM: res.emplace_back( TableType("geodetic_datum", std::string())); if (!startsWithDUnderscore) { res.emplace_back( TableType("vertical_datum", std::string())); } break; case ObjectType::GEODETIC_REFERENCE_FRAME: res.emplace_back( TableType("geodetic_datum", std::string())); break; case ObjectType::DYNAMIC_GEODETIC_REFERENCE_FRAME: res.emplace_back( TableType("geodetic_datum", "frame_reference_epoch")); break; case ObjectType::VERTICAL_REFERENCE_FRAME: res.emplace_back( TableType("vertical_datum", std::string())); break; case ObjectType::DYNAMIC_VERTICAL_REFERENCE_FRAME: res.emplace_back( TableType("vertical_datum", "frame_reference_epoch")); break; case ObjectType::CRS: res.emplace_back(TableType("geodetic_crs", std::string())); res.emplace_back(TableType("projected_crs", std::string())); res.emplace_back(TableType("vertical_crs", std::string())); res.emplace_back(TableType("compound_crs", std::string())); break; case ObjectType::GEODETIC_CRS: res.emplace_back(TableType("geodetic_crs", std::string())); break; case ObjectType::GEOCENTRIC_CRS: res.emplace_back(TableType("geodetic_crs", GEOCENTRIC)); break; case ObjectType::GEOGRAPHIC_CRS: res.emplace_back(TableType("geodetic_crs", GEOG_2D)); res.emplace_back(TableType("geodetic_crs", GEOG_3D)); break; case ObjectType::GEOGRAPHIC_2D_CRS: res.emplace_back(TableType("geodetic_crs", GEOG_2D)); break; case ObjectType::GEOGRAPHIC_3D_CRS: res.emplace_back(TableType("geodetic_crs", GEOG_3D)); break; case ObjectType::PROJECTED_CRS: res.emplace_back(TableType("projected_crs", std::string())); break; case ObjectType::VERTICAL_CRS: res.emplace_back(TableType("vertical_crs", std::string())); break; case ObjectType::COMPOUND_CRS: res.emplace_back(TableType("compound_crs", std::string())); break; case ObjectType::COORDINATE_OPERATION: res.emplace_back(TableType("conversion", std::string())); res.emplace_back( TableType("helmert_transformation", std::string())); res.emplace_back( TableType("grid_transformation", std::string())); res.emplace_back( TableType("other_transformation", std::string())); res.emplace_back( TableType("concatenated_operation", std::string())); break; case ObjectType::CONVERSION: res.emplace_back(TableType("conversion", std::string())); break; case ObjectType::TRANSFORMATION: res.emplace_back( TableType("helmert_transformation", std::string())); res.emplace_back( TableType("grid_transformation", std::string())); res.emplace_back( TableType("other_transformation", std::string())); break; case ObjectType::CONCATENATED_OPERATION: res.emplace_back( TableType("concatenated_operation", std::string())); break; case ObjectType::DATUM_ENSEMBLE: res.emplace_back(TableType("geodetic_datum", "ensemble")); res.emplace_back(TableType("vertical_datum", "ensemble")); break; } } } return res; }; bool datumEnsembleAllowed = false; if (allowedObjectTypes.empty()) { datumEnsembleAllowed = true; } else { for (const auto type : allowedObjectTypes) { if (type == ObjectType::DATUM_ENSEMBLE) { datumEnsembleAllowed = true; break; } } } const auto listTableNameType = getTableAndTypeConstraints(); bool first = true; ListOfParams params; for (const auto &tableNameTypePair : listTableNameType) { if (!first) { sql += " UNION "; } first = false; sql += "SELECT '"; sql += tableNameTypePair.first; sql += "' AS table_name, auth_name, code, name, deprecated, " "0 AS is_alias FROM "; sql += tableNameTypePair.first; sql += " WHERE 1 = 1 "; if (!tableNameTypePair.second.empty()) { if (tableNameTypePair.second == "frame_reference_epoch") { sql += "AND frame_reference_epoch IS NOT NULL "; } else if (tableNameTypePair.second == "ensemble") { sql += "AND ensemble_accuracy IS NOT NULL "; } else { sql += "AND type = '"; sql += tableNameTypePair.second; sql += "' "; } } if (deprecated) { sql += "AND deprecated = 1 "; } if (!approximateMatch) { sql += "AND name = ? COLLATE NOCASE "; params.push_back(searchedNameWithoutDeprecated); } if (d->hasAuthorityRestriction()) { sql += "AND auth_name = ? "; params.emplace_back(d->authority()); } sql += " UNION SELECT '"; sql += tableNameTypePair.first; sql += "' AS table_name, " "ov.auth_name AS auth_name, " "ov.code AS code, a.alt_name AS name, " "ov.deprecated AS deprecated, 1 as is_alias FROM "; sql += tableNameTypePair.first; sql += " ov " "JOIN alias_name a ON " "ov.auth_name = a.auth_name AND ov.code = a.code WHERE " "a.table_name = '"; sql += tableNameTypePair.first; sql += "' "; if (!tableNameTypePair.second.empty()) { if (tableNameTypePair.second == "frame_reference_epoch") { sql += "AND ov.frame_reference_epoch IS NOT NULL "; } else if (tableNameTypePair.second == "ensemble") { sql += "AND ov.ensemble_accuracy IS NOT NULL "; } else { sql += "AND ov.type = '"; sql += tableNameTypePair.second; sql += "' "; } } if (deprecated) { sql += "AND ov.deprecated = 1 "; } if (!approximateMatch) { sql += "AND a.alt_name = ? COLLATE NOCASE "; params.push_back(searchedNameWithoutDeprecated); } if (d->hasAuthorityRestriction()) { sql += "AND ov.auth_name = ? "; params.emplace_back(d->authority()); } } sql += ") ORDER BY deprecated, is_alias, length(name), name"; if (limitResultCount > 0 && limitResultCount < static_cast<size_t>(std::numeric_limits<int>::max()) && !approximateMatch) { sql += " LIMIT "; sql += toString(static_cast<int>(limitResultCount)); } std::list<PairObjectName> res; std::set<std::pair<std::string, std::string>> setIdentified; // Querying geodetic datum is a super hot path when importing from WKT1 // so cache results. if (allowedObjectTypes.size() == 1 && allowedObjectTypes[0] == ObjectType::GEODETIC_REFERENCE_FRAME && approximateMatch && d->authority().empty()) { auto &mapCanonicalizeGRFName = d->context()->getPrivate()->getMapCanonicalizeGRFName(); if (mapCanonicalizeGRFName.empty()) { auto sqlRes = d->run(sql, params); for (const auto &row : sqlRes) { const auto &name = row[3]; const auto &deprecatedStr = row[4]; const auto canonicalizedName( metadata::Identifier::canonicalizeName(name)); auto &v = mapCanonicalizeGRFName[canonicalizedName]; if (deprecatedStr == "0" || v.empty() || v.front()[4] == "1") { v.push_back(row); } } } auto iter = mapCanonicalizeGRFName.find(canonicalizedSearchedName); if (iter != mapCanonicalizeGRFName.end()) { const auto &listOfRow = iter->second; for (const auto &row : listOfRow) { const auto &auth_name = row[1]; const auto &code = row[2]; const auto key = std::pair<std::string, std::string>(auth_name, code); if (setIdentified.find(key) != setIdentified.end()) { continue; } setIdentified.insert(key); auto factory = d->createFactory(auth_name); const auto &name = row[3]; res.emplace_back( PairObjectName(factory->createGeodeticDatum(code), name)); if (limitResultCount > 0 && res.size() == limitResultCount) { break; } } } else { for (const auto &pair : mapCanonicalizeGRFName) { const auto &listOfRow = pair.second; for (const auto &row : listOfRow) { const auto &name = row[3]; bool match = ci_find(name, searchedNameWithoutDeprecated) != std::string::npos; if (!match) { const auto &canonicalizedName(pair.first); match = ci_find(canonicalizedName, canonicalizedSearchedName) != std::string::npos; } if (!match) { continue; } const auto &auth_name = row[1]; const auto &code = row[2]; const auto key = std::pair<std::string, std::string>(auth_name, code); if (setIdentified.find(key) != setIdentified.end()) { continue; } setIdentified.insert(key); auto factory = d->createFactory(auth_name); res.emplace_back(PairObjectName( factory->createGeodeticDatum(code), name)); if (limitResultCount > 0 && res.size() == limitResultCount) { break; } } if (limitResultCount > 0 && res.size() == limitResultCount) { break; } } } } else { auto sqlRes = d->run(sql, params); bool isFirst = true; bool firstIsDeprecated = false; bool foundExactMatch = false; std::size_t hashCodeFirstMatch = 0; for (const auto &row : sqlRes) { const auto &name = row[3]; if (approximateMatch) { bool match = ci_find(name, searchedNameWithoutDeprecated) != std::string::npos; if (!match) { const auto canonicalizedName( metadata::Identifier::canonicalizeName(name)); match = ci_find(canonicalizedName, canonicalizedSearchedName) != std::string::npos; } if (!match) { continue; } } const auto &table_name = row[0]; const auto &auth_name = row[1]; const auto &code = row[2]; const auto key = std::pair<std::string, std::string>(auth_name, code); if (setIdentified.find(key) != setIdentified.end()) { continue; } setIdentified.insert(key); const auto &deprecatedStr = row[4]; if (isFirst) { firstIsDeprecated = deprecatedStr == "1"; isFirst = false; } if (deprecatedStr == "1" && !res.empty() && !firstIsDeprecated) { break; } auto factory = d->createFactory(auth_name); auto getObject = [&factory, datumEnsembleAllowed]( const std::string &l_table_name, const std::string &l_code) -> common::IdentifiedObjectNNPtr { if (l_table_name == "prime_meridian") { return factory->createPrimeMeridian(l_code); } else if (l_table_name == "ellipsoid") { return factory->createEllipsoid(l_code); } else if (l_table_name == "geodetic_datum") { if (datumEnsembleAllowed) { datum::GeodeticReferenceFramePtr datum; datum::DatumEnsemblePtr datumEnsemble; constexpr bool turnEnsembleAsDatum = false; factory->createGeodeticDatumOrEnsemble( l_code, datum, datumEnsemble, turnEnsembleAsDatum); if (datum) { return NN_NO_CHECK(datum); } assert(datumEnsemble); return NN_NO_CHECK(datumEnsemble); } return factory->createGeodeticDatum(l_code); } else if (l_table_name == "vertical_datum") { if (datumEnsembleAllowed) { datum::VerticalReferenceFramePtr datum; datum::DatumEnsemblePtr datumEnsemble; constexpr bool turnEnsembleAsDatum = false; factory->createVerticalDatumOrEnsemble( l_code, datum, datumEnsemble, turnEnsembleAsDatum); if (datum) { return NN_NO_CHECK(datum); } assert(datumEnsemble); return NN_NO_CHECK(datumEnsemble); } return factory->createVerticalDatum(l_code); } else if (l_table_name == "geodetic_crs") { return factory->createGeodeticCRS(l_code); } else if (l_table_name == "projected_crs") { return factory->createProjectedCRS(l_code); } else if (l_table_name == "vertical_crs") { return factory->createVerticalCRS(l_code); } else if (l_table_name == "compound_crs") { return factory->createCompoundCRS(l_code); } else if (l_table_name == "conversion") { return factory->createConversion(l_code); } else if (l_table_name == "grid_transformation" || l_table_name == "helmert_transformation" || l_table_name == "other_transformation" || l_table_name == "concatenated_operation") { return factory->createCoordinateOperation(l_code, true); } throw std::runtime_error("Unsupported table_name"); }; const auto obj = getObject(table_name, code); if (metadata::Identifier::canonicalizeName(obj->nameStr()) == canonicalizedSearchedName) { foundExactMatch = true; } const auto objPtr = obj.get(); if (res.empty()) { hashCodeFirstMatch = typeid(*objPtr).hash_code(); } else if (hashCodeFirstMatch != typeid(*objPtr).hash_code()) { hashCodeFirstMatch = 0; } res.emplace_back(PairObjectName(obj, name)); if (limitResultCount > 0 && res.size() == limitResultCount) { break; } } // If we found a name that is an exact match, and all objects have the // same type, and we are not in approximate mode, only keep the // object(s) with the exact name match. if (foundExactMatch && hashCodeFirstMatch != 0 && !approximateMatch) { std::list<PairObjectName> resTmp; for (const auto &pair : res) { if (metadata::Identifier::canonicalizeName( pair.first->nameStr()) == canonicalizedSearchedName) { resTmp.emplace_back(pair); } } res = std::move(resTmp); } } auto sortLambda = [](const PairObjectName &a, const PairObjectName &b) { const auto &aName = a.first->nameStr(); const auto &bName = b.first->nameStr(); if (aName.size() < bName.size()) { return true; } if (aName.size() > bName.size()) { return false; } const auto &aIds = a.first->identifiers(); const auto &bIds = b.first->identifiers(); if (aIds.size() < bIds.size()) { return true; } if (aIds.size() > bIds.size()) { return false; } for (size_t idx = 0; idx < aIds.size(); idx++) { const auto &aCodeSpace = *aIds[idx]->codeSpace(); const auto &bCodeSpace = *bIds[idx]->codeSpace(); const auto codeSpaceComparison = aCodeSpace.compare(bCodeSpace); if (codeSpaceComparison < 0) { return true; } if (codeSpaceComparison > 0) { return false; } const auto &aCode = aIds[idx]->code(); const auto &bCode = bIds[idx]->code(); const auto codeComparison = aCode.compare(bCode); if (codeComparison < 0) { return true; } if (codeComparison > 0) { return false; } } return strcmp(typeid(a.first.get()).name(), typeid(b.first.get()).name()) < 0; }; res.sort(sortLambda); return res; } //! @endcond // --------------------------------------------------------------------------- /** \brief Return a list of area of use from their name * * @param name Searched name. * @param approximateMatch Whether approximate name identification is allowed. * @return list of (auth_name, code) of matched objects. * @throw FactoryException */ std::list<std::pair<std::string, std::string>> AuthorityFactory::listAreaOfUseFromName(const std::string &name, bool approximateMatch) const { std::string sql( "SELECT auth_name, code FROM extent WHERE deprecated = 0 AND "); ListOfParams params; if (d->hasAuthorityRestriction()) { sql += " auth_name = ? AND "; params.emplace_back(d->authority()); } sql += "name LIKE ?"; if (!approximateMatch) { params.push_back(name); } else { params.push_back('%' + name + '%'); } auto sqlRes = d->run(sql, params); std::list<std::pair<std::string, std::string>> res; for (const auto &row : sqlRes) { res.emplace_back(row[0], row[1]); } return res; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<datum::EllipsoidNNPtr> AuthorityFactory::createEllipsoidFromExisting( const datum::EllipsoidNNPtr &ellipsoid) const { std::string sql( "SELECT auth_name, code FROM ellipsoid WHERE " "abs(semi_major_axis - ?) < 1e-10 * abs(semi_major_axis) AND " "((semi_minor_axis IS NOT NULL AND " "abs(semi_minor_axis - ?) < 1e-10 * abs(semi_minor_axis)) OR " "((inv_flattening IS NOT NULL AND " "abs(inv_flattening - ?) < 1e-10 * abs(inv_flattening))))"); ListOfParams params{ellipsoid->semiMajorAxis().getSIValue(), ellipsoid->computeSemiMinorAxis().getSIValue(), ellipsoid->computedInverseFlattening()}; auto sqlRes = d->run(sql, params); std::list<datum::EllipsoidNNPtr> res; for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back(d->createFactory(auth_name)->createEllipsoid(code)); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<crs::GeodeticCRSNNPtr> AuthorityFactory::createGeodeticCRSFromDatum( const std::string &datum_auth_name, const std::string &datum_code, const std::string &geodetic_crs_type) const { std::string sql( "SELECT auth_name, code FROM geodetic_crs WHERE " "datum_auth_name = ? AND datum_code = ? AND deprecated = 0"); ListOfParams params{datum_auth_name, datum_code}; if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; params.emplace_back(d->authority()); } if (!geodetic_crs_type.empty()) { sql += " AND type = ?"; params.emplace_back(geodetic_crs_type); } sql += " ORDER BY auth_name, code"; auto sqlRes = d->run(sql, params); std::list<crs::GeodeticCRSNNPtr> res; for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back(d->createFactory(auth_name)->createGeodeticCRS(code)); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<crs::GeodeticCRSNNPtr> AuthorityFactory::createGeodeticCRSFromDatum( const datum::GeodeticReferenceFrameNNPtr &datum, const std::string &preferredAuthName, const std::string &geodetic_crs_type) const { std::list<crs::GeodeticCRSNNPtr> candidates; const auto &ids = datum->identifiers(); const auto &datumName = datum->nameStr(); if (!ids.empty()) { for (const auto &id : ids) { const auto &authName = *(id->codeSpace()); const auto &code = id->code(); if (!authName.empty()) { const auto tmpFactory = (preferredAuthName == authName) ? create(databaseContext(), authName) : NN_NO_CHECK(d->getSharedFromThis()); auto l_candidates = tmpFactory->createGeodeticCRSFromDatum( authName, code, geodetic_crs_type); for (const auto &candidate : l_candidates) { candidates.emplace_back(candidate); } } } } else if (datumName != "unknown" && datumName != "unnamed") { auto matches = createObjectsFromName( datumName, {io::AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, false, 2); if (matches.size() == 1) { const auto &match = matches.front(); if (datum->_isEquivalentTo(match.get(), util::IComparable::Criterion::EQUIVALENT, databaseContext().as_nullable()) && !match->identifiers().empty()) { return createGeodeticCRSFromDatum( util::nn_static_pointer_cast<datum::GeodeticReferenceFrame>( match), preferredAuthName, geodetic_crs_type); } } } return candidates; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<crs::VerticalCRSNNPtr> AuthorityFactory::createVerticalCRSFromDatum( const std::string &datum_auth_name, const std::string &datum_code) const { std::string sql( "SELECT auth_name, code FROM vertical_crs WHERE " "datum_auth_name = ? AND datum_code = ? AND deprecated = 0"); ListOfParams params{datum_auth_name, datum_code}; if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; params.emplace_back(d->authority()); } auto sqlRes = d->run(sql, params); std::list<crs::VerticalCRSNNPtr> res; for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back(d->createFactory(auth_name)->createVerticalCRS(code)); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<crs::GeodeticCRSNNPtr> AuthorityFactory::createGeodeticCRSFromEllipsoid( const std::string &ellipsoid_auth_name, const std::string &ellipsoid_code, const std::string &geodetic_crs_type) const { std::string sql( "SELECT geodetic_crs.auth_name, geodetic_crs.code FROM geodetic_crs " "JOIN geodetic_datum ON " "geodetic_crs.datum_auth_name = geodetic_datum.auth_name AND " "geodetic_crs.datum_code = geodetic_datum.code WHERE " "geodetic_datum.ellipsoid_auth_name = ? AND " "geodetic_datum.ellipsoid_code = ? AND " "geodetic_datum.deprecated = 0 AND " "geodetic_crs.deprecated = 0"); ListOfParams params{ellipsoid_auth_name, ellipsoid_code}; if (d->hasAuthorityRestriction()) { sql += " AND geodetic_crs.auth_name = ?"; params.emplace_back(d->authority()); } if (!geodetic_crs_type.empty()) { sql += " AND geodetic_crs.type = ?"; params.emplace_back(geodetic_crs_type); } auto sqlRes = d->run(sql, params); std::list<crs::GeodeticCRSNNPtr> res; for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back(d->createFactory(auth_name)->createGeodeticCRS(code)); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static std::string buildSqlLookForAuthNameCode( const std::list<std::pair<crs::CRSNNPtr, int>> &list, ListOfParams &params, const char *prefixField) { std::string sql("("); std::set<std::string> authorities; for (const auto &crs : list) { auto boundCRS = dynamic_cast<crs::BoundCRS *>(crs.first.get()); const auto &ids = boundCRS ? boundCRS->baseCRS()->identifiers() : crs.first->identifiers(); if (!ids.empty()) { authorities.insert(*(ids[0]->codeSpace())); } } bool firstAuth = true; for (const auto &auth_name : authorities) { if (!firstAuth) { sql += " OR "; } firstAuth = false; sql += "( "; sql += prefixField; sql += "auth_name = ? AND "; sql += prefixField; sql += "code IN ("; params.emplace_back(auth_name); bool firstGeodCRSForAuth = true; for (const auto &crs : list) { auto boundCRS = dynamic_cast<crs::BoundCRS *>(crs.first.get()); const auto &ids = boundCRS ? boundCRS->baseCRS()->identifiers() : crs.first->identifiers(); if (!ids.empty() && *(ids[0]->codeSpace()) == auth_name) { if (!firstGeodCRSForAuth) { sql += ','; } firstGeodCRSForAuth = false; sql += '?'; params.emplace_back(ids[0]->code()); } } sql += "))"; } sql += ')'; return sql; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<crs::ProjectedCRSNNPtr> AuthorityFactory::createProjectedCRSFromExisting( const crs::ProjectedCRSNNPtr &crs) const { std::list<crs::ProjectedCRSNNPtr> res; const auto &conv = crs->derivingConversionRef(); const auto &method = conv->method(); const auto methodEPSGCode = method->getEPSGCode(); if (methodEPSGCode == 0) { return res; } auto lockedThisFactory(d->getSharedFromThis()); assert(lockedThisFactory); const auto &baseCRS(crs->baseCRS()); auto candidatesGeodCRS = baseCRS->crs::CRS::identify(lockedThisFactory); auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(baseCRS.get()); if (geogCRS) { const auto axisOrder = geogCRS->coordinateSystem()->axisOrder(); if (axisOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH || axisOrder == cs::EllipsoidalCS::AxisOrder::LAT_NORTH_LONG_EAST) { const auto &unit = geogCRS->coordinateSystem()->axisList()[0]->unit(); auto otherOrderGeogCRS = crs::GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, geogCRS->nameStr()), geogCRS->datum(), geogCRS->datumEnsemble(), axisOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH ? cs::EllipsoidalCS::createLatitudeLongitude(unit) : cs::EllipsoidalCS::createLongitudeLatitude(unit)); auto otherCandidatesGeodCRS = otherOrderGeogCRS->crs::CRS::identify(lockedThisFactory); candidatesGeodCRS.insert(candidatesGeodCRS.end(), otherCandidatesGeodCRS.begin(), otherCandidatesGeodCRS.end()); } } std::string sql( "SELECT projected_crs.auth_name, projected_crs.code FROM projected_crs " "JOIN conversion_table conv ON " "projected_crs.conversion_auth_name = conv.auth_name AND " "projected_crs.conversion_code = conv.code WHERE " "projected_crs.deprecated = 0 AND "); ListOfParams params; if (!candidatesGeodCRS.empty()) { sql += buildSqlLookForAuthNameCode(candidatesGeodCRS, params, "projected_crs.geodetic_crs_"); sql += " AND "; } sql += "conv.method_auth_name = 'EPSG' AND " "conv.method_code = ?"; params.emplace_back(toString(methodEPSGCode)); if (d->hasAuthorityRestriction()) { sql += " AND projected_crs.auth_name = ?"; params.emplace_back(d->authority()); } int iParam = 0; bool hasLat1stStd = false; double lat1stStd = 0; int iParamLat1stStd = 0; bool hasLat2ndStd = false; double lat2ndStd = 0; int iParamLat2ndStd = 0; for (const auto &genOpParamvalue : conv->parameterValues()) { iParam++; auto opParamvalue = dynamic_cast<const operation::OperationParameterValue *>( genOpParamvalue.get()); if (!opParamvalue) { break; } const auto paramEPSGCode = opParamvalue->parameter()->getEPSGCode(); const auto &parameterValue = opParamvalue->parameterValue(); if (!(paramEPSGCode > 0 && parameterValue->type() == operation::ParameterValue::Type::MEASURE)) { break; } const auto &measure = parameterValue->value(); const auto &unit = measure.unit(); if (unit == common::UnitOfMeasure::DEGREE && baseCRS->coordinateSystem()->axisList()[0]->unit() == unit) { if (methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP) { // Special case for standard parallels of LCC_2SP. See below if (paramEPSGCode == EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL) { hasLat1stStd = true; lat1stStd = measure.value(); iParamLat1stStd = iParam; continue; } else if (paramEPSGCode == EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL) { hasLat2ndStd = true; lat2ndStd = measure.value(); iParamLat2ndStd = iParam; continue; } } const auto iParamAsStr(toString(iParam)); sql += " AND conv.param"; sql += iParamAsStr; sql += "_code = ? AND conv.param"; sql += iParamAsStr; sql += "_auth_name = 'EPSG' AND conv.param"; sql += iParamAsStr; sql += "_value BETWEEN ? AND ?"; // As angles might be expressed with the odd unit EPSG:9110 // "sexagesimal DMS", we have to provide a broad range params.emplace_back(toString(paramEPSGCode)); params.emplace_back(measure.value() - 1); params.emplace_back(measure.value() + 1); } } // Special case for standard parallels of LCC_2SP: they can be switched if (methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP && hasLat1stStd && hasLat2ndStd) { const auto iParam1AsStr(toString(iParamLat1stStd)); const auto iParam2AsStr(toString(iParamLat2ndStd)); sql += " AND conv.param"; sql += iParam1AsStr; sql += "_code = ? AND conv.param"; sql += iParam1AsStr; sql += "_auth_name = 'EPSG' AND conv.param"; sql += iParam2AsStr; sql += "_code = ? AND conv.param"; sql += iParam2AsStr; sql += "_auth_name = 'EPSG' AND (("; params.emplace_back( toString(EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL)); params.emplace_back( toString(EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL)); double val1 = lat1stStd; double val2 = lat2ndStd; for (int i = 0; i < 2; i++) { if (i == 1) { sql += ") OR ("; std::swap(val1, val2); } sql += "conv.param"; sql += iParam1AsStr; sql += "_value BETWEEN ? AND ? AND conv.param"; sql += iParam2AsStr; sql += "_value BETWEEN ? AND ?"; params.emplace_back(val1 - 1); params.emplace_back(val1 + 1); params.emplace_back(val2 - 1); params.emplace_back(val2 + 1); } sql += "))"; } auto sqlRes = d->run(sql, params); params.clear(); sql = "SELECT auth_name, code FROM projected_crs WHERE " "deprecated = 0 AND conversion_auth_name IS NULL AND "; if (!candidatesGeodCRS.empty()) { sql += buildSqlLookForAuthNameCode(candidatesGeodCRS, params, "geodetic_crs_"); sql += " AND "; } const auto escapeLikeStr = [](const std::string &str) { return replaceAll(replaceAll(replaceAll(str, "\\", "\\\\"), "_", "\\_"), "%", "\\%"); }; const auto ellpsSemiMajorStr = toString(baseCRS->ellipsoid()->semiMajorAxis().getSIValue(), 10); sql += "(text_definition LIKE ? ESCAPE '\\'"; // WKT2 definition { std::string patternVal("%"); patternVal += ','; patternVal += ellpsSemiMajorStr; patternVal += '%'; patternVal += escapeLikeStr(method->nameStr()); patternVal += '%'; params.emplace_back(patternVal); } const auto *mapping = getMapping(method.get()); if (mapping && mapping->proj_name_main) { sql += " OR (text_definition LIKE ? AND (text_definition LIKE ?"; std::string patternVal("%"); patternVal += "proj="; patternVal += mapping->proj_name_main; patternVal += '%'; params.emplace_back(patternVal); // could be a= or R= patternVal = "%="; patternVal += ellpsSemiMajorStr; patternVal += '%'; params.emplace_back(patternVal); std::string projEllpsName; std::string ellpsName; if (baseCRS->ellipsoid()->lookForProjWellKnownEllps(projEllpsName, ellpsName)) { sql += " OR text_definition LIKE ?"; // Could be ellps= or datum= patternVal = "%="; patternVal += projEllpsName; patternVal += '%'; params.emplace_back(patternVal); } sql += "))"; } // WKT1_GDAL definition const char *wkt1GDALMethodName = conv->getWKT1GDALMethodName(); if (wkt1GDALMethodName) { sql += " OR text_definition LIKE ? ESCAPE '\\'"; std::string patternVal("%"); patternVal += ','; patternVal += ellpsSemiMajorStr; patternVal += '%'; patternVal += escapeLikeStr(wkt1GDALMethodName); patternVal += '%'; params.emplace_back(patternVal); } // WKT1_ESRI definition const char *esriMethodName = conv->getESRIMethodName(); if (esriMethodName) { sql += " OR text_definition LIKE ? ESCAPE '\\'"; std::string patternVal("%"); patternVal += ','; patternVal += ellpsSemiMajorStr; patternVal += '%'; patternVal += escapeLikeStr(esriMethodName); patternVal += '%'; auto fe = &conv->parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_EASTING); if (*fe == Measure()) { fe = &conv->parameterValueMeasure( EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN); } if (!(*fe == Measure())) { patternVal += "PARAMETER[\"False\\_Easting\","; patternVal += toString(fe->convertToUnit( crs->coordinateSystem()->axisList()[0]->unit()), 10); patternVal += '%'; } auto lat = &conv->parameterValueMeasure( EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN); if (*lat == Measure()) { lat = &conv->parameterValueMeasure( EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN); } if (!(*lat == Measure())) { patternVal += "PARAMETER[\"Latitude\\_Of\\_Origin\","; const auto &angularUnit = dynamic_cast<crs::GeographicCRS *>(crs->baseCRS().get()) ? crs->baseCRS()->coordinateSystem()->axisList()[0]->unit() : UnitOfMeasure::DEGREE; patternVal += toString(lat->convertToUnit(angularUnit), 10); patternVal += '%'; } params.emplace_back(patternVal); } sql += ")"; if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; params.emplace_back(d->authority()); } auto sqlRes2 = d->run(sql, params); if (sqlRes.size() <= 200) { for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back( d->createFactory(auth_name)->createProjectedCRS(code)); } } if (sqlRes2.size() <= 200) { for (const auto &row : sqlRes2) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back( d->createFactory(auth_name)->createProjectedCRS(code)); } } return res; } // --------------------------------------------------------------------------- std::list<crs::CompoundCRSNNPtr> AuthorityFactory::createCompoundCRSFromExisting( const crs::CompoundCRSNNPtr &crs) const { std::list<crs::CompoundCRSNNPtr> res; auto lockedThisFactory(d->getSharedFromThis()); assert(lockedThisFactory); const auto &components = crs->componentReferenceSystems(); if (components.size() != 2) { return res; } auto candidatesHorizCRS = components[0]->identify(lockedThisFactory); auto candidatesVertCRS = components[1]->identify(lockedThisFactory); if (candidatesHorizCRS.empty() && candidatesVertCRS.empty()) { return res; } std::string sql("SELECT auth_name, code FROM compound_crs WHERE " "deprecated = 0 AND "); ListOfParams params; bool addAnd = false; if (!candidatesHorizCRS.empty()) { sql += buildSqlLookForAuthNameCode(candidatesHorizCRS, params, "horiz_crs_"); addAnd = true; } if (!candidatesVertCRS.empty()) { if (addAnd) { sql += " AND "; } sql += buildSqlLookForAuthNameCode(candidatesVertCRS, params, "vertical_crs_"); addAnd = true; } if (d->hasAuthorityRestriction()) { if (addAnd) { sql += " AND "; } sql += "auth_name = ?"; params.emplace_back(d->authority()); } auto sqlRes = d->run(sql, params); for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back(d->createFactory(auth_name)->createCompoundCRS(code)); } return res; } // --------------------------------------------------------------------------- std::vector<operation::CoordinateOperationNNPtr> AuthorityFactory::getTransformationsForGeoid( const std::string &geoidName, bool usePROJAlternativeGridNames) const { std::vector<operation::CoordinateOperationNNPtr> res; const std::string sql("SELECT operation_auth_name, operation_code FROM " "geoid_model WHERE name = ?"); auto sqlRes = d->run(sql, {geoidName}); for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; res.emplace_back(d->createFactory(auth_name)->createCoordinateOperation( code, usePROJAlternativeGridNames)); } return res; } // --------------------------------------------------------------------------- std::vector<operation::PointMotionOperationNNPtr> AuthorityFactory::getPointMotionOperationsFor( const crs::GeodeticCRSNNPtr &crs, bool usePROJAlternativeGridNames) const { std::vector<operation::PointMotionOperationNNPtr> res; const auto crsList = createGeodeticCRSFromDatum(crs->datumNonNull(d->context()), /* preferredAuthName = */ std::string(), /* geodetic_crs_type = */ std::string()); if (crsList.empty()) return res; std::string sql("SELECT auth_name, code FROM coordinate_operation_view " "WHERE source_crs_auth_name = target_crs_auth_name AND " "source_crs_code = target_crs_code AND deprecated = 0 AND " "("); bool addOr = false; ListOfParams params; for (const auto &candidateCrs : crsList) { if (addOr) sql += " OR "; addOr = true; sql += "(source_crs_auth_name = ? AND source_crs_code = ?)"; const auto &ids = candidateCrs->identifiers(); params.emplace_back(*(ids[0]->codeSpace())); params.emplace_back(ids[0]->code()); } sql += ")"; if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; params.emplace_back(d->authority()); } auto sqlRes = d->run(sql, params); for (const auto &row : sqlRes) { const auto &auth_name = row[0]; const auto &code = row[1]; auto pmo = util::nn_dynamic_pointer_cast<operation::PointMotionOperation>( d->createFactory(auth_name)->createCoordinateOperation( code, usePROJAlternativeGridNames)); if (pmo) { res.emplace_back(NN_NO_CHECK(pmo)); } } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress FactoryException::FactoryException(const char *message) : Exception(message) {} // --------------------------------------------------------------------------- FactoryException::FactoryException(const std::string &message) : Exception(message) {} // --------------------------------------------------------------------------- FactoryException::~FactoryException() = default; // --------------------------------------------------------------------------- FactoryException::FactoryException(const FactoryException &) = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct NoSuchAuthorityCodeException::Private { std::string authority_; std::string code_; Private(const std::string &authority, const std::string &code) : authority_(authority), code_(code) {} }; // --------------------------------------------------------------------------- NoSuchAuthorityCodeException::NoSuchAuthorityCodeException( const std::string &message, const std::string &authority, const std::string &code) : FactoryException(message), d(internal::make_unique<Private>(authority, code)) {} // --------------------------------------------------------------------------- NoSuchAuthorityCodeException::~NoSuchAuthorityCodeException() = default; // --------------------------------------------------------------------------- NoSuchAuthorityCodeException::NoSuchAuthorityCodeException( const NoSuchAuthorityCodeException &other) : FactoryException(other), d(internal::make_unique<Private>(*(other.d))) {} //! @endcond // --------------------------------------------------------------------------- /** \brief Returns authority name. */ const std::string &NoSuchAuthorityCodeException::getAuthority() const { return d->authority_; } // --------------------------------------------------------------------------- /** \brief Returns authority code. */ const std::string &NoSuchAuthorityCodeException::getAuthorityCode() const { return d->code_; } // --------------------------------------------------------------------------- } // namespace io NS_PROJ_END // --------------------------------------------------------------------------- void pj_clear_sqlite_cache() { NS_PROJ::io::SQLiteHandleCache::get().clear(); }
cpp
PROJ
data/projects/PROJ/src/iso19111/coordinatesystem.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/coordinatesystem.hpp" #include "proj/common.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/coordinatesystem_internal.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj_json_streaming_writer.hpp" #include <map> #include <memory> #include <set> #include <string> #include <vector> using namespace NS_PROJ::internal; #if 0 namespace dropbox{ namespace oxygen { template<> nn<NS_PROJ::cs::MeridianPtr>::~nn() = default; template<> nn<NS_PROJ::cs::CoordinateSystemAxisPtr>::~nn() = default; template<> nn<NS_PROJ::cs::CoordinateSystemPtr>::~nn() = default; template<> nn<NS_PROJ::cs::SphericalCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::EllipsoidalCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::CartesianCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::TemporalCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::TemporalCountCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::TemporalMeasureCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::DateTimeTemporalCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::VerticalCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::ParametricCSPtr>::~nn() = default; template<> nn<NS_PROJ::cs::OrdinalCSPtr>::~nn() = default; }} #endif NS_PROJ_START namespace cs { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Meridian::Private { common::Angle longitude_{}; explicit Private(const common::Angle &longitude) : longitude_(longitude) {} }; //! @endcond // --------------------------------------------------------------------------- Meridian::Meridian(const common::Angle &longitudeIn) : d(internal::make_unique<Private>(longitudeIn)) {} // --------------------------------------------------------------------------- #ifdef notdef Meridian::Meridian(const Meridian &other) : IdentifiedObject(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Meridian::~Meridian() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the longitude of the meridian that the axis follows from the * pole. * * @return the longitude. */ const common::Angle &Meridian::longitude() PROJ_PURE_DEFN { return d->longitude_; } // --------------------------------------------------------------------------- /** \brief Instantiate a Meridian. * * @param longitudeIn longitude of the meridian that the axis follows from the * pole. * @return new Meridian. */ MeridianNNPtr Meridian::create(const common::Angle &longitudeIn) { return Meridian::nn_make_shared<Meridian>(longitudeIn); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Meridian::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { formatter->startNode(io::WKTConstants::MERIDIAN, !identifiers().empty()); formatter->add(longitude().value()); longitude().unit()._exportToWKT(formatter, io::WKTConstants::ANGLEUNIT); if (formatter->outputId()) { formatID(formatter); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Meridian::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("Meridian", !identifiers().empty())); const auto &l_long = longitude(); writer->AddObjKey("longitude"); const auto &unit = l_long.unit(); if (unit == common::UnitOfMeasure::DEGREE) { writer->Add(l_long.value(), 15); } else { auto longitudeContext(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("value"); writer->Add(l_long.value(), 15); writer->AddObjKey("unit"); unit._exportToJSON(formatter); } if (formatter->outputId()) { formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CoordinateSystemAxis::Private { std::string abbreviation{}; const AxisDirection *direction = &(AxisDirection::UNSPECIFIED); common::UnitOfMeasure unit{}; util::optional<RangeMeaning> rangeMeaning = util::optional<RangeMeaning>(); util::optional<double> minimumValue{}; util::optional<double> maximumValue{}; MeridianPtr meridian{}; }; //! @endcond // --------------------------------------------------------------------------- CoordinateSystemAxis::CoordinateSystemAxis() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- #ifdef notdef CoordinateSystemAxis::CoordinateSystemAxis(const CoordinateSystemAxis &other) : IdentifiedObject(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateSystemAxis::~CoordinateSystemAxis() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the axis abbreviation. * * The abbreviation used for this coordinate system axis; this abbreviation * is also used to identify the coordinates in the coordinate tuple. * Examples are X and Y. * * @return the abbreviation. */ const std::string &CoordinateSystemAxis::abbreviation() PROJ_PURE_DEFN { return d->abbreviation; } // --------------------------------------------------------------------------- /** \brief Return the axis direction. * * The direction of this coordinate system axis (or in the case of Cartesian * projected coordinates, the direction of this coordinate system axis locally) * Examples: north or south, east or west, up or down. Within any set of * coordinate system axes, only one of each pair of terms can be used. For * Earth-fixed CRSs, this direction is often approximate and intended to * provide a human interpretable meaning to the axis. When a geodetic reference * frame is used, the precise directions of the axes may therefore vary * slightly from this approximate direction. Note that an EngineeringCRS often * requires specific descriptions of the directions of its coordinate system * axes. * * @return the direction. */ const AxisDirection &CoordinateSystemAxis::direction() PROJ_PURE_DEFN { return *(d->direction); } // --------------------------------------------------------------------------- /** \brief Return the axis unit. * * This is the spatial unit or temporal quantity used for this coordinate * system axis. The value of a coordinate in a coordinate tuple shall be * recorded using this unit. * * @return the axis unit. */ const common::UnitOfMeasure &CoordinateSystemAxis::unit() PROJ_PURE_DEFN { return d->unit; } // --------------------------------------------------------------------------- /** \brief Return the minimum value normally allowed for this axis, in the unit * for the axis. * * @return the minimum value, or empty. */ const util::optional<double> & CoordinateSystemAxis::minimumValue() PROJ_PURE_DEFN { return d->minimumValue; } // --------------------------------------------------------------------------- /** \brief Return the maximum value normally allowed for this axis, in the unit * for the axis. * * @return the maximum value, or empty. */ const util::optional<double> & CoordinateSystemAxis::maximumValue() PROJ_PURE_DEFN { return d->maximumValue; } // --------------------------------------------------------------------------- /** \brief Return the range meaning * * @return the range meaning, or empty. * @since 9.2 */ const util::optional<RangeMeaning> & CoordinateSystemAxis::rangeMeaning() PROJ_PURE_DEFN { return d->rangeMeaning; } // --------------------------------------------------------------------------- /** \brief Return the meridian that the axis follows from the pole, for a * coordinate * reference system centered on a pole. * * @return the meridian, or null. */ const MeridianPtr &CoordinateSystemAxis::meridian() PROJ_PURE_DEFN { return d->meridian; } // --------------------------------------------------------------------------- /** \brief Instantiate a CoordinateSystemAxis. * * @param properties See \ref general_properties. The name should generally be * defined. * @param abbreviationIn Axis abbreviation (might be empty) * @param directionIn Axis direction * @param unitIn Axis unit * @param meridianIn The meridian that the axis follows from the pole, for a * coordinate * reference system centered on a pole, or nullptr * @return a new CoordinateSystemAxis. */ CoordinateSystemAxisNNPtr CoordinateSystemAxis::create( const util::PropertyMap &properties, const std::string &abbreviationIn, const AxisDirection &directionIn, const common::UnitOfMeasure &unitIn, const MeridianPtr &meridianIn) { auto csa(CoordinateSystemAxis::nn_make_shared<CoordinateSystemAxis>()); csa->setProperties(properties); csa->d->abbreviation = abbreviationIn; csa->d->direction = &directionIn; csa->d->unit = unitIn; csa->d->meridian = meridianIn; return csa; } // --------------------------------------------------------------------------- /** \brief Instantiate a CoordinateSystemAxis. * * @param properties See \ref general_properties. The name should generally be * defined. * @param abbreviationIn Axis abbreviation (might be empty) * @param directionIn Axis direction * @param unitIn Axis unit * @param minimumValueIn Minimum value along axis * @param maximumValueIn Maximum value along axis * @param rangeMeaningIn Range Meaning * @param meridianIn The meridian that the axis follows from the pole, for a * coordinate * reference system centered on a pole, or nullptr * @return a new CoordinateSystemAxis. * @since 9.2 */ CoordinateSystemAxisNNPtr CoordinateSystemAxis::create( const util::PropertyMap &properties, const std::string &abbreviationIn, const AxisDirection &directionIn, const common::UnitOfMeasure &unitIn, const util::optional<double> &minimumValueIn, const util::optional<double> &maximumValueIn, const util::optional<RangeMeaning> &rangeMeaningIn, const MeridianPtr &meridianIn) { auto csa(CoordinateSystemAxis::nn_make_shared<CoordinateSystemAxis>()); csa->setProperties(properties); csa->d->abbreviation = abbreviationIn; csa->d->direction = &directionIn; csa->d->unit = unitIn; csa->d->minimumValue = minimumValueIn; csa->d->maximumValue = maximumValueIn; csa->d->rangeMeaning = rangeMeaningIn; csa->d->meridian = meridianIn; return csa; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateSystemAxis::_exportToWKT( // cppcheck-suppress passedByValue io::WKTFormatter *formatter) const // throw(FormattingException) { _exportToWKT(formatter, 0, false); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::string CoordinateSystemAxis::normalizeAxisName(const std::string &str) { if (str.empty()) { return str; } // on import, transform from WKT2 "longitude" to "Longitude", as in the // EPSG database. return toupper(str.substr(0, 1)) + str.substr(1); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateSystemAxis::_exportToWKT(io::WKTFormatter *formatter, int order, bool disableAbbrev) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; formatter->startNode(io::WKTConstants::AXIS, !identifiers().empty()); const std::string &axisName = nameStr(); const std::string &abbrev = abbreviation(); const std::string parenthesizedAbbrev = "(" + abbrev + ")"; std::string dir = direction().toString(); std::string axisDesignation; // It seems that the convention in WKT2 for axis name is first letter in // lower case. Whereas in WKT1 GDAL, it is in upper case (as in the EPSG // database) if (!axisName.empty()) { if (isWKT2) { axisDesignation = tolower(axisName.substr(0, 1)) + axisName.substr(1); } else { if (axisName == "Geodetic latitude") { axisDesignation = "Latitude"; } else if (axisName == "Geodetic longitude") { axisDesignation = "Longitude"; } else { axisDesignation = axisName; } } } if (!disableAbbrev && isWKT2 && // For geodetic CS, export the axis name without abbreviation !(axisName == AxisName::Latitude || axisName == AxisName::Longitude)) { if (!axisDesignation.empty() && !abbrev.empty()) { axisDesignation += " "; } if (!abbrev.empty()) { axisDesignation += parenthesizedAbbrev; } } if (!isWKT2) { dir = toupper(dir); if (direction() == AxisDirection::GEOCENTRIC_Z) { dir = AxisDirectionWKT1::NORTH; } else if (AxisDirectionWKT1::valueOf(dir) == nullptr) { dir = AxisDirectionWKT1::OTHER; } } else if (!abbrev.empty()) { // For geocentric CS, just put the abbreviation if (direction() == AxisDirection::GEOCENTRIC_X || direction() == AxisDirection::GEOCENTRIC_Y || direction() == AxisDirection::GEOCENTRIC_Z) { axisDesignation = parenthesizedAbbrev; } // For cartesian CS with Easting/Northing, export only the abbreviation else if ((order == 1 && axisName == AxisName::Easting && abbrev == AxisAbbreviation::E) || (order == 2 && axisName == AxisName::Northing && abbrev == AxisAbbreviation::N)) { axisDesignation = parenthesizedAbbrev; } } formatter->addQuotedString(axisDesignation); formatter->add(dir); const auto &l_meridian = meridian(); if (isWKT2 && l_meridian) { l_meridian->_exportToWKT(formatter); } if (formatter->outputAxisOrder() && order > 0) { formatter->startNode(io::WKTConstants::ORDER, false); formatter->add(order); formatter->endNode(); } if (formatter->outputUnit() && unit().type() != common::UnitOfMeasure::Type::NONE) { unit()._exportToWKT(formatter); } if (isWKT2 && formatter->use2019Keywords()) { if (d->minimumValue.has_value()) { formatter->startNode(io::WKTConstants::AXISMINVALUE, false); formatter->add(*(d->minimumValue)); formatter->endNode(); } if (d->maximumValue.has_value()) { formatter->startNode(io::WKTConstants::AXISMAXVALUE, false); formatter->add(*(d->maximumValue)); formatter->endNode(); } if (d->minimumValue.has_value() && d->maximumValue.has_value() && d->rangeMeaning.has_value()) { formatter->startNode(io::WKTConstants::RANGEMEANING, false); formatter->add(d->rangeMeaning->toString()); formatter->endNode(); } } if (formatter->outputId()) { formatID(formatter); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateSystemAxis::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("Axis", !identifiers().empty())); writer->AddObjKey("name"); writer->Add(nameStr()); writer->AddObjKey("abbreviation"); writer->Add(abbreviation()); writer->AddObjKey("direction"); writer->Add(direction().toString()); const auto &l_meridian = meridian(); if (l_meridian) { writer->AddObjKey("meridian"); formatter->setOmitTypeInImmediateChild(); l_meridian->_exportToJSON(formatter); } const auto &l_unit(unit()); if (l_unit == common::UnitOfMeasure::METRE || l_unit == common::UnitOfMeasure::DEGREE) { writer->AddObjKey("unit"); writer->Add(l_unit.name()); } else if (l_unit.type() != common::UnitOfMeasure::Type::NONE) { writer->AddObjKey("unit"); l_unit._exportToJSON(formatter); } if (d->minimumValue.has_value()) { writer->AddObjKey("minimum_value"); writer->Add(*(d->minimumValue)); } if (d->maximumValue.has_value()) { writer->AddObjKey("maximum_value"); writer->Add(*(d->maximumValue)); } if (d->minimumValue.has_value() && d->maximumValue.has_value() && d->rangeMeaning.has_value()) { writer->AddObjKey("range_meaning"); writer->Add(d->rangeMeaning->toString()); } if (formatter->outputId()) { formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool CoordinateSystemAxis::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherCSA = dynamic_cast<const CoordinateSystemAxis *>(other); if (otherCSA == nullptr) { return false; } // For approximate comparison, only care about axis direction and unit. if (!(*(d->direction) == *(otherCSA->d->direction) && d->unit._isEquivalentTo(otherCSA->d->unit, criterion))) { return false; } if (criterion == util::IComparable::Criterion::STRICT) { if (!IdentifiedObject::_isEquivalentTo(other, criterion, dbContext)) { return false; } if (abbreviation() != otherCSA->abbreviation()) { return false; } // TODO other metadata } return true; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateSystemAxisNNPtr CoordinateSystemAxis::alterUnit(const common::UnitOfMeasure &newUnit) const { return create(util::PropertyMap().set(IdentifiedObject::NAME_KEY, name()), abbreviation(), direction(), newUnit, meridian()); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CoordinateSystem::Private { std::vector<CoordinateSystemAxisNNPtr> axisList{}; explicit Private(const std::vector<CoordinateSystemAxisNNPtr> &axisListIn) : axisList(axisListIn) {} }; //! @endcond // --------------------------------------------------------------------------- CoordinateSystem::CoordinateSystem( const std::vector<CoordinateSystemAxisNNPtr> &axisIn) : d(internal::make_unique<Private>(axisIn)) {} // --------------------------------------------------------------------------- #ifdef notdef CoordinateSystem::CoordinateSystem(const CoordinateSystem &other) : IdentifiedObject(other), d(internal::make_unique<Private>(*other.d)) {} #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateSystem::~CoordinateSystem() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the list of axes of this coordinate system. * * @return the axes. */ const std::vector<CoordinateSystemAxisNNPtr> & CoordinateSystem::axisList() PROJ_PURE_DEFN { return d->axisList; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateSystem::_exportToWKT( io::WKTFormatter *formatter) const // throw(FormattingException) { if (formatter->outputAxis() != io::WKTFormatter::OutputAxisRule::YES) { return; } const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; const auto &l_axisList = axisList(); if (isWKT2) { formatter->startNode(io::WKTConstants::CS_, !identifiers().empty()); formatter->add(getWKT2Type(formatter->use2019Keywords())); formatter->add(static_cast<int>(l_axisList.size())); formatter->endNode(); formatter->startNode(std::string(), false); // anonymous indentation level } common::UnitOfMeasure unit = common::UnitOfMeasure::NONE; bool bAllSameUnit = true; bool bFirstUnit = true; for (const auto &axis : l_axisList) { const auto &l_unit = axis->unit(); if (bFirstUnit) { unit = l_unit; bFirstUnit = false; } else if (unit != l_unit) { bAllSameUnit = false; } } formatter->pushOutputUnit( isWKT2 && (!bAllSameUnit || !formatter->outputCSUnitOnlyOnceIfSame())); int order = 1; const bool disableAbbrev = (l_axisList.size() == 3 && l_axisList[0]->nameStr() == AxisName::Latitude && l_axisList[1]->nameStr() == AxisName::Longitude && l_axisList[2]->nameStr() == AxisName::Ellipsoidal_height); for (auto &axis : l_axisList) { int axisOrder = (isWKT2 && l_axisList.size() > 1) ? order : 0; axis->_exportToWKT(formatter, axisOrder, disableAbbrev); order++; } if (isWKT2 && !l_axisList.empty() && bAllSameUnit && formatter->outputCSUnitOnlyOnceIfSame()) { unit._exportToWKT(formatter); } formatter->popOutputUnit(); if (isWKT2) { formatter->endNode(); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateSystem::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext(formatter->MakeObjectContext("CoordinateSystem", !identifiers().empty())); writer->AddObjKey("subtype"); writer->Add(getWKT2Type(true)); writer->AddObjKey("axis"); { auto axisContext(writer->MakeArrayContext(false)); const auto &l_axisList = axisList(); for (auto &axis : l_axisList) { formatter->setOmitTypeInImmediateChild(); axis->_exportToJSON(formatter); } } if (formatter->outputId()) { formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool CoordinateSystem::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherCS = dynamic_cast<const CoordinateSystem *>(other); if (otherCS == nullptr || !IdentifiedObject::_isEquivalentTo(other, criterion, dbContext)) { return false; } const auto &list = axisList(); const auto &otherList = otherCS->axisList(); if (list.size() != otherList.size()) { return false; } if (getWKT2Type(true) != otherCS->getWKT2Type(true)) { return false; } for (size_t i = 0; i < list.size(); i++) { if (!list[i]->_isEquivalentTo(otherList[i].get(), criterion, dbContext)) { return false; } } return true; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress SphericalCS::~SphericalCS() = default; //! @endcond // --------------------------------------------------------------------------- SphericalCS::SphericalCS(const std::vector<CoordinateSystemAxisNNPtr> &axisIn) : CoordinateSystem(axisIn) {} // --------------------------------------------------------------------------- #ifdef notdef SphericalCS::SphericalCS(const SphericalCS &) = default; #endif // --------------------------------------------------------------------------- /** \brief Instantiate a SphericalCS. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @param axis3 The third axis. * @return a new SphericalCS. */ SphericalCSNNPtr SphericalCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2, axis3}; auto cs(SphericalCS::nn_make_shared<SphericalCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- /** \brief Instantiate a SphericalCS with 2 axis. * * This is an extension to ISO19111 to support (planet)-ocentric CS with * geocentric latitude. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @return a new SphericalCS. */ SphericalCSNNPtr SphericalCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2}; auto cs(SphericalCS::nn_make_shared<SphericalCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress EllipsoidalCS::~EllipsoidalCS() = default; //! @endcond // --------------------------------------------------------------------------- EllipsoidalCS::EllipsoidalCS( const std::vector<CoordinateSystemAxisNNPtr> &axisIn) : CoordinateSystem(axisIn) {} // --------------------------------------------------------------------------- #ifdef notdef EllipsoidalCS::EllipsoidalCS(const EllipsoidalCS &) = default; #endif // --------------------------------------------------------------------------- /** \brief Instantiate a EllipsoidalCS. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @return a new EllipsoidalCS. */ EllipsoidalCSNNPtr EllipsoidalCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2}; auto cs(EllipsoidalCS::nn_make_shared<EllipsoidalCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- /** \brief Instantiate a EllipsoidalCS. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @param axis3 The third axis. * @return a new EllipsoidalCS. */ EllipsoidalCSNNPtr EllipsoidalCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2, axis3}; auto cs(EllipsoidalCS::nn_make_shared<EllipsoidalCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateSystemAxisNNPtr CoordinateSystemAxis::createLAT_NORTH(const common::UnitOfMeasure &unit) { return create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Latitude), AxisAbbreviation::lat, AxisDirection::NORTH, unit); } CoordinateSystemAxisNNPtr CoordinateSystemAxis::createLONG_EAST(const common::UnitOfMeasure &unit) { return create(util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Longitude), AxisAbbreviation::lon, AxisDirection::EAST, unit); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a EllipsoidalCS with a Latitude (first) and Longitude * (second) axis. * * @param unit Angular unit of the axes. * @return a new EllipsoidalCS. */ EllipsoidalCSNNPtr EllipsoidalCS::createLatitudeLongitude(const common::UnitOfMeasure &unit) { return EllipsoidalCS::create(util::PropertyMap(), CoordinateSystemAxis::createLAT_NORTH(unit), CoordinateSystemAxis::createLONG_EAST(unit)); } // --------------------------------------------------------------------------- /** \brief Instantiate a EllipsoidalCS with a Latitude (first), Longitude * (second) axis and ellipsoidal height (third) axis. * * @param angularUnit Angular unit of the latitude and longitude axes. * @param linearUnit Linear unit of the ellipsoidal height axis. * @return a new EllipsoidalCS. */ EllipsoidalCSNNPtr EllipsoidalCS::createLatitudeLongitudeEllipsoidalHeight( const common::UnitOfMeasure &angularUnit, const common::UnitOfMeasure &linearUnit) { return EllipsoidalCS::create( util::PropertyMap(), CoordinateSystemAxis::createLAT_NORTH(angularUnit), CoordinateSystemAxis::createLONG_EAST(angularUnit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Ellipsoidal_height), AxisAbbreviation::h, AxisDirection::UP, linearUnit)); } // --------------------------------------------------------------------------- /** \brief Instantiate a EllipsoidalCS with a Longitude (first) and Latitude * (second) axis. * * @param unit Angular unit of the axes. * @return a new EllipsoidalCS. */ EllipsoidalCSNNPtr EllipsoidalCS::createLongitudeLatitude(const common::UnitOfMeasure &unit) { return EllipsoidalCS::create(util::PropertyMap(), CoordinateSystemAxis::createLONG_EAST(unit), CoordinateSystemAxis::createLAT_NORTH(unit)); } // --------------------------------------------------------------------------- /** \brief Instantiate a EllipsoidalCS with a Longitude (first), Latitude * (second) axis and ellipsoidal height (third) axis. * * @param angularUnit Angular unit of the latitude and longitude axes. * @param linearUnit Linear unit of the ellipsoidal height axis. * @return a new EllipsoidalCS. * @since 7.0 */ EllipsoidalCSNNPtr EllipsoidalCS::createLongitudeLatitudeEllipsoidalHeight( const common::UnitOfMeasure &angularUnit, const common::UnitOfMeasure &linearUnit) { return EllipsoidalCS::create( util::PropertyMap(), CoordinateSystemAxis::createLONG_EAST(angularUnit), CoordinateSystemAxis::createLAT_NORTH(angularUnit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Ellipsoidal_height), AxisAbbreviation::h, AxisDirection::UP, linearUnit)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return the axis order in an enumerated way. */ EllipsoidalCS::AxisOrder EllipsoidalCS::axisOrder() const { const auto &l_axisList = CoordinateSystem::getPrivate()->axisList; const auto &dir0 = l_axisList[0]->direction(); const auto &dir1 = l_axisList[1]->direction(); if (&dir0 == &AxisDirection::NORTH && &dir1 == &AxisDirection::EAST) { if (l_axisList.size() == 2) { return AxisOrder::LAT_NORTH_LONG_EAST; } else if (&l_axisList[2]->direction() == &AxisDirection::UP) { return AxisOrder::LAT_NORTH_LONG_EAST_HEIGHT_UP; } } else if (&dir0 == &AxisDirection::EAST && &dir1 == &AxisDirection::NORTH) { if (l_axisList.size() == 2) { return AxisOrder::LONG_EAST_LAT_NORTH; } else if (&l_axisList[2]->direction() == &AxisDirection::UP) { return AxisOrder::LONG_EAST_LAT_NORTH_HEIGHT_UP; } } return AxisOrder::OTHER; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress EllipsoidalCSNNPtr EllipsoidalCS::alterAngularUnit( const common::UnitOfMeasure &angularUnit) const { const auto &l_axisList = CoordinateSystem::getPrivate()->axisList; if (l_axisList.size() == 2) { return EllipsoidalCS::create(util::PropertyMap(), l_axisList[0]->alterUnit(angularUnit), l_axisList[1]->alterUnit(angularUnit)); } else { assert(l_axisList.size() == 3); return EllipsoidalCS::create( util::PropertyMap(), l_axisList[0]->alterUnit(angularUnit), l_axisList[1]->alterUnit(angularUnit), l_axisList[2]); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress EllipsoidalCSNNPtr EllipsoidalCS::alterLinearUnit(const common::UnitOfMeasure &linearUnit) const { const auto &l_axisList = CoordinateSystem::getPrivate()->axisList; if (l_axisList.size() == 2) { return EllipsoidalCS::create(util::PropertyMap(), l_axisList[0], l_axisList[1]); } else { assert(l_axisList.size() == 3); return EllipsoidalCS::create(util::PropertyMap(), l_axisList[0], l_axisList[1], l_axisList[2]->alterUnit(linearUnit)); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress VerticalCS::~VerticalCS() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress VerticalCS::VerticalCS(const CoordinateSystemAxisNNPtr &axisIn) : CoordinateSystem(std::vector<CoordinateSystemAxisNNPtr>{axisIn}) {} //! @endcond // --------------------------------------------------------------------------- #ifdef notdef VerticalCS::VerticalCS(const VerticalCS &) = default; #endif // --------------------------------------------------------------------------- /** \brief Instantiate a VerticalCS. * * @param properties See \ref general_properties. * @param axis The axis. * @return a new VerticalCS. */ VerticalCSNNPtr VerticalCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis) { auto cs(VerticalCS::nn_make_shared<VerticalCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- /** \brief Instantiate a VerticalCS with a Gravity-related height axis * * @param unit linear unit. * @return a new VerticalCS. */ VerticalCSNNPtr VerticalCS::createGravityRelatedHeight(const common::UnitOfMeasure &unit) { auto cs(VerticalCS::nn_make_shared<VerticalCS>(CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, "Gravity-related height"), "H", AxisDirection::UP, unit))); return cs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress VerticalCSNNPtr VerticalCS::alterUnit(const common::UnitOfMeasure &unit) const { const auto &l_axisList = CoordinateSystem::getPrivate()->axisList; return VerticalCS::nn_make_shared<VerticalCS>( l_axisList[0]->alterUnit(unit)); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CartesianCS::~CartesianCS() = default; //! @endcond // --------------------------------------------------------------------------- CartesianCS::CartesianCS(const std::vector<CoordinateSystemAxisNNPtr> &axisIn) : CoordinateSystem(axisIn) {} // --------------------------------------------------------------------------- #ifdef notdef CartesianCS::CartesianCS(const CartesianCS &) = default; #endif // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2}; auto cs(CartesianCS::nn_make_shared<CartesianCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @param axis3 The third axis. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2, axis3}; auto cs(CartesianCS::nn_make_shared<CartesianCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS with a Easting (first) and Northing * (second) axis. * * @param unit Linear unit of the axes. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::createEastingNorthing(const common::UnitOfMeasure &unit) { return create(util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Easting), AxisAbbreviation::E, AxisDirection::EAST, unit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Northing), AxisAbbreviation::N, AxisDirection::NORTH, unit)); } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS with a Northing (first) and Easting * (second) axis. * * @param unit Linear unit of the axes. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::createNorthingEasting(const common::UnitOfMeasure &unit) { return create(util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Northing), AxisAbbreviation::N, AxisDirection::NORTH, unit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Easting), AxisAbbreviation::E, AxisDirection::EAST, unit)); } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS with a Westing (first) and Southing * (second) axis. * * @param unit Linear unit of the axes. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::createWestingSouthing(const common::UnitOfMeasure &unit) { return create(util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Easting), AxisAbbreviation::Y, AxisDirection::WEST, unit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Northing), AxisAbbreviation::X, AxisDirection::SOUTH, unit)); } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS, north-pole centered, * with a Easting (first) South-Oriented and * Northing (second) South-Oriented axis. * * @param unit Linear unit of the axes. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::createNorthPoleEastingSouthNorthingSouth( const common::UnitOfMeasure &unit) { return create(util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Easting), AxisAbbreviation::E, AxisDirection::SOUTH, unit, Meridian::create(common::Angle(90))), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Northing), AxisAbbreviation::N, AxisDirection::SOUTH, unit, Meridian::create(common::Angle(180)))); } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS, south-pole centered, * with a Easting (first) North-Oriented and * Northing (second) North-Oriented axis. * * @param unit Linear unit of the axes. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::createSouthPoleEastingNorthNorthingNorth( const common::UnitOfMeasure &unit) { return create(util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Easting), AxisAbbreviation::E, AxisDirection::NORTH, unit, Meridian::create(common::Angle(90))), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Northing), AxisAbbreviation::N, AxisDirection::NORTH, unit, Meridian::create(common::Angle(0)))); } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesianCS with the three geocentric axes. * * @param unit Linear unit of the axes. * @return a new CartesianCS. */ CartesianCSNNPtr CartesianCS::createGeocentric(const common::UnitOfMeasure &unit) { return create(util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Geocentric_X), AxisAbbreviation::X, AxisDirection::GEOCENTRIC_X, unit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Geocentric_Y), AxisAbbreviation::Y, AxisDirection::GEOCENTRIC_Y, unit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Geocentric_Z), AxisAbbreviation::Z, AxisDirection::GEOCENTRIC_Z, unit)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CartesianCSNNPtr CartesianCS::alterUnit(const common::UnitOfMeasure &unit) const { const auto &l_axisList = CoordinateSystem::getPrivate()->axisList; if (l_axisList.size() == 2) { return CartesianCS::create(util::PropertyMap(), l_axisList[0]->alterUnit(unit), l_axisList[1]->alterUnit(unit)); } else { assert(l_axisList.size() == 3); return CartesianCS::create( util::PropertyMap(), l_axisList[0]->alterUnit(unit), l_axisList[1]->alterUnit(unit), l_axisList[2]->alterUnit(unit)); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress AffineCS::~AffineCS() = default; //! @endcond // --------------------------------------------------------------------------- AffineCS::AffineCS(const std::vector<CoordinateSystemAxisNNPtr> &axisIn) : CoordinateSystem(axisIn) {} // --------------------------------------------------------------------------- /** \brief Instantiate a AffineCS. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @return a new AffineCS. */ AffineCSNNPtr AffineCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2}; auto cs(AffineCS::nn_make_shared<AffineCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- /** \brief Instantiate a AffineCS. * * @param properties See \ref general_properties. * @param axis1 The first axis. * @param axis2 The second axis. * @param axis3 The third axis. * @return a new AffineCS. */ AffineCSNNPtr AffineCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3) { std::vector<CoordinateSystemAxisNNPtr> axis{axis1, axis2, axis3}; auto cs(AffineCS::nn_make_shared<AffineCS>(axis)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress AffineCSNNPtr AffineCS::alterUnit(const common::UnitOfMeasure &unit) const { const auto &l_axisList = CoordinateSystem::getPrivate()->axisList; if (l_axisList.size() == 2) { return AffineCS::create(util::PropertyMap(), l_axisList[0]->alterUnit(unit), l_axisList[1]->alterUnit(unit)); } else { assert(l_axisList.size() == 3); return AffineCS::create( util::PropertyMap(), l_axisList[0]->alterUnit(unit), l_axisList[1]->alterUnit(unit), l_axisList[2]->alterUnit(unit)); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress OrdinalCS::~OrdinalCS() = default; //! @endcond // --------------------------------------------------------------------------- OrdinalCS::OrdinalCS(const std::vector<CoordinateSystemAxisNNPtr> &axisIn) : CoordinateSystem(axisIn) {} // --------------------------------------------------------------------------- #ifdef notdef OrdinalCS::OrdinalCS(const OrdinalCS &) = default; #endif // --------------------------------------------------------------------------- /** \brief Instantiate a OrdinalCS. * * @param properties See \ref general_properties. * @param axisIn List of axis. * @return a new OrdinalCS. */ OrdinalCSNNPtr OrdinalCS::create(const util::PropertyMap &properties, const std::vector<CoordinateSystemAxisNNPtr> &axisIn) { auto cs(OrdinalCS::nn_make_shared<OrdinalCS>(axisIn)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ParametricCS::~ParametricCS() = default; //! @endcond // --------------------------------------------------------------------------- ParametricCS::ParametricCS(const std::vector<CoordinateSystemAxisNNPtr> &axisIn) : CoordinateSystem(axisIn) {} // --------------------------------------------------------------------------- #ifdef notdef ParametricCS::ParametricCS(const ParametricCS &) = default; #endif // --------------------------------------------------------------------------- /** \brief Instantiate a ParametricCS. * * @param properties See \ref general_properties. * @param axisIn Axis. * @return a new ParametricCS. */ ParametricCSNNPtr ParametricCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axisIn) { auto cs(ParametricCS::nn_make_shared<ParametricCS>( std::vector<CoordinateSystemAxisNNPtr>{axisIn})); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- AxisDirection::AxisDirection(const std::string &nameIn) : CodeList(nameIn) { auto lowerName = tolower(nameIn); assert(registry.find(lowerName) == registry.end()); registry[lowerName] = this; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const AxisDirection * AxisDirection::valueOf(const std::string &nameIn) noexcept { auto iter = registry.find(tolower(nameIn)); if (iter == registry.end()) return nullptr; return iter->second; } //! @endcond // --------------------------------------------------------------------------- RangeMeaning::RangeMeaning(const std::string &nameIn) : CodeList(nameIn) { auto lowerName = tolower(nameIn); assert(registry.find(lowerName) == registry.end()); registry[lowerName] = this; } // --------------------------------------------------------------------------- RangeMeaning::RangeMeaning() : CodeList(std::string()) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const RangeMeaning *RangeMeaning::valueOf(const std::string &nameIn) noexcept { auto iter = registry.find(tolower(nameIn)); if (iter == registry.end()) return nullptr; return iter->second; } //! @endcond //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- AxisDirectionWKT1::AxisDirectionWKT1(const std::string &nameIn) : CodeList(nameIn) { auto lowerName = tolower(nameIn); assert(registry.find(lowerName) == registry.end()); registry[lowerName] = this; } // --------------------------------------------------------------------------- const AxisDirectionWKT1 *AxisDirectionWKT1::valueOf(const std::string &nameIn) { auto iter = registry.find(tolower(nameIn)); if (iter == registry.end()) return nullptr; return iter->second; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TemporalCS::~TemporalCS() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TemporalCS::TemporalCS(const CoordinateSystemAxisNNPtr &axisIn) : CoordinateSystem(std::vector<CoordinateSystemAxisNNPtr>{axisIn}) {} //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DateTimeTemporalCS::~DateTimeTemporalCS() = default; //! @endcond // --------------------------------------------------------------------------- DateTimeTemporalCS::DateTimeTemporalCS(const CoordinateSystemAxisNNPtr &axisIn) : TemporalCS(axisIn) {} // --------------------------------------------------------------------------- /** \brief Instantiate a DateTimeTemporalCS. * * @param properties See \ref general_properties. * @param axisIn The axis. * @return a new DateTimeTemporalCS. */ DateTimeTemporalCSNNPtr DateTimeTemporalCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axisIn) { auto cs(DateTimeTemporalCS::nn_make_shared<DateTimeTemporalCS>(axisIn)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- std::string DateTimeTemporalCS::getWKT2Type(bool use2019Keywords) const { return use2019Keywords ? WKT2_2019_TYPE : WKT2_2015_TYPE; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TemporalCountCS::~TemporalCountCS() = default; //! @endcond // --------------------------------------------------------------------------- TemporalCountCS::TemporalCountCS(const CoordinateSystemAxisNNPtr &axisIn) : TemporalCS(axisIn) {} // --------------------------------------------------------------------------- /** \brief Instantiate a TemporalCountCS. * * @param properties See \ref general_properties. * @param axisIn The axis. * @return a new TemporalCountCS. */ TemporalCountCSNNPtr TemporalCountCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axisIn) { auto cs(TemporalCountCS::nn_make_shared<TemporalCountCS>(axisIn)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- std::string TemporalCountCS::getWKT2Type(bool use2019Keywords) const { return use2019Keywords ? WKT2_2019_TYPE : WKT2_2015_TYPE; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TemporalMeasureCS::~TemporalMeasureCS() = default; //! @endcond // --------------------------------------------------------------------------- TemporalMeasureCS::TemporalMeasureCS(const CoordinateSystemAxisNNPtr &axisIn) : TemporalCS(axisIn) {} // --------------------------------------------------------------------------- /** \brief Instantiate a TemporalMeasureCS. * * @param properties See \ref general_properties. * @param axisIn The axis. * @return a new TemporalMeasureCS. */ TemporalMeasureCSNNPtr TemporalMeasureCS::create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axisIn) { auto cs(TemporalMeasureCS::nn_make_shared<TemporalMeasureCS>(axisIn)); cs->setProperties(properties); return cs; } // --------------------------------------------------------------------------- std::string TemporalMeasureCS::getWKT2Type(bool use2019Keywords) const { return use2019Keywords ? WKT2_2019_TYPE : WKT2_2015_TYPE; } } // namespace cs NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/crs.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif //! @cond Doxygen_Suppress #define DO_NOT_DEFINE_EXTERN_DERIVED_CRS_TEMPLATE //! @endcond #include "proj/crs.hpp" #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinatesystem.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/coordinatesystem_internal.hpp" #include "proj/internal/crs_internal.hpp" #include "proj/internal/datum_internal.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "operation/oputils.hpp" #include "proj_constants.h" #include "proj_json_streaming_writer.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <iostream> #include <memory> #include <string> #include <vector> using namespace NS_PROJ::internal; #if 0 namespace dropbox{ namespace oxygen { template<> nn<NS_PROJ::crs::CRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::SingleCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::GeodeticCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::GeographicCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::ProjectedCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::VerticalCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::CompoundCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::TemporalCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::EngineeringCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::ParametricCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::BoundCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedGeodeticCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedGeographicCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedProjectedCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedVerticalCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedTemporalCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedEngineeringCRSPtr>::~nn() = default; template<> nn<NS_PROJ::crs::DerivedParametricCRSPtr>::~nn() = default; }} #endif NS_PROJ_START namespace crs { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CRS::Private { BoundCRSPtr canonicalBoundCRS_{}; std::string extensionProj4_{}; bool implicitCS_ = false; bool over_ = false; bool allowNonConformantWKT1Export_ = false; // for what was initially a COMPD_CS with a VERT_CS with a datum type == // ellipsoidal height / 2002 CompoundCRSPtr originalCompoundCRS_{}; void setNonStandardProperties(const util::PropertyMap &properties) { { const auto pVal = properties.get("IMPLICIT_CS"); if (pVal) { if (const auto genVal = dynamic_cast<const util::BoxedValue *>(pVal->get())) { if (genVal->type() == util::BoxedValue::Type::BOOLEAN && genVal->booleanValue()) { implicitCS_ = true; } } } } { const auto pVal = properties.get("OVER"); if (pVal) { if (const auto genVal = dynamic_cast<const util::BoxedValue *>(pVal->get())) { if (genVal->type() == util::BoxedValue::Type::BOOLEAN && genVal->booleanValue()) { over_ = true; } } } } } }; //! @endcond // --------------------------------------------------------------------------- CRS::CRS() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- CRS::CRS(const CRS &other) : ObjectUsage(other), d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRS::~CRS() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return whether the CRS has an implicit coordinate system * (e.g from ESRI WKT) */ bool CRS::hasImplicitCS() const { return d->implicitCS_; } /** \brief Return whether the CRS has a +over flag */ bool CRS::hasOver() const { return d->over_; } //! @endcond // --------------------------------------------------------------------------- /** \brief Return the BoundCRS potentially attached to this CRS. * * In the case this method is called on a object returned by * BoundCRS::baseCRSWithCanonicalBoundCRS(), this method will return this * BoundCRS * * @return a BoundCRSPtr, that might be null. */ const BoundCRSPtr &CRS::canonicalBoundCRS() PROJ_PURE_DEFN { return d->canonicalBoundCRS_; } // --------------------------------------------------------------------------- /** \brief Return whether a CRS is a dynamic CRS. * * A dynamic CRS is a CRS that contains a geodetic CRS whose geodetic reference * frame is dynamic, or a vertical CRS whose vertical reference frame is * dynamic. * @param considerWGS84AsDynamic set to true to consider the WGS 84 / EPSG:6326 * datum ensemble as dynamic. * @since 9.2 */ bool CRS::isDynamic(bool considerWGS84AsDynamic) const { if (auto raw = extractGeodeticCRSRaw()) { const auto &l_datum = raw->datum(); if (l_datum) { if (dynamic_cast<datum::DynamicGeodeticReferenceFrame *>( l_datum.get())) { return true; } if (considerWGS84AsDynamic && l_datum->nameStr() == "World Geodetic System 1984") { return true; } } if (considerWGS84AsDynamic) { const auto &l_datumEnsemble = raw->datumEnsemble(); if (l_datumEnsemble && l_datumEnsemble->nameStr() == "World Geodetic System 1984 ensemble") { return true; } } } if (auto vertCRS = extractVerticalCRS()) { const auto &l_datum = vertCRS->datum(); if (l_datum && dynamic_cast<datum::DynamicVerticalReferenceFrame *>( l_datum.get())) { return true; } } return false; } // --------------------------------------------------------------------------- /** \brief Return the GeodeticCRS of the CRS. * * Returns the GeodeticCRS contained in a CRS. This works currently with * input parameters of type GeodeticCRS or derived, ProjectedCRS, * CompoundCRS or BoundCRS. * * @return a GeodeticCRSPtr, that might be null. */ GeodeticCRSPtr CRS::extractGeodeticCRS() const { auto raw = extractGeodeticCRSRaw(); if (raw) { return std::dynamic_pointer_cast<GeodeticCRS>( raw->shared_from_this().as_nullable()); } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const GeodeticCRS *CRS::extractGeodeticCRSRaw() const { auto geodCRS = dynamic_cast<const GeodeticCRS *>(this); if (geodCRS) { return geodCRS; } auto projCRS = dynamic_cast<const ProjectedCRS *>(this); if (projCRS) { return projCRS->baseCRS()->extractGeodeticCRSRaw(); } auto compoundCRS = dynamic_cast<const CompoundCRS *>(this); if (compoundCRS) { for (const auto &subCrs : compoundCRS->componentReferenceSystems()) { auto retGeogCRS = subCrs->extractGeodeticCRSRaw(); if (retGeogCRS) { return retGeogCRS; } } } auto boundCRS = dynamic_cast<const BoundCRS *>(this); if (boundCRS) { return boundCRS->baseCRS()->extractGeodeticCRSRaw(); } auto derivedProjectedCRS = dynamic_cast<const DerivedProjectedCRS *>(this); if (derivedProjectedCRS) { return derivedProjectedCRS->baseCRS()->extractGeodeticCRSRaw(); } return nullptr; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const std::string &CRS::getExtensionProj4() const noexcept { return d->extensionProj4_; } //! @endcond // --------------------------------------------------------------------------- /** \brief Return the GeographicCRS of the CRS. * * Returns the GeographicCRS contained in a CRS. This works currently with * input parameters of type GeographicCRS or derived, ProjectedCRS, * CompoundCRS or BoundCRS. * * @return a GeographicCRSPtr, that might be null. */ GeographicCRSPtr CRS::extractGeographicCRS() const { auto raw = extractGeodeticCRSRaw(); if (raw) { return std::dynamic_pointer_cast<GeographicCRS>( raw->shared_from_this().as_nullable()); } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static util::PropertyMap createPropertyMap(const common::IdentifiedObject *obj) { auto props = util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, obj->nameStr()); if (obj->isDeprecated()) { props.set(common::IdentifiedObject::DEPRECATED_KEY, true); } return props; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRSNNPtr CRS::alterGeodeticCRS(const GeodeticCRSNNPtr &newGeodCRS) const { if (dynamic_cast<const GeodeticCRS *>(this)) { return newGeodCRS; } if (auto projCRS = dynamic_cast<const ProjectedCRS *>(this)) { return ProjectedCRS::create(createPropertyMap(this), newGeodCRS, projCRS->derivingConversion(), projCRS->coordinateSystem()); } if (auto derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this)) { auto newProjCRS = NN_CHECK_ASSERT(util::nn_dynamic_pointer_cast<ProjectedCRS>( derivedProjCRS->baseCRS()->alterGeodeticCRS(newGeodCRS))); return DerivedProjectedCRS::create(createPropertyMap(this), newProjCRS, derivedProjCRS->derivingConversion(), derivedProjCRS->coordinateSystem()); } if (auto compoundCRS = dynamic_cast<const CompoundCRS *>(this)) { std::vector<CRSNNPtr> components; for (const auto &subCrs : compoundCRS->componentReferenceSystems()) { components.emplace_back(subCrs->alterGeodeticCRS(newGeodCRS)); } return CompoundCRS::create(createPropertyMap(this), components); } return NN_NO_CHECK( std::dynamic_pointer_cast<CRS>(shared_from_this().as_nullable())); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRSNNPtr CRS::alterCSLinearUnit(const common::UnitOfMeasure &unit) const { { auto projCRS = dynamic_cast<const ProjectedCRS *>(this); if (projCRS) { return ProjectedCRS::create( createPropertyMap(this), projCRS->baseCRS(), projCRS->derivingConversion(), projCRS->coordinateSystem()->alterUnit(unit)); } } { auto geodCRS = dynamic_cast<const GeodeticCRS *>(this); if (geodCRS && geodCRS->isGeocentric()) { auto cs = dynamic_cast<const cs::CartesianCS *>( geodCRS->coordinateSystem().get()); assert(cs); return GeodeticCRS::create( createPropertyMap(this), geodCRS->datum(), geodCRS->datumEnsemble(), cs->alterUnit(unit)); } } { auto geogCRS = dynamic_cast<const GeographicCRS *>(this); if (geogCRS && geogCRS->coordinateSystem()->axisList().size() == 3) { return GeographicCRS::create( createPropertyMap(this), geogCRS->datum(), geogCRS->datumEnsemble(), geogCRS->coordinateSystem()->alterLinearUnit(unit)); } } { auto vertCRS = dynamic_cast<const VerticalCRS *>(this); if (vertCRS) { return VerticalCRS::create( createPropertyMap(this), vertCRS->datum(), vertCRS->datumEnsemble(), vertCRS->coordinateSystem()->alterUnit(unit)); } } { auto engCRS = dynamic_cast<const EngineeringCRS *>(this); if (engCRS) { auto cartCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>( engCRS->coordinateSystem()); if (cartCS) { return EngineeringCRS::create(createPropertyMap(this), engCRS->datum(), cartCS->alterUnit(unit)); } else { auto vertCS = util::nn_dynamic_pointer_cast<cs::VerticalCS>( engCRS->coordinateSystem()); if (vertCS) { return EngineeringCRS::create(createPropertyMap(this), engCRS->datum(), vertCS->alterUnit(unit)); } } } } { auto derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this); if (derivedProjCRS) { auto cs = derivedProjCRS->coordinateSystem(); auto cartCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>(cs); if (cartCS) { cs = cartCS->alterUnit(unit); } return DerivedProjectedCRS::create( createPropertyMap(this), derivedProjCRS->baseCRS(), derivedProjCRS->derivingConversion(), cs); } } { auto compoundCRS = dynamic_cast<const CompoundCRS *>(this); if (compoundCRS) { std::vector<CRSNNPtr> components; for (const auto &subCrs : compoundCRS->componentReferenceSystems()) { components.push_back(subCrs->alterCSLinearUnit(unit)); } return CompoundCRS::create(createPropertyMap(this), components); } } { auto boundCRS = dynamic_cast<const BoundCRS *>(this); if (boundCRS) { return BoundCRS::create( createPropertyMap(this), boundCRS->baseCRS()->alterCSLinearUnit(unit), boundCRS->hubCRS(), boundCRS->transformation()); } } return NN_NO_CHECK( std::dynamic_pointer_cast<CRS>(shared_from_this().as_nullable())); } //! @endcond // --------------------------------------------------------------------------- /** \brief Return the VerticalCRS of the CRS. * * Returns the VerticalCRS contained in a CRS. This works currently with * input parameters of type VerticalCRS or derived, CompoundCRS or BoundCRS. * * @return a VerticalCRSPtr, that might be null. */ VerticalCRSPtr CRS::extractVerticalCRS() const { auto vertCRS = dynamic_cast<const VerticalCRS *>(this); if (vertCRS) { return std::dynamic_pointer_cast<VerticalCRS>( shared_from_this().as_nullable()); } auto compoundCRS = dynamic_cast<const CompoundCRS *>(this); if (compoundCRS) { for (const auto &subCrs : compoundCRS->componentReferenceSystems()) { auto retVertCRS = subCrs->extractVerticalCRS(); if (retVertCRS) { return retVertCRS; } } } auto boundCRS = dynamic_cast<const BoundCRS *>(this); if (boundCRS) { return boundCRS->baseCRS()->extractVerticalCRS(); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Returns potentially * a BoundCRS, with a transformation to EPSG:4326, wrapping this CRS * * If no such BoundCRS is possible, the object will be returned. * * The purpose of this method is to be able to format a PROJ.4 string with * a +towgs84 parameter or a WKT1:GDAL string with a TOWGS node. * * This method will fetch the GeographicCRS of this CRS and find a * transformation to EPSG:4326 using the domain of the validity of the main CRS, * and there's only one Helmert transformation. * * @return a CRS. */ CRSNNPtr CRS::createBoundCRSToWGS84IfPossible( const io::DatabaseContextPtr &dbContext, operation::CoordinateOperationContext::IntermediateCRSUse allowIntermediateCRSUse) const { auto thisAsCRS = NN_NO_CHECK( std::static_pointer_cast<CRS>(shared_from_this().as_nullable())); auto boundCRS = util::nn_dynamic_pointer_cast<BoundCRS>(thisAsCRS); if (!boundCRS) { boundCRS = canonicalBoundCRS(); } if (boundCRS) { if (boundCRS->hubCRS()->_isEquivalentTo( GeographicCRS::EPSG_4326.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { return NN_NO_CHECK(boundCRS); } } auto compoundCRS = dynamic_cast<const CompoundCRS *>(this); if (compoundCRS) { const auto &comps = compoundCRS->componentReferenceSystems(); if (comps.size() == 2) { auto horiz = comps[0]->createBoundCRSToWGS84IfPossible( dbContext, allowIntermediateCRSUse); auto vert = comps[1]->createBoundCRSToWGS84IfPossible( dbContext, allowIntermediateCRSUse); if (horiz.get() != comps[0].get() || vert.get() != comps[1].get()) { return CompoundCRS::create(createPropertyMap(this), {std::move(horiz), std::move(vert)}); } } return thisAsCRS; } if (!dbContext) { return thisAsCRS; } const auto &l_domains = domains(); metadata::ExtentPtr extent; if (!l_domains.empty()) { if (l_domains.size() > 1) { // If there are several domains of validity, then it is extremely // unlikely, we could get a single transformation valid for all. // At least, in the current state of the code of createOperations() // which returns a single extent, this can't happen. return thisAsCRS; } extent = l_domains[0]->domainOfValidity(); } std::string crs_authority; const auto &l_identifiers = identifiers(); // If the object has an authority, restrict the transformations to // come from that codespace too. This avoids for example EPSG:4269 // (NAD83) to use a (dubious) ESRI transformation. if (!l_identifiers.empty()) { crs_authority = *(l_identifiers[0]->codeSpace()); } auto authorities = dbContext->getAllowedAuthorities( crs_authority, metadata::Identifier::EPSG); if (authorities.empty()) { authorities.emplace_back(); } // Vertical CRS ? auto vertCRS = dynamic_cast<const VerticalCRS *>(this); if (vertCRS) { auto hubCRS = util::nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4979); for (const auto &authority : authorities) { try { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), authority == "any" ? std::string() : authority); auto ctxt = operation::CoordinateOperationContext::create( authFactory, extent, 0.0); ctxt->setAllowUseIntermediateCRS(allowIntermediateCRSUse); // ctxt->setSpatialCriterion( // operation::CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = operation::CoordinateOperationFactory::create() ->createOperations(hubCRS, thisAsCRS, ctxt); CRSPtr candidateBoundCRS; for (const auto &op : list) { auto transf = util::nn_dynamic_pointer_cast< operation::Transformation>(op); // Only keep transformations that use a known grid if (transf && !transf->hasBallparkTransformation()) { auto gridsNeeded = transf->gridsNeeded(dbContext, true); bool gridsKnown = !gridsNeeded.empty(); for (const auto &gridDesc : gridsNeeded) { if (gridDesc.packageName.empty() && !(!gridDesc.url.empty() && gridDesc.openLicense) && !gridDesc.available) { gridsKnown = false; break; } } if (gridsKnown) { if (candidateBoundCRS) { candidateBoundCRS = nullptr; break; } candidateBoundCRS = BoundCRS::create(thisAsCRS, hubCRS, NN_NO_CHECK(transf)) .as_nullable(); } } } if (candidateBoundCRS) { return NN_NO_CHECK(candidateBoundCRS); } } catch (const std::exception &) { } } return thisAsCRS; } // Geodetic/geographic CRS ? auto geodCRS = util::nn_dynamic_pointer_cast<GeodeticCRS>(thisAsCRS); auto geogCRS = extractGeographicCRS(); auto hubCRS = util::nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326); if (geodCRS && !geogCRS) { if (geodCRS->datumNonNull(dbContext)->nameStr() != "unknown" && geodCRS->_isEquivalentTo(GeographicCRS::EPSG_4978.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { return thisAsCRS; } hubCRS = util::nn_static_pointer_cast<CRS>(GeodeticCRS::EPSG_4978); } else if (!geogCRS || (geogCRS->datumNonNull(dbContext)->nameStr() != "unknown" && geogCRS->_isEquivalentTo( GeographicCRS::EPSG_4326.get(), util::IComparable::Criterion::EQUIVALENT, dbContext))) { return thisAsCRS; } else { geodCRS = geogCRS; } for (const auto &authority : authorities) { try { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), authority == "any" ? std::string() : authority); metadata::ExtentPtr extentResolved(extent); if (!extent) { getResolvedCRS(thisAsCRS, authFactory, extentResolved); } auto ctxt = operation::CoordinateOperationContext::create( authFactory, extentResolved, 0.0); ctxt->setAllowUseIntermediateCRS(allowIntermediateCRSUse); // ctxt->setSpatialCriterion( // operation::CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = operation::CoordinateOperationFactory::create() ->createOperations(NN_NO_CHECK(geodCRS), hubCRS, ctxt); CRSPtr candidateBoundCRS; int candidateCount = 0; const auto takeIntoAccountCandidate = [&](const operation::TransformationNNPtr &transf) { try { transf->getTOWGS84Parameters(); } catch (const std::exception &) { return; } candidateCount++; if (candidateBoundCRS == nullptr) { candidateCount = 1; candidateBoundCRS = BoundCRS::create(thisAsCRS, hubCRS, transf) .as_nullable(); } }; for (const auto &op : list) { auto transf = util::nn_dynamic_pointer_cast<operation::Transformation>( op); if (transf && !starts_with(transf->nameStr(), "Ballpark geo")) { takeIntoAccountCandidate(NN_NO_CHECK(transf)); } else { auto concatenated = dynamic_cast<const operation::ConcatenatedOperation *>( op.get()); if (concatenated) { // Case for EPSG:4807 / "NTF (Paris)" that is made of a // longitude rotation followed by a Helmert // The prime meridian shift will be accounted elsewhere const auto &subops = concatenated->operations(); if (subops.size() == 2) { auto firstOpIsTransformation = dynamic_cast<const operation::Transformation *>( subops[0].get()); auto firstOpIsConversion = dynamic_cast<const operation::Conversion *>( subops[0].get()); if ((firstOpIsTransformation && firstOpIsTransformation ->isLongitudeRotation()) || (dynamic_cast<DerivedCRS *>(thisAsCRS.get()) && firstOpIsConversion)) { transf = util::nn_dynamic_pointer_cast< operation::Transformation>(subops[1]); if (transf && !starts_with(transf->nameStr(), "Ballpark geo")) { takeIntoAccountCandidate( NN_NO_CHECK(transf)); } } } } } } if (candidateCount == 1 && candidateBoundCRS) { return NN_NO_CHECK(candidateBoundCRS); } } catch (const std::exception &) { } } return thisAsCRS; } // --------------------------------------------------------------------------- /** \brief Returns a CRS whose coordinate system does not contain a vertical * component * * @return a CRS. */ CRSNNPtr CRS::stripVerticalComponent() const { auto self = NN_NO_CHECK( std::dynamic_pointer_cast<CRS>(shared_from_this().as_nullable())); if (auto geogCRS = dynamic_cast<const GeographicCRS *>(this)) { const auto &axisList = geogCRS->coordinateSystem()->axisList(); if (axisList.size() == 3) { auto cs = cs::EllipsoidalCS::create(util::PropertyMap(), axisList[0], axisList[1]); return util::nn_static_pointer_cast<CRS>(GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, nameStr()), geogCRS->datum(), geogCRS->datumEnsemble(), cs)); } } if (auto projCRS = dynamic_cast<const ProjectedCRS *>(this)) { const auto &axisList = projCRS->coordinateSystem()->axisList(); if (axisList.size() == 3) { auto cs = cs::CartesianCS::create(util::PropertyMap(), axisList[0], axisList[1]); return util::nn_static_pointer_cast<CRS>(ProjectedCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, nameStr()), projCRS->baseCRS(), projCRS->derivingConversion(), cs)); } } if (auto derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this)) { const auto &axisList = derivedProjCRS->coordinateSystem()->axisList(); if (axisList.size() == 3) { auto cs = cs::CartesianCS::create(util::PropertyMap(), axisList[0], axisList[1]); return util::nn_static_pointer_cast<CRS>( DerivedProjectedCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, nameStr()), derivedProjCRS->baseCRS(), derivedProjCRS->derivingConversion(), cs)); } } return self; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return a shallow clone of this object. */ CRSNNPtr CRS::shallowClone() const { return _shallowClone(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRSNNPtr CRS::allowNonConformantWKT1Export() const { const auto boundCRS = dynamic_cast<const BoundCRS *>(this); if (boundCRS) { return BoundCRS::create( boundCRS->baseCRS()->allowNonConformantWKT1Export(), boundCRS->hubCRS(), boundCRS->transformation()); } auto crs(shallowClone()); crs->d->allowNonConformantWKT1Export_ = true; return crs; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRSNNPtr CRS::attachOriginalCompoundCRS(const CompoundCRSNNPtr &compoundCRS) const { const auto boundCRS = dynamic_cast<const BoundCRS *>(this); if (boundCRS) { return BoundCRS::create( boundCRS->baseCRS()->attachOriginalCompoundCRS(compoundCRS), boundCRS->hubCRS(), boundCRS->transformation()); } auto crs(shallowClone()); crs->d->originalCompoundCRS_ = compoundCRS.as_nullable(); return crs; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRSNNPtr CRS::alterName(const std::string &newName) const { auto crs = shallowClone(); auto newNameMod(newName); auto props = util::PropertyMap(); if (ends_with(newNameMod, " (deprecated)")) { newNameMod.resize(newNameMod.size() - strlen(" (deprecated)")); props.set(common::IdentifiedObject::DEPRECATED_KEY, true); } props.set(common::IdentifiedObject::NAME_KEY, newNameMod); crs->setProperties(props); return crs; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRSNNPtr CRS::alterId(const std::string &authName, const std::string &code) const { auto crs = shallowClone(); auto props = util::PropertyMap(); props.set(metadata::Identifier::CODESPACE_KEY, authName) .set(metadata::Identifier::CODE_KEY, code); crs->setProperties(props); return crs; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool mustAxisOrderBeSwitchedForVisualizationInternal( const std::vector<cs::CoordinateSystemAxisNNPtr> &axisList) { const auto &dir0 = axisList[0]->direction(); const auto &dir1 = axisList[1]->direction(); if (&dir0 == &cs::AxisDirection::NORTH && &dir1 == &cs::AxisDirection::EAST) { return true; } // Address EPSG:32661 "WGS 84 / UPS North (N,E)" if (&dir0 == &cs::AxisDirection::SOUTH && &dir1 == &cs::AxisDirection::SOUTH) { const auto &meridian0 = axisList[0]->meridian(); const auto &meridian1 = axisList[1]->meridian(); return meridian0 != nullptr && meridian1 != nullptr && std::abs(meridian0->longitude().convertToUnit( common::UnitOfMeasure::DEGREE) - 180.0) < 1e-10 && std::abs(meridian1->longitude().convertToUnit( common::UnitOfMeasure::DEGREE) - 90.0) < 1e-10; } if (&dir0 == &cs::AxisDirection::NORTH && &dir1 == &cs::AxisDirection::NORTH) { const auto &meridian0 = axisList[0]->meridian(); const auto &meridian1 = axisList[1]->meridian(); return meridian0 != nullptr && meridian1 != nullptr && (( // Address EPSG:32761 "WGS 84 / UPS South (N,E)" std::abs(meridian0->longitude().convertToUnit( common::UnitOfMeasure::DEGREE) - 0.0) < 1e-10 && std::abs(meridian1->longitude().convertToUnit( common::UnitOfMeasure::DEGREE) - 90.0) < 1e-10) || // Address EPSG:5482 "RSRGD2000 / RSPS2000" (std::abs(meridian0->longitude().convertToUnit( common::UnitOfMeasure::DEGREE) - 180) < 1e-10 && std::abs(meridian1->longitude().convertToUnit( common::UnitOfMeasure::DEGREE) - -90.0) < 1e-10)); } return false; } // --------------------------------------------------------------------------- bool CRS::mustAxisOrderBeSwitchedForVisualization() const { if (const CompoundCRS *compoundCRS = dynamic_cast<const CompoundCRS *>(this)) { const auto &comps = compoundCRS->componentReferenceSystems(); if (!comps.empty()) { return comps[0]->mustAxisOrderBeSwitchedForVisualization(); } } if (const GeographicCRS *geogCRS = dynamic_cast<const GeographicCRS *>(this)) { return mustAxisOrderBeSwitchedForVisualizationInternal( geogCRS->coordinateSystem()->axisList()); } if (const ProjectedCRS *projCRS = dynamic_cast<const ProjectedCRS *>(this)) { return mustAxisOrderBeSwitchedForVisualizationInternal( projCRS->coordinateSystem()->axisList()); } if (const DerivedProjectedCRS *derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this)) { return mustAxisOrderBeSwitchedForVisualizationInternal( derivedProjCRS->coordinateSystem()->axisList()); } return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CRS::setProperties( const util::PropertyMap &properties) // throw(InvalidValueTypeException) { std::string l_remarks; std::string extensionProj4; properties.getStringValue(IdentifiedObject::REMARKS_KEY, l_remarks); properties.getStringValue("EXTENSION_PROJ4", extensionProj4); const char *PROJ_CRS_STRING_PREFIX = "PROJ CRS string: "; const char *PROJ_CRS_STRING_SUFFIX = ". "; const auto beginOfProjStringPos = l_remarks.find(PROJ_CRS_STRING_PREFIX); if (beginOfProjStringPos == std::string::npos && extensionProj4.empty()) { ObjectUsage::setProperties(properties); return; } util::PropertyMap newProperties(properties); // Parse remarks and extract EXTENSION_PROJ4 from it if (extensionProj4.empty()) { if (beginOfProjStringPos != std::string::npos) { const auto endOfProjStringPos = l_remarks.find(PROJ_CRS_STRING_SUFFIX, beginOfProjStringPos); if (endOfProjStringPos == std::string::npos) { extensionProj4 = l_remarks.substr( beginOfProjStringPos + strlen(PROJ_CRS_STRING_PREFIX)); } else { extensionProj4 = l_remarks.substr( beginOfProjStringPos + strlen(PROJ_CRS_STRING_PREFIX), endOfProjStringPos - beginOfProjStringPos - strlen(PROJ_CRS_STRING_PREFIX)); } } } if (!extensionProj4.empty()) { if (beginOfProjStringPos == std::string::npos) { // Add EXTENSION_PROJ4 to remarks l_remarks = PROJ_CRS_STRING_PREFIX + extensionProj4 + (l_remarks.empty() ? std::string() : PROJ_CRS_STRING_SUFFIX + l_remarks); } } newProperties.set(IdentifiedObject::REMARKS_KEY, l_remarks); ObjectUsage::setProperties(newProperties); d->extensionProj4_ = std::move(extensionProj4); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- CRSNNPtr CRS::applyAxisOrderReversal(const char *nameSuffix) const { const auto createProperties = [this, nameSuffix](const std::string &newNameIn = std::string()) { std::string newName(newNameIn); if (newName.empty()) { newName = nameStr(); if (ends_with(newName, NORMALIZED_AXIS_ORDER_SUFFIX_STR)) { newName.resize(newName.size() - strlen(NORMALIZED_AXIS_ORDER_SUFFIX_STR)); } else if (ends_with(newName, AXIS_ORDER_REVERSED_SUFFIX_STR)) { newName.resize(newName.size() - strlen(AXIS_ORDER_REVERSED_SUFFIX_STR)); } else { newName += nameSuffix; } } auto props = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, newName); const auto &l_domains = domains(); if (!l_domains.empty()) { auto array = util::ArrayOfBaseObject::create(); for (const auto &domain : l_domains) { array->add(domain); } if (!array->empty()) { props.set(common::ObjectUsage::OBJECT_DOMAIN_KEY, array); } } const auto &l_identifiers = identifiers(); const auto &l_remarks = remarks(); if (l_identifiers.size() == 1) { std::string remarks("Axis order reversed compared to "); if (!starts_with(l_remarks, remarks)) { remarks += *(l_identifiers[0]->codeSpace()); remarks += ':'; remarks += l_identifiers[0]->code(); if (!l_remarks.empty()) { remarks += ". "; remarks += l_remarks; } props.set(common::IdentifiedObject::REMARKS_KEY, remarks); } } else if (!l_remarks.empty()) { props.set(common::IdentifiedObject::REMARKS_KEY, l_remarks); } return props; }; if (const CompoundCRS *compoundCRS = dynamic_cast<const CompoundCRS *>(this)) { const auto &comps = compoundCRS->componentReferenceSystems(); if (!comps.empty()) { std::vector<CRSNNPtr> newComps; newComps.emplace_back(comps[0]->applyAxisOrderReversal(nameSuffix)); std::string l_name = newComps.back()->nameStr(); for (size_t i = 1; i < comps.size(); i++) { newComps.emplace_back(comps[i]); l_name += " + "; l_name += newComps.back()->nameStr(); } return util::nn_static_pointer_cast<CRS>( CompoundCRS::create(createProperties(l_name), newComps)); } } if (const GeographicCRS *geogCRS = dynamic_cast<const GeographicCRS *>(this)) { const auto &axisList = geogCRS->coordinateSystem()->axisList(); auto cs = axisList.size() == 2 ? cs::EllipsoidalCS::create(util::PropertyMap(), axisList[1], axisList[0]) : cs::EllipsoidalCS::create(util::PropertyMap(), axisList[1], axisList[0], axisList[2]); return util::nn_static_pointer_cast<CRS>( GeographicCRS::create(createProperties(), geogCRS->datum(), geogCRS->datumEnsemble(), cs)); } if (const ProjectedCRS *projCRS = dynamic_cast<const ProjectedCRS *>(this)) { const auto &axisList = projCRS->coordinateSystem()->axisList(); auto cs = axisList.size() == 2 ? cs::CartesianCS::create(util::PropertyMap(), axisList[1], axisList[0]) : cs::CartesianCS::create(util::PropertyMap(), axisList[1], axisList[0], axisList[2]); return util::nn_static_pointer_cast<CRS>( ProjectedCRS::create(createProperties(), projCRS->baseCRS(), projCRS->derivingConversion(), cs)); } if (const DerivedProjectedCRS *derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this)) { const auto &axisList = derivedProjCRS->coordinateSystem()->axisList(); auto cs = axisList.size() == 2 ? cs::CartesianCS::create(util::PropertyMap(), axisList[1], axisList[0]) : cs::CartesianCS::create(util::PropertyMap(), axisList[1], axisList[0], axisList[2]); return util::nn_static_pointer_cast<CRS>(DerivedProjectedCRS::create( createProperties(), derivedProjCRS->baseCRS(), derivedProjCRS->derivingConversion(), cs)); } throw util::UnsupportedOperationException( "axis order reversal not supported on this type of CRS"); } // --------------------------------------------------------------------------- CRSNNPtr CRS::normalizeForVisualization() const { if (const CompoundCRS *compoundCRS = dynamic_cast<const CompoundCRS *>(this)) { const auto &comps = compoundCRS->componentReferenceSystems(); if (!comps.empty() && comps[0]->mustAxisOrderBeSwitchedForVisualization()) { return applyAxisOrderReversal(NORMALIZED_AXIS_ORDER_SUFFIX_STR); } } if (const GeographicCRS *geogCRS = dynamic_cast<const GeographicCRS *>(this)) { const auto &axisList = geogCRS->coordinateSystem()->axisList(); if (mustAxisOrderBeSwitchedForVisualizationInternal(axisList)) { return applyAxisOrderReversal(NORMALIZED_AXIS_ORDER_SUFFIX_STR); } } if (const ProjectedCRS *projCRS = dynamic_cast<const ProjectedCRS *>(this)) { const auto &axisList = projCRS->coordinateSystem()->axisList(); if (mustAxisOrderBeSwitchedForVisualizationInternal(axisList)) { return applyAxisOrderReversal(NORMALIZED_AXIS_ORDER_SUFFIX_STR); } } if (const DerivedProjectedCRS *derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this)) { const auto &axisList = derivedProjCRS->coordinateSystem()->axisList(); if (mustAxisOrderBeSwitchedForVisualizationInternal(axisList)) { return applyAxisOrderReversal(NORMALIZED_AXIS_ORDER_SUFFIX_STR); } } if (const BoundCRS *boundCRS = dynamic_cast<const BoundCRS *>(this)) { auto baseNormCRS = boundCRS->baseCRS()->normalizeForVisualization(); return BoundCRS::create(baseNormCRS, boundCRS->hubCRS(), boundCRS->transformation()); } return NN_NO_CHECK( std::static_pointer_cast<CRS>(shared_from_this().as_nullable())); } //! @endcond // --------------------------------------------------------------------------- /** \brief Identify the CRS with reference CRSs. * * The candidate CRSs are either hard-coded, or looked in the database when * authorityFactory is not null. * * Note that the implementation uses a set of heuristics to have a good * compromise of successful identifications over execution time. It might miss * legitimate matches in some circumstances. * * The method returns a list of matching reference CRS, and the percentage * (0-100) of confidence in the match. The list is sorted by decreasing * confidence. * <ul> * <li>100% means that the name of the reference entry * perfectly matches the CRS name, and both are equivalent. In which case a * single result is returned. * Note: in the case of a GeographicCRS whose axis * order is implicit in the input definition (for example ESRI WKT), then axis * order is ignored for the purpose of identification. That is the CRS built * from * GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]], * PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]] * will be identified to EPSG:4326, but will not pass a * isEquivalentTo(EPSG_4326, util::IComparable::Criterion::EQUIVALENT) test, * but rather isEquivalentTo(EPSG_4326, * util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS) * </li> * <li>90% means that CRS are equivalent, but the names are not exactly the * same.</li> * <li>70% means that CRS are equivalent), but the names do not match at * all.</li> * <li>25% means that the CRS are not equivalent, but there is some similarity * in * the names.</li> * </ul> * Other confidence values may be returned by some specialized implementations. * * This is implemented for GeodeticCRS, ProjectedCRS, VerticalCRS and * CompoundCRS. * * @param authorityFactory Authority factory (or null, but degraded * functionality) * @return a list of matching reference CRS, and the percentage (0-100) of * confidence in the match. */ std::list<std::pair<CRSNNPtr, int>> CRS::identify(const io::AuthorityFactoryPtr &authorityFactory) const { return _identify(authorityFactory); } // --------------------------------------------------------------------------- /** \brief Return CRSs that are non-deprecated substitutes for the current CRS. */ std::list<CRSNNPtr> CRS::getNonDeprecated(const io::DatabaseContextNNPtr &dbContext) const { std::list<CRSNNPtr> res; const auto &l_identifiers = identifiers(); if (l_identifiers.empty()) { return res; } const char *tableName = nullptr; if (dynamic_cast<const GeodeticCRS *>(this)) { tableName = "geodetic_crs"; } else if (dynamic_cast<const ProjectedCRS *>(this)) { tableName = "projected_crs"; } else if (dynamic_cast<const VerticalCRS *>(this)) { tableName = "vertical_crs"; } else if (dynamic_cast<const CompoundCRS *>(this)) { tableName = "compound_crs"; } if (!tableName) { return res; } const auto &id = l_identifiers[0]; auto tmpRes = dbContext->getNonDeprecated(tableName, *(id->codeSpace()), id->code()); for (const auto &pair : tmpRes) { res.emplace_back(io::AuthorityFactory::create(dbContext, pair.first) ->createCoordinateReferenceSystem(pair.second)); } return res; } // --------------------------------------------------------------------------- /** \brief Return a variant of this CRS "promoted" to a 3D one, if not already * the case. * * The new axis will be ellipsoidal height, oriented upwards, and with metre * units. * * @param newName Name of the new CRS. If empty, nameStr() will be used. * @param dbContext Database context to look for potentially already registered * 3D CRS. May be nullptr. * @return a new CRS promoted to 3D, or the current one if already 3D or not * applicable. * @since 6.3 */ CRSNNPtr CRS::promoteTo3D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const { auto upAxis = cs::CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, cs::AxisName::Ellipsoidal_height), cs::AxisAbbreviation::h, cs::AxisDirection::UP, common::UnitOfMeasure::METRE); return promoteTo3D(newName, dbContext, upAxis); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CRSNNPtr CRS::promoteTo3D(const std::string &newName, const io::DatabaseContextPtr &dbContext, const cs::CoordinateSystemAxisNNPtr &verticalAxisIfNotAlreadyPresent) const { const auto createProperties = [this, &newName]() { auto props = util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, !newName.empty() ? newName : nameStr()); const auto &l_domains = domains(); if (!l_domains.empty()) { auto array = util::ArrayOfBaseObject::create(); for (const auto &domain : l_domains) { auto extent = domain->domainOfValidity(); if (extent) { // Propagate only the extent, not the scope, as it might // imply more that we can guarantee with the promotion to // 3D. auto newDomain = common::ObjectDomain::create( util::optional<std::string>(), extent); array->add(newDomain); } } if (!array->empty()) { props.set(common::ObjectUsage::OBJECT_DOMAIN_KEY, array); } } const auto &l_identifiers = identifiers(); const auto &l_remarks = remarks(); if (l_identifiers.size() == 1) { std::string remarks("Promoted to 3D from "); remarks += *(l_identifiers[0]->codeSpace()); remarks += ':'; remarks += l_identifiers[0]->code(); if (!l_remarks.empty()) { remarks += ". "; remarks += l_remarks; } props.set(common::IdentifiedObject::REMARKS_KEY, remarks); } else if (!l_remarks.empty()) { props.set(common::IdentifiedObject::REMARKS_KEY, l_remarks); } return props; }; if (auto derivedGeogCRS = dynamic_cast<const DerivedGeographicCRS *>(this)) { const auto &axisList = derivedGeogCRS->coordinateSystem()->axisList(); if (axisList.size() == 2) { auto cs = cs::EllipsoidalCS::create( util::PropertyMap(), axisList[0], axisList[1], verticalAxisIfNotAlreadyPresent); auto baseGeog3DCRS = util::nn_dynamic_pointer_cast<GeodeticCRS>( derivedGeogCRS->baseCRS()->promoteTo3D( std::string(), dbContext, verticalAxisIfNotAlreadyPresent)); return util::nn_static_pointer_cast<CRS>( DerivedGeographicCRS::create( createProperties(), NN_CHECK_THROW(std::move(baseGeog3DCRS)), derivedGeogCRS->derivingConversion(), std::move(cs))); } } else if (auto derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this)) { const auto &axisList = derivedProjCRS->coordinateSystem()->axisList(); if (axisList.size() == 2) { auto cs = cs::CartesianCS::create(util::PropertyMap(), axisList[0], axisList[1], verticalAxisIfNotAlreadyPresent); auto baseProj3DCRS = util::nn_dynamic_pointer_cast<ProjectedCRS>( derivedProjCRS->baseCRS()->promoteTo3D( std::string(), dbContext, verticalAxisIfNotAlreadyPresent)); return util::nn_static_pointer_cast<CRS>( DerivedProjectedCRS::create( createProperties(), NN_CHECK_THROW(std::move(baseProj3DCRS)), derivedProjCRS->derivingConversion(), std::move(cs))); } } else if (auto geogCRS = dynamic_cast<const GeographicCRS *>(this)) { const auto &axisList = geogCRS->coordinateSystem()->axisList(); if (axisList.size() == 2) { const auto &l_identifiers = identifiers(); // First check if there is a Geographic 3D CRS in the database // of the same name. // This is the common practice in the EPSG dataset. if (dbContext && l_identifiers.size() == 1) { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), *(l_identifiers[0]->codeSpace())); auto res = authFactory->createObjectsFromName( nameStr(), {io::AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS}, false); if (!res.empty()) { const auto &firstRes = res.front(); const auto firstResGeog = dynamic_cast<GeographicCRS *>(firstRes.get()); const auto &firstResAxisList = firstResGeog->coordinateSystem()->axisList(); if (firstResAxisList[2]->_isEquivalentTo( verticalAxisIfNotAlreadyPresent.get(), util::IComparable::Criterion::EQUIVALENT) && geogCRS->is2DPartOf3D(NN_NO_CHECK(firstResGeog), dbContext)) { return NN_NO_CHECK( util::nn_dynamic_pointer_cast<CRS>(firstRes)); } } } auto cs = cs::EllipsoidalCS::create( util::PropertyMap(), axisList[0], axisList[1], verticalAxisIfNotAlreadyPresent); return util::nn_static_pointer_cast<CRS>( GeographicCRS::create(createProperties(), geogCRS->datum(), geogCRS->datumEnsemble(), std::move(cs))); } } else if (auto projCRS = dynamic_cast<const ProjectedCRS *>(this)) { const auto &axisList = projCRS->coordinateSystem()->axisList(); if (axisList.size() == 2) { auto base3DCRS = projCRS->baseCRS()->promoteTo3D(std::string(), dbContext); auto cs = cs::CartesianCS::create(util::PropertyMap(), axisList[0], axisList[1], verticalAxisIfNotAlreadyPresent); return util::nn_static_pointer_cast<CRS>(ProjectedCRS::create( createProperties(), NN_NO_CHECK( util::nn_dynamic_pointer_cast<GeodeticCRS>(base3DCRS)), projCRS->derivingConversion(), std::move(cs))); } } else if (auto boundCRS = dynamic_cast<const BoundCRS *>(this)) { auto base3DCRS = boundCRS->baseCRS()->promoteTo3D( newName, dbContext, verticalAxisIfNotAlreadyPresent); auto transf = boundCRS->transformation(); try { transf->getTOWGS84Parameters(); return BoundCRS::create( createProperties(), base3DCRS, boundCRS->hubCRS()->promoteTo3D(std::string(), dbContext), transf->promoteTo3D(std::string(), dbContext)); } catch (const io::FormattingException &) { return BoundCRS::create(base3DCRS, boundCRS->hubCRS(), std::move(transf)); } } return NN_NO_CHECK( std::static_pointer_cast<CRS>(shared_from_this().as_nullable())); } //! @endcond // --------------------------------------------------------------------------- /** \brief Return a variant of this CRS "demoted" to a 2D one, if not already * the case. * * * @param newName Name of the new CRS. If empty, nameStr() will be used. * @param dbContext Database context to look for potentially already registered * 2D CRS. May be nullptr. * @return a new CRS demoted to 2D, or the current one if already 2D or not * applicable. * @since 6.3 */ CRSNNPtr CRS::demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const { if (auto derivedGeogCRS = dynamic_cast<const DerivedGeographicCRS *>(this)) { return derivedGeogCRS->demoteTo2D(newName, dbContext); } else if (auto derivedProjCRS = dynamic_cast<const DerivedProjectedCRS *>(this)) { return derivedProjCRS->demoteTo2D(newName, dbContext); } else if (auto geogCRS = dynamic_cast<const GeographicCRS *>(this)) { return geogCRS->demoteTo2D(newName, dbContext); } else if (auto projCRS = dynamic_cast<const ProjectedCRS *>(this)) { return projCRS->demoteTo2D(newName, dbContext); } else if (auto boundCRS = dynamic_cast<const BoundCRS *>(this)) { auto base2DCRS = boundCRS->baseCRS()->demoteTo2D(newName, dbContext); auto transf = boundCRS->transformation(); try { transf->getTOWGS84Parameters(); return BoundCRS::create( base2DCRS, boundCRS->hubCRS()->demoteTo2D(std::string(), dbContext), transf->demoteTo2D(std::string(), dbContext)); } catch (const io::FormattingException &) { return BoundCRS::create(base2DCRS, boundCRS->hubCRS(), transf); } } else if (auto compoundCRS = dynamic_cast<const CompoundCRS *>(this)) { const auto &components = compoundCRS->componentReferenceSystems(); if (components.size() >= 2) { return components[0]; } } return NN_NO_CHECK( std::static_pointer_cast<CRS>(shared_from_this().as_nullable())); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> CRS::_identify(const io::AuthorityFactoryPtr &) const { return {}; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct SingleCRS::Private { datum::DatumPtr datum{}; datum::DatumEnsemblePtr datumEnsemble{}; cs::CoordinateSystemNNPtr coordinateSystem; Private(const datum::DatumPtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::CoordinateSystemNNPtr &csIn) : datum(datumIn), datumEnsemble(datumEnsembleIn), coordinateSystem(csIn) { if ((datum ? 1 : 0) + (datumEnsemble ? 1 : 0) != 1) { throw util::Exception("datum or datumEnsemble should be set"); } } }; //! @endcond // --------------------------------------------------------------------------- SingleCRS::SingleCRS(const datum::DatumPtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::CoordinateSystemNNPtr &csIn) : d(internal::make_unique<Private>(datumIn, datumEnsembleIn, csIn)) {} // --------------------------------------------------------------------------- SingleCRS::SingleCRS(const SingleCRS &other) : CRS(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress SingleCRS::~SingleCRS() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the datum::Datum associated with the CRS. * * This might be null, in which case datumEnsemble() return will not be null. * * @return a Datum that might be null. */ const datum::DatumPtr &SingleCRS::datum() PROJ_PURE_DEFN { return d->datum; } // --------------------------------------------------------------------------- /** \brief Return the datum::DatumEnsemble associated with the CRS. * * This might be null, in which case datum() return will not be null. * * @return a DatumEnsemble that might be null. */ const datum::DatumEnsemblePtr &SingleCRS::datumEnsemble() PROJ_PURE_DEFN { return d->datumEnsemble; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return the real datum or a synthetized one if a datumEnsemble. */ const datum::DatumNNPtr SingleCRS::datumNonNull(const io::DatabaseContextPtr &dbContext) const { return d->datum ? NN_NO_CHECK(d->datum) : d->datumEnsemble->asDatum(dbContext); } //! @endcond // --------------------------------------------------------------------------- /** \brief Return the cs::CoordinateSystem associated with the CRS. * * @return a CoordinateSystem. */ const cs::CoordinateSystemNNPtr &SingleCRS::coordinateSystem() PROJ_PURE_DEFN { return d->coordinateSystem; } // --------------------------------------------------------------------------- bool SingleCRS::baseIsEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherSingleCRS = dynamic_cast<const SingleCRS *>(other); if (otherSingleCRS == nullptr || (criterion == util::IComparable::Criterion::STRICT && !ObjectUsage::_isEquivalentTo(other, criterion, dbContext))) { return false; } // Check datum const auto &thisDatum = d->datum; const auto &otherDatum = otherSingleCRS->d->datum; const auto &thisDatumEnsemble = d->datumEnsemble; const auto &otherDatumEnsemble = otherSingleCRS->d->datumEnsemble; if (thisDatum && otherDatum) { if (!thisDatum->_isEquivalentTo(otherDatum.get(), criterion, dbContext)) { return false; } } else if (thisDatumEnsemble && otherDatumEnsemble) { if (!thisDatumEnsemble->_isEquivalentTo(otherDatumEnsemble.get(), criterion, dbContext)) { return false; } } if (criterion == util::IComparable::Criterion::STRICT) { if ((thisDatum != nullptr) ^ (otherDatum != nullptr)) { return false; } if ((thisDatumEnsemble != nullptr) ^ (otherDatumEnsemble != nullptr)) { return false; } } else { if (!datumNonNull(dbContext)->_isEquivalentTo( otherSingleCRS->datumNonNull(dbContext).get(), criterion, dbContext)) { return false; } } // Check coordinate system if (!(d->coordinateSystem->_isEquivalentTo( otherSingleCRS->d->coordinateSystem.get(), criterion, dbContext))) { return false; } // Now compare PROJ4 extensions const auto &thisProj4 = getExtensionProj4(); const auto &otherProj4 = otherSingleCRS->getExtensionProj4(); if (thisProj4.empty() && otherProj4.empty()) { return true; } if (!(thisProj4.empty() ^ otherProj4.empty())) { return true; } // Asks for a "normalized" output during toString(), aimed at comparing two // strings for equivalence. auto formatter1 = io::PROJStringFormatter::create(); formatter1->setNormalizeOutput(); formatter1->ingestPROJString(thisProj4); auto formatter2 = io::PROJStringFormatter::create(); formatter2->setNormalizeOutput(); formatter2->ingestPROJString(otherProj4); return formatter1->toString() == formatter2->toString(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void SingleCRS::exportDatumOrDatumEnsembleToWkt( io::WKTFormatter *formatter) const // throw(io::FormattingException) { const auto &l_datum = d->datum; if (l_datum) { l_datum->_exportToWKT(formatter); } else { const auto &l_datumEnsemble = d->datumEnsemble; assert(l_datumEnsemble); l_datumEnsemble->_exportToWKT(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GeodeticCRS::Private { std::vector<operation::PointMotionOperationNNPtr> velocityModel{}; datum::GeodeticReferenceFramePtr datum_; explicit Private(const datum::GeodeticReferenceFramePtr &datumIn) : datum_(datumIn) {} }; // --------------------------------------------------------------------------- static const datum::DatumEnsemblePtr & checkEnsembleForGeodeticCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &ensemble) { const char *msg = "One of Datum or DatumEnsemble should be defined"; if (datumIn) { if (!ensemble) { return ensemble; } msg = "Datum and DatumEnsemble should not be defined"; } else if (ensemble) { const auto &datums = ensemble->datums(); assert(!datums.empty()); auto grfFirst = dynamic_cast<datum::GeodeticReferenceFrame *>(datums[0].get()); if (grfFirst) { return ensemble; } msg = "Ensemble should contain GeodeticReferenceFrame"; } throw util::Exception(msg); } //! @endcond // --------------------------------------------------------------------------- GeodeticCRS::GeodeticCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::EllipsoidalCSNNPtr &csIn) : SingleCRS(datumIn, checkEnsembleForGeodeticCRS(datumIn, datumEnsembleIn), csIn), d(internal::make_unique<Private>(datumIn)) {} // --------------------------------------------------------------------------- GeodeticCRS::GeodeticCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::SphericalCSNNPtr &csIn) : SingleCRS(datumIn, checkEnsembleForGeodeticCRS(datumIn, datumEnsembleIn), csIn), d(internal::make_unique<Private>(datumIn)) {} // --------------------------------------------------------------------------- GeodeticCRS::GeodeticCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::CartesianCSNNPtr &csIn) : SingleCRS(datumIn, checkEnsembleForGeodeticCRS(datumIn, datumEnsembleIn), csIn), d(internal::make_unique<Private>(datumIn)) {} // --------------------------------------------------------------------------- GeodeticCRS::GeodeticCRS(const GeodeticCRS &other) : SingleCRS(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeodeticCRS::~GeodeticCRS() = default; //! @endcond // --------------------------------------------------------------------------- CRSNNPtr GeodeticCRS::_shallowClone() const { auto crs(GeodeticCRS::nn_make_shared<GeodeticCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- /** \brief Return the datum::GeodeticReferenceFrame associated with the CRS. * * @return a GeodeticReferenceFrame or null (in which case datumEnsemble() * should return a non-null pointer.) */ const datum::GeodeticReferenceFramePtr &GeodeticCRS::datum() PROJ_PURE_DEFN { return d->datum_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return the real datum or a synthetized one if a datumEnsemble. */ const datum::GeodeticReferenceFrameNNPtr GeodeticCRS::datumNonNull(const io::DatabaseContextPtr &dbContext) const { return NN_NO_CHECK( d->datum_ ? d->datum_ : util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>( SingleCRS::getPrivate()->datumEnsemble->asDatum(dbContext))); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static datum::GeodeticReferenceFrame *oneDatum(const GeodeticCRS *crs) { const auto &l_datumEnsemble = crs->datumEnsemble(); assert(l_datumEnsemble); const auto &l_datums = l_datumEnsemble->datums(); return static_cast<datum::GeodeticReferenceFrame *>(l_datums[0].get()); } //! @endcond // --------------------------------------------------------------------------- /** \brief Return the PrimeMeridian associated with the GeodeticReferenceFrame * or with one of the GeodeticReferenceFrame of the datumEnsemble(). * * @return the PrimeMeridian. */ const datum::PrimeMeridianNNPtr &GeodeticCRS::primeMeridian() PROJ_PURE_DEFN { if (d->datum_) { return d->datum_->primeMeridian(); } return oneDatum(this)->primeMeridian(); } // --------------------------------------------------------------------------- /** \brief Return the ellipsoid associated with the GeodeticReferenceFrame * or with one of the GeodeticReferenceFrame of the datumEnsemble(). * * @return the PrimeMeridian. */ const datum::EllipsoidNNPtr &GeodeticCRS::ellipsoid() PROJ_PURE_DEFN { if (d->datum_) { return d->datum_->ellipsoid(); } return oneDatum(this)->ellipsoid(); } // --------------------------------------------------------------------------- /** \brief Return the velocity model associated with the CRS. * * @return a velocity model. might be null. */ const std::vector<operation::PointMotionOperationNNPtr> & GeodeticCRS::velocityModel() PROJ_PURE_DEFN { return d->velocityModel; } // --------------------------------------------------------------------------- /** \brief Return whether the CRS is a Cartesian geocentric one. * * A geocentric CRS is a geodetic CRS that has a Cartesian coordinate system * with three axis, whose direction is respectively * cs::AxisDirection::GEOCENTRIC_X, * cs::AxisDirection::GEOCENTRIC_Y and cs::AxisDirection::GEOCENTRIC_Z. * * @return true if the CRS is a geocentric CRS. */ bool GeodeticCRS::isGeocentric() PROJ_PURE_DEFN { const auto &cs = coordinateSystem(); const auto &axisList = cs->axisList(); return axisList.size() == 3 && dynamic_cast<cs::CartesianCS *>(cs.get()) != nullptr && &axisList[0]->direction() == &cs::AxisDirection::GEOCENTRIC_X && &axisList[1]->direction() == &cs::AxisDirection::GEOCENTRIC_Y && &axisList[2]->direction() == &cs::AxisDirection::GEOCENTRIC_Z; } // --------------------------------------------------------------------------- /** \brief Return whether the CRS is a Spherical planetocentric one. * * A Spherical planetocentric CRS is a geodetic CRS that has a spherical * (angular) coordinate system with 2 axis, which represent geocentric latitude/ * longitude or longitude/geocentric latitude. * * Such CRS are typically used in use case that apply to non-Earth bodies. * * @return true if the CRS is a Spherical planetocentric CRS. * * @since 8.2 */ bool GeodeticCRS::isSphericalPlanetocentric() PROJ_PURE_DEFN { const auto &cs = coordinateSystem(); const auto &axisList = cs->axisList(); return axisList.size() == 2 && dynamic_cast<cs::SphericalCS *>(cs.get()) != nullptr && ((ci_equal(axisList[0]->nameStr(), "planetocentric latitude") && ci_equal(axisList[1]->nameStr(), "planetocentric longitude")) || (ci_equal(axisList[0]->nameStr(), "planetocentric longitude") && ci_equal(axisList[1]->nameStr(), "planetocentric latitude"))); } // --------------------------------------------------------------------------- /** \brief Instantiate a GeodeticCRS from a datum::GeodeticReferenceFrame and a * cs::SphericalCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datum The datum of the CRS. * @param cs a SphericalCS. * @return new GeodeticCRS. */ GeodeticCRSNNPtr GeodeticCRS::create(const util::PropertyMap &properties, const datum::GeodeticReferenceFrameNNPtr &datum, const cs::SphericalCSNNPtr &cs) { return create(properties, datum.as_nullable(), nullptr, cs); } // --------------------------------------------------------------------------- /** \brief Instantiate a GeodeticCRS from a datum::GeodeticReferenceFrame or * datum::DatumEnsemble and a cs::SphericalCS. * * One and only one of datum or datumEnsemble should be set to a non-null value. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datum The datum of the CRS, or nullptr * @param datumEnsemble The datum ensemble of the CRS, or nullptr. * @param cs a SphericalCS. * @return new GeodeticCRS. */ GeodeticCRSNNPtr GeodeticCRS::create(const util::PropertyMap &properties, const datum::GeodeticReferenceFramePtr &datum, const datum::DatumEnsemblePtr &datumEnsemble, const cs::SphericalCSNNPtr &cs) { auto crs( GeodeticCRS::nn_make_shared<GeodeticCRS>(datum, datumEnsemble, cs)); crs->assignSelf(crs); crs->setProperties(properties); return crs; } // --------------------------------------------------------------------------- /** \brief Instantiate a GeodeticCRS from a datum::GeodeticReferenceFrame and a * cs::CartesianCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datum The datum of the CRS. * @param cs a CartesianCS. * @return new GeodeticCRS. */ GeodeticCRSNNPtr GeodeticCRS::create(const util::PropertyMap &properties, const datum::GeodeticReferenceFrameNNPtr &datum, const cs::CartesianCSNNPtr &cs) { return create(properties, datum.as_nullable(), nullptr, cs); } // --------------------------------------------------------------------------- /** \brief Instantiate a GeodeticCRS from a datum::GeodeticReferenceFrame or * datum::DatumEnsemble and a cs::CartesianCS. * * One and only one of datum or datumEnsemble should be set to a non-null value. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datum The datum of the CRS, or nullptr * @param datumEnsemble The datum ensemble of the CRS, or nullptr. * @param cs a CartesianCS * @return new GeodeticCRS. */ GeodeticCRSNNPtr GeodeticCRS::create(const util::PropertyMap &properties, const datum::GeodeticReferenceFramePtr &datum, const datum::DatumEnsemblePtr &datumEnsemble, const cs::CartesianCSNNPtr &cs) { auto crs( GeodeticCRS::nn_make_shared<GeodeticCRS>(datum, datumEnsemble, cs)); crs->assignSelf(crs); crs->setProperties(properties); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // Try to format a Geographic/ProjectedCRS 3D CRS as a // GEOGCS[]/PROJCS[],VERTCS[...,DATUM[],...] if we find corresponding objects static bool exportAsESRIWktCompoundCRSWithEllipsoidalHeight( const CRS *self, const GeodeticCRS *geodCRS, io::WKTFormatter *formatter) { const auto &dbContext = formatter->databaseContext(); if (!dbContext) { return false; } const auto l_datum = geodCRS->datumNonNull(formatter->databaseContext()); auto l_esri_name = dbContext->getAliasFromOfficialName( l_datum->nameStr(), "geodetic_datum", "ESRI"); if (l_esri_name.empty()) { l_esri_name = l_datum->nameStr(); } auto authFactory = io::AuthorityFactory::create(NN_NO_CHECK(dbContext), std::string()); auto list = authFactory->createObjectsFromName( l_esri_name, {io::AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, false /* approximate=false*/); if (list.empty()) { return false; } auto gdatum = util::nn_dynamic_pointer_cast<datum::Datum>(list.front()); if (gdatum == nullptr || gdatum->identifiers().empty()) { return false; } const auto &gdatum_ids = gdatum->identifiers(); auto vertCRSList = authFactory->createVerticalCRSFromDatum( "ESRI", "from_geogdatum_" + *gdatum_ids[0]->codeSpace() + '_' + gdatum_ids[0]->code()); self->demoteTo2D(std::string(), dbContext)->_exportToWKT(formatter); if (vertCRSList.size() == 1) { vertCRSList.front()->_exportToWKT(formatter); } else { // This will not be recognized properly by ESRI software // See https://github.com/OSGeo/PROJ/issues/2757 const auto &axisList = geodCRS->coordinateSystem()->axisList(); assert(axisList.size() == 3U); formatter->startNode(io::WKTConstants::VERTCS, false); auto vertcs_name = std::move(l_esri_name); if (starts_with(vertcs_name.c_str(), "GCS_")) vertcs_name = vertcs_name.substr(4); formatter->addQuotedString(vertcs_name); gdatum->_exportToWKT(formatter); // Seems to be a constant value... formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("Vertical_Shift"); formatter->add(0.0); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("Direction"); formatter->add( axisList[2]->direction() == cs::AxisDirection::UP ? 1.0 : -1.0); formatter->endNode(); axisList[2]->unit()._exportToWKT(formatter); formatter->endNode(); } return true; } // --------------------------------------------------------------------------- // Try to format a Geographic/ProjectedCRS 3D CRS as a // GEOGCS[]/PROJCS[],VERTCS["Ellipsoid (metre)",DATUM["Ellipsoid",2002],...] static bool exportAsWKT1CompoundCRSWithEllipsoidalHeight( const CRSNNPtr &base2DCRS, const cs::CoordinateSystemAxisNNPtr &verticalAxis, io::WKTFormatter *formatter) { std::string verticalCRSName = "Ellipsoid ("; verticalCRSName += verticalAxis->unit().name(); verticalCRSName += ')'; auto vertDatum = datum::VerticalReferenceFrame::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, "Ellipsoid") .set("VERT_DATUM_TYPE", "2002")); auto vertCRS = VerticalCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, verticalCRSName), vertDatum.as_nullable(), nullptr, cs::VerticalCS::create(util::PropertyMap(), verticalAxis)); formatter->startNode(io::WKTConstants::COMPD_CS, false); formatter->addQuotedString(base2DCRS->nameStr() + " + " + verticalCRSName); base2DCRS->_exportToWKT(formatter); vertCRS->_exportToWKT(formatter); formatter->endNode(); return true; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; const bool isGeographic = dynamic_cast<const GeographicCRS *>(this) != nullptr; const auto &cs = coordinateSystem(); const auto &axisList = cs->axisList(); const bool isGeographic3D = isGeographic && axisList.size() == 3; const auto oldAxisOutputRule = formatter->outputAxis(); std::string l_name = nameStr(); const auto &dbContext = formatter->databaseContext(); const bool isESRIExport = !isWKT2 && formatter->useESRIDialect(); const auto &l_identifiers = identifiers(); if (isESRIExport && axisList.size() == 3) { if (!isGeographic) { io::FormattingException::Throw( "Geocentric CRS not supported in WKT1_ESRI"); } if (!formatter->isAllowedLINUNITNode()) { // Try to format the Geographic 3D CRS as a // GEOGCS[],VERTCS[...,DATUM[]] if we find corresponding objects if (dbContext) { if (exportAsESRIWktCompoundCRSWithEllipsoidalHeight( this, this, formatter)) { return; } } io::FormattingException::Throw( "Cannot export this Geographic 3D CRS in WKT1_ESRI"); } } if (!isWKT2 && !isESRIExport && formatter->isStrict() && isGeographic && axisList.size() == 3 && oldAxisOutputRule != io::WKTFormatter::OutputAxisRule::NO) { auto geogCRS2D = demoteTo2D(std::string(), dbContext); if (dbContext) { const auto res = geogCRS2D->identify(io::AuthorityFactory::create( NN_NO_CHECK(dbContext), metadata::Identifier::EPSG)); if (res.size() == 1) { const auto &front = res.front(); if (front.second == 100) { geogCRS2D = front.first; } } } if (CRS::getPrivate()->allowNonConformantWKT1Export_) { formatter->startNode(io::WKTConstants::COMPD_CS, false); formatter->addQuotedString(l_name + " + " + l_name); geogCRS2D->_exportToWKT(formatter); const std::vector<double> oldTOWGSParameters( formatter->getTOWGS84Parameters()); formatter->setTOWGS84Parameters({}); geogCRS2D->_exportToWKT(formatter); formatter->setTOWGS84Parameters(oldTOWGSParameters); formatter->endNode(); return; } auto &originalCompoundCRS = CRS::getPrivate()->originalCompoundCRS_; if (originalCompoundCRS) { originalCompoundCRS->_exportToWKT(formatter); return; } if (formatter->isAllowedEllipsoidalHeightAsVerticalCRS()) { if (exportAsWKT1CompoundCRSWithEllipsoidalHeight( geogCRS2D, axisList[2], formatter)) { return; } } io::FormattingException::Throw( "WKT1 does not support Geographic 3D CRS."); } formatter->startNode(isWKT2 ? ((formatter->use2019Keywords() && isGeographic) ? io::WKTConstants::GEOGCRS : io::WKTConstants::GEODCRS) : isGeocentric() ? io::WKTConstants::GEOCCS : io::WKTConstants::GEOGCS, !l_identifiers.empty()); if (isESRIExport) { std::string l_esri_name; if (l_name == "WGS 84") { l_esri_name = isGeographic3D ? "WGS_1984_3D" : "GCS_WGS_1984"; } else { if (dbContext) { const auto tableName = isGeographic3D ? "geographic_3D_crs" : "geodetic_crs"; if (!l_identifiers.empty()) { // Try to find the ESRI alias from the CRS identified by its // id const auto aliases = dbContext->getAliases(*(l_identifiers[0]->codeSpace()), l_identifiers[0]->code(), std::string(), // officialName, tableName, "ESRI"); if (aliases.size() == 1) l_esri_name = aliases.front(); } if (l_esri_name.empty()) { // Then find the ESRI alias from the CRS name l_esri_name = dbContext->getAliasFromOfficialName( l_name, tableName, "ESRI"); } if (l_esri_name.empty()) { // Then try to build an ESRI CRS from the CRS name, and if // there's one, the ESRI name is the CRS name auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), "ESRI"); const bool found = authFactory ->createObjectsFromName( l_name, {io::AuthorityFactory:: ObjectType::GEODETIC_CRS}, false // approximateMatch ) .size() == 1; if (found) l_esri_name = l_name; } } if (l_esri_name.empty()) { l_esri_name = io::WKTFormatter::morphNameToESRI(l_name); if (!starts_with(l_esri_name, "GCS_")) { l_esri_name = "GCS_" + l_esri_name; } } } const std::string &l_esri_name_ref(l_esri_name); l_name = l_esri_name_ref; } else if (!isWKT2 && isDeprecated()) { l_name += " (deprecated)"; } formatter->addQuotedString(l_name); const auto &unit = axisList[0]->unit(); formatter->pushAxisAngularUnit(common::UnitOfMeasure::create(unit)); exportDatumOrDatumEnsembleToWkt(formatter); primeMeridian()->_exportToWKT(formatter); formatter->popAxisAngularUnit(); if (!isWKT2) { unit._exportToWKT(formatter); } if (isGeographic3D && isESRIExport) { axisList[2]->unit()._exportToWKT(formatter, io::WKTConstants::LINUNIT); } if (oldAxisOutputRule == io::WKTFormatter::OutputAxisRule::WKT1_GDAL_EPSG_STYLE && isGeocentric()) { formatter->setOutputAxis(io::WKTFormatter::OutputAxisRule::YES); } cs->_exportToWKT(formatter); formatter->setOutputAxis(oldAxisOutputRule); ObjectUsage::baseExportToWKT(formatter); if (!isWKT2 && !isESRIExport) { const auto &extensionProj4 = CRS::getPrivate()->extensionProj4_; if (!extensionProj4.empty()) { formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4"); formatter->addQuotedString(extensionProj4); formatter->endNode(); } } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticCRS::addGeocentricUnitConversionIntoPROJString( io::PROJStringFormatter *formatter) const { const auto &axisList = coordinateSystem()->axisList(); const auto &unit = axisList[0]->unit(); if (!unit._isEquivalentTo(common::UnitOfMeasure::METRE, util::IComparable::Criterion::EQUIVALENT)) { if (formatter->getCRSExport()) { io::FormattingException::Throw( "GeodeticCRS::exportToPROJString() only " "supports metre unit"); } formatter->addStep("unitconvert"); formatter->addParam("xy_in", "m"); formatter->addParam("z_in", "m"); { auto projUnit = unit.exportToPROJString(); if (!projUnit.empty()) { formatter->addParam("xy_out", projUnit); formatter->addParam("z_out", projUnit); return; } } const auto &toSI = unit.conversionToSI(); formatter->addParam("xy_out", toSI); formatter->addParam("z_out", toSI); } else if (formatter->getCRSExport()) { formatter->addParam("units", "m"); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticCRS::addAngularUnitConvertAndAxisSwap( io::PROJStringFormatter *formatter) const { const auto &axisList = coordinateSystem()->axisList(); formatter->addStep("unitconvert"); formatter->addParam("xy_in", "rad"); if (axisList.size() == 3 && !formatter->omitZUnitConversion()) { formatter->addParam("z_in", "m"); } { const auto &unitHoriz = axisList[0]->unit(); const auto projUnit = unitHoriz.exportToPROJString(); if (projUnit.empty()) { formatter->addParam("xy_out", unitHoriz.conversionToSI()); } else { formatter->addParam("xy_out", projUnit); } } if (axisList.size() == 3 && !formatter->omitZUnitConversion()) { const auto &unitZ = axisList[2]->unit(); auto projVUnit = unitZ.exportToPROJString(); if (projVUnit.empty()) { formatter->addParam("z_out", unitZ.conversionToSI()); } else { formatter->addParam("z_out", projVUnit); } } const char *order[2] = {nullptr, nullptr}; const char *one = "1"; const char *two = "2"; for (int i = 0; i < 2; i++) { const auto &dir = axisList[i]->direction(); if (&dir == &cs::AxisDirection::WEST) { order[i] = "-1"; } else if (&dir == &cs::AxisDirection::EAST) { order[i] = one; } else if (&dir == &cs::AxisDirection::SOUTH) { order[i] = "-2"; } else if (&dir == &cs::AxisDirection::NORTH) { order[i] = two; } } if (order[0] && order[1] && (order[0] != one || order[1] != two)) { formatter->addStep("axisswap"); char orderStr[10]; snprintf(orderStr, sizeof(orderStr), "%.2s,%.2s", order[0], order[1]); formatter->addParam("order", orderStr); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticCRS::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { const auto &extensionProj4 = CRS::getPrivate()->extensionProj4_; if (!extensionProj4.empty()) { formatter->ingestPROJString( replaceAll(extensionProj4, " +type=crs", "")); formatter->addNoDefs(false); return; } if (isGeocentric()) { if (!formatter->getCRSExport()) { formatter->addStep("cart"); } else { formatter->addStep("geocent"); } addDatumInfoToPROJString(formatter); addGeocentricUnitConversionIntoPROJString(formatter); } else if (isSphericalPlanetocentric()) { if (!formatter->getCRSExport()) { if (!formatter->omitProjLongLatIfPossible() || primeMeridian()->longitude().getSIValue() != 0.0 || !ellipsoid()->isSphere() || !formatter->getTOWGS84Parameters().empty() || !formatter->getHDatumExtension().empty()) { formatter->addStep("geoc"); addDatumInfoToPROJString(formatter); } addAngularUnitConvertAndAxisSwap(formatter); } else { io::FormattingException::Throw( "GeodeticCRS::exportToPROJString() not supported on spherical " "planetocentric coordinate systems"); // The below code now works as input to PROJ, but I'm not sure we // want to propagate this, given that we got cs2cs doing conversion // in the wrong direction in past versions. /*formatter->addStep("longlat"); formatter->addParam("geoc"); addDatumInfoToPROJString(formatter);*/ } } else { io::FormattingException::Throw( "GeodeticCRS::exportToPROJString() only " "supports geocentric or spherical planetocentric " "coordinate systems"); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticCRS::addDatumInfoToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { const auto &TOWGS84Params = formatter->getTOWGS84Parameters(); bool datumWritten = false; const auto &nadgrids = formatter->getHDatumExtension(); const auto l_datum = datumNonNull(formatter->databaseContext()); if (formatter->getCRSExport() && TOWGS84Params.empty() && nadgrids.empty() && l_datum->nameStr() != "unknown") { if (l_datum->_isEquivalentTo( datum::GeodeticReferenceFrame::EPSG_6326.get(), util::IComparable::Criterion::EQUIVALENT)) { datumWritten = true; formatter->addParam("datum", "WGS84"); } else if (l_datum->_isEquivalentTo( datum::GeodeticReferenceFrame::EPSG_6267.get(), util::IComparable::Criterion::EQUIVALENT)) { datumWritten = true; formatter->addParam("datum", "NAD27"); } else if (l_datum->_isEquivalentTo( datum::GeodeticReferenceFrame::EPSG_6269.get(), util::IComparable::Criterion::EQUIVALENT)) { datumWritten = true; if (formatter->getLegacyCRSToCRSContext()) { // We do not want datum=NAD83 to cause a useless towgs84=0,0,0 formatter->addParam("ellps", "GRS80"); } else { formatter->addParam("datum", "NAD83"); } } } if (!datumWritten) { ellipsoid()->_exportToPROJString(formatter); primeMeridian()->_exportToPROJString(formatter); } if (TOWGS84Params.size() == 7) { formatter->addParam("towgs84", TOWGS84Params); } if (!nadgrids.empty()) { formatter->addParam("nadgrids", nadgrids); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeodeticCRS::_exportToJSONInternal( io::JSONFormatter *formatter, const char *objectName) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext(objectName, !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } const auto &l_datum(datum()); if (l_datum) { writer->AddObjKey("datum"); l_datum->_exportToJSON(formatter); } else { writer->AddObjKey("datum_ensemble"); formatter->setOmitTypeInImmediateChild(); datumEnsemble()->_exportToJSON(formatter); } writer->AddObjKey("coordinate_system"); formatter->setOmitTypeInImmediateChild(); coordinateSystem()->_exportToJSON(formatter); if (const auto dynamicGRF = dynamic_cast<datum::DynamicGeodeticReferenceFrame *>( l_datum.get())) { const auto &deformationModel = dynamicGRF->deformationModelName(); if (deformationModel.has_value()) { writer->AddObjKey("deformation_models"); auto arrayContext(writer->MakeArrayContext(false)); auto objectContext2(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("name"); writer->Add(*deformationModel); } } ObjectUsage::baseExportToJSON(formatter); } void GeodeticCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { _exportToJSONInternal(formatter, "GeodeticCRS"); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static util::IComparable::Criterion getStandardCriterion(util::IComparable::Criterion criterion) { return criterion == util::IComparable::Criterion:: EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS ? util::IComparable::Criterion::EQUIVALENT : criterion; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool GeodeticCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { if (other == nullptr || !util::isOfExactType<GeodeticCRS>(*other)) { return false; } return _isEquivalentToNoTypeCheck(other, criterion, dbContext); } bool GeodeticCRS::_isEquivalentToNoTypeCheck( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { const auto standardCriterion = getStandardCriterion(criterion); // TODO test velocityModel return SingleCRS::baseIsEquivalentTo(other, standardCriterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static util::PropertyMap createMapNameEPSGCode(const char *name, int code) { return util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, code); } //! @endcond // --------------------------------------------------------------------------- GeodeticCRSNNPtr GeodeticCRS::createEPSG_4978() { return create( createMapNameEPSGCode("WGS 84", 4978), datum::GeodeticReferenceFrame::EPSG_6326, cs::CartesianCS::createGeocentric(common::UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool hasCodeCompatibleOfAuthorityFactory( const common::IdentifiedObject *obj, const io::AuthorityFactoryPtr &authorityFactory) { const auto &ids = obj->identifiers(); if (!ids.empty() && authorityFactory->getAuthority().empty()) { return true; } for (const auto &id : ids) { if (*(id->codeSpace()) == authorityFactory->getAuthority()) { return true; } } return false; } static bool hasCodeCompatibleOfAuthorityFactory( const metadata::IdentifierNNPtr &id, const io::AuthorityFactoryPtr &authorityFactory) { if (authorityFactory->getAuthority().empty()) { return true; } return *(id->codeSpace()) == authorityFactory->getAuthority(); } //! @endcond // --------------------------------------------------------------------------- /** \brief Identify the CRS with reference CRSs. * * The candidate CRSs are either hard-coded, or looked in the database when * authorityFactory is not null. * * Note that the implementation uses a set of heuristics to have a good * compromise of successful identifications over execution time. It might miss * legitimate matches in some circumstances. * * The method returns a list of matching reference CRS, and the percentage * (0-100) of confidence in the match: * <ul> * <li>100% means that the name of the reference entry * perfectly matches the CRS name, and both are equivalent. In which case a * single result is returned. * Note: in the case of a GeographicCRS whose axis * order is implicit in the input definition (for example ESRI WKT), then axis * order is ignored for the purpose of identification. That is the CRS built * from * GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]], * PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]] * will be identified to EPSG:4326, but will not pass a * isEquivalentTo(EPSG_4326, util::IComparable::Criterion::EQUIVALENT) test, * but rather isEquivalentTo(EPSG_4326, * util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS) * </li> * <li>90% means that CRS are equivalent, but the names are not exactly the * same. * <li>70% means that CRS are equivalent (equivalent datum and coordinate * system), * but the names are not equivalent.</li> * <li>60% means that ellipsoid, prime meridian and coordinate systems are * equivalent, but the CRS and datum names do not match.</li> * <li>25% means that the CRS are not equivalent, but there is some similarity * in * the names.</li> * </ul> * * @param authorityFactory Authority factory (or null, but degraded * functionality) * @return a list of matching reference CRS, and the percentage (0-100) of * confidence in the match. */ std::list<std::pair<GeodeticCRSNNPtr, int>> GeodeticCRS::identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<GeodeticCRSNNPtr, int> Pair; std::list<Pair> res; const auto &thisName(nameStr()); io::DatabaseContextPtr dbContext = authorityFactory ? authorityFactory->databaseContext().as_nullable() : nullptr; const bool l_implicitCS = hasImplicitCS(); const auto crsCriterion = l_implicitCS ? util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS : util::IComparable::Criterion::EQUIVALENT; if (authorityFactory == nullptr || authorityFactory->getAuthority().empty() || authorityFactory->getAuthority() == metadata::Identifier::EPSG) { const GeographicCRSNNPtr candidatesCRS[] = {GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4267, GeographicCRS::EPSG_4269}; for (const auto &crs : candidatesCRS) { const bool nameEquivalent = metadata::Identifier::isEquivalentName( thisName.c_str(), crs->nameStr().c_str()); const bool nameEqual = thisName == crs->nameStr(); const bool isEq = _isEquivalentTo(crs.get(), crsCriterion, dbContext); if (nameEquivalent && isEq && (!authorityFactory || nameEqual)) { res.emplace_back(util::nn_static_pointer_cast<GeodeticCRS>(crs), nameEqual ? 100 : 90); return res; } else if (nameEqual && !isEq && !authorityFactory) { res.emplace_back(util::nn_static_pointer_cast<GeodeticCRS>(crs), 25); return res; } else if (isEq && !authorityFactory) { res.emplace_back(util::nn_static_pointer_cast<GeodeticCRS>(crs), 70); return res; } } } std::string geodetic_crs_type; if (isGeocentric()) { geodetic_crs_type = "geocentric"; } else { auto geogCRS = dynamic_cast<const GeographicCRS *>(this); if (geogCRS) { if (coordinateSystem()->axisList().size() == 2) { geodetic_crs_type = "geographic 2D"; } else { geodetic_crs_type = "geographic 3D"; } } } if (authorityFactory) { const auto thisDatum(datumNonNull(dbContext)); auto searchByDatumCode = [this, &authorityFactory, &res, &geodetic_crs_type, crsCriterion, &dbContext](const common::IdentifiedObjectNNPtr &l_datum) { bool resModified = false; for (const auto &id : l_datum->identifiers()) { try { auto tempRes = authorityFactory->createGeodeticCRSFromDatum( *id->codeSpace(), id->code(), geodetic_crs_type); for (const auto &crs : tempRes) { if (_isEquivalentTo(crs.get(), crsCriterion, dbContext)) { res.emplace_back(crs, 70); resModified = true; } } } catch (const std::exception &) { } } return resModified; }; auto searchByEllipsoid = [this, &authorityFactory, &res, &thisDatum, &geodetic_crs_type, l_implicitCS, &dbContext]() { const auto &thisEllipsoid = thisDatum->ellipsoid(); const std::list<datum::EllipsoidNNPtr> ellipsoids( thisEllipsoid->identifiers().empty() ? authorityFactory->createEllipsoidFromExisting( thisEllipsoid) : std::list<datum::EllipsoidNNPtr>{thisEllipsoid}); for (const auto &ellps : ellipsoids) { for (const auto &id : ellps->identifiers()) { try { auto tempRes = authorityFactory->createGeodeticCRSFromEllipsoid( *id->codeSpace(), id->code(), geodetic_crs_type); for (const auto &crs : tempRes) { const auto crsDatum(crs->datumNonNull(dbContext)); if (crsDatum->ellipsoid()->_isEquivalentTo( ellps.get(), util::IComparable::Criterion::EQUIVALENT, dbContext) && crsDatum->primeMeridian()->_isEquivalentTo( thisDatum->primeMeridian().get(), util::IComparable::Criterion::EQUIVALENT, dbContext) && (l_implicitCS || coordinateSystem()->_isEquivalentTo( crs->coordinateSystem().get(), util::IComparable::Criterion::EQUIVALENT, dbContext))) { res.emplace_back(crs, 60); } } } catch (const std::exception &) { } } } }; const auto searchByDatumOrEllipsoid = [&authorityFactory, &thisDatum, searchByDatumCode, searchByEllipsoid]() { if (!thisDatum->identifiers().empty()) { searchByDatumCode(thisDatum); } else { auto candidateDatums = authorityFactory->createObjectsFromName( thisDatum->nameStr(), {io::AuthorityFactory::ObjectType:: GEODETIC_REFERENCE_FRAME}, false); bool resModified = false; for (const auto &candidateDatum : candidateDatums) { if (searchByDatumCode(candidateDatum)) resModified = true; } if (!resModified) { searchByEllipsoid(); } } }; const bool insignificantName = thisName.empty() || ci_equal(thisName, "unknown") || ci_equal(thisName, "unnamed"); if (insignificantName) { searchByDatumOrEllipsoid(); } else if (hasCodeCompatibleOfAuthorityFactory(this, authorityFactory)) { // If the CRS has already an id, check in the database for the // official object, and verify that they are equivalent. for (const auto &id : identifiers()) { if (hasCodeCompatibleOfAuthorityFactory(id, authorityFactory)) { try { auto crs = io::AuthorityFactory::create( authorityFactory->databaseContext(), *id->codeSpace()) ->createGeodeticCRS(id->code()); bool match = _isEquivalentTo(crs.get(), crsCriterion, dbContext); res.emplace_back(crs, match ? 100 : 25); return res; } catch (const std::exception &) { } } } } else { bool gotAbove25Pct = false; for (int ipass = 0; ipass < 2; ipass++) { const bool approximateMatch = ipass == 1; auto objects = authorityFactory->createObjectsFromName( thisName, {io::AuthorityFactory::ObjectType::GEODETIC_CRS}, approximateMatch); for (const auto &obj : objects) { auto crs = util::nn_dynamic_pointer_cast<GeodeticCRS>(obj); assert(crs); auto crsNN = NN_NO_CHECK(crs); if (_isEquivalentTo(crs.get(), crsCriterion, dbContext)) { if (crs->nameStr() == thisName) { res.clear(); res.emplace_back(crsNN, 100); return res; } const bool eqName = metadata::Identifier::isEquivalentName( thisName.c_str(), crs->nameStr().c_str()); res.emplace_back(crsNN, eqName ? 90 : 70); gotAbove25Pct = true; } else { res.emplace_back(crsNN, 25); } } if (!res.empty()) { break; } } if (!gotAbove25Pct) { searchByDatumOrEllipsoid(); } } const auto &thisCS(coordinateSystem()); // Sort results res.sort([&thisName, &thisDatum, &thisCS, &dbContext](const Pair &a, const Pair &b) { // First consider confidence if (a.second > b.second) { return true; } if (a.second < b.second) { return false; } // Then consider exact name matching const auto &aName(a.first->nameStr()); const auto &bName(b.first->nameStr()); if (aName == thisName && bName != thisName) { return true; } if (bName == thisName && aName != thisName) { return false; } // Then datum matching const auto aDatum(a.first->datumNonNull(dbContext)); const auto bDatum(b.first->datumNonNull(dbContext)); const auto thisEquivADatum(thisDatum->_isEquivalentTo( aDatum.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)); const auto thisEquivBDatum(thisDatum->_isEquivalentTo( bDatum.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)); if (thisEquivADatum && !thisEquivBDatum) { return true; } if (!thisEquivADatum && thisEquivBDatum) { return false; } // Then coordinate system matching const auto &aCS(a.first->coordinateSystem()); const auto &bCS(b.first->coordinateSystem()); const auto thisEquivACs(thisCS->_isEquivalentTo( aCS.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)); const auto thisEquivBCs(thisCS->_isEquivalentTo( bCS.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)); if (thisEquivACs && !thisEquivBCs) { return true; } if (!thisEquivACs && thisEquivBCs) { return false; } // Then dimension of the coordinate system matching const auto thisCSAxisListSize = thisCS->axisList().size(); const auto aCSAxistListSize = aCS->axisList().size(); const auto bCSAxistListSize = bCS->axisList().size(); if (thisCSAxisListSize == aCSAxistListSize && thisCSAxisListSize != bCSAxistListSize) { return true; } if (thisCSAxisListSize != aCSAxistListSize && thisCSAxisListSize == bCSAxistListSize) { return false; } // Favor the CRS whole ellipsoid names matches the ellipsoid // name (WGS84...) const bool aEllpsNameEqCRSName = metadata::Identifier::isEquivalentName( aDatum->ellipsoid()->nameStr().c_str(), a.first->nameStr().c_str()); const bool bEllpsNameEqCRSName = metadata::Identifier::isEquivalentName( bDatum->ellipsoid()->nameStr().c_str(), b.first->nameStr().c_str()); if (aEllpsNameEqCRSName && !bEllpsNameEqCRSName) { return true; } if (bEllpsNameEqCRSName && !aEllpsNameEqCRSName) { return false; } // Arbitrary final sorting criterion return aName < bName; }); // If there are results with 90% confidence, only keep those if (res.size() >= 2 && res.front().second == 90) { std::list<Pair> newRes; for (const auto &pair : res) { if (pair.second == 90) { newRes.push_back(pair); } else { break; } } return newRes; } } return res; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> GeodeticCRS::_identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<CRSNNPtr, int> Pair; std::list<Pair> res; auto resTemp = identify(authorityFactory); for (const auto &pair : resTemp) { res.emplace_back(pair.first, pair.second); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GeographicCRS::Private { cs::EllipsoidalCSNNPtr coordinateSystem_; explicit Private(const cs::EllipsoidalCSNNPtr &csIn) : coordinateSystem_(csIn) {} }; //! @endcond // --------------------------------------------------------------------------- GeographicCRS::GeographicCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::EllipsoidalCSNNPtr &csIn) : SingleCRS(datumIn, datumEnsembleIn, csIn), GeodeticCRS(datumIn, checkEnsembleForGeodeticCRS(datumIn, datumEnsembleIn), csIn), d(internal::make_unique<Private>(csIn)) {} // --------------------------------------------------------------------------- GeographicCRS::GeographicCRS(const GeographicCRS &other) : SingleCRS(other), GeodeticCRS(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeographicCRS::~GeographicCRS() = default; //! @endcond // --------------------------------------------------------------------------- CRSNNPtr GeographicCRS::_shallowClone() const { auto crs(GeographicCRS::nn_make_shared<GeographicCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- /** \brief Return the cs::EllipsoidalCS associated with the CRS. * * @return a EllipsoidalCS. */ const cs::EllipsoidalCSNNPtr &GeographicCRS::coordinateSystem() PROJ_PURE_DEFN { return d->coordinateSystem_; } // --------------------------------------------------------------------------- /** \brief Instantiate a GeographicCRS from a datum::GeodeticReferenceFrameNNPtr * and a * cs::EllipsoidalCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datum The datum of the CRS. * @param cs a EllipsoidalCS. * @return new GeographicCRS. */ GeographicCRSNNPtr GeographicCRS::create(const util::PropertyMap &properties, const datum::GeodeticReferenceFrameNNPtr &datum, const cs::EllipsoidalCSNNPtr &cs) { return create(properties, datum.as_nullable(), nullptr, cs); } // --------------------------------------------------------------------------- /** \brief Instantiate a GeographicCRS from a datum::GeodeticReferenceFramePtr * or * datum::DatumEnsemble and a * cs::EllipsoidalCS. * * One and only one of datum or datumEnsemble should be set to a non-null value. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datum The datum of the CRS, or nullptr * @param datumEnsemble The datum ensemble of the CRS, or nullptr. * @param cs a EllipsoidalCS. * @return new GeographicCRS. */ GeographicCRSNNPtr GeographicCRS::create(const util::PropertyMap &properties, const datum::GeodeticReferenceFramePtr &datum, const datum::DatumEnsemblePtr &datumEnsemble, const cs::EllipsoidalCSNNPtr &cs) { GeographicCRSNNPtr crs( GeographicCRS::nn_make_shared<GeographicCRS>(datum, datumEnsemble, cs)); crs->assignSelf(crs); crs->setProperties(properties); crs->CRS::getPrivate()->setNonStandardProperties(properties); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return whether the current GeographicCRS is the 2D part of the * other 3D GeographicCRS. */ bool GeographicCRS::is2DPartOf3D(util::nn<const GeographicCRS *> other, const io::DatabaseContextPtr &dbContext) PROJ_PURE_DEFN { const auto &axis = d->coordinateSystem_->axisList(); const auto &otherAxis = other->d->coordinateSystem_->axisList(); if (!(axis.size() == 2 && otherAxis.size() == 3)) { return false; } const auto &firstAxis = axis[0]; const auto &secondAxis = axis[1]; const auto &otherFirstAxis = otherAxis[0]; const auto &otherSecondAxis = otherAxis[1]; if (!(firstAxis->_isEquivalentTo( otherFirstAxis.get(), util::IComparable::Criterion::EQUIVALENT) && secondAxis->_isEquivalentTo( otherSecondAxis.get(), util::IComparable::Criterion::EQUIVALENT))) { return false; } try { const auto thisDatum = datumNonNull(dbContext); const auto otherDatum = other->datumNonNull(dbContext); return thisDatum->_isEquivalentTo( otherDatum.get(), util::IComparable::Criterion::EQUIVALENT); } catch (const util::InvalidValueTypeException &) { // should not happen really, but potentially thrown by // Identifier::Private::setProperties() assert(false); return false; } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool GeographicCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { if (other == nullptr || !util::isOfExactType<GeographicCRS>(*other)) { return false; } const auto standardCriterion = getStandardCriterion(criterion); if (GeodeticCRS::_isEquivalentToNoTypeCheck(other, standardCriterion, dbContext)) { // Make sure GeoPackage "Undefined geographic SRS" != EPSG:4326 const auto otherGeogCRS = dynamic_cast<const GeographicCRS *>(other); if ((nameStr() == "Undefined geographic SRS" || otherGeogCRS->nameStr() == "Undefined geographic SRS") && otherGeogCRS->nameStr() != nameStr()) { return false; } return true; } if (criterion != util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS) { return false; } const auto axisOrder = coordinateSystem()->axisOrder(); if (axisOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH || axisOrder == cs::EllipsoidalCS::AxisOrder::LAT_NORTH_LONG_EAST) { const auto &unit = coordinateSystem()->axisList()[0]->unit(); return GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, nameStr()), datum(), datumEnsemble(), axisOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH ? cs::EllipsoidalCS::createLatitudeLongitude(unit) : cs::EllipsoidalCS::createLongitudeLatitude(unit)) ->GeodeticCRS::_isEquivalentToNoTypeCheck(other, standardCriterion, dbContext); } if (axisOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH_HEIGHT_UP || axisOrder == cs::EllipsoidalCS::AxisOrder::LAT_NORTH_LONG_EAST_HEIGHT_UP) { const auto &angularUnit = coordinateSystem()->axisList()[0]->unit(); const auto &linearUnit = coordinateSystem()->axisList()[2]->unit(); return GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, nameStr()), datum(), datumEnsemble(), axisOrder == cs::EllipsoidalCS::AxisOrder:: LONG_EAST_LAT_NORTH_HEIGHT_UP ? cs::EllipsoidalCS:: createLatitudeLongitudeEllipsoidalHeight( angularUnit, linearUnit) : cs::EllipsoidalCS:: createLongitudeLatitudeEllipsoidalHeight( angularUnit, linearUnit)) ->GeodeticCRS::_isEquivalentToNoTypeCheck(other, standardCriterion, dbContext); } return false; } //! @endcond // --------------------------------------------------------------------------- GeographicCRSNNPtr GeographicCRS::createEPSG_4267() { return create(createMapNameEPSGCode("NAD27", 4267), datum::GeodeticReferenceFrame::EPSG_6267, cs::EllipsoidalCS::createLatitudeLongitude( common::UnitOfMeasure::DEGREE)); } // --------------------------------------------------------------------------- GeographicCRSNNPtr GeographicCRS::createEPSG_4269() { return create(createMapNameEPSGCode("NAD83", 4269), datum::GeodeticReferenceFrame::EPSG_6269, cs::EllipsoidalCS::createLatitudeLongitude( common::UnitOfMeasure::DEGREE)); } // --------------------------------------------------------------------------- GeographicCRSNNPtr GeographicCRS::createEPSG_4326() { return create(createMapNameEPSGCode("WGS 84", 4326), datum::GeodeticReferenceFrame::EPSG_6326, cs::EllipsoidalCS::createLatitudeLongitude( common::UnitOfMeasure::DEGREE)); } // --------------------------------------------------------------------------- GeographicCRSNNPtr GeographicCRS::createOGC_CRS84() { util::PropertyMap propertiesCRS; propertiesCRS .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::OGC) .set(metadata::Identifier::CODE_KEY, "CRS84") .set(common::IdentifiedObject::NAME_KEY, "WGS 84 (CRS84)"); return create(propertiesCRS, datum::GeodeticReferenceFrame::EPSG_6326, cs::EllipsoidalCS::createLongitudeLatitude( // Long Lat ! common::UnitOfMeasure::DEGREE)); } // --------------------------------------------------------------------------- GeographicCRSNNPtr GeographicCRS::createEPSG_4979() { return create( createMapNameEPSGCode("WGS 84", 4979), datum::GeodeticReferenceFrame::EPSG_6326, cs::EllipsoidalCS::createLatitudeLongitudeEllipsoidalHeight( common::UnitOfMeasure::DEGREE, common::UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- GeographicCRSNNPtr GeographicCRS::createEPSG_4807() { auto ellps(datum::Ellipsoid::createFlattenedSphere( createMapNameEPSGCode("Clarke 1880 (IGN)", 7011), common::Length(6378249.2), common::Scale(293.4660212936269))); auto cs(cs::EllipsoidalCS::createLatitudeLongitude( common::UnitOfMeasure::GRAD)); auto datum(datum::GeodeticReferenceFrame::create( createMapNameEPSGCode("Nouvelle Triangulation Francaise (Paris)", 6807), ellps, util::optional<std::string>(), datum::PrimeMeridian::PARIS)); return create(createMapNameEPSGCode("NTF (Paris)", 4807), datum, cs); } // --------------------------------------------------------------------------- /** \brief Return a variant of this CRS "demoted" to a 2D one, if not already * the case. * * * @param newName Name of the new CRS. If empty, nameStr() will be used. * @param dbContext Database context to look for potentially already registered * 2D CRS. May be nullptr. * @return a new CRS demoted to 2D, or the current one if already 2D or not * applicable. * @since 6.3 */ GeographicCRSNNPtr GeographicCRS::demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const { const auto &axisList = coordinateSystem()->axisList(); if (axisList.size() == 3) { const auto &l_identifiers = identifiers(); // First check if there is a Geographic 2D CRS in the database // of the same name. // This is the common practice in the EPSG dataset. if (dbContext && l_identifiers.size() == 1) { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), *(l_identifiers[0]->codeSpace())); auto res = authFactory->createObjectsFromName( nameStr(), {io::AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS}, false); if (!res.empty()) { const auto &firstRes = res.front(); auto firstResAsGeogCRS = util::nn_dynamic_pointer_cast<GeographicCRS>(firstRes); if (firstResAsGeogCRS && firstResAsGeogCRS->is2DPartOf3D( NN_NO_CHECK(this), dbContext)) { return NN_NO_CHECK(firstResAsGeogCRS); } } } auto cs = cs::EllipsoidalCS::create(util::PropertyMap(), axisList[0], axisList[1]); return GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, !newName.empty() ? newName : nameStr()), datum(), datumEnsemble(), cs); } return NN_NO_CHECK(std::dynamic_pointer_cast<GeographicCRS>( shared_from_this().as_nullable())); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeographicCRS::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { const auto &extensionProj4 = CRS::getPrivate()->extensionProj4_; if (!extensionProj4.empty()) { formatter->ingestPROJString( replaceAll(extensionProj4, " +type=crs", "")); formatter->addNoDefs(false); return; } if (!formatter->omitProjLongLatIfPossible() || primeMeridian()->longitude().getSIValue() != 0.0 || !formatter->getTOWGS84Parameters().empty() || !formatter->getHDatumExtension().empty()) { formatter->addStep("longlat"); bool done = false; if (formatter->getLegacyCRSToCRSContext() && formatter->getHDatumExtension().empty() && formatter->getTOWGS84Parameters().empty()) { const auto l_datum = datumNonNull(formatter->databaseContext()); if (l_datum->_isEquivalentTo( datum::GeodeticReferenceFrame::EPSG_6326.get(), util::IComparable::Criterion::EQUIVALENT)) { done = true; formatter->addParam("ellps", "WGS84"); } else if (l_datum->_isEquivalentTo( datum::GeodeticReferenceFrame::EPSG_6269.get(), util::IComparable::Criterion::EQUIVALENT)) { done = true; // We do not want datum=NAD83 to cause a useless towgs84=0,0,0 formatter->addParam("ellps", "GRS80"); } } if (!done) { addDatumInfoToPROJString(formatter); } } if (!formatter->getCRSExport()) { addAngularUnitConvertAndAxisSwap(formatter); } if (hasOver()) { formatter->addParam("over"); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void GeographicCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { _exportToJSONInternal(formatter, "GeographicCRS"); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct VerticalCRS::Private { std::vector<operation::TransformationNNPtr> geoidModel{}; std::vector<operation::PointMotionOperationNNPtr> velocityModel{}; }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const datum::DatumEnsemblePtr & checkEnsembleForVerticalCRS(const datum::VerticalReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &ensemble) { const char *msg = "One of Datum or DatumEnsemble should be defined"; if (datumIn) { if (!ensemble) { return ensemble; } msg = "Datum and DatumEnsemble should not be defined"; } else if (ensemble) { const auto &datums = ensemble->datums(); assert(!datums.empty()); auto grfFirst = dynamic_cast<datum::VerticalReferenceFrame *>(datums[0].get()); if (grfFirst) { return ensemble; } msg = "Ensemble should contain VerticalReferenceFrame"; } throw util::Exception(msg); } //! @endcond // --------------------------------------------------------------------------- VerticalCRS::VerticalCRS(const datum::VerticalReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::VerticalCSNNPtr &csIn) : SingleCRS(datumIn, checkEnsembleForVerticalCRS(datumIn, datumEnsembleIn), csIn), d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- VerticalCRS::VerticalCRS(const VerticalCRS &other) : SingleCRS(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress VerticalCRS::~VerticalCRS() = default; //! @endcond // --------------------------------------------------------------------------- CRSNNPtr VerticalCRS::_shallowClone() const { auto crs(VerticalCRS::nn_make_shared<VerticalCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- /** \brief Return the datum::VerticalReferenceFrame associated with the CRS. * * @return a VerticalReferenceFrame. */ const datum::VerticalReferenceFramePtr VerticalCRS::datum() const { return std::static_pointer_cast<datum::VerticalReferenceFrame>( SingleCRS::getPrivate()->datum); } // --------------------------------------------------------------------------- /** \brief Return the geoid model associated with the CRS. * * Geoid height model or height correction model linked to a geoid-based * vertical CRS. * * @return a geoid model. might be null */ const std::vector<operation::TransformationNNPtr> & VerticalCRS::geoidModel() PROJ_PURE_DEFN { return d->geoidModel; } // --------------------------------------------------------------------------- /** \brief Return the velocity model associated with the CRS. * * @return a velocity model. might be null. */ const std::vector<operation::PointMotionOperationNNPtr> & VerticalCRS::velocityModel() PROJ_PURE_DEFN { return d->velocityModel; } // --------------------------------------------------------------------------- /** \brief Return the cs::VerticalCS associated with the CRS. * * @return a VerticalCS. */ const cs::VerticalCSNNPtr VerticalCRS::coordinateSystem() const { return util::nn_static_pointer_cast<cs::VerticalCS>( SingleCRS::getPrivate()->coordinateSystem); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return the real datum or a synthetized one if a datumEnsemble. */ const datum::VerticalReferenceFrameNNPtr VerticalCRS::datumNonNull(const io::DatabaseContextPtr &dbContext) const { return NN_NO_CHECK( util::nn_dynamic_pointer_cast<datum::VerticalReferenceFrame>( SingleCRS::datumNonNull(dbContext))); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void VerticalCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; formatter->startNode(isWKT2 ? io::WKTConstants::VERTCRS : formatter->useESRIDialect() ? io::WKTConstants::VERTCS : io::WKTConstants::VERT_CS, !identifiers().empty()); std::string l_name(nameStr()); const auto &dbContext = formatter->databaseContext(); if (formatter->useESRIDialect()) { bool aliasFound = false; if (dbContext) { auto l_alias = dbContext->getAliasFromOfficialName( l_name, "vertical_crs", "ESRI"); if (!l_alias.empty()) { l_name = std::move(l_alias); aliasFound = true; } } if (!aliasFound && dbContext) { auto authFactory = io::AuthorityFactory::create(NN_NO_CHECK(dbContext), "ESRI"); aliasFound = authFactory ->createObjectsFromName( l_name, {io::AuthorityFactory::ObjectType::VERTICAL_CRS}, false // approximateMatch ) .size() == 1; } if (!aliasFound) { l_name = io::WKTFormatter::morphNameToESRI(l_name); } } formatter->addQuotedString(l_name); const auto l_datum = datum(); if (formatter->useESRIDialect() && l_datum && l_datum->getWKT1DatumType() == "2002") { bool foundMatch = false; if (dbContext) { auto authFactory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), std::string()); auto list = authFactory->createObjectsFromName( l_datum->nameStr(), {io::AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, false /* approximate=false*/); if (!list.empty()) { auto gdatum = util::nn_dynamic_pointer_cast<datum::Datum>(list.front()); if (gdatum) { gdatum->_exportToWKT(formatter); foundMatch = true; } } } if (!foundMatch) { // We should export a geodetic datum, but we cannot really do better l_datum->_exportToWKT(formatter); } } else { exportDatumOrDatumEnsembleToWkt(formatter); } const auto &cs = SingleCRS::getPrivate()->coordinateSystem; const auto &axisList = cs->axisList(); if (formatter->useESRIDialect()) { // Seems to be a constant value... formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("Vertical_Shift"); formatter->add(0.0); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("Direction"); formatter->add( axisList[0]->direction() == cs::AxisDirection::UP ? 1.0 : -1.0); formatter->endNode(); } if (!isWKT2) { axisList[0]->unit()._exportToWKT(formatter); } const auto oldAxisOutputRule = formatter->outputAxis(); if (oldAxisOutputRule == io::WKTFormatter::OutputAxisRule::WKT1_GDAL_EPSG_STYLE) { formatter->setOutputAxis(io::WKTFormatter::OutputAxisRule::YES); } cs->_exportToWKT(formatter); formatter->setOutputAxis(oldAxisOutputRule); if (isWKT2 && formatter->use2019Keywords() && !d->geoidModel.empty()) { for (const auto &model : d->geoidModel) { formatter->startNode(io::WKTConstants::GEOIDMODEL, false); formatter->addQuotedString(model->nameStr()); model->formatID(formatter); formatter->endNode(); } } ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void VerticalCRS::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { const auto &geoidgrids = formatter->getVDatumExtension(); if (!geoidgrids.empty()) { formatter->addParam("geoidgrids", geoidgrids); } const auto &geoidCRS = formatter->getGeoidCRSValue(); if (!geoidCRS.empty()) { formatter->addParam("geoid_crs", geoidCRS); } auto &axisList = coordinateSystem()->axisList(); if (!axisList.empty()) { auto projUnit = axisList[0]->unit().exportToPROJString(); if (projUnit.empty()) { formatter->addParam("vto_meter", axisList[0]->unit().conversionToSI()); } else { formatter->addParam("vunits", projUnit); } } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void VerticalCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("VerticalCRS", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } const auto &l_datum(datum()); if (l_datum) { writer->AddObjKey("datum"); l_datum->_exportToJSON(formatter); } else { writer->AddObjKey("datum_ensemble"); formatter->setOmitTypeInImmediateChild(); datumEnsemble()->_exportToJSON(formatter); } writer->AddObjKey("coordinate_system"); formatter->setOmitTypeInImmediateChild(); coordinateSystem()->_exportToJSON(formatter); const auto geoidModelExport = [&writer, &formatter](const operation::TransformationNNPtr &model) { auto objectContext2(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("name"); writer->Add(model->nameStr()); if (model->identifiers().empty()) { const auto &interpCRS = model->interpolationCRS(); if (interpCRS) { writer->AddObjKey("interpolation_crs"); interpCRS->_exportToJSON(formatter); } } model->formatID(formatter); }; if (d->geoidModel.size() == 1) { writer->AddObjKey("geoid_model"); geoidModelExport(d->geoidModel[0]); } else if (d->geoidModel.size() > 1) { writer->AddObjKey("geoid_models"); auto geoidModelsArrayContext(writer->MakeArrayContext(false)); for (const auto &model : d->geoidModel) { geoidModelExport(model); } } if (const auto dynamicVRF = dynamic_cast<datum::DynamicVerticalReferenceFrame *>( l_datum.get())) { const auto &deformationModel = dynamicVRF->deformationModelName(); if (deformationModel.has_value()) { writer->AddObjKey("deformation_models"); auto arrayContext(writer->MakeArrayContext(false)); auto objectContext2(formatter->MakeObjectContext(nullptr, false)); writer->AddObjKey("name"); writer->Add(*deformationModel); } } ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void VerticalCRS::addLinearUnitConvert( io::PROJStringFormatter *formatter) const { auto &axisList = coordinateSystem()->axisList(); if (!axisList.empty()) { if (axisList[0]->unit().conversionToSI() != 1.0) { formatter->addStep("unitconvert"); formatter->addParam("z_in", "m"); auto projVUnit = axisList[0]->unit().exportToPROJString(); if (projVUnit.empty()) { formatter->addParam("z_out", axisList[0]->unit().conversionToSI()); } else { formatter->addParam("z_out", projVUnit); } } } } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a VerticalCRS from a datum::VerticalReferenceFrame and a * cs::VerticalCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. The GEOID_MODEL property can be set * to a TransformationNNPtr object. * @param datumIn The datum of the CRS. * @param csIn a VerticalCS. * @return new VerticalCRS. */ VerticalCRSNNPtr VerticalCRS::create(const util::PropertyMap &properties, const datum::VerticalReferenceFrameNNPtr &datumIn, const cs::VerticalCSNNPtr &csIn) { return create(properties, datumIn.as_nullable(), nullptr, csIn); } // --------------------------------------------------------------------------- /** \brief Instantiate a VerticalCRS from a datum::VerticalReferenceFrame or * datum::DatumEnsemble and a cs::VerticalCS. * * One and only one of datum or datumEnsemble should be set to a non-null value. * * @param properties See \ref general_properties. * At minimum the name should be defined. The GEOID_MODEL property can be set * to a TransformationNNPtr object. * @param datumIn The datum of the CRS, or nullptr * @param datumEnsembleIn The datum ensemble of the CRS, or nullptr. * @param csIn a VerticalCS. * @return new VerticalCRS. */ VerticalCRSNNPtr VerticalCRS::create(const util::PropertyMap &properties, const datum::VerticalReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::VerticalCSNNPtr &csIn) { auto crs(VerticalCRS::nn_make_shared<VerticalCRS>(datumIn, datumEnsembleIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); const auto geoidModelPtr = properties.get("GEOID_MODEL"); if (geoidModelPtr) { if (auto array = util::nn_dynamic_pointer_cast<util::ArrayOfBaseObject>( *geoidModelPtr)) { for (const auto &item : *array) { auto transf = util::nn_dynamic_pointer_cast<operation::Transformation>( item); if (transf) { crs->d->geoidModel.emplace_back(NN_NO_CHECK(transf)); } } } else if (auto transf = util::nn_dynamic_pointer_cast<operation::Transformation>( *geoidModelPtr)) { crs->d->geoidModel.emplace_back(NN_NO_CHECK(transf)); } } return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool VerticalCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherVertCRS = dynamic_cast<const VerticalCRS *>(other); if (otherVertCRS == nullptr || !util::isOfExactType<VerticalCRS>(*otherVertCRS)) { return false; } // TODO test geoidModel and velocityModel return SingleCRS::baseIsEquivalentTo(other, criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- /** \brief Identify the CRS with reference CRSs. * * The candidate CRSs are looked in the database when * authorityFactory is not null. * * Note that the implementation uses a set of heuristics to have a good * compromise of successful identifications over execution time. It might miss * legitimate matches in some circumstances. * * The method returns a list of matching reference CRS, and the percentage * (0-100) of confidence in the match. * 100% means that the name of the reference entry * perfectly matches the CRS name, and both are equivalent. In which case a * single result is returned. * 90% means that CRS are equivalent, but the names are not exactly the same. * 70% means that CRS are equivalent (equivalent datum and coordinate system), * but the names are not equivalent. * 25% means that the CRS are not equivalent, but there is some similarity in * the names. * * @param authorityFactory Authority factory (if null, will return an empty * list) * @return a list of matching reference CRS, and the percentage (0-100) of * confidence in the match. */ std::list<std::pair<VerticalCRSNNPtr, int>> VerticalCRS::identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<VerticalCRSNNPtr, int> Pair; std::list<Pair> res; const auto &thisName(nameStr()); if (authorityFactory) { const io::DatabaseContextNNPtr &dbContext = authorityFactory->databaseContext(); const bool insignificantName = thisName.empty() || ci_equal(thisName, "unknown") || ci_equal(thisName, "unnamed"); if (hasCodeCompatibleOfAuthorityFactory(this, authorityFactory)) { // If the CRS has already an id, check in the database for the // official object, and verify that they are equivalent. for (const auto &id : identifiers()) { if (hasCodeCompatibleOfAuthorityFactory(id, authorityFactory)) { try { auto crs = io::AuthorityFactory::create( dbContext, *id->codeSpace()) ->createVerticalCRS(id->code()); bool match = _isEquivalentTo( crs.get(), util::IComparable::Criterion::EQUIVALENT, dbContext); res.emplace_back(crs, match ? 100 : 25); return res; } catch (const std::exception &) { } } } } else if (!insignificantName) { for (int ipass = 0; ipass < 2; ipass++) { const bool approximateMatch = ipass == 1; auto objects = authorityFactory->createObjectsFromName( thisName, {io::AuthorityFactory::ObjectType::VERTICAL_CRS}, approximateMatch); for (const auto &obj : objects) { auto crs = util::nn_dynamic_pointer_cast<VerticalCRS>(obj); assert(crs); auto crsNN = NN_NO_CHECK(crs); if (_isEquivalentTo( crs.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { if (crs->nameStr() == thisName) { res.clear(); res.emplace_back(crsNN, 100); return res; } res.emplace_back(crsNN, 90); } else { res.emplace_back(crsNN, 25); } } if (!res.empty()) { break; } } } // Sort results res.sort([&thisName](const Pair &a, const Pair &b) { // First consider confidence if (a.second > b.second) { return true; } if (a.second < b.second) { return false; } // Then consider exact name matching const auto &aName(a.first->nameStr()); const auto &bName(b.first->nameStr()); if (aName == thisName && bName != thisName) { return true; } if (bName == thisName && aName != thisName) { return false; } // Arbitrary final sorting criterion return aName < bName; }); // Keep only results of the highest confidence if (res.size() >= 2) { const auto highestConfidence = res.front().second; std::list<Pair> newRes; for (const auto &pair : res) { if (pair.second == highestConfidence) { newRes.push_back(pair); } else { break; } } return newRes; } } return res; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> VerticalCRS::_identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<CRSNNPtr, int> Pair; std::list<Pair> res; auto resTemp = identify(authorityFactory); for (const auto &pair : resTemp) { res.emplace_back(pair.first, pair.second); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DerivedCRS::Private { SingleCRSNNPtr baseCRS_; operation::ConversionNNPtr derivingConversion_; Private(const SingleCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn) : baseCRS_(baseCRSIn), derivingConversion_(derivingConversionIn) {} // For the conversion make a _shallowClone(), so that we can later set // its targetCRS to this. Private(const Private &other) : baseCRS_(other.baseCRS_), derivingConversion_(other.derivingConversion_->shallowClone()) {} }; //! @endcond // --------------------------------------------------------------------------- // DerivedCRS is an abstract class, that virtually inherits from SingleCRS // Consequently the base constructor in SingleCRS will never be called by // that constructor. clang -Wabstract-vbase-init and VC++ underline this, but // other // compilers will complain if we don't call the base constructor. DerivedCRS::DerivedCRS(const SingleCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CoordinateSystemNNPtr & #if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT) cs #endif ) : #if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT) SingleCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), cs), #endif d(internal::make_unique<Private>(baseCRSIn, derivingConversionIn)) { } // --------------------------------------------------------------------------- DerivedCRS::DerivedCRS(const DerivedCRS &other) : #if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT) SingleCRS(other), #endif d(internal::make_unique<Private>(*other.d)) { } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DerivedCRS::~DerivedCRS() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the base CRS of a DerivedCRS. * * @return the base CRS. */ const SingleCRSNNPtr &DerivedCRS::baseCRS() PROJ_PURE_DEFN { return d->baseCRS_; } // --------------------------------------------------------------------------- /** \brief Return the deriving conversion from the base CRS to this CRS. * * @return the deriving conversion. */ const operation::ConversionNNPtr DerivedCRS::derivingConversion() const { return d->derivingConversion_->shallowClone(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const operation::ConversionNNPtr & DerivedCRS::derivingConversionRef() PROJ_PURE_DEFN { return d->derivingConversion_; } //! @endcond // --------------------------------------------------------------------------- bool DerivedCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDerivedCRS = dynamic_cast<const DerivedCRS *>(other); const auto standardCriterion = getStandardCriterion(criterion); if (otherDerivedCRS == nullptr || !SingleCRS::baseIsEquivalentTo(other, standardCriterion, dbContext)) { return false; } return d->baseCRS_->_isEquivalentTo(otherDerivedCRS->d->baseCRS_.get(), criterion, dbContext) && d->derivingConversion_->_isEquivalentTo( otherDerivedCRS->d->derivingConversion_.get(), standardCriterion, dbContext); } // --------------------------------------------------------------------------- void DerivedCRS::setDerivingConversionCRS() { derivingConversionRef()->setWeakSourceTargetCRS( baseCRS().as_nullable(), std::static_pointer_cast<CRS>(shared_from_this().as_nullable())); } // --------------------------------------------------------------------------- void DerivedCRS::baseExportToWKT(io::WKTFormatter *formatter, const std::string &keyword, const std::string &baseKeyword) const { formatter->startNode(keyword, !identifiers().empty()); formatter->addQuotedString(nameStr()); const auto &l_baseCRS = d->baseCRS_; formatter->startNode(baseKeyword, formatter->use2019Keywords() && !l_baseCRS->identifiers().empty()); formatter->addQuotedString(l_baseCRS->nameStr()); l_baseCRS->exportDatumOrDatumEnsembleToWkt(formatter); if (formatter->use2019Keywords() && !(formatter->idOnTopLevelOnly() && formatter->topLevelHasId())) { l_baseCRS->formatID(formatter); } formatter->endNode(); formatter->setUseDerivingConversion(true); derivingConversionRef()->_exportToWKT(formatter); formatter->setUseDerivingConversion(false); coordinateSystem()->_exportToWKT(formatter); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DerivedCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext(className(), !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("base_crs"); baseCRS()->_exportToJSON(formatter); writer->AddObjKey("conversion"); formatter->setOmitTypeInImmediateChild(); derivingConversionRef()->_exportToJSON(formatter); writer->AddObjKey("coordinate_system"); formatter->setOmitTypeInImmediateChild(); coordinateSystem()->_exportToJSON(formatter); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ProjectedCRS::Private { GeodeticCRSNNPtr baseCRS_; cs::CartesianCSNNPtr cs_; Private(const GeodeticCRSNNPtr &baseCRSIn, const cs::CartesianCSNNPtr &csIn) : baseCRS_(baseCRSIn), cs_(csIn) {} inline const GeodeticCRSNNPtr &baseCRS() const { return baseCRS_; } inline const cs::CartesianCSNNPtr &coordinateSystem() const { return cs_; } }; //! @endcond // --------------------------------------------------------------------------- ProjectedCRS::ProjectedCRS( const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn) : SingleCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), DerivedCRS(baseCRSIn, derivingConversionIn, csIn), d(internal::make_unique<Private>(baseCRSIn, csIn)) {} // --------------------------------------------------------------------------- ProjectedCRS::ProjectedCRS(const ProjectedCRS &other) : SingleCRS(other), DerivedCRS(other), d(internal::make_unique<Private>(other.baseCRS(), other.coordinateSystem())) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ProjectedCRS::~ProjectedCRS() = default; //! @endcond // --------------------------------------------------------------------------- CRSNNPtr ProjectedCRS::_shallowClone() const { auto crs(ProjectedCRS::nn_make_shared<ProjectedCRS>(*this)); crs->assignSelf(crs); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- /** \brief Return the base CRS (a GeodeticCRS, which is generally a * GeographicCRS) of the ProjectedCRS. * * @return the base CRS. */ const GeodeticCRSNNPtr &ProjectedCRS::baseCRS() PROJ_PURE_DEFN { return d->baseCRS(); } // --------------------------------------------------------------------------- /** \brief Return the cs::CartesianCS associated with the CRS. * * @return a CartesianCS */ const cs::CartesianCSNNPtr &ProjectedCRS::coordinateSystem() PROJ_PURE_DEFN { return d->coordinateSystem(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ProjectedCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; const auto &l_identifiers = identifiers(); // Try to perfectly round-trip ESRI projectedCRS if the current object // perfectly matches the database definition const auto &dbContext = formatter->databaseContext(); std::string l_name(nameStr()); const auto &l_coordinateSystem = d->coordinateSystem(); const auto &axisList = l_coordinateSystem->axisList(); if (axisList.size() == 3 && !(isWKT2 && formatter->use2019Keywords())) { auto projCRS2D = demoteTo2D(std::string(), dbContext); if (dbContext) { const auto res = projCRS2D->identify(io::AuthorityFactory::create( NN_NO_CHECK(dbContext), metadata::Identifier::EPSG)); if (res.size() == 1) { const auto &front = res.front(); if (front.second == 100) { projCRS2D = front.first; } } } if (formatter->useESRIDialect() && dbContext) { // Try to format the ProjecteD 3D CRS as a // PROJCS[],VERTCS[...,DATUM[]] // if we find corresponding objects if (exportAsESRIWktCompoundCRSWithEllipsoidalHeight( this, baseCRS().as_nullable().get(), formatter)) { return; } } if (!formatter->useESRIDialect() && CRS::getPrivate()->allowNonConformantWKT1Export_) { formatter->startNode(io::WKTConstants::COMPD_CS, false); formatter->addQuotedString(l_name + " + " + baseCRS()->nameStr()); projCRS2D->_exportToWKT(formatter); baseCRS() ->demoteTo2D(std::string(), dbContext) ->_exportToWKT(formatter); formatter->endNode(); return; } auto &originalCompoundCRS = CRS::getPrivate()->originalCompoundCRS_; if (!formatter->useESRIDialect() && originalCompoundCRS) { originalCompoundCRS->_exportToWKT(formatter); return; } if (!formatter->useESRIDialect() && formatter->isAllowedEllipsoidalHeightAsVerticalCRS()) { if (exportAsWKT1CompoundCRSWithEllipsoidalHeight( projCRS2D, axisList[2], formatter)) { return; } } io::FormattingException::Throw( "Projected 3D CRS can only be exported since WKT2:2019"); } std::string l_esri_name; if (formatter->useESRIDialect() && dbContext) { if (!l_identifiers.empty()) { // Try to find the ESRI alias from the CRS identified by its id const auto aliases = dbContext->getAliases( *(l_identifiers[0]->codeSpace()), l_identifiers[0]->code(), std::string(), // officialName, "projected_crs", "ESRI"); if (aliases.size() == 1) l_esri_name = aliases.front(); } if (l_esri_name.empty()) { // Then find the ESRI alias from the CRS name l_esri_name = dbContext->getAliasFromOfficialName( l_name, "projected_crs", "ESRI"); } if (l_esri_name.empty()) { // Then try to build an ESRI CRS from the CRS name, and if there's // one, the ESRI name is the CRS name auto authFactory = io::AuthorityFactory::create(NN_NO_CHECK(dbContext), "ESRI"); const bool found = authFactory ->createObjectsFromName( l_name, {io::AuthorityFactory::ObjectType::PROJECTED_CRS}, false // approximateMatch ) .size() == 1; if (found) l_esri_name = l_name; } if (!isWKT2 && !l_identifiers.empty() && *(l_identifiers[0]->codeSpace()) == "ESRI") { try { // If the id of the object is in the ESRI namespace, then // try to find the full ESRI WKT from the database const auto definition = dbContext->getTextDefinition( "projected_crs", "ESRI", l_identifiers[0]->code()); if (starts_with(definition, "PROJCS")) { auto crsFromFromDef = io::WKTParser() .attachDatabaseContext(dbContext) .createFromWKT(definition); if (_isEquivalentTo( dynamic_cast<IComparable *>(crsFromFromDef.get()), util::IComparable::Criterion::EQUIVALENT)) { formatter->ingestWKTNode( io::WKTNode::createFrom(definition)); return; } } } catch (const std::exception &) { } } else if (!isWKT2 && !l_esri_name.empty()) { try { auto res = io::AuthorityFactory::create(NN_NO_CHECK(dbContext), "ESRI") ->createObjectsFromName( l_esri_name, {io::AuthorityFactory::ObjectType::PROJECTED_CRS}, false); if (res.size() == 1) { const auto definition = dbContext->getTextDefinition( "projected_crs", "ESRI", res.front()->identifiers()[0]->code()); if (starts_with(definition, "PROJCS")) { if (_isEquivalentTo( dynamic_cast<IComparable *>(res.front().get()), util::IComparable::Criterion::EQUIVALENT)) { formatter->ingestWKTNode( io::WKTNode::createFrom(definition)); return; } } } } catch (const std::exception &) { } } } const auto exportAxis = [&l_coordinateSystem, &axisList, &formatter]() { const auto oldAxisOutputRule = formatter->outputAxis(); if (oldAxisOutputRule == io::WKTFormatter::OutputAxisRule::WKT1_GDAL_EPSG_STYLE) { if (&axisList[0]->direction() == &cs::AxisDirection::EAST && &axisList[1]->direction() == &cs::AxisDirection::NORTH) { formatter->setOutputAxis(io::WKTFormatter::OutputAxisRule::YES); } } l_coordinateSystem->_exportToWKT(formatter); formatter->setOutputAxis(oldAxisOutputRule); }; if (!isWKT2 && !formatter->useESRIDialect() && starts_with(nameStr(), "Popular Visualisation CRS / Mercator")) { formatter->startNode(io::WKTConstants::PROJCS, !l_identifiers.empty()); formatter->addQuotedString(nameStr()); formatter->setTOWGS84Parameters({0, 0, 0, 0, 0, 0, 0}); baseCRS()->_exportToWKT(formatter); formatter->setTOWGS84Parameters({}); formatter->startNode(io::WKTConstants::PROJECTION, false); formatter->addQuotedString("Mercator_1SP"); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("central_meridian"); formatter->add(0.0); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("scale_factor"); formatter->add(1.0); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("false_easting"); formatter->add(0.0); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("false_northing"); formatter->add(0.0); formatter->endNode(); axisList[0]->unit()._exportToWKT(formatter); exportAxis(); derivingConversionRef()->addWKTExtensionNode(formatter); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); return; } formatter->startNode(isWKT2 ? io::WKTConstants::PROJCRS : io::WKTConstants::PROJCS, !l_identifiers.empty()); if (formatter->useESRIDialect()) { if (l_esri_name.empty()) { l_name = io::WKTFormatter::morphNameToESRI(l_name); } else { const std::string &l_esri_name_ref(l_esri_name); l_name = l_esri_name_ref; } } if (!isWKT2 && !formatter->useESRIDialect() && isDeprecated()) { l_name += " (deprecated)"; } formatter->addQuotedString(l_name); const auto &l_baseCRS = d->baseCRS(); const auto &geodeticCRSAxisList = l_baseCRS->coordinateSystem()->axisList(); if (isWKT2) { formatter->startNode( (formatter->use2019Keywords() && dynamic_cast<const GeographicCRS *>(l_baseCRS.get())) ? io::WKTConstants::BASEGEOGCRS : io::WKTConstants::BASEGEODCRS, formatter->use2019Keywords() && !l_baseCRS->identifiers().empty()); formatter->addQuotedString(l_baseCRS->nameStr()); l_baseCRS->exportDatumOrDatumEnsembleToWkt(formatter); // insert ellipsoidal cs unit when the units of the map // projection angular parameters are not explicitly given within those // parameters. See // http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#61 if (formatter->primeMeridianOrParameterUnitOmittedIfSameAsAxis()) { geodeticCRSAxisList[0]->unit()._exportToWKT(formatter); } l_baseCRS->primeMeridian()->_exportToWKT(formatter); if (formatter->use2019Keywords() && !(formatter->idOnTopLevelOnly() && formatter->topLevelHasId())) { l_baseCRS->formatID(formatter); } formatter->endNode(); } else { const auto oldAxisOutputRule = formatter->outputAxis(); formatter->setOutputAxis(io::WKTFormatter::OutputAxisRule::NO); l_baseCRS->_exportToWKT(formatter); formatter->setOutputAxis(oldAxisOutputRule); } formatter->pushAxisLinearUnit( common::UnitOfMeasure::create(axisList[0]->unit())); formatter->pushAxisAngularUnit( common::UnitOfMeasure::create(geodeticCRSAxisList[0]->unit())); derivingConversionRef()->_exportToWKT(formatter); formatter->popAxisAngularUnit(); formatter->popAxisLinearUnit(); if (!isWKT2) { axisList[0]->unit()._exportToWKT(formatter); } exportAxis(); if (!isWKT2 && !formatter->useESRIDialect()) { const auto &extensionProj4 = CRS::getPrivate()->extensionProj4_; if (!extensionProj4.empty()) { formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4"); formatter->addQuotedString(extensionProj4); formatter->endNode(); } else { derivingConversionRef()->addWKTExtensionNode(formatter); } } ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); return; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ProjectedCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("ProjectedCRS", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("base_crs"); formatter->setAllowIDInImmediateChild(); formatter->setOmitTypeInImmediateChild(); baseCRS()->_exportToJSON(formatter); writer->AddObjKey("conversion"); formatter->setOmitTypeInImmediateChild(); derivingConversionRef()->_exportToJSON(formatter); writer->AddObjKey("coordinate_system"); formatter->setOmitTypeInImmediateChild(); coordinateSystem()->_exportToJSON(formatter); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- void ProjectedCRS::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { const auto &extensionProj4 = CRS::getPrivate()->extensionProj4_; if (!extensionProj4.empty()) { formatter->ingestPROJString( replaceAll(extensionProj4, " +type=crs", "")); formatter->addNoDefs(false); return; } derivingConversionRef()->_exportToPROJString(formatter); } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS from a base CRS, a deriving * operation::Conversion * and a coordinate system. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param baseCRSIn The base CRS, a GeodeticCRS that is generally a * GeographicCRS. * @param derivingConversionIn The deriving operation::Conversion (typically * using a map * projection method) * @param csIn The coordniate system. * @return new ProjectedCRS. */ ProjectedCRSNNPtr ProjectedCRS::create(const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn) { auto crs = ProjectedCRS::nn_make_shared<ProjectedCRS>( baseCRSIn, derivingConversionIn, csIn); crs->assignSelf(crs); crs->setProperties(properties); crs->setDerivingConversionCRS(); crs->CRS::getPrivate()->setNonStandardProperties(properties); return crs; } // --------------------------------------------------------------------------- bool ProjectedCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherProjCRS = dynamic_cast<const ProjectedCRS *>(other); if (otherProjCRS != nullptr && criterion == util::IComparable::Criterion::EQUIVALENT && (d->baseCRS_->hasImplicitCS() || otherProjCRS->d->baseCRS_->hasImplicitCS())) { // If one of the 2 base CRS has implicit coordinate system, then // relax the check. The axis order of the base CRS doesn't matter // for most purposes. criterion = util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS; } return other != nullptr && util::isOfExactType<ProjectedCRS>(*other) && DerivedCRS::_isEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ProjectedCRSNNPtr ProjectedCRS::alterParametersLinearUnit(const common::UnitOfMeasure &unit, bool convertToNewUnit) const { return create( createPropertyMap(this), baseCRS(), derivingConversion()->alterParametersLinearUnit(unit, convertToNewUnit), coordinateSystem()); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ProjectedCRS::addUnitConvertAndAxisSwap(io::PROJStringFormatter *formatter, bool axisSpecFound) const { ProjectedCRS::addUnitConvertAndAxisSwap(d->coordinateSystem()->axisList(), formatter, axisSpecFound); } void ProjectedCRS::addUnitConvertAndAxisSwap( const std::vector<cs::CoordinateSystemAxisNNPtr> &axisListIn, io::PROJStringFormatter *formatter, bool axisSpecFound) { const auto &unit = axisListIn[0]->unit(); const auto *zUnit = axisListIn.size() == 3 ? &(axisListIn[2]->unit()) : nullptr; if (!unit._isEquivalentTo(common::UnitOfMeasure::METRE, util::IComparable::Criterion::EQUIVALENT) || (zUnit && !zUnit->_isEquivalentTo(common::UnitOfMeasure::METRE, util::IComparable::Criterion::EQUIVALENT))) { auto projUnit = unit.exportToPROJString(); const double toSI = unit.conversionToSI(); if (!formatter->getCRSExport()) { formatter->addStep("unitconvert"); formatter->addParam("xy_in", "m"); if (zUnit) formatter->addParam("z_in", "m"); if (projUnit.empty()) { formatter->addParam("xy_out", toSI); } else { formatter->addParam("xy_out", projUnit); } if (zUnit) { auto projZUnit = zUnit->exportToPROJString(); const double zToSI = zUnit->conversionToSI(); if (projZUnit.empty()) { formatter->addParam("z_out", zToSI); } else { formatter->addParam("z_out", projZUnit); } } } else { if (projUnit.empty()) { formatter->addParam("to_meter", toSI); } else { formatter->addParam("units", projUnit); } } } else if (formatter->getCRSExport() && !formatter->getLegacyCRSToCRSContext()) { formatter->addParam("units", "m"); } if (!axisSpecFound && (!formatter->getCRSExport() || formatter->getLegacyCRSToCRSContext())) { const auto &dir0 = axisListIn[0]->direction(); const auto &dir1 = axisListIn[1]->direction(); if (!(&dir0 == &cs::AxisDirection::EAST && &dir1 == &cs::AxisDirection::NORTH) && // For polar projections, that have south+south direction, // we don't want to mess with axes. dir0 != dir1) { const char *order[2] = {nullptr, nullptr}; for (int i = 0; i < 2; i++) { const auto &dir = axisListIn[i]->direction(); if (&dir == &cs::AxisDirection::WEST) order[i] = "-1"; else if (&dir == &cs::AxisDirection::EAST) order[i] = "1"; else if (&dir == &cs::AxisDirection::SOUTH) order[i] = "-2"; else if (&dir == &cs::AxisDirection::NORTH) order[i] = "2"; } if (order[0] && order[1]) { formatter->addStep("axisswap"); char orderStr[10]; snprintf(orderStr, sizeof(orderStr), "%.2s,%.2s", order[0], order[1]); formatter->addParam("order", orderStr); } } else { const auto &name0 = axisListIn[0]->nameStr(); const auto &name1 = axisListIn[1]->nameStr(); const bool northingEasting = ci_starts_with(name0, "northing") && ci_starts_with(name1, "easting"); // case of EPSG:32661 ["WGS 84 / UPS North (N,E)]" // case of EPSG:32761 ["WGS 84 / UPS South (N,E)]" if (((&dir0 == &cs::AxisDirection::SOUTH && &dir1 == &cs::AxisDirection::SOUTH) || (&dir0 == &cs::AxisDirection::NORTH && &dir1 == &cs::AxisDirection::NORTH)) && northingEasting) { formatter->addStep("axisswap"); formatter->addParam("order", "2,1"); } } } } //! @endcond // --------------------------------------------------------------------------- /** \brief Identify the CRS with reference CRSs. * * The candidate CRSs are either hard-coded, or looked in the database when * authorityFactory is not null. * * Note that the implementation uses a set of heuristics to have a good * compromise of successful identifications over execution time. It might miss * legitimate matches in some circumstances. * * The method returns a list of matching reference CRS, and the percentage * (0-100) of confidence in the match. The list is sorted by decreasing * confidence. * * 100% means that the name of the reference entry * perfectly matches the CRS name, and both are equivalent. In which case a * single result is returned. * 90% means that CRS are equivalent, but the names are not exactly the same. * 70% means that CRS are equivalent (equivalent base CRS, conversion and * coordinate system), but the names are not equivalent. * 60% means that CRS have strong similarity (equivalent base datum, conversion * and coordinate system), but the names are not equivalent. * 50% means that CRS have similarity (equivalent base ellipsoid and * conversion), * but the coordinate system do not match (e.g. different axis ordering or * axis unit). * 25% means that the CRS are not equivalent, but there is some similarity in * the names. * * For the purpose of this function, equivalence is tested with the * util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS, that is * to say that the axis order of the base GeographicCRS is ignored. * * @param authorityFactory Authority factory (or null, but degraded * functionality) * @return a list of matching reference CRS, and the percentage (0-100) of * confidence in the match. */ std::list<std::pair<ProjectedCRSNNPtr, int>> ProjectedCRS::identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<ProjectedCRSNNPtr, int> Pair; std::list<Pair> res; const auto &thisName(nameStr()); io::DatabaseContextPtr dbContext = authorityFactory ? authorityFactory->databaseContext().as_nullable() : nullptr; std::list<std::pair<GeodeticCRSNNPtr, int>> baseRes; const auto &l_baseCRS(baseCRS()); const auto l_datum = l_baseCRS->datumNonNull(dbContext); const bool significantNameForDatum = !ci_starts_with(l_datum->nameStr(), "unknown") && l_datum->nameStr() != "unnamed"; const auto &ellipsoid = l_baseCRS->ellipsoid(); auto geogCRS = dynamic_cast<const GeographicCRS *>(l_baseCRS.get()); if (geogCRS && geogCRS->coordinateSystem()->axisOrder() == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH) { baseRes = GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, geogCRS->nameStr()), geogCRS->datum(), geogCRS->datumEnsemble(), cs::EllipsoidalCS::createLatitudeLongitude( geogCRS->coordinateSystem()->axisList()[0]->unit())) ->identify(authorityFactory); } else { baseRes = l_baseCRS->identify(authorityFactory); } int zone = 0; bool north = false; auto computeConfidence = [&thisName](const std::string &crsName) { return crsName == thisName ? 100 : metadata::Identifier::isEquivalentName(crsName.c_str(), thisName.c_str()) ? 90 : 70; }; const auto &conv = derivingConversionRef(); const auto &cs = coordinateSystem(); if (baseRes.size() == 1 && baseRes.front().second >= 70 && (authorityFactory == nullptr || authorityFactory->getAuthority().empty() || authorityFactory->getAuthority() == metadata::Identifier::EPSG) && conv->isUTM(zone, north) && cs->_isEquivalentTo( cs::CartesianCS::createEastingNorthing(common::UnitOfMeasure::METRE) .get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { auto computeUTMCRSName = [](const char *base, int l_zone, bool l_north) { return base + toString(l_zone) + (l_north ? "N" : "S"); }; if (baseRes.front().first->_isEquivalentTo( GeographicCRS::EPSG_4326.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { std::string crsName( computeUTMCRSName("WGS 84 / UTM zone ", zone, north)); res.emplace_back( ProjectedCRS::create( createMapNameEPSGCode(crsName.c_str(), (north ? 32600 : 32700) + zone), GeographicCRS::EPSG_4326, conv->identify(), cs), computeConfidence(crsName)); return res; } else if (((zone >= 1 && zone <= 22) || zone == 59 || zone == 60) && north && baseRes.front().first->_isEquivalentTo( GeographicCRS::EPSG_4267.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { std::string crsName( computeUTMCRSName("NAD27 / UTM zone ", zone, north)); res.emplace_back( ProjectedCRS::create( createMapNameEPSGCode(crsName.c_str(), (zone >= 59) ? 3370 + zone - 59 : 26700 + zone), GeographicCRS::EPSG_4267, conv->identify(), cs), computeConfidence(crsName)); return res; } else if (((zone >= 1 && zone <= 23) || zone == 59 || zone == 60) && north && baseRes.front().first->_isEquivalentTo( GeographicCRS::EPSG_4269.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { std::string crsName( computeUTMCRSName("NAD83 / UTM zone ", zone, north)); res.emplace_back( ProjectedCRS::create( createMapNameEPSGCode(crsName.c_str(), (zone >= 59) ? 3372 + zone - 59 : 26900 + zone), GeographicCRS::EPSG_4269, conv->identify(), cs), computeConfidence(crsName)); return res; } } const bool l_implicitCS = hasImplicitCS(); const auto addCRS = [&](const ProjectedCRSNNPtr &crs, const bool eqName, bool hasNonMatchingId) -> Pair { const auto &l_unit = cs->axisList()[0]->unit(); if ((_isEquivalentTo(crs.get(), util::IComparable::Criterion:: EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS, dbContext) || (l_implicitCS && l_unit._isEquivalentTo( crs->coordinateSystem()->axisList()[0]->unit(), util::IComparable::Criterion::EQUIVALENT) && l_baseCRS->_isEquivalentTo( crs->baseCRS().get(), util::IComparable::Criterion:: EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS, dbContext) && derivingConversionRef()->_isEquivalentTo( crs->derivingConversionRef().get(), util::IComparable::Criterion::EQUIVALENT, dbContext))) && !((baseCRS()->datumNonNull(dbContext)->nameStr() == "unknown" && crs->baseCRS()->datumNonNull(dbContext)->nameStr() != "unknown") || (baseCRS()->datumNonNull(dbContext)->nameStr() != "unknown" && crs->baseCRS()->datumNonNull(dbContext)->nameStr() == "unknown"))) { if (crs->nameStr() == thisName) { res.clear(); res.emplace_back(crs, hasNonMatchingId ? 70 : 100); } else { res.emplace_back(crs, eqName ? 90 : 70); } } else if (ellipsoid->_isEquivalentTo( crs->baseCRS()->ellipsoid().get(), util::IComparable::Criterion::EQUIVALENT, dbContext) && derivingConversionRef()->_isEquivalentTo( crs->derivingConversionRef().get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { if ((l_implicitCS && l_unit._isEquivalentTo( crs->coordinateSystem()->axisList()[0]->unit(), util::IComparable::Criterion::EQUIVALENT)) || cs->_isEquivalentTo(crs->coordinateSystem().get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { if (!significantNameForDatum || l_datum->_isEquivalentTo( crs->baseCRS()->datumNonNull(dbContext).get(), util::IComparable::Criterion::EQUIVALENT)) { res.emplace_back(crs, 70); } else { res.emplace_back(crs, 60); } } else { res.emplace_back(crs, 50); } } else { res.emplace_back(crs, 25); } return res.back(); }; if (authorityFactory) { const bool insignificantName = thisName.empty() || ci_equal(thisName, "unknown") || ci_equal(thisName, "unnamed"); bool foundEquivalentName = false; bool hasNonMatchingId = false; if (hasCodeCompatibleOfAuthorityFactory(this, authorityFactory)) { // If the CRS has already an id, check in the database for the // official object, and verify that they are equivalent. for (const auto &id : identifiers()) { if (hasCodeCompatibleOfAuthorityFactory(id, authorityFactory)) { try { auto crs = io::AuthorityFactory::create( authorityFactory->databaseContext(), *id->codeSpace()) ->createProjectedCRS(id->code()); bool match = _isEquivalentTo( crs.get(), util::IComparable::Criterion:: EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS, dbContext); res.emplace_back(crs, match ? 100 : 25); if (match) { return res; } } catch (const std::exception &) { } } } hasNonMatchingId = true; } else if (!insignificantName) { for (int ipass = 0; ipass < 2; ipass++) { const bool approximateMatch = ipass == 1; auto objects = authorityFactory->createObjectsFromNameEx( thisName, {io::AuthorityFactory::ObjectType::PROJECTED_CRS}, approximateMatch); for (const auto &pairObjName : objects) { auto crs = util::nn_dynamic_pointer_cast<ProjectedCRS>( pairObjName.first); assert(crs); auto crsNN = NN_NO_CHECK(crs); const bool eqName = metadata::Identifier::isEquivalentName( thisName.c_str(), pairObjName.second.c_str()); foundEquivalentName |= eqName; if (addCRS(crsNN, eqName, false).second == 100) { return res; } } if (!res.empty()) { break; } } } const auto lambdaSort = [&thisName](const Pair &a, const Pair &b) { // First consider confidence if (a.second > b.second) { return true; } if (a.second < b.second) { return false; } // Then consider exact name matching const auto &aName(a.first->nameStr()); const auto &bName(b.first->nameStr()); if (aName == thisName && bName != thisName) { return true; } if (bName == thisName && aName != thisName) { return false; } // Arbitrary final sorting criterion return aName < bName; }; // Sort results res.sort(lambdaSort); if (!foundEquivalentName && (res.empty() || res.front().second < 50)) { std::set<std::pair<std::string, std::string>> alreadyKnown; for (const auto &pair : res) { const auto &ids = pair.first->identifiers(); assert(!ids.empty()); alreadyKnown.insert(std::pair<std::string, std::string>( *(ids[0]->codeSpace()), ids[0]->code())); } auto self = NN_NO_CHECK(std::dynamic_pointer_cast<ProjectedCRS>( shared_from_this().as_nullable())); auto candidates = authorityFactory->createProjectedCRSFromExisting(self); for (const auto &crs : candidates) { const auto &ids = crs->identifiers(); assert(!ids.empty()); if (alreadyKnown.find(std::pair<std::string, std::string>( *(ids[0]->codeSpace()), ids[0]->code())) != alreadyKnown.end()) { continue; } addCRS(crs, insignificantName, hasNonMatchingId); } res.sort(lambdaSort); } // Keep only results of the highest confidence if (res.size() >= 2) { const auto highestConfidence = res.front().second; std::list<Pair> newRes; for (const auto &pair : res) { if (pair.second == highestConfidence) { newRes.push_back(pair); } else { break; } } return newRes; } } return res; } // --------------------------------------------------------------------------- /** \brief Return a variant of this CRS "demoted" to a 2D one, if not already * the case. * * * @param newName Name of the new CRS. If empty, nameStr() will be used. * @param dbContext Database context to look for potentially already registered * 2D CRS. May be nullptr. * @return a new CRS demoted to 2D, or the current one if already 2D or not * applicable. * @since 6.3 */ ProjectedCRSNNPtr ProjectedCRS::demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const { const auto &axisList = coordinateSystem()->axisList(); if (axisList.size() == 3) { auto cs = cs::CartesianCS::create(util::PropertyMap(), axisList[0], axisList[1]); const auto &l_baseCRS = baseCRS(); const auto geogCRS = dynamic_cast<const GeographicCRS *>(l_baseCRS.get()); const auto newBaseCRS = geogCRS ? util::nn_static_pointer_cast<GeodeticCRS>( geogCRS->demoteTo2D(std::string(), dbContext)) : l_baseCRS; return ProjectedCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, !newName.empty() ? newName : nameStr()), newBaseCRS, derivingConversion(), cs); } return NN_NO_CHECK(std::dynamic_pointer_cast<ProjectedCRS>( shared_from_this().as_nullable())); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> ProjectedCRS::_identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<CRSNNPtr, int> Pair; std::list<Pair> res; auto resTemp = identify(authorityFactory); for (const auto &pair : resTemp) { res.emplace_back(pair.first, pair.second); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress InvalidCompoundCRSException::InvalidCompoundCRSException(const char *message) : Exception(message) {} // --------------------------------------------------------------------------- InvalidCompoundCRSException::InvalidCompoundCRSException( const std::string &message) : Exception(message) {} // --------------------------------------------------------------------------- InvalidCompoundCRSException::~InvalidCompoundCRSException() = default; // --------------------------------------------------------------------------- InvalidCompoundCRSException::InvalidCompoundCRSException( const InvalidCompoundCRSException &) = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CompoundCRS::Private { std::vector<CRSNNPtr> components_{}; }; //! @endcond // --------------------------------------------------------------------------- CompoundCRS::CompoundCRS(const std::vector<CRSNNPtr> &components) : CRS(), d(internal::make_unique<Private>()) { d->components_ = components; } // --------------------------------------------------------------------------- CompoundCRS::CompoundCRS(const CompoundCRS &other) : CRS(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CompoundCRS::~CompoundCRS() = default; //! @endcond // --------------------------------------------------------------------------- CRSNNPtr CompoundCRS::_shallowClone() const { auto crs(CompoundCRS::nn_make_shared<CompoundCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- /** \brief Return the components of a CompoundCRS. * * @return the components. */ const std::vector<CRSNNPtr> & CompoundCRS::componentReferenceSystems() PROJ_PURE_DEFN { return d->components_; } // --------------------------------------------------------------------------- /** \brief Instantiate a CompoundCRS from a vector of CRS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param components the component CRS of the CompoundCRS. * @return new CompoundCRS. * @throw InvalidCompoundCRSException */ CompoundCRSNNPtr CompoundCRS::create(const util::PropertyMap &properties, const std::vector<CRSNNPtr> &components) { if (components.size() < 2) { throw InvalidCompoundCRSException( "compound CRS should have at least 2 components"); } auto comp0 = components[0].get(); auto comp0Bound = dynamic_cast<const BoundCRS *>(comp0); if (comp0Bound) { comp0 = comp0Bound->baseCRS().get(); } auto comp0Geog = dynamic_cast<const GeographicCRS *>(comp0); auto comp0Proj = dynamic_cast<const ProjectedCRS *>(comp0); auto comp0DerPr = dynamic_cast<const DerivedProjectedCRS *>(comp0); auto comp0Eng = dynamic_cast<const EngineeringCRS *>(comp0); auto comp1 = components[1].get(); auto comp1Bound = dynamic_cast<const BoundCRS *>(comp1); if (comp1Bound) { comp1 = comp1Bound->baseCRS().get(); } auto comp1Vert = dynamic_cast<const VerticalCRS *>(comp1); auto comp1Eng = dynamic_cast<const EngineeringCRS *>(comp1); // Loose validation based on // http://docs.opengeospatial.org/as/18-005r5/18-005r5.html#34 bool ok = false; const bool comp1IsVertOrEng1 = comp1Vert || (comp1Eng && comp1Eng->coordinateSystem()->axisList().size() == 1); if ((comp0Geog && comp0Geog->coordinateSystem()->axisList().size() == 2 && comp1IsVertOrEng1) || (comp0Proj && comp0Proj->coordinateSystem()->axisList().size() == 2 && comp1IsVertOrEng1) || (comp0DerPr && comp0DerPr->coordinateSystem()->axisList().size() == 2 && comp1IsVertOrEng1) || (comp0Eng && comp0Eng->coordinateSystem()->axisList().size() <= 2 && comp1Vert)) { // Spatial compound coordinate reference system ok = true; } else { bool isComp0Spatial = comp0Geog || comp0Proj || comp0DerPr || comp0Eng || dynamic_cast<const GeodeticCRS *>(comp0) || dynamic_cast<const VerticalCRS *>(comp0); if (isComp0Spatial && dynamic_cast<const TemporalCRS *>(comp1)) { // Spatio-temporal compound coordinate reference system ok = true; } else if (isComp0Spatial && dynamic_cast<const ParametricCRS *>(comp1)) { // Spatio-parametric compound coordinate reference system ok = true; } } if (!ok) { throw InvalidCompoundCRSException( "components of the compound CRS do not belong to one of the " "allowed combinations of " "http://docs.opengeospatial.org/as/18-005r5/18-005r5.html#34"); } auto compoundCRS(CompoundCRS::nn_make_shared<CompoundCRS>(components)); compoundCRS->assignSelf(compoundCRS); compoundCRS->setProperties(properties); if (!properties.get(common::IdentifiedObject::NAME_KEY)) { std::string name; for (const auto &crs : components) { if (!name.empty()) { name += " + "; } const auto &l_name = crs->nameStr(); if (!l_name.empty()) { name += l_name; } else { name += "unnamed"; } } util::PropertyMap propertyName; propertyName.set(common::IdentifiedObject::NAME_KEY, name); compoundCRS->setProperties(propertyName); } return compoundCRS; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Instantiate a CompoundCRS, a Geographic 3D CRS or a Projected CRS * from a vector of CRS. * * Be a bit "lax", in allowing formulations like EPSG:4326+4326 or * EPSG:32631+4326 to express Geographic 3D CRS / Projected3D CRS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param components the component CRS of the CompoundCRS. * @return new CRS. * @throw InvalidCompoundCRSException */ CRSNNPtr CompoundCRS::createLax(const util::PropertyMap &properties, const std::vector<CRSNNPtr> &components, const io::DatabaseContextPtr &dbContext) { if (components.size() == 2) { auto comp0 = components[0].get(); auto comp1 = components[1].get(); auto comp0Geog = dynamic_cast<const GeographicCRS *>(comp0); auto comp0Proj = dynamic_cast<const ProjectedCRS *>(comp0); auto comp0Bound = dynamic_cast<const BoundCRS *>(comp0); if (comp0Geog == nullptr && comp0Proj == nullptr) { if (comp0Bound) { const auto *baseCRS = comp0Bound->baseCRS().get(); comp0Geog = dynamic_cast<const GeographicCRS *>(baseCRS); comp0Proj = dynamic_cast<const ProjectedCRS *>(baseCRS); } } auto comp1Geog = dynamic_cast<const GeographicCRS *>(comp1); if ((comp0Geog != nullptr || comp0Proj != nullptr) && comp1Geog != nullptr) { const auto horizGeog = (comp0Proj != nullptr) ? comp0Proj->baseCRS().as_nullable().get() : comp0Geog; if (horizGeog->_isEquivalentTo( comp1Geog->demoteTo2D(std::string(), dbContext).get())) { return components[0] ->promoteTo3D(std::string(), dbContext) ->allowNonConformantWKT1Export(); } throw InvalidCompoundCRSException( "The 'vertical' geographic CRS is not equivalent to the " "geographic CRS of the horizontal part"); } // Detect a COMPD_CS whose VERT_CS is for ellipoidal heights auto comp1Vert = util::nn_dynamic_pointer_cast<VerticalCRS>(components[1]); if (comp1Vert != nullptr && comp1Vert->datum() && comp1Vert->datum()->getWKT1DatumType() == "2002") { const auto &axis = comp1Vert->coordinateSystem()->axisList()[0]; std::string name(components[0]->nameStr()); if (!(axis->unit()._isEquivalentTo( common::UnitOfMeasure::METRE, util::IComparable::Criterion::EQUIVALENT) && &(axis->direction()) == &(cs::AxisDirection::UP))) { name += " (" + comp1Vert->nameStr() + ')'; } auto newVertAxis = cs::CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, cs::AxisName::Ellipsoidal_height), cs::AxisAbbreviation::h, axis->direction(), axis->unit()); return components[0] ->promoteTo3D(name, dbContext, newVertAxis) ->attachOriginalCompoundCRS(create( properties, comp0Bound ? std::vector<CRSNNPtr>{comp0Bound->baseCRS(), components[1]} : components)); } } return create(properties, components); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CompoundCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; const auto &l_components = componentReferenceSystems(); if (!isWKT2 && formatter->useESRIDialect() && l_components.size() == 2) { l_components[0]->_exportToWKT(formatter); l_components[1]->_exportToWKT(formatter); } else { formatter->startNode(isWKT2 ? io::WKTConstants::COMPOUNDCRS : io::WKTConstants::COMPD_CS, !identifiers().empty()); formatter->addQuotedString(nameStr()); if (!l_components.empty()) { formatter->setGeogCRSOfCompoundCRS( l_components[0]->extractGeographicCRS()); } for (const auto &crs : l_components) { crs->_exportToWKT(formatter); } formatter->setGeogCRSOfCompoundCRS(nullptr); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CompoundCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("CompoundCRS", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("components"); { auto componentsContext(writer->MakeArrayContext(false)); for (const auto &crs : componentReferenceSystems()) { crs->_exportToJSON(formatter); } } ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- void CompoundCRS::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { const auto &l_components = componentReferenceSystems(); if (!l_components.empty()) { formatter->setGeogCRSOfCompoundCRS( l_components[0]->extractGeographicCRS()); } for (const auto &crs : l_components) { auto crs_exportable = dynamic_cast<const IPROJStringExportable *>(crs.get()); if (crs_exportable) { crs_exportable->_exportToPROJString(formatter); } } formatter->setGeogCRSOfCompoundCRS(nullptr); } // --------------------------------------------------------------------------- bool CompoundCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherCompoundCRS = dynamic_cast<const CompoundCRS *>(other); if (otherCompoundCRS == nullptr || (criterion == util::IComparable::Criterion::STRICT && !ObjectUsage::_isEquivalentTo(other, criterion, dbContext))) { return false; } const auto &components = componentReferenceSystems(); const auto &otherComponents = otherCompoundCRS->componentReferenceSystems(); if (components.size() != otherComponents.size()) { return false; } for (size_t i = 0; i < components.size(); i++) { if (!components[i]->_isEquivalentTo(otherComponents[i].get(), criterion, dbContext)) { return false; } } return true; } // --------------------------------------------------------------------------- /** \brief Identify the CRS with reference CRSs. * * The candidate CRSs are looked in the database when * authorityFactory is not null. * * Note that the implementation uses a set of heuristics to have a good * compromise of successful identifications over execution time. It might miss * legitimate matches in some circumstances. * * The method returns a list of matching reference CRS, and the percentage * (0-100) of confidence in the match. The list is sorted by decreasing * confidence. * * 100% means that the name of the reference entry * perfectly matches the CRS name, and both are equivalent. In which case a * single result is returned. * 90% means that CRS are equivalent, but the names are not exactly the same. * 70% means that CRS are equivalent (equivalent horizontal and vertical CRS), * but the names are not equivalent. * 25% means that the CRS are not equivalent, but there is some similarity in * the names. * * @param authorityFactory Authority factory (if null, will return an empty * list) * @return a list of matching reference CRS, and the percentage (0-100) of * confidence in the match. */ std::list<std::pair<CompoundCRSNNPtr, int>> CompoundCRS::identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<CompoundCRSNNPtr, int> Pair; std::list<Pair> res; const auto &thisName(nameStr()); const auto &components = componentReferenceSystems(); bool l_implicitCS = components[0]->hasImplicitCS(); if (!l_implicitCS) { const auto projCRS = dynamic_cast<const ProjectedCRS *>(components[0].get()); if (projCRS) { l_implicitCS = projCRS->baseCRS()->hasImplicitCS(); } } const auto crsCriterion = l_implicitCS ? util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS : util::IComparable::Criterion::EQUIVALENT; if (authorityFactory) { const io::DatabaseContextNNPtr &dbContext = authorityFactory->databaseContext(); const bool insignificantName = thisName.empty() || ci_equal(thisName, "unknown") || ci_equal(thisName, "unnamed"); bool foundEquivalentName = false; if (hasCodeCompatibleOfAuthorityFactory(this, authorityFactory)) { // If the CRS has already an id, check in the database for the // official object, and verify that they are equivalent. for (const auto &id : identifiers()) { if (hasCodeCompatibleOfAuthorityFactory(id, authorityFactory)) { try { auto crs = io::AuthorityFactory::create( dbContext, *id->codeSpace()) ->createCompoundCRS(id->code()); bool match = _isEquivalentTo(crs.get(), crsCriterion, dbContext); res.emplace_back(crs, match ? 100 : 25); return res; } catch (const std::exception &) { } } } } else if (!insignificantName) { for (int ipass = 0; ipass < 2; ipass++) { const bool approximateMatch = ipass == 1; auto objects = authorityFactory->createObjectsFromName( thisName, {io::AuthorityFactory::ObjectType::COMPOUND_CRS}, approximateMatch); for (const auto &obj : objects) { auto crs = util::nn_dynamic_pointer_cast<CompoundCRS>(obj); assert(crs); auto crsNN = NN_NO_CHECK(crs); const bool eqName = metadata::Identifier::isEquivalentName( thisName.c_str(), crs->nameStr().c_str()); foundEquivalentName |= eqName; if (_isEquivalentTo(crs.get(), crsCriterion, dbContext)) { if (crs->nameStr() == thisName) { res.clear(); res.emplace_back(crsNN, 100); return res; } res.emplace_back(crsNN, eqName ? 90 : 70); } else { res.emplace_back(crsNN, 25); } } if (!res.empty()) { break; } } } const auto lambdaSort = [&thisName](const Pair &a, const Pair &b) { // First consider confidence if (a.second > b.second) { return true; } if (a.second < b.second) { return false; } // Then consider exact name matching const auto &aName(a.first->nameStr()); const auto &bName(b.first->nameStr()); if (aName == thisName && bName != thisName) { return true; } if (bName == thisName && aName != thisName) { return false; } // Arbitrary final sorting criterion return aName < bName; }; // Sort results res.sort(lambdaSort); if (identifiers().empty() && !foundEquivalentName && (res.empty() || res.front().second < 50)) { std::set<std::pair<std::string, std::string>> alreadyKnown; for (const auto &pair : res) { const auto &ids = pair.first->identifiers(); assert(!ids.empty()); alreadyKnown.insert(std::pair<std::string, std::string>( *(ids[0]->codeSpace()), ids[0]->code())); } auto self = NN_NO_CHECK(std::dynamic_pointer_cast<CompoundCRS>( shared_from_this().as_nullable())); auto candidates = authorityFactory->createCompoundCRSFromExisting(self); for (const auto &crs : candidates) { const auto &ids = crs->identifiers(); assert(!ids.empty()); if (alreadyKnown.find(std::pair<std::string, std::string>( *(ids[0]->codeSpace()), ids[0]->code())) != alreadyKnown.end()) { continue; } if (_isEquivalentTo(crs.get(), crsCriterion, dbContext)) { res.emplace_back(crs, insignificantName ? 90 : 70); } else { res.emplace_back(crs, 25); } } res.sort(lambdaSort); // If there's a single candidate at 90% confidence with same name, // then promote it to 100% if (res.size() == 1 && res.front().second == 90 && thisName == res.front().first->nameStr()) { res.front().second = 100; } } // If we didn't find a match for the CompoundCRS, check if the // horizontal and vertical parts are not themselves well known. if (identifiers().empty() && res.empty() && components.size() == 2) { auto candidatesHorizCRS = components[0]->identify(authorityFactory); auto candidatesVertCRS = components[1]->identify(authorityFactory); if (candidatesHorizCRS.size() == 1 && candidatesVertCRS.size() == 1 && candidatesHorizCRS.front().second >= 70 && candidatesVertCRS.front().second >= 70) { auto newCRS = CompoundCRS::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, candidatesHorizCRS.front().first->nameStr() + " + " + candidatesVertCRS.front().first->nameStr()), {candidatesHorizCRS.front().first, candidatesVertCRS.front().first}); const bool eqName = metadata::Identifier::isEquivalentName( thisName.c_str(), newCRS->nameStr().c_str()); res.emplace_back( newCRS, std::min(thisName == newCRS->nameStr() ? 100 : eqName ? 90 : 70, std::min(candidatesHorizCRS.front().second, candidatesVertCRS.front().second))); } } // Keep only results of the highest confidence if (res.size() >= 2) { const auto highestConfidence = res.front().second; std::list<Pair> newRes; for (const auto &pair : res) { if (pair.second == highestConfidence) { newRes.push_back(pair); } else { break; } } return newRes; } } return res; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> CompoundCRS::_identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<CRSNNPtr, int> Pair; std::list<Pair> res; auto resTemp = identify(authorityFactory); for (const auto &pair : resTemp) { res.emplace_back(pair.first, pair.second); } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PROJ_INTERNAL BoundCRS::Private { CRSNNPtr baseCRS_; CRSNNPtr hubCRS_; operation::TransformationNNPtr transformation_; Private(const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn); inline const CRSNNPtr &baseCRS() const { return baseCRS_; } inline const CRSNNPtr &hubCRS() const { return hubCRS_; } inline const operation::TransformationNNPtr &transformation() const { return transformation_; } }; BoundCRS::Private::Private( const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn) : baseCRS_(baseCRSIn), hubCRS_(hubCRSIn), transformation_(transformationIn) {} //! @endcond // --------------------------------------------------------------------------- BoundCRS::BoundCRS(const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn) : d(internal::make_unique<Private>(baseCRSIn, hubCRSIn, transformationIn)) { } // --------------------------------------------------------------------------- BoundCRS::BoundCRS(const BoundCRS &other) : CRS(other), d(internal::make_unique<Private>(other.d->baseCRS(), other.d->hubCRS(), other.d->transformation())) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress BoundCRS::~BoundCRS() = default; //! @endcond // --------------------------------------------------------------------------- BoundCRSNNPtr BoundCRS::shallowCloneAsBoundCRS() const { auto crs(BoundCRS::nn_make_shared<BoundCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- CRSNNPtr BoundCRS::_shallowClone() const { return shallowCloneAsBoundCRS(); } // --------------------------------------------------------------------------- /** \brief Return the base CRS. * * This is the CRS into which coordinates of the BoundCRS are expressed. * * @return the base CRS. */ const CRSNNPtr &BoundCRS::baseCRS() PROJ_PURE_DEFN { return d->baseCRS_; } // --------------------------------------------------------------------------- // The only legit caller is BoundCRS::baseCRSWithCanonicalBoundCRS() void CRS::setCanonicalBoundCRS(const BoundCRSNNPtr &boundCRS) { d->canonicalBoundCRS_ = boundCRS; } // --------------------------------------------------------------------------- /** \brief Return a shallow clone of the base CRS that points to a * shallow clone of this BoundCRS. * * The base CRS is the CRS into which coordinates of the BoundCRS are expressed. * * The returned CRS will actually be a shallow clone of the actual base CRS, * with the extra property that CRS::canonicalBoundCRS() will point to a * shallow clone of this BoundCRS. Use this only if you want to work with * the base CRS object rather than the BoundCRS, but wanting to be able to * retrieve the BoundCRS later. * * @return the base CRS. */ CRSNNPtr BoundCRS::baseCRSWithCanonicalBoundCRS() const { auto baseCRSClone = baseCRS()->_shallowClone(); baseCRSClone->setCanonicalBoundCRS(shallowCloneAsBoundCRS()); return baseCRSClone; } // --------------------------------------------------------------------------- /** \brief Return the target / hub CRS. * * @return the hub CRS. */ const CRSNNPtr &BoundCRS::hubCRS() PROJ_PURE_DEFN { return d->hubCRS_; } // --------------------------------------------------------------------------- /** \brief Return the transformation to the hub RS. * * @return transformation. */ const operation::TransformationNNPtr & BoundCRS::transformation() PROJ_PURE_DEFN { return d->transformation_; } // --------------------------------------------------------------------------- /** \brief Instantiate a BoundCRS from a base CRS, a hub CRS and a * transformation. * * @param properties See \ref general_properties. * @param baseCRSIn base CRS. * @param hubCRSIn hub CRS. * @param transformationIn transformation from base CRS to hub CRS. * @return new BoundCRS. * @since PROJ 8.2 */ BoundCRSNNPtr BoundCRS::create(const util::PropertyMap &properties, const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn) { auto crs = BoundCRS::nn_make_shared<BoundCRS>(baseCRSIn, hubCRSIn, transformationIn); crs->assignSelf(crs); const auto &l_name = baseCRSIn->nameStr(); if (properties.get(common::IdentifiedObject::NAME_KEY) == nullptr && !l_name.empty()) { auto newProperties(properties); newProperties.set(common::IdentifiedObject::NAME_KEY, l_name); crs->setProperties(newProperties); } else { crs->setProperties(properties); } return crs; } // --------------------------------------------------------------------------- /** \brief Instantiate a BoundCRS from a base CRS, a hub CRS and a * transformation. * * @param baseCRSIn base CRS. * @param hubCRSIn hub CRS. * @param transformationIn transformation from base CRS to hub CRS. * @return new BoundCRS. */ BoundCRSNNPtr BoundCRS::create(const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn) { return create(util::PropertyMap(), baseCRSIn, hubCRSIn, transformationIn); } // --------------------------------------------------------------------------- /** \brief Instantiate a BoundCRS from a base CRS and TOWGS84 parameters * * @param baseCRSIn base CRS. * @param TOWGS84Parameters a vector of 3 or 7 double values representing WKT1 * TOWGS84 parameter. * @return new BoundCRS. */ BoundCRSNNPtr BoundCRS::createFromTOWGS84(const CRSNNPtr &baseCRSIn, const std::vector<double> &TOWGS84Parameters) { auto transf = operation::Transformation::createTOWGS84(baseCRSIn, TOWGS84Parameters); return create(baseCRSIn, transf->targetCRS(), transf); } // --------------------------------------------------------------------------- /** \brief Instantiate a BoundCRS from a base CRS and nadgrids parameters * * @param baseCRSIn base CRS. * @param filename Horizontal grid filename * @return new BoundCRS. */ BoundCRSNNPtr BoundCRS::createFromNadgrids(const CRSNNPtr &baseCRSIn, const std::string &filename) { const auto sourceGeographicCRS = baseCRSIn->extractGeographicCRS(); auto transformationSourceCRS = sourceGeographicCRS ? NN_NO_CHECK(std::static_pointer_cast<CRS>(sourceGeographicCRS)) : baseCRSIn; if (sourceGeographicCRS != nullptr && sourceGeographicCRS->primeMeridian()->longitude().getSIValue() != 0.0) { transformationSourceCRS = GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, sourceGeographicCRS->nameStr() + " (with Greenwich prime meridian)"), datum::GeodeticReferenceFrame::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, sourceGeographicCRS->datumNonNull(nullptr)->nameStr() + " (with Greenwich prime meridian)"), sourceGeographicCRS->datumNonNull(nullptr)->ellipsoid(), util::optional<std::string>(), datum::PrimeMeridian::GREENWICH), cs::EllipsoidalCS::createLatitudeLongitude( common::UnitOfMeasure::DEGREE)); } std::string transformationName = transformationSourceCRS->nameStr(); transformationName += " to WGS84"; return create( baseCRSIn, GeographicCRS::EPSG_4326, operation::Transformation::createNTv2( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, transformationName), transformationSourceCRS, GeographicCRS::EPSG_4326, filename, std::vector<metadata::PositionalAccuracyNNPtr>())); } // --------------------------------------------------------------------------- bool BoundCRS::isTOWGS84Compatible() const { return dynamic_cast<GeodeticCRS *>(d->hubCRS().get()) != nullptr && ci_equal(d->hubCRS()->nameStr(), "WGS 84"); } // --------------------------------------------------------------------------- std::string BoundCRS::getHDatumPROJ4GRIDS() const { if (ci_equal(d->hubCRS()->nameStr(), "WGS 84")) { return d->transformation()->getNTv2Filename(); } return std::string(); } // --------------------------------------------------------------------------- std::string BoundCRS::getVDatumPROJ4GRIDS(const crs::GeographicCRS *geogCRSOfCompoundCRS, const char **outGeoidCRSValue) const { // When importing from WKT1 PROJ4_GRIDS extension, we used to hardcode // "WGS 84" as the hub CRS, so let's test that for backward compatibility. if (dynamic_cast<VerticalCRS *>(d->baseCRS().get()) && ci_equal(d->hubCRS()->nameStr(), "WGS 84")) { if (outGeoidCRSValue) *outGeoidCRSValue = "WGS84"; return d->transformation()->getHeightToGeographic3DFilename(); } else if (geogCRSOfCompoundCRS && dynamic_cast<VerticalCRS *>(d->baseCRS().get()) && ci_equal(d->hubCRS()->nameStr(), geogCRSOfCompoundCRS->nameStr())) { if (outGeoidCRSValue) *outGeoidCRSValue = "horizontal_crs"; return d->transformation()->getHeightToGeographic3DFilename(); } return std::string(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void BoundCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (isWKT2) { formatter->startNode(io::WKTConstants::BOUNDCRS, false); formatter->startNode(io::WKTConstants::SOURCECRS, false); d->baseCRS()->_exportToWKT(formatter); formatter->endNode(); formatter->startNode(io::WKTConstants::TARGETCRS, false); d->hubCRS()->_exportToWKT(formatter); formatter->endNode(); formatter->setAbridgedTransformation(true); d->transformation()->_exportToWKT(formatter); formatter->setAbridgedTransformation(false); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } else { auto vdatumProj4GridName = getVDatumPROJ4GRIDS( formatter->getGeogCRSOfCompoundCRS().get(), nullptr); if (!vdatumProj4GridName.empty()) { formatter->setVDatumExtension(vdatumProj4GridName); d->baseCRS()->_exportToWKT(formatter); formatter->setVDatumExtension(std::string()); return; } auto hdatumProj4GridName = getHDatumPROJ4GRIDS(); if (!hdatumProj4GridName.empty()) { formatter->setHDatumExtension(hdatumProj4GridName); d->baseCRS()->_exportToWKT(formatter); formatter->setHDatumExtension(std::string()); return; } if (!isTOWGS84Compatible()) { io::FormattingException::Throw( "Cannot export BoundCRS with non-WGS 84 hub CRS in WKT1"); } auto params = d->transformation()->getTOWGS84Parameters(); if (!formatter->useESRIDialect()) { formatter->setTOWGS84Parameters(params); } d->baseCRS()->_exportToWKT(formatter); formatter->setTOWGS84Parameters(std::vector<double>()); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void BoundCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); const auto &l_name = nameStr(); auto objectContext(formatter->MakeObjectContext("BoundCRS", false)); const auto &l_sourceCRS = d->baseCRS(); if (!l_name.empty() && l_name != l_sourceCRS->nameStr()) { writer->AddObjKey("name"); writer->Add(l_name); } writer->AddObjKey("source_crs"); l_sourceCRS->_exportToJSON(formatter); writer->AddObjKey("target_crs"); const auto &l_targetCRS = d->hubCRS(); l_targetCRS->_exportToJSON(formatter); writer->AddObjKey("transformation"); formatter->setOmitTypeInImmediateChild(); formatter->setAbridgedTransformation(true); // Only write the source_crs of the transformation if it is different from // the source_crs of the BoundCRS. But don't do it for projectedCRS if its // base CRS matches the source_crs of the transformation and the targetCRS // is geographic const auto sourceCRSAsProjectedCRS = dynamic_cast<const ProjectedCRS *>(l_sourceCRS.get()); if (!l_sourceCRS->_isEquivalentTo( d->transformation()->sourceCRS().get(), util::IComparable::Criterion::EQUIVALENT) && (sourceCRSAsProjectedCRS == nullptr || (dynamic_cast<GeographicCRS *>(l_targetCRS.get()) && !sourceCRSAsProjectedCRS->baseCRS()->_isEquivalentTo( d->transformation()->sourceCRS().get(), util::IComparable::Criterion::EQUIVALENT)))) { formatter->setAbridgedTransformationWriteSourceCRS(true); } d->transformation()->_exportToJSON(formatter); formatter->setAbridgedTransformation(false); formatter->setAbridgedTransformationWriteSourceCRS(false); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- void BoundCRS::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { auto crs_exportable = dynamic_cast<const io::IPROJStringExportable *>(d->baseCRS_.get()); if (!crs_exportable) { io::FormattingException::Throw( "baseCRS of BoundCRS cannot be exported as a PROJ string"); } const char *geoidCRSValue = ""; auto vdatumProj4GridName = getVDatumPROJ4GRIDS( formatter->getGeogCRSOfCompoundCRS().get(), &geoidCRSValue); if (!vdatumProj4GridName.empty()) { formatter->setVDatumExtension(vdatumProj4GridName, geoidCRSValue); crs_exportable->_exportToPROJString(formatter); formatter->setVDatumExtension(std::string(), std::string()); } else { auto hdatumProj4GridName = getHDatumPROJ4GRIDS(); if (!hdatumProj4GridName.empty()) { formatter->setHDatumExtension(hdatumProj4GridName); crs_exportable->_exportToPROJString(formatter); formatter->setHDatumExtension(std::string()); } else { if (isTOWGS84Compatible()) { auto params = transformation()->getTOWGS84Parameters(); formatter->setTOWGS84Parameters(params); } crs_exportable->_exportToPROJString(formatter); formatter->setTOWGS84Parameters(std::vector<double>()); } } } // --------------------------------------------------------------------------- bool BoundCRS::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherBoundCRS = dynamic_cast<const BoundCRS *>(other); if (otherBoundCRS == nullptr || (criterion == util::IComparable::Criterion::STRICT && !ObjectUsage::_isEquivalentTo(other, criterion, dbContext))) { return false; } const auto standardCriterion = getStandardCriterion(criterion); return d->baseCRS_->_isEquivalentTo(otherBoundCRS->d->baseCRS_.get(), criterion, dbContext) && d->hubCRS_->_isEquivalentTo(otherBoundCRS->d->hubCRS_.get(), criterion, dbContext) && d->transformation_->_isEquivalentTo( otherBoundCRS->d->transformation_.get(), standardCriterion, dbContext); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> BoundCRS::_identify(const io::AuthorityFactoryPtr &authorityFactory) const { typedef std::pair<CRSNNPtr, int> Pair; std::list<Pair> res; if (!authorityFactory) return res; std::list<Pair> resMatchOfTransfToWGS84; const io::DatabaseContextNNPtr &dbContext = authorityFactory->databaseContext(); if (d->hubCRS_->_isEquivalentTo(GeographicCRS::EPSG_4326.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { auto resTemp = d->baseCRS_->identify(authorityFactory); std::string refTransfPROJString; bool refTransfPROJStringValid = false; auto refTransf = d->transformation_->normalizeForVisualization(); try { refTransfPROJString = refTransf->exportToPROJString( io::PROJStringFormatter::create().get()); refTransfPROJString = replaceAll( refTransfPROJString, " +rx=0 +ry=0 +rz=0 +s=0 +convention=position_vector", ""); refTransfPROJStringValid = true; } catch (const std::exception &) { } bool refIsNullTransform = false; if (isTOWGS84Compatible()) { auto params = transformation()->getTOWGS84Parameters(); if (params == std::vector<double>{0, 0, 0, 0, 0, 0, 0}) { refIsNullTransform = true; } } for (const auto &pair : resTemp) { const auto &candidateBaseCRS = pair.first; auto projCRS = dynamic_cast<const ProjectedCRS *>(candidateBaseCRS.get()); auto geodCRS = projCRS ? projCRS->baseCRS().as_nullable() : util::nn_dynamic_pointer_cast<GeodeticCRS>( candidateBaseCRS); if (geodCRS) { auto context = operation::CoordinateOperationContext::create( authorityFactory, nullptr, 0.0); context->setSpatialCriterion( operation::CoordinateOperationContext::SpatialCriterion:: PARTIAL_INTERSECTION); auto ops = operation::CoordinateOperationFactory::create() ->createOperations(NN_NO_CHECK(geodCRS), GeographicCRS::EPSG_4326, context); bool foundOp = false; for (const auto &op : ops) { auto opNormalized = op->normalizeForVisualization(); std::string opTransfPROJString; bool opTransfPROJStringValid = false; const auto &opName = op->nameStr(); if (starts_with( opName, operation::BALLPARK_GEOCENTRIC_TRANSLATION) || starts_with(opName, operation::NULL_GEOGRAPHIC_OFFSET)) { if (refIsNullTransform) { res.emplace_back(create(candidateBaseCRS, d->hubCRS_, transformation()), pair.second); foundOp = true; break; } continue; } try { opTransfPROJString = opNormalized->exportToPROJString( io::PROJStringFormatter::create().get()); opTransfPROJStringValid = true; opTransfPROJString = replaceAll(opTransfPROJString, " +rx=0 +ry=0 +rz=0 +s=0 " "+convention=position_vector", ""); } catch (const std::exception &) { } if ((refTransfPROJStringValid && opTransfPROJStringValid && refTransfPROJString == opTransfPROJString) || opNormalized->_isEquivalentTo( refTransf.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { resMatchOfTransfToWGS84.emplace_back( create(candidateBaseCRS, d->hubCRS_, NN_NO_CHECK(util::nn_dynamic_pointer_cast< operation::Transformation>(op))), pair.second); foundOp = true; break; } } if (!foundOp) { res.emplace_back( create(candidateBaseCRS, d->hubCRS_, transformation()), std::min(70, pair.second)); } } } } return !resMatchOfTransfToWGS84.empty() ? resMatchOfTransfToWGS84 : res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DerivedGeodeticCRS::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DerivedGeodeticCRS::~DerivedGeodeticCRS() = default; //! @endcond // --------------------------------------------------------------------------- DerivedGeodeticCRS::DerivedGeodeticCRS( const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn) : SingleCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), GeodeticCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), DerivedCRS(baseCRSIn, derivingConversionIn, csIn), d(nullptr) {} // --------------------------------------------------------------------------- DerivedGeodeticCRS::DerivedGeodeticCRS( const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::SphericalCSNNPtr &csIn) : SingleCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), GeodeticCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), DerivedCRS(baseCRSIn, derivingConversionIn, csIn), d(nullptr) {} // --------------------------------------------------------------------------- DerivedGeodeticCRS::DerivedGeodeticCRS(const DerivedGeodeticCRS &other) : SingleCRS(other), GeodeticCRS(other), DerivedCRS(other), d(nullptr) {} // --------------------------------------------------------------------------- CRSNNPtr DerivedGeodeticCRS::_shallowClone() const { auto crs(DerivedGeodeticCRS::nn_make_shared<DerivedGeodeticCRS>(*this)); crs->assignSelf(crs); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- /** \brief Return the base CRS (a GeodeticCRS) of a DerivedGeodeticCRS. * * @return the base CRS. */ const GeodeticCRSNNPtr DerivedGeodeticCRS::baseCRS() const { return NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>( DerivedCRS::getPrivate()->baseCRS_)); } // --------------------------------------------------------------------------- /** \brief Instantiate a DerivedGeodeticCRS from a base CRS, a deriving * conversion and a cs::CartesianCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param baseCRSIn base CRS. * @param derivingConversionIn the deriving conversion from the base CRS to this * CRS. * @param csIn the coordinate system. * @return new DerivedGeodeticCRS. */ DerivedGeodeticCRSNNPtr DerivedGeodeticCRS::create( const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn) { auto crs(DerivedGeodeticCRS::nn_make_shared<DerivedGeodeticCRS>( baseCRSIn, derivingConversionIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- /** \brief Instantiate a DerivedGeodeticCRS from a base CRS, a deriving * conversion and a cs::SphericalCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param baseCRSIn base CRS. * @param derivingConversionIn the deriving conversion from the base CRS to this * CRS. * @param csIn the coordinate system. * @return new DerivedGeodeticCRS. */ DerivedGeodeticCRSNNPtr DerivedGeodeticCRS::create( const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::SphericalCSNNPtr &csIn) { auto crs(DerivedGeodeticCRS::nn_make_shared<DerivedGeodeticCRS>( baseCRSIn, derivingConversionIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DerivedGeodeticCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { io::FormattingException::Throw( "DerivedGeodeticCRS can only be exported to WKT2"); } formatter->startNode(io::WKTConstants::GEODCRS, !identifiers().empty()); formatter->addQuotedString(nameStr()); auto l_baseCRS = baseCRS(); formatter->startNode((formatter->use2019Keywords() && dynamic_cast<const GeographicCRS *>(l_baseCRS.get())) ? io::WKTConstants::BASEGEOGCRS : io::WKTConstants::BASEGEODCRS, !baseCRS()->identifiers().empty()); formatter->addQuotedString(l_baseCRS->nameStr()); auto l_datum = l_baseCRS->datum(); if (l_datum) { l_datum->_exportToWKT(formatter); } else { auto l_datumEnsemble = datumEnsemble(); assert(l_datumEnsemble); l_datumEnsemble->_exportToWKT(formatter); } l_baseCRS->primeMeridian()->_exportToWKT(formatter); formatter->endNode(); formatter->setUseDerivingConversion(true); derivingConversionRef()->_exportToWKT(formatter); formatter->setUseDerivingConversion(false); coordinateSystem()->_exportToWKT(formatter); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- void DerivedGeodeticCRS::_exportToPROJString( io::PROJStringFormatter *) const // throw(io::FormattingException) { throw io::FormattingException( "DerivedGeodeticCRS cannot be exported to PROJ string"); } // --------------------------------------------------------------------------- bool DerivedGeodeticCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDerivedCRS = dynamic_cast<const DerivedGeodeticCRS *>(other); return otherDerivedCRS != nullptr && DerivedCRS::_isEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> DerivedGeodeticCRS::_identify(const io::AuthorityFactoryPtr &factory) const { return CRS::_identify(factory); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DerivedGeographicCRS::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DerivedGeographicCRS::~DerivedGeographicCRS() = default; //! @endcond // --------------------------------------------------------------------------- DerivedGeographicCRS::DerivedGeographicCRS( const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::EllipsoidalCSNNPtr &csIn) : SingleCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), GeographicCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), DerivedCRS(baseCRSIn, derivingConversionIn, csIn), d(nullptr) {} // --------------------------------------------------------------------------- DerivedGeographicCRS::DerivedGeographicCRS(const DerivedGeographicCRS &other) : SingleCRS(other), GeographicCRS(other), DerivedCRS(other), d(nullptr) {} // --------------------------------------------------------------------------- CRSNNPtr DerivedGeographicCRS::_shallowClone() const { auto crs(DerivedGeographicCRS::nn_make_shared<DerivedGeographicCRS>(*this)); crs->assignSelf(crs); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- /** \brief Return the base CRS (a GeodeticCRS) of a DerivedGeographicCRS. * * @return the base CRS. */ const GeodeticCRSNNPtr DerivedGeographicCRS::baseCRS() const { return NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>( DerivedCRS::getPrivate()->baseCRS_)); } // --------------------------------------------------------------------------- /** \brief Instantiate a DerivedGeographicCRS from a base CRS, a deriving * conversion and a cs::EllipsoidalCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param baseCRSIn base CRS. * @param derivingConversionIn the deriving conversion from the base CRS to this * CRS. * @param csIn the coordinate system. * @return new DerivedGeographicCRS. */ DerivedGeographicCRSNNPtr DerivedGeographicCRS::create( const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::EllipsoidalCSNNPtr &csIn) { auto crs(DerivedGeographicCRS::nn_make_shared<DerivedGeographicCRS>( baseCRSIn, derivingConversionIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DerivedGeographicCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { io::FormattingException::Throw( "DerivedGeographicCRS can only be exported to WKT2"); } formatter->startNode(formatter->use2019Keywords() ? io::WKTConstants::GEOGCRS : io::WKTConstants::GEODCRS, !identifiers().empty()); formatter->addQuotedString(nameStr()); auto l_baseCRS = baseCRS(); formatter->startNode((formatter->use2019Keywords() && dynamic_cast<const GeographicCRS *>(l_baseCRS.get())) ? io::WKTConstants::BASEGEOGCRS : io::WKTConstants::BASEGEODCRS, !l_baseCRS->identifiers().empty()); formatter->addQuotedString(l_baseCRS->nameStr()); l_baseCRS->exportDatumOrDatumEnsembleToWkt(formatter); l_baseCRS->primeMeridian()->_exportToWKT(formatter); formatter->endNode(); formatter->setUseDerivingConversion(true); derivingConversionRef()->_exportToWKT(formatter); formatter->setUseDerivingConversion(false); coordinateSystem()->_exportToWKT(formatter); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- void DerivedGeographicCRS::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(io::FormattingException) { const auto &l_conv = derivingConversionRef(); const auto &methodName = l_conv->method()->nameStr(); for (const char *substr : {"PROJ ob_tran o_proj=longlat", "PROJ ob_tran o_proj=lonlat", "PROJ ob_tran o_proj=latlon", "PROJ ob_tran o_proj=latlong"}) { if (starts_with(methodName, substr)) { l_conv->_exportToPROJString(formatter); return; } } if (ci_equal(methodName, PROJ_WKT2_NAME_METHOD_POLE_ROTATION_GRIB_CONVENTION) || ci_equal(methodName, PROJ_WKT2_NAME_METHOD_POLE_ROTATION_NETCDF_CF_CONVENTION)) { l_conv->_exportToPROJString(formatter); return; } throw io::FormattingException( "DerivedGeographicCRS cannot be exported to PROJ string"); } // --------------------------------------------------------------------------- bool DerivedGeographicCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDerivedCRS = dynamic_cast<const DerivedGeographicCRS *>(other); return otherDerivedCRS != nullptr && DerivedCRS::_isEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- /** \brief Return a variant of this CRS "demoted" to a 2D one, if not already * the case. * * * @param newName Name of the new CRS. If empty, nameStr() will be used. * @param dbContext Database context to look for potentially already registered * 2D CRS. May be nullptr. * @return a new CRS demoted to 2D, or the current one if already 2D or not * applicable. * @since 8.1.1 */ DerivedGeographicCRSNNPtr DerivedGeographicCRS::demoteTo2D( const std::string &newName, const io::DatabaseContextPtr &dbContext) const { const auto &axisList = coordinateSystem()->axisList(); if (axisList.size() == 3) { auto cs = cs::EllipsoidalCS::create(util::PropertyMap(), axisList[0], axisList[1]); auto baseGeog2DCRS = util::nn_dynamic_pointer_cast<GeodeticCRS>( baseCRS()->demoteTo2D(std::string(), dbContext)); return DerivedGeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, !newName.empty() ? newName : nameStr()), NN_CHECK_THROW(std::move(baseGeog2DCRS)), derivingConversion(), std::move(cs)); } return NN_NO_CHECK(std::dynamic_pointer_cast<DerivedGeographicCRS>( shared_from_this().as_nullable())); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> DerivedGeographicCRS::_identify(const io::AuthorityFactoryPtr &factory) const { return CRS::_identify(factory); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DerivedProjectedCRS::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DerivedProjectedCRS::~DerivedProjectedCRS() = default; //! @endcond // --------------------------------------------------------------------------- DerivedProjectedCRS::DerivedProjectedCRS( const ProjectedCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CoordinateSystemNNPtr &csIn) : SingleCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), DerivedCRS(baseCRSIn, derivingConversionIn, csIn), d(nullptr) {} // --------------------------------------------------------------------------- DerivedProjectedCRS::DerivedProjectedCRS(const DerivedProjectedCRS &other) : SingleCRS(other), DerivedCRS(other), d(nullptr) {} // --------------------------------------------------------------------------- CRSNNPtr DerivedProjectedCRS::_shallowClone() const { auto crs(DerivedProjectedCRS::nn_make_shared<DerivedProjectedCRS>(*this)); crs->assignSelf(crs); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- /** \brief Return the base CRS (a ProjectedCRS) of a DerivedProjectedCRS. * * @return the base CRS. */ const ProjectedCRSNNPtr DerivedProjectedCRS::baseCRS() const { return NN_NO_CHECK(util::nn_dynamic_pointer_cast<ProjectedCRS>( DerivedCRS::getPrivate()->baseCRS_)); } // --------------------------------------------------------------------------- /** \brief Instantiate a DerivedProjectedCRS from a base CRS, a deriving * conversion and a cs::CS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param baseCRSIn base CRS. * @param derivingConversionIn the deriving conversion from the base CRS to this * CRS. * @param csIn the coordinate system. * @return new DerivedProjectedCRS. */ DerivedProjectedCRSNNPtr DerivedProjectedCRS::create( const util::PropertyMap &properties, const ProjectedCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CoordinateSystemNNPtr &csIn) { auto crs(DerivedProjectedCRS::nn_make_shared<DerivedProjectedCRS>( baseCRSIn, derivingConversionIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- /** \brief Return a variant of this CRS "demoted" to a 2D one, if not already * the case. * * * @param newName Name of the new CRS. If empty, nameStr() will be used. * @param dbContext Database context to look for potentially already registered * 2D CRS. May be nullptr. * @return a new CRS demoted to 2D, or the current one if already 2D or not * applicable. * @since 9.1.1 */ DerivedProjectedCRSNNPtr DerivedProjectedCRS::demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const { const auto &axisList = coordinateSystem()->axisList(); if (axisList.size() == 3) { auto cs = cs::CartesianCS::create(util::PropertyMap(), axisList[0], axisList[1]); auto baseProj2DCRS = util::nn_dynamic_pointer_cast<ProjectedCRS>( baseCRS()->demoteTo2D(std::string(), dbContext)); return DerivedProjectedCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, !newName.empty() ? newName : nameStr()), NN_CHECK_THROW(std::move(baseProj2DCRS)), derivingConversion(), std::move(cs)); } return NN_NO_CHECK(std::dynamic_pointer_cast<DerivedProjectedCRS>( shared_from_this().as_nullable())); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DerivedProjectedCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2 || !formatter->use2019Keywords()) { io::FormattingException::Throw( "DerivedProjectedCRS can only be exported to WKT2:2019"); } formatter->startNode(io::WKTConstants::DERIVEDPROJCRS, !identifiers().empty()); formatter->addQuotedString(nameStr()); { auto l_baseProjCRS = baseCRS(); formatter->startNode(io::WKTConstants::BASEPROJCRS, !l_baseProjCRS->identifiers().empty()); formatter->addQuotedString(l_baseProjCRS->nameStr()); auto l_baseGeodCRS = l_baseProjCRS->baseCRS(); auto &geodeticCRSAxisList = l_baseGeodCRS->coordinateSystem()->axisList(); formatter->startNode( dynamic_cast<const GeographicCRS *>(l_baseGeodCRS.get()) ? io::WKTConstants::BASEGEOGCRS : io::WKTConstants::BASEGEODCRS, !l_baseGeodCRS->identifiers().empty()); formatter->addQuotedString(l_baseGeodCRS->nameStr()); l_baseGeodCRS->exportDatumOrDatumEnsembleToWkt(formatter); // insert ellipsoidal cs unit when the units of the map // projection angular parameters are not explicitly given within those // parameters. See // http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#61 if (formatter->primeMeridianOrParameterUnitOmittedIfSameAsAxis() && !geodeticCRSAxisList.empty()) { geodeticCRSAxisList[0]->unit()._exportToWKT(formatter); } l_baseGeodCRS->primeMeridian()->_exportToWKT(formatter); formatter->endNode(); l_baseProjCRS->derivingConversionRef()->_exportToWKT(formatter); formatter->endNode(); } formatter->setUseDerivingConversion(true); derivingConversionRef()->_exportToWKT(formatter); formatter->setUseDerivingConversion(false); coordinateSystem()->_exportToWKT(formatter); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- bool DerivedProjectedCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDerivedCRS = dynamic_cast<const DerivedProjectedCRS *>(other); return otherDerivedCRS != nullptr && DerivedCRS::_isEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DerivedProjectedCRS::addUnitConvertAndAxisSwap( io::PROJStringFormatter *formatter) const { ProjectedCRS::addUnitConvertAndAxisSwap(coordinateSystem()->axisList(), formatter, false); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct TemporalCRS::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TemporalCRS::~TemporalCRS() = default; //! @endcond // --------------------------------------------------------------------------- TemporalCRS::TemporalCRS(const datum::TemporalDatumNNPtr &datumIn, const cs::TemporalCSNNPtr &csIn) : SingleCRS(datumIn.as_nullable(), nullptr, csIn), d(nullptr) {} // --------------------------------------------------------------------------- TemporalCRS::TemporalCRS(const TemporalCRS &other) : SingleCRS(other), d(nullptr) {} // --------------------------------------------------------------------------- CRSNNPtr TemporalCRS::_shallowClone() const { auto crs(TemporalCRS::nn_make_shared<TemporalCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- /** \brief Return the datum::TemporalDatum associated with the CRS. * * @return a TemporalDatum */ const datum::TemporalDatumNNPtr TemporalCRS::datum() const { return NN_NO_CHECK(std::static_pointer_cast<datum::TemporalDatum>( SingleCRS::getPrivate()->datum)); } // --------------------------------------------------------------------------- /** \brief Return the cs::TemporalCS associated with the CRS. * * @return a TemporalCS */ const cs::TemporalCSNNPtr TemporalCRS::coordinateSystem() const { return util::nn_static_pointer_cast<cs::TemporalCS>( SingleCRS::getPrivate()->coordinateSystem); } // --------------------------------------------------------------------------- /** \brief Instantiate a TemporalCRS from a datum and a coordinate system. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datumIn the datum. * @param csIn the coordinate system. * @return new TemporalCRS. */ TemporalCRSNNPtr TemporalCRS::create(const util::PropertyMap &properties, const datum::TemporalDatumNNPtr &datumIn, const cs::TemporalCSNNPtr &csIn) { auto crs(TemporalCRS::nn_make_shared<TemporalCRS>(datumIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void TemporalCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { io::FormattingException::Throw( "TemporalCRS can only be exported to WKT2"); } formatter->startNode(io::WKTConstants::TIMECRS, !identifiers().empty()); formatter->addQuotedString(nameStr()); datum()->_exportToWKT(formatter); coordinateSystem()->_exportToWKT(formatter); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void TemporalCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("TemporalCRS", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("datum"); formatter->setOmitTypeInImmediateChild(); datum()->_exportToJSON(formatter); writer->AddObjKey("coordinate_system"); formatter->setOmitTypeInImmediateChild(); coordinateSystem()->_exportToJSON(formatter); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- bool TemporalCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherTemporalCRS = dynamic_cast<const TemporalCRS *>(other); return otherTemporalCRS != nullptr && SingleCRS::baseIsEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct EngineeringCRS::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress EngineeringCRS::~EngineeringCRS() = default; //! @endcond // --------------------------------------------------------------------------- EngineeringCRS::EngineeringCRS(const datum::EngineeringDatumNNPtr &datumIn, const cs::CoordinateSystemNNPtr &csIn) : SingleCRS(datumIn.as_nullable(), nullptr, csIn), d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- EngineeringCRS::EngineeringCRS(const EngineeringCRS &other) : SingleCRS(other), d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- CRSNNPtr EngineeringCRS::_shallowClone() const { auto crs(EngineeringCRS::nn_make_shared<EngineeringCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- /** \brief Return the datum::EngineeringDatum associated with the CRS. * * @return a EngineeringDatum */ const datum::EngineeringDatumNNPtr EngineeringCRS::datum() const { return NN_NO_CHECK(std::static_pointer_cast<datum::EngineeringDatum>( SingleCRS::getPrivate()->datum)); } // --------------------------------------------------------------------------- /** \brief Instantiate a EngineeringCRS from a datum and a coordinate system. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datumIn the datum. * @param csIn the coordinate system. * @return new EngineeringCRS. */ EngineeringCRSNNPtr EngineeringCRS::create(const util::PropertyMap &properties, const datum::EngineeringDatumNNPtr &datumIn, const cs::CoordinateSystemNNPtr &csIn) { auto crs(EngineeringCRS::nn_make_shared<EngineeringCRS>(datumIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void EngineeringCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; formatter->startNode(isWKT2 ? io::WKTConstants::ENGCRS : io::WKTConstants::LOCAL_CS, !identifiers().empty()); formatter->addQuotedString(nameStr()); const auto &datumName = datum()->nameStr(); if (isWKT2 || (!datumName.empty() && datumName != UNKNOWN_ENGINEERING_DATUM)) { datum()->_exportToWKT(formatter); } if (!isWKT2) { coordinateSystem()->axisList()[0]->unit()._exportToWKT(formatter); } const auto oldAxisOutputRule = formatter->outputAxis(); formatter->setOutputAxis(io::WKTFormatter::OutputAxisRule::YES); coordinateSystem()->_exportToWKT(formatter); formatter->setOutputAxis(oldAxisOutputRule); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void EngineeringCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("EngineeringCRS", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("datum"); formatter->setOmitTypeInImmediateChild(); datum()->_exportToJSON(formatter); writer->AddObjKey("coordinate_system"); formatter->setOmitTypeInImmediateChild(); coordinateSystem()->_exportToJSON(formatter); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- bool EngineeringCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherEngineeringCRS = dynamic_cast<const EngineeringCRS *>(other); if (otherEngineeringCRS == nullptr || (criterion == util::IComparable::Criterion::STRICT && !ObjectUsage::_isEquivalentTo(other, criterion, dbContext))) { return false; } // Check datum const auto &thisDatum = datum(); const auto &otherDatum = otherEngineeringCRS->datum(); if (!thisDatum->_isEquivalentTo(otherDatum.get(), criterion, dbContext)) { return false; } // Check coordinate system const auto &thisCS = coordinateSystem(); const auto &otherCS = otherEngineeringCRS->coordinateSystem(); if (!(thisCS->_isEquivalentTo(otherCS.get(), criterion, dbContext))) { const auto thisCartCS = dynamic_cast<cs::CartesianCS *>(thisCS.get()); const auto otherCartCS = dynamic_cast<cs::CartesianCS *>(otherCS.get()); const auto &thisAxisList = thisCS->axisList(); const auto &otherAxisList = otherCS->axisList(); // Check particular case of // https://github.com/r-spatial/sf/issues/2049#issuecomment-1486600723 if (criterion != util::IComparable::Criterion::STRICT && thisCartCS && otherCartCS && thisAxisList.size() == 2 && otherAxisList.size() == 2 && ((&thisAxisList[0]->direction() == &cs::AxisDirection::UNSPECIFIED && &thisAxisList[1]->direction() == &cs::AxisDirection::UNSPECIFIED) || (&otherAxisList[0]->direction() == &cs::AxisDirection::UNSPECIFIED && &otherAxisList[1]->direction() == &cs::AxisDirection::UNSPECIFIED)) && ((thisAxisList[0]->nameStr() == "X" && otherAxisList[0]->nameStr() == "Easting" && thisAxisList[1]->nameStr() == "Y" && otherAxisList[1]->nameStr() == "Northing") || (otherAxisList[0]->nameStr() == "X" && thisAxisList[0]->nameStr() == "Easting" && otherAxisList[1]->nameStr() == "Y" && thisAxisList[1]->nameStr() == "Northing"))) { return true; } return false; } return true; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ParametricCRS::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ParametricCRS::~ParametricCRS() = default; //! @endcond // --------------------------------------------------------------------------- ParametricCRS::ParametricCRS(const datum::ParametricDatumNNPtr &datumIn, const cs::ParametricCSNNPtr &csIn) : SingleCRS(datumIn.as_nullable(), nullptr, csIn), d(nullptr) {} // --------------------------------------------------------------------------- ParametricCRS::ParametricCRS(const ParametricCRS &other) : SingleCRS(other), d(nullptr) {} // --------------------------------------------------------------------------- CRSNNPtr ParametricCRS::_shallowClone() const { auto crs(ParametricCRS::nn_make_shared<ParametricCRS>(*this)); crs->assignSelf(crs); return crs; } // --------------------------------------------------------------------------- /** \brief Return the datum::ParametricDatum associated with the CRS. * * @return a ParametricDatum */ const datum::ParametricDatumNNPtr ParametricCRS::datum() const { return NN_NO_CHECK(std::static_pointer_cast<datum::ParametricDatum>( SingleCRS::getPrivate()->datum)); } // --------------------------------------------------------------------------- /** \brief Return the cs::TemporalCS associated with the CRS. * * @return a TemporalCS */ const cs::ParametricCSNNPtr ParametricCRS::coordinateSystem() const { return util::nn_static_pointer_cast<cs::ParametricCS>( SingleCRS::getPrivate()->coordinateSystem); } // --------------------------------------------------------------------------- /** \brief Instantiate a ParametricCRS from a datum and a coordinate system. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param datumIn the datum. * @param csIn the coordinate system. * @return new ParametricCRS. */ ParametricCRSNNPtr ParametricCRS::create(const util::PropertyMap &properties, const datum::ParametricDatumNNPtr &datumIn, const cs::ParametricCSNNPtr &csIn) { auto crs(ParametricCRS::nn_make_shared<ParametricCRS>(datumIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ParametricCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { io::FormattingException::Throw( "ParametricCRS can only be exported to WKT2"); } formatter->startNode(io::WKTConstants::PARAMETRICCRS, !identifiers().empty()); formatter->addQuotedString(nameStr()); datum()->_exportToWKT(formatter); coordinateSystem()->_exportToWKT(formatter); ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ParametricCRS::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("ParametricCRS", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("datum"); formatter->setOmitTypeInImmediateChild(); datum()->_exportToJSON(formatter); writer->AddObjKey("coordinate_system"); formatter->setOmitTypeInImmediateChild(); coordinateSystem()->_exportToJSON(formatter); ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- bool ParametricCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherParametricCRS = dynamic_cast<const ParametricCRS *>(other); return otherParametricCRS != nullptr && SingleCRS::baseIsEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct DerivedVerticalCRS::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress DerivedVerticalCRS::~DerivedVerticalCRS() = default; //! @endcond // --------------------------------------------------------------------------- DerivedVerticalCRS::DerivedVerticalCRS( const VerticalCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::VerticalCSNNPtr &csIn) : SingleCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), VerticalCRS(baseCRSIn->datum(), baseCRSIn->datumEnsemble(), csIn), DerivedCRS(baseCRSIn, derivingConversionIn, csIn), d(nullptr) {} // --------------------------------------------------------------------------- DerivedVerticalCRS::DerivedVerticalCRS(const DerivedVerticalCRS &other) : SingleCRS(other), VerticalCRS(other), DerivedCRS(other), d(nullptr) {} // --------------------------------------------------------------------------- CRSNNPtr DerivedVerticalCRS::_shallowClone() const { auto crs(DerivedVerticalCRS::nn_make_shared<DerivedVerticalCRS>(*this)); crs->assignSelf(crs); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- /** \brief Return the base CRS (a VerticalCRS) of a DerivedVerticalCRS. * * @return the base CRS. */ const VerticalCRSNNPtr DerivedVerticalCRS::baseCRS() const { return NN_NO_CHECK(util::nn_dynamic_pointer_cast<VerticalCRS>( DerivedCRS::getPrivate()->baseCRS_)); } // --------------------------------------------------------------------------- /** \brief Instantiate a DerivedVerticalCRS from a base CRS, a deriving * conversion and a cs::VerticalCS. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param baseCRSIn base CRS. * @param derivingConversionIn the deriving conversion from the base CRS to this * CRS. * @param csIn the coordinate system. * @return new DerivedVerticalCRS. */ DerivedVerticalCRSNNPtr DerivedVerticalCRS::create( const util::PropertyMap &properties, const VerticalCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::VerticalCSNNPtr &csIn) { auto crs(DerivedVerticalCRS::nn_make_shared<DerivedVerticalCRS>( baseCRSIn, derivingConversionIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void DerivedVerticalCRS::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { bool useBaseMethod = true; const DerivedVerticalCRS *dvcrs = this; while (true) { // If the derived vertical CRS is obtained through simple conversion // methods that just do unit change or height/depth reversal, export // it as a regular VerticalCRS const int methodCode = dvcrs->derivingConversionRef()->method()->getEPSGCode(); if (methodCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT || methodCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR || methodCode == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { dvcrs = dynamic_cast<DerivedVerticalCRS *>(baseCRS().get()); if (dvcrs == nullptr) { break; } } else { useBaseMethod = false; break; } } if (useBaseMethod) { VerticalCRS::_exportToWKT(formatter); return; } io::FormattingException::Throw( "DerivedVerticalCRS can only be exported to WKT2"); } baseExportToWKT(formatter, io::WKTConstants::VERTCRS, io::WKTConstants::BASEVERTCRS); } //! @endcond // --------------------------------------------------------------------------- void DerivedVerticalCRS::_exportToPROJString( io::PROJStringFormatter *) const // throw(io::FormattingException) { throw io::FormattingException( "DerivedVerticalCRS cannot be exported to PROJ string"); } // --------------------------------------------------------------------------- bool DerivedVerticalCRS::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDerivedCRS = dynamic_cast<const DerivedVerticalCRS *>(other); return otherDerivedCRS != nullptr && DerivedCRS::_isEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::list<std::pair<CRSNNPtr, int>> DerivedVerticalCRS::_identify(const io::AuthorityFactoryPtr &factory) const { return CRS::_identify(factory); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress template <class DerivedCRSTraits> struct DerivedCRSTemplate<DerivedCRSTraits>::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress template <class DerivedCRSTraits> DerivedCRSTemplate<DerivedCRSTraits>::~DerivedCRSTemplate() = default; //! @endcond // --------------------------------------------------------------------------- template <class DerivedCRSTraits> DerivedCRSTemplate<DerivedCRSTraits>::DerivedCRSTemplate( const BaseNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const CSNNPtr &csIn) : SingleCRS(baseCRSIn->datum().as_nullable(), nullptr, csIn), BaseType(baseCRSIn->datum(), csIn), DerivedCRS(baseCRSIn, derivingConversionIn, csIn), d(nullptr) {} // --------------------------------------------------------------------------- template <class DerivedCRSTraits> DerivedCRSTemplate<DerivedCRSTraits>::DerivedCRSTemplate( const DerivedCRSTemplate &other) : SingleCRS(other), BaseType(other), DerivedCRS(other), d(nullptr) {} // --------------------------------------------------------------------------- template <class DerivedCRSTraits> const typename DerivedCRSTemplate<DerivedCRSTraits>::BaseNNPtr DerivedCRSTemplate<DerivedCRSTraits>::baseCRS() const { auto l_baseCRS = DerivedCRS::getPrivate()->baseCRS_; return NN_NO_CHECK(util::nn_dynamic_pointer_cast<BaseType>(l_baseCRS)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress template <class DerivedCRSTraits> CRSNNPtr DerivedCRSTemplate<DerivedCRSTraits>::_shallowClone() const { auto crs(DerivedCRSTemplate::nn_make_shared<DerivedCRSTemplate>(*this)); crs->assignSelf(crs); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- template <class DerivedCRSTraits> typename DerivedCRSTemplate<DerivedCRSTraits>::NNPtr DerivedCRSTemplate<DerivedCRSTraits>::create( const util::PropertyMap &properties, const BaseNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const CSNNPtr &csIn) { auto crs(DerivedCRSTemplate::nn_make_shared<DerivedCRSTemplate>( baseCRSIn, derivingConversionIn, csIn)); crs->assignSelf(crs); crs->setProperties(properties); crs->setDerivingConversionCRS(); return crs; } // --------------------------------------------------------------------------- template <class DerivedCRSTraits> const char *DerivedCRSTemplate<DerivedCRSTraits>::className() const { return DerivedCRSTraits::CRSName().c_str(); } // --------------------------------------------------------------------------- static void DerivedCRSTemplateCheckExportToWKT(io::WKTFormatter *formatter, const std::string &crsName, bool wkt2_2019_only) { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2 || (wkt2_2019_only && !formatter->use2019Keywords())) { io::FormattingException::Throw(crsName + " can only be exported to WKT2" + (wkt2_2019_only ? ":2019" : "")); } } // --------------------------------------------------------------------------- template <class DerivedCRSTraits> void DerivedCRSTemplate<DerivedCRSTraits>::_exportToWKT( io::WKTFormatter *formatter) const { DerivedCRSTemplateCheckExportToWKT(formatter, DerivedCRSTraits::CRSName(), DerivedCRSTraits::wkt2_2019_only); baseExportToWKT(formatter, DerivedCRSTraits::WKTKeyword(), DerivedCRSTraits::WKTBaseKeyword()); } // --------------------------------------------------------------------------- template <class DerivedCRSTraits> bool DerivedCRSTemplate<DerivedCRSTraits>::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherDerivedCRS = dynamic_cast<const DerivedCRSTemplate *>(other); return otherDerivedCRS != nullptr && DerivedCRS::_isEquivalentTo(other, criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string STRING_DerivedEngineeringCRS("DerivedEngineeringCRS"); const std::string &DerivedEngineeringCRSTraits::CRSName() { return STRING_DerivedEngineeringCRS; } const std::string &DerivedEngineeringCRSTraits::WKTKeyword() { return io::WKTConstants::ENGCRS; } const std::string &DerivedEngineeringCRSTraits::WKTBaseKeyword() { return io::WKTConstants::BASEENGCRS; } template class DerivedCRSTemplate<DerivedEngineeringCRSTraits>; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string STRING_DerivedParametricCRS("DerivedParametricCRS"); const std::string &DerivedParametricCRSTraits::CRSName() { return STRING_DerivedParametricCRS; } const std::string &DerivedParametricCRSTraits::WKTKeyword() { return io::WKTConstants::PARAMETRICCRS; } const std::string &DerivedParametricCRSTraits::WKTBaseKeyword() { return io::WKTConstants::BASEPARAMCRS; } template class DerivedCRSTemplate<DerivedParametricCRSTraits>; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string STRING_DerivedTemporalCRS("DerivedTemporalCRS"); const std::string &DerivedTemporalCRSTraits::CRSName() { return STRING_DerivedTemporalCRS; } const std::string &DerivedTemporalCRSTraits::WKTKeyword() { return io::WKTConstants::TIMECRS; } const std::string &DerivedTemporalCRSTraits::WKTBaseKeyword() { return io::WKTConstants::BASETIMECRS; } template class DerivedCRSTemplate<DerivedTemporalCRSTraits>; //! @endcond // --------------------------------------------------------------------------- } // namespace crs NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/util.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/util.hpp" #include "proj/io.hpp" #include "proj/internal/internal.hpp" #include <map> #include <memory> #include <string> using namespace NS_PROJ::internal; #if 0 namespace dropbox{ namespace oxygen { template<> nn<NS_PROJ::util::BaseObjectPtr>::~nn() = default; template<> nn<NS_PROJ::util::BoxedValuePtr>::~nn() = default; template<> nn<NS_PROJ::util::ArrayOfBaseObjectPtr>::~nn() = default; template<> nn<NS_PROJ::util::LocalNamePtr>::~nn() = default; template<> nn<NS_PROJ::util::GenericNamePtr>::~nn() = default; template<> nn<NS_PROJ::util::NameSpacePtr>::~nn() = default; }} #endif NS_PROJ_START namespace util { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct BaseObject::Private { // This is a manual implementation of std::enable_shared_from_this<> that // avoids publicly deriving from it. std::weak_ptr<BaseObject> self_{}; }; //! @endcond // --------------------------------------------------------------------------- BaseObject::BaseObject() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress BaseObject::~BaseObject() = default; // --------------------------------------------------------------------------- BaseObjectNNPtr::~BaseObjectNNPtr() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // cppcheck-suppress operatorEqVarError BaseObject &BaseObject::operator=(BaseObject &&) { d->self_.reset(); return *this; } //! @endcond // --------------------------------------------------------------------------- /** Keep a reference to ourselves as an internal weak pointer. So that * extractGeographicBaseObject() can later return a shared pointer on itself. */ void BaseObject::assignSelf(const BaseObjectNNPtr &self) { assert(self.get() == this); d->self_ = self.as_nullable(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress BaseObjectNNPtr BaseObject::shared_from_this() const { // This assertion checks that in all code paths where we create a // shared pointer, we took care of assigning it to self_, by calling // assignSelf(); return NN_CHECK_ASSERT(d->self_.lock()); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct BoxedValue::Private { BoxedValue::Type type_{BoxedValue::Type::INTEGER}; std::string stringValue_{}; int integerValue_{}; bool booleanValue_{}; explicit Private(const std::string &stringValueIn) : type_(BoxedValue::Type::STRING), stringValue_(stringValueIn) {} explicit Private(int integerValueIn) : type_(BoxedValue::Type::INTEGER), integerValue_(integerValueIn) {} explicit Private(bool booleanValueIn) : type_(BoxedValue::Type::BOOLEAN), booleanValue_(booleanValueIn) {} }; //! @endcond // --------------------------------------------------------------------------- BoxedValue::BoxedValue() : d(internal::make_unique<Private>(std::string())) {} // --------------------------------------------------------------------------- /** \brief Constructs a BoxedValue from a string. */ BoxedValue::BoxedValue(const char *stringValueIn) : d(internal::make_unique<Private>( std::string(stringValueIn ? stringValueIn : ""))) {} // --------------------------------------------------------------------------- /** \brief Constructs a BoxedValue from a string. */ BoxedValue::BoxedValue(const std::string &stringValueIn) : d(internal::make_unique<Private>(stringValueIn)) {} // --------------------------------------------------------------------------- /** \brief Constructs a BoxedValue from an integer. */ BoxedValue::BoxedValue(int integerValueIn) : d(internal::make_unique<Private>(integerValueIn)) {} // --------------------------------------------------------------------------- /** \brief Constructs a BoxedValue from a boolean. */ BoxedValue::BoxedValue(bool booleanValueIn) : d(internal::make_unique<Private>(booleanValueIn)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress BoxedValue::BoxedValue(const BoxedValue &other) : d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- BoxedValue::~BoxedValue() = default; // --------------------------------------------------------------------------- const BoxedValue::Type &BoxedValue::type() const { return d->type_; } // --------------------------------------------------------------------------- const std::string &BoxedValue::stringValue() const { return d->stringValue_; } // --------------------------------------------------------------------------- int BoxedValue::integerValue() const { return d->integerValue_; } // --------------------------------------------------------------------------- bool BoxedValue::booleanValue() const { return d->booleanValue_; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ArrayOfBaseObject::Private { std::vector<BaseObjectNNPtr> values_{}; }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ArrayOfBaseObject::ArrayOfBaseObject() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- ArrayOfBaseObject::~ArrayOfBaseObject() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Adds an object to the array. * * @param obj the object to add. */ void ArrayOfBaseObject::add(const BaseObjectNNPtr &obj) { d->values_.emplace_back(obj); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::vector<BaseObjectNNPtr>::const_iterator ArrayOfBaseObject::begin() const { return d->values_.begin(); } // --------------------------------------------------------------------------- std::vector<BaseObjectNNPtr>::const_iterator ArrayOfBaseObject::end() const { return d->values_.end(); } // --------------------------------------------------------------------------- bool ArrayOfBaseObject::empty() const { return d->values_.empty(); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a ArrayOfBaseObject. * * @return a new ArrayOfBaseObject. */ ArrayOfBaseObjectNNPtr ArrayOfBaseObject::create() { return ArrayOfBaseObject::nn_make_shared<ArrayOfBaseObject>(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PropertyMap::Private { std::list<std::pair<std::string, BaseObjectNNPtr>> list_{}; // cppcheck-suppress functionStatic void set(const std::string &key, const BoxedValueNNPtr &val) { for (auto &pair : list_) { if (pair.first == key) { pair.second = val; return; } } list_.emplace_back(key, val); } }; //! @endcond // --------------------------------------------------------------------------- PropertyMap::PropertyMap() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PropertyMap::PropertyMap(const PropertyMap &other) : d(internal::make_unique<Private>(*(other.d))) {} //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PropertyMap::~PropertyMap() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const BaseObjectNNPtr *PropertyMap::get(const std::string &key) const { for (const auto &pair : d->list_) { if (pair.first == key) { return &(pair.second); } } return nullptr; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void PropertyMap::unset(const std::string &key) { auto &list = d->list_; for (auto iter = list.begin(); iter != list.end(); ++iter) { if (iter->first == key) { list.erase(iter); return; } } } //! @endcond // --------------------------------------------------------------------------- /** \brief Set a BaseObjectNNPtr as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, const BaseObjectNNPtr &val) { for (auto &pair : d->list_) { if (pair.first == key) { pair.second = val; return *this; } } d->list_.emplace_back(key, val); return *this; } // --------------------------------------------------------------------------- /** \brief Set a string as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, const std::string &val) { d->set(key, util::nn_make_shared<BoxedValue>(val)); return *this; } // --------------------------------------------------------------------------- /** \brief Set a string as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, const char *val) { d->set(key, util::nn_make_shared<BoxedValue>(val)); return *this; } // --------------------------------------------------------------------------- /** \brief Set a integer as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, int val) { d->set(key, util::nn_make_shared<BoxedValue>(val)); return *this; } // --------------------------------------------------------------------------- /** \brief Set a boolean as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, bool val) { d->set(key, util::nn_make_shared<BoxedValue>(val)); return *this; } // --------------------------------------------------------------------------- /** \brief Set a vector of strings as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, const std::vector<std::string> &arrayIn) { ArrayOfBaseObjectNNPtr array = ArrayOfBaseObject::create(); for (const auto &str : arrayIn) { array->add(util::nn_make_shared<BoxedValue>(str)); } return set(key, array); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool PropertyMap::getStringValue( const std::string &key, std::string &outVal) const // throw(InvalidValueTypeException) { for (const auto &pair : d->list_) { if (pair.first == key) { auto genVal = dynamic_cast<const BoxedValue *>(pair.second.get()); if (genVal && genVal->type() == BoxedValue::Type::STRING) { outVal = genVal->stringValue(); return true; } throw InvalidValueTypeException("Invalid value type for " + key); } } return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool PropertyMap::getStringValue( const std::string &key, optional<std::string> &outVal) const // throw(InvalidValueTypeException) { for (const auto &pair : d->list_) { if (pair.first == key) { auto genVal = dynamic_cast<const BoxedValue *>(pair.second.get()); if (genVal && genVal->type() == BoxedValue::Type::STRING) { outVal = genVal->stringValue(); return true; } throw InvalidValueTypeException("Invalid value type for " + key); } } return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GenericName::Private {}; //! @endcond // --------------------------------------------------------------------------- GenericName::GenericName() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- GenericName::GenericName(const GenericName &other) : d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GenericName::~GenericName() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct NameSpace::Private { GenericNamePtr name{}; bool isGlobal{}; std::string separator = std::string(":"); std::string separatorHead = std::string(":"); }; //! @endcond // --------------------------------------------------------------------------- NameSpace::NameSpace(const GenericNamePtr &nameIn) : d(internal::make_unique<Private>()) { d->name = nameIn; } // --------------------------------------------------------------------------- NameSpace::NameSpace(const NameSpace &other) : d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress NameSpace::~NameSpace() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Returns whether this is a global namespace. */ bool NameSpace::isGlobal() const { return d->isGlobal; } // --------------------------------------------------------------------------- NameSpaceNNPtr NameSpace::getGlobalFromThis() const { NameSpaceNNPtr ns(NameSpace::nn_make_shared<NameSpace>(*this)); ns->d->isGlobal = true; ns->d->name = LocalName::make_shared<LocalName>("global"); return ns; } // --------------------------------------------------------------------------- /** \brief Returns the name of this namespace. */ const GenericNamePtr &NameSpace::name() const { return d->name; } // --------------------------------------------------------------------------- const std::string &NameSpace::separator() const { return d->separator; } // --------------------------------------------------------------------------- NameSpaceNNPtr NameSpace::createGLOBAL() { NameSpaceNNPtr ns(NameSpace::nn_make_shared<NameSpace>( LocalName::make_shared<LocalName>("global"))); ns->d->isGlobal = true; return ns; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct LocalName::Private { NameSpacePtr scope{}; std::string name{}; }; //! @endcond // --------------------------------------------------------------------------- LocalName::LocalName(const std::string &name) : d(internal::make_unique<Private>()) { d->name = name; } // --------------------------------------------------------------------------- LocalName::LocalName(const NameSpacePtr &ns, const std::string &name) : d(internal::make_unique<Private>()) { d->scope = ns ? ns : static_cast<NameSpacePtr>(NameSpace::GLOBAL); d->name = name; } // --------------------------------------------------------------------------- LocalName::LocalName(const LocalName &other) : GenericName(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress LocalName::~LocalName() = default; //! @endcond // --------------------------------------------------------------------------- const NameSpacePtr LocalName::scope() const { if (d->scope) return d->scope; return NameSpace::GLOBAL; } // --------------------------------------------------------------------------- GenericNameNNPtr LocalName::toFullyQualifiedName() const { if (scope()->isGlobal()) return LocalName::nn_make_shared<LocalName>(*this); return LocalName::nn_make_shared<LocalName>( d->scope->getGlobalFromThis(), d->scope->name()->toFullyQualifiedName()->toString() + d->scope->separator() + d->name); } // --------------------------------------------------------------------------- std::string LocalName::toString() const { return d->name; } // --------------------------------------------------------------------------- /** \brief Instantiate a NameSpace. * * @param name name of the namespace. * @param properties Properties. Allowed keys are "separator" and * "separator.head". * @return a new NameFactory. */ NameSpaceNNPtr NameFactory::createNameSpace(const GenericNameNNPtr &name, const PropertyMap &properties) { NameSpaceNNPtr ns(NameSpace::nn_make_shared<NameSpace>(name)); properties.getStringValue("separator", ns->d->separator); properties.getStringValue("separator.head", ns->d->separatorHead); return ns; } // --------------------------------------------------------------------------- /** \brief Instantiate a LocalName. * * @param scope scope. * @param name string of the local name. * @return a new LocalName. */ LocalNameNNPtr NameFactory::createLocalName(const NameSpacePtr &scope, const std::string &name) { return LocalName::nn_make_shared<LocalName>(scope, name); } // --------------------------------------------------------------------------- /** \brief Instantiate a GenericName. * * @param scope scope. * @param parsedNames the components of the name. * @return a new GenericName. */ GenericNameNNPtr NameFactory::createGenericName(const NameSpacePtr &scope, const std::vector<std::string> &parsedNames) { std::string name; const std::string separator(scope ? scope->separator() : NameSpace::GLOBAL->separator()); bool first = true; for (const auto &str : parsedNames) { if (!first) name += separator; first = false; name += str; } return LocalName::nn_make_shared<LocalName>(scope, name); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CodeList::~CodeList() = default; //! @endcond // --------------------------------------------------------------------------- CodeList &CodeList::operator=(const CodeList &other) { name_ = other.name_; return *this; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Exception::Exception(const char *message) : msg_(message) {} // --------------------------------------------------------------------------- Exception::Exception(const std::string &message) : msg_(message) {} // --------------------------------------------------------------------------- Exception::Exception(const Exception &) = default; // --------------------------------------------------------------------------- Exception::~Exception() = default; //! @endcond // --------------------------------------------------------------------------- /** Return the exception text. */ const char *Exception::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress InvalidValueTypeException::InvalidValueTypeException(const char *message) : Exception(message) {} // --------------------------------------------------------------------------- InvalidValueTypeException::InvalidValueTypeException(const std::string &message) : Exception(message) {} // --------------------------------------------------------------------------- InvalidValueTypeException::~InvalidValueTypeException() = default; // --------------------------------------------------------------------------- InvalidValueTypeException::InvalidValueTypeException( const InvalidValueTypeException &) = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress UnsupportedOperationException::UnsupportedOperationException( const char *message) : Exception(message) {} // --------------------------------------------------------------------------- UnsupportedOperationException::UnsupportedOperationException( const std::string &message) : Exception(message) {} // --------------------------------------------------------------------------- UnsupportedOperationException::~UnsupportedOperationException() = default; // --------------------------------------------------------------------------- UnsupportedOperationException::UnsupportedOperationException( const UnsupportedOperationException &) = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress IComparable::~IComparable() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Returns whether an object is equivalent to another one. * @param other other object to compare to * @param criterion comparison criterion. * @param dbContext Database context, or nullptr. * @return true if objects are equivalent. */ bool IComparable::isEquivalentTo( const IComparable *other, Criterion criterion, const io::DatabaseContextPtr &dbContext) const { if (this == other) return true; return _isEquivalentTo(other, criterion, dbContext); } // --------------------------------------------------------------------------- } // namespace util NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/coordinates.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2023, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/coordinates.hpp" #include "proj/common.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj_json_streaming_writer.hpp" #include <cmath> #include <limits> using namespace NS_PROJ::internal; NS_PROJ_START namespace coordinates { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CoordinateMetadata::Private { crs::CRSNNPtr crs_; util::optional<common::DataEpoch> coordinateEpoch_{}; explicit Private(const crs::CRSNNPtr &crs) : crs_(crs) {} Private(const crs::CRSNNPtr &crs, const common::DataEpoch &coordinateEpoch) : crs_(crs), coordinateEpoch_(coordinateEpoch) {} }; //! @endcond // --------------------------------------------------------------------------- CoordinateMetadata::CoordinateMetadata(const crs::CRSNNPtr &crsIn) : d(internal::make_unique<Private>(crsIn)) {} // --------------------------------------------------------------------------- CoordinateMetadata::CoordinateMetadata(const crs::CRSNNPtr &crsIn, double coordinateEpochAsDecimalYearIn) : d(internal::make_unique<Private>( crsIn, common::DataEpoch(common::Measure(coordinateEpochAsDecimalYearIn, common::UnitOfMeasure::YEAR)))) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateMetadata::~CoordinateMetadata() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a CoordinateMetadata from a static CRS. * @param crsIn a static CRS * @return new CoordinateMetadata. * @throw util::Exception if crsIn is a dynamic CRS. */ CoordinateMetadataNNPtr CoordinateMetadata::create(const crs::CRSNNPtr &crsIn) { if (crsIn->isDynamic(/*considerWGS84AsDynamic=*/false)) { throw util::Exception( "Coordinate epoch should be provided for a dynamic CRS"); } auto coordinateMetadata( CoordinateMetadata::nn_make_shared<CoordinateMetadata>(crsIn)); coordinateMetadata->assignSelf(coordinateMetadata); return coordinateMetadata; } // --------------------------------------------------------------------------- /** \brief Instantiate a CoordinateMetadata from a dynamic CRS and an associated * coordinate epoch. * * @param crsIn a dynamic CRS * @param coordinateEpochIn coordinate epoch expressed in decimal year. * @return new CoordinateMetadata. * @throw util::Exception if crsIn is a static CRS. */ CoordinateMetadataNNPtr CoordinateMetadata::create(const crs::CRSNNPtr &crsIn, double coordinateEpochIn) { return create(crsIn, coordinateEpochIn, nullptr); } // --------------------------------------------------------------------------- /** \brief Instantiate a CoordinateMetadata from a dynamic CRS and an associated * coordinate epoch. * * @param crsIn a dynamic CRS * @param coordinateEpochIn coordinate epoch expressed in decimal year. * @param dbContext Database context (may be null) * @return new CoordinateMetadata. * @throw util::Exception if crsIn is a static CRS. */ CoordinateMetadataNNPtr CoordinateMetadata::create(const crs::CRSNNPtr &crsIn, double coordinateEpochIn, const io::DatabaseContextPtr &dbContext) { if (!crsIn->isDynamic(/*considerWGS84AsDynamic=*/true)) { bool ok = false; if (dbContext) { auto geodCrs = crsIn->extractGeodeticCRS(); if (geodCrs) { auto factory = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), std::string()); ok = !factory ->getPointMotionOperationsFor(NN_NO_CHECK(geodCrs), false) .empty(); } } if (!ok) { throw util::Exception( "Coordinate epoch should not be provided for a static CRS"); } } auto coordinateMetadata( CoordinateMetadata::nn_make_shared<CoordinateMetadata>( crsIn, coordinateEpochIn)); coordinateMetadata->assignSelf(coordinateMetadata); return coordinateMetadata; } // --------------------------------------------------------------------------- /** \brief Get the CRS associated with this CoordinateMetadata object. */ const crs::CRSNNPtr &CoordinateMetadata::crs() PROJ_PURE_DEFN { return d->crs_; } // --------------------------------------------------------------------------- /** \brief Get the coordinate epoch associated with this CoordinateMetadata * object. * * The coordinate epoch is mandatory for a dynamic CRS, * and forbidden for a static CRS. */ const util::optional<common::DataEpoch> & CoordinateMetadata::coordinateEpoch() PROJ_PURE_DEFN { return d->coordinateEpoch_; } // --------------------------------------------------------------------------- /** \brief Get the coordinate epoch associated with this CoordinateMetadata * object, as decimal year. * * The coordinate epoch is mandatory for a dynamic CRS, * and forbidden for a static CRS. */ double CoordinateMetadata::coordinateEpochAsDecimalYear() PROJ_PURE_DEFN { if (d->coordinateEpoch_.has_value()) { return getRoundedEpochInDecimalYear( d->coordinateEpoch_->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)); } return std::numeric_limits<double>::quiet_NaN(); } // --------------------------------------------------------------------------- /** \brief Return a variant of this CoordinateMetadata "promoted" to a 3D one, * if not already the case. * * @param newName Name of the new underlying CRS. If empty, nameStr() will be * used. * @param dbContext Database context to look for potentially already registered * 3D CRS. May be nullptr. * @return a new CoordinateMetadata object promoted to 3D, or the current one if * already 3D or not applicable. */ CoordinateMetadataNNPtr CoordinateMetadata::promoteTo3D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const { auto crs = d->crs_->promoteTo3D(newName, dbContext); auto coordinateMetadata( d->coordinateEpoch_.has_value() ? CoordinateMetadata::nn_make_shared<CoordinateMetadata>( crs, coordinateEpochAsDecimalYear()) : CoordinateMetadata::nn_make_shared<CoordinateMetadata>(crs)); coordinateMetadata->assignSelf(coordinateMetadata); return coordinateMetadata; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateMetadata::_exportToWKT(io::WKTFormatter *formatter) const { if (formatter->version() != io::WKTFormatter::Version::WKT2 || !formatter->use2019Keywords()) { io::FormattingException::Throw( "CoordinateMetadata can only be exported since WKT2:2019"); } formatter->startNode(io::WKTConstants::COORDINATEMETADATA, false); crs()->_exportToWKT(formatter); if (d->coordinateEpoch_.has_value()) { formatter->startNode(io::WKTConstants::EPOCH, false); formatter->add(coordinateEpochAsDecimalYear()); formatter->endNode(); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateMetadata::_exportToJSON( io::JSONFormatter *formatter) const // throw(io::FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("CoordinateMetadata", false)); writer->AddObjKey("crs"); crs()->_exportToJSON(formatter); if (d->coordinateEpoch_.has_value()) { writer->AddObjKey("coordinateEpoch"); writer->Add(coordinateEpochAsDecimalYear()); } } //! @endcond } // namespace coordinates NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/internal.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/internal/internal.hpp" #include <cmath> #include <cstdint> #include <cstring> #ifdef _MSC_VER #include <string.h> #else #include <strings.h> #endif #include <exception> #include <iomanip> // std::setprecision #include <locale> #include <sstream> // std::istringstream and std::ostringstream #include <string> #include "sqlite3.h" NS_PROJ_START namespace internal { // --------------------------------------------------------------------------- /** * Replace all occurrences of before with after. */ std::string replaceAll(const std::string &str, const std::string &before, const std::string &after) { std::string ret(str); const size_t nBeforeSize = before.size(); const size_t nAfterSize = after.size(); if (nBeforeSize) { size_t nStartPos = 0; while ((nStartPos = ret.find(before, nStartPos)) != std::string::npos) { ret.replace(nStartPos, nBeforeSize, after); nStartPos += nAfterSize; } } return ret; } // --------------------------------------------------------------------------- inline static bool EQUALN(const char *a, const char *b, size_t size) { #ifdef _MSC_VER return _strnicmp(a, b, size) == 0; #else return strncasecmp(a, b, size) == 0; #endif } /** * Case-insensitive equality test */ bool ci_equal(const std::string &a, const std::string &b) noexcept { const auto size = a.size(); if (size != b.size()) { return false; } return EQUALN(a.c_str(), b.c_str(), size); } bool ci_equal(const std::string &a, const char *b) noexcept { const auto size = a.size(); if (size != strlen(b)) { return false; } return EQUALN(a.c_str(), b, size); } bool ci_equal(const char *a, const char *b) noexcept { const auto size = strlen(a); if (size != strlen(b)) { return false; } return EQUALN(a, b, size); } // --------------------------------------------------------------------------- bool ci_less(const std::string &a, const std::string &b) noexcept { #ifdef _MSC_VER return _stricmp(a.c_str(), b.c_str()) < 0; #else return strcasecmp(a.c_str(), b.c_str()) < 0; #endif } // --------------------------------------------------------------------------- /** * Convert to lower case. */ std::string tolower(const std::string &str) { std::string ret(str); for (size_t i = 0; i < ret.size(); i++) ret[i] = static_cast<char>(::tolower(ret[i])); return ret; } // --------------------------------------------------------------------------- /** * Convert to upper case. */ std::string toupper(const std::string &str) { std::string ret(str); for (size_t i = 0; i < ret.size(); i++) ret[i] = static_cast<char>(::toupper(ret[i])); return ret; } // --------------------------------------------------------------------------- /** Strip leading and trailing double quote characters */ std::string stripQuotes(const std::string &str) { if (str.size() >= 2 && str[0] == '"' && str.back() == '"') { return str.substr(1, str.size() - 2); } return str; } // --------------------------------------------------------------------------- size_t ci_find(const std::string &str, const char *needle) noexcept { const size_t needleSize = strlen(needle); for (size_t i = 0; i + needleSize <= str.size(); i++) { if (EQUALN(str.c_str() + i, needle, needleSize)) { return i; } } return std::string::npos; } // --------------------------------------------------------------------------- size_t ci_find(const std::string &str, const std::string &needle, size_t startPos) noexcept { const size_t needleSize = needle.size(); for (size_t i = startPos; i + needleSize <= str.size(); i++) { if (EQUALN(str.c_str() + i, needle.c_str(), needleSize)) { return i; } } return std::string::npos; } // --------------------------------------------------------------------------- /* bool starts_with(const std::string &str, const std::string &prefix) noexcept { if (str.size() < prefix.size()) { return false; } return std::memcmp(str.c_str(), prefix.c_str(), prefix.size()) == 0; } */ // --------------------------------------------------------------------------- /* bool starts_with(const std::string &str, const char *prefix) noexcept { const size_t prefixSize = std::strlen(prefix); if (str.size() < prefixSize) { return false; } return std::memcmp(str.c_str(), prefix, prefixSize) == 0; } */ // --------------------------------------------------------------------------- bool ci_starts_with(const char *str, const char *prefix) noexcept { const auto str_size = strlen(str); const auto prefix_size = strlen(prefix); if (str_size < prefix_size) { return false; } return EQUALN(str, prefix, prefix_size); } // --------------------------------------------------------------------------- bool ci_starts_with(const std::string &str, const std::string &prefix) noexcept { if (str.size() < prefix.size()) { return false; } return EQUALN(str.c_str(), prefix.c_str(), prefix.size()); } // --------------------------------------------------------------------------- bool ends_with(const std::string &str, const std::string &suffix) noexcept { if (str.size() < suffix.size()) { return false; } return std::memcmp(str.c_str() + str.size() - suffix.size(), suffix.c_str(), suffix.size()) == 0; } // --------------------------------------------------------------------------- double c_locale_stod(const std::string &s) { bool success; double val = c_locale_stod(s, success); if (!success) { throw std::invalid_argument("non double value"); } return val; } double c_locale_stod(const std::string &s, bool &success) { success = true; const auto s_size = s.size(); // Fast path if (s_size > 0 && s_size < 15) { std::int64_t acc = 0; std::int64_t div = 1; bool afterDot = false; size_t i = 0; if (s[0] == '-') { ++i; div = -1; } else if (s[0] == '+') { ++i; } for (; i < s_size; ++i) { const auto ch = s[i]; if (ch >= '0' && ch <= '9') { acc = acc * 10 + ch - '0'; if (afterDot) { div *= 10; } } else if (ch == '.') { afterDot = true; } else { div = 0; } } if (div) { return static_cast<double>(acc) / div; } } std::istringstream iss(s); iss.imbue(std::locale::classic()); double d; iss >> d; if (!iss.eof() || iss.fail()) { success = false; d = 0; } return d; } // --------------------------------------------------------------------------- std::vector<std::string> split(const std::string &str, char separator) { std::vector<std::string> res; size_t lastPos = 0; size_t newPos = 0; while ((newPos = str.find(separator, lastPos)) != std::string::npos) { res.push_back(str.substr(lastPos, newPos - lastPos)); lastPos = newPos + 1; } res.push_back(str.substr(lastPos)); return res; } // --------------------------------------------------------------------------- std::vector<std::string> split(const std::string &str, const std::string &separator) { std::vector<std::string> res; size_t lastPos = 0; size_t newPos = 0; while ((newPos = str.find(separator, lastPos)) != std::string::npos) { res.push_back(str.substr(lastPos, newPos - lastPos)); lastPos = newPos + separator.size(); } res.push_back(str.substr(lastPos)); return res; } // --------------------------------------------------------------------------- #ifdef _WIN32 // For some reason, sqlite3_snprintf() in the sqlite3 builds used on AppVeyor // doesn't round identically to the Unix builds, and thus breaks a number of // unit test. So to avoid this, use the stdlib formatting std::string toString(int val) { std::ostringstream buffer; buffer.imbue(std::locale::classic()); buffer << val; return buffer.str(); } std::string toString(double val, int precision) { std::ostringstream buffer; buffer.imbue(std::locale::classic()); buffer << std::setprecision(precision); buffer << val; auto str = buffer.str(); if (precision == 15 && str.find("9999999999") != std::string::npos) { buffer.str(""); buffer.clear(); buffer << std::setprecision(14); buffer << val; return buffer.str(); } return str; } #else std::string toString(int val) { // use sqlite3 API that is slightly faster than std::ostringstream // with forcing the C locale. sqlite3_snprintf() emulates a C locale. constexpr int BUF_SIZE = 16; char szBuffer[BUF_SIZE]; sqlite3_snprintf(BUF_SIZE, szBuffer, "%d", val); return szBuffer; } std::string toString(double val, int precision) { // use sqlite3 API that is slightly faster than std::ostringstream // with forcing the C locale. sqlite3_snprintf() emulates a C locale. constexpr int BUF_SIZE = 32; char szBuffer[BUF_SIZE]; sqlite3_snprintf(BUF_SIZE, szBuffer, "%.*g", precision, val); if (precision == 15 && strstr(szBuffer, "9999999999")) { sqlite3_snprintf(BUF_SIZE, szBuffer, "%.14g", val); } return szBuffer; } #endif // --------------------------------------------------------------------------- std::string concat(const char *a, const std::string &b) { std::string res(a); res += b; return res; } std::string concat(const char *a, const std::string &b, const char *c) { std::string res(a); res += b; res += c; return res; } // --------------------------------------------------------------------------- // Avoid rounding issues due to year -> second (SI unit) -> year roundtrips double getRoundedEpochInDecimalYear(double year) { // Try to see if the value is close to xxxx.yyy decimal year. if (std::fabs(1000 * year - std::round(1000 * year)) <= 1e-3) { year = std::round(1000 * year) / 1000.0; } return year; } // --------------------------------------------------------------------------- } // namespace internal NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/io.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include <algorithm> #include <cassert> #include <cctype> #include <cmath> #include <cstring> #include <limits> #include <list> #include <locale> #include <map> #include <set> #include <sstream> // std::istringstream #include <string> #include <utility> #include <vector> #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinates.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "operation/coordinateoperation_internal.hpp" #include "operation/esriparammappings.hpp" #include "operation/oputils.hpp" #include "operation/parammappings.hpp" #include "proj/internal/coordinatesystem_internal.hpp" #include "proj/internal/datum_internal.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj/internal/include_nlohmann_json.hpp" #include "proj_constants.h" #include "proj_json_streaming_writer.hpp" #include "wkt1_parser.h" #include "wkt2_parser.h" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // clang-format on using namespace NS_PROJ::common; using namespace NS_PROJ::coordinates; using namespace NS_PROJ::crs; using namespace NS_PROJ::cs; using namespace NS_PROJ::datum; using namespace NS_PROJ::internal; using namespace NS_PROJ::metadata; using namespace NS_PROJ::operation; using namespace NS_PROJ::util; using json = nlohmann::json; //! @cond Doxygen_Suppress static const std::string emptyString{}; //! @endcond #if 0 namespace dropbox{ namespace oxygen { template<> nn<NS_PROJ::io::DatabaseContextPtr>::~nn() = default; template<> nn<NS_PROJ::io::AuthorityFactoryPtr>::~nn() = default; template<> nn<std::shared_ptr<NS_PROJ::io::IPROJStringExportable>>::~nn() = default; template<> nn<std::unique_ptr<NS_PROJ::io::PROJStringFormatter, std::default_delete<NS_PROJ::io::PROJStringFormatter> > >::~nn() = default; template<> nn<std::unique_ptr<NS_PROJ::io::WKTFormatter, std::default_delete<NS_PROJ::io::WKTFormatter> > >::~nn() = default; template<> nn<std::unique_ptr<NS_PROJ::io::WKTNode, std::default_delete<NS_PROJ::io::WKTNode> > >::~nn() = default; }} #endif NS_PROJ_START namespace io { //! @cond Doxygen_Suppress const char *JSONFormatter::PROJJSON_v0_7 = "https://proj.org/schemas/v0.7/projjson.schema.json"; #define PROJJSON_DEFAULT_VERSION JSONFormatter::PROJJSON_v0_7 //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress IWKTExportable::~IWKTExportable() = default; // --------------------------------------------------------------------------- std::string IWKTExportable::exportToWKT(WKTFormatter *formatter) const { _exportToWKT(formatter); return formatter->toString(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct WKTFormatter::Private { struct Params { WKTFormatter::Convention convention_ = WKTFormatter::Convention::WKT2; WKTFormatter::Version version_ = WKTFormatter::Version::WKT2; bool multiLine_ = true; bool strict_ = true; int indentWidth_ = 4; bool idOnTopLevelOnly_ = false; bool outputAxisOrder_ = false; bool primeMeridianOmittedIfGreenwich_ = false; bool ellipsoidUnitOmittedIfMetre_ = false; bool primeMeridianOrParameterUnitOmittedIfSameAsAxis_ = false; bool forceUNITKeyword_ = false; bool outputCSUnitOnlyOnceIfSame_ = false; bool primeMeridianInDegree_ = false; bool use2019Keywords_ = false; bool useESRIDialect_ = false; bool allowEllipsoidalHeightAsVerticalCRS_ = false; bool allowLINUNITNode_ = false; OutputAxisRule outputAxis_ = WKTFormatter::OutputAxisRule::YES; }; Params params_{}; DatabaseContextPtr dbContext_{}; int indentLevel_ = 0; int level_ = 0; std::vector<bool> stackHasChild_{}; std::vector<bool> stackHasId_{false}; std::vector<bool> stackEmptyKeyword_{}; std::vector<bool> stackDisableUsage_{}; std::vector<bool> outputUnitStack_{true}; std::vector<bool> outputIdStack_{true}; std::vector<UnitOfMeasureNNPtr> axisLinearUnitStack_{ util::nn_make_shared<UnitOfMeasure>(UnitOfMeasure::METRE)}; std::vector<UnitOfMeasureNNPtr> axisAngularUnitStack_{ util::nn_make_shared<UnitOfMeasure>(UnitOfMeasure::DEGREE)}; bool abridgedTransformation_ = false; bool useDerivingConversion_ = false; std::vector<double> toWGS84Parameters_{}; std::string hDatumExtension_{}; std::string vDatumExtension_{}; crs::GeographicCRSPtr geogCRSOfCompoundCRS_{}; std::string result_{}; // cppcheck-suppress functionStatic void addNewLine(); void addIndentation(); // cppcheck-suppress functionStatic void startNewChild(); }; //! @endcond // --------------------------------------------------------------------------- /** \brief Constructs a new formatter. * * A formatter can be used only once (its internal state is mutated) * * Its default behavior can be adjusted with the different setters. * * @param convention WKT flavor. Defaults to Convention::WKT2 * @param dbContext Database context, to allow queries in it if needed. * This is used for example for WKT1_ESRI output to do name substitutions. * * @return new formatter. */ WKTFormatterNNPtr WKTFormatter::create(Convention convention, // cppcheck-suppress passedByValue DatabaseContextPtr dbContext) { auto ret = NN_NO_CHECK(WKTFormatter::make_unique<WKTFormatter>(convention)); ret->d->dbContext_ = std::move(dbContext); return ret; } // --------------------------------------------------------------------------- /** \brief Constructs a new formatter from another one. * * A formatter can be used only once (its internal state is mutated) * * Its default behavior can be adjusted with the different setters. * * @param other source formatter. * @return new formatter. */ WKTFormatterNNPtr WKTFormatter::create(const WKTFormatterNNPtr &other) { auto f = create(other->d->params_.convention_, other->d->dbContext_); f->d->params_ = other->d->params_; return f; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress WKTFormatter::~WKTFormatter() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Whether to use multi line output or not. */ WKTFormatter &WKTFormatter::setMultiLine(bool multiLine) noexcept { d->params_.multiLine_ = multiLine; return *this; } // --------------------------------------------------------------------------- /** \brief Set number of spaces for each indentation level (defaults to 4). */ WKTFormatter &WKTFormatter::setIndentationWidth(int width) noexcept { d->params_.indentWidth_ = width; return *this; } // --------------------------------------------------------------------------- /** \brief Set whether AXIS nodes should be output. */ WKTFormatter & WKTFormatter::setOutputAxis(OutputAxisRule outputAxisIn) noexcept { d->params_.outputAxis_ = outputAxisIn; return *this; } // --------------------------------------------------------------------------- /** \brief Set whether the formatter should operate on strict more or not. * * The default is strict mode, in which case a FormattingException can be * thrown. * In non-strict mode, a Geographic 3D CRS can be for example exported as * WKT1_GDAL with 3 axes, whereas this is normally not allowed. */ WKTFormatter &WKTFormatter::setStrict(bool strictIn) noexcept { d->params_.strict_ = strictIn; return *this; } // --------------------------------------------------------------------------- /** \brief Returns whether the formatter is in strict mode. */ bool WKTFormatter::isStrict() const noexcept { return d->params_.strict_; } // --------------------------------------------------------------------------- /** \brief Set whether the formatter should export, in WKT1, a Geographic or * Projected 3D CRS as a compound CRS whose vertical part represents an * ellipsoidal height. */ WKTFormatter & WKTFormatter::setAllowEllipsoidalHeightAsVerticalCRS(bool allow) noexcept { d->params_.allowEllipsoidalHeightAsVerticalCRS_ = allow; return *this; } // --------------------------------------------------------------------------- /** \brief Return whether the formatter should export, in WKT1, a Geographic or * Projected 3D CRS as a compound CRS whose vertical part represents an * ellipsoidal height. */ bool WKTFormatter::isAllowedEllipsoidalHeightAsVerticalCRS() const noexcept { return d->params_.allowEllipsoidalHeightAsVerticalCRS_; } // --------------------------------------------------------------------------- /** \brief Set whether the formatter should export, in WKT1_ESRI, a Geographic * 3D CRS with the relatively new (ArcGIS Pro >= 2.7) LINUNIT node. * Defaults to true. * @since PROJ 9.1 */ WKTFormatter &WKTFormatter::setAllowLINUNITNode(bool allow) noexcept { d->params_.allowLINUNITNode_ = allow; return *this; } // --------------------------------------------------------------------------- /** \brief Return whether the formatter should export, in WKT1_ESRI, a * Geographic 3D CRS with the relatively new (ArcGIS Pro >= 2.7) LINUNIT node. * Defaults to true. * @since PROJ 9.1 */ bool WKTFormatter::isAllowedLINUNITNode() const noexcept { return d->params_.allowLINUNITNode_; } // --------------------------------------------------------------------------- /** Returns the WKT string from the formatter. */ const std::string &WKTFormatter::toString() const { if (d->indentLevel_ > 0 || d->level_ > 0) { // For intermediary nodes, the formatter is in a inconsistent // state. throw FormattingException("toString() called on intermediate nodes"); } if (d->axisLinearUnitStack_.size() != 1) throw FormattingException( "Unbalanced pushAxisLinearUnit() / popAxisLinearUnit()"); if (d->axisAngularUnitStack_.size() != 1) throw FormattingException( "Unbalanced pushAxisAngularUnit() / popAxisAngularUnit()"); if (d->outputIdStack_.size() != 1) throw FormattingException("Unbalanced pushOutputId() / popOutputId()"); if (d->outputUnitStack_.size() != 1) throw FormattingException( "Unbalanced pushOutputUnit() / popOutputUnit()"); if (d->stackHasId_.size() != 1) throw FormattingException("Unbalanced pushHasId() / popHasId()"); if (!d->stackDisableUsage_.empty()) throw FormattingException( "Unbalanced pushDisableUsage() / popDisableUsage()"); return d->result_; } //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- WKTFormatter::WKTFormatter(Convention convention) : d(internal::make_unique<Private>()) { d->params_.convention_ = convention; switch (convention) { case Convention::WKT2_2019: d->params_.use2019Keywords_ = true; PROJ_FALLTHROUGH; case Convention::WKT2: d->params_.version_ = WKTFormatter::Version::WKT2; d->params_.outputAxisOrder_ = true; break; case Convention::WKT2_2019_SIMPLIFIED: d->params_.use2019Keywords_ = true; PROJ_FALLTHROUGH; case Convention::WKT2_SIMPLIFIED: d->params_.version_ = WKTFormatter::Version::WKT2; d->params_.idOnTopLevelOnly_ = true; d->params_.outputAxisOrder_ = false; d->params_.primeMeridianOmittedIfGreenwich_ = true; d->params_.ellipsoidUnitOmittedIfMetre_ = true; d->params_.primeMeridianOrParameterUnitOmittedIfSameAsAxis_ = true; d->params_.forceUNITKeyword_ = true; d->params_.outputCSUnitOnlyOnceIfSame_ = true; break; case Convention::WKT1_GDAL: d->params_.version_ = WKTFormatter::Version::WKT1; d->params_.outputAxisOrder_ = false; d->params_.forceUNITKeyword_ = true; d->params_.primeMeridianInDegree_ = true; d->params_.outputAxis_ = WKTFormatter::OutputAxisRule::WKT1_GDAL_EPSG_STYLE; break; case Convention::WKT1_ESRI: d->params_.version_ = WKTFormatter::Version::WKT1; d->params_.outputAxisOrder_ = false; d->params_.forceUNITKeyword_ = true; d->params_.primeMeridianInDegree_ = true; d->params_.useESRIDialect_ = true; d->params_.multiLine_ = false; d->params_.outputAxis_ = WKTFormatter::OutputAxisRule::NO; d->params_.allowLINUNITNode_ = true; break; default: assert(false); break; } } // --------------------------------------------------------------------------- WKTFormatter &WKTFormatter::setOutputId(bool outputIdIn) { if (d->indentLevel_ != 0) { throw Exception( "setOutputId() shall only be called when the stack state is empty"); } d->outputIdStack_[0] = outputIdIn; return *this; } // --------------------------------------------------------------------------- void WKTFormatter::Private::addNewLine() { result_ += '\n'; } // --------------------------------------------------------------------------- void WKTFormatter::Private::addIndentation() { result_ += std::string( static_cast<size_t>(indentLevel_) * params_.indentWidth_, ' '); } // --------------------------------------------------------------------------- void WKTFormatter::enter() { if (d->indentLevel_ == 0 && d->level_ == 0) { d->stackHasChild_.push_back(false); } ++d->level_; } // --------------------------------------------------------------------------- void WKTFormatter::leave() { assert(d->level_ > 0); --d->level_; if (d->indentLevel_ == 0 && d->level_ == 0) { d->stackHasChild_.pop_back(); } } // --------------------------------------------------------------------------- bool WKTFormatter::isAtTopLevel() const { return d->level_ == 0 && d->indentLevel_ == 0; } // --------------------------------------------------------------------------- void WKTFormatter::startNode(const std::string &keyword, bool hasId) { if (!d->stackHasChild_.empty()) { d->startNewChild(); } else if (!d->result_.empty()) { d->result_ += ','; if (d->params_.multiLine_ && !keyword.empty()) { d->addNewLine(); } } if (d->params_.multiLine_) { if ((d->indentLevel_ || d->level_) && !keyword.empty()) { if (!d->result_.empty()) { d->addNewLine(); } d->addIndentation(); } } if (!keyword.empty()) { d->result_ += keyword; d->result_ += '['; } d->indentLevel_++; d->stackHasChild_.push_back(false); d->stackEmptyKeyword_.push_back(keyword.empty()); // Starting from a node that has a ID, we should emit ID nodes for : // - this node // - and for METHOD&PARAMETER nodes in WKT2, unless idOnTopLevelOnly_ is // set. // For WKT2, all other intermediate nodes shouldn't have ID ("not // recommended") if (!d->params_.idOnTopLevelOnly_ && d->indentLevel_ >= 2 && d->params_.version_ == WKTFormatter::Version::WKT2 && (keyword == WKTConstants::METHOD || keyword == WKTConstants::PARAMETER)) { pushOutputId(d->outputIdStack_[0]); } else if (d->indentLevel_ >= 2 && d->params_.version_ == WKTFormatter::Version::WKT2) { pushOutputId(d->outputIdStack_[0] && !d->stackHasId_.back()); } else { pushOutputId(outputId()); } d->stackHasId_.push_back(hasId || d->stackHasId_.back()); } // --------------------------------------------------------------------------- void WKTFormatter::endNode() { assert(d->indentLevel_ > 0); d->stackHasId_.pop_back(); popOutputId(); d->indentLevel_--; bool emptyKeyword = d->stackEmptyKeyword_.back(); d->stackEmptyKeyword_.pop_back(); d->stackHasChild_.pop_back(); if (!emptyKeyword) d->result_ += ']'; } // --------------------------------------------------------------------------- WKTFormatter &WKTFormatter::simulCurNodeHasId() { d->stackHasId_.back() = true; return *this; } // --------------------------------------------------------------------------- void WKTFormatter::Private::startNewChild() { assert(!stackHasChild_.empty()); if (stackHasChild_.back()) { result_ += ','; } stackHasChild_.back() = true; } // --------------------------------------------------------------------------- void WKTFormatter::addQuotedString(const char *str) { addQuotedString(std::string(str)); } void WKTFormatter::addQuotedString(const std::string &str) { d->startNewChild(); d->result_ += '"'; d->result_ += replaceAll(str, "\"", "\"\""); d->result_ += '"'; } // --------------------------------------------------------------------------- void WKTFormatter::add(const std::string &str) { d->startNewChild(); d->result_ += str; } // --------------------------------------------------------------------------- void WKTFormatter::add(int number) { d->startNewChild(); d->result_ += internal::toString(number); } // --------------------------------------------------------------------------- #ifdef __MINGW32__ static std::string normalizeExponent(const std::string &in) { // mingw will output 1e-0xy instead of 1e-xy. Fix that auto pos = in.find("e-0"); if (pos == std::string::npos) { return in; } if (pos + 4 < in.size() && isdigit(in[pos + 3]) && isdigit(in[pos + 4])) { return in.substr(0, pos + 2) + in.substr(pos + 3); } return in; } #else static inline std::string normalizeExponent(const std::string &in) { return in; } #endif static inline std::string normalizeSerializedString(const std::string &in) { auto ret(normalizeExponent(in)); return ret; } // --------------------------------------------------------------------------- void WKTFormatter::add(double number, int precision) { d->startNewChild(); if (number == 0.0) { if (d->params_.useESRIDialect_) { d->result_ += "0.0"; } else { d->result_ += '0'; } } else { std::string val( normalizeSerializedString(internal::toString(number, precision))); d->result_ += replaceAll(val, "e", "E"); if (d->params_.useESRIDialect_ && val.find('.') == std::string::npos) { d->result_ += ".0"; } } } // --------------------------------------------------------------------------- void WKTFormatter::pushOutputUnit(bool outputUnitIn) { d->outputUnitStack_.push_back(outputUnitIn); } // --------------------------------------------------------------------------- void WKTFormatter::popOutputUnit() { d->outputUnitStack_.pop_back(); } // --------------------------------------------------------------------------- bool WKTFormatter::outputUnit() const { return d->outputUnitStack_.back(); } // --------------------------------------------------------------------------- void WKTFormatter::pushOutputId(bool outputIdIn) { d->outputIdStack_.push_back(outputIdIn); } // --------------------------------------------------------------------------- void WKTFormatter::popOutputId() { d->outputIdStack_.pop_back(); } // --------------------------------------------------------------------------- bool WKTFormatter::outputId() const { return !d->params_.useESRIDialect_ && d->outputIdStack_.back(); } // --------------------------------------------------------------------------- void WKTFormatter::pushHasId(bool hasId) { d->stackHasId_.push_back(hasId); } // --------------------------------------------------------------------------- void WKTFormatter::popHasId() { d->stackHasId_.pop_back(); } // --------------------------------------------------------------------------- void WKTFormatter::pushDisableUsage() { d->stackDisableUsage_.push_back(true); } // --------------------------------------------------------------------------- void WKTFormatter::popDisableUsage() { d->stackDisableUsage_.pop_back(); } // --------------------------------------------------------------------------- bool WKTFormatter::outputUsage() const { return outputId() && d->stackDisableUsage_.empty(); } // --------------------------------------------------------------------------- void WKTFormatter::pushAxisLinearUnit(const UnitOfMeasureNNPtr &unit) { d->axisLinearUnitStack_.push_back(unit); } // --------------------------------------------------------------------------- void WKTFormatter::popAxisLinearUnit() { d->axisLinearUnitStack_.pop_back(); } // --------------------------------------------------------------------------- const UnitOfMeasureNNPtr &WKTFormatter::axisLinearUnit() const { return d->axisLinearUnitStack_.back(); } // --------------------------------------------------------------------------- void WKTFormatter::pushAxisAngularUnit(const UnitOfMeasureNNPtr &unit) { d->axisAngularUnitStack_.push_back(unit); } // --------------------------------------------------------------------------- void WKTFormatter::popAxisAngularUnit() { d->axisAngularUnitStack_.pop_back(); } // --------------------------------------------------------------------------- const UnitOfMeasureNNPtr &WKTFormatter::axisAngularUnit() const { return d->axisAngularUnitStack_.back(); } // --------------------------------------------------------------------------- WKTFormatter::OutputAxisRule WKTFormatter::outputAxis() const { return d->params_.outputAxis_; } // --------------------------------------------------------------------------- bool WKTFormatter::outputAxisOrder() const { return d->params_.outputAxisOrder_; } // --------------------------------------------------------------------------- bool WKTFormatter::primeMeridianOmittedIfGreenwich() const { return d->params_.primeMeridianOmittedIfGreenwich_; } // --------------------------------------------------------------------------- bool WKTFormatter::ellipsoidUnitOmittedIfMetre() const { return d->params_.ellipsoidUnitOmittedIfMetre_; } // --------------------------------------------------------------------------- bool WKTFormatter::primeMeridianOrParameterUnitOmittedIfSameAsAxis() const { return d->params_.primeMeridianOrParameterUnitOmittedIfSameAsAxis_; } // --------------------------------------------------------------------------- bool WKTFormatter::outputCSUnitOnlyOnceIfSame() const { return d->params_.outputCSUnitOnlyOnceIfSame_; } // --------------------------------------------------------------------------- bool WKTFormatter::forceUNITKeyword() const { return d->params_.forceUNITKeyword_; } // --------------------------------------------------------------------------- bool WKTFormatter::primeMeridianInDegree() const { return d->params_.primeMeridianInDegree_; } // --------------------------------------------------------------------------- bool WKTFormatter::idOnTopLevelOnly() const { return d->params_.idOnTopLevelOnly_; } // --------------------------------------------------------------------------- bool WKTFormatter::topLevelHasId() const { return d->stackHasId_.size() >= 2 && d->stackHasId_[1]; } // --------------------------------------------------------------------------- WKTFormatter::Version WKTFormatter::version() const { return d->params_.version_; } // --------------------------------------------------------------------------- bool WKTFormatter::use2019Keywords() const { return d->params_.use2019Keywords_; } // --------------------------------------------------------------------------- bool WKTFormatter::useESRIDialect() const { return d->params_.useESRIDialect_; } // --------------------------------------------------------------------------- const DatabaseContextPtr &WKTFormatter::databaseContext() const { return d->dbContext_; } // --------------------------------------------------------------------------- void WKTFormatter::setAbridgedTransformation(bool outputIn) { d->abridgedTransformation_ = outputIn; } // --------------------------------------------------------------------------- bool WKTFormatter::abridgedTransformation() const { return d->abridgedTransformation_; } // --------------------------------------------------------------------------- void WKTFormatter::setUseDerivingConversion(bool useDerivingConversionIn) { d->useDerivingConversion_ = useDerivingConversionIn; } // --------------------------------------------------------------------------- bool WKTFormatter::useDerivingConversion() const { return d->useDerivingConversion_; } // --------------------------------------------------------------------------- void WKTFormatter::setTOWGS84Parameters(const std::vector<double> &params) { d->toWGS84Parameters_ = params; } // --------------------------------------------------------------------------- const std::vector<double> &WKTFormatter::getTOWGS84Parameters() const { return d->toWGS84Parameters_; } // --------------------------------------------------------------------------- void WKTFormatter::setVDatumExtension(const std::string &filename) { d->vDatumExtension_ = filename; } // --------------------------------------------------------------------------- const std::string &WKTFormatter::getVDatumExtension() const { return d->vDatumExtension_; } // --------------------------------------------------------------------------- void WKTFormatter::setHDatumExtension(const std::string &filename) { d->hDatumExtension_ = filename; } // --------------------------------------------------------------------------- const std::string &WKTFormatter::getHDatumExtension() const { return d->hDatumExtension_; } // --------------------------------------------------------------------------- void WKTFormatter::setGeogCRSOfCompoundCRS(const crs::GeographicCRSPtr &crs) { d->geogCRSOfCompoundCRS_ = crs; } // --------------------------------------------------------------------------- const crs::GeographicCRSPtr &WKTFormatter::getGeogCRSOfCompoundCRS() const { return d->geogCRSOfCompoundCRS_; } // --------------------------------------------------------------------------- std::string WKTFormatter::morphNameToESRI(const std::string &name) { for (const auto *suffix : {"(m)", "(ftUS)", "(E-N)", "(N-E)"}) { if (ends_with(name, suffix)) { return morphNameToESRI( name.substr(0, name.size() - strlen(suffix))) + suffix; } } std::string ret; bool insertUnderscore = false; // Replace any special character by underscore, except at the beginning // and of the name where those characters are removed. for (char ch : name) { if (ch == '+' || ch == '-' || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { if (insertUnderscore && !ret.empty()) { ret += '_'; } ret += ch; insertUnderscore = false; } else { insertUnderscore = true; } } return ret; } // --------------------------------------------------------------------------- void WKTFormatter::ingestWKTNode(const WKTNodeNNPtr &node) { startNode(node->value(), true); for (const auto &child : node->children()) { if (!child->children().empty()) { ingestWKTNode(child); } else { add(child->value()); } } endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static WKTNodeNNPtr null_node(NN_NO_CHECK(internal::make_unique<WKTNode>(std::string()))); static inline bool isNull(const WKTNodeNNPtr &node) { return &node == &null_node; } struct WKTNode::Private { std::string value_{}; std::vector<WKTNodeNNPtr> children_{}; explicit Private(const std::string &valueIn) : value_(valueIn) {} // cppcheck-suppress functionStatic inline const std::string &value() PROJ_PURE_DEFN { return value_; } // cppcheck-suppress functionStatic inline const std::vector<WKTNodeNNPtr> &children() PROJ_PURE_DEFN { return children_; } // cppcheck-suppress functionStatic inline size_t childrenSize() PROJ_PURE_DEFN { return children_.size(); } // cppcheck-suppress functionStatic const WKTNodeNNPtr &lookForChild(const std::string &childName, int occurrence) const noexcept; // cppcheck-suppress functionStatic const WKTNodeNNPtr &lookForChild(const std::string &name) const noexcept; // cppcheck-suppress functionStatic const WKTNodeNNPtr &lookForChild(const std::string &name, const std::string &name2) const noexcept; // cppcheck-suppress functionStatic const WKTNodeNNPtr &lookForChild(const std::string &name, const std::string &name2, const std::string &name3) const noexcept; // cppcheck-suppress functionStatic const WKTNodeNNPtr &lookForChild(const std::string &name, const std::string &name2, const std::string &name3, const std::string &name4) const noexcept; }; #define GP() getPrivate() // --------------------------------------------------------------------------- const WKTNodeNNPtr & WKTNode::Private::lookForChild(const std::string &childName, int occurrence) const noexcept { int occCount = 0; for (const auto &child : children_) { if (ci_equal(child->GP()->value(), childName)) { if (occurrence == occCount) { return child; } occCount++; } } return null_node; } const WKTNodeNNPtr & WKTNode::Private::lookForChild(const std::string &name) const noexcept { for (const auto &child : children_) { const auto &v = child->GP()->value(); if (ci_equal(v, name)) { return child; } } return null_node; } const WKTNodeNNPtr & WKTNode::Private::lookForChild(const std::string &name, const std::string &name2) const noexcept { for (const auto &child : children_) { const auto &v = child->GP()->value(); if (ci_equal(v, name) || ci_equal(v, name2)) { return child; } } return null_node; } const WKTNodeNNPtr & WKTNode::Private::lookForChild(const std::string &name, const std::string &name2, const std::string &name3) const noexcept { for (const auto &child : children_) { const auto &v = child->GP()->value(); if (ci_equal(v, name) || ci_equal(v, name2) || ci_equal(v, name3)) { return child; } } return null_node; } const WKTNodeNNPtr &WKTNode::Private::lookForChild( const std::string &name, const std::string &name2, const std::string &name3, const std::string &name4) const noexcept { for (const auto &child : children_) { const auto &v = child->GP()->value(); if (ci_equal(v, name) || ci_equal(v, name2) || ci_equal(v, name3) || ci_equal(v, name4)) { return child; } } return null_node; } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a WKTNode. * * @param valueIn the name of the node. */ WKTNode::WKTNode(const std::string &valueIn) : d(internal::make_unique<Private>(valueIn)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress WKTNode::~WKTNode() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Adds a child to the current node. * * @param child child to add. This should not be a parent of this node. */ void WKTNode::addChild(WKTNodeNNPtr &&child) { d->children_.push_back(std::move(child)); } // --------------------------------------------------------------------------- /** \brief Return the (occurrence-1)th sub-node of name childName. * * @param childName name of the child. * @param occurrence occurrence index (starting at 0) * @return the child, or nullptr. */ const WKTNodePtr &WKTNode::lookForChild(const std::string &childName, int occurrence) const noexcept { int occCount = 0; for (const auto &child : d->children_) { if (ci_equal(child->GP()->value(), childName)) { if (occurrence == occCount) { return child; } occCount++; } } return null_node; } // --------------------------------------------------------------------------- /** \brief Return the count of children of given name. * * @param childName name of the children to look for. * @return count */ int WKTNode::countChildrenOfName(const std::string &childName) const noexcept { int occCount = 0; for (const auto &child : d->children_) { if (ci_equal(child->GP()->value(), childName)) { occCount++; } } return occCount; } // --------------------------------------------------------------------------- /** \brief Return the value of a node. */ const std::string &WKTNode::value() const { return d->value_; } // --------------------------------------------------------------------------- /** \brief Return the children of a node. */ const std::vector<WKTNodeNNPtr> &WKTNode::children() const { return d->children_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static size_t skipSpace(const std::string &str, size_t start) { size_t i = start; while (i < str.size() && ::isspace(static_cast<unsigned char>(str[i]))) { ++i; } return i; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // As used in examples of OGC 12-063r5 static const std::string startPrintedQuote("\xE2\x80\x9C"); static const std::string endPrintedQuote("\xE2\x80\x9D"); //! @endcond WKTNodeNNPtr WKTNode::createFrom(const std::string &wkt, size_t indexStart, int recLevel, size_t &indexEnd) { if (recLevel == 16) { throw ParsingException("too many nesting levels"); } std::string value; size_t i = skipSpace(wkt, indexStart); if (i == wkt.size()) { throw ParsingException("whitespace only string"); } std::string closingStringMarker; bool inString = false; for (; i < wkt.size() && (inString || (wkt[i] != '[' && wkt[i] != '(' && wkt[i] != ',' && wkt[i] != ']' && wkt[i] != ')' && !::isspace(static_cast<unsigned char>(wkt[i])))); ++i) { if (wkt[i] == '"') { if (!inString) { inString = true; closingStringMarker = "\""; } else if (closingStringMarker == "\"") { if (i + 1 < wkt.size() && wkt[i + 1] == '"') { i++; } else { inString = false; closingStringMarker.clear(); } } } else if (i + 3 <= wkt.size() && wkt.substr(i, 3) == startPrintedQuote) { if (!inString) { inString = true; closingStringMarker = endPrintedQuote; value += '"'; i += 2; continue; } } else if (i + 3 <= wkt.size() && closingStringMarker == endPrintedQuote && wkt.substr(i, 3) == endPrintedQuote) { inString = false; closingStringMarker.clear(); value += '"'; i += 2; continue; } value += wkt[i]; } i = skipSpace(wkt, i); if (i == wkt.size()) { if (indexStart == 0) { throw ParsingException("missing ["); } else { throw ParsingException("missing , or ]"); } } auto node = NN_NO_CHECK(internal::make_unique<WKTNode>(value)); if (indexStart > 0) { if (wkt[i] == ',') { indexEnd = i + 1; return node; } if (wkt[i] == ']' || wkt[i] == ')') { indexEnd = i; return node; } } if (wkt[i] != '[' && wkt[i] != '(') { throw ParsingException("missing ["); } ++i; // skip [ i = skipSpace(wkt, i); while (i < wkt.size() && wkt[i] != ']' && wkt[i] != ')') { size_t indexEndChild; node->addChild(createFrom(wkt, i, recLevel + 1, indexEndChild)); assert(indexEndChild > i); i = indexEndChild; i = skipSpace(wkt, i); if (i < wkt.size() && wkt[i] == ',') { ++i; i = skipSpace(wkt, i); } } if (i == wkt.size() || (wkt[i] != ']' && wkt[i] != ')')) { throw ParsingException("missing ]"); } indexEnd = i + 1; return node; } // --------------------------------------------------------------------------- /** \brief Instantiate a WKTNode hierarchy from a WKT string. * * @param wkt the WKT string to parse. * @param indexStart the start index in the wkt string. * @throw ParsingException */ WKTNodeNNPtr WKTNode::createFrom(const std::string &wkt, size_t indexStart) { size_t indexEnd; return createFrom(wkt, indexStart, 0, indexEnd); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static std::string escapeIfQuotedString(const std::string &str) { if (str.size() > 2 && str[0] == '"' && str.back() == '"') { std::string res("\""); res += replaceAll(str.substr(1, str.size() - 2), "\"", "\"\""); res += '"'; return res; } else { return str; } } //! @endcond // --------------------------------------------------------------------------- /** \brief Return a WKT representation of the tree structure. */ std::string WKTNode::toString() const { std::string str(escapeIfQuotedString(d->value_)); if (!d->children_.empty()) { str += "["; bool first = true; for (auto &child : d->children_) { if (!first) { str += ','; } first = false; str += child->toString(); } str += "]"; } return str; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct WKTParser::Private { struct ci_less_struct { bool operator()(const std::string &lhs, const std::string &rhs) const noexcept { return ci_less(lhs, rhs); } }; bool strict_ = true; bool unsetIdentifiersIfIncompatibleDef_ = true; std::list<std::string> warningList_{}; std::vector<double> toWGS84Parameters_{}; std::string datumPROJ4Grids_{}; bool esriStyle_ = false; bool maybeEsriStyle_ = false; DatabaseContextPtr dbContext_{}; crs::GeographicCRSPtr geogCRSOfCompoundCRS_{}; static constexpr int MAX_PROPERTY_SIZE = 1024; PropertyMap **properties_{}; int propertyCount_ = 0; Private() { properties_ = new PropertyMap *[MAX_PROPERTY_SIZE]; } ~Private() { for (int i = 0; i < propertyCount_; i++) { delete properties_[i]; } delete[] properties_; } Private(const Private &) = delete; Private &operator=(const Private &) = delete; void emitRecoverableWarning(const std::string &errorMsg); void emitRecoverableMissingUNIT(const std::string &parentNodeName, const UnitOfMeasure &fallbackUnit); BaseObjectNNPtr build(const WKTNodeNNPtr &node); IdentifierPtr buildId(const WKTNodeNNPtr &node, bool tolerant, bool removeInverseOf); PropertyMap &buildProperties(const WKTNodeNNPtr &node, bool removeInverseOf = false, bool hasName = true); ObjectDomainPtr buildObjectDomain(const WKTNodeNNPtr &node); static std::string stripQuotes(const WKTNodeNNPtr &node); static double asDouble(const WKTNodeNNPtr &node); UnitOfMeasure buildUnit(const WKTNodeNNPtr &node, UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN); UnitOfMeasure buildUnitInSubNode( const WKTNodeNNPtr &node, common::UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN); EllipsoidNNPtr buildEllipsoid(const WKTNodeNNPtr &node); PrimeMeridianNNPtr buildPrimeMeridian(const WKTNodeNNPtr &node, const UnitOfMeasure &defaultAngularUnit); static optional<std::string> getAnchor(const WKTNodeNNPtr &node); static optional<common::Measure> getAnchorEpoch(const WKTNodeNNPtr &node); static void parseDynamic(const WKTNodeNNPtr &dynamicNode, double &frameReferenceEpoch, util::optional<std::string> &modelName); GeodeticReferenceFrameNNPtr buildGeodeticReferenceFrame(const WKTNodeNNPtr &node, const PrimeMeridianNNPtr &primeMeridian, const WKTNodeNNPtr &dynamicNode); DatumEnsembleNNPtr buildDatumEnsemble(const WKTNodeNNPtr &node, const PrimeMeridianPtr &primeMeridian, bool expectEllipsoid); MeridianNNPtr buildMeridian(const WKTNodeNNPtr &node); CoordinateSystemAxisNNPtr buildAxis(const WKTNodeNNPtr &node, const UnitOfMeasure &unitIn, const UnitOfMeasure::Type &unitType, bool isGeocentric, int expectedOrderNum); CoordinateSystemNNPtr buildCS(const WKTNodeNNPtr &node, /* maybe null */ const WKTNodeNNPtr &parentNode, const UnitOfMeasure &defaultAngularUnit); GeodeticCRSNNPtr buildGeodeticCRS(const WKTNodeNNPtr &node); CRSNNPtr buildDerivedGeodeticCRS(const WKTNodeNNPtr &node); static UnitOfMeasure guessUnitForParameter(const std::string &paramName, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit); void consumeParameters(const WKTNodeNNPtr &node, bool isAbridged, std::vector<OperationParameterNNPtr> &parameters, std::vector<ParameterValueNNPtr> &values, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit); static std::string getExtensionProj4(const WKTNode::Private *nodeP); static void addExtensionProj4ToProp(const WKTNode::Private *nodeP, PropertyMap &props); ConversionNNPtr buildConversion(const WKTNodeNNPtr &node, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit); static bool hasWebMercPROJ4String(const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode); static std::string projectionGetParameter(const WKTNodeNNPtr &projCRSNode, const char *paramName); ConversionNNPtr buildProjection(const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit); ConversionNNPtr buildProjectionStandard(const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit); const ESRIMethodMapping * getESRIMapping(const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue); static ConversionNNPtr buildProjectionFromESRI(const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit, const ESRIMethodMapping *esriMapping, std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue); ConversionNNPtr buildProjectionFromESRI(const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit); ProjectedCRSNNPtr buildProjectedCRS(const WKTNodeNNPtr &node); VerticalReferenceFrameNNPtr buildVerticalReferenceFrame(const WKTNodeNNPtr &node, const WKTNodeNNPtr &dynamicNode); TemporalDatumNNPtr buildTemporalDatum(const WKTNodeNNPtr &node); EngineeringDatumNNPtr buildEngineeringDatum(const WKTNodeNNPtr &node); ParametricDatumNNPtr buildParametricDatum(const WKTNodeNNPtr &node); CRSNNPtr buildVerticalCRS(const WKTNodeNNPtr &node); DerivedVerticalCRSNNPtr buildDerivedVerticalCRS(const WKTNodeNNPtr &node); CRSNNPtr buildCompoundCRS(const WKTNodeNNPtr &node); BoundCRSNNPtr buildBoundCRS(const WKTNodeNNPtr &node); TemporalCSNNPtr buildTemporalCS(const WKTNodeNNPtr &parentNode); TemporalCRSNNPtr buildTemporalCRS(const WKTNodeNNPtr &node); DerivedTemporalCRSNNPtr buildDerivedTemporalCRS(const WKTNodeNNPtr &node); EngineeringCRSNNPtr buildEngineeringCRS(const WKTNodeNNPtr &node); EngineeringCRSNNPtr buildEngineeringCRSFromLocalCS(const WKTNodeNNPtr &node); DerivedEngineeringCRSNNPtr buildDerivedEngineeringCRS(const WKTNodeNNPtr &node); ParametricCSNNPtr buildParametricCS(const WKTNodeNNPtr &parentNode); ParametricCRSNNPtr buildParametricCRS(const WKTNodeNNPtr &node); DerivedParametricCRSNNPtr buildDerivedParametricCRS(const WKTNodeNNPtr &node); DerivedProjectedCRSNNPtr buildDerivedProjectedCRS(const WKTNodeNNPtr &node); CRSPtr buildCRS(const WKTNodeNNPtr &node); TransformationNNPtr buildCoordinateOperation(const WKTNodeNNPtr &node); PointMotionOperationNNPtr buildPointMotionOperation(const WKTNodeNNPtr &node); ConcatenatedOperationNNPtr buildConcatenatedOperation(const WKTNodeNNPtr &node); CoordinateMetadataNNPtr buildCoordinateMetadata(const WKTNodeNNPtr &node); }; //! @endcond // --------------------------------------------------------------------------- WKTParser::WKTParser() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress WKTParser::~WKTParser() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Set whether parsing should be done in strict mode. */ WKTParser &WKTParser::setStrict(bool strict) { d->strict_ = strict; return *this; } // --------------------------------------------------------------------------- /** \brief Set whether object identifiers should be unset when there is * a contradiction between the definition from WKT and the one from * the database. * * At time of writing, this only applies to the base geographic CRS of a * projected CRS, when comparing its coordinate system. */ WKTParser &WKTParser::setUnsetIdentifiersIfIncompatibleDef(bool unset) { d->unsetIdentifiersIfIncompatibleDef_ = unset; return *this; } // --------------------------------------------------------------------------- /** \brief Return the list of warnings found during parsing. * * \note The list might be non-empty only is setStrict(false) has been called. */ std::list<std::string> WKTParser::warningList() const { return d->warningList_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void WKTParser::Private::emitRecoverableWarning(const std::string &errorMsg) { if (strict_) { throw ParsingException(errorMsg); } else { warningList_.push_back(errorMsg); } } // --------------------------------------------------------------------------- static double asDouble(const std::string &val) { return c_locale_stod(val); } // --------------------------------------------------------------------------- PROJ_NO_RETURN static void ThrowNotEnoughChildren(const std::string &nodeName) { throw ParsingException( concat("not enough children in ", nodeName, " node")); } // --------------------------------------------------------------------------- PROJ_NO_RETURN static void ThrowNotRequiredNumberOfChildren(const std::string &nodeName) { throw ParsingException( concat("not required number of children in ", nodeName, " node")); } // --------------------------------------------------------------------------- PROJ_NO_RETURN static void ThrowMissing(const std::string &nodeName) { throw ParsingException(concat("missing ", nodeName, " node")); } // --------------------------------------------------------------------------- PROJ_NO_RETURN static void ThrowNotExpectedCSType(const std::string &expectedCSType) { throw ParsingException(concat("CS node is not of type ", expectedCSType)); } // --------------------------------------------------------------------------- static ParsingException buildRethrow(const char *funcName, const std::exception &e) { std::string res(funcName); res += ": "; res += e.what(); return ParsingException(res); } // --------------------------------------------------------------------------- std::string WKTParser::Private::stripQuotes(const WKTNodeNNPtr &node) { return ::stripQuotes(node->GP()->value()); } // --------------------------------------------------------------------------- double WKTParser::Private::asDouble(const WKTNodeNNPtr &node) { return io::asDouble(node->GP()->value()); } // --------------------------------------------------------------------------- IdentifierPtr WKTParser::Private::buildId(const WKTNodeNNPtr &node, bool tolerant, bool removeInverseOf) { const auto *nodeP = node->GP(); const auto &nodeChildren = nodeP->children(); if (nodeChildren.size() >= 2) { auto codeSpace = stripQuotes(nodeChildren[0]); if (removeInverseOf && starts_with(codeSpace, "INVERSE(") && codeSpace.back() == ')') { codeSpace = codeSpace.substr(strlen("INVERSE(")); codeSpace.resize(codeSpace.size() - 1); } PropertyMap propertiesId; if (nodeChildren.size() >= 3 && nodeChildren[2]->GP()->childrenSize() == 0) { std::string version = stripQuotes(nodeChildren[2]); // IAU + 2015 -> IAU_2015 if (dbContext_) { std::string codeSpaceOut; if (dbContext_->getVersionedAuthority(codeSpace, version, codeSpaceOut)) { codeSpace = std::move(codeSpaceOut); version.clear(); } } if (!version.empty()) { propertiesId.set(Identifier::VERSION_KEY, version); } } auto code = stripQuotes(nodeChildren[1]); auto &citationNode = nodeP->lookForChild(WKTConstants::CITATION); auto &uriNode = nodeP->lookForChild(WKTConstants::URI); propertiesId.set(Identifier::CODESPACE_KEY, codeSpace); bool authoritySet = false; /*if (!isNull(citationNode))*/ { const auto *citationNodeP = citationNode->GP(); if (citationNodeP->childrenSize() == 1) { authoritySet = true; propertiesId.set(Identifier::AUTHORITY_KEY, stripQuotes(citationNodeP->children()[0])); } } if (!authoritySet) { propertiesId.set(Identifier::AUTHORITY_KEY, codeSpace); } /*if (!isNull(uriNode))*/ { const auto *uriNodeP = uriNode->GP(); if (uriNodeP->childrenSize() == 1) { propertiesId.set(Identifier::URI_KEY, stripQuotes(uriNodeP->children()[0])); } } return Identifier::create(code, propertiesId); } else if (strict_ || !tolerant) { ThrowNotEnoughChildren(nodeP->value()); } else { std::string msg("not enough children in "); msg += nodeP->value(); msg += " node"; warningList_.emplace_back(std::move(msg)); } return nullptr; } // --------------------------------------------------------------------------- PropertyMap &WKTParser::Private::buildProperties(const WKTNodeNNPtr &node, bool removeInverseOf, bool hasName) { if (propertyCount_ == MAX_PROPERTY_SIZE) { throw ParsingException("MAX_PROPERTY_SIZE reached"); } properties_[propertyCount_] = new PropertyMap(); auto &&properties = properties_[propertyCount_]; propertyCount_++; std::string authNameFromAlias; std::string codeFromAlias; const auto *nodeP = node->GP(); const auto &nodeChildren = nodeP->children(); auto identifiers = ArrayOfBaseObject::create(); for (const auto &subNode : nodeChildren) { const auto &subNodeName(subNode->GP()->value()); if (ci_equal(subNodeName, WKTConstants::ID) || ci_equal(subNodeName, WKTConstants::AUTHORITY)) { auto id = buildId(subNode, true, removeInverseOf); if (id) { identifiers->add(NN_NO_CHECK(id)); } } } if (hasName && !nodeChildren.empty()) { const auto &nodeName(nodeP->value()); auto name(stripQuotes(nodeChildren[0])); if (removeInverseOf && starts_with(name, "Inverse of ")) { name = name.substr(strlen("Inverse of ")); } if (ends_with(name, " (deprecated)")) { name.resize(name.size() - strlen(" (deprecated)")); properties->set(common::IdentifiedObject::DEPRECATED_KEY, true); } // Oracle WKT can contain names like // "Reseau Geodesique Francais 1993 (EPSG ID 6171)" // for WKT attributes to the auth_name = "IGN - Paris" // Strip that suffix from the name and assign a true EPSG code to the // object if (identifiers->empty()) { const auto pos = name.find(" (EPSG ID "); if (pos != std::string::npos && name.back() == ')') { const auto code = name.substr(pos + strlen(" (EPSG ID "), name.size() - 1 - pos - strlen(" (EPSG ID ")); name.resize(pos); PropertyMap propertiesId; propertiesId.set(Identifier::CODESPACE_KEY, Identifier::EPSG); propertiesId.set(Identifier::AUTHORITY_KEY, Identifier::EPSG); identifiers->add(Identifier::create(code, propertiesId)); } } const char *tableNameForAlias = nullptr; if (ci_equal(nodeName, WKTConstants::GEOGCS)) { if (starts_with(name, "GCS_")) { esriStyle_ = true; if (name == "GCS_WGS_1984") { name = "WGS 84"; } else if (name == "GCS_unknown") { name = "unknown"; } else { tableNameForAlias = "geodetic_crs"; } } } else if (esriStyle_ && ci_equal(nodeName, WKTConstants::SPHEROID)) { if (name == "WGS_1984") { name = "WGS 84"; authNameFromAlias = Identifier::EPSG; codeFromAlias = "7030"; } else { tableNameForAlias = "ellipsoid"; } } if (dbContext_ && tableNameForAlias) { std::string outTableName; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); auto officialName = authFactory->getOfficialNameFromAlias( name, tableNameForAlias, "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { name = std::move(officialName); // Clearing authority for geodetic_crs because of // potential axis order mismatch. if (strcmp(tableNameForAlias, "geodetic_crs") == 0) { authNameFromAlias.clear(); codeFromAlias.clear(); } } } properties->set(IdentifiedObject::NAME_KEY, name); } if (identifiers->empty() && !authNameFromAlias.empty()) { identifiers->add(Identifier::create( codeFromAlias, PropertyMap() .set(Identifier::CODESPACE_KEY, authNameFromAlias) .set(Identifier::AUTHORITY_KEY, authNameFromAlias))); } if (!identifiers->empty()) { properties->set(IdentifiedObject::IDENTIFIERS_KEY, identifiers); } auto &remarkNode = nodeP->lookForChild(WKTConstants::REMARK); if (!isNull(remarkNode)) { const auto &remarkChildren = remarkNode->GP()->children(); if (remarkChildren.size() == 1) { properties->set(IdentifiedObject::REMARKS_KEY, stripQuotes(remarkChildren[0])); } else { ThrowNotRequiredNumberOfChildren(remarkNode->GP()->value()); } } ArrayOfBaseObjectNNPtr array = ArrayOfBaseObject::create(); for (const auto &subNode : nodeP->children()) { const auto &subNodeName(subNode->GP()->value()); if (ci_equal(subNodeName, WKTConstants::USAGE)) { auto objectDomain = buildObjectDomain(subNode); if (!objectDomain) { throw ParsingException( concat("missing children in ", subNodeName, " node")); } array->add(NN_NO_CHECK(objectDomain)); } } if (!array->empty()) { properties->set(ObjectUsage::OBJECT_DOMAIN_KEY, array); } else { auto objectDomain = buildObjectDomain(node); if (objectDomain) { properties->set(ObjectUsage::OBJECT_DOMAIN_KEY, NN_NO_CHECK(objectDomain)); } } auto &versionNode = nodeP->lookForChild(WKTConstants::VERSION); if (!isNull(versionNode)) { const auto &versionChildren = versionNode->GP()->children(); if (versionChildren.size() == 1) { properties->set(CoordinateOperation::OPERATION_VERSION_KEY, stripQuotes(versionChildren[0])); } else { ThrowNotRequiredNumberOfChildren(versionNode->GP()->value()); } } return *properties; } // --------------------------------------------------------------------------- ObjectDomainPtr WKTParser::Private::buildObjectDomain(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &scopeNode = nodeP->lookForChild(WKTConstants::SCOPE); auto &areaNode = nodeP->lookForChild(WKTConstants::AREA); auto &bboxNode = nodeP->lookForChild(WKTConstants::BBOX); auto &verticalExtentNode = nodeP->lookForChild(WKTConstants::VERTICALEXTENT); auto &temporalExtentNode = nodeP->lookForChild(WKTConstants::TIMEEXTENT); if (!isNull(scopeNode) || !isNull(areaNode) || !isNull(bboxNode) || !isNull(verticalExtentNode) || !isNull(temporalExtentNode)) { optional<std::string> scope; const auto *scopeNodeP = scopeNode->GP(); const auto &scopeChildren = scopeNodeP->children(); if (scopeChildren.size() == 1) { scope = stripQuotes(scopeChildren[0]); } ExtentPtr extent; if (!isNull(areaNode) || !isNull(bboxNode)) { util::optional<std::string> description; std::vector<GeographicExtentNNPtr> geogExtent; std::vector<VerticalExtentNNPtr> verticalExtent; std::vector<TemporalExtentNNPtr> temporalExtent; if (!isNull(areaNode)) { const auto &areaChildren = areaNode->GP()->children(); if (areaChildren.size() == 1) { description = stripQuotes(areaChildren[0]); } else { ThrowNotRequiredNumberOfChildren(areaNode->GP()->value()); } } if (!isNull(bboxNode)) { const auto &bboxChildren = bboxNode->GP()->children(); if (bboxChildren.size() == 4) { try { double south = asDouble(bboxChildren[0]); double west = asDouble(bboxChildren[1]); double north = asDouble(bboxChildren[2]); double east = asDouble(bboxChildren[3]); auto bbox = GeographicBoundingBox::create(west, south, east, north); geogExtent.emplace_back(bbox); } catch (const std::exception &) { throw ParsingException(concat("not 4 double values in ", bboxNode->GP()->value(), " node")); } } else { ThrowNotRequiredNumberOfChildren(bboxNode->GP()->value()); } } if (!isNull(verticalExtentNode)) { const auto &verticalExtentChildren = verticalExtentNode->GP()->children(); const auto verticalExtentChildrenSize = verticalExtentChildren.size(); if (verticalExtentChildrenSize == 2 || verticalExtentChildrenSize == 3) { double min; double max; try { min = asDouble(verticalExtentChildren[0]); max = asDouble(verticalExtentChildren[1]); } catch (const std::exception &) { throw ParsingException( concat("not 2 double values in ", verticalExtentNode->GP()->value(), " node")); } UnitOfMeasure unit = UnitOfMeasure::METRE; if (verticalExtentChildrenSize == 3) { unit = buildUnit(verticalExtentChildren[2], UnitOfMeasure::Type::LINEAR); } verticalExtent.emplace_back(VerticalExtent::create( min, max, util::nn_make_shared<UnitOfMeasure>(unit))); } else { ThrowNotRequiredNumberOfChildren( verticalExtentNode->GP()->value()); } } if (!isNull(temporalExtentNode)) { const auto &temporalExtentChildren = temporalExtentNode->GP()->children(); if (temporalExtentChildren.size() == 2) { temporalExtent.emplace_back(TemporalExtent::create( stripQuotes(temporalExtentChildren[0]), stripQuotes(temporalExtentChildren[1]))); } else { ThrowNotRequiredNumberOfChildren( temporalExtentNode->GP()->value()); } } extent = Extent::create(description, geogExtent, verticalExtent, temporalExtent) .as_nullable(); } return ObjectDomain::create(scope, extent).as_nullable(); } return nullptr; } // --------------------------------------------------------------------------- UnitOfMeasure WKTParser::Private::buildUnit(const WKTNodeNNPtr &node, UnitOfMeasure::Type type) { const auto *nodeP = node->GP(); const auto &children = nodeP->children(); if ((type != UnitOfMeasure::Type::TIME && children.size() < 2) || (type == UnitOfMeasure::Type::TIME && children.size() < 1)) { ThrowNotEnoughChildren(nodeP->value()); } try { std::string unitName(stripQuotes(children[0])); PropertyMap properties(buildProperties(node)); auto &idNode = nodeP->lookForChild(WKTConstants::ID, WKTConstants::AUTHORITY); if (!isNull(idNode) && idNode->GP()->childrenSize() < 2) { emitRecoverableWarning("not enough children in " + idNode->GP()->value() + " node"); } const bool hasValidIdNode = !isNull(idNode) && idNode->GP()->childrenSize() >= 2; const auto &idNodeChildren(idNode->GP()->children()); std::string codeSpace(hasValidIdNode ? stripQuotes(idNodeChildren[0]) : std::string()); std::string code(hasValidIdNode ? stripQuotes(idNodeChildren[1]) : std::string()); bool queryDb = true; if (type == UnitOfMeasure::Type::UNKNOWN) { if (ci_equal(unitName, "METER") || ci_equal(unitName, "METRE")) { type = UnitOfMeasure::Type::LINEAR; unitName = "metre"; if (codeSpace.empty()) { codeSpace = Identifier::EPSG; code = "9001"; queryDb = false; } } else if (ci_equal(unitName, "DEGREE") || ci_equal(unitName, "GRAD")) { type = UnitOfMeasure::Type::ANGULAR; } } if (esriStyle_ && dbContext_ && queryDb) { std::string outTableName; std::string authNameFromAlias; std::string codeFromAlias; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); auto officialName = authFactory->getOfficialNameFromAlias( unitName, "unit_of_measure", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { unitName = std::move(officialName); codeSpace = std::move(authNameFromAlias); code = std::move(codeFromAlias); } } double convFactor = children.size() >= 2 ? asDouble(children[1]) : 0.0; constexpr double US_FOOT_CONV_FACTOR = 12.0 / 39.37; constexpr double REL_ERROR = 1e-10; // Fix common rounding errors if (std::fabs(convFactor - UnitOfMeasure::DEGREE.conversionToSI()) < REL_ERROR * convFactor) { convFactor = UnitOfMeasure::DEGREE.conversionToSI(); } else if (std::fabs(convFactor - US_FOOT_CONV_FACTOR) < REL_ERROR * convFactor) { convFactor = US_FOOT_CONV_FACTOR; } return UnitOfMeasure(unitName, convFactor, type, codeSpace, code); } catch (const std::exception &e) { throw buildRethrow(__FUNCTION__, e); } } // --------------------------------------------------------------------------- // node here is a parent node, not a UNIT/LENGTHUNIT/ANGLEUNIT/TIMEUNIT/... node UnitOfMeasure WKTParser::Private::buildUnitInSubNode(const WKTNodeNNPtr &node, UnitOfMeasure::Type type) { const auto *nodeP = node->GP(); { auto &unitNode = nodeP->lookForChild(WKTConstants::LENGTHUNIT); if (!isNull(unitNode)) { return buildUnit(unitNode, UnitOfMeasure::Type::LINEAR); } } { auto &unitNode = nodeP->lookForChild(WKTConstants::ANGLEUNIT); if (!isNull(unitNode)) { return buildUnit(unitNode, UnitOfMeasure::Type::ANGULAR); } } { auto &unitNode = nodeP->lookForChild(WKTConstants::SCALEUNIT); if (!isNull(unitNode)) { return buildUnit(unitNode, UnitOfMeasure::Type::SCALE); } } { auto &unitNode = nodeP->lookForChild(WKTConstants::TIMEUNIT); if (!isNull(unitNode)) { return buildUnit(unitNode, UnitOfMeasure::Type::TIME); } } { auto &unitNode = nodeP->lookForChild(WKTConstants::TEMPORALQUANTITY); if (!isNull(unitNode)) { return buildUnit(unitNode, UnitOfMeasure::Type::TIME); } } { auto &unitNode = nodeP->lookForChild(WKTConstants::PARAMETRICUNIT); if (!isNull(unitNode)) { return buildUnit(unitNode, UnitOfMeasure::Type::PARAMETRIC); } } { auto &unitNode = nodeP->lookForChild(WKTConstants::UNIT); if (!isNull(unitNode)) { return buildUnit(unitNode, type); } } return UnitOfMeasure::NONE; } // --------------------------------------------------------------------------- EllipsoidNNPtr WKTParser::Private::buildEllipsoid(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); const auto &children = nodeP->children(); if (children.size() < 3) { ThrowNotEnoughChildren(nodeP->value()); } try { UnitOfMeasure unit = buildUnitInSubNode(node, UnitOfMeasure::Type::LINEAR); if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure::METRE; } Length semiMajorAxis(asDouble(children[1]), unit); // Some WKT in the wild use "inf". Cf SPHEROID["unnamed",6370997,"inf"] // in https://zenodo.org/record/3878979#.Y_P4g4CZNH4, // https://zenodo.org/record/5831940#.Y_P4i4CZNH5 // or https://grasswiki.osgeo.org/wiki/Marine_Science const auto &invFlatteningChild = children[2]; if (invFlatteningChild->GP()->value() == "\"inf\"") { emitRecoverableWarning("Inverse flattening = \"inf\" is not " "conformant, but understood"); } Scale invFlattening(invFlatteningChild->GP()->value() == "\"inf\"" ? 0 : asDouble(invFlatteningChild)); const auto celestialBody( Ellipsoid::guessBodyName(dbContext_, semiMajorAxis.getSIValue())); if (invFlattening.getSIValue() == 0) { return Ellipsoid::createSphere(buildProperties(node), semiMajorAxis, celestialBody); } else { return Ellipsoid::createFlattenedSphere( buildProperties(node), semiMajorAxis, invFlattening, celestialBody); } } catch (const std::exception &e) { throw buildRethrow(__FUNCTION__, e); } } // --------------------------------------------------------------------------- PrimeMeridianNNPtr WKTParser::Private::buildPrimeMeridian( const WKTNodeNNPtr &node, const UnitOfMeasure &defaultAngularUnit) { const auto *nodeP = node->GP(); const auto &children = nodeP->children(); if (children.size() < 2) { ThrowNotEnoughChildren(nodeP->value()); } auto name = stripQuotes(children[0]); UnitOfMeasure unit = buildUnitInSubNode(node, UnitOfMeasure::Type::ANGULAR); if (unit == UnitOfMeasure::NONE) { unit = defaultAngularUnit; if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure::DEGREE; } } try { double angleValue = asDouble(children[1]); // Correct for GDAL WKT1 and WKT1-ESRI departure if (name == "Paris" && std::fabs(angleValue - 2.33722917) < 1e-8 && unit._isEquivalentTo(UnitOfMeasure::GRAD, util::IComparable::Criterion::EQUIVALENT)) { angleValue = 2.5969213; } else { static const struct { const char *name; int deg; int min; double sec; } primeMeridiansDMS[] = { {"Lisbon", -9, 7, 54.862}, {"Bogota", -74, 4, 51.3}, {"Madrid", -3, 41, 14.55}, {"Rome", 12, 27, 8.4}, {"Bern", 7, 26, 22.5}, {"Jakarta", 106, 48, 27.79}, {"Ferro", -17, 40, 0}, {"Brussels", 4, 22, 4.71}, {"Stockholm", 18, 3, 29.8}, {"Athens", 23, 42, 58.815}, {"Oslo", 10, 43, 22.5}, {"Paris RGS", 2, 20, 13.95}, {"Paris_RGS", 2, 20, 13.95}}; // Current epsg.org output may use the EPSG:9110 "sexagesimal DMS" // unit and a DD.MMSSsss value, but this will likely be changed to // use decimal degree. // Or WKT1 may for example use the Paris RGS decimal degree value // but with a GEOGCS with UNIT["Grad"] for (const auto &pmDef : primeMeridiansDMS) { if (name == pmDef.name) { double dmsAsDecimalValue = (pmDef.deg >= 0 ? 1 : -1) * (std::abs(pmDef.deg) + pmDef.min / 100. + pmDef.sec / 10000.); double dmsAsDecimalDegreeValue = (pmDef.deg >= 0 ? 1 : -1) * (std::abs(pmDef.deg) + pmDef.min / 60. + pmDef.sec / 3600.); if (std::fabs(angleValue - dmsAsDecimalValue) < 1e-8 || std::fabs(angleValue - dmsAsDecimalDegreeValue) < 1e-8) { angleValue = dmsAsDecimalDegreeValue; unit = UnitOfMeasure::DEGREE; } break; } } } auto &properties = buildProperties(node); if (dbContext_ && esriStyle_) { std::string outTableName; std::string codeFromAlias; std::string authNameFromAlias; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); auto officialName = authFactory->getOfficialNameFromAlias( name, "prime_meridian", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { properties.set(IdentifiedObject::NAME_KEY, officialName); if (!authNameFromAlias.empty()) { auto identifiers = ArrayOfBaseObject::create(); identifiers->add(Identifier::create( codeFromAlias, PropertyMap() .set(Identifier::CODESPACE_KEY, authNameFromAlias) .set(Identifier::AUTHORITY_KEY, authNameFromAlias))); properties.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers); } } } Angle angle(angleValue, unit); return PrimeMeridian::create(properties, angle); } catch (const std::exception &e) { throw buildRethrow(__FUNCTION__, e); } } // --------------------------------------------------------------------------- optional<std::string> WKTParser::Private::getAnchor(const WKTNodeNNPtr &node) { auto &anchorNode = node->GP()->lookForChild(WKTConstants::ANCHOR); if (anchorNode->GP()->childrenSize() == 1) { return optional<std::string>( stripQuotes(anchorNode->GP()->children()[0])); } return optional<std::string>(); } // --------------------------------------------------------------------------- optional<common::Measure> WKTParser::Private::getAnchorEpoch(const WKTNodeNNPtr &node) { auto &anchorEpochNode = node->GP()->lookForChild(WKTConstants::ANCHOREPOCH); if (anchorEpochNode->GP()->childrenSize() == 1) { try { double value = asDouble(anchorEpochNode->GP()->children()[0]); return optional<common::Measure>( common::Measure(value, common::UnitOfMeasure::YEAR)); } catch (const std::exception &e) { throw buildRethrow(__FUNCTION__, e); } } return optional<common::Measure>(); } // --------------------------------------------------------------------------- static const PrimeMeridianNNPtr & fixupPrimeMeridan(const EllipsoidNNPtr &ellipsoid, const PrimeMeridianNNPtr &pm) { return (ellipsoid->celestialBody() != Ellipsoid::EARTH && pm.get() == PrimeMeridian::GREENWICH.get()) ? PrimeMeridian::REFERENCE_MERIDIAN : pm; } // --------------------------------------------------------------------------- GeodeticReferenceFrameNNPtr WKTParser::Private::buildGeodeticReferenceFrame( const WKTNodeNNPtr &node, const PrimeMeridianNNPtr &primeMeridian, const WKTNodeNNPtr &dynamicNode) { const auto *nodeP = node->GP(); auto &ellipsoidNode = nodeP->lookForChild(WKTConstants::ELLIPSOID, WKTConstants::SPHEROID); if (isNull(ellipsoidNode)) { ThrowMissing(WKTConstants::ELLIPSOID); } auto &properties = buildProperties(node); // do that before buildEllipsoid() so that esriStyle_ can be set auto name = stripQuotes(nodeP->children()[0]); const auto identifyFromName = [&](const std::string &l_name) { if (dbContext_) { auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); auto res = authFactory->createObjectsFromName( l_name, {AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, true, 1); if (!res.empty()) { bool foundDatumName = false; const auto &refDatum = res.front(); if (metadata::Identifier::isEquivalentName( l_name.c_str(), refDatum->nameStr().c_str())) { foundDatumName = true; } else if (refDatum->identifiers().size() == 1) { const auto &id = refDatum->identifiers()[0]; const auto aliases = authFactory->databaseContext()->getAliases( *id->codeSpace(), id->code(), refDatum->nameStr(), "geodetic_datum", std::string()); for (const auto &alias : aliases) { if (metadata::Identifier::isEquivalentName( l_name.c_str(), alias.c_str())) { foundDatumName = true; break; } } } if (foundDatumName) { properties.set(IdentifiedObject::NAME_KEY, refDatum->nameStr()); if (!properties.get(Identifier::CODESPACE_KEY) && refDatum->identifiers().size() == 1) { const auto &id = refDatum->identifiers()[0]; auto identifiers = ArrayOfBaseObject::create(); identifiers->add(Identifier::create( id->code(), PropertyMap() .set(Identifier::CODESPACE_KEY, *id->codeSpace()) .set(Identifier::AUTHORITY_KEY, *id->codeSpace()))); properties.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers); } return true; } } else { // Get official name from database if AUTHORITY is present auto &idNode = nodeP->lookForChild(WKTConstants::AUTHORITY); if (!isNull(idNode)) { try { auto id = buildId(idNode, false, false); auto authFactory2 = AuthorityFactory::create( NN_NO_CHECK(dbContext_), *id->codeSpace()); auto dbDatum = authFactory2->createGeodeticDatum(id->code()); properties.set(IdentifiedObject::NAME_KEY, dbDatum->nameStr()); return true; } catch (const std::exception &) { } } } } return false; }; // Remap GDAL WGS_1984 to EPSG v9 "World Geodetic System 1984" official // name. // Also remap EPSG v10 datum ensemble names to non-ensemble EPSG v9 bool nameSet = false; if (name == "WGS_1984" || name == "World Geodetic System 1984 ensemble") { nameSet = true; properties.set(IdentifiedObject::NAME_KEY, GeodeticReferenceFrame::EPSG_6326->nameStr()); } else if (name == "European Terrestrial Reference System 1989 ensemble") { nameSet = true; properties.set(IdentifiedObject::NAME_KEY, "European Terrestrial Reference System 1989"); } // If we got hints this might be a ESRI WKT, then check in the DB to // confirm std::string officialName; std::string authNameFromAlias; std::string codeFromAlias; if (!nameSet && maybeEsriStyle_ && dbContext_ && !(starts_with(name, "D_") || esriStyle_)) { std::string outTableName; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); officialName = authFactory->getOfficialNameFromAlias( name, "geodetic_datum", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { maybeEsriStyle_ = false; esriStyle_ = true; } } if (!nameSet && (starts_with(name, "D_") || esriStyle_)) { esriStyle_ = true; const char *tableNameForAlias = nullptr; if (name == "D_WGS_1984") { name = "World Geodetic System 1984"; authNameFromAlias = Identifier::EPSG; codeFromAlias = "6326"; } else if (name == "D_ETRS_1989") { name = "European Terrestrial Reference System 1989"; authNameFromAlias = Identifier::EPSG; codeFromAlias = "6258"; } else if (name == "D_unknown") { name = "unknown"; } else { tableNameForAlias = "geodetic_datum"; } bool setNameAndId = true; if (dbContext_ && tableNameForAlias) { if (officialName.empty()) { std::string outTableName; auto authFactory = AuthorityFactory::create( NN_NO_CHECK(dbContext_), std::string()); officialName = authFactory->getOfficialNameFromAlias( name, tableNameForAlias, "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); } if (officialName.empty()) { if (starts_with(name, "D_")) { // For the case of "D_GDA2020" where there is no D_GDA2020 // ESRI alias, so just try without the D_ prefix. const auto nameWithoutDPrefix = name.substr(2); if (identifyFromName(nameWithoutDPrefix)) { setNameAndId = false; // already done in identifyFromName() } } } else { if (primeMeridian->nameStr() != PrimeMeridian::GREENWICH->nameStr()) { auto nameWithPM = officialName + " (" + primeMeridian->nameStr() + ")"; if (dbContext_->isKnownName(nameWithPM, "geodetic_datum")) { officialName = std::move(nameWithPM); } } name = std::move(officialName); } } if (setNameAndId) { properties.set(IdentifiedObject::NAME_KEY, name); if (!authNameFromAlias.empty()) { auto identifiers = ArrayOfBaseObject::create(); identifiers->add(Identifier::create( codeFromAlias, PropertyMap() .set(Identifier::CODESPACE_KEY, authNameFromAlias) .set(Identifier::AUTHORITY_KEY, authNameFromAlias))); properties.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers); } } } else if (!nameSet && name.find('_') != std::string::npos) { // Likely coming from WKT1 identifyFromName(name); } auto ellipsoid = buildEllipsoid(ellipsoidNode); const auto &primeMeridianModified = fixupPrimeMeridan(ellipsoid, primeMeridian); auto &TOWGS84Node = nodeP->lookForChild(WKTConstants::TOWGS84); if (!isNull(TOWGS84Node)) { const auto &TOWGS84Children = TOWGS84Node->GP()->children(); const size_t TOWGS84Size = TOWGS84Children.size(); if (TOWGS84Size == 3 || TOWGS84Size == 7) { try { for (const auto &child : TOWGS84Children) { toWGS84Parameters_.push_back(asDouble(child)); } for (size_t i = TOWGS84Size; i < 7; ++i) { toWGS84Parameters_.push_back(0.0); } } catch (const std::exception &) { throw ParsingException("Invalid TOWGS84 node"); } } else { throw ParsingException("Invalid TOWGS84 node"); } } auto &extensionNode = nodeP->lookForChild(WKTConstants::EXTENSION); const auto &extensionChildren = extensionNode->GP()->children(); if (extensionChildren.size() == 2) { if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4_GRIDS")) { datumPROJ4Grids_ = stripQuotes(extensionChildren[1]); } } if (!isNull(dynamicNode)) { double frameReferenceEpoch = 0.0; util::optional<std::string> modelName; parseDynamic(dynamicNode, frameReferenceEpoch, modelName); return DynamicGeodeticReferenceFrame::create( properties, ellipsoid, getAnchor(node), primeMeridianModified, common::Measure(frameReferenceEpoch, common::UnitOfMeasure::YEAR), modelName); } return GeodeticReferenceFrame::create(properties, ellipsoid, getAnchor(node), getAnchorEpoch(node), primeMeridianModified); } // --------------------------------------------------------------------------- DatumEnsembleNNPtr WKTParser::Private::buildDatumEnsemble(const WKTNodeNNPtr &node, const PrimeMeridianPtr &primeMeridian, bool expectEllipsoid) { const auto *nodeP = node->GP(); auto &ellipsoidNode = nodeP->lookForChild(WKTConstants::ELLIPSOID, WKTConstants::SPHEROID); if (expectEllipsoid && isNull(ellipsoidNode)) { ThrowMissing(WKTConstants::ELLIPSOID); } std::vector<DatumNNPtr> datums; for (const auto &subNode : nodeP->children()) { if (ci_equal(subNode->GP()->value(), WKTConstants::MEMBER)) { if (subNode->GP()->childrenSize() == 0) { throw ParsingException("Invalid MEMBER node"); } if (expectEllipsoid) { datums.emplace_back(GeodeticReferenceFrame::create( buildProperties(subNode), buildEllipsoid(ellipsoidNode), optional<std::string>(), primeMeridian ? NN_NO_CHECK(primeMeridian) : PrimeMeridian::GREENWICH)); } else { datums.emplace_back( VerticalReferenceFrame::create(buildProperties(subNode))); } } } auto &accuracyNode = nodeP->lookForChild(WKTConstants::ENSEMBLEACCURACY); auto &accuracyNodeChildren = accuracyNode->GP()->children(); if (accuracyNodeChildren.empty()) { ThrowMissing(WKTConstants::ENSEMBLEACCURACY); } auto accuracy = PositionalAccuracy::create(accuracyNodeChildren[0]->GP()->value()); try { return DatumEnsemble::create(buildProperties(node), datums, accuracy); } catch (const util::Exception &e) { throw buildRethrow(__FUNCTION__, e); } } // --------------------------------------------------------------------------- MeridianNNPtr WKTParser::Private::buildMeridian(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); const auto &children = nodeP->children(); if (children.size() < 2) { ThrowNotEnoughChildren(nodeP->value()); } UnitOfMeasure unit = buildUnitInSubNode(node, UnitOfMeasure::Type::ANGULAR); try { double angleValue = asDouble(children[0]); Angle angle(angleValue, unit); return Meridian::create(angle); } catch (const std::exception &e) { throw buildRethrow(__FUNCTION__, e); } } // --------------------------------------------------------------------------- PROJ_NO_RETURN static void ThrowParsingExceptionMissingUNIT() { throw ParsingException("buildCS: missing UNIT"); } // --------------------------------------------------------------------------- CoordinateSystemAxisNNPtr WKTParser::Private::buildAxis(const WKTNodeNNPtr &node, const UnitOfMeasure &unitIn, const UnitOfMeasure::Type &unitType, bool isGeocentric, int expectedOrderNum) { const auto *nodeP = node->GP(); const auto &children = nodeP->children(); if (children.size() < 2) { ThrowNotEnoughChildren(nodeP->value()); } auto &orderNode = nodeP->lookForChild(WKTConstants::ORDER); if (!isNull(orderNode)) { const auto &orderNodeChildren = orderNode->GP()->children(); if (orderNodeChildren.size() != 1) { ThrowNotEnoughChildren(WKTConstants::ORDER); } const auto &order = orderNodeChildren[0]->GP()->value(); int orderNum; try { orderNum = std::stoi(order); } catch (const std::exception &) { throw ParsingException( concat("buildAxis: invalid ORDER value: ", order)); } if (orderNum != expectedOrderNum) { throw ParsingException( concat("buildAxis: did not get expected ORDER value: ", order)); } } // The axis designation in WK2 can be: "name", "(abbrev)" or "name // (abbrev)" std::string axisDesignation(stripQuotes(children[0])); size_t sepPos = axisDesignation.find(" ("); std::string axisName; std::string abbreviation; if (sepPos != std::string::npos && axisDesignation.back() == ')') { axisName = CoordinateSystemAxis::normalizeAxisName( axisDesignation.substr(0, sepPos)); abbreviation = axisDesignation.substr(sepPos + 2); abbreviation.resize(abbreviation.size() - 1); } else if (!axisDesignation.empty() && axisDesignation[0] == '(' && axisDesignation.back() == ')') { abbreviation = axisDesignation.substr(1, axisDesignation.size() - 2); if (abbreviation == AxisAbbreviation::E) { axisName = AxisName::Easting; } else if (abbreviation == AxisAbbreviation::N) { axisName = AxisName::Northing; } else if (abbreviation == AxisAbbreviation::lat) { axisName = AxisName::Latitude; } else if (abbreviation == AxisAbbreviation::lon) { axisName = AxisName::Longitude; } } else { axisName = CoordinateSystemAxis::normalizeAxisName(axisDesignation); if (axisName == AxisName::Latitude) { abbreviation = AxisAbbreviation::lat; } else if (axisName == AxisName::Longitude) { abbreviation = AxisAbbreviation::lon; } else if (axisName == AxisName::Ellipsoidal_height) { abbreviation = AxisAbbreviation::h; } } const std::string &dirString = children[1]->GP()->value(); const AxisDirection *direction = AxisDirection::valueOf(dirString); // WKT2, geocentric CS: axis names are omitted if (axisName.empty()) { if (direction == &AxisDirection::GEOCENTRIC_X && abbreviation == AxisAbbreviation::X) { axisName = AxisName::Geocentric_X; } else if (direction == &AxisDirection::GEOCENTRIC_Y && abbreviation == AxisAbbreviation::Y) { axisName = AxisName::Geocentric_Y; } else if (direction == &AxisDirection::GEOCENTRIC_Z && abbreviation == AxisAbbreviation::Z) { axisName = AxisName::Geocentric_Z; } } // WKT1 if (!direction && isGeocentric && axisName == AxisName::Geocentric_X) { abbreviation = AxisAbbreviation::X; direction = &AxisDirection::GEOCENTRIC_X; } else if (!direction && isGeocentric && axisName == AxisName::Geocentric_Y) { abbreviation = AxisAbbreviation::Y; direction = &AxisDirection::GEOCENTRIC_Y; } else if (isGeocentric && axisName == AxisName::Geocentric_Z && (dirString == AxisDirectionWKT1::NORTH.toString() || dirString == AxisDirectionWKT1::OTHER.toString())) { abbreviation = AxisAbbreviation::Z; direction = &AxisDirection::GEOCENTRIC_Z; } else if (dirString == AxisDirectionWKT1::OTHER.toString()) { direction = &AxisDirection::UNSPECIFIED; } else if (dirString == "UNKNOWN") { // Found in WKT1 of NSIDC's EASE-Grid Sea Ice Age datasets. // Cf https://github.com/OSGeo/gdal/issues/7210 emitRecoverableWarning("UNKNOWN is not a valid direction name."); direction = &AxisDirection::UNSPECIFIED; } if (!direction) { throw ParsingException( concat("unhandled axis direction: ", children[1]->GP()->value())); } UnitOfMeasure unit(buildUnitInSubNode(node)); if (unit == UnitOfMeasure::NONE) { // If no unit in the AXIS node, use the one potentially coming from // the CS. unit = unitIn; if (unit == UnitOfMeasure::NONE && unitType != UnitOfMeasure::Type::NONE && unitType != UnitOfMeasure::Type::TIME) { ThrowParsingExceptionMissingUNIT(); } } auto &meridianNode = nodeP->lookForChild(WKTConstants::MERIDIAN); util::optional<double> minVal; auto &axisMinValueNode = nodeP->lookForChild(WKTConstants::AXISMINVALUE); if (!isNull(axisMinValueNode)) { const auto &axisMinValueNodeChildren = axisMinValueNode->GP()->children(); if (axisMinValueNodeChildren.size() != 1) { ThrowNotEnoughChildren(WKTConstants::AXISMINVALUE); } const auto &val = axisMinValueNodeChildren[0]; try { minVal = asDouble(val); } catch (const std::exception &) { throw ParsingException(concat( "buildAxis: invalid AXISMINVALUE value: ", val->GP()->value())); } } util::optional<double> maxVal; auto &axisMaxValueNode = nodeP->lookForChild(WKTConstants::AXISMAXVALUE); if (!isNull(axisMaxValueNode)) { const auto &axisMaxValueNodeChildren = axisMaxValueNode->GP()->children(); if (axisMaxValueNodeChildren.size() != 1) { ThrowNotEnoughChildren(WKTConstants::AXISMAXVALUE); } const auto &val = axisMaxValueNodeChildren[0]; try { maxVal = asDouble(val); } catch (const std::exception &) { throw ParsingException(concat( "buildAxis: invalid AXISMAXVALUE value: ", val->GP()->value())); } } util::optional<RangeMeaning> rangeMeaning; auto &rangeMeaningNode = nodeP->lookForChild(WKTConstants::RANGEMEANING); if (!isNull(rangeMeaningNode)) { const auto &rangeMeaningNodeChildren = rangeMeaningNode->GP()->children(); if (rangeMeaningNodeChildren.size() != 1) { ThrowNotEnoughChildren(WKTConstants::RANGEMEANING); } const std::string &val = rangeMeaningNodeChildren[0]->GP()->value(); const RangeMeaning *meaning = RangeMeaning::valueOf(val); if (meaning == nullptr) { throw ParsingException( concat("buildAxis: invalid RANGEMEANING value: ", val)); } rangeMeaning = util::optional<RangeMeaning>(*meaning); } return CoordinateSystemAxis::create( buildProperties(node).set(IdentifiedObject::NAME_KEY, axisName), abbreviation, *direction, unit, minVal, maxVal, rangeMeaning, !isNull(meridianNode) ? buildMeridian(meridianNode).as_nullable() : nullptr); } // --------------------------------------------------------------------------- static const PropertyMap emptyPropertyMap{}; // --------------------------------------------------------------------------- PROJ_NO_RETURN static void ThrowParsingException(const std::string &msg) { throw ParsingException(msg); } // --------------------------------------------------------------------------- static ParsingException buildParsingExceptionInvalidAxisCount(const std::string &csType) { return ParsingException( concat("buildCS: invalid CS axis count for ", csType)); } // --------------------------------------------------------------------------- void WKTParser::Private::emitRecoverableMissingUNIT( const std::string &parentNodeName, const UnitOfMeasure &fallbackUnit) { std::string msg("buildCS: missing UNIT in "); msg += parentNodeName; if (!strict_ && fallbackUnit == UnitOfMeasure::METRE) { msg += ". Assuming metre"; } else if (!strict_ && fallbackUnit == UnitOfMeasure::DEGREE) { msg += ". Assuming degree"; } emitRecoverableWarning(msg); } // --------------------------------------------------------------------------- CoordinateSystemNNPtr WKTParser::Private::buildCS(const WKTNodeNNPtr &node, /* maybe null */ const WKTNodeNNPtr &parentNode, const UnitOfMeasure &defaultAngularUnit) { bool isGeocentric = false; std::string csType; const int numberOfAxis = parentNode->countChildrenOfName(WKTConstants::AXIS); int axisCount = numberOfAxis; const auto &parentNodeName = parentNode->GP()->value(); if (!isNull(node)) { const auto *nodeP = node->GP(); const auto &children = nodeP->children(); if (children.size() < 2) { ThrowNotEnoughChildren(nodeP->value()); } csType = children[0]->GP()->value(); try { axisCount = std::stoi(children[1]->GP()->value()); } catch (const std::exception &) { ThrowParsingException(concat("buildCS: invalid CS axis count: ", children[1]->GP()->value())); } } else { const char *csTypeCStr = ""; if (ci_equal(parentNodeName, WKTConstants::GEOCCS)) { csTypeCStr = CartesianCS::WKT2_TYPE; isGeocentric = true; if (axisCount == 0) { auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR); if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure::METRE; emitRecoverableMissingUNIT(parentNodeName, unit); } return CartesianCS::createGeocentric(unit); } } else if (ci_equal(parentNodeName, WKTConstants::GEOGCS)) { csTypeCStr = EllipsoidalCS::WKT2_TYPE; if (axisCount == 0) { // Missing axis with GEOGCS ? Presumably Long/Lat order // implied auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::ANGULAR); if (unit == UnitOfMeasure::NONE) { unit = defaultAngularUnit; emitRecoverableMissingUNIT(parentNodeName, unit); } // ESRI WKT for geographic 3D CRS auto &linUnitNode = parentNode->GP()->lookForChild(WKTConstants::LINUNIT); if (!isNull(linUnitNode)) { return EllipsoidalCS:: createLongitudeLatitudeEllipsoidalHeight( unit, buildUnit(linUnitNode, UnitOfMeasure::Type::LINEAR)); } // WKT1 --> long/lat return EllipsoidalCS::createLongitudeLatitude(unit); } } else if (ci_equal(parentNodeName, WKTConstants::BASEGEODCRS) || ci_equal(parentNodeName, WKTConstants::BASEGEOGCRS)) { csTypeCStr = EllipsoidalCS::WKT2_TYPE; if (axisCount == 0) { auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::ANGULAR); if (unit == UnitOfMeasure::NONE) { unit = defaultAngularUnit; } // WKT2 --> presumably lat/long return EllipsoidalCS::createLatitudeLongitude(unit); } } else if (ci_equal(parentNodeName, WKTConstants::PROJCS) || ci_equal(parentNodeName, WKTConstants::BASEPROJCRS) || ci_equal(parentNodeName, WKTConstants::BASEENGCRS)) { csTypeCStr = CartesianCS::WKT2_TYPE; if (axisCount == 0) { auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR); if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure::METRE; if (ci_equal(parentNodeName, WKTConstants::PROJCS)) { emitRecoverableMissingUNIT(parentNodeName, unit); } } return CartesianCS::createEastingNorthing(unit); } } else if (ci_equal(parentNodeName, WKTConstants::VERT_CS) || ci_equal(parentNodeName, WKTConstants::VERTCS) || ci_equal(parentNodeName, WKTConstants::BASEVERTCRS)) { csTypeCStr = VerticalCS::WKT2_TYPE; bool downDirection = false; if (ci_equal(parentNodeName, WKTConstants::VERTCS)) // ESRI { for (const auto &childNode : parentNode->GP()->children()) { const auto &childNodeChildren = childNode->GP()->children(); if (childNodeChildren.size() == 2 && ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER) && childNodeChildren[0]->GP()->value() == "\"Direction\"") { const auto &paramValue = childNodeChildren[1]->GP()->value(); try { double val = asDouble(childNodeChildren[1]); if (val == 1.0) { // ok } else if (val == -1.0) { downDirection = true; } } catch (const std::exception &) { throw ParsingException( concat("unhandled parameter value type : ", paramValue)); } } } } if (axisCount == 0) { auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR); if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure::METRE; if (ci_equal(parentNodeName, WKTConstants::VERT_CS) || ci_equal(parentNodeName, WKTConstants::VERTCS)) { emitRecoverableMissingUNIT(parentNodeName, unit); } } if (downDirection) { return VerticalCS::create( util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, "depth"), "D", AxisDirection::DOWN, unit)); } return VerticalCS::createGravityRelatedHeight(unit); } } else if (ci_equal(parentNodeName, WKTConstants::LOCAL_CS)) { if (axisCount == 0) { auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR); if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure::METRE; } return CartesianCS::createEastingNorthing(unit); } else if (axisCount == 1) { csTypeCStr = VerticalCS::WKT2_TYPE; } else if (axisCount == 2 || axisCount == 3) { csTypeCStr = CartesianCS::WKT2_TYPE; } else { throw ParsingException( "buildCS: unexpected AXIS count for LOCAL_CS"); } } else if (ci_equal(parentNodeName, WKTConstants::BASEPARAMCRS)) { csTypeCStr = ParametricCS::WKT2_TYPE; if (axisCount == 0) { auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR); if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure("unknown", 1, UnitOfMeasure::Type::PARAMETRIC); } return ParametricCS::create( emptyPropertyMap, CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unknown parametric"), std::string(), AxisDirection::UNSPECIFIED, unit)); } } else if (ci_equal(parentNodeName, WKTConstants::BASETIMECRS)) { csTypeCStr = TemporalCS::WKT2_2015_TYPE; if (axisCount == 0) { auto unit = buildUnitInSubNode(parentNode, UnitOfMeasure::Type::TIME); if (unit == UnitOfMeasure::NONE) { unit = UnitOfMeasure("unknown", 1, UnitOfMeasure::Type::TIME); } return DateTimeTemporalCS::create( emptyPropertyMap, CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unknown temporal"), std::string(), AxisDirection::FUTURE, unit)); } } else { // Shouldn't happen normally throw ParsingException( concat("buildCS: unexpected parent node: ", parentNodeName)); } csType = csTypeCStr; } if (axisCount != 1 && axisCount != 2 && axisCount != 3) { throw buildParsingExceptionInvalidAxisCount(csType); } if (numberOfAxis != axisCount) { throw ParsingException("buildCS: declared number of axis by CS node " "and number of AXIS are inconsistent"); } const auto unitType = ci_equal(csType, EllipsoidalCS::WKT2_TYPE) ? UnitOfMeasure::Type::ANGULAR : ci_equal(csType, OrdinalCS::WKT2_TYPE) ? UnitOfMeasure::Type::NONE : ci_equal(csType, ParametricCS::WKT2_TYPE) ? UnitOfMeasure::Type::PARAMETRIC : ci_equal(csType, CartesianCS::WKT2_TYPE) || ci_equal(csType, VerticalCS::WKT2_TYPE) || ci_equal(csType, AffineCS::WKT2_TYPE) ? UnitOfMeasure::Type::LINEAR : (ci_equal(csType, TemporalCS::WKT2_2015_TYPE) || ci_equal(csType, DateTimeTemporalCS::WKT2_2019_TYPE) || ci_equal(csType, TemporalCountCS::WKT2_2019_TYPE) || ci_equal(csType, TemporalMeasureCS::WKT2_2019_TYPE)) ? UnitOfMeasure::Type::TIME : UnitOfMeasure::Type::UNKNOWN; UnitOfMeasure unit = buildUnitInSubNode(parentNode, unitType); if (unit == UnitOfMeasure::NONE) { if (ci_equal(parentNodeName, WKTConstants::VERT_CS) || ci_equal(parentNodeName, WKTConstants::VERTCS)) { unit = UnitOfMeasure::METRE; emitRecoverableMissingUNIT(parentNodeName, unit); } } std::vector<CoordinateSystemAxisNNPtr> axisList; for (int i = 0; i < axisCount; i++) { axisList.emplace_back( buildAxis(parentNode->GP()->lookForChild(WKTConstants::AXIS, i), unit, unitType, isGeocentric, i + 1)); } const PropertyMap &csMap = emptyPropertyMap; if (ci_equal(csType, EllipsoidalCS::WKT2_TYPE)) { if (axisCount == 2) { return EllipsoidalCS::create(csMap, axisList[0], axisList[1]); } else if (axisCount == 3) { return EllipsoidalCS::create(csMap, axisList[0], axisList[1], axisList[2]); } } else if (ci_equal(csType, CartesianCS::WKT2_TYPE)) { if (axisCount == 2) { return CartesianCS::create(csMap, axisList[0], axisList[1]); } else if (axisCount == 3) { return CartesianCS::create(csMap, axisList[0], axisList[1], axisList[2]); } } else if (ci_equal(csType, AffineCS::WKT2_TYPE)) { if (axisCount == 2) { return AffineCS::create(csMap, axisList[0], axisList[1]); } else if (axisCount == 3) { return AffineCS::create(csMap, axisList[0], axisList[1], axisList[2]); } } else if (ci_equal(csType, VerticalCS::WKT2_TYPE)) { if (axisCount == 1) { return VerticalCS::create(csMap, axisList[0]); } } else if (ci_equal(csType, SphericalCS::WKT2_TYPE)) { if (axisCount == 2) { // Extension to ISO19111 to support (planet)-ocentric CS with // geocentric latitude return SphericalCS::create(csMap, axisList[0], axisList[1]); } else if (axisCount == 3) { return SphericalCS::create(csMap, axisList[0], axisList[1], axisList[2]); } } else if (ci_equal(csType, OrdinalCS::WKT2_TYPE)) { // WKT2-2019 return OrdinalCS::create(csMap, axisList); } else if (ci_equal(csType, ParametricCS::WKT2_TYPE)) { if (axisCount == 1) { return ParametricCS::create(csMap, axisList[0]); } } else if (ci_equal(csType, TemporalCS::WKT2_2015_TYPE)) { if (axisCount == 1) { if (isNull( parentNode->GP()->lookForChild(WKTConstants::TIMEUNIT)) && isNull(parentNode->GP()->lookForChild(WKTConstants::UNIT))) { return DateTimeTemporalCS::create(csMap, axisList[0]); } else { // Default to TemporalMeasureCS // TemporalCount could also be possible return TemporalMeasureCS::create(csMap, axisList[0]); } } } else if (ci_equal(csType, DateTimeTemporalCS::WKT2_2019_TYPE)) { if (axisCount == 1) { return DateTimeTemporalCS::create(csMap, axisList[0]); } } else if (ci_equal(csType, TemporalCountCS::WKT2_2019_TYPE)) { if (axisCount == 1) { return TemporalCountCS::create(csMap, axisList[0]); } } else if (ci_equal(csType, TemporalMeasureCS::WKT2_2019_TYPE)) { if (axisCount == 1) { return TemporalMeasureCS::create(csMap, axisList[0]); } } else { throw ParsingException(concat("unhandled CS type: ", csType)); } throw buildParsingExceptionInvalidAxisCount(csType); } // --------------------------------------------------------------------------- std::string WKTParser::Private::getExtensionProj4(const WKTNode::Private *nodeP) { auto &extensionNode = nodeP->lookForChild(WKTConstants::EXTENSION); const auto &extensionChildren = extensionNode->GP()->children(); if (extensionChildren.size() == 2) { if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4")) { return stripQuotes(extensionChildren[1]); } } return std::string(); } // --------------------------------------------------------------------------- void WKTParser::Private::addExtensionProj4ToProp(const WKTNode::Private *nodeP, PropertyMap &props) { const auto extensionProj4(getExtensionProj4(nodeP)); if (!extensionProj4.empty()) { props.set("EXTENSION_PROJ4", extensionProj4); } } // --------------------------------------------------------------------------- GeodeticCRSNNPtr WKTParser::Private::buildGeodeticCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &datumNode = nodeP->lookForChild( WKTConstants::DATUM, WKTConstants::GEODETICDATUM, WKTConstants::TRF); auto &ensembleNode = nodeP->lookForChild(WKTConstants::ENSEMBLE); if (isNull(datumNode) && isNull(ensembleNode)) { throw ParsingException("Missing DATUM or ENSEMBLE node"); } // Do that now so that esriStyle_ can be set before buildPrimeMeridian() auto props = buildProperties(node); auto &dynamicNode = nodeP->lookForChild(WKTConstants::DYNAMIC); auto &csNode = nodeP->lookForChild(WKTConstants::CS_); const auto &nodeName = nodeP->value(); if (isNull(csNode) && !ci_equal(nodeName, WKTConstants::GEOGCS) && !ci_equal(nodeName, WKTConstants::GEOCCS) && !ci_equal(nodeName, WKTConstants::BASEGEODCRS) && !ci_equal(nodeName, WKTConstants::BASEGEOGCRS)) { ThrowMissing(WKTConstants::CS_); } auto &primeMeridianNode = nodeP->lookForChild(WKTConstants::PRIMEM, WKTConstants::PRIMEMERIDIAN); if (isNull(primeMeridianNode)) { // PRIMEM is required in WKT1 if (ci_equal(nodeName, WKTConstants::GEOGCS) || ci_equal(nodeName, WKTConstants::GEOCCS)) { emitRecoverableWarning(nodeName + " should have a PRIMEM node"); } } auto angularUnit = buildUnitInSubNode(node, ci_equal(nodeName, WKTConstants::GEOGCS) ? UnitOfMeasure::Type::ANGULAR : UnitOfMeasure::Type::UNKNOWN); if (angularUnit.type() != UnitOfMeasure::Type::ANGULAR) { angularUnit = UnitOfMeasure::NONE; } auto primeMeridian = !isNull(primeMeridianNode) ? buildPrimeMeridian(primeMeridianNode, angularUnit) : PrimeMeridian::GREENWICH; if (angularUnit == UnitOfMeasure::NONE) { angularUnit = primeMeridian->longitude().unit(); } addExtensionProj4ToProp(nodeP, props); // No explicit AXIS node ? (WKT1) if (isNull(nodeP->lookForChild(WKTConstants::AXIS))) { props.set("IMPLICIT_CS", true); } const std::string crsName = stripQuotes(nodeP->children()[0]); if (esriStyle_ && dbContext_) { std::string outTableName; std::string authNameFromAlias; std::string codeFromAlias; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); auto officialName = authFactory->getOfficialNameFromAlias( crsName, "geodetic_crs", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { props.set(IdentifiedObject::NAME_KEY, officialName); } } auto datum = !isNull(datumNode) ? buildGeodeticReferenceFrame(datumNode, primeMeridian, dynamicNode) .as_nullable() : nullptr; auto datumEnsemble = !isNull(ensembleNode) ? buildDatumEnsemble(ensembleNode, primeMeridian, true) .as_nullable() : nullptr; auto cs = buildCS(csNode, node, angularUnit); // If there's no CS[] node, typically for a BASEGEODCRS of a projected CRS, // in a few rare cases, this might be a Geocentric CRS, and thus a // Cartesian CS, and not the ellipsoidalCS we assumed above. The only way // to figure that is to resolve the CRS from its code... if (isNull(csNode) && dbContext_ && ci_equal(nodeName, WKTConstants::BASEGEODCRS)) { const auto &nodeChildren = nodeP->children(); for (const auto &subNode : nodeChildren) { const auto &subNodeName(subNode->GP()->value()); if (ci_equal(subNodeName, WKTConstants::ID) || ci_equal(subNodeName, WKTConstants::AUTHORITY)) { auto id = buildId(subNode, true, false); if (id) { try { auto authFactory = AuthorityFactory::create( NN_NO_CHECK(dbContext_), *id->codeSpace()); auto dbCRS = authFactory->createGeodeticCRS(id->code()); cs = dbCRS->coordinateSystem(); } catch (const util::Exception &) { } } } } } auto ellipsoidalCS = nn_dynamic_pointer_cast<EllipsoidalCS>(cs); if (ellipsoidalCS) { if (ci_equal(nodeName, WKTConstants::GEOCCS)) { throw ParsingException("ellipsoidal CS not expected in GEOCCS"); } try { auto crs = GeographicCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(ellipsoidalCS)); // In case of missing CS node, or to check it, query the coordinate // system from the DB if possible (typically for the baseCRS of a // ProjectedCRS) if (!crs->identifiers().empty() && dbContext_) { GeographicCRSPtr dbCRS; try { const auto &id = crs->identifiers()[0]; auto authFactory = AuthorityFactory::create( NN_NO_CHECK(dbContext_), *id->codeSpace()); dbCRS = authFactory->createGeographicCRS(id->code()) .as_nullable(); } catch (const util::Exception &) { } if (dbCRS && (!isNull(csNode) || node->countChildrenOfName(WKTConstants::AXIS) != 0) && !ellipsoidalCS->_isEquivalentTo( dbCRS->coordinateSystem().get(), util::IComparable::Criterion::EQUIVALENT)) { if (unsetIdentifiersIfIncompatibleDef_) { emitRecoverableWarning( "Coordinate system of GeographicCRS in the WKT " "definition is different from the one of the " "authority. Unsetting the identifier to avoid " "confusion"); props.unset(Identifier::CODESPACE_KEY); props.unset(Identifier::AUTHORITY_KEY); props.unset(IdentifiedObject::IDENTIFIERS_KEY); } crs = GeographicCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(ellipsoidalCS)); } else if (dbCRS) { auto csFromDB = dbCRS->coordinateSystem(); auto csFromDBAltered = csFromDB; if (!isNull(nodeP->lookForChild(WKTConstants::UNIT))) { csFromDBAltered = csFromDB->alterAngularUnit(angularUnit); if (unsetIdentifiersIfIncompatibleDef_ && !csFromDBAltered->_isEquivalentTo( csFromDB.get(), util::IComparable::Criterion::EQUIVALENT)) { emitRecoverableWarning( "Coordinate system of GeographicCRS in the WKT " "definition is different from the one of the " "authority. Unsetting the identifier to avoid " "confusion"); props.unset(Identifier::CODESPACE_KEY); props.unset(Identifier::AUTHORITY_KEY); props.unset(IdentifiedObject::IDENTIFIERS_KEY); } } crs = GeographicCRS::create(props, datum, datumEnsemble, csFromDBAltered); } } return crs; } catch (const util::Exception &e) { throw ParsingException(std::string("buildGeodeticCRS: ") + e.what()); } } else if (ci_equal(nodeName, WKTConstants::GEOGCRS) || ci_equal(nodeName, WKTConstants::GEOGRAPHICCRS) || ci_equal(nodeName, WKTConstants::BASEGEOGCRS)) { // This is a WKT2-2019 GeographicCRS. An ellipsoidal CS is expected throw ParsingException(concat("ellipsoidal CS expected, but found ", cs->getWKT2Type(true))); } auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs); if (cartesianCS) { if (cartesianCS->axisList().size() != 3) { throw ParsingException( "Cartesian CS for a GeodeticCRS should have 3 axis"); } try { return GeodeticCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(cartesianCS)); } catch (const util::Exception &e) { throw ParsingException(std::string("buildGeodeticCRS: ") + e.what()); } } auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs); if (sphericalCS) { try { return GeodeticCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(sphericalCS)); } catch (const util::Exception &e) { throw ParsingException(std::string("buildGeodeticCRS: ") + e.what()); } } throw ParsingException( concat("unhandled CS type: ", cs->getWKT2Type(true))); } // --------------------------------------------------------------------------- CRSNNPtr WKTParser::Private::buildDerivedGeodeticCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &baseGeodCRSNode = nodeP->lookForChild(WKTConstants::BASEGEODCRS, WKTConstants::BASEGEOGCRS); // given the constraints enforced on calling code path assert(!isNull(baseGeodCRSNode)); auto baseGeodCRS = buildGeodeticCRS(baseGeodCRSNode); auto &derivingConversionNode = nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION); if (isNull(derivingConversionNode)) { ThrowMissing(WKTConstants::DERIVINGCONVERSION); } auto derivingConversion = buildConversion( derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE); auto &csNode = nodeP->lookForChild(WKTConstants::CS_); if (isNull(csNode)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, node, UnitOfMeasure::NONE); auto ellipsoidalCS = nn_dynamic_pointer_cast<EllipsoidalCS>(cs); if (ellipsoidalCS) { if (ellipsoidalCS->axisList().size() == 3 && baseGeodCRS->coordinateSystem()->axisList().size() == 2) { baseGeodCRS = NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>( baseGeodCRS->promoteTo3D(std::string(), dbContext_))); } return DerivedGeographicCRS::create(buildProperties(node), baseGeodCRS, derivingConversion, NN_NO_CHECK(ellipsoidalCS)); } else if (ci_equal(nodeP->value(), WKTConstants::GEOGCRS)) { // This is a WKT2-2019 GeographicCRS. An ellipsoidal CS is expected throw ParsingException(concat("ellipsoidal CS expected, but found ", cs->getWKT2Type(true))); } auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs); if (cartesianCS) { if (cartesianCS->axisList().size() != 3) { throw ParsingException( "Cartesian CS for a GeodeticCRS should have 3 axis"); } return DerivedGeodeticCRS::create(buildProperties(node), baseGeodCRS, derivingConversion, NN_NO_CHECK(cartesianCS)); } auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs); if (sphericalCS) { return DerivedGeodeticCRS::create(buildProperties(node), baseGeodCRS, derivingConversion, NN_NO_CHECK(sphericalCS)); } throw ParsingException( concat("unhandled CS type: ", cs->getWKT2Type(true))); } // --------------------------------------------------------------------------- UnitOfMeasure WKTParser::Private::guessUnitForParameter( const std::string &paramName, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit) { UnitOfMeasure unit; // scale must be first because of 'Scale factor on pseudo standard parallel' if (ci_find(paramName, "scale") != std::string::npos || ci_find(paramName, "scaling factor") != std::string::npos) { unit = UnitOfMeasure::SCALE_UNITY; } else if (ci_find(paramName, "latitude") != std::string::npos || ci_find(paramName, "longitude") != std::string::npos || ci_find(paramName, "meridian") != std::string::npos || ci_find(paramName, "parallel") != std::string::npos || ci_find(paramName, "azimuth") != std::string::npos || ci_find(paramName, "angle") != std::string::npos || ci_find(paramName, "heading") != std::string::npos || ci_find(paramName, "rotation") != std::string::npos) { unit = defaultAngularUnit; } else if (ci_find(paramName, "easting") != std::string::npos || ci_find(paramName, "northing") != std::string::npos || ci_find(paramName, "height") != std::string::npos) { unit = defaultLinearUnit; } return unit; } // --------------------------------------------------------------------------- static bool isEPSGCodeForInterpolationParameter(const OperationParameterNNPtr &parameter) { const auto &name = parameter->nameStr(); const auto epsgCode = parameter->getEPSGCode(); return name == EPSG_NAME_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS || epsgCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS || name == EPSG_NAME_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS || epsgCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS; } // --------------------------------------------------------------------------- static bool isIntegerParameter(const OperationParameterNNPtr &parameter) { return isEPSGCodeForInterpolationParameter(parameter); } // --------------------------------------------------------------------------- void WKTParser::Private::consumeParameters( const WKTNodeNNPtr &node, bool isAbridged, std::vector<OperationParameterNNPtr> &parameters, std::vector<ParameterValueNNPtr> &values, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit) { for (const auto &childNode : node->GP()->children()) { const auto &childNodeChildren = childNode->GP()->children(); if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) { if (childNodeChildren.size() < 2) { ThrowNotEnoughChildren(childNode->GP()->value()); } parameters.push_back( OperationParameter::create(buildProperties(childNode))); const auto &paramValue = childNodeChildren[1]->GP()->value(); if (!paramValue.empty() && paramValue[0] == '"') { values.push_back( ParameterValue::create(stripQuotes(childNodeChildren[1]))); } else { try { double val = asDouble(childNodeChildren[1]); auto unit = buildUnitInSubNode(childNode); if (unit == UnitOfMeasure::NONE) { const auto &paramName = childNodeChildren[0]->GP()->value(); unit = guessUnitForParameter( paramName, defaultLinearUnit, defaultAngularUnit); } if (isAbridged) { const auto &paramName = parameters.back()->nameStr(); int paramEPSGCode = 0; const auto &paramIds = parameters.back()->identifiers(); if (paramIds.size() == 1 && ci_equal(*(paramIds[0]->codeSpace()), Identifier::EPSG)) { paramEPSGCode = ::atoi(paramIds[0]->code().c_str()); } const common::UnitOfMeasure *pUnit = nullptr; if (OperationParameterValue::convertFromAbridged( paramName, val, pUnit, paramEPSGCode)) { unit = *pUnit; parameters.back() = OperationParameter::create( buildProperties(childNode) .set(Identifier::CODESPACE_KEY, Identifier::EPSG) .set(Identifier::CODE_KEY, paramEPSGCode)); } } if (isIntegerParameter(parameters.back())) { values.push_back(ParameterValue::create( std::stoi(childNodeChildren[1]->GP()->value()))); } else { values.push_back( ParameterValue::create(Measure(val, unit))); } } catch (const std::exception &) { throw ParsingException(concat( "unhandled parameter value type : ", paramValue)); } } } else if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETERFILE)) { if (childNodeChildren.size() < 2) { ThrowNotEnoughChildren(childNode->GP()->value()); } parameters.push_back( OperationParameter::create(buildProperties(childNode))); values.push_back(ParameterValue::createFilename( stripQuotes(childNodeChildren[1]))); } } } // --------------------------------------------------------------------------- static CRSPtr dealWithEPSGCodeForInterpolationCRSParameter( DatabaseContextPtr &dbContext, std::vector<OperationParameterNNPtr> &parameters, std::vector<ParameterValueNNPtr> &values); ConversionNNPtr WKTParser::Private::buildConversion(const WKTNodeNNPtr &node, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit) { auto &methodNode = node->GP()->lookForChild(WKTConstants::METHOD, WKTConstants::PROJECTION); if (isNull(methodNode)) { ThrowMissing(WKTConstants::METHOD); } if (methodNode->GP()->childrenSize() == 0) { ThrowNotEnoughChildren(WKTConstants::METHOD); } std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; consumeParameters(node, false, parameters, values, defaultLinearUnit, defaultAngularUnit); auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter( dbContext_, parameters, values); auto &convProps = buildProperties(node); auto &methodProps = buildProperties(methodNode); std::string convName; std::string methodName; if (convProps.getStringValue(IdentifiedObject::NAME_KEY, convName) && methodProps.getStringValue(IdentifiedObject::NAME_KEY, methodName) && starts_with(convName, "Inverse of ") && starts_with(methodName, "Inverse of ")) { auto &invConvProps = buildProperties(node, true); auto &invMethodProps = buildProperties(methodNode, true); auto conv = NN_NO_CHECK(util::nn_dynamic_pointer_cast<Conversion>( Conversion::create(invConvProps, invMethodProps, parameters, values) ->inverse())); if (interpolationCRS) conv->setInterpolationCRS(interpolationCRS); return conv; } auto conv = Conversion::create(convProps, methodProps, parameters, values); if (interpolationCRS) conv->setInterpolationCRS(interpolationCRS); return conv; } // --------------------------------------------------------------------------- static CRSPtr dealWithEPSGCodeForInterpolationCRSParameter( DatabaseContextPtr &dbContext, std::vector<OperationParameterNNPtr> &parameters, std::vector<ParameterValueNNPtr> &values) { // Transform EPSG hacky PARAMETER["EPSG code for Interpolation CRS", // crs_epsg_code] into proper interpolation CRS if (dbContext != nullptr) { for (size_t i = 0; i < parameters.size(); ++i) { if (isEPSGCodeForInterpolationParameter(parameters[i])) { const int code = values[i]->integerValue(); try { auto authFactory = AuthorityFactory::create( NN_NO_CHECK(dbContext), Identifier::EPSG); auto interpolationCRS = authFactory ->createGeographicCRS(internal::toString(code)) .as_nullable(); parameters.erase(parameters.begin() + i); values.erase(values.begin() + i); return interpolationCRS; } catch (const util::Exception &) { } } } } return nullptr; } // --------------------------------------------------------------------------- TransformationNNPtr WKTParser::Private::buildCoordinateOperation(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &methodNode = nodeP->lookForChild(WKTConstants::METHOD); if (isNull(methodNode)) { ThrowMissing(WKTConstants::METHOD); } if (methodNode->GP()->childrenSize() == 0) { ThrowNotEnoughChildren(WKTConstants::METHOD); } auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS); if (/*isNull(sourceCRSNode) ||*/ sourceCRSNode->GP()->childrenSize() != 1) { ThrowMissing(WKTConstants::SOURCECRS); } auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]); if (!sourceCRS) { throw ParsingException("Invalid content in SOURCECRS node"); } auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS); if (/*isNull(targetCRSNode) ||*/ targetCRSNode->GP()->childrenSize() != 1) { ThrowMissing(WKTConstants::TARGETCRS); } auto targetCRS = buildCRS(targetCRSNode->GP()->children()[0]); if (!targetCRS) { throw ParsingException("Invalid content in TARGETCRS node"); } auto &interpolationCRSNode = nodeP->lookForChild(WKTConstants::INTERPOLATIONCRS); CRSPtr interpolationCRS; if (/*!isNull(interpolationCRSNode) && */ interpolationCRSNode->GP() ->childrenSize() == 1) { interpolationCRS = buildCRS(interpolationCRSNode->GP()->children()[0]); } std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; const auto &defaultLinearUnit = UnitOfMeasure::NONE; const auto &defaultAngularUnit = UnitOfMeasure::NONE; consumeParameters(node, false, parameters, values, defaultLinearUnit, defaultAngularUnit); if (interpolationCRS == nullptr) interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter( dbContext_, parameters, values); std::vector<PositionalAccuracyNNPtr> accuracies; auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY); if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) { accuracies.push_back(PositionalAccuracy::create( stripQuotes(accuracyNode->GP()->children()[0]))); } return Transformation::create(buildProperties(node), NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), interpolationCRS, buildProperties(methodNode), parameters, values, accuracies); } // --------------------------------------------------------------------------- PointMotionOperationNNPtr WKTParser::Private::buildPointMotionOperation(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &methodNode = nodeP->lookForChild(WKTConstants::METHOD); if (isNull(methodNode)) { ThrowMissing(WKTConstants::METHOD); } if (methodNode->GP()->childrenSize() == 0) { ThrowNotEnoughChildren(WKTConstants::METHOD); } auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS); if (sourceCRSNode->GP()->childrenSize() != 1) { ThrowMissing(WKTConstants::SOURCECRS); } auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]); if (!sourceCRS) { throw ParsingException("Invalid content in SOURCECRS node"); } std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; const auto &defaultLinearUnit = UnitOfMeasure::NONE; const auto &defaultAngularUnit = UnitOfMeasure::NONE; consumeParameters(node, false, parameters, values, defaultLinearUnit, defaultAngularUnit); std::vector<PositionalAccuracyNNPtr> accuracies; auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY); if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) { accuracies.push_back(PositionalAccuracy::create( stripQuotes(accuracyNode->GP()->children()[0]))); } return PointMotionOperation::create( buildProperties(node), NN_NO_CHECK(sourceCRS), buildProperties(methodNode), parameters, values, accuracies); } // --------------------------------------------------------------------------- ConcatenatedOperationNNPtr WKTParser::Private::buildConcatenatedOperation(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS); if (/*isNull(sourceCRSNode) ||*/ sourceCRSNode->GP()->childrenSize() != 1) { ThrowMissing(WKTConstants::SOURCECRS); } auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]); if (!sourceCRS) { throw ParsingException("Invalid content in SOURCECRS node"); } auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS); if (/*isNull(targetCRSNode) ||*/ targetCRSNode->GP()->childrenSize() != 1) { ThrowMissing(WKTConstants::TARGETCRS); } auto targetCRS = buildCRS(targetCRSNode->GP()->children()[0]); if (!targetCRS) { throw ParsingException("Invalid content in TARGETCRS node"); } std::vector<CoordinateOperationNNPtr> operations; for (const auto &childNode : nodeP->children()) { if (ci_equal(childNode->GP()->value(), WKTConstants::STEP)) { if (childNode->GP()->childrenSize() != 1) { throw ParsingException("Invalid content in STEP node"); } auto op = nn_dynamic_pointer_cast<CoordinateOperation>( build(childNode->GP()->children()[0])); if (!op) { throw ParsingException("Invalid content in STEP node"); } operations.emplace_back(NN_NO_CHECK(op)); } } ConcatenatedOperation::fixStepsDirection( NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), operations, dbContext_); std::vector<PositionalAccuracyNNPtr> accuracies; auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY); if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) { accuracies.push_back(PositionalAccuracy::create( stripQuotes(accuracyNode->GP()->children()[0]))); } try { return ConcatenatedOperation::create(buildProperties(node), operations, accuracies); } catch (const InvalidOperation &e) { throw ParsingException( std::string("Cannot build concatenated operation: ") + e.what()); } } // --------------------------------------------------------------------------- bool WKTParser::Private::hasWebMercPROJ4String( const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode) { if (projectionNode->GP()->childrenSize() == 0) { ThrowNotEnoughChildren(WKTConstants::PROJECTION); } const std::string wkt1ProjectionName = stripQuotes(projectionNode->GP()->children()[0]); auto &extensionNode = projCRSNode->lookForChild(WKTConstants::EXTENSION); if (metadata::Identifier::isEquivalentName(wkt1ProjectionName.c_str(), "Mercator_1SP") && projCRSNode->countChildrenOfName("center_latitude") == 0) { // Hack to detect the hacky way of encodign webmerc in GDAL WKT1 // with a EXTENSION["PROJ4", "+proj=merc +a=6378137 +b=6378137 // +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m // +nadgrids=@null +wktext +no_defs"] node if (extensionNode && extensionNode->GP()->childrenSize() == 2 && ci_equal(stripQuotes(extensionNode->GP()->children()[0]), "PROJ4")) { std::string projString = stripQuotes(extensionNode->GP()->children()[1]); if (projString.find("+proj=merc") != std::string::npos && projString.find("+a=6378137") != std::string::npos && projString.find("+b=6378137") != std::string::npos && projString.find("+lon_0=0") != std::string::npos && projString.find("+x_0=0") != std::string::npos && projString.find("+y_0=0") != std::string::npos && projString.find("+nadgrids=@null") != std::string::npos && (projString.find("+lat_ts=") == std::string::npos || projString.find("+lat_ts=0") != std::string::npos) && (projString.find("+k=") == std::string::npos || projString.find("+k=1") != std::string::npos) && (projString.find("+units=") == std::string::npos || projString.find("+units=m") != std::string::npos)) { return true; } } } return false; } // --------------------------------------------------------------------------- static const MethodMapping * selectSphericalOrEllipsoidal(const MethodMapping *mapping, const GeodeticCRSNNPtr &baseGeodCRS) { if (mapping->epsg_code == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL || mapping->epsg_code == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA) { mapping = getMapping( baseGeodCRS->ellipsoid()->isSphere() ? EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL : EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA); } else if (mapping->epsg_code == EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL || mapping->epsg_code == EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA) { mapping = getMapping( baseGeodCRS->ellipsoid()->isSphere() ? EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL : EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA); } else if (mapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL || mapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL) { mapping = getMapping(baseGeodCRS->ellipsoid()->isSphere() ? EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL : EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL); } return mapping; } // --------------------------------------------------------------------------- const ESRIMethodMapping *WKTParser::Private::getESRIMapping( const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue) { const std::string esriProjectionName = stripQuotes(projectionNode->GP()->children()[0]); // Lambert_Conformal_Conic or Krovak may map to different WKT2 methods // depending // on the parameters / their values const auto esriMappings = getMappingsFromESRI(esriProjectionName); if (esriMappings.empty()) { return nullptr; } // Build a map of present parameters for (const auto &childNode : projCRSNode->GP()->children()) { if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) { const auto &childNodeChildren = childNode->GP()->children(); if (childNodeChildren.size() < 2) { ThrowNotEnoughChildren(WKTConstants::PARAMETER); } const std::string parameterName(stripQuotes(childNodeChildren[0])); const auto &paramValue = childNodeChildren[1]->GP()->value(); mapParamNameToValue[parameterName] = paramValue; } } // Compare parameters present with the ones expected in the mapping const ESRIMethodMapping *esriMapping = nullptr; int bestMatchCount = -1; for (const auto &mapping : esriMappings) { int matchCount = 0; int unmatchCount = 0; for (const auto *param = mapping->params; param->esri_name; ++param) { auto iter = mapParamNameToValue.find(param->esri_name); if (iter != mapParamNameToValue.end()) { if (param->wkt2_name == nullptr) { bool ok = true; try { if (io::asDouble(param->fixed_value) == io::asDouble(iter->second)) { matchCount++; } else { ok = false; } } catch (const std::exception &) { ok = false; } if (!ok) { matchCount = -1; break; } } else { matchCount++; } } else if (param->is_fixed_value) { mapParamNameToValue[param->esri_name] = param->fixed_value; } else { unmatchCount++; } } if (matchCount > bestMatchCount && !(maybeEsriStyle_ && unmatchCount >= matchCount)) { esriMapping = mapping; bestMatchCount = matchCount; } } return esriMapping; } // --------------------------------------------------------------------------- ConversionNNPtr WKTParser::Private::buildProjectionFromESRI( const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit, const ESRIMethodMapping *esriMapping, std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue) { std::map<std::string, const char *> mapWKT2NameToESRIName; for (const auto *param = esriMapping->params; param->esri_name; ++param) { if (param->wkt2_name) { mapWKT2NameToESRIName[param->wkt2_name] = param->esri_name; } } const std::string esriProjectionName = stripQuotes(projectionNode->GP()->children()[0]); const char *projectionMethodWkt2Name = esriMapping->wkt2_name; if (ci_equal(esriProjectionName, "Krovak")) { const std::string projCRSName = stripQuotes(projCRSNode->GP()->children()[0]); if (projCRSName.find("_East_North") != std::string::npos) { projectionMethodWkt2Name = EPSG_NAME_METHOD_KROVAK_NORTH_ORIENTED; } } const auto *wkt2_mapping = getMapping(projectionMethodWkt2Name); if (ci_equal(esriProjectionName, "Stereographic")) { try { const auto iterLatitudeOfOrigin = mapParamNameToValue.find("Latitude_Of_Origin"); if (iterLatitudeOfOrigin != mapParamNameToValue.end() && std::fabs(io::asDouble(iterLatitudeOfOrigin->second)) == 90.0) { wkt2_mapping = getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A); } } catch (const std::exception &) { } } assert(wkt2_mapping); wkt2_mapping = selectSphericalOrEllipsoidal(wkt2_mapping, baseGeodCRS); PropertyMap propertiesMethod; propertiesMethod.set(IdentifiedObject::NAME_KEY, wkt2_mapping->wkt2_name); if (wkt2_mapping->epsg_code != 0) { propertiesMethod.set(Identifier::CODE_KEY, wkt2_mapping->epsg_code); propertiesMethod.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; if (wkt2_mapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL && ci_equal(esriProjectionName, "Plate_Carree")) { // Add a fixed Latitude of 1st parallel = 0 so as to have all // parameters expected by Equidistant Cylindrical. mapWKT2NameToESRIName[EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL] = "Standard_Parallel_1"; mapParamNameToValue["Standard_Parallel_1"] = "0"; } else if ((wkt2_mapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A || wkt2_mapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B) && !ci_equal(esriProjectionName, "Rectified_Skew_Orthomorphic_Natural_Origin") && !ci_equal(esriProjectionName, "Rectified_Skew_Orthomorphic_Center")) { // ESRI WKT lacks the angle to skew grid // Take it from the azimuth value mapWKT2NameToESRIName [EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID] = "Azimuth"; } for (int i = 0; wkt2_mapping->params[i] != nullptr; i++) { const auto *paramMapping = wkt2_mapping->params[i]; auto iter = mapWKT2NameToESRIName.find(paramMapping->wkt2_name); if (iter == mapWKT2NameToESRIName.end()) { continue; } const auto &esriParamName = iter->second; auto iter2 = mapParamNameToValue.find(esriParamName); auto mapParamNameToValueEnd = mapParamNameToValue.end(); if (iter2 == mapParamNameToValueEnd) { // In case we don't find a direct match, try the aliases for (iter2 = mapParamNameToValue.begin(); iter2 != mapParamNameToValueEnd; ++iter2) { if (areEquivalentParameters(iter2->first, esriParamName)) { break; } } if (iter2 == mapParamNameToValueEnd) { continue; } } PropertyMap propertiesParameter; propertiesParameter.set(IdentifiedObject::NAME_KEY, paramMapping->wkt2_name); if (paramMapping->epsg_code != 0) { propertiesParameter.set(Identifier::CODE_KEY, paramMapping->epsg_code); propertiesParameter.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } parameters.push_back(OperationParameter::create(propertiesParameter)); try { double val = io::asDouble(iter2->second); auto unit = guessUnitForParameter( paramMapping->wkt2_name, defaultLinearUnit, defaultAngularUnit); values.push_back(ParameterValue::create(Measure(val, unit))); } catch (const std::exception &) { throw ParsingException( concat("unhandled parameter value type : ", iter2->second)); } } return Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, esriProjectionName == "Gauss_Kruger" ? "unnnamed (Gauss Kruger)" : "unnamed"), propertiesMethod, parameters, values) ->identify(); } // --------------------------------------------------------------------------- ConversionNNPtr WKTParser::Private::buildProjectionFromESRI( const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit) { std::map<std::string, std::string, ci_less_struct> mapParamNameToValue; const auto esriMapping = getESRIMapping(projCRSNode, projectionNode, mapParamNameToValue); if (esriMapping == nullptr) { return buildProjectionStandard(baseGeodCRS, projCRSNode, projectionNode, defaultLinearUnit, defaultAngularUnit); } return buildProjectionFromESRI(baseGeodCRS, projCRSNode, projectionNode, defaultLinearUnit, defaultAngularUnit, esriMapping, mapParamNameToValue); } // --------------------------------------------------------------------------- ConversionNNPtr WKTParser::Private::buildProjection( const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit) { if (projectionNode->GP()->childrenSize() == 0) { ThrowNotEnoughChildren(WKTConstants::PROJECTION); } if (esriStyle_ || maybeEsriStyle_) { return buildProjectionFromESRI(baseGeodCRS, projCRSNode, projectionNode, defaultLinearUnit, defaultAngularUnit); } return buildProjectionStandard(baseGeodCRS, projCRSNode, projectionNode, defaultLinearUnit, defaultAngularUnit); } // --------------------------------------------------------------------------- std::string WKTParser::Private::projectionGetParameter(const WKTNodeNNPtr &projCRSNode, const char *paramName) { for (const auto &childNode : projCRSNode->GP()->children()) { if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) { const auto &childNodeChildren = childNode->GP()->children(); if (childNodeChildren.size() == 2 && metadata::Identifier::isEquivalentName( stripQuotes(childNodeChildren[0]).c_str(), paramName)) { return childNodeChildren[1]->GP()->value(); } } } return std::string(); } // --------------------------------------------------------------------------- ConversionNNPtr WKTParser::Private::buildProjectionStandard( const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit, const UnitOfMeasure &defaultAngularUnit) { std::string wkt1ProjectionName = stripQuotes(projectionNode->GP()->children()[0]); std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; bool tryToIdentifyWKT1Method = true; auto &extensionNode = projCRSNode->lookForChild(WKTConstants::EXTENSION); const auto &extensionChildren = extensionNode->GP()->children(); bool gdal_3026_hack = false; if (metadata::Identifier::isEquivalentName(wkt1ProjectionName.c_str(), "Mercator_1SP") && projectionGetParameter(projCRSNode, "center_latitude").empty()) { // Hack for https://trac.osgeo.org/gdal/ticket/3026 std::string lat0( projectionGetParameter(projCRSNode, "latitude_of_origin")); if (!lat0.empty() && lat0 != "0" && lat0 != "0.0") { wkt1ProjectionName = "Mercator_2SP"; gdal_3026_hack = true; } else { // The latitude of origin, which should always be zero, is // missing // in GDAL WKT1, but provisionned in the EPSG Mercator_1SP // definition, // so add it manually. PropertyMap propertiesParameter; propertiesParameter.set(IdentifiedObject::NAME_KEY, "Latitude of natural origin"); propertiesParameter.set(Identifier::CODE_KEY, 8801); propertiesParameter.set(Identifier::CODESPACE_KEY, Identifier::EPSG); parameters.push_back( OperationParameter::create(propertiesParameter)); values.push_back( ParameterValue::create(Measure(0, UnitOfMeasure::DEGREE))); } } else if (metadata::Identifier::isEquivalentName( wkt1ProjectionName.c_str(), "Polar_Stereographic")) { std::map<std::string, Measure> mapParameters; for (const auto &childNode : projCRSNode->GP()->children()) { const auto &childNodeChildren = childNode->GP()->children(); if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER) && childNodeChildren.size() == 2) { const std::string wkt1ParameterName( stripQuotes(childNodeChildren[0])); try { double val = asDouble(childNodeChildren[1]); auto unit = guessUnitForParameter(wkt1ParameterName, defaultLinearUnit, defaultAngularUnit); mapParameters.insert(std::pair<std::string, Measure>( tolower(wkt1ParameterName), Measure(val, unit))); } catch (const std::exception &) { } } } Measure latitudeOfOrigin = mapParameters["latitude_of_origin"]; Measure centralMeridian = mapParameters["central_meridian"]; Measure scaleFactorFromMap = mapParameters["scale_factor"]; Measure scaleFactor((scaleFactorFromMap.unit() == UnitOfMeasure::NONE) ? Measure(1.0, UnitOfMeasure::SCALE_UNITY) : scaleFactorFromMap); Measure falseEasting = mapParameters["false_easting"]; Measure falseNorthing = mapParameters["false_northing"]; if (latitudeOfOrigin.unit() != UnitOfMeasure::NONE && scaleFactor.getSIValue() == 1.0) { return Conversion::createPolarStereographicVariantB( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(latitudeOfOrigin.value(), latitudeOfOrigin.unit()), Angle(centralMeridian.value(), centralMeridian.unit()), Length(falseEasting.value(), falseEasting.unit()), Length(falseNorthing.value(), falseNorthing.unit())); } if (latitudeOfOrigin.unit() != UnitOfMeasure::NONE && std::fabs(std::fabs(latitudeOfOrigin.convertToUnit( UnitOfMeasure::DEGREE)) - 90.0) < 1e-10) { return Conversion::createPolarStereographicVariantA( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(latitudeOfOrigin.value(), latitudeOfOrigin.unit()), Angle(centralMeridian.value(), centralMeridian.unit()), Scale(scaleFactor.value(), scaleFactor.unit()), Length(falseEasting.value(), falseEasting.unit()), Length(falseNorthing.value(), falseNorthing.unit())); } tryToIdentifyWKT1Method = false; // Import GDAL PROJ4 extension nodes } else if (extensionChildren.size() == 2 && ci_equal(stripQuotes(extensionChildren[0]), "PROJ4")) { std::string projString = stripQuotes(extensionChildren[1]); if (starts_with(projString, "+proj=")) { if (projString.find(" +type=crs") == std::string::npos) { projString += " +type=crs"; } try { auto projObj = PROJStringParser().createFromPROJString(projString); auto projObjCrs = nn_dynamic_pointer_cast<ProjectedCRS>(projObj); if (projObjCrs) { return projObjCrs->derivingConversion(); } } catch (const io::ParsingException &) { } } } std::string projectionName(std::move(wkt1ProjectionName)); const MethodMapping *mapping = tryToIdentifyWKT1Method ? getMappingFromWKT1(projectionName) : nullptr; if (!mapping) { // Sometimes non-WKT1:ESRI looking WKT can actually use WKT1:ESRI // projection definitions std::map<std::string, std::string, ci_less_struct> mapParamNameToValue; const auto esriMapping = getESRIMapping(projCRSNode, projectionNode, mapParamNameToValue); if (esriMapping != nullptr) { return buildProjectionFromESRI( baseGeodCRS, projCRSNode, projectionNode, defaultLinearUnit, defaultAngularUnit, esriMapping, mapParamNameToValue); } } if (mapping) { mapping = selectSphericalOrEllipsoidal(mapping, baseGeodCRS); } else if (metadata::Identifier::isEquivalentName( projectionName.c_str(), "Lambert Conformal Conic")) { // Lambert Conformal Conic or Lambert_Conformal_Conic are respectively // used by Oracle WKT and Trimble for either LCC 1SP or 2SP, so we // have to look at parameters to figure out the variant. bool found2ndStdParallel = false; bool foundScaleFactor = false; for (const auto &childNode : projCRSNode->GP()->children()) { if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) { const auto &childNodeChildren = childNode->GP()->children(); if (childNodeChildren.size() < 2) { ThrowNotEnoughChildren(WKTConstants::PARAMETER); } const std::string wkt1ParameterName( stripQuotes(childNodeChildren[0])); if (metadata::Identifier::isEquivalentName( wkt1ParameterName.c_str(), WKT1_STANDARD_PARALLEL_2)) { found2ndStdParallel = true; } else if (metadata::Identifier::isEquivalentName( wkt1ParameterName.c_str(), WKT1_SCALE_FACTOR)) { foundScaleFactor = true; } } } if (found2ndStdParallel && !foundScaleFactor) { mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); } else if (!found2ndStdParallel && foundScaleFactor) { mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); } else if (found2ndStdParallel && foundScaleFactor) { // Not sure if that happens mapping = getMapping( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN); } } // For Krovak, we need to look at axis to decide between the Krovak and // Krovak East-North Oriented methods if (ci_equal(projectionName, "Krovak") && projCRSNode->countChildrenOfName(WKTConstants::AXIS) == 2 && &buildAxis(projCRSNode->GP()->lookForChild(WKTConstants::AXIS, 0), defaultLinearUnit, UnitOfMeasure::Type::LINEAR, false, 1) ->direction() == &AxisDirection::SOUTH && &buildAxis(projCRSNode->GP()->lookForChild(WKTConstants::AXIS, 1), defaultLinearUnit, UnitOfMeasure::Type::LINEAR, false, 2) ->direction() == &AxisDirection::WEST) { mapping = getMapping(EPSG_CODE_METHOD_KROVAK); } PropertyMap propertiesMethod; if (mapping) { projectionName = mapping->wkt2_name; if (mapping->epsg_code != 0) { propertiesMethod.set(Identifier::CODE_KEY, mapping->epsg_code); propertiesMethod.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } } propertiesMethod.set(IdentifiedObject::NAME_KEY, projectionName); std::vector<bool> foundParameters; if (mapping) { size_t countParams = 0; while (mapping->params[countParams] != nullptr) { ++countParams; } foundParameters.resize(countParams); } for (const auto &childNode : projCRSNode->GP()->children()) { if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) { const auto &childNodeChildren = childNode->GP()->children(); if (childNodeChildren.size() < 2) { ThrowNotEnoughChildren(WKTConstants::PARAMETER); } const auto &paramValue = childNodeChildren[1]->GP()->value(); PropertyMap propertiesParameter; const std::string wkt1ParameterName( stripQuotes(childNodeChildren[0])); std::string parameterName(wkt1ParameterName); if (gdal_3026_hack) { if (ci_equal(parameterName, "latitude_of_origin")) { parameterName = "standard_parallel_1"; } else if (ci_equal(parameterName, "scale_factor") && paramValue == "1") { continue; } } auto *paramMapping = mapping ? getMappingFromWKT1(mapping, parameterName) : nullptr; if (mapping && mapping->epsg_code == EPSG_CODE_METHOD_MERCATOR_VARIANT_B && ci_equal(parameterName, "latitude_of_origin")) { // Some illegal formulations of Mercator_2SP have a unexpected // latitude_of_origin parameter. We accept it on import, but // do not accept it when exporting to PROJ string, unless it is // zero. // No need to try to update foundParameters[] as this is a // unexpected one. parameterName = EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN; propertiesParameter.set( Identifier::CODE_KEY, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN); propertiesParameter.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } else if (mapping && paramMapping) { for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) { if (mapping->params[idx] == paramMapping) { foundParameters[idx] = true; break; } } parameterName = paramMapping->wkt2_name; if (paramMapping->epsg_code != 0) { propertiesParameter.set(Identifier::CODE_KEY, paramMapping->epsg_code); propertiesParameter.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } } propertiesParameter.set(IdentifiedObject::NAME_KEY, parameterName); parameters.push_back( OperationParameter::create(propertiesParameter)); try { double val = io::asDouble(paramValue); auto unit = guessUnitForParameter( wkt1ParameterName, defaultLinearUnit, defaultAngularUnit); values.push_back(ParameterValue::create(Measure(val, unit))); } catch (const std::exception &) { throw ParsingException( concat("unhandled parameter value type : ", paramValue)); } } } // Add back important parameters that should normally be present, but // are sometimes missing. Currently we only deal with Scale factor at // natural origin. This is to avoid a default value of 0 to slip in later. // But such WKT should be considered invalid. if (mapping) { for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) { if (!foundParameters[idx] && mapping->params[idx]->epsg_code == EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN) { emitRecoverableWarning( "The WKT string lacks a value " "for " EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN ". Default it to 1."); PropertyMap propertiesParameter; propertiesParameter.set( Identifier::CODE_KEY, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN); propertiesParameter.set(Identifier::CODESPACE_KEY, Identifier::EPSG); propertiesParameter.set( IdentifiedObject::NAME_KEY, EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN); parameters.push_back( OperationParameter::create(propertiesParameter)); values.push_back(ParameterValue::create( Measure(1.0, UnitOfMeasure::SCALE_UNITY))); } } } if (mapping && (mapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A || mapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B)) { // Special case when importing some GDAL WKT of Hotine Oblique Mercator // that have a Azimuth parameter but lacks the Rectified Grid Angle. // We have code in the exportToPROJString() to deal with that situation, // but also adds the rectified grid angle from the azimuth on import. bool foundAngleRecifiedToSkewGrid = false; bool foundAzimuth = false; for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) { if (foundParameters[idx] && mapping->params[idx]->epsg_code == EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID) { foundAngleRecifiedToSkewGrid = true; } else if (foundParameters[idx] && mapping->params[idx]->epsg_code == EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE) { foundAzimuth = true; } } if (!foundAngleRecifiedToSkewGrid && foundAzimuth) { for (size_t idx = 0; idx < parameters.size(); ++idx) { if (parameters[idx]->getEPSGCode() == EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE) { PropertyMap propertiesParameter; propertiesParameter.set( Identifier::CODE_KEY, EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID); propertiesParameter.set(Identifier::CODESPACE_KEY, Identifier::EPSG); propertiesParameter.set( IdentifiedObject::NAME_KEY, EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID); parameters.push_back( OperationParameter::create(propertiesParameter)); values.push_back(values[idx]); } } } } return Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), propertiesMethod, parameters, values) ->identify(); } // --------------------------------------------------------------------------- static ProjectedCRSNNPtr createPseudoMercator(const PropertyMap &props, const cs::CartesianCSNNPtr &cs) { auto conversion = Conversion::createPopularVisualisationPseudoMercator( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(0), Angle(0), Length(0), Length(0)); return ProjectedCRS::create(props, GeographicCRS::EPSG_4326, conversion, cs); } // --------------------------------------------------------------------------- ProjectedCRSNNPtr WKTParser::Private::buildProjectedCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &conversionNode = nodeP->lookForChild(WKTConstants::CONVERSION); auto &projectionNode = nodeP->lookForChild(WKTConstants::PROJECTION); if (isNull(conversionNode) && isNull(projectionNode)) { ThrowMissing(WKTConstants::CONVERSION); } auto &baseGeodCRSNode = nodeP->lookForChild(WKTConstants::BASEGEODCRS, WKTConstants::BASEGEOGCRS, WKTConstants::GEOGCS); if (isNull(baseGeodCRSNode)) { throw ParsingException( "Missing BASEGEODCRS / BASEGEOGCRS / GEOGCS node"); } auto baseGeodCRS = buildGeodeticCRS(baseGeodCRSNode); auto props = buildProperties(node); auto &csNode = nodeP->lookForChild(WKTConstants::CS_); const auto &nodeValue = nodeP->value(); if (isNull(csNode) && !ci_equal(nodeValue, WKTConstants::PROJCS) && !ci_equal(nodeValue, WKTConstants::BASEPROJCRS)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, node, UnitOfMeasure::NONE); auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs); const std::string projCRSName = stripQuotes(nodeP->children()[0]); if (esriStyle_ && dbContext_) { if (cartesianCS) { std::string outTableName; std::string authNameFromAlias; std::string codeFromAlias; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); auto officialName = authFactory->getOfficialNameFromAlias( projCRSName, "projected_crs", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { // Special case for https://github.com/OSGeo/PROJ/issues/2086 // The name of the CRS to identify is // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501 // whereas it should be // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501_Feet constexpr double US_FOOT_CONV_FACTOR = 12.0 / 39.37; if (projCRSName.find("_FIPS_") != std::string::npos && projCRSName.find("_Feet") == std::string::npos && std::fabs( cartesianCS->axisList()[0]->unit().conversionToSI() - US_FOOT_CONV_FACTOR) < 1e-10 * US_FOOT_CONV_FACTOR) { auto officialNameFromFeet = authFactory->getOfficialNameFromAlias( projCRSName + "_Feet", "projected_crs", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialNameFromFeet.empty()) { officialName = std::move(officialNameFromFeet); } } props.set(IdentifiedObject::NAME_KEY, officialName); } } } if (isNull(conversionNode) && hasWebMercPROJ4String(node, projectionNode) && cartesianCS) { toWGS84Parameters_.clear(); return createPseudoMercator(props, NN_NO_CHECK(cartesianCS)); } // WGS_84_Pseudo_Mercator: Particular case for corrupted ESRI WKT generated // by older GDAL versions // https://trac.osgeo.org/gdal/changeset/30732 // WGS_1984_Web_Mercator: deprecated ESRI:102113 if (cartesianCS && (metadata::Identifier::isEquivalentName( projCRSName.c_str(), "WGS_84_Pseudo_Mercator") || metadata::Identifier::isEquivalentName( projCRSName.c_str(), "WGS_1984_Web_Mercator"))) { toWGS84Parameters_.clear(); return createPseudoMercator(props, NN_NO_CHECK(cartesianCS)); } // For WKT2, if there is no explicit parameter unit, use metre for linear // units and degree for angular units const UnitOfMeasure linearUnit( !isNull(conversionNode) ? UnitOfMeasure::METRE : buildUnitInSubNode(node, UnitOfMeasure::Type::LINEAR)); const auto &angularUnit = !isNull(conversionNode) ? UnitOfMeasure::DEGREE : baseGeodCRS->coordinateSystem()->axisList()[0]->unit(); auto conversion = !isNull(conversionNode) ? buildConversion(conversionNode, linearUnit, angularUnit) : buildProjection(baseGeodCRS, node, projectionNode, linearUnit, angularUnit); // No explicit AXIS node ? (WKT1) if (isNull(nodeP->lookForChild(WKTConstants::AXIS))) { props.set("IMPLICIT_CS", true); } if (isNull(csNode) && node->countChildrenOfName(WKTConstants::AXIS) == 0) { const auto methodCode = conversion->method()->getEPSGCode(); // Krovak south oriented ? if (methodCode == EPSG_CODE_METHOD_KROVAK) { cartesianCS = CartesianCS::create( PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Southing), emptyString, AxisDirection::SOUTH, linearUnit), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Westing), emptyString, AxisDirection::WEST, linearUnit)) .as_nullable(); } else if (methodCode == EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A || methodCode == EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA) { // It is likely that the ESRI definition of EPSG:32661 (UPS North) & // EPSG:32761 (UPS South) uses the easting-northing order, instead // of the EPSG northing-easting order. // Same for WKT1_GDAL const double lat0 = conversion->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, common::UnitOfMeasure::DEGREE); if (std::fabs(lat0 - 90) < 1e-10) { cartesianCS = CartesianCS::createNorthPoleEastingSouthNorthingSouth( linearUnit) .as_nullable(); } else if (std::fabs(lat0 - -90) < 1e-10) { cartesianCS = CartesianCS::createSouthPoleEastingNorthNorthingNorth( linearUnit) .as_nullable(); } } else if (methodCode == EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B) { const double lat_ts = conversion->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL, common::UnitOfMeasure::DEGREE); if (lat_ts > 0) { cartesianCS = CartesianCS::createNorthPoleEastingSouthNorthingSouth( linearUnit) .as_nullable(); } else if (lat_ts < 0) { cartesianCS = CartesianCS::createSouthPoleEastingNorthNorthingNorth( linearUnit) .as_nullable(); } } else if (methodCode == EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED) { cartesianCS = CartesianCS::createWestingSouthing(linearUnit).as_nullable(); } } if (!cartesianCS) { ThrowNotExpectedCSType(CartesianCS::WKT2_TYPE); } if (cartesianCS->axisList().size() == 3 && baseGeodCRS->coordinateSystem()->axisList().size() == 2) { baseGeodCRS = NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>( baseGeodCRS->promoteTo3D(std::string(), dbContext_))); } addExtensionProj4ToProp(nodeP, props); return ProjectedCRS::create(props, baseGeodCRS, conversion, NN_NO_CHECK(cartesianCS)); } // --------------------------------------------------------------------------- void WKTParser::Private::parseDynamic(const WKTNodeNNPtr &dynamicNode, double &frameReferenceEpoch, util::optional<std::string> &modelName) { auto &frameEpochNode = dynamicNode->lookForChild(WKTConstants::FRAMEEPOCH); const auto &frameEpochChildren = frameEpochNode->GP()->children(); if (frameEpochChildren.empty()) { ThrowMissing(WKTConstants::FRAMEEPOCH); } try { frameReferenceEpoch = asDouble(frameEpochChildren[0]); } catch (const std::exception &) { throw ParsingException("Invalid FRAMEEPOCH node"); } auto &modelNode = dynamicNode->GP()->lookForChild( WKTConstants::MODEL, WKTConstants::VELOCITYGRID); const auto &modelChildren = modelNode->GP()->children(); if (modelChildren.size() == 1) { modelName = stripQuotes(modelChildren[0]); } } // --------------------------------------------------------------------------- VerticalReferenceFrameNNPtr WKTParser::Private::buildVerticalReferenceFrame( const WKTNodeNNPtr &node, const WKTNodeNNPtr &dynamicNode) { if (!isNull(dynamicNode)) { double frameReferenceEpoch = 0.0; util::optional<std::string> modelName; parseDynamic(dynamicNode, frameReferenceEpoch, modelName); return DynamicVerticalReferenceFrame::create( buildProperties(node), getAnchor(node), optional<RealizationMethod>(), common::Measure(frameReferenceEpoch, common::UnitOfMeasure::YEAR), modelName); } // WKT1 VERT_DATUM has a datum type after the datum name const auto *nodeP = node->GP(); const std::string &name(nodeP->value()); auto &props = buildProperties(node); if (esriStyle_ && dbContext_) { std::string outTableName; std::string authNameFromAlias; std::string codeFromAlias; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); const std::string datumName = stripQuotes(nodeP->children()[0]); auto officialName = authFactory->getOfficialNameFromAlias( datumName, "vertical_datum", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { props.set(IdentifiedObject::NAME_KEY, officialName); } } if (ci_equal(name, WKTConstants::VERT_DATUM)) { const auto &children = nodeP->children(); if (children.size() >= 2) { props.set("VERT_DATUM_TYPE", children[1]->GP()->value()); } } return VerticalReferenceFrame::create(props, getAnchor(node), getAnchorEpoch(node)); } // --------------------------------------------------------------------------- TemporalDatumNNPtr WKTParser::Private::buildTemporalDatum(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &calendarNode = nodeP->lookForChild(WKTConstants::CALENDAR); std::string calendar = TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN; const auto &calendarChildren = calendarNode->GP()->children(); if (calendarChildren.size() == 1) { calendar = stripQuotes(calendarChildren[0]); } auto &timeOriginNode = nodeP->lookForChild(WKTConstants::TIMEORIGIN); std::string originStr; const auto &timeOriginNodeChildren = timeOriginNode->GP()->children(); if (timeOriginNodeChildren.size() == 1) { originStr = stripQuotes(timeOriginNodeChildren[0]); } auto origin = DateTime::create(originStr); return TemporalDatum::create(buildProperties(node), origin, calendar); } // --------------------------------------------------------------------------- EngineeringDatumNNPtr WKTParser::Private::buildEngineeringDatum(const WKTNodeNNPtr &node) { return EngineeringDatum::create(buildProperties(node), getAnchor(node)); } // --------------------------------------------------------------------------- ParametricDatumNNPtr WKTParser::Private::buildParametricDatum(const WKTNodeNNPtr &node) { return ParametricDatum::create(buildProperties(node), getAnchor(node)); } // --------------------------------------------------------------------------- static CRSNNPtr createBoundCRSSourceTransformationCRS(const crs::CRSPtr &sourceCRS, const crs::CRSPtr &targetCRS) { CRSPtr sourceTransformationCRS; if (dynamic_cast<GeographicCRS *>(targetCRS.get())) { GeographicCRSPtr sourceGeographicCRS = sourceCRS->extractGeographicCRS(); sourceTransformationCRS = sourceGeographicCRS; if (sourceGeographicCRS) { const auto &sourceDatum = sourceGeographicCRS->datum(); if (sourceDatum != nullptr && sourceGeographicCRS->primeMeridian() ->longitude() .getSIValue() != 0.0) { sourceTransformationCRS = GeographicCRS::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, sourceGeographicCRS->nameStr() + " (with Greenwich prime meridian)"), datum::GeodeticReferenceFrame::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, sourceDatum->nameStr() + " (with Greenwich prime meridian)"), sourceDatum->ellipsoid(), util::optional<std::string>(), datum::PrimeMeridian::GREENWICH), sourceGeographicCRS->coordinateSystem()) .as_nullable(); } } else { auto vertSourceCRS = std::dynamic_pointer_cast<VerticalCRS>(sourceCRS); if (!vertSourceCRS) { throw ParsingException( "Cannot find GeographicCRS or VerticalCRS in sourceCRS"); } const auto &axis = vertSourceCRS->coordinateSystem()->axisList()[0]; if (axis->unit() == common::UnitOfMeasure::METRE && &(axis->direction()) == &AxisDirection::UP) { sourceTransformationCRS = sourceCRS; } else { std::string sourceTransformationCRSName( vertSourceCRS->nameStr()); if (ends_with(sourceTransformationCRSName, " (ftUS)")) { sourceTransformationCRSName.resize( sourceTransformationCRSName.size() - strlen(" (ftUS)")); } if (ends_with(sourceTransformationCRSName, " depth")) { sourceTransformationCRSName.resize( sourceTransformationCRSName.size() - strlen(" depth")); } if (!ends_with(sourceTransformationCRSName, " height")) { sourceTransformationCRSName += " height"; } sourceTransformationCRS = VerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, sourceTransformationCRSName), vertSourceCRS->datum(), vertSourceCRS->datumEnsemble(), VerticalCS::createGravityRelatedHeight( common::UnitOfMeasure::METRE)) .as_nullable(); } } } else { sourceTransformationCRS = sourceCRS; } return NN_NO_CHECK(sourceTransformationCRS); } // --------------------------------------------------------------------------- CRSNNPtr WKTParser::Private::buildVerticalCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); const auto &nodeValue = nodeP->value(); auto &vdatumNode = nodeP->lookForChild(WKTConstants::VDATUM, WKTConstants::VERT_DATUM, WKTConstants::VERTICALDATUM, WKTConstants::VRF); auto &ensembleNode = nodeP->lookForChild(WKTConstants::ENSEMBLE); // like in ESRI VERTCS["WGS_1984",DATUM["D_WGS_1984", // SPHEROID["WGS_1984",6378137.0,298.257223563]], // PARAMETER["Vertical_Shift",0.0], // PARAMETER["Direction",1.0],UNIT["Meter",1.0] auto &geogDatumNode = ci_equal(nodeValue, WKTConstants::VERTCS) ? nodeP->lookForChild(WKTConstants::DATUM) : null_node; if (isNull(vdatumNode) && isNull(geogDatumNode) && isNull(ensembleNode)) { throw ParsingException("Missing VDATUM or ENSEMBLE node"); } for (const auto &childNode : nodeP->children()) { const auto &childNodeChildren = childNode->GP()->children(); if (childNodeChildren.size() == 2 && ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER) && childNodeChildren[0]->GP()->value() == "\"Vertical_Shift\"") { esriStyle_ = true; break; } } auto &dynamicNode = nodeP->lookForChild(WKTConstants::DYNAMIC); auto vdatum = !isNull(geogDatumNode) ? VerticalReferenceFrame::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, buildGeodeticReferenceFrame(geogDatumNode, PrimeMeridian::GREENWICH, null_node) ->nameStr()) .set("VERT_DATUM_TYPE", "2002")) .as_nullable() : !isNull(vdatumNode) ? buildVerticalReferenceFrame(vdatumNode, dynamicNode).as_nullable() : nullptr; auto datumEnsemble = !isNull(ensembleNode) ? buildDatumEnsemble(ensembleNode, nullptr, false).as_nullable() : nullptr; auto &csNode = nodeP->lookForChild(WKTConstants::CS_); if (isNull(csNode) && !ci_equal(nodeValue, WKTConstants::VERT_CS) && !ci_equal(nodeValue, WKTConstants::VERTCS) && !ci_equal(nodeValue, WKTConstants::BASEVERTCRS)) { ThrowMissing(WKTConstants::CS_); } auto verticalCS = nn_dynamic_pointer_cast<VerticalCS>( buildCS(csNode, node, UnitOfMeasure::NONE)); if (!verticalCS) { ThrowNotExpectedCSType(VerticalCS::WKT2_TYPE); } if (vdatum && vdatum->getWKT1DatumType() == "2002" && &(verticalCS->axisList()[0]->direction()) == &(AxisDirection::UP)) { verticalCS = VerticalCS::create( util::PropertyMap(), CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, "ellipsoidal height"), "h", AxisDirection::UP, verticalCS->axisList()[0]->unit())) .as_nullable(); } auto &props = buildProperties(node); if (esriStyle_ && dbContext_) { std::string outTableName; std::string authNameFromAlias; std::string codeFromAlias; auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); const std::string vertCRSName = stripQuotes(nodeP->children()[0]); auto officialName = authFactory->getOfficialNameFromAlias( vertCRSName, "vertical_crs", "ESRI", false, outTableName, authNameFromAlias, codeFromAlias); if (!officialName.empty()) { props.set(IdentifiedObject::NAME_KEY, officialName); } } // Deal with Lidar WKT1 VertCRS that embeds geoid model in CRS name, // following conventions from // https://pubs.usgs.gov/tm/11b4/pdf/tm11-B4.pdf // page 9 if (ci_equal(nodeValue, WKTConstants::VERT_CS) || ci_equal(nodeValue, WKTConstants::VERTCS)) { std::string name; if (props.getStringValue(IdentifiedObject::NAME_KEY, name)) { std::string geoidName; for (const char *prefix : {"NAVD88 - ", "NAVD88 via ", "NAVD88 height - ", "NAVD88 height (ftUS) - "}) { if (starts_with(name, prefix)) { geoidName = name.substr(strlen(prefix)); auto pos = geoidName.find_first_of(" ("); if (pos != std::string::npos) { geoidName.resize(pos); } break; } } if (!geoidName.empty()) { const auto &axis = verticalCS->axisList()[0]; const auto &dir = axis->direction(); if (dir == cs::AxisDirection::UP) { if (axis->unit() == common::UnitOfMeasure::METRE) { props.set(IdentifiedObject::NAME_KEY, "NAVD88 height"); props.set(Identifier::CODE_KEY, 5703); props.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } else if (axis->unit().name() == "US survey foot") { props.set(IdentifiedObject::NAME_KEY, "NAVD88 height (ftUS)"); props.set(Identifier::CODE_KEY, 6360); props.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } } PropertyMap propsModel; propsModel.set(IdentifiedObject::NAME_KEY, toupper(geoidName)); PropertyMap propsDatum; propsDatum.set(IdentifiedObject::NAME_KEY, "North American Vertical Datum 1988"); propsDatum.set(Identifier::CODE_KEY, 5103); propsDatum.set(Identifier::CODESPACE_KEY, Identifier::EPSG); vdatum = VerticalReferenceFrame::create(propsDatum).as_nullable(); const auto dummyCRS = VerticalCRS::create(PropertyMap(), vdatum, datumEnsemble, NN_NO_CHECK(verticalCS)); const auto model(Transformation::create( propsModel, dummyCRS, dummyCRS, nullptr, OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>()), {}, {})); props.set("GEOID_MODEL", model); } } } auto &geoidModelNode = nodeP->lookForChild(WKTConstants::GEOIDMODEL); if (!isNull(geoidModelNode)) { ArrayOfBaseObjectNNPtr arrayModels = ArrayOfBaseObject::create(); for (const auto &childNode : nodeP->children()) { const auto &childNodeChildren = childNode->GP()->children(); if (childNodeChildren.size() >= 1 && ci_equal(childNode->GP()->value(), WKTConstants::GEOIDMODEL)) { auto &propsModel = buildProperties(childNode); const auto dummyCRS = VerticalCRS::create(PropertyMap(), vdatum, datumEnsemble, NN_NO_CHECK(verticalCS)); const auto model(Transformation::create( propsModel, dummyCRS, dummyCRS, nullptr, OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>()), {}, {})); arrayModels->add(model); } } props.set("GEOID_MODEL", arrayModels); } auto crs = nn_static_pointer_cast<CRS>(VerticalCRS::create( props, vdatum, datumEnsemble, NN_NO_CHECK(verticalCS))); if (!isNull(vdatumNode)) { auto &extensionNode = vdatumNode->lookForChild(WKTConstants::EXTENSION); const auto &extensionChildren = extensionNode->GP()->children(); if (extensionChildren.size() == 2) { if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4_GRIDS")) { const auto gridName(stripQuotes(extensionChildren[1])); // This is the expansion of EPSG:5703 by old GDAL versions. // See // https://trac.osgeo.org/metacrs/changeset?reponame=&new=2281%40geotiff%2Ftrunk%2Flibgeotiff%2Fcsv%2Fvertcs.override.csv&old=1893%40geotiff%2Ftrunk%2Flibgeotiff%2Fcsv%2Fvertcs.override.csv // It is unlikely that the user really explicitly wants this. if (gridName != "g2003conus.gtx,g2003alaska.gtx," "g2003h01.gtx,g2003p01.gtx" && gridName != "g2012a_conus.gtx,g2012a_alaska.gtx," "g2012a_guam.gtx,g2012a_hawaii.gtx," "g2012a_puertorico.gtx,g2012a_samoa.gtx") { auto geogCRS = geogCRSOfCompoundCRS_ && geogCRSOfCompoundCRS_->primeMeridian() ->longitude() .getSIValue() == 0 && geogCRSOfCompoundCRS_->coordinateSystem() ->axisList()[0] ->unit() == UnitOfMeasure::DEGREE ? geogCRSOfCompoundCRS_->promoteTo3D(std::string(), dbContext_) : GeographicCRS::EPSG_4979; auto sourceTransformationCRS = createBoundCRSSourceTransformationCRS( crs.as_nullable(), geogCRS.as_nullable()); auto transformation = Transformation:: createGravityRelatedHeightToGeographic3D( PropertyMap().set( IdentifiedObject::NAME_KEY, sourceTransformationCRS->nameStr() + " to " + geogCRS->nameStr() + " ellipsoidal height"), sourceTransformationCRS, geogCRS, nullptr, gridName, std::vector<PositionalAccuracyNNPtr>()); return nn_static_pointer_cast<CRS>( BoundCRS::create(crs, geogCRS, transformation)); } } } } return crs; } // --------------------------------------------------------------------------- DerivedVerticalCRSNNPtr WKTParser::Private::buildDerivedVerticalCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &baseVertCRSNode = nodeP->lookForChild(WKTConstants::BASEVERTCRS); // given the constraints enforced on calling code path assert(!isNull(baseVertCRSNode)); auto baseVertCRS_tmp = buildVerticalCRS(baseVertCRSNode); auto baseVertCRS = NN_NO_CHECK(baseVertCRS_tmp->extractVerticalCRS()); auto &derivingConversionNode = nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION); if (isNull(derivingConversionNode)) { ThrowMissing(WKTConstants::DERIVINGCONVERSION); } auto derivingConversion = buildConversion( derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE); auto &csNode = nodeP->lookForChild(WKTConstants::CS_); if (isNull(csNode)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, node, UnitOfMeasure::NONE); auto verticalCS = nn_dynamic_pointer_cast<VerticalCS>(cs); if (!verticalCS) { throw ParsingException( concat("vertical CS expected, but found ", cs->getWKT2Type(true))); } return DerivedVerticalCRS::create(buildProperties(node), baseVertCRS, derivingConversion, NN_NO_CHECK(verticalCS)); } // --------------------------------------------------------------------------- CRSNNPtr WKTParser::Private::buildCompoundCRS(const WKTNodeNNPtr &node) { std::vector<CRSNNPtr> components; bool bFirstNode = true; for (const auto &child : node->GP()->children()) { auto crs = buildCRS(child); if (crs) { if (bFirstNode) { geogCRSOfCompoundCRS_ = crs->extractGeographicCRS(); bFirstNode = false; } components.push_back(NN_NO_CHECK(crs)); } } if (ci_equal(node->GP()->value(), WKTConstants::COMPD_CS)) { return CompoundCRS::createLax(buildProperties(node), components, dbContext_); } else { return CompoundCRS::create(buildProperties(node), components); } } // --------------------------------------------------------------------------- static TransformationNNPtr buildTransformationForBoundCRS( DatabaseContextPtr &dbContext, const util::PropertyMap &abridgedNodeProperties, const util::PropertyMap &methodNodeProperties, const CRSNNPtr &sourceCRS, const CRSNNPtr &targetCRS, std::vector<OperationParameterNNPtr> &parameters, std::vector<ParameterValueNNPtr> &values) { auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter( dbContext, parameters, values); const auto sourceTransformationCRS( createBoundCRSSourceTransformationCRS(sourceCRS, targetCRS)); auto transformation = Transformation::create( abridgedNodeProperties, sourceTransformationCRS, targetCRS, interpolationCRS, methodNodeProperties, parameters, values, std::vector<PositionalAccuracyNNPtr>()); // If the transformation is a "Geographic3D to GravityRelatedHeight" one, // then the sourceCRS is expected to be a GeographicCRS and the target a // VerticalCRS. Due to how things work in a BoundCRS, we have the opposite, // so use our "GravityRelatedHeight to Geographic3D" method instead. if (Transformation::isGeographic3DToGravityRelatedHeight( transformation->method(), true) && dynamic_cast<VerticalCRS *>(sourceTransformationCRS.get()) && dynamic_cast<GeographicCRS *>(targetCRS.get())) { auto fileParameter = transformation->parameterValue( EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME, EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { const auto &filename = fileParameter->valueFile(); transformation = Transformation::createGravityRelatedHeightToGeographic3D( abridgedNodeProperties, sourceTransformationCRS, targetCRS, interpolationCRS, filename, std::vector<PositionalAccuracyNNPtr>()); } } return transformation; } // --------------------------------------------------------------------------- BoundCRSNNPtr WKTParser::Private::buildBoundCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &abridgedNode = nodeP->lookForChild(WKTConstants::ABRIDGEDTRANSFORMATION); if (isNull(abridgedNode)) { ThrowNotEnoughChildren(WKTConstants::ABRIDGEDTRANSFORMATION); } auto &methodNode = abridgedNode->GP()->lookForChild(WKTConstants::METHOD); if (isNull(methodNode)) { ThrowMissing(WKTConstants::METHOD); } if (methodNode->GP()->childrenSize() == 0) { ThrowNotEnoughChildren(WKTConstants::METHOD); } auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS); const auto &sourceCRSNodeChildren = sourceCRSNode->GP()->children(); if (sourceCRSNodeChildren.size() != 1) { ThrowNotEnoughChildren(WKTConstants::SOURCECRS); } auto sourceCRS = buildCRS(sourceCRSNodeChildren[0]); if (!sourceCRS) { throw ParsingException("Invalid content in SOURCECRS node"); } auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS); const auto &targetCRSNodeChildren = targetCRSNode->GP()->children(); if (targetCRSNodeChildren.size() != 1) { ThrowNotEnoughChildren(WKTConstants::TARGETCRS); } auto targetCRS = buildCRS(targetCRSNodeChildren[0]); if (!targetCRS) { throw ParsingException("Invalid content in TARGETCRS node"); } std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; const auto &defaultLinearUnit = UnitOfMeasure::NONE; const auto &defaultAngularUnit = UnitOfMeasure::NONE; consumeParameters(abridgedNode, true, parameters, values, defaultLinearUnit, defaultAngularUnit); const auto nnSourceCRS = NN_NO_CHECK(sourceCRS); const auto nnTargetCRS = NN_NO_CHECK(targetCRS); const auto transformation = buildTransformationForBoundCRS( dbContext_, buildProperties(abridgedNode), buildProperties(methodNode), nnSourceCRS, nnTargetCRS, parameters, values); return BoundCRS::create(buildProperties(node, false, false), NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), transformation); } // --------------------------------------------------------------------------- TemporalCSNNPtr WKTParser::Private::buildTemporalCS(const WKTNodeNNPtr &parentNode) { auto &csNode = parentNode->GP()->lookForChild(WKTConstants::CS_); if (isNull(csNode) && !ci_equal(parentNode->GP()->value(), WKTConstants::BASETIMECRS)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, parentNode, UnitOfMeasure::NONE); auto temporalCS = nn_dynamic_pointer_cast<TemporalCS>(cs); if (!temporalCS) { ThrowNotExpectedCSType(TemporalCS::WKT2_2015_TYPE); } return NN_NO_CHECK(temporalCS); } // --------------------------------------------------------------------------- TemporalCRSNNPtr WKTParser::Private::buildTemporalCRS(const WKTNodeNNPtr &node) { auto &datumNode = node->GP()->lookForChild(WKTConstants::TDATUM, WKTConstants::TIMEDATUM); if (isNull(datumNode)) { throw ParsingException("Missing TDATUM / TIMEDATUM node"); } return TemporalCRS::create(buildProperties(node), buildTemporalDatum(datumNode), buildTemporalCS(node)); } // --------------------------------------------------------------------------- DerivedTemporalCRSNNPtr WKTParser::Private::buildDerivedTemporalCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &baseCRSNode = nodeP->lookForChild(WKTConstants::BASETIMECRS); // given the constraints enforced on calling code path assert(!isNull(baseCRSNode)); auto &derivingConversionNode = nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION); if (isNull(derivingConversionNode)) { ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION); } return DerivedTemporalCRS::create( buildProperties(node), buildTemporalCRS(baseCRSNode), buildConversion(derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE), buildTemporalCS(node)); } // --------------------------------------------------------------------------- EngineeringCRSNNPtr WKTParser::Private::buildEngineeringCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &datumNode = nodeP->lookForChild(WKTConstants::EDATUM, WKTConstants::ENGINEERINGDATUM); if (isNull(datumNode)) { throw ParsingException("Missing EDATUM / ENGINEERINGDATUM node"); } auto &csNode = nodeP->lookForChild(WKTConstants::CS_); if (isNull(csNode) && !ci_equal(nodeP->value(), WKTConstants::BASEENGCRS)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, node, UnitOfMeasure::NONE); return EngineeringCRS::create(buildProperties(node), buildEngineeringDatum(datumNode), cs); } // --------------------------------------------------------------------------- EngineeringCRSNNPtr WKTParser::Private::buildEngineeringCRSFromLocalCS(const WKTNodeNNPtr &node) { auto &datumNode = node->GP()->lookForChild(WKTConstants::LOCAL_DATUM); auto cs = buildCS(null_node, node, UnitOfMeasure::NONE); auto datum = EngineeringDatum::create( !isNull(datumNode) ? buildProperties(datumNode) : // In theory OGC 01-009 mandates LOCAL_DATUM, but GDAL // has a tradition of emitting just LOCAL_CS["foo"] []() { PropertyMap map; map.set(IdentifiedObject::NAME_KEY, UNKNOWN_ENGINEERING_DATUM); return map; }()); return EngineeringCRS::create(buildProperties(node), datum, cs); } // --------------------------------------------------------------------------- DerivedEngineeringCRSNNPtr WKTParser::Private::buildDerivedEngineeringCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &baseEngCRSNode = nodeP->lookForChild(WKTConstants::BASEENGCRS); // given the constraints enforced on calling code path assert(!isNull(baseEngCRSNode)); auto baseEngCRS = buildEngineeringCRS(baseEngCRSNode); auto &derivingConversionNode = nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION); if (isNull(derivingConversionNode)) { ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION); } auto derivingConversion = buildConversion( derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE); auto &csNode = nodeP->lookForChild(WKTConstants::CS_); if (isNull(csNode)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, node, UnitOfMeasure::NONE); return DerivedEngineeringCRS::create(buildProperties(node), baseEngCRS, derivingConversion, cs); } // --------------------------------------------------------------------------- ParametricCSNNPtr WKTParser::Private::buildParametricCS(const WKTNodeNNPtr &parentNode) { auto &csNode = parentNode->GP()->lookForChild(WKTConstants::CS_); if (isNull(csNode) && !ci_equal(parentNode->GP()->value(), WKTConstants::BASEPARAMCRS)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, parentNode, UnitOfMeasure::NONE); auto parametricCS = nn_dynamic_pointer_cast<ParametricCS>(cs); if (!parametricCS) { ThrowNotExpectedCSType(ParametricCS::WKT2_TYPE); } return NN_NO_CHECK(parametricCS); } // --------------------------------------------------------------------------- ParametricCRSNNPtr WKTParser::Private::buildParametricCRS(const WKTNodeNNPtr &node) { auto &datumNode = node->GP()->lookForChild(WKTConstants::PDATUM, WKTConstants::PARAMETRICDATUM); if (isNull(datumNode)) { throw ParsingException("Missing PDATUM / PARAMETRICDATUM node"); } return ParametricCRS::create(buildProperties(node), buildParametricDatum(datumNode), buildParametricCS(node)); } // --------------------------------------------------------------------------- DerivedParametricCRSNNPtr WKTParser::Private::buildDerivedParametricCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &baseParamCRSNode = nodeP->lookForChild(WKTConstants::BASEPARAMCRS); // given the constraints enforced on calling code path assert(!isNull(baseParamCRSNode)); auto &derivingConversionNode = nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION); if (isNull(derivingConversionNode)) { ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION); } return DerivedParametricCRS::create( buildProperties(node), buildParametricCRS(baseParamCRSNode), buildConversion(derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE), buildParametricCS(node)); } // --------------------------------------------------------------------------- DerivedProjectedCRSNNPtr WKTParser::Private::buildDerivedProjectedCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); auto &baseProjCRSNode = nodeP->lookForChild(WKTConstants::BASEPROJCRS); if (isNull(baseProjCRSNode)) { ThrowNotEnoughChildren(WKTConstants::BASEPROJCRS); } auto baseProjCRS = buildProjectedCRS(baseProjCRSNode); auto &conversionNode = nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION); if (isNull(conversionNode)) { ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION); } auto linearUnit = buildUnitInSubNode(node); const auto &angularUnit = baseProjCRS->baseCRS()->coordinateSystem()->axisList()[0]->unit(); auto conversion = buildConversion(conversionNode, linearUnit, angularUnit); auto &csNode = nodeP->lookForChild(WKTConstants::CS_); if (isNull(csNode) && !ci_equal(nodeP->value(), WKTConstants::PROJCS)) { ThrowMissing(WKTConstants::CS_); } auto cs = buildCS(csNode, node, UnitOfMeasure::NONE); if (cs->axisList().size() == 3 && baseProjCRS->coordinateSystem()->axisList().size() == 2) { baseProjCRS = NN_NO_CHECK(util::nn_dynamic_pointer_cast<ProjectedCRS>( baseProjCRS->promoteTo3D(std::string(), dbContext_))); } return DerivedProjectedCRS::create(buildProperties(node), baseProjCRS, conversion, cs); } // --------------------------------------------------------------------------- CoordinateMetadataNNPtr WKTParser::Private::buildCoordinateMetadata(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); const auto &l_children = nodeP->children(); if (l_children.empty()) { ThrowNotEnoughChildren(WKTConstants::COORDINATEMETADATA); } auto crs = buildCRS(l_children[0]); if (!crs) { throw ParsingException("Invalid content in CRS node"); } auto &epochNode = nodeP->lookForChild(WKTConstants::EPOCH); if (!isNull(epochNode)) { const auto &epochChildren = epochNode->GP()->children(); if (epochChildren.empty()) { ThrowMissing(WKTConstants::EPOCH); } double coordinateEpoch; try { coordinateEpoch = asDouble(epochChildren[0]); } catch (const std::exception &) { throw ParsingException("Invalid EPOCH node"); } return CoordinateMetadata::create(NN_NO_CHECK(crs), coordinateEpoch, dbContext_); } return CoordinateMetadata::create(NN_NO_CHECK(crs)); } // --------------------------------------------------------------------------- static bool isGeodeticCRS(const std::string &name) { return ci_equal(name, WKTConstants::GEODCRS) || // WKT2 ci_equal(name, WKTConstants::GEODETICCRS) || // WKT2 ci_equal(name, WKTConstants::GEOGCRS) || // WKT2 2019 ci_equal(name, WKTConstants::GEOGRAPHICCRS) || // WKT2 2019 ci_equal(name, WKTConstants::GEOGCS) || // WKT1 ci_equal(name, WKTConstants::GEOCCS); // WKT1 } // --------------------------------------------------------------------------- CRSPtr WKTParser::Private::buildCRS(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); const std::string &name(nodeP->value()); const auto applyHorizontalBoundCRSParams = [&](const CRSNNPtr &crs) { if (!toWGS84Parameters_.empty()) { auto ret = BoundCRS::createFromTOWGS84(crs, toWGS84Parameters_); toWGS84Parameters_.clear(); return util::nn_static_pointer_cast<CRS>(ret); } else if (!datumPROJ4Grids_.empty()) { auto ret = BoundCRS::createFromNadgrids(crs, datumPROJ4Grids_); datumPROJ4Grids_.clear(); return util::nn_static_pointer_cast<CRS>(ret); } return crs; }; if (isGeodeticCRS(name)) { if (!isNull(nodeP->lookForChild(WKTConstants::BASEGEOGCRS, WKTConstants::BASEGEODCRS))) { return util::nn_static_pointer_cast<CRS>( applyHorizontalBoundCRSParams(buildDerivedGeodeticCRS(node))); } else { return util::nn_static_pointer_cast<CRS>( applyHorizontalBoundCRSParams(buildGeodeticCRS(node))); } } if (ci_equal(name, WKTConstants::PROJCS) || ci_equal(name, WKTConstants::PROJCRS) || ci_equal(name, WKTConstants::PROJECTEDCRS)) { // Get the EXTENSION "PROJ4" node before attempting to call // buildProjectedCRS() since formulations of WKT1_GDAL from GDAL 2.x // with the netCDF driver and the lack the required UNIT[] node std::string projString = getExtensionProj4(nodeP); if (!projString.empty() && (starts_with(projString, "+proj=ob_tran +o_proj=longlat") || starts_with(projString, "+proj=ob_tran +o_proj=lonlat") || starts_with(projString, "+proj=ob_tran +o_proj=latlong") || starts_with(projString, "+proj=ob_tran +o_proj=latlon"))) { // Those are not a projected CRS, but a DerivedGeographic one... if (projString.find(" +type=crs") == std::string::npos) { projString += " +type=crs"; } try { auto projObj = PROJStringParser().createFromPROJString(projString); auto crs = nn_dynamic_pointer_cast<CRS>(projObj); if (crs) { return util::nn_static_pointer_cast<CRS>( applyHorizontalBoundCRSParams(NN_NO_CHECK(crs))); } } catch (const io::ParsingException &) { } } return util::nn_static_pointer_cast<CRS>( applyHorizontalBoundCRSParams(buildProjectedCRS(node))); } if (ci_equal(name, WKTConstants::VERT_CS) || ci_equal(name, WKTConstants::VERTCS) || ci_equal(name, WKTConstants::VERTCRS) || ci_equal(name, WKTConstants::VERTICALCRS)) { if (!isNull(nodeP->lookForChild(WKTConstants::BASEVERTCRS))) { return util::nn_static_pointer_cast<CRS>( buildDerivedVerticalCRS(node)); } else { return util::nn_static_pointer_cast<CRS>(buildVerticalCRS(node)); } } if (ci_equal(name, WKTConstants::COMPD_CS) || ci_equal(name, WKTConstants::COMPOUNDCRS)) { return util::nn_static_pointer_cast<CRS>(buildCompoundCRS(node)); } if (ci_equal(name, WKTConstants::BOUNDCRS)) { return util::nn_static_pointer_cast<CRS>(buildBoundCRS(node)); } if (ci_equal(name, WKTConstants::TIMECRS)) { if (!isNull(nodeP->lookForChild(WKTConstants::BASETIMECRS))) { return util::nn_static_pointer_cast<CRS>( buildDerivedTemporalCRS(node)); } else { return util::nn_static_pointer_cast<CRS>(buildTemporalCRS(node)); } } if (ci_equal(name, WKTConstants::DERIVEDPROJCRS)) { return util::nn_static_pointer_cast<CRS>( buildDerivedProjectedCRS(node)); } if (ci_equal(name, WKTConstants::ENGCRS) || ci_equal(name, WKTConstants::ENGINEERINGCRS)) { if (!isNull(nodeP->lookForChild(WKTConstants::BASEENGCRS))) { return util::nn_static_pointer_cast<CRS>( buildDerivedEngineeringCRS(node)); } else { return util::nn_static_pointer_cast<CRS>(buildEngineeringCRS(node)); } } if (ci_equal(name, WKTConstants::LOCAL_CS)) { return util::nn_static_pointer_cast<CRS>( buildEngineeringCRSFromLocalCS(node)); } if (ci_equal(name, WKTConstants::PARAMETRICCRS)) { if (!isNull(nodeP->lookForChild(WKTConstants::BASEPARAMCRS))) { return util::nn_static_pointer_cast<CRS>( buildDerivedParametricCRS(node)); } else { return util::nn_static_pointer_cast<CRS>(buildParametricCRS(node)); } } return nullptr; } // --------------------------------------------------------------------------- BaseObjectNNPtr WKTParser::Private::build(const WKTNodeNNPtr &node) { const auto *nodeP = node->GP(); const std::string &name(nodeP->value()); auto crs = buildCRS(node); if (crs) { return util::nn_static_pointer_cast<BaseObject>(NN_NO_CHECK(crs)); } // Datum handled by caller code WKTParser::createFromWKT() if (ci_equal(name, WKTConstants::ENSEMBLE)) { return util::nn_static_pointer_cast<BaseObject>(buildDatumEnsemble( node, PrimeMeridian::GREENWICH, !isNull(nodeP->lookForChild(WKTConstants::ELLIPSOID)))); } if (ci_equal(name, WKTConstants::VDATUM) || ci_equal(name, WKTConstants::VERT_DATUM) || ci_equal(name, WKTConstants::VERTICALDATUM) || ci_equal(name, WKTConstants::VRF)) { return util::nn_static_pointer_cast<BaseObject>( buildVerticalReferenceFrame(node, null_node)); } if (ci_equal(name, WKTConstants::TDATUM) || ci_equal(name, WKTConstants::TIMEDATUM)) { return util::nn_static_pointer_cast<BaseObject>( buildTemporalDatum(node)); } if (ci_equal(name, WKTConstants::EDATUM) || ci_equal(name, WKTConstants::ENGINEERINGDATUM)) { return util::nn_static_pointer_cast<BaseObject>( buildEngineeringDatum(node)); } if (ci_equal(name, WKTConstants::PDATUM) || ci_equal(name, WKTConstants::PARAMETRICDATUM)) { return util::nn_static_pointer_cast<BaseObject>( buildParametricDatum(node)); } if (ci_equal(name, WKTConstants::ELLIPSOID) || ci_equal(name, WKTConstants::SPHEROID)) { return util::nn_static_pointer_cast<BaseObject>(buildEllipsoid(node)); } if (ci_equal(name, WKTConstants::COORDINATEOPERATION)) { auto transf = buildCoordinateOperation(node); const char *prefixes[] = { "PROJ-based operation method: ", "PROJ-based operation method (approximate): "}; for (const char *prefix : prefixes) { if (starts_with(transf->method()->nameStr(), prefix)) { auto projString = transf->method()->nameStr().substr(strlen(prefix)); return util::nn_static_pointer_cast<BaseObject>( PROJBasedOperation::create( PropertyMap(), projString, transf->sourceCRS(), transf->targetCRS(), transf->coordinateOperationAccuracies())); } } return util::nn_static_pointer_cast<BaseObject>(transf); } if (ci_equal(name, WKTConstants::CONVERSION)) { auto conv = buildConversion(node, UnitOfMeasure::METRE, UnitOfMeasure::DEGREE); if (starts_with(conv->method()->nameStr(), "PROJ-based operation method: ")) { auto projString = conv->method()->nameStr().substr( strlen("PROJ-based operation method: ")); return util::nn_static_pointer_cast<BaseObject>( PROJBasedOperation::create(PropertyMap(), projString, nullptr, nullptr, {})); } return util::nn_static_pointer_cast<BaseObject>(conv); } if (ci_equal(name, WKTConstants::CONCATENATEDOPERATION)) { return util::nn_static_pointer_cast<BaseObject>( buildConcatenatedOperation(node)); } if (ci_equal(name, WKTConstants::POINTMOTIONOPERATION)) { return util::nn_static_pointer_cast<BaseObject>( buildPointMotionOperation(node)); } if (ci_equal(name, WKTConstants::ID) || ci_equal(name, WKTConstants::AUTHORITY)) { return util::nn_static_pointer_cast<BaseObject>( NN_NO_CHECK(buildId(node, false, false))); } if (ci_equal(name, WKTConstants::COORDINATEMETADATA)) { return util::nn_static_pointer_cast<BaseObject>( buildCoordinateMetadata(node)); } throw ParsingException(concat("unhandled keyword: ", name)); } // --------------------------------------------------------------------------- class JSONParser { DatabaseContextPtr dbContext_{}; std::string deformationModelName_{}; static std::string getString(const json &j, const char *key); static json getObject(const json &j, const char *key); static json getArray(const json &j, const char *key); static int getInteger(const json &j, const char *key); static double getNumber(const json &j, const char *key); static UnitOfMeasure getUnit(const json &j, const char *key); static std::string getName(const json &j); static std::string getType(const json &j); static Length getLength(const json &j, const char *key); static Measure getMeasure(const json &j); IdentifierNNPtr buildId(const json &j, bool removeInverseOf); static ObjectDomainPtr buildObjectDomain(const json &j); PropertyMap buildProperties(const json &j, bool removeInverseOf = false, bool nameRequired = true); GeographicCRSNNPtr buildGeographicCRS(const json &j); GeodeticCRSNNPtr buildGeodeticCRS(const json &j); ProjectedCRSNNPtr buildProjectedCRS(const json &j); ConversionNNPtr buildConversion(const json &j); DatumEnsembleNNPtr buildDatumEnsemble(const json &j); GeodeticReferenceFrameNNPtr buildGeodeticReferenceFrame(const json &j); VerticalReferenceFrameNNPtr buildVerticalReferenceFrame(const json &j); DynamicGeodeticReferenceFrameNNPtr buildDynamicGeodeticReferenceFrame(const json &j); DynamicVerticalReferenceFrameNNPtr buildDynamicVerticalReferenceFrame(const json &j); EllipsoidNNPtr buildEllipsoid(const json &j); PrimeMeridianNNPtr buildPrimeMeridian(const json &j); CoordinateSystemNNPtr buildCS(const json &j); MeridianNNPtr buildMeridian(const json &j); CoordinateSystemAxisNNPtr buildAxis(const json &j); VerticalCRSNNPtr buildVerticalCRS(const json &j); CRSNNPtr buildCRS(const json &j); CompoundCRSNNPtr buildCompoundCRS(const json &j); BoundCRSNNPtr buildBoundCRS(const json &j); TransformationNNPtr buildTransformation(const json &j); PointMotionOperationNNPtr buildPointMotionOperation(const json &j); ConcatenatedOperationNNPtr buildConcatenatedOperation(const json &j); CoordinateMetadataNNPtr buildCoordinateMetadata(const json &j); void buildGeodeticDatumOrDatumEnsemble(const json &j, GeodeticReferenceFramePtr &datum, DatumEnsemblePtr &datumEnsemble); static util::optional<std::string> getAnchor(const json &j) { util::optional<std::string> anchor; if (j.contains("anchor")) { anchor = getString(j, "anchor"); } return anchor; } static util::optional<common::Measure> getAnchorEpoch(const json &j) { if (j.contains("anchor_epoch")) { return util::optional<common::Measure>(common::Measure( getNumber(j, "anchor_epoch"), common::UnitOfMeasure::YEAR)); } return util::optional<common::Measure>(); } EngineeringDatumNNPtr buildEngineeringDatum(const json &j) { return EngineeringDatum::create(buildProperties(j), getAnchor(j)); } ParametricDatumNNPtr buildParametricDatum(const json &j) { return ParametricDatum::create(buildProperties(j), getAnchor(j)); } TemporalDatumNNPtr buildTemporalDatum(const json &j) { auto calendar = getString(j, "calendar"); auto origin = DateTime::create(j.contains("time_origin") ? getString(j, "time_origin") : std::string()); return TemporalDatum::create(buildProperties(j), origin, calendar); } template <class TargetCRS, class DatumBuilderType, class CSClass = CoordinateSystem> util::nn<std::shared_ptr<TargetCRS>> buildCRS(const json &j, DatumBuilderType f) { auto datum = (this->*f)(getObject(j, "datum")); auto cs = buildCS(getObject(j, "coordinate_system")); auto csCast = util::nn_dynamic_pointer_cast<CSClass>(cs); if (!csCast) { throw ParsingException("coordinate_system not of expected type"); } return TargetCRS::create(buildProperties(j), datum, NN_NO_CHECK(csCast)); } template <class TargetCRS, class BaseCRS, class CSClass = CoordinateSystem> util::nn<std::shared_ptr<TargetCRS>> buildDerivedCRS(const json &j) { auto baseCRSObj = create(getObject(j, "base_crs")); auto baseCRS = util::nn_dynamic_pointer_cast<BaseCRS>(baseCRSObj); if (!baseCRS) { throw ParsingException("base_crs not of expected type"); } auto cs = buildCS(getObject(j, "coordinate_system")); auto csCast = util::nn_dynamic_pointer_cast<CSClass>(cs); if (!csCast) { throw ParsingException("coordinate_system not of expected type"); } auto conv = buildConversion(getObject(j, "conversion")); return TargetCRS::create(buildProperties(j), NN_NO_CHECK(baseCRS), conv, NN_NO_CHECK(csCast)); } public: JSONParser() = default; JSONParser &attachDatabaseContext(const DatabaseContextPtr &dbContext) { dbContext_ = dbContext; return *this; } BaseObjectNNPtr create(const json &j); }; // --------------------------------------------------------------------------- std::string JSONParser::getString(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } auto v = j[key]; if (!v.is_string()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a string"); } return v.get<std::string>(); } // --------------------------------------------------------------------------- json JSONParser::getObject(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } auto v = j[key]; if (!v.is_object()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a object"); } return v.get<json>(); } // --------------------------------------------------------------------------- json JSONParser::getArray(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } auto v = j[key]; if (!v.is_array()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a array"); } return v.get<json>(); } // --------------------------------------------------------------------------- int JSONParser::getInteger(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } auto v = j[key]; if (!v.is_number()) { throw ParsingException(std::string("The value of \"") + key + "\" should be an integer"); } const double dbl = v.get<double>(); if (!(dbl >= std::numeric_limits<int>::min() && dbl <= std::numeric_limits<int>::max() && static_cast<int>(dbl) == dbl)) { throw ParsingException(std::string("The value of \"") + key + "\" should be an integer"); } return static_cast<int>(dbl); } // --------------------------------------------------------------------------- double JSONParser::getNumber(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } auto v = j[key]; if (!v.is_number()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a number"); } return v.get<double>(); } // --------------------------------------------------------------------------- UnitOfMeasure JSONParser::getUnit(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } auto v = j[key]; if (v.is_string()) { auto vStr = v.get<std::string>(); for (const auto &unit : {UnitOfMeasure::METRE, UnitOfMeasure::DEGREE, UnitOfMeasure::SCALE_UNITY}) { if (vStr == unit.name()) return unit; } throw ParsingException("Unknown unit name: " + vStr); } if (!v.is_object()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a string or an object"); } auto typeStr = getType(v); UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN; if (typeStr == "LinearUnit") { type = UnitOfMeasure::Type::LINEAR; } else if (typeStr == "AngularUnit") { type = UnitOfMeasure::Type::ANGULAR; } else if (typeStr == "ScaleUnit") { type = UnitOfMeasure::Type::SCALE; } else if (typeStr == "TimeUnit") { type = UnitOfMeasure::Type::TIME; } else if (typeStr == "ParametricUnit") { type = UnitOfMeasure::Type::PARAMETRIC; } else if (typeStr == "Unit") { type = UnitOfMeasure::Type::UNKNOWN; } else { throw ParsingException("Unsupported value of \"type\""); } auto nameStr = getName(v); auto convFactor = getNumber(v, "conversion_factor"); std::string authorityStr; std::string codeStr; if (v.contains("authority") && v.contains("code")) { authorityStr = getString(v, "authority"); auto code = v["code"]; if (code.is_string()) { codeStr = code.get<std::string>(); } else if (code.is_number_integer()) { codeStr = internal::toString(code.get<int>()); } else { throw ParsingException("Unexpected type for value of \"code\""); } } return UnitOfMeasure(nameStr, convFactor, type, authorityStr, codeStr); } // --------------------------------------------------------------------------- std::string JSONParser::getName(const json &j) { return getString(j, "name"); } // --------------------------------------------------------------------------- std::string JSONParser::getType(const json &j) { return getString(j, "type"); } // --------------------------------------------------------------------------- Length JSONParser::getLength(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } auto v = j[key]; if (v.is_number()) { return Length(v.get<double>(), UnitOfMeasure::METRE); } if (v.is_object()) { return Length(getMeasure(v)); } throw ParsingException(std::string("The value of \"") + key + "\" should be a number or an object"); } // --------------------------------------------------------------------------- Measure JSONParser::getMeasure(const json &j) { return Measure(getNumber(j, "value"), getUnit(j, "unit")); } // --------------------------------------------------------------------------- ObjectDomainPtr JSONParser::buildObjectDomain(const json &j) { optional<std::string> scope; if (j.contains("scope")) { scope = getString(j, "scope"); } std::string area; if (j.contains("area")) { area = getString(j, "area"); } std::vector<GeographicExtentNNPtr> geogExtent; if (j.contains("bbox")) { auto bbox = getObject(j, "bbox"); double south = getNumber(bbox, "south_latitude"); double west = getNumber(bbox, "west_longitude"); double north = getNumber(bbox, "north_latitude"); double east = getNumber(bbox, "east_longitude"); geogExtent.emplace_back( GeographicBoundingBox::create(west, south, east, north)); } std::vector<VerticalExtentNNPtr> verticalExtent; if (j.contains("vertical_extent")) { const auto vertical_extent = getObject(j, "vertical_extent"); const auto min = getNumber(vertical_extent, "minimum"); const auto max = getNumber(vertical_extent, "maximum"); const auto unit = vertical_extent.contains("unit") ? getUnit(vertical_extent, "unit") : UnitOfMeasure::METRE; verticalExtent.emplace_back(VerticalExtent::create( min, max, util::nn_make_shared<UnitOfMeasure>(unit))); } std::vector<TemporalExtentNNPtr> temporalExtent; if (j.contains("temporal_extent")) { const auto temporal_extent = getObject(j, "temporal_extent"); const auto start = getString(temporal_extent, "start"); const auto end = getString(temporal_extent, "end"); temporalExtent.emplace_back(TemporalExtent::create(start, end)); } if (scope.has_value() || !area.empty() || !geogExtent.empty() || !verticalExtent.empty() || !temporalExtent.empty()) { util::optional<std::string> description; if (!area.empty()) description = area; ExtentPtr extent; if (description.has_value() || !geogExtent.empty() || !verticalExtent.empty() || !temporalExtent.empty()) { extent = Extent::create(description, geogExtent, verticalExtent, temporalExtent) .as_nullable(); } return ObjectDomain::create(scope, extent).as_nullable(); } return nullptr; } // --------------------------------------------------------------------------- IdentifierNNPtr JSONParser::buildId(const json &j, bool removeInverseOf) { PropertyMap propertiesId; auto codeSpace(getString(j, "authority")); if (removeInverseOf && starts_with(codeSpace, "INVERSE(") && codeSpace.back() == ')') { codeSpace = codeSpace.substr(strlen("INVERSE(")); codeSpace.resize(codeSpace.size() - 1); } std::string version; if (j.contains("version")) { auto versionJ = j["version"]; if (versionJ.is_string()) { version = versionJ.get<std::string>(); } else if (versionJ.is_number()) { const double dblVersion = versionJ.get<double>(); if (dblVersion >= std::numeric_limits<int>::min() && dblVersion <= std::numeric_limits<int>::max() && static_cast<int>(dblVersion) == dblVersion) { version = internal::toString(static_cast<int>(dblVersion)); } else { version = internal::toString(dblVersion, /*precision=*/15); } } else { throw ParsingException("Unexpected type for value of \"version\""); } } // IAU + 2015 -> IAU_2015 if (dbContext_ && !version.empty()) { std::string codeSpaceOut; if (dbContext_->getVersionedAuthority(codeSpace, version, codeSpaceOut)) { codeSpace = std::move(codeSpaceOut); version.clear(); } } propertiesId.set(metadata::Identifier::CODESPACE_KEY, codeSpace); propertiesId.set(metadata::Identifier::AUTHORITY_KEY, codeSpace); if (!j.contains("code")) { throw ParsingException("Missing \"code\" key"); } std::string code; auto codeJ = j["code"]; if (codeJ.is_string()) { code = codeJ.get<std::string>(); } else if (codeJ.is_number_integer()) { code = internal::toString(codeJ.get<int>()); } else { throw ParsingException("Unexpected type for value of \"code\""); } if (!version.empty()) { propertiesId.set(Identifier::VERSION_KEY, version); } if (j.contains("authority_citation")) { propertiesId.set(Identifier::AUTHORITY_KEY, getString(j, "authority_citation")); } if (j.contains("uri")) { propertiesId.set(Identifier::URI_KEY, getString(j, "uri")); } return Identifier::create(code, propertiesId); } // --------------------------------------------------------------------------- PropertyMap JSONParser::buildProperties(const json &j, bool removeInverseOf, bool nameRequired) { PropertyMap map; if (j.contains("name") || nameRequired) { std::string name(getName(j)); if (removeInverseOf && starts_with(name, "Inverse of ")) { name = name.substr(strlen("Inverse of ")); } map.set(IdentifiedObject::NAME_KEY, name); } if (j.contains("ids")) { auto idsJ = getArray(j, "ids"); auto identifiers = ArrayOfBaseObject::create(); for (const auto &idJ : idsJ) { if (!idJ.is_object()) { throw ParsingException( "Unexpected type for value of \"ids\" child"); } identifiers->add(buildId(idJ, removeInverseOf)); } map.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers); } else if (j.contains("id")) { auto idJ = getObject(j, "id"); auto identifiers = ArrayOfBaseObject::create(); identifiers->add(buildId(idJ, removeInverseOf)); map.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers); } if (j.contains("remarks")) { map.set(IdentifiedObject::REMARKS_KEY, getString(j, "remarks")); } if (j.contains("usages")) { ArrayOfBaseObjectNNPtr array = ArrayOfBaseObject::create(); auto usages = j["usages"]; if (!usages.is_array()) { throw ParsingException("Unexpected type for value of \"usages\""); } for (const auto &usage : usages) { if (!usage.is_object()) { throw ParsingException( "Unexpected type for value of \"usages\" child"); } auto objectDomain = buildObjectDomain(usage); if (!objectDomain) { throw ParsingException("missing children in \"usages\" child"); } array->add(NN_NO_CHECK(objectDomain)); } if (!array->empty()) { map.set(ObjectUsage::OBJECT_DOMAIN_KEY, array); } } else { auto objectDomain = buildObjectDomain(j); if (objectDomain) { map.set(ObjectUsage::OBJECT_DOMAIN_KEY, NN_NO_CHECK(objectDomain)); } } return map; } // --------------------------------------------------------------------------- BaseObjectNNPtr JSONParser::create(const json &j) { if (!j.is_object()) { throw ParsingException("JSON object expected"); } auto type = getString(j, "type"); if (type == "GeographicCRS") { return buildGeographicCRS(j); } if (type == "GeodeticCRS") { return buildGeodeticCRS(j); } if (type == "ProjectedCRS") { return buildProjectedCRS(j); } if (type == "VerticalCRS") { return buildVerticalCRS(j); } if (type == "CompoundCRS") { return buildCompoundCRS(j); } if (type == "BoundCRS") { return buildBoundCRS(j); } if (type == "EngineeringCRS") { return buildCRS<EngineeringCRS>(j, &JSONParser::buildEngineeringDatum); } if (type == "ParametricCRS") { return buildCRS<ParametricCRS, decltype(&JSONParser::buildParametricDatum), ParametricCS>(j, &JSONParser::buildParametricDatum); } if (type == "TemporalCRS") { return buildCRS<TemporalCRS, decltype(&JSONParser::buildTemporalDatum), TemporalCS>(j, &JSONParser::buildTemporalDatum); } if (type == "DerivedGeodeticCRS") { auto baseCRSObj = create(getObject(j, "base_crs")); auto baseCRS = util::nn_dynamic_pointer_cast<GeodeticCRS>(baseCRSObj); if (!baseCRS) { throw ParsingException("base_crs not of expected type"); } auto cs = buildCS(getObject(j, "coordinate_system")); auto conv = buildConversion(getObject(j, "conversion")); auto csCartesian = util::nn_dynamic_pointer_cast<CartesianCS>(cs); if (csCartesian) return DerivedGeodeticCRS::create(buildProperties(j), NN_NO_CHECK(baseCRS), conv, NN_NO_CHECK(csCartesian)); auto csSpherical = util::nn_dynamic_pointer_cast<SphericalCS>(cs); if (csSpherical) return DerivedGeodeticCRS::create(buildProperties(j), NN_NO_CHECK(baseCRS), conv, NN_NO_CHECK(csSpherical)); throw ParsingException("coordinate_system not of expected type"); } if (type == "DerivedGeographicCRS") { return buildDerivedCRS<DerivedGeographicCRS, GeodeticCRS, EllipsoidalCS>(j); } if (type == "DerivedProjectedCRS") { return buildDerivedCRS<DerivedProjectedCRS, ProjectedCRS>(j); } if (type == "DerivedVerticalCRS") { return buildDerivedCRS<DerivedVerticalCRS, VerticalCRS, VerticalCS>(j); } if (type == "DerivedEngineeringCRS") { return buildDerivedCRS<DerivedEngineeringCRS, EngineeringCRS>(j); } if (type == "DerivedParametricCRS") { return buildDerivedCRS<DerivedParametricCRS, ParametricCRS, ParametricCS>(j); } if (type == "DerivedTemporalCRS") { return buildDerivedCRS<DerivedTemporalCRS, TemporalCRS, TemporalCS>(j); } if (type == "DatumEnsemble") { return buildDatumEnsemble(j); } if (type == "GeodeticReferenceFrame") { return buildGeodeticReferenceFrame(j); } if (type == "VerticalReferenceFrame") { return buildVerticalReferenceFrame(j); } if (type == "DynamicGeodeticReferenceFrame") { return buildDynamicGeodeticReferenceFrame(j); } if (type == "DynamicVerticalReferenceFrame") { return buildDynamicVerticalReferenceFrame(j); } if (type == "EngineeringDatum") { return buildEngineeringDatum(j); } if (type == "ParametricDatum") { return buildParametricDatum(j); } if (type == "TemporalDatum") { return buildTemporalDatum(j); } if (type == "Ellipsoid") { return buildEllipsoid(j); } if (type == "PrimeMeridian") { return buildPrimeMeridian(j); } if (type == "CoordinateSystem") { return buildCS(j); } if (type == "Conversion") { return buildConversion(j); } if (type == "Transformation") { return buildTransformation(j); } if (type == "PointMotionOperation") { return buildPointMotionOperation(j); } if (type == "ConcatenatedOperation") { return buildConcatenatedOperation(j); } if (type == "CoordinateMetadata") { return buildCoordinateMetadata(j); } if (type == "Axis") { return buildAxis(j); } throw ParsingException("Unsupported value of \"type\""); } // --------------------------------------------------------------------------- void JSONParser::buildGeodeticDatumOrDatumEnsemble( const json &j, GeodeticReferenceFramePtr &datum, DatumEnsemblePtr &datumEnsemble) { if (j.contains("datum")) { auto datumJ = getObject(j, "datum"); if (j.contains("deformation_models")) { auto deformationModelsJ = getArray(j, "deformation_models"); if (!deformationModelsJ.empty()) { const auto &deformationModelJ = deformationModelsJ[0]; deformationModelName_ = getString(deformationModelJ, "name"); // We can handle only one for now } } datum = util::nn_dynamic_pointer_cast<GeodeticReferenceFrame>( create(datumJ)); if (!datum) { throw ParsingException("datum of wrong type"); } deformationModelName_.clear(); } else { datumEnsemble = buildDatumEnsemble(getObject(j, "datum_ensemble")).as_nullable(); } } // --------------------------------------------------------------------------- GeographicCRSNNPtr JSONParser::buildGeographicCRS(const json &j) { GeodeticReferenceFramePtr datum; DatumEnsemblePtr datumEnsemble; buildGeodeticDatumOrDatumEnsemble(j, datum, datumEnsemble); auto csJ = getObject(j, "coordinate_system"); auto ellipsoidalCS = util::nn_dynamic_pointer_cast<EllipsoidalCS>(buildCS(csJ)); if (!ellipsoidalCS) { throw ParsingException("expected an ellipsoidal CS"); } return GeographicCRS::create(buildProperties(j), datum, datumEnsemble, NN_NO_CHECK(ellipsoidalCS)); } // --------------------------------------------------------------------------- GeodeticCRSNNPtr JSONParser::buildGeodeticCRS(const json &j) { GeodeticReferenceFramePtr datum; DatumEnsemblePtr datumEnsemble; buildGeodeticDatumOrDatumEnsemble(j, datum, datumEnsemble); auto csJ = getObject(j, "coordinate_system"); auto cs = buildCS(csJ); auto props = buildProperties(j); auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs); if (cartesianCS) { if (cartesianCS->axisList().size() != 3) { throw ParsingException( "Cartesian CS for a GeodeticCRS should have 3 axis"); } try { return GeodeticCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(cartesianCS)); } catch (const util::Exception &e) { throw ParsingException(std::string("buildGeodeticCRS: ") + e.what()); } } auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs); if (sphericalCS) { try { return GeodeticCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(sphericalCS)); } catch (const util::Exception &e) { throw ParsingException(std::string("buildGeodeticCRS: ") + e.what()); } } throw ParsingException("expected a Cartesian or spherical CS"); } // --------------------------------------------------------------------------- ProjectedCRSNNPtr JSONParser::buildProjectedCRS(const json &j) { auto jBaseCRS = getObject(j, "base_crs"); auto jBaseCS = getObject(jBaseCRS, "coordinate_system"); auto baseCS = buildCS(jBaseCS); auto baseCRS = dynamic_cast<EllipsoidalCS *>(baseCS.get()) != nullptr ? util::nn_static_pointer_cast<GeodeticCRS>( buildGeographicCRS(jBaseCRS)) : buildGeodeticCRS(jBaseCRS); auto csJ = getObject(j, "coordinate_system"); auto cartesianCS = util::nn_dynamic_pointer_cast<CartesianCS>(buildCS(csJ)); if (!cartesianCS) { throw ParsingException("expected a Cartesian CS"); } auto conv = buildConversion(getObject(j, "conversion")); return ProjectedCRS::create(buildProperties(j), baseCRS, conv, NN_NO_CHECK(cartesianCS)); } // --------------------------------------------------------------------------- VerticalCRSNNPtr JSONParser::buildVerticalCRS(const json &j) { VerticalReferenceFramePtr datum; DatumEnsemblePtr datumEnsemble; if (j.contains("datum")) { auto datumJ = getObject(j, "datum"); if (j.contains("deformation_models")) { auto deformationModelsJ = getArray(j, "deformation_models"); if (!deformationModelsJ.empty()) { const auto &deformationModelJ = deformationModelsJ[0]; deformationModelName_ = getString(deformationModelJ, "name"); // We can handle only one for now } } datum = util::nn_dynamic_pointer_cast<VerticalReferenceFrame>( create(datumJ)); if (!datum) { throw ParsingException("datum of wrong type"); } } else { datumEnsemble = buildDatumEnsemble(getObject(j, "datum_ensemble")).as_nullable(); } auto csJ = getObject(j, "coordinate_system"); auto verticalCS = util::nn_dynamic_pointer_cast<VerticalCS>(buildCS(csJ)); if (!verticalCS) { throw ParsingException("expected a vertical CS"); } const auto buildGeoidModel = [this, &datum, &datumEnsemble, &verticalCS](const json &geoidModelJ) { auto propsModel = buildProperties(geoidModelJ); const auto dummyCRS = VerticalCRS::create( PropertyMap(), datum, datumEnsemble, NN_NO_CHECK(verticalCS)); CRSPtr interpolationCRS; if (geoidModelJ.contains("interpolation_crs")) { auto interpolationCRSJ = getObject(geoidModelJ, "interpolation_crs"); interpolationCRS = buildCRS(interpolationCRSJ).as_nullable(); } return Transformation::create( propsModel, dummyCRS, GeographicCRS::EPSG_4979, // arbitrarily chosen. Ignored, interpolationCRS, OperationMethod::create(PropertyMap(), std::vector<OperationParameterNNPtr>()), {}, {}); }; auto props = buildProperties(j); if (j.contains("geoid_model")) { auto geoidModelJ = getObject(j, "geoid_model"); props.set("GEOID_MODEL", buildGeoidModel(geoidModelJ)); } else if (j.contains("geoid_models")) { auto geoidModelsJ = getArray(j, "geoid_models"); auto geoidModels = ArrayOfBaseObject::create(); for (const auto &geoidModelJ : geoidModelsJ) { geoidModels->add(buildGeoidModel(geoidModelJ)); } props.set("GEOID_MODEL", geoidModels); } return VerticalCRS::create(props, datum, datumEnsemble, NN_NO_CHECK(verticalCS)); } // --------------------------------------------------------------------------- CRSNNPtr JSONParser::buildCRS(const json &j) { auto crs = util::nn_dynamic_pointer_cast<CRS>(create(j)); if (crs) { return NN_NO_CHECK(crs); } throw ParsingException("Object is not a CRS"); } // --------------------------------------------------------------------------- CompoundCRSNNPtr JSONParser::buildCompoundCRS(const json &j) { auto componentsJ = getArray(j, "components"); std::vector<CRSNNPtr> components; for (const auto &componentJ : componentsJ) { if (!componentJ.is_object()) { throw ParsingException( "Unexpected type for a \"components\" child"); } components.push_back(buildCRS(componentJ)); } return CompoundCRS::create(buildProperties(j), components); } // --------------------------------------------------------------------------- ConversionNNPtr JSONParser::buildConversion(const json &j) { auto methodJ = getObject(j, "method"); auto convProps = buildProperties(j); auto methodProps = buildProperties(methodJ); if (!j.contains("parameters")) { return Conversion::create(convProps, methodProps, {}, {}); } auto parametersJ = getArray(j, "parameters"); std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; for (const auto &param : parametersJ) { if (!param.is_object()) { throw ParsingException( "Unexpected type for a \"parameters\" child"); } parameters.emplace_back( OperationParameter::create(buildProperties(param))); if (isIntegerParameter(parameters.back())) { values.emplace_back( ParameterValue::create(getInteger(param, "value"))); } else { values.emplace_back(ParameterValue::create(getMeasure(param))); } } auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter( dbContext_, parameters, values); std::string convName; std::string methodName; if (convProps.getStringValue(IdentifiedObject::NAME_KEY, convName) && methodProps.getStringValue(IdentifiedObject::NAME_KEY, methodName) && starts_with(convName, "Inverse of ") && starts_with(methodName, "Inverse of ")) { auto invConvProps = buildProperties(j, true); auto invMethodProps = buildProperties(methodJ, true); auto conv = NN_NO_CHECK(util::nn_dynamic_pointer_cast<Conversion>( Conversion::create(invConvProps, invMethodProps, parameters, values) ->inverse())); if (interpolationCRS) conv->setInterpolationCRS(interpolationCRS); return conv; } auto conv = Conversion::create(convProps, methodProps, parameters, values); if (interpolationCRS) conv->setInterpolationCRS(interpolationCRS); return conv; } // --------------------------------------------------------------------------- BoundCRSNNPtr JSONParser::buildBoundCRS(const json &j) { auto sourceCRS = buildCRS(getObject(j, "source_crs")); auto targetCRS = buildCRS(getObject(j, "target_crs")); auto transformationJ = getObject(j, "transformation"); auto methodJ = getObject(transformationJ, "method"); auto parametersJ = getArray(transformationJ, "parameters"); std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; for (const auto &param : parametersJ) { if (!param.is_object()) { throw ParsingException( "Unexpected type for a \"parameters\" child"); } parameters.emplace_back( OperationParameter::create(buildProperties(param))); if (param.contains("value")) { auto v = param["value"]; if (v.is_string()) { values.emplace_back( ParameterValue::createFilename(v.get<std::string>())); continue; } } values.emplace_back(ParameterValue::create(getMeasure(param))); } const auto transformation = [&]() { // Unofficial extension / mostly for testing purposes. // Allow to explicitly specify the source_crs of the transformation of // the boundCRS if it is not the source_crs of the BoundCRS. Cf // https://github.com/OSGeo/PROJ/issues/3428 use case if (transformationJ.contains("source_crs")) { auto sourceTransformationCRS = buildCRS(getObject(transformationJ, "source_crs")); auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter( dbContext_, parameters, values); return Transformation::create( buildProperties(transformationJ), sourceTransformationCRS, targetCRS, interpolationCRS, buildProperties(methodJ), parameters, values, std::vector<PositionalAccuracyNNPtr>()); } return buildTransformationForBoundCRS( dbContext_, buildProperties(transformationJ), buildProperties(methodJ), sourceCRS, targetCRS, parameters, values); }(); return BoundCRS::create(buildProperties(j, /* removeInverseOf= */ false, /* nameRequired=*/false), sourceCRS, targetCRS, transformation); } // --------------------------------------------------------------------------- TransformationNNPtr JSONParser::buildTransformation(const json &j) { auto sourceCRS = buildCRS(getObject(j, "source_crs")); auto targetCRS = buildCRS(getObject(j, "target_crs")); auto methodJ = getObject(j, "method"); auto parametersJ = getArray(j, "parameters"); std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; for (const auto &param : parametersJ) { if (!param.is_object()) { throw ParsingException( "Unexpected type for a \"parameters\" child"); } parameters.emplace_back( OperationParameter::create(buildProperties(param))); if (param.contains("value")) { auto v = param["value"]; if (v.is_string()) { values.emplace_back( ParameterValue::createFilename(v.get<std::string>())); continue; } } values.emplace_back(ParameterValue::create(getMeasure(param))); } CRSPtr interpolationCRS; if (j.contains("interpolation_crs")) { interpolationCRS = buildCRS(getObject(j, "interpolation_crs")).as_nullable(); } std::vector<PositionalAccuracyNNPtr> accuracies; if (j.contains("accuracy")) { accuracies.push_back( PositionalAccuracy::create(getString(j, "accuracy"))); } return Transformation::create(buildProperties(j), sourceCRS, targetCRS, interpolationCRS, buildProperties(methodJ), parameters, values, accuracies); } // --------------------------------------------------------------------------- PointMotionOperationNNPtr JSONParser::buildPointMotionOperation(const json &j) { auto sourceCRS = buildCRS(getObject(j, "source_crs")); auto methodJ = getObject(j, "method"); auto parametersJ = getArray(j, "parameters"); std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; for (const auto &param : parametersJ) { if (!param.is_object()) { throw ParsingException( "Unexpected type for a \"parameters\" child"); } parameters.emplace_back( OperationParameter::create(buildProperties(param))); if (param.contains("value")) { auto v = param["value"]; if (v.is_string()) { values.emplace_back( ParameterValue::createFilename(v.get<std::string>())); continue; } } values.emplace_back(ParameterValue::create(getMeasure(param))); } std::vector<PositionalAccuracyNNPtr> accuracies; if (j.contains("accuracy")) { accuracies.push_back( PositionalAccuracy::create(getString(j, "accuracy"))); } return PointMotionOperation::create(buildProperties(j), sourceCRS, buildProperties(methodJ), parameters, values, accuracies); } // --------------------------------------------------------------------------- ConcatenatedOperationNNPtr JSONParser::buildConcatenatedOperation(const json &j) { auto sourceCRS = buildCRS(getObject(j, "source_crs")); auto targetCRS = buildCRS(getObject(j, "target_crs")); auto stepsJ = getArray(j, "steps"); std::vector<CoordinateOperationNNPtr> operations; for (const auto &stepJ : stepsJ) { if (!stepJ.is_object()) { throw ParsingException("Unexpected type for a \"steps\" child"); } auto op = nn_dynamic_pointer_cast<CoordinateOperation>(create(stepJ)); if (!op) { throw ParsingException("Invalid content in a \"steps\" child"); } operations.emplace_back(NN_NO_CHECK(op)); } ConcatenatedOperation::fixStepsDirection(sourceCRS, targetCRS, operations, dbContext_); std::vector<PositionalAccuracyNNPtr> accuracies; if (j.contains("accuracy")) { accuracies.push_back( PositionalAccuracy::create(getString(j, "accuracy"))); } try { return ConcatenatedOperation::create(buildProperties(j), operations, accuracies); } catch (const InvalidOperation &e) { throw ParsingException( std::string("Cannot build concatenated operation: ") + e.what()); } } // --------------------------------------------------------------------------- CoordinateMetadataNNPtr JSONParser::buildCoordinateMetadata(const json &j) { auto crs = buildCRS(getObject(j, "crs")); if (j.contains("coordinateEpoch")) { auto jCoordinateEpoch = j["coordinateEpoch"]; if (jCoordinateEpoch.is_number()) { return CoordinateMetadata::create( crs, jCoordinateEpoch.get<double>(), dbContext_); } throw ParsingException( "Unexpected type for value of \"coordinateEpoch\""); } return CoordinateMetadata::create(crs); } // --------------------------------------------------------------------------- MeridianNNPtr JSONParser::buildMeridian(const json &j) { if (!j.contains("longitude")) { throw ParsingException("Missing \"longitude\" key"); } auto longitude = j["longitude"]; if (longitude.is_number()) { return Meridian::create( Angle(longitude.get<double>(), UnitOfMeasure::DEGREE)); } else if (longitude.is_object()) { return Meridian::create(Angle(getMeasure(longitude))); } throw ParsingException("Unexpected type for value of \"longitude\""); } // --------------------------------------------------------------------------- CoordinateSystemAxisNNPtr JSONParser::buildAxis(const json &j) { auto dirString = getString(j, "direction"); auto abbreviation = getString(j, "abbreviation"); const UnitOfMeasure unit( j.contains("unit") ? getUnit(j, "unit") : UnitOfMeasure(std::string(), 1.0, UnitOfMeasure::Type::NONE)); auto direction = AxisDirection::valueOf(dirString); if (!direction) { throw ParsingException(concat("unhandled axis direction: ", dirString)); } auto meridian = j.contains("meridian") ? buildMeridian(getObject(j, "meridian")).as_nullable() : nullptr; util::optional<double> minVal; if (j.contains("minimum_value")) { minVal = getNumber(j, "minimum_value"); } util::optional<double> maxVal; if (j.contains("maximum_value")) { maxVal = getNumber(j, "maximum_value"); } util::optional<RangeMeaning> rangeMeaning; if (j.contains("range_meaning")) { const auto val = getString(j, "range_meaning"); const RangeMeaning *meaning = RangeMeaning::valueOf(val); if (meaning == nullptr) { throw ParsingException( concat("buildAxis: invalid range_meaning value: ", val)); } rangeMeaning = util::optional<RangeMeaning>(*meaning); } return CoordinateSystemAxis::create(buildProperties(j), abbreviation, *direction, unit, minVal, maxVal, rangeMeaning, meridian); } // --------------------------------------------------------------------------- CoordinateSystemNNPtr JSONParser::buildCS(const json &j) { auto subtype = getString(j, "subtype"); if (!j.contains("axis")) { throw ParsingException("Missing \"axis\" key"); } auto jAxisList = j["axis"]; if (!jAxisList.is_array()) { throw ParsingException("Unexpected type for value of \"axis\""); } std::vector<CoordinateSystemAxisNNPtr> axisList; for (const auto &axis : jAxisList) { if (!axis.is_object()) { throw ParsingException( "Unexpected type for value of a \"axis\" member"); } axisList.emplace_back(buildAxis(axis)); } const PropertyMap &csMap = emptyPropertyMap; const auto axisCount = axisList.size(); if (subtype == EllipsoidalCS::WKT2_TYPE) { if (axisCount == 2) { return EllipsoidalCS::create(csMap, axisList[0], axisList[1]); } if (axisCount == 3) { return EllipsoidalCS::create(csMap, axisList[0], axisList[1], axisList[2]); } throw ParsingException("Expected 2 or 3 axis"); } if (subtype == CartesianCS::WKT2_TYPE) { if (axisCount == 2) { return CartesianCS::create(csMap, axisList[0], axisList[1]); } if (axisCount == 3) { return CartesianCS::create(csMap, axisList[0], axisList[1], axisList[2]); } throw ParsingException("Expected 2 or 3 axis"); } if (subtype == AffineCS::WKT2_TYPE) { if (axisCount == 2) { return AffineCS::create(csMap, axisList[0], axisList[1]); } if (axisCount == 3) { return AffineCS::create(csMap, axisList[0], axisList[1], axisList[2]); } throw ParsingException("Expected 2 or 3 axis"); } if (subtype == VerticalCS::WKT2_TYPE) { if (axisCount == 1) { return VerticalCS::create(csMap, axisList[0]); } throw ParsingException("Expected 1 axis"); } if (subtype == SphericalCS::WKT2_TYPE) { if (axisCount == 2) { // Extension to ISO19111 to support (planet)-ocentric CS with // geocentric latitude return SphericalCS::create(csMap, axisList[0], axisList[1]); } else if (axisCount == 3) { return SphericalCS::create(csMap, axisList[0], axisList[1], axisList[2]); } throw ParsingException("Expected 2 or 3 axis"); } if (subtype == OrdinalCS::WKT2_TYPE) { return OrdinalCS::create(csMap, axisList); } if (subtype == ParametricCS::WKT2_TYPE) { if (axisCount == 1) { return ParametricCS::create(csMap, axisList[0]); } throw ParsingException("Expected 1 axis"); } if (subtype == DateTimeTemporalCS::WKT2_2019_TYPE) { if (axisCount == 1) { return DateTimeTemporalCS::create(csMap, axisList[0]); } throw ParsingException("Expected 1 axis"); } if (subtype == TemporalCountCS::WKT2_2019_TYPE) { if (axisCount == 1) { return TemporalCountCS::create(csMap, axisList[0]); } throw ParsingException("Expected 1 axis"); } if (subtype == TemporalMeasureCS::WKT2_2019_TYPE) { if (axisCount == 1) { return TemporalMeasureCS::create(csMap, axisList[0]); } throw ParsingException("Expected 1 axis"); } throw ParsingException("Unhandled value for subtype"); } // --------------------------------------------------------------------------- DatumEnsembleNNPtr JSONParser::buildDatumEnsemble(const json &j) { auto membersJ = getArray(j, "members"); std::vector<DatumNNPtr> datums; const bool hasEllipsoid(j.contains("ellipsoid")); for (const auto &memberJ : membersJ) { if (!memberJ.is_object()) { throw ParsingException( "Unexpected type for value of a \"members\" member"); } auto datumName(getName(memberJ)); bool datumAdded = false; if (dbContext_ && memberJ.contains("id")) { auto id = getObject(memberJ, "id"); auto authority = getString(id, "authority"); auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), authority); auto code = id["code"]; std::string codeStr; if (code.is_string()) { codeStr = code.get<std::string>(); } else if (code.is_number_integer()) { codeStr = internal::toString(code.get<int>()); } else { throw ParsingException("Unexpected type for value of \"code\""); } try { datums.push_back(authFactory->createDatum(codeStr)); datumAdded = true; } catch (const std::exception &) { // Silently ignore, as this isn't necessary an error. // If an older PROJ version parses a DatumEnsemble object of // a more recent PROJ version where the datum ensemble got // a new member, it might be unknown from the older PROJ. } } if (dbContext_ && !datumAdded) { auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string()); auto list = authFactory->createObjectsFromName( datumName, {AuthorityFactory::ObjectType::DATUM}, false /* approximate=false*/); if (!list.empty()) { auto datum = util::nn_dynamic_pointer_cast<Datum>(list.front()); if (!datum) throw ParsingException( "DatumEnsemble member is not a datum"); datums.push_back(NN_NO_CHECK(datum)); datumAdded = true; } } if (!datumAdded) { // Fallback if no db match if (hasEllipsoid) { datums.emplace_back(GeodeticReferenceFrame::create( buildProperties(memberJ), buildEllipsoid(getObject(j, "ellipsoid")), optional<std::string>(), PrimeMeridian::GREENWICH)); } else { datums.emplace_back( VerticalReferenceFrame::create(buildProperties(memberJ))); } } } return DatumEnsemble::create( buildProperties(j), datums, PositionalAccuracy::create(getString(j, "accuracy"))); } // --------------------------------------------------------------------------- GeodeticReferenceFrameNNPtr JSONParser::buildGeodeticReferenceFrame(const json &j) { auto ellipsoidJ = getObject(j, "ellipsoid"); auto pm = j.contains("prime_meridian") ? buildPrimeMeridian(getObject(j, "prime_meridian")) : PrimeMeridian::GREENWICH; return GeodeticReferenceFrame::create(buildProperties(j), buildEllipsoid(ellipsoidJ), getAnchor(j), getAnchorEpoch(j), pm); } // --------------------------------------------------------------------------- DynamicGeodeticReferenceFrameNNPtr JSONParser::buildDynamicGeodeticReferenceFrame(const json &j) { auto ellipsoidJ = getObject(j, "ellipsoid"); auto pm = j.contains("prime_meridian") ? buildPrimeMeridian(getObject(j, "prime_meridian")) : PrimeMeridian::GREENWICH; Measure frameReferenceEpoch(getNumber(j, "frame_reference_epoch"), UnitOfMeasure::YEAR); optional<std::string> deformationModel; if (j.contains("deformation_model")) { // Before PROJJSON v0.5 / PROJ 9.1 deformationModel = getString(j, "deformation_model"); } else if (!deformationModelName_.empty()) { deformationModel = deformationModelName_; } return DynamicGeodeticReferenceFrame::create( buildProperties(j), buildEllipsoid(ellipsoidJ), getAnchor(j), pm, frameReferenceEpoch, deformationModel); } // --------------------------------------------------------------------------- VerticalReferenceFrameNNPtr JSONParser::buildVerticalReferenceFrame(const json &j) { return VerticalReferenceFrame::create(buildProperties(j), getAnchor(j), getAnchorEpoch(j)); } // --------------------------------------------------------------------------- DynamicVerticalReferenceFrameNNPtr JSONParser::buildDynamicVerticalReferenceFrame(const json &j) { Measure frameReferenceEpoch(getNumber(j, "frame_reference_epoch"), UnitOfMeasure::YEAR); optional<std::string> deformationModel; if (j.contains("deformation_model")) { // Before PROJJSON v0.5 / PROJ 9.1 deformationModel = getString(j, "deformation_model"); } else if (!deformationModelName_.empty()) { deformationModel = deformationModelName_; } return DynamicVerticalReferenceFrame::create( buildProperties(j), getAnchor(j), util::optional<RealizationMethod>(), frameReferenceEpoch, deformationModel); } // --------------------------------------------------------------------------- PrimeMeridianNNPtr JSONParser::buildPrimeMeridian(const json &j) { if (!j.contains("longitude")) { throw ParsingException("Missing \"longitude\" key"); } auto longitude = j["longitude"]; if (longitude.is_number()) { return PrimeMeridian::create( buildProperties(j), Angle(longitude.get<double>(), UnitOfMeasure::DEGREE)); } else if (longitude.is_object()) { return PrimeMeridian::create(buildProperties(j), Angle(getMeasure(longitude))); } throw ParsingException("Unexpected type for value of \"longitude\""); } // --------------------------------------------------------------------------- EllipsoidNNPtr JSONParser::buildEllipsoid(const json &j) { if (j.contains("semi_major_axis")) { auto semiMajorAxis = getLength(j, "semi_major_axis"); const auto celestialBody( Ellipsoid::guessBodyName(dbContext_, semiMajorAxis.getSIValue())); if (j.contains("semi_minor_axis")) { return Ellipsoid::createTwoAxis(buildProperties(j), semiMajorAxis, getLength(j, "semi_minor_axis"), celestialBody); } else if (j.contains("inverse_flattening")) { return Ellipsoid::createFlattenedSphere( buildProperties(j), semiMajorAxis, Scale(getNumber(j, "inverse_flattening")), celestialBody); } else { throw ParsingException( "Missing semi_minor_axis or inverse_flattening"); } } else if (j.contains("radius")) { auto radius = getLength(j, "radius"); const auto celestialBody( Ellipsoid::guessBodyName(dbContext_, radius.getSIValue())); return Ellipsoid::createSphere(buildProperties(j), radius, celestialBody); } throw ParsingException("Missing semi_major_axis or radius"); } // --------------------------------------------------------------------------- // import a CRS encoded as OGC Best Practice document 11-135. static const char *const crsURLPrefixes[] = { "http://opengis.net/def/crs", "https://opengis.net/def/crs", "http://www.opengis.net/def/crs", "https://www.opengis.net/def/crs", "www.opengis.net/def/crs", }; static bool isCRSURL(const std::string &text) { for (const auto crsURLPrefix : crsURLPrefixes) { if (starts_with(text, crsURLPrefix)) { return true; } } return false; } static CRSNNPtr importFromCRSURL(const std::string &text, const DatabaseContextNNPtr &dbContext) { // e.g http://www.opengis.net/def/crs/EPSG/0/4326 std::vector<std::string> parts; for (const auto crsURLPrefix : crsURLPrefixes) { if (starts_with(text, crsURLPrefix)) { parts = split(text.substr(strlen(crsURLPrefix)), '/'); break; } } // e.g // "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/3855" if (!parts.empty() && starts_with(parts[0], "-compound?")) { parts = split(text.substr(text.find('?') + 1), '&'); std::map<int, std::string> mapParts; for (const auto &part : parts) { const auto queryParam = split(part, '='); if (queryParam.size() != 2) { throw ParsingException("invalid OGC CRS URL"); } try { mapParts[std::stoi(queryParam[0])] = queryParam[1]; } catch (const std::exception &) { throw ParsingException("invalid OGC CRS URL"); } } std::vector<CRSNNPtr> components; std::string name; for (size_t i = 1; i <= mapParts.size(); ++i) { const auto iter = mapParts.find(static_cast<int>(i)); if (iter == mapParts.end()) { throw ParsingException("invalid OGC CRS URL"); } components.emplace_back(importFromCRSURL(iter->second, dbContext)); if (!name.empty()) { name += " + "; } name += components.back()->nameStr(); } return CompoundCRS::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, name), components); } if (parts.size() < 4) { throw ParsingException("invalid OGC CRS URL"); } const auto &auth_name = parts[1]; const auto &code = parts[3]; try { auto factoryCRS = AuthorityFactory::create(dbContext, auth_name); return factoryCRS->createCoordinateReferenceSystem(code, true); } catch (...) { const auto &version = parts[2]; if (version.empty() || version == "0") { const auto authoritiesFromAuthName = dbContext->getVersionedAuthoritiesFromName(auth_name); for (const auto &authNameVersioned : authoritiesFromAuthName) { try { auto factoryCRS = AuthorityFactory::create(dbContext, authNameVersioned); return factoryCRS->createCoordinateReferenceSystem(code, true); } catch (...) { } } throw; } std::string authNameWithVersion; if (!dbContext->getVersionedAuthority(auth_name, version, authNameWithVersion)) { throw; } auto factoryCRS = AuthorityFactory::create(dbContext, authNameWithVersion); return factoryCRS->createCoordinateReferenceSystem(code, true); } } // --------------------------------------------------------------------------- /* Import a CRS encoded as WMSAUTO string. * * Note that the WMS 1.3 specification does not include the * units code, while apparently earlier specs do. We try to * guess around this. * * (code derived from GDAL's importFromWMSAUTO()) */ static CRSNNPtr importFromWMSAUTO(const std::string &text) { int nUnitsId = 9001; double dfRefLong; double dfRefLat = 0.0; assert(ci_starts_with(text, "AUTO:")); const auto parts = split(text.substr(strlen("AUTO:")), ','); try { constexpr int AUTO_MOLLWEIDE = 42005; if (parts.size() == 4) { nUnitsId = std::stoi(parts[1]); dfRefLong = c_locale_stod(parts[2]); dfRefLat = c_locale_stod(parts[3]); } else if (parts.size() == 3 && std::stoi(parts[0]) == AUTO_MOLLWEIDE) { nUnitsId = std::stoi(parts[1]); dfRefLong = c_locale_stod(parts[2]); } else if (parts.size() == 3) { dfRefLong = c_locale_stod(parts[1]); dfRefLat = c_locale_stod(parts[2]); } else if (parts.size() == 2 && std::stoi(parts[0]) == AUTO_MOLLWEIDE) { dfRefLong = c_locale_stod(parts[1]); } else { throw ParsingException("invalid WMS AUTO CRS definition"); } const auto getConversion = [=]() { const int nProjId = std::stoi(parts[0]); switch (nProjId) { case 42001: // Auto UTM if (!(dfRefLong >= -180 && dfRefLong < 180)) { throw ParsingException("invalid WMS AUTO CRS definition: " "invalid longitude"); } return Conversion::createUTM( util::PropertyMap(), static_cast<int>(floor((dfRefLong + 180.0) / 6.0)) + 1, dfRefLat >= 0.0); case 42002: // Auto TM (strangely very UTM-like). return Conversion::createTransverseMercator( util::PropertyMap(), common::Angle(0), common::Angle(dfRefLong), common::Scale(0.9996), common::Length(500000), common::Length((dfRefLat >= 0.0) ? 0.0 : 10000000.0)); case 42003: // Auto Orthographic. return Conversion::createOrthographic( util::PropertyMap(), common::Angle(dfRefLat), common::Angle(dfRefLong), common::Length(0), common::Length(0)); case 42004: // Auto Equirectangular return Conversion::createEquidistantCylindrical( util::PropertyMap(), common::Angle(dfRefLat), common::Angle(dfRefLong), common::Length(0), common::Length(0)); case 42005: // MSVC 2015 thinks that AUTO_MOLLWEIDE is not constant return Conversion::createMollweide( util::PropertyMap(), common::Angle(dfRefLong), common::Length(0), common::Length(0)); default: throw ParsingException("invalid WMS AUTO CRS definition: " "unsupported projection id"); } }; const auto getUnits = [=]() -> const UnitOfMeasure & { switch (nUnitsId) { case 9001: return UnitOfMeasure::METRE; case 9002: return UnitOfMeasure::FOOT; case 9003: return UnitOfMeasure::US_FOOT; default: throw ParsingException("invalid WMS AUTO CRS definition: " "unsupported units code"); } }; return crs::ProjectedCRS::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), crs::GeographicCRS::EPSG_4326, getConversion(), cs::CartesianCS::createEastingNorthing(getUnits())); } catch (const std::exception &) { throw ParsingException("invalid WMS AUTO CRS definition"); } } // --------------------------------------------------------------------------- static BaseObjectNNPtr createFromURNPart(const DatabaseContextPtr &dbContext, const std::string &type, const std::string &authName, const std::string &version, const std::string &code) { if (!dbContext) { throw ParsingException("no database context specified"); } try { auto factory = AuthorityFactory::create(NN_NO_CHECK(dbContext), authName); if (type == "crs") { return factory->createCoordinateReferenceSystem(code); } if (type == "coordinateOperation") { return factory->createCoordinateOperation(code, true); } if (type == "datum") { return factory->createDatum(code); } if (type == "ensemble") { return factory->createDatumEnsemble(code); } if (type == "ellipsoid") { return factory->createEllipsoid(code); } if (type == "meridian") { return factory->createPrimeMeridian(code); } // Extension of OGC URN syntax to CoordinateMetadata if (type == "coordinateMetadata") { return factory->createCoordinateMetadata(code); } throw ParsingException(concat("unhandled object type: ", type)); } catch (...) { if (version.empty()) { const auto authoritiesFromAuthName = dbContext->getVersionedAuthoritiesFromName(authName); for (const auto &authNameVersioned : authoritiesFromAuthName) { try { return createFromURNPart(dbContext, type, authNameVersioned, std::string(), code); } catch (...) { } } throw; } std::string authNameWithVersion; if (!dbContext->getVersionedAuthority(authName, version, authNameWithVersion)) { throw; } return createFromURNPart(dbContext, type, authNameWithVersion, std::string(), code); } } // --------------------------------------------------------------------------- static BaseObjectNNPtr createFromUserInput(const std::string &text, const DatabaseContextPtr &dbContext, bool usePROJ4InitRules, PJ_CONTEXT *ctx, bool ignoreCoordinateEpoch) { std::size_t idxFirstCharNotSpace = text.find_first_not_of(" \t\r\n"); if (idxFirstCharNotSpace > 0 && idxFirstCharNotSpace != std::string::npos) { return createFromUserInput(text.substr(idxFirstCharNotSpace), dbContext, usePROJ4InitRules, ctx, ignoreCoordinateEpoch); } // Parse strings like "ITRF2014 @ 2025.0" const auto posAt = text.find('@'); if (!ignoreCoordinateEpoch && posAt != std::string::npos) { // Try first as if belonged to the name try { return createFromUserInput(text, dbContext, usePROJ4InitRules, ctx, /* ignoreCoordinateEpoch = */ true); } catch (...) { } std::string leftPart = text.substr(0, posAt); while (!leftPart.empty() && leftPart.back() == ' ') leftPart.resize(leftPart.size() - 1); const auto nonSpacePos = text.find_first_not_of(' ', posAt + 1); if (nonSpacePos != std::string::npos) { auto obj = createFromUserInput(leftPart, dbContext, usePROJ4InitRules, ctx, /* ignoreCoordinateEpoch = */ true); auto crs = nn_dynamic_pointer_cast<CRS>(obj); if (crs) { double epoch; try { epoch = c_locale_stod(text.substr(nonSpacePos)); } catch (const std::exception &) { throw ParsingException("non-numeric value after @"); } try { return CoordinateMetadata::create(NN_NO_CHECK(crs), epoch, dbContext); } catch (const std::exception &e) { throw ParsingException( std::string( "CoordinateMetadata::create() failed with: ") + e.what()); } } } } if (!text.empty() && text[0] == '{') { json j; try { j = json::parse(text); } catch (const std::exception &e) { throw ParsingException(e.what()); } return JSONParser().attachDatabaseContext(dbContext).create(j); } if (!ci_starts_with(text, "step proj=") && !ci_starts_with(text, "step +proj=")) { for (const auto &wktConstant : WKTConstants::constants()) { if (ci_starts_with(text, wktConstant)) { for (auto wkt = text.c_str() + wktConstant.size(); *wkt != '\0'; ++wkt) { if (isspace(static_cast<unsigned char>(*wkt))) continue; if (*wkt == '[') { return WKTParser() .attachDatabaseContext(dbContext) .setStrict(false) .createFromWKT(text); } break; } } } } const char *textWithoutPlusPrefix = text.c_str(); if (textWithoutPlusPrefix[0] == '+') textWithoutPlusPrefix++; if (strncmp(textWithoutPlusPrefix, "proj=", strlen("proj=")) == 0 || text.find(" +proj=") != std::string::npos || text.find(" proj=") != std::string::npos || strncmp(textWithoutPlusPrefix, "init=", strlen("init=")) == 0 || text.find(" +init=") != std::string::npos || text.find(" init=") != std::string::npos || strncmp(textWithoutPlusPrefix, "title=", strlen("title=")) == 0) { return PROJStringParser() .attachDatabaseContext(dbContext) .attachContext(ctx) .setUsePROJ4InitRules(ctx != nullptr ? (proj_context_get_use_proj4_init_rules( ctx, false) == TRUE) : usePROJ4InitRules) .createFromPROJString(text); } if (isCRSURL(text) && dbContext) { return importFromCRSURL(text, NN_NO_CHECK(dbContext)); } if (ci_starts_with(text, "AUTO:")) { return importFromWMSAUTO(text); } auto tokens = split(text, ':'); if (tokens.size() == 2) { if (!dbContext) { throw ParsingException("no database context specified"); } DatabaseContextNNPtr dbContextNNPtr(NN_NO_CHECK(dbContext)); const auto &authName = tokens[0]; const auto &code = tokens[1]; auto factory = AuthorityFactory::create(dbContextNNPtr, authName); try { return factory->createCoordinateReferenceSystem(code); } catch (...) { // Convenience for well-known misused code // See https://github.com/OSGeo/PROJ/issues/1730 if (ci_equal(authName, "EPSG") && code == "102100") { factory = AuthorityFactory::create(dbContextNNPtr, "ESRI"); return factory->createCoordinateReferenceSystem(code); } const auto authoritiesFromAuthName = dbContextNNPtr->getVersionedAuthoritiesFromName(authName); for (const auto &authNameVersioned : authoritiesFromAuthName) { factory = AuthorityFactory::create(dbContextNNPtr, authNameVersioned); try { return factory->createCoordinateReferenceSystem(code); } catch (...) { } } const auto allAuthorities = dbContextNNPtr->getAuthorities(); for (const auto &authCandidate : allAuthorities) { if (ci_equal(authCandidate, authName)) { factory = AuthorityFactory::create(dbContextNNPtr, authCandidate); try { return factory->createCoordinateReferenceSystem(code); } catch (...) { // EPSG:4326+3855 auto tokensCode = split(code, '+'); if (tokensCode.size() == 2) { auto crs1(factory->createCoordinateReferenceSystem( tokensCode[0], false)); auto crs2(factory->createCoordinateReferenceSystem( tokensCode[1], false)); return CompoundCRS::createLax( util::PropertyMap().set( IdentifiedObject::NAME_KEY, crs1->nameStr() + " + " + crs2->nameStr()), {crs1, crs2}, dbContext); } throw; } } } throw; } } else if (tokens.size() == 3) { // ESRI:103668+EPSG:5703 ... compound auto tokensCenter = split(tokens[1], '+'); if (tokensCenter.size() == 2) { if (!dbContext) { throw ParsingException("no database context specified"); } DatabaseContextNNPtr dbContextNNPtr(NN_NO_CHECK(dbContext)); const auto &authName1 = tokens[0]; const auto &code1 = tokensCenter[0]; const auto &authName2 = tokensCenter[1]; const auto &code2 = tokens[2]; auto factory1 = AuthorityFactory::create(dbContextNNPtr, authName1); auto crs1 = factory1->createCoordinateReferenceSystem(code1, false); auto factory2 = AuthorityFactory::create(dbContextNNPtr, authName2); auto crs2 = factory2->createCoordinateReferenceSystem(code2, false); return CompoundCRS::createLax( util::PropertyMap().set(IdentifiedObject::NAME_KEY, crs1->nameStr() + " + " + crs2->nameStr()), {crs1, crs2}, dbContext); } } if (starts_with(text, "urn:ogc:def:crs,")) { if (!dbContext) { throw ParsingException("no database context specified"); } auto tokensComma = split(text, ','); if (tokensComma.size() == 4 && starts_with(tokensComma[1], "crs:") && starts_with(tokensComma[2], "cs:") && starts_with(tokensComma[3], "coordinateOperation:")) { // OGC 07-092r2: para 7.5.4 // URN combined references for projected or derived CRSs const auto &crsPart = tokensComma[1]; const auto tokensCRS = split(crsPart, ':'); if (tokensCRS.size() != 4) { throw ParsingException( concat("invalid crs component: ", crsPart)); } auto factoryCRS = AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensCRS[1]); auto baseCRS = factoryCRS->createCoordinateReferenceSystem(tokensCRS[3], true); const auto &csPart = tokensComma[2]; auto tokensCS = split(csPart, ':'); if (tokensCS.size() != 4) { throw ParsingException( concat("invalid cs component: ", csPart)); } auto factoryCS = AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensCS[1]); auto cs = factoryCS->createCoordinateSystem(tokensCS[3]); const auto &opPart = tokensComma[3]; auto tokensOp = split(opPart, ':'); if (tokensOp.size() != 4) { throw ParsingException( concat("invalid coordinateOperation component: ", opPart)); } auto factoryOp = AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensOp[1]); auto op = factoryOp->createCoordinateOperation(tokensOp[3], true); const auto &baseName = baseCRS->nameStr(); std::string name(baseName); auto geogCRS = util::nn_dynamic_pointer_cast<GeographicCRS>(baseCRS); if (geogCRS && geogCRS->coordinateSystem()->axisList().size() == 3 && baseName.find("3D") == std::string::npos) { name += " (3D)"; } name += " / "; name += op->nameStr(); auto props = util::PropertyMap().set(IdentifiedObject::NAME_KEY, name); if (auto conv = util::nn_dynamic_pointer_cast<Conversion>(op)) { auto convNN = NN_NO_CHECK(conv); if (geogCRS != nullptr) { auto geogCRSNN = NN_NO_CHECK(geogCRS); if (CartesianCSPtr ccs = util::nn_dynamic_pointer_cast<CartesianCS>(cs)) { return ProjectedCRS::create(props, geogCRSNN, convNN, NN_NO_CHECK(ccs)); } if (EllipsoidalCSPtr ecs = util::nn_dynamic_pointer_cast<EllipsoidalCS>(cs)) { return DerivedGeographicCRS::create( props, geogCRSNN, convNN, NN_NO_CHECK(ecs)); } } else if (dynamic_cast<GeodeticCRS *>(baseCRS.get()) && dynamic_cast<CartesianCS *>(cs.get())) { return DerivedGeodeticCRS::create( props, NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>( baseCRS)), convNN, NN_NO_CHECK( util::nn_dynamic_pointer_cast<CartesianCS>(cs))); } else if (auto pcrs = util::nn_dynamic_pointer_cast<ProjectedCRS>( baseCRS)) { return DerivedProjectedCRS::create(props, NN_NO_CHECK(pcrs), convNN, cs); } else if (auto vertBaseCRS = util::nn_dynamic_pointer_cast<VerticalCRS>( baseCRS)) { if (auto vertCS = util::nn_dynamic_pointer_cast<VerticalCS>(cs)) { const int methodCode = convNN->method()->getEPSGCode(); std::string newName(baseName); std::string unitNameSuffix; for (const char *suffix : {" (ft)", " (ftUS)"}) { if (ends_with(newName, suffix)) { unitNameSuffix = suffix; newName.resize(newName.size() - strlen(suffix)); break; } } bool newNameOk = false; if (methodCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR || methodCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT) { const auto &unitName = vertCS->axisList()[0]->unit().name(); if (unitName == UnitOfMeasure::METRE.name()) { newNameOk = true; } else if (unitName == UnitOfMeasure::FOOT.name()) { newName += " (ft)"; newNameOk = true; } else if (unitName == UnitOfMeasure::US_FOOT.name()) { newName += " (ftUS)"; newNameOk = true; } } else if (methodCode == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { if (ends_with(newName, " height")) { newName.resize(newName.size() - strlen(" height")); newName += " depth"; newName += unitNameSuffix; newNameOk = true; } else if (ends_with(newName, " depth")) { newName.resize(newName.size() - strlen(" depth")); newName += " height"; newName += unitNameSuffix; newNameOk = true; } } if (newNameOk) { props.set(IdentifiedObject::NAME_KEY, newName); } return DerivedVerticalCRS::create( props, NN_NO_CHECK(vertBaseCRS), convNN, NN_NO_CHECK(vertCS)); } } } throw ParsingException("unsupported combination of baseCRS, CS " "and coordinateOperation for a " "DerivedCRS"); } // OGC 07-092r2: para 7.5.2 // URN combined references for compound coordinate reference systems std::vector<CRSNNPtr> components; std::string name; for (size_t i = 1; i < tokensComma.size(); i++) { tokens = split(tokensComma[i], ':'); if (tokens.size() != 4) { throw ParsingException( concat("invalid crs component: ", tokensComma[i])); } const auto &type = tokens[0]; auto factory = AuthorityFactory::create(NN_NO_CHECK(dbContext), tokens[1]); const auto &code = tokens[3]; if (type == "crs") { auto crs(factory->createCoordinateReferenceSystem(code, false)); components.emplace_back(crs); if (!name.empty()) { name += " + "; } name += crs->nameStr(); } else { throw ParsingException( concat("unexpected object type: ", type)); } } return CompoundCRS::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, name), components); } // OGC 07-092r2: para 7.5.3 // 7.5.3 URN combined references for concatenated operations if (starts_with(text, "urn:ogc:def:coordinateOperation,")) { if (!dbContext) { throw ParsingException("no database context specified"); } auto tokensComma = split(text, ','); std::vector<CoordinateOperationNNPtr> components; for (size_t i = 1; i < tokensComma.size(); i++) { tokens = split(tokensComma[i], ':'); if (tokens.size() != 4) { throw ParsingException(concat( "invalid coordinateOperation component: ", tokensComma[i])); } const auto &type = tokens[0]; auto factory = AuthorityFactory::create(NN_NO_CHECK(dbContext), tokens[1]); const auto &code = tokens[3]; if (type == "coordinateOperation") { auto op(factory->createCoordinateOperation(code, false)); components.emplace_back(op); } else { throw ParsingException( concat("unexpected object type: ", type)); } } return ConcatenatedOperation::createComputeMetadata(components, true); } // urn:ogc:def:crs:EPSG::4326 if (tokens.size() == 7 && tolower(tokens[0]) == "urn") { const std::string type(tokens[3] == "CRS" ? "crs" : tokens[3]); const auto &authName = tokens[4]; const auto &version = tokens[5]; const auto &code = tokens[6]; return createFromURNPart(dbContext, type, authName, version, code); } // urn:ogc:def:crs:OGC::AUTO42001:-117:33 if (tokens.size() > 7 && tokens[0] == "urn" && tokens[4] == "OGC" && ci_starts_with(tokens[6], "AUTO")) { const auto textAUTO = text.substr(text.find(":AUTO") + 5); return importFromWMSAUTO("AUTO:" + replaceAll(textAUTO, ":", ",")); } // Legacy urn:opengis:crs:EPSG:0:4326 (note the missing def: compared to // above) if (tokens.size() == 6 && tokens[0] == "urn" && tokens[2] != "def") { const auto &type = tokens[2]; const auto &authName = tokens[3]; const auto &version = tokens[4]; const auto &code = tokens[5]; return createFromURNPart(dbContext, type, authName, version, code); } // Legacy urn:x-ogc:def:crs:EPSG:4326 (note the missing version) if (tokens.size() == 6 && tokens[0] == "urn") { const auto &type = tokens[3]; const auto &authName = tokens[4]; const auto &code = tokens[5]; return createFromURNPart(dbContext, type, authName, std::string(), code); } if (dbContext) { auto factory = AuthorityFactory::create(NN_NO_CHECK(dbContext), std::string()); const auto searchObject = [&factory]( const std::string &objectName, bool approximateMatch, const std::vector<AuthorityFactory::ObjectType> &objectTypes) -> IdentifiedObjectPtr { constexpr size_t limitResultCount = 10; auto res = factory->createObjectsFromName( objectName, objectTypes, approximateMatch, limitResultCount); if (res.size() == 1) { return res.front().as_nullable(); } if (res.size() > 1) { if (objectTypes.size() == 1 && objectTypes[0] == AuthorityFactory::ObjectType::CRS) { for (size_t ndim = 2; ndim <= 3; ndim++) { for (const auto &obj : res) { auto crs = dynamic_cast<crs::GeographicCRS *>(obj.get()); if (crs && crs->coordinateSystem()->axisList().size() == ndim) { return obj.as_nullable(); } } } } // If there's exactly only one object whose name is equivalent // to the user input, return it. IdentifiedObjectPtr identifiedObj; for (const auto &obj : res) { if (Identifier::isEquivalentName(obj->nameStr().c_str(), objectName.c_str())) { if (identifiedObj == nullptr) { identifiedObj = obj.as_nullable(); } else { identifiedObj = nullptr; break; } } } if (identifiedObj) { return identifiedObj; } std::string msg("several objects matching this name: "); bool first = true; for (const auto &obj : res) { if (msg.size() > 200) { msg += ", ..."; break; } if (!first) { msg += ", "; } first = false; msg += obj->nameStr(); } throw ParsingException(msg); } return nullptr; }; const auto searchCRS = [&searchObject](const std::string &objectName) { const auto objectTypes = std::vector<AuthorityFactory::ObjectType>{ AuthorityFactory::ObjectType::CRS}; { constexpr bool approximateMatch = false; auto ret = searchObject(objectName, approximateMatch, objectTypes); if (ret) return ret; } constexpr bool approximateMatch = true; return searchObject(objectName, approximateMatch, objectTypes); }; // strings like "WGS 84 + EGM96 height" CompoundCRSPtr compoundCRS; try { const auto tokensCompound = split(text, " + "); if (tokensCompound.size() == 2) { auto obj1 = searchCRS(tokensCompound[0]); auto obj2 = searchCRS(tokensCompound[1]); auto crs1 = std::dynamic_pointer_cast<CRS>(obj1); auto crs2 = std::dynamic_pointer_cast<CRS>(obj2); if (crs1 && crs2) { compoundCRS = CompoundCRS::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, crs1->nameStr() + " + " + crs2->nameStr()), {NN_NO_CHECK(crs1), NN_NO_CHECK(crs2)}) .as_nullable(); } } } catch (const std::exception &) { } // First pass: exact match on CRS objects // Second pass: exact match on other objects // Third pass: approximate match on CRS objects // Fourth pass: approximate match on other objects // But only allow approximate matching if the size of the text is // large enough (>= 5), otherwise we get a lot of false positives: // "foo" -> "Amersfoort", "bar" -> "Barbados 1938" // Also only accept approximate matching if the ratio between the // input and match size is not too small, so that "omerc" doesn't match // with "WGS 84 / Pseudo-Mercator" const int maxNumberPasses = text.size() <= 4 ? 2 : 4; for (int pass = 0; pass < maxNumberPasses; ++pass) { const bool approximateMatch = (pass >= 2); auto ret = searchObject( text, approximateMatch, (pass == 0 || pass == 2) ? std::vector< AuthorityFactory::ObjectType>{AuthorityFactory:: ObjectType::CRS} : std::vector<AuthorityFactory::ObjectType>{ AuthorityFactory::ObjectType::ELLIPSOID, AuthorityFactory::ObjectType::DATUM, AuthorityFactory::ObjectType::DATUM_ENSEMBLE, AuthorityFactory::ObjectType::COORDINATE_OPERATION}); if (ret) { if (!approximateMatch || ret->nameStr().size() < 2 * text.size()) return NN_NO_CHECK(ret); } if (compoundCRS) { if (!approximateMatch || compoundCRS->nameStr().size() < 2 * text.size()) return NN_NO_CHECK(compoundCRS); } } } throw ParsingException("unrecognized format / unknown name"); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a sub-class of BaseObject from a user specified text. * * The text can be a: * <ul> * <li>WKT string</li> * <li>PROJ string</li> * <li>database code, prefixed by its authority. e.g. "EPSG:4326"</li> * <li>OGC URN. e.g. "urn:ogc:def:crs:EPSG::4326", * "urn:ogc:def:coordinateOperation:EPSG::1671", * "urn:ogc:def:ellipsoid:EPSG::7001" * or "urn:ogc:def:datum:EPSG::6326"</li> * <li> OGC URN combining references for compound coordinate reference systems * e.g. "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717" * We also accept a custom abbreviated syntax EPSG:2393+5717 * or ESRI:103668+EPSG:5703 * </li> * <li> OGC URN combining references for references for projected or derived * CRSs * e.g. for Projected 3D CRS "UTM zone 31N / WGS 84 (3D)" * "urn:ogc:def:crs,crs:EPSG::4979,cs:PROJ::ENh,coordinateOperation:EPSG::16031" * </li> * <li>Extension of OGC URN for CoordinateMetadata. * e.g. * "urn:ogc:def:coordinateMetadata:NRCAN::NAD83_CSRS_1997_MTM11_HT2_1997"</li> * <li> OGC URN combining references for concatenated operations * e.g. * "urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618"</li> * <li>OGC URL for a single CRS. e.g. * "http://www.opengis.net/def/crs/EPSG/0/4326"</li> * <li>OGC URL for a compound * CRS. e.g * "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/3855"</li> * <li>an Object name. e.g "WGS 84", "WGS 84 / UTM zone 31N". In that case as * uniqueness is not guaranteed, the function may apply heuristics to * determine the appropriate best match.</li> * <li>a CRS name and a coordinate epoch, separated with '@'. For example * "[email protected]". (added in PROJ 9.2)</li> * <li>a compound CRS made from two object names separated with " + ". * e.g. "WGS 84 + EGM96 height"</li> * <li>PROJJSON string</li> * </ul> * * @param text One of the above mentioned text format * @param dbContext Database context, or nullptr (in which case database * lookups will not work) * @param usePROJ4InitRules When set to true, * init=epsg:XXXX syntax will be allowed and will be interpreted according to * PROJ.4 and PROJ.5 rules, that is geodeticCRS will have longitude, latitude * order and will expect/output coordinates in radians. ProjectedCRS will have * easting, northing axis order (except the ones with Transverse Mercator South * Orientated projection). In that mode, the epsg:XXXX syntax will be also * interpreted the same way. * @throw ParsingException */ BaseObjectNNPtr createFromUserInput(const std::string &text, const DatabaseContextPtr &dbContext, bool usePROJ4InitRules) { return createFromUserInput(text, dbContext, usePROJ4InitRules, nullptr, /* ignoreCoordinateEpoch = */ false); } // --------------------------------------------------------------------------- /** \brief Instantiate a sub-class of BaseObject from a user specified text. * * The text can be a: * <ul> * <li>WKT string</li> * <li>PROJ string</li> * <li>database code, prefixed by its authority. e.g. "EPSG:4326"</li> * <li>OGC URN. e.g. "urn:ogc:def:crs:EPSG::4326", * "urn:ogc:def:coordinateOperation:EPSG::1671", * "urn:ogc:def:ellipsoid:EPSG::7001" * or "urn:ogc:def:datum:EPSG::6326"</li> * <li> OGC URN combining references for compound coordinate reference systems * e.g. "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717" * We also accept a custom abbreviated syntax EPSG:2393+5717 * </li> * <li> OGC URN combining references for references for projected or derived * CRSs * e.g. for Projected 3D CRS "UTM zone 31N / WGS 84 (3D)" * "urn:ogc:def:crs,crs:EPSG::4979,cs:PROJ::ENh,coordinateOperation:EPSG::16031" * </li> * <li>Extension of OGC URN for CoordinateMetadata. * e.g. * "urn:ogc:def:coordinateMetadata:NRCAN::NAD83_CSRS_1997_MTM11_HT2_1997"</li> * <li> OGC URN combining references for concatenated operations * e.g. * "urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618"</li> * <li>an Object name. e.g "WGS 84", "WGS 84 / UTM zone 31N". In that case as * uniqueness is not guaranteed, the function may apply heuristics to * determine the appropriate best match.</li> * <li>a compound CRS made from two object names separated with " + ". * e.g. "WGS 84 + EGM96 height"</li> * <li>PROJJSON string</li> * </ul> * * @param text One of the above mentioned text format * @param ctx PROJ context * @throw ParsingException */ BaseObjectNNPtr createFromUserInput(const std::string &text, PJ_CONTEXT *ctx) { DatabaseContextPtr dbContext; try { if (ctx != nullptr) { // Only connect to proj.db if needed if (text.find("proj=") == std::string::npos || text.find("init=") != std::string::npos) { dbContext = ctx->get_cpp_context()->getDatabaseContext().as_nullable(); } } } catch (const std::exception &) { } return createFromUserInput(text, dbContext, false, ctx, /* ignoreCoordinateEpoch = */ false); } // --------------------------------------------------------------------------- /** \brief Instantiate a sub-class of BaseObject from a WKT string. * * By default, validation is strict (to the extent of the checks that are * actually implemented. Currently only WKT1 strict grammar is checked), and * any issue detected will cause an exception to be thrown, unless * setStrict(false) is called priorly. * * In non-strict mode, non-fatal issues will be recovered and simply listed * in warningList(). This does not prevent more severe errors to cause an * exception to be thrown. * * @throw ParsingException */ BaseObjectNNPtr WKTParser::createFromWKT(const std::string &wkt) { const auto dialect = guessDialect(wkt); d->maybeEsriStyle_ = (dialect == WKTGuessedDialect::WKT1_ESRI); if (d->maybeEsriStyle_) { if (wkt.find("PARAMETER[\"X_Scale\",") != std::string::npos) { d->esriStyle_ = true; d->maybeEsriStyle_ = false; } } const auto build = [this, &wkt]() -> BaseObjectNNPtr { size_t indexEnd; WKTNodeNNPtr root = WKTNode::createFrom(wkt, 0, 0, indexEnd); const std::string &name(root->GP()->value()); if (ci_equal(name, WKTConstants::DATUM) || ci_equal(name, WKTConstants::GEODETICDATUM) || ci_equal(name, WKTConstants::TRF)) { auto primeMeridian = PrimeMeridian::GREENWICH; if (indexEnd < wkt.size()) { indexEnd = skipSpace(wkt, indexEnd); if (indexEnd < wkt.size() && wkt[indexEnd] == ',') { ++indexEnd; indexEnd = skipSpace(wkt, indexEnd); if (indexEnd < wkt.size() && ci_starts_with(wkt.c_str() + indexEnd, WKTConstants::PRIMEM.c_str())) { primeMeridian = d->buildPrimeMeridian( WKTNode::createFrom(wkt, indexEnd, 0, indexEnd), UnitOfMeasure::DEGREE); } } } return d->buildGeodeticReferenceFrame(root, primeMeridian, null_node); } else if (ci_equal(name, WKTConstants::GEOGCS) || ci_equal(name, WKTConstants::PROJCS)) { // Parse implicit compoundCRS from ESRI that is // "PROJCS[...],VERTCS[...]" or "GEOGCS[...],VERTCS[...]" if (indexEnd < wkt.size()) { indexEnd = skipSpace(wkt, indexEnd); if (indexEnd < wkt.size() && wkt[indexEnd] == ',') { ++indexEnd; indexEnd = skipSpace(wkt, indexEnd); if (indexEnd < wkt.size() && ci_starts_with(wkt.c_str() + indexEnd, WKTConstants::VERTCS.c_str())) { auto horizCRS = d->buildCRS(root); if (horizCRS) { auto vertCRS = d->buildVerticalCRS(WKTNode::createFrom( wkt, indexEnd, 0, indexEnd)); return CompoundCRS::createLax( util::PropertyMap().set( IdentifiedObject::NAME_KEY, horizCRS->nameStr() + " + " + vertCRS->nameStr()), {NN_NO_CHECK(horizCRS), vertCRS}, d->dbContext_); } } } } } return d->build(root); }; auto obj = build(); if (dialect == WKTGuessedDialect::WKT1_GDAL || dialect == WKTGuessedDialect::WKT1_ESRI) { auto errorMsg = pj_wkt1_parse(wkt); if (!errorMsg.empty()) { d->emitRecoverableWarning(errorMsg); } } else if (dialect == WKTGuessedDialect::WKT2_2015 || dialect == WKTGuessedDialect::WKT2_2019) { auto errorMsg = pj_wkt2_parse(wkt); if (!errorMsg.empty()) { d->emitRecoverableWarning(errorMsg); } } return obj; } // --------------------------------------------------------------------------- /** \brief Attach a database context, to allow queries in it if needed. */ WKTParser & WKTParser::attachDatabaseContext(const DatabaseContextPtr &dbContext) { d->dbContext_ = dbContext; return *this; } // --------------------------------------------------------------------------- /** \brief Guess the "dialect" of the WKT string. */ WKTParser::WKTGuessedDialect WKTParser::guessDialect(const std::string &inputWkt) noexcept { std::string wkt = inputWkt; std::size_t idxFirstCharNotSpace = wkt.find_first_not_of(" \t\r\n"); if (idxFirstCharNotSpace > 0 && idxFirstCharNotSpace != std::string::npos) { wkt = wkt.substr(idxFirstCharNotSpace); } if (ci_starts_with(wkt, WKTConstants::VERTCS)) { return WKTGuessedDialect::WKT1_ESRI; } const std::string *const wkt1_keywords[] = { &WKTConstants::GEOCCS, &WKTConstants::GEOGCS, &WKTConstants::COMPD_CS, &WKTConstants::PROJCS, &WKTConstants::VERT_CS, &WKTConstants::LOCAL_CS}; for (const auto &pointerKeyword : wkt1_keywords) { if (ci_starts_with(wkt, *pointerKeyword)) { if ((ci_find(wkt, "GEOGCS[\"GCS_") != std::string::npos || (!ci_starts_with(wkt, WKTConstants::LOCAL_CS) && ci_find(wkt, "AXIS[") == std::string::npos && ci_find(wkt, "AUTHORITY[") == std::string::npos)) && // WKT1:GDAL and WKT1:ESRI have both a // Hotine_Oblique_Mercator_Azimuth_Center If providing a // WKT1:GDAL without AXIS, we may wrongly detect it as WKT1:ESRI // and skip the rectified_grid_angle parameter cf // https://github.com/OSGeo/PROJ/issues/3279 ci_find(wkt, "PARAMETER[\"rectified_grid_angle") == std::string::npos) { return WKTGuessedDialect::WKT1_ESRI; } return WKTGuessedDialect::WKT1_GDAL; } } const std::string *const wkt2_2019_only_keywords[] = { &WKTConstants::GEOGCRS, // contained in previous one // &WKTConstants::BASEGEOGCRS, &WKTConstants::CONCATENATEDOPERATION, &WKTConstants::USAGE, &WKTConstants::DYNAMIC, &WKTConstants::FRAMEEPOCH, &WKTConstants::MODEL, &WKTConstants::VELOCITYGRID, &WKTConstants::ENSEMBLE, &WKTConstants::DERIVEDPROJCRS, &WKTConstants::BASEPROJCRS, &WKTConstants::GEOGRAPHICCRS, &WKTConstants::TRF, &WKTConstants::VRF, &WKTConstants::POINTMOTIONOPERATION}; for (const auto &pointerKeyword : wkt2_2019_only_keywords) { auto pos = ci_find(wkt, *pointerKeyword); if (pos != std::string::npos && wkt[pos + pointerKeyword->size()] == '[') { return WKTGuessedDialect::WKT2_2019; } } static const char *const wkt2_2019_only_substrings[] = { "CS[TemporalDateTime,", "CS[TemporalCount,", "CS[TemporalMeasure,", }; for (const auto &substrings : wkt2_2019_only_substrings) { if (ci_find(wkt, substrings) != std::string::npos) { return WKTGuessedDialect::WKT2_2019; } } for (const auto &wktConstant : WKTConstants::constants()) { if (ci_starts_with(wkt, wktConstant)) { for (auto wktPtr = wkt.c_str() + wktConstant.size(); *wktPtr != '\0'; ++wktPtr) { if (isspace(static_cast<unsigned char>(*wktPtr))) continue; if (*wktPtr == '[') { return WKTGuessedDialect::WKT2_2015; } break; } } } return WKTGuessedDialect::NOT_WKT; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress FormattingException::FormattingException(const char *message) : Exception(message) {} // --------------------------------------------------------------------------- FormattingException::FormattingException(const std::string &message) : Exception(message) {} // --------------------------------------------------------------------------- FormattingException::FormattingException(const FormattingException &) = default; // --------------------------------------------------------------------------- FormattingException::~FormattingException() = default; // --------------------------------------------------------------------------- void FormattingException::Throw(const char *msg) { throw FormattingException(msg); } // --------------------------------------------------------------------------- void FormattingException::Throw(const std::string &msg) { throw FormattingException(msg); } // --------------------------------------------------------------------------- ParsingException::ParsingException(const char *message) : Exception(message) {} // --------------------------------------------------------------------------- ParsingException::ParsingException(const std::string &message) : Exception(message) {} // --------------------------------------------------------------------------- ParsingException::ParsingException(const ParsingException &) = default; // --------------------------------------------------------------------------- ParsingException::~ParsingException() = default; // --------------------------------------------------------------------------- IPROJStringExportable::~IPROJStringExportable() = default; // --------------------------------------------------------------------------- std::string IPROJStringExportable::exportToPROJString( PROJStringFormatter *formatter) const { const bool bIsCRS = dynamic_cast<const crs::CRS *>(this) != nullptr; if (bIsCRS) { formatter->setCRSExport(true); } _exportToPROJString(formatter); if (formatter->getAddNoDefs() && bIsCRS) { if (!formatter->hasParam("no_defs")) { formatter->addParam("no_defs"); } } if (bIsCRS) { if (!formatter->hasParam("type")) { formatter->addParam("type", "crs"); } formatter->setCRSExport(false); } return formatter->toString(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Step { std::string name{}; bool isInit = false; bool inverted{false}; struct KeyValue { std::string key{}; std::string value{}; bool usedByParser = false; // only for PROJStringParser used explicit KeyValue(const std::string &keyIn) : key(keyIn) {} KeyValue(const char *keyIn, const std::string &valueIn); KeyValue(const std::string &keyIn, const std::string &valueIn) : key(keyIn), value(valueIn) {} // cppcheck-suppress functionStatic bool keyEquals(const char *otherKey) const noexcept { return key == otherKey; } // cppcheck-suppress functionStatic bool equals(const char *otherKey, const char *otherVal) const noexcept { return key == otherKey && value == otherVal; } bool operator==(const KeyValue &other) const noexcept { return key == other.key && value == other.value; } bool operator!=(const KeyValue &other) const noexcept { return key != other.key || value != other.value; } }; std::vector<KeyValue> paramValues{}; bool hasKey(const char *keyName) const { for (const auto &kv : paramValues) { if (kv.key == keyName) { return true; } } return false; } }; Step::KeyValue::KeyValue(const char *keyIn, const std::string &valueIn) : key(keyIn), value(valueIn) {} struct PROJStringFormatter::Private { PROJStringFormatter::Convention convention_ = PROJStringFormatter::Convention::PROJ_5; std::vector<double> toWGS84Parameters_{}; std::string vDatumExtension_{}; std::string geoidCRSValue_{}; std::string hDatumExtension_{}; crs::GeographicCRSPtr geogCRSOfCompoundCRS_{}; std::list<Step> steps_{}; std::vector<Step::KeyValue> globalParamValues_{}; struct InversionStackElt { std::list<Step>::iterator startIter{}; bool iterValid = false; bool currentInversionState = false; }; std::vector<InversionStackElt> inversionStack_{InversionStackElt()}; bool omitProjLongLatIfPossible_ = false; std::vector<bool> omitZUnitConversion_{false}; std::vector<bool> omitHorizontalConversionInVertTransformation_{false}; DatabaseContextPtr dbContext_{}; bool useApproxTMerc_ = false; bool addNoDefs_ = true; bool coordOperationOptimizations_ = false; bool crsExport_ = false; bool legacyCRSToCRSContext_ = false; bool multiLine_ = false; bool normalizeOutput_ = false; int indentWidth_ = 2; int indentLevel_ = 0; int maxLineLength_ = 80; std::string result_{}; // cppcheck-suppress functionStatic void appendToResult(const char *str); // cppcheck-suppress functionStatic void addStep(); }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PROJStringFormatter::PROJStringFormatter(Convention conventionIn, const DatabaseContextPtr &dbContext) : d(internal::make_unique<Private>()) { d->convention_ = conventionIn; d->dbContext_ = dbContext; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PROJStringFormatter::~PROJStringFormatter() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Constructs a new formatter. * * A formatter can be used only once (its internal state is mutated) * * Its default behavior can be adjusted with the different setters. * * @param conventionIn PROJ string flavor. Defaults to Convention::PROJ_5 * @param dbContext Database context (can help to find alternative grid names). * May be nullptr * @return new formatter. */ PROJStringFormatterNNPtr PROJStringFormatter::create(Convention conventionIn, DatabaseContextPtr dbContext) { return NN_NO_CHECK(PROJStringFormatter::make_unique<PROJStringFormatter>( conventionIn, dbContext)); } // --------------------------------------------------------------------------- /** \brief Set whether approximate Transverse Mercator or UTM should be used */ void PROJStringFormatter::setUseApproxTMerc(bool flag) { d->useApproxTMerc_ = flag; } // --------------------------------------------------------------------------- /** \brief Whether to use multi line output or not. */ PROJStringFormatter & PROJStringFormatter::setMultiLine(bool multiLine) noexcept { d->multiLine_ = multiLine; return *this; } // --------------------------------------------------------------------------- /** \brief Set number of spaces for each indentation level (defaults to 2). */ PROJStringFormatter & PROJStringFormatter::setIndentationWidth(int width) noexcept { d->indentWidth_ = width; return *this; } // --------------------------------------------------------------------------- /** \brief Set the maximum size of a line (when multiline output is enable). * Can be set to 0 for unlimited length. */ PROJStringFormatter & PROJStringFormatter::setMaxLineLength(int maxLineLength) noexcept { d->maxLineLength_ = maxLineLength; return *this; } // --------------------------------------------------------------------------- /** \brief Returns the PROJ string. */ const std::string &PROJStringFormatter::toString() const { assert(d->inversionStack_.size() == 1); d->result_.clear(); auto &steps = d->steps_; if (d->normalizeOutput_) { // Sort +key=value options of each step in lexicographic order. for (auto &step : steps) { std::sort(step.paramValues.begin(), step.paramValues.end(), [](const Step::KeyValue &a, const Step::KeyValue &b) { return a.key < b.key; }); } } for (auto iter = steps.begin(); iter != steps.end();) { // Remove no-op helmert auto &step = *iter; const auto paramCount = step.paramValues.size(); if (step.name == "helmert" && (paramCount == 3 || paramCount == 8) && step.paramValues[0].equals("x", "0") && step.paramValues[1].equals("y", "0") && step.paramValues[2].equals("z", "0") && (paramCount == 3 || (step.paramValues[3].equals("rx", "0") && step.paramValues[4].equals("ry", "0") && step.paramValues[5].equals("rz", "0") && step.paramValues[6].equals("s", "0") && step.paramValues[7].keyEquals("convention")))) { iter = steps.erase(iter); } else if (d->coordOperationOptimizations_ && step.name == "unitconvert" && paramCount == 2 && step.paramValues[0].keyEquals("xy_in") && step.paramValues[1].keyEquals("xy_out") && step.paramValues[0].value == step.paramValues[1].value) { iter = steps.erase(iter); } else if (step.name == "push" && step.inverted) { step.name = "pop"; step.inverted = false; ++iter; } else if (step.name == "pop" && step.inverted) { step.name = "push"; step.inverted = false; ++iter; } else if (step.name == "noop" && steps.size() > 1) { iter = steps.erase(iter); } else { ++iter; } } for (auto &step : steps) { if (!step.inverted) { continue; } const auto paramCount = step.paramValues.size(); // axisswap order=2,1 (or 1,-2) is its own inverse if (step.name == "axisswap" && paramCount == 1 && (step.paramValues[0].equals("order", "2,1") || step.paramValues[0].equals("order", "1,-2"))) { step.inverted = false; continue; } // axisswap inv order=2,-1 ==> axisswap order -2,1 if (step.name == "axisswap" && paramCount == 1 && step.paramValues[0].equals("order", "2,-1")) { step.inverted = false; step.paramValues[0] = Step::KeyValue("order", "-2,1"); continue; } // axisswap order=1,2,-3 is its own inverse if (step.name == "axisswap" && paramCount == 1 && step.paramValues[0].equals("order", "1,2,-3")) { step.inverted = false; continue; } // handle unitconvert inverse if (step.name == "unitconvert" && paramCount == 2 && step.paramValues[0].keyEquals("xy_in") && step.paramValues[1].keyEquals("xy_out")) { std::swap(step.paramValues[0].value, step.paramValues[1].value); step.inverted = false; continue; } if (step.name == "unitconvert" && paramCount == 2 && step.paramValues[0].keyEquals("z_in") && step.paramValues[1].keyEquals("z_out")) { std::swap(step.paramValues[0].value, step.paramValues[1].value); step.inverted = false; continue; } if (step.name == "unitconvert" && paramCount == 4 && step.paramValues[0].keyEquals("xy_in") && step.paramValues[1].keyEquals("z_in") && step.paramValues[2].keyEquals("xy_out") && step.paramValues[3].keyEquals("z_out")) { std::swap(step.paramValues[0].value, step.paramValues[2].value); std::swap(step.paramValues[1].value, step.paramValues[3].value); step.inverted = false; continue; } } { auto iterCur = steps.begin(); if (iterCur != steps.end()) { ++iterCur; } while (iterCur != steps.end()) { assert(iterCur != steps.begin()); auto iterPrev = std::prev(iterCur); auto &prevStep = *iterPrev; auto &curStep = *iterCur; const auto curStepParamCount = curStep.paramValues.size(); const auto prevStepParamCount = prevStep.paramValues.size(); const auto deletePrevAndCurIter = [&steps, &iterPrev, &iterCur]() { iterCur = steps.erase(iterPrev, std::next(iterCur)); if (iterCur != steps.begin()) iterCur = std::prev(iterCur); if (iterCur == steps.begin() && iterCur != steps.end()) ++iterCur; }; // longlat (or its inverse) with ellipsoid only is a no-op // do that only for an internal step if (std::next(iterCur) != steps.end() && curStep.name == "longlat" && curStepParamCount == 1 && curStep.paramValues[0].keyEquals("ellps")) { iterCur = steps.erase(iterCur); continue; } // push v_x followed by pop v_x is a no-op. if (curStep.name == "pop" && prevStep.name == "push" && !curStep.inverted && !prevStep.inverted && curStepParamCount == 1 && prevStepParamCount == 1 && curStep.paramValues[0].key == prevStep.paramValues[0].key) { deletePrevAndCurIter(); continue; } // pop v_x followed by push v_x is, almost, a no-op. For our // purposes, // we consider it as a no-op for better pipeline optimizations. if (curStep.name == "push" && prevStep.name == "pop" && !curStep.inverted && !prevStep.inverted && curStepParamCount == 1 && prevStepParamCount == 1 && curStep.paramValues[0].key == prevStep.paramValues[0].key) { deletePrevAndCurIter(); continue; } // unitconvert (xy) followed by its inverse is a no-op if (curStep.name == "unitconvert" && prevStep.name == "unitconvert" && !curStep.inverted && !prevStep.inverted && curStepParamCount == 2 && prevStepParamCount == 2 && curStep.paramValues[0].keyEquals("xy_in") && prevStep.paramValues[0].keyEquals("xy_in") && curStep.paramValues[1].keyEquals("xy_out") && prevStep.paramValues[1].keyEquals("xy_out") && curStep.paramValues[0].value == prevStep.paramValues[1].value && curStep.paramValues[1].value == prevStep.paramValues[0].value) { deletePrevAndCurIter(); continue; } // unitconvert (z) followed by its inverse is a no-op if (curStep.name == "unitconvert" && prevStep.name == "unitconvert" && !curStep.inverted && !prevStep.inverted && curStepParamCount == 2 && prevStepParamCount == 2 && curStep.paramValues[0].keyEquals("z_in") && prevStep.paramValues[0].keyEquals("z_in") && curStep.paramValues[1].keyEquals("z_out") && prevStep.paramValues[1].keyEquals("z_out") && curStep.paramValues[0].value == prevStep.paramValues[1].value && curStep.paramValues[1].value == prevStep.paramValues[0].value) { deletePrevAndCurIter(); continue; } // unitconvert (xyz) followed by its inverse is a no-op if (curStep.name == "unitconvert" && prevStep.name == "unitconvert" && !curStep.inverted && !prevStep.inverted && curStepParamCount == 4 && prevStepParamCount == 4 && curStep.paramValues[0].keyEquals("xy_in") && prevStep.paramValues[0].keyEquals("xy_in") && curStep.paramValues[1].keyEquals("z_in") && prevStep.paramValues[1].keyEquals("z_in") && curStep.paramValues[2].keyEquals("xy_out") && prevStep.paramValues[2].keyEquals("xy_out") && curStep.paramValues[3].keyEquals("z_out") && prevStep.paramValues[3].keyEquals("z_out") && curStep.paramValues[0].value == prevStep.paramValues[2].value && curStep.paramValues[1].value == prevStep.paramValues[3].value && curStep.paramValues[2].value == prevStep.paramValues[0].value && curStep.paramValues[3].value == prevStep.paramValues[1].value) { deletePrevAndCurIter(); continue; } const auto deletePrevIter = [&steps, &iterPrev, &iterCur]() { steps.erase(iterPrev, iterCur); if (iterCur != steps.begin()) iterCur = std::prev(iterCur); if (iterCur == steps.begin()) ++iterCur; }; // combine unitconvert (xy) and unitconvert (z) bool changeDone = false; for (int k = 0; k < 2; ++k) { auto &first = (k == 0) ? curStep : prevStep; auto &second = (k == 0) ? prevStep : curStep; if (first.name == "unitconvert" && second.name == "unitconvert" && !first.inverted && !second.inverted && first.paramValues.size() == 2 && second.paramValues.size() == 2 && second.paramValues[0].keyEquals("xy_in") && second.paramValues[1].keyEquals("xy_out") && first.paramValues[0].keyEquals("z_in") && first.paramValues[1].keyEquals("z_out")) { const std::string xy_in(second.paramValues[0].value); const std::string xy_out(second.paramValues[1].value); const std::string z_in(first.paramValues[0].value); const std::string z_out(first.paramValues[1].value); iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("xy_in", xy_in)); iterCur->paramValues.emplace_back( Step::KeyValue("z_in", z_in)); iterCur->paramValues.emplace_back( Step::KeyValue("xy_out", xy_out)); iterCur->paramValues.emplace_back( Step::KeyValue("z_out", z_out)); deletePrevIter(); changeDone = true; break; } } if (changeDone) { continue; } // +step +proj=unitconvert +xy_in=X1 +xy_out=X2 // +step +proj=unitconvert +xy_in=X2 +z_in=Z1 +xy_out=X1 +z_out=Z2 // ==> step +proj=unitconvert +z_in=Z1 +z_out=Z2 for (int k = 0; k < 2; ++k) { auto &first = (k == 0) ? curStep : prevStep; auto &second = (k == 0) ? prevStep : curStep; if (first.name == "unitconvert" && second.name == "unitconvert" && !first.inverted && !second.inverted && first.paramValues.size() == 4 && second.paramValues.size() == 2 && first.paramValues[0].keyEquals("xy_in") && first.paramValues[1].keyEquals("z_in") && first.paramValues[2].keyEquals("xy_out") && first.paramValues[3].keyEquals("z_out") && second.paramValues[0].keyEquals("xy_in") && second.paramValues[1].keyEquals("xy_out") && first.paramValues[0].value == second.paramValues[1].value && first.paramValues[2].value == second.paramValues[0].value) { const std::string z_in(first.paramValues[1].value); const std::string z_out(first.paramValues[3].value); if (z_in != z_out) { iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("z_in", z_in)); iterCur->paramValues.emplace_back( Step::KeyValue("z_out", z_out)); deletePrevIter(); } else { deletePrevAndCurIter(); } changeDone = true; break; } } if (changeDone) { continue; } // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2 // +step +proj=unitconvert +z_in=Z2 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 // +z_out=Z3 if (prevStep.name == "unitconvert" && curStep.name == "unitconvert" && !prevStep.inverted && !curStep.inverted && prevStep.paramValues.size() == 4 && curStep.paramValues.size() == 2 && prevStep.paramValues[0].keyEquals("xy_in") && prevStep.paramValues[1].keyEquals("z_in") && prevStep.paramValues[2].keyEquals("xy_out") && prevStep.paramValues[3].keyEquals("z_out") && curStep.paramValues[0].keyEquals("z_in") && curStep.paramValues[1].keyEquals("z_out") && prevStep.paramValues[3].value == curStep.paramValues[0].value) { const std::string xy_in(prevStep.paramValues[0].value); const std::string z_in(prevStep.paramValues[1].value); const std::string xy_out(prevStep.paramValues[2].value); const std::string z_out(curStep.paramValues[1].value); iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("xy_in", xy_in)); iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in)); iterCur->paramValues.emplace_back( Step::KeyValue("xy_out", xy_out)); iterCur->paramValues.emplace_back( Step::KeyValue("z_out", z_out)); deletePrevIter(); continue; } // +step +proj=unitconvert +z_in=Z1 +z_out=Z2 // +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X2 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 // +z_out=Z3 if (prevStep.name == "unitconvert" && curStep.name == "unitconvert" && !prevStep.inverted && !curStep.inverted && prevStep.paramValues.size() == 2 && curStep.paramValues.size() == 4 && prevStep.paramValues[0].keyEquals("z_in") && prevStep.paramValues[1].keyEquals("z_out") && curStep.paramValues[0].keyEquals("xy_in") && curStep.paramValues[1].keyEquals("z_in") && curStep.paramValues[2].keyEquals("xy_out") && curStep.paramValues[3].keyEquals("z_out") && prevStep.paramValues[1].value == curStep.paramValues[1].value) { const std::string xy_in(curStep.paramValues[0].value); const std::string z_in(prevStep.paramValues[0].value); const std::string xy_out(curStep.paramValues[2].value); const std::string z_out(curStep.paramValues[3].value); iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("xy_in", xy_in)); iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in)); iterCur->paramValues.emplace_back( Step::KeyValue("xy_out", xy_out)); iterCur->paramValues.emplace_back( Step::KeyValue("z_out", z_out)); deletePrevIter(); continue; } // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2 // +step +proj=unitconvert +xy_in=X2 +xy_out=X3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3 // +z_out=Z2 if (prevStep.name == "unitconvert" && curStep.name == "unitconvert" && !prevStep.inverted && !curStep.inverted && prevStep.paramValues.size() == 4 && curStep.paramValues.size() == 2 && prevStep.paramValues[0].keyEquals("xy_in") && prevStep.paramValues[1].keyEquals("z_in") && prevStep.paramValues[2].keyEquals("xy_out") && prevStep.paramValues[3].keyEquals("z_out") && curStep.paramValues[0].keyEquals("xy_in") && curStep.paramValues[1].keyEquals("xy_out") && prevStep.paramValues[2].value == curStep.paramValues[0].value) { const std::string xy_in(prevStep.paramValues[0].value); const std::string z_in(prevStep.paramValues[1].value); const std::string xy_out(curStep.paramValues[1].value); const std::string z_out(prevStep.paramValues[3].value); iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("xy_in", xy_in)); iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in)); iterCur->paramValues.emplace_back( Step::KeyValue("xy_out", xy_out)); iterCur->paramValues.emplace_back( Step::KeyValue("z_out", z_out)); deletePrevIter(); continue; } // clang-format off // A bit odd. Used to simplify geog3d_feet -> EPSG:6318+6360 // of https://github.com/OSGeo/PROJ/issues/3938 // where we get originally // +step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=us-ft // +step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m // and want it simplified as: // +step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=deg +z_out=us-ft // // More generally: // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2 // +step +proj=unitconvert +xy_in=X2 +z_in=Z3 +xy_out=X3 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3 +z_out=Z2 // clang-format on if (prevStep.name == "unitconvert" && curStep.name == "unitconvert" && !prevStep.inverted && !curStep.inverted && prevStep.paramValues.size() == 4 && curStep.paramValues.size() == 4 && prevStep.paramValues[0].keyEquals("xy_in") && prevStep.paramValues[1].keyEquals("z_in") && prevStep.paramValues[2].keyEquals("xy_out") && prevStep.paramValues[3].keyEquals("z_out") && curStep.paramValues[0].keyEquals("xy_in") && curStep.paramValues[1].keyEquals("z_in") && curStep.paramValues[2].keyEquals("xy_out") && curStep.paramValues[3].keyEquals("z_out") && prevStep.paramValues[2].value == curStep.paramValues[0].value && curStep.paramValues[1].value == curStep.paramValues[3].value) { const std::string xy_in(prevStep.paramValues[0].value); const std::string z_in(prevStep.paramValues[1].value); const std::string xy_out(curStep.paramValues[2].value); const std::string z_out(prevStep.paramValues[3].value); iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("xy_in", xy_in)); iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in)); iterCur->paramValues.emplace_back( Step::KeyValue("xy_out", xy_out)); iterCur->paramValues.emplace_back( Step::KeyValue("z_out", z_out)); deletePrevIter(); continue; } // clang-format off // Variant of above // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z1 // +step +proj=unitconvert +xy_in=X2 +z_in=Z2 +xy_out=X3 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X3 +z_out=Z3 // clang-format on if (prevStep.name == "unitconvert" && curStep.name == "unitconvert" && !prevStep.inverted && !curStep.inverted && prevStep.paramValues.size() == 4 && curStep.paramValues.size() == 4 && prevStep.paramValues[0].keyEquals("xy_in") && prevStep.paramValues[1].keyEquals("z_in") && prevStep.paramValues[2].keyEquals("xy_out") && prevStep.paramValues[3].keyEquals("z_out") && curStep.paramValues[0].keyEquals("xy_in") && curStep.paramValues[1].keyEquals("z_in") && curStep.paramValues[2].keyEquals("xy_out") && curStep.paramValues[3].keyEquals("z_out") && prevStep.paramValues[1].value == prevStep.paramValues[3].value && curStep.paramValues[0].value == prevStep.paramValues[2].value) { const std::string xy_in(prevStep.paramValues[0].value); const std::string z_in(curStep.paramValues[1].value); const std::string xy_out(curStep.paramValues[2].value); const std::string z_out(curStep.paramValues[3].value); iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("xy_in", xy_in)); iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in)); iterCur->paramValues.emplace_back( Step::KeyValue("xy_out", xy_out)); iterCur->paramValues.emplace_back( Step::KeyValue("z_out", z_out)); deletePrevIter(); continue; } // unitconvert (1), axisswap order=2,1, unitconvert(2) ==> // axisswap order=2,1, unitconvert (1), unitconvert(2) which // will get further optimized by previous case if (std::next(iterCur) != steps.end() && prevStep.name == "unitconvert" && curStep.name == "axisswap" && curStepParamCount == 1 && curStep.paramValues[0].equals("order", "2,1")) { auto iterNext = std::next(iterCur); auto &nextStep = *iterNext; if (nextStep.name == "unitconvert") { std::swap(*iterPrev, *iterCur); ++iterCur; continue; } } // axisswap order=2,1 followed by itself is a no-op if (curStep.name == "axisswap" && prevStep.name == "axisswap" && curStepParamCount == 1 && prevStepParamCount == 1 && curStep.paramValues[0].equals("order", "2,1") && prevStep.paramValues[0].equals("order", "2,1")) { deletePrevAndCurIter(); continue; } // axisswap order=2,-1 followed by axisswap order=-2,1 is a no-op if (curStep.name == "axisswap" && prevStep.name == "axisswap" && curStepParamCount == 1 && prevStepParamCount == 1 && !prevStep.inverted && prevStep.paramValues[0].equals("order", "2,-1") && !curStep.inverted && curStep.paramValues[0].equals("order", "-2,1")) { deletePrevAndCurIter(); continue; } // axisswap order=2,-1 followed by axisswap order=1,-2 is // equivalent to axisswap order=2,1 if (curStep.name == "axisswap" && prevStep.name == "axisswap" && curStepParamCount == 1 && prevStepParamCount == 1 && !prevStep.inverted && prevStep.paramValues[0].equals("order", "2,-1") && !curStep.inverted && curStep.paramValues[0].equals("order", "1,-2")) { prevStep.inverted = false; prevStep.paramValues[0] = Step::KeyValue("order", "2,1"); // Delete this iter iterCur = steps.erase(iterCur); continue; } // axisswap order=2,1 followed by axisswap order=2,-1 is // equivalent to axisswap order=1,-2 // Same for axisswap order=-2,1 followed by axisswap order=2,1 if (curStep.name == "axisswap" && prevStep.name == "axisswap" && curStepParamCount == 1 && prevStepParamCount == 1 && ((prevStep.paramValues[0].equals("order", "2,1") && !curStep.inverted && curStep.paramValues[0].equals("order", "2,-1")) || (prevStep.paramValues[0].equals("order", "-2,1") && !prevStep.inverted && curStep.paramValues[0].equals("order", "2,1")))) { prevStep.inverted = false; prevStep.paramValues[0] = Step::KeyValue("order", "1,-2"); // Delete this iter iterCur = steps.erase(iterCur); continue; } // axisswap order=2,1, unitconvert, axisswap order=2,1 -> can // suppress axisswap if (std::next(iterCur) != steps.end() && prevStep.name == "axisswap" && curStep.name == "unitconvert" && prevStepParamCount == 1 && prevStep.paramValues[0].equals("order", "2,1")) { auto iterNext = std::next(iterCur); auto &nextStep = *iterNext; if (nextStep.name == "axisswap" && nextStep.paramValues.size() == 1 && nextStep.paramValues[0].equals("order", "2,1")) { steps.erase(iterPrev); steps.erase(iterNext); // Coverity complains about invalid usage of iterCur // due to the above erase(iterNext). To the best of our // understanding, this is a false-positive. // coverity[use_iterator] if (iterCur != steps.begin()) iterCur = std::prev(iterCur); if (iterCur == steps.begin()) ++iterCur; continue; } } // for practical purposes WGS84 and GRS80 ellipsoids are // equivalents (cartesian transform between both lead to differences // of the order of 1e-14 deg..). // No need to do a cart roundtrip for that... // and actually IGNF uses the GRS80 definition for the WGS84 datum if (curStep.name == "cart" && prevStep.name == "cart" && curStep.inverted == !prevStep.inverted && curStepParamCount == 1 && prevStepParamCount == 1 && ((curStep.paramValues[0].equals("ellps", "WGS84") && prevStep.paramValues[0].equals("ellps", "GRS80")) || (curStep.paramValues[0].equals("ellps", "GRS80") && prevStep.paramValues[0].equals("ellps", "WGS84")))) { deletePrevAndCurIter(); continue; } if (curStep.name == "helmert" && prevStep.name == "helmert" && !curStep.inverted && !prevStep.inverted && curStepParamCount == 3 && curStepParamCount == prevStepParamCount) { std::map<std::string, double> leftParamsMap; std::map<std::string, double> rightParamsMap; try { for (const auto &kv : prevStep.paramValues) { leftParamsMap[kv.key] = c_locale_stod(kv.value); } for (const auto &kv : curStep.paramValues) { rightParamsMap[kv.key] = c_locale_stod(kv.value); } } catch (const std::invalid_argument &) { break; } const std::string x("x"); const std::string y("y"); const std::string z("z"); if (leftParamsMap.find(x) != leftParamsMap.end() && leftParamsMap.find(y) != leftParamsMap.end() && leftParamsMap.find(z) != leftParamsMap.end() && rightParamsMap.find(x) != rightParamsMap.end() && rightParamsMap.find(y) != rightParamsMap.end() && rightParamsMap.find(z) != rightParamsMap.end()) { const double xSum = leftParamsMap[x] + rightParamsMap[x]; const double ySum = leftParamsMap[y] + rightParamsMap[y]; const double zSum = leftParamsMap[z] + rightParamsMap[z]; if (xSum == 0.0 && ySum == 0.0 && zSum == 0.0) { deletePrevAndCurIter(); } else { prevStep.paramValues[0] = Step::KeyValue("x", internal::toString(xSum)); prevStep.paramValues[1] = Step::KeyValue("y", internal::toString(ySum)); prevStep.paramValues[2] = Step::KeyValue("z", internal::toString(zSum)); // Delete this iter iterCur = steps.erase(iterCur); } continue; } } // Helmert followed by its inverse is a no-op if (curStep.name == "helmert" && prevStep.name == "helmert" && !curStep.inverted && !prevStep.inverted && curStepParamCount == prevStepParamCount) { std::set<std::string> leftParamsSet; std::set<std::string> rightParamsSet; std::map<std::string, std::string> leftParamsMap; std::map<std::string, std::string> rightParamsMap; for (const auto &kv : prevStep.paramValues) { leftParamsSet.insert(kv.key); leftParamsMap[kv.key] = kv.value; } for (const auto &kv : curStep.paramValues) { rightParamsSet.insert(kv.key); rightParamsMap[kv.key] = kv.value; } if (leftParamsSet == rightParamsSet) { bool doErase = true; try { for (const auto &param : leftParamsSet) { if (param == "convention" || param == "t_epoch" || param == "t_obs") { if (leftParamsMap[param] != rightParamsMap[param]) { doErase = false; break; } } else if (c_locale_stod(leftParamsMap[param]) != -c_locale_stod(rightParamsMap[param])) { doErase = false; break; } } } catch (const std::invalid_argument &) { break; } if (doErase) { deletePrevAndCurIter(); continue; } } } // The following should be optimized as a no-op // +step +proj=helmert +x=25 +y=-141 +z=-78.5 +rx=0 +ry=-0.35 // +rz=-0.736 +s=0 +convention=coordinate_frame // +step +inv +proj=helmert +x=25 +y=-141 +z=-78.5 +rx=0 +ry=0.35 // +rz=0.736 +s=0 +convention=position_vector if (curStep.name == "helmert" && prevStep.name == "helmert" && ((curStep.inverted && !prevStep.inverted) || (!curStep.inverted && prevStep.inverted)) && curStepParamCount == prevStepParamCount) { std::set<std::string> leftParamsSet; std::set<std::string> rightParamsSet; std::map<std::string, std::string> leftParamsMap; std::map<std::string, std::string> rightParamsMap; for (const auto &kv : prevStep.paramValues) { leftParamsSet.insert(kv.key); leftParamsMap[kv.key] = kv.value; } for (const auto &kv : curStep.paramValues) { rightParamsSet.insert(kv.key); rightParamsMap[kv.key] = kv.value; } if (leftParamsSet == rightParamsSet) { bool doErase = true; try { for (const auto &param : leftParamsSet) { if (param == "convention") { // Convention must be different if (leftParamsMap[param] == rightParamsMap[param]) { doErase = false; break; } } else if (param == "rx" || param == "ry" || param == "rz" || param == "drx" || param == "dry" || param == "drz") { // Rotational parameters should have opposite // value if (c_locale_stod(leftParamsMap[param]) != -c_locale_stod(rightParamsMap[param])) { doErase = false; break; } } else { // Non rotational parameters should have the // same value if (leftParamsMap[param] != rightParamsMap[param]) { doErase = false; break; } } } } catch (const std::invalid_argument &) { break; } if (doErase) { deletePrevAndCurIter(); continue; } } } // Optimize patterns like Krovak (South West) to Krovak East North // (also applies to Modified Krovak) // +step +inv +proj=krovak +axis=swu +lat_0=49.5 // +lon_0=24.8333333333333 // +alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel // +step +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333 // +alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel // as: // +step +proj=axisswap +order=-2,-1 // Also applies for the symmetrical case where +axis=swu is on the // second step. if (curStep.inverted != prevStep.inverted && curStep.name == prevStep.name && ((curStepParamCount + 1 == prevStepParamCount && prevStep.paramValues[0].equals("axis", "swu")) || (prevStepParamCount + 1 == curStepParamCount && curStep.paramValues[0].equals("axis", "swu")))) { const auto &swStep = (curStepParamCount < prevStepParamCount) ? prevStep : curStep; const auto &enStep = (curStepParamCount < prevStepParamCount) ? curStep : prevStep; // Check if all remaining parameters (except leading axis=swu // in swStep) are identical. bool allSame = true; for (size_t j = 0; j < std::min(curStepParamCount, prevStepParamCount); j++) { if (enStep.paramValues[j] != swStep.paramValues[j + 1]) { allSame = false; break; } } if (allSame) { iterCur->inverted = false; iterCur->name = "axisswap"; iterCur->paramValues.clear(); iterCur->paramValues.emplace_back( Step::KeyValue("order", "-2,-1")); deletePrevIter(); continue; } } // detect a step and its inverse if (curStep.inverted != prevStep.inverted && curStep.name == prevStep.name && curStepParamCount == prevStepParamCount) { bool allSame = true; for (size_t j = 0; j < curStepParamCount; j++) { if (curStep.paramValues[j] != prevStep.paramValues[j]) { allSame = false; break; } } if (allSame) { deletePrevAndCurIter(); continue; } } ++iterCur; } } { auto iterCur = steps.begin(); if (iterCur != steps.end()) { ++iterCur; } while (iterCur != steps.end()) { assert(iterCur != steps.begin()); auto iterPrev = std::prev(iterCur); auto &prevStep = *iterPrev; auto &curStep = *iterCur; const auto curStepParamCount = curStep.paramValues.size(); const auto prevStepParamCount = prevStep.paramValues.size(); // +step +proj=hgridshift +grids=grid_A // +step +proj=vgridshift [...] <== curStep // +step +inv +proj=hgridshift +grids=grid_A // ==> // +step +proj=push +v_1 +v_2 // +step +proj=hgridshift +grids=grid_A +omit_inv // +step +proj=vgridshift [...] // +step +inv +proj=hgridshift +grids=grid_A +omit_fwd // +step +proj=pop +v_1 +v_2 if (std::next(iterCur) != steps.end() && prevStep.name == "hgridshift" && prevStepParamCount == 1 && curStep.name == "vgridshift") { auto iterNext = std::next(iterCur); auto &nextStep = *iterNext; if (nextStep.name == "hgridshift" && nextStep.inverted != prevStep.inverted && nextStep.paramValues.size() == 1 && prevStep.paramValues[0] == nextStep.paramValues[0]) { Step pushStep; pushStep.name = "push"; pushStep.paramValues.emplace_back("v_1"); pushStep.paramValues.emplace_back("v_2"); steps.insert(iterPrev, pushStep); prevStep.paramValues.emplace_back("omit_inv"); nextStep.paramValues.emplace_back("omit_fwd"); Step popStep; popStep.name = "pop"; popStep.paramValues.emplace_back("v_1"); popStep.paramValues.emplace_back("v_2"); steps.insert(std::next(iterNext), popStep); continue; } } // +step +proj=unitconvert +xy_in=rad +xy_out=deg // +step +proj=axisswap +order=2,1 // +step +proj=push +v_1 +v_2 // +step +proj=axisswap +order=2,1 // +step +proj=unitconvert +xy_in=deg +xy_out=rad // +step +proj=vgridshift ... // +step +proj=unitconvert +xy_in=rad +xy_out=deg // +step +proj=axisswap +order=2,1 // +step +proj=pop +v_1 +v_2 // ==> // +step +proj=vgridshift ... // +step +proj=unitconvert +xy_in=rad +xy_out=deg // +step +proj=axisswap +order=2,1 if (prevStep.name == "unitconvert" && prevStepParamCount == 2 && prevStep.paramValues[0].equals("xy_in", "rad") && prevStep.paramValues[1].equals("xy_out", "deg") && curStep.name == "axisswap" && curStepParamCount == 1 && curStep.paramValues[0].equals("order", "2,1")) { auto iterNext = std::next(iterCur); bool ok = false; if (iterNext != steps.end()) { auto &nextStep = *iterNext; if (nextStep.name == "push" && nextStep.paramValues.size() == 2 && nextStep.paramValues[0].keyEquals("v_1") && nextStep.paramValues[1].keyEquals("v_2")) { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "axisswap" && nextStep.paramValues.size() == 1 && nextStep.paramValues[0].equals("order", "2,1")) { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "unitconvert" && nextStep.paramValues.size() == 2 && nextStep.paramValues[0].equals("xy_in", "deg") && nextStep.paramValues[1].equals("xy_out", "rad")) { ok = true; iterNext = std::next(iterNext); } } auto iterVgridshift = iterNext; ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "vgridshift") { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "unitconvert" && nextStep.paramValues.size() == 2 && nextStep.paramValues[0].equals("xy_in", "rad") && nextStep.paramValues[1].equals("xy_out", "deg")) { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "axisswap" && nextStep.paramValues.size() == 1 && nextStep.paramValues[0].equals("order", "2,1")) { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "pop" && nextStep.paramValues.size() == 2 && nextStep.paramValues[0].keyEquals("v_1") && nextStep.paramValues[1].keyEquals("v_2")) { ok = true; // iterNext = std::next(iterNext); } } if (ok) { steps.erase(iterPrev, iterVgridshift); steps.erase(iterNext, std::next(iterNext)); iterPrev = std::prev(iterVgridshift); iterCur = iterVgridshift; continue; } } // +step +proj=axisswap +order=2,1 // +step +proj=unitconvert +xy_in=deg +xy_out=rad // +step +proj=vgridshift ... // +step +proj=unitconvert +xy_in=rad +xy_out=deg // +step +proj=axisswap +order=2,1 // +step +proj=push +v_1 +v_2 // +step +proj=axisswap +order=2,1 // +step +proj=unitconvert +xy_in=deg +xy_out=rad // ==> // +step +proj=push +v_1 +v_2 // +step +proj=axisswap +order=2,1 // +step +proj=unitconvert +xy_in=deg +xy_out=rad // +step +proj=vgridshift ... if (prevStep.name == "axisswap" && prevStepParamCount == 1 && prevStep.paramValues[0].equals("order", "2,1") && curStep.name == "unitconvert" && curStepParamCount == 2 && !curStep.inverted && curStep.paramValues[0].equals("xy_in", "deg") && curStep.paramValues[1].equals("xy_out", "rad")) { auto iterNext = std::next(iterCur); bool ok = false; auto iterVgridshift = iterNext; if (iterNext != steps.end()) { auto &nextStep = *iterNext; if (nextStep.name == "vgridshift") { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "unitconvert" && !nextStep.inverted && nextStep.paramValues.size() == 2 && nextStep.paramValues[0].equals("xy_in", "rad") && nextStep.paramValues[1].equals("xy_out", "deg")) { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "axisswap" && nextStep.paramValues.size() == 1 && nextStep.paramValues[0].equals("order", "2,1")) { ok = true; iterNext = std::next(iterNext); } } auto iterPush = iterNext; ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "push" && nextStep.paramValues.size() == 2 && nextStep.paramValues[0].keyEquals("v_1") && nextStep.paramValues[1].keyEquals("v_2")) { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "axisswap" && nextStep.paramValues.size() == 1 && nextStep.paramValues[0].equals("order", "2,1")) { ok = true; iterNext = std::next(iterNext); } } ok &= iterNext != steps.end(); if (ok) { ok = false; auto &nextStep = *iterNext; if (nextStep.name == "unitconvert" && nextStep.paramValues.size() == 2 && !nextStep.inverted && nextStep.paramValues[0].equals("xy_in", "deg") && nextStep.paramValues[1].equals("xy_out", "rad")) { ok = true; // iterNext = std::next(iterNext); } } if (ok) { Step stepVgridshift(*iterVgridshift); steps.erase(iterPrev, iterPush); steps.insert(std::next(iterNext), std::move(stepVgridshift)); iterPrev = iterPush; iterCur = std::next(iterPush); continue; } } ++iterCur; } } { auto iterCur = steps.begin(); if (iterCur != steps.end()) { ++iterCur; } while (iterCur != steps.end()) { assert(iterCur != steps.begin()); auto iterPrev = std::prev(iterCur); auto &prevStep = *iterPrev; auto &curStep = *iterCur; const auto curStepParamCount = curStep.paramValues.size(); const auto prevStepParamCount = prevStep.paramValues.size(); const auto deletePrevAndCurIter = [&steps, &iterPrev, &iterCur]() { iterCur = steps.erase(iterPrev, std::next(iterCur)); if (iterCur != steps.begin()) iterCur = std::prev(iterCur); if (iterCur == steps.begin() && iterCur != steps.end()) ++iterCur; }; // axisswap order=2,1 followed by itself is a no-op if (curStep.name == "axisswap" && prevStep.name == "axisswap" && curStepParamCount == 1 && prevStepParamCount == 1 && curStep.paramValues[0].equals("order", "2,1") && prevStep.paramValues[0].equals("order", "2,1")) { deletePrevAndCurIter(); continue; } // detect a step and its inverse if (curStep.inverted != prevStep.inverted && curStep.name == prevStep.name && curStepParamCount == prevStepParamCount) { bool allSame = true; for (size_t j = 0; j < curStepParamCount; j++) { if (curStep.paramValues[j] != prevStep.paramValues[j]) { allSame = false; break; } } if (allSame) { deletePrevAndCurIter(); continue; } } ++iterCur; } } if (steps.size() > 1 || (steps.size() == 1 && (steps.front().inverted || steps.front().hasKey("omit_inv") || steps.front().hasKey("omit_fwd") || !d->globalParamValues_.empty()))) { d->appendToResult("+proj=pipeline"); for (const auto &paramValue : d->globalParamValues_) { d->appendToResult("+"); d->result_ += paramValue.key; if (!paramValue.value.empty()) { d->result_ += '='; d->result_ += pj_double_quote_string_param_if_needed(paramValue.value); } } if (d->multiLine_) { d->indentLevel_++; } } for (const auto &step : steps) { std::string curLine; if (!d->result_.empty()) { if (d->multiLine_) { curLine = std::string(static_cast<size_t>(d->indentLevel_) * d->indentWidth_, ' '); curLine += "+step"; } else { curLine = " +step"; } } if (step.inverted) { curLine += " +inv"; } if (!step.name.empty()) { if (!curLine.empty()) curLine += ' '; curLine += step.isInit ? "+init=" : "+proj="; curLine += step.name; } for (const auto &paramValue : step.paramValues) { std::string newKV = "+"; newKV += paramValue.key; if (!paramValue.value.empty()) { newKV += '='; newKV += pj_double_quote_string_param_if_needed(paramValue.value); } if (d->maxLineLength_ > 0 && d->multiLine_ && curLine.size() + newKV.size() > static_cast<size_t>(d->maxLineLength_)) { if (!d->result_.empty()) d->result_ += '\n'; d->result_ += curLine; curLine = std::string(static_cast<size_t>(d->indentLevel_) * d->indentWidth_ + strlen("+step "), ' '); } else { if (!curLine.empty()) curLine += ' '; } curLine += newKV; } if (d->multiLine_ && !d->result_.empty()) d->result_ += '\n'; d->result_ += curLine; } if (d->result_.empty()) { d->appendToResult("+proj=noop"); } return d->result_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PROJStringFormatter::Convention PROJStringFormatter::convention() const { return d->convention_; } // --------------------------------------------------------------------------- // Return the number of steps in the pipeline. // Note: this value will change after calling toString() that will run // optimizations. size_t PROJStringFormatter::getStepCount() const { return d->steps_.size(); } // --------------------------------------------------------------------------- bool PROJStringFormatter::getUseApproxTMerc() const { return d->useApproxTMerc_; } // --------------------------------------------------------------------------- void PROJStringFormatter::setCoordinateOperationOptimizations(bool enable) { d->coordOperationOptimizations_ = enable; } // --------------------------------------------------------------------------- void PROJStringFormatter::Private::appendToResult(const char *str) { if (!result_.empty()) { result_ += ' '; } result_ += str; } // --------------------------------------------------------------------------- static void PROJStringSyntaxParser(const std::string &projString, std::vector<Step> &steps, std::vector<Step::KeyValue> &globalParamValues, std::string &title) { std::vector<std::string> tokens; bool hasProj = false; bool hasInit = false; bool hasPipeline = false; std::string projStringModified(projString); // Special case for "+title=several words +foo=bar" if (starts_with(projStringModified, "+title=") && projStringModified.size() > 7 && projStringModified[7] != '"') { const auto plusPos = projStringModified.find(" +", 1); const auto spacePos = projStringModified.find(' '); if (plusPos != std::string::npos && spacePos != std::string::npos && spacePos < plusPos) { std::string tmp("+title="); tmp += pj_double_quote_string_param_if_needed( projStringModified.substr(7, plusPos - 7)); tmp += projStringModified.substr(plusPos); projStringModified = std::move(tmp); } } size_t argc = pj_trim_argc(&projStringModified[0]); char **argv = pj_trim_argv(argc, &projStringModified[0]); for (size_t i = 0; i < argc; i++) { std::string token(argv[i]); if (!hasPipeline && token == "proj=pipeline") { hasPipeline = true; } else if (!hasProj && starts_with(token, "proj=")) { hasProj = true; } else if (!hasInit && starts_with(token, "init=")) { hasInit = true; } tokens.emplace_back(token); } free(argv); if (!hasPipeline) { if (hasProj || hasInit) { steps.push_back(Step()); } for (auto &word : tokens) { if (starts_with(word, "proj=") && !hasInit && steps.back().name.empty()) { assert(hasProj); auto stepName = word.substr(strlen("proj=")); steps.back().name = std::move(stepName); } else if (starts_with(word, "init=")) { assert(hasInit); auto initName = word.substr(strlen("init=")); steps.back().name = std::move(initName); steps.back().isInit = true; } else if (word == "inv") { if (!steps.empty()) { steps.back().inverted = true; } } else if (starts_with(word, "title=")) { title = word.substr(strlen("title=")); } else if (word != "step") { const auto pos = word.find('='); auto key = word.substr(0, pos); const Step::KeyValue pair( (pos != std::string::npos) ? Step::KeyValue(key, word.substr(pos + 1)) : Step::KeyValue(key)); if (steps.empty()) { globalParamValues.push_back(pair); } else { steps.back().paramValues.push_back(pair); } } } return; } bool inPipeline = false; bool invGlobal = false; for (auto &word : tokens) { if (word == "proj=pipeline") { if (inPipeline) { throw ParsingException("nested pipeline not supported"); } inPipeline = true; } else if (word == "step") { if (!inPipeline) { throw ParsingException("+step found outside pipeline"); } steps.push_back(Step()); } else if (word == "inv") { if (steps.empty()) { invGlobal = true; } else { steps.back().inverted = true; } } else if (inPipeline && !steps.empty() && starts_with(word, "proj=") && steps.back().name.empty()) { auto stepName = word.substr(strlen("proj=")); steps.back().name = std::move(stepName); } else if (inPipeline && !steps.empty() && starts_with(word, "init=") && steps.back().name.empty()) { auto initName = word.substr(strlen("init=")); steps.back().name = std::move(initName); steps.back().isInit = true; } else if (!inPipeline && starts_with(word, "title=")) { title = word.substr(strlen("title=")); } else { const auto pos = word.find('='); auto key = word.substr(0, pos); Step::KeyValue pair((pos != std::string::npos) ? Step::KeyValue(key, word.substr(pos + 1)) : Step::KeyValue(key)); if (steps.empty()) { globalParamValues.emplace_back(std::move(pair)); } else { steps.back().paramValues.emplace_back(std::move(pair)); } } } if (invGlobal) { for (auto &step : steps) { step.inverted = !step.inverted; } std::reverse(steps.begin(), steps.end()); } } // --------------------------------------------------------------------------- void PROJStringFormatter::ingestPROJString( const std::string &str) // throw ParsingException { std::vector<Step> steps; std::string title; PROJStringSyntaxParser(str, steps, d->globalParamValues_, title); d->steps_.insert(d->steps_.end(), steps.begin(), steps.end()); } // --------------------------------------------------------------------------- void PROJStringFormatter::setCRSExport(bool b) { d->crsExport_ = b; } // --------------------------------------------------------------------------- bool PROJStringFormatter::getCRSExport() const { return d->crsExport_; } // --------------------------------------------------------------------------- void PROJStringFormatter::startInversion() { PROJStringFormatter::Private::InversionStackElt elt; elt.startIter = d->steps_.end(); if (elt.startIter != d->steps_.begin()) { elt.iterValid = true; --elt.startIter; // point to the last valid element } else { elt.iterValid = false; } elt.currentInversionState = !d->inversionStack_.back().currentInversionState; d->inversionStack_.push_back(elt); } // --------------------------------------------------------------------------- void PROJStringFormatter::stopInversion() { assert(!d->inversionStack_.empty()); auto startIter = d->inversionStack_.back().startIter; if (!d->inversionStack_.back().iterValid) { startIter = d->steps_.begin(); } else { ++startIter; // advance after the last valid element we marked above } // Invert the inversion status of the steps between the start point and // the current end of steps for (auto iter = startIter; iter != d->steps_.end(); ++iter) { iter->inverted = !iter->inverted; for (auto &paramValue : iter->paramValues) { if (paramValue.key == "omit_fwd") paramValue.key = "omit_inv"; else if (paramValue.key == "omit_inv") paramValue.key = "omit_fwd"; } } // And reverse the order of steps in that range as well. std::reverse(startIter, d->steps_.end()); d->inversionStack_.pop_back(); } // --------------------------------------------------------------------------- bool PROJStringFormatter::isInverted() const { return d->inversionStack_.back().currentInversionState; } // --------------------------------------------------------------------------- void PROJStringFormatter::Private::addStep() { steps_.emplace_back(Step()); } // --------------------------------------------------------------------------- void PROJStringFormatter::addStep(const char *stepName) { d->addStep(); d->steps_.back().name.assign(stepName); } // --------------------------------------------------------------------------- void PROJStringFormatter::addStep(const std::string &stepName) { d->addStep(); d->steps_.back().name = stepName; } // --------------------------------------------------------------------------- void PROJStringFormatter::setCurrentStepInverted(bool inverted) { assert(!d->steps_.empty()); d->steps_.back().inverted = inverted; } // --------------------------------------------------------------------------- bool PROJStringFormatter::hasParam(const char *paramName) const { if (!d->steps_.empty()) { for (const auto &paramValue : d->steps_.back().paramValues) { if (paramValue.keyEquals(paramName)) { return true; } } } return false; } // --------------------------------------------------------------------------- void PROJStringFormatter::addNoDefs(bool b) { d->addNoDefs_ = b; } // --------------------------------------------------------------------------- bool PROJStringFormatter::getAddNoDefs() const { return d->addNoDefs_; } // --------------------------------------------------------------------------- void PROJStringFormatter::addParam(const std::string &paramName) { if (d->steps_.empty()) { d->addStep(); } d->steps_.back().paramValues.push_back(Step::KeyValue(paramName)); } // --------------------------------------------------------------------------- void PROJStringFormatter::addParam(const char *paramName, int val) { addParam(std::string(paramName), val); } void PROJStringFormatter::addParam(const std::string &paramName, int val) { addParam(paramName, internal::toString(val)); } // --------------------------------------------------------------------------- static std::string formatToString(double val) { if (std::abs(val * 10 - std::round(val * 10)) < 1e-8) { // For the purpose of // https://www.epsg-registry.org/export.htm?wkt=urn:ogc:def:crs:EPSG::27561 // Latitude of natural of origin to be properly rounded from 55 grad // to // 49.5 deg val = std::round(val * 10) / 10; } return normalizeSerializedString(internal::toString(val)); } // --------------------------------------------------------------------------- void PROJStringFormatter::addParam(const char *paramName, double val) { addParam(std::string(paramName), val); } void PROJStringFormatter::addParam(const std::string &paramName, double val) { addParam(paramName, formatToString(val)); } // --------------------------------------------------------------------------- void PROJStringFormatter::addParam(const char *paramName, const std::vector<double> &vals) { std::string paramValue; for (size_t i = 0; i < vals.size(); ++i) { if (i > 0) { paramValue += ','; } paramValue += formatToString(vals[i]); } addParam(paramName, paramValue); } // --------------------------------------------------------------------------- void PROJStringFormatter::addParam(const char *paramName, const char *val) { addParam(std::string(paramName), val); } void PROJStringFormatter::addParam(const char *paramName, const std::string &val) { addParam(std::string(paramName), val); } void PROJStringFormatter::addParam(const std::string &paramName, const char *val) { addParam(paramName, std::string(val)); } // --------------------------------------------------------------------------- void PROJStringFormatter::addParam(const std::string &paramName, const std::string &val) { if (d->steps_.empty()) { d->addStep(); } d->steps_.back().paramValues.push_back(Step::KeyValue(paramName, val)); } // --------------------------------------------------------------------------- void PROJStringFormatter::setTOWGS84Parameters( const std::vector<double> &params) { d->toWGS84Parameters_ = params; } // --------------------------------------------------------------------------- const std::vector<double> &PROJStringFormatter::getTOWGS84Parameters() const { return d->toWGS84Parameters_; } // --------------------------------------------------------------------------- std::set<std::string> PROJStringFormatter::getUsedGridNames() const { std::set<std::string> res; for (const auto &step : d->steps_) { for (const auto &param : step.paramValues) { if (param.keyEquals("grids") || param.keyEquals("file")) { const auto gridNames = split(param.value, ","); for (const auto &gridName : gridNames) { res.insert(gridName); } } } } return res; } // --------------------------------------------------------------------------- void PROJStringFormatter::setVDatumExtension(const std::string &filename, const std::string &geoidCRSValue) { d->vDatumExtension_ = filename; d->geoidCRSValue_ = geoidCRSValue; } // --------------------------------------------------------------------------- const std::string &PROJStringFormatter::getVDatumExtension() const { return d->vDatumExtension_; } // --------------------------------------------------------------------------- const std::string &PROJStringFormatter::getGeoidCRSValue() const { return d->geoidCRSValue_; } // --------------------------------------------------------------------------- void PROJStringFormatter::setHDatumExtension(const std::string &filename) { d->hDatumExtension_ = filename; } // --------------------------------------------------------------------------- const std::string &PROJStringFormatter::getHDatumExtension() const { return d->hDatumExtension_; } // --------------------------------------------------------------------------- void PROJStringFormatter::setGeogCRSOfCompoundCRS( const crs::GeographicCRSPtr &crs) { d->geogCRSOfCompoundCRS_ = crs; } // --------------------------------------------------------------------------- const crs::GeographicCRSPtr & PROJStringFormatter::getGeogCRSOfCompoundCRS() const { return d->geogCRSOfCompoundCRS_; } // --------------------------------------------------------------------------- void PROJStringFormatter::setOmitProjLongLatIfPossible(bool omit) { assert(d->omitProjLongLatIfPossible_ ^ omit); d->omitProjLongLatIfPossible_ = omit; } // --------------------------------------------------------------------------- bool PROJStringFormatter::omitProjLongLatIfPossible() const { return d->omitProjLongLatIfPossible_; } // --------------------------------------------------------------------------- void PROJStringFormatter::pushOmitZUnitConversion() { d->omitZUnitConversion_.push_back(true); } // --------------------------------------------------------------------------- void PROJStringFormatter::popOmitZUnitConversion() { assert(d->omitZUnitConversion_.size() > 1); d->omitZUnitConversion_.pop_back(); } // --------------------------------------------------------------------------- bool PROJStringFormatter::omitZUnitConversion() const { return d->omitZUnitConversion_.back(); } // --------------------------------------------------------------------------- void PROJStringFormatter::pushOmitHorizontalConversionInVertTransformation() { d->omitHorizontalConversionInVertTransformation_.push_back(true); } // --------------------------------------------------------------------------- void PROJStringFormatter::popOmitHorizontalConversionInVertTransformation() { assert(d->omitHorizontalConversionInVertTransformation_.size() > 1); d->omitHorizontalConversionInVertTransformation_.pop_back(); } // --------------------------------------------------------------------------- bool PROJStringFormatter::omitHorizontalConversionInVertTransformation() const { return d->omitHorizontalConversionInVertTransformation_.back(); } // --------------------------------------------------------------------------- void PROJStringFormatter::setLegacyCRSToCRSContext(bool legacyContext) { d->legacyCRSToCRSContext_ = legacyContext; } // --------------------------------------------------------------------------- bool PROJStringFormatter::getLegacyCRSToCRSContext() const { return d->legacyCRSToCRSContext_; } // --------------------------------------------------------------------------- /** Asks for a "normalized" output during toString(), aimed at comparing two * strings for equivalence. * * This consists for now in sorting the +key=value option in lexicographic * order. */ PROJStringFormatter &PROJStringFormatter::setNormalizeOutput() { d->normalizeOutput_ = true; return *this; } // --------------------------------------------------------------------------- const DatabaseContextPtr &PROJStringFormatter::databaseContext() const { return d->dbContext_; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PROJStringParser::Private { DatabaseContextPtr dbContext_{}; PJ_CONTEXT *ctx_{}; bool usePROJ4InitRules_ = false; std::vector<std::string> warningList_{}; std::string projString_{}; std::vector<Step> steps_{}; std::vector<Step::KeyValue> globalParamValues_{}; std::string title_{}; bool ignoreNadgrids_ = false; template <class T> // cppcheck-suppress functionStatic bool hasParamValue(Step &step, const T key) { for (auto &pair : globalParamValues_) { if (ci_equal(pair.key, key)) { pair.usedByParser = true; return true; } } for (auto &pair : step.paramValues) { if (ci_equal(pair.key, key)) { pair.usedByParser = true; return true; } } return false; } template <class T> // cppcheck-suppress functionStatic const std::string &getGlobalParamValue(T key) { for (auto &pair : globalParamValues_) { if (ci_equal(pair.key, key)) { pair.usedByParser = true; return pair.value; } } return emptyString; } template <class T> // cppcheck-suppress functionStatic const std::string &getParamValue(Step &step, const T key) { for (auto &pair : globalParamValues_) { if (ci_equal(pair.key, key)) { pair.usedByParser = true; return pair.value; } } for (auto &pair : step.paramValues) { if (ci_equal(pair.key, key)) { pair.usedByParser = true; return pair.value; } } return emptyString; } static const std::string &getParamValueK(Step &step) { for (auto &pair : step.paramValues) { if (ci_equal(pair.key, "k") || ci_equal(pair.key, "k_0")) { pair.usedByParser = true; return pair.value; } } return emptyString; } // cppcheck-suppress functionStatic bool hasUnusedParameters(const Step &step) const { if (steps_.size() == 1) { for (const auto &pair : step.paramValues) { if (pair.key != "no_defs" && !pair.usedByParser) { return true; } } } return false; } // cppcheck-suppress functionStatic std::string guessBodyName(double a); PrimeMeridianNNPtr buildPrimeMeridian(Step &step); GeodeticReferenceFrameNNPtr buildDatum(Step &step, const std::string &title); GeodeticCRSNNPtr buildGeodeticCRS(int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis); GeodeticCRSNNPtr buildGeocentricCRS(int iStep, int iUnitConvert); CRSNNPtr buildProjectedCRS(int iStep, const GeodeticCRSNNPtr &geogCRS, int iUnitConvert, int iAxisSwap); CRSNNPtr buildBoundOrCompoundCRSIfNeeded(int iStep, CRSNNPtr crs); UnitOfMeasure buildUnit(Step &step, const std::string &unitsParamName, const std::string &toMeterParamName); enum class AxisType { REGULAR, NORTH_POLE, SOUTH_POLE }; std::vector<CoordinateSystemAxisNNPtr> processAxisSwap(Step &step, const UnitOfMeasure &unit, int iAxisSwap, AxisType axisType, bool ignorePROJAxis); EllipsoidalCSNNPtr buildEllipsoidalCS(int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis); SphericalCSNNPtr buildSphericalCS(int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis); }; //! @endcond // --------------------------------------------------------------------------- PROJStringParser::PROJStringParser() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PROJStringParser::~PROJStringParser() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Attach a database context, to allow queries in it if needed. */ PROJStringParser & PROJStringParser::attachDatabaseContext(const DatabaseContextPtr &dbContext) { d->dbContext_ = dbContext; return *this; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PROJStringParser &PROJStringParser::attachContext(PJ_CONTEXT *ctx) { d->ctx_ = ctx; return *this; } //! @endcond // --------------------------------------------------------------------------- /** \brief Set how init=epsg:XXXX syntax should be interpreted. * * @param enable When set to true, * init=epsg:XXXX syntax will be allowed and will be interpreted according to * PROJ.4 and PROJ.5 rules, that is geodeticCRS will have longitude, latitude * order and will expect/output coordinates in radians. ProjectedCRS will have * easting, northing axis order (except the ones with Transverse Mercator South * Orientated projection). */ PROJStringParser &PROJStringParser::setUsePROJ4InitRules(bool enable) { d->usePROJ4InitRules_ = enable; return *this; } // --------------------------------------------------------------------------- /** \brief Return the list of warnings found during parsing. */ std::vector<std::string> PROJStringParser::warningList() const { return d->warningList_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- static const struct LinearUnitDesc { const char *projName; const char *convToMeter; const char *name; int epsgCode; } linearUnitDescs[] = { {"mm", "0.001", "millimetre", 1025}, {"cm", "0.01", "centimetre", 1033}, {"m", "1.0", "metre", 9001}, {"meter", "1.0", "metre", 9001}, // alternative {"metre", "1.0", "metre", 9001}, // alternative {"ft", "0.3048", "foot", 9002}, {"us-ft", "0.3048006096012192", "US survey foot", 9003}, {"fath", "1.8288", "fathom", 9014}, {"kmi", "1852", "nautical mile", 9030}, {"us-ch", "20.11684023368047", "US survey chain", 9033}, {"us-mi", "1609.347218694437", "US survey mile", 9035}, {"km", "1000.0", "kilometre", 9036}, {"ind-ft", "0.30479841", "Indian foot (1937)", 9081}, {"ind-yd", "0.91439523", "Indian yard (1937)", 9085}, {"mi", "1609.344", "Statute mile", 9093}, {"yd", "0.9144", "yard", 9096}, {"ch", "20.1168", "chain", 9097}, {"link", "0.201168", "link", 9098}, {"dm", "0.1", "decimetre", 0}, // no EPSG equivalent {"in", "0.0254", "inch", 0}, // no EPSG equivalent {"us-in", "0.025400050800101", "US survey inch", 0}, // no EPSG equivalent {"us-yd", "0.914401828803658", "US survey yard", 0}, // no EPSG equivalent {"ind-ch", "20.11669506", "Indian chain", 0}, // no EPSG equivalent }; static const LinearUnitDesc *getLinearUnits(const std::string &projName) { for (const auto &desc : linearUnitDescs) { if (desc.projName == projName) return &desc; } return nullptr; } static const LinearUnitDesc *getLinearUnits(double toMeter) { for (const auto &desc : linearUnitDescs) { if (std::fabs(c_locale_stod(desc.convToMeter) - toMeter) < 1e-10 * toMeter) { return &desc; } } return nullptr; } // --------------------------------------------------------------------------- static UnitOfMeasure _buildUnit(const LinearUnitDesc *unitsMatch) { std::string unitsCode; if (unitsMatch->epsgCode) { std::ostringstream buffer; buffer.imbue(std::locale::classic()); buffer << unitsMatch->epsgCode; unitsCode = buffer.str(); } return UnitOfMeasure( unitsMatch->name, c_locale_stod(unitsMatch->convToMeter), UnitOfMeasure::Type::LINEAR, unitsMatch->epsgCode ? Identifier::EPSG : std::string(), unitsCode); } // --------------------------------------------------------------------------- static UnitOfMeasure _buildUnit(double to_meter_value) { // TODO: look-up in EPSG catalog if (to_meter_value == 0) { throw ParsingException("invalid unit value"); } return UnitOfMeasure("unknown", to_meter_value, UnitOfMeasure::Type::LINEAR); } // --------------------------------------------------------------------------- UnitOfMeasure PROJStringParser::Private::buildUnit(Step &step, const std::string &unitsParamName, const std::string &toMeterParamName) { UnitOfMeasure unit = UnitOfMeasure::METRE; const LinearUnitDesc *unitsMatch = nullptr; const auto &projUnits = getParamValue(step, unitsParamName); if (!projUnits.empty()) { unitsMatch = getLinearUnits(projUnits); if (unitsMatch == nullptr) { throw ParsingException("unhandled " + unitsParamName + "=" + projUnits); } } const auto &toMeter = getParamValue(step, toMeterParamName); if (!toMeter.empty()) { double to_meter_value; try { to_meter_value = c_locale_stod(toMeter); } catch (const std::invalid_argument &) { throw ParsingException("invalid value for " + toMeterParamName); } unitsMatch = getLinearUnits(to_meter_value); if (unitsMatch == nullptr) { unit = _buildUnit(to_meter_value); } } if (unitsMatch) { unit = _buildUnit(unitsMatch); } return unit; } // --------------------------------------------------------------------------- static const struct DatumDesc { const char *projName; const char *gcsName; int gcsCode; const char *datumName; int datumCode; const char *ellipsoidName; int ellipsoidCode; double a; double rf; } datumDescs[] = { {"GGRS87", "GGRS87", 4121, "Greek Geodetic Reference System 1987", 6121, "GRS 1980", 7019, 6378137, 298.257222101}, {"potsdam", "DHDN", 4314, "Deutsches Hauptdreiecksnetz", 6314, "Bessel 1841", 7004, 6377397.155, 299.1528128}, {"carthage", "Carthage", 4223, "Carthage", 6223, "Clarke 1880 (IGN)", 7011, 6378249.2, 293.4660213}, {"hermannskogel", "MGI", 4312, "Militar-Geographische Institut", 6312, "Bessel 1841", 7004, 6377397.155, 299.1528128}, {"ire65", "TM65", 4299, "TM65", 6299, "Airy Modified 1849", 7002, 6377340.189, 299.3249646}, {"nzgd49", "NZGD49", 4272, "New Zealand Geodetic Datum 1949", 6272, "International 1924", 7022, 6378388, 297}, {"OSGB36", "OSGB 1936", 4277, "OSGB 1936", 6277, "Airy 1830", 7001, 6377563.396, 299.3249646}, }; // --------------------------------------------------------------------------- static bool isGeographicStep(const std::string &name) { return name == "longlat" || name == "lonlat" || name == "latlong" || name == "latlon"; } // --------------------------------------------------------------------------- static bool isGeocentricStep(const std::string &name) { return name == "geocent" || name == "cart"; } // --------------------------------------------------------------------------- static bool isTopocentricStep(const std::string &name) { return name == "topocentric"; } // --------------------------------------------------------------------------- static bool isProjectedStep(const std::string &name) { if (name == "etmerc" || name == "utm" || !getMappingsFromPROJName(name).empty()) { return true; } // IMPROVE ME: have a better way of distinguishing projections from // other // transformations. if (name == "pipeline" || name == "geoc" || name == "deformation" || name == "helmert" || name == "hgridshift" || name == "molodensky" || name == "vgridshift") { return false; } const auto *operations = proj_list_operations(); for (int i = 0; operations[i].id != nullptr; ++i) { if (name == operations[i].id) { return true; } } return false; } // --------------------------------------------------------------------------- static PropertyMap createMapWithUnknownName() { return PropertyMap().set(common::IdentifiedObject::NAME_KEY, "unknown"); } // --------------------------------------------------------------------------- PrimeMeridianNNPtr PROJStringParser::Private::buildPrimeMeridian(Step &step) { PrimeMeridianNNPtr pm = PrimeMeridian::GREENWICH; const auto &pmStr = getParamValue(step, "pm"); if (!pmStr.empty()) { char *end; double pmValue = dmstor(pmStr.c_str(), &end) * RAD_TO_DEG; if (pmValue != HUGE_VAL && *end == '\0') { pm = PrimeMeridian::create(createMapWithUnknownName(), Angle(pmValue)); } else { bool found = false; if (pmStr == "paris") { found = true; pm = PrimeMeridian::PARIS; } auto proj_prime_meridians = proj_list_prime_meridians(); for (int i = 0; !found && proj_prime_meridians[i].id != nullptr; i++) { if (pmStr == proj_prime_meridians[i].id) { found = true; std::string name = static_cast<char>(::toupper(pmStr[0])) + pmStr.substr(1); pmValue = dmstor(proj_prime_meridians[i].defn, nullptr) * RAD_TO_DEG; pm = PrimeMeridian::create( PropertyMap().set(IdentifiedObject::NAME_KEY, name), Angle(pmValue)); break; } } if (!found) { throw ParsingException("unknown pm " + pmStr); } } } return pm; } // --------------------------------------------------------------------------- std::string PROJStringParser::Private::guessBodyName(double a) { auto ret = Ellipsoid::guessBodyName(dbContext_, a); if (ret == "Non-Earth body" && dbContext_ == nullptr && ctx_ != nullptr) { dbContext_ = ctx_->get_cpp_context()->getDatabaseContext().as_nullable(); if (dbContext_) { ret = Ellipsoid::guessBodyName(dbContext_, a); } } return ret; } // --------------------------------------------------------------------------- GeodeticReferenceFrameNNPtr PROJStringParser::Private::buildDatum(Step &step, const std::string &title) { std::string ellpsStr = getParamValue(step, "ellps"); const auto &datumStr = getParamValue(step, "datum"); const auto &RStr = getParamValue(step, "R"); const auto &aStr = getParamValue(step, "a"); const auto &bStr = getParamValue(step, "b"); const auto &rfStr = getParamValue(step, "rf"); const auto &fStr = getParamValue(step, "f"); const auto &esStr = getParamValue(step, "es"); const auto &eStr = getParamValue(step, "e"); double a = -1.0; double b = -1.0; double rf = -1.0; const util::optional<std::string> optionalEmptyString{}; const bool numericParamPresent = !RStr.empty() || !aStr.empty() || !bStr.empty() || !rfStr.empty() || !fStr.empty() || !esStr.empty() || !eStr.empty(); if (!numericParamPresent && ellpsStr.empty() && datumStr.empty() && (step.name == "krovak" || step.name == "mod_krovak")) { ellpsStr = "bessel"; } PrimeMeridianNNPtr pm(buildPrimeMeridian(step)); PropertyMap grfMap; const auto &nadgrids = getParamValue(step, "nadgrids"); const auto &towgs84 = getParamValue(step, "towgs84"); std::string datumNameSuffix; if (!nadgrids.empty()) { datumNameSuffix = " using nadgrids=" + nadgrids; } else if (!towgs84.empty()) { datumNameSuffix = " using towgs84=" + towgs84; } // It is arguable that we allow the prime meridian of a datum defined by // its name to be overridden, but this is found at least in a regression // test // of GDAL. So let's keep the ellipsoid part of the datum in that case and // use the specified prime meridian. const auto overridePmIfNeeded = [&pm, &datumNameSuffix](const GeodeticReferenceFrameNNPtr &grf) { if (pm->_isEquivalentTo(PrimeMeridian::GREENWICH.get())) { return grf; } else { return GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Unknown based on " + grf->ellipsoid()->nameStr() + " ellipsoid" + datumNameSuffix), grf->ellipsoid(), grf->anchorDefinition(), pm); } }; // R take precedence if (!RStr.empty()) { double R; try { R = c_locale_stod(RStr); } catch (const std::invalid_argument &) { throw ParsingException("Invalid R value"); } auto ellipsoid = Ellipsoid::createSphere(createMapWithUnknownName(), Length(R), guessBodyName(R)); return GeodeticReferenceFrame::create( grfMap.set(IdentifiedObject::NAME_KEY, title.empty() ? "unknown" + datumNameSuffix : title), ellipsoid, optionalEmptyString, fixupPrimeMeridan(ellipsoid, pm)); } if (!datumStr.empty()) { auto l_datum = [&datumStr, &overridePmIfNeeded, &grfMap, &optionalEmptyString, &pm]() { if (datumStr == "WGS84") { return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6326); } else if (datumStr == "NAD83") { return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6269); } else if (datumStr == "NAD27") { return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6267); } else { for (const auto &datumDesc : datumDescs) { if (datumStr == datumDesc.projName) { (void)datumDesc.gcsName; // to please cppcheck (void)datumDesc.gcsCode; // to please cppcheck auto ellipsoid = Ellipsoid::createFlattenedSphere( grfMap .set(IdentifiedObject::NAME_KEY, datumDesc.ellipsoidName) .set(Identifier::CODESPACE_KEY, Identifier::EPSG) .set(Identifier::CODE_KEY, datumDesc.ellipsoidCode), Length(datumDesc.a), Scale(datumDesc.rf)); return GeodeticReferenceFrame::create( grfMap .set(IdentifiedObject::NAME_KEY, datumDesc.datumName) .set(Identifier::CODESPACE_KEY, Identifier::EPSG) .set(Identifier::CODE_KEY, datumDesc.datumCode), ellipsoid, optionalEmptyString, pm); } } } throw ParsingException("unknown datum " + datumStr); }(); if (!numericParamPresent) { return l_datum; } a = l_datum->ellipsoid()->semiMajorAxis().getSIValue(); rf = l_datum->ellipsoid()->computedInverseFlattening(); } else if (!ellpsStr.empty()) { auto l_datum = [&ellpsStr, &title, &grfMap, &optionalEmptyString, &pm, &datumNameSuffix]() { if (ellpsStr == "WGS84") { return GeodeticReferenceFrame::create( grfMap.set(IdentifiedObject::NAME_KEY, title.empty() ? "Unknown based on WGS 84 ellipsoid" + datumNameSuffix : title), Ellipsoid::WGS84, optionalEmptyString, pm); } else if (ellpsStr == "GRS80") { return GeodeticReferenceFrame::create( grfMap.set(IdentifiedObject::NAME_KEY, title.empty() ? "Unknown based on GRS 1980 ellipsoid" + datumNameSuffix : title), Ellipsoid::GRS1980, optionalEmptyString, pm); } else { auto proj_ellps = proj_list_ellps(); for (int i = 0; proj_ellps[i].id != nullptr; i++) { if (ellpsStr == proj_ellps[i].id) { assert(strncmp(proj_ellps[i].major, "a=", 2) == 0); const double a_iter = c_locale_stod(proj_ellps[i].major + 2); EllipsoidPtr ellipsoid; PropertyMap ellpsMap; if (strncmp(proj_ellps[i].ell, "b=", 2) == 0) { const double b_iter = c_locale_stod(proj_ellps[i].ell + 2); ellipsoid = Ellipsoid::createTwoAxis( ellpsMap.set(IdentifiedObject::NAME_KEY, proj_ellps[i].name), Length(a_iter), Length(b_iter)) .as_nullable(); } else { assert(strncmp(proj_ellps[i].ell, "rf=", 3) == 0); const double rf_iter = c_locale_stod(proj_ellps[i].ell + 3); ellipsoid = Ellipsoid::createFlattenedSphere( ellpsMap.set(IdentifiedObject::NAME_KEY, proj_ellps[i].name), Length(a_iter), Scale(rf_iter)) .as_nullable(); } return GeodeticReferenceFrame::create( grfMap.set(IdentifiedObject::NAME_KEY, title.empty() ? std::string("Unknown based on ") + proj_ellps[i].name + " ellipsoid" + datumNameSuffix : title), NN_NO_CHECK(ellipsoid), optionalEmptyString, pm); } } throw ParsingException("unknown ellipsoid " + ellpsStr); } }(); if (!numericParamPresent) { return l_datum; } a = l_datum->ellipsoid()->semiMajorAxis().getSIValue(); if (l_datum->ellipsoid()->semiMinorAxis().has_value()) { b = l_datum->ellipsoid()->semiMinorAxis()->getSIValue(); } else { rf = l_datum->ellipsoid()->computedInverseFlattening(); } } if (!aStr.empty()) { try { a = c_locale_stod(aStr); } catch (const std::invalid_argument &) { throw ParsingException("Invalid a value"); } } const auto createGRF = [&grfMap, &title, &optionalEmptyString, &datumNameSuffix, &pm](const EllipsoidNNPtr &ellipsoid) { std::string datumName(title); if (title.empty()) { if (ellipsoid->nameStr() != "unknown") { datumName = "Unknown based on "; datumName += ellipsoid->nameStr(); datumName += " ellipsoid"; } else { datumName = "unknown"; } datumName += datumNameSuffix; } return GeodeticReferenceFrame::create( grfMap.set(IdentifiedObject::NAME_KEY, datumName), ellipsoid, optionalEmptyString, fixupPrimeMeridan(ellipsoid, pm)); }; if (a > 0 && (b > 0 || !bStr.empty())) { if (!bStr.empty()) { try { b = c_locale_stod(bStr); } catch (const std::invalid_argument &) { throw ParsingException("Invalid b value"); } } auto ellipsoid = Ellipsoid::createTwoAxis(createMapWithUnknownName(), Length(a), Length(b), guessBodyName(a)) ->identify(); return createGRF(ellipsoid); } else if (a > 0 && (rf >= 0 || !rfStr.empty())) { if (!rfStr.empty()) { try { rf = c_locale_stod(rfStr); } catch (const std::invalid_argument &) { throw ParsingException("Invalid rf value"); } } auto ellipsoid = Ellipsoid::createFlattenedSphere( createMapWithUnknownName(), Length(a), Scale(rf), guessBodyName(a)) ->identify(); return createGRF(ellipsoid); } else if (a > 0 && !fStr.empty()) { double f; try { f = c_locale_stod(fStr); } catch (const std::invalid_argument &) { throw ParsingException("Invalid f value"); } auto ellipsoid = Ellipsoid::createFlattenedSphere( createMapWithUnknownName(), Length(a), Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a)) ->identify(); return createGRF(ellipsoid); } else if (a > 0 && !eStr.empty()) { double e; try { e = c_locale_stod(eStr); } catch (const std::invalid_argument &) { throw ParsingException("Invalid e value"); } double alpha = asin(e); /* angular eccentricity */ double f = 1 - cos(alpha); /* = 1 - sqrt (1 - es); */ auto ellipsoid = Ellipsoid::createFlattenedSphere( createMapWithUnknownName(), Length(a), Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a)) ->identify(); return createGRF(ellipsoid); } else if (a > 0 && !esStr.empty()) { double es; try { es = c_locale_stod(esStr); } catch (const std::invalid_argument &) { throw ParsingException("Invalid es value"); } double f = 1 - sqrt(1 - es); auto ellipsoid = Ellipsoid::createFlattenedSphere( createMapWithUnknownName(), Length(a), Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a)) ->identify(); return createGRF(ellipsoid); } // If only a is specified, create a sphere if (a > 0 && bStr.empty() && rfStr.empty() && eStr.empty() && esStr.empty()) { auto ellipsoid = Ellipsoid::createSphere(createMapWithUnknownName(), Length(a), guessBodyName(a)); return createGRF(ellipsoid); } if (!bStr.empty() && aStr.empty()) { throw ParsingException("b found, but a missing"); } if (!rfStr.empty() && aStr.empty()) { throw ParsingException("rf found, but a missing"); } if (!fStr.empty() && aStr.empty()) { throw ParsingException("f found, but a missing"); } if (!eStr.empty() && aStr.empty()) { throw ParsingException("e found, but a missing"); } if (!esStr.empty() && aStr.empty()) { throw ParsingException("es found, but a missing"); } return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6326); } // --------------------------------------------------------------------------- static const MeridianPtr nullMeridian{}; static CoordinateSystemAxisNNPtr createAxis(const std::string &name, const std::string &abbreviation, const AxisDirection &direction, const common::UnitOfMeasure &unit, const MeridianPtr &meridian = nullMeridian) { return CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, name), abbreviation, direction, unit, meridian); } std::vector<CoordinateSystemAxisNNPtr> PROJStringParser::Private::processAxisSwap(Step &step, const UnitOfMeasure &unit, int iAxisSwap, AxisType axisType, bool ignorePROJAxis) { assert(iAxisSwap < 0 || ci_equal(steps_[iAxisSwap].name, "axisswap")); const bool isGeographic = unit.type() == UnitOfMeasure::Type::ANGULAR; const bool isSpherical = isGeographic && hasParamValue(step, "geoc"); const auto &eastName = isSpherical ? "Planetocentric longitude" : isGeographic ? AxisName::Longitude : AxisName::Easting; const auto &eastAbbev = isSpherical ? "V" : isGeographic ? AxisAbbreviation::lon : AxisAbbreviation::E; const auto &eastDir = isGeographic ? AxisDirection::EAST : (axisType == AxisType::NORTH_POLE) ? AxisDirection::SOUTH : (axisType == AxisType::SOUTH_POLE) ? AxisDirection::NORTH : AxisDirection::EAST; CoordinateSystemAxisNNPtr east = createAxis( eastName, eastAbbev, eastDir, unit, (!isGeographic && (axisType == AxisType::NORTH_POLE || axisType == AxisType::SOUTH_POLE)) ? Meridian::create(Angle(90, UnitOfMeasure::DEGREE)).as_nullable() : nullMeridian); const auto &northName = isSpherical ? "Planetocentric latitude" : isGeographic ? AxisName::Latitude : AxisName::Northing; const auto &northAbbev = isSpherical ? "U" : isGeographic ? AxisAbbreviation::lat : AxisAbbreviation::N; const auto &northDir = isGeographic ? AxisDirection::NORTH : (axisType == AxisType::NORTH_POLE) ? AxisDirection::SOUTH /*: (axisType == AxisType::SOUTH_POLE) ? AxisDirection::NORTH*/ : AxisDirection::NORTH; const CoordinateSystemAxisNNPtr north = createAxis( northName, northAbbev, northDir, unit, isGeographic ? nullMeridian : (axisType == AxisType::NORTH_POLE) ? Meridian::create(Angle(180, UnitOfMeasure::DEGREE)).as_nullable() : (axisType == AxisType::SOUTH_POLE) ? Meridian::create(Angle(0, UnitOfMeasure::DEGREE)).as_nullable() : nullMeridian); const CoordinateSystemAxisNNPtr west = createAxis(isSpherical ? "Planetocentric longitude" : isGeographic ? AxisName::Longitude : AxisName::Westing, isSpherical ? "V" : isGeographic ? AxisAbbreviation::lon : std::string(), AxisDirection::WEST, unit); const CoordinateSystemAxisNNPtr south = createAxis(isSpherical ? "Planetocentric latitude" : isGeographic ? AxisName::Latitude : AxisName::Southing, isSpherical ? "U" : isGeographic ? AxisAbbreviation::lat : std::string(), AxisDirection::SOUTH, unit); std::vector<CoordinateSystemAxisNNPtr> axis{east, north}; const auto &axisStr = getParamValue(step, "axis"); if (!ignorePROJAxis && !axisStr.empty()) { if (axisStr.size() == 3) { for (int i = 0; i < 2; i++) { if (axisStr[i] == 'n') { axis[i] = north; } else if (axisStr[i] == 's') { axis[i] = south; } else if (axisStr[i] == 'e') { axis[i] = east; } else if (axisStr[i] == 'w') { axis[i] = west; } else { throw ParsingException("Unhandled axis=" + axisStr); } } } else { throw ParsingException("Unhandled axis=" + axisStr); } } else if (iAxisSwap >= 0) { auto &stepAxisSwap = steps_[iAxisSwap]; const auto &orderStr = getParamValue(stepAxisSwap, "order"); auto orderTab = split(orderStr, ','); if (orderTab.size() != 2) { throw ParsingException("Unhandled order=" + orderStr); } if (stepAxisSwap.inverted) { throw ParsingException("Unhandled +inv for +proj=axisswap"); } for (size_t i = 0; i < 2; i++) { if (orderTab[i] == "1") { axis[i] = east; } else if (orderTab[i] == "-1") { axis[i] = west; } else if (orderTab[i] == "2") { axis[i] = north; } else if (orderTab[i] == "-2") { axis[i] = south; } else { throw ParsingException("Unhandled order=" + orderStr); } } } else if ((step.name == "krovak" || step.name == "mod_krovak") && hasParamValue(step, "czech")) { axis[0] = west; axis[1] = south; } return axis; } // --------------------------------------------------------------------------- EllipsoidalCSNNPtr PROJStringParser::Private::buildEllipsoidalCS( int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) { auto &step = steps_[iStep]; assert(iUnitConvert < 0 || ci_equal(steps_[iUnitConvert].name, "unitconvert")); UnitOfMeasure angularUnit = UnitOfMeasure::DEGREE; if (iUnitConvert >= 0) { auto &stepUnitConvert = steps_[iUnitConvert]; const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in"); const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out"); if (stepUnitConvert.inverted) { std::swap(xy_in, xy_out); } if (iUnitConvert < iStep) { std::swap(xy_in, xy_out); } if (xy_in->empty() || xy_out->empty() || *xy_in != "rad" || (*xy_out != "rad" && *xy_out != "deg" && *xy_out != "grad")) { throw ParsingException("unhandled values for xy_in and/or xy_out"); } if (*xy_out == "rad") { angularUnit = UnitOfMeasure::RADIAN; } else if (*xy_out == "grad") { angularUnit = UnitOfMeasure::GRAD; } } std::vector<CoordinateSystemAxisNNPtr> axis = processAxisSwap( step, angularUnit, iAxisSwap, AxisType::REGULAR, ignorePROJAxis); CoordinateSystemAxisNNPtr up = CoordinateSystemAxis::create( util::PropertyMap().set(IdentifiedObject::NAME_KEY, AxisName::Ellipsoidal_height), AxisAbbreviation::h, AxisDirection::UP, buildUnit(step, "vunits", "vto_meter")); return (!hasParamValue(step, "geoidgrids") && (hasParamValue(step, "vunits") || hasParamValue(step, "vto_meter"))) ? EllipsoidalCS::create(emptyPropertyMap, axis[0], axis[1], up) : EllipsoidalCS::create(emptyPropertyMap, axis[0], axis[1]); } // --------------------------------------------------------------------------- SphericalCSNNPtr PROJStringParser::Private::buildSphericalCS( int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) { auto &step = steps_[iStep]; assert(iUnitConvert < 0 || ci_equal(steps_[iUnitConvert].name, "unitconvert")); UnitOfMeasure angularUnit = UnitOfMeasure::DEGREE; if (iUnitConvert >= 0) { auto &stepUnitConvert = steps_[iUnitConvert]; const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in"); const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out"); if (stepUnitConvert.inverted) { std::swap(xy_in, xy_out); } if (iUnitConvert < iStep) { std::swap(xy_in, xy_out); } if (xy_in->empty() || xy_out->empty() || *xy_in != "rad" || (*xy_out != "rad" && *xy_out != "deg" && *xy_out != "grad")) { throw ParsingException("unhandled values for xy_in and/or xy_out"); } if (*xy_out == "rad") { angularUnit = UnitOfMeasure::RADIAN; } else if (*xy_out == "grad") { angularUnit = UnitOfMeasure::GRAD; } } std::vector<CoordinateSystemAxisNNPtr> axis = processAxisSwap( step, angularUnit, iAxisSwap, AxisType::REGULAR, ignorePROJAxis); return SphericalCS::create(emptyPropertyMap, axis[0], axis[1]); } // --------------------------------------------------------------------------- static double getNumericValue(const std::string &paramValue, bool *pHasError = nullptr) { bool success; double value = c_locale_stod(paramValue, success); if (pHasError) *pHasError = !success; return value; } // --------------------------------------------------------------------------- namespace { template <class T> inline void ignoreRetVal(T) {} } // namespace GeodeticCRSNNPtr PROJStringParser::Private::buildGeodeticCRS( int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) { auto &step = steps_[iStep]; const bool l_isGeographicStep = isGeographicStep(step.name); const auto &title = l_isGeographicStep ? title_ : emptyString; // units=m is often found in the wild. // No need to create a extension string for this ignoreRetVal(hasParamValue(step, "units")); auto datum = buildDatum(step, title); auto props = PropertyMap().set(IdentifiedObject::NAME_KEY, title.empty() ? "unknown" : title); if (l_isGeographicStep && (hasUnusedParameters(step) || getNumericValue(getParamValue(step, "lon_0")) != 0.0)) { props.set("EXTENSION_PROJ4", projString_); } props.set("IMPLICIT_CS", true); if (!hasParamValue(step, "geoc")) { auto cs = buildEllipsoidalCS(iStep, iUnitConvert, iAxisSwap, ignorePROJAxis); return GeographicCRS::create(props, datum, cs); } else { auto cs = buildSphericalCS(iStep, iUnitConvert, iAxisSwap, ignorePROJAxis); return GeodeticCRS::create(props, datum, cs); } } // --------------------------------------------------------------------------- GeodeticCRSNNPtr PROJStringParser::Private::buildGeocentricCRS(int iStep, int iUnitConvert) { auto &step = steps_[iStep]; assert(isGeocentricStep(step.name) || isTopocentricStep(step.name)); assert(iUnitConvert < 0 || ci_equal(steps_[iUnitConvert].name, "unitconvert")); const auto &title = title_; auto datum = buildDatum(step, title); UnitOfMeasure unit = buildUnit(step, "units", ""); if (iUnitConvert >= 0) { auto &stepUnitConvert = steps_[iUnitConvert]; const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in"); const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out"); const std::string *z_in = &getParamValue(stepUnitConvert, "z_in"); const std::string *z_out = &getParamValue(stepUnitConvert, "z_out"); if (stepUnitConvert.inverted) { std::swap(xy_in, xy_out); std::swap(z_in, z_out); } if (xy_in->empty() || xy_out->empty() || *xy_in != "m" || *z_in != "m" || *xy_out != *z_out) { throw ParsingException( "unhandled values for xy_in, z_in, xy_out or z_out"); } const LinearUnitDesc *unitsMatch = nullptr; try { double to_meter_value = c_locale_stod(*xy_out); unitsMatch = getLinearUnits(to_meter_value); if (unitsMatch == nullptr) { unit = _buildUnit(to_meter_value); } } catch (const std::invalid_argument &) { unitsMatch = getLinearUnits(*xy_out); if (!unitsMatch) { throw ParsingException( "unhandled values for xy_in, z_in, xy_out or z_out"); } unit = _buildUnit(unitsMatch); } } auto props = PropertyMap().set(IdentifiedObject::NAME_KEY, title.empty() ? "unknown" : title); auto cs = CartesianCS::createGeocentric(unit); if (hasUnusedParameters(step)) { props.set("EXTENSION_PROJ4", projString_); } return GeodeticCRS::create(props, datum, cs); } // --------------------------------------------------------------------------- CRSNNPtr PROJStringParser::Private::buildBoundOrCompoundCRSIfNeeded(int iStep, CRSNNPtr crs) { auto &step = steps_[iStep]; const auto &nadgrids = getParamValue(step, "nadgrids"); const auto &towgs84 = getParamValue(step, "towgs84"); // nadgrids has the priority over towgs84 if (!ignoreNadgrids_ && !nadgrids.empty()) { crs = BoundCRS::createFromNadgrids(crs, nadgrids); } else if (!towgs84.empty()) { std::vector<double> towgs84Values; const auto tokens = split(towgs84, ','); for (const auto &str : tokens) { try { towgs84Values.push_back(c_locale_stod(str)); } catch (const std::invalid_argument &) { throw ParsingException("Non numerical value in towgs84 clause"); } } crs = BoundCRS::createFromTOWGS84(crs, towgs84Values); } const auto &geoidgrids = getParamValue(step, "geoidgrids"); if (!geoidgrids.empty()) { auto vdatum = VerticalReferenceFrame::create( PropertyMap().set(common::IdentifiedObject::NAME_KEY, "unknown using geoidgrids=" + geoidgrids)); const UnitOfMeasure unit = buildUnit(step, "vunits", "vto_meter"); auto vcrs = VerticalCRS::create(createMapWithUnknownName(), vdatum, VerticalCS::createGravityRelatedHeight(unit)); CRSNNPtr geogCRS = GeographicCRS::EPSG_4979; // default const auto &geoid_crs = getParamValue(step, "geoid_crs"); if (!geoid_crs.empty()) { if (geoid_crs == "WGS84") { // nothing to do } else if (geoid_crs == "horizontal_crs") { auto geogCRSOfCompoundCRS = crs->extractGeographicCRS(); if (geogCRSOfCompoundCRS && geogCRSOfCompoundCRS->primeMeridian() ->longitude() .getSIValue() == 0 && geogCRSOfCompoundCRS->coordinateSystem() ->axisList()[0] ->unit() == UnitOfMeasure::DEGREE) { geogCRS = geogCRSOfCompoundCRS->promoteTo3D(std::string(), nullptr); } else if (geogCRSOfCompoundCRS) { auto geogCRSOfCompoundCRSDatum = geogCRSOfCompoundCRS->datumNonNull(nullptr); geogCRS = GeographicCRS::create( createMapWithUnknownName(), datum::GeodeticReferenceFrame::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, geogCRSOfCompoundCRSDatum->nameStr() + " (with Greenwich prime meridian)"), geogCRSOfCompoundCRSDatum->ellipsoid(), util::optional<std::string>(), datum::PrimeMeridian::GREENWICH), EllipsoidalCS::createLongitudeLatitudeEllipsoidalHeight( UnitOfMeasure::DEGREE, UnitOfMeasure::METRE)); } } else { throw ParsingException("Unsupported value for geoid_crs: " "should be 'WGS84' or 'horizontal_crs'"); } } auto transformation = Transformation::createGravityRelatedHeightToGeographic3D( PropertyMap().set(IdentifiedObject::NAME_KEY, "unknown to " + geogCRS->nameStr() + " ellipsoidal height"), VerticalCRS::create(createMapWithUnknownName(), vdatum, VerticalCS::createGravityRelatedHeight( common::UnitOfMeasure::METRE)), geogCRS, nullptr, geoidgrids, std::vector<PositionalAccuracyNNPtr>()); auto boundvcrs = BoundCRS::create(vcrs, geogCRS, transformation); crs = CompoundCRS::create(createMapWithUnknownName(), std::vector<CRSNNPtr>{crs, boundvcrs}); } return crs; } // --------------------------------------------------------------------------- static double getAngularValue(const std::string &paramValue, bool *pHasError = nullptr) { char *endptr = nullptr; double value = dmstor(paramValue.c_str(), &endptr) * RAD_TO_DEG; if (value == HUGE_VAL || endptr != paramValue.c_str() + paramValue.size()) { if (pHasError) *pHasError = true; return 0.0; } if (pHasError) *pHasError = false; return value; } // --------------------------------------------------------------------------- static bool is_in_stringlist(const std::string &str, const char *stringlist) { if (str.empty()) return false; const char *haystack = stringlist; while (true) { const char *res = strstr(haystack, str.c_str()); if (res == nullptr) return false; if ((res == stringlist || res[-1] == ',') && (res[str.size()] == ',' || res[str.size()] == '\0')) return true; haystack += str.size(); } } // --------------------------------------------------------------------------- CRSNNPtr PROJStringParser::Private::buildProjectedCRS(int iStep, const GeodeticCRSNNPtr &geodCRS, int iUnitConvert, int iAxisSwap) { auto &step = steps_[iStep]; const auto mappings = getMappingsFromPROJName(step.name); const MethodMapping *mapping = mappings.empty() ? nullptr : mappings[0]; bool foundStrictlyMatchingMapping = false; if (mappings.size() >= 2) { // To distinguish for example +ortho from +ortho +f=0 bool allMappingsHaveAuxParam = true; for (const auto *mappingIter : mappings) { if (mappingIter->proj_name_aux == nullptr) { allMappingsHaveAuxParam = false; } if (mappingIter->proj_name_aux != nullptr && strchr(mappingIter->proj_name_aux, '=') == nullptr && hasParamValue(step, mappingIter->proj_name_aux)) { foundStrictlyMatchingMapping = true; mapping = mappingIter; break; } else if (mappingIter->proj_name_aux != nullptr && strchr(mappingIter->proj_name_aux, '=') != nullptr) { const auto tokens = split(mappingIter->proj_name_aux, '='); if (tokens.size() == 2 && getParamValue(step, tokens[0]) == tokens[1]) { foundStrictlyMatchingMapping = true; mapping = mappingIter; break; } } } if (allMappingsHaveAuxParam && !foundStrictlyMatchingMapping) { mapping = nullptr; } } if (mapping && !foundStrictlyMatchingMapping) { mapping = selectSphericalOrEllipsoidal(mapping, geodCRS); } assert(isProjectedStep(step.name)); assert(iUnitConvert < 0 || ci_equal(steps_[iUnitConvert].name, "unitconvert")); const auto &title = title_; if (!buildPrimeMeridian(step)->longitude()._isEquivalentTo( geodCRS->primeMeridian()->longitude(), util::IComparable::Criterion::EQUIVALENT)) { throw ParsingException("inconsistent pm values between projectedCRS " "and its base geographicalCRS"); } auto axisType = AxisType::REGULAR; bool bWebMercator = false; std::string webMercatorName("WGS 84 / Pseudo-Mercator"); if (step.name == "tmerc" && ((getParamValue(step, "axis") == "wsu" && iAxisSwap < 0) || (iAxisSwap > 0 && getParamValue(steps_[iAxisSwap], "order") == "-1,-2"))) { mapping = getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED); } else if (step.name == "etmerc") { mapping = getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR); } else if (step.name == "lcc") { const auto &lat_0 = getParamValue(step, "lat_0"); const auto &lat_1 = getParamValue(step, "lat_1"); const auto &lat_2 = getParamValue(step, "lat_2"); const auto &k = getParamValueK(step); if (lat_2.empty() && !lat_0.empty() && !lat_1.empty()) { if (lat_0 == lat_1 || // For some reason with gcc 5.3.1-14ubuntu2 32bit, the following // comparison returns false even if lat_0 == lat_1. Smells like // a compiler bug getAngularValue(lat_0) == getAngularValue(lat_1)) { mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); } else { mapping = getMapping( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B); } } else if (!k.empty() && getNumericValue(k) != 1.0) { mapping = getMapping( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN); } else { mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); } } else if (step.name == "aeqd" && hasParamValue(step, "guam")) { mapping = getMapping(EPSG_CODE_METHOD_GUAM_PROJECTION); } else if (step.name == "geos" && getParamValue(step, "sweep") == "x") { mapping = getMapping(PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X); } else if (step.name == "geos") { mapping = getMapping(PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y); } else if (step.name == "omerc") { if (hasParamValue(step, "no_rot")) { mapping = nullptr; } else if (hasParamValue(step, "no_uoff") || hasParamValue(step, "no_off")) { mapping = getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A); } else if (hasParamValue(step, "lat_1") && hasParamValue(step, "lon_1") && hasParamValue(step, "lat_2") && hasParamValue(step, "lon_2")) { mapping = getMapping( PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN); } else { mapping = getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B); } } else if (step.name == "somerc") { mapping = getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B); if (!hasParamValue(step, "alpha") && !hasParamValue(step, "gamma") && !hasParamValue(step, "lonc")) { step.paramValues.emplace_back(Step::KeyValue("alpha", "90")); step.paramValues.emplace_back(Step::KeyValue("gamma", "90")); step.paramValues.emplace_back( Step::KeyValue("lonc", getParamValue(step, "lon_0"))); } } else if (step.name == "krovak" && ((iAxisSwap < 0 && getParamValue(step, "axis") == "swu" && !hasParamValue(step, "czech")) || (iAxisSwap > 0 && getParamValue(steps_[iAxisSwap], "order") == "-2,-1" && !hasParamValue(step, "czech")))) { mapping = getMapping(EPSG_CODE_METHOD_KROVAK); } else if (step.name == "krovak" && iAxisSwap < 0 && hasParamValue(step, "czech") && !hasParamValue(step, "axis")) { mapping = getMapping(EPSG_CODE_METHOD_KROVAK); } else if (step.name == "mod_krovak" && ((iAxisSwap < 0 && getParamValue(step, "axis") == "swu" && !hasParamValue(step, "czech")) || (iAxisSwap > 0 && getParamValue(steps_[iAxisSwap], "order") == "-2,-1" && !hasParamValue(step, "czech")))) { mapping = getMapping(EPSG_CODE_METHOD_KROVAK_MODIFIED); } else if (step.name == "mod_krovak" && iAxisSwap < 0 && hasParamValue(step, "czech") && !hasParamValue(step, "axis")) { mapping = getMapping(EPSG_CODE_METHOD_KROVAK_MODIFIED); } else if (step.name == "merc") { if (hasParamValue(step, "a") && hasParamValue(step, "b") && getParamValue(step, "a") == getParamValue(step, "b") && (!hasParamValue(step, "lat_ts") || getAngularValue(getParamValue(step, "lat_ts")) == 0.0) && getNumericValue(getParamValueK(step)) == 1.0 && getParamValue(step, "nadgrids") == "@null") { mapping = getMapping( EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR); for (size_t i = 0; i < step.paramValues.size(); ++i) { if (ci_equal(step.paramValues[i].key, "nadgrids")) { ignoreNadgrids_ = true; break; } } if (getNumericValue(getParamValue(step, "a")) == 6378137 && getAngularValue(getParamValue(step, "lon_0")) == 0.0 && getAngularValue(getParamValue(step, "lat_0")) == 0.0 && getAngularValue(getParamValue(step, "x_0")) == 0.0 && getAngularValue(getParamValue(step, "y_0")) == 0.0) { bWebMercator = true; if (hasParamValue(step, "units") && getParamValue(step, "units") != "m") { webMercatorName += " (unit " + getParamValue(step, "units") + ')'; } } } else if (hasParamValue(step, "lat_ts")) { if (hasParamValue(step, "R_C") && !geodCRS->ellipsoid()->isSphere() && getAngularValue(getParamValue(step, "lat_ts")) != 0) { throw ParsingException("lat_ts != 0 not supported for " "spherical Mercator on an ellipsoid"); } mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_B); } else if (hasParamValue(step, "R_C")) { const auto &k = getParamValueK(step); if (!k.empty() && getNumericValue(k) != 1.0) { if (geodCRS->ellipsoid()->isSphere()) { mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_A); } else { throw ParsingException( "k_0 != 1 not supported for spherical Mercator on an " "ellipsoid"); } } else { mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_SPHERICAL); } } else { mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_A); } } else if (step.name == "stere") { if (hasParamValue(step, "lat_0") && std::fabs(std::fabs(getAngularValue(getParamValue(step, "lat_0"))) - 90.0) < 1e-10) { const double lat_0 = getAngularValue(getParamValue(step, "lat_0")); if (lat_0 > 0) { axisType = AxisType::NORTH_POLE; } else { axisType = AxisType::SOUTH_POLE; } const auto &lat_ts = getParamValue(step, "lat_ts"); const auto &k = getParamValueK(step); if (!lat_ts.empty() && std::fabs(getAngularValue(lat_ts) - lat_0) > 1e-10 && !k.empty() && std::fabs(getNumericValue(k) - 1) > 1e-10) { throw ParsingException("lat_ts != lat_0 and k != 1 not " "supported for Polar Stereographic"); } if (!lat_ts.empty() && (k.empty() || std::fabs(getNumericValue(k) - 1) < 1e-10)) { mapping = getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B); } else { mapping = getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A); } } else { mapping = getMapping(PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC); } } else if (step.name == "laea") { if (hasParamValue(step, "lat_0") && std::fabs(std::fabs(getAngularValue(getParamValue(step, "lat_0"))) - 90.0) < 1e-10) { const double lat_0 = getAngularValue(getParamValue(step, "lat_0")); if (lat_0 > 0) { axisType = AxisType::NORTH_POLE; } else { axisType = AxisType::SOUTH_POLE; } } } UnitOfMeasure unit = buildUnit(step, "units", "to_meter"); if (iUnitConvert >= 0) { auto &stepUnitConvert = steps_[iUnitConvert]; const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in"); const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out"); if (stepUnitConvert.inverted) { std::swap(xy_in, xy_out); } if (xy_in->empty() || xy_out->empty() || *xy_in != "m") { if (step.name != "ob_tran") { throw ParsingException( "unhandled values for xy_in and/or xy_out"); } } const LinearUnitDesc *unitsMatch = nullptr; try { double to_meter_value = c_locale_stod(*xy_out); unitsMatch = getLinearUnits(to_meter_value); if (unitsMatch == nullptr) { unit = _buildUnit(to_meter_value); } } catch (const std::invalid_argument &) { unitsMatch = getLinearUnits(*xy_out); if (!unitsMatch) { if (step.name != "ob_tran") { throw ParsingException( "unhandled values for xy_in and/or xy_out"); } } else { unit = _buildUnit(unitsMatch); } } } ConversionPtr conv; auto mapWithUnknownName = createMapWithUnknownName(); if (step.name == "utm") { const int zone = std::atoi(getParamValue(step, "zone").c_str()); const bool north = !hasParamValue(step, "south"); conv = Conversion::createUTM(emptyPropertyMap, zone, north).as_nullable(); } else if (mapping) { auto methodMap = PropertyMap().set(IdentifiedObject::NAME_KEY, mapping->wkt2_name); if (mapping->epsg_code) { methodMap.set(Identifier::CODESPACE_KEY, Identifier::EPSG) .set(Identifier::CODE_KEY, mapping->epsg_code); } std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; for (int i = 0; mapping->params[i] != nullptr; i++) { const auto *param = mapping->params[i]; std::string proj_name(param->proj_name ? param->proj_name : ""); const std::string *paramValue = (proj_name == "k" || proj_name == "k_0") ? &getParamValueK(step) : !proj_name.empty() ? &getParamValue(step, proj_name) : &emptyString; double value = 0; if (!paramValue->empty()) { bool hasError = false; if (param->unit_type == UnitOfMeasure::Type::ANGULAR) { value = getAngularValue(*paramValue, &hasError); } else { value = getNumericValue(*paramValue, &hasError); } if (hasError) { throw ParsingException("invalid value for " + proj_name); } } // For omerc, if gamma is missing, the default value is // alpha else if (step.name == "omerc" && proj_name == "gamma") { paramValue = &getParamValue(step, "alpha"); if (!paramValue->empty()) { value = getAngularValue(*paramValue); } } else if (step.name == "krovak" || step.name == "mod_krovak") { // Keep it in sync with defaults of krovak.cpp if (param->epsg_code == EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE) { value = 49.5; } else if (param->epsg_code == EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN) { value = 24.833333333333333333; } else if (param->epsg_code == EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS) { value = 30.28813975277777776; } else if ( param->epsg_code == EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL) { value = 78.5; } else if ( param->epsg_code == EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL) { value = 0.9999; } } else if (step.name == "cea" && proj_name == "lat_ts") { paramValue = &getParamValueK(step); if (!paramValue->empty()) { bool hasError = false; const double k = getNumericValue(*paramValue, &hasError); if (hasError) { throw ParsingException("invalid value for k/k_0"); } if (k >= 0 && k <= 1) { const double es = geodCRS->ellipsoid()->squaredEccentricity(); if (es < 0 || es == 1) { throw ParsingException("Invalid flattening"); } value = Angle(acos(k * sqrt((1 - es) / (1 - k * k * es))), UnitOfMeasure::RADIAN) .convertToUnit(UnitOfMeasure::DEGREE); } else { throw ParsingException("k/k_0 should be in [0,1]"); } } } else if (param->unit_type == UnitOfMeasure::Type::SCALE) { value = 1; } else if (step.name == "peirce_q" && proj_name == "lat_0") { value = 90; } PropertyMap propertiesParameter; propertiesParameter.set(IdentifiedObject::NAME_KEY, param->wkt2_name); if (param->epsg_code) { propertiesParameter.set(Identifier::CODE_KEY, param->epsg_code); propertiesParameter.set(Identifier::CODESPACE_KEY, Identifier::EPSG); } parameters.push_back( OperationParameter::create(propertiesParameter)); // In PROJ convention, angular parameters are always in degree // and linear parameters always in metre. double valRounded = param->unit_type == UnitOfMeasure::Type::LINEAR ? Length(value, UnitOfMeasure::METRE).convertToUnit(unit) : value; if (std::fabs(valRounded - std::round(valRounded)) < 1e-8) { valRounded = std::round(valRounded); } values.push_back(ParameterValue::create( Measure(valRounded, param->unit_type == UnitOfMeasure::Type::ANGULAR ? UnitOfMeasure::DEGREE : param->unit_type == UnitOfMeasure::Type::LINEAR ? unit : param->unit_type == UnitOfMeasure::Type::SCALE ? UnitOfMeasure::SCALE_UNITY : UnitOfMeasure::NONE))); } if (step.name == "tmerc" && hasParamValue(step, "approx")) { methodMap.set("proj_method", "tmerc approx"); } else if (step.name == "utm" && hasParamValue(step, "approx")) { methodMap.set("proj_method", "utm approx"); } conv = Conversion::create(mapWithUnknownName, methodMap, parameters, values) .as_nullable(); } else { std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; std::string methodName = "PROJ " + step.name; for (const auto &param : step.paramValues) { if (is_in_stringlist(param.key, "wktext,no_defs,datum,ellps,a,b,R,f,rf," "towgs84,nadgrids,geoidgrids," "units,to_meter,vunits,vto_meter,type")) { continue; } if (param.value.empty()) { methodName += " " + param.key; } else if (isalpha(param.value[0])) { methodName += " " + param.key + "=" + param.value; } else { parameters.push_back(OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, param.key))); bool hasError = false; if (is_in_stringlist(param.key, "x_0,y_0,h,h_0")) { double value = getNumericValue(param.value, &hasError); values.push_back(ParameterValue::create( Measure(value, UnitOfMeasure::METRE))); } else if (is_in_stringlist( param.key, "k,k_0," "north_square,south_square," // rhealpix "n,m," // sinu "q," // urm5 "path,lsat," // lsat "W,M," // hammer "aperture,resolution," // isea )) { double value = getNumericValue(param.value, &hasError); values.push_back(ParameterValue::create( Measure(value, UnitOfMeasure::SCALE_UNITY))); } else { double value = getAngularValue(param.value, &hasError); values.push_back(ParameterValue::create( Measure(value, UnitOfMeasure::DEGREE))); } if (hasError) { throw ParsingException("invalid value for " + param.key); } } } conv = Conversion::create( mapWithUnknownName, PropertyMap().set(IdentifiedObject::NAME_KEY, methodName), parameters, values) .as_nullable(); for (const char *substr : {"PROJ ob_tran o_proj=longlat", "PROJ ob_tran o_proj=lonlat", "PROJ ob_tran o_proj=latlon", "PROJ ob_tran o_proj=latlong"}) { if (starts_with(methodName, substr)) { auto geogCRS = util::nn_dynamic_pointer_cast<GeographicCRS>(geodCRS); if (geogCRS) { return DerivedGeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), NN_NO_CHECK(geogCRS), NN_NO_CHECK(conv), buildEllipsoidalCS(iStep, iUnitConvert, iAxisSwap, false)); } } } } std::vector<CoordinateSystemAxisNNPtr> axis = processAxisSwap(step, unit, iAxisSwap, axisType, false); auto csGeodCRS = geodCRS->coordinateSystem(); auto cs = csGeodCRS->axisList().size() == 2 ? CartesianCS::create(emptyPropertyMap, axis[0], axis[1]) : CartesianCS::create(emptyPropertyMap, axis[0], axis[1], csGeodCRS->axisList()[2]); if (isTopocentricStep(step.name)) { cs = CartesianCS::create( emptyPropertyMap, createAxis("topocentric East", "U", AxisDirection::EAST, unit), createAxis("topocentric North", "V", AxisDirection::NORTH, unit), createAxis("topocentric Up", "W", AxisDirection::UP, unit)); } auto props = PropertyMap().set(IdentifiedObject::NAME_KEY, title.empty() ? "unknown" : title); if (hasUnusedParameters(step)) { props.set("EXTENSION_PROJ4", projString_); } props.set("IMPLICIT_CS", true); CRSNNPtr crs = bWebMercator ? createPseudoMercator( props.set(IdentifiedObject::NAME_KEY, webMercatorName), cs) : ProjectedCRS::create(props, geodCRS, NN_NO_CHECK(conv), cs); return crs; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const metadata::ExtentPtr nullExtent{}; static const metadata::ExtentPtr &getExtent(const crs::CRS *crs) { const auto &domains = crs->domains(); if (!domains.empty()) { return domains[0]->domainOfValidity(); } return nullExtent; } //! @endcond namespace { struct PJContextHolder { PJ_CONTEXT *ctx_; bool bFree_; PJContextHolder(PJ_CONTEXT *ctx, bool bFree) : ctx_(ctx), bFree_(bFree) {} ~PJContextHolder() { if (bFree_) proj_context_destroy(ctx_); } PJContextHolder(const PJContextHolder &) = delete; PJContextHolder &operator=(const PJContextHolder &) = delete; }; } // namespace // --------------------------------------------------------------------------- /** \brief Instantiate a sub-class of BaseObject from a PROJ string. * * The projString must contain +type=crs for the object to be detected as a * CRS instead of a CoordinateOperation. * * @throw ParsingException */ BaseObjectNNPtr PROJStringParser::createFromPROJString(const std::string &projString) { // In some abnormal situations involving init=epsg:XXXX syntax, we could // have infinite loop if (d->ctx_ && d->ctx_->projStringParserCreateFromPROJStringRecursionCounter == 2) { throw ParsingException( "Infinite recursion in PROJStringParser::createFromPROJString()"); } d->steps_.clear(); d->title_.clear(); d->globalParamValues_.clear(); d->projString_ = projString; PROJStringSyntaxParser(projString, d->steps_, d->globalParamValues_, d->title_); if (d->steps_.empty()) { const auto &vunits = d->getGlobalParamValue("vunits"); const auto &vto_meter = d->getGlobalParamValue("vto_meter"); if (!vunits.empty() || !vto_meter.empty()) { Step fakeStep; if (!vunits.empty()) { fakeStep.paramValues.emplace_back( Step::KeyValue("vunits", vunits)); } if (!vto_meter.empty()) { fakeStep.paramValues.emplace_back( Step::KeyValue("vto_meter", vto_meter)); } auto vdatum = VerticalReferenceFrame::create(createMapWithUnknownName()); auto vcrs = VerticalCRS::create( createMapWithUnknownName(), vdatum, VerticalCS::createGravityRelatedHeight( d->buildUnit(fakeStep, "vunits", "vto_meter"))); return vcrs; } } const bool isGeocentricCRS = ((d->steps_.size() == 1 && d->getParamValue(d->steps_[0], "type") == "crs") || (d->steps_.size() == 2 && d->steps_[1].name == "unitconvert")) && !d->steps_[0].inverted && isGeocentricStep(d->steps_[0].name); const bool isTopocentricCRS = (d->steps_.size() == 1 && isTopocentricStep(d->steps_[0].name) && d->getParamValue(d->steps_[0], "type") == "crs"); // +init=xxxx:yyyy syntax if (d->steps_.size() == 1 && d->steps_[0].isInit && !d->steps_[0].inverted) { // Those used to come from a text init file // We only support them in compatibility mode const std::string &stepName = d->steps_[0].name; if (ci_starts_with(stepName, "epsg:") || ci_starts_with(stepName, "IGNF:")) { /* We create a new context so as to avoid messing up with the */ /* errorno of the main context, when trying to find the likely */ /* missing epsg file */ auto ctx = proj_context_create(); if (!ctx) { throw ParsingException("out of memory"); } PJContextHolder contextHolder(ctx, true); if (d->ctx_) { ctx->set_search_paths(d->ctx_->search_paths); ctx->file_finder = d->ctx_->file_finder; ctx->file_finder_user_data = d->ctx_->file_finder_user_data; } bool usePROJ4InitRules = d->usePROJ4InitRules_; if (!usePROJ4InitRules) { usePROJ4InitRules = proj_context_get_use_proj4_init_rules(ctx, FALSE) == TRUE; } if (!usePROJ4InitRules) { throw ParsingException("init=epsg:/init=IGNF: syntax not " "supported in non-PROJ4 emulation mode"); } char unused[256]; std::string initname(stepName); initname.resize(initname.find(':')); int file_found = pj_find_file(ctx, initname.c_str(), unused, sizeof(unused)); if (!file_found) { auto obj = createFromUserInput(stepName, d->dbContext_, true); auto crs = dynamic_cast<CRS *>(obj.get()); bool hasSignificantParamValues = false; bool hasOver = false; for (const auto &kv : d->steps_[0].paramValues) { if (kv.key == "over") { hasOver = true; } else if (!((kv.key == "type" && kv.value == "crs") || kv.key == "wktext" || kv.key == "no_defs")) { hasSignificantParamValues = true; break; } } if (crs && !hasSignificantParamValues) { PropertyMap properties; properties.set(IdentifiedObject::NAME_KEY, d->title_.empty() ? crs->nameStr() : d->title_); if (hasOver) { properties.set("OVER", true); } const auto &extent = getExtent(crs); if (extent) { properties.set( common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, NN_NO_CHECK(extent)); } auto geogCRS = dynamic_cast<GeographicCRS *>(crs); if (geogCRS) { const auto &cs = geogCRS->coordinateSystem(); // Override with longitude latitude in degrees return GeographicCRS::create( properties, geogCRS->datum(), geogCRS->datumEnsemble(), cs->axisList().size() == 2 ? EllipsoidalCS::createLongitudeLatitude( UnitOfMeasure::DEGREE) : EllipsoidalCS:: createLongitudeLatitudeEllipsoidalHeight( UnitOfMeasure::DEGREE, cs->axisList()[2]->unit())); } auto projCRS = dynamic_cast<ProjectedCRS *>(crs); if (projCRS) { // Override with easting northing order const auto conv = projCRS->derivingConversion(); if (conv->method()->getEPSGCode() != EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED) { return ProjectedCRS::create( properties, projCRS->baseCRS(), conv, CartesianCS::createEastingNorthing( projCRS->coordinateSystem() ->axisList()[0] ->unit())); } } return obj; } auto projStringExportable = dynamic_cast<IPROJStringExportable *>(crs); if (projStringExportable) { std::string expanded; if (!d->title_.empty()) { expanded = "title="; expanded += pj_double_quote_string_param_if_needed(d->title_); } for (const auto &pair : d->steps_[0].paramValues) { if (!expanded.empty()) expanded += ' '; expanded += '+'; expanded += pair.key; if (!pair.value.empty()) { expanded += '='; expanded += pj_double_quote_string_param_if_needed( pair.value); } } expanded += ' '; expanded += projStringExportable->exportToPROJString( PROJStringFormatter::create().get()); return createFromPROJString(expanded); } } } auto ctx = d->ctx_ ? d->ctx_ : proj_context_create(); if (!ctx) { throw ParsingException("out of memory"); } PJContextHolder contextHolder(ctx, ctx != d->ctx_); paralist *init = pj_mkparam(("init=" + d->steps_[0].name).c_str()); if (!init) { throw ParsingException("out of memory"); } ctx->projStringParserCreateFromPROJStringRecursionCounter++; paralist *list = pj_expand_init(ctx, init); ctx->projStringParserCreateFromPROJStringRecursionCounter--; if (!list) { free(init); throw ParsingException("cannot expand " + projString); } std::string expanded; if (!d->title_.empty()) { expanded = "title=" + pj_double_quote_string_param_if_needed(d->title_); } bool first = true; bool has_init_term = false; for (auto t = list; t;) { if (!expanded.empty()) { expanded += ' '; } if (first) { // first parameter is the init= itself first = false; } else if (starts_with(t->param, "init=")) { has_init_term = true; } else { expanded += t->param; } auto n = t->next; free(t); t = n; } for (const auto &pair : d->steps_[0].paramValues) { expanded += " +"; expanded += pair.key; if (!pair.value.empty()) { expanded += '='; expanded += pj_double_quote_string_param_if_needed(pair.value); } } if (!has_init_term) { return createFromPROJString(expanded); } } int iFirstGeogStep = -1; int iSecondGeogStep = -1; int iProjStep = -1; int iFirstUnitConvert = -1; int iSecondUnitConvert = -1; int iFirstAxisSwap = -1; int iSecondAxisSwap = -1; bool unexpectedStructure = d->steps_.empty(); for (int i = 0; i < static_cast<int>(d->steps_.size()); i++) { const auto &stepName = d->steps_[i].name; if (isGeographicStep(stepName)) { if (iFirstGeogStep < 0) { iFirstGeogStep = i; } else if (iSecondGeogStep < 0) { iSecondGeogStep = i; } else { unexpectedStructure = true; break; } } else if (ci_equal(stepName, "unitconvert")) { if (iFirstUnitConvert < 0) { iFirstUnitConvert = i; } else if (iSecondUnitConvert < 0) { iSecondUnitConvert = i; } else { unexpectedStructure = true; break; } } else if (ci_equal(stepName, "axisswap")) { if (iFirstAxisSwap < 0) { iFirstAxisSwap = i; } else if (iSecondAxisSwap < 0) { iSecondAxisSwap = i; } else { unexpectedStructure = true; break; } } else if (isProjectedStep(stepName)) { if (iProjStep >= 0) { unexpectedStructure = true; break; } iProjStep = i; } else { unexpectedStructure = true; break; } } if (!d->steps_.empty()) { // CRS candidate if ((d->steps_.size() == 1 && d->getParamValue(d->steps_[0], "type") != "crs") || (d->steps_.size() > 1 && d->getGlobalParamValue("type") != "crs")) { unexpectedStructure = true; } } struct Logger { std::string msg{}; // cppcheck-suppress functionStatic void setMessage(const char *msgIn) noexcept { try { msg = msgIn; } catch (const std::exception &) { } } static void log(void *user_data, int level, const char *msg) { if (level == PJ_LOG_ERROR) { static_cast<Logger *>(user_data)->setMessage(msg); } } }; // If the structure is not recognized, then try to instantiate the // pipeline, and if successful, wrap it in a PROJBasedOperation Logger logger; bool valid; auto pj_context = d->ctx_ ? d->ctx_ : proj_context_create(); if (!pj_context) { throw ParsingException("out of memory"); } // Backup error logger and level, and install temporary handler auto old_logger = pj_context->logger; auto old_logger_app_data = pj_context->logger_app_data; auto log_level = proj_log_level(pj_context, PJ_LOG_ERROR); proj_log_func(pj_context, &logger, Logger::log); if (pj_context != d->ctx_) { proj_context_use_proj4_init_rules(pj_context, d->usePROJ4InitRules_); } pj_context->projStringParserCreateFromPROJStringRecursionCounter++; auto pj = pj_create_internal( pj_context, (projString.find("type=crs") != std::string::npos ? projString + " +disable_grid_presence_check" : projString) .c_str()); pj_context->projStringParserCreateFromPROJStringRecursionCounter--; valid = pj != nullptr; // Restore initial error logger and level proj_log_level(pj_context, log_level); pj_context->logger = old_logger; pj_context->logger_app_data = old_logger_app_data; // Remove parameters not understood by PROJ. if (valid && d->steps_.size() == 1) { std::vector<Step::KeyValue> newParamValues{}; std::set<std::string> foundKeys; auto &step = d->steps_[0]; for (auto &kv : step.paramValues) { bool recognizedByPROJ = false; if (foundKeys.find(kv.key) != foundKeys.end()) { continue; } foundKeys.insert(kv.key); if ((step.name == "krovak" || step.name == "mod_krovak") && kv.key == "alpha") { // We recognize it in our CRS parsing code recognizedByPROJ = true; } else { for (auto cur = pj->params; cur; cur = cur->next) { const char *equal = strchr(cur->param, '='); if (equal && static_cast<size_t>(equal - cur->param) == kv.key.size()) { if (memcmp(cur->param, kv.key.c_str(), kv.key.size()) == 0) { recognizedByPROJ = (cur->used == 1); break; } } else if (strcmp(cur->param, kv.key.c_str()) == 0) { recognizedByPROJ = (cur->used == 1); break; } } } if (!recognizedByPROJ && kv.key == "geoid_crs") { for (auto &pair : step.paramValues) { if (ci_equal(pair.key, "geoidgrids")) { recognizedByPROJ = true; break; } } } if (recognizedByPROJ) { newParamValues.emplace_back(kv); } } step.paramValues = std::move(newParamValues); d->projString_.clear(); if (!step.name.empty()) { d->projString_ += step.isInit ? "+init=" : "+proj="; d->projString_ += step.name; } for (const auto &paramValue : step.paramValues) { if (!d->projString_.empty()) { d->projString_ += ' '; } d->projString_ += '+'; d->projString_ += paramValue.key; if (!paramValue.value.empty()) { d->projString_ += '='; d->projString_ += pj_double_quote_string_param_if_needed(paramValue.value); } } } proj_destroy(pj); if (!valid) { const int l_errno = proj_context_errno(pj_context); std::string msg("Error " + toString(l_errno) + " (" + proj_errno_string(l_errno) + ")"); if (!logger.msg.empty()) { msg += ": "; msg += logger.msg; } logger.msg = std::move(msg); } if (pj_context != d->ctx_) { proj_context_destroy(pj_context); } if (!valid) { throw ParsingException(logger.msg); } if (isGeocentricCRS) { // First run is dry run to mark all recognized/unrecognized tokens for (int iter = 0; iter < 2; iter++) { auto obj = d->buildBoundOrCompoundCRSIfNeeded( 0, d->buildGeocentricCRS(0, (d->steps_.size() == 2 && d->steps_[1].name == "unitconvert") ? 1 : -1)); if (iter == 1) { return nn_static_pointer_cast<BaseObject>(obj); } } } if (isTopocentricCRS) { // First run is dry run to mark all recognized/unrecognized tokens for (int iter = 0; iter < 2; iter++) { auto obj = d->buildBoundOrCompoundCRSIfNeeded( 0, d->buildProjectedCRS(0, d->buildGeocentricCRS(0, -1), -1, -1)); if (iter == 1) { return nn_static_pointer_cast<BaseObject>(obj); } } } if (!unexpectedStructure) { if (iFirstGeogStep == 0 && !d->steps_[iFirstGeogStep].inverted && iSecondGeogStep < 0 && iProjStep < 0 && (iFirstUnitConvert < 0 || iSecondUnitConvert < 0) && (iFirstAxisSwap < 0 || iSecondAxisSwap < 0)) { // First run is dry run to mark all recognized/unrecognized tokens for (int iter = 0; iter < 2; iter++) { auto obj = d->buildBoundOrCompoundCRSIfNeeded( 0, d->buildGeodeticCRS(iFirstGeogStep, iFirstUnitConvert, iFirstAxisSwap, false)); if (iter == 1) { return nn_static_pointer_cast<BaseObject>(obj); } } } if (iProjStep >= 0 && !d->steps_[iProjStep].inverted && (iFirstGeogStep < 0 || iFirstGeogStep + 1 == iProjStep) && iSecondGeogStep < 0) { if (iFirstGeogStep < 0) iFirstGeogStep = iProjStep; // First run is dry run to mark all recognized/unrecognized tokens for (int iter = 0; iter < 2; iter++) { auto obj = d->buildBoundOrCompoundCRSIfNeeded( iProjStep, d->buildProjectedCRS( iProjStep, d->buildGeodeticCRS(iFirstGeogStep, iFirstUnitConvert < iFirstGeogStep ? iFirstUnitConvert : -1, iFirstAxisSwap < iFirstGeogStep ? iFirstAxisSwap : -1, true), iFirstUnitConvert < iFirstGeogStep ? iSecondUnitConvert : iFirstUnitConvert, iFirstAxisSwap < iFirstGeogStep ? iSecondAxisSwap : iFirstAxisSwap)); if (iter == 1) { return nn_static_pointer_cast<BaseObject>(obj); } } } } auto props = PropertyMap(); if (!d->title_.empty()) { props.set(IdentifiedObject::NAME_KEY, d->title_); } return operation::SingleOperation::createPROJBased(props, projString, nullptr, nullptr, {}); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct JSONFormatter::Private { CPLJSonStreamingWriter writer_{nullptr, nullptr}; DatabaseContextPtr dbContext_{}; std::vector<bool> stackHasId_{false}; std::vector<bool> outputIdStack_{true}; bool allowIDInImmediateChild_ = false; bool omitTypeInImmediateChild_ = false; bool abridgedTransformation_ = false; bool abridgedTransformationWriteSourceCRS_ = false; std::string schema_ = PROJJSON_DEFAULT_VERSION; // cppcheck-suppress functionStatic void pushOutputId(bool outputIdIn) { outputIdStack_.push_back(outputIdIn); } // cppcheck-suppress functionStatic void popOutputId() { outputIdStack_.pop_back(); } }; //! @endcond // --------------------------------------------------------------------------- /** \brief Constructs a new formatter. * * A formatter can be used only once (its internal state is mutated) * * @return new formatter. */ JSONFormatterNNPtr JSONFormatter::create( // cppcheck-suppress passedByValue DatabaseContextPtr dbContext) { auto ret = NN_NO_CHECK(JSONFormatter::make_unique<JSONFormatter>()); ret->d->dbContext_ = std::move(dbContext); return ret; } // --------------------------------------------------------------------------- /** \brief Whether to use multi line output or not. */ JSONFormatter &JSONFormatter::setMultiLine(bool multiLine) noexcept { d->writer_.SetPrettyFormatting(multiLine); return *this; } // --------------------------------------------------------------------------- /** \brief Set number of spaces for each indentation level (defaults to 4). */ JSONFormatter &JSONFormatter::setIndentationWidth(int width) noexcept { d->writer_.SetIndentationSize(width); return *this; } // --------------------------------------------------------------------------- /** \brief Set the value of the "$schema" key in the top level object. * * If set to empty string, it will not be written. */ JSONFormatter &JSONFormatter::setSchema(const std::string &schema) noexcept { d->schema_ = schema; return *this; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress JSONFormatter::JSONFormatter() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- JSONFormatter::~JSONFormatter() = default; // --------------------------------------------------------------------------- CPLJSonStreamingWriter *JSONFormatter::writer() const { return &(d->writer_); } // --------------------------------------------------------------------------- const DatabaseContextPtr &JSONFormatter::databaseContext() const { return d->dbContext_; } // --------------------------------------------------------------------------- bool JSONFormatter::outputId() const { return d->outputIdStack_.back(); } // --------------------------------------------------------------------------- bool JSONFormatter::outputUsage(bool calledBeforeObjectContext) const { return outputId() && d->outputIdStack_.size() == (calledBeforeObjectContext ? 1U : 2U); } // --------------------------------------------------------------------------- void JSONFormatter::setAllowIDInImmediateChild() { d->allowIDInImmediateChild_ = true; } // --------------------------------------------------------------------------- void JSONFormatter::setOmitTypeInImmediateChild() { d->omitTypeInImmediateChild_ = true; } // --------------------------------------------------------------------------- JSONFormatter::ObjectContext::ObjectContext(JSONFormatter &formatter, const char *objectType, bool hasId) : m_formatter(formatter) { m_formatter.d->writer_.StartObj(); if (m_formatter.d->outputIdStack_.size() == 1 && !m_formatter.d->schema_.empty()) { m_formatter.d->writer_.AddObjKey("$schema"); m_formatter.d->writer_.Add(m_formatter.d->schema_); } if (objectType && !m_formatter.d->omitTypeInImmediateChild_) { m_formatter.d->writer_.AddObjKey("type"); m_formatter.d->writer_.Add(objectType); } m_formatter.d->omitTypeInImmediateChild_ = false; // All intermediate nodes shouldn't have ID if a parent has an ID // unless explicitly enabled. if (m_formatter.d->allowIDInImmediateChild_) { m_formatter.d->pushOutputId(m_formatter.d->outputIdStack_[0]); m_formatter.d->allowIDInImmediateChild_ = false; } else { m_formatter.d->pushOutputId(m_formatter.d->outputIdStack_[0] && !m_formatter.d->stackHasId_.back()); } m_formatter.d->stackHasId_.push_back(hasId || m_formatter.d->stackHasId_.back()); } // --------------------------------------------------------------------------- JSONFormatter::ObjectContext::~ObjectContext() { m_formatter.d->writer_.EndObj(); m_formatter.d->stackHasId_.pop_back(); m_formatter.d->popOutputId(); } // --------------------------------------------------------------------------- void JSONFormatter::setAbridgedTransformation(bool outputIn) { d->abridgedTransformation_ = outputIn; } // --------------------------------------------------------------------------- bool JSONFormatter::abridgedTransformation() const { return d->abridgedTransformation_; } // --------------------------------------------------------------------------- void JSONFormatter::setAbridgedTransformationWriteSourceCRS(bool writeCRS) { d->abridgedTransformationWriteSourceCRS_ = writeCRS; } // --------------------------------------------------------------------------- bool JSONFormatter::abridgedTransformationWriteSourceCRS() const { return d->abridgedTransformationWriteSourceCRS_; } //! @endcond // --------------------------------------------------------------------------- /** \brief Return the serialized JSON. */ const std::string &JSONFormatter::toString() const { return d->writer_.GetString(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress IJSONExportable::~IJSONExportable() = default; // --------------------------------------------------------------------------- std::string IJSONExportable::exportToJSON(JSONFormatter *formatter) const { _exportToJSON(formatter); return formatter->toString(); } //! @endcond } // namespace io NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/c_api.cpp
/****************************************************************************** * * Project: PROJ * Purpose: C API wrapper of C++ API * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include <algorithm> #include <cassert> #include <cstdarg> #include <cstring> #include <limits> #include <map> #include <memory> #include <new> #include <utility> #include <vector> #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinates.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/datum_internal.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" #include "proj_experimental.h" // clang-format on #include "geodesic.h" #include "proj_constants.h" using namespace NS_PROJ::common; using namespace NS_PROJ::coordinates; using namespace NS_PROJ::crs; using namespace NS_PROJ::cs; using namespace NS_PROJ::datum; using namespace NS_PROJ::io; using namespace NS_PROJ::internal; using namespace NS_PROJ::metadata; using namespace NS_PROJ::operation; using namespace NS_PROJ::util; using namespace NS_PROJ; // --------------------------------------------------------------------------- static void PROJ_NO_INLINE proj_log_error(PJ_CONTEXT *ctx, const char *function, const char *text) { if (ctx->debug_level != PJ_LOG_NONE) { std::string msg(function); msg += ": "; msg += text; ctx->logger(ctx->logger_app_data, PJ_LOG_ERROR, msg.c_str()); } auto previous_errno = proj_context_errno(ctx); if (previous_errno == 0) { // only set errno if it wasn't set deeper down the call stack proj_context_errno_set(ctx, PROJ_ERR_OTHER); } } // --------------------------------------------------------------------------- static void PROJ_NO_INLINE proj_log_debug(PJ_CONTEXT *ctx, const char *function, const char *text) { std::string msg(function); msg += ": "; msg += text; ctx->logger(ctx->logger_app_data, PJ_LOG_DEBUG, msg.c_str()); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- template <class T> static PROJ_STRING_LIST to_string_list(T &&set) { auto ret = new char *[set.size() + 1]; size_t i = 0; for (const auto &str : set) { try { ret[i] = new char[str.size() + 1]; } catch (const std::exception &) { while (--i > 0) { delete[] ret[i]; } delete[] ret; throw; } std::memcpy(ret[i], str.c_str(), str.size() + 1); i++; } ret[i] = nullptr; return ret; } // --------------------------------------------------------------------------- void proj_context_delete_cpp_context(struct projCppContext *cppContext) { delete cppContext; } // --------------------------------------------------------------------------- projCppContext::projCppContext(PJ_CONTEXT *ctx, const char *dbPath, const std::vector<std::string> &auxDbPaths) : ctx_(ctx), dbPath_(dbPath ? dbPath : std::string()), auxDbPaths_(auxDbPaths) {} // --------------------------------------------------------------------------- std::vector<std::string> projCppContext::toVector(const char *const *auxDbPaths) { std::vector<std::string> res; for (auto iter = auxDbPaths; iter && *iter; ++iter) { res.emplace_back(std::string(*iter)); } return res; } // --------------------------------------------------------------------------- projCppContext *projCppContext::clone(PJ_CONTEXT *ctx) const { projCppContext *newContext = new projCppContext(ctx, getDbPath().c_str(), getAuxDbPaths()); return newContext; } // --------------------------------------------------------------------------- NS_PROJ::io::DatabaseContextNNPtr projCppContext::getDatabaseContext() { if (databaseContext_) { return NN_NO_CHECK(databaseContext_); } auto dbContext = NS_PROJ::io::DatabaseContext::create(dbPath_, auxDbPaths_, ctx_); databaseContext_ = dbContext; return dbContext; } // --------------------------------------------------------------------------- static PROJ_NO_INLINE DatabaseContextNNPtr getDBcontext(PJ_CONTEXT *ctx) { return ctx->get_cpp_context()->getDatabaseContext(); } // --------------------------------------------------------------------------- static PROJ_NO_INLINE DatabaseContextPtr getDBcontextNoException(PJ_CONTEXT *ctx, const char *function) { try { return getDBcontext(ctx).as_nullable(); } catch (const std::exception &e) { proj_log_debug(ctx, function, e.what()); return nullptr; } } // --------------------------------------------------------------------------- PJ *pj_obj_create(PJ_CONTEXT *ctx, const BaseObjectNNPtr &objIn) { auto coordop = dynamic_cast<const CoordinateOperation *>(objIn.get()); if (coordop) { auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { auto formatter = PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, std::move(dbContext)); auto projString = coordop->exportToPROJString(formatter.get()); if (proj_context_is_network_enabled(ctx)) { ctx->defer_grid_opening = true; } auto pj = pj_create_internal(ctx, projString.c_str()); ctx->defer_grid_opening = false; if (pj) { pj->iso_obj = objIn; pj->iso_obj_is_coordinate_operation = true; auto sourceEpoch = coordop->sourceCoordinateEpoch(); auto targetEpoch = coordop->targetCoordinateEpoch(); if (sourceEpoch.has_value()) { if (!targetEpoch.has_value()) { pj->hasCoordinateEpoch = true; pj->coordinateEpoch = sourceEpoch->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR); } } else { if (targetEpoch.has_value()) { pj->hasCoordinateEpoch = true; pj->coordinateEpoch = targetEpoch->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR); } } return pj; } } catch (const std::exception &) { // Silence, since we may not always be able to export as a // PROJ string. } } auto pj = pj_new(); if (pj) { pj->ctx = ctx; pj->descr = "ISO-19111 object"; pj->iso_obj = objIn; pj->iso_obj_is_coordinate_operation = coordop != nullptr; try { auto crs = dynamic_cast<const CRS *>(objIn.get()); if (crs) { auto geodCRS = crs->extractGeodeticCRS(); if (geodCRS) { const auto &ellps = geodCRS->ellipsoid(); const double a = ellps->semiMajorAxis().getSIValue(); const double es = ellps->squaredEccentricity(); if (!(a > 0 && es >= 0 && es < 1)) { proj_log_error(pj, _("Invalid ellipsoid parameters")); proj_errno_set(pj, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); proj_destroy(pj); return nullptr; } pj_calc_ellipsoid_params(pj, a, es); assert(pj->geod == nullptr); pj->geod = static_cast<struct geod_geodesic *>( calloc(1, sizeof(struct geod_geodesic))); if (pj->geod) { geod_init(pj->geod, pj->a, pj->es / (1 + sqrt(pj->one_es))); } } } } catch (const std::exception &) { } } return pj; } //! @endcond // --------------------------------------------------------------------------- /** \brief Opaque object representing a set of operation results. */ struct PJ_OBJ_LIST { //! @cond Doxygen_Suppress std::vector<IdentifiedObjectNNPtr> objects; explicit PJ_OBJ_LIST(std::vector<IdentifiedObjectNNPtr> &&objectsIn) : objects(std::move(objectsIn)) {} virtual ~PJ_OBJ_LIST(); PJ_OBJ_LIST(const PJ_OBJ_LIST &) = delete; PJ_OBJ_LIST &operator=(const PJ_OBJ_LIST &) = delete; //! @endcond }; //! @cond Doxygen_Suppress PJ_OBJ_LIST::~PJ_OBJ_LIST() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress #define SANITIZE_CTX(ctx) \ do { \ if (ctx == nullptr) { \ ctx = pj_get_default_ctx(); \ } \ } while (0) //! @endcond // --------------------------------------------------------------------------- /** \brief Starting with PROJ 8.1, this function does nothing. * * If you want to take into account changes to the PROJ database, you need to * re-create a new context. * * @param ctx Ignored * @param autoclose Ignored * @since 6.2 * deprecated Since 8.1 */ void proj_context_set_autoclose_database(PJ_CONTEXT *ctx, int autoclose) { (void)ctx; (void)autoclose; } // --------------------------------------------------------------------------- /** \brief Explicitly point to the main PROJ CRS and coordinate operation * definition database ("proj.db"), and potentially auxiliary databases with * same structure. * * Starting with PROJ 8.1, if the auxDbPaths parameter is an empty array, * the PROJ_AUX_DB environment variable will be used, if set. * It must contain one or several paths. If several paths are * provided, they must be separated by the colon (:) character on Unix, and * on Windows, by the semi-colon (;) character. * * @param ctx PROJ context, or NULL for default context * @param dbPath Path to main database, or NULL for default. * @param auxDbPaths NULL-terminated list of auxiliary database filenames, or * NULL. * @param options should be set to NULL for now * @return TRUE in case of success */ int proj_context_set_database_path(PJ_CONTEXT *ctx, const char *dbPath, const char *const *auxDbPaths, const char *const *options) { SANITIZE_CTX(ctx); (void)options; std::string osPrevDbPath; std::vector<std::string> osPrevAuxDbPaths; if (ctx->cpp_context) { osPrevDbPath = ctx->cpp_context->getDbPath(); osPrevAuxDbPaths = ctx->cpp_context->getAuxDbPaths(); } delete ctx->cpp_context; ctx->cpp_context = nullptr; try { ctx->cpp_context = new projCppContext( ctx, dbPath, projCppContext::toVector(auxDbPaths)); ctx->cpp_context->getDatabaseContext(); return true; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); delete ctx->cpp_context; ctx->cpp_context = new projCppContext(ctx, osPrevDbPath.c_str(), osPrevAuxDbPaths); return false; } } // --------------------------------------------------------------------------- /** \brief Returns the path to the database. * * The returned pointer remains valid while ctx is valid, and until * proj_context_set_database_path() is called. * * @param ctx PROJ context, or NULL for default context * @return path, or nullptr */ const char *proj_context_get_database_path(PJ_CONTEXT *ctx) { SANITIZE_CTX(ctx); try { // temporary variable must be used as getDBcontext() might create // ctx->cpp_context const std::string osPath(getDBcontext(ctx)->getPath()); ctx->get_cpp_context()->lastDbPath_ = osPath; return ctx->cpp_context->lastDbPath_.c_str(); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Return a metadata from the database. * * The returned pointer remains valid while ctx is valid, and until * proj_context_get_database_metadata() is called. * * Available keys: * * - DATABASE.LAYOUT.VERSION.MAJOR * - DATABASE.LAYOUT.VERSION.MINOR * - EPSG.VERSION * - EPSG.DATE * - ESRI.VERSION * - ESRI.DATE * - IGNF.SOURCE * - IGNF.VERSION * - IGNF.DATE * - NKG.SOURCE * - NKG.VERSION * - NKG.DATE * - PROJ.VERSION * - PROJ_DATA.VERSION : PROJ-data version most compatible with this database. * * * @param ctx PROJ context, or NULL for default context * @param key Metadata key. Must not be NULL * @return value, or nullptr */ const char *proj_context_get_database_metadata(PJ_CONTEXT *ctx, const char *key) { SANITIZE_CTX(ctx); if (!key) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } try { // temporary variable must be used as getDBcontext() might create // ctx->cpp_context auto osVal(getDBcontext(ctx)->getMetadata(key)); if (osVal == nullptr) { return nullptr; } ctx->get_cpp_context()->lastDbMetadataItem_ = osVal; return ctx->cpp_context->lastDbMetadataItem_.c_str(); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Return the database structure * * Return SQL statements to run to initiate a new valid auxiliary empty * database. It contains definitions of tables, views and triggers, as well * as metadata for the version of the layout of the database. * * @param ctx PROJ context, or NULL for default context * @param options null-terminated list of options, or NULL. None currently. * @return list of SQL statements (to be freed with proj_string_list_destroy()), * or NULL in case of error. * @since 8.1 */ PROJ_STRING_LIST proj_context_get_database_structure(PJ_CONTEXT *ctx, const char *const *options) { SANITIZE_CTX(ctx); (void)options; try { auto ret = to_string_list(getDBcontext(ctx)->getDatabaseStructure()); return ret; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Guess the "dialect" of the WKT string. * * @param ctx PROJ context, or NULL for default context * @param wkt String (must not be NULL) */ PJ_GUESSED_WKT_DIALECT proj_context_guess_wkt_dialect(PJ_CONTEXT *ctx, const char *wkt) { (void)ctx; if (!wkt) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return PJ_GUESSED_NOT_WKT; } switch (WKTParser().guessDialect(wkt)) { case WKTParser::WKTGuessedDialect::WKT2_2019: return PJ_GUESSED_WKT2_2019; case WKTParser::WKTGuessedDialect::WKT2_2015: return PJ_GUESSED_WKT2_2015; case WKTParser::WKTGuessedDialect::WKT1_GDAL: return PJ_GUESSED_WKT1_GDAL; case WKTParser::WKTGuessedDialect::WKT1_ESRI: return PJ_GUESSED_WKT1_ESRI; case WKTParser::WKTGuessedDialect::NOT_WKT: break; } return PJ_GUESSED_NOT_WKT; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const char *getOptionValue(const char *option, const char *keyWithEqual) noexcept { if (ci_starts_with(option, keyWithEqual)) { return option + strlen(keyWithEqual); } return nullptr; } //! @endcond // --------------------------------------------------------------------------- /** \brief "Clone" an object. * * The object might be used independently of the original object, provided that * the use of context is compatible. In particular if you intend to use a * clone in a different thread than the original object, you should pass a * context that is different from the one of the original object (or later * assign a different context with proj_assign_context()). * * The returned object must be unreferenced with proj_destroy() after use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object to clone. Must not be NULL. * @return Object that must be unreferenced with proj_destroy(), or NULL in * case of error. */ PJ *proj_clone(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } if (!obj->iso_obj) { if (!obj->alternativeCoordinateOperations.empty()) { auto newPj = pj_new(); if (newPj) { newPj->descr = "Set of coordinate operations"; newPj->ctx = ctx; const int old_debug_level = ctx->debug_level; ctx->debug_level = PJ_LOG_NONE; for (const auto &altOp : obj->alternativeCoordinateOperations) { newPj->alternativeCoordinateOperations.emplace_back( PJCoordOperation(ctx, altOp)); } ctx->debug_level = old_debug_level; } return newPj; } return nullptr; } try { return pj_obj_create(ctx, NN_NO_CHECK(obj->iso_obj)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate an object from a WKT string, PROJ string, object code * (like "EPSG:4326", "urn:ogc:def:crs:EPSG::4326", * "urn:ogc:def:coordinateOperation:EPSG::1671"), a PROJJSON string, an object * name (e.g "WGS 84") of a compound CRS build from object names * (e.g "WGS 84 + EGM96 height") * * This function calls osgeo::proj::io::createFromUserInput() * * The returned object must be unreferenced with proj_destroy() after use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param text String (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL in * case of error. */ PJ *proj_create(PJ_CONTEXT *ctx, const char *text) { SANITIZE_CTX(ctx); if (!text) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } // Only connect to proj.db if needed if (strstr(text, "proj=") == nullptr || strstr(text, "init=") != nullptr) { getDBcontextNoException(ctx, __FUNCTION__); } try { auto obj = nn_dynamic_pointer_cast<BaseObject>(createFromUserInput(text, ctx)); if (obj) { return pj_obj_create(ctx, NN_NO_CHECK(obj)); } } catch (const io::ParsingException &e) { if (proj_context_errno(ctx) == 0) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); } proj_log_error(ctx, __FUNCTION__, e.what()); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate an object from a WKT string. * * This function calls osgeo::proj::io::WKTParser::createFromWKT() * * The returned object must be unreferenced with proj_destroy() after use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param wkt WKT string (must not be NULL) * @param options null-terminated list of options, or NULL. Currently * supported options are: * <ul> * <li>STRICT=YES/NO. Defaults to NO. When set to YES, strict validation will * be enabled.</li> * <li>UNSET_IDENTIFIERS_IF_INCOMPATIBLE_DEF=YES/NO. Defaults to YES. * When set to YES, object identifiers are unset when there is * a contradiction between the definition from WKT and the one from * the database./<li> * </ul> * @param out_warnings Pointer to a PROJ_STRING_LIST object, or NULL. * If provided, *out_warnings will contain a list of warnings, typically for * non recognized projection method or parameters. It must be freed with * proj_string_list_destroy(). * @param out_grammar_errors Pointer to a PROJ_STRING_LIST object, or NULL. * If provided, *out_grammar_errors will contain a list of errors regarding the * WKT grammar. It must be freed with proj_string_list_destroy(). * @return Object that must be unreferenced with proj_destroy(), or NULL in * case of error. */ PJ *proj_create_from_wkt(PJ_CONTEXT *ctx, const char *wkt, const char *const *options, PROJ_STRING_LIST *out_warnings, PROJ_STRING_LIST *out_grammar_errors) { SANITIZE_CTX(ctx); if (!wkt) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } if (out_warnings) { *out_warnings = nullptr; } if (out_grammar_errors) { *out_grammar_errors = nullptr; } try { WKTParser parser; auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); if (dbContext) { parser.attachDatabaseContext(NN_NO_CHECK(dbContext)); } parser.setStrict(false); for (auto iter = options; iter && iter[0]; ++iter) { const char *value; if ((value = getOptionValue(*iter, "STRICT="))) { parser.setStrict(ci_equal(value, "YES")); } else if ((value = getOptionValue( *iter, "UNSET_IDENTIFIERS_IF_INCOMPATIBLE_DEF="))) { parser.setUnsetIdentifiersIfIncompatibleDef( ci_equal(value, "YES")); } else { std::string msg("Unknown option :"); msg += *iter; proj_log_error(ctx, __FUNCTION__, msg.c_str()); return nullptr; } } auto obj = parser.createFromWKT(wkt); std::vector<std::string> warningsFromParsing; if (out_grammar_errors) { auto rawWarnings = parser.warningList(); std::vector<std::string> grammarWarnings; for (const auto &msg : rawWarnings) { if (msg.find("Default it to") != std::string::npos) { warningsFromParsing.push_back(msg); } else { grammarWarnings.push_back(msg); } } if (!grammarWarnings.empty()) { *out_grammar_errors = to_string_list(grammarWarnings); } } if (out_warnings) { auto derivedCRS = dynamic_cast<const crs::DerivedCRS *>(obj.get()); if (derivedCRS) { auto warnings = derivedCRS->derivingConversionRef()->validateParameters(); warnings.insert(warnings.end(), warningsFromParsing.begin(), warningsFromParsing.end()); if (!warnings.empty()) { *out_warnings = to_string_list(warnings); } } else { auto singleOp = dynamic_cast<const operation::SingleOperation *>(obj.get()); if (singleOp) { auto warnings = singleOp->validateParameters(); if (!warnings.empty()) { *out_warnings = to_string_list(warnings); } } } } return pj_obj_create(ctx, NN_NO_CHECK(obj)); } catch (const std::exception &e) { if (out_grammar_errors) { std::list<std::string> exc{e.what()}; try { *out_grammar_errors = to_string_list(exc); } catch (const std::exception &) { proj_log_error(ctx, __FUNCTION__, e.what()); } } else { proj_log_error(ctx, __FUNCTION__, e.what()); } } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate an object from a database lookup. * * The returned object must be unreferenced with proj_destroy() after use. * It should be used by at most one thread at a time. * * @param ctx Context, or NULL for default context. * @param auth_name Authority name (must not be NULL) * @param code Object code (must not be NULL) * @param category Object category * @param usePROJAlternativeGridNames Whether PROJ alternative grid names * should be substituted to the official grid names. Only used on * transformations * @param options should be set to NULL for now * @return Object that must be unreferenced with proj_destroy(), or NULL in * case of error. */ PJ *proj_create_from_database(PJ_CONTEXT *ctx, const char *auth_name, const char *code, PJ_CATEGORY category, int usePROJAlternativeGridNames, const char *const *options) { SANITIZE_CTX(ctx); if (!auth_name || !code) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } (void)options; try { const std::string codeStr(code); auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name); IdentifiedObjectPtr obj; switch (category) { case PJ_CATEGORY_ELLIPSOID: obj = factory->createEllipsoid(codeStr).as_nullable(); break; case PJ_CATEGORY_PRIME_MERIDIAN: obj = factory->createPrimeMeridian(codeStr).as_nullable(); break; case PJ_CATEGORY_DATUM: obj = factory->createDatum(codeStr).as_nullable(); break; case PJ_CATEGORY_CRS: obj = factory->createCoordinateReferenceSystem(codeStr).as_nullable(); break; case PJ_CATEGORY_COORDINATE_OPERATION: obj = factory ->createCoordinateOperation( codeStr, usePROJAlternativeGridNames != 0) .as_nullable(); break; case PJ_CATEGORY_DATUM_ENSEMBLE: obj = factory->createDatumEnsemble(codeStr).as_nullable(); break; } return pj_obj_create(ctx, NN_NO_CHECK(obj)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const char *get_unit_category(const std::string &unit_name, UnitOfMeasure::Type type) { const char *ret = nullptr; switch (type) { case UnitOfMeasure::Type::UNKNOWN: ret = "unknown"; break; case UnitOfMeasure::Type::NONE: ret = "none"; break; case UnitOfMeasure::Type::ANGULAR: ret = unit_name.find(" per ") != std::string::npos ? "angular_per_time" : "angular"; break; case UnitOfMeasure::Type::LINEAR: ret = unit_name.find(" per ") != std::string::npos ? "linear_per_time" : "linear"; break; case UnitOfMeasure::Type::SCALE: ret = unit_name.find(" per year") != std::string::npos || unit_name.find(" per second") != std::string::npos ? "scale_per_time" : "scale"; break; case UnitOfMeasure::Type::TIME: ret = "time"; break; case UnitOfMeasure::Type::PARAMETRIC: ret = unit_name.find(" per ") != std::string::npos ? "parametric_per_time" : "parametric"; break; } return ret; } //! @endcond // --------------------------------------------------------------------------- /** \brief Get information for a unit of measure from a database lookup. * * @param ctx Context, or NULL for default context. * @param auth_name Authority name (must not be NULL) * @param code Unit of measure code (must not be NULL) * @param out_name Pointer to a string value to store the parameter name. or * NULL. This value remains valid until the next call to * proj_uom_get_info_from_database() or the context destruction. * @param out_conv_factor Pointer to a value to store the conversion * factor of the prime meridian longitude unit to radian. or NULL * @param out_category Pointer to a string value to store the parameter name. or * NULL. This value might be "unknown", "none", "linear", "linear_per_time", * "angular", "angular_per_time", "scale", "scale_per_time", "time", * "parametric" or "parametric_per_time" * @return TRUE in case of success */ int proj_uom_get_info_from_database(PJ_CONTEXT *ctx, const char *auth_name, const char *code, const char **out_name, double *out_conv_factor, const char **out_category) { SANITIZE_CTX(ctx); if (!auth_name || !code) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } try { auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name); auto obj = factory->createUnitOfMeasure(code); if (out_name) { ctx->get_cpp_context()->lastUOMName_ = obj->name(); *out_name = ctx->cpp_context->lastUOMName_.c_str(); } if (out_conv_factor) { *out_conv_factor = obj->conversionToSI(); } if (out_category) { *out_category = get_unit_category(obj->name(), obj->type()); } return true; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return false; } // --------------------------------------------------------------------------- /** \brief Get information for a grid from a database lookup. * * @param ctx Context, or NULL for default context. * @param grid_name Grid name (must not be NULL) * @param out_full_name Pointer to a string value to store the grid full * filename. or NULL * @param out_package_name Pointer to a string value to store the package name * where * the grid might be found. or NULL * @param out_url Pointer to a string value to store the grid URL or the * package URL where the grid might be found. or NULL * @param out_direct_download Pointer to a int (boolean) value to store whether * *out_url can be downloaded directly. or NULL * @param out_open_license Pointer to a int (boolean) value to store whether * the grid is released with an open license. or NULL * @param out_available Pointer to a int (boolean) value to store whether the * grid is available at runtime. or NULL * @return TRUE in case of success. */ int proj_grid_get_info_from_database( PJ_CONTEXT *ctx, const char *grid_name, const char **out_full_name, const char **out_package_name, const char **out_url, int *out_direct_download, int *out_open_license, int *out_available) { SANITIZE_CTX(ctx); if (!grid_name) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } try { auto db_context = getDBcontext(ctx); bool direct_download; bool open_license; bool available; if (!db_context->lookForGridInfo( grid_name, false, ctx->get_cpp_context()->lastGridFullName_, ctx->get_cpp_context()->lastGridPackageName_, ctx->get_cpp_context()->lastGridUrl_, direct_download, open_license, available)) { return false; } if (out_full_name) *out_full_name = ctx->get_cpp_context()->lastGridFullName_.c_str(); if (out_package_name) *out_package_name = ctx->get_cpp_context()->lastGridPackageName_.c_str(); if (out_url) *out_url = ctx->get_cpp_context()->lastGridUrl_.c_str(); if (out_direct_download) *out_direct_download = direct_download ? 1 : 0; if (out_open_license) *out_open_license = open_license ? 1 : 0; if (out_available) *out_available = available ? 1 : 0; return true; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return false; } // --------------------------------------------------------------------------- /** \brief Return GeodeticCRS that use the specified datum. * * @param ctx Context, or NULL for default context. * @param crs_auth_name CRS authority name, or NULL. * @param datum_auth_name Datum authority name (must not be NULL) * @param datum_code Datum code (must not be NULL) * @param crs_type "geographic 2D", "geographic 3D", "geocentric" or NULL * @return a result set that must be unreferenced with * proj_list_destroy(), or NULL in case of error. */ PJ_OBJ_LIST *proj_query_geodetic_crs_from_datum(PJ_CONTEXT *ctx, const char *crs_auth_name, const char *datum_auth_name, const char *datum_code, const char *crs_type) { SANITIZE_CTX(ctx); if (!datum_auth_name || !datum_code) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } try { auto factory = AuthorityFactory::create( getDBcontext(ctx), crs_auth_name ? crs_auth_name : ""); auto res = factory->createGeodeticCRSFromDatum( datum_auth_name, datum_code, crs_type ? crs_type : ""); std::vector<IdentifiedObjectNNPtr> objects; for (const auto &obj : res) { objects.push_back(obj); } return new PJ_OBJ_LIST(std::move(objects)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static AuthorityFactory::ObjectType convertPJObjectTypeToObjectType(PJ_TYPE type, bool &valid) { valid = true; AuthorityFactory::ObjectType cppType = AuthorityFactory::ObjectType::CRS; switch (type) { case PJ_TYPE_ELLIPSOID: cppType = AuthorityFactory::ObjectType::ELLIPSOID; break; case PJ_TYPE_PRIME_MERIDIAN: cppType = AuthorityFactory::ObjectType::PRIME_MERIDIAN; break; case PJ_TYPE_GEODETIC_REFERENCE_FRAME: cppType = AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME; break; case PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME: cppType = AuthorityFactory::ObjectType::DYNAMIC_GEODETIC_REFERENCE_FRAME; break; case PJ_TYPE_VERTICAL_REFERENCE_FRAME: cppType = AuthorityFactory::ObjectType::VERTICAL_REFERENCE_FRAME; break; case PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME: cppType = AuthorityFactory::ObjectType::DYNAMIC_VERTICAL_REFERENCE_FRAME; break; case PJ_TYPE_DATUM_ENSEMBLE: cppType = AuthorityFactory::ObjectType::DATUM_ENSEMBLE; break; case PJ_TYPE_TEMPORAL_DATUM: valid = false; break; case PJ_TYPE_ENGINEERING_DATUM: valid = false; break; case PJ_TYPE_PARAMETRIC_DATUM: valid = false; break; case PJ_TYPE_CRS: cppType = AuthorityFactory::ObjectType::CRS; break; case PJ_TYPE_GEODETIC_CRS: cppType = AuthorityFactory::ObjectType::GEODETIC_CRS; break; case PJ_TYPE_GEOCENTRIC_CRS: cppType = AuthorityFactory::ObjectType::GEOCENTRIC_CRS; break; case PJ_TYPE_GEOGRAPHIC_CRS: cppType = AuthorityFactory::ObjectType::GEOGRAPHIC_CRS; break; case PJ_TYPE_GEOGRAPHIC_2D_CRS: cppType = AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS; break; case PJ_TYPE_GEOGRAPHIC_3D_CRS: cppType = AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS; break; case PJ_TYPE_VERTICAL_CRS: cppType = AuthorityFactory::ObjectType::VERTICAL_CRS; break; case PJ_TYPE_PROJECTED_CRS: cppType = AuthorityFactory::ObjectType::PROJECTED_CRS; break; case PJ_TYPE_DERIVED_PROJECTED_CRS: valid = false; break; case PJ_TYPE_COMPOUND_CRS: cppType = AuthorityFactory::ObjectType::COMPOUND_CRS; break; case PJ_TYPE_ENGINEERING_CRS: valid = false; break; case PJ_TYPE_TEMPORAL_CRS: valid = false; break; case PJ_TYPE_BOUND_CRS: valid = false; break; case PJ_TYPE_OTHER_CRS: cppType = AuthorityFactory::ObjectType::CRS; break; case PJ_TYPE_CONVERSION: cppType = AuthorityFactory::ObjectType::CONVERSION; break; case PJ_TYPE_TRANSFORMATION: cppType = AuthorityFactory::ObjectType::TRANSFORMATION; break; case PJ_TYPE_CONCATENATED_OPERATION: cppType = AuthorityFactory::ObjectType::CONCATENATED_OPERATION; break; case PJ_TYPE_OTHER_COORDINATE_OPERATION: cppType = AuthorityFactory::ObjectType::COORDINATE_OPERATION; break; case PJ_TYPE_UNKNOWN: valid = false; break; case PJ_TYPE_COORDINATE_METADATA: valid = false; break; } return cppType; } //! @endcond // --------------------------------------------------------------------------- /** \brief Return a list of objects by their name. * * @param ctx Context, or NULL for default context. * @param auth_name Authority name, used to restrict the search. * Or NULL for all authorities. * @param searchedName Searched name. Must be at least 2 character long. * @param types List of object types into which to search. If * NULL, all object types will be searched. * @param typesCount Number of elements in types, or 0 if types is NULL * @param approximateMatch Whether approximate name identification is allowed. * @param limitResultCount Maximum number of results to return. * Or 0 for unlimited. * @param options should be set to NULL for now * @return a result set that must be unreferenced with * proj_list_destroy(), or NULL in case of error. */ PJ_OBJ_LIST *proj_create_from_name(PJ_CONTEXT *ctx, const char *auth_name, const char *searchedName, const PJ_TYPE *types, size_t typesCount, int approximateMatch, size_t limitResultCount, const char *const *options) { SANITIZE_CTX(ctx); if (!searchedName || (types != nullptr && typesCount == 0) || (types == nullptr && typesCount > 0)) { proj_log_error(ctx, __FUNCTION__, "invalid input"); return nullptr; } (void)options; try { auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name ? auth_name : ""); std::vector<AuthorityFactory::ObjectType> allowedTypes; for (size_t i = 0; i < typesCount; ++i) { bool valid = false; auto type = convertPJObjectTypeToObjectType(types[i], valid); if (valid) { allowedTypes.push_back(type); } } auto res = factory->createObjectsFromName(searchedName, allowedTypes, approximateMatch != 0, limitResultCount); std::vector<IdentifiedObjectNNPtr> objects; for (const auto &obj : res) { objects.push_back(obj); } return new PJ_OBJ_LIST(std::move(objects)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Return the type of an object. * * @param obj Object (must not be NULL) * @return its type. */ PJ_TYPE proj_get_type(const PJ *obj) { if (!obj || !obj->iso_obj) { return PJ_TYPE_UNKNOWN; } if (obj->type != PJ_TYPE_UNKNOWN) return obj->type; const auto getType = [&obj]() { auto ptr = obj->iso_obj.get(); if (dynamic_cast<Ellipsoid *>(ptr)) { return PJ_TYPE_ELLIPSOID; } if (dynamic_cast<PrimeMeridian *>(ptr)) { return PJ_TYPE_PRIME_MERIDIAN; } if (dynamic_cast<DynamicGeodeticReferenceFrame *>(ptr)) { return PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME; } if (dynamic_cast<GeodeticReferenceFrame *>(ptr)) { return PJ_TYPE_GEODETIC_REFERENCE_FRAME; } if (dynamic_cast<DynamicVerticalReferenceFrame *>(ptr)) { return PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME; } if (dynamic_cast<VerticalReferenceFrame *>(ptr)) { return PJ_TYPE_VERTICAL_REFERENCE_FRAME; } if (dynamic_cast<DatumEnsemble *>(ptr)) { return PJ_TYPE_DATUM_ENSEMBLE; } if (dynamic_cast<TemporalDatum *>(ptr)) { return PJ_TYPE_TEMPORAL_DATUM; } if (dynamic_cast<EngineeringDatum *>(ptr)) { return PJ_TYPE_ENGINEERING_DATUM; } if (dynamic_cast<ParametricDatum *>(ptr)) { return PJ_TYPE_PARAMETRIC_DATUM; } if (auto crs = dynamic_cast<GeographicCRS *>(ptr)) { if (crs->coordinateSystem()->axisList().size() == 2) { return PJ_TYPE_GEOGRAPHIC_2D_CRS; } else { return PJ_TYPE_GEOGRAPHIC_3D_CRS; } } if (auto crs = dynamic_cast<GeodeticCRS *>(ptr)) { if (crs->isGeocentric()) { return PJ_TYPE_GEOCENTRIC_CRS; } else { return PJ_TYPE_GEODETIC_CRS; } } if (dynamic_cast<VerticalCRS *>(ptr)) { return PJ_TYPE_VERTICAL_CRS; } if (dynamic_cast<ProjectedCRS *>(ptr)) { return PJ_TYPE_PROJECTED_CRS; } if (dynamic_cast<DerivedProjectedCRS *>(ptr)) { return PJ_TYPE_DERIVED_PROJECTED_CRS; } if (dynamic_cast<CompoundCRS *>(ptr)) { return PJ_TYPE_COMPOUND_CRS; } if (dynamic_cast<TemporalCRS *>(ptr)) { return PJ_TYPE_TEMPORAL_CRS; } if (dynamic_cast<EngineeringCRS *>(ptr)) { return PJ_TYPE_ENGINEERING_CRS; } if (dynamic_cast<BoundCRS *>(ptr)) { return PJ_TYPE_BOUND_CRS; } if (dynamic_cast<CRS *>(ptr)) { return PJ_TYPE_OTHER_CRS; } if (dynamic_cast<Conversion *>(ptr)) { return PJ_TYPE_CONVERSION; } if (dynamic_cast<Transformation *>(ptr)) { return PJ_TYPE_TRANSFORMATION; } if (dynamic_cast<ConcatenatedOperation *>(ptr)) { return PJ_TYPE_CONCATENATED_OPERATION; } if (dynamic_cast<CoordinateOperation *>(ptr)) { return PJ_TYPE_OTHER_COORDINATE_OPERATION; } if (dynamic_cast<CoordinateMetadata *>(ptr)) { return PJ_TYPE_COORDINATE_METADATA; } return PJ_TYPE_UNKNOWN; }; obj->type = getType(); return obj->type; } // --------------------------------------------------------------------------- /** \brief Return whether an object is deprecated. * * @param obj Object (must not be NULL) * @return TRUE if it is deprecated, FALSE otherwise */ int proj_is_deprecated(const PJ *obj) { if (!obj) { return false; } auto identifiedObj = dynamic_cast<IdentifiedObject *>(obj->iso_obj.get()); if (!identifiedObj) { return false; } return identifiedObj->isDeprecated(); } // --------------------------------------------------------------------------- /** \brief Return a list of non-deprecated objects related to the passed one * * @param ctx Context, or NULL for default context. * @param obj Object (of type CRS for now) for which non-deprecated objects * must be searched. Must not be NULL * @return a result set that must be unreferenced with * proj_list_destroy(), or NULL in case of error. */ PJ_OBJ_LIST *proj_get_non_deprecated(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto crs = dynamic_cast<const CRS *>(obj->iso_obj.get()); if (!crs) { return nullptr; } try { std::vector<IdentifiedObjectNNPtr> objects; auto res = crs->getNonDeprecated(getDBcontext(ctx)); for (const auto &resObj : res) { objects.push_back(resObj); } return new PJ_OBJ_LIST(std::move(objects)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- static int proj_is_equivalent_to_internal(PJ_CONTEXT *ctx, const PJ *obj, const PJ *other, PJ_COMPARISON_CRITERION criterion) { if (!obj || !other) { if (ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); } return false; } if (obj->iso_obj == nullptr && other->iso_obj == nullptr && !obj->alternativeCoordinateOperations.empty() && obj->alternativeCoordinateOperations.size() == other->alternativeCoordinateOperations.size()) { for (size_t i = 0; i < obj->alternativeCoordinateOperations.size(); ++i) { if (obj->alternativeCoordinateOperations[i] != other->alternativeCoordinateOperations[i]) { return false; } } return true; } auto identifiedObj = dynamic_cast<IdentifiedObject *>(obj->iso_obj.get()); if (!identifiedObj) { return false; } auto otherIdentifiedObj = dynamic_cast<IdentifiedObject *>(other->iso_obj.get()); if (!otherIdentifiedObj) { return false; } const auto cppCriterion = ([](PJ_COMPARISON_CRITERION l_criterion) { switch (l_criterion) { case PJ_COMP_STRICT: return IComparable::Criterion::STRICT; case PJ_COMP_EQUIVALENT: return IComparable::Criterion::EQUIVALENT; case PJ_COMP_EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS: break; } return IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS; })(criterion); int res = identifiedObj->isEquivalentTo( otherIdentifiedObj, cppCriterion, ctx ? getDBcontextNoException(ctx, "proj_is_equivalent_to_with_ctx") : nullptr); return res; } // --------------------------------------------------------------------------- /** \brief Return whether two objects are equivalent. * * Use proj_is_equivalent_to_with_ctx() to be able to use database information. * * @param obj Object (must not be NULL) * @param other Other object (must not be NULL) * @param criterion Comparison criterion * @return TRUE if they are equivalent */ int proj_is_equivalent_to(const PJ *obj, const PJ *other, PJ_COMPARISON_CRITERION criterion) { return proj_is_equivalent_to_internal(nullptr, obj, other, criterion); } // --------------------------------------------------------------------------- /** \brief Return whether two objects are equivalent * * Possibly using database to check for name aliases. * * @param ctx PROJ context, or NULL for default context * @param obj Object (must not be NULL) * @param other Other object (must not be NULL) * @param criterion Comparison criterion * @return TRUE if they are equivalent * @since 6.3 */ int proj_is_equivalent_to_with_ctx(PJ_CONTEXT *ctx, const PJ *obj, const PJ *other, PJ_COMPARISON_CRITERION criterion) { SANITIZE_CTX(ctx); return proj_is_equivalent_to_internal(ctx, obj, other, criterion); } // --------------------------------------------------------------------------- /** \brief Return whether an object is a CRS * * @param obj Object (must not be NULL) */ int proj_is_crs(const PJ *obj) { if (!obj) { return false; } return dynamic_cast<CRS *>(obj->iso_obj.get()) != nullptr; } // --------------------------------------------------------------------------- /** \brief Get the name of an object. * * The lifetime of the returned string is the same as the input obj parameter. * * @param obj Object (must not be NULL) * @return a string, or NULL in case of error or missing name. */ const char *proj_get_name(const PJ *obj) { if (!obj) { return nullptr; } auto identifiedObj = dynamic_cast<IdentifiedObject *>(obj->iso_obj.get()); if (!identifiedObj) { return nullptr; } const auto &desc = identifiedObj->name()->description(); if (!desc.has_value()) { return nullptr; } // The object will still be alive after the function call. // cppcheck-suppress stlcstr return desc->c_str(); } // --------------------------------------------------------------------------- /** \brief Get the remarks of an object. * * The lifetime of the returned string is the same as the input obj parameter. * * @param obj Object (must not be NULL) * @return a string, or NULL in case of error. */ const char *proj_get_remarks(const PJ *obj) { if (!obj) { return nullptr; } auto identifiedObj = dynamic_cast<IdentifiedObject *>(obj->iso_obj.get()); if (!identifiedObj) { return nullptr; } // The object will still be alive after the function call. // cppcheck-suppress stlcstr return identifiedObj->remarks().c_str(); } // --------------------------------------------------------------------------- /** \brief Get the authority name / codespace of an identifier of an object. * * The lifetime of the returned string is the same as the input obj parameter. * * @param obj Object (must not be NULL) * @param index Index of the identifier. 0 = first identifier * @return a string, or NULL in case of error or missing name. */ const char *proj_get_id_auth_name(const PJ *obj, int index) { if (!obj) { return nullptr; } auto identifiedObj = dynamic_cast<IdentifiedObject *>(obj->iso_obj.get()); if (!identifiedObj) { return nullptr; } const auto &ids = identifiedObj->identifiers(); if (static_cast<size_t>(index) >= ids.size()) { return nullptr; } const auto &codeSpace = ids[index]->codeSpace(); if (!codeSpace.has_value()) { return nullptr; } // The object will still be alive after the function call. // cppcheck-suppress stlcstr return codeSpace->c_str(); } // --------------------------------------------------------------------------- /** \brief Get the code of an identifier of an object. * * The lifetime of the returned string is the same as the input obj parameter. * * @param obj Object (must not be NULL) * @param index Index of the identifier. 0 = first identifier * @return a string, or NULL in case of error or missing name. */ const char *proj_get_id_code(const PJ *obj, int index) { if (!obj) { return nullptr; } auto identifiedObj = dynamic_cast<IdentifiedObject *>(obj->iso_obj.get()); if (!identifiedObj) { return nullptr; } const auto &ids = identifiedObj->identifiers(); if (static_cast<size_t>(index) >= ids.size()) { return nullptr; } return ids[index]->code().c_str(); } // --------------------------------------------------------------------------- /** \brief Get a WKT representation of an object. * * The returned string is valid while the input obj parameter is valid, * and until a next call to proj_as_wkt() with the same input object. * * This function calls osgeo::proj::io::IWKTExportable::exportToWKT(). * * This function may return NULL if the object is not compatible with an * export to the requested type. * * @param ctx PROJ context, or NULL for default context * @param obj Object (must not be NULL) * @param type WKT version. * @param options null-terminated list of options, or NULL. Currently * supported options are: * <ul> * <li>MULTILINE=YES/NO. Defaults to YES, except for WKT1_ESRI</li> * <li>INDENTATION_WIDTH=number. Defaults to 4 (when multiline output is * on).</li> * <li>OUTPUT_AXIS=AUTO/YES/NO. In AUTO mode, axis will be output for WKT2 * variants, for WKT1_GDAL for ProjectedCRS with easting/northing ordering * (otherwise stripped), but not for WKT1_ESRI. Setting to YES will output * them unconditionally, and to NO will omit them unconditionally.</li> * <li>STRICT=YES/NO. Default is YES. If NO, a Geographic 3D CRS can be for * example exported as WKT1_GDAL with 3 axes, whereas this is normally not * allowed.</li> * <li>ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS=YES/NO. Default is NO. If set * to YES and type == PJ_WKT1_GDAL, a Geographic 3D CRS or a Projected 3D CRS * will be exported as a compound CRS whose vertical part represents an * ellipsoidal height (for example for use with LAS 1.4 WKT1).</li> * <li>ALLOW_LINUNIT_NODE=YES/NO. Default is YES starting with PROJ 9.1. * Only taken into account with type == PJ_WKT1_ESRI on a Geographic 3D * CRS.</li> * </ul> * @return a string, or NULL in case of error. */ const char *proj_as_wkt(PJ_CONTEXT *ctx, const PJ *obj, PJ_WKT_TYPE type, const char *const *options) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto iWKTExportable = dynamic_cast<IWKTExportable *>(obj->iso_obj.get()); if (!iWKTExportable) { return nullptr; } const auto convention = ([](PJ_WKT_TYPE l_type) { switch (l_type) { case PJ_WKT2_2015: return WKTFormatter::Convention::WKT2_2015; case PJ_WKT2_2015_SIMPLIFIED: return WKTFormatter::Convention::WKT2_2015_SIMPLIFIED; case PJ_WKT2_2019: return WKTFormatter::Convention::WKT2_2019; case PJ_WKT2_2019_SIMPLIFIED: return WKTFormatter::Convention::WKT2_2019_SIMPLIFIED; case PJ_WKT1_GDAL: return WKTFormatter::Convention::WKT1_GDAL; case PJ_WKT1_ESRI: break; } return WKTFormatter::Convention::WKT1_ESRI; })(type); try { auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); auto formatter = WKTFormatter::create(convention, std::move(dbContext)); for (auto iter = options; iter && iter[0]; ++iter) { const char *value; if ((value = getOptionValue(*iter, "MULTILINE="))) { formatter->setMultiLine(ci_equal(value, "YES")); } else if ((value = getOptionValue(*iter, "INDENTATION_WIDTH="))) { formatter->setIndentationWidth(std::atoi(value)); } else if ((value = getOptionValue(*iter, "OUTPUT_AXIS="))) { if (!ci_equal(value, "AUTO")) { formatter->setOutputAxis( ci_equal(value, "YES") ? WKTFormatter::OutputAxisRule::YES : WKTFormatter::OutputAxisRule::NO); } } else if ((value = getOptionValue(*iter, "STRICT="))) { formatter->setStrict(ci_equal(value, "YES")); } else if ((value = getOptionValue( *iter, "ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS="))) { formatter->setAllowEllipsoidalHeightAsVerticalCRS( ci_equal(value, "YES")); } else if ((value = getOptionValue(*iter, "ALLOW_LINUNIT_NODE="))) { formatter->setAllowLINUNITNode(ci_equal(value, "YES")); } else { std::string msg("Unknown option :"); msg += *iter; proj_log_error(ctx, __FUNCTION__, msg.c_str()); return nullptr; } } obj->lastWKT = iWKTExportable->exportToWKT(formatter.get()); return obj->lastWKT.c_str(); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Get a PROJ string representation of an object. * * The returned string is valid while the input obj parameter is valid, * and until a next call to proj_as_proj_string() with the same input * object. * * \warning If a CRS object was not created from a PROJ string, * exporting to a PROJ string will in most cases * cause a loss of information. This can potentially lead to * erroneous transformations. * * This function calls * osgeo::proj::io::IPROJStringExportable::exportToPROJString(). * * This function may return NULL if the object is not compatible with an * export to the requested type. * * @param ctx PROJ context, or NULL for default context * @param obj Object (must not be NULL) * @param type PROJ String version. * @param options NULL-terminated list of strings with "KEY=VALUE" format. or * NULL. Currently supported options are: * <ul> * <li>USE_APPROX_TMERC=YES to add the +approx flag to +proj=tmerc or * +proj=utm.</li> * <li>MULTILINE=YES/NO. Defaults to NO</li> * <li>INDENTATION_WIDTH=number. Defaults to 2 (when multiline output is * on).</li> * <li>MAX_LINE_LENGTH=number. Defaults to 80 (when multiline output is * on).</li> * </ul> * @return a string, or NULL in case of error. */ const char *proj_as_proj_string(PJ_CONTEXT *ctx, const PJ *obj, PJ_PROJ_STRING_TYPE type, const char *const *options) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto exportable = dynamic_cast<const IPROJStringExportable *>(obj->iso_obj.get()); if (!exportable) { proj_log_error(ctx, __FUNCTION__, "Object type not exportable to PROJ"); return nullptr; } // Make sure that the C and C++ enumeration match static_assert(static_cast<int>(PJ_PROJ_5) == static_cast<int>(PROJStringFormatter::Convention::PROJ_5), ""); static_assert(static_cast<int>(PJ_PROJ_4) == static_cast<int>(PROJStringFormatter::Convention::PROJ_4), ""); // Make sure we enumerate all values. If adding a new value, as we // don't have a default clause, the compiler will warn. switch (type) { case PJ_PROJ_5: case PJ_PROJ_4: break; } const PROJStringFormatter::Convention convention = static_cast<PROJStringFormatter::Convention>(type); auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { auto formatter = PROJStringFormatter::create(convention, std::move(dbContext)); for (auto iter = options; iter && iter[0]; ++iter) { const char *value; if ((value = getOptionValue(*iter, "MULTILINE="))) { formatter->setMultiLine(ci_equal(value, "YES")); } else if ((value = getOptionValue(*iter, "INDENTATION_WIDTH="))) { formatter->setIndentationWidth(std::atoi(value)); } else if ((value = getOptionValue(*iter, "MAX_LINE_LENGTH="))) { formatter->setMaxLineLength(std::atoi(value)); } else if ((value = getOptionValue(*iter, "USE_APPROX_TMERC="))) { formatter->setUseApproxTMerc(ci_equal(value, "YES")); } else { std::string msg("Unknown option :"); msg += *iter; proj_log_error(ctx, __FUNCTION__, msg.c_str()); return nullptr; } } obj->lastPROJString = exportable->exportToPROJString(formatter.get()); return obj->lastPROJString.c_str(); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Get a PROJJSON string representation of an object. * * The returned string is valid while the input obj parameter is valid, * and until a next call to proj_as_proj_string() with the same input * object. * * This function calls * osgeo::proj::io::IJSONExportable::exportToJSON(). * * This function may return NULL if the object is not compatible with an * export to the requested type. * * @param ctx PROJ context, or NULL for default context * @param obj Object (must not be NULL) * @param options NULL-terminated list of strings with "KEY=VALUE" format. or * NULL. Currently * supported options are: * <ul> * <li>MULTILINE=YES/NO. Defaults to YES</li> * <li>INDENTATION_WIDTH=number. Defaults to 2 (when multiline output is * on).</li> * <li>SCHEMA=string. URL to PROJJSON schema. Can be set to empty string to * disable it.</li> * </ul> * @return a string, or NULL in case of error. * * @since 6.2 */ const char *proj_as_projjson(PJ_CONTEXT *ctx, const PJ *obj, const char *const *options) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto exportable = dynamic_cast<const IJSONExportable *>(obj->iso_obj.get()); if (!exportable) { proj_log_error(ctx, __FUNCTION__, "Object type not exportable to JSON"); return nullptr; } auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { auto formatter = JSONFormatter::create(std::move(dbContext)); for (auto iter = options; iter && iter[0]; ++iter) { const char *value; if ((value = getOptionValue(*iter, "MULTILINE="))) { formatter->setMultiLine(ci_equal(value, "YES")); } else if ((value = getOptionValue(*iter, "INDENTATION_WIDTH="))) { formatter->setIndentationWidth(std::atoi(value)); } else if ((value = getOptionValue(*iter, "SCHEMA="))) { formatter->setSchema(value); } else { std::string msg("Unknown option :"); msg += *iter; proj_log_error(ctx, __FUNCTION__, msg.c_str()); return nullptr; } } obj->lastJSONString = exportable->exportToJSON(formatter.get()); return obj->lastJSONString.c_str(); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Get the number of domains/usages for a given object. * * Most objects have a single domain/usage, but for some of them, there might * be multiple. * * @param obj Object (must not be NULL) * @return the number of domains, or 0 in case of error. * @since 9.2 */ int proj_get_domain_count(const PJ *obj) { if (!obj || !obj->iso_obj) { return 0; } auto objectUsage = dynamic_cast<const ObjectUsage *>(obj->iso_obj.get()); if (!objectUsage) { return 0; } const auto &domains = objectUsage->domains(); return static_cast<int>(domains.size()); } // --------------------------------------------------------------------------- /** \brief Get the scope of an object. * * In case of multiple usages, this will be the one of first usage. * * The lifetime of the returned string is the same as the input obj parameter. * * @param obj Object (must not be NULL) * @return a string, or NULL in case of error or missing scope. */ const char *proj_get_scope(const PJ *obj) { return proj_get_scope_ex(obj, 0); } // --------------------------------------------------------------------------- /** \brief Get the scope of an object. * * The lifetime of the returned string is the same as the input obj parameter. * * @param obj Object (must not be NULL) * @param domainIdx Index of the domain/usage. In [0,proj_get_domain_count(obj)[ * @return a string, or NULL in case of error or missing scope. * @since 9.2 */ const char *proj_get_scope_ex(const PJ *obj, int domainIdx) { if (!obj || !obj->iso_obj) { return nullptr; } auto objectUsage = dynamic_cast<const ObjectUsage *>(obj->iso_obj.get()); if (!objectUsage) { return nullptr; } const auto &domains = objectUsage->domains(); if (domainIdx < 0 || static_cast<size_t>(domainIdx) >= domains.size()) { return nullptr; } const auto &scope = domains[domainIdx]->scope(); if (!scope.has_value()) { return nullptr; } // The object will still be alive after the function call. // cppcheck-suppress stlcstr return scope->c_str(); } // --------------------------------------------------------------------------- /** \brief Return the area of use of an object. * * In case of multiple usages, this will be the one of first usage. * * @param ctx PROJ context, or NULL for default context * @param obj Object (must not be NULL) * @param out_west_lon_degree Pointer to a double to receive the west longitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_south_lat_degree Pointer to a double to receive the south latitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_east_lon_degree Pointer to a double to receive the east longitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_north_lat_degree Pointer to a double to receive the north latitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_area_name Pointer to a string to receive the name of the area of * use. Or NULL. *p_area_name is valid while obj is valid itself. * @return TRUE in case of success, FALSE in case of error or if the area * of use is unknown. */ int proj_get_area_of_use(PJ_CONTEXT *ctx, const PJ *obj, double *out_west_lon_degree, double *out_south_lat_degree, double *out_east_lon_degree, double *out_north_lat_degree, const char **out_area_name) { return proj_get_area_of_use_ex(ctx, obj, 0, out_west_lon_degree, out_south_lat_degree, out_east_lon_degree, out_north_lat_degree, out_area_name); } // --------------------------------------------------------------------------- /** \brief Return the area of use of an object. * * @param ctx PROJ context, or NULL for default context * @param obj Object (must not be NULL) * @param domainIdx Index of the domain/usage. In [0,proj_get_domain_count(obj)[ * @param out_west_lon_degree Pointer to a double to receive the west longitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_south_lat_degree Pointer to a double to receive the south latitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_east_lon_degree Pointer to a double to receive the east longitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_north_lat_degree Pointer to a double to receive the north latitude * (in degrees). Or NULL. If the returned value is -1000, the bounding box is * unknown. * @param out_area_name Pointer to a string to receive the name of the area of * use. Or NULL. *p_area_name is valid while obj is valid itself. * @return TRUE in case of success, FALSE in case of error or if the area * of use is unknown. */ int proj_get_area_of_use_ex(PJ_CONTEXT *ctx, const PJ *obj, int domainIdx, double *out_west_lon_degree, double *out_south_lat_degree, double *out_east_lon_degree, double *out_north_lat_degree, const char **out_area_name) { (void)ctx; if (out_area_name) { *out_area_name = nullptr; } auto objectUsage = dynamic_cast<const ObjectUsage *>(obj->iso_obj.get()); if (!objectUsage) { return false; } const auto &domains = objectUsage->domains(); if (domainIdx < 0 || static_cast<size_t>(domainIdx) >= domains.size()) { return false; } const auto &extent = domains[domainIdx]->domainOfValidity(); if (!extent) { return false; } const auto &desc = extent->description(); if (desc.has_value() && out_area_name) { *out_area_name = desc->c_str(); } const auto &geogElements = extent->geographicElements(); if (!geogElements.empty()) { auto bbox = dynamic_cast<const GeographicBoundingBox *>(geogElements[0].get()); if (bbox) { if (out_west_lon_degree) { *out_west_lon_degree = bbox->westBoundLongitude(); } if (out_south_lat_degree) { *out_south_lat_degree = bbox->southBoundLatitude(); } if (out_east_lon_degree) { *out_east_lon_degree = bbox->eastBoundLongitude(); } if (out_north_lat_degree) { *out_north_lat_degree = bbox->northBoundLatitude(); } return true; } } if (out_west_lon_degree) { *out_west_lon_degree = -1000; } if (out_south_lat_degree) { *out_south_lat_degree = -1000; } if (out_east_lon_degree) { *out_east_lon_degree = -1000; } if (out_north_lat_degree) { *out_north_lat_degree = -1000; } return true; } // --------------------------------------------------------------------------- static const GeodeticCRS *extractGeodeticCRS(PJ_CONTEXT *ctx, const PJ *crs, const char *fname) { if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, fname, "missing required input"); return nullptr; } auto l_crs = dynamic_cast<const CRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, fname, "Object is not a CRS"); return nullptr; } auto geodCRS = l_crs->extractGeodeticCRSRaw(); if (!geodCRS) { proj_log_error(ctx, fname, "CRS has no geodetic CRS"); } return geodCRS; } // --------------------------------------------------------------------------- /** \brief Get the geodeticCRS / geographicCRS from a CRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type CRS (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_crs_get_geodetic_crs(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); auto geodCRS = extractGeodeticCRS(ctx, crs, __FUNCTION__); if (!geodCRS) { return nullptr; } return pj_obj_create(ctx, NN_NO_CHECK(nn_dynamic_pointer_cast<IdentifiedObject>( geodCRS->shared_from_this()))); } // --------------------------------------------------------------------------- /** \brief Returns whether a CRS is a derived CRS. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type CRS (must not be NULL) * @return TRUE if the CRS is a derived CRS. * @since 8.0 */ int proj_crs_is_derived(PJ_CONTEXT *ctx, const PJ *crs) { if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto l_crs = dynamic_cast<const CRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CRS"); return false; } return dynamic_cast<const DerivedCRS *>(l_crs) != nullptr; } // --------------------------------------------------------------------------- /** \brief Get a CRS component from a CompoundCRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type CRS (must not be NULL) * @param index Index of the CRS component (typically 0 = horizontal, 1 = * vertical) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_crs_get_sub_crs(PJ_CONTEXT *ctx, const PJ *crs, int index) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_crs = dynamic_cast<CompoundCRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CompoundCRS"); return nullptr; } const auto &components = l_crs->componentReferenceSystems(); if (static_cast<size_t>(index) >= components.size()) { return nullptr; } return pj_obj_create(ctx, components[index]); } // --------------------------------------------------------------------------- /** \brief Returns a BoundCRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param base_crs Base CRS (must not be NULL) * @param hub_crs Hub CRS (must not be NULL) * @param transformation Transformation (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_crs_create_bound_crs(PJ_CONTEXT *ctx, const PJ *base_crs, const PJ *hub_crs, const PJ *transformation) { SANITIZE_CTX(ctx); if (!base_crs || !hub_crs || !transformation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_base_crs = std::dynamic_pointer_cast<CRS>(base_crs->iso_obj); if (!l_base_crs) { proj_log_error(ctx, __FUNCTION__, "base_crs is not a CRS"); return nullptr; } auto l_hub_crs = std::dynamic_pointer_cast<CRS>(hub_crs->iso_obj); if (!l_hub_crs) { proj_log_error(ctx, __FUNCTION__, "hub_crs is not a CRS"); return nullptr; } auto l_transformation = std::dynamic_pointer_cast<Transformation>(transformation->iso_obj); if (!l_transformation) { proj_log_error(ctx, __FUNCTION__, "transformation is not a CRS"); return nullptr; } try { return pj_obj_create(ctx, BoundCRS::create(NN_NO_CHECK(l_base_crs), NN_NO_CHECK(l_hub_crs), NN_NO_CHECK(l_transformation))); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Returns potentially * a BoundCRS, with a transformation to EPSG:4326, wrapping this CRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * This is the same as method * osgeo::proj::crs::CRS::createBoundCRSToWGS84IfPossible() * * @param ctx PROJ context, or NULL for default context * @param crs Object of type CRS (must not be NULL) * @param options null-terminated list of options, or NULL. Currently * supported options are: * <ul> * <li>ALLOW_INTERMEDIATE_CRS=ALWAYS/IF_NO_DIRECT_TRANSFORMATION/NEVER. Defaults * to NEVER. When set to ALWAYS/IF_NO_DIRECT_TRANSFORMATION, * intermediate CRS may be considered when computing the possible * transformations. Slower.</li> * </ul> * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_crs_create_bound_crs_to_WGS84(PJ_CONTEXT *ctx, const PJ *crs, const char *const *options) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_crs = dynamic_cast<const CRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CRS"); return nullptr; } auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { CoordinateOperationContext::IntermediateCRSUse allowIntermediateCRS = CoordinateOperationContext::IntermediateCRSUse::NEVER; for (auto iter = options; iter && iter[0]; ++iter) { const char *value; if ((value = getOptionValue(*iter, "ALLOW_INTERMEDIATE_CRS="))) { if (ci_equal(value, "YES") || ci_equal(value, "ALWAYS")) { allowIntermediateCRS = CoordinateOperationContext::IntermediateCRSUse::ALWAYS; } else if (ci_equal(value, "IF_NO_DIRECT_TRANSFORMATION")) { allowIntermediateCRS = CoordinateOperationContext:: IntermediateCRSUse::IF_NO_DIRECT_TRANSFORMATION; } } else { std::string msg("Unknown option :"); msg += *iter; proj_log_error(ctx, __FUNCTION__, msg.c_str()); return nullptr; } } return pj_obj_create(ctx, l_crs->createBoundCRSToWGS84IfPossible( dbContext, allowIntermediateCRS)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Returns a BoundCRS, with a transformation to a hub geographic 3D crs * (use EPSG:4979 for WGS84 for example), using a grid. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param vert_crs Object of type VerticalCRS (must not be NULL) * @param hub_geographic_3D_crs Object of type Geographic 3D CRS (must not be * NULL) * @param grid_name Grid name (typically a .gtx file) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. * @since 6.3 */ PJ *proj_crs_create_bound_vertical_crs(PJ_CONTEXT *ctx, const PJ *vert_crs, const PJ *hub_geographic_3D_crs, const char *grid_name) { SANITIZE_CTX(ctx); if (!vert_crs || !hub_geographic_3D_crs || !grid_name) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_crs = std::dynamic_pointer_cast<VerticalCRS>(vert_crs->iso_obj); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "vert_crs is not a VerticalCRS"); return nullptr; } auto hub_crs = std::dynamic_pointer_cast<CRS>(hub_geographic_3D_crs->iso_obj); if (!hub_crs) { proj_log_error(ctx, __FUNCTION__, "hub_geographic_3D_crs is not a CRS"); return nullptr; } try { auto nnCRS = NN_NO_CHECK(l_crs); auto nnHubCRS = NN_NO_CHECK(hub_crs); auto transformation = Transformation::createGravityRelatedHeightToGeographic3D( PropertyMap().set(IdentifiedObject::NAME_KEY, "unknown to " + hub_crs->nameStr() + " ellipsoidal height"), nnCRS, nnHubCRS, nullptr, std::string(grid_name), std::vector<PositionalAccuracyNNPtr>()); return pj_obj_create(ctx, BoundCRS::create(nnCRS, nnHubCRS, transformation)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Get the ellipsoid from a CRS or a GeodeticReferenceFrame. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS or GeodeticReferenceFrame (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_get_ellipsoid(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); auto ptr = obj->iso_obj.get(); if (dynamic_cast<const CRS *>(ptr)) { auto geodCRS = extractGeodeticCRS(ctx, obj, __FUNCTION__); if (geodCRS) { return pj_obj_create(ctx, geodCRS->ellipsoid()); } } else { auto datum = dynamic_cast<const GeodeticReferenceFrame *>(ptr); if (datum) { return pj_obj_create(ctx, datum->ellipsoid()); } } proj_log_error(ctx, __FUNCTION__, "Object is not a CRS or GeodeticReferenceFrame"); return nullptr; } // --------------------------------------------------------------------------- /** \brief Get the name of the celestial body of this object. * * Object should be a CRS, Datum or Ellipsoid. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS, Datum or Ellipsoid.(must not be NULL) * @return the name of the celestial body, or NULL. * @since 8.1 */ const char *proj_get_celestial_body_name(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); const BaseObject *ptr = obj->iso_obj.get(); if (dynamic_cast<const CRS *>(ptr)) { const auto geodCRS = extractGeodeticCRS(ctx, obj, __FUNCTION__); if (!geodCRS) { // FIXME when vertical CRS can be non-EARTH... return datum::Ellipsoid::EARTH.c_str(); } return geodCRS->ellipsoid()->celestialBody().c_str(); } const auto ensemble = dynamic_cast<const DatumEnsemble *>(ptr); if (ensemble) { ptr = ensemble->datums().front().get(); // Go on } const auto geodetic_datum = dynamic_cast<const GeodeticReferenceFrame *>(ptr); if (geodetic_datum) { return geodetic_datum->ellipsoid()->celestialBody().c_str(); } const auto vertical_datum = dynamic_cast<const VerticalReferenceFrame *>(ptr); if (vertical_datum) { // FIXME when vertical CRS can be non-EARTH... return datum::Ellipsoid::EARTH.c_str(); } const auto ellipsoid = dynamic_cast<const Ellipsoid *>(ptr); if (ellipsoid) { return ellipsoid->celestialBody().c_str(); } proj_log_error(ctx, __FUNCTION__, "Object is not a CRS, Datum or Ellipsoid"); return nullptr; } // --------------------------------------------------------------------------- /** \brief Get the horizontal datum from a CRS * * This function may return a Datum or DatumEnsemble object. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type CRS (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_crs_get_horizontal_datum(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); auto geodCRS = extractGeodeticCRS(ctx, crs, __FUNCTION__); if (!geodCRS) { return nullptr; } const auto &datum = geodCRS->datum(); if (datum) { return pj_obj_create(ctx, NN_NO_CHECK(datum)); } const auto &datumEnsemble = geodCRS->datumEnsemble(); if (datumEnsemble) { return pj_obj_create(ctx, NN_NO_CHECK(datumEnsemble)); } proj_log_error(ctx, __FUNCTION__, "CRS has no datum"); return nullptr; } // --------------------------------------------------------------------------- /** \brief Return ellipsoid parameters. * * @param ctx PROJ context, or NULL for default context * @param ellipsoid Object of type Ellipsoid (must not be NULL) * @param out_semi_major_metre Pointer to a value to store the semi-major axis * in * metre. or NULL * @param out_semi_minor_metre Pointer to a value to store the semi-minor axis * in * metre. or NULL * @param out_is_semi_minor_computed Pointer to a boolean value to indicate if * the * semi-minor value was computed. If FALSE, its value comes from the * definition. or NULL * @param out_inv_flattening Pointer to a value to store the inverse * flattening. or NULL * @return TRUE in case of success. */ int proj_ellipsoid_get_parameters(PJ_CONTEXT *ctx, const PJ *ellipsoid, double *out_semi_major_metre, double *out_semi_minor_metre, int *out_is_semi_minor_computed, double *out_inv_flattening) { SANITIZE_CTX(ctx); if (!ellipsoid) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return FALSE; } auto l_ellipsoid = dynamic_cast<const Ellipsoid *>(ellipsoid->iso_obj.get()); if (!l_ellipsoid) { proj_log_error(ctx, __FUNCTION__, "Object is not a Ellipsoid"); return FALSE; } if (out_semi_major_metre) { *out_semi_major_metre = l_ellipsoid->semiMajorAxis().getSIValue(); } if (out_semi_minor_metre) { *out_semi_minor_metre = l_ellipsoid->computeSemiMinorAxis().getSIValue(); } if (out_is_semi_minor_computed) { *out_is_semi_minor_computed = !(l_ellipsoid->semiMinorAxis().has_value()); } if (out_inv_flattening) { *out_inv_flattening = l_ellipsoid->computedInverseFlattening(); } return TRUE; } // --------------------------------------------------------------------------- /** \brief Get the prime meridian of a CRS or a GeodeticReferenceFrame. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS or GeodeticReferenceFrame (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_get_prime_meridian(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); auto ptr = obj->iso_obj.get(); if (dynamic_cast<CRS *>(ptr)) { auto geodCRS = extractGeodeticCRS(ctx, obj, __FUNCTION__); if (geodCRS) { return pj_obj_create(ctx, geodCRS->primeMeridian()); } } else { auto datum = dynamic_cast<const GeodeticReferenceFrame *>(ptr); if (datum) { return pj_obj_create(ctx, datum->primeMeridian()); } } proj_log_error(ctx, __FUNCTION__, "Object is not a CRS or GeodeticReferenceFrame"); return nullptr; } // --------------------------------------------------------------------------- /** \brief Return prime meridian parameters. * * @param ctx PROJ context, or NULL for default context * @param prime_meridian Object of type PrimeMeridian (must not be NULL) * @param out_longitude Pointer to a value to store the longitude of the prime * meridian, in its native unit. or NULL * @param out_unit_conv_factor Pointer to a value to store the conversion * factor of the prime meridian longitude unit to radian. or NULL * @param out_unit_name Pointer to a string value to store the unit name. * or NULL * @return TRUE in case of success. */ int proj_prime_meridian_get_parameters(PJ_CONTEXT *ctx, const PJ *prime_meridian, double *out_longitude, double *out_unit_conv_factor, const char **out_unit_name) { SANITIZE_CTX(ctx); if (!prime_meridian) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto l_pm = dynamic_cast<const PrimeMeridian *>(prime_meridian->iso_obj.get()); if (!l_pm) { proj_log_error(ctx, __FUNCTION__, "Object is not a PrimeMeridian"); return false; } const auto &longitude = l_pm->longitude(); if (out_longitude) { *out_longitude = longitude.value(); } const auto &unit = longitude.unit(); if (out_unit_conv_factor) { *out_unit_conv_factor = unit.conversionToSI(); } if (out_unit_name) { *out_unit_name = unit.name().c_str(); } return true; } // --------------------------------------------------------------------------- /** \brief Return the base CRS of a BoundCRS or a DerivedCRS/ProjectedCRS, or * the source CRS of a CoordinateOperation, or the CRS of a CoordinateMetadata. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type BoundCRS or CoordinateOperation (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error, or missing source CRS. */ PJ *proj_get_source_crs(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); if (!obj) { return nullptr; } auto ptr = obj->iso_obj.get(); auto boundCRS = dynamic_cast<const BoundCRS *>(ptr); if (boundCRS) { return pj_obj_create(ctx, boundCRS->baseCRS()); } auto derivedCRS = dynamic_cast<const DerivedCRS *>(ptr); if (derivedCRS) { return pj_obj_create(ctx, derivedCRS->baseCRS()); } auto co = dynamic_cast<const CoordinateOperation *>(ptr); if (co) { auto sourceCRS = co->sourceCRS(); if (sourceCRS) { return pj_obj_create(ctx, NN_NO_CHECK(sourceCRS)); } return nullptr; } if (!obj->alternativeCoordinateOperations.empty()) { return proj_get_source_crs(ctx, obj->alternativeCoordinateOperations[0].pj); } auto coordinateMetadata = dynamic_cast<const CoordinateMetadata *>(ptr); if (coordinateMetadata) { return pj_obj_create(ctx, coordinateMetadata->crs()); } proj_log_error(ctx, __FUNCTION__, "Object is not a BoundCRS, a CoordinateOperation or a " "CoordinateMetadata"); return nullptr; } // --------------------------------------------------------------------------- /** \brief Return the hub CRS of a BoundCRS or the target CRS of a * CoordinateOperation. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type BoundCRS or CoordinateOperation (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error, or missing target CRS. */ PJ *proj_get_target_crs(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto ptr = obj->iso_obj.get(); auto boundCRS = dynamic_cast<const BoundCRS *>(ptr); if (boundCRS) { return pj_obj_create(ctx, boundCRS->hubCRS()); } auto co = dynamic_cast<const CoordinateOperation *>(ptr); if (co) { auto targetCRS = co->targetCRS(); if (targetCRS) { return pj_obj_create(ctx, NN_NO_CHECK(targetCRS)); } return nullptr; } if (!obj->alternativeCoordinateOperations.empty()) { return proj_get_target_crs(ctx, obj->alternativeCoordinateOperations[0].pj); } proj_log_error(ctx, __FUNCTION__, "Object is not a BoundCRS or a CoordinateOperation"); return nullptr; } // --------------------------------------------------------------------------- /** \brief Identify the CRS with reference CRSs. * * The candidate CRSs are either hard-coded, or looked in the database when * it is available. * * Note that the implementation uses a set of heuristics to have a good * compromise of successful identifications over execution time. It might miss * legitimate matches in some circumstances. * * The method returns a list of matching reference CRS, and the percentage * (0-100) of confidence in the match. The list is sorted by decreasing * confidence. * <ul> * <li>100% means that the name of the reference entry * perfectly matches the CRS name, and both are equivalent. In which case a * single result is returned. * Note: in the case of a GeographicCRS whose axis * order is implicit in the input definition (for example ESRI WKT), then axis * order is ignored for the purpose of identification. That is the CRS built * from * GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]], * PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]] * will be identified to EPSG:4326, but will not pass a * isEquivalentTo(EPSG_4326, util::IComparable::Criterion::EQUIVALENT) test, * but rather isEquivalentTo(EPSG_4326, * util::IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS) * </li> * <li>90% means that CRS are equivalent, but the names are not exactly the * same.</li> * <li>70% means that CRS are equivalent, but the names are not equivalent. * </li> * <li>25% means that the CRS are not equivalent, but there is some similarity * in * the names.</li> * </ul> * Other confidence values may be returned by some specialized implementations. * * This is implemented for GeodeticCRS, ProjectedCRS, VerticalCRS and * CompoundCRS. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS. Must not be NULL * @param auth_name Authority name, or NULL for all authorities * @param options Placeholder for future options. Should be set to NULL. * @param out_confidence Output parameter. Pointer to an array of integers that * will be allocated by the function and filled with the confidence values * (0-100). There are as many elements in this array as * proj_list_get_count() * returns on the return value of this function. *confidence should be * released with proj_int_list_destroy(). * @return a list of matching reference CRS, or nullptr in case of error. */ PJ_OBJ_LIST *proj_identify(PJ_CONTEXT *ctx, const PJ *obj, const char *auth_name, const char *const *options, int **out_confidence) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } (void)options; if (out_confidence) { *out_confidence = nullptr; } auto ptr = obj->iso_obj.get(); auto crs = dynamic_cast<const CRS *>(ptr); if (!crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CRS"); } else { int *confidenceTemp = nullptr; try { auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name ? auth_name : ""); auto res = crs->identify(factory); std::vector<IdentifiedObjectNNPtr> objects; confidenceTemp = out_confidence ? new int[res.size()] : nullptr; size_t i = 0; for (const auto &pair : res) { objects.push_back(pair.first); if (confidenceTemp) { confidenceTemp[i] = pair.second; ++i; } } auto ret = internal::make_unique<PJ_OBJ_LIST>(std::move(objects)); if (out_confidence) { *out_confidence = confidenceTemp; confidenceTemp = nullptr; } return ret.release(); } catch (const std::exception &e) { delete[] confidenceTemp; proj_log_error(ctx, __FUNCTION__, e.what()); } } return nullptr; } // --------------------------------------------------------------------------- /** \brief Free an array of integer. */ void proj_int_list_destroy(int *list) { delete[] list; } // --------------------------------------------------------------------------- /** \brief Return the list of authorities used in the database. * * The returned list is NULL terminated and must be freed with * proj_string_list_destroy(). * * @param ctx PROJ context, or NULL for default context * * @return a NULL terminated list of NUL-terminated strings that must be * freed with proj_string_list_destroy(), or NULL in case of error. */ PROJ_STRING_LIST proj_get_authorities_from_database(PJ_CONTEXT *ctx) { SANITIZE_CTX(ctx); try { auto ret = to_string_list(getDBcontext(ctx)->getAuthorities()); return ret; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Returns the set of authority codes of the given object type. * * The returned list is NULL terminated and must be freed with * proj_string_list_destroy(). * * @param ctx PROJ context, or NULL for default context. * @param auth_name Authority name (must not be NULL) * @param type Object type. * @param allow_deprecated whether we should return deprecated objects as well. * * @return a NULL terminated list of NUL-terminated strings that must be * freed with proj_string_list_destroy(), or NULL in case of error. * * @see proj_get_crs_info_list_from_database() */ PROJ_STRING_LIST proj_get_codes_from_database(PJ_CONTEXT *ctx, const char *auth_name, PJ_TYPE type, int allow_deprecated) { SANITIZE_CTX(ctx); if (!auth_name) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } try { auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name); bool valid = false; auto typeInternal = convertPJObjectTypeToObjectType(type, valid); if (!valid) { return nullptr; } auto ret = to_string_list( factory->getAuthorityCodes(typeInternal, allow_deprecated != 0)); return ret; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Enumerate celestial bodies from the database. * * The returned object is an array of PROJ_CELESTIAL_BODY_INFO* pointers, whose * last entry is NULL. This array should be freed with * proj_celestial_body_list_destroy() * * @param ctx PROJ context, or NULL for default context * @param auth_name Authority name, used to restrict the search. * Or NULL for all authorities. * @param out_result_count Output parameter pointing to an integer to receive * the size of the result list. Might be NULL * @return an array of PROJ_CELESTIAL_BODY_INFO* pointers to be freed with * proj_celestial_body_list_destroy(), or NULL in case of error. * @since 8.1 */ PROJ_CELESTIAL_BODY_INFO **proj_get_celestial_body_list_from_database( PJ_CONTEXT *ctx, const char *auth_name, int *out_result_count) { SANITIZE_CTX(ctx); PROJ_CELESTIAL_BODY_INFO **ret = nullptr; int i = 0; try { auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name ? auth_name : ""); auto list = factory->getCelestialBodyList(); ret = new PROJ_CELESTIAL_BODY_INFO *[list.size() + 1]; for (const auto &info : list) { ret[i] = new PROJ_CELESTIAL_BODY_INFO; ret[i]->auth_name = pj_strdup(info.authName.c_str()); ret[i]->name = pj_strdup(info.name.c_str()); i++; } ret[i] = nullptr; if (out_result_count) *out_result_count = i; return ret; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); if (ret) { ret[i + 1] = nullptr; proj_celestial_body_list_destroy(ret); } if (out_result_count) *out_result_count = 0; } return nullptr; } // --------------------------------------------------------------------------- /** \brief Destroy the result returned by * proj_get_celestial_body_list_from_database(). * * @since 8.1 */ void proj_celestial_body_list_destroy(PROJ_CELESTIAL_BODY_INFO **list) { if (list) { for (int i = 0; list[i] != nullptr; i++) { free(list[i]->auth_name); free(list[i]->name); delete list[i]; } delete[] list; } } // --------------------------------------------------------------------------- /** Free a list of NULL terminated strings. */ void proj_string_list_destroy(PROJ_STRING_LIST list) { if (list) { for (size_t i = 0; list[i] != nullptr; i++) { delete[] list[i]; } delete[] list; } } // --------------------------------------------------------------------------- /** \brief Instantiate a default set of parameters to be used by * proj_get_crs_list(). * * @return a new object to free with proj_get_crs_list_parameters_destroy() */ PROJ_CRS_LIST_PARAMETERS *proj_get_crs_list_parameters_create() { auto ret = new (std::nothrow) PROJ_CRS_LIST_PARAMETERS(); if (ret) { ret->types = nullptr; ret->typesCount = 0; ret->crs_area_of_use_contains_bbox = TRUE; ret->bbox_valid = FALSE; ret->west_lon_degree = 0.0; ret->south_lat_degree = 0.0; ret->east_lon_degree = 0.0; ret->north_lat_degree = 0.0; ret->allow_deprecated = FALSE; ret->celestial_body_name = nullptr; } return ret; } // --------------------------------------------------------------------------- /** \brief Destroy an object returned by proj_get_crs_list_parameters_create() */ void proj_get_crs_list_parameters_destroy(PROJ_CRS_LIST_PARAMETERS *params) { delete params; } // --------------------------------------------------------------------------- /** \brief Enumerate CRS objects from the database, taking into account various * criteria. * * The returned object is an array of PROJ_CRS_INFO* pointers, whose last * entry is NULL. This array should be freed with proj_crs_info_list_destroy() * * When no filter parameters are set, this is functionally equivalent to * proj_get_codes_from_database(), instantiating a PJ* object for each * of the codes with proj_create_from_database() and retrieving information * with the various getters. However this function will be much faster. * * @param ctx PROJ context, or NULL for default context * @param auth_name Authority name, used to restrict the search. * Or NULL for all authorities. * @param params Additional criteria, or NULL. If not-NULL, params SHOULD * have been allocated by proj_get_crs_list_parameters_create(), as the * PROJ_CRS_LIST_PARAMETERS structure might grow over time. * @param out_result_count Output parameter pointing to an integer to receive * the size of the result list. Might be NULL * @return an array of PROJ_CRS_INFO* pointers to be freed with * proj_crs_info_list_destroy(), or NULL in case of error. */ PROJ_CRS_INFO ** proj_get_crs_info_list_from_database(PJ_CONTEXT *ctx, const char *auth_name, const PROJ_CRS_LIST_PARAMETERS *params, int *out_result_count) { SANITIZE_CTX(ctx); PROJ_CRS_INFO **ret = nullptr; int i = 0; try { auto dbContext = getDBcontext(ctx); const std::string authName = auth_name ? auth_name : ""; auto actualAuthNames = dbContext->getVersionedAuthoritiesFromName(authName); if (actualAuthNames.empty()) actualAuthNames.push_back(authName); std::list<AuthorityFactory::CRSInfo> concatList; for (const auto &actualAuthName : actualAuthNames) { auto factory = AuthorityFactory::create(dbContext, actualAuthName); auto list = factory->getCRSInfoList(); concatList.splice(concatList.end(), std::move(list)); } ret = new PROJ_CRS_INFO *[concatList.size() + 1]; GeographicBoundingBoxPtr bbox; if (params && params->bbox_valid) { bbox = GeographicBoundingBox::create( params->west_lon_degree, params->south_lat_degree, params->east_lon_degree, params->north_lat_degree) .as_nullable(); } for (const auto &info : concatList) { auto type = PJ_TYPE_CRS; if (info.type == AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS) { type = PJ_TYPE_GEOGRAPHIC_2D_CRS; } else if (info.type == AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS) { type = PJ_TYPE_GEOGRAPHIC_3D_CRS; } else if (info.type == AuthorityFactory::ObjectType::GEOCENTRIC_CRS) { type = PJ_TYPE_GEOCENTRIC_CRS; } else if (info.type == AuthorityFactory::ObjectType::GEODETIC_CRS) { type = PJ_TYPE_GEODETIC_CRS; } else if (info.type == AuthorityFactory::ObjectType::PROJECTED_CRS) { type = PJ_TYPE_PROJECTED_CRS; } else if (info.type == AuthorityFactory::ObjectType::VERTICAL_CRS) { type = PJ_TYPE_VERTICAL_CRS; } else if (info.type == AuthorityFactory::ObjectType::COMPOUND_CRS) { type = PJ_TYPE_COMPOUND_CRS; } if (params && params->typesCount) { bool typeValid = false; for (size_t j = 0; j < params->typesCount; j++) { if (params->types[j] == type) { typeValid = true; break; } else if (params->types[j] == PJ_TYPE_GEOGRAPHIC_CRS && (type == PJ_TYPE_GEOGRAPHIC_2D_CRS || type == PJ_TYPE_GEOGRAPHIC_3D_CRS)) { typeValid = true; break; } else if (params->types[j] == PJ_TYPE_GEODETIC_CRS && (type == PJ_TYPE_GEOCENTRIC_CRS || type == PJ_TYPE_GEOGRAPHIC_2D_CRS || type == PJ_TYPE_GEOGRAPHIC_3D_CRS)) { typeValid = true; break; } } if (!typeValid) { continue; } } if (params && !params->allow_deprecated && info.deprecated) { continue; } if (params && params->bbox_valid) { if (!info.bbox_valid) { continue; } if (info.west_lon_degree <= info.east_lon_degree && params->west_lon_degree <= params->east_lon_degree) { if (params->crs_area_of_use_contains_bbox) { if (params->west_lon_degree < info.west_lon_degree || params->east_lon_degree > info.east_lon_degree || params->south_lat_degree < info.south_lat_degree || params->north_lat_degree > info.north_lat_degree) { continue; } } else { if (info.east_lon_degree < params->west_lon_degree || info.west_lon_degree > params->east_lon_degree || info.north_lat_degree < params->south_lat_degree || info.south_lat_degree > params->north_lat_degree) { continue; } } } else { auto crsExtent = GeographicBoundingBox::create( info.west_lon_degree, info.south_lat_degree, info.east_lon_degree, info.north_lat_degree); if (params->crs_area_of_use_contains_bbox) { if (!crsExtent->contains(NN_NO_CHECK(bbox))) { continue; } } else { if (!bbox->intersects(crsExtent)) { continue; } } } } if (params && params->celestial_body_name && params->celestial_body_name != info.celestialBodyName) { continue; } ret[i] = new PROJ_CRS_INFO; ret[i]->auth_name = pj_strdup(info.authName.c_str()); ret[i]->code = pj_strdup(info.code.c_str()); ret[i]->name = pj_strdup(info.name.c_str()); ret[i]->type = type; ret[i]->deprecated = info.deprecated; ret[i]->bbox_valid = info.bbox_valid; ret[i]->west_lon_degree = info.west_lon_degree; ret[i]->south_lat_degree = info.south_lat_degree; ret[i]->east_lon_degree = info.east_lon_degree; ret[i]->north_lat_degree = info.north_lat_degree; ret[i]->area_name = pj_strdup(info.areaName.c_str()); ret[i]->projection_method_name = info.projectionMethodName.empty() ? nullptr : pj_strdup(info.projectionMethodName.c_str()); ret[i]->celestial_body_name = pj_strdup(info.celestialBodyName.c_str()); i++; } ret[i] = nullptr; if (out_result_count) *out_result_count = i; return ret; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); if (ret) { ret[i + 1] = nullptr; proj_crs_info_list_destroy(ret); } if (out_result_count) *out_result_count = 0; } return nullptr; } // --------------------------------------------------------------------------- /** \brief Destroy the result returned by * proj_get_crs_info_list_from_database(). */ void proj_crs_info_list_destroy(PROJ_CRS_INFO **list) { if (list) { for (int i = 0; list[i] != nullptr; i++) { free(list[i]->auth_name); free(list[i]->code); free(list[i]->name); free(list[i]->area_name); free(list[i]->projection_method_name); free(list[i]->celestial_body_name); delete list[i]; } delete[] list; } } // --------------------------------------------------------------------------- /** \brief Enumerate units from the database, taking into account various * criteria. * * The returned object is an array of PROJ_UNIT_INFO* pointers, whose last * entry is NULL. This array should be freed with proj_unit_list_destroy() * * @param ctx PROJ context, or NULL for default context * @param auth_name Authority name, used to restrict the search. * Or NULL for all authorities. * @param category Filter by category, if this parameter is not NULL. Category * is one of "linear", "linear_per_time", "angular", "angular_per_time", * "scale", "scale_per_time" or "time" * @param allow_deprecated whether we should return deprecated objects as well. * @param out_result_count Output parameter pointing to an integer to receive * the size of the result list. Might be NULL * @return an array of PROJ_UNIT_INFO* pointers to be freed with * proj_unit_list_destroy(), or NULL in case of error. * * @since 7.1 */ PROJ_UNIT_INFO **proj_get_units_from_database(PJ_CONTEXT *ctx, const char *auth_name, const char *category, int allow_deprecated, int *out_result_count) { SANITIZE_CTX(ctx); PROJ_UNIT_INFO **ret = nullptr; int i = 0; try { auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name ? auth_name : ""); auto list = factory->getUnitList(); ret = new PROJ_UNIT_INFO *[list.size() + 1]; for (const auto &info : list) { if (category && info.category != category) { continue; } if (!allow_deprecated && info.deprecated) { continue; } ret[i] = new PROJ_UNIT_INFO; ret[i]->auth_name = pj_strdup(info.authName.c_str()); ret[i]->code = pj_strdup(info.code.c_str()); ret[i]->name = pj_strdup(info.name.c_str()); ret[i]->category = pj_strdup(info.category.c_str()); ret[i]->conv_factor = info.convFactor; ret[i]->proj_short_name = info.projShortName.empty() ? nullptr : pj_strdup(info.projShortName.c_str()); ret[i]->deprecated = info.deprecated; i++; } ret[i] = nullptr; if (out_result_count) *out_result_count = i; return ret; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); if (ret) { ret[i + 1] = nullptr; proj_unit_list_destroy(ret); } if (out_result_count) *out_result_count = 0; } return nullptr; } // --------------------------------------------------------------------------- /** \brief Destroy the result returned by * proj_get_units_from_database(). * * @since 7.1 */ void proj_unit_list_destroy(PROJ_UNIT_INFO **list) { if (list) { for (int i = 0; list[i] != nullptr; i++) { free(list[i]->auth_name); free(list[i]->code); free(list[i]->name); free(list[i]->category); free(list[i]->proj_short_name); delete list[i]; } delete[] list; } } // --------------------------------------------------------------------------- /** \brief Return the Conversion of a DerivedCRS (such as a ProjectedCRS), * or the Transformation from the baseCRS to the hubCRS of a BoundCRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type DerivedCRS or BoundCRSs (must not be NULL) * @return Object of type SingleOperation that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_crs_get_coordoperation(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } SingleOperationPtr co; auto derivedCRS = dynamic_cast<const DerivedCRS *>(crs->iso_obj.get()); if (derivedCRS) { co = derivedCRS->derivingConversion().as_nullable(); } else { auto boundCRS = dynamic_cast<const BoundCRS *>(crs->iso_obj.get()); if (boundCRS) { co = boundCRS->transformation().as_nullable(); } else { proj_log_error(ctx, __FUNCTION__, "Object is not a DerivedCRS or BoundCRS"); return nullptr; } } return pj_obj_create(ctx, NN_NO_CHECK(co)); } // --------------------------------------------------------------------------- /** \brief Return information on the operation method of the SingleOperation. * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type SingleOperation (typically a Conversion * or Transformation) (must not be NULL) * @param out_method_name Pointer to a string value to store the method * (projection) name. or NULL * @param out_method_auth_name Pointer to a string value to store the method * authority name. or NULL * @param out_method_code Pointer to a string value to store the method * code. or NULL * @return TRUE in case of success. */ int proj_coordoperation_get_method_info(PJ_CONTEXT *ctx, const PJ *coordoperation, const char **out_method_name, const char **out_method_auth_name, const char **out_method_code) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto singleOp = dynamic_cast<const SingleOperation *>(coordoperation->iso_obj.get()); if (!singleOp) { proj_log_error(ctx, __FUNCTION__, "Object is not a DerivedCRS or BoundCRS"); return false; } const auto &method = singleOp->method(); const auto &method_ids = method->identifiers(); if (out_method_name) { *out_method_name = method->name()->description()->c_str(); } if (out_method_auth_name) { if (!method_ids.empty()) { *out_method_auth_name = method_ids[0]->codeSpace()->c_str(); } else { *out_method_auth_name = nullptr; } } if (out_method_code) { if (!method_ids.empty()) { *out_method_code = method_ids[0]->code().c_str(); } else { *out_method_code = nullptr; } } return true; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static PropertyMap createPropertyMapName(const char *c_name, const char *auth_name = nullptr, const char *code = nullptr) { std::string name(c_name ? c_name : "unnamed"); PropertyMap properties; if (ends_with(name, " (deprecated)")) { name.resize(name.size() - strlen(" (deprecated)")); properties.set(common::IdentifiedObject::DEPRECATED_KEY, true); } if (auth_name && code) { properties.set(metadata::Identifier::CODESPACE_KEY, auth_name); properties.set(metadata::Identifier::CODE_KEY, code); } return properties.set(common::IdentifiedObject::NAME_KEY, name); } // --------------------------------------------------------------------------- static UnitOfMeasure createLinearUnit(const char *name, double convFactor, const char *unit_auth_name = nullptr, const char *unit_code = nullptr) { return name == nullptr ? UnitOfMeasure::METRE : UnitOfMeasure(name, convFactor, UnitOfMeasure::Type::LINEAR, unit_auth_name ? unit_auth_name : "", unit_code ? unit_code : ""); } // --------------------------------------------------------------------------- static UnitOfMeasure createAngularUnit(const char *name, double convFactor, const char *unit_auth_name = nullptr, const char *unit_code = nullptr) { return name ? (ci_equal(name, "degree") ? UnitOfMeasure::DEGREE : ci_equal(name, "grad") ? UnitOfMeasure::GRAD : UnitOfMeasure(name, convFactor, UnitOfMeasure::Type::ANGULAR, unit_auth_name ? unit_auth_name : "", unit_code ? unit_code : "")) : UnitOfMeasure::DEGREE; } // --------------------------------------------------------------------------- static GeodeticReferenceFrameNNPtr createGeodeticReferenceFrame( PJ_CONTEXT *ctx, const char *datum_name, const char *ellps_name, double semi_major_metre, double inv_flattening, const char *prime_meridian_name, double prime_meridian_offset, const char *angular_units, double angular_units_conv) { const UnitOfMeasure angUnit( createAngularUnit(angular_units, angular_units_conv)); auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); auto body = Ellipsoid::guessBodyName(dbContext, semi_major_metre); auto ellpsName = createPropertyMapName(ellps_name); auto ellps = inv_flattening != 0.0 ? Ellipsoid::createFlattenedSphere( ellpsName, Length(semi_major_metre), Scale(inv_flattening), body) : Ellipsoid::createSphere(ellpsName, Length(semi_major_metre), body); auto pm = PrimeMeridian::create( PropertyMap().set( common::IdentifiedObject::NAME_KEY, prime_meridian_name ? prime_meridian_name : prime_meridian_offset == 0.0 ? (ellps->celestialBody() == Ellipsoid::EARTH ? PrimeMeridian::GREENWICH->nameStr().c_str() : PrimeMeridian::REFERENCE_MERIDIAN->nameStr().c_str()) : "unnamed"), Angle(prime_meridian_offset, angUnit)); std::string datumName(datum_name ? datum_name : "unnamed"); if (datumName == "WGS_1984") { datumName = GeodeticReferenceFrame::EPSG_6326->nameStr(); } else if (datumName.find('_') != std::string::npos) { // Likely coming from WKT1 if (dbContext) { auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext), std::string()); auto res = authFactory->createObjectsFromName( datumName, {AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, true, 1); if (!res.empty()) { const auto &refDatum = res.front(); if (metadata::Identifier::isEquivalentName( datumName.c_str(), refDatum->nameStr().c_str())) { datumName = refDatum->nameStr(); } else if (refDatum->identifiers().size() == 1) { const auto &id = refDatum->identifiers()[0]; const auto aliases = authFactory->databaseContext()->getAliases( *id->codeSpace(), id->code(), refDatum->nameStr(), "geodetic_datum", std::string()); for (const auto &alias : aliases) { if (metadata::Identifier::isEquivalentName( datumName.c_str(), alias.c_str())) { datumName = refDatum->nameStr(); break; } } } } } } return GeodeticReferenceFrame::create( createPropertyMapName(datumName.c_str()), ellps, util::optional<std::string>(), pm); } //! @endcond // --------------------------------------------------------------------------- /** \brief Create a GeographicCRS. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param datum_name Name of the GeodeticReferenceFrame. Or NULL * @param ellps_name Name of the Ellipsoid. Or NULL * @param semi_major_metre Ellipsoid semi-major axis, in metres. * @param inv_flattening Ellipsoid inverse flattening. Or 0 for a sphere. * @param prime_meridian_name Name of the PrimeMeridian. Or NULL * @param prime_meridian_offset Offset of the prime meridian, expressed in the * specified angular units. * @param pm_angular_units Name of the angular units. Or NULL for Degree * @param pm_angular_units_conv Conversion factor from the angular unit to * radian. * Or * 0 for Degree if pm_angular_units == NULL. Otherwise should be not NULL * @param ellipsoidal_cs Coordinate system. Must not be NULL. * * @return Object of type GeographicCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_geographic_crs(PJ_CONTEXT *ctx, const char *crs_name, const char *datum_name, const char *ellps_name, double semi_major_metre, double inv_flattening, const char *prime_meridian_name, double prime_meridian_offset, const char *pm_angular_units, double pm_angular_units_conv, PJ *ellipsoidal_cs) { SANITIZE_CTX(ctx); auto cs = std::dynamic_pointer_cast<EllipsoidalCS>(ellipsoidal_cs->iso_obj); if (!cs) { return nullptr; } try { auto datum = createGeodeticReferenceFrame( ctx, datum_name, ellps_name, semi_major_metre, inv_flattening, prime_meridian_name, prime_meridian_offset, pm_angular_units, pm_angular_units_conv); auto geogCRS = GeographicCRS::create(createPropertyMapName(crs_name), datum, NN_NO_CHECK(cs)); return pj_obj_create(ctx, geogCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Create a GeographicCRS. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param datum_or_datum_ensemble Datum or DatumEnsemble (DatumEnsemble possible * since 7.2). Must not be NULL. * @param ellipsoidal_cs Coordinate system. Must not be NULL. * * @return Object of type GeographicCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_geographic_crs_from_datum(PJ_CONTEXT *ctx, const char *crs_name, PJ *datum_or_datum_ensemble, PJ *ellipsoidal_cs) { SANITIZE_CTX(ctx); if (datum_or_datum_ensemble == nullptr) { proj_log_error(ctx, __FUNCTION__, "Missing input datum_or_datum_ensemble"); return nullptr; } auto l_datum = std::dynamic_pointer_cast<GeodeticReferenceFrame>( datum_or_datum_ensemble->iso_obj); auto l_datum_ensemble = std::dynamic_pointer_cast<DatumEnsemble>( datum_or_datum_ensemble->iso_obj); auto cs = std::dynamic_pointer_cast<EllipsoidalCS>(ellipsoidal_cs->iso_obj); if (!cs) { return nullptr; } try { auto geogCRS = GeographicCRS::create(createPropertyMapName(crs_name), l_datum, l_datum_ensemble, NN_NO_CHECK(cs)); return pj_obj_create(ctx, geogCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Create a GeodeticCRS of geocentric type. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param datum_name Name of the GeodeticReferenceFrame. Or NULL * @param ellps_name Name of the Ellipsoid. Or NULL * @param semi_major_metre Ellipsoid semi-major axis, in metres. * @param inv_flattening Ellipsoid inverse flattening. Or 0 for a sphere. * @param prime_meridian_name Name of the PrimeMeridian. Or NULL * @param prime_meridian_offset Offset of the prime meridian, expressed in the * specified angular units. * @param angular_units Name of the angular units. Or NULL for Degree * @param angular_units_conv Conversion factor from the angular unit to radian. * Or * 0 for Degree if angular_units == NULL. Otherwise should be not NULL * @param linear_units Name of the linear units. Or NULL for Metre * @param linear_units_conv Conversion factor from the linear unit to metre. Or * 0 for Metre if linear_units == NULL. Otherwise should be not NULL * * @return Object of type GeodeticCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_geocentric_crs( PJ_CONTEXT *ctx, const char *crs_name, const char *datum_name, const char *ellps_name, double semi_major_metre, double inv_flattening, const char *prime_meridian_name, double prime_meridian_offset, const char *angular_units, double angular_units_conv, const char *linear_units, double linear_units_conv) { SANITIZE_CTX(ctx); try { const UnitOfMeasure linearUnit( createLinearUnit(linear_units, linear_units_conv)); auto datum = createGeodeticReferenceFrame( ctx, datum_name, ellps_name, semi_major_metre, inv_flattening, prime_meridian_name, prime_meridian_offset, angular_units, angular_units_conv); auto geodCRS = GeodeticCRS::create(createPropertyMapName(crs_name), datum, cs::CartesianCS::createGeocentric(linearUnit)); return pj_obj_create(ctx, geodCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Create a GeodeticCRS of geocentric type. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param datum_or_datum_ensemble Datum or DatumEnsemble (DatumEnsemble possible * since 7.2). Must not be NULL. * @param linear_units Name of the linear units. Or NULL for Metre * @param linear_units_conv Conversion factor from the linear unit to metre. Or * 0 for Metre if linear_units == NULL. Otherwise should be not NULL * * @return Object of type GeodeticCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_geocentric_crs_from_datum(PJ_CONTEXT *ctx, const char *crs_name, const PJ *datum_or_datum_ensemble, const char *linear_units, double linear_units_conv) { SANITIZE_CTX(ctx); if (datum_or_datum_ensemble == nullptr) { proj_log_error(ctx, __FUNCTION__, "Missing input datum_or_datum_ensemble"); return nullptr; } auto l_datum = std::dynamic_pointer_cast<GeodeticReferenceFrame>( datum_or_datum_ensemble->iso_obj); auto l_datum_ensemble = std::dynamic_pointer_cast<DatumEnsemble>( datum_or_datum_ensemble->iso_obj); try { const UnitOfMeasure linearUnit( createLinearUnit(linear_units, linear_units_conv)); auto geodCRS = GeodeticCRS::create( createPropertyMapName(crs_name), l_datum, l_datum_ensemble, cs::CartesianCS::createGeocentric(linearUnit)); return pj_obj_create(ctx, geodCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Create a DerivedGeograhicCRS. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param base_geographic_crs Base Geographic CRS. Must not be NULL. * @param conversion Conversion from the base Geographic to the * DerivedGeograhicCRS. Must not be NULL. * @param ellipsoidal_cs Coordinate system. Must not be NULL. * * @return Object of type GeodeticCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. * * @since 7.0 */ PJ *proj_create_derived_geographic_crs(PJ_CONTEXT *ctx, const char *crs_name, const PJ *base_geographic_crs, const PJ *conversion, const PJ *ellipsoidal_cs) { SANITIZE_CTX(ctx); auto base_crs = std::dynamic_pointer_cast<GeographicCRS>(base_geographic_crs->iso_obj); auto conversion_cpp = std::dynamic_pointer_cast<Conversion>(conversion->iso_obj); auto cs = std::dynamic_pointer_cast<EllipsoidalCS>(ellipsoidal_cs->iso_obj); if (!base_crs || !conversion_cpp || !cs) { return nullptr; } try { auto derivedCRS = DerivedGeographicCRS::create( createPropertyMapName(crs_name), NN_NO_CHECK(base_crs), NN_NO_CHECK(conversion_cpp), NN_NO_CHECK(cs)); return pj_obj_create(ctx, derivedCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Return whether a CRS is a Derived CRS. * * @param ctx PROJ context, or NULL for default context * @param crs CRS. Must not be NULL. * * @return whether a CRS is a Derived CRS. * * @since 7.0 */ int proj_is_derived_crs(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); return dynamic_cast<DerivedCRS *>(crs->iso_obj.get()) != nullptr; } // --------------------------------------------------------------------------- /** \brief Create a VerticalCRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param datum_name Name of the VerticalReferenceFrame. Or NULL * @param linear_units Name of the linear units. Or NULL for Metre * @param linear_units_conv Conversion factor from the linear unit to metre. Or * 0 for Metre if linear_units == NULL. Otherwise should be not NULL * * @return Object of type VerticalCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_vertical_crs(PJ_CONTEXT *ctx, const char *crs_name, const char *datum_name, const char *linear_units, double linear_units_conv) { return proj_create_vertical_crs_ex( ctx, crs_name, datum_name, nullptr, nullptr, linear_units, linear_units_conv, nullptr, nullptr, nullptr, nullptr, nullptr); } // --------------------------------------------------------------------------- /** \brief Create a VerticalCRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * This is an extended (_ex) version of proj_create_vertical_crs() that adds * the capability of defining a geoid model. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param datum_name Name of the VerticalReferenceFrame. Or NULL * @param datum_auth_name Authority name of the VerticalReferenceFrame. Or NULL * @param datum_code Code of the VerticalReferenceFrame. Or NULL * @param linear_units Name of the linear units. Or NULL for Metre * @param linear_units_conv Conversion factor from the linear unit to metre. Or * 0 for Metre if linear_units == NULL. Otherwise should be not NULL * @param geoid_model_name Geoid model name, or NULL. Can be a name from the * geoid_model name or a string "PROJ foo.gtx" * @param geoid_model_auth_name Authority name of the transformation for * the geoid model. or NULL * @param geoid_model_code Code of the transformation for * the geoid model. or NULL * @param geoid_geog_crs Geographic CRS for the geoid transformation, or NULL. * @param options NULL-terminated list of strings with "KEY=VALUE" format. or * NULL. * The currently recognized option is ACCURACY=value, where value is in metre. * @return Object of type VerticalCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_vertical_crs_ex( PJ_CONTEXT *ctx, const char *crs_name, const char *datum_name, const char *datum_auth_name, const char *datum_code, const char *linear_units, double linear_units_conv, const char *geoid_model_name, const char *geoid_model_auth_name, const char *geoid_model_code, const PJ *geoid_geog_crs, const char *const *options) { SANITIZE_CTX(ctx); try { const UnitOfMeasure linearUnit( createLinearUnit(linear_units, linear_units_conv)); auto datum = VerticalReferenceFrame::create( createPropertyMapName(datum_name, datum_auth_name, datum_code)); auto props = createPropertyMapName(crs_name); auto cs = cs::VerticalCS::createGravityRelatedHeight(linearUnit); if (geoid_model_name) { auto propsModel = createPropertyMapName( geoid_model_name, geoid_model_auth_name, geoid_model_code); const auto vertCRSWithoutGeoid = VerticalCRS::create(props, datum, cs); const auto interpCRS = geoid_geog_crs && std::dynamic_pointer_cast<GeographicCRS>( geoid_geog_crs->iso_obj) ? std::dynamic_pointer_cast<CRS>(geoid_geog_crs->iso_obj) : nullptr; std::vector<metadata::PositionalAccuracyNNPtr> accuracies; for (auto iter = options; iter && iter[0]; ++iter) { const char *value; if ((value = getOptionValue(*iter, "ACCURACY="))) { accuracies.emplace_back( metadata::PositionalAccuracy::create(value)); } } const auto model(Transformation::create( propsModel, vertCRSWithoutGeoid, GeographicCRS::EPSG_4979, // arbitrarily chosen. Ignored interpCRS, OperationMethod::create(PropertyMap(), std::vector<OperationParameterNNPtr>()), {}, accuracies)); props.set("GEOID_MODEL", model); } auto vertCRS = VerticalCRS::create(props, datum, cs); return pj_obj_create(ctx, vertCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Create a CompoundCRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name Name of the GeographicCRS. Or NULL * @param horiz_crs Horizontal CRS. must not be NULL. * @param vert_crs Vertical CRS. must not be NULL. * * @return Object of type CompoundCRS that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_compound_crs(PJ_CONTEXT *ctx, const char *crs_name, PJ *horiz_crs, PJ *vert_crs) { SANITIZE_CTX(ctx); if (!horiz_crs || !vert_crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_horiz_crs = std::dynamic_pointer_cast<CRS>(horiz_crs->iso_obj); if (!l_horiz_crs) { return nullptr; } auto l_vert_crs = std::dynamic_pointer_cast<CRS>(vert_crs->iso_obj); if (!l_vert_crs) { return nullptr; } try { auto compoundCRS = CompoundCRS::create( createPropertyMapName(crs_name), {NN_NO_CHECK(l_horiz_crs), NN_NO_CHECK(l_vert_crs)}); return pj_obj_create(ctx, compoundCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Return a copy of the object with its name changed * * Currently, only implemented on CRS objects. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS. Must not be NULL * @param name New name. Must not be NULL * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_alter_name(PJ_CONTEXT *ctx, const PJ *obj, const char *name) { SANITIZE_CTX(ctx); if (!obj || !name) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto crs = dynamic_cast<const CRS *>(obj->iso_obj.get()); if (!crs) { return nullptr; } try { return pj_obj_create(ctx, crs->alterName(name)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Return a copy of the object with its identifier changed/set * * Currently, only implemented on CRS objects. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS. Must not be NULL * @param auth_name Authority name. Must not be NULL * @param code Code. Must not be NULL * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_alter_id(PJ_CONTEXT *ctx, const PJ *obj, const char *auth_name, const char *code) { SANITIZE_CTX(ctx); if (!obj || !auth_name || !code) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto crs = dynamic_cast<const CRS *>(obj->iso_obj.get()); if (!crs) { return nullptr; } try { return pj_obj_create(ctx, crs->alterId(auth_name, code)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Return a copy of the CRS with its geodetic CRS changed * * Currently, when obj is a GeodeticCRS, it returns a clone of new_geod_crs * When obj is a ProjectedCRS, it replaces its base CRS with new_geod_crs. * When obj is a CompoundCRS, it replaces the GeodeticCRS part of the horizontal * CRS with new_geod_crs. * In other cases, it returns a clone of obj. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS. Must not be NULL * @param new_geod_crs Object of type GeodeticCRS. Must not be NULL * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_crs_alter_geodetic_crs(PJ_CONTEXT *ctx, const PJ *obj, const PJ *new_geod_crs) { SANITIZE_CTX(ctx); if (!obj || !new_geod_crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_new_geod_crs = std::dynamic_pointer_cast<GeodeticCRS>(new_geod_crs->iso_obj); if (!l_new_geod_crs) { proj_log_error(ctx, __FUNCTION__, "new_geod_crs is not a GeodeticCRS"); return nullptr; } auto crs = dynamic_cast<const CRS *>(obj->iso_obj.get()); if (!crs) { proj_log_error(ctx, __FUNCTION__, "obj is not a CRS"); return nullptr; } try { return pj_obj_create( ctx, crs->alterGeodeticCRS(NN_NO_CHECK(l_new_geod_crs))); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Return a copy of the CRS with its angular units changed * * The CRS must be or contain a GeographicCRS. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS. Must not be NULL * @param angular_units Name of the angular units. Or NULL for Degree * @param angular_units_conv Conversion factor from the angular unit to radian. * Or 0 for Degree if angular_units == NULL. Otherwise should be not NULL * @param unit_auth_name Unit authority name. Or NULL. * @param unit_code Unit code. Or NULL. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_crs_alter_cs_angular_unit(PJ_CONTEXT *ctx, const PJ *obj, const char *angular_units, double angular_units_conv, const char *unit_auth_name, const char *unit_code) { SANITIZE_CTX(ctx); auto geodCRS = proj_crs_get_geodetic_crs(ctx, obj); if (!geodCRS) { return nullptr; } auto geogCRS = dynamic_cast<const GeographicCRS *>(geodCRS->iso_obj.get()); if (!geogCRS) { proj_destroy(geodCRS); return nullptr; } PJ *geogCRSAltered = nullptr; try { const UnitOfMeasure angUnit(createAngularUnit( angular_units, angular_units_conv, unit_auth_name, unit_code)); geogCRSAltered = pj_obj_create( ctx, GeographicCRS::create( createPropertyMapName(proj_get_name(geodCRS)), geogCRS->datum(), geogCRS->datumEnsemble(), geogCRS->coordinateSystem()->alterAngularUnit(angUnit))); proj_destroy(geodCRS); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); proj_destroy(geodCRS); return nullptr; } auto ret = proj_crs_alter_geodetic_crs(ctx, obj, geogCRSAltered); proj_destroy(geogCRSAltered); return ret; } // --------------------------------------------------------------------------- /** \brief Return a copy of the CRS with the linear units of its coordinate * system changed * * The CRS must be or contain a ProjectedCRS, VerticalCRS or a GeocentricCRS. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS. Must not be NULL * @param linear_units Name of the linear units. Or NULL for Metre * @param linear_units_conv Conversion factor from the linear unit to metre. Or * 0 for Metre if linear_units == NULL. Otherwise should be not NULL * @param unit_auth_name Unit authority name. Or NULL. * @param unit_code Unit code. Or NULL. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_crs_alter_cs_linear_unit(PJ_CONTEXT *ctx, const PJ *obj, const char *linear_units, double linear_units_conv, const char *unit_auth_name, const char *unit_code) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto crs = dynamic_cast<const CRS *>(obj->iso_obj.get()); if (!crs) { return nullptr; } try { const UnitOfMeasure linearUnit(createLinearUnit( linear_units, linear_units_conv, unit_auth_name, unit_code)); return pj_obj_create(ctx, crs->alterCSLinearUnit(linearUnit)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Return a copy of the CRS with the linear units of the parameters * of its conversion modified. * * The CRS must be or contain a ProjectedCRS, VerticalCRS or a GeocentricCRS. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type ProjectedCRS. Must not be NULL * @param linear_units Name of the linear units. Or NULL for Metre * @param linear_units_conv Conversion factor from the linear unit to metre. Or * 0 for Metre if linear_units == NULL. Otherwise should be not NULL * @param unit_auth_name Unit authority name. Or NULL. * @param unit_code Unit code. Or NULL. * @param convert_to_new_unit TRUE if existing values should be converted from * their current unit to the new unit. If FALSE, their value will be left * unchanged and the unit overridden (so the resulting CRS will not be * equivalent to the original one for reprojection purposes). * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_crs_alter_parameters_linear_unit(PJ_CONTEXT *ctx, const PJ *obj, const char *linear_units, double linear_units_conv, const char *unit_auth_name, const char *unit_code, int convert_to_new_unit) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto crs = dynamic_cast<const ProjectedCRS *>(obj->iso_obj.get()); if (!crs) { return nullptr; } try { const UnitOfMeasure linearUnit(createLinearUnit( linear_units, linear_units_conv, unit_auth_name, unit_code)); return pj_obj_create(ctx, crs->alterParametersLinearUnit( linearUnit, convert_to_new_unit == TRUE)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Create a 3D CRS from an existing 2D CRS. * * The new axis will be ellipsoidal height, oriented upwards, and with metre * units. * * See osgeo::proj::crs::CRS::promoteTo3D(). * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_3D_name CRS name. Or NULL (in which case the name of crs_2D * will be used) * @param crs_2D 2D CRS to be "promoted" to 3D. Must not be NULL. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. * @since 6.3 */ PJ *proj_crs_promote_to_3D(PJ_CONTEXT *ctx, const char *crs_3D_name, const PJ *crs_2D) { SANITIZE_CTX(ctx); if (!crs_2D) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto cpp_2D_crs = dynamic_cast<const CRS *>(crs_2D->iso_obj.get()); if (!cpp_2D_crs) { auto coordinateMetadata = dynamic_cast<const CoordinateMetadata *>(crs_2D->iso_obj.get()); if (!coordinateMetadata) { proj_log_error(ctx, __FUNCTION__, "crs_2D is not a CRS or a CoordinateMetadata"); return nullptr; } try { auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); auto crs = coordinateMetadata->crs(); auto crs_3D = crs->promoteTo3D( crs_3D_name ? std::string(crs_3D_name) : crs->nameStr(), dbContext); if (coordinateMetadata->coordinateEpoch().has_value()) { return pj_obj_create( ctx, CoordinateMetadata::create( crs_3D, coordinateMetadata->coordinateEpochAsDecimalYear(), dbContext)); } else { return pj_obj_create(ctx, CoordinateMetadata::create(crs_3D)); } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } else { try { auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); return pj_obj_create(ctx, cpp_2D_crs->promoteTo3D( crs_3D_name ? std::string(crs_3D_name) : cpp_2D_crs->nameStr(), dbContext)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } } // --------------------------------------------------------------------------- /** \brief Create a projected 3D CRS from an existing projected 2D CRS. * * The passed projected_2D_crs is used so that its name is replaced by * crs_name and its base geographic CRS is replaced by geog_3D_crs. The vertical * axis of geog_3D_crs (ellipsoidal height) will be added as the 3rd axis of * the resulting projected 3D CRS. * Normally, the passed geog_3D_crs should be the 3D counterpart of the original * 2D base geographic CRS of projected_2D_crs, but such no check is done. * * It is also possible to invoke this function with a NULL geog_3D_crs. In which * case, the existing base geographic 2D CRS of projected_2D_crs will be * automatically promoted to 3D by assuming a 3rd axis being an ellipsoidal * height, oriented upwards, and with metre units. This is equivalent to using * proj_crs_promote_to_3D(). * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name CRS name. Or NULL (in which case the name of projected_2D_crs * will be used) * @param projected_2D_crs Projected 2D CRS to be "promoted" to 3D. Must not be * NULL. * @param geog_3D_crs Base geographic 3D CRS for the new CRS. May be NULL. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. * @since 6.3 */ PJ *proj_crs_create_projected_3D_crs_from_2D(PJ_CONTEXT *ctx, const char *crs_name, const PJ *projected_2D_crs, const PJ *geog_3D_crs) { SANITIZE_CTX(ctx); if (!projected_2D_crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto cpp_projected_2D_crs = dynamic_cast<const ProjectedCRS *>(projected_2D_crs->iso_obj.get()); if (!cpp_projected_2D_crs) { proj_log_error(ctx, __FUNCTION__, "projected_2D_crs is not a Projected CRS"); return nullptr; } const auto &oldCS = cpp_projected_2D_crs->coordinateSystem(); const auto &oldCSAxisList = oldCS->axisList(); if (geog_3D_crs && geog_3D_crs->iso_obj) { auto cpp_geog_3D_CRS = std::dynamic_pointer_cast<GeographicCRS>(geog_3D_crs->iso_obj); if (!cpp_geog_3D_CRS) { proj_log_error(ctx, __FUNCTION__, "geog_3D_crs is not a Geographic CRS"); return nullptr; } const auto &geogCS = cpp_geog_3D_CRS->coordinateSystem(); const auto &geogCSAxisList = geogCS->axisList(); if (geogCSAxisList.size() != 3) { proj_log_error(ctx, __FUNCTION__, "geog_3D_crs is not a Geographic 3D CRS"); return nullptr; } try { auto newCS = cs::CartesianCS::create(PropertyMap(), oldCSAxisList[0], oldCSAxisList[1], geogCSAxisList[2]); return pj_obj_create( ctx, ProjectedCRS::create( createPropertyMapName( crs_name ? crs_name : cpp_projected_2D_crs->nameStr().c_str()), NN_NO_CHECK(cpp_geog_3D_CRS), cpp_projected_2D_crs->derivingConversion(), newCS)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } else { try { auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); return pj_obj_create(ctx, cpp_projected_2D_crs->promoteTo3D( crs_name ? std::string(crs_name) : cpp_projected_2D_crs->nameStr(), dbContext)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } } // --------------------------------------------------------------------------- /** \brief Create a 2D CRS from an existing 3D CRS. * * See osgeo::proj::crs::CRS::demoteTo2D(). * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_2D_name CRS name. Or NULL (in which case the name of crs_3D * will be used) * @param crs_3D 3D CRS to be "demoted" to 2D. Must not be NULL. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. * @since 6.3 */ PJ *proj_crs_demote_to_2D(PJ_CONTEXT *ctx, const char *crs_2D_name, const PJ *crs_3D) { SANITIZE_CTX(ctx); if (!crs_3D) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto cpp_3D_crs = dynamic_cast<const CRS *>(crs_3D->iso_obj.get()); if (!cpp_3D_crs) { proj_log_error(ctx, __FUNCTION__, "crs_3D is not a CRS"); return nullptr; } try { auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); return pj_obj_create( ctx, cpp_3D_crs->demoteTo2D(crs_2D_name ? std::string(crs_2D_name) : cpp_3D_crs->nameStr(), dbContext)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Instantiate a EngineeringCRS with just a name * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name CRS name. Or NULL. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_engineering_crs(PJ_CONTEXT *ctx, const char *crs_name) { SANITIZE_CTX(ctx); try { return pj_obj_create( ctx, EngineeringCRS::create( createPropertyMapName(crs_name), EngineeringDatum::create( createPropertyMapName(UNKNOWN_ENGINEERING_DATUM)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE))); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static void setSingleOperationElements( const char *name, const char *auth_name, const char *code, const char *method_name, const char *method_auth_name, const char *method_code, int param_count, const PJ_PARAM_DESCRIPTION *params, PropertyMap &propSingleOp, PropertyMap &propMethod, std::vector<OperationParameterNNPtr> &parameters, std::vector<ParameterValueNNPtr> &values) { propSingleOp.set(common::IdentifiedObject::NAME_KEY, name ? name : "unnamed"); if (auth_name && code) { propSingleOp.set(metadata::Identifier::CODESPACE_KEY, auth_name) .set(metadata::Identifier::CODE_KEY, code); } propMethod.set(common::IdentifiedObject::NAME_KEY, method_name ? method_name : "unnamed"); if (method_auth_name && method_code) { propMethod.set(metadata::Identifier::CODESPACE_KEY, method_auth_name) .set(metadata::Identifier::CODE_KEY, method_code); } for (int i = 0; i < param_count; i++) { PropertyMap propParam; propParam.set(common::IdentifiedObject::NAME_KEY, params[i].name ? params[i].name : "unnamed"); if (params[i].auth_name && params[i].code) { propParam .set(metadata::Identifier::CODESPACE_KEY, params[i].auth_name) .set(metadata::Identifier::CODE_KEY, params[i].code); } parameters.emplace_back(OperationParameter::create(propParam)); auto unit_type = UnitOfMeasure::Type::UNKNOWN; switch (params[i].unit_type) { case PJ_UT_ANGULAR: unit_type = UnitOfMeasure::Type::ANGULAR; break; case PJ_UT_LINEAR: unit_type = UnitOfMeasure::Type::LINEAR; break; case PJ_UT_SCALE: unit_type = UnitOfMeasure::Type::SCALE; break; case PJ_UT_TIME: unit_type = UnitOfMeasure::Type::TIME; break; case PJ_UT_PARAMETRIC: unit_type = UnitOfMeasure::Type::PARAMETRIC; break; } Measure measure( params[i].value, params[i].unit_type == PJ_UT_ANGULAR ? createAngularUnit(params[i].unit_name, params[i].unit_conv_factor) : params[i].unit_type == PJ_UT_LINEAR ? createLinearUnit(params[i].unit_name, params[i].unit_conv_factor) : UnitOfMeasure(params[i].unit_name ? params[i].unit_name : "unnamed", params[i].unit_conv_factor, unit_type)); values.emplace_back(ParameterValue::create(measure)); } } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a Conversion * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param name Conversion name. Or NULL. * @param auth_name Conversion authority name. Or NULL. * @param code Conversion code. Or NULL. * @param method_name Method name. Or NULL. * @param method_auth_name Method authority name. Or NULL. * @param method_code Method code. Or NULL. * @param param_count Number of parameters (size of params argument) * @param params Parameter descriptions (array of size param_count) * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_conversion(PJ_CONTEXT *ctx, const char *name, const char *auth_name, const char *code, const char *method_name, const char *method_auth_name, const char *method_code, int param_count, const PJ_PARAM_DESCRIPTION *params) { SANITIZE_CTX(ctx); try { PropertyMap propSingleOp; PropertyMap propMethod; std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; setSingleOperationElements( name, auth_name, code, method_name, method_auth_name, method_code, param_count, params, propSingleOp, propMethod, parameters, values); return pj_obj_create(ctx, Conversion::create(propSingleOp, propMethod, parameters, values)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Instantiate a Transformation * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param name Transformation name. Or NULL. * @param auth_name Transformation authority name. Or NULL. * @param code Transformation code. Or NULL. * @param source_crs Object of type CRS representing the source CRS. * Must not be NULL. * @param target_crs Object of type CRS representing the target CRS. * Must not be NULL. * @param interpolation_crs Object of type CRS representing the interpolation * CRS. Or NULL. * @param method_name Method name. Or NULL. * @param method_auth_name Method authority name. Or NULL. * @param method_code Method code. Or NULL. * @param param_count Number of parameters (size of params argument) * @param params Parameter descriptions (array of size param_count) * @param accuracy Accuracy of the transformation in meters. A negative * values means unknown. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_transformation(PJ_CONTEXT *ctx, const char *name, const char *auth_name, const char *code, PJ *source_crs, PJ *target_crs, PJ *interpolation_crs, const char *method_name, const char *method_auth_name, const char *method_code, int param_count, const PJ_PARAM_DESCRIPTION *params, double accuracy) { SANITIZE_CTX(ctx); if (!source_crs || !target_crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_sourceCRS = std::dynamic_pointer_cast<CRS>(source_crs->iso_obj); if (!l_sourceCRS) { proj_log_error(ctx, __FUNCTION__, "source_crs is not a CRS"); return nullptr; } auto l_targetCRS = std::dynamic_pointer_cast<CRS>(target_crs->iso_obj); if (!l_targetCRS) { proj_log_error(ctx, __FUNCTION__, "target_crs is not a CRS"); return nullptr; } CRSPtr l_interpolationCRS; if (interpolation_crs) { l_interpolationCRS = std::dynamic_pointer_cast<CRS>(interpolation_crs->iso_obj); if (!l_interpolationCRS) { proj_log_error(ctx, __FUNCTION__, "interpolation_crs is not a CRS"); return nullptr; } } try { PropertyMap propSingleOp; PropertyMap propMethod; std::vector<OperationParameterNNPtr> parameters; std::vector<ParameterValueNNPtr> values; setSingleOperationElements( name, auth_name, code, method_name, method_auth_name, method_code, param_count, params, propSingleOp, propMethod, parameters, values); std::vector<metadata::PositionalAccuracyNNPtr> accuracies; if (accuracy >= 0.0) { accuracies.emplace_back( PositionalAccuracy::create(toString(accuracy))); } return pj_obj_create( ctx, Transformation::create(propSingleOp, NN_NO_CHECK(l_sourceCRS), NN_NO_CHECK(l_targetCRS), l_interpolationCRS, propMethod, parameters, values, accuracies)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** * \brief Return an equivalent projection. * * Currently implemented: * <ul> * <li>EPSG_CODE_METHOD_MERCATOR_VARIANT_A (1SP) to * EPSG_CODE_METHOD_MERCATOR_VARIANT_B (2SP)</li> * <li>EPSG_CODE_METHOD_MERCATOR_VARIANT_B (2SP) to * EPSG_CODE_METHOD_MERCATOR_VARIANT_A (1SP)</li> * <li>EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP to * EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP</li> * <li>EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP to * EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP</li> * </ul> * * @param ctx PROJ context, or NULL for default context * @param conversion Object of type Conversion. Must not be NULL. * @param new_method_epsg_code EPSG code of the target method. Or 0 (in which * case new_method_name must be specified). * @param new_method_name EPSG or PROJ target method name. Or nullptr (in which * case new_method_epsg_code must be specified). * @return new conversion that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_convert_conversion_to_other_method(PJ_CONTEXT *ctx, const PJ *conversion, int new_method_epsg_code, const char *new_method_name) { SANITIZE_CTX(ctx); if (!conversion) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto conv = dynamic_cast<const Conversion *>(conversion->iso_obj.get()); if (!conv) { proj_log_error(ctx, __FUNCTION__, "not a Conversion"); return nullptr; } if (new_method_epsg_code == 0) { if (!new_method_name) { return nullptr; } if (metadata::Identifier::isEquivalentName( new_method_name, EPSG_NAME_METHOD_MERCATOR_VARIANT_A)) { new_method_epsg_code = EPSG_CODE_METHOD_MERCATOR_VARIANT_A; } else if (metadata::Identifier::isEquivalentName( new_method_name, EPSG_NAME_METHOD_MERCATOR_VARIANT_B)) { new_method_epsg_code = EPSG_CODE_METHOD_MERCATOR_VARIANT_B; } else if (metadata::Identifier::isEquivalentName( new_method_name, EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_1SP)) { new_method_epsg_code = EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP; } else if (metadata::Identifier::isEquivalentName( new_method_name, EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP)) { new_method_epsg_code = EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP; } } try { auto new_conv = conv->convertToOtherMethod(new_method_epsg_code); if (!new_conv) return nullptr; return pj_obj_create(ctx, NN_NO_CHECK(new_conv)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static CoordinateSystemAxisNNPtr createAxis(const PJ_AXIS_DESCRIPTION &axis) { const auto dir = axis.direction ? AxisDirection::valueOf(axis.direction) : nullptr; if (dir == nullptr) throw Exception("invalid value for axis direction"); auto unit_type = UnitOfMeasure::Type::UNKNOWN; switch (axis.unit_type) { case PJ_UT_ANGULAR: unit_type = UnitOfMeasure::Type::ANGULAR; break; case PJ_UT_LINEAR: unit_type = UnitOfMeasure::Type::LINEAR; break; case PJ_UT_SCALE: unit_type = UnitOfMeasure::Type::SCALE; break; case PJ_UT_TIME: unit_type = UnitOfMeasure::Type::TIME; break; case PJ_UT_PARAMETRIC: unit_type = UnitOfMeasure::Type::PARAMETRIC; break; } const common::UnitOfMeasure unit( axis.unit_type == PJ_UT_ANGULAR ? createAngularUnit(axis.unit_name, axis.unit_conv_factor) : axis.unit_type == PJ_UT_LINEAR ? createLinearUnit(axis.unit_name, axis.unit_conv_factor) : UnitOfMeasure(axis.unit_name ? axis.unit_name : "unnamed", axis.unit_conv_factor, unit_type)); return CoordinateSystemAxis::create( createPropertyMapName(axis.name), axis.abbreviation ? axis.abbreviation : std::string(), *dir, unit); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a CoordinateSystem. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param type Coordinate system type. * @param axis_count Number of axis * @param axis Axis description (array of size axis_count) * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_cs(PJ_CONTEXT *ctx, PJ_COORDINATE_SYSTEM_TYPE type, int axis_count, const PJ_AXIS_DESCRIPTION *axis) { SANITIZE_CTX(ctx); try { switch (type) { case PJ_CS_TYPE_UNKNOWN: return nullptr; case PJ_CS_TYPE_CARTESIAN: { if (axis_count == 2) { return pj_obj_create( ctx, CartesianCS::create(PropertyMap(), createAxis(axis[0]), createAxis(axis[1]))); } else if (axis_count == 3) { return pj_obj_create( ctx, CartesianCS::create(PropertyMap(), createAxis(axis[0]), createAxis(axis[1]), createAxis(axis[2]))); } break; } case PJ_CS_TYPE_ELLIPSOIDAL: { if (axis_count == 2) { return pj_obj_create( ctx, EllipsoidalCS::create(PropertyMap(), createAxis(axis[0]), createAxis(axis[1]))); } else if (axis_count == 3) { return pj_obj_create( ctx, EllipsoidalCS::create( PropertyMap(), createAxis(axis[0]), createAxis(axis[1]), createAxis(axis[2]))); } break; } case PJ_CS_TYPE_VERTICAL: { if (axis_count == 1) { return pj_obj_create( ctx, VerticalCS::create(PropertyMap(), createAxis(axis[0]))); } break; } case PJ_CS_TYPE_SPHERICAL: { if (axis_count == 3) { return pj_obj_create( ctx, EllipsoidalCS::create( PropertyMap(), createAxis(axis[0]), createAxis(axis[1]), createAxis(axis[2]))); } break; } case PJ_CS_TYPE_PARAMETRIC: { if (axis_count == 1) { return pj_obj_create( ctx, ParametricCS::create(PropertyMap(), createAxis(axis[0]))); } break; } case PJ_CS_TYPE_ORDINAL: { std::vector<CoordinateSystemAxisNNPtr> axisVector; for (int i = 0; i < axis_count; i++) { axisVector.emplace_back(createAxis(axis[i])); } return pj_obj_create(ctx, OrdinalCS::create(PropertyMap(), axisVector)); } case PJ_CS_TYPE_DATETIMETEMPORAL: { if (axis_count == 1) { return pj_obj_create( ctx, DateTimeTemporalCS::create(PropertyMap(), createAxis(axis[0]))); } break; } case PJ_CS_TYPE_TEMPORALCOUNT: { if (axis_count == 1) { return pj_obj_create( ctx, TemporalCountCS::create(PropertyMap(), createAxis(axis[0]))); } break; } case PJ_CS_TYPE_TEMPORALMEASURE: { if (axis_count == 1) { return pj_obj_create( ctx, TemporalMeasureCS::create(PropertyMap(), createAxis(axis[0]))); } break; } } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } proj_log_error(ctx, __FUNCTION__, "Wrong value for axis_count"); return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a CartesiansCS 2D * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param type Coordinate system type. * @param unit_name Unit name. * @param unit_conv_factor Unit conversion factor to SI. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_cartesian_2D_cs(PJ_CONTEXT *ctx, PJ_CARTESIAN_CS_2D_TYPE type, const char *unit_name, double unit_conv_factor) { SANITIZE_CTX(ctx); try { switch (type) { case PJ_CART2D_EASTING_NORTHING: return pj_obj_create( ctx, CartesianCS::createEastingNorthing( createLinearUnit(unit_name, unit_conv_factor))); case PJ_CART2D_NORTHING_EASTING: return pj_obj_create( ctx, CartesianCS::createNorthingEasting( createLinearUnit(unit_name, unit_conv_factor))); case PJ_CART2D_NORTH_POLE_EASTING_SOUTH_NORTHING_SOUTH: return pj_obj_create( ctx, CartesianCS::createNorthPoleEastingSouthNorthingSouth( createLinearUnit(unit_name, unit_conv_factor))); case PJ_CART2D_SOUTH_POLE_EASTING_NORTH_NORTHING_NORTH: return pj_obj_create( ctx, CartesianCS::createSouthPoleEastingNorthNorthingNorth( createLinearUnit(unit_name, unit_conv_factor))); case PJ_CART2D_WESTING_SOUTHING: return pj_obj_create( ctx, CartesianCS::createWestingSouthing( createLinearUnit(unit_name, unit_conv_factor))); } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a Ellipsoidal 2D * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param type Coordinate system type. * @param unit_name Name of the angular units. Or NULL for Degree * @param unit_conv_factor Conversion factor from the angular unit to radian. * Or 0 for Degree if unit_name == NULL. Otherwise should be not NULL * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_ellipsoidal_2D_cs(PJ_CONTEXT *ctx, PJ_ELLIPSOIDAL_CS_2D_TYPE type, const char *unit_name, double unit_conv_factor) { SANITIZE_CTX(ctx); try { switch (type) { case PJ_ELLPS2D_LONGITUDE_LATITUDE: return pj_obj_create( ctx, EllipsoidalCS::createLongitudeLatitude( createAngularUnit(unit_name, unit_conv_factor))); case PJ_ELLPS2D_LATITUDE_LONGITUDE: return pj_obj_create( ctx, EllipsoidalCS::createLatitudeLongitude( createAngularUnit(unit_name, unit_conv_factor))); } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a Ellipsoidal 3D * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param type Coordinate system type. * @param horizontal_angular_unit_name Name of the angular units. Or NULL for * Degree. * @param horizontal_angular_unit_conv_factor Conversion factor from the angular * unit to radian. Or 0 for Degree if horizontal_angular_unit_name == NULL. * Otherwise should be not NULL * @param vertical_linear_unit_name Vertical linear unit name. Or NULL for * Metre. * @param vertical_linear_unit_conv_factor Vertical linear unit conversion * factor to metre. Or 0 for Metre if vertical_linear_unit_name == NULL. * Otherwise should be not NULL * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. * @since 6.3 */ PJ *proj_create_ellipsoidal_3D_cs(PJ_CONTEXT *ctx, PJ_ELLIPSOIDAL_CS_3D_TYPE type, const char *horizontal_angular_unit_name, double horizontal_angular_unit_conv_factor, const char *vertical_linear_unit_name, double vertical_linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { switch (type) { case PJ_ELLPS3D_LONGITUDE_LATITUDE_HEIGHT: return pj_obj_create( ctx, EllipsoidalCS::createLongitudeLatitudeEllipsoidalHeight( createAngularUnit(horizontal_angular_unit_name, horizontal_angular_unit_conv_factor), createLinearUnit(vertical_linear_unit_name, vertical_linear_unit_conv_factor))); case PJ_ELLPS3D_LATITUDE_LONGITUDE_HEIGHT: return pj_obj_create( ctx, EllipsoidalCS::createLatitudeLongitudeEllipsoidalHeight( createAngularUnit(horizontal_angular_unit_name, horizontal_angular_unit_conv_factor), createLinearUnit(vertical_linear_unit_name, vertical_linear_unit_conv_factor))); } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs_name CRS name. Or NULL * @param geodetic_crs Base GeodeticCRS. Must not be NULL. * @param conversion Conversion. Must not be NULL. * @param coordinate_system Cartesian coordinate system. Must not be NULL. * * @return Object that must be unreferenced with * proj_destroy(), or NULL in case of error. */ PJ *proj_create_projected_crs(PJ_CONTEXT *ctx, const char *crs_name, const PJ *geodetic_crs, const PJ *conversion, const PJ *coordinate_system) { SANITIZE_CTX(ctx); if (!geodetic_crs || !conversion || !coordinate_system) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto geodCRS = std::dynamic_pointer_cast<GeodeticCRS>(geodetic_crs->iso_obj); if (!geodCRS) { return nullptr; } auto conv = std::dynamic_pointer_cast<Conversion>(conversion->iso_obj); if (!conv) { return nullptr; } auto cs = std::dynamic_pointer_cast<CartesianCS>(coordinate_system->iso_obj); if (!cs) { return nullptr; } try { return pj_obj_create( ctx, ProjectedCRS::create(createPropertyMapName(crs_name), NN_NO_CHECK(geodCRS), NN_NO_CHECK(conv), NN_NO_CHECK(cs))); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static PJ *proj_create_conversion(PJ_CONTEXT *ctx, const ConversionNNPtr &conv) { return pj_obj_create(ctx, conv); } //! @endcond /* BEGIN: Generated by scripts/create_c_api_projections.py*/ // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a Universal Transverse Mercator * conversion. * * See osgeo::proj::operation::Conversion::createUTM(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). */ PJ *proj_create_conversion_utm(PJ_CONTEXT *ctx, int zone, int north) { SANITIZE_CTX(ctx); try { auto conv = Conversion::createUTM(PropertyMap(), zone, north != 0); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Transverse * Mercator projection method. * * See osgeo::proj::operation::Conversion::createTransverseMercator(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_transverse_mercator( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createTransverseMercator( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Gauss * Schreiber Transverse Mercator projection method. * * See * osgeo::proj::operation::Conversion::createGaussSchreiberTransverseMercator(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_gauss_schreiber_transverse_mercator( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createGaussSchreiberTransverseMercator( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Transverse * Mercator South Orientated projection method. * * See * osgeo::proj::operation::Conversion::createTransverseMercatorSouthOriented(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_transverse_mercator_south_oriented( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createTransverseMercatorSouthOriented( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Two Point * Equidistant projection method. * * See osgeo::proj::operation::Conversion::createTwoPointEquidistant(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_two_point_equidistant( PJ_CONTEXT *ctx, double latitude_first_point, double longitude_first_point, double latitude_second_point, double longitude_secon_point, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createTwoPointEquidistant( PropertyMap(), Angle(latitude_first_point, angUnit), Angle(longitude_first_point, angUnit), Angle(latitude_second_point, angUnit), Angle(longitude_secon_point, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Tunisia * Mining Grid projection method. * * See osgeo::proj::operation::Conversion::createTunisiaMiningGrid(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). * * @since 9.2 */ PJ *proj_create_conversion_tunisia_mining_grid( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createTunisiaMiningGrid( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Tunisia * Mining Grid projection method. * * See osgeo::proj::operation::Conversion::createTunisiaMiningGrid(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). * * @deprecated Replaced by proj_create_conversion_tunisia_mining_grid */ PJ *proj_create_conversion_tunisia_mapping_grid( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createTunisiaMiningGrid( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Albers * Conic Equal Area projection method. * * See osgeo::proj::operation::Conversion::createAlbersEqualArea(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_albers_equal_area( PJ_CONTEXT *ctx, double latitude_false_origin, double longitude_false_origin, double latitude_first_parallel, double latitude_second_parallel, double easting_false_origin, double northing_false_origin, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createAlbersEqualArea( PropertyMap(), Angle(latitude_false_origin, angUnit), Angle(longitude_false_origin, angUnit), Angle(latitude_first_parallel, angUnit), Angle(latitude_second_parallel, angUnit), Length(easting_false_origin, linearUnit), Length(northing_false_origin, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Conic Conformal 1SP projection method. * * See osgeo::proj::operation::Conversion::createLambertConicConformal_1SP(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_lambert_conic_conformal_1sp( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertConicConformal_1SP( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Conic Conformal (1SP Variant B) projection method. * * See * osgeo::proj::operation::Conversion::createLambertConicConformal_1SP_VariantB(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). * @since 9.2.1 */ PJ *proj_create_conversion_lambert_conic_conformal_1sp_variant_b( PJ_CONTEXT *ctx, double latitude_nat_origin, double scale, double latitude_false_origin, double longitude_false_origin, double easting_false_origin, double northing_false_origin, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertConicConformal_1SP_VariantB( PropertyMap(), Angle(latitude_nat_origin, angUnit), Scale(scale), Angle(latitude_false_origin, angUnit), Angle(longitude_false_origin, angUnit), Length(easting_false_origin, linearUnit), Length(northing_false_origin, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Conic Conformal (2SP) projection method. * * See osgeo::proj::operation::Conversion::createLambertConicConformal_2SP(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_lambert_conic_conformal_2sp( PJ_CONTEXT *ctx, double latitude_false_origin, double longitude_false_origin, double latitude_first_parallel, double latitude_second_parallel, double easting_false_origin, double northing_false_origin, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(latitude_false_origin, angUnit), Angle(longitude_false_origin, angUnit), Angle(latitude_first_parallel, angUnit), Angle(latitude_second_parallel, angUnit), Length(easting_false_origin, linearUnit), Length(northing_false_origin, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Conic Conformal (2SP Michigan) projection method. * * See * osgeo::proj::operation::Conversion::createLambertConicConformal_2SP_Michigan(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_lambert_conic_conformal_2sp_michigan( PJ_CONTEXT *ctx, double latitude_false_origin, double longitude_false_origin, double latitude_first_parallel, double latitude_second_parallel, double easting_false_origin, double northing_false_origin, double ellipsoid_scaling_factor, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertConicConformal_2SP_Michigan( PropertyMap(), Angle(latitude_false_origin, angUnit), Angle(longitude_false_origin, angUnit), Angle(latitude_first_parallel, angUnit), Angle(latitude_second_parallel, angUnit), Length(easting_false_origin, linearUnit), Length(northing_false_origin, linearUnit), Scale(ellipsoid_scaling_factor)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Conic Conformal (2SP Belgium) projection method. * * See * osgeo::proj::operation::Conversion::createLambertConicConformal_2SP_Belgium(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_lambert_conic_conformal_2sp_belgium( PJ_CONTEXT *ctx, double latitude_false_origin, double longitude_false_origin, double latitude_first_parallel, double latitude_second_parallel, double easting_false_origin, double northing_false_origin, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertConicConformal_2SP_Belgium( PropertyMap(), Angle(latitude_false_origin, angUnit), Angle(longitude_false_origin, angUnit), Angle(latitude_first_parallel, angUnit), Angle(latitude_second_parallel, angUnit), Length(easting_false_origin, linearUnit), Length(northing_false_origin, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Modified * Azimuthal Equidistant projection method. * * See osgeo::proj::operation::Conversion::createAzimuthalEquidistant(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_azimuthal_equidistant( PJ_CONTEXT *ctx, double latitude_nat_origin, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createAzimuthalEquidistant( PropertyMap(), Angle(latitude_nat_origin, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Guam * Projection projection method. * * See osgeo::proj::operation::Conversion::createGuamProjection(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_guam_projection( PJ_CONTEXT *ctx, double latitude_nat_origin, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createGuamProjection( PropertyMap(), Angle(latitude_nat_origin, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Bonne * projection method. * * See osgeo::proj::operation::Conversion::createBonne(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_bonne(PJ_CONTEXT *ctx, double latitude_nat_origin, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createBonne( PropertyMap(), Angle(latitude_nat_origin, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Cylindrical Equal Area (Spherical) projection method. * * See * osgeo::proj::operation::Conversion::createLambertCylindricalEqualAreaSpherical(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_lambert_cylindrical_equal_area_spherical( PJ_CONTEXT *ctx, double latitude_first_parallel, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertCylindricalEqualAreaSpherical( PropertyMap(), Angle(latitude_first_parallel, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Cylindrical Equal Area (ellipsoidal form) projection method. * * See osgeo::proj::operation::Conversion::createLambertCylindricalEqualArea(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_lambert_cylindrical_equal_area( PJ_CONTEXT *ctx, double latitude_first_parallel, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertCylindricalEqualArea( PropertyMap(), Angle(latitude_first_parallel, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the * Cassini-Soldner projection method. * * See osgeo::proj::operation::Conversion::createCassiniSoldner(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_cassini_soldner( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createCassiniSoldner( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Equidistant * Conic projection method. * * See osgeo::proj::operation::Conversion::createEquidistantConic(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_equidistant_conic( PJ_CONTEXT *ctx, double center_lat, double center_long, double latitude_first_parallel, double latitude_second_parallel, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEquidistantConic( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Angle(latitude_first_parallel, angUnit), Angle(latitude_second_parallel, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Eckert I * projection method. * * See osgeo::proj::operation::Conversion::createEckertI(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_eckert_i(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEckertI( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Eckert II * projection method. * * See osgeo::proj::operation::Conversion::createEckertII(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_eckert_ii(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEckertII( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Eckert III * projection method. * * See osgeo::proj::operation::Conversion::createEckertIII(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_eckert_iii(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEckertIII( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Eckert IV * projection method. * * See osgeo::proj::operation::Conversion::createEckertIV(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_eckert_iv(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEckertIV( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Eckert V * projection method. * * See osgeo::proj::operation::Conversion::createEckertV(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_eckert_v(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEckertV( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Eckert VI * projection method. * * See osgeo::proj::operation::Conversion::createEckertVI(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_eckert_vi(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEckertVI( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Equidistant * Cylindrical projection method. * * See osgeo::proj::operation::Conversion::createEquidistantCylindrical(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_equidistant_cylindrical( PJ_CONTEXT *ctx, double latitude_first_parallel, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEquidistantCylindrical( PropertyMap(), Angle(latitude_first_parallel, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Equidistant * Cylindrical (Spherical) projection method. * * See * osgeo::proj::operation::Conversion::createEquidistantCylindricalSpherical(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_equidistant_cylindrical_spherical( PJ_CONTEXT *ctx, double latitude_first_parallel, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEquidistantCylindricalSpherical( PropertyMap(), Angle(latitude_first_parallel, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Gall * (Stereographic) projection method. * * See osgeo::proj::operation::Conversion::createGall(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_gall(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createGall(PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Goode * Homolosine projection method. * * See osgeo::proj::operation::Conversion::createGoodeHomolosine(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_goode_homolosine(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createGoodeHomolosine( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Interrupted * Goode Homolosine projection method. * * See osgeo::proj::operation::Conversion::createInterruptedGoodeHomolosine(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_interrupted_goode_homolosine( PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createInterruptedGoodeHomolosine( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the * Geostationary Satellite View projection method, with the sweep angle axis of * the viewing instrument being x. * * See osgeo::proj::operation::Conversion::createGeostationarySatelliteSweepX(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_geostationary_satellite_sweep_x( PJ_CONTEXT *ctx, double center_long, double height, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createGeostationarySatelliteSweepX( PropertyMap(), Angle(center_long, angUnit), Length(height, linearUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the * Geostationary Satellite View projection method, with the sweep angle axis of * the viewing instrument being y. * * See osgeo::proj::operation::Conversion::createGeostationarySatelliteSweepY(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_geostationary_satellite_sweep_y( PJ_CONTEXT *ctx, double center_long, double height, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createGeostationarySatelliteSweepY( PropertyMap(), Angle(center_long, angUnit), Length(height, linearUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Gnomonic * projection method. * * See osgeo::proj::operation::Conversion::createGnomonic(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_gnomonic(PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createGnomonic( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Hotine * Oblique Mercator (Variant A) projection method. * * See * osgeo::proj::operation::Conversion::createHotineObliqueMercatorVariantA(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_hotine_oblique_mercator_variant_a( PJ_CONTEXT *ctx, double latitude_projection_centre, double longitude_projection_centre, double azimuth_initial_line, double angle_from_rectified_to_skrew_grid, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createHotineObliqueMercatorVariantA( PropertyMap(), Angle(latitude_projection_centre, angUnit), Angle(longitude_projection_centre, angUnit), Angle(azimuth_initial_line, angUnit), Angle(angle_from_rectified_to_skrew_grid, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Hotine * Oblique Mercator (Variant B) projection method. * * See * osgeo::proj::operation::Conversion::createHotineObliqueMercatorVariantB(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_hotine_oblique_mercator_variant_b( PJ_CONTEXT *ctx, double latitude_projection_centre, double longitude_projection_centre, double azimuth_initial_line, double angle_from_rectified_to_skrew_grid, double scale, double easting_projection_centre, double northing_projection_centre, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createHotineObliqueMercatorVariantB( PropertyMap(), Angle(latitude_projection_centre, angUnit), Angle(longitude_projection_centre, angUnit), Angle(azimuth_initial_line, angUnit), Angle(angle_from_rectified_to_skrew_grid, angUnit), Scale(scale), Length(easting_projection_centre, linearUnit), Length(northing_projection_centre, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Hotine * Oblique Mercator Two Point Natural Origin projection method. * * See * osgeo::proj::operation::Conversion::createHotineObliqueMercatorTwoPointNaturalOrigin(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_hotine_oblique_mercator_two_point_natural_origin( PJ_CONTEXT *ctx, double latitude_projection_centre, double latitude_point1, double longitude_point1, double latitude_point2, double longitude_point2, double scale, double easting_projection_centre, double northing_projection_centre, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createHotineObliqueMercatorTwoPointNaturalOrigin( PropertyMap(), Angle(latitude_projection_centre, angUnit), Angle(latitude_point1, angUnit), Angle(longitude_point1, angUnit), Angle(latitude_point2, angUnit), Angle(longitude_point2, angUnit), Scale(scale), Length(easting_projection_centre, linearUnit), Length(northing_projection_centre, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Laborde * Oblique Mercator projection method. * * See * osgeo::proj::operation::Conversion::createLabordeObliqueMercator(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_laborde_oblique_mercator( PJ_CONTEXT *ctx, double latitude_projection_centre, double longitude_projection_centre, double azimuth_initial_line, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLabordeObliqueMercator( PropertyMap(), Angle(latitude_projection_centre, angUnit), Angle(longitude_projection_centre, angUnit), Angle(azimuth_initial_line, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the * International Map of the World Polyconic projection method. * * See * osgeo::proj::operation::Conversion::createInternationalMapWorldPolyconic(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_international_map_world_polyconic( PJ_CONTEXT *ctx, double center_long, double latitude_first_parallel, double latitude_second_parallel, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createInternationalMapWorldPolyconic( PropertyMap(), Angle(center_long, angUnit), Angle(latitude_first_parallel, angUnit), Angle(latitude_second_parallel, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Krovak * (north oriented) projection method. * * See osgeo::proj::operation::Conversion::createKrovakNorthOriented(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_krovak_north_oriented( PJ_CONTEXT *ctx, double latitude_projection_centre, double longitude_of_origin, double colatitude_cone_axis, double latitude_pseudo_standard_parallel, double scale_factor_pseudo_standard_parallel, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createKrovakNorthOriented( PropertyMap(), Angle(latitude_projection_centre, angUnit), Angle(longitude_of_origin, angUnit), Angle(colatitude_cone_axis, angUnit), Angle(latitude_pseudo_standard_parallel, angUnit), Scale(scale_factor_pseudo_standard_parallel), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Krovak * projection method. * * See osgeo::proj::operation::Conversion::createKrovak(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_krovak( PJ_CONTEXT *ctx, double latitude_projection_centre, double longitude_of_origin, double colatitude_cone_axis, double latitude_pseudo_standard_parallel, double scale_factor_pseudo_standard_parallel, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createKrovak( PropertyMap(), Angle(latitude_projection_centre, angUnit), Angle(longitude_of_origin, angUnit), Angle(colatitude_cone_axis, angUnit), Angle(latitude_pseudo_standard_parallel, angUnit), Scale(scale_factor_pseudo_standard_parallel), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Lambert * Azimuthal Equal Area projection method. * * See osgeo::proj::operation::Conversion::createLambertAzimuthalEqualArea(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_lambert_azimuthal_equal_area( PJ_CONTEXT *ctx, double latitude_nat_origin, double longitude_nat_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createLambertAzimuthalEqualArea( PropertyMap(), Angle(latitude_nat_origin, angUnit), Angle(longitude_nat_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Miller * Cylindrical projection method. * * See osgeo::proj::operation::Conversion::createMillerCylindrical(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_miller_cylindrical( PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createMillerCylindrical( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Mercator * projection method. * * See osgeo::proj::operation::Conversion::createMercatorVariantA(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_mercator_variant_a( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createMercatorVariantA( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Mercator * projection method. * * See osgeo::proj::operation::Conversion::createMercatorVariantB(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_mercator_variant_b( PJ_CONTEXT *ctx, double latitude_first_parallel, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createMercatorVariantB( PropertyMap(), Angle(latitude_first_parallel, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Popular * Visualisation Pseudo Mercator projection method. * * See * osgeo::proj::operation::Conversion::createPopularVisualisationPseudoMercator(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_popular_visualisation_pseudo_mercator( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createPopularVisualisationPseudoMercator( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Mollweide * projection method. * * See osgeo::proj::operation::Conversion::createMollweide(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_mollweide(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createMollweide( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the New Zealand * Map Grid projection method. * * See osgeo::proj::operation::Conversion::createNewZealandMappingGrid(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_new_zealand_mapping_grid( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createNewZealandMappingGrid( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Oblique * Stereographic (Alternative) projection method. * * See osgeo::proj::operation::Conversion::createObliqueStereographic(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_oblique_stereographic( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createObliqueStereographic( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the * Orthographic projection method. * * See osgeo::proj::operation::Conversion::createOrthographic(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_orthographic( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createOrthographic( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the American * Polyconic projection method. * * See osgeo::proj::operation::Conversion::createAmericanPolyconic(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_american_polyconic( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createAmericanPolyconic( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Polar * Stereographic (Variant A) projection method. * * See osgeo::proj::operation::Conversion::createPolarStereographicVariantA(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_polar_stereographic_variant_a( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createPolarStereographicVariantA( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Polar * Stereographic (Variant B) projection method. * * See osgeo::proj::operation::Conversion::createPolarStereographicVariantB(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_polar_stereographic_variant_b( PJ_CONTEXT *ctx, double latitude_standard_parallel, double longitude_of_origin, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createPolarStereographicVariantB( PropertyMap(), Angle(latitude_standard_parallel, angUnit), Angle(longitude_of_origin, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Robinson * projection method. * * See osgeo::proj::operation::Conversion::createRobinson(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_robinson(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createRobinson( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Sinusoidal * projection method. * * See osgeo::proj::operation::Conversion::createSinusoidal(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_sinusoidal(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createSinusoidal( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the * Stereographic projection method. * * See osgeo::proj::operation::Conversion::createStereographic(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_stereographic( PJ_CONTEXT *ctx, double center_lat, double center_long, double scale, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createStereographic( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Scale(scale), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Van der * Grinten projection method. * * See osgeo::proj::operation::Conversion::createVanDerGrinten(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_van_der_grinten(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createVanDerGrinten( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Wagner I * projection method. * * See osgeo::proj::operation::Conversion::createWagnerI(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_wagner_i(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createWagnerI( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Wagner II * projection method. * * See osgeo::proj::operation::Conversion::createWagnerII(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_wagner_ii(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createWagnerII( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Wagner III * projection method. * * See osgeo::proj::operation::Conversion::createWagnerIII(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_wagner_iii( PJ_CONTEXT *ctx, double latitude_true_scale, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createWagnerIII( PropertyMap(), Angle(latitude_true_scale, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Wagner IV * projection method. * * See osgeo::proj::operation::Conversion::createWagnerIV(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_wagner_iv(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createWagnerIV( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Wagner V * projection method. * * See osgeo::proj::operation::Conversion::createWagnerV(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_wagner_v(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createWagnerV( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Wagner VI * projection method. * * See osgeo::proj::operation::Conversion::createWagnerVI(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_wagner_vi(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createWagnerVI( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Wagner VII * projection method. * * See osgeo::proj::operation::Conversion::createWagnerVII(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_wagner_vii(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createWagnerVII( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the * Quadrilateralized Spherical Cube projection method. * * See * osgeo::proj::operation::Conversion::createQuadrilateralizedSphericalCube(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_quadrilateralized_spherical_cube( PJ_CONTEXT *ctx, double center_lat, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createQuadrilateralizedSphericalCube( PropertyMap(), Angle(center_lat, angUnit), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Spherical * Cross-Track Height projection method. * * See osgeo::proj::operation::Conversion::createSphericalCrossTrackHeight(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_spherical_cross_track_height( PJ_CONTEXT *ctx, double peg_point_lat, double peg_point_long, double peg_point_heading, double peg_point_height, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createSphericalCrossTrackHeight( PropertyMap(), Angle(peg_point_lat, angUnit), Angle(peg_point_long, angUnit), Angle(peg_point_heading, angUnit), Length(peg_point_height, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a ProjectedCRS with a conversion based on the Equal Earth * projection method. * * See osgeo::proj::operation::Conversion::createEqualEarth(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_equal_earth(PJ_CONTEXT *ctx, double center_long, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createEqualEarth( PropertyMap(), Angle(center_long, angUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Vertical Perspective projection * method. * * See osgeo::proj::operation::Conversion::createVerticalPerspective(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). * * @since 6.3 */ PJ *proj_create_conversion_vertical_perspective( PJ_CONTEXT *ctx, double topo_origin_lat, double topo_origin_long, double topo_origin_height, double view_point_height, double false_easting, double false_northing, const char *ang_unit_name, double ang_unit_conv_factor, const char *linear_unit_name, double linear_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure linearUnit( createLinearUnit(linear_unit_name, linear_unit_conv_factor)); UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createVerticalPerspective( PropertyMap(), Angle(topo_origin_lat, angUnit), Angle(topo_origin_long, angUnit), Length(topo_origin_height, linearUnit), Length(view_point_height, linearUnit), Length(false_easting, linearUnit), Length(false_northing, linearUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Pole Rotation method, using the * conventions of the GRIB 1 and GRIB 2 data formats. * * See osgeo::proj::operation::Conversion::createPoleRotationGRIBConvention(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_pole_rotation_grib_convention( PJ_CONTEXT *ctx, double south_pole_lat_in_unrotated_crs, double south_pole_long_in_unrotated_crs, double axis_rotation, const char *ang_unit_name, double ang_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createPoleRotationGRIBConvention( PropertyMap(), Angle(south_pole_lat_in_unrotated_crs, angUnit), Angle(south_pole_long_in_unrotated_crs, angUnit), Angle(axis_rotation, angUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Pole Rotation method, using * the conventions of the netCDF CF convention for the netCDF format. * * See * osgeo::proj::operation::Conversion::createPoleRotationNetCDFCFConvention(). * * Linear parameters are expressed in (linear_unit_name, * linear_unit_conv_factor). * Angular parameters are expressed in (ang_unit_name, ang_unit_conv_factor). */ PJ *proj_create_conversion_pole_rotation_netcdf_cf_convention( PJ_CONTEXT *ctx, double grid_north_pole_latitude, double grid_north_pole_longitude, double north_pole_grid_longitude, const char *ang_unit_name, double ang_unit_conv_factor) { SANITIZE_CTX(ctx); try { UnitOfMeasure angUnit( createAngularUnit(ang_unit_name, ang_unit_conv_factor)); auto conv = Conversion::createPoleRotationNetCDFCFConvention( PropertyMap(), Angle(grid_north_pole_latitude, angUnit), Angle(grid_north_pole_longitude, angUnit), Angle(north_pole_grid_longitude, angUnit)); return proj_create_conversion(ctx, conv); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } /* END: Generated by scripts/create_c_api_projections.py*/ // --------------------------------------------------------------------------- /** \brief Return whether a coordinate operation can be instantiated as * a PROJ pipeline, checking in particular that referenced grids are * available. * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type CoordinateOperation or derived classes * (must not be NULL) * @return TRUE or FALSE. */ int proj_coordoperation_is_instantiable(PJ_CONTEXT *ctx, const PJ *coordoperation) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto op = dynamic_cast<const CoordinateOperation *>( coordoperation->iso_obj.get()); if (!op) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateOperation"); return 0; } auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { auto ret = op->isPROJInstantiable( dbContext, proj_context_is_network_enabled(ctx) != FALSE) ? 1 : 0; return ret; } catch (const std::exception &) { return 0; } } // --------------------------------------------------------------------------- /** \brief Return whether a coordinate operation has a "ballpark" * transformation, * that is a very approximate one, due to lack of more accurate transformations. * * Typically a null geographic offset between two horizontal datum, or a * null vertical offset (or limited to unit changes) between two vertical * datum. Errors of several tens to one hundred meters might be expected, * compared to more accurate transformations. * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type CoordinateOperation or derived classes * (must not be NULL) * @return TRUE or FALSE. */ int proj_coordoperation_has_ballpark_transformation(PJ_CONTEXT *ctx, const PJ *coordoperation) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto op = dynamic_cast<const CoordinateOperation *>( coordoperation->iso_obj.get()); if (!op) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateOperation"); return 0; } return op->hasBallparkTransformation(); } // --------------------------------------------------------------------------- /** \brief Return the number of parameters of a SingleOperation * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type SingleOperation or derived classes * (must not be NULL) */ int proj_coordoperation_get_param_count(PJ_CONTEXT *ctx, const PJ *coordoperation) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto op = dynamic_cast<const SingleOperation *>(coordoperation->iso_obj.get()); if (!op) { proj_log_error(ctx, __FUNCTION__, "Object is not a SingleOperation"); return 0; } return static_cast<int>(op->parameterValues().size()); } // --------------------------------------------------------------------------- /** \brief Return the index of a parameter of a SingleOperation * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type SingleOperation or derived classes * (must not be NULL) * @param name Parameter name. Must not be NULL * @return index (>=0), or -1 in case of error. */ int proj_coordoperation_get_param_index(PJ_CONTEXT *ctx, const PJ *coordoperation, const char *name) { SANITIZE_CTX(ctx); if (!coordoperation || !name) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return -1; } auto op = dynamic_cast<const SingleOperation *>(coordoperation->iso_obj.get()); if (!op) { proj_log_error(ctx, __FUNCTION__, "Object is not a SingleOperation"); return -1; } int index = 0; for (const auto &genParam : op->method()->parameters()) { if (Identifier::isEquivalentName(genParam->nameStr().c_str(), name)) { return index; } index++; } return -1; } // --------------------------------------------------------------------------- /** \brief Return a parameter of a SingleOperation * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type SingleOperation or derived classes * (must not be NULL) * @param index Parameter index. * @param out_name Pointer to a string value to store the parameter name. or * NULL * @param out_auth_name Pointer to a string value to store the parameter * authority name. or NULL * @param out_code Pointer to a string value to store the parameter * code. or NULL * @param out_value Pointer to a double value to store the parameter * value (if numeric). or NULL * @param out_value_string Pointer to a string value to store the parameter * value (if of type string). or NULL * @param out_unit_conv_factor Pointer to a double value to store the parameter * unit conversion factor. or NULL * @param out_unit_name Pointer to a string value to store the parameter * unit name. or NULL * @param out_unit_auth_name Pointer to a string value to store the * unit authority name. or NULL * @param out_unit_code Pointer to a string value to store the * unit code. or NULL * @param out_unit_category Pointer to a string value to store the parameter * name. or * NULL. This value might be "unknown", "none", "linear", "linear_per_time", * "angular", "angular_per_time", "scale", "scale_per_time", "time", * "parametric" or "parametric_per_time" * @return TRUE in case of success. */ int proj_coordoperation_get_param( PJ_CONTEXT *ctx, const PJ *coordoperation, int index, const char **out_name, const char **out_auth_name, const char **out_code, double *out_value, const char **out_value_string, double *out_unit_conv_factor, const char **out_unit_name, const char **out_unit_auth_name, const char **out_unit_code, const char **out_unit_category) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto op = dynamic_cast<const SingleOperation *>(coordoperation->iso_obj.get()); if (!op) { proj_log_error(ctx, __FUNCTION__, "Object is not a SingleOperation"); return false; } const auto &parameters = op->method()->parameters(); const auto &values = op->parameterValues(); if (static_cast<size_t>(index) >= parameters.size() || static_cast<size_t>(index) >= values.size()) { proj_log_error(ctx, __FUNCTION__, "Invalid index"); return false; } const auto &param = parameters[index]; const auto &param_ids = param->identifiers(); if (out_name) { *out_name = param->name()->description()->c_str(); } if (out_auth_name) { if (!param_ids.empty()) { *out_auth_name = param_ids[0]->codeSpace()->c_str(); } else { *out_auth_name = nullptr; } } if (out_code) { if (!param_ids.empty()) { *out_code = param_ids[0]->code().c_str(); } else { *out_code = nullptr; } } const auto &value = values[index]; ParameterValuePtr paramValue = nullptr; auto opParamValue = dynamic_cast<const OperationParameterValue *>(value.get()); if (opParamValue) { paramValue = opParamValue->parameterValue().as_nullable(); } if (out_value) { *out_value = 0; if (paramValue) { if (paramValue->type() == ParameterValue::Type::MEASURE) { *out_value = paramValue->value().value(); } } } if (out_value_string) { *out_value_string = nullptr; if (paramValue) { if (paramValue->type() == ParameterValue::Type::FILENAME) { *out_value_string = paramValue->valueFile().c_str(); } else if (paramValue->type() == ParameterValue::Type::STRING) { *out_value_string = paramValue->stringValue().c_str(); } } } if (out_unit_conv_factor) { *out_unit_conv_factor = 0; } if (out_unit_name) { *out_unit_name = nullptr; } if (out_unit_auth_name) { *out_unit_auth_name = nullptr; } if (out_unit_code) { *out_unit_code = nullptr; } if (out_unit_category) { *out_unit_category = nullptr; } if (paramValue) { if (paramValue->type() == ParameterValue::Type::MEASURE) { const auto &unit = paramValue->value().unit(); if (out_unit_conv_factor) { *out_unit_conv_factor = unit.conversionToSI(); } if (out_unit_name) { *out_unit_name = unit.name().c_str(); } if (out_unit_auth_name) { *out_unit_auth_name = unit.codeSpace().c_str(); } if (out_unit_code) { *out_unit_code = unit.code().c_str(); } if (out_unit_category) { *out_unit_category = get_unit_category(unit.name(), unit.type()); } } } return true; } // --------------------------------------------------------------------------- /** \brief Return the parameters of a Helmert transformation as WKT1 TOWGS84 * values. * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type Transformation, that can be represented * as a WKT1 TOWGS84 node (must not be NULL) * @param out_values Pointer to an array of value_count double values. * @param value_count Size of out_values array. The suggested size is 7 to get * translation, rotation and scale difference parameters. Rotation and scale * difference terms might be zero if the transformation only includes * translation * parameters. In that case, value_count could be set to 3. * @param emit_error_if_incompatible Boolean to indicate if an error must be * logged if coordoperation is not compatible with a WKT1 TOWGS84 * representation. * @return TRUE in case of success, or FALSE if coordoperation is not * compatible with a WKT1 TOWGS84 representation. */ int proj_coordoperation_get_towgs84_values(PJ_CONTEXT *ctx, const PJ *coordoperation, double *out_values, int value_count, int emit_error_if_incompatible) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto transf = dynamic_cast<const Transformation *>(coordoperation->iso_obj.get()); if (!transf) { if (emit_error_if_incompatible) { proj_log_error(ctx, __FUNCTION__, "Object is not a Transformation"); } return FALSE; } try { auto values = transf->getTOWGS84Parameters(); for (int i = 0; i < value_count && static_cast<size_t>(i) < values.size(); i++) { out_values[i] = values[i]; } return TRUE; } catch (const std::exception &e) { if (emit_error_if_incompatible) { proj_log_error(ctx, __FUNCTION__, e.what()); } return FALSE; } } // --------------------------------------------------------------------------- /** \brief Return the number of grids used by a CoordinateOperation * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type CoordinateOperation or derived classes * (must not be NULL) */ int proj_coordoperation_get_grid_used_count(PJ_CONTEXT *ctx, const PJ *coordoperation) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto co = dynamic_cast<const CoordinateOperation *>( coordoperation->iso_obj.get()); if (!co) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateOperation"); return 0; } auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { if (!coordoperation->gridsNeededAsked) { coordoperation->gridsNeededAsked = true; const auto gridsNeeded = co->gridsNeeded( dbContext, proj_context_is_network_enabled(ctx) != FALSE); for (const auto &gridDesc : gridsNeeded) { coordoperation->gridsNeeded.emplace_back(gridDesc); } } return static_cast<int>(coordoperation->gridsNeeded.size()); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return 0; } } // --------------------------------------------------------------------------- /** \brief Return a parameter of a SingleOperation * * @param ctx PROJ context, or NULL for default context * @param coordoperation Object of type SingleOperation or derived classes * (must not be NULL) * @param index Parameter index. * @param out_short_name Pointer to a string value to store the grid short name. * or NULL * @param out_full_name Pointer to a string value to store the grid full * filename. or NULL * @param out_package_name Pointer to a string value to store the package name * where * the grid might be found. or NULL * @param out_url Pointer to a string value to store the grid URL or the * package URL where the grid might be found. or NULL * @param out_direct_download Pointer to a int (boolean) value to store whether * *out_url can be downloaded directly. or NULL * @param out_open_license Pointer to a int (boolean) value to store whether * the grid is released with an open license. or NULL * @param out_available Pointer to a int (boolean) value to store whether the * grid is available at runtime. or NULL * @return TRUE in case of success. */ int proj_coordoperation_get_grid_used( PJ_CONTEXT *ctx, const PJ *coordoperation, int index, const char **out_short_name, const char **out_full_name, const char **out_package_name, const char **out_url, int *out_direct_download, int *out_open_license, int *out_available) { SANITIZE_CTX(ctx); const int count = proj_coordoperation_get_grid_used_count(ctx, coordoperation); if (index < 0 || index >= count) { proj_log_error(ctx, __FUNCTION__, "Invalid index"); return false; } const auto &gridDesc = coordoperation->gridsNeeded[index]; if (out_short_name) { *out_short_name = gridDesc.shortName.c_str(); } if (out_full_name) { *out_full_name = gridDesc.fullName.c_str(); } if (out_package_name) { *out_package_name = gridDesc.packageName.c_str(); } if (out_url) { *out_url = gridDesc.url.c_str(); } if (out_direct_download) { *out_direct_download = gridDesc.directDownload; } if (out_open_license) { *out_open_license = gridDesc.openLicense; } if (out_available) { *out_available = gridDesc.available; } return true; } // --------------------------------------------------------------------------- /** \brief Opaque object representing an operation factory context. */ struct PJ_OPERATION_FACTORY_CONTEXT { //! @cond Doxygen_Suppress CoordinateOperationContextNNPtr operationContext; explicit PJ_OPERATION_FACTORY_CONTEXT( CoordinateOperationContextNNPtr &&operationContextIn) : operationContext(std::move(operationContextIn)) {} PJ_OPERATION_FACTORY_CONTEXT(const PJ_OPERATION_FACTORY_CONTEXT &) = delete; PJ_OPERATION_FACTORY_CONTEXT & operator=(const PJ_OPERATION_FACTORY_CONTEXT &) = delete; //! @endcond }; // --------------------------------------------------------------------------- /** \brief Instantiate a context for building coordinate operations between * two CRS. * * The returned object must be unreferenced with * proj_operation_factory_context_destroy() after use. * * If authority is NULL or the empty string, then coordinate * operations from any authority will be searched, with the restrictions set * in the authority_to_authority_preference database table. * If authority is set to "any", then coordinate * operations from any authority will be searched * If authority is a non-empty string different of "any", * then coordinate operations will be searched only in that authority namespace. * * @param ctx Context, or NULL for default context. * @param authority Name of authority to which to restrict the search of * candidate operations. * @return Object that must be unreferenced with * proj_operation_factory_context_destroy(), or NULL in * case of error. */ PJ_OPERATION_FACTORY_CONTEXT * proj_create_operation_factory_context(PJ_CONTEXT *ctx, const char *authority) { SANITIZE_CTX(ctx); auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { if (dbContext) { auto factory = CoordinateOperationFactory::create(); auto authFactory = AuthorityFactory::create( NN_NO_CHECK(dbContext), std::string(authority ? authority : "")); auto operationContext = CoordinateOperationContext::create(authFactory, nullptr, 0.0); return new PJ_OPERATION_FACTORY_CONTEXT( std::move(operationContext)); } else { auto operationContext = CoordinateOperationContext::create(nullptr, nullptr, 0.0); return new PJ_OPERATION_FACTORY_CONTEXT( std::move(operationContext)); } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Drops a reference on an object. * * This method should be called one and exactly one for each function * returning a PJ_OPERATION_FACTORY_CONTEXT* * * @param ctx Object, or NULL. */ void proj_operation_factory_context_destroy(PJ_OPERATION_FACTORY_CONTEXT *ctx) { delete ctx; } // --------------------------------------------------------------------------- /** \brief Set the desired accuracy of the resulting coordinate transformations. * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param accuracy Accuracy in meter (or 0 to disable the filter). */ void proj_operation_factory_context_set_desired_accuracy( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, double accuracy) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { factory_ctx->operationContext->setDesiredAccuracy(accuracy); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set the desired area of interest for the resulting coordinate * transformations. * * For an area of interest crossing the anti-meridian, west_lon_degree will be * greater than east_lon_degree. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param west_lon_degree West longitude (in degrees). * @param south_lat_degree South latitude (in degrees). * @param east_lon_degree East longitude (in degrees). * @param north_lat_degree North latitude (in degrees). */ void proj_operation_factory_context_set_area_of_interest( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, double west_lon_degree, double south_lat_degree, double east_lon_degree, double north_lat_degree) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { factory_ctx->operationContext->setAreaOfInterest( Extent::createFromBBOX(west_lon_degree, south_lat_degree, east_lon_degree, north_lat_degree)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set the name of the desired area of interest for the resulting * coordinate transformations. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param area_name Area name. Must be known of the database. */ void proj_operation_factory_context_set_area_of_interest_name( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, const char *area_name) { SANITIZE_CTX(ctx); if (!factory_ctx || !area_name) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { auto extent = factory_ctx->operationContext->getAreaOfInterest(); if (extent == nullptr) { auto dbContext = getDBcontext(ctx); auto factory = AuthorityFactory::create(dbContext, std::string()); auto res = factory->listAreaOfUseFromName(area_name, false); if (res.size() == 1) { factory_ctx->operationContext->setAreaOfInterest( AuthorityFactory::create(dbContext, res.front().first) ->createExtent(res.front().second) .as_nullable()); } else { proj_log_error(ctx, __FUNCTION__, "cannot find area"); return; } } else { factory_ctx->operationContext->setAreaOfInterest( metadata::Extent::create(util::optional<std::string>(area_name), extent->geographicElements(), extent->verticalElements(), extent->temporalElements()) .as_nullable()); } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set how source and target CRS extent should be used * when considering if a transformation can be used (only takes effect if * no area of interest is explicitly defined). * * The default is PJ_CRS_EXTENT_SMALLEST. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param use How source and target CRS extent should be used. */ void proj_operation_factory_context_set_crs_extent_use( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_CRS_EXTENT_USE use) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { switch (use) { case PJ_CRS_EXTENT_NONE: factory_ctx->operationContext->setSourceAndTargetCRSExtentUse( CoordinateOperationContext::SourceTargetCRSExtentUse::NONE); break; case PJ_CRS_EXTENT_BOTH: factory_ctx->operationContext->setSourceAndTargetCRSExtentUse( CoordinateOperationContext::SourceTargetCRSExtentUse::BOTH); break; case PJ_CRS_EXTENT_INTERSECTION: factory_ctx->operationContext->setSourceAndTargetCRSExtentUse( CoordinateOperationContext::SourceTargetCRSExtentUse:: INTERSECTION); break; case PJ_CRS_EXTENT_SMALLEST: factory_ctx->operationContext->setSourceAndTargetCRSExtentUse( CoordinateOperationContext::SourceTargetCRSExtentUse::SMALLEST); break; } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set the spatial criterion to use when comparing the area of * validity of coordinate operations with the area of interest / area of * validity of * source and target CRS. * * The default is PROJ_SPATIAL_CRITERION_STRICT_CONTAINMENT. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param criterion spatial criterion to use */ void proj_operation_factory_context_set_spatial_criterion( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_SPATIAL_CRITERION criterion) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { switch (criterion) { case PROJ_SPATIAL_CRITERION_STRICT_CONTAINMENT: factory_ctx->operationContext->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion:: STRICT_CONTAINMENT); break; case PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION: factory_ctx->operationContext->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion:: PARTIAL_INTERSECTION); break; } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set how grid availability is used. * * The default is USE_FOR_SORTING. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param use how grid availability is used. */ void proj_operation_factory_context_set_grid_availability_use( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_GRID_AVAILABILITY_USE use) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { switch (use) { case PROJ_GRID_AVAILABILITY_USED_FOR_SORTING: factory_ctx->operationContext->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: USE_FOR_SORTING); break; case PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID: factory_ctx->operationContext->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: DISCARD_OPERATION_IF_MISSING_GRID); break; case PROJ_GRID_AVAILABILITY_IGNORED: factory_ctx->operationContext->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); break; case PROJ_GRID_AVAILABILITY_KNOWN_AVAILABLE: factory_ctx->operationContext->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE); break; } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set whether PROJ alternative grid names should be substituted to * the official authority names. * * The default is true. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param usePROJNames whether PROJ alternative grid names should be used */ void proj_operation_factory_context_set_use_proj_alternative_grid_names( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, int usePROJNames) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { factory_ctx->operationContext->setUsePROJAlternativeGridNames( usePROJNames != 0); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set whether an intermediate pivot CRS can be used for researching * coordinate operations between a source and target CRS. * * Concretely if in the database there is an operation from A to C * (or C to A), and another one from C to B (or B to C), but no direct * operation between A and B, setting this parameter to true, allow * chaining both operations. * * The current implementation is limited to researching one intermediate * step. * * By default, with the IF_NO_DIRECT_TRANSFORMATION strategy, all potential * C candidates will be used if there is no direct transformation. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param use whether and how intermediate CRS may be used. */ void proj_operation_factory_context_set_allow_use_intermediate_crs( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_INTERMEDIATE_CRS_USE use) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { switch (use) { case PROJ_INTERMEDIATE_CRS_USE_ALWAYS: factory_ctx->operationContext->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::ALWAYS); break; case PROJ_INTERMEDIATE_CRS_USE_IF_NO_DIRECT_TRANSFORMATION: factory_ctx->operationContext->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse:: IF_NO_DIRECT_TRANSFORMATION); break; case PROJ_INTERMEDIATE_CRS_USE_NEVER: factory_ctx->operationContext->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::NEVER); break; } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Restrict the potential pivot CRSs that can be used when trying to * build a coordinate operation between two CRS that have no direct operation. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param list_of_auth_name_codes an array of strings NLL terminated, * with the format { "auth_name1", "code1", "auth_name2", "code2", ... NULL } */ void proj_operation_factory_context_set_allowed_intermediate_crs( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, const char *const *list_of_auth_name_codes) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { std::vector<std::pair<std::string, std::string>> pivots; for (auto iter = list_of_auth_name_codes; iter && iter[0] && iter[1]; iter += 2) { pivots.emplace_back(std::pair<std::string, std::string>( std::string(iter[0]), std::string(iter[1]))); } factory_ctx->operationContext->setIntermediateCRS(pivots); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set whether transformations that are superseded (but not deprecated) * should be discarded. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param discard superseded crs or not */ void proj_operation_factory_context_set_discard_superseded( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, int discard) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { factory_ctx->operationContext->setDiscardSuperseded(discard != 0); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- /** \brief Set whether ballpark transformations are allowed. * * @param ctx PROJ context, or NULL for default context * @param factory_ctx Operation factory context. must not be NULL * @param allow set to TRUE to allow ballpark transformations. * @since 7.1 */ void proj_operation_factory_context_set_allow_ballpark_transformations( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, int allow) { SANITIZE_CTX(ctx); if (!factory_ctx) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return; } try { factory_ctx->operationContext->setAllowBallparkTransformations(allow != 0); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Opaque object representing a set of operation results. */ struct PJ_OPERATION_LIST : PJ_OBJ_LIST { PJ *source_crs; PJ *target_crs; bool hasPreparedOperation = false; std::vector<PJCoordOperation> preparedOperations{}; explicit PJ_OPERATION_LIST(PJ_CONTEXT *ctx, const PJ *source_crsIn, const PJ *target_crsIn, std::vector<IdentifiedObjectNNPtr> &&objectsIn); ~PJ_OPERATION_LIST() override; PJ_OPERATION_LIST(const PJ_OPERATION_LIST &) = delete; PJ_OPERATION_LIST &operator=(const PJ_OPERATION_LIST &) = delete; const std::vector<PJCoordOperation> &getPreparedOperations(PJ_CONTEXT *ctx); }; // --------------------------------------------------------------------------- PJ_OPERATION_LIST::PJ_OPERATION_LIST( PJ_CONTEXT *ctx, const PJ *source_crsIn, const PJ *target_crsIn, std::vector<IdentifiedObjectNNPtr> &&objectsIn) : PJ_OBJ_LIST(std::move(objectsIn)), source_crs(proj_clone(ctx, source_crsIn)), target_crs(proj_clone(ctx, target_crsIn)) {} // --------------------------------------------------------------------------- PJ_OPERATION_LIST::~PJ_OPERATION_LIST() { auto tmpCtxt = proj_context_create(); proj_assign_context(source_crs, tmpCtxt); proj_assign_context(target_crs, tmpCtxt); proj_destroy(source_crs); proj_destroy(target_crs); proj_context_destroy(tmpCtxt); } // --------------------------------------------------------------------------- const std::vector<PJCoordOperation> & PJ_OPERATION_LIST::getPreparedOperations(PJ_CONTEXT *ctx) { if (!hasPreparedOperation) { hasPreparedOperation = true; preparedOperations = pj_create_prepared_operations(ctx, source_crs, target_crs, this); } return preparedOperations; } //! @endcond // --------------------------------------------------------------------------- /** \brief Find a list of CoordinateOperation from source_crs to target_crs. * * The operations are sorted with the most relevant ones first: by * descending * area (intersection of the transformation area with the area of interest, * or intersection of the transformation with the area of use of the CRS), * and * by increasing accuracy. Operations with unknown accuracy are sorted last, * whatever their area. * * Starting with PROJ 9.1, vertical transformations are only done if both * source CRS and target CRS are 3D CRS or Compound CRS with a vertical * component. You may need to use proj_crs_promote_to_3D(). * * @param ctx PROJ context, or NULL for default context * @param source_crs source CRS. Must not be NULL. * @param target_crs source CRS. Must not be NULL. * @param operationContext Search context. Must not be NULL. * @return a result set that must be unreferenced with * proj_list_destroy(), or NULL in case of error. */ PJ_OBJ_LIST * proj_create_operations(PJ_CONTEXT *ctx, const PJ *source_crs, const PJ *target_crs, const PJ_OPERATION_FACTORY_CONTEXT *operationContext) { SANITIZE_CTX(ctx); if (!source_crs || !target_crs || !operationContext) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto sourceCRS = std::dynamic_pointer_cast<CRS>(source_crs->iso_obj); CoordinateMetadataPtr sourceCoordinateMetadata; if (!sourceCRS) { sourceCoordinateMetadata = std::dynamic_pointer_cast<CoordinateMetadata>(source_crs->iso_obj); if (!sourceCoordinateMetadata) { proj_log_error(ctx, __FUNCTION__, "source_crs is not a CRS or a CoordinateMetadata"); return nullptr; } if (!sourceCoordinateMetadata->coordinateEpoch().has_value()) { sourceCRS = sourceCoordinateMetadata->crs().as_nullable(); sourceCoordinateMetadata.reset(); } } auto targetCRS = std::dynamic_pointer_cast<CRS>(target_crs->iso_obj); CoordinateMetadataPtr targetCoordinateMetadata; if (!targetCRS) { targetCoordinateMetadata = std::dynamic_pointer_cast<CoordinateMetadata>(target_crs->iso_obj); if (!targetCoordinateMetadata) { proj_log_error(ctx, __FUNCTION__, "target_crs is not a CRS or a CoordinateMetadata"); return nullptr; } if (!targetCoordinateMetadata->coordinateEpoch().has_value()) { targetCRS = targetCoordinateMetadata->crs().as_nullable(); targetCoordinateMetadata.reset(); } } try { auto factory = CoordinateOperationFactory::create(); std::vector<IdentifiedObjectNNPtr> objects; auto ops = sourceCoordinateMetadata != nullptr ? (targetCoordinateMetadata != nullptr ? factory->createOperations( NN_NO_CHECK(sourceCoordinateMetadata), NN_NO_CHECK(targetCoordinateMetadata), operationContext->operationContext) : factory->createOperations( NN_NO_CHECK(sourceCoordinateMetadata), NN_NO_CHECK(targetCRS), operationContext->operationContext)) : targetCoordinateMetadata != nullptr ? factory->createOperations( NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCoordinateMetadata), operationContext->operationContext) : factory->createOperations( NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), operationContext->operationContext); for (const auto &op : ops) { objects.emplace_back(op); } return new PJ_OPERATION_LIST(ctx, source_crs, target_crs, std::move(objects)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** Return the index of the operation that would be the most appropriate to * transform the specified coordinates. * * This operation may use resources that are not locally available, depending * on the search criteria used by proj_create_operations(). * * This could be done by using proj_create_operations() with a punctual bounding * box, but this function is faster when one needs to evaluate on many points * with the same (source_crs, target_crs) tuple. * * @param ctx PROJ context, or NULL for default context * @param operations List of operations returned by proj_create_operations() * @param direction Direction into which to transform the point. * @param coord Coordinate to transform * @return the index in operations that would be used to transform coord. Or -1 * in case of error, or no match. * * @since 7.1 */ int proj_get_suggested_operation(PJ_CONTEXT *ctx, PJ_OBJ_LIST *operations, // cppcheck-suppress passedByValue PJ_DIRECTION direction, PJ_COORD coord) { SANITIZE_CTX(ctx); auto opList = dynamic_cast<PJ_OPERATION_LIST *>(operations); if (opList == nullptr) { proj_log_error(ctx, __FUNCTION__, "operations is not a list of operations"); return -1; } // Special case: // proj_create_crs_to_crs_from_pj() always use the unique operation // if there's a single one if (opList->objects.size() == 1) { return 0; } int iExcluded[2] = {-1, -1}; const auto &preparedOps = opList->getPreparedOperations(ctx); int idx = pj_get_suggested_operation(ctx, preparedOps, iExcluded, /* skipNonInstantiable= */ false, direction, coord); if (idx >= 0) { idx = preparedOps[idx].idxInOriginalList; } return idx; } // --------------------------------------------------------------------------- /** \brief Return the number of objects in the result set * * @param result Object of type PJ_OBJ_LIST (must not be NULL) */ int proj_list_get_count(const PJ_OBJ_LIST *result) { if (!result) { return 0; } return static_cast<int>(result->objects.size()); } // --------------------------------------------------------------------------- /** \brief Return an object from the result set * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param result Object of type PJ_OBJ_LIST (must not be NULL) * @param index Index * @return a new object that must be unreferenced with proj_destroy(), * or nullptr in case of error. */ PJ *proj_list_get(PJ_CONTEXT *ctx, const PJ_OBJ_LIST *result, int index) { SANITIZE_CTX(ctx); if (!result) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } if (index < 0 || index >= proj_list_get_count(result)) { proj_log_error(ctx, __FUNCTION__, "Invalid index"); return nullptr; } return pj_obj_create(ctx, result->objects[index]); } // --------------------------------------------------------------------------- /** \brief Drops a reference on the result set. * * This method should be called one and exactly one for each function * returning a PJ_OBJ_LIST* * * @param result Object, or NULL. */ void proj_list_destroy(PJ_OBJ_LIST *result) { delete result; } // --------------------------------------------------------------------------- /** \brief Return the accuracy (in metre) of a coordinate operation. * * @param ctx PROJ context, or NULL for default context * @param coordoperation Coordinate operation. Must not be NULL. * @return the accuracy, or a negative value if unknown or in case of error. */ double proj_coordoperation_get_accuracy(PJ_CONTEXT *ctx, const PJ *coordoperation) { SANITIZE_CTX(ctx); if (!coordoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return -1; } auto co = dynamic_cast<const CoordinateOperation *>( coordoperation->iso_obj.get()); if (!co) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateOperation"); return -1; } const auto &accuracies = co->coordinateOperationAccuracies(); if (accuracies.empty()) { return -1; } try { return c_locale_stod(accuracies[0]->value()); } catch (const std::exception &) { } return -1; } // --------------------------------------------------------------------------- /** \brief Returns the datum of a SingleCRS. * * If that function returns NULL, @see proj_crs_get_datum_ensemble() to * potentially get a DatumEnsemble instead. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type SingleCRS (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error (or if there is no datum) */ PJ *proj_crs_get_datum(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_crs = dynamic_cast<const SingleCRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a SingleCRS"); return nullptr; } const auto &datum = l_crs->datum(); if (!datum) { return nullptr; } return pj_obj_create(ctx, NN_NO_CHECK(datum)); } // --------------------------------------------------------------------------- /** \brief Returns the datum ensemble of a SingleCRS. * * If that function returns NULL, @see proj_crs_get_datum() to * potentially get a Datum instead. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type SingleCRS (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error (or if there is no datum ensemble) * * @since 7.2 */ PJ *proj_crs_get_datum_ensemble(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_crs = dynamic_cast<const SingleCRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a SingleCRS"); return nullptr; } const auto &datumEnsemble = l_crs->datumEnsemble(); if (!datumEnsemble) { return nullptr; } return pj_obj_create(ctx, NN_NO_CHECK(datumEnsemble)); } // --------------------------------------------------------------------------- /** \brief Returns the number of members of a datum ensemble. * * @param ctx PROJ context, or NULL for default context * @param datum_ensemble Object of type DatumEnsemble (must not be NULL) * * @since 7.2 */ int proj_datum_ensemble_get_member_count(PJ_CONTEXT *ctx, const PJ *datum_ensemble) { SANITIZE_CTX(ctx); if (!datum_ensemble) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return 0; } auto l_datum_ensemble = dynamic_cast<const DatumEnsemble *>(datum_ensemble->iso_obj.get()); if (!l_datum_ensemble) { proj_log_error(ctx, __FUNCTION__, "Object is not a DatumEnsemble"); return 0; } return static_cast<int>(l_datum_ensemble->datums().size()); } // --------------------------------------------------------------------------- /** \brief Returns the positional accuracy of the datum ensemble. * * @param ctx PROJ context, or NULL for default context * @param datum_ensemble Object of type DatumEnsemble (must not be NULL) * @return the accuracy, or -1 in case of error. * * @since 7.2 */ double proj_datum_ensemble_get_accuracy(PJ_CONTEXT *ctx, const PJ *datum_ensemble) { SANITIZE_CTX(ctx); if (!datum_ensemble) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return -1; } auto l_datum_ensemble = dynamic_cast<const DatumEnsemble *>(datum_ensemble->iso_obj.get()); if (!l_datum_ensemble) { proj_log_error(ctx, __FUNCTION__, "Object is not a DatumEnsemble"); return -1; } const auto &accuracy = l_datum_ensemble->positionalAccuracy(); try { return c_locale_stod(accuracy->value()); } catch (const std::exception &) { } return -1; } // --------------------------------------------------------------------------- /** \brief Returns a member from a datum ensemble. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param datum_ensemble Object of type DatumEnsemble (must not be NULL) * @param member_index Index of the datum member to extract (between 0 and * proj_datum_ensemble_get_member_count()-1) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error (or if there is no datum ensemble) * * @since 7.2 */ PJ *proj_datum_ensemble_get_member(PJ_CONTEXT *ctx, const PJ *datum_ensemble, int member_index) { SANITIZE_CTX(ctx); if (!datum_ensemble) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_datum_ensemble = dynamic_cast<const DatumEnsemble *>(datum_ensemble->iso_obj.get()); if (!l_datum_ensemble) { proj_log_error(ctx, __FUNCTION__, "Object is not a DatumEnsemble"); return nullptr; } if (member_index < 0 || member_index >= static_cast<int>(l_datum_ensemble->datums().size())) { proj_log_error(ctx, __FUNCTION__, "Invalid member_index"); return nullptr; } return pj_obj_create(ctx, l_datum_ensemble->datums()[member_index]); } // --------------------------------------------------------------------------- /** \brief Returns a datum for a SingleCRS. * * If the SingleCRS has a datum, then this datum is returned. * Otherwise, the SingleCRS has a datum ensemble, and this datum ensemble is * returned as a regular datum instead of a datum ensemble. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type SingleCRS (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error (or if there is no datum) * * @since 7.2 */ PJ *proj_crs_get_datum_forced(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_crs = dynamic_cast<const SingleCRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a SingleCRS"); return nullptr; } const auto &datum = l_crs->datum(); if (datum) { return pj_obj_create(ctx, NN_NO_CHECK(datum)); } const auto &datumEnsemble = l_crs->datumEnsemble(); assert(datumEnsemble); auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { return pj_obj_create(ctx, datumEnsemble->asDatum(dbContext)); } catch (const std::exception &e) { proj_log_debug(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Returns the frame reference epoch of a dynamic geodetic or vertical * reference frame. * * @param ctx PROJ context, or NULL for default context * @param datum Object of type DynamicGeodeticReferenceFrame or * DynamicVerticalReferenceFrame (must not be NULL) * @return the frame reference epoch as decimal year, or -1 in case of error. * * @since 7.2 */ double proj_dynamic_datum_get_frame_reference_epoch(PJ_CONTEXT *ctx, const PJ *datum) { SANITIZE_CTX(ctx); if (!datum) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return -1; } auto dgrf = dynamic_cast<const DynamicGeodeticReferenceFrame *>( datum->iso_obj.get()); auto dvrf = dynamic_cast<const DynamicVerticalReferenceFrame *>( datum->iso_obj.get()); if (!dgrf && !dvrf) { proj_log_error(ctx, __FUNCTION__, "Object is not a " "DynamicGeodeticReferenceFrame or " "DynamicVerticalReferenceFrame"); return -1; } const auto &frameReferenceEpoch = dgrf ? dgrf->frameReferenceEpoch() : dvrf->frameReferenceEpoch(); return frameReferenceEpoch.value(); } // --------------------------------------------------------------------------- /** \brief Returns the coordinate system of a SingleCRS. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param crs Object of type SingleCRS (must not be NULL) * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_crs_get_coordinate_system(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_crs = dynamic_cast<const SingleCRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a SingleCRS"); return nullptr; } return pj_obj_create(ctx, l_crs->coordinateSystem()); } // --------------------------------------------------------------------------- /** \brief Returns the type of the coordinate system. * * @param ctx PROJ context, or NULL for default context * @param cs Object of type CoordinateSystem (must not be NULL) * @return type, or PJ_CS_TYPE_UNKNOWN in case of error. */ PJ_COORDINATE_SYSTEM_TYPE proj_cs_get_type(PJ_CONTEXT *ctx, const PJ *cs) { SANITIZE_CTX(ctx); if (!cs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return PJ_CS_TYPE_UNKNOWN; } auto l_cs = dynamic_cast<const CoordinateSystem *>(cs->iso_obj.get()); if (!l_cs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateSystem"); return PJ_CS_TYPE_UNKNOWN; } if (dynamic_cast<const CartesianCS *>(l_cs)) { return PJ_CS_TYPE_CARTESIAN; } if (dynamic_cast<const EllipsoidalCS *>(l_cs)) { return PJ_CS_TYPE_ELLIPSOIDAL; } if (dynamic_cast<const VerticalCS *>(l_cs)) { return PJ_CS_TYPE_VERTICAL; } if (dynamic_cast<const SphericalCS *>(l_cs)) { return PJ_CS_TYPE_SPHERICAL; } if (dynamic_cast<const OrdinalCS *>(l_cs)) { return PJ_CS_TYPE_ORDINAL; } if (dynamic_cast<const ParametricCS *>(l_cs)) { return PJ_CS_TYPE_PARAMETRIC; } if (dynamic_cast<const DateTimeTemporalCS *>(l_cs)) { return PJ_CS_TYPE_DATETIMETEMPORAL; } if (dynamic_cast<const TemporalCountCS *>(l_cs)) { return PJ_CS_TYPE_TEMPORALCOUNT; } if (dynamic_cast<const TemporalMeasureCS *>(l_cs)) { return PJ_CS_TYPE_TEMPORALMEASURE; } return PJ_CS_TYPE_UNKNOWN; } // --------------------------------------------------------------------------- /** \brief Returns the number of axis of the coordinate system. * * @param ctx PROJ context, or NULL for default context * @param cs Object of type CoordinateSystem (must not be NULL) * @return number of axis, or -1 in case of error. */ int proj_cs_get_axis_count(PJ_CONTEXT *ctx, const PJ *cs) { SANITIZE_CTX(ctx); if (!cs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return -1; } auto l_cs = dynamic_cast<const CoordinateSystem *>(cs->iso_obj.get()); if (!l_cs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateSystem"); return -1; } return static_cast<int>(l_cs->axisList().size()); } // --------------------------------------------------------------------------- /** \brief Returns information on an axis * * @param ctx PROJ context, or NULL for default context * @param cs Object of type CoordinateSystem (must not be NULL) * @param index Index of the coordinate system (between 0 and * proj_cs_get_axis_count() - 1) * @param out_name Pointer to a string value to store the axis name. or NULL * @param out_abbrev Pointer to a string value to store the axis abbreviation. * or NULL * @param out_direction Pointer to a string value to store the axis direction. * or NULL * @param out_unit_conv_factor Pointer to a double value to store the axis * unit conversion factor. or NULL * @param out_unit_name Pointer to a string value to store the axis * unit name. or NULL * @param out_unit_auth_name Pointer to a string value to store the axis * unit authority name. or NULL * @param out_unit_code Pointer to a string value to store the axis * unit code. or NULL * @return TRUE in case of success */ int proj_cs_get_axis_info(PJ_CONTEXT *ctx, const PJ *cs, int index, const char **out_name, const char **out_abbrev, const char **out_direction, double *out_unit_conv_factor, const char **out_unit_name, const char **out_unit_auth_name, const char **out_unit_code) { SANITIZE_CTX(ctx); if (!cs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto l_cs = dynamic_cast<const CoordinateSystem *>(cs->iso_obj.get()); if (!l_cs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateSystem"); return false; } const auto &axisList = l_cs->axisList(); if (index < 0 || static_cast<size_t>(index) >= axisList.size()) { proj_log_error(ctx, __FUNCTION__, "Invalid index"); return false; } const auto &axis = axisList[index]; if (out_name) { *out_name = axis->nameStr().c_str(); } if (out_abbrev) { *out_abbrev = axis->abbreviation().c_str(); } if (out_direction) { *out_direction = axis->direction().toString().c_str(); } if (out_unit_conv_factor) { *out_unit_conv_factor = axis->unit().conversionToSI(); } if (out_unit_name) { *out_unit_name = axis->unit().name().c_str(); } if (out_unit_auth_name) { *out_unit_auth_name = axis->unit().codeSpace().c_str(); } if (out_unit_code) { *out_unit_code = axis->unit().code().c_str(); } return true; } // --------------------------------------------------------------------------- /** \brief Returns a PJ* object whose axis order is the one expected for * visualization purposes. * * The input object must be either: * <ul> * <li>a coordinate operation, that has been created with * proj_create_crs_to_crs(). If the axis order of its source or target CRS * is northing,easting, then an axis swap operation will be inserted.</li> * <li>or a CRS. The axis order of geographic CRS will be longitude, latitude * [,height], and the one of projected CRS will be easting, northing * [, height]</li> * </ul> * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CRS, or CoordinateOperation created with * proj_create_crs_to_crs() (must not be NULL) * @return a new PJ* object to free with proj_destroy() in case of success, or * nullptr in case of error */ PJ *proj_normalize_for_visualization(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); if (!obj->alternativeCoordinateOperations.empty()) { try { auto pjNew = std::unique_ptr<PJ>(pj_new()); if (!pjNew) return nullptr; pjNew->ctx = ctx; pjNew->descr = "Set of coordinate operations"; pjNew->left = obj->left; pjNew->right = obj->right; pjNew->over = obj->over; for (const auto &alt : obj->alternativeCoordinateOperations) { auto co = dynamic_cast<const CoordinateOperation *>( alt.pj->iso_obj.get()); if (co) { double minxSrc = alt.minxSrc; double minySrc = alt.minySrc; double maxxSrc = alt.maxxSrc; double maxySrc = alt.maxySrc; double minxDst = alt.minxDst; double minyDst = alt.minyDst; double maxxDst = alt.maxxDst; double maxyDst = alt.maxyDst; auto l_sourceCRS = co->sourceCRS(); auto l_targetCRS = co->targetCRS(); if (l_sourceCRS && l_targetCRS) { const bool swapSource = l_sourceCRS ->mustAxisOrderBeSwitchedForVisualization(); if (swapSource) { std::swap(minxSrc, minySrc); std::swap(maxxSrc, maxySrc); } const bool swapTarget = l_targetCRS ->mustAxisOrderBeSwitchedForVisualization(); if (swapTarget) { std::swap(minxDst, minyDst); std::swap(maxxDst, maxyDst); } } ctx->forceOver = alt.pj->over != 0; auto pjNormalized = pj_obj_create(ctx, co->normalizeForVisualization()); pjNormalized->over = alt.pj->over; ctx->forceOver = false; pjNew->alternativeCoordinateOperations.emplace_back( alt.idxInOriginalList, minxSrc, minySrc, maxxSrc, maxySrc, minxDst, minyDst, maxxDst, maxyDst, pjNormalized, co->nameStr(), alt.accuracy, alt.pseudoArea, alt.areaName.c_str(), alt.pjSrcGeocentricToLonLat, alt.pjDstGeocentricToLonLat); } } return pjNew.release(); } catch (const std::exception &e) { ctx->forceOver = false; proj_log_debug(ctx, __FUNCTION__, e.what()); return nullptr; } } auto crs = dynamic_cast<const CRS *>(obj->iso_obj.get()); if (crs) { try { return pj_obj_create(ctx, crs->normalizeForVisualization()); } catch (const std::exception &e) { proj_log_debug(ctx, __FUNCTION__, e.what()); return nullptr; } } auto co = dynamic_cast<const CoordinateOperation *>(obj->iso_obj.get()); if (!co) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateOperation " "created with " "proj_create_crs_to_crs"); return nullptr; } try { ctx->forceOver = obj->over != 0; auto pjNormalized = pj_obj_create(ctx, co->normalizeForVisualization()); pjNormalized->over = obj->over; ctx->forceOver = false; return pjNormalized; } catch (const std::exception &e) { ctx->forceOver = false; proj_log_debug(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Returns a PJ* coordinate operation object which represents the * inverse operation of the specified coordinate operation. * * @param ctx PROJ context, or NULL for default context * @param obj Object of type CoordinateOperation (must not be NULL) * @return a new PJ* object to free with proj_destroy() in case of success, or * nullptr in case of error * @since 6.3 */ PJ *proj_coordoperation_create_inverse(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto co = dynamic_cast<const CoordinateOperation *>(obj->iso_obj.get()); if (!co) { proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateOperation"); return nullptr; } try { return pj_obj_create(ctx, co->inverse()); } catch (const std::exception &e) { proj_log_debug(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Returns the number of steps of a concatenated operation. * * The input object must be a concatenated operation. * * @param ctx PROJ context, or NULL for default context * @param concatoperation Concatenated operation (must not be NULL) * @return the number of steps, or 0 in case of error. */ int proj_concatoperation_get_step_count(PJ_CONTEXT *ctx, const PJ *concatoperation) { SANITIZE_CTX(ctx); if (!concatoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto l_co = dynamic_cast<const ConcatenatedOperation *>( concatoperation->iso_obj.get()); if (!l_co) { proj_log_error(ctx, __FUNCTION__, "Object is not a ConcatenatedOperation"); return false; } return static_cast<int>(l_co->operations().size()); } // --------------------------------------------------------------------------- /** \brief Returns a step of a concatenated operation. * * The input object must be a concatenated operation. * * The returned object must be unreferenced with proj_destroy() after * use. * It should be used by at most one thread at a time. * * @param ctx PROJ context, or NULL for default context * @param concatoperation Concatenated operation (must not be NULL) * @param i_step Index of the step to extract. Between 0 and * proj_concatoperation_get_step_count()-1 * @return Object that must be unreferenced with proj_destroy(), or NULL * in case of error. */ PJ *proj_concatoperation_get_step(PJ_CONTEXT *ctx, const PJ *concatoperation, int i_step) { SANITIZE_CTX(ctx); if (!concatoperation) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto l_co = dynamic_cast<const ConcatenatedOperation *>( concatoperation->iso_obj.get()); if (!l_co) { proj_log_error(ctx, __FUNCTION__, "Object is not a ConcatenatedOperation"); return nullptr; } const auto &steps = l_co->operations(); if (i_step < 0 || static_cast<size_t>(i_step) >= steps.size()) { proj_log_error(ctx, __FUNCTION__, "Invalid step index"); return nullptr; } return pj_obj_create(ctx, steps[i_step]); } // --------------------------------------------------------------------------- /** \brief Opaque object representing an insertion session. */ struct PJ_INSERT_SESSION { //! @cond Doxygen_Suppress PJ_CONTEXT *ctx = nullptr; //!  @endcond }; // --------------------------------------------------------------------------- /** \brief Starts a session for proj_get_insert_statements() * * Starts a new session for one or several calls to * proj_get_insert_statements(). * * An insertion session guarantees that the inserted objects will not create * conflicting intermediate objects. * * The session must be stopped with proj_insert_object_session_destroy(). * * Only one session may be active at a time for a given context. * * @param ctx PROJ context, or NULL for default context * @return the session, or NULL in case of error. * * @since 8.1 */ PJ_INSERT_SESSION *proj_insert_object_session_create(PJ_CONTEXT *ctx) { SANITIZE_CTX(ctx); try { auto dbContext = getDBcontext(ctx); dbContext->startInsertStatementsSession(); PJ_INSERT_SESSION *session = new PJ_INSERT_SESSION; session->ctx = ctx; return session; } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Stops an insertion session started with * proj_insert_object_session_create() * * @param ctx PROJ context, or NULL for default context * @param session The insertion session. * @since 8.1 */ void proj_insert_object_session_destroy(PJ_CONTEXT *ctx, PJ_INSERT_SESSION *session) { SANITIZE_CTX(ctx); if (session) { try { if (session->ctx != ctx) { proj_log_error(ctx, __FUNCTION__, "proj_insert_object_session_destroy() called " "with a context different from the one of " "proj_insert_object_session_create()"); } else { auto dbContext = getDBcontext(ctx); dbContext->stopInsertStatementsSession(); } } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } delete session; } } // --------------------------------------------------------------------------- /** \brief Suggests a database code for the passed object. * * Supported type of objects are PrimeMeridian, Ellipsoid, Datum, DatumEnsemble, * GeodeticCRS, ProjectedCRS, VerticalCRS, CompoundCRS, BoundCRS, Conversion. * * @param ctx PROJ context, or NULL for default context * @param object Object for which to suggest a code. * @param authority Authority name into which the object will be inserted. * @param numeric_code Whether the code should be numeric, or derived from the * object name. * @param options NULL terminated list of options, or NULL. * No options are supported currently. * @return the suggested code, that is guaranteed to not conflict with an * existing one (to be freed with proj_string_destroy), * or nullptr in case of error. * * @since 8.1 */ char *proj_suggests_code_for(PJ_CONTEXT *ctx, const PJ *object, const char *authority, int numeric_code, const char *const *options) { SANITIZE_CTX(ctx); (void)options; if (!object || !authority) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto identifiedObject = std::dynamic_pointer_cast<IdentifiedObject>(object->iso_obj); if (!identifiedObject) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "Object is not a IdentifiedObject"); return nullptr; } try { auto dbContext = getDBcontext(ctx); return pj_strdup(dbContext ->suggestsCodeFor(NN_NO_CHECK(identifiedObject), std::string(authority), numeric_code != FALSE) .c_str()); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Free a string. * * Only to be used with functions that document using this function. * * @param str String to free. * * @since 8.1 */ void proj_string_destroy(char *str) { free(str); } // --------------------------------------------------------------------------- /** \brief Returns SQL statements needed to insert the passed object into the * database. * * proj_insert_object_session_create() may have been called previously. * * It is strongly recommended that new objects should not be added in common * registries, such as "EPSG", "ESRI", "IAU", etc. Users should use a custom * authority name instead. If a new object should be * added to the official EPSG registry, users are invited to follow the * procedure explained at https://epsg.org/dataset-change-requests.html. * * Combined with proj_context_get_database_structure(), users can create * auxiliary databases, instead of directly modifying the main proj.db database. * Those auxiliary databases can be specified through * proj_context_set_database_path() or the PROJ_AUX_DB environment variable. * * @param ctx PROJ context, or NULL for default context * @param session The insertion session. May be NULL if a single object must be * inserted. * @param object The object to insert into the database. Currently only * PrimeMeridian, Ellipsoid, Datum, GeodeticCRS, ProjectedCRS, * VerticalCRS, CompoundCRS or BoundCRS are supported. * @param authority Authority name into which the object will be inserted. * Must not be NULL. * @param code Code with which the object will be inserted.Must not be NULL. * @param numeric_codes Whether intermediate objects that can be created should * use numeric codes (true), or may be alphanumeric (false) * @param allowed_authorities NULL terminated list of authority names, or NULL. * Authorities to which intermediate objects are * allowed to refer to. "authority" will be * implicitly added to it. Note that unit, * coordinate systems, projection methods and * parameters will in any case be allowed to refer * to EPSG. * If NULL, allowed_authorities defaults to * {"EPSG", "PROJ", nullptr} * @param options NULL terminated list of options, or NULL. * No options are supported currently. * * @return a list of insert statements (to be freed with * proj_string_list_destroy()), or NULL in case of error. * @since 8.1 */ PROJ_STRING_LIST proj_get_insert_statements( PJ_CONTEXT *ctx, PJ_INSERT_SESSION *session, const PJ *object, const char *authority, const char *code, int numeric_codes, const char *const *allowed_authorities, const char *const *options) { SANITIZE_CTX(ctx); (void)options; struct TempSessionHolder { PJ_CONTEXT *m_ctx; PJ_INSERT_SESSION *m_tempSession = nullptr; TempSessionHolder(const TempSessionHolder &) = delete; TempSessionHolder &operator=(const TempSessionHolder &) = delete; TempSessionHolder(PJ_CONTEXT *ctx, PJ_INSERT_SESSION *session) : m_ctx(ctx), m_tempSession(session ? nullptr : proj_insert_object_session_create(ctx)) {} ~TempSessionHolder() { if (m_tempSession) { proj_insert_object_session_destroy(m_ctx, m_tempSession); } } }; try { TempSessionHolder oHolder(ctx, session); if (!session) { session = oHolder.m_tempSession; if (!session) { return nullptr; } } if (!object || !authority || !code) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto identifiedObject = std::dynamic_pointer_cast<IdentifiedObject>(object->iso_obj); if (!identifiedObject) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "Object is not a IdentifiedObject"); return nullptr; } auto dbContext = getDBcontext(ctx); std::vector<std::string> allowedAuthorities{"EPSG", "PROJ"}; if (allowed_authorities) { allowedAuthorities.clear(); for (auto iter = allowed_authorities; *iter; ++iter) { allowedAuthorities.emplace_back(*iter); } } auto statements = dbContext->getInsertStatementsFor( NN_NO_CHECK(identifiedObject), authority, code, numeric_codes != FALSE, allowedAuthorities); return to_string_list(std::move(statements)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Returns a list of geoid models available for that crs * * The list includes the geoid models connected directly with the crs, * or via "Height Depth Reversal" or "Change of Vertical Unit" transformations. * The returned list is NULL terminated and must be freed with * proj_string_list_destroy(). * * @param ctx Context, or NULL for default context. * @param auth_name Authority name (must not be NULL) * @param code Object code (must not be NULL) * @param options should be set to NULL for now * @return list of geoid models names (to be freed with * proj_string_list_destroy()), or NULL in case of error. * @since 8.1 */ PROJ_STRING_LIST proj_get_geoid_models_from_database(PJ_CONTEXT *ctx, const char *auth_name, const char *code, const char *const *options) { SANITIZE_CTX(ctx); if (!auth_name || !code) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } (void)options; try { const std::string codeStr(code); auto factory = AuthorityFactory::create(getDBcontext(ctx), auth_name); auto geoidModels = factory->getGeoidModels(codeStr); return to_string_list(std::move(geoidModels)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return nullptr; } // --------------------------------------------------------------------------- /** \brief Instanciate a CoordinateMetadata object * * @since 9.4 */ PJ *proj_coordinate_metadata_create(PJ_CONTEXT *ctx, const PJ *crs, double epoch) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return nullptr; } auto crsCast = std::dynamic_pointer_cast<CRS>(crs->iso_obj); if (!crsCast) { proj_log_error(ctx, __FUNCTION__, "Object is not a CRS"); return nullptr; } try { auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); return pj_obj_create(ctx, CoordinateMetadata::create( NN_NO_CHECK(crsCast), epoch, dbContext)); } catch (const std::exception &e) { proj_log_debug(ctx, __FUNCTION__, e.what()); return nullptr; } } // --------------------------------------------------------------------------- /** \brief Return the coordinate epoch associated with a CoordinateMetadata. * * It may return a NaN value if there is no associated coordinate epoch. * * @since 9.2 */ double proj_coordinate_metadata_get_epoch(PJ_CONTEXT *ctx, const PJ *obj) { SANITIZE_CTX(ctx); if (!obj) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return std::numeric_limits<double>::quiet_NaN(); } auto ptr = obj->iso_obj.get(); auto coordinateMetadata = dynamic_cast<const CoordinateMetadata *>(ptr); if (coordinateMetadata) { if (coordinateMetadata->coordinateEpoch().has_value()) { return coordinateMetadata->coordinateEpochAsDecimalYear(); } return std::numeric_limits<double>::quiet_NaN(); } proj_log_error(ctx, __FUNCTION__, "Object is not a CoordinateMetadata"); return std::numeric_limits<double>::quiet_NaN(); } // --------------------------------------------------------------------------- /** \brief Return whether a CRS has an associated PointMotionOperation * * @since 9.4 */ int proj_crs_has_point_motion_operation(PJ_CONTEXT *ctx, const PJ *crs) { SANITIZE_CTX(ctx); if (!crs) { proj_context_errno_set(ctx, PROJ_ERR_OTHER_API_MISUSE); proj_log_error(ctx, __FUNCTION__, "missing required input"); return false; } auto l_crs = dynamic_cast<const CRS *>(crs->iso_obj.get()); if (!l_crs) { proj_log_error(ctx, __FUNCTION__, "Object is not a CRS"); return false; } auto geodeticCRS = l_crs->extractGeodeticCRS(); if (!geodeticCRS) return false; try { auto factory = AuthorityFactory::create(getDBcontext(ctx), std::string()); return !factory ->getPointMotionOperationsFor(NN_NO_CHECK(geodeticCRS), false) .empty(); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); } return false; }
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/oputils.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef OPUTILS_HPP #define OPUTILS_HPP #include "proj/coordinateoperation.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress extern const common::Measure nullMeasure; extern const std::string INVERSE_OF; extern const char *BALLPARK_GEOCENTRIC_TRANSLATION; extern const char *NULL_GEOGRAPHIC_OFFSET; extern const char *NULL_GEOCENTRIC_TRANSLATION; extern const char *BALLPARK_GEOGRAPHIC_OFFSET; extern const char *BALLPARK_VERTICAL_TRANSFORMATION; extern const char *BALLPARK_VERTICAL_TRANSFORMATION_NO_ELLIPSOID_VERT_HEIGHT; extern const std::string AXIS_ORDER_CHANGE_2D_NAME; extern const std::string AXIS_ORDER_CHANGE_3D_NAME; OperationParameterNNPtr createOpParamNameEPSGCode(int code); util::PropertyMap createMethodMapNameEPSGCode(int code); util::PropertyMap createMapNameEPSGCode(const std::string &name, int code); util::PropertyMap createMapNameEPSGCode(const char *name, int code); util::PropertyMap &addDomains(util::PropertyMap &map, const common::ObjectUsage *obj); std::string buildOpName(const char *opType, const crs::CRSPtr &source, const crs::CRSPtr &target); void addModifiedIdentifier(util::PropertyMap &map, const common::IdentifiedObject *obj, bool inverse, bool derivedFrom); util::PropertyMap createPropertiesForInverse(const OperationMethodNNPtr &method); util::PropertyMap createPropertiesForInverse(const CoordinateOperation *op, bool derivedFrom, bool approximateInversion); util::PropertyMap addDefaultNameIfNeeded(const util::PropertyMap &properties, const std::string &defaultName); bool areEquivalentParameters(const std::string &a, const std::string &b); bool isTimeDependent(const std::string &methodName); std::string computeConcatenatedName( const std::vector<CoordinateOperationNNPtr> &flattenOps); metadata::ExtentPtr getExtent(const std::vector<CoordinateOperationNNPtr> &ops, bool conversionExtentIsWorld, bool &emptyIntersection); metadata::ExtentPtr getExtent(const CoordinateOperationNNPtr &op, bool conversionExtentIsWorld, bool &emptyIntersection); const metadata::ExtentPtr &getExtent(const crs::CRSNNPtr &crs); const metadata::ExtentPtr getExtentPossiblySynthetized(const crs::CRSNNPtr &crs, bool &approxOut); double getAccuracy(const CoordinateOperationNNPtr &op); double getAccuracy(const std::vector<CoordinateOperationNNPtr> &ops); void exportSourceCRSAndTargetCRSToWKT(const CoordinateOperation *co, io::WKTFormatter *formatter); //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END #endif // OPUTILS_HPP
hpp
PROJ
data/projects/PROJ/src/iso19111/operation/projbasedoperation.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "coordinateoperation_internal.hpp" #include "oputils.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // M_PI // clang-format on #include "proj_constants.h" #include "proj_json_streaming_writer.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <memory> #include <set> #include <string> #include <vector> using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- PROJBasedOperation::~PROJBasedOperation() = default; // --------------------------------------------------------------------------- PROJBasedOperation::PROJBasedOperation(const OperationMethodNNPtr &methodIn) : SingleOperation(methodIn) {} // --------------------------------------------------------------------------- PROJBasedOperationNNPtr PROJBasedOperation::create( const util::PropertyMap &properties, const std::string &PROJString, const crs::CRSPtr &sourceCRS, const crs::CRSPtr &targetCRS, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { auto method = OperationMethod::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, "PROJ-based operation method: " + PROJString), std::vector<GeneralOperationParameterNNPtr>{}); auto op = PROJBasedOperation::nn_make_shared<PROJBasedOperation>(method); op->assignSelf(op); op->projString_ = PROJString; if (sourceCRS && targetCRS) { op->setCRSs(NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), nullptr); } op->setProperties( addDefaultNameIfNeeded(properties, "PROJ-based coordinate operation")); op->setAccuracies(accuracies); return op; } // --------------------------------------------------------------------------- PROJBasedOperationNNPtr PROJBasedOperation::create( const util::PropertyMap &properties, const io::IPROJStringExportableNNPtr &projExportable, bool inverse, const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const crs::CRSPtr &interpolationCRS, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies, bool hasBallparkTransformation) { auto formatter = io::PROJStringFormatter::create(); if (inverse) { formatter->startInversion(); } projExportable->_exportToPROJString(formatter.get()); if (inverse) { formatter->stopInversion(); } const auto &projString = formatter->toString(); auto method = OperationMethod::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, "PROJ-based operation method (approximate): " + projString), std::vector<GeneralOperationParameterNNPtr>{}); auto op = PROJBasedOperation::nn_make_shared<PROJBasedOperation>(method); op->assignSelf(op); op->projString_ = projString; op->setCRSs(sourceCRS, targetCRS, interpolationCRS); op->setProperties( addDefaultNameIfNeeded(properties, "PROJ-based coordinate operation")); op->setAccuracies(accuracies); op->projStringExportable_ = projExportable.as_nullable(); op->inverse_ = inverse; op->setHasBallparkTransformation(hasBallparkTransformation); return op; } // --------------------------------------------------------------------------- CoordinateOperationNNPtr PROJBasedOperation::inverse() const { if (projStringExportable_ && sourceCRS() && targetCRS()) { return util::nn_static_pointer_cast<CoordinateOperation>( PROJBasedOperation::create( createPropertiesForInverse(this, false, false), NN_NO_CHECK(projStringExportable_), !inverse_, NN_NO_CHECK(targetCRS()), NN_NO_CHECK(sourceCRS()), interpolationCRS(), coordinateOperationAccuracies(), hasBallparkTransformation())); } auto formatter = io::PROJStringFormatter::create(); formatter->startInversion(); try { formatter->ingestPROJString(projString_); } catch (const io::ParsingException &e) { throw util::UnsupportedOperationException( std::string("PROJBasedOperation::inverse() failed: ") + e.what()); } formatter->stopInversion(); auto op = PROJBasedOperation::create( createPropertiesForInverse(this, false, false), formatter->toString(), targetCRS(), sourceCRS(), coordinateOperationAccuracies()); if (sourceCRS() && targetCRS()) { op->setCRSs(NN_NO_CHECK(targetCRS()), NN_NO_CHECK(sourceCRS()), interpolationCRS()); } op->setHasBallparkTransformation(hasBallparkTransformation()); return util::nn_static_pointer_cast<CoordinateOperation>(op); } // --------------------------------------------------------------------------- void PROJBasedOperation::_exportToWKT(io::WKTFormatter *formatter) const { if (sourceCRS() && targetCRS()) { exportTransformationToWKT(formatter); return; } const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { throw io::FormattingException( "PROJBasedOperation can only be exported to WKT2"); } formatter->startNode(io::WKTConstants::CONVERSION, false); formatter->addQuotedString(nameStr()); method()->_exportToWKT(formatter); for (const auto &paramValue : parameterValues()) { paramValue->_exportToWKT(formatter); } formatter->endNode(); } // --------------------------------------------------------------------------- void PROJBasedOperation::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext(formatter->MakeObjectContext( (sourceCRS() && targetCRS()) ? "Transformation" : "Conversion", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } if (sourceCRS() && targetCRS()) { writer->AddObjKey("source_crs"); formatter->setAllowIDInImmediateChild(); sourceCRS()->_exportToJSON(formatter); writer->AddObjKey("target_crs"); formatter->setAllowIDInImmediateChild(); targetCRS()->_exportToJSON(formatter); } writer->AddObjKey("method"); formatter->setOmitTypeInImmediateChild(); formatter->setAllowIDInImmediateChild(); method()->_exportToJSON(formatter); const auto &l_parameterValues = parameterValues(); writer->AddObjKey("parameters"); { auto parametersContext(writer->MakeArrayContext(false)); for (const auto &genOpParamvalue : l_parameterValues) { formatter->setAllowIDInImmediateChild(); formatter->setOmitTypeInImmediateChild(); genOpParamvalue->_exportToJSON(formatter); } } } // --------------------------------------------------------------------------- void PROJBasedOperation::_exportToPROJString( io::PROJStringFormatter *formatter) const { if (projStringExportable_) { if (inverse_) { formatter->startInversion(); } projStringExportable_->_exportToPROJString(formatter); if (inverse_) { formatter->stopInversion(); } return; } try { formatter->ingestPROJString(projString_); } catch (const io::ParsingException &e) { throw io::FormattingException( std::string("PROJBasedOperation::exportToPROJString() failed: ") + e.what()); } } // --------------------------------------------------------------------------- CoordinateOperationNNPtr PROJBasedOperation::_shallowClone() const { auto op = PROJBasedOperation::nn_make_shared<PROJBasedOperation>(*this); op->assignSelf(op); op->setCRSs(this, false); return util::nn_static_pointer_cast<CoordinateOperation>(op); } // --------------------------------------------------------------------------- std::set<GridDescription> PROJBasedOperation::gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const { std::set<GridDescription> res; try { auto formatterOut = io::PROJStringFormatter::create(); auto formatter = io::PROJStringFormatter::create(); formatter->ingestPROJString(exportToPROJString(formatterOut.get())); const auto usedGridNames = formatter->getUsedGridNames(); for (const auto &shortName : usedGridNames) { GridDescription desc; desc.shortName = shortName; if (databaseContext) { databaseContext->lookForGridInfo( desc.shortName, considerKnownGridsAsAvailable, desc.fullName, desc.packageName, desc.url, desc.directDownload, desc.openLicense, desc.available); } res.insert(desc); } } catch (const io::ParsingException &) { } return res; } //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/vectorofvaluesparams.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "vectorofvaluesparams.hpp" // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static std::vector<ParameterValueNNPtr> buildParameterValueFromMeasure( const std::initializer_list<common::Measure> &list) { std::vector<ParameterValueNNPtr> res; for (const auto &v : list) { res.emplace_back(ParameterValue::create(v)); } return res; } VectorOfValues::VectorOfValues(std::initializer_list<common::Measure> list) : std::vector<ParameterValueNNPtr>(buildParameterValueFromMeasure(list)) {} // This way, we disable inlining of destruction, and save a lot of space VectorOfValues::~VectorOfValues() = default; VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3) { return VectorOfValues{ParameterValue::create(m1), ParameterValue::create(m2), ParameterValue::create(m3)}; } VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4) { return VectorOfValues{ ParameterValue::create(m1), ParameterValue::create(m2), ParameterValue::create(m3), ParameterValue::create(m4)}; } VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4, const common::Measure &m5) { return VectorOfValues{ ParameterValue::create(m1), ParameterValue::create(m2), ParameterValue::create(m3), ParameterValue::create(m4), ParameterValue::create(m5), }; } VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4, const common::Measure &m5, const common::Measure &m6) { return VectorOfValues{ ParameterValue::create(m1), ParameterValue::create(m2), ParameterValue::create(m3), ParameterValue::create(m4), ParameterValue::create(m5), ParameterValue::create(m6), }; } VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4, const common::Measure &m5, const common::Measure &m6, const common::Measure &m7) { return VectorOfValues{ ParameterValue::create(m1), ParameterValue::create(m2), ParameterValue::create(m3), ParameterValue::create(m4), ParameterValue::create(m5), ParameterValue::create(m6), ParameterValue::create(m7), }; } // This way, we disable inlining of destruction, and save a lot of space VectorOfParameters::~VectorOfParameters() = default; //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/coordinateoperationfactory.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinates.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj/internal/tracing.hpp" #include "coordinateoperation_internal.hpp" #include "coordinateoperation_private.hpp" #include "oputils.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // M_PI // clang-format on #include "proj_constants.h" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <memory> #include <set> #include <string> #include <vector> // #define TRACE_CREATE_OPERATIONS // #define DEBUG_SORT // #define DEBUG_CONCATENATED_OPERATION #if defined(DEBUG_SORT) || defined(DEBUG_CONCATENATED_OPERATION) #include <iostream> void dumpWKT(const NS_PROJ::crs::CRS *crs); void dumpWKT(const NS_PROJ::crs::CRS *crs) { auto f(NS_PROJ::io::WKTFormatter::create( NS_PROJ::io::WKTFormatter::Convention::WKT2_2019)); std::cerr << crs->exportToWKT(f.get()) << std::endl; } void dumpWKT(const NS_PROJ::crs::CRSPtr &crs); void dumpWKT(const NS_PROJ::crs::CRSPtr &crs) { dumpWKT(crs.get()); } void dumpWKT(const NS_PROJ::crs::CRSNNPtr &crs); void dumpWKT(const NS_PROJ::crs::CRSNNPtr &crs) { dumpWKT(crs.as_nullable().get()); } void dumpWKT(const NS_PROJ::crs::GeographicCRSPtr &crs); void dumpWKT(const NS_PROJ::crs::GeographicCRSPtr &crs) { dumpWKT(crs.get()); } void dumpWKT(const NS_PROJ::crs::GeographicCRSNNPtr &crs); void dumpWKT(const NS_PROJ::crs::GeographicCRSNNPtr &crs) { dumpWKT(crs.as_nullable().get()); } #endif using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- #ifdef TRACE_CREATE_OPERATIONS //! @cond Doxygen_Suppress static std::string objectAsStr(const common::IdentifiedObject *obj) { std::string ret(obj->nameStr()); const auto &ids = obj->identifiers(); if (const auto *geogCRS = dynamic_cast<const crs::GeographicCRS *>(obj)) { if (geogCRS->coordinateSystem()->axisList().size() == 3U) ret += " (geographic3D)"; else ret += " (geographic2D)"; } if (const auto *geodCRS = dynamic_cast<const crs::GeodeticCRS *>(obj)) { if (geodCRS->isGeocentric()) { ret += " (geocentric)"; } } if (!ids.empty()) { ret += " ("; ret += (*ids[0]->codeSpace()) + ":" + ids[0]->code(); ret += ")"; } return ret; } //! @endcond #endif // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static double getPseudoArea(const metadata::ExtentPtr &extent) { if (!extent) return 0.0; const auto &geographicElements = extent->geographicElements(); if (geographicElements.empty()) return 0.0; auto bbox = dynamic_cast<const metadata::GeographicBoundingBox *>( geographicElements[0].get()); if (!bbox) return 0; double w = bbox->westBoundLongitude(); double s = bbox->southBoundLatitude(); double e = bbox->eastBoundLongitude(); double n = bbox->northBoundLatitude(); if (w > e) { e += 360.0; } // Integrate cos(lat) between south_lat and north_lat return (e - w) * (std::sin(common::Angle(n).getSIValue()) - std::sin(common::Angle(s).getSIValue())); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CoordinateOperationContext::Private { io::AuthorityFactoryPtr authorityFactory_{}; metadata::ExtentPtr extent_{}; double accuracy_ = 0.0; SourceTargetCRSExtentUse sourceAndTargetCRSExtentUse_ = CoordinateOperationContext::SourceTargetCRSExtentUse::SMALLEST; SpatialCriterion spatialCriterion_ = CoordinateOperationContext::SpatialCriterion::STRICT_CONTAINMENT; bool usePROJNames_ = true; GridAvailabilityUse gridAvailabilityUse_ = GridAvailabilityUse::USE_FOR_SORTING; IntermediateCRSUse allowUseIntermediateCRS_ = CoordinateOperationContext:: IntermediateCRSUse::IF_NO_DIRECT_TRANSFORMATION; std::vector<std::pair<std::string, std::string>> intermediateCRSAuthCodes_{}; bool discardSuperseded_ = true; bool allowBallpark_ = true; std::shared_ptr<util::optional<common::DataEpoch>> sourceCoordinateEpoch_{ std::make_shared<util::optional<common::DataEpoch>>()}; std::shared_ptr<util::optional<common::DataEpoch>> targetCoordinateEpoch_{ std::make_shared<util::optional<common::DataEpoch>>()}; Private() = default; Private(const Private &) = default; }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateOperationContext::~CoordinateOperationContext() = default; //! @endcond // --------------------------------------------------------------------------- CoordinateOperationContext::CoordinateOperationContext() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- CoordinateOperationContext::CoordinateOperationContext( const CoordinateOperationContext &other) : d(internal::make_unique<Private>(*(other.d))) {} // --------------------------------------------------------------------------- /** \brief Return the authority factory, or null */ const io::AuthorityFactoryPtr & CoordinateOperationContext::getAuthorityFactory() const { return d->authorityFactory_; } // --------------------------------------------------------------------------- /** \brief Return the desired area of interest, or null */ const metadata::ExtentPtr & CoordinateOperationContext::getAreaOfInterest() const { return d->extent_; } // --------------------------------------------------------------------------- /** \brief Set the desired area of interest, or null */ void CoordinateOperationContext::setAreaOfInterest( const metadata::ExtentPtr &extent) { d->extent_ = extent; } // --------------------------------------------------------------------------- /** \brief Return the desired accuracy (in metre), or 0 */ double CoordinateOperationContext::getDesiredAccuracy() const { return d->accuracy_; } // --------------------------------------------------------------------------- /** \brief Set the desired accuracy (in metre), or 0 */ void CoordinateOperationContext::setDesiredAccuracy(double accuracy) { d->accuracy_ = accuracy; } // --------------------------------------------------------------------------- /** \brief Return whether ballpark transformations are allowed */ bool CoordinateOperationContext::getAllowBallparkTransformations() const { return d->allowBallpark_; } // --------------------------------------------------------------------------- /** \brief Set whether ballpark transformations are allowed */ void CoordinateOperationContext::setAllowBallparkTransformations(bool allow) { d->allowBallpark_ = allow; } // --------------------------------------------------------------------------- /** \brief Set how source and target CRS extent should be used * when considering if a transformation can be used (only takes effect if * no area of interest is explicitly defined). * * The default is * CoordinateOperationContext::SourceTargetCRSExtentUse::SMALLEST. */ void CoordinateOperationContext::setSourceAndTargetCRSExtentUse( SourceTargetCRSExtentUse use) { d->sourceAndTargetCRSExtentUse_ = use; } // --------------------------------------------------------------------------- /** \brief Return how source and target CRS extent should be used * when considering if a transformation can be used (only takes effect if * no area of interest is explicitly defined). * * The default is * CoordinateOperationContext::SourceTargetCRSExtentUse::SMALLEST. */ CoordinateOperationContext::SourceTargetCRSExtentUse CoordinateOperationContext::getSourceAndTargetCRSExtentUse() const { return d->sourceAndTargetCRSExtentUse_; } // --------------------------------------------------------------------------- /** \brief Set the spatial criterion to use when comparing the area of * validity * of coordinate operations with the area of interest / area of validity of * source and target CRS. * * The default is STRICT_CONTAINMENT. */ void CoordinateOperationContext::setSpatialCriterion( SpatialCriterion criterion) { d->spatialCriterion_ = criterion; } // --------------------------------------------------------------------------- /** \brief Return the spatial criterion to use when comparing the area of * validity * of coordinate operations with the area of interest / area of validity of * source and target CRS. * * The default is STRICT_CONTAINMENT. */ CoordinateOperationContext::SpatialCriterion CoordinateOperationContext::getSpatialCriterion() const { return d->spatialCriterion_; } // --------------------------------------------------------------------------- /** \brief Set whether PROJ alternative grid names should be substituted to * the official authority names. * * This only has effect is an authority factory with a non-null database context * has been attached to this context. * * If set to false, it is still possible to * obtain later the substitution by using io::PROJStringFormatter::create() * with a non-null database context. * * The default is true. */ void CoordinateOperationContext::setUsePROJAlternativeGridNames( bool usePROJNames) { d->usePROJNames_ = usePROJNames; } // --------------------------------------------------------------------------- /** \brief Return whether PROJ alternative grid names should be substituted to * the official authority names. * * The default is true. */ bool CoordinateOperationContext::getUsePROJAlternativeGridNames() const { return d->usePROJNames_; } // --------------------------------------------------------------------------- /** \brief Return whether transformations that are superseded (but not * deprecated) * should be discarded. * * The default is true. */ bool CoordinateOperationContext::getDiscardSuperseded() const { return d->discardSuperseded_; } // --------------------------------------------------------------------------- /** \brief Set whether transformations that are superseded (but not deprecated) * should be discarded. * * The default is true. */ void CoordinateOperationContext::setDiscardSuperseded(bool discard) { d->discardSuperseded_ = discard; } // --------------------------------------------------------------------------- /** \brief Set how grid availability is used. * * The default is USE_FOR_SORTING. */ void CoordinateOperationContext::setGridAvailabilityUse( GridAvailabilityUse use) { d->gridAvailabilityUse_ = use; } // --------------------------------------------------------------------------- /** \brief Return how grid availability is used. * * The default is USE_FOR_SORTING. */ CoordinateOperationContext::GridAvailabilityUse CoordinateOperationContext::getGridAvailabilityUse() const { return d->gridAvailabilityUse_; } // --------------------------------------------------------------------------- /** \brief Set whether an intermediate pivot CRS can be used for researching * coordinate operations between a source and target CRS. * * Concretely if in the database there is an operation from A to C * (or C to A), and another one from C to B (or B to C), but no direct * operation between A and B, setting this parameter to * ALWAYS/IF_NO_DIRECT_TRANSFORMATION, allow chaining both operations. * * The current implementation is limited to researching one intermediate * step. * * By default, with the IF_NO_DIRECT_TRANSFORMATION strategy, all potential * C candidates will be used if there is no direct transformation. */ void CoordinateOperationContext::setAllowUseIntermediateCRS( IntermediateCRSUse use) { d->allowUseIntermediateCRS_ = use; } // --------------------------------------------------------------------------- /** \brief Return whether an intermediate pivot CRS can be used for researching * coordinate operations between a source and target CRS. * * Concretely if in the database there is an operation from A to C * (or C to A), and another one from C to B (or B to C), but no direct * operation between A and B, setting this parameter to * ALWAYS/IF_NO_DIRECT_TRANSFORMATION, allow chaining both operations. * * The default is IF_NO_DIRECT_TRANSFORMATION. */ CoordinateOperationContext::IntermediateCRSUse CoordinateOperationContext::getAllowUseIntermediateCRS() const { return d->allowUseIntermediateCRS_; } // --------------------------------------------------------------------------- /** \brief Restrict the potential pivot CRSs that can be used when trying to * build a coordinate operation between two CRS that have no direct operation. * * @param intermediateCRSAuthCodes a vector of (auth_name, code) that can be * used as potential pivot RS */ void CoordinateOperationContext::setIntermediateCRS( const std::vector<std::pair<std::string, std::string>> &intermediateCRSAuthCodes) { d->intermediateCRSAuthCodes_ = intermediateCRSAuthCodes; } // --------------------------------------------------------------------------- /** \brief Return the potential pivot CRSs that can be used when trying to * build a coordinate operation between two CRS that have no direct operation. * */ const std::vector<std::pair<std::string, std::string>> & CoordinateOperationContext::getIntermediateCRS() const { return d->intermediateCRSAuthCodes_; } // --------------------------------------------------------------------------- /** \brief Set the source coordinate epoch. */ void CoordinateOperationContext::setSourceCoordinateEpoch( const util::optional<common::DataEpoch> &epoch) { d->sourceCoordinateEpoch_ = std::make_shared<util::optional<common::DataEpoch>>(epoch); } // --------------------------------------------------------------------------- /** \brief Return the source coordinate epoch. */ const util::optional<common::DataEpoch> & CoordinateOperationContext::getSourceCoordinateEpoch() const { return *(d->sourceCoordinateEpoch_); } // --------------------------------------------------------------------------- /** \brief Set the target coordinate epoch. */ void CoordinateOperationContext::setTargetCoordinateEpoch( const util::optional<common::DataEpoch> &epoch) { d->targetCoordinateEpoch_ = std::make_shared<util::optional<common::DataEpoch>>(epoch); } // --------------------------------------------------------------------------- /** \brief Return the target coordinate epoch. */ const util::optional<common::DataEpoch> & CoordinateOperationContext::getTargetCoordinateEpoch() const { return *(d->targetCoordinateEpoch_); } // --------------------------------------------------------------------------- /** \brief Creates a context for a coordinate operation. * * If a non null authorityFactory is provided, the resulting context should * not be used simultaneously by more than one thread. * * If authorityFactory->getAuthority() is the empty string, then coordinate * operations from any authority will be searched, with the restrictions set * in the authority_to_authority_preference database table. * If authorityFactory->getAuthority() is set to "any", then coordinate * operations from any authority will be searched * If authorityFactory->getAuthority() is a non-empty string different of "any", * then coordinate operations will be searched only in that authority namespace. * * @param authorityFactory Authority factory, or null if no database lookup * is allowed. * Use io::authorityFactory::create(context, std::string()) to allow all * authorities to be used. * @param extent Area of interest, or null if none is known. * @param accuracy Maximum allowed accuracy in metre, as specified in or * 0 to get best accuracy. * @return a new context. */ CoordinateOperationContextNNPtr CoordinateOperationContext::create( const io::AuthorityFactoryPtr &authorityFactory, const metadata::ExtentPtr &extent, double accuracy) { auto ctxt = NN_NO_CHECK( CoordinateOperationContext::make_unique<CoordinateOperationContext>()); ctxt->d->authorityFactory_ = authorityFactory; ctxt->d->extent_ = extent; ctxt->d->accuracy_ = accuracy; return ctxt; } // --------------------------------------------------------------------------- /** \brief Clone a coordinate operation context. * * @return a new context. * @since 9.2 */ CoordinateOperationContextNNPtr CoordinateOperationContext::clone() const { return NN_NO_CHECK( CoordinateOperationContext::make_unique<CoordinateOperationContext>( *this)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CoordinateOperationFactory::Private { struct Context { // This is the extent of the source CRS and target CRS of the initial // CoordinateOperationFactory::createOperations() public call, not // necessarily the ones of intermediate // CoordinateOperationFactory::Private::createOperations() calls. // This is used to compare transformations area of use against the // area of use of the source & target CRS. const metadata::ExtentPtr &extent1; const metadata::ExtentPtr &extent2; const CoordinateOperationContextNNPtr &context; bool inCreateOperationsWithDatumPivotAntiRecursion = false; bool inCreateOperationsGeogToVertWithAlternativeGeog = false; bool inCreateOperationsGeogToVertWithIntermediateVert = false; bool skipHorizontalTransformation = false; int nRecLevelCreateOperations = 0; std::map<std::pair<io::AuthorityFactory::ObjectType, std::string>, std::list<std::pair<std::string, std::string>>> cacheNameToCRS{}; Context(const metadata::ExtentPtr &extent1In, const metadata::ExtentPtr &extent2In, const CoordinateOperationContextNNPtr &contextIn) : extent1(extent1In), extent2(extent2In), context(contextIn) {} }; static std::vector<CoordinateOperationNNPtr> createOperations(const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Context &context); private: static constexpr bool disallowEmptyIntersection = true; static void buildCRSIds(const crs::CRSNNPtr &crs, Private::Context &context, std::list<std::pair<std::string, std::string>> &ids); static std::vector<CoordinateOperationNNPtr> findOpsInRegistryDirect( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, bool &resNonEmptyBeforeFiltering); static std::vector<CoordinateOperationNNPtr> findOpsInRegistryDirectTo(const crs::CRSNNPtr &targetCRS, Private::Context &context); static std::vector<CoordinateOperationNNPtr> findsOpsInRegistryWithIntermediate( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, bool useCreateBetweenGeodeticCRSWithDatumBasedIntermediates); static void createOperationsFromProj4Ext( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const crs::BoundCRS *boundSrc, const crs::BoundCRS *boundDst, std::vector<CoordinateOperationNNPtr> &res); static bool createOperationsFromDatabase( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeodeticCRS *geodSrc, const crs::GeodeticCRS *geodDst, const crs::GeographicCRS *geogSrc, const crs::GeographicCRS *geogDst, const crs::VerticalCRS *vertSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res); static std::vector<CoordinateOperationNNPtr> createOperationsGeogToVertFromGeoid(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const crs::VerticalCRS *vertDst, Context &context); static std::vector<CoordinateOperationNNPtr> createOperationsGeogToVertWithIntermediateVert( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, const crs::VerticalCRS *vertDst, Context &context); static std::vector<CoordinateOperationNNPtr> createOperationsGeogToVertWithAlternativeGeog( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Context &context); static void createOperationsFromDatabaseWithVertCRS( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeographicCRS *geogSrc, const crs::GeographicCRS *geogDst, const crs::VerticalCRS *vertSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsGeodToGeod( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::GeodeticCRS *geodSrc, const crs::GeodeticCRS *geodDst, std::vector<CoordinateOperationNNPtr> &res, bool forceBallpark); static void createOperationsFromSphericalPlanetocentric( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeodeticCRS *geodSrc, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsFromBoundOfSphericalPlanetocentric( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::GeodeticCRSNNPtr &geodSrcBase, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsDerivedTo( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::DerivedCRS *derivedSrc, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsBoundToGeog( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsBoundToVert( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsVertToVert( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::VerticalCRS *vertSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsVertToGeog( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::VerticalCRS *vertSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsVertToGeogBallpark( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::VerticalCRS *vertSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsBoundToBound( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::BoundCRS *boundDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsCompoundToGeog( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::CompoundCRS *compoundSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsToGeod(const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeodeticCRS *geodDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsCompoundToCompound( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::CompoundCRS *compoundSrc, const crs::CompoundCRS *compoundDst, std::vector<CoordinateOperationNNPtr> &res); static void createOperationsBoundToCompound( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::CompoundCRS *compoundDst, std::vector<CoordinateOperationNNPtr> &res); static std::vector<CoordinateOperationNNPtr> createOperationsGeogToGeog( std::vector<CoordinateOperationNNPtr> &res, const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::GeographicCRS *geogSrc, const crs::GeographicCRS *geogDst, bool forceBallpark); static void createOperationsWithDatumPivot( std::vector<CoordinateOperationNNPtr> &res, const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, const crs::GeodeticCRS *geodSrc, const crs::GeodeticCRS *geodDst, Context &context); static bool hasPerfectAccuracyResult(const std::vector<CoordinateOperationNNPtr> &res, const Context &context); static void setCRSs(CoordinateOperation *co, const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS); }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateOperationFactory::~CoordinateOperationFactory() = default; //! @endcond // --------------------------------------------------------------------------- CoordinateOperationFactory::CoordinateOperationFactory() : d(nullptr) {} // --------------------------------------------------------------------------- /** \brief Find a CoordinateOperation from sourceCRS to targetCRS. * * This is a helper of createOperations(), using a coordinate operation * context * with no authority factory (so no catalog searching is done), no desired * accuracy and no area of interest. * This returns the first operation of the result set of createOperations(), * or null if none found. * * @param sourceCRS source CRS. * @param targetCRS source CRS. * @return a CoordinateOperation or nullptr. */ CoordinateOperationPtr CoordinateOperationFactory::createOperation( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS) const { auto res = createOperations( sourceCRS, targetCRS, CoordinateOperationContext::create(nullptr, nullptr, 0.0)); if (!res.empty()) { return res[0]; } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- struct PrecomputedOpCharacteristics { double area_{}; double accuracy_{}; bool isPROJExportable_ = false; bool hasGrids_ = false; bool gridsAvailable_ = false; bool gridsKnown_ = false; size_t stepCount_ = 0; size_t projStepCount_ = 0; bool isApprox_ = false; bool hasBallparkVertical_ = false; bool isNullTransformation_ = false; PrecomputedOpCharacteristics() = default; PrecomputedOpCharacteristics(double area, double accuracy, bool isPROJExportable, bool hasGrids, bool gridsAvailable, bool gridsKnown, size_t stepCount, size_t projStepCount, bool isApprox, bool hasBallparkVertical, bool isNullTransformation) : area_(area), accuracy_(accuracy), isPROJExportable_(isPROJExportable), hasGrids_(hasGrids), gridsAvailable_(gridsAvailable), gridsKnown_(gridsKnown), stepCount_(stepCount), projStepCount_(projStepCount), isApprox_(isApprox), hasBallparkVertical_(hasBallparkVertical), isNullTransformation_(isNullTransformation) {} }; // --------------------------------------------------------------------------- // We could have used a lambda instead of this old-school way, but // filterAndSort() is already huge. struct SortFunction { const std::map<CoordinateOperation *, PrecomputedOpCharacteristics> &map; const std::string BALLPARK_GEOGRAPHIC_OFFSET_FROM; explicit SortFunction(const std::map<CoordinateOperation *, PrecomputedOpCharacteristics> &mapIn) : map(mapIn), BALLPARK_GEOGRAPHIC_OFFSET_FROM( std::string(BALLPARK_GEOGRAPHIC_OFFSET) + " from ") {} // Sorting function // Return true if a < b bool compare(const CoordinateOperationNNPtr &a, const CoordinateOperationNNPtr &b) const { auto iterA = map.find(a.get()); assert(iterA != map.end()); auto iterB = map.find(b.get()); assert(iterB != map.end()); // CAUTION: the order of the comparisons is extremely important // to get the intended result. if (iterA->second.isPROJExportable_ && !iterB->second.isPROJExportable_) { return true; } if (!iterA->second.isPROJExportable_ && iterB->second.isPROJExportable_) { return false; } if (!iterA->second.isApprox_ && iterB->second.isApprox_) { return true; } if (iterA->second.isApprox_ && !iterB->second.isApprox_) { return false; } if (!iterA->second.hasBallparkVertical_ && iterB->second.hasBallparkVertical_) { return true; } if (iterA->second.hasBallparkVertical_ && !iterB->second.hasBallparkVertical_) { return false; } if (!iterA->second.isNullTransformation_ && iterB->second.isNullTransformation_) { return true; } if (iterA->second.isNullTransformation_ && !iterB->second.isNullTransformation_) { return false; } // Operations where grids are all available go before other if (iterA->second.gridsAvailable_ && !iterB->second.gridsAvailable_) { return true; } if (iterB->second.gridsAvailable_ && !iterA->second.gridsAvailable_) { return false; } // Operations where grids are all known in our DB go before other if (iterA->second.gridsKnown_ && !iterB->second.gridsKnown_) { return true; } if (iterB->second.gridsKnown_ && !iterA->second.gridsKnown_) { return false; } // Operations with known accuracy go before those with unknown accuracy const double accuracyA = iterA->second.accuracy_; const double accuracyB = iterB->second.accuracy_; if (accuracyA >= 0 && accuracyB < 0) { return true; } if (accuracyB >= 0 && accuracyA < 0) { return false; } if (accuracyA < 0 && accuracyB < 0) { // unknown accuracy ? then prefer operations with grids, which // are likely to have best practical accuracy if (iterA->second.hasGrids_ && !iterB->second.hasGrids_) { return true; } if (!iterA->second.hasGrids_ && iterB->second.hasGrids_) { return false; } } // Operations with larger non-zero area of use go before those with // lower one const double areaA = iterA->second.area_; const double areaB = iterB->second.area_; if (areaA > 0) { if (areaA > areaB) { return true; } if (areaA < areaB) { return false; } } else if (areaB > 0) { return false; } // Operations with better accuracy go before those with worse one if (accuracyA >= 0 && accuracyA < accuracyB) { return true; } if (accuracyB >= 0 && accuracyB < accuracyA) { return false; } if (accuracyA >= 0 && accuracyA == accuracyB) { // same accuracy ? then prefer operations without grids if (!iterA->second.hasGrids_ && iterB->second.hasGrids_) { return true; } if (iterA->second.hasGrids_ && !iterB->second.hasGrids_) { return false; } } // The less intermediate steps, the better if (iterA->second.stepCount_ < iterB->second.stepCount_) { return true; } if (iterB->second.stepCount_ < iterA->second.stepCount_) { return false; } // Compare number of steps in PROJ pipeline, and prefer the ones // with less operations. if (iterA->second.projStepCount_ != 0 && iterB->second.projStepCount_ != 0) { if (iterA->second.projStepCount_ < iterB->second.projStepCount_) { return true; } if (iterB->second.projStepCount_ < iterA->second.projStepCount_) { return false; } } const auto &a_name = a->nameStr(); const auto &b_name = b->nameStr(); // Make sure that // "Ballpark geographic offset from NAD83(CSRS)v6 to NAD83(CSRS)" // has more priority than // "Ballpark geographic offset from ITRF2008 to NAD83(CSRS)" const auto posA = a_name.find(BALLPARK_GEOGRAPHIC_OFFSET_FROM); const auto posB = b_name.find(BALLPARK_GEOGRAPHIC_OFFSET_FROM); if (posA != std::string::npos && posB != std::string::npos) { const auto pos2A = a_name.find(" to ", posA); const auto pos2B = b_name.find(" to ", posB); if (pos2A != std::string::npos && pos2B != std::string::npos) { const auto pos3A = a_name.find(" + ", pos2A); const auto pos3B = b_name.find(" + ", pos2B); const std::string fromA = a_name.substr( posA + BALLPARK_GEOGRAPHIC_OFFSET_FROM.size(), pos2A - (posA + BALLPARK_GEOGRAPHIC_OFFSET_FROM.size())); const std::string toA = a_name.substr(pos2A + strlen(" to "), pos3A == std::string::npos ? pos3A : pos3A - (pos2A + strlen(" to "))); const std::string fromB = b_name.substr( posB + BALLPARK_GEOGRAPHIC_OFFSET_FROM.size(), pos2B - (posB + BALLPARK_GEOGRAPHIC_OFFSET_FROM.size())); const std::string toB = b_name.substr(pos2B + strlen(" to "), pos3B == std::string::npos ? pos3B : pos3B - (pos2B + strlen(" to "))); const bool similarCRSInA = (fromA.find(toA) == 0 || toA.find(fromA) == 0); const bool similarCRSInB = (fromB.find(toB) == 0 || toB.find(fromB) == 0); if (similarCRSInA && !similarCRSInB) { return true; } if (!similarCRSInA && similarCRSInB) { return false; } } } // The shorter name, the better ? if (a_name.size() < b_name.size()) { return true; } if (b_name.size() < a_name.size()) { return false; } // Arbitrary final criterion. We actually return the greater element // first, so that "Amersfoort to WGS 84 (4)" is presented before // "Amersfoort to WGS 84 (3)", which is probably a better guess. // Except for French NTF (Paris) to NTF, where the (1) conversion // should be preferred because in the remarks of (2), it is mentioned // OGP prefers value from IGN Paris (code 1467)... if (a_name.find("NTF (Paris) to NTF (1)") != std::string::npos && b_name.find("NTF (Paris) to NTF (2)") != std::string::npos) { return true; } if (a_name.find("NTF (Paris) to NTF (2)") != std::string::npos && b_name.find("NTF (Paris) to NTF (1)") != std::string::npos) { return false; } if (a_name.find("NTF (Paris) to RGF93 v1 (1)") != std::string::npos && b_name.find("NTF (Paris) to RGF93 v1 (2)") != std::string::npos) { return true; } if (a_name.find("NTF (Paris) to RGF93 v1 (2)") != std::string::npos && b_name.find("NTF (Paris) to RGF93 v1 (1)") != std::string::npos) { return false; } return a_name > b_name; } bool operator()(const CoordinateOperationNNPtr &a, const CoordinateOperationNNPtr &b) const { const bool ret = compare(a, b); #if 0 std::cerr << a->nameStr() << " < " << b->nameStr() << " : " << ret << std::endl; #endif return ret; } }; // --------------------------------------------------------------------------- static size_t getStepCount(const CoordinateOperationNNPtr &op) { auto concat = dynamic_cast<const ConcatenatedOperation *>(op.get()); size_t stepCount = 1; if (concat) { stepCount = concat->operations().size(); } return stepCount; } // --------------------------------------------------------------------------- // Return number of steps that are transformations (and not conversions) static size_t getTransformationStepCount(const CoordinateOperationNNPtr &op) { auto concat = dynamic_cast<const ConcatenatedOperation *>(op.get()); size_t stepCount = 1; if (concat) { stepCount = 0; for (const auto &subOp : concat->operations()) { if (dynamic_cast<const Conversion *>(subOp.get()) == nullptr) { stepCount++; } } } return stepCount; } // --------------------------------------------------------------------------- static bool isNullTransformation(const std::string &name) { if (name.find(" + ") != std::string::npos) return false; return starts_with(name, BALLPARK_GEOCENTRIC_TRANSLATION) || starts_with(name, BALLPARK_GEOGRAPHIC_OFFSET) || starts_with(name, NULL_GEOGRAPHIC_OFFSET) || starts_with(name, NULL_GEOCENTRIC_TRANSLATION); } // --------------------------------------------------------------------------- struct FilterResults { FilterResults(const std::vector<CoordinateOperationNNPtr> &sourceListIn, const CoordinateOperationContextNNPtr &contextIn, const metadata::ExtentPtr &extent1In, const metadata::ExtentPtr &extent2In, bool forceStrictContainmentTest) : sourceList(sourceListIn), context(contextIn), extent1(extent1In), extent2(extent2In), areaOfInterest(context->getAreaOfInterest()), areaOfInterestUserSpecified(areaOfInterest != nullptr), desiredAccuracy(context->getDesiredAccuracy()), sourceAndTargetCRSExtentUse( context->getSourceAndTargetCRSExtentUse()) { computeAreaOfInterest(); filterOut(forceStrictContainmentTest); } FilterResults &andSort() { sort(); // And now that we have a sorted list, we can remove uninteresting // results // ... removeSyntheticNullTransforms(); removeUninterestingOps(); removeDuplicateOps(); removeSyntheticNullTransforms(); return *this; } // ---------------------------------------------------------------------- // cppcheck-suppress functionStatic const std::vector<CoordinateOperationNNPtr> &getRes() { return res; } // ---------------------------------------------------------------------- private: const std::vector<CoordinateOperationNNPtr> &sourceList; const CoordinateOperationContextNNPtr &context; const metadata::ExtentPtr &extent1; const metadata::ExtentPtr &extent2; metadata::ExtentPtr areaOfInterest; const bool areaOfInterestUserSpecified; const double desiredAccuracy = context->getDesiredAccuracy(); const CoordinateOperationContext::SourceTargetCRSExtentUse sourceAndTargetCRSExtentUse; bool hasOpThatContainsAreaOfInterestAndNoGrid = false; std::vector<CoordinateOperationNNPtr> res{}; // ---------------------------------------------------------------------- void computeAreaOfInterest() { // Compute an area of interest from the CRS extent if the user did // not specify one if (!areaOfInterest) { if (sourceAndTargetCRSExtentUse == CoordinateOperationContext::SourceTargetCRSExtentUse:: INTERSECTION) { if (extent1 && extent2) { areaOfInterest = extent1->intersection(NN_NO_CHECK(extent2)); } } else if (sourceAndTargetCRSExtentUse == CoordinateOperationContext::SourceTargetCRSExtentUse:: SMALLEST) { if (extent1 && extent2) { if (getPseudoArea(extent1) < getPseudoArea(extent2)) { areaOfInterest = extent1; } else { areaOfInterest = extent2; } } else if (extent1) { areaOfInterest = extent1; } else { areaOfInterest = extent2; } } } } // --------------------------------------------------------------------------- void filterOut(bool forceStrictContainmentTest) { // Filter out operations that do not match the expected accuracy // and area of use. const auto spatialCriterion = forceStrictContainmentTest ? CoordinateOperationContext::SpatialCriterion:: STRICT_CONTAINMENT : context->getSpatialCriterion(); bool hasOnlyBallpark = true; bool hasNonBallparkWithoutExtent = false; bool hasNonBallparkOpWithExtent = false; const bool allowBallpark = context->getAllowBallparkTransformations(); bool foundExtentWithExpectedDescription = false; if (areaOfInterestUserSpecified && areaOfInterest && areaOfInterest->description().has_value()) { for (const auto &op : sourceList) { bool emptyIntersection = false; auto extent = getExtent(op, true, emptyIntersection); if (extent && extent->description().has_value()) { if (*(areaOfInterest->description()) == *(extent->description())) { foundExtentWithExpectedDescription = true; break; } } } } for (const auto &op : sourceList) { if (desiredAccuracy != 0) { const double accuracy = getAccuracy(op); if (accuracy < 0 || accuracy > desiredAccuracy) { continue; } } if (!allowBallpark && op->hasBallparkTransformation()) { continue; } if (areaOfInterest) { bool emptyIntersection = false; auto extent = getExtent(op, true, emptyIntersection); if (!extent) { if (!op->hasBallparkTransformation()) { hasNonBallparkWithoutExtent = true; } continue; } if (foundExtentWithExpectedDescription && (!extent->description().has_value() || *(areaOfInterest->description()) != *(extent->description()))) { continue; } if (!op->hasBallparkTransformation()) { hasNonBallparkOpWithExtent = true; } bool extentContains = extent->contains(NN_NO_CHECK(areaOfInterest)); if (!hasOpThatContainsAreaOfInterestAndNoGrid && extentContains) { if (!op->hasBallparkTransformation() && op->gridsNeeded(nullptr, true).empty()) { hasOpThatContainsAreaOfInterestAndNoGrid = true; } } if (spatialCriterion == CoordinateOperationContext::SpatialCriterion:: STRICT_CONTAINMENT && !extentContains) { continue; } if (spatialCriterion == CoordinateOperationContext::SpatialCriterion:: PARTIAL_INTERSECTION && !extent->intersects(NN_NO_CHECK(areaOfInterest))) { continue; } } else if (sourceAndTargetCRSExtentUse == CoordinateOperationContext::SourceTargetCRSExtentUse:: BOTH) { bool emptyIntersection = false; auto extent = getExtent(op, true, emptyIntersection); if (!extent) { if (!op->hasBallparkTransformation()) { hasNonBallparkWithoutExtent = true; } continue; } if (!op->hasBallparkTransformation()) { hasNonBallparkOpWithExtent = true; } bool extentContainsExtent1 = !extent1 || extent->contains(NN_NO_CHECK(extent1)); bool extentContainsExtent2 = !extent2 || extent->contains(NN_NO_CHECK(extent2)); if (!hasOpThatContainsAreaOfInterestAndNoGrid && extentContainsExtent1 && extentContainsExtent2) { if (!op->hasBallparkTransformation() && op->gridsNeeded(nullptr, true).empty()) { hasOpThatContainsAreaOfInterestAndNoGrid = true; } } if (spatialCriterion == CoordinateOperationContext::SpatialCriterion:: STRICT_CONTAINMENT) { if (!extentContainsExtent1 || !extentContainsExtent2) { continue; } } else if (spatialCriterion == CoordinateOperationContext::SpatialCriterion:: PARTIAL_INTERSECTION) { bool extentIntersectsExtent1 = !extent1 || extent->intersects(NN_NO_CHECK(extent1)); bool extentIntersectsExtent2 = extent2 && extent->intersects(NN_NO_CHECK(extent2)); if (!extentIntersectsExtent1 || !extentIntersectsExtent2) { continue; } } } if (!op->hasBallparkTransformation()) { hasOnlyBallpark = false; } res.emplace_back(op); } // In case no operation has an extent and no result is found, // retain all initial operations that match accuracy criterion. if ((res.empty() && !hasNonBallparkOpWithExtent) || (hasOnlyBallpark && hasNonBallparkWithoutExtent)) { for (const auto &op : sourceList) { if (desiredAccuracy != 0) { const double accuracy = getAccuracy(op); if (accuracy < 0 || accuracy > desiredAccuracy) { continue; } } if (!allowBallpark && op->hasBallparkTransformation()) { continue; } res.emplace_back(op); } } } // ---------------------------------------------------------------------- void sort() { // Precompute a number of parameters for each operation that will be // useful for the sorting. std::map<CoordinateOperation *, PrecomputedOpCharacteristics> map; const auto gridAvailabilityUse = context->getGridAvailabilityUse(); for (const auto &op : res) { bool dummy = false; auto extentOp = getExtent(op, true, dummy); double area = 0.0; if (extentOp) { if (areaOfInterest) { area = getPseudoArea( extentOp->intersection(NN_NO_CHECK(areaOfInterest))); } else if (extent1 && extent2) { auto x = extentOp->intersection(NN_NO_CHECK(extent1)); auto y = extentOp->intersection(NN_NO_CHECK(extent2)); area = getPseudoArea(x) + getPseudoArea(y) - ((x && y) ? getPseudoArea(x->intersection(NN_NO_CHECK(y))) : 0.0); } else if (extent1) { area = getPseudoArea( extentOp->intersection(NN_NO_CHECK(extent1))); } else if (extent2) { area = getPseudoArea( extentOp->intersection(NN_NO_CHECK(extent2))); } else { area = getPseudoArea(extentOp); } } bool hasGrids = false; bool gridsAvailable = true; bool gridsKnown = true; if (context->getAuthorityFactory()) { const auto gridsNeeded = op->gridsNeeded( context->getAuthorityFactory()->databaseContext(), gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE); for (const auto &gridDesc : gridsNeeded) { hasGrids = true; if (gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: USE_FOR_SORTING && !gridDesc.available) { gridsAvailable = false; } if (gridDesc.packageName.empty() && !(!gridDesc.url.empty() && gridDesc.openLicense) && !gridDesc.available) { gridsKnown = false; } } } const auto stepCount = getStepCount(op); bool isPROJExportable = false; auto formatter = io::PROJStringFormatter::create(); size_t projStepCount = 0; try { const auto str = op->exportToPROJString(formatter.get()); // Grids might be missing, but at least this is something // PROJ could potentially process isPROJExportable = true; // We exclude pipelines with +proj=xyzgridshift as they // generate more steps, but are more precise. if (str.find("+proj=xyzgridshift") == std::string::npos) { auto formatter2 = io::PROJStringFormatter::create(); formatter2->ingestPROJString(str); projStepCount = formatter2->getStepCount(); } } catch (const std::exception &) { } #if 0 std::cerr << "name=" << op->nameStr() << " "; std::cerr << "area=" << area << " "; std::cerr << "accuracy=" << getAccuracy(op) << " "; std::cerr << "isPROJExportable=" << isPROJExportable << " "; std::cerr << "hasGrids=" << hasGrids << " "; std::cerr << "gridsAvailable=" << gridsAvailable << " "; std::cerr << "gridsKnown=" << gridsKnown << " "; std::cerr << "stepCount=" << stepCount << " "; std::cerr << "projStepCount=" << projStepCount << " "; std::cerr << "ballpark=" << op->hasBallparkTransformation() << " "; std::cerr << "vertBallpark=" << (op->nameStr().find( BALLPARK_VERTICAL_TRANSFORMATION) != std::string::npos) << " "; std::cerr << "isNull=" << isNullTransformation(op->nameStr()) << " "; std::cerr << std::endl; #endif map[op.get()] = PrecomputedOpCharacteristics( area, getAccuracy(op), isPROJExportable, hasGrids, gridsAvailable, gridsKnown, stepCount, projStepCount, op->hasBallparkTransformation(), op->nameStr().find(BALLPARK_VERTICAL_TRANSFORMATION) != std::string::npos, isNullTransformation(op->nameStr())); } // Sort ! SortFunction sortFunc(map); std::sort(res.begin(), res.end(), sortFunc); // Debug code to check consistency of the sort function #ifdef DEBUG_SORT constexpr bool debugSort = true; #elif !defined(NDEBUG) const bool debugSort = getenv("PROJ_DEBUG_SORT_FUNCT") != nullptr; #endif #if defined(DEBUG_SORT) || !defined(NDEBUG) if (debugSort) { const bool assertIfIssue = !(getenv("PROJ_DEBUG_SORT_FUNCT_ASSERT") != nullptr); for (size_t i = 0; i < res.size(); ++i) { for (size_t j = i + 1; j < res.size(); ++j) { if (sortFunc(res[j], res[i])) { #ifdef DEBUG_SORT std::cerr << "Sorting issue with entry " << i << "(" << res[i]->nameStr() << ") and " << j << "(" << res[j]->nameStr() << ")" << std::endl; #endif if (assertIfIssue) { assert(false); } } } } } #endif } // ---------------------------------------------------------------------- void removeSyntheticNullTransforms() { // If we have more than one result, and than the last result is the // default "Ballpark geographic offset" or "Ballpark geocentric // translation" operations we have synthetized, and that at least one // operation has the desired area of interest and does not require the // use of grids, remove it as all previous results are necessarily // better if (hasOpThatContainsAreaOfInterestAndNoGrid && res.size() > 1) { const auto &opLast = res.back(); if (opLast->hasBallparkTransformation() || isNullTransformation(opLast->nameStr())) { std::vector<CoordinateOperationNNPtr> resTemp; for (size_t i = 0; i < res.size() - 1; i++) { resTemp.emplace_back(res[i]); } res = std::move(resTemp); } } } // ---------------------------------------------------------------------- void removeUninterestingOps() { // Eliminate operations that bring nothing, ie for a given area of use, // do not keep operations that have similar or worse accuracy, but // involve more (non conversion) steps std::vector<CoordinateOperationNNPtr> resTemp; metadata::ExtentPtr lastExtent; double lastAccuracy = -1; size_t lastStepCount = 0; CoordinateOperationPtr lastOp; bool first = true; for (const auto &op : res) { const auto curAccuracy = getAccuracy(op); bool dummy = false; const auto curExtent = getExtent(op, true, dummy); // If a concatenated operation has an identifier, consider it as // a single step (to be opposed to synthetized concatenated // operations). Helps for example to get EPSG:8537, // "Egypt 1907 to WGS 84 (2)" const auto curStepCount = op->identifiers().empty() ? getTransformationStepCount(op) : 1; if (first) { resTemp.emplace_back(op); first = false; } else { if (lastOp->_isEquivalentTo(op.get())) { continue; } const bool sameExtent = ((!curExtent && !lastExtent) || (curExtent && lastExtent && curExtent->contains(NN_NO_CHECK(lastExtent)) && lastExtent->contains(NN_NO_CHECK(curExtent)))); if (((curAccuracy >= lastAccuracy && lastAccuracy >= 0) || (curAccuracy < 0 && lastAccuracy >= 0)) && sameExtent && curStepCount > lastStepCount) { continue; } resTemp.emplace_back(op); } lastOp = op.as_nullable(); lastStepCount = curStepCount; lastExtent = curExtent; lastAccuracy = curAccuracy; } res = std::move(resTemp); } // ---------------------------------------------------------------------- // cppcheck-suppress functionStatic void removeDuplicateOps() { if (res.size() <= 1) { return; } // When going from EPSG:4807 (NTF Paris) to EPSG:4171 (RGC93), we get // EPSG:7811, NTF (Paris) to RGF93 (2), 1 m // and unknown id, NTF (Paris) to NTF (1) + Inverse of RGF93 to NTF (2), // 1 m // both have same PROJ string and extent // Do not keep the later (that has more steps) as it adds no value. std::set<std::string> setPROJPlusExtent; std::vector<CoordinateOperationNNPtr> resTemp; for (const auto &op : res) { auto formatter = io::PROJStringFormatter::create(); try { std::string key(op->exportToPROJString(formatter.get())); bool dummy = false; auto extentOp = getExtent(op, true, dummy); if (extentOp) { const auto &geogElts = extentOp->geographicElements(); if (geogElts.size() == 1) { auto bbox = dynamic_cast< const metadata::GeographicBoundingBox *>( geogElts[0].get()); if (bbox) { double w = bbox->westBoundLongitude(); double s = bbox->southBoundLatitude(); double e = bbox->eastBoundLongitude(); double n = bbox->northBoundLatitude(); key += "-"; key += toString(w); key += "-"; key += toString(s); key += "-"; key += toString(e); key += "-"; key += toString(n); } } } if (setPROJPlusExtent.find(key) == setPROJPlusExtent.end()) { resTemp.emplace_back(op); setPROJPlusExtent.insert(key); } } catch (const std::exception &) { resTemp.emplace_back(op); } } res = std::move(resTemp); } }; // --------------------------------------------------------------------------- /** \brief Filter operations and sort them given context. * * If a desired accuracy is specified, only keep operations whose accuracy * is at least the desired one. * If an area of interest is specified, only keep operations whose area of * use include the area of interest. * Then sort remaining operations by descending area of use, and increasing * accuracy. */ static std::vector<CoordinateOperationNNPtr> filterAndSort(const std::vector<CoordinateOperationNNPtr> &sourceList, const CoordinateOperationContextNNPtr &context, const metadata::ExtentPtr &extent1, const metadata::ExtentPtr &extent2) { #ifdef TRACE_CREATE_OPERATIONS ENTER_FUNCTION(); logTrace("number of results before filter and sort: " + toString(static_cast<int>(sourceList.size()))); #endif auto resFiltered = FilterResults(sourceList, context, extent1, extent2, false) .andSort() .getRes(); #ifdef TRACE_CREATE_OPERATIONS logTrace("number of results after filter and sort: " + toString(static_cast<int>(resFiltered.size()))); #endif return resFiltered; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // Apply the inverse() method on all elements of the input list static std::vector<CoordinateOperationNNPtr> applyInverse(const std::vector<CoordinateOperationNNPtr> &list) { auto res = list; for (auto &op : res) { #ifdef DEBUG auto opNew = op->inverse(); assert(opNew->targetCRS()->isEquivalentTo(op->sourceCRS().get())); assert(opNew->sourceCRS()->isEquivalentTo(op->targetCRS().get())); op = opNew; #else op = op->inverse(); #endif } return res; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void CoordinateOperationFactory::Private::buildCRSIds( const crs::CRSNNPtr &crs, Private::Context &context, std::list<std::pair<std::string, std::string>> &ids) { const auto &authFactory = context.context->getAuthorityFactory(); assert(authFactory); for (const auto &id : crs->identifiers()) { const auto &authName = *(id->codeSpace()); const auto &code = id->code(); if (!authName.empty()) { const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), authName); try { // Consistency check for the ID attached to the object. // See https://github.com/OSGeo/PROJ/issues/1982 where EPSG:4656 // is attached to a GeographicCRS whereas it is a ProjectedCRS if (tmpAuthFactory->createCoordinateReferenceSystem(code) ->_isEquivalentTo( crs.get(), util::IComparable::Criterion:: EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS)) { ids.emplace_back(authName, code); } else { // TODO? log this inconsistency } } catch (const std::exception &) { // TODO? log this inconsistency } } } if (ids.empty()) { std::vector<io::AuthorityFactory::ObjectType> allowedObjects; auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(crs.get()); if (geogCRS) { if (geogCRS->datumNonNull(authFactory->databaseContext()) ->nameStr() == "unknown") { return; } allowedObjects.push_back( geogCRS->coordinateSystem()->axisList().size() == 2 ? io::AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS : io::AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS); } else if (dynamic_cast<crs::ProjectedCRS *>(crs.get())) { allowedObjects.push_back( io::AuthorityFactory::ObjectType::PROJECTED_CRS); } else if (dynamic_cast<crs::VerticalCRS *>(crs.get())) { allowedObjects.push_back( io::AuthorityFactory::ObjectType::VERTICAL_CRS); } if (!allowedObjects.empty()) { const std::pair<io::AuthorityFactory::ObjectType, std::string> key( allowedObjects[0], crs->nameStr()); auto iter = context.cacheNameToCRS.find(key); if (iter != context.cacheNameToCRS.end()) { ids = iter->second; return; } const auto &authFactoryName = authFactory->getAuthority(); try { const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), (authFactoryName.empty() || authFactoryName == "any") ? std::string() : authFactoryName); auto matches = tmpAuthFactory->createObjectsFromName( crs->nameStr(), allowedObjects, false, 2); if (matches.size() == 1 && crs->_isEquivalentTo( matches.front().get(), util::IComparable::Criterion::EQUIVALENT) && !matches.front()->identifiers().empty()) { const auto &tmpIds = matches.front()->identifiers(); ids.emplace_back(*(tmpIds[0]->codeSpace()), tmpIds[0]->code()); } } catch (const std::exception &) { } context.cacheNameToCRS[key] = ids; } } } // --------------------------------------------------------------------------- static std::vector<std::string> getCandidateAuthorities(const io::AuthorityFactoryPtr &authFactory, const std::string &srcAuthName, const std::string &targetAuthName) { const auto &authFactoryName = authFactory->getAuthority(); std::vector<std::string> authorities; if (authFactoryName == "any") { authorities.emplace_back(); } if (authFactoryName.empty()) { authorities = authFactory->databaseContext()->getAllowedAuthorities( srcAuthName, targetAuthName); if (authorities.empty()) { authorities.emplace_back(); } } else { authorities.emplace_back(authFactoryName); } return authorities; } // --------------------------------------------------------------------------- // Look in the authority registry for operations from sourceCRS to targetCRS std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private::findOpsInRegistryDirect( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, bool &resNonEmptyBeforeFiltering) { const auto &authFactory = context.context->getAuthorityFactory(); assert(authFactory); #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("findOpsInRegistryDirect(" + objectAsStr(sourceCRS.get()) + " --> " + objectAsStr(targetCRS.get()) + ")"); #endif resNonEmptyBeforeFiltering = false; std::list<std::pair<std::string, std::string>> sourceIds; std::list<std::pair<std::string, std::string>> targetIds; buildCRSIds(sourceCRS, context, sourceIds); buildCRSIds(targetCRS, context, targetIds); const auto gridAvailabilityUse = context.context->getGridAvailabilityUse(); for (const auto &idSrc : sourceIds) { const auto &srcAuthName = idSrc.first; const auto &srcCode = idSrc.second; for (const auto &idTarget : targetIds) { const auto &targetAuthName = idTarget.first; const auto &targetCode = idTarget.second; const auto authorities(getCandidateAuthorities( authFactory, srcAuthName, targetAuthName)); std::vector<CoordinateOperationNNPtr> res; for (const auto &authority : authorities) { const auto authName = authority == "any" ? std::string() : authority; const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), authName); auto resTmp = tmpAuthFactory->createFromCoordinateReferenceSystemCodes( srcAuthName, srcCode, targetAuthName, targetCode, context.context->getUsePROJAlternativeGridNames(), gridAvailabilityUse == CoordinateOperationContext:: GridAvailabilityUse:: DISCARD_OPERATION_IF_MISSING_GRID || gridAvailabilityUse == CoordinateOperationContext:: GridAvailabilityUse::KNOWN_AVAILABLE, gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE, context.context->getDiscardSuperseded(), true, false, context.extent1, context.extent2); res.insert(res.end(), resTmp.begin(), resTmp.end()); if (authName == "PROJ") { // Do not stop at the first transformations available in // the PROJ namespace, but allow the next authority to // continue continue; } if (!res.empty()) { resNonEmptyBeforeFiltering = true; auto resFiltered = FilterResults(res, context.context, context.extent1, context.extent2, false) .getRes(); #ifdef TRACE_CREATE_OPERATIONS logTrace("filtering reduced from " + toString(static_cast<int>(res.size())) + " to " + toString(static_cast<int>(resFiltered.size()))); #endif return resFiltered; } } } } return std::vector<CoordinateOperationNNPtr>(); } // --------------------------------------------------------------------------- // Look in the authority registry for operations to targetCRS std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private::findOpsInRegistryDirectTo( const crs::CRSNNPtr &targetCRS, Private::Context &context) { #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("findOpsInRegistryDirectTo({any} -->" + objectAsStr(targetCRS.get()) + ")"); #endif const auto &authFactory = context.context->getAuthorityFactory(); assert(authFactory); std::list<std::pair<std::string, std::string>> ids; buildCRSIds(targetCRS, context, ids); const auto gridAvailabilityUse = context.context->getGridAvailabilityUse(); for (const auto &id : ids) { const auto &targetAuthName = id.first; const auto &targetCode = id.second; const auto authorities(getCandidateAuthorities( authFactory, targetAuthName, targetAuthName)); std::vector<CoordinateOperationNNPtr> res; for (const auto &authority : authorities) { const auto authName = authority == "any" ? std::string() : authority; const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), authName); auto resTmp = tmpAuthFactory->createFromCoordinateReferenceSystemCodes( std::string(), std::string(), targetAuthName, targetCode, context.context->getUsePROJAlternativeGridNames(), gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: DISCARD_OPERATION_IF_MISSING_GRID || gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE, gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE, context.context->getDiscardSuperseded(), true, true, context.extent1, context.extent2); res.insert(res.end(), resTmp.begin(), resTmp.end()); if (authName == "PROJ") { // Do not stop at the first transformations available in // the PROJ namespace, but allow the next authority to continue continue; } if (!res.empty()) { auto resFiltered = FilterResults(res, context.context, context.extent1, context.extent2, false) .getRes(); #ifdef TRACE_CREATE_OPERATIONS logTrace("filtering reduced from " + toString(static_cast<int>(res.size())) + " to " + toString(static_cast<int>(resFiltered.size()))); #endif return resFiltered; } } } return std::vector<CoordinateOperationNNPtr>(); } //! @endcond // --------------------------------------------------------------------------- static std::list<crs::GeodeticCRSNNPtr> findCandidateGeodCRSForDatum(const io::AuthorityFactoryPtr &authFactory, const crs::GeodeticCRS *crs, const datum::GeodeticReferenceFrameNNPtr &datum) { std::string preferredAuthName; const auto &crsIds = crs->identifiers(); if (crsIds.size() == 1) preferredAuthName = *(crsIds.front()->codeSpace()); return authFactory->createGeodeticCRSFromDatum(datum, preferredAuthName, std::string()); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool isSameGeodeticDatum(const datum::GeodeticReferenceFrameNNPtr &datum1, const datum::GeodeticReferenceFrameNNPtr &datum2, const io::DatabaseContextPtr &dbContext) { if (datum1->nameStr() == "unknown" && datum2->nameStr() != "unknown") return false; if (datum2->nameStr() == "unknown" && datum1->nameStr() != "unknown") return false; return datum1->_isEquivalentTo( datum2.get(), util::IComparable::Criterion::EQUIVALENT, dbContext); } // --------------------------------------------------------------------------- // Look in the authority registry for operations from sourceCRS to targetCRS // using an intermediate pivot std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private::findsOpsInRegistryWithIntermediate( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, bool useCreateBetweenGeodeticCRSWithDatumBasedIntermediates) { #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("findsOpsInRegistryWithIntermediate(" + objectAsStr(sourceCRS.get()) + " --> " + objectAsStr(targetCRS.get()) + ")"); #endif const auto &authFactory = context.context->getAuthorityFactory(); assert(authFactory); std::list<std::pair<std::string, std::string>> sourceIds; buildCRSIds(sourceCRS, context, sourceIds); if (sourceIds.empty()) { auto geodSrc = dynamic_cast<crs::GeodeticCRS *>(sourceCRS.get()); auto geodDst = dynamic_cast<crs::GeodeticCRS *>(targetCRS.get()); if (geodSrc) { const auto dbContext = authFactory->databaseContext().as_nullable(); const auto candidatesSrcGeod(findCandidateGeodCRSForDatum( authFactory, geodSrc, geodSrc->datumNonNull(dbContext))); std::vector<CoordinateOperationNNPtr> res; for (const auto &candidateSrcGeod : candidatesSrcGeod) { if (candidateSrcGeod->coordinateSystem()->axisList().size() == geodSrc->coordinateSystem()->axisList().size() && ((dynamic_cast<crs::GeographicCRS *>(sourceCRS.get()) != nullptr) == (dynamic_cast<crs::GeographicCRS *>( candidateSrcGeod.get()) != nullptr))) { if (geodDst) { const auto srcDatum = candidateSrcGeod->datumNonNull(dbContext); const auto dstDatum = geodDst->datumNonNull(dbContext); const bool sameGeodeticDatum = isSameGeodeticDatum(srcDatum, dstDatum, dbContext); if (sameGeodeticDatum) { continue; } } const auto opsWithIntermediate = findsOpsInRegistryWithIntermediate( candidateSrcGeod, targetCRS, context, useCreateBetweenGeodeticCRSWithDatumBasedIntermediates); if (!opsWithIntermediate.empty()) { const auto opsFirst = createOperations( sourceCRS, util::optional<common::DataEpoch>(), candidateSrcGeod, util::optional<common::DataEpoch>(), context); for (const auto &opFirst : opsFirst) { for (const auto &opSecond : opsWithIntermediate) { try { res.emplace_back( ConcatenatedOperation:: createComputeMetadata( {opFirst, opSecond}, disallowEmptyIntersection)); } catch ( const InvalidOperationEmptyIntersection &) { } } } if (!res.empty()) return res; } } } } return std::vector<CoordinateOperationNNPtr>(); } std::list<std::pair<std::string, std::string>> targetIds; buildCRSIds(targetCRS, context, targetIds); if (targetIds.empty()) { return applyInverse(findsOpsInRegistryWithIntermediate( targetCRS, sourceCRS, context, useCreateBetweenGeodeticCRSWithDatumBasedIntermediates)); } const auto gridAvailabilityUse = context.context->getGridAvailabilityUse(); for (const auto &idSrc : sourceIds) { const auto &srcAuthName = idSrc.first; const auto &srcCode = idSrc.second; for (const auto &idTarget : targetIds) { const auto &targetAuthName = idTarget.first; const auto &targetCode = idTarget.second; const auto authorities(getCandidateAuthorities( authFactory, srcAuthName, targetAuthName)); assert(!authorities.empty()); const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), (authFactory->getAuthority() == "any" || authorities.size() > 1) ? std::string() : authorities.front()); std::vector<CoordinateOperationNNPtr> res; if (useCreateBetweenGeodeticCRSWithDatumBasedIntermediates) { res = tmpAuthFactory ->createBetweenGeodeticCRSWithDatumBasedIntermediates( sourceCRS, srcAuthName, srcCode, targetCRS, targetAuthName, targetCode, context.context->getUsePROJAlternativeGridNames(), gridAvailabilityUse == CoordinateOperationContext:: GridAvailabilityUse:: DISCARD_OPERATION_IF_MISSING_GRID || gridAvailabilityUse == CoordinateOperationContext:: GridAvailabilityUse::KNOWN_AVAILABLE, gridAvailabilityUse == CoordinateOperationContext:: GridAvailabilityUse::KNOWN_AVAILABLE, context.context->getDiscardSuperseded(), authFactory->getAuthority() != "any" && authorities.size() > 1 ? authorities : std::vector<std::string>(), context.extent1, context.extent2); } else { io::AuthorityFactory::ObjectType intermediateObjectType = io::AuthorityFactory::ObjectType::CRS; // If doing GeogCRS --> GeogCRS, only use GeogCRS as // intermediate CRS // Avoid weird behavior when doing NAD83 -> NAD83(2011) // that would go through NAVD88 otherwise. if (context.context->getIntermediateCRS().empty() && dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()) && dynamic_cast<const crs::GeographicCRS *>(targetCRS.get())) { intermediateObjectType = io::AuthorityFactory::ObjectType::GEOGRAPHIC_CRS; } res = tmpAuthFactory->createFromCRSCodesWithIntermediates( srcAuthName, srcCode, targetAuthName, targetCode, context.context->getUsePROJAlternativeGridNames(), gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: DISCARD_OPERATION_IF_MISSING_GRID || gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE, gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE, context.context->getDiscardSuperseded(), context.context->getIntermediateCRS(), intermediateObjectType, authFactory->getAuthority() != "any" && authorities.size() > 1 ? authorities : std::vector<std::string>(), context.extent1, context.extent2); } if (!res.empty()) { auto resFiltered = FilterResults(res, context.context, context.extent1, context.extent2, false) .getRes(); #ifdef TRACE_CREATE_OPERATIONS logTrace("filtering reduced from " + toString(static_cast<int>(res.size())) + " to " + toString(static_cast<int>(resFiltered.size()))); #endif return resFiltered; } } } return std::vector<CoordinateOperationNNPtr>(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static TransformationNNPtr createBallparkGeographicOffset( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const io::DatabaseContextPtr &dbContext, bool forceBallpark) { const crs::GeographicCRS *geogSrc = dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()); const crs::GeographicCRS *geogDst = dynamic_cast<const crs::GeographicCRS *>(targetCRS.get()); const bool isSameDatum = !forceBallpark && geogSrc && geogDst && isSameGeodeticDatum(geogSrc->datumNonNull(dbContext), geogDst->datumNonNull(dbContext), dbContext); auto name = buildOpName(isSameDatum ? NULL_GEOGRAPHIC_OFFSET : BALLPARK_GEOGRAPHIC_OFFSET, sourceCRS, targetCRS); const auto &sourceCRSExtent = getExtent(sourceCRS); const auto &targetCRSExtent = getExtent(targetCRS); const bool sameExtent = sourceCRSExtent && targetCRSExtent && sourceCRSExtent->_isEquivalentTo( targetCRSExtent.get(), util::IComparable::Criterion::EQUIVALENT); util::PropertyMap map; map.set(common::IdentifiedObject::NAME_KEY, name) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, sameExtent ? NN_NO_CHECK(sourceCRSExtent) : metadata::Extent::WORLD); const common::Angle angle0(0); std::vector<metadata::PositionalAccuracyNNPtr> accuracies; if (isSameDatum) { accuracies.emplace_back(metadata::PositionalAccuracy::create("0")); } const auto singleSourceCRS = dynamic_cast<const crs::SingleCRS *>(sourceCRS.get()); const auto singleTargetCRS = dynamic_cast<const crs::SingleCRS *>(targetCRS.get()); if ((singleSourceCRS && singleSourceCRS->coordinateSystem()->axisList().size() == 3) || (singleTargetCRS && singleTargetCRS->coordinateSystem()->axisList().size() == 3)) { return Transformation::createGeographic3DOffsets( map, sourceCRS, targetCRS, angle0, angle0, common::Length(0), accuracies); } else { return Transformation::createGeographic2DOffsets( map, sourceCRS, targetCRS, angle0, angle0, accuracies); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- struct MyPROJStringExportableGeodToGeod final : public io::IPROJStringExportable { crs::GeodeticCRSPtr geodSrc{}; crs::GeodeticCRSPtr geodDst{}; MyPROJStringExportableGeodToGeod(const crs::GeodeticCRSPtr &geodSrcIn, const crs::GeodeticCRSPtr &geodDstIn) : geodSrc(geodSrcIn), geodDst(geodDstIn) {} ~MyPROJStringExportableGeodToGeod() override; void // cppcheck-suppress functionStatic _exportToPROJString(io::PROJStringFormatter *formatter) const override { formatter->startInversion(); geodSrc->_exportToPROJString(formatter); formatter->stopInversion(); geodDst->_exportToPROJString(formatter); } }; MyPROJStringExportableGeodToGeod::~MyPROJStringExportableGeodToGeod() = default; // --------------------------------------------------------------------------- struct MyPROJStringExportableHorizVertical final : public io::IPROJStringExportable { CoordinateOperationPtr horizTransform{}; CoordinateOperationPtr verticalTransform{}; crs::GeographicCRSPtr geogDst{}; MyPROJStringExportableHorizVertical( const CoordinateOperationPtr &horizTransformIn, const CoordinateOperationPtr &verticalTransformIn, const crs::GeographicCRSPtr &geogDstIn) : horizTransform(horizTransformIn), verticalTransform(verticalTransformIn), geogDst(geogDstIn) {} ~MyPROJStringExportableHorizVertical() override; void // cppcheck-suppress functionStatic _exportToPROJString(io::PROJStringFormatter *formatter) const override { horizTransform->_exportToPROJString(formatter); formatter->startInversion(); geogDst->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); formatter->pushOmitHorizontalConversionInVertTransformation(); verticalTransform->_exportToPROJString(formatter); formatter->popOmitHorizontalConversionInVertTransformation(); formatter->pushOmitZUnitConversion(); geogDst->addAngularUnitConvertAndAxisSwap(formatter); formatter->popOmitZUnitConversion(); } }; MyPROJStringExportableHorizVertical::~MyPROJStringExportableHorizVertical() = default; // --------------------------------------------------------------------------- struct MyPROJStringExportableHorizVerticalHorizPROJBased final : public io::IPROJStringExportable { CoordinateOperationPtr opSrcCRSToGeogCRS{}; CoordinateOperationPtr verticalTransform{}; CoordinateOperationPtr opGeogCRStoDstCRS{}; crs::GeographicCRSPtr interpolationGeogCRS{}; MyPROJStringExportableHorizVerticalHorizPROJBased( const CoordinateOperationPtr &opSrcCRSToGeogCRSIn, const CoordinateOperationPtr &verticalTransformIn, const CoordinateOperationPtr &opGeogCRStoDstCRSIn, const crs::GeographicCRSPtr &interpolationGeogCRSIn) : opSrcCRSToGeogCRS(opSrcCRSToGeogCRSIn), verticalTransform(verticalTransformIn), opGeogCRStoDstCRS(opGeogCRStoDstCRSIn), interpolationGeogCRS(interpolationGeogCRSIn) {} ~MyPROJStringExportableHorizVerticalHorizPROJBased() override; void // cppcheck-suppress functionStatic _exportToPROJString(io::PROJStringFormatter *formatter) const override { bool saveHorizontalCoords = false; const auto transf = dynamic_cast<Transformation *>(opSrcCRSToGeogCRS.get()); if (transf && opSrcCRSToGeogCRS->sourceCRS()->_isEquivalentTo( opGeogCRStoDstCRS->targetCRS() ->demoteTo2D(std::string(), nullptr) .get(), util::IComparable::Criterion::EQUIVALENT)) { int methodEPSGCode = transf->method()->getEPSGCode(); if (methodEPSGCode == 0) { // If the transformation is actually an inverse transformation, // we will not get the EPSG code. So get the forward // transformation. const auto invTrans = transf->inverse(); const auto invTransAsTrans = dynamic_cast<Transformation *>(invTrans.get()); if (invTransAsTrans) methodEPSGCode = invTransAsTrans->method()->getEPSGCode(); } const bool bGeocentricTranslation = methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D; if ((bGeocentricTranslation && !(transf->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION) == 0 && transf->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION) == 0 && transf->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION) == 0)) || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D) { saveHorizontalCoords = true; } } if (saveHorizontalCoords) { formatter->addStep("push"); formatter->addParam("v_1"); formatter->addParam("v_2"); } formatter->pushOmitZUnitConversion(); opSrcCRSToGeogCRS->_exportToPROJString(formatter); formatter->startInversion(); interpolationGeogCRS->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); formatter->popOmitZUnitConversion(); formatter->pushOmitHorizontalConversionInVertTransformation(); verticalTransform->_exportToPROJString(formatter); formatter->popOmitHorizontalConversionInVertTransformation(); formatter->pushOmitZUnitConversion(); interpolationGeogCRS->addAngularUnitConvertAndAxisSwap(formatter); opGeogCRStoDstCRS->_exportToPROJString(formatter); formatter->popOmitZUnitConversion(); if (saveHorizontalCoords) { formatter->addStep("pop"); formatter->addParam("v_1"); formatter->addParam("v_2"); } } }; MyPROJStringExportableHorizVerticalHorizPROJBased:: ~MyPROJStringExportableHorizVerticalHorizPROJBased() = default; // --------------------------------------------------------------------------- struct MyPROJStringExportableHorizNullVertical final : public io::IPROJStringExportable { CoordinateOperationPtr horizTransform{}; explicit MyPROJStringExportableHorizNullVertical( const CoordinateOperationPtr &horizTransformIn) : horizTransform(horizTransformIn) {} ~MyPROJStringExportableHorizNullVertical() override; void // cppcheck-suppress functionStatic _exportToPROJString(io::PROJStringFormatter *formatter) const override { horizTransform->_exportToPROJString(formatter); } }; MyPROJStringExportableHorizNullVertical:: ~MyPROJStringExportableHorizNullVertical() = default; //! @endcond } // namespace operation NS_PROJ_END #if 0 namespace dropbox{ namespace oxygen { template<> nn<std::shared_ptr<NS_PROJ::operation::MyPROJStringExportableGeodToGeod>>::~nn() = default; template<> nn<std::shared_ptr<NS_PROJ::operation::MyPROJStringExportableHorizVertical>>::~nn() = default; template<> nn<std::shared_ptr<NS_PROJ::operation::MyPROJStringExportableHorizVerticalHorizPROJBased>>::~nn() = default; template<> nn<std::shared_ptr<NS_PROJ::operation::MyPROJStringExportableHorizNullVertical>>::~nn() = default; }} #endif NS_PROJ_START namespace operation { //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- static std::string buildTransfName(const std::string &srcName, const std::string &targetName) { std::string name("Transformation from "); name += srcName; name += " to "; name += targetName; return name; } // --------------------------------------------------------------------------- static std::string buildConvName(const std::string &srcName, const std::string &targetName) { std::string name("Conversion from "); name += srcName; name += " to "; name += targetName; return name; } // --------------------------------------------------------------------------- static SingleOperationNNPtr createPROJBased( const util::PropertyMap &properties, const io::IPROJStringExportableNNPtr &projExportable, const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const crs::CRSPtr &interpolationCRS, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies, bool hasBallparkTransformation) { return util::nn_static_pointer_cast<SingleOperation>( PROJBasedOperation::create(properties, projExportable, false, sourceCRS, targetCRS, interpolationCRS, accuracies, hasBallparkTransformation)); } // --------------------------------------------------------------------------- static CoordinateOperationNNPtr createGeodToGeodPROJBased(const crs::CRSNNPtr &geodSrc, const crs::CRSNNPtr &geodDst) { auto exportable = util::nn_make_shared<MyPROJStringExportableGeodToGeod>( util::nn_dynamic_pointer_cast<crs::GeodeticCRS>(geodSrc), util::nn_dynamic_pointer_cast<crs::GeodeticCRS>(geodDst)); auto properties = util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, buildTransfName(geodSrc->nameStr(), geodDst->nameStr())) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD); return createPROJBased(properties, exportable, geodSrc, geodDst, nullptr, {}, false); } // --------------------------------------------------------------------------- static std::string getRemarks(const std::vector<operation::CoordinateOperationNNPtr> &ops) { std::string remarks; for (const auto &op : ops) { const auto &opRemarks = op->remarks(); if (!opRemarks.empty()) { if (!remarks.empty()) { remarks += '\n'; } std::string opName(op->nameStr()); if (starts_with(opName, INVERSE_OF)) { opName = opName.substr(INVERSE_OF.size()); } remarks += "For "; remarks += opName; const auto &ids = op->identifiers(); if (!ids.empty()) { std::string authority(*ids.front()->codeSpace()); if (starts_with(authority, "INVERSE(") && authority.back() == ')') { authority = authority.substr(strlen("INVERSE("), authority.size() - 1 - strlen("INVERSE(")); } if (starts_with(authority, "DERIVED_FROM(") && authority.back() == ')') { authority = authority.substr(strlen("DERIVED_FROM("), authority.size() - 1 - strlen("DERIVED_FROM(")); } remarks += " ("; remarks += authority; remarks += ':'; remarks += ids.front()->code(); remarks += ')'; } remarks += ": "; remarks += opRemarks; } } return remarks; } // --------------------------------------------------------------------------- static CoordinateOperationNNPtr createHorizVerticalPROJBased( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const operation::CoordinateOperationNNPtr &horizTransform, const operation::CoordinateOperationNNPtr &verticalTransform, bool checkExtent) { auto geogDst = util::nn_dynamic_pointer_cast<crs::GeographicCRS>(targetCRS); assert(geogDst); auto exportable = util::nn_make_shared<MyPROJStringExportableHorizVertical>( horizTransform, verticalTransform, geogDst); const bool horizTransformIsNoOp = starts_with(horizTransform->nameStr(), NULL_GEOGRAPHIC_OFFSET) && horizTransform->nameStr().find(" + ") == std::string::npos; if (horizTransformIsNoOp) { auto properties = util::PropertyMap(); properties.set(common::IdentifiedObject::NAME_KEY, verticalTransform->nameStr()); bool dummy = false; auto extent = getExtent(verticalTransform, true, dummy); if (extent) { properties.set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, NN_NO_CHECK(extent)); } const auto &remarks = verticalTransform->remarks(); if (!remarks.empty()) { properties.set(common::IdentifiedObject::REMARKS_KEY, remarks); } return createPROJBased( properties, exportable, sourceCRS, targetCRS, nullptr, verticalTransform->coordinateOperationAccuracies(), verticalTransform->hasBallparkTransformation()); } else { bool emptyIntersection = false; auto ops = std::vector<CoordinateOperationNNPtr>{horizTransform, verticalTransform}; auto extent = getExtent(ops, true, emptyIntersection); if (checkExtent && emptyIntersection) { std::string msg( "empty intersection of area of validity of concatenated " "operations"); throw InvalidOperationEmptyIntersection(msg); } auto properties = util::PropertyMap(); properties.set(common::IdentifiedObject::NAME_KEY, computeConcatenatedName(ops)); if (extent) { properties.set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, NN_NO_CHECK(extent)); } const auto remarks = getRemarks(ops); if (!remarks.empty()) { properties.set(common::IdentifiedObject::REMARKS_KEY, remarks); } std::vector<metadata::PositionalAccuracyNNPtr> accuracies; const double accuracy = getAccuracy(ops); if (accuracy >= 0.0) { accuracies.emplace_back( metadata::PositionalAccuracy::create(toString(accuracy))); } return createPROJBased( properties, exportable, sourceCRS, targetCRS, nullptr, accuracies, horizTransform->hasBallparkTransformation() || verticalTransform->hasBallparkTransformation()); } } // --------------------------------------------------------------------------- static CoordinateOperationNNPtr createHorizVerticalHorizPROJBased( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const operation::CoordinateOperationNNPtr &opSrcCRSToGeogCRS, const operation::CoordinateOperationNNPtr &verticalTransform, const operation::CoordinateOperationNNPtr &opGeogCRStoDstCRS, const crs::GeographicCRSPtr &interpolationGeogCRS, bool checkExtent) { auto exportable = util::nn_make_shared<MyPROJStringExportableHorizVerticalHorizPROJBased>( opSrcCRSToGeogCRS, verticalTransform, opGeogCRStoDstCRS, interpolationGeogCRS); std::vector<CoordinateOperationNNPtr> ops; if (!(starts_with(opSrcCRSToGeogCRS->nameStr(), NULL_GEOGRAPHIC_OFFSET) && opSrcCRSToGeogCRS->nameStr().find(" + ") == std::string::npos)) { ops.emplace_back(opSrcCRSToGeogCRS); } ops.emplace_back(verticalTransform); if (!(starts_with(opGeogCRStoDstCRS->nameStr(), NULL_GEOGRAPHIC_OFFSET) && opGeogCRStoDstCRS->nameStr().find(" + ") == std::string::npos)) { ops.emplace_back(opGeogCRStoDstCRS); } std::vector<CoordinateOperationNNPtr> opsForRemarks; std::vector<CoordinateOperationNNPtr> opsForAccuracy; std::string opName; if (ops.size() == 3 && opGeogCRStoDstCRS->inverse()->_isEquivalentTo( opSrcCRSToGeogCRS.get(), util::IComparable::Criterion::EQUIVALENT)) { opsForRemarks.emplace_back(opSrcCRSToGeogCRS); opsForRemarks.emplace_back(verticalTransform); // Only taking into account the accuracy of the vertical transform when // opSrcCRSToGeogCRS and opGeogCRStoDstCRS are reversed and cancel // themselves would make sense. Unfortunately it causes // EPSG:4313+5710 (BD72 + Ostend height) to EPSG:9707 // (WGS 84 + EGM96 height) to use a non-ideal pipeline. // opsForAccuracy.emplace_back(verticalTransform); opsForAccuracy = ops; opName = verticalTransform->nameStr() + " using "; if (!starts_with(opSrcCRSToGeogCRS->nameStr(), "Inverse of")) opName += opSrcCRSToGeogCRS->nameStr(); else opName += opGeogCRStoDstCRS->nameStr(); } else { opsForRemarks = ops; opsForAccuracy = ops; opName = computeConcatenatedName(ops); } bool hasBallparkTransformation = false; for (const auto &op : ops) { hasBallparkTransformation |= op->hasBallparkTransformation(); } bool emptyIntersection = false; auto extent = getExtent(ops, false, emptyIntersection); if (checkExtent && emptyIntersection) { std::string msg( "empty intersection of area of validity of concatenated " "operations"); throw InvalidOperationEmptyIntersection(msg); } auto properties = util::PropertyMap(); properties.set(common::IdentifiedObject::NAME_KEY, opName); if (extent) { properties.set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, NN_NO_CHECK(extent)); } const auto remarks = getRemarks(opsForRemarks); if (!remarks.empty()) { properties.set(common::IdentifiedObject::REMARKS_KEY, remarks); } std::vector<metadata::PositionalAccuracyNNPtr> accuracies; const double accuracy = getAccuracy(opsForAccuracy); if (accuracy >= 0.0) { accuracies.emplace_back( metadata::PositionalAccuracy::create(toString(accuracy))); } return createPROJBased(properties, exportable, sourceCRS, targetCRS, nullptr, accuracies, hasBallparkTransformation); } // --------------------------------------------------------------------------- static CoordinateOperationNNPtr createHorizNullVerticalPROJBased( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const operation::CoordinateOperationNNPtr &horizTransform, const operation::CoordinateOperationNNPtr &verticalTransform) { auto exportable = util::nn_make_shared<MyPROJStringExportableHorizNullVertical>( horizTransform); std::vector<CoordinateOperationNNPtr> ops = {horizTransform, verticalTransform}; const std::string opName = computeConcatenatedName(ops); auto properties = util::PropertyMap(); properties.set(common::IdentifiedObject::NAME_KEY, opName); bool emptyIntersection = false; auto extent = getExtent(ops, false, emptyIntersection); if (extent) { properties.set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, NN_NO_CHECK(extent)); } const auto remarks = getRemarks(ops); if (!remarks.empty()) { properties.set(common::IdentifiedObject::REMARKS_KEY, remarks); } return createPROJBased(properties, exportable, sourceCRS, targetCRS, nullptr, {}, /*hasBallparkTransformation=*/true); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private::createOperationsGeogToGeog( std::vector<CoordinateOperationNNPtr> &res, const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::GeographicCRS *geogSrc, const crs::GeographicCRS *geogDst, bool forceBallpark) { assert(sourceCRS.get() == geogSrc); assert(targetCRS.get() == geogDst); const auto &src_pm = geogSrc->primeMeridian()->longitude(); const auto &dst_pm = geogDst->primeMeridian()->longitude(); const common::Angle offset_pm( (src_pm.unit() == dst_pm.unit()) ? common::Angle(src_pm.value() - dst_pm.value(), src_pm.unit()) : common::Angle( src_pm.convertToUnit(common::UnitOfMeasure::DEGREE) - dst_pm.convertToUnit(common::UnitOfMeasure::DEGREE), common::UnitOfMeasure::DEGREE)); double vconvSrc = 1.0; const auto &srcCS = geogSrc->coordinateSystem(); const auto &srcAxisList = srcCS->axisList(); if (srcAxisList.size() == 3) { vconvSrc = srcAxisList[2]->unit().conversionToSI(); } double vconvDst = 1.0; const auto &dstCS = geogDst->coordinateSystem(); const auto &dstAxisList = dstCS->axisList(); if (dstAxisList.size() == 3) { vconvDst = dstAxisList[2]->unit().conversionToSI(); } std::string name(buildTransfName(geogSrc->nameStr(), geogDst->nameStr())); const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; const bool sameDatum = !forceBallpark && isSameGeodeticDatum(geogSrc->datumNonNull(dbContext), geogDst->datumNonNull(dbContext), dbContext); // Do the CRS differ by their axis order ? bool axisReversal2D = false; bool axisReversal3D = false; if (!srcCS->_isEquivalentTo(dstCS.get(), util::IComparable::Criterion::EQUIVALENT)) { auto srcOrder = srcCS->axisOrder(); auto dstOrder = dstCS->axisOrder(); if (((srcOrder == cs::EllipsoidalCS::AxisOrder::LAT_NORTH_LONG_EAST || srcOrder == cs::EllipsoidalCS::AxisOrder:: LAT_NORTH_LONG_EAST_HEIGHT_UP) && (dstOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH || dstOrder == cs::EllipsoidalCS::AxisOrder:: LONG_EAST_LAT_NORTH_HEIGHT_UP)) || ((srcOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH || srcOrder == cs::EllipsoidalCS::AxisOrder:: LONG_EAST_LAT_NORTH_HEIGHT_UP) && (dstOrder == cs::EllipsoidalCS::AxisOrder::LAT_NORTH_LONG_EAST || dstOrder == cs::EllipsoidalCS::AxisOrder:: LAT_NORTH_LONG_EAST_HEIGHT_UP))) { if (srcAxisList.size() == 3 || dstAxisList.size() == 3) axisReversal3D = true; else axisReversal2D = true; } } // Do they differ by vertical units ? if (vconvSrc != vconvDst && geogSrc->ellipsoid()->_isEquivalentTo( geogDst->ellipsoid().get(), util::IComparable::Criterion::EQUIVALENT)) { if (offset_pm.value() == 0 && !axisReversal2D && !axisReversal3D) { // If only by vertical units, use a Change of Vertical // Unit transformation if (vconvDst == 0) throw InvalidOperation("Conversion factor of target unit is 0"); const double factor = vconvSrc / vconvDst; auto conv = Conversion::createChangeVerticalUnit( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, name), common::Scale(factor)); conv->setCRSs(sourceCRS, targetCRS, nullptr); conv->setHasBallparkTransformation(!sameDatum); res.push_back(conv); return res; } else { auto op = createGeodToGeodPROJBased(sourceCRS, targetCRS); op->setHasBallparkTransformation(!sameDatum); res.emplace_back(op); return res; } } // Do the CRS differ only by their axis order ? if (sameDatum && (axisReversal2D || axisReversal3D)) { auto conv = Conversion::createAxisOrderReversal(axisReversal3D); conv->setCRSs(sourceCRS, targetCRS, nullptr); res.emplace_back(conv); return res; } std::vector<CoordinateOperationNNPtr> steps; // If both are geographic and only differ by their prime // meridian, // apply a longitude rotation transformation. if (geogSrc->ellipsoid()->_isEquivalentTo( geogDst->ellipsoid().get(), util::IComparable::Criterion::EQUIVALENT) && src_pm.getSIValue() != dst_pm.getSIValue()) { steps.emplace_back(Transformation::createLongitudeRotation( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), sourceCRS, targetCRS, offset_pm)); // If only the target has a non-zero prime meridian, chain a // null geographic offset and then the longitude rotation } else if (src_pm.getSIValue() == 0 && dst_pm.getSIValue() != 0) { auto datum = datum::GeodeticReferenceFrame::create( util::PropertyMap(), geogDst->ellipsoid(), util::optional<std::string>(), geogSrc->primeMeridian()); std::string interm_crs_name(geogDst->nameStr()); interm_crs_name += " altered to use prime meridian of "; interm_crs_name += geogSrc->nameStr(); auto interm_crs = util::nn_static_pointer_cast<crs::CRS>(crs::GeographicCRS::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, interm_crs_name) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), datum, dstCS)); steps.emplace_back(createBallparkGeographicOffset( sourceCRS, interm_crs, dbContext, forceBallpark)); steps.emplace_back(Transformation::createLongitudeRotation( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, buildTransfName(geogSrc->nameStr(), interm_crs->nameStr())) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), interm_crs, targetCRS, offset_pm)); } else { // If the prime meridians are different, chain a longitude // rotation and the null geographic offset. if (src_pm.getSIValue() != dst_pm.getSIValue()) { auto datum = datum::GeodeticReferenceFrame::create( util::PropertyMap(), geogSrc->ellipsoid(), util::optional<std::string>(), geogDst->primeMeridian()); std::string interm_crs_name(geogSrc->nameStr()); interm_crs_name += " altered to use prime meridian of "; interm_crs_name += geogDst->nameStr(); auto interm_crs = util::nn_static_pointer_cast<crs::CRS>( crs::GeographicCRS::create( util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, interm_crs_name), datum, srcCS)); steps.emplace_back(Transformation::createLongitudeRotation( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, buildTransfName(geogSrc->nameStr(), interm_crs->nameStr())) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), sourceCRS, interm_crs, offset_pm)); steps.emplace_back(createBallparkGeographicOffset( interm_crs, targetCRS, dbContext, forceBallpark)); } else { steps.emplace_back(createBallparkGeographicOffset( sourceCRS, targetCRS, dbContext, forceBallpark)); } } auto op = ConcatenatedOperation::createComputeMetadata( steps, disallowEmptyIntersection); op->setHasBallparkTransformation(!sameDatum); res.emplace_back(op); return res; } // --------------------------------------------------------------------------- static bool hasIdentifiers(const CoordinateOperationNNPtr &op) { if (!op->identifiers().empty()) { return true; } auto concatenated = dynamic_cast<const ConcatenatedOperation *>(op.get()); if (concatenated) { for (const auto &subOp : concatenated->operations()) { if (hasIdentifiers(subOp)) { return true; } } } return false; } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::setCRSs( CoordinateOperation *co, const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS) { const auto &interpolationCRS = co->interpolationCRS(); co->setCRSs(sourceCRS, targetCRS, interpolationCRS); auto invCO = dynamic_cast<InverseCoordinateOperation *>(co); if (invCO) { invCO->forwardOperation()->setCRSs(targetCRS, sourceCRS, interpolationCRS); } auto transf = dynamic_cast<Transformation *>(co); if (transf) { transf->inverseAsTransformation()->setCRSs(targetCRS, sourceCRS, interpolationCRS); } auto concat = dynamic_cast<ConcatenatedOperation *>(co); if (concat) { auto first = concat->operations().front().get(); auto &firstTarget(first->targetCRS()); if (firstTarget) { setCRSs(first, sourceCRS, NN_NO_CHECK(firstTarget)); } auto last = concat->operations().back().get(); auto &lastSource(last->sourceCRS()); if (lastSource) { setCRSs(last, NN_NO_CHECK(lastSource), targetCRS); } } } // --------------------------------------------------------------------------- static bool hasResultSetOnlyResultsWithPROJStep( const std::vector<CoordinateOperationNNPtr> &res) { for (const auto &op : res) { auto concat = dynamic_cast<const ConcatenatedOperation *>(op.get()); if (concat) { bool hasPROJStep = false; const auto &steps = concat->operations(); for (const auto &step : steps) { const auto &ids = step->identifiers(); if (!ids.empty()) { const auto &opAuthority = *(ids.front()->codeSpace()); if (opAuthority == "PROJ" || opAuthority == "INVERSE(PROJ)" || opAuthority == "DERIVED_FROM(PROJ)") { hasPROJStep = true; break; } } } if (!hasPROJStep) { return false; } } else { return false; } } return true; } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsWithDatumPivot( std::vector<CoordinateOperationNNPtr> &res, const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, const crs::GeodeticCRS *geodSrc, const crs::GeodeticCRS *geodDst, Private::Context &context) { #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("createOperationsWithDatumPivot(" + objectAsStr(sourceCRS.get()) + "," + objectAsStr(targetCRS.get()) + ")"); #endif struct CreateOperationsWithDatumPivotAntiRecursion { Context &context; explicit CreateOperationsWithDatumPivotAntiRecursion(Context &contextIn) : context(contextIn) { assert(!context.inCreateOperationsWithDatumPivotAntiRecursion); context.inCreateOperationsWithDatumPivotAntiRecursion = true; } ~CreateOperationsWithDatumPivotAntiRecursion() { context.inCreateOperationsWithDatumPivotAntiRecursion = false; } }; CreateOperationsWithDatumPivotAntiRecursion guard(context); const auto &authFactory = context.context->getAuthorityFactory(); const auto &dbContext = authFactory->databaseContext(); const auto candidatesSrcGeod(findCandidateGeodCRSForDatum( authFactory, geodSrc, geodSrc->datumNonNull(dbContext.as_nullable()))); const auto candidatesDstGeod(findCandidateGeodCRSForDatum( authFactory, geodDst, geodDst->datumNonNull(dbContext.as_nullable()))); const bool sourceAndTargetAre3D = geodSrc->coordinateSystem()->axisList().size() == 3 && geodDst->coordinateSystem()->axisList().size() == 3; auto createTransformations = [&](const crs::CRSNNPtr &candidateSrcGeod, const crs::CRSNNPtr &candidateDstGeod, const CoordinateOperationNNPtr &opFirst, bool isNullFirst, bool useOnlyDirectRegistryOp) { bool resNonEmptyBeforeFiltering; // Deal with potential epoch change std::vector<CoordinateOperationNNPtr> opsEpochChangeSrc; std::vector<CoordinateOperationNNPtr> opsEpochChangeDst; if (sourceEpoch.has_value() && targetEpoch.has_value() && !sourceEpoch->coordinateEpoch()._isEquivalentTo( targetEpoch->coordinateEpoch())) { const auto pmoSrc = context.context->getAuthorityFactory() ->getPointMotionOperationsFor( NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( candidateSrcGeod)), true); if (!pmoSrc.empty()) { opsEpochChangeSrc = createOperations(candidateSrcGeod, sourceEpoch, candidateSrcGeod, targetEpoch, context); } else { const auto pmoDst = context.context->getAuthorityFactory() ->getPointMotionOperationsFor( NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( candidateDstGeod)), true); if (!pmoDst.empty()) { opsEpochChangeDst = createOperations( candidateDstGeod, sourceEpoch, candidateDstGeod, targetEpoch, context); } } } const std::vector<CoordinateOperationNNPtr> opsSecond( useOnlyDirectRegistryOp ? findOpsInRegistryDirect(candidateSrcGeod, candidateDstGeod, context, resNonEmptyBeforeFiltering) : createOperations(candidateSrcGeod, targetEpoch, candidateDstGeod, targetEpoch, context)); const auto opsThird = createOperations( sourceAndTargetAre3D ? candidateDstGeod->promoteTo3D(std::string(), dbContext) : candidateDstGeod, targetEpoch, targetCRS, targetEpoch, context); assert(!opsThird.empty()); const CoordinateOperationNNPtr &opThird(opsThird[0]); const auto nIters = std::max<size_t>( 1, std::max(opsEpochChangeSrc.size(), opsEpochChangeDst.size())); for (size_t iEpochChange = 0; iEpochChange < nIters; ++iEpochChange) { for (auto &opSecond : opsSecond) { // Check that it is not a transformation synthetized by // ourselves if (!hasIdentifiers(opSecond)) { continue; } // And even if it is a referenced transformation, check that // it is not a trivial one auto so = dynamic_cast<const SingleOperation *>(opSecond.get()); if (so && isAxisOrderReversal(so->method()->getEPSGCode())) { continue; } std::vector<CoordinateOperationNNPtr> subOps; const bool isNullThird = isNullTransformation(opThird->nameStr()); CoordinateOperationNNPtr opSecondCloned( (isNullFirst || isNullThird || sourceAndTargetAre3D) ? opSecond->shallowClone() : opSecond); if (isNullFirst || isNullThird) { if (opSecondCloned->identifiers().size() == 1 && (*opSecondCloned->identifiers()[0]->codeSpace()) .find("DERIVED_FROM") == std::string::npos) { { util::PropertyMap map; addModifiedIdentifier(map, opSecondCloned.get(), false, true); opSecondCloned->setProperties(map); } auto invCO = dynamic_cast<InverseCoordinateOperation *>( opSecondCloned.get()); if (invCO) { auto invCOForward = invCO->forwardOperation().get(); if (invCOForward->identifiers().size() == 1 && (*invCOForward->identifiers()[0]->codeSpace()) .find("DERIVED_FROM") == std::string::npos) { util::PropertyMap map; addModifiedIdentifier(map, invCOForward, false, true); invCOForward->setProperties(map); } } } } if (sourceAndTargetAre3D) { // Force Helmert operations to use the 3D domain, even if // the ones we found in EPSG are advertized for the 2D // domain. auto concat = dynamic_cast<ConcatenatedOperation *>( opSecondCloned.get()); if (concat) { std::vector<CoordinateOperationNNPtr> newSteps; for (const auto &step : concat->operations()) { auto newStep = step->shallowClone(); setCRSs(newStep.get(), newStep->sourceCRS()->promoteTo3D( std::string(), dbContext), newStep->targetCRS()->promoteTo3D( std::string(), dbContext)); newSteps.emplace_back(newStep); } opSecondCloned = ConcatenatedOperation::createComputeMetadata( newSteps, disallowEmptyIntersection); } else { setCRSs(opSecondCloned.get(), opSecondCloned->sourceCRS()->promoteTo3D( std::string(), dbContext), opSecondCloned->targetCRS()->promoteTo3D( std::string(), dbContext)); } } if (!isNullFirst) { subOps.emplace_back(opFirst); } if (!opsEpochChangeSrc.empty()) { subOps.emplace_back(opsEpochChangeSrc[iEpochChange]); } subOps.emplace_back(opSecondCloned); if (!opsEpochChangeDst.empty()) { subOps.emplace_back(opsEpochChangeDst[iEpochChange]); } if (!isNullThird) { subOps.emplace_back(opThird); } subOps[0] = subOps[0]->shallowClone(); if (subOps[0]->targetCRS()) setCRSs(subOps[0].get(), sourceCRS, NN_NO_CHECK(subOps[0]->targetCRS())); subOps.back() = subOps.back()->shallowClone(); if (subOps[0]->sourceCRS()) setCRSs(subOps.back().get(), NN_NO_CHECK(subOps.back()->sourceCRS()), targetCRS); #ifdef TRACE_CREATE_OPERATIONS std::string debugStr; for (const auto &op : subOps) { if (!debugStr.empty()) { debugStr += " + "; } debugStr += objectAsStr(op.get()); debugStr += " ("; debugStr += objectAsStr(op->sourceCRS().get()); debugStr += "->"; debugStr += objectAsStr(op->targetCRS().get()); debugStr += ")"; } logTrace("transformation " + debugStr); #endif try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( subOps, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } }; // The below logic is thus quite fragile, and attempts at changing it // result in degraded results for other use cases... // // Start in priority with candidates that have exactly the same name as // the sourceCRS and targetCRS (Typically for the case of init=IGNF:XXXX); // and then attempt candidate geodetic CRS with different names // // Transformation from IGNF:NTFP to IGNF:RGF93G, // using // NTF geographiques Paris (gr) vers NTF GEOGRAPHIQUES GREENWICH (DMS) + // NOUVELLE TRIANGULATION DE LA FRANCE (NTF) vers RGF93 (ETRS89) // that is using ntf_r93.gsb, is horribly dependent // of IGNF:RGF93G being returned before IGNF:RGF93GEO in candidatesDstGeod. // If RGF93GEO is returned before then we go through WGS84 and use // instead a Helmert transformation. // // Actually, in the general case, we do the lookup in 3 passes with the 2 // above steps in each pass: // - one first pass where we only consider direct transformations (no // other intermediate CRS) // - a second pass where we allow transformation through another // intermediate CRS, but we make sure the candidate geodetic CRS are of // the same type // - a third where we allow transformation through another // intermediate CRS, where the candidate geodetic CRS are of different // type. // ... but when transforming between 2 IGNF CRS, we do just one single pass // by allowing directly all transformation. There is no strong reason for // that particular case, except that otherwise we'd get different results // for thest test/cli/testIGNF script when transforming a point outside // the area of validity... Not totally sure the behaviour we try to preserve // here with the particular case is fundamentally better than the general // case. The general case is needed typically for the RGNC91-93 -> RGNC15 // transformation where we we need to actually use a transformation between // RGNC91-93 (lon-lat) -> RGNC15 (lon-lat), and not chain 2 no-op // transformations RGNC91-93 -> WGS 84 and RGNC15 -> WGS84. const auto isIGNF = [](const crs::CRSNNPtr &crs) { const auto &ids = crs->identifiers(); return !ids.empty() && *(ids.front()->codeSpace()) == "IGNF"; }; const int nIters = (isIGNF(sourceCRS) && isIGNF(targetCRS)) ? 1 : 3; const auto getType = [](const crs::GeodeticCRSNNPtr &crs) { if (auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(crs.get())) { if (geogCRS->coordinateSystem()->axisList().size() == 3) return 1; return 0; } return 2; }; for (int iter = 0; iter < nIters; ++iter) { const bool useOnlyDirectRegistryOp = (iter == 0 && nIters == 3); for (const auto &candidateSrcGeod : candidatesSrcGeod) { if (candidateSrcGeod->nameStr() == sourceCRS->nameStr()) { const auto typeSource = (iter >= 1) ? getType(candidateSrcGeod) : -1; auto sourceSrcGeodModified(sourceAndTargetAre3D ? candidateSrcGeod->promoteTo3D( std::string(), dbContext) : candidateSrcGeod); for (const auto &candidateDstGeod : candidatesDstGeod) { if (candidateDstGeod->nameStr() == targetCRS->nameStr()) { if (iter == 1) { if (typeSource != getType(candidateDstGeod)) { continue; } } else if (iter == 2) { if (typeSource == getType(candidateDstGeod)) { continue; } } #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("iter=" + toString(iter) + ", try " + objectAsStr(sourceCRS.get()) + "->" + objectAsStr(candidateSrcGeod.get()) + "->" + objectAsStr(candidateDstGeod.get()) + "->" + objectAsStr(targetCRS.get()) + ")"); #endif const auto opsFirst = createOperations( sourceCRS, sourceEpoch, sourceSrcGeodModified, sourceEpoch, context); assert(!opsFirst.empty()); const bool isNullFirst = isNullTransformation(opsFirst[0]->nameStr()); createTransformations( candidateSrcGeod, candidateDstGeod, opsFirst[0], isNullFirst, useOnlyDirectRegistryOp); if (!res.empty()) { if (hasResultSetOnlyResultsWithPROJStep(res)) { continue; } return; } } } } } for (const auto &candidateSrcGeod : candidatesSrcGeod) { const bool bSameSrcName = candidateSrcGeod->nameStr() == sourceCRS->nameStr(); #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK(""); #endif auto sourceSrcGeodModified( sourceAndTargetAre3D ? candidateSrcGeod->promoteTo3D(std::string(), dbContext) : candidateSrcGeod); const auto opsFirst = createOperations(sourceCRS, sourceEpoch, sourceSrcGeodModified, sourceEpoch, context); assert(!opsFirst.empty()); const bool isNullFirst = isNullTransformation(opsFirst[0]->nameStr()); for (const auto &candidateDstGeod : candidatesDstGeod) { if (bSameSrcName && candidateDstGeod->nameStr() == targetCRS->nameStr()) { continue; } #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("try " + objectAsStr(sourceCRS.get()) + "->" + objectAsStr(candidateSrcGeod.get()) + "->" + objectAsStr(candidateDstGeod.get()) + "->" + objectAsStr(targetCRS.get()) + ")"); #endif createTransformations(candidateSrcGeod, candidateDstGeod, opsFirst[0], isNullFirst, useOnlyDirectRegistryOp); if (!res.empty() && !hasResultSetOnlyResultsWithPROJStep(res)) { return; } } } } } // --------------------------------------------------------------------------- static CoordinateOperationNNPtr createBallparkGeocentricTranslation(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS) { std::string name(BALLPARK_GEOCENTRIC_TRANSLATION); name += " from "; name += sourceCRS->nameStr(); name += " to "; name += targetCRS->nameStr(); return util::nn_static_pointer_cast<CoordinateOperation>( Transformation::createGeocentricTranslations( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), sourceCRS, targetCRS, 0.0, 0.0, 0.0, {})); } // --------------------------------------------------------------------------- bool CoordinateOperationFactory::Private::hasPerfectAccuracyResult( const std::vector<CoordinateOperationNNPtr> &res, const Context &context) { auto resTmp = FilterResults(res, context.context, context.extent1, context.extent2, true) .getRes(); for (const auto &op : resTmp) { const double acc = getAccuracy(op); if (acc == 0.0) { return true; } } return false; } // --------------------------------------------------------------------------- std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private::createOperations( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context) { #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("createOperations(" + objectAsStr(sourceCRS.get()) + " --> " + objectAsStr(targetCRS.get()) + ")"); #endif #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION // 10 is arbitrary and hopefully large enough for all transformations PROJ // can handle. // At time of writing 7 is the maximum known to be required by a few tests // like // operation.compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert_WKT1_same_geoidgrids_context // We don't enable that check for fuzzing, to be able to detect // the root cause of recursions. if (context.nRecLevelCreateOperations == 10) { throw InvalidOperation("Too deep recursion in createOperations()"); } #endif struct RecLevelIncrementer { Private::Context &context_; explicit inline RecLevelIncrementer(Private::Context &contextIn) : context_(contextIn) { ++context_.nRecLevelCreateOperations; } inline ~RecLevelIncrementer() { --context_.nRecLevelCreateOperations; } }; RecLevelIncrementer recLevelIncrementer(context); std::vector<CoordinateOperationNNPtr> res; auto boundSrc = dynamic_cast<const crs::BoundCRS *>(sourceCRS.get()); auto boundDst = dynamic_cast<const crs::BoundCRS *>(targetCRS.get()); const auto &sourceProj4Ext = boundSrc ? boundSrc->baseCRS()->getExtensionProj4() : sourceCRS->getExtensionProj4(); const auto &targetProj4Ext = boundDst ? boundDst->baseCRS()->getExtensionProj4() : targetCRS->getExtensionProj4(); if (!sourceProj4Ext.empty() || !targetProj4Ext.empty()) { createOperationsFromProj4Ext(sourceCRS, targetCRS, boundSrc, boundDst, res); return res; } auto geodSrc = dynamic_cast<const crs::GeodeticCRS *>(sourceCRS.get()); auto geodDst = dynamic_cast<const crs::GeodeticCRS *>(targetCRS.get()); auto geogSrc = dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()); auto geogDst = dynamic_cast<const crs::GeographicCRS *>(targetCRS.get()); auto vertSrc = dynamic_cast<const crs::VerticalCRS *>(sourceCRS.get()); auto vertDst = dynamic_cast<const crs::VerticalCRS *>(targetCRS.get()); // First look-up if the registry provide us with operations. auto derivedSrc = dynamic_cast<const crs::DerivedCRS *>(sourceCRS.get()); auto derivedDst = dynamic_cast<const crs::DerivedCRS *>(targetCRS.get()); const auto &authFactory = context.context->getAuthorityFactory(); if (authFactory && (derivedSrc == nullptr || !derivedSrc->baseCRS()->_isEquivalentTo( targetCRS.get(), util::IComparable::Criterion::EQUIVALENT)) && (derivedDst == nullptr || !derivedDst->baseCRS()->_isEquivalentTo( sourceCRS.get(), util::IComparable::Criterion::EQUIVALENT))) { if (createOperationsFromDatabase( sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, geodSrc, geodDst, geogSrc, geogDst, vertSrc, vertDst, res)) { return res; } } if (geodSrc && geodSrc->isSphericalPlanetocentric()) { createOperationsFromSphericalPlanetocentric(sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, geodSrc, res); return res; } else if (geodDst && geodDst->isSphericalPlanetocentric()) { return applyInverse(createOperations(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } // Special case if both CRS are geodetic if (geodSrc && geodDst && !derivedSrc && !derivedDst) { createOperationsGeodToGeod(sourceCRS, targetCRS, context, geodSrc, geodDst, res, /*forceBallpark=*/false); return res; } if (boundSrc) { auto geodSrcBase = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( boundSrc->baseCRS()); if (geodSrcBase && geodSrcBase->isSphericalPlanetocentric()) { createOperationsFromBoundOfSphericalPlanetocentric( sourceCRS, targetCRS, context, boundSrc, NN_NO_CHECK(geodSrcBase), res); return res; } } else if (boundDst) { auto geodDstBase = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( boundDst->baseCRS()); if (geodDstBase && geodDstBase->isSphericalPlanetocentric()) { return applyInverse(createOperations( targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } } // If the source is a derived CRS, then chain the inverse of its // deriving conversion, with transforms from its baseCRS to the // targetCRS if (derivedSrc) { createOperationsDerivedTo(sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, derivedSrc, res); return res; } // reverse of previous case if (derivedDst) { return applyInverse(createOperations(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } // Order of comparison between the geogDst vs geodDst is important if (boundSrc && geogDst) { createOperationsBoundToGeog(sourceCRS, targetCRS, context, boundSrc, geogDst, res); return res; } else if (boundSrc && geodDst) { createOperationsToGeod(sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, geodDst, res); return res; } // reverse of previous case if (geodSrc && boundDst) { return applyInverse(createOperations(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } // vertCRS (as boundCRS with transformation to target vertCRS) to // vertCRS if (boundSrc && vertDst) { createOperationsBoundToVert(sourceCRS, targetCRS, context, boundSrc, vertDst, res); return res; } // reverse of previous case if (boundDst && vertSrc) { return applyInverse(createOperations(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } if (vertSrc && vertDst) { createOperationsVertToVert(sourceCRS, targetCRS, context, vertSrc, vertDst, res); return res; } // A bit odd case as we are comparing apples to oranges, but in case // the vertical unit differ, do something useful. if (vertSrc && geogDst) { createOperationsVertToGeog(sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, vertSrc, geogDst, res); return res; } // reverse of previous case if (vertDst && geogSrc) { return applyInverse(createOperations(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } // boundCRS to boundCRS if (boundSrc && boundDst) { createOperationsBoundToBound(sourceCRS, targetCRS, context, boundSrc, boundDst, res); return res; } auto compoundSrc = dynamic_cast<crs::CompoundCRS *>(sourceCRS.get()); // Order of comparison between the geogDst vs geodDst is important if (compoundSrc && geogDst) { createOperationsCompoundToGeog(sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, compoundSrc, geogDst, res); return res; } else if (compoundSrc && geodDst) { createOperationsToGeod(sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, geodDst, res); return res; } // reverse of previous cases auto compoundDst = dynamic_cast<const crs::CompoundCRS *>(targetCRS.get()); if (geodSrc && compoundDst) { return applyInverse(createOperations(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } if (compoundSrc && compoundDst) { createOperationsCompoundToCompound(sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, compoundSrc, compoundDst, res); return res; } // '+proj=longlat +ellps=GRS67 [email protected] +type=crs' to // '+proj=longlat +ellps=GRS80 [email protected] [email protected] // +type=crs' if (boundSrc && compoundDst) { createOperationsBoundToCompound(sourceCRS, targetCRS, context, boundSrc, compoundDst, res); return res; } // reverse of previous case if (boundDst && compoundSrc) { return applyInverse(createOperations(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context)); } return res; } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsFromProj4Ext( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const crs::BoundCRS *boundSrc, const crs::BoundCRS *boundDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); auto sourceProjExportable = dynamic_cast<const io::IPROJStringExportable *>( boundSrc ? boundSrc : sourceCRS.get()); auto targetProjExportable = dynamic_cast<const io::IPROJStringExportable *>( boundDst ? boundDst : targetCRS.get()); if (!sourceProjExportable) { throw InvalidOperation("Source CRS is not PROJ exportable"); } if (!targetProjExportable) { throw InvalidOperation("Target CRS is not PROJ exportable"); } auto projFormatter = io::PROJStringFormatter::create(); projFormatter->setCRSExport(true); projFormatter->setLegacyCRSToCRSContext(true); projFormatter->startInversion(); sourceProjExportable->_exportToPROJString(projFormatter.get()); auto geogSrc = dynamic_cast<const crs::GeographicCRS *>( boundSrc ? boundSrc->baseCRS().get() : sourceCRS.get()); if (geogSrc) { auto tmpFormatter = io::PROJStringFormatter::create(); geogSrc->addAngularUnitConvertAndAxisSwap(tmpFormatter.get()); projFormatter->ingestPROJString(tmpFormatter->toString()); } projFormatter->stopInversion(); targetProjExportable->_exportToPROJString(projFormatter.get()); auto geogDst = dynamic_cast<const crs::GeographicCRS *>( boundDst ? boundDst->baseCRS().get() : targetCRS.get()); if (geogDst) { auto tmpFormatter = io::PROJStringFormatter::create(); geogDst->addAngularUnitConvertAndAxisSwap(tmpFormatter.get()); projFormatter->ingestPROJString(tmpFormatter->toString()); } auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, buildTransfName(sourceCRS->nameStr(), targetCRS->nameStr())); res.emplace_back(SingleOperation::createPROJBased( properties, projFormatter->toString(), sourceCRS, targetCRS, {})); } // --------------------------------------------------------------------------- bool CoordinateOperationFactory::Private::createOperationsFromDatabase( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeodeticCRS *geodSrc, const crs::GeodeticCRS *geodDst, const crs::GeographicCRS *geogSrc, const crs::GeographicCRS *geogDst, const crs::VerticalCRS *vertSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); if (geogSrc && vertDst) { createOperationsFromDatabase(targetCRS, targetEpoch, sourceCRS, sourceEpoch, context, geodDst, geodSrc, geogDst, geogSrc, vertDst, vertSrc, res); res = applyInverse(res); } else if (geogDst && vertSrc) { res = applyInverse(createOperationsGeogToVertFromGeoid( targetCRS, sourceCRS, vertSrc, context)); if (!res.empty()) { createOperationsVertToGeogBallpark(sourceCRS, targetCRS, context, vertSrc, geogDst, res); } } if (!res.empty()) { return true; } // Use PointMotionOperations if appropriate and available if (geodSrc && geodDst && sourceEpoch.has_value() && targetEpoch.has_value() && !sourceEpoch->coordinateEpoch()._isEquivalentTo( targetEpoch->coordinateEpoch())) { const auto pmoSrc = context.context->getAuthorityFactory()->getPointMotionOperationsFor( NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::GeodeticCRS>(sourceCRS)), true); if (!pmoSrc.empty()) { const auto pmoDst = context.context->getAuthorityFactory() ->getPointMotionOperationsFor( NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( targetCRS)), true); if (pmoDst.size() == pmoSrc.size()) { bool ok = true; for (size_t i = 0; i < pmoSrc.size(); ++i) { if (pmoSrc[i]->_isEquivalentTo(pmoDst[i].get())) { auto pmo = pmoSrc[i]->cloneWithEpochs(*sourceEpoch, *targetEpoch); std::vector<operation::CoordinateOperationNNPtr> ops; if (!pmo->sourceCRS()->_isEquivalentTo( sourceCRS.get(), util::IComparable::Criterion::EQUIVALENT)) { auto tmp = createOperations(sourceCRS, sourceEpoch, pmo->sourceCRS(), sourceEpoch, context); assert(!tmp.empty()); ops.emplace_back(tmp.front()); } ops.emplace_back(pmo); // pmo->sourceCRS() == pmo->targetCRS() by definition if (!pmo->sourceCRS()->_isEquivalentTo( targetCRS.get(), util::IComparable::Criterion::EQUIVALENT)) { auto tmp = createOperations(pmo->sourceCRS(), targetEpoch, targetCRS, targetEpoch, context); assert(!tmp.empty()); ops.emplace_back(tmp.front()); } res.emplace_back( ConcatenatedOperation::createComputeMetadata( ops, disallowEmptyIntersection)); } else { ok = false; break; } } if (ok) { std::vector<CoordinateOperationNNPtr> resTmp; createOperationsGeodToGeod(sourceCRS, targetCRS, context, geodSrc, geodDst, resTmp, /*forceBallpark=*/true); res.insert(res.end(), resTmp.begin(), resTmp.end()); return true; } } } } bool resFindDirectNonEmptyBeforeFiltering = false; res = findOpsInRegistryDirect(sourceCRS, targetCRS, context, resFindDirectNonEmptyBeforeFiltering); // If we get at least a result with perfect accuracy, do not // bother generating synthetic transforms. if (hasPerfectAccuracyResult(res, context)) { return true; } bool doFilterAndCheckPerfectOp = false; bool sameGeodeticDatum = false; if (vertSrc || vertDst) { if (res.empty()) { if (geogSrc && geogSrc->coordinateSystem()->axisList().size() == 2 && vertDst) { auto dbContext = context.context->getAuthorityFactory()->databaseContext(); auto resTmp = findOpsInRegistryDirect( sourceCRS->promoteTo3D(std::string(), dbContext), targetCRS, context, resFindDirectNonEmptyBeforeFiltering); for (auto &op : resTmp) { auto newOp = op->shallowClone(); setCRSs(newOp.get(), sourceCRS, targetCRS); res.emplace_back(newOp); } } else if (geogDst && geogDst->coordinateSystem()->axisList().size() == 2 && vertSrc) { auto dbContext = context.context->getAuthorityFactory()->databaseContext(); auto resTmp = findOpsInRegistryDirect( sourceCRS, targetCRS->promoteTo3D(std::string(), dbContext), context, resFindDirectNonEmptyBeforeFiltering); for (auto &op : resTmp) { auto newOp = op->shallowClone(); setCRSs(newOp.get(), sourceCRS, targetCRS); res.emplace_back(newOp); } } } if (res.empty()) { createOperationsFromDatabaseWithVertCRS( sourceCRS, sourceEpoch, targetCRS, targetEpoch, context, geogSrc, geogDst, vertSrc, vertDst, res); } } else if (geodSrc && geodDst) { const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory->databaseContext().as_nullable(); const auto srcDatum = geodSrc->datumNonNull(dbContext); const auto dstDatum = geodDst->datumNonNull(dbContext); sameGeodeticDatum = isSameGeodeticDatum(srcDatum, dstDatum, dbContext); if (res.empty() && !sameGeodeticDatum && !context.inCreateOperationsWithDatumPivotAntiRecursion) { // If we still didn't find a transformation, and that the source // and target are GeodeticCRS, then go through their underlying // datum to find potential transformations between other // GeodeticCRSs // that are made of those datum // The typical example is if transforming between two // GeographicCRS, // but transformations are only available between their // corresponding geocentric CRS. createOperationsWithDatumPivot(res, sourceCRS, sourceEpoch, targetCRS, targetEpoch, geodSrc, geodDst, context); doFilterAndCheckPerfectOp = !res.empty(); } } bool foundInstantiableOp = false; // FIXME: the limitation to .size() == 1 is just for the // -s EPSG:4959+5759 -t "EPSG:4959+7839" case // finding EPSG:7860 'NZVD2016 height to Auckland 1946 // height (1)', which uses the EPSG:1071 'Vertical Offset by Grid // Interpolation (NZLVD)' method which is not currently implemented by PROJ // (cannot deal with .csv files) // Initially the test was written to iterate over for all operations of a // non-empty res, but this causes failures in the test suite when no grids // are installed at all. Ideally we should tweak the test suite to be // robust to that, or skip some tests. if (res.size() == 1) { try { res.front()->exportToPROJString( io::PROJStringFormatter::create().get()); foundInstantiableOp = true; } catch (const std::exception &) { } if (!foundInstantiableOp) { resFindDirectNonEmptyBeforeFiltering = false; } } else if (res.size() > 1) { foundInstantiableOp = true; } // NAD27 to NAD83 has tens of results already. No need to look // for a pivot if (!sameGeodeticDatum && (((res.empty() || !foundInstantiableOp) && !resFindDirectNonEmptyBeforeFiltering && context.context->getAllowUseIntermediateCRS() == CoordinateOperationContext::IntermediateCRSUse:: IF_NO_DIRECT_TRANSFORMATION) || context.context->getAllowUseIntermediateCRS() == CoordinateOperationContext::IntermediateCRSUse::ALWAYS || getenv("PROJ_FORCE_SEARCH_PIVOT"))) { auto resWithIntermediate = findsOpsInRegistryWithIntermediate( sourceCRS, targetCRS, context, false); res.insert(res.end(), resWithIntermediate.begin(), resWithIntermediate.end()); doFilterAndCheckPerfectOp = !res.empty(); } if (res.empty() && !context.inCreateOperationsWithDatumPivotAntiRecursion && !resFindDirectNonEmptyBeforeFiltering && geodSrc && geodDst && !sameGeodeticDatum && context.context->getIntermediateCRS().empty() && context.context->getAllowUseIntermediateCRS() != CoordinateOperationContext::IntermediateCRSUse::NEVER) { // Currently triggered by "IG05/12 Intermediate CRS" to ITRF2014 auto resWithIntermediate = findsOpsInRegistryWithIntermediate( sourceCRS, targetCRS, context, true); res.insert(res.end(), resWithIntermediate.begin(), resWithIntermediate.end()); doFilterAndCheckPerfectOp = !res.empty(); } if (doFilterAndCheckPerfectOp) { // If we get at least a result with perfect accuracy, do not bother // generating synthetic transforms. if (hasPerfectAccuracyResult(res, context)) { return true; } } return false; } // --------------------------------------------------------------------------- static std::vector<crs::CRSNNPtr> findCandidateVertCRSForDatum(const io::AuthorityFactoryPtr &authFactory, const datum::VerticalReferenceFrame *datum) { std::vector<crs::CRSNNPtr> candidates; assert(datum); const auto &ids = datum->identifiers(); const auto &datumName = datum->nameStr(); if (!ids.empty()) { for (const auto &id : ids) { const auto &authName = *(id->codeSpace()); const auto &code = id->code(); if (!authName.empty()) { auto l_candidates = authFactory->createVerticalCRSFromDatum(authName, code); for (const auto &candidate : l_candidates) { candidates.emplace_back(candidate); } } } } else if (datumName != "unknown" && datumName != "unnamed") { auto matches = authFactory->createObjectsFromName( datumName, {io::AuthorityFactory::ObjectType::VERTICAL_REFERENCE_FRAME}, false, 2); if (matches.size() == 1) { const auto &match = matches.front(); if (datum->_isEquivalentTo( match.get(), util::IComparable::Criterion::EQUIVALENT, authFactory->databaseContext().as_nullable()) && !match->identifiers().empty()) { return findCandidateVertCRSForDatum( authFactory, dynamic_cast<const datum::VerticalReferenceFrame *>( match.get())); } } } return candidates; } // --------------------------------------------------------------------------- std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private::createOperationsGeogToVertFromGeoid( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const crs::VerticalCRS *vertDst, Private::Context &context) { ENTER_FUNCTION(); const auto useTransf = [&sourceCRS, &targetCRS, &context, vertDst](const CoordinateOperationNNPtr &op) { // If the source geographic CRS has a non-metre vertical unit, we need // to create an intermediate and operation to do the vertical unit // conversion from that vertical unit to the one of the geographic CRS // of the source of the operation const auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()); assert(geogCRS); const auto &srcAxisList = geogCRS->coordinateSystem()->axisList(); CoordinateOperationPtr opPtr; const auto opSourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(op->sourceCRS().get()); // I assume opSourceCRSGeog should always be null in practice... if (opSourceCRSGeog && srcAxisList.size() == 3 && srcAxisList[2]->unit().conversionToSI() != 1) { const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; auto tmpCRSWithSrcZ = opSourceCRSGeog->demoteTo2D(std::string(), dbContext) ->promoteTo3D(std::string(), dbContext, srcAxisList[2]); std::vector<CoordinateOperationNNPtr> opsUnitConvert; createOperationsGeogToGeog( opsUnitConvert, tmpCRSWithSrcZ, NN_NO_CHECK(op->sourceCRS()), context, dynamic_cast<const crs::GeographicCRS *>(tmpCRSWithSrcZ.get()), opSourceCRSGeog, /*forceBallpark=*/false); assert(opsUnitConvert.size() == 1); opPtr = opsUnitConvert.front().as_nullable(); } std::vector<CoordinateOperationNNPtr> ops; if (opPtr) ops.emplace_back(NN_NO_CHECK(opPtr)); ops.emplace_back(op); const auto targetOp = dynamic_cast<const crs::VerticalCRS *>(op->targetCRS().get()); assert(targetOp); if (targetOp->_isEquivalentTo( vertDst, util::IComparable::Criterion::EQUIVALENT)) { auto ret = ConcatenatedOperation::createComputeMetadata( ops, disallowEmptyIntersection); return ret; } std::vector<CoordinateOperationNNPtr> tmp; createOperationsVertToVert(NN_NO_CHECK(op->targetCRS()), targetCRS, context, targetOp, vertDst, tmp); assert(!tmp.empty()); ops.emplace_back(tmp.front()); auto ret = ConcatenatedOperation::createComputeMetadata( ops, disallowEmptyIntersection); return ret; }; const auto getProjGeoidTransformation = [&sourceCRS, &targetCRS, &vertDst, &context](const CoordinateOperationNNPtr &model, const std::string &projFilename) { const auto getNameVertCRSMetre = [](const std::string &name) { if (name.empty()) return std::string("unnamed"); auto ret(name); bool haveOriginalUnit = false; if (name.back() == ')') { const auto pos = ret.rfind(" ("); if (pos != std::string::npos) { haveOriginalUnit = true; ret = ret.substr(0, pos); } } const auto pos = ret.rfind(" depth"); if (pos != std::string::npos) { ret = ret.substr(0, pos) + " height"; } if (!haveOriginalUnit) { ret += " (metre)"; } return ret; }; const auto &axis = vertDst->coordinateSystem()->axisList()[0]; const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; const auto geogSrcCRS = dynamic_cast<crs::GeographicCRS *>( model->interpolationCRS().get()) ? NN_NO_CHECK(model->interpolationCRS()) : sourceCRS->demoteTo2D(std::string(), dbContext) ->promoteTo3D(std::string(), dbContext); const auto vertCRSMetre = axis->unit() == common::UnitOfMeasure::METRE && axis->direction() == cs::AxisDirection::UP ? targetCRS : util::nn_static_pointer_cast<crs::CRS>( crs::VerticalCRS::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, getNameVertCRSMetre(targetCRS->nameStr())), vertDst->datum(), vertDst->datumEnsemble(), cs::VerticalCS::createGravityRelatedHeight( common::UnitOfMeasure::METRE))); auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, buildOpName("Transformation", vertCRSMetre, geogSrcCRS)); // Try to find a representative value for the accuracy of this grid // from the registered transformations. std::vector<metadata::PositionalAccuracyNNPtr> accuracies; const auto &modelAccuracies = model->coordinateOperationAccuracies(); std::vector<CoordinateOperationNNPtr> transformationsForGrid; double accuracy = -1; size_t idx = static_cast<size_t>(-1); if (modelAccuracies.empty()) { if (authFactory) { transformationsForGrid = io::DatabaseContext::getTransformationsForGridName( authFactory->databaseContext(), projFilename); for (size_t i = 0; i < transformationsForGrid.size(); ++i) { const auto &transf = transformationsForGrid[i]; const double transfAcc = getAccuracy(transf); if (transfAcc - accuracy > 1e-10) { accuracy = transfAcc; idx = i; } } if (accuracy >= 0) { accuracies.emplace_back( metadata::PositionalAccuracy::create( toString(accuracy))); } } } // Set extent bool dummy = false; // Use in priority the one of the geoid model transformation auto extent = getExtent(model, true, dummy); // Otherwise fallback to the extent of a transformation using // the grid. if (extent == nullptr && authFactory != nullptr) { if (transformationsForGrid.empty()) { transformationsForGrid = io::DatabaseContext::getTransformationsForGridName( authFactory->databaseContext(), projFilename); } if (idx != static_cast<size_t>(-1)) { const auto &transf = transformationsForGrid[idx]; extent = getExtent(transf, true, dummy); } else if (!transformationsForGrid.empty()) { const auto &transf = transformationsForGrid.front(); extent = getExtent(transf, true, dummy); } } if (extent) { properties.set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, NN_NO_CHECK(extent)); } return Transformation::createGravityRelatedHeightToGeographic3D( properties, vertCRSMetre, geogSrcCRS, nullptr, projFilename, !modelAccuracies.empty() ? modelAccuracies : accuracies); }; std::vector<CoordinateOperationNNPtr> res; const auto &authFactory = context.context->getAuthorityFactory(); if (authFactory) { const auto &models = vertDst->geoidModel(); for (const auto &model : models) { const auto &modelName = model->nameStr(); const auto &modelIds = model->identifiers(); const std::vector<CoordinateOperationNNPtr> transformations( !modelIds.empty() ? std::vector< CoordinateOperationNNPtr>{io::AuthorityFactory::create( authFactory ->databaseContext(), *(modelIds[0] ->codeSpace())) ->createCoordinateOperation( modelIds[0]->code(), true)} : starts_with(modelName, "PROJ ") ? std::vector< CoordinateOperationNNPtr>{getProjGeoidTransformation( model, modelName.substr(strlen("PROJ ")))} : authFactory->getTransformationsForGeoid( modelName, context.context->getUsePROJAlternativeGridNames())); for (const auto &transf : transformations) { if (dynamic_cast<crs::GeographicCRS *>( transf->sourceCRS().get()) && dynamic_cast<crs::VerticalCRS *>( transf->targetCRS().get())) { res.push_back(useTransf(transf)); } else if (dynamic_cast<crs::GeographicCRS *>( transf->targetCRS().get()) && dynamic_cast<crs::VerticalCRS *>( transf->sourceCRS().get())) { res.push_back(useTransf(transf->inverse())); } } } } return res; } // --------------------------------------------------------------------------- std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private:: createOperationsGeogToVertWithIntermediateVert( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, const crs::VerticalCRS *vertDst, Private::Context &context) { ENTER_FUNCTION(); std::vector<CoordinateOperationNNPtr> res; struct AntiRecursionGuard { Context &context; explicit AntiRecursionGuard(Context &contextIn) : context(contextIn) { assert(!context.inCreateOperationsGeogToVertWithIntermediateVert); context.inCreateOperationsGeogToVertWithIntermediateVert = true; } ~AntiRecursionGuard() { context.inCreateOperationsGeogToVertWithIntermediateVert = false; } }; AntiRecursionGuard guard(context); const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory->databaseContext().as_nullable(); auto candidatesVert = findCandidateVertCRSForDatum( authFactory, vertDst->datumNonNull(dbContext).get()); for (const auto &candidateVert : candidatesVert) { auto resTmp = createOperations(sourceCRS, sourceEpoch, candidateVert, sourceEpoch, context); if (!resTmp.empty()) { const auto opsSecond = createOperations( candidateVert, sourceEpoch, targetCRS, targetEpoch, context); if (!opsSecond.empty()) { // The transformation from candidateVert to targetCRS should // be just a unit change typically, so take only the first one, // which is likely/hopefully the only one. for (const auto &opFirst : resTmp) { if (hasIdentifiers(opFirst)) { if (candidateVert->_isEquivalentTo( targetCRS.get(), util::IComparable::Criterion::EQUIVALENT)) { res.emplace_back(opFirst); } else { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opFirst, opsSecond.front()}, disallowEmptyIntersection)); } } } if (!res.empty()) break; } } } return res; } // --------------------------------------------------------------------------- std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::Private:: createOperationsGeogToVertWithAlternativeGeog( const crs::CRSNNPtr &sourceCRS, // geographic CRS const crs::CRSNNPtr &targetCRS, // vertical CRS Private::Context &context) { ENTER_FUNCTION(); std::vector<CoordinateOperationNNPtr> res; struct AntiRecursionGuard { Context &context; explicit AntiRecursionGuard(Context &contextIn) : context(contextIn) { assert(!context.inCreateOperationsGeogToVertWithAlternativeGeog); context.inCreateOperationsGeogToVertWithAlternativeGeog = true; } ~AntiRecursionGuard() { context.inCreateOperationsGeogToVertWithAlternativeGeog = false; } }; AntiRecursionGuard guard(context); // Generally EPSG has operations from GeogCrs to VertCRS auto ops = findOpsInRegistryDirectTo(targetCRS, context); const auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()); assert(geogCRS); const auto &srcAxisList = geogCRS->coordinateSystem()->axisList(); for (const auto &op : ops) { const auto tmpCRS = dynamic_cast<const crs::GeographicCRS *>(op->sourceCRS().get()); if (tmpCRS) { if (srcAxisList.size() == 3 && srcAxisList[2]->unit().conversionToSI() != 1) { const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory->databaseContext().as_nullable(); auto tmpCRSWithSrcZ = tmpCRS->demoteTo2D(std::string(), dbContext) ->promoteTo3D(std::string(), dbContext, srcAxisList[2]); std::vector<CoordinateOperationNNPtr> opsUnitConvert; createOperationsGeogToGeog( opsUnitConvert, tmpCRSWithSrcZ, NN_NO_CHECK(op->sourceCRS()), context, dynamic_cast<const crs::GeographicCRS *>( tmpCRSWithSrcZ.get()), tmpCRS, /*forceBallpark=*/false); assert(opsUnitConvert.size() == 1); auto concat = ConcatenatedOperation::createComputeMetadata( {opsUnitConvert.front(), op}, disallowEmptyIntersection); res.emplace_back(concat); } else { res.emplace_back(op); } } } return res; } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private:: createOperationsFromDatabaseWithVertCRS( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeographicCRS *geogSrc, const crs::GeographicCRS *geogDst, const crs::VerticalCRS *vertSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res) { // Typically to transform from "NAVD88 height (ftUS)" to a geog CRS // by using transformations of "NAVD88 height" (metre) to that geog CRS if (res.empty() && !context.inCreateOperationsGeogToVertWithIntermediateVert && geogSrc && vertDst) { res = createOperationsGeogToVertWithIntermediateVert( sourceCRS, sourceEpoch, targetCRS, targetEpoch, vertDst, context); } else if (res.empty() && !context.inCreateOperationsGeogToVertWithIntermediateVert && geogDst && vertSrc) { res = applyInverse(createOperationsGeogToVertWithIntermediateVert( targetCRS, targetEpoch, sourceCRS, sourceEpoch, vertSrc, context)); } // NAD83 only exists in 2D version in EPSG, so if it has been // promoted to 3D, when researching a vertical to geog // transformation, try to down cast to 2D. const auto geog3DToVertTryThroughGeog2D = [&res, &context](const crs::GeographicCRS *geogSrcIn, const crs::VerticalCRS *vertDstIn, const crs::CRSNNPtr &targetCRSIn) { const auto &authFactory = context.context->getAuthorityFactory(); if (res.empty() && geogSrcIn && vertDstIn && authFactory && geogSrcIn->coordinateSystem()->axisList().size() == 3) { const auto &dbContext = authFactory->databaseContext(); const auto candidatesSrcGeod(findCandidateGeodCRSForDatum( authFactory, geogSrcIn, geogSrcIn->datumNonNull(dbContext))); for (const auto &candidate : candidatesSrcGeod) { auto geogCandidate = util::nn_dynamic_pointer_cast<crs::GeographicCRS>( candidate); if (geogCandidate && geogCandidate->coordinateSystem()->axisList().size() == 2) { bool ignored; res = findOpsInRegistryDirect( NN_NO_CHECK(geogCandidate), targetCRSIn, context, ignored); break; } } return true; } return false; }; if (geog3DToVertTryThroughGeog2D(geogSrc, vertDst, targetCRS)) { // do nothing } else if (geog3DToVertTryThroughGeog2D(geogDst, vertSrc, sourceCRS)) { res = applyInverse(res); } // There's no direct transformation from NAVD88 height to WGS84, // so try to research all transformations from NAVD88 to another // intermediate GeographicCRS. if (res.empty() && !context.inCreateOperationsGeogToVertWithAlternativeGeog && geogSrc && vertDst) { res = createOperationsGeogToVertWithAlternativeGeog(sourceCRS, targetCRS, context); } else if (res.empty() && !context.inCreateOperationsGeogToVertWithAlternativeGeog && geogDst && vertSrc) { res = applyInverse(createOperationsGeogToVertWithAlternativeGeog( targetCRS, sourceCRS, context)); } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsGeodToGeod( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::GeodeticCRS *geodSrc, const crs::GeodeticCRS *geodDst, std::vector<CoordinateOperationNNPtr> &res, bool forceBallpark) { ENTER_FUNCTION(); if (geodSrc->ellipsoid()->celestialBody() != geodDst->ellipsoid()->celestialBody()) { const char *envVarVal = getenv("PROJ_IGNORE_CELESTIAL_BODY"); if (envVarVal == nullptr) { std::string osMsg( "Source and target ellipsoid do not belong to the same " "celestial body ("); osMsg += geodSrc->ellipsoid()->celestialBody(); osMsg += " vs "; osMsg += geodDst->ellipsoid()->celestialBody(); osMsg += "). You may override this check by setting the " "PROJ_IGNORE_CELESTIAL_BODY environment variable to YES."; throw util::UnsupportedOperationException(osMsg.c_str()); } else if (ci_equal(envVarVal, "NO") || ci_equal(envVarVal, "FALSE") || ci_equal(envVarVal, "OFF")) { std::string osMsg( "Source and target ellipsoid do not belong to the same " "celestial body ("); osMsg += geodSrc->ellipsoid()->celestialBody(); osMsg += " vs "; osMsg += geodDst->ellipsoid()->celestialBody(); osMsg += ")."; throw util::UnsupportedOperationException(osMsg.c_str()); } } auto geogSrc = dynamic_cast<const crs::GeographicCRS *>(geodSrc); auto geogDst = dynamic_cast<const crs::GeographicCRS *>(geodDst); if (geogSrc && geogDst) { createOperationsGeogToGeog(res, sourceCRS, targetCRS, context, geogSrc, geogDst, forceBallpark); return; } const bool isSrcGeocentric = geodSrc->isGeocentric(); const bool isSrcGeographic = geogSrc != nullptr; const bool isTargetGeocentric = geodDst->isGeocentric(); const bool isTargetGeographic = geogDst != nullptr; const auto IsSameDatum = [&context, &geodSrc, &geodDst]() { const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; return geodSrc->datumNonNull(dbContext)->_isEquivalentTo( geodDst->datumNonNull(dbContext).get(), util::IComparable::Criterion::EQUIVALENT); }; if (((isSrcGeocentric && isTargetGeographic) || (isSrcGeographic && isTargetGeocentric))) { // Same datum ? if (IsSameDatum()) { if (forceBallpark) { auto op = createGeodToGeodPROJBased(sourceCRS, targetCRS); op->setHasBallparkTransformation(true); res.emplace_back(op); } else { res.emplace_back(Conversion::createGeographicGeocentric( sourceCRS, targetCRS)); } } else if (isSrcGeocentric && geogDst) { #if 0 // The below logic was used between PROJ >= 6.0 and < 9.2 // It assumed that the geocentric origin of the 2 datums // matched. std::string interm_crs_name(geogDst->nameStr()); interm_crs_name += " (geocentric)"; auto interm_crs = util::nn_static_pointer_cast<crs::CRS>(crs::GeodeticCRS::create( addDomains(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, interm_crs_name), geogDst), geogDst->datum(), geogDst->datumEnsemble(), NN_CHECK_ASSERT( util::nn_dynamic_pointer_cast<cs::CartesianCS>( geodSrc->coordinateSystem())))); auto opFirst = createBallparkGeocentricTranslation(sourceCRS, interm_crs); auto opSecond = Conversion::createGeographicGeocentric(interm_crs, targetCRS); #else // The below logic is used since PROJ >= 9.2. It emulates the // behavior of PROJ < 6 by converting from the source geocentric CRS // to its corresponding geographic CRS, and then doing a null // geographic offset between that CRS and the target geographic CRS std::string interm_crs_name(geodSrc->nameStr()); interm_crs_name += " (geographic)"; auto interm_crs = util::nn_static_pointer_cast<crs::CRS>( crs::GeographicCRS::create( addDomains(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, interm_crs_name), geodSrc), geodSrc->datum(), geodSrc->datumEnsemble(), cs::EllipsoidalCS::createLongitudeLatitudeEllipsoidalHeight( common::UnitOfMeasure::DEGREE, common::UnitOfMeasure::METRE))); auto opFirst = Conversion::createGeographicGeocentric(sourceCRS, interm_crs); auto opsSecond = createOperations( interm_crs, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); for (const auto &opSecond : opsSecond) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opFirst, opSecond}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } #endif } else { // Apply previous case in reverse way std::vector<CoordinateOperationNNPtr> resTmp; createOperationsGeodToGeod(targetCRS, sourceCRS, context, geodDst, geodSrc, resTmp, forceBallpark); resTmp = applyInverse(resTmp); res.insert(res.end(), resTmp.begin(), resTmp.end()); } return; } if (isSrcGeocentric && isTargetGeocentric) { if (!forceBallpark && (sourceCRS->_isEquivalentTo( targetCRS.get(), util::IComparable::Criterion::EQUIVALENT) || IsSameDatum())) { std::string name(NULL_GEOCENTRIC_TRANSLATION); name += " from "; name += sourceCRS->nameStr(); name += " to "; name += targetCRS->nameStr(); res.emplace_back(Transformation::createGeocentricTranslations( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), sourceCRS, targetCRS, 0.0, 0.0, 0.0, {metadata::PositionalAccuracy::create("0")})); } else { res.emplace_back( createBallparkGeocentricTranslation(sourceCRS, targetCRS)); } return; } // Transformation between two geodetic systems of unknown type // This should normally not be triggered with "standard" CRS res.emplace_back(createGeodToGeodPROJBased(sourceCRS, targetCRS)); } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private:: createOperationsFromSphericalPlanetocentric( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeodeticCRS *geodSrc, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); const auto IsSameDatum = [&context, &geodSrc](const crs::GeodeticCRS *geodDst) { const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; return geodSrc->datumNonNull(dbContext)->_isEquivalentTo( geodDst->datumNonNull(dbContext).get(), util::IComparable::Criterion::EQUIVALENT); }; auto geogDst = dynamic_cast<const crs::GeographicCRS *>(targetCRS.get()); if (geogDst && IsSameDatum(geogDst)) { res.emplace_back(Conversion::createGeographicGeocentricLatitude( sourceCRS, targetCRS)); return; } // Create an intermediate geographic CRS with the same datum as the // source spherical planetocentric one std::string interm_crs_name(geodSrc->nameStr()); interm_crs_name += " (geographic)"; auto interm_crs = util::nn_static_pointer_cast<crs::CRS>(crs::GeographicCRS::create( addDomains(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, interm_crs_name), geodSrc), geodSrc->datum(), geodSrc->datumEnsemble(), cs::EllipsoidalCS::createLatitudeLongitude( common::UnitOfMeasure::DEGREE))); auto opFirst = Conversion::createGeographicGeocentricLatitude(sourceCRS, interm_crs); auto opsSecond = createOperations(interm_crs, sourceEpoch, targetCRS, targetEpoch, context); for (const auto &opSecond : opsSecond) { try { res.emplace_back(ConcatenatedOperation::createComputeMetadata( {opFirst, opSecond}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private:: createOperationsFromBoundOfSphericalPlanetocentric( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::GeodeticCRSNNPtr &geodSrcBase, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); // Create an intermediate geographic CRS with the same datum as the // source spherical planetocentric one std::string interm_crs_name(geodSrcBase->nameStr()); interm_crs_name += " (geographic)"; auto intermGeog = util::nn_static_pointer_cast<crs::CRS>(crs::GeographicCRS::create( addDomains(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, interm_crs_name), geodSrcBase.get()), geodSrcBase->datum(), geodSrcBase->datumEnsemble(), cs::EllipsoidalCS::createLatitudeLongitude( common::UnitOfMeasure::DEGREE))); // Create an intermediate boundCRS wrapping the above intermediate // geographic CRS auto transf = boundSrc->transformation()->shallowClone(); // keep a reference to the target before patching it with itself // (this is due to our abuse of passing shared_ptr by reference auto transfTarget = transf->targetCRS(); setCRSs(transf.get(), intermGeog, transfTarget); auto intermBoundCRS = crs::BoundCRS::create(intermGeog, boundSrc->hubCRS(), transf); auto opFirst = Conversion::createGeographicGeocentricLatitude(geodSrcBase, intermGeog); setCRSs(opFirst.get(), sourceCRS, intermBoundCRS); auto opsSecond = createOperations( intermBoundCRS, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); for (const auto &opSecond : opsSecond) { try { auto opSecondClone = opSecond->shallowClone(); // In theory, we should not need that setCRSs() forcing, but due // how BoundCRS transformations are implemented currently, we // need it in practice. setCRSs(opSecondClone.get(), intermBoundCRS, targetCRS); res.emplace_back(ConcatenatedOperation::createComputeMetadata( {opFirst, std::move(opSecondClone)}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsDerivedTo( const crs::CRSNNPtr & /*sourceCRS*/, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::DerivedCRS *derivedSrc, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); auto opFirst = derivedSrc->derivingConversion()->inverse(); // Small optimization if the targetCRS is the baseCRS of the source // derivedCRS. if (derivedSrc->baseCRS()->_isEquivalentTo( targetCRS.get(), util::IComparable::Criterion::EQUIVALENT)) { res.emplace_back(opFirst); return; } auto opsSecond = createOperations(derivedSrc->baseCRS(), sourceEpoch, targetCRS, targetEpoch, context); for (const auto &opSecond : opsSecond) { try { res.emplace_back(ConcatenatedOperation::createComputeMetadata( {opFirst, opSecond}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsBoundToGeog( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); const auto &hubSrc = boundSrc->hubCRS(); auto hubSrcGeog = dynamic_cast<const crs::GeographicCRS *>(hubSrc.get()); auto geogCRSOfBaseOfBoundSrc = boundSrc->baseCRS()->extractGeographicCRS(); { // If geogCRSOfBaseOfBoundSrc is a DerivedGeographicCRS, use its base // instead (if it is a GeographicCRS) auto derivedGeogCRS = std::dynamic_pointer_cast<crs::DerivedGeographicCRS>( geogCRSOfBaseOfBoundSrc); if (derivedGeogCRS) { auto baseCRS = std::dynamic_pointer_cast<crs::GeographicCRS>( derivedGeogCRS->baseCRS().as_nullable()); if (baseCRS) { geogCRSOfBaseOfBoundSrc = std::move(baseCRS); } } } const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; const auto geogDstDatum = geogDst->datumNonNull(dbContext); // If the underlying datum of the source is the same as the target, do // not consider the boundCRS at all, but just its base if (geogCRSOfBaseOfBoundSrc) { auto geogCRSOfBaseOfBoundSrcDatum = geogCRSOfBaseOfBoundSrc->datumNonNull(dbContext); if (geogCRSOfBaseOfBoundSrcDatum->_isEquivalentTo( geogDstDatum.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { res = createOperations( boundSrc->baseCRS(), util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); return; } } bool triedBoundCrsToGeogCRSSameAsHubCRS = false; // Is it: boundCRS to a geogCRS that is the same as the hubCRS ? if (hubSrcGeog && geogCRSOfBaseOfBoundSrc && (hubSrcGeog->_isEquivalentTo( geogDst, util::IComparable::Criterion::EQUIVALENT) || hubSrcGeog->is2DPartOf3D(NN_NO_CHECK(geogDst), dbContext))) { triedBoundCrsToGeogCRSSameAsHubCRS = true; CoordinateOperationPtr opIntermediate; if (!geogCRSOfBaseOfBoundSrc->_isEquivalentTo( boundSrc->transformation()->sourceCRS().get(), util::IComparable::Criterion::EQUIVALENT)) { auto opsIntermediate = createOperations(NN_NO_CHECK(geogCRSOfBaseOfBoundSrc), util::optional<common::DataEpoch>(), boundSrc->transformation()->sourceCRS(), util::optional<common::DataEpoch>(), context); assert(!opsIntermediate.empty()); opIntermediate = opsIntermediate.front(); } if (boundSrc->baseCRS() == geogCRSOfBaseOfBoundSrc) { if (opIntermediate) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {NN_NO_CHECK(opIntermediate), boundSrc->transformation()}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } else { // Optimization to avoid creating a useless concatenated // operation res.emplace_back(boundSrc->transformation()); } return; } auto opsFirst = createOperations( boundSrc->baseCRS(), util::optional<common::DataEpoch>(), NN_NO_CHECK(geogCRSOfBaseOfBoundSrc), util::optional<common::DataEpoch>(), context); if (!opsFirst.empty()) { for (const auto &opFirst : opsFirst) { try { std::vector<CoordinateOperationNNPtr> subops; subops.emplace_back(opFirst); if (opIntermediate) { subops.emplace_back(NN_NO_CHECK(opIntermediate)); } subops.emplace_back(boundSrc->transformation()); res.emplace_back( ConcatenatedOperation::createComputeMetadata( subops, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } if (!res.empty()) { return; } } // If the datum are equivalent, this is also fine } else if (geogCRSOfBaseOfBoundSrc && hubSrcGeog && hubSrcGeog->datumNonNull(dbContext)->_isEquivalentTo( geogDstDatum.get(), util::IComparable::Criterion::EQUIVALENT)) { auto opsFirst = createOperations( boundSrc->baseCRS(), util::optional<common::DataEpoch>(), NN_NO_CHECK(geogCRSOfBaseOfBoundSrc), util::optional<common::DataEpoch>(), context); auto opsLast = createOperations( hubSrc, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); if (!opsFirst.empty() && !opsLast.empty()) { CoordinateOperationPtr opIntermediate; if (!geogCRSOfBaseOfBoundSrc->_isEquivalentTo( boundSrc->transformation()->sourceCRS().get(), util::IComparable::Criterion::EQUIVALENT)) { auto opsIntermediate = createOperations( NN_NO_CHECK(geogCRSOfBaseOfBoundSrc), util::optional<common::DataEpoch>(), boundSrc->transformation()->sourceCRS(), util::optional<common::DataEpoch>(), context); assert(!opsIntermediate.empty()); opIntermediate = opsIntermediate.front(); } for (const auto &opFirst : opsFirst) { for (const auto &opLast : opsLast) { try { std::vector<CoordinateOperationNNPtr> subops; subops.emplace_back(opFirst); if (opIntermediate) { subops.emplace_back(NN_NO_CHECK(opIntermediate)); } subops.emplace_back(boundSrc->transformation()); subops.emplace_back(opLast); res.emplace_back( ConcatenatedOperation::createComputeMetadata( subops, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } if (!res.empty()) { return; } } // Consider WGS 84 and NAD83 as equivalent in that context if the // geogCRSOfBaseOfBoundSrc ellipsoid is Clarke66 (for NAD27) // Case of "+proj=latlong +ellps=clrk66 // +nadgrids=ntv1_can.dat,conus" // to "+proj=latlong +datum=NAD83" } else if (geogCRSOfBaseOfBoundSrc && hubSrcGeog && geogCRSOfBaseOfBoundSrc->ellipsoid()->_isEquivalentTo( datum::Ellipsoid::CLARKE_1866.get(), util::IComparable::Criterion::EQUIVALENT, dbContext) && hubSrcGeog->datumNonNull(dbContext)->_isEquivalentTo( datum::GeodeticReferenceFrame::EPSG_6326.get(), util::IComparable::Criterion::EQUIVALENT, dbContext) && geogDstDatum->_isEquivalentTo( datum::GeodeticReferenceFrame::EPSG_6269.get(), util::IComparable::Criterion::EQUIVALENT, dbContext)) { auto nnGeogCRSOfBaseOfBoundSrc = NN_NO_CHECK(geogCRSOfBaseOfBoundSrc); if (boundSrc->baseCRS()->_isEquivalentTo( nnGeogCRSOfBaseOfBoundSrc.get(), util::IComparable::Criterion::EQUIVALENT)) { auto transf = boundSrc->transformation()->shallowClone(); transf->setProperties(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, buildTransfName(boundSrc->baseCRS()->nameStr(), targetCRS->nameStr()))); transf->setCRSs(boundSrc->baseCRS(), targetCRS, nullptr); res.emplace_back(transf); return; } else { auto opsFirst = createOperations( boundSrc->baseCRS(), util::optional<common::DataEpoch>(), nnGeogCRSOfBaseOfBoundSrc, util::optional<common::DataEpoch>(), context); auto transf = boundSrc->transformation()->shallowClone(); transf->setProperties(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, buildTransfName(nnGeogCRSOfBaseOfBoundSrc->nameStr(), targetCRS->nameStr()))); transf->setCRSs(nnGeogCRSOfBaseOfBoundSrc, targetCRS, nullptr); if (!opsFirst.empty()) { for (const auto &opFirst : opsFirst) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opFirst, transf}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } if (!res.empty()) { return; } } } } if (hubSrcGeog && hubSrcGeog->_isEquivalentTo(geogDst, util::IComparable::Criterion::EQUIVALENT) && dynamic_cast<const crs::VerticalCRS *>(boundSrc->baseCRS().get())) { auto transfSrc = boundSrc->transformation()->sourceCRS(); if (dynamic_cast<const crs::VerticalCRS *>(transfSrc.get()) && !boundSrc->baseCRS()->_isEquivalentTo( transfSrc.get(), util::IComparable::Criterion::EQUIVALENT)) { auto opsFirst = createOperations( boundSrc->baseCRS(), util::optional<common::DataEpoch>(), transfSrc, util::optional<common::DataEpoch>(), context); for (const auto &opFirst : opsFirst) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opFirst, boundSrc->transformation()}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } return; } res.emplace_back(boundSrc->transformation()); return; } if (!triedBoundCrsToGeogCRSSameAsHubCRS && hubSrcGeog && geogCRSOfBaseOfBoundSrc) { // This one should go to the above 'Is it: boundCRS to a geogCRS // that is the same as the hubCRS ?' case auto opsFirst = createOperations( sourceCRS, util::optional<common::DataEpoch>(), hubSrc, util::optional<common::DataEpoch>(), context); auto opsLast = createOperations( hubSrc, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); if (!opsFirst.empty() && !opsLast.empty()) { for (const auto &opFirst : opsFirst) { for (const auto &opLast : opsLast) { // Exclude artificial transformations from the hub // to the target CRS, if it is the only one. if (opsLast.size() > 1 || !opLast->hasBallparkTransformation()) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opFirst, opLast}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } else { // std::cerr << "excluded " << opLast->nameStr() << // std::endl; } } } if (!res.empty()) { return; } } } auto vertCRSOfBaseOfBoundSrc = dynamic_cast<const crs::VerticalCRS *>(boundSrc->baseCRS().get()); // The test for hubSrcGeog not being a DerivedCRS is to avoid infinite // recursion in a scenario involving a // BoundCRS[SourceCRS[VertCRS],TargetCRS[DerivedGeographicCRS]] to a // GeographicCRS if (vertCRSOfBaseOfBoundSrc && hubSrcGeog && dynamic_cast<const crs::DerivedCRS *>(hubSrcGeog) == nullptr) { auto opsFirst = createOperations( sourceCRS, util::optional<common::DataEpoch>(), hubSrc, util::optional<common::DataEpoch>(), context); if (context.skipHorizontalTransformation) { if (!opsFirst.empty()) { const auto &hubAxisList = hubSrcGeog->coordinateSystem()->axisList(); const auto &targetAxisList = geogDst->coordinateSystem()->axisList(); if (hubAxisList.size() == 3 && targetAxisList.size() == 3 && !hubAxisList[2]->_isEquivalentTo( targetAxisList[2].get(), util::IComparable::Criterion::EQUIVALENT)) { const auto &srcAxis = hubAxisList[2]; const double convSrc = srcAxis->unit().conversionToSI(); const auto &dstAxis = targetAxisList[2]; const double convDst = dstAxis->unit().conversionToSI(); const bool srcIsUp = srcAxis->direction() == cs::AxisDirection::UP; const bool srcIsDown = srcAxis->direction() == cs::AxisDirection::DOWN; const bool dstIsUp = dstAxis->direction() == cs::AxisDirection::UP; const bool dstIsDown = dstAxis->direction() == cs::AxisDirection::DOWN; const bool heightDepthReversal = ((srcIsUp && dstIsDown) || (srcIsDown && dstIsUp)); if (convDst == 0) throw InvalidOperation( "Conversion factor of target unit is 0"); const double factor = convSrc / convDst; auto conv = Conversion::createChangeVerticalUnit( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "Change of vertical unit"), common::Scale(heightDepthReversal ? -factor : factor)); conv->setCRSs( hubSrc, hubSrc->demoteTo2D(std::string(), dbContext) ->promoteTo3D(std::string(), dbContext, dstAxis), nullptr); for (const auto &op : opsFirst) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {op, conv}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } else { res = std::move(opsFirst); } } return; } else { auto opsSecond = createOperations( hubSrc, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); if (!opsFirst.empty() && !opsSecond.empty()) { for (const auto &opFirst : opsFirst) { for (const auto &opLast : opsSecond) { // Exclude artificial transformations from the hub // to the target CRS if (!opLast->hasBallparkTransformation()) { try { res.emplace_back( ConcatenatedOperation:: createComputeMetadata( {opFirst, opLast}, disallowEmptyIntersection)); } catch ( const InvalidOperationEmptyIntersection &) { } } else { // std::cerr << "excluded " << opLast->nameStr() << // std::endl; } } } if (!res.empty()) { return; } } } } res = createOperations(boundSrc->baseCRS(), util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsBoundToVert( const crs::CRSNNPtr & /*sourceCRS*/, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); auto baseSrcVert = dynamic_cast<const crs::VerticalCRS *>(boundSrc->baseCRS().get()); const auto &hubSrc = boundSrc->hubCRS(); auto hubSrcVert = dynamic_cast<const crs::VerticalCRS *>(hubSrc.get()); if (baseSrcVert && hubSrcVert && vertDst->_isEquivalentTo(hubSrcVert, util::IComparable::Criterion::EQUIVALENT)) { res.emplace_back(boundSrc->transformation()); return; } res = createOperations(boundSrc->baseCRS(), util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); } // --------------------------------------------------------------------------- static std::string getBallparkTransformationVertToVert(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS) { auto name = buildTransfName(sourceCRS->nameStr(), targetCRS->nameStr()); name += " ("; name += BALLPARK_VERTICAL_TRANSFORMATION; name += ')'; return name; } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsVertToVert( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::VerticalCRS *vertSrc, const crs::VerticalCRS *vertDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; const auto srcDatum = vertSrc->datumNonNull(dbContext); const auto dstDatum = vertDst->datumNonNull(dbContext); const bool equivalentVDatum = srcDatum->_isEquivalentTo( dstDatum.get(), util::IComparable::Criterion::EQUIVALENT, dbContext); const auto &srcAxis = vertSrc->coordinateSystem()->axisList()[0]; const double convSrc = srcAxis->unit().conversionToSI(); const auto &dstAxis = vertDst->coordinateSystem()->axisList()[0]; const double convDst = dstAxis->unit().conversionToSI(); const bool srcIsUp = srcAxis->direction() == cs::AxisDirection::UP; const bool srcIsDown = srcAxis->direction() == cs::AxisDirection::DOWN; const bool dstIsUp = dstAxis->direction() == cs::AxisDirection::UP; const bool dstIsDown = dstAxis->direction() == cs::AxisDirection::DOWN; const bool heightDepthReversal = ((srcIsUp && dstIsDown) || (srcIsDown && dstIsUp)); if (convDst == 0) throw InvalidOperation("Conversion factor of target unit is 0"); const double factor = convSrc / convDst; const auto &sourceCRSExtent = getExtent(sourceCRS); const auto &targetCRSExtent = getExtent(targetCRS); const bool sameExtent = sourceCRSExtent && targetCRSExtent && sourceCRSExtent->_isEquivalentTo( targetCRSExtent.get(), util::IComparable::Criterion::EQUIVALENT); util::PropertyMap map; map.set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, sameExtent ? NN_NO_CHECK(sourceCRSExtent) : metadata::Extent::WORLD); if (!equivalentVDatum) { const auto name = getBallparkTransformationVertToVert(sourceCRS, targetCRS); auto conv = Transformation::createChangeVerticalUnit( map.set(common::IdentifiedObject::NAME_KEY, name), sourceCRS, targetCRS, // In case of a height depth reversal, we should probably have // 2 steps instead of putting a negative factor... common::Scale(heightDepthReversal ? -factor : factor), {}); conv->setHasBallparkTransformation(true); res.push_back(conv); } else if (convSrc != convDst || !heightDepthReversal) { auto name = buildConvName(sourceCRS->nameStr(), targetCRS->nameStr()); auto conv = Conversion::createChangeVerticalUnit( map.set(common::IdentifiedObject::NAME_KEY, name), // In case of a height depth reversal, we should probably have // 2 steps instead of putting a negative factor... common::Scale(heightDepthReversal ? -factor : factor)); conv->setCRSs(sourceCRS, targetCRS, nullptr); res.push_back(conv); } else { auto name = buildConvName(sourceCRS->nameStr(), targetCRS->nameStr()); auto conv = Conversion::createHeightDepthReversal( map.set(common::IdentifiedObject::NAME_KEY, name)); conv->setCRSs(sourceCRS, targetCRS, nullptr); res.push_back(conv); } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsVertToGeog( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::VerticalCRS *vertSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); if (vertSrc->identifiers().empty()) { const auto &vertSrcName = vertSrc->nameStr(); const auto &authFactory = context.context->getAuthorityFactory(); if (authFactory != nullptr && vertSrcName != "unnamed" && vertSrcName != "unknown") { auto matches = authFactory->createObjectsFromName( vertSrcName, {io::AuthorityFactory::ObjectType::VERTICAL_CRS}, false, 2); if (matches.size() == 1) { const auto &match = matches.front(); if (vertSrc->_isEquivalentTo( match.get(), util::IComparable::Criterion::EQUIVALENT) && !match->identifiers().empty()) { auto resTmp = createOperations( NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::VerticalCRS>( match)), sourceEpoch, targetCRS, targetEpoch, context); res.insert(res.end(), resTmp.begin(), resTmp.end()); return; } } } } createOperationsVertToGeogBallpark(sourceCRS, targetCRS, context, vertSrc, geogDst, res); } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsVertToGeogBallpark( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &, const crs::VerticalCRS *vertSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); const auto &srcAxis = vertSrc->coordinateSystem()->axisList()[0]; const double convSrc = srcAxis->unit().conversionToSI(); double convDst = 1.0; const auto &geogAxis = geogDst->coordinateSystem()->axisList(); bool dstIsUp = true; bool dstIsDown = false; if (geogAxis.size() == 3) { const auto &dstAxis = geogAxis[2]; convDst = dstAxis->unit().conversionToSI(); dstIsUp = dstAxis->direction() == cs::AxisDirection::UP; dstIsDown = dstAxis->direction() == cs::AxisDirection::DOWN; } const bool srcIsUp = srcAxis->direction() == cs::AxisDirection::UP; const bool srcIsDown = srcAxis->direction() == cs::AxisDirection::DOWN; const bool heightDepthReversal = ((srcIsUp && dstIsDown) || (srcIsDown && dstIsUp)); if (convDst == 0) throw InvalidOperation("Conversion factor of target unit is 0"); const double factor = convSrc / convDst; const auto &sourceCRSExtent = getExtent(sourceCRS); const auto &targetCRSExtent = getExtent(targetCRS); const bool sameExtent = sourceCRSExtent && targetCRSExtent && sourceCRSExtent->_isEquivalentTo( targetCRSExtent.get(), util::IComparable::Criterion::EQUIVALENT); util::PropertyMap map; std::string transfName( buildTransfName(sourceCRS->nameStr(), targetCRS->nameStr())); transfName += " ("; transfName += BALLPARK_VERTICAL_TRANSFORMATION_NO_ELLIPSOID_VERT_HEIGHT; transfName += ')'; map.set(common::IdentifiedObject::NAME_KEY, transfName) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, sameExtent ? NN_NO_CHECK(sourceCRSExtent) : metadata::Extent::WORLD); auto conv = Transformation::createChangeVerticalUnit( map, sourceCRS, targetCRS, common::Scale(heightDepthReversal ? -factor : factor), {}); conv->setHasBallparkTransformation(true); res.push_back(conv); } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsBoundToBound( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::BoundCRS *boundDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); // BoundCRS to BoundCRS of horizontal CRS using the same (geographic) hub const auto &hubSrc = boundSrc->hubCRS(); auto hubSrcGeog = dynamic_cast<const crs::GeographicCRS *>(hubSrc.get()); const auto &hubDst = boundDst->hubCRS(); auto hubDstGeog = dynamic_cast<const crs::GeographicCRS *>(hubDst.get()); if (hubSrcGeog && hubDstGeog && hubSrcGeog->_isEquivalentTo(hubDstGeog, util::IComparable::Criterion::EQUIVALENT)) { auto opsFirst = createOperations( sourceCRS, util::optional<common::DataEpoch>(), hubSrc, util::optional<common::DataEpoch>(), context); auto opsLast = createOperations( hubSrc, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); for (const auto &opFirst : opsFirst) { for (const auto &opLast : opsLast) { try { std::vector<CoordinateOperationNNPtr> ops; ops.push_back(opFirst); ops.push_back(opLast); res.emplace_back( ConcatenatedOperation::createComputeMetadata( ops, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } if (!res.empty()) { return; } } // BoundCRS to BoundCRS of vertical CRS using the same vertical datum // ==> ignore the bound transformation auto baseOfBoundSrcAsVertCRS = dynamic_cast<crs::VerticalCRS *>(boundSrc->baseCRS().get()); auto baseOfBoundDstAsVertCRS = dynamic_cast<crs::VerticalCRS *>(boundDst->baseCRS().get()); if (baseOfBoundSrcAsVertCRS && baseOfBoundDstAsVertCRS) { const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; const auto datumSrc = baseOfBoundSrcAsVertCRS->datumNonNull(dbContext); const auto datumDst = baseOfBoundDstAsVertCRS->datumNonNull(dbContext); if (datumSrc->nameStr() == datumDst->nameStr() && (datumSrc->nameStr() != "unknown" || boundSrc->transformation()->_isEquivalentTo( boundDst->transformation().get(), util::IComparable::Criterion::EQUIVALENT))) { res = createOperations( boundSrc->baseCRS(), util::optional<common::DataEpoch>(), boundDst->baseCRS(), util::optional<common::DataEpoch>(), context); return; } } // BoundCRS to BoundCRS of vertical CRS auto vertCRSOfBaseOfBoundSrc = boundSrc->baseCRS()->extractVerticalCRS(); auto vertCRSOfBaseOfBoundDst = boundDst->baseCRS()->extractVerticalCRS(); if (hubSrcGeog && hubDstGeog && hubSrcGeog->_isEquivalentTo(hubDstGeog, util::IComparable::Criterion::EQUIVALENT) && vertCRSOfBaseOfBoundSrc && vertCRSOfBaseOfBoundDst) { auto opsFirst = createOperations( sourceCRS, util::optional<common::DataEpoch>(), hubSrc, util::optional<common::DataEpoch>(), context); auto opsLast = createOperations( hubSrc, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); if (!opsFirst.empty() && !opsLast.empty()) { for (const auto &opFirst : opsFirst) { for (const auto &opLast : opsLast) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opFirst, opLast}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } if (!res.empty()) { return; } } } res = createOperations( boundSrc->baseCRS(), util::optional<common::DataEpoch>(), boundDst->baseCRS(), util::optional<common::DataEpoch>(), context); } // --------------------------------------------------------------------------- static std::vector<CoordinateOperationNNPtr> getOps(const CoordinateOperationNNPtr &op) { auto concatenated = dynamic_cast<const ConcatenatedOperation *>(op.get()); if (concatenated) return concatenated->operations(); return {op}; } // --------------------------------------------------------------------------- static std::string normalize2D3DInName(const std::string &s) { std::string out = s; const char *const patterns[] = { " (2D)", " (geographic3D horizontal)", " (geog2D)", " (geog3D)", }; for (const char *pattern : patterns) { out = replaceAll(out, pattern, ""); } return out; } // --------------------------------------------------------------------------- static bool useCompatibleTransformationsForSameSourceTarget( const CoordinateOperationNNPtr &opA, const CoordinateOperationNNPtr &opB) { const auto subOpsA = getOps(opA); const auto subOpsB = getOps(opB); for (const auto &subOpA : subOpsA) { if (!dynamic_cast<const Transformation *>(subOpA.get())) continue; const auto subOpAName = normalize2D3DInName(subOpA->nameStr()); const auto &subOpASourceCRSName = subOpA->sourceCRS()->nameStr(); const auto &subOpATargetCRSName = subOpA->targetCRS()->nameStr(); if (subOpASourceCRSName == "unknown" || subOpATargetCRSName == "unknown") continue; for (const auto &subOpB : subOpsB) { if (!dynamic_cast<const Transformation *>(subOpB.get())) continue; const auto &subOpBSourceCRSName = subOpB->sourceCRS()->nameStr(); const auto &subOpBTargetCRSName = subOpB->targetCRS()->nameStr(); if (subOpBSourceCRSName == "unknown" || subOpBTargetCRSName == "unknown") continue; if (subOpASourceCRSName == subOpBSourceCRSName && subOpATargetCRSName == subOpBTargetCRSName) { const auto &subOpBName = normalize2D3DInName(subOpB->nameStr()); if (starts_with(subOpAName, NULL_GEOGRAPHIC_OFFSET) && starts_with(subOpB->nameStr(), NULL_GEOGRAPHIC_OFFSET)) { continue; } if (subOpAName != subOpBName) { return false; } } else if (subOpASourceCRSName == subOpBTargetCRSName && subOpATargetCRSName == subOpBSourceCRSName) { const auto &subOpBName = subOpB->nameStr(); if (starts_with(subOpAName, NULL_GEOGRAPHIC_OFFSET) && starts_with(subOpBName, NULL_GEOGRAPHIC_OFFSET)) { continue; } if (subOpAName != normalize2D3DInName(subOpB->inverse()->nameStr())) { return false; } } } } return true; } // --------------------------------------------------------------------------- static crs::GeographicCRSPtr getInterpolationGeogCRS(const CoordinateOperationNNPtr &verticalTransform, const io::DatabaseContextPtr &dbContext) { crs::GeographicCRSPtr interpolationGeogCRS; auto transformationVerticalTransform = dynamic_cast<const Transformation *>(verticalTransform.get()); if (transformationVerticalTransform == nullptr) { const auto concat = dynamic_cast<const ConcatenatedOperation *>( verticalTransform.get()); if (concat) { const auto &steps = concat->operations(); // Is this change of unit and/or height depth reversal + // transformation ? for (const auto &step : steps) { const auto transf = dynamic_cast<const Transformation *>(step.get()); if (transf) { // Only support a single Transformation in the steps if (transformationVerticalTransform != nullptr) { transformationVerticalTransform = nullptr; break; } transformationVerticalTransform = transf; } } } } if (transformationVerticalTransform && !transformationVerticalTransform->hasBallparkTransformation()) { auto interpTransformCRS = transformationVerticalTransform->interpolationCRS(); if (interpTransformCRS) { interpolationGeogCRS = std::dynamic_pointer_cast<crs::GeographicCRS>( interpTransformCRS); } else { // If no explicit interpolation CRS, then // this will be the geographic CRS of the // vertical to geog transformation interpolationGeogCRS = std::dynamic_pointer_cast<crs::GeographicCRS>( transformationVerticalTransform->targetCRS().as_nullable()); } } if (interpolationGeogCRS) { if (interpolationGeogCRS->coordinateSystem()->axisList().size() == 3) { // We need to force the interpolation CRS, which // will // frequently be 3D, to 2D to avoid transformations // between source CRS and interpolation CRS to have // 3D terms. interpolationGeogCRS = interpolationGeogCRS->demoteTo2D(std::string(), dbContext) .as_nullable(); } } return interpolationGeogCRS; } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsCompoundToGeog( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::CompoundCRS *compoundSrc, const crs::GeographicCRS *geogDst, std::vector<CoordinateOperationNNPtr> &res) { ENTER_FUNCTION(); const auto &authFactory = context.context->getAuthorityFactory(); const auto &componentsSrc = compoundSrc->componentReferenceSystems(); if (!componentsSrc.empty()) { const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; if (componentsSrc.size() == 2) { auto derivedHSrc = dynamic_cast<const crs::DerivedCRS *>(componentsSrc[0].get()); if (derivedHSrc) { std::vector<crs::CRSNNPtr> intermComponents{ derivedHSrc->baseCRS(), componentsSrc[1]}; auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, intermComponents[0]->nameStr() + " + " + intermComponents[1]->nameStr()); auto intermCompound = crs::CompoundCRS::create(properties, intermComponents); auto opsFirst = createOperations(sourceCRS, sourceEpoch, intermCompound, sourceEpoch, context); assert(!opsFirst.empty()); auto opsLast = createOperations(intermCompound, sourceEpoch, targetCRS, targetEpoch, context); for (const auto &opLast : opsLast) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opsFirst.front(), opLast}, disallowEmptyIntersection)); } catch (const std::exception &) { } } return; } auto geogSrc = dynamic_cast<const crs::GeographicCRS *>( componentsSrc[0].get()); // Sorry for this hack... aimed at transforming // "NAD83(CSRS)v7 + CGVD2013a(1997) height @ 1997" to "NAD83(CSRS)v7 // @ 1997" to "NAD83(CSRS)v3 + CGVD2013a(1997) height" to // "NAD83(CSRS)v3" OR "NAD83(CSRS)v7 + CGVD2013a(2002) height @ // 2002" to "NAD83(CSRS)v7 @ 2002" to "NAD83(CSRS)v4 + // CGVD2013a(2002) height" to "NAD83(CSRS)v4" if (dbContext && geogSrc && geogSrc->nameStr() == "NAD83(CSRS)v7" && sourceEpoch.has_value() && geogDst->coordinateSystem()->axisList().size() == 3U && geogDst->nameStr() == geogSrc->nameStr() && targetEpoch.has_value() && sourceEpoch->coordinateEpoch()._isEquivalentTo( targetEpoch->coordinateEpoch())) { const bool is1997 = std::abs(sourceEpoch->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR) - 1997) < 1e-10; const bool is2002 = std::abs(sourceEpoch->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR) - 2002) < 1e-10; try { auto authFactoryEPSG = io::AuthorityFactory::create( authFactory->databaseContext(), "EPSG"); if (geogSrc->_isEquivalentTo( authFactoryEPSG ->createCoordinateReferenceSystem("8255") .get(), util::IComparable::Criterion:: EQUIVALENT) && // NAD83(CSRS)v7 // 2D geogDst->_isEquivalentTo( authFactoryEPSG ->createCoordinateReferenceSystem("8254") .get(), util::IComparable::Criterion:: EQUIVALENT) && // NAD83(CSRS)v7 // 3D ((is1997 && componentsSrc[1]->nameStr() == "CGVD2013a(1997) height") || (is2002 && componentsSrc[1]->nameStr() == "CGVD2013a(2002) height"))) { const auto newGeogCRS_2D( authFactoryEPSG->createCoordinateReferenceSystem( is1997 ? "8240" : // NAD83(CSRS)v3 2D "8246" // NAD83(CSRS)v4 2D )); const auto newGeogCRS_3D( authFactoryEPSG->createCoordinateReferenceSystem( is1997 ? "8239" : // NAD83(CSRS)v3 3D "8244" // NAD83(CSRS)v4 3D )); std::vector<crs::CRSNNPtr> intermComponents{ newGeogCRS_2D, componentsSrc[1]}; auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, intermComponents[0]->nameStr() + " + " + intermComponents[1]->nameStr()); auto newCompound = crs::CompoundCRS::create( properties, intermComponents); auto ops = createOperations(newCompound, sourceEpoch, newGeogCRS_3D, sourceEpoch, context); for (const auto &op : ops) { auto opClone = op->shallowClone(); setCRSs(opClone.get(), sourceCRS, targetCRS); res.emplace_back(opClone); } return; } } catch (const std::exception &) { } } auto boundSrc = dynamic_cast<const crs::BoundCRS *>(componentsSrc[0].get()); if (boundSrc) { derivedHSrc = dynamic_cast<const crs::DerivedCRS *>( boundSrc->baseCRS().get()); if (derivedHSrc) { std::vector<crs::CRSNNPtr> intermComponents{ crs::BoundCRS::create(derivedHSrc->baseCRS(), boundSrc->hubCRS(), boundSrc->transformation()), componentsSrc[1]}; auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, intermComponents[0]->nameStr() + " + " + intermComponents[1]->nameStr()); auto intermCompound = crs::CompoundCRS::create(properties, intermComponents); auto opsFirst = createOperations(sourceCRS, sourceEpoch, intermCompound, sourceEpoch, context); assert(!opsFirst.empty()); auto opsLast = createOperations(intermCompound, sourceEpoch, targetCRS, targetEpoch, context); for (const auto &opLast : opsLast) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {opsFirst.front(), opLast}, disallowEmptyIntersection)); } catch (const std::exception &) { } } return; } } } // Deal with "+proj=something +geoidgrids +nadgrids/+towgs84" to // another CRS whose datum is not the same as the horizontal datum // of the source if (componentsSrc.size() == 2) { auto comp0Bound = dynamic_cast<crs::BoundCRS *>(componentsSrc[0].get()); auto comp1Bound = dynamic_cast<crs::BoundCRS *>(componentsSrc[1].get()); auto comp0Geog = componentsSrc[0]->extractGeographicCRS(); auto dstGeog = targetCRS->extractGeographicCRS(); if (comp0Bound && comp1Bound && comp0Geog && comp1Bound->hubCRS() ->demoteTo2D(std::string(), dbContext) ->isEquivalentTo( comp0Geog.get(), util::IComparable::Criterion::EQUIVALENT) && dstGeog && !comp0Geog->datumNonNull(dbContext)->isEquivalentTo( dstGeog->datumNonNull(dbContext).get(), util::IComparable::Criterion::EQUIVALENT)) { const auto &op1Dest = comp1Bound->hubCRS(); const auto ops1 = createOperations( crs::CompoundCRS::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, std::string()), {comp0Bound->baseCRS(), componentsSrc[1]}), util::optional<common::DataEpoch>(), op1Dest, util::optional<common::DataEpoch>(), context); const auto op2Dest = comp0Bound->hubCRS()->promoteTo3D(std::string(), dbContext); const auto ops2 = createOperations( crs::BoundCRS::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, std::string()), NN_NO_CHECK(comp0Geog), comp0Bound->hubCRS(), comp0Bound->transformation()) ->promoteTo3D(std::string(), dbContext), util::optional<common::DataEpoch>(), op2Dest, util::optional<common::DataEpoch>(), context); const auto ops3 = createOperations( op2Dest, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); for (const auto &op1 : ops1) { auto op1Clone = op1->shallowClone(); setCRSs(op1Clone.get(), sourceCRS, op1Dest); for (const auto &op2 : ops2) { auto op2Clone = op2->shallowClone(); setCRSs(op2Clone.get(), op1Dest, op2Dest); for (const auto &op3 : ops3) { try { res.emplace_back( ConcatenatedOperation:: createComputeMetadata( {op1Clone, op2Clone, op3}, disallowEmptyIntersection)); } catch (const std::exception &) { } } } } if (!res.empty()) { return; } } } // Only do a vertical transformation if the target CRS is 3D. const auto dstSingle = dynamic_cast<crs::SingleCRS *>(targetCRS.get()); if (dstSingle && dstSingle->coordinateSystem()->axisList().size() == 2) { auto tmp = createOperations(componentsSrc[0], sourceEpoch, targetCRS, targetEpoch, context); for (const auto &op : tmp) { auto opClone = op->shallowClone(); setCRSs(opClone.get(), sourceCRS, targetCRS); res.emplace_back(opClone); } return; } std::vector<CoordinateOperationNNPtr> horizTransforms; auto srcGeogCRS = componentsSrc[0]->extractGeographicCRS(); if (srcGeogCRS) { horizTransforms = createOperations(componentsSrc[0], sourceEpoch, targetCRS, targetEpoch, context); } std::vector<CoordinateOperationNNPtr> verticalTransforms; if (componentsSrc.size() >= 2 && componentsSrc[1]->extractVerticalCRS()) { struct SetSkipHorizontalTransform { Context &context; explicit SetSkipHorizontalTransform(Context &contextIn) : context(contextIn) { assert(!context.skipHorizontalTransformation); context.skipHorizontalTransformation = true; } ~SetSkipHorizontalTransform() { context.skipHorizontalTransformation = false; } }; SetSkipHorizontalTransform setSkipHorizontalTransform(context); verticalTransforms = createOperations( componentsSrc[1], util::optional<common::DataEpoch>(), targetCRS->promoteTo3D(std::string(), dbContext), util::optional<common::DataEpoch>(), context); bool foundRegisteredTransformWithAllGridsAvailable = false; const auto gridAvailabilityUse = context.context->getGridAvailabilityUse(); const bool ignoreMissingGrids = gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY; for (const auto &op : verticalTransforms) { if (hasIdentifiers(op) && dbContext) { bool missingGrid = false; if (!ignoreMissingGrids) { const auto gridsNeeded = op->gridsNeeded( dbContext, gridAvailabilityUse == CoordinateOperationContext:: GridAvailabilityUse::KNOWN_AVAILABLE); for (const auto &gridDesc : gridsNeeded) { if (!gridDesc.available) { missingGrid = true; break; } } } if (!missingGrid) { foundRegisteredTransformWithAllGridsAvailable = true; break; } } } if (srcGeogCRS && !srcGeogCRS->_isEquivalentTo( geogDst, util::IComparable::Criterion::EQUIVALENT) && !srcGeogCRS->is2DPartOf3D(NN_NO_CHECK(geogDst), dbContext)) { auto geogCRSTmp = NN_NO_CHECK(srcGeogCRS) ->demoteTo2D(std::string(), dbContext) ->promoteTo3D( std::string(), dbContext, geogDst->coordinateSystem()->axisList().size() == 3 ? geogDst->coordinateSystem()->axisList()[2] : cs::VerticalCS::createGravityRelatedHeight( common::UnitOfMeasure::METRE) ->axisList()[0]); auto verticalTransformsTmp = createOperations( componentsSrc[1], util::optional<common::DataEpoch>(), geogCRSTmp, util::optional<common::DataEpoch>(), context); bool foundRegisteredTransform = false; bool foundRegisteredTransformWithAllGridsAvailable2 = false; for (const auto &op : verticalTransformsTmp) { if (hasIdentifiers(op) && dbContext) { bool missingGrid = false; if (!ignoreMissingGrids) { const auto gridsNeeded = op->gridsNeeded( dbContext, gridAvailabilityUse == CoordinateOperationContext:: GridAvailabilityUse::KNOWN_AVAILABLE); for (const auto &gridDesc : gridsNeeded) { if (!gridDesc.available) { missingGrid = true; break; } } } foundRegisteredTransform = true; if (!missingGrid) { foundRegisteredTransformWithAllGridsAvailable2 = true; break; } } } if (foundRegisteredTransformWithAllGridsAvailable2 && !foundRegisteredTransformWithAllGridsAvailable) { verticalTransforms = std::move(verticalTransformsTmp); } else if (foundRegisteredTransform) { verticalTransforms.insert(verticalTransforms.end(), verticalTransformsTmp.begin(), verticalTransformsTmp.end()); } } } if (horizTransforms.empty() || verticalTransforms.empty()) { res = horizTransforms; return; } typedef std::pair<std::vector<CoordinateOperationNNPtr>, std::vector<CoordinateOperationNNPtr>> PairOfTransforms; std::map<std::string, PairOfTransforms> cacheHorizToInterpAndInterpToTarget; for (const auto &verticalTransform : verticalTransforms) { #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("Considering vertical transform " + objectAsStr(verticalTransform.get())); #endif crs::GeographicCRSPtr interpolationGeogCRS = getInterpolationGeogCRS(verticalTransform, dbContext); if (interpolationGeogCRS) { #ifdef TRACE_CREATE_OPERATIONS logTrace("Using " + objectAsStr(interpolationGeogCRS.get()) + " as interpolation CRS"); #endif std::vector<CoordinateOperationNNPtr> srcToInterpOps; std::vector<CoordinateOperationNNPtr> interpToTargetOps; std::string key; const auto &ids = interpolationGeogCRS->identifiers(); if (!ids.empty()) { key = (*ids.front()->codeSpace()) + ':' + ids.front()->code(); } const auto computeOpsToInterp = [&srcToInterpOps, &interpToTargetOps, &componentsSrc, &interpolationGeogCRS, &targetCRS, &geogDst, &dbContext, &context]() { // Do the sourceCRS to interpolation CRS in 2D only // to avoid altering the orthometric elevation srcToInterpOps = createOperations( componentsSrc[0], util::optional<common::DataEpoch>(), NN_NO_CHECK(interpolationGeogCRS), util::optional<common::DataEpoch>(), context); // e.g when doing COMPOUND_CRS[ // NAD83(CRS)+TOWGS84[0,0,0], // CGVD28 height + EXTENSION["PROJ4_GRIDS","HT2_0.gtx"] // to NAD83(CRS) 3D const auto boundSrc = dynamic_cast<crs::BoundCRS *>(componentsSrc[0].get()); if (boundSrc && boundSrc->baseCRS()->isEquivalentTo( targetCRS->demoteTo2D(std::string(), dbContext) .get(), util::IComparable::Criterion::EQUIVALENT) && boundSrc->hubCRS()->isEquivalentTo( interpolationGeogCRS ->demoteTo2D(std::string(), dbContext) .get(), util::IComparable::Criterion::EQUIVALENT)) { // Make sure to use the same horizontal transformation // (likely a null shift) interpToTargetOps = applyInverse(srcToInterpOps); return; } // But do the interpolation CRS to targetCRS in 3D // to have proper ellipsoid height transformation. // We need to force the vertical axis of this 3D'ified // interpolation CRS to be the same as the target CRS, // to avoid potential double vertical unit conversion, // as the vertical transformation already takes care of // that. auto interp3D = interpolationGeogCRS ->demoteTo2D(std::string(), dbContext) ->promoteTo3D( std::string(), dbContext, geogDst->coordinateSystem() ->axisList() .size() == 3 ? geogDst->coordinateSystem()->axisList()[2] : cs::VerticalCS:: createGravityRelatedHeight( common::UnitOfMeasure::METRE) ->axisList()[0]); interpToTargetOps = createOperations( interp3D, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); }; if (!key.empty()) { auto iter = cacheHorizToInterpAndInterpToTarget.find(key); if (iter == cacheHorizToInterpAndInterpToTarget.end()) { #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("looking for horizontal transformation " "from source to interpCRS and interpCRS to " "target"); #endif computeOpsToInterp(); cacheHorizToInterpAndInterpToTarget[key] = PairOfTransforms(srcToInterpOps, interpToTargetOps); } else { srcToInterpOps = iter->second.first; interpToTargetOps = iter->second.second; } } else { #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("looking for horizontal transformation " "from source to interpCRS and interpCRS to " "target"); #endif computeOpsToInterp(); } #ifdef TRACE_CREATE_OPERATIONS ENTER_BLOCK("creating HorizVerticalHorizPROJBased operations"); #endif const bool srcAndTargetGeogAreSame = componentsSrc[0]->isEquivalentTo( targetCRS->demoteTo2D(std::string(), dbContext).get(), util::IComparable::Criterion::EQUIVALENT); // Lambda to add to the set the name of geodetic datum of the // CRS const auto addDatumOfToSet = [&dbContext]( std::set<std::string> &set, const crs::CRSNNPtr &crs) { auto geodCRS = crs->extractGeodeticCRS(); if (geodCRS) { set.insert(geodCRS->datumNonNull(dbContext)->nameStr()); } }; // Lambda to return the set of names of geodetic datums used // by the source and target CRS of a list of operations. const auto makeDatumSet = [&addDatumOfToSet]( const std::vector<CoordinateOperationNNPtr> &ops) { std::set<std::string> datumSetOps; for (const auto &subOp : ops) { if (!dynamic_cast<const Transformation *>( subOp.get())) continue; addDatumOfToSet(datumSetOps, NN_NO_CHECK(subOp->sourceCRS())); addDatumOfToSet(datumSetOps, NN_NO_CHECK(subOp->targetCRS())); } return datumSetOps; }; std::map<CoordinateOperation *, std::set<std::string>> mapSetDatumsUsed; if (srcAndTargetGeogAreSame) { // When the geographic CRS of the source and target, we // want to make sure that the transformation from the // source to the interpolation CRS uses the same datums as // the one from the interpolation CRS to the target CRS. // A simplistic view would be that the srcToInterp and // interpToTarget should be the same, but they are // subtelties, like interpToTarget being done in 3D, so with // additional conversion steps, slightly different names in // operations between 2D and 3D. The initial filter on // checking that we use the same set of datum enable us // to be confident we reject upfront geodetically-dubious // operations. for (const auto &op : srcToInterpOps) { mapSetDatumsUsed[op.get()] = makeDatumSet(getOps(op)); } for (const auto &op : interpToTargetOps) { mapSetDatumsUsed[op.get()] = makeDatumSet(getOps(op)); } } const bool hasOnlyOneOp = srcToInterpOps.size() == 1 && interpToTargetOps.size() == 1; for (const auto &srcToInterp : srcToInterpOps) { for (const auto &interpToTarget : interpToTargetOps) { if (!hasOnlyOneOp && ((srcAndTargetGeogAreSame && mapSetDatumsUsed[srcToInterp.get()] != mapSetDatumsUsed[interpToTarget.get()]) || !useCompatibleTransformationsForSameSourceTarget( srcToInterp, interpToTarget))) { #ifdef TRACE_CREATE_OPERATIONS logTrace( "Considering that '" + srcToInterp->nameStr() + "' and '" + interpToTarget->nameStr() + "' do not use consistent operations in the pre " "and post-vertical transformation steps"); #endif continue; } try { auto op = createHorizVerticalHorizPROJBased( sourceCRS, targetCRS, srcToInterp, verticalTransform, interpToTarget, interpolationGeogCRS, true); res.emplace_back(op); } catch (const std::exception &) { } } } } else { // This case is probably only correct if // verticalTransform and horizTransform are independent // and in particular that verticalTransform does not // involve a grid, because of the rather arbitrary order // horizontal then vertical applied for (const auto &horizTransform : horizTransforms) { try { auto op = createHorizVerticalPROJBased( sourceCRS, targetCRS, horizTransform, verticalTransform, disallowEmptyIntersection); res.emplace_back(op); } catch (const std::exception &) { } } } } } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsToGeod( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::GeodeticCRS *geodDst, std::vector<CoordinateOperationNNPtr> &res) { auto cs = cs::EllipsoidalCS::createLatitudeLongitudeEllipsoidalHeight( common::UnitOfMeasure::DEGREE, common::UnitOfMeasure::METRE); auto intermGeog3DCRS = util::nn_static_pointer_cast<crs::CRS>(crs::GeographicCRS::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, geodDst->nameStr()) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), geodDst->datum(), geodDst->datumEnsemble(), cs)); auto sourceToGeog3DOps = createOperations( sourceCRS, sourceEpoch, intermGeog3DCRS, sourceEpoch, context); auto geog3DToTargetOps = createOperations(intermGeog3DCRS, targetEpoch, targetCRS, targetEpoch, context); if (!geog3DToTargetOps.empty()) { for (const auto &op : sourceToGeog3DOps) { auto newOp = op->shallowClone(); setCRSs(newOp.get(), sourceCRS, intermGeog3DCRS); try { res.emplace_back(ConcatenatedOperation::createComputeMetadata( {std::move(newOp), geog3DToTargetOps.front()}, disallowEmptyIntersection)); } catch (const InvalidOperationEmptyIntersection &) { } } } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsCompoundToCompound( const crs::CRSNNPtr &sourceCRS, const util::optional<common::DataEpoch> &sourceEpoch, const crs::CRSNNPtr &targetCRS, const util::optional<common::DataEpoch> &targetEpoch, Private::Context &context, const crs::CompoundCRS *compoundSrc, const crs::CompoundCRS *compoundDst, std::vector<CoordinateOperationNNPtr> &res) { const auto &componentsSrc = compoundSrc->componentReferenceSystems(); const auto &componentsDst = compoundDst->componentReferenceSystems(); if (componentsSrc.empty() || componentsSrc.size() != componentsDst.size()) { return; } const auto srcGeog = componentsSrc[0]->extractGeographicCRS(); const auto dstGeog = componentsDst[0]->extractGeographicCRS(); if (srcGeog == nullptr || dstGeog == nullptr) { return; } // Use PointMotionOperations if appropriate and available const auto &authFactory = context.context->getAuthorityFactory(); auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; if (authFactory && sourceEpoch.has_value() && targetEpoch.has_value() && !sourceEpoch->coordinateEpoch()._isEquivalentTo( targetEpoch->coordinateEpoch()) && srcGeog->_isEquivalentTo(dstGeog.get(), util::IComparable::Criterion::EQUIVALENT)) { const auto pmoSrc = authFactory->getPointMotionOperationsFor( NN_NO_CHECK(srcGeog), true); if (!pmoSrc.empty()) { auto geog3D = srcGeog->promoteTo3D( std::string(), authFactory->databaseContext().as_nullable()); auto opsFirst = createOperations(sourceCRS, sourceEpoch, geog3D, sourceEpoch, context); auto pmoOps = createOperations(geog3D, sourceEpoch, geog3D, targetEpoch, context); auto opsLast = createOperations(geog3D, targetEpoch, targetCRS, targetEpoch, context); for (const auto &opFirst : opsFirst) { if (!opFirst->hasBallparkTransformation()) { for (const auto &opMiddle : pmoOps) { if (!opMiddle->hasBallparkTransformation()) { for (const auto &opLast : opsLast) { if (!opLast->hasBallparkTransformation()) { try { res.emplace_back( ConcatenatedOperation:: createComputeMetadata( {opFirst, opMiddle, opLast}, disallowEmptyIntersection)); } catch (const std::exception &) { } } } } } } } if (!res.empty()) { return; } } } // Deal with "+proj=something +geoidgrids +nadgrids/+towgs84" to // "+proj=something +geoidgrids +nadgrids/+towgs84", using WGS 84 as an // intermediate. if (componentsSrc.size() == 2 && componentsDst.size() == 2) { auto comp0SrcBound = dynamic_cast<crs::BoundCRS *>(componentsSrc[0].get()); auto comp1SrcBound = dynamic_cast<crs::BoundCRS *>(componentsSrc[1].get()); auto comp0DstBound = dynamic_cast<crs::BoundCRS *>(componentsDst[0].get()); auto comp1DstBound = dynamic_cast<crs::BoundCRS *>(componentsDst[1].get()); if (comp0SrcBound && comp1SrcBound && comp0DstBound && comp1DstBound && comp0SrcBound->hubCRS()->isEquivalentTo( comp0DstBound->hubCRS().get(), util::IComparable::Criterion::EQUIVALENT) && !comp1SrcBound->isEquivalentTo( comp1DstBound, util::IComparable::Criterion::EQUIVALENT)) { auto hub3D = comp0SrcBound->hubCRS()->promoteTo3D(std::string(), dbContext); const auto ops1 = createOperations(sourceCRS, sourceEpoch, hub3D, sourceEpoch, context); const auto ops2 = createOperations(hub3D, targetEpoch, targetCRS, targetEpoch, context); for (const auto &op1 : ops1) { for (const auto &op2 : ops2) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {op1, op2}, disallowEmptyIntersection)); } catch (const std::exception &) { } } } return; } } std::vector<CoordinateOperationNNPtr> verticalTransforms; bool bTryThroughIntermediateGeogCRS = false; if (componentsSrc.size() >= 2) { const auto vertSrc = componentsSrc[1]->extractVerticalCRS(); const auto vertDst = componentsDst[1]->extractVerticalCRS(); if (vertSrc && vertDst && !componentsSrc[1]->_isEquivalentTo(componentsDst[1].get())) { if ((!vertSrc->geoidModel().empty() || !vertDst->geoidModel().empty()) && // To be able to use "CGVD28 height to // CGVD2013a(1997|2002|2010)" single grid !(vertSrc->nameStr() == "CGVD28 height" && !vertSrc->geoidModel().empty() && vertSrc->geoidModel().front()->nameStr() == "HT2_1997" && vertDst->nameStr() == "CGVD2013a(1997) height" && vertDst->geoidModel().empty()) && !(vertSrc->nameStr() == "CGVD28 height" && !vertSrc->geoidModel().empty() && vertSrc->geoidModel().front()->nameStr() == "HT2_2002" && vertDst->nameStr() == "CGVD2013a(2002) height" && vertDst->geoidModel().empty()) && !(vertSrc->nameStr() == "CGVD28 height" && !vertSrc->geoidModel().empty() && vertSrc->geoidModel().front()->nameStr() == "HT2_2010" && vertDst->nameStr() == "CGVD2013a(2010) height" && vertDst->geoidModel().empty()) && !(vertDst->nameStr() == "CGVD28 height" && !vertDst->geoidModel().empty() && vertDst->geoidModel().front()->nameStr() == "HT2_1997" && vertSrc->nameStr() == "CGVD2013a(1997) height" && vertSrc->geoidModel().empty()) && !(vertDst->nameStr() == "CGVD28 height" && !vertDst->geoidModel().empty() && vertDst->geoidModel().front()->nameStr() == "HT2_2002" && vertSrc->nameStr() == "CGVD2013a(2002) height" && vertSrc->geoidModel().empty()) && !(vertDst->nameStr() == "CGVD28 height" && !vertDst->geoidModel().empty() && vertDst->geoidModel().front()->nameStr() == "HT2_2010" && vertSrc->nameStr() == "CGVD2013a(2010) height" && vertSrc->geoidModel().empty())) { // If we have a geoid model, force using through it bTryThroughIntermediateGeogCRS = true; } else { verticalTransforms = createOperations(componentsSrc[1], sourceEpoch, componentsDst[1], targetEpoch, context); // If we didn't find a non-ballpark transformation between // the 2 vertical CRS, then try through intermediate geographic // CRS bTryThroughIntermediateGeogCRS = (verticalTransforms.size() == 1 && verticalTransforms.front()->hasBallparkTransformation()); } } } if (bTryThroughIntermediateGeogCRS) { const auto createWithIntermediateCRS = [&sourceCRS, &sourceEpoch, &targetCRS, &targetEpoch, &context, &res](const crs::CRSNNPtr &intermCRS) { const auto ops1 = createOperations( sourceCRS, sourceEpoch, intermCRS, sourceEpoch, context); const auto ops2 = createOperations( intermCRS, targetEpoch, targetCRS, targetEpoch, context); for (const auto &op1 : ops1) { for (const auto &op2 : ops2) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {op1, op2}, disallowEmptyIntersection)); } catch (const std::exception &) { } } } }; const auto boundSrcHorizontal = dynamic_cast<const crs::BoundCRS *>(componentsSrc[0].get()); const auto boundDstHorizontal = dynamic_cast<const crs::BoundCRS *>(componentsDst[0].get()); // CompoundCRS[something_with_TOWGS84, ...] to CompoundCRS[WGS84, ...] if (boundSrcHorizontal != nullptr && boundDstHorizontal == nullptr && boundSrcHorizontal->hubCRS()->_isEquivalentTo( componentsDst[0].get(), util::IComparable::Criterion::EQUIVALENT)) { createWithIntermediateCRS( componentsDst[0]->promoteTo3D(std::string(), dbContext)); if (!res.empty()) { return; } } // Inverse of above else if (boundDstHorizontal != nullptr && boundSrcHorizontal == nullptr && boundDstHorizontal->hubCRS()->_isEquivalentTo( componentsSrc[0].get(), util::IComparable::Criterion::EQUIVALENT)) { createWithIntermediateCRS( componentsSrc[0]->promoteTo3D(std::string(), dbContext)); if (!res.empty()) { return; } } // Deal with situation like // WGS 84 + EGM96 --> ETRS89 + Belfast height where // there is a geoid model for EGM96 referenced to WGS 84 // and a geoid model for Belfast height referenced to ETRS89 const auto intermGeogSrc = srcGeog->promoteTo3D(std::string(), dbContext); const bool intermGeogSrcIsSameAsIntermGeogDst = srcGeog->_isEquivalentTo(dstGeog.get()); const auto intermGeogDst = intermGeogSrcIsSameAsIntermGeogDst ? intermGeogSrc : dstGeog->promoteTo3D(std::string(), dbContext); const auto opsSrcToGeog = createOperations( sourceCRS, sourceEpoch, intermGeogSrc, sourceEpoch, context); const auto opsGeogToTarget = createOperations( intermGeogDst, targetEpoch, targetCRS, targetEpoch, context); // We preferably accept using an intermediate if the operations // to it do not include ballpark operations, but if they do include // grids, using such operations result will be better than nothing. // This will help for example for "NAD83(CSRS) + CGVD28 height" to // "NAD83(CSRS) + CGVD2013(CGG2013) height" where the transformation // between "CGVD2013(CGG2013) height" and "NAD83(CSRS)" actually // involves going through NAD83(CSRS)v6 const auto hasKnownGrid = [&dbContext](const CoordinateOperationNNPtr &op) { const auto grids = op->gridsNeeded(dbContext, true); if (grids.empty()) { return false; } for (const auto &grid : grids) { if (grid.available) { return true; } } return false; }; const auto hasNonTrivialTransf = [&hasKnownGrid](const std::vector<CoordinateOperationNNPtr> &ops) { return !ops.empty() && (!ops.front()->hasBallparkTransformation() || hasKnownGrid(ops.front())); }; const bool hasNonTrivialSrcTransf = hasNonTrivialTransf(opsSrcToGeog); const bool hasNonTrivialTargetTransf = hasNonTrivialTransf(opsGeogToTarget); double bestAccuracy = -1; size_t bestStepCount = 0; if (hasNonTrivialSrcTransf && hasNonTrivialTargetTransf) { const auto opsGeogSrcToGeogDst = createOperations(intermGeogSrc, sourceEpoch, intermGeogDst, targetEpoch, context); // In first pass, exclude (horizontal) ballpark operations, but // accept them in second pass. for (int pass = 0; pass <= 1 && res.empty(); pass++) { for (const auto &op1 : opsSrcToGeog) { if (pass == 0 && op1->hasBallparkTransformation()) { // std::cerr << "excluded " << op1->nameStr() << // std::endl; continue; } if (op1->nameStr().find(BALLPARK_VERTICAL_TRANSFORMATION) != std::string::npos) { continue; } for (const auto &op2 : opsGeogSrcToGeogDst) { for (const auto &op3 : opsGeogToTarget) { if (pass == 0 && op3->hasBallparkTransformation()) { // std::cerr << "excluded " << op3->nameStr() << // std::endl; continue; } if (op3->nameStr().find( BALLPARK_VERTICAL_TRANSFORMATION) != std::string::npos) { continue; } try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( intermGeogSrcIsSameAsIntermGeogDst ? std::vector< CoordinateOperationNNPtr>{op1, op3} : std::vector< CoordinateOperationNNPtr>{op1, op2, op3}, disallowEmptyIntersection)); const double accuracy = getAccuracy(res.back()); const size_t stepCount = getStepCount(res.back()); if (accuracy >= 0 && (bestAccuracy < 0 || (accuracy < bestAccuracy || (accuracy == bestAccuracy && stepCount < bestStepCount)))) { bestAccuracy = accuracy; bestStepCount = stepCount; } } catch (const std::exception &) { } } } } } } const auto createOpsInTwoSteps = [&res, bestAccuracy, bestStepCount](const std::vector<CoordinateOperationNNPtr> &ops1, const std::vector<CoordinateOperationNNPtr> &ops2) { std::vector<CoordinateOperationNNPtr> res2; double bestAccuracy2 = -1; size_t bestStepCount2 = 0; // In first pass, exclude (horizontal) ballpark operations, but // accept them in second pass. for (int pass = 0; pass <= 1 && res2.empty(); pass++) { for (const auto &op1 : ops1) { if (pass == 0 && op1->hasBallparkTransformation()) { // std::cerr << "excluded " << op1->nameStr() << // std::endl; continue; } if (op1->nameStr().find( BALLPARK_VERTICAL_TRANSFORMATION) != std::string::npos) { continue; } for (const auto &op2 : ops2) { if (pass == 0 && op2->hasBallparkTransformation()) { // std::cerr << "excluded " << op2->nameStr() << // std::endl; continue; } if (op2->nameStr().find( BALLPARK_VERTICAL_TRANSFORMATION) != std::string::npos) { continue; } try { res2.emplace_back( ConcatenatedOperation:: createComputeMetadata( {op1, op2}, disallowEmptyIntersection)); const double accuracy = getAccuracy(res2.back()); const size_t stepCount = getStepCount(res2.back()); if (accuracy >= 0 && (bestAccuracy2 < 0 || (accuracy < bestAccuracy2 || (accuracy == bestAccuracy2 && stepCount < bestStepCount2)))) { bestAccuracy2 = accuracy; bestStepCount2 = stepCount; } } catch (const std::exception &) { } } } } // Keep the results of this new attempt, if there are better // than the previous ones if (bestAccuracy2 >= 0 && (bestAccuracy < 0 || (bestAccuracy2 < bestAccuracy || (bestAccuracy2 == bestAccuracy && bestStepCount2 < bestStepCount)))) { res = std::move(res2); } }; // If the promoted-to-3D source geographic CRS is not a known object, // transformations from it to another 3D one may not be relevant, // so try doing source -> geogDst 3D -> dest, if geogDst 3D is a known // object if (!srcGeog->identifiers().empty() && intermGeogSrc->identifiers().empty() && !intermGeogDst->identifiers().empty() && hasNonTrivialTargetTransf) { const auto opsSrcToIntermGeog = createOperations( sourceCRS, util::optional<common::DataEpoch>(), intermGeogDst, util::optional<common::DataEpoch>(), context); if (hasNonTrivialTransf(opsSrcToIntermGeog)) { createOpsInTwoSteps(opsSrcToIntermGeog, opsGeogToTarget); } } // Symmetrical situation with the promoted-to-3D target geographic CRS else if (!dstGeog->identifiers().empty() && intermGeogDst->identifiers().empty() && !intermGeogSrc->identifiers().empty() && hasNonTrivialSrcTransf) { const auto opsIntermGeogToDst = createOperations( intermGeogSrc, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); if (hasNonTrivialTransf(opsIntermGeogToDst)) { createOpsInTwoSteps(opsSrcToGeog, opsIntermGeogToDst); } } if (!res.empty()) { return; } } for (const auto &verticalTransform : verticalTransforms) { auto interpolationGeogCRS = NN_NO_CHECK(srcGeog); auto interpTransformCRS = verticalTransform->interpolationCRS(); if (interpTransformCRS) { auto nn_interpTransformCRS = NN_NO_CHECK(interpTransformCRS); if (dynamic_cast<const crs::GeographicCRS *>( nn_interpTransformCRS.get())) { interpolationGeogCRS = NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::GeographicCRS>( nn_interpTransformCRS)); } } else { auto compSrc0BoundCrs = dynamic_cast<crs::BoundCRS *>(componentsSrc[0].get()); auto compDst0BoundCrs = dynamic_cast<crs::BoundCRS *>(componentsDst[0].get()); if (compSrc0BoundCrs && compDst0BoundCrs && dynamic_cast<crs::GeographicCRS *>( compSrc0BoundCrs->hubCRS().get()) && compSrc0BoundCrs->hubCRS()->_isEquivalentTo( compDst0BoundCrs->hubCRS().get())) { interpolationGeogCRS = NN_NO_CHECK( util::nn_dynamic_pointer_cast<crs::GeographicCRS>( compSrc0BoundCrs->hubCRS())); } } // Hack for // NAD83_CSRS_1997_xxxx_HT2_1997 to NAD83_CSRS_1997_yyyy_CGVD2013_1997 // NAD83_CSRS_2002_xxxx_HT2_2002 to NAD83_CSRS_2002_yyyy_CGVD2013_2002 if (dbContext && sourceEpoch.has_value() && targetEpoch.has_value() && sourceEpoch->coordinateEpoch()._isEquivalentTo( targetEpoch->coordinateEpoch()) && srcGeog->_isEquivalentTo( dstGeog.get(), util::IComparable::Criterion::EQUIVALENT) && srcGeog->nameStr() == "NAD83(CSRS)v7") { const bool is1997 = std::abs(sourceEpoch->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR) - 1997) < 1e-10; const bool is2002 = std::abs(sourceEpoch->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR) - 2002) < 1e-10; try { auto authFactoryEPSG = io::AuthorityFactory::create( NN_NO_CHECK(dbContext), "EPSG"); auto nad83CSRSv7 = authFactoryEPSG->createGeographicCRS("8255"); if (srcGeog->_isEquivalentTo(nad83CSRSv7.get(), util::IComparable::Criterion:: EQUIVALENT) && // NAD83(CSRS)v7 // 2D ((is1997 && verticalTransform->nameStr().find( "CGVD28 height to CGVD2013a(1997) height (1)") != std::string::npos) || (is2002 && verticalTransform->nameStr().find( "CGVD28 height to CGVD2013a(2002) height (1)") != std::string::npos))) { interpolationGeogCRS = std::move(nad83CSRSv7); } } catch (const std::exception &) { } } const auto opSrcCRSToGeogCRS = createOperations( componentsSrc[0], util::optional<common::DataEpoch>(), interpolationGeogCRS, util::optional<common::DataEpoch>(), context); const auto opGeogCRStoDstCRS = createOperations( interpolationGeogCRS, util::optional<common::DataEpoch>(), componentsDst[0], util::optional<common::DataEpoch>(), context); for (const auto &opSrc : opSrcCRSToGeogCRS) { for (const auto &opDst : opGeogCRStoDstCRS) { try { auto op = createHorizVerticalHorizPROJBased( sourceCRS, targetCRS, opSrc, verticalTransform, opDst, interpolationGeogCRS, true); res.emplace_back(op); } catch (const InvalidOperationEmptyIntersection &) { } catch (const io::FormattingException &) { } } } if (verticalTransforms.size() == 1U && verticalTransform->hasBallparkTransformation() && context.context->getAuthorityFactory() && dynamic_cast<crs::ProjectedCRS *>(componentsSrc[0].get()) && dynamic_cast<crs::ProjectedCRS *>(componentsDst[0].get()) && verticalTransform->nameStr() == getBallparkTransformationVertToVert(componentsSrc[1], componentsDst[1])) { // e.g EPSG:3912+EPSG:5779 to EPSG:3794+EPSG:8690 // "MGI 1901 / Slovene National Grid + SVS2000 height" to // "Slovenia 1996 / Slovene National Grid + SVS2010 height" // using the "D48/GK to D96/TM (xx)" family of horizontal // transformatoins between the projected CRS // Cf // https://github.com/OSGeo/PROJ/issues/3854#issuecomment-1689964773 // We restrict to a ballpark vertical transformation for now, // but ideally we should deal with a regular vertical transformation // but that would involve doing a transformation to its // interpolation CRS and we don't have such cases for now. std::vector<CoordinateOperationNNPtr> opsHoriz; createOperationsFromDatabase( componentsSrc[0], util::optional<common::DataEpoch>(), componentsDst[0], util::optional<common::DataEpoch>(), context, srcGeog.get(), dstGeog.get(), srcGeog.get(), dstGeog.get(), /*vertSrc=*/nullptr, /*vertDst=*/nullptr, opsHoriz); for (const auto &opHoriz : opsHoriz) { res.emplace_back(createHorizNullVerticalPROJBased( sourceCRS, targetCRS, opHoriz, verticalTransform)); } } } if (verticalTransforms.empty()) { auto resTmp = createOperations( componentsSrc[0], util::optional<common::DataEpoch>(), componentsDst[0], util::optional<common::DataEpoch>(), context); for (const auto &op : resTmp) { auto opClone = op->shallowClone(); setCRSs(opClone.get(), sourceCRS, targetCRS); res.emplace_back(opClone); } } } // --------------------------------------------------------------------------- void CoordinateOperationFactory::Private::createOperationsBoundToCompound( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, Private::Context &context, const crs::BoundCRS *boundSrc, const crs::CompoundCRS *compoundDst, std::vector<CoordinateOperationNNPtr> &res) { const auto &authFactory = context.context->getAuthorityFactory(); const auto dbContext = authFactory ? authFactory->databaseContext().as_nullable() : nullptr; const auto &componentsDst = compoundDst->componentReferenceSystems(); // Case of BOUND[NAD83_3D,TOWGS84] to // COMPOUND[BOUND[NAD83_2D,TOWGS84],BOUND[VERT[NAVD88],HUB=NAD83_3D,GRID]] // ==> We can ignore the TOWGS84 BOUND aspect and just ask for // NAD83_3D to COMPOUND[NAD83_2D,BOUND[VERT[NAVD88],HUB=NAD83_3D,GRID]] if (componentsDst.size() >= 2) { auto srcGeogCRS = boundSrc->baseCRS()->extractGeodeticCRS(); auto compDst0BoundCrs = util::nn_dynamic_pointer_cast<crs::BoundCRS>(componentsDst[0]); auto compDst1BoundCrs = dynamic_cast<crs::BoundCRS *>(componentsDst[1].get()); if (srcGeogCRS && compDst0BoundCrs && compDst1BoundCrs) { auto compDst0Geog = compDst0BoundCrs->extractGeographicCRS(); auto compDst1Vert = dynamic_cast<const crs::VerticalCRS *>( compDst1BoundCrs->baseCRS().get()); auto compDst1BoundCrsHubCrsGeog = dynamic_cast<const crs::GeographicCRS *>( compDst1BoundCrs->hubCRS().get()); if (compDst1BoundCrsHubCrsGeog) { auto hubDst1Datum = compDst1BoundCrsHubCrsGeog->datumNonNull(dbContext); if (compDst0Geog && compDst1Vert && srcGeogCRS->datumNonNull(dbContext)->isEquivalentTo( hubDst1Datum.get(), util::IComparable::Criterion::EQUIVALENT) && compDst0Geog->datumNonNull(dbContext)->isEquivalentTo( hubDst1Datum.get(), util::IComparable::Criterion::EQUIVALENT)) { auto srcNew = boundSrc->baseCRS(); auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, compDst0BoundCrs->nameStr() + " + " + componentsDst[1]->nameStr()); auto dstNew = crs::CompoundCRS::create( properties, {NN_NO_CHECK(compDst0BoundCrs), componentsDst[1]}); auto tmpRes = createOperations( srcNew, util::optional<common::DataEpoch>(), dstNew, util::optional<common::DataEpoch>(), context); for (const auto &op : tmpRes) { auto opClone = op->shallowClone(); setCRSs(opClone.get(), sourceCRS, targetCRS); res.emplace_back(opClone); } return; } } } } if (!componentsDst.empty()) { auto compDst0BoundCrs = dynamic_cast<crs::BoundCRS *>(componentsDst[0].get()); if (compDst0BoundCrs) { auto boundSrcHubAsGeogCRS = dynamic_cast<crs::GeographicCRS *>(boundSrc->hubCRS().get()); auto compDst0BoundCrsHubAsGeogCRS = dynamic_cast<crs::GeographicCRS *>( compDst0BoundCrs->hubCRS().get()); if (boundSrcHubAsGeogCRS && compDst0BoundCrsHubAsGeogCRS) { const auto boundSrcHubAsGeogCRSDatum = boundSrcHubAsGeogCRS->datumNonNull(dbContext); const auto compDst0BoundCrsHubAsGeogCRSDatum = compDst0BoundCrsHubAsGeogCRS->datumNonNull(dbContext); if (boundSrcHubAsGeogCRSDatum->_isEquivalentTo( compDst0BoundCrsHubAsGeogCRSDatum.get())) { auto cs = cs::EllipsoidalCS:: createLatitudeLongitudeEllipsoidalHeight( common::UnitOfMeasure::DEGREE, common::UnitOfMeasure::METRE); auto intermGeog3DCRS = util::nn_static_pointer_cast< crs::CRS>(crs::GeographicCRS::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, boundSrcHubAsGeogCRS->nameStr()) .set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, metadata::Extent::WORLD), boundSrcHubAsGeogCRS->datum(), boundSrcHubAsGeogCRS->datumEnsemble(), cs)); auto sourceToGeog3DOps = createOperations( sourceCRS, util::optional<common::DataEpoch>(), intermGeog3DCRS, util::optional<common::DataEpoch>(), context); auto geog3DToTargetOps = createOperations( intermGeog3DCRS, util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); for (const auto &opSrc : sourceToGeog3DOps) { for (const auto &opDst : geog3DToTargetOps) { if (opSrc->targetCRS() && opDst->sourceCRS() && !opSrc->targetCRS()->_isEquivalentTo( opDst->sourceCRS().get())) { // Shouldn't happen normally, but typically // one of them can be 2D and the other 3D // due to above createOperations() not // exactly setting the expected source and // target CRS. // So create an adapter operation... auto intermOps = createOperations( NN_NO_CHECK(opSrc->targetCRS()), util::optional<common::DataEpoch>(), NN_NO_CHECK(opDst->sourceCRS()), util::optional<common::DataEpoch>(), context); if (!intermOps.empty()) { res.emplace_back( ConcatenatedOperation:: createComputeMetadata( {opSrc, intermOps.front(), opDst}, disallowEmptyIntersection)); } } else { res.emplace_back( ConcatenatedOperation:: createComputeMetadata( {opSrc, opDst}, disallowEmptyIntersection)); } } } return; } } } // e.g transforming from a Bound[something_not_WGS84_but_with_TOWGS84] // to a CompoundCRS[WGS84, ...] const auto srcBaseSingleCRS = dynamic_cast<const crs::SingleCRS *>(boundSrc->baseCRS().get()); const auto srcGeogCRS = boundSrc->extractGeographicCRS(); const auto boundSrcHubAsGeogCRS = dynamic_cast<const crs::GeographicCRS *>(boundSrc->hubCRS().get()); const auto comp0Geog = componentsDst[0]->extractGeographicCRS(); if (srcBaseSingleCRS && srcBaseSingleCRS->coordinateSystem()->axisList().size() == 3 && srcGeogCRS && boundSrcHubAsGeogCRS && comp0Geog && boundSrcHubAsGeogCRS->coordinateSystem()->axisList().size() == 3 && !srcGeogCRS->datumNonNull(dbContext)->isEquivalentTo( comp0Geog->datumNonNull(dbContext).get(), util::IComparable::Criterion::EQUIVALENT) && boundSrcHubAsGeogCRS && boundSrcHubAsGeogCRS->datumNonNull(dbContext)->isEquivalentTo( comp0Geog->datumNonNull(dbContext).get(), util::IComparable::Criterion::EQUIVALENT)) { const auto ops1 = createOperations(sourceCRS, util::optional<common::DataEpoch>(), boundSrc->hubCRS(), util::optional<common::DataEpoch>(), context); const auto ops2 = createOperations( boundSrc->hubCRS(), util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); for (const auto &op1 : ops1) { for (const auto &op2 : ops2) { try { res.emplace_back( ConcatenatedOperation::createComputeMetadata( {op1, op2}, disallowEmptyIntersection)); } catch (const std::exception &) { } } } if (!res.empty()) { return; } } } // There might be better things to do, but for now just ignore the // transformation of the bound CRS res = createOperations(boundSrc->baseCRS(), util::optional<common::DataEpoch>(), targetCRS, util::optional<common::DataEpoch>(), context); } //! @endcond // --------------------------------------------------------------------------- /** \brief Find a list of CoordinateOperation from sourceCRS to targetCRS. * * The operations are sorted with the most relevant ones first: by * descending * area (intersection of the transformation area with the area of interest, * or intersection of the transformation with the area of use of the CRS), * and * by increasing accuracy. Operations with unknown accuracy are sorted last, * whatever their area. * * When one of the source or target CRS has a vertical component but not the * other one, the one that has no vertical component is automatically promoted * to a 3D version, where its vertical axis is the ellipsoidal height in metres, * using the ellipsoid of the base geodetic CRS. * * @param sourceCRS source CRS. * @param targetCRS target CRS. * @param context Search context. * @return a list */ std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::createOperations( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const CoordinateOperationContextNNPtr &context) const { #ifdef TRACE_CREATE_OPERATIONS ENTER_FUNCTION(); #endif // Look if we are called on CRS that have a link to a 'canonical' // BoundCRS // If so, use that one as input const auto &srcBoundCRS = sourceCRS->canonicalBoundCRS(); const auto &targetBoundCRS = targetCRS->canonicalBoundCRS(); auto l_sourceCRS = srcBoundCRS ? NN_NO_CHECK(srcBoundCRS) : sourceCRS; auto l_targetCRS = targetBoundCRS ? NN_NO_CHECK(targetBoundCRS) : targetCRS; const auto &authFactory = context->getAuthorityFactory(); metadata::ExtentPtr sourceCRSExtent; auto l_resolvedSourceCRS = crs::CRS::getResolvedCRS(l_sourceCRS, authFactory, sourceCRSExtent); metadata::ExtentPtr targetCRSExtent; auto l_resolvedTargetCRS = crs::CRS::getResolvedCRS(l_targetCRS, authFactory, targetCRSExtent); if (context->getSourceAndTargetCRSExtentUse() == CoordinateOperationContext::SourceTargetCRSExtentUse::NONE) { // Make sure *not* to use CRS extent if requested to ignore it sourceCRSExtent.reset(); targetCRSExtent.reset(); } Private::Context contextPrivate(sourceCRSExtent, targetCRSExtent, context); if (context->getSourceAndTargetCRSExtentUse() == CoordinateOperationContext::SourceTargetCRSExtentUse::INTERSECTION) { if (sourceCRSExtent && targetCRSExtent && !sourceCRSExtent->intersects(NN_NO_CHECK(targetCRSExtent))) { return std::vector<CoordinateOperationNNPtr>(); } } auto resFiltered = filterAndSort( Private::createOperations( l_resolvedSourceCRS, context->getSourceCoordinateEpoch(), l_resolvedTargetCRS, context->getTargetCoordinateEpoch(), contextPrivate), context, sourceCRSExtent, targetCRSExtent); if (context->getSourceCoordinateEpoch().has_value() || context->getTargetCoordinateEpoch().has_value()) { std::vector<CoordinateOperationNNPtr> res; res.reserve(resFiltered.size()); for (const auto &op : resFiltered) { auto opClone = op->shallowClone(); opClone->setSourceCoordinateEpoch( context->getSourceCoordinateEpoch()); opClone->setTargetCoordinateEpoch( context->getTargetCoordinateEpoch()); res.emplace_back(opClone); } return res; } return resFiltered; } // --------------------------------------------------------------------------- /** \brief Find a list of CoordinateOperation from a source coordinate metadata * to targetCRS. * @param sourceCoordinateMetadata source CoordinateMetadata. * @param targetCRS target CRS. * @param context Search context. * @return a list * @since 9.2 */ std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::createOperations( const coordinates::CoordinateMetadataNNPtr &sourceCoordinateMetadata, const crs::CRSNNPtr &targetCRS, const CoordinateOperationContextNNPtr &context) const { auto newContext = context->clone(); newContext->setSourceCoordinateEpoch( sourceCoordinateMetadata->coordinateEpoch()); return createOperations(sourceCoordinateMetadata->crs(), targetCRS, newContext); } // --------------------------------------------------------------------------- /** \brief Find a list of CoordinateOperation from a source CRS to a target * coordinate metadata. * @param sourceCRS source CRS. * @param targetCoordinateMetadata target CoordinateMetadata. * @param context Search context. * @return a list * @since 9.2 */ std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::createOperations( const crs::CRSNNPtr &sourceCRS, const coordinates::CoordinateMetadataNNPtr &targetCoordinateMetadata, const CoordinateOperationContextNNPtr &context) const { auto newContext = context->clone(); newContext->setTargetCoordinateEpoch( targetCoordinateMetadata->coordinateEpoch()); return createOperations(sourceCRS, targetCoordinateMetadata->crs(), newContext); } // --------------------------------------------------------------------------- /** \brief Find a list of CoordinateOperation from a source coordinate metadata * to a target coordinate metadata. * * Both source_crs and target_crs can be a CoordinateMetadata * with an associated coordinate epoch, to perform changes of coordinate epochs. * Note however than this is in practice limited to use of velocity grids inside * the same dynamic CRS. * * @param sourceCoordinateMetadata source CoordinateMetadata. * @param targetCoordinateMetadata target CoordinateMetadata. * @param context Search context. * @return a list * @since 9.4 */ std::vector<CoordinateOperationNNPtr> CoordinateOperationFactory::createOperations( const coordinates::CoordinateMetadataNNPtr &sourceCoordinateMetadata, const coordinates::CoordinateMetadataNNPtr &targetCoordinateMetadata, const CoordinateOperationContextNNPtr &context) const { auto newContext = context->clone(); newContext->setSourceCoordinateEpoch( sourceCoordinateMetadata->coordinateEpoch()); newContext->setTargetCoordinateEpoch( targetCoordinateMetadata->coordinateEpoch()); return createOperations(sourceCoordinateMetadata->crs(), targetCoordinateMetadata->crs(), newContext); } // --------------------------------------------------------------------------- /** \brief Instantiate a CoordinateOperationFactory. */ CoordinateOperationFactoryNNPtr CoordinateOperationFactory::create() { return NN_NO_CHECK( CoordinateOperationFactory::make_unique<CoordinateOperationFactory>()); } // --------------------------------------------------------------------------- } // namespace operation namespace crs { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress crs::CRSNNPtr CRS::getResolvedCRS(const crs::CRSNNPtr &crs, const io::AuthorityFactoryPtr &authFactory, metadata::ExtentPtr &extentOut) { if (crs->hasOver()) { return crs; } const auto &ids = crs->identifiers(); const auto &name = crs->nameStr(); bool approxExtent; extentOut = operation::getExtentPossiblySynthetized(crs, approxExtent); // We try to "identify" the provided CRS with the ones of the database, // but in a more restricted way that what identify() does. // If we get a match from id in priority, and from name as a fallback, and // that they are equivalent to the input CRS, then use the identified CRS. // Even if they aren't equivalent, we update extentOut with the one of the // identified CRS if our input one is absent/not reliable. const auto tryToIdentifyByName = [&crs, &name, &authFactory, approxExtent, &extentOut](io::AuthorityFactory::ObjectType objectType) { if (name != "unknown" && name != "unnamed") { auto matches = authFactory->createObjectsFromName( name, {objectType}, false, 2); if (matches.size() == 1) { const auto match = util::nn_static_pointer_cast<crs::CRS>(matches.front()); if (approxExtent || !extentOut) { extentOut = operation::getExtent(match); } if (match->isEquivalentTo( crs.get(), util::IComparable::Criterion::EQUIVALENT)) { return match; } } } return crs; }; auto geogCRS = dynamic_cast<crs::GeographicCRS *>(crs.get()); if (geogCRS && authFactory) { if (!ids.empty()) { const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), *ids.front()->codeSpace()); try { auto resolvedCrs( tmpAuthFactory->createGeographicCRS(ids.front()->code())); if (approxExtent || !extentOut) { extentOut = operation::getExtent(resolvedCrs); } if (resolvedCrs->isEquivalentTo( crs.get(), util::IComparable::Criterion::EQUIVALENT)) { return util::nn_static_pointer_cast<crs::CRS>(resolvedCrs); } } catch (const std::exception &) { } } else { return tryToIdentifyByName( geogCRS->coordinateSystem()->axisList().size() == 2 ? io::AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS : io::AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS); } } auto projectedCrs = dynamic_cast<crs::ProjectedCRS *>(crs.get()); if (projectedCrs && authFactory) { if (!ids.empty()) { const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), *ids.front()->codeSpace()); try { auto resolvedCrs( tmpAuthFactory->createProjectedCRS(ids.front()->code())); if (approxExtent || !extentOut) { extentOut = operation::getExtent(resolvedCrs); } if (resolvedCrs->isEquivalentTo( crs.get(), util::IComparable::Criterion::EQUIVALENT)) { return util::nn_static_pointer_cast<crs::CRS>(resolvedCrs); } } catch (const std::exception &) { } } else { return tryToIdentifyByName( io::AuthorityFactory::ObjectType::PROJECTED_CRS); } } auto compoundCrs = dynamic_cast<crs::CompoundCRS *>(crs.get()); if (compoundCrs && authFactory) { if (!ids.empty()) { const auto tmpAuthFactory = io::AuthorityFactory::create( authFactory->databaseContext(), *ids.front()->codeSpace()); try { auto resolvedCrs( tmpAuthFactory->createCompoundCRS(ids.front()->code())); if (approxExtent || !extentOut) { extentOut = operation::getExtent(resolvedCrs); } if (resolvedCrs->isEquivalentTo( crs.get(), util::IComparable::Criterion::EQUIVALENT)) { return util::nn_static_pointer_cast<crs::CRS>(resolvedCrs); } } catch (const std::exception &) { } } else { auto outCrs = tryToIdentifyByName( io::AuthorityFactory::ObjectType::COMPOUND_CRS); const auto &components = compoundCrs->componentReferenceSystems(); if (outCrs.get() != crs.get()) { bool hasGeoid = false; if (components.size() == 2) { auto vertCRS = dynamic_cast<crs::VerticalCRS *>(components[1].get()); if (vertCRS && !vertCRS->geoidModel().empty()) { hasGeoid = true; } } if (!hasGeoid) { return outCrs; } } if (approxExtent || !extentOut) { // If we still did not get a reliable extent, then try to // resolve the components of the compoundCRS, and take the // intersection of their extent. extentOut = metadata::ExtentPtr(); for (const auto &component : components) { metadata::ExtentPtr componentExtent; getResolvedCRS(component, authFactory, componentExtent); if (extentOut && componentExtent) extentOut = extentOut->intersection( NN_NO_CHECK(componentExtent)); else if (componentExtent) extentOut = std::move(componentExtent); } } } } return crs; } //! @endcond } // namespace crs NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/esriparammappings.cpp
// This file was generated by scripts/build_esri_projection_mapping.py. DO NOT // EDIT ! /****************************************************************************** * * Project: PROJ * Purpose: Mappings between ESRI projection and parameters names and WKT2 * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2019, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "esriparammappings.hpp" #include "proj_constants.h" #include "proj/internal/internal.hpp" NS_PROJ_START using namespace internal; namespace operation { //! @cond Doxygen_Suppress const ESRIParamMapping paramsESRI_Plate_Carree[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; const ESRIParamMapping paramsESRI_Equidistant_Cylindrical[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Miller_Cylindrical[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Mercator[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; const ESRIParamMapping paramsESRI_Gauss_Kruger[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; const ESRIParamMapping paramsESRI_Transverse_Mercator[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Transverse_Mercator_Complex[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Albers[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {"Standard_Parallel_2", EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Sinusoidal[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Mollweide[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Eckert_I[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Eckert_II[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Eckert_III[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Eckert_IV[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Eckert_V[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Eckert_VI[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Gall_Stereographic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Behrmann[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", true}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "30.0", true}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Winkel_I[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Winkel_II[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Lambert_Conformal_Conic_alt1[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Lambert_Conformal_Conic_alt2[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {"Standard_Parallel_2", EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Lambert_Conformal_Conic_alt3[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {"Standard_Parallel_2", EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, "0.0", false}, {"Scale_Factor", nullptr, 0, "1.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Lambert_Conformal_Conic_alt4[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {"Standard_Parallel_2", EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_ELLIPSOID_SCALE_FACTOR, EPSG_CODE_PARAMETER_ELLIPSOID_SCALE_FACTOR, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Polyconic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Quartic_Authalic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Loximuthal[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Central_Parallel", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Bonne[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Hotine_Oblique_Mercator_Two_Point_Natural_Origin[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE, "0.0", false}, {"Latitude_Of_1st_Point", "Latitude of 1st point", 0, "0.0", false}, {"Latitude_Of_2nd_Point", "Latitude of 2nd point", 0, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, "0.0", false}, {"Longitude_Of_1st_Point", "Longitude of 1st point", 0, "0.0", false}, {"Longitude_Of_2nd_Point", "Longitude of 2nd point", 0, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Stereographic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Polar_Stereographic_Variant_A[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Equidistant_Conic[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {"Standard_Parallel_2", EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Cassini[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", nullptr, 0, "1.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Van_der_Grinten_I[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Robinson[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Two_Point_Equidistant[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Latitude_Of_1st_Point", "Latitude of 1st point", 0, "0.0", false}, {"Latitude_Of_2nd_Point", "Latitude of 2nd point", 0, "0.0", false}, {"Longitude_Of_1st_Point", "Longitude of 1st point", 0, "0.0", false}, {"Longitude_Of_2nd_Point", "Longitude of 2nd point", 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Azimuthal_Equidistant[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Lambert_Azimuthal_Equal_Area[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Cylindrical_Equal_Area[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Hotine_Oblique_Mercator_Two_Point_Center[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE, "0.0", false}, {"Latitude_Of_1st_Point", "Latitude of 1st point", 0, "0.0", false}, {"Latitude_Of_2nd_Point", "Latitude of 2nd point", 0, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, "0.0", false}, {"Longitude_Of_1st_Point", "Longitude of 1st point", 0, "0.0", false}, {"Longitude_Of_2nd_Point", "Longitude of 2nd point", 0, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; const ESRIParamMapping paramsESRI_Hotine_Oblique_Mercator_Azimuth_Natural_Origin[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, "0.0", false}, {"Azimuth", EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; const ESRIParamMapping paramsESRI_Hotine_Oblique_Mercator_Azimuth_Center[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, "0.0", false}, {"Azimuth", EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Double_Stereographic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Krovak_alt1[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Pseudo_Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, "0.0", false}, {"Azimuth", EPSG_NAME_PARAMETER_COLATITUDE_CONE_AXIS, EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {"X_Scale", nullptr, 0, "1.0", false}, {"Y_Scale", nullptr, 0, "1.0", false}, {"XY_Plane_Rotation", nullptr, 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Krovak_alt2[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Pseudo_Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, "0.0", false}, {"Azimuth", EPSG_NAME_PARAMETER_COLATITUDE_CONE_AXIS, EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {"X_Scale", nullptr, 0, "-1.0", false}, {"Y_Scale", nullptr, 0, "1.0", false}, {"XY_Plane_Rotation", nullptr, 0, "90.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_New_Zealand_Map_Grid[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Longitude_Of_Origin", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Orthographic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Local[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Scale_Factor", nullptr, 0, "1.0", false}, {"Azimuth", nullptr, 0, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Winkel_Tripel[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Aitoff[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Flat_Polar_Quartic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Craster_Parabolic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Gnomonic[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Times[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Vertical_Near_Side_Perspective[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN, "0.0", false}, {"Height", EPSG_NAME_PARAMETER_VIEWPOINT_HEIGHT, EPSG_CODE_PARAMETER_VIEWPOINT_HEIGHT, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Stereographic_North_Pole[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Stereographic_South_Pole[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; const ESRIParamMapping paramsESRI_Rectified_Skew_Orthomorphic_Natural_Origin[] = {{"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, "0.0", false}, {"Azimuth", EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {"XY_Plane_Rotation", EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; const ESRIParamMapping paramsESRI_Rectified_Skew_Orthomorphic_Center[] = { {"False_Easting", EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, "0.0", false}, {"Azimuth", EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {"XY_Plane_Rotation", EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Goode_Homolosine_alt1[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Option", nullptr, 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Goode_Homolosine_alt2[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Option", nullptr, 0, "1.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Goode_Homolosine_alt3[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Option", nullptr, 0, "2.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Equidistant_Cylindrical_Ellipsoidal[] = {{"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Laborde_Oblique_Mercator[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, "0.0", false}, {"Azimuth", EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Gnomonic_Ellipsoidal[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Wagner_IV[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", nullptr, 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Wagner_V[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Wagner_VII[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Natural_Earth[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Natural_Earth_II[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Patterson[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Compact_Miller[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Geostationary_Satellite[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Height", "Satellite Height", 0, "0.0", false}, {"Option", nullptr, 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Mercator_Auxiliary_Sphere[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Auxiliary_Sphere_Type", nullptr, 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Mercator_Variant_A[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Mercator_Variant_C[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Standard_Parallel_1", EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, "0.0", false}, {"Latitude_Of_Origin", nullptr, 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Transverse_Cylindrical_Equal_Area[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_IGAC_Plano_Cartesiano[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Longitude_Of_Center", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Center", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Height", EPSG_NAME_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT, EPSG_CODE_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Equal_Earth[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Peirce_Quincuncial_alt1[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Option", nullptr, 0, "0.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIParamMapping paramsESRI_Peirce_Quincuncial_alt2[] = { {"False_Easting", EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, "0.0", false}, {"False_Northing", EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, "0.0", false}, {"Central_Meridian", EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Scale_Factor", EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, "0.0", false}, {"Latitude_Of_Origin", EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, "0.0", false}, {"Option", nullptr, 0, "1.0", false}, {nullptr, nullptr, 0, "0.0", false}}; static const ESRIMethodMapping esriMappings[] = { {"Plate_Carree", EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL, paramsESRI_Plate_Carree}, {"Plate_Carree", EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL, paramsESRI_Plate_Carree}, {"Equidistant_Cylindrical", EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL, paramsESRI_Equidistant_Cylindrical}, {"Miller_Cylindrical", PROJ_WKT2_NAME_METHOD_MILLER_CYLINDRICAL, 0, paramsESRI_Miller_Cylindrical}, {"Mercator", EPSG_NAME_METHOD_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, paramsESRI_Mercator}, {"Gauss_Kruger", EPSG_NAME_METHOD_TRANSVERSE_MERCATOR, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR, paramsESRI_Gauss_Kruger}, {"Transverse_Mercator", EPSG_NAME_METHOD_TRANSVERSE_MERCATOR, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR, paramsESRI_Transverse_Mercator}, {"Transverse_Mercator_Complex", EPSG_NAME_METHOD_TRANSVERSE_MERCATOR, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR, paramsESRI_Transverse_Mercator_Complex}, {"Albers", EPSG_NAME_METHOD_ALBERS_EQUAL_AREA, EPSG_CODE_METHOD_ALBERS_EQUAL_AREA, paramsESRI_Albers}, {"Sinusoidal", PROJ_WKT2_NAME_METHOD_SINUSOIDAL, 0, paramsESRI_Sinusoidal}, {"Mollweide", PROJ_WKT2_NAME_METHOD_MOLLWEIDE, 0, paramsESRI_Mollweide}, {"Eckert_I", PROJ_WKT2_NAME_METHOD_ECKERT_I, 0, paramsESRI_Eckert_I}, {"Eckert_II", PROJ_WKT2_NAME_METHOD_ECKERT_II, 0, paramsESRI_Eckert_II}, {"Eckert_III", PROJ_WKT2_NAME_METHOD_ECKERT_III, 0, paramsESRI_Eckert_III}, {"Eckert_IV", PROJ_WKT2_NAME_METHOD_ECKERT_IV, 0, paramsESRI_Eckert_IV}, {"Eckert_V", PROJ_WKT2_NAME_METHOD_ECKERT_V, 0, paramsESRI_Eckert_V}, {"Eckert_VI", PROJ_WKT2_NAME_METHOD_ECKERT_VI, 0, paramsESRI_Eckert_VI}, {"Gall_Stereographic", PROJ_WKT2_NAME_METHOD_GALL_STEREOGRAPHIC, 0, paramsESRI_Gall_Stereographic}, {"Behrmann", EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, paramsESRI_Behrmann}, {"Winkel_I", "Winkel I", 0, paramsESRI_Winkel_I}, {"Winkel_II", "Winkel II", 0, paramsESRI_Winkel_II}, {"Lambert_Conformal_Conic", EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_1SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP, paramsESRI_Lambert_Conformal_Conic_alt1}, {"Lambert_Conformal_Conic", EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, paramsESRI_Lambert_Conformal_Conic_alt2}, {"Lambert_Conformal_Conic", EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, paramsESRI_Lambert_Conformal_Conic_alt3}, {"Lambert_Conformal_Conic", EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN, paramsESRI_Lambert_Conformal_Conic_alt4}, {"Polyconic", EPSG_NAME_METHOD_AMERICAN_POLYCONIC, EPSG_CODE_METHOD_AMERICAN_POLYCONIC, paramsESRI_Polyconic}, {"Quartic_Authalic", "Quartic Authalic", 0, paramsESRI_Quartic_Authalic}, {"Loximuthal", "Loximuthal", 0, paramsESRI_Loximuthal}, {"Bonne", EPSG_NAME_METHOD_BONNE, EPSG_CODE_METHOD_BONNE, paramsESRI_Bonne}, {"Hotine_Oblique_Mercator_Two_Point_Natural_Origin", PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN, 0, paramsESRI_Hotine_Oblique_Mercator_Two_Point_Natural_Origin}, {"Stereographic", PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC, 0, paramsESRI_Stereographic}, {"Polar_Stereographic_Variant_A", EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A, paramsESRI_Polar_Stereographic_Variant_A}, {"Equidistant_Conic", PROJ_WKT2_NAME_METHOD_EQUIDISTANT_CONIC, 0, paramsESRI_Equidistant_Conic}, {"Cassini", EPSG_NAME_METHOD_CASSINI_SOLDNER, EPSG_CODE_METHOD_CASSINI_SOLDNER, paramsESRI_Cassini}, {"Van_der_Grinten_I", PROJ_WKT2_NAME_METHOD_VAN_DER_GRINTEN, 0, paramsESRI_Van_der_Grinten_I}, {"Robinson", PROJ_WKT2_NAME_METHOD_ROBINSON, 0, paramsESRI_Robinson}, {"Two_Point_Equidistant", PROJ_WKT2_NAME_METHOD_TWO_POINT_EQUIDISTANT, 0, paramsESRI_Two_Point_Equidistant}, {"Azimuthal_Equidistant", EPSG_NAME_METHOD_AZIMUTHAL_EQUIDISTANT, EPSG_CODE_METHOD_AZIMUTHAL_EQUIDISTANT, paramsESRI_Azimuthal_Equidistant}, {"Lambert_Azimuthal_Equal_Area", EPSG_NAME_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA, EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA, paramsESRI_Lambert_Azimuthal_Equal_Area}, {"Cylindrical_Equal_Area", EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, paramsESRI_Cylindrical_Equal_Area}, {"Hotine_Oblique_Mercator_Two_Point_Center", PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN, 0, paramsESRI_Hotine_Oblique_Mercator_Two_Point_Center}, {"Hotine_Oblique_Mercator_Azimuth_Natural_Origin", EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, paramsESRI_Hotine_Oblique_Mercator_Azimuth_Natural_Origin}, {"Hotine_Oblique_Mercator_Azimuth_Center", EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, paramsESRI_Hotine_Oblique_Mercator_Azimuth_Center}, {"Double_Stereographic", EPSG_NAME_METHOD_OBLIQUE_STEREOGRAPHIC, EPSG_CODE_METHOD_OBLIQUE_STEREOGRAPHIC, paramsESRI_Double_Stereographic}, {"Krovak", EPSG_NAME_METHOD_KROVAK, EPSG_CODE_METHOD_KROVAK, paramsESRI_Krovak_alt1}, {"Krovak", EPSG_NAME_METHOD_KROVAK_NORTH_ORIENTED, EPSG_CODE_METHOD_KROVAK_NORTH_ORIENTED, paramsESRI_Krovak_alt2}, {"New_Zealand_Map_Grid", EPSG_NAME_METHOD_NZMG, EPSG_CODE_METHOD_NZMG, paramsESRI_New_Zealand_Map_Grid}, {"Orthographic", PROJ_WKT2_NAME_ORTHOGRAPHIC_SPHERICAL, 0, paramsESRI_Orthographic}, {"Local", EPSG_NAME_METHOD_ORTHOGRAPHIC, EPSG_CODE_METHOD_ORTHOGRAPHIC, paramsESRI_Local}, {"Winkel_Tripel", "Winkel Tripel", 0, paramsESRI_Winkel_Tripel}, {"Aitoff", "Aitoff", 0, paramsESRI_Aitoff}, {"Flat_Polar_Quartic", PROJ_WKT2_NAME_METHOD_FLAT_POLAR_QUARTIC, 0, paramsESRI_Flat_Polar_Quartic}, {"Craster_Parabolic", "Craster Parabolic", 0, paramsESRI_Craster_Parabolic}, {"Gnomonic", PROJ_WKT2_NAME_METHOD_GNOMONIC, 0, paramsESRI_Gnomonic}, {"Times", PROJ_WKT2_NAME_METHOD_TIMES, 0, paramsESRI_Times}, {"Vertical_Near_Side_Perspective", EPSG_NAME_METHOD_VERTICAL_PERSPECTIVE, EPSG_CODE_METHOD_VERTICAL_PERSPECTIVE, paramsESRI_Vertical_Near_Side_Perspective}, {"Stereographic_North_Pole", EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, paramsESRI_Stereographic_North_Pole}, {"Stereographic_South_Pole", EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, paramsESRI_Stereographic_South_Pole}, {"Rectified_Skew_Orthomorphic_Natural_Origin", EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, paramsESRI_Rectified_Skew_Orthomorphic_Natural_Origin}, {"Rectified_Skew_Orthomorphic_Center", EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, paramsESRI_Rectified_Skew_Orthomorphic_Center}, {"Goode_Homolosine", PROJ_WKT2_NAME_METHOD_GOODE_HOMOLOSINE, 0, paramsESRI_Goode_Homolosine_alt1}, {"Goode_Homolosine", PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE, 0, paramsESRI_Goode_Homolosine_alt2}, {"Goode_Homolosine", PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE_OCEAN, 0, paramsESRI_Goode_Homolosine_alt3}, {"Equidistant_Cylindrical_Ellipsoidal", EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL, paramsESRI_Equidistant_Cylindrical_Ellipsoidal}, {"Laborde_Oblique_Mercator", EPSG_NAME_METHOD_LABORDE_OBLIQUE_MERCATOR, EPSG_CODE_METHOD_LABORDE_OBLIQUE_MERCATOR, paramsESRI_Laborde_Oblique_Mercator}, {"Gnomonic_Ellipsoidal", PROJ_WKT2_NAME_METHOD_GNOMONIC, 0, paramsESRI_Gnomonic_Ellipsoidal}, {"Wagner_IV", PROJ_WKT2_NAME_METHOD_WAGNER_IV, 0, paramsESRI_Wagner_IV}, {"Wagner_V", PROJ_WKT2_NAME_METHOD_WAGNER_V, 0, paramsESRI_Wagner_V}, {"Wagner_VII", PROJ_WKT2_NAME_METHOD_WAGNER_VII, 0, paramsESRI_Wagner_VII}, {"Natural_Earth", PROJ_WKT2_NAME_METHOD_NATURAL_EARTH, 0, paramsESRI_Natural_Earth}, {"Natural_Earth_II", PROJ_WKT2_NAME_METHOD_NATURAL_EARTH_II, 0, paramsESRI_Natural_Earth_II}, {"Patterson", PROJ_WKT2_NAME_METHOD_PATTERSON, 0, paramsESRI_Patterson}, {"Compact_Miller", PROJ_WKT2_NAME_METHOD_COMPACT_MILLER, 0, paramsESRI_Compact_Miller}, {"Geostationary_Satellite", PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y, 0, paramsESRI_Geostationary_Satellite}, {"Mercator_Auxiliary_Sphere", EPSG_NAME_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR, EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR, paramsESRI_Mercator_Auxiliary_Sphere}, {"Mercator_Variant_A", EPSG_NAME_METHOD_MERCATOR_VARIANT_A, EPSG_CODE_METHOD_MERCATOR_VARIANT_A, paramsESRI_Mercator_Variant_A}, {"Mercator_Variant_C", EPSG_NAME_METHOD_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, paramsESRI_Mercator_Variant_C}, {"Transverse_Cylindrical_Equal_Area", "Transverse Cylindrical Equal Area", 0, paramsESRI_Transverse_Cylindrical_Equal_Area}, {"IGAC_Plano_Cartesiano", EPSG_NAME_METHOD_COLOMBIA_URBAN, EPSG_CODE_METHOD_COLOMBIA_URBAN, paramsESRI_IGAC_Plano_Cartesiano}, {"Equal_Earth", EPSG_NAME_METHOD_EQUAL_EARTH, EPSG_CODE_METHOD_EQUAL_EARTH, paramsESRI_Equal_Earth}, {"Peirce_Quincuncial", PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_SQUARE, 0, paramsESRI_Peirce_Quincuncial_alt1}, {"Peirce_Quincuncial", PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_DIAMOND, 0, paramsESRI_Peirce_Quincuncial_alt2}, }; // --------------------------------------------------------------------------- const ESRIMethodMapping *getEsriMappings(size_t &nElts) { nElts = sizeof(esriMappings) / sizeof(esriMappings[0]); return esriMappings; } // --------------------------------------------------------------------------- std::vector<const ESRIMethodMapping *> getMappingsFromESRI(const std::string &esri_name) { std::vector<const ESRIMethodMapping *> res; for (const auto &mapping : esriMappings) { if (ci_equal(esri_name, mapping.esri_name)) { res.push_back(&mapping); } } return res; } //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/oputils.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include <string.h> #include "proj/coordinateoperation.hpp" #include "proj/crs.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "oputils.hpp" #include "parammappings.hpp" #include "proj_constants.h" // --------------------------------------------------------------------------- NS_PROJ_START using namespace internal; namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const char *BALLPARK_GEOCENTRIC_TRANSLATION = "Ballpark geocentric translation"; const char *NULL_GEOGRAPHIC_OFFSET = "Null geographic offset"; const char *NULL_GEOCENTRIC_TRANSLATION = "Null geocentric translation"; const char *BALLPARK_GEOGRAPHIC_OFFSET = "Ballpark geographic offset"; const char *BALLPARK_VERTICAL_TRANSFORMATION = "ballpark vertical transformation"; const char *BALLPARK_VERTICAL_TRANSFORMATION_NO_ELLIPSOID_VERT_HEIGHT = "ballpark vertical transformation, without ellipsoid height to vertical " "height correction"; // --------------------------------------------------------------------------- OperationParameterNNPtr createOpParamNameEPSGCode(int code) { const char *name = OperationParameter::getNameForEPSGCode(code); assert(name); return OperationParameter::create(createMapNameEPSGCode(name, code)); } // --------------------------------------------------------------------------- util::PropertyMap createMethodMapNameEPSGCode(int code) { const char *name = nullptr; size_t nMethodNameCodes = 0; const auto methodNameCodes = getMethodNameCodes(nMethodNameCodes); for (size_t i = 0; i < nMethodNameCodes; ++i) { const auto &tuple = methodNameCodes[i]; if (tuple.epsg_code == code) { name = tuple.name; break; } } assert(name); return createMapNameEPSGCode(name, code); } // --------------------------------------------------------------------------- util::PropertyMap createMapNameEPSGCode(const std::string &name, int code) { return util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, code); } // --------------------------------------------------------------------------- util::PropertyMap createMapNameEPSGCode(const char *name, int code) { return util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, name) .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, code); } // --------------------------------------------------------------------------- util::PropertyMap &addDomains(util::PropertyMap &map, const common::ObjectUsage *obj) { auto ar = util::ArrayOfBaseObject::create(); for (const auto &domain : obj->domains()) { ar->add(domain); } if (!ar->empty()) { map.set(common::ObjectUsage::OBJECT_DOMAIN_KEY, ar); } return map; } // --------------------------------------------------------------------------- static const char *getCRSQualifierStr(const crs::CRSPtr &crs) { auto geod = dynamic_cast<crs::GeodeticCRS *>(crs.get()); if (geod) { if (geod->isGeocentric()) { return " (geocentric)"; } auto geog = dynamic_cast<crs::GeographicCRS *>(geod); if (geog) { if (geog->coordinateSystem()->axisList().size() == 2) { return " (geog2D)"; } else { return " (geog3D)"; } } } return ""; } // --------------------------------------------------------------------------- std::string buildOpName(const char *opType, const crs::CRSPtr &source, const crs::CRSPtr &target) { std::string res(opType); const auto &srcName = source->nameStr(); const auto &targetName = target->nameStr(); const char *srcQualifier = ""; const char *targetQualifier = ""; if (srcName == targetName) { srcQualifier = getCRSQualifierStr(source); targetQualifier = getCRSQualifierStr(target); if (strcmp(srcQualifier, targetQualifier) == 0) { srcQualifier = ""; targetQualifier = ""; } } res += " from "; res += srcName; res += srcQualifier; res += " to "; res += targetName; res += targetQualifier; return res; } // --------------------------------------------------------------------------- void addModifiedIdentifier(util::PropertyMap &map, const common::IdentifiedObject *obj, bool inverse, bool derivedFrom) { // If original operation is AUTH:CODE, then assign INVERSE(AUTH):CODE // as identifier. auto ar = util::ArrayOfBaseObject::create(); for (const auto &idSrc : obj->identifiers()) { auto authName = *(idSrc->codeSpace()); const auto &srcCode = idSrc->code(); if (derivedFrom) { authName = concat("DERIVED_FROM(", authName, ")"); } if (inverse) { if (starts_with(authName, "INVERSE(") && authName.back() == ')') { authName = authName.substr(strlen("INVERSE(")); authName.resize(authName.size() - 1); } else { authName = concat("INVERSE(", authName, ")"); } } auto idsProp = util::PropertyMap().set( metadata::Identifier::CODESPACE_KEY, authName); ar->add(metadata::Identifier::create(srcCode, idsProp)); } if (!ar->empty()) { map.set(common::IdentifiedObject::IDENTIFIERS_KEY, ar); } } // --------------------------------------------------------------------------- util::PropertyMap createPropertiesForInverse(const OperationMethodNNPtr &method) { util::PropertyMap map; const std::string &forwardName = method->nameStr(); if (!forwardName.empty()) { if (starts_with(forwardName, INVERSE_OF)) { map.set(common::IdentifiedObject::NAME_KEY, forwardName.substr(INVERSE_OF.size())); } else { map.set(common::IdentifiedObject::NAME_KEY, INVERSE_OF + forwardName); } } addModifiedIdentifier(map, method.get(), true, false); return map; } // --------------------------------------------------------------------------- util::PropertyMap createPropertiesForInverse(const CoordinateOperation *op, bool derivedFrom, bool approximateInversion) { assert(op); util::PropertyMap map; // The domain(s) are unchanged by the inverse operation addDomains(map, op); const std::string &forwardName = op->nameStr(); // Forge a name for the inverse, either from the forward name, or // from the source and target CRS names const char *opType; if (starts_with(forwardName, BALLPARK_GEOCENTRIC_TRANSLATION)) { opType = BALLPARK_GEOCENTRIC_TRANSLATION; } else if (starts_with(forwardName, BALLPARK_GEOGRAPHIC_OFFSET)) { opType = BALLPARK_GEOGRAPHIC_OFFSET; } else if (starts_with(forwardName, NULL_GEOGRAPHIC_OFFSET)) { opType = NULL_GEOGRAPHIC_OFFSET; } else if (starts_with(forwardName, NULL_GEOCENTRIC_TRANSLATION)) { opType = NULL_GEOCENTRIC_TRANSLATION; } else if (dynamic_cast<const Transformation *>(op) || starts_with(forwardName, "Transformation from ")) { opType = "Transformation"; } else if (dynamic_cast<const Conversion *>(op)) { opType = "Conversion"; } else { opType = "Operation"; } auto sourceCRS = op->sourceCRS(); auto targetCRS = op->targetCRS(); std::string name; if (!forwardName.empty()) { if (dynamic_cast<const Transformation *>(op) == nullptr && dynamic_cast<const ConcatenatedOperation *>(op) == nullptr && (starts_with(forwardName, INVERSE_OF) || forwardName.find(" + ") != std::string::npos)) { std::vector<std::string> tokens; std::string curToken; bool inString = false; for (size_t i = 0; i < forwardName.size(); ++i) { if (inString) { curToken += forwardName[i]; if (forwardName[i] == '\'') { inString = false; } } else if (i + 3 < forwardName.size() && memcmp(&forwardName[i], " + ", 3) == 0) { tokens.push_back(curToken); curToken.clear(); i += 2; } else if (forwardName[i] == '\'') { inString = true; curToken += forwardName[i]; } else { curToken += forwardName[i]; } } if (!curToken.empty()) { tokens.push_back(curToken); } for (size_t i = tokens.size(); i > 0;) { i--; if (!name.empty()) { name += " + "; } if (starts_with(tokens[i], INVERSE_OF)) { name += tokens[i].substr(INVERSE_OF.size()); } else if (tokens[i] == AXIS_ORDER_CHANGE_2D_NAME || tokens[i] == AXIS_ORDER_CHANGE_3D_NAME) { name += tokens[i]; } else { name += INVERSE_OF + tokens[i]; } } } else if (!sourceCRS || !targetCRS || forwardName != buildOpName(opType, sourceCRS, targetCRS)) { if (forwardName.find(" + ") != std::string::npos) { name = INVERSE_OF + '\'' + forwardName + '\''; } else { name = INVERSE_OF + forwardName; } } } if (name.empty() && sourceCRS && targetCRS) { name = buildOpName(opType, targetCRS, sourceCRS); } if (approximateInversion) { name += " (approx. inversion)"; } if (!name.empty()) { map.set(common::IdentifiedObject::NAME_KEY, name); } const std::string &remarks = op->remarks(); if (!remarks.empty()) { map.set(common::IdentifiedObject::REMARKS_KEY, remarks); } addModifiedIdentifier(map, op, true, derivedFrom); const auto so = dynamic_cast<const SingleOperation *>(op); if (so) { const int soMethodEPSGCode = so->method()->getEPSGCode(); if (soMethodEPSGCode > 0) { map.set("OPERATION_METHOD_EPSG_CODE", soMethodEPSGCode); } } return map; } // --------------------------------------------------------------------------- util::PropertyMap addDefaultNameIfNeeded(const util::PropertyMap &properties, const std::string &defaultName) { if (!properties.get(common::IdentifiedObject::NAME_KEY)) { return util::PropertyMap(properties) .set(common::IdentifiedObject::NAME_KEY, defaultName); } else { return properties; } } // --------------------------------------------------------------------------- static std::string createEntryEqParam(const std::string &a, const std::string &b) { return a < b ? a + b : b + a; } static std::set<std::string> buildSetEquivalentParameters() { std::set<std::string> set; const char *const listOfEquivalentParameterNames[][7] = { {"latitude_of_point_1", "Latitude_Of_1st_Point", nullptr}, {"longitude_of_point_1", "Longitude_Of_1st_Point", nullptr}, {"latitude_of_point_2", "Latitude_Of_2nd_Point", nullptr}, {"longitude_of_point_2", "Longitude_Of_2nd_Point", nullptr}, {"satellite_height", "height", nullptr}, {EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, nullptr}, {EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, nullptr}, {EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, WKT1_SCALE_FACTOR, EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_NAME_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, nullptr}, {WKT1_LATITUDE_OF_ORIGIN, WKT1_LATITUDE_OF_CENTER, EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, "Central_Parallel", nullptr}, {WKT1_CENTRAL_MERIDIAN, WKT1_LONGITUDE_OF_CENTER, EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, nullptr}, {"pseudo_standard_parallel_1", WKT1_STANDARD_PARALLEL_1, nullptr}, }; for (const auto &paramList : listOfEquivalentParameterNames) { for (size_t i = 0; paramList[i]; i++) { auto a = metadata::Identifier::canonicalizeName(paramList[i]); for (size_t j = i + 1; paramList[j]; j++) { auto b = metadata::Identifier::canonicalizeName(paramList[j]); set.insert(createEntryEqParam(a, b)); } } } return set; } bool areEquivalentParameters(const std::string &a, const std::string &b) { static const std::set<std::string> setEquivalentParameters = buildSetEquivalentParameters(); auto a_can = metadata::Identifier::canonicalizeName(a); auto b_can = metadata::Identifier::canonicalizeName(b); return setEquivalentParameters.find(createEntryEqParam(a_can, b_can)) != setEquivalentParameters.end(); } // --------------------------------------------------------------------------- bool isTimeDependent(const std::string &methodName) { return ci_find(methodName, "Time dependent") != std::string::npos || ci_find(methodName, "Time-dependent") != std::string::npos; } // --------------------------------------------------------------------------- std::string computeConcatenatedName( const std::vector<CoordinateOperationNNPtr> &flattenOps) { std::string name; for (const auto &subOp : flattenOps) { if (!name.empty()) { name += " + "; } const auto &l_name = subOp->nameStr(); if (l_name.empty()) { name += "unnamed"; } else { name += l_name; } } return name; } // --------------------------------------------------------------------------- metadata::ExtentPtr getExtent(const CoordinateOperationNNPtr &op, bool conversionExtentIsWorld, bool &emptyIntersection) { auto conv = dynamic_cast<const Conversion *>(op.get()); if (conv) { emptyIntersection = false; return metadata::Extent::WORLD; } const auto &domains = op->domains(); if (!domains.empty()) { emptyIntersection = false; return domains[0]->domainOfValidity(); } auto concatenated = dynamic_cast<const ConcatenatedOperation *>(op.get()); if (!concatenated) { emptyIntersection = false; return nullptr; } return getExtent(concatenated->operations(), conversionExtentIsWorld, emptyIntersection); } // --------------------------------------------------------------------------- static const metadata::ExtentPtr nullExtent{}; const metadata::ExtentPtr &getExtent(const crs::CRSNNPtr &crs) { const auto &domains = crs->domains(); if (!domains.empty()) { return domains[0]->domainOfValidity(); } const auto *boundCRS = dynamic_cast<const crs::BoundCRS *>(crs.get()); if (boundCRS) { return getExtent(boundCRS->baseCRS()); } return nullExtent; } const metadata::ExtentPtr getExtentPossiblySynthetized(const crs::CRSNNPtr &crs, bool &approxOut) { const auto &rawExtent(getExtent(crs)); approxOut = false; if (rawExtent) return rawExtent; const auto compoundCRS = dynamic_cast<const crs::CompoundCRS *>(crs.get()); if (compoundCRS) { // For a compoundCRS, take the intersection of the extent of its // components. const auto &components = compoundCRS->componentReferenceSystems(); metadata::ExtentPtr extent; approxOut = true; for (const auto &component : components) { const auto &componentExtent(getExtent(component)); if (extent && componentExtent) extent = extent->intersection(NN_NO_CHECK(componentExtent)); else if (componentExtent) extent = componentExtent; } return extent; } return rawExtent; } // --------------------------------------------------------------------------- metadata::ExtentPtr getExtent(const std::vector<CoordinateOperationNNPtr> &ops, bool conversionExtentIsWorld, bool &emptyIntersection) { metadata::ExtentPtr res = nullptr; for (const auto &subop : ops) { const auto &subExtent = getExtent(subop, conversionExtentIsWorld, emptyIntersection); if (!subExtent) { if (emptyIntersection) { return nullptr; } continue; } if (res == nullptr) { res = subExtent; } else { res = res->intersection(NN_NO_CHECK(subExtent)); if (!res) { emptyIntersection = true; return nullptr; } } } emptyIntersection = false; return res; } // --------------------------------------------------------------------------- // Returns the accuracy of an operation, or -1 if unknown double getAccuracy(const CoordinateOperationNNPtr &op) { if (dynamic_cast<const Conversion *>(op.get())) { // A conversion is perfectly accurate. return 0.0; } double accuracy = -1.0; const auto &accuracies = op->coordinateOperationAccuracies(); if (!accuracies.empty()) { try { accuracy = c_locale_stod(accuracies[0]->value()); } catch (const std::exception &) { } } else { auto concatenated = dynamic_cast<const ConcatenatedOperation *>(op.get()); if (concatenated) { accuracy = getAccuracy(concatenated->operations()); } } return accuracy; } // --------------------------------------------------------------------------- // Returns the accuracy of a set of concatenated operations, or -1 if unknown double getAccuracy(const std::vector<CoordinateOperationNNPtr> &ops) { double accuracy = -1.0; for (const auto &subop : ops) { const double subops_accuracy = getAccuracy(subop); if (subops_accuracy < 0.0) { return -1.0; } if (accuracy < 0.0) { accuracy = 0.0; } accuracy += subops_accuracy; } return accuracy; } // --------------------------------------------------------------------------- void exportSourceCRSAndTargetCRSToWKT(const CoordinateOperation *co, io::WKTFormatter *formatter) { auto l_sourceCRS = co->sourceCRS(); assert(l_sourceCRS); auto l_targetCRS = co->targetCRS(); assert(l_targetCRS); const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; const bool canExportCRSId = (isWKT2 && formatter->use2019Keywords() && !(formatter->idOnTopLevelOnly() && formatter->topLevelHasId())); const bool hasDomains = !co->domains().empty(); if (hasDomains) { formatter->pushDisableUsage(); } formatter->startNode(io::WKTConstants::SOURCECRS, false); if (canExportCRSId && !l_sourceCRS->identifiers().empty()) { // fake that top node has no id, so that the sourceCRS id is // considered formatter->pushHasId(false); l_sourceCRS->_exportToWKT(formatter); formatter->popHasId(); } else { l_sourceCRS->_exportToWKT(formatter); } formatter->endNode(); formatter->startNode(io::WKTConstants::TARGETCRS, false); if (canExportCRSId && !l_targetCRS->identifiers().empty()) { // fake that top node has no id, so that the targetCRS id is // considered formatter->pushHasId(false); l_targetCRS->_exportToWKT(formatter); formatter->popHasId(); } else { l_targetCRS->_exportToWKT(formatter); } formatter->endNode(); if (hasDomains) { formatter->popDisableUsage(); } } //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/transformation.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "coordinateoperation_internal.hpp" #include "coordinateoperation_private.hpp" #include "esriparammappings.hpp" #include "operationmethod_private.hpp" #include "oputils.hpp" #include "parammappings.hpp" #include "vectorofvaluesparams.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // M_PI // clang-format on #include "proj_constants.h" #include "proj_json_streaming_writer.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <memory> #include <set> #include <string> #include <vector> using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Transformation::Private { TransformationPtr forwardOperation_{}; static TransformationNNPtr registerInv(const Transformation *thisIn, TransformationNNPtr invTransform); }; //! @endcond // --------------------------------------------------------------------------- Transformation::Transformation( const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) : SingleOperation(methodIn), d(internal::make_unique<Private>()) { setParameterValues(values); setCRSs(sourceCRSIn, targetCRSIn, interpolationCRSIn); setAccuracies(accuracies); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Transformation::~Transformation() = default; //! @endcond // --------------------------------------------------------------------------- Transformation::Transformation(const Transformation &other) : CoordinateOperation(other), SingleOperation(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- /** \brief Return the source crs::CRS of the transformation. * * @return the source CRS. */ const crs::CRSNNPtr &Transformation::sourceCRS() PROJ_PURE_DEFN { return CoordinateOperation::getPrivate()->strongRef_->sourceCRS_; } // --------------------------------------------------------------------------- /** \brief Return the target crs::CRS of the transformation. * * @return the target CRS. */ const crs::CRSNNPtr &Transformation::targetCRS() PROJ_PURE_DEFN { return CoordinateOperation::getPrivate()->strongRef_->targetCRS_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TransformationNNPtr Transformation::shallowClone() const { auto transf = Transformation::nn_make_shared<Transformation>(*this); transf->assignSelf(transf); transf->setCRSs(this, false); if (transf->d->forwardOperation_) { transf->d->forwardOperation_ = transf->d->forwardOperation_->shallowClone().as_nullable(); } return transf; } CoordinateOperationNNPtr Transformation::_shallowClone() const { return util::nn_static_pointer_cast<CoordinateOperation>(shallowClone()); } // --------------------------------------------------------------------------- TransformationNNPtr Transformation::promoteTo3D(const std::string &, const io::DatabaseContextPtr &dbContext) const { auto transf = shallowClone(); transf->setCRSs(sourceCRS()->promoteTo3D(std::string(), dbContext), targetCRS()->promoteTo3D(std::string(), dbContext), interpolationCRS()); return transf; } // --------------------------------------------------------------------------- TransformationNNPtr Transformation::demoteTo2D(const std::string &, const io::DatabaseContextPtr &dbContext) const { auto transf = shallowClone(); transf->setCRSs(sourceCRS()->demoteTo2D(std::string(), dbContext), targetCRS()->demoteTo2D(std::string(), dbContext), interpolationCRS()); return transf; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** \brief Return the TOWGS84 parameters of the transformation. * * If this transformation uses Coordinate Frame Rotation, Position Vector * transformation or Geocentric translations, a vector of 7 double values * using the Position Vector convention (EPSG:9606) is returned. Those values * can be used as the value of the WKT1 TOWGS84 parameter or * PROJ +towgs84 parameter. * * @return a vector of 7 values if valid, otherwise a io::FormattingException * is thrown. * @throws io::FormattingException */ std::vector<double> Transformation::getTOWGS84Parameters() const // throw(io::FormattingException) { // GDAL WKT1 assumes EPSG:9606 / Position Vector convention bool sevenParamsTransform = false; bool threeParamsTransform = false; bool invertRotSigns = false; const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const int methodEPSGCode = l_method->getEPSGCode(); const auto paramCount = parameterValues().size(); if ((paramCount == 7 && ci_find(methodName, "Coordinate Frame") != std::string::npos) || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D) { sevenParamsTransform = true; invertRotSigns = true; } else if ((paramCount == 7 && ci_find(methodName, "Position Vector") != std::string::npos) || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D) { sevenParamsTransform = true; invertRotSigns = false; } else if ((paramCount == 3 && ci_find(methodName, "Geocentric translations") != std::string::npos) || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D) { threeParamsTransform = true; } if (threeParamsTransform || sevenParamsTransform) { std::vector<double> params(7, 0.0); bool foundX = false; bool foundY = false; bool foundZ = false; bool foundRotX = false; bool foundRotY = false; bool foundRotZ = false; bool foundScale = false; const double rotSign = invertRotSigns ? -1.0 : 1.0; const auto fixNegativeZero = [](double x) { if (x == 0.0) return 0.0; return x; }; for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &parameter = opParamvalue->parameter(); const auto epsg_code = parameter->getEPSGCode(); const auto &l_parameterValue = opParamvalue->parameterValue(); if (l_parameterValue->type() == ParameterValue::Type::MEASURE) { const auto &measure = l_parameterValue->value(); if (epsg_code == EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION) { params[0] = measure.getSIValue(); foundX = true; } else if (epsg_code == EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION) { params[1] = measure.getSIValue(); foundY = true; } else if (epsg_code == EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION) { params[2] = measure.getSIValue(); foundZ = true; } else if (epsg_code == EPSG_CODE_PARAMETER_X_AXIS_ROTATION) { params[3] = fixNegativeZero( rotSign * measure.convertToUnit( common::UnitOfMeasure::ARC_SECOND)); foundRotX = true; } else if (epsg_code == EPSG_CODE_PARAMETER_Y_AXIS_ROTATION) { params[4] = fixNegativeZero( rotSign * measure.convertToUnit( common::UnitOfMeasure::ARC_SECOND)); foundRotY = true; } else if (epsg_code == EPSG_CODE_PARAMETER_Z_AXIS_ROTATION) { params[5] = fixNegativeZero( rotSign * measure.convertToUnit( common::UnitOfMeasure::ARC_SECOND)); foundRotZ = true; } else if (epsg_code == EPSG_CODE_PARAMETER_SCALE_DIFFERENCE) { params[6] = measure.convertToUnit( common::UnitOfMeasure::PARTS_PER_MILLION); foundScale = true; } } } } if (foundX && foundY && foundZ && (threeParamsTransform || (foundRotX && foundRotY && foundRotZ && foundScale))) { return params; } else { throw io::FormattingException( "Missing required parameter values in transformation"); } } #if 0 if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS || methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS) { auto offsetLat = parameterValueMeasure(EPSG_CODE_PARAMETER_LATITUDE_OFFSET); auto offsetLong = parameterValueMeasure(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET); auto offsetHeight = parameterValueMeasure(EPSG_CODE_PARAMETER_VERTICAL_OFFSET); if (offsetLat.getSIValue() == 0.0 && offsetLong.getSIValue() == 0.0 && offsetHeight.getSIValue() == 0.0) { std::vector<double> params(7, 0.0); return params; } } #endif throw io::FormattingException( "Transformation cannot be formatted as WKT1 TOWGS84 parameters"); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a transformation from a vector of GeneralParameterValue. * * @param properties See \ref general_properties. At minimum the name should be * defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param interpolationCRSIn Interpolation CRS (might be null) * @param methodIn Operation method. * @param values Vector of GeneralOperationParameterNNPtr. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. * @throws InvalidOperation */ TransformationNNPtr Transformation::create( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { if (methodIn->parameters().size() != values.size()) { throw InvalidOperation( "Inconsistent number of parameters and parameter values"); } auto transf = Transformation::nn_make_shared<Transformation>( sourceCRSIn, targetCRSIn, interpolationCRSIn, methodIn, values, accuracies); transf->assignSelf(transf); transf->setProperties(properties); std::string name; if (properties.getStringValue(common::IdentifiedObject::NAME_KEY, name) && ci_find(name, "ballpark") != std::string::npos) { transf->setHasBallparkTransformation(true); } return transf; } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation and its OperationMethod. * * @param propertiesTransformation The \ref general_properties of the * Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param interpolationCRSIn Interpolation CRS (might be null) * @param propertiesOperationMethod The \ref general_properties of the * OperationMethod. * At minimum the name should be defined. * @param parameters Vector of parameters of the operation method. * @param values Vector of ParameterValueNNPtr. Constraint: * values.size() == parameters.size() * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. * @throws InvalidOperation */ TransformationNNPtr Transformation::create(const util::PropertyMap &propertiesTransformation, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const util::PropertyMap &propertiesOperationMethod, const std::vector<OperationParameterNNPtr> &parameters, const std::vector<ParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) // throw InvalidOperation { OperationMethodNNPtr op( OperationMethod::create(propertiesOperationMethod, parameters)); if (parameters.size() != values.size()) { throw InvalidOperation( "Inconsistent number of parameters and parameter values"); } std::vector<GeneralParameterValueNNPtr> generalParameterValues; generalParameterValues.reserve(values.size()); for (size_t i = 0; i < values.size(); i++) { generalParameterValues.push_back( OperationParameterValue::create(parameters[i], values[i])); } return create(propertiesTransformation, sourceCRSIn, targetCRSIn, interpolationCRSIn, op, generalParameterValues, accuracies); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- static TransformationNNPtr createSevenParamsTransform( const util::PropertyMap &properties, const util::PropertyMap &methodProperties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return Transformation::create( properties, sourceCRSIn, targetCRSIn, nullptr, methodProperties, VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_X_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Y_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Z_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_SCALE_DIFFERENCE), }, createParams(common::Length(translationXMetre), common::Length(translationYMetre), common::Length(translationZMetre), common::Angle(rotationXArcSecond, common::UnitOfMeasure::ARC_SECOND), common::Angle(rotationYArcSecond, common::UnitOfMeasure::ARC_SECOND), common::Angle(rotationZArcSecond, common::UnitOfMeasure::ARC_SECOND), common::Scale(scaleDifferencePPM, common::UnitOfMeasure::PARTS_PER_MILLION)), accuracies); } // --------------------------------------------------------------------------- static void getTransformationType(const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, bool &isGeocentric, bool &isGeog2D, bool &isGeog3D) { auto sourceCRSGeod = dynamic_cast<const crs::GeodeticCRS *>(sourceCRSIn.get()); auto targetCRSGeod = dynamic_cast<const crs::GeodeticCRS *>(targetCRSIn.get()); isGeocentric = sourceCRSGeod && sourceCRSGeod->isGeocentric() && targetCRSGeod && targetCRSGeod->isGeocentric(); if (isGeocentric) { isGeog2D = false; isGeog3D = false; return; } isGeocentric = false; auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRSIn.get()); auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRSIn.get()); if (!(sourceCRSGeog || (sourceCRSGeod && sourceCRSGeod->isSphericalPlanetocentric())) || !(targetCRSGeog || (targetCRSGeod && targetCRSGeod->isSphericalPlanetocentric()))) { throw InvalidOperation("Inconsistent CRS type"); } const auto nSrcAxisCount = sourceCRSGeod->coordinateSystem()->axisList().size(); const auto nTargetAxisCount = targetCRSGeod->coordinateSystem()->axisList().size(); isGeog2D = nSrcAxisCount == 2 && nTargetAxisCount == 2; isGeog3D = !isGeog2D && nSrcAxisCount >= 2 && nTargetAxisCount >= 2; } // --------------------------------------------------------------------------- static int useOperationMethodEPSGCodeIfPresent(const util::PropertyMap &properties, int nDefaultOperationMethodEPSGCode) { const auto *operationMethodEPSGCode = properties.get("OPERATION_METHOD_EPSG_CODE"); if (operationMethodEPSGCode) { const auto boxedValue = dynamic_cast<const util::BoxedValue *>( (*operationMethodEPSGCode).get()); if (boxedValue && boxedValue->type() == util::BoxedValue::Type::INTEGER) { return boxedValue->integerValue(); } } return nDefaultOperationMethodEPSGCode; } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with Geocentric Translations method. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param translationXMetre Value of the Translation_X parameter (in metre). * @param translationYMetre Value of the Translation_Y parameter (in metre). * @param translationZMetre Value of the Translation_Z parameter (in metre). * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createGeocentricTranslations( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { bool isGeocentric; bool isGeog2D; bool isGeog3D; getTransformationType(sourceCRSIn, targetCRSIn, isGeocentric, isGeog2D, isGeog3D); return create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(useOperationMethodEPSGCodeIfPresent( properties, isGeocentric ? EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC : isGeog2D ? EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D : EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D)), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION), }, createParams(common::Length(translationXMetre), common::Length(translationYMetre), common::Length(translationZMetre)), accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with Position vector transformation * method. * * This is similar to createCoordinateFrameRotation(), except that the sign of * the rotation terms is inverted. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param translationXMetre Value of the Translation_X parameter (in metre). * @param translationYMetre Value of the Translation_Y parameter (in metre). * @param translationZMetre Value of the Translation_Z parameter (in metre). * @param rotationXArcSecond Value of the Rotation_X parameter (in * arc-second). * @param rotationYArcSecond Value of the Rotation_Y parameter (in * arc-second). * @param rotationZArcSecond Value of the Rotation_Z parameter (in * arc-second). * @param scaleDifferencePPM Value of the Scale_Difference parameter (in * parts-per-million). * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createPositionVector( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { bool isGeocentric; bool isGeog2D; bool isGeog3D; getTransformationType(sourceCRSIn, targetCRSIn, isGeocentric, isGeog2D, isGeog3D); return createSevenParamsTransform( properties, createMethodMapNameEPSGCode(useOperationMethodEPSGCodeIfPresent( properties, isGeocentric ? EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC : isGeog2D ? EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D : EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D)), sourceCRSIn, targetCRSIn, translationXMetre, translationYMetre, translationZMetre, rotationXArcSecond, rotationYArcSecond, rotationZArcSecond, scaleDifferencePPM, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with Coordinate Frame Rotation method. * * This is similar to createPositionVector(), except that the sign of * the rotation terms is inverted. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param translationXMetre Value of the Translation_X parameter (in metre). * @param translationYMetre Value of the Translation_Y parameter (in metre). * @param translationZMetre Value of the Translation_Z parameter (in metre). * @param rotationXArcSecond Value of the Rotation_X parameter (in * arc-second). * @param rotationYArcSecond Value of the Rotation_Y parameter (in * arc-second). * @param rotationZArcSecond Value of the Rotation_Z parameter (in * arc-second). * @param scaleDifferencePPM Value of the Scale_Difference parameter (in * parts-per-million). * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createCoordinateFrameRotation( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { bool isGeocentric; bool isGeog2D; bool isGeog3D; getTransformationType(sourceCRSIn, targetCRSIn, isGeocentric, isGeog2D, isGeog3D); return createSevenParamsTransform( properties, createMethodMapNameEPSGCode(useOperationMethodEPSGCodeIfPresent( properties, isGeocentric ? EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC : isGeog2D ? EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D : EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D)), sourceCRSIn, targetCRSIn, translationXMetre, translationYMetre, translationZMetre, rotationXArcSecond, rotationYArcSecond, rotationZArcSecond, scaleDifferencePPM, accuracies); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static TransformationNNPtr createFifteenParamsTransform( const util::PropertyMap &properties, const util::PropertyMap &methodProperties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, double rateTranslationX, double rateTranslationY, double rateTranslationZ, double rateRotationX, double rateRotationY, double rateRotationZ, double rateScaleDifference, double referenceEpochYear, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return Transformation::create( properties, sourceCRSIn, targetCRSIn, nullptr, methodProperties, VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_X_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Y_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Z_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_SCALE_DIFFERENCE), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_REFERENCE_EPOCH), }, VectorOfValues{ common::Length(translationXMetre), common::Length(translationYMetre), common::Length(translationZMetre), common::Angle(rotationXArcSecond, common::UnitOfMeasure::ARC_SECOND), common::Angle(rotationYArcSecond, common::UnitOfMeasure::ARC_SECOND), common::Angle(rotationZArcSecond, common::UnitOfMeasure::ARC_SECOND), common::Scale(scaleDifferencePPM, common::UnitOfMeasure::PARTS_PER_MILLION), common::Measure(rateTranslationX, common::UnitOfMeasure::METRE_PER_YEAR), common::Measure(rateTranslationY, common::UnitOfMeasure::METRE_PER_YEAR), common::Measure(rateTranslationZ, common::UnitOfMeasure::METRE_PER_YEAR), common::Measure(rateRotationX, common::UnitOfMeasure::ARC_SECOND_PER_YEAR), common::Measure(rateRotationY, common::UnitOfMeasure::ARC_SECOND_PER_YEAR), common::Measure(rateRotationZ, common::UnitOfMeasure::ARC_SECOND_PER_YEAR), common::Measure(rateScaleDifference, common::UnitOfMeasure::PPM_PER_YEAR), common::Measure(referenceEpochYear, common::UnitOfMeasure::YEAR), }, accuracies); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with Time Dependent position vector * transformation method. * * This is similar to createTimeDependentCoordinateFrameRotation(), except that * the sign of * the rotation terms is inverted. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1053/index.html"> * EPSG:1053</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param translationXMetre Value of the Translation_X parameter (in metre). * @param translationYMetre Value of the Translation_Y parameter (in metre). * @param translationZMetre Value of the Translation_Z parameter (in metre). * @param rotationXArcSecond Value of the Rotation_X parameter (in * arc-second). * @param rotationYArcSecond Value of the Rotation_Y parameter (in * arc-second). * @param rotationZArcSecond Value of the Rotation_Z parameter (in * arc-second). * @param scaleDifferencePPM Value of the Scale_Difference parameter (in * parts-per-million). * @param rateTranslationX Value of the rate of change of X-axis translation (in * metre/year) * @param rateTranslationY Value of the rate of change of Y-axis translation (in * metre/year) * @param rateTranslationZ Value of the rate of change of Z-axis translation (in * metre/year) * @param rateRotationX Value of the rate of change of X-axis rotation (in * arc-second/year) * @param rateRotationY Value of the rate of change of Y-axis rotation (in * arc-second/year) * @param rateRotationZ Value of the rate of change of Z-axis rotation (in * arc-second/year) * @param rateScaleDifference Value of the rate of change of scale difference * (in PPM/year) * @param referenceEpochYear Parameter reference epoch (in decimal year) * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createTimeDependentPositionVector( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, double rateTranslationX, double rateTranslationY, double rateTranslationZ, double rateRotationX, double rateRotationY, double rateRotationZ, double rateScaleDifference, double referenceEpochYear, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { bool isGeocentric; bool isGeog2D; bool isGeog3D; getTransformationType(sourceCRSIn, targetCRSIn, isGeocentric, isGeog2D, isGeog3D); return createFifteenParamsTransform( properties, createMethodMapNameEPSGCode(useOperationMethodEPSGCodeIfPresent( properties, isGeocentric ? EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC : isGeog2D ? EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D : EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D)), sourceCRSIn, targetCRSIn, translationXMetre, translationYMetre, translationZMetre, rotationXArcSecond, rotationYArcSecond, rotationZArcSecond, scaleDifferencePPM, rateTranslationX, rateTranslationY, rateTranslationZ, rateRotationX, rateRotationY, rateRotationZ, rateScaleDifference, referenceEpochYear, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with Time Dependent Position coordinate * frame rotation transformation method. * * This is similar to createTimeDependentPositionVector(), except that the sign * of * the rotation terms is inverted. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1056/index.html"> * EPSG:1056</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param translationXMetre Value of the Translation_X parameter (in metre). * @param translationYMetre Value of the Translation_Y parameter (in metre). * @param translationZMetre Value of the Translation_Z parameter (in metre). * @param rotationXArcSecond Value of the Rotation_X parameter (in * arc-second). * @param rotationYArcSecond Value of the Rotation_Y parameter (in * arc-second). * @param rotationZArcSecond Value of the Rotation_Z parameter (in * arc-second). * @param scaleDifferencePPM Value of the Scale_Difference parameter (in * parts-per-million). * @param rateTranslationX Value of the rate of change of X-axis translation (in * metre/year) * @param rateTranslationY Value of the rate of change of Y-axis translation (in * metre/year) * @param rateTranslationZ Value of the rate of change of Z-axis translation (in * metre/year) * @param rateRotationX Value of the rate of change of X-axis rotation (in * arc-second/year) * @param rateRotationY Value of the rate of change of Y-axis rotation (in * arc-second/year) * @param rateRotationZ Value of the rate of change of Z-axis rotation (in * arc-second/year) * @param rateScaleDifference Value of the rate of change of scale difference * (in PPM/year) * @param referenceEpochYear Parameter reference epoch (in decimal year) * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. * @throws InvalidOperation */ TransformationNNPtr Transformation::createTimeDependentCoordinateFrameRotation( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, double rateTranslationX, double rateTranslationY, double rateTranslationZ, double rateRotationX, double rateRotationY, double rateRotationZ, double rateScaleDifference, double referenceEpochYear, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { bool isGeocentric; bool isGeog2D; bool isGeog3D; getTransformationType(sourceCRSIn, targetCRSIn, isGeocentric, isGeog2D, isGeog3D); return createFifteenParamsTransform( properties, createMethodMapNameEPSGCode(useOperationMethodEPSGCodeIfPresent( properties, isGeocentric ? EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC : isGeog2D ? EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D : EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D)), sourceCRSIn, targetCRSIn, translationXMetre, translationYMetre, translationZMetre, rotationXArcSecond, rotationYArcSecond, rotationZArcSecond, scaleDifferencePPM, rateTranslationX, rateTranslationY, rateTranslationZ, rateRotationX, rateRotationY, rateRotationZ, rateScaleDifference, referenceEpochYear, accuracies); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static TransformationNNPtr _createMolodensky( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, int methodEPSGCode, double translationXMetre, double translationYMetre, double translationZMetre, double semiMajorAxisDifferenceMetre, double flattingDifference, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return Transformation::create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(methodEPSGCode), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_FLATTENING_DIFFERENCE), }, createParams( common::Length(translationXMetre), common::Length(translationYMetre), common::Length(translationZMetre), common::Length(semiMajorAxisDifferenceMetre), common::Measure(flattingDifference, common::UnitOfMeasure::NONE)), accuracies); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with Molodensky method. * * @see createAbridgedMolodensky() for a related method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9604/index.html"> * EPSG:9604</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param translationXMetre Value of the Translation_X parameter (in metre). * @param translationYMetre Value of the Translation_Y parameter (in metre). * @param translationZMetre Value of the Translation_Z parameter (in metre). * @param semiMajorAxisDifferenceMetre The difference between the semi-major * axis values of the ellipsoids used in the target and source CRS (in metre). * @param flattingDifference The difference between the flattening values of * the ellipsoids used in the target and source CRS. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. * @throws InvalidOperation */ TransformationNNPtr Transformation::createMolodensky( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double semiMajorAxisDifferenceMetre, double flattingDifference, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return _createMolodensky( properties, sourceCRSIn, targetCRSIn, EPSG_CODE_METHOD_MOLODENSKY, translationXMetre, translationYMetre, translationZMetre, semiMajorAxisDifferenceMetre, flattingDifference, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with Abridged Molodensky method. * * @see createdMolodensky() for a related method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9605/index.html"> * EPSG:9605</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param translationXMetre Value of the Translation_X parameter (in metre). * @param translationYMetre Value of the Translation_Y parameter (in metre). * @param translationZMetre Value of the Translation_Z parameter (in metre). * @param semiMajorAxisDifferenceMetre The difference between the semi-major * axis values of the ellipsoids used in the target and source CRS (in metre). * @param flattingDifference The difference between the flattening values of * the ellipsoids used in the target and source CRS. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. * @throws InvalidOperation */ TransformationNNPtr Transformation::createAbridgedMolodensky( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double semiMajorAxisDifferenceMetre, double flattingDifference, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return _createMolodensky(properties, sourceCRSIn, targetCRSIn, EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY, translationXMetre, translationYMetre, translationZMetre, semiMajorAxisDifferenceMetre, flattingDifference, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation from TOWGS84 parameters. * * This is a helper of createPositionVector() with the source CRS being the * GeographicCRS of sourceCRSIn, and the target CRS being EPSG:4326 * * @param sourceCRSIn Source CRS. * @param TOWGS84Parameters The vector of 3 double values (Translation_X,_Y,_Z) * or 7 double values (Translation_X,_Y,_Z, Rotation_X,_Y,_Z, Scale_Difference) * passed to createPositionVector() * @return new Transformation. * @throws InvalidOperation */ TransformationNNPtr Transformation::createTOWGS84( const crs::CRSNNPtr &sourceCRSIn, const std::vector<double> &TOWGS84Parameters) // throw InvalidOperation { if (TOWGS84Parameters.size() != 3 && TOWGS84Parameters.size() != 7) { throw InvalidOperation( "Invalid number of elements in TOWGS84Parameters"); } auto transformSourceGeodCRS = sourceCRSIn->extractGeodeticCRS(); if (!transformSourceGeodCRS) { throw InvalidOperation( "Cannot find GeodeticCRS in sourceCRS of TOWGS84 transformation"); } util::PropertyMap properties; properties.set(common::IdentifiedObject::NAME_KEY, concat("Transformation from ", transformSourceGeodCRS->nameStr(), " to WGS84")); auto targetCRS = dynamic_cast<const crs::GeographicCRS *>( transformSourceGeodCRS.get()) || transformSourceGeodCRS->isSphericalPlanetocentric() ? util::nn_static_pointer_cast<crs::CRS>( crs::GeographicCRS::EPSG_4326) : util::nn_static_pointer_cast<crs::CRS>( crs::GeodeticCRS::EPSG_4978); crs::CRSNNPtr transformSourceCRS = NN_NO_CHECK(transformSourceGeodCRS); if (TOWGS84Parameters.size() == 3) { return createGeocentricTranslations( properties, transformSourceCRS, targetCRS, TOWGS84Parameters[0], TOWGS84Parameters[1], TOWGS84Parameters[2], {}); } return createPositionVector( properties, transformSourceCRS, targetCRS, TOWGS84Parameters[0], TOWGS84Parameters[1], TOWGS84Parameters[2], TOWGS84Parameters[3], TOWGS84Parameters[4], TOWGS84Parameters[5], TOWGS84Parameters[6], {}); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with NTv2 method. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param filename NTv2 filename. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createNTv2( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return create(properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_NTV2), VectorOfParameters{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE)}, VectorOfValues{ParameterValue::createFilename(filename)}, accuracies); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static TransformationNNPtr _createGravityRelatedHeightToGeographic3D( const util::PropertyMap &properties, bool inverse, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return Transformation::create( properties, sourceCRSIn, targetCRSIn, interpolationCRSIn, util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, inverse ? INVERSE_OF + PROJ_WKT2_NAME_METHOD_HEIGHT_TO_GEOG3D : PROJ_WKT2_NAME_METHOD_HEIGHT_TO_GEOG3D), VectorOfParameters{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME)}, VectorOfValues{ParameterValue::createFilename(filename)}, accuracies); } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a transformation from GravityRelatedHeight to * Geographic3D * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param interpolationCRSIn Interpolation CRS. (might be null) * @param filename GRID filename. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createGravityRelatedHeightToGeographic3D( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return _createGravityRelatedHeightToGeographic3D( properties, false, sourceCRSIn, targetCRSIn, interpolationCRSIn, filename, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with method VERTCON * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param filename GRID filename. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createVERTCON( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return create(properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_VERTCON), VectorOfParameters{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_VERTICAL_OFFSET_FILE)}, VectorOfValues{ParameterValue::createFilename(filename)}, accuracies); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static inline std::vector<metadata::PositionalAccuracyNNPtr> buildAccuracyZero() { return std::vector<metadata::PositionalAccuracyNNPtr>{ metadata::PositionalAccuracy::create("0")}; } // --------------------------------------------------------------------------- //! @endcond /** \brief Instantiate a transformation with method Longitude rotation * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9601/index.html"> * EPSG:9601</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param offset Longitude offset to add. * @return new Transformation. */ TransformationNNPtr Transformation::createLongitudeRotation( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offset) { return create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_LONGITUDE_ROTATION), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET)}, VectorOfValues{ParameterValue::create(offset)}, buildAccuracyZero()); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with method Geographic 2D offsets * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9619/index.html"> * EPSG:9619</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param offsetLat Latitude offset to add. * @param offsetLong Longitude offset to add. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createGeographic2DOffsets( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offsetLat, const common::Angle &offsetLong, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LATITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET)}, VectorOfValues{offsetLat, offsetLong}, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with method Geographic 3D offsets * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9660/index.html"> * EPSG:9660</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param offsetLat Latitude offset to add. * @param offsetLong Longitude offset to add. * @param offsetHeight Height offset to add. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createGeographic3DOffsets( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LATITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_VERTICAL_OFFSET)}, VectorOfValues{offsetLat, offsetLong, offsetHeight}, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with method Geographic 2D with * height * offsets * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9618/index.html"> * EPSG:9618</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param offsetLat Latitude offset to add. * @param offsetLong Longitude offset to add. * @param offsetHeight Geoid undulation to add. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createGeographic2DWithHeightOffsets( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode( EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LATITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_GEOID_UNDULATION)}, VectorOfValues{offsetLat, offsetLong, offsetHeight}, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation with method Vertical Offset. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9616/index.html"> * EPSG:9616</a>. * * @param properties See \ref general_properties of the Transformation. * At minimum the name should be defined. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param offsetHeight Geoid undulation to add. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. */ TransformationNNPtr Transformation::createVerticalOffset( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Length &offsetHeight, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return create(properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_VERTICAL_OFFSET), VectorOfParameters{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_VERTICAL_OFFSET)}, VectorOfValues{offsetHeight}, accuracies); } // --------------------------------------------------------------------------- /** \brief Instantiate a transformation based on the Change of Vertical Unit * method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1069/index.html"> * EPSG:1069</a> [DEPRECATED]. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param sourceCRSIn Source CRS. * @param targetCRSIn Target CRS. * @param factor Conversion factor * @param accuracies Vector of positional accuracy (might be empty). * @return a new Transformation. */ TransformationNNPtr Transformation::createChangeVerticalUnit( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Scale &factor, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT), VectorOfParameters{ createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR), }, VectorOfValues{ factor, }, accuracies); } // --------------------------------------------------------------------------- // to avoid -0... static double negate(double val) { if (val != 0) { return -val; } return 0.0; } // --------------------------------------------------------------------------- static CoordinateOperationPtr createApproximateInverseIfPossible(const Transformation *op) { bool sevenParamsTransform = false; bool fifteenParamsTransform = false; const auto &method = op->method(); const auto &methodName = method->nameStr(); const int methodEPSGCode = method->getEPSGCode(); const auto paramCount = op->parameterValues().size(); const bool isPositionVector = ci_find(methodName, "Position Vector") != std::string::npos; const bool isCoordinateFrame = ci_find(methodName, "Coordinate Frame") != std::string::npos; // See end of "2.4.3.3 Helmert 7-parameter transformations" // in EPSG 7-2 guidance // For practical purposes, the inverse of 7- or 15-parameters Helmert // can be obtained by using the forward method with all parameters // negated // (except reference epoch!) // So for WKT export use that. But for PROJ string, we use the +inv flag // so as to get "perfect" round-tripability. if ((paramCount == 7 && isCoordinateFrame && !isTimeDependent(methodName)) || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D) { sevenParamsTransform = true; } else if ( (paramCount == 15 && isCoordinateFrame && isTimeDependent(methodName)) || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D) { fifteenParamsTransform = true; } else if ((paramCount == 7 && isPositionVector && !isTimeDependent(methodName)) || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D) { sevenParamsTransform = true; } else if ( (paramCount == 15 && isPositionVector && isTimeDependent(methodName)) || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D) { fifteenParamsTransform = true; } if (sevenParamsTransform || fifteenParamsTransform) { double neg_x = negate(op->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION)); double neg_y = negate(op->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION)); double neg_z = negate(op->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION)); double neg_rx = negate( op->parameterValueNumeric(EPSG_CODE_PARAMETER_X_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND)); double neg_ry = negate( op->parameterValueNumeric(EPSG_CODE_PARAMETER_Y_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND)); double neg_rz = negate( op->parameterValueNumeric(EPSG_CODE_PARAMETER_Z_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND)); double neg_scaleDiff = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_SCALE_DIFFERENCE, common::UnitOfMeasure::PARTS_PER_MILLION)); auto methodProperties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, methodName); int method_epsg_code = method->getEPSGCode(); if (method_epsg_code) { methodProperties .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, method_epsg_code); } bool exactInverse = (neg_rx == 0 && neg_ry == 0 && neg_rz == 0 && neg_scaleDiff == 0); if (fifteenParamsTransform) { double neg_rate_x = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION, common::UnitOfMeasure::METRE_PER_YEAR)); double neg_rate_y = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION, common::UnitOfMeasure::METRE_PER_YEAR)); double neg_rate_z = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION, common::UnitOfMeasure::METRE_PER_YEAR)); double neg_rate_rx = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND_PER_YEAR)); double neg_rate_ry = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND_PER_YEAR)); double neg_rate_rz = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND_PER_YEAR)); double neg_rate_scaleDiff = negate(op->parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE, common::UnitOfMeasure::PPM_PER_YEAR)); double referenceEpochYear = op->parameterValueNumeric(EPSG_CODE_PARAMETER_REFERENCE_EPOCH, common::UnitOfMeasure::YEAR); exactInverse &= (neg_rate_rx == 0 && neg_rate_ry == 0 && neg_rate_rz == 0 && neg_rate_scaleDiff == 0); return util::nn_static_pointer_cast<CoordinateOperation>( createFifteenParamsTransform( createPropertiesForInverse(op, false, !exactInverse), methodProperties, op->targetCRS(), op->sourceCRS(), neg_x, neg_y, neg_z, neg_rx, neg_ry, neg_rz, neg_scaleDiff, neg_rate_x, neg_rate_y, neg_rate_z, neg_rate_rx, neg_rate_ry, neg_rate_rz, neg_rate_scaleDiff, referenceEpochYear, op->coordinateOperationAccuracies())) .as_nullable(); } else { return util::nn_static_pointer_cast<CoordinateOperation>( createSevenParamsTransform( createPropertiesForInverse(op, false, !exactInverse), methodProperties, op->targetCRS(), op->sourceCRS(), neg_x, neg_y, neg_z, neg_rx, neg_ry, neg_rz, neg_scaleDiff, op->coordinateOperationAccuracies())) .as_nullable(); } } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress TransformationNNPtr Transformation::Private::registerInv(const Transformation *thisIn, TransformationNNPtr invTransform) { invTransform->d->forwardOperation_ = thisIn->shallowClone().as_nullable(); invTransform->setHasBallparkTransformation( thisIn->hasBallparkTransformation()); return invTransform; } //! @endcond // --------------------------------------------------------------------------- CoordinateOperationNNPtr Transformation::inverse() const { return inverseAsTransformation(); } // --------------------------------------------------------------------------- TransformationNNPtr Transformation::inverseAsTransformation() const { if (d->forwardOperation_) { return NN_NO_CHECK(d->forwardOperation_); } const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const int methodEPSGCode = l_method->getEPSGCode(); const auto &l_sourceCRS = sourceCRS(); const auto &l_targetCRS = targetCRS(); // For geocentric translation, the inverse is exactly the negation of // the parameters. if (ci_find(methodName, "Geocentric translations") != std::string::npos || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D) { double x = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION); double y = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION); double z = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION); auto properties = createPropertiesForInverse(this, false, false); return Private::registerInv( this, create(properties, l_targetCRS, l_sourceCRS, nullptr, createMethodMapNameEPSGCode( useOperationMethodEPSGCodeIfPresent( properties, methodEPSGCode)), VectorOfParameters{ createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION), createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION), }, createParams(common::Length(negate(x)), common::Length(negate(y)), common::Length(negate(z))), coordinateOperationAccuracies())); } if (methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY || methodEPSGCode == EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY) { double x = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION); double y = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION); double z = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION); double da = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE); double df = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_FLATTENING_DIFFERENCE); if (methodEPSGCode == EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY) { return Private::registerInv( this, createAbridgedMolodensky( createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, negate(x), negate(y), negate(z), negate(da), negate(df), coordinateOperationAccuracies())); } else { return Private::registerInv( this, createMolodensky(createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, negate(x), negate(y), negate(z), negate(da), negate(df), coordinateOperationAccuracies())); } } if (isLongitudeRotation()) { const auto &offset = parameterValueMeasure(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET); const common::Angle newOffset(negate(offset.value()), offset.unit()); return Private::registerInv( this, createLongitudeRotation( createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, newOffset)); } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS) { const auto &offsetLat = parameterValueMeasure(EPSG_CODE_PARAMETER_LATITUDE_OFFSET); const common::Angle newOffsetLat(negate(offsetLat.value()), offsetLat.unit()); const auto &offsetLong = parameterValueMeasure(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET); const common::Angle newOffsetLong(negate(offsetLong.value()), offsetLong.unit()); return Private::registerInv( this, createGeographic2DOffsets( createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, newOffsetLat, newOffsetLong, coordinateOperationAccuracies())); } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS) { const auto &offsetLat = parameterValueMeasure(EPSG_CODE_PARAMETER_LATITUDE_OFFSET); const common::Angle newOffsetLat(negate(offsetLat.value()), offsetLat.unit()); const auto &offsetLong = parameterValueMeasure(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET); const common::Angle newOffsetLong(negate(offsetLong.value()), offsetLong.unit()); const auto &offsetHeight = parameterValueMeasure(EPSG_CODE_PARAMETER_VERTICAL_OFFSET); const common::Length newOffsetHeight(negate(offsetHeight.value()), offsetHeight.unit()); return Private::registerInv( this, createGeographic3DOffsets( createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, newOffsetLat, newOffsetLong, newOffsetHeight, coordinateOperationAccuracies())); } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS) { const auto &offsetLat = parameterValueMeasure(EPSG_CODE_PARAMETER_LATITUDE_OFFSET); const common::Angle newOffsetLat(negate(offsetLat.value()), offsetLat.unit()); const auto &offsetLong = parameterValueMeasure(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET); const common::Angle newOffsetLong(negate(offsetLong.value()), offsetLong.unit()); const auto &offsetHeight = parameterValueMeasure(EPSG_CODE_PARAMETER_GEOID_UNDULATION); const common::Length newOffsetHeight(negate(offsetHeight.value()), offsetHeight.unit()); return Private::registerInv( this, createGeographic2DWithHeightOffsets( createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, newOffsetLat, newOffsetLong, newOffsetHeight, coordinateOperationAccuracies())); } if (methodEPSGCode == EPSG_CODE_METHOD_VERTICAL_OFFSET) { const auto &offsetHeight = parameterValueMeasure(EPSG_CODE_PARAMETER_VERTICAL_OFFSET); const common::Length newOffsetHeight(negate(offsetHeight.value()), offsetHeight.unit()); return Private::registerInv( this, createVerticalOffset(createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, newOffsetHeight, coordinateOperationAccuracies())); } if (methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT) { const double convFactor = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR); return Private::registerInv( this, createChangeVerticalUnit( createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, common::Scale(convFactor == 0.0 ? 0.0 : 1.0 / convFactor), coordinateOperationAccuracies())); } #ifdef notdef // We don't need that currently, but we might... if (methodEPSGCode == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { return Private::registerInv( this, createHeightDepthReversal( createPropertiesForInverse(this, false, false), l_targetCRS, l_sourceCRS, coordinateOperationAccuracies())); } #endif return InverseTransformation::create(NN_NO_CHECK( util::nn_dynamic_pointer_cast<Transformation>(shared_from_this()))); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- InverseTransformation::InverseTransformation(const TransformationNNPtr &forward) : Transformation( forward->targetCRS(), forward->sourceCRS(), forward->interpolationCRS(), OperationMethod::create(createPropertiesForInverse(forward->method()), forward->method()->parameters()), forward->parameterValues(), forward->coordinateOperationAccuracies()), InverseCoordinateOperation(forward, true) { setPropertiesFromForward(); } // --------------------------------------------------------------------------- InverseTransformation::~InverseTransformation() = default; // --------------------------------------------------------------------------- TransformationNNPtr InverseTransformation::create(const TransformationNNPtr &forward) { auto conv = util::nn_make_shared<InverseTransformation>(forward); conv->assignSelf(conv); return conv; } // --------------------------------------------------------------------------- TransformationNNPtr InverseTransformation::inverseAsTransformation() const { return NN_NO_CHECK( util::nn_dynamic_pointer_cast<Transformation>(forwardOperation_)); } // --------------------------------------------------------------------------- void InverseTransformation::_exportToWKT(io::WKTFormatter *formatter) const { auto approxInverse = createApproximateInverseIfPossible( util::nn_dynamic_pointer_cast<Transformation>(forwardOperation_).get()); if (approxInverse) { approxInverse->_exportToWKT(formatter); } else { Transformation::_exportToWKT(formatter); } } // --------------------------------------------------------------------------- CoordinateOperationNNPtr InverseTransformation::_shallowClone() const { auto op = InverseTransformation::nn_make_shared<InverseTransformation>( inverseAsTransformation()->shallowClone()); op->assignSelf(op); op->setCRSs(this, false); return util::nn_static_pointer_cast<CoordinateOperation>(op); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Transformation::_exportToWKT(io::WKTFormatter *formatter) const { exportTransformationToWKT(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Transformation::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext(formatter->MakeObjectContext( formatter->abridgedTransformation() ? "AbridgedTransformation" : "Transformation", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } if (!formatter->abridgedTransformation()) { writer->AddObjKey("source_crs"); formatter->setAllowIDInImmediateChild(); sourceCRS()->_exportToJSON(formatter); writer->AddObjKey("target_crs"); formatter->setAllowIDInImmediateChild(); targetCRS()->_exportToJSON(formatter); const auto &l_interpolationCRS = interpolationCRS(); if (l_interpolationCRS) { writer->AddObjKey("interpolation_crs"); formatter->setAllowIDInImmediateChild(); l_interpolationCRS->_exportToJSON(formatter); } } else { if (formatter->abridgedTransformationWriteSourceCRS()) { writer->AddObjKey("source_crs"); formatter->setAllowIDInImmediateChild(); sourceCRS()->_exportToJSON(formatter); } } writer->AddObjKey("method"); formatter->setOmitTypeInImmediateChild(); formatter->setAllowIDInImmediateChild(); method()->_exportToJSON(formatter); writer->AddObjKey("parameters"); { auto parametersContext(writer->MakeArrayContext(false)); for (const auto &genOpParamvalue : parameterValues()) { formatter->setAllowIDInImmediateChild(); formatter->setOmitTypeInImmediateChild(); genOpParamvalue->_exportToJSON(formatter); } } if (!formatter->abridgedTransformation()) { if (!coordinateOperationAccuracies().empty()) { writer->AddObjKey("accuracy"); writer->Add(coordinateOperationAccuracies()[0]->value()); } } if (formatter->abridgedTransformation()) { if (formatter->outputId()) { formatID(formatter); } } else { ObjectUsage::baseExportToJSON(formatter); } } //! @endcond // --------------------------------------------------------------------------- void Transformation::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(FormattingException) { if (formatter->convention() == io::PROJStringFormatter::Convention::PROJ_4) { throw io::FormattingException( "Transformation cannot be exported as a PROJ.4 string"); } if (exportToPROJStringGeneric(formatter)) { return; } throw io::FormattingException("Unimplemented " + nameStr()); } } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/operationmethod_private.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef OPERATIONMETHOD_PRIVATE_HPP #define OPERATIONMETHOD_PRIVATE_HPP #include "proj/coordinateoperation.hpp" #include "proj/util.hpp" // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct OperationMethod::Private { util::optional<std::string> formula_{}; util::optional<metadata::Citation> formulaCitation_{}; std::vector<GeneralOperationParameterNNPtr> parameters_{}; std::string projMethodOverride_{}; }; //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END #endif // OPERATIONMETHOD_PRIVATE_HPP
hpp
PROJ
data/projects/PROJ/src/iso19111/operation/singleoperation.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "coordinateoperation_internal.hpp" #include "coordinateoperation_private.hpp" #include "operationmethod_private.hpp" #include "oputils.hpp" #include "parammappings.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // M_PI // clang-format on #include "proj_constants.h" #include "proj_json_streaming_writer.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <memory> #include <set> #include <string> #include <vector> using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress InvalidOperationEmptyIntersection::InvalidOperationEmptyIntersection( const std::string &message) : InvalidOperation(message) {} InvalidOperationEmptyIntersection::InvalidOperationEmptyIntersection( const InvalidOperationEmptyIntersection &) = default; InvalidOperationEmptyIntersection::~InvalidOperationEmptyIntersection() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- GridDescription::GridDescription() : shortName{}, fullName{}, packageName{}, url{}, directDownload(false), openLicense(false), available(false) {} GridDescription::~GridDescription() = default; GridDescription::GridDescription(const GridDescription &) = default; GridDescription::GridDescription(GridDescription &&other) noexcept : shortName(std::move(other.shortName)), fullName(std::move(other.fullName)), packageName(std::move(other.packageName)), url(std::move(other.url)), directDownload(other.directDownload), openLicense(other.openLicense), available(other.available) {} //! @endcond // --------------------------------------------------------------------------- CoordinateOperation::CoordinateOperation() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- CoordinateOperation::CoordinateOperation(const CoordinateOperation &other) : ObjectUsage(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateOperation::~CoordinateOperation() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the version of the coordinate transformation (i.e. * instantiation * due to the stochastic nature of the parameters). * * Mandatory when describing a coordinate transformation or point motion * operation, and should not be supplied for a coordinate conversion. * * @return version or empty. */ const util::optional<std::string> & CoordinateOperation::operationVersion() const { return d->operationVersion_; } // --------------------------------------------------------------------------- /** \brief Return estimate(s) of the impact of this coordinate operation on * point accuracy. * * Gives position error estimates for target coordinates of this coordinate * operation, assuming no errors in source coordinates. * * @return estimate(s) or empty vector. */ const std::vector<metadata::PositionalAccuracyNNPtr> & CoordinateOperation::coordinateOperationAccuracies() const { return d->coordinateOperationAccuracies_; } // --------------------------------------------------------------------------- /** \brief Return the source CRS of this coordinate operation. * * This should not be null, expect for of a derivingConversion of a DerivedCRS * when the owning DerivedCRS has been destroyed. * * @return source CRS, or null. */ const crs::CRSPtr CoordinateOperation::sourceCRS() const { return d->sourceCRSWeak_.lock(); } // --------------------------------------------------------------------------- /** \brief Return the target CRS of this coordinate operation. * * This should not be null, expect for of a derivingConversion of a DerivedCRS * when the owning DerivedCRS has been destroyed. * * @return target CRS, or null. */ const crs::CRSPtr CoordinateOperation::targetCRS() const { return d->targetCRSWeak_.lock(); } // --------------------------------------------------------------------------- /** \brief Return the interpolation CRS of this coordinate operation. * * @return interpolation CRS, or null. */ const crs::CRSPtr &CoordinateOperation::interpolationCRS() const { return d->interpolationCRS_; } // --------------------------------------------------------------------------- /** \brief Return the source epoch of coordinates. * * @return source epoch of coordinates, or empty. */ const util::optional<common::DataEpoch> & CoordinateOperation::sourceCoordinateEpoch() const { return *(d->sourceCoordinateEpoch_); } // --------------------------------------------------------------------------- /** \brief Return the target epoch of coordinates. * * @return target epoch of coordinates, or empty. */ const util::optional<common::DataEpoch> & CoordinateOperation::targetCoordinateEpoch() const { return *(d->targetCoordinateEpoch_); } // --------------------------------------------------------------------------- void CoordinateOperation::setWeakSourceTargetCRS( std::weak_ptr<crs::CRS> sourceCRSIn, std::weak_ptr<crs::CRS> targetCRSIn) { d->sourceCRSWeak_ = std::move(sourceCRSIn); d->targetCRSWeak_ = std::move(targetCRSIn); } // --------------------------------------------------------------------------- void CoordinateOperation::setCRSs(const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn) { d->strongRef_ = internal::make_unique<Private::CRSStrongRef>(sourceCRSIn, targetCRSIn); d->sourceCRSWeak_ = sourceCRSIn.as_nullable(); d->targetCRSWeak_ = targetCRSIn.as_nullable(); d->interpolationCRS_ = interpolationCRSIn; } // --------------------------------------------------------------------------- void CoordinateOperation::setInterpolationCRS( const crs::CRSPtr &interpolationCRSIn) { d->interpolationCRS_ = interpolationCRSIn; } // --------------------------------------------------------------------------- void CoordinateOperation::setCRSs(const CoordinateOperation *in, bool inverseSourceTarget) { auto l_sourceCRS = in->sourceCRS(); auto l_targetCRS = in->targetCRS(); if (l_sourceCRS && l_targetCRS) { auto nn_sourceCRS = NN_NO_CHECK(l_sourceCRS); auto nn_targetCRS = NN_NO_CHECK(l_targetCRS); if (inverseSourceTarget) { setCRSs(nn_targetCRS, nn_sourceCRS, in->interpolationCRS()); } else { setCRSs(nn_sourceCRS, nn_targetCRS, in->interpolationCRS()); } } } // --------------------------------------------------------------------------- void CoordinateOperation::setSourceCoordinateEpoch( const util::optional<common::DataEpoch> &epoch) { d->sourceCoordinateEpoch_ = std::make_shared<util::optional<common::DataEpoch>>(epoch); } // --------------------------------------------------------------------------- void CoordinateOperation::setTargetCoordinateEpoch( const util::optional<common::DataEpoch> &epoch) { d->targetCoordinateEpoch_ = std::make_shared<util::optional<common::DataEpoch>>(epoch); } // --------------------------------------------------------------------------- void CoordinateOperation::setAccuracies( const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { d->coordinateOperationAccuracies_ = accuracies; } // --------------------------------------------------------------------------- /** \brief Return whether a coordinate operation can be instantiated as * a PROJ pipeline, checking in particular that referenced grids are * available. */ bool CoordinateOperation::isPROJInstantiable( const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const { try { exportToPROJString(io::PROJStringFormatter::create().get()); } catch (const std::exception &) { return false; } for (const auto &gridDesc : gridsNeeded(databaseContext, considerKnownGridsAsAvailable)) { // Grid name starting with @ are considered as optional. if (!gridDesc.available && (gridDesc.shortName.empty() || gridDesc.shortName[0] != '@')) { return false; } } return true; } // --------------------------------------------------------------------------- /** \brief Return whether a coordinate operation has a "ballpark" * transformation, * that is a very approximate one, due to lack of more accurate transformations. * * Typically a null geographic offset between two horizontal datum, or a * null vertical offset (or limited to unit changes) between two vertical * datum. Errors of several tens to one hundred meters might be expected, * compared to more accurate transformations. */ bool CoordinateOperation::hasBallparkTransformation() const { return d->hasBallparkTransformation_; } // --------------------------------------------------------------------------- void CoordinateOperation::setHasBallparkTransformation(bool b) { d->hasBallparkTransformation_ = b; } // --------------------------------------------------------------------------- void CoordinateOperation::setProperties( const util::PropertyMap &properties) // throw(InvalidValueTypeException) { ObjectUsage::setProperties(properties); properties.getStringValue(OPERATION_VERSION_KEY, d->operationVersion_); } // --------------------------------------------------------------------------- /** \brief Return a variation of the current coordinate operation whose axis * order is the one expected for visualization purposes. */ CoordinateOperationNNPtr CoordinateOperation::normalizeForVisualization() const { auto l_sourceCRS = sourceCRS(); auto l_targetCRS = targetCRS(); if (!l_sourceCRS || !l_targetCRS) { throw util::UnsupportedOperationException( "Cannot retrieve source or target CRS"); } const bool swapSource = l_sourceCRS->mustAxisOrderBeSwitchedForVisualization(); const bool swapTarget = l_targetCRS->mustAxisOrderBeSwitchedForVisualization(); auto l_this = NN_NO_CHECK(std::dynamic_pointer_cast<CoordinateOperation>( shared_from_this().as_nullable())); if (!swapSource && !swapTarget) { return l_this; } std::vector<CoordinateOperationNNPtr> subOps; if (swapSource) { auto op = Conversion::createAxisOrderReversal(false); op->setCRSs(l_sourceCRS->normalizeForVisualization(), NN_NO_CHECK(l_sourceCRS), nullptr); subOps.emplace_back(op); } subOps.emplace_back(l_this); if (swapTarget) { auto op = Conversion::createAxisOrderReversal(false); op->setCRSs(NN_NO_CHECK(l_targetCRS), l_targetCRS->normalizeForVisualization(), nullptr); subOps.emplace_back(op); } return util::nn_static_pointer_cast<CoordinateOperation>( ConcatenatedOperation::createComputeMetadata(subOps, true)); } // --------------------------------------------------------------------------- /** \brief Return a coordinate transformer for this operation. * * The returned coordinate transformer is tied to the provided context, * and should only be called by the thread "owning" the passed context. * It should not be used after the context has been destroyed. * * @param ctx Execution context to which the transformer will be tied to. * If null, the default context will be used (only sfe for * single-threaded applications). * @return a new CoordinateTransformer instance. * @since 9.3 * @throw UnsupportedOperationException if the transformer cannot be * instantiated. */ CoordinateTransformerNNPtr CoordinateOperation::coordinateTransformer(PJ_CONTEXT *ctx) const { auto l_this = NN_NO_CHECK(std::dynamic_pointer_cast<CoordinateOperation>( shared_from_this().as_nullable())); return CoordinateTransformer::create(l_this, ctx); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateOperationNNPtr CoordinateOperation::shallowClone() const { return _shallowClone(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CoordinateTransformer::Private { PJ *pj_; }; //! @endcond // --------------------------------------------------------------------------- CoordinateTransformer::CoordinateTransformer() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateTransformer::~CoordinateTransformer() { if (d->pj_) { proj_assign_context(d->pj_, pj_get_default_ctx()); proj_destroy(d->pj_); } } //! @endcond // --------------------------------------------------------------------------- CoordinateTransformerNNPtr CoordinateTransformer::create(const CoordinateOperationNNPtr &op, PJ_CONTEXT *ctx) { auto transformer = NN_NO_CHECK( CoordinateTransformer::make_unique<CoordinateTransformer>()); transformer->d->pj_ = pj_obj_create(ctx, op); if (transformer->d->pj_ == nullptr) throw util::UnsupportedOperationException( "Cannot instantiate transformer"); return transformer; } // --------------------------------------------------------------------------- /** Transforms a coordinate tuple. * * PJ_COORD is a union of many structures. In the context of this method, * it is prudent to only use the v[] array, with the understanding that * the expected input values should be passed in the order and the unit of * the successive axis of the input CRS. Similarly the values returned in the * v[] array of the output PJ_COORD are in the order and the unit of the * successive axis of the output CRS. * For coordinate operations involving a time-dependent operation, * coord.v[3] is the decimal year of the coordinate epoch of the input (or * HUGE_VAL to indicate none) * * If an error occurs, HUGE_VAL is returned in the .v[0] member of the output * coordinate tuple. * * Example how to transform coordinates from EPSG:4326 (WGS 84 * latitude/longitude) to EPSG:32631 (WGS 84 / UTM zone 31N). \code{.cpp} auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto coord_op_ctxt = CoordinateOperationContext::create( authFactory, nullptr, 0.0); auto authFactoryEPSG = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto list = CoordinateOperationFactory::create()->createOperations( authFactoryEPSG->createCoordinateReferenceSystem("4326"), authFactoryEPSG->createCoordinateReferenceSystem("32631"), coord_op_ctxt); ASSERT_TRUE(!list.empty()); PJ_CONTEXT* ctx = proj_context_create(); auto transformer = list[0]->coordinateTransformer(ctx); PJ_COORD c; c.v[0] = 49; // latitude in degree c.v[1] = 2; // longitude in degree c.v[2] = 0; c.v[3] = HUGE_VAL; c = transformer->transform(c); EXPECT_NEAR(c.v[0], 426857.98771728, 1e-8); // easting in metre EXPECT_NEAR(c.v[1], 5427937.52346492, 1e-8); // northing in metre proj_context_destroy(ctx); \endcode */ PJ_COORD CoordinateTransformer::transform(PJ_COORD coord) { return proj_trans(d->pj_, PJ_FWD, coord); } // --------------------------------------------------------------------------- OperationMethod::OperationMethod() : d(internal::make_unique<Private>()) {} // --------------------------------------------------------------------------- OperationMethod::OperationMethod(const OperationMethod &other) : IdentifiedObject(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress OperationMethod::~OperationMethod() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the formula(s) or procedure used by this coordinate operation * method. * * This may be a reference to a publication (in which case use * formulaCitation()). * * Note that the operation method may not be analytic, in which case this * attribute references or contains the procedure, not an analytic formula. * * @return the formula, or empty. */ const util::optional<std::string> &OperationMethod::formula() PROJ_PURE_DEFN { return d->formula_; } // --------------------------------------------------------------------------- /** \brief Return a reference to a publication giving the formula(s) or * procedure * used by the coordinate operation method. * * @return the formula citation, or empty. */ const util::optional<metadata::Citation> & OperationMethod::formulaCitation() PROJ_PURE_DEFN { return d->formulaCitation_; } // --------------------------------------------------------------------------- /** \brief Return the parameters of this operation method. * * @return the parameters. */ const std::vector<GeneralOperationParameterNNPtr> & OperationMethod::parameters() PROJ_PURE_DEFN { return d->parameters_; } // --------------------------------------------------------------------------- /** \brief Instantiate a operation method from a vector of * GeneralOperationParameter. * * @param properties See \ref general_properties. At minimum the name should be * defined. * @param parameters Vector of GeneralOperationParameterNNPtr. * @return a new OperationMethod. */ OperationMethodNNPtr OperationMethod::create( const util::PropertyMap &properties, const std::vector<GeneralOperationParameterNNPtr> &parameters) { OperationMethodNNPtr method( OperationMethod::nn_make_shared<OperationMethod>()); method->assignSelf(method); method->setProperties(properties); method->d->parameters_ = parameters; properties.getStringValue("proj_method", method->d->projMethodOverride_); return method; } // --------------------------------------------------------------------------- /** \brief Instantiate a operation method from a vector of OperationParameter. * * @param properties See \ref general_properties. At minimum the name should be * defined. * @param parameters Vector of OperationParameterNNPtr. * @return a new OperationMethod. */ OperationMethodNNPtr OperationMethod::create( const util::PropertyMap &properties, const std::vector<OperationParameterNNPtr> &parameters) { std::vector<GeneralOperationParameterNNPtr> parametersGeneral; parametersGeneral.reserve(parameters.size()); for (const auto &p : parameters) { parametersGeneral.push_back(p); } return create(properties, parametersGeneral); } // --------------------------------------------------------------------------- /** \brief Return the EPSG code, either directly, or through the name * @return code, or 0 if not found */ int OperationMethod::getEPSGCode() PROJ_PURE_DEFN { int epsg_code = IdentifiedObject::getEPSGCode(); if (epsg_code == 0) { auto l_name = nameStr(); if (ends_with(l_name, " (3D)")) { l_name.resize(l_name.size() - strlen(" (3D)")); } size_t nMethodNameCodes = 0; const auto methodNameCodes = getMethodNameCodes(nMethodNameCodes); for (size_t i = 0; i < nMethodNameCodes; ++i) { const auto &tuple = methodNameCodes[i]; if (metadata::Identifier::isEquivalentName(l_name.c_str(), tuple.name)) { return tuple.epsg_code; } } } return epsg_code; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void OperationMethod::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; formatter->startNode(isWKT2 ? io::WKTConstants::METHOD : io::WKTConstants::PROJECTION, !identifiers().empty()); std::string l_name(nameStr()); if (!isWKT2) { const MethodMapping *mapping = getMapping(this); if (mapping == nullptr) { l_name = replaceAll(l_name, " ", "_"); } else { if (l_name == PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X) { l_name = "Geostationary_Satellite"; } else { if (mapping->wkt1_name == nullptr) { throw io::FormattingException( std::string("Unsupported conversion method: ") + mapping->wkt2_name); } l_name = mapping->wkt1_name; } } } formatter->addQuotedString(l_name); if (formatter->outputId()) { formatID(formatter); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void OperationMethod::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext(formatter->MakeObjectContext("OperationMethod", !identifiers().empty())); writer->AddObjKey("name"); writer->Add(nameStr()); if (formatter->outputId()) { formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool OperationMethod::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherOM = dynamic_cast<const OperationMethod *>(other); if (otherOM == nullptr || !IdentifiedObject::_isEquivalentTo(other, criterion, dbContext)) { return false; } // TODO test formula and formulaCitation const auto &params = parameters(); const auto &otherParams = otherOM->parameters(); const auto paramsSize = params.size(); if (paramsSize != otherParams.size()) { return false; } if (criterion == util::IComparable::Criterion::STRICT) { for (size_t i = 0; i < paramsSize; i++) { if (!params[i]->_isEquivalentTo(otherParams[i].get(), criterion, dbContext)) { return false; } } } else { std::vector<bool> candidateIndices(paramsSize, true); for (size_t i = 0; i < paramsSize; i++) { bool found = false; for (size_t j = 0; j < paramsSize; j++) { if (candidateIndices[j] && params[i]->_isEquivalentTo(otherParams[j].get(), criterion, dbContext)) { candidateIndices[j] = false; found = true; break; } } if (!found) { return false; } } } return true; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GeneralParameterValue::Private {}; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeneralParameterValue::GeneralParameterValue() : d(nullptr) {} // --------------------------------------------------------------------------- GeneralParameterValue::GeneralParameterValue(const GeneralParameterValue &) : d(nullptr) {} //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeneralParameterValue::~GeneralParameterValue() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct OperationParameterValue::Private { OperationParameterNNPtr parameter; ParameterValueNNPtr parameterValue; Private(const OperationParameterNNPtr &parameterIn, const ParameterValueNNPtr &valueIn) : parameter(parameterIn), parameterValue(valueIn) {} }; //! @endcond // --------------------------------------------------------------------------- OperationParameterValue::OperationParameterValue( const OperationParameterValue &other) : GeneralParameterValue(other), d(internal::make_unique<Private>(*other.d)) {} // --------------------------------------------------------------------------- OperationParameterValue::OperationParameterValue( const OperationParameterNNPtr &parameterIn, const ParameterValueNNPtr &valueIn) : GeneralParameterValue(), d(internal::make_unique<Private>(parameterIn, valueIn)) {} // --------------------------------------------------------------------------- /** \brief Instantiate a OperationParameterValue. * * @param parameterIn Parameter (definition). * @param valueIn Parameter value. * @return a new OperationParameterValue. */ OperationParameterValueNNPtr OperationParameterValue::create(const OperationParameterNNPtr &parameterIn, const ParameterValueNNPtr &valueIn) { return OperationParameterValue::nn_make_shared<OperationParameterValue>( parameterIn, valueIn); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress OperationParameterValue::~OperationParameterValue() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the parameter (definition) * * @return the parameter (definition). */ const OperationParameterNNPtr & OperationParameterValue::parameter() PROJ_PURE_DEFN { return d->parameter; } // --------------------------------------------------------------------------- /** \brief Return the parameter value. * * @return the parameter value. */ const ParameterValueNNPtr & OperationParameterValue::parameterValue() PROJ_PURE_DEFN { return d->parameterValue; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void OperationParameterValue::_exportToWKT( // cppcheck-suppress passedByValue io::WKTFormatter *formatter) const { _exportToWKT(formatter, nullptr); } void OperationParameterValue::_exportToWKT(io::WKTFormatter *formatter, const MethodMapping *mapping) const { const ParamMapping *paramMapping = mapping ? getMapping(mapping, d->parameter) : nullptr; if (paramMapping && paramMapping->wkt1_name == nullptr) { return; } const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (isWKT2 && parameterValue()->type() == ParameterValue::Type::FILENAME) { formatter->startNode(io::WKTConstants::PARAMETERFILE, !parameter()->identifiers().empty()); } else { formatter->startNode(io::WKTConstants::PARAMETER, !parameter()->identifiers().empty()); } if (paramMapping) { formatter->addQuotedString(paramMapping->wkt1_name); } else { formatter->addQuotedString(parameter()->nameStr()); } parameterValue()->_exportToWKT(formatter); if (formatter->outputId()) { parameter()->formatID(formatter); } formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void OperationParameterValue::_exportToJSON( io::JSONFormatter *formatter) const { auto writer = formatter->writer(); auto objectContext(formatter->MakeObjectContext( "ParameterValue", !parameter()->identifiers().empty())); writer->AddObjKey("name"); writer->Add(parameter()->nameStr()); const auto &l_value(parameterValue()); const auto value_type = l_value->type(); if (value_type == ParameterValue::Type::MEASURE) { writer->AddObjKey("value"); writer->Add(l_value->value().value(), 15); writer->AddObjKey("unit"); const auto &l_unit(l_value->value().unit()); if (l_unit == common::UnitOfMeasure::METRE || l_unit == common::UnitOfMeasure::DEGREE || l_unit == common::UnitOfMeasure::SCALE_UNITY) { writer->Add(l_unit.name()); } else { l_unit._exportToJSON(formatter); } } else if (value_type == ParameterValue::Type::FILENAME) { writer->AddObjKey("value"); writer->Add(l_value->valueFile()); } else if (value_type == ParameterValue::Type::INTEGER) { writer->AddObjKey("value"); writer->Add(l_value->integerValue()); } if (formatter->outputId()) { parameter()->formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress /** Utility method used on WKT2 import to convert from abridged transformation * to "normal" transformation parameters. */ bool OperationParameterValue::convertFromAbridged( const std::string &paramName, double &val, const common::UnitOfMeasure *&unit, int &paramEPSGCode) { if (metadata::Identifier::isEquivalentName( paramName.c_str(), EPSG_NAME_PARAMETER_X_AXIS_TRANSLATION) || paramEPSGCode == EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION) { unit = &common::UnitOfMeasure::METRE; paramEPSGCode = EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION; return true; } else if (metadata::Identifier::isEquivalentName( paramName.c_str(), EPSG_NAME_PARAMETER_Y_AXIS_TRANSLATION) || paramEPSGCode == EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION) { unit = &common::UnitOfMeasure::METRE; paramEPSGCode = EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION; return true; } else if (metadata::Identifier::isEquivalentName( paramName.c_str(), EPSG_NAME_PARAMETER_Z_AXIS_TRANSLATION) || paramEPSGCode == EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION) { unit = &common::UnitOfMeasure::METRE; paramEPSGCode = EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION; return true; } else if (metadata::Identifier::isEquivalentName( paramName.c_str(), EPSG_NAME_PARAMETER_X_AXIS_ROTATION) || paramEPSGCode == EPSG_CODE_PARAMETER_X_AXIS_ROTATION) { unit = &common::UnitOfMeasure::ARC_SECOND; paramEPSGCode = EPSG_CODE_PARAMETER_X_AXIS_ROTATION; return true; } else if (metadata::Identifier::isEquivalentName( paramName.c_str(), EPSG_NAME_PARAMETER_Y_AXIS_ROTATION) || paramEPSGCode == EPSG_CODE_PARAMETER_Y_AXIS_ROTATION) { unit = &common::UnitOfMeasure::ARC_SECOND; paramEPSGCode = EPSG_CODE_PARAMETER_Y_AXIS_ROTATION; return true; } else if (metadata::Identifier::isEquivalentName( paramName.c_str(), EPSG_NAME_PARAMETER_Z_AXIS_ROTATION) || paramEPSGCode == EPSG_CODE_PARAMETER_Z_AXIS_ROTATION) { unit = &common::UnitOfMeasure::ARC_SECOND; paramEPSGCode = EPSG_CODE_PARAMETER_Z_AXIS_ROTATION; return true; } else if (metadata::Identifier::isEquivalentName( paramName.c_str(), EPSG_NAME_PARAMETER_SCALE_DIFFERENCE) || paramEPSGCode == EPSG_CODE_PARAMETER_SCALE_DIFFERENCE) { val = (val - 1.0) * 1e6; unit = &common::UnitOfMeasure::PARTS_PER_MILLION; paramEPSGCode = EPSG_CODE_PARAMETER_SCALE_DIFFERENCE; return true; } return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool OperationParameterValue::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherOPV = dynamic_cast<const OperationParameterValue *>(other); if (otherOPV == nullptr) { return false; } if (!d->parameter->_isEquivalentTo(otherOPV->d->parameter.get(), criterion, dbContext)) { return false; } if (criterion == util::IComparable::Criterion::STRICT) { return d->parameterValue->_isEquivalentTo( otherOPV->d->parameterValue.get(), criterion); } if (d->parameterValue->_isEquivalentTo(otherOPV->d->parameterValue.get(), criterion, dbContext)) { return true; } if (d->parameter->getEPSGCode() == EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE || d->parameter->getEPSGCode() == EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID) { if (parameterValue()->type() == ParameterValue::Type::MEASURE && otherOPV->parameterValue()->type() == ParameterValue::Type::MEASURE) { const double a = std::fmod(parameterValue()->value().convertToUnit( common::UnitOfMeasure::DEGREE) + 360.0, 360.0); const double b = std::fmod(otherOPV->parameterValue()->value().convertToUnit( common::UnitOfMeasure::DEGREE) + 360.0, 360.0); return std::fabs(a - b) <= 1e-10 * std::fabs(a); } } return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct GeneralOperationParameter::Private {}; //! @endcond // --------------------------------------------------------------------------- GeneralOperationParameter::GeneralOperationParameter() : d(nullptr) {} // --------------------------------------------------------------------------- GeneralOperationParameter::GeneralOperationParameter( const GeneralOperationParameter &other) : IdentifiedObject(other), d(nullptr) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress GeneralOperationParameter::~GeneralOperationParameter() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct OperationParameter::Private {}; //! @endcond // --------------------------------------------------------------------------- OperationParameter::OperationParameter() : d(nullptr) {} // --------------------------------------------------------------------------- OperationParameter::OperationParameter(const OperationParameter &other) : GeneralOperationParameter(other), d(nullptr) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress OperationParameter::~OperationParameter() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a OperationParameter. * * @param properties See \ref general_properties. At minimum the name should be * defined. * @return a new OperationParameter. */ OperationParameterNNPtr OperationParameter::create(const util::PropertyMap &properties) { OperationParameterNNPtr op( OperationParameter::nn_make_shared<OperationParameter>()); op->assignSelf(op); op->setProperties(properties); return op; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool OperationParameter::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherOP = dynamic_cast<const OperationParameter *>(other); if (otherOP == nullptr) { return false; } if (criterion == util::IComparable::Criterion::STRICT) { return IdentifiedObject::_isEquivalentTo(other, criterion, dbContext); } if (IdentifiedObject::_isEquivalentTo(other, criterion, dbContext)) { return true; } auto l_epsgCode = getEPSGCode(); return l_epsgCode != 0 && l_epsgCode == otherOP->getEPSGCode(); } //! @endcond // --------------------------------------------------------------------------- void OperationParameter::_exportToWKT(io::WKTFormatter *) const {} // --------------------------------------------------------------------------- /** \brief Return the name of a parameter designed by its EPSG code * @return name, or nullptr if not found */ const char *OperationParameter::getNameForEPSGCode(int epsg_code) noexcept { size_t nParamNameCodes = 0; const auto paramNameCodes = getParamNameCodes(nParamNameCodes); for (size_t i = 0; i < nParamNameCodes; ++i) { const auto &tuple = paramNameCodes[i]; if (tuple.epsg_code == epsg_code) { return tuple.name; } } return nullptr; } // --------------------------------------------------------------------------- /** \brief Return the EPSG code, either directly, or through the name * @return code, or 0 if not found */ int OperationParameter::getEPSGCode() PROJ_PURE_DEFN { int epsg_code = IdentifiedObject::getEPSGCode(); if (epsg_code == 0) { const auto &l_name = nameStr(); size_t nParamNameCodes = 0; const auto paramNameCodes = getParamNameCodes(nParamNameCodes); for (size_t i = 0; i < nParamNameCodes; ++i) { const auto &tuple = paramNameCodes[i]; if (metadata::Identifier::isEquivalentName(l_name.c_str(), tuple.name)) { return tuple.epsg_code; } } if (metadata::Identifier::isEquivalentName(l_name.c_str(), "Latitude of origin")) { return EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN; } if (metadata::Identifier::isEquivalentName(l_name.c_str(), "Scale factor")) { return EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN; } } return epsg_code; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct SingleOperation::Private { std::vector<GeneralParameterValueNNPtr> parameterValues_{}; OperationMethodNNPtr method_; explicit Private(const OperationMethodNNPtr &methodIn) : method_(methodIn) {} }; //! @endcond // --------------------------------------------------------------------------- SingleOperation::SingleOperation(const OperationMethodNNPtr &methodIn) : d(internal::make_unique<Private>(methodIn)) {} // --------------------------------------------------------------------------- SingleOperation::SingleOperation(const SingleOperation &other) : #if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT) CoordinateOperation(other), #endif d(internal::make_unique<Private>(*other.d)) { } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress SingleOperation::~SingleOperation() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Return the parameter values. * * @return the parameter values. */ const std::vector<GeneralParameterValueNNPtr> & SingleOperation::parameterValues() PROJ_PURE_DEFN { return d->parameterValues_; } // --------------------------------------------------------------------------- /** \brief Return the operation method associated to the operation. * * @return the operation method. */ const OperationMethodNNPtr &SingleOperation::method() PROJ_PURE_DEFN { return d->method_; } // --------------------------------------------------------------------------- void SingleOperation::setParameterValues( const std::vector<GeneralParameterValueNNPtr> &values) { d->parameterValues_ = values; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const ParameterValuePtr nullParameterValue; //! @endcond /** \brief Return the parameter value corresponding to a parameter name or * EPSG code * * @param paramName the parameter name (or empty, in which case epsg_code * should be non zero) * @param epsg_code the parameter EPSG code (possibly zero) * @return the value, or nullptr if not found. */ const ParameterValuePtr & SingleOperation::parameterValue(const std::string &paramName, int epsg_code) const noexcept { if (epsg_code) { for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &parameter = opParamvalue->parameter(); if (parameter->getEPSGCode() == epsg_code) { return opParamvalue->parameterValue(); } } } } for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &parameter = opParamvalue->parameter(); if (metadata::Identifier::isEquivalentName( paramName.c_str(), parameter->nameStr().c_str())) { return opParamvalue->parameterValue(); } } } for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &parameter = opParamvalue->parameter(); if (areEquivalentParameters(paramName, parameter->nameStr())) { return opParamvalue->parameterValue(); } } } return nullParameterValue; } // --------------------------------------------------------------------------- /** \brief Return the parameter value corresponding to a EPSG code * * @param epsg_code the parameter EPSG code * @return the value, or nullptr if not found. */ const ParameterValuePtr & SingleOperation::parameterValue(int epsg_code) const noexcept { for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &parameter = opParamvalue->parameter(); if (parameter->getEPSGCode() == epsg_code) { return opParamvalue->parameterValue(); } } } return nullParameterValue; } // --------------------------------------------------------------------------- /** \brief Return the parameter value, as a measure, corresponding to a * parameter name or EPSG code * * @param paramName the parameter name (or empty, in which case epsg_code * should be non zero) * @param epsg_code the parameter EPSG code (possibly zero) * @return the measure, or the empty Measure() object if not found. */ const common::Measure & SingleOperation::parameterValueMeasure(const std::string &paramName, int epsg_code) const noexcept { const auto &val = parameterValue(paramName, epsg_code); if (val && val->type() == ParameterValue::Type::MEASURE) { return val->value(); } return nullMeasure; } /** \brief Return the parameter value, as a measure, corresponding to a * EPSG code * * @param epsg_code the parameter EPSG code * @return the measure, or the empty Measure() object if not found. */ const common::Measure & SingleOperation::parameterValueMeasure(int epsg_code) const noexcept { const auto &val = parameterValue(epsg_code); if (val && val->type() == ParameterValue::Type::MEASURE) { return val->value(); } return nullMeasure; } //! @cond Doxygen_Suppress double SingleOperation::parameterValueNumericAsSI(int epsg_code) const noexcept { const auto &val = parameterValue(epsg_code); if (val && val->type() == ParameterValue::Type::MEASURE) { return val->value().getSIValue(); } return 0.0; } double SingleOperation::parameterValueNumeric( int epsg_code, const common::UnitOfMeasure &targetUnit) const noexcept { const auto &val = parameterValue(epsg_code); if (val && val->type() == ParameterValue::Type::MEASURE) { return val->value().convertToUnit(targetUnit); } return 0.0; } double SingleOperation::parameterValueNumeric( const char *param_name, const common::UnitOfMeasure &targetUnit) const noexcept { const auto &val = parameterValue(param_name, 0); if (val && val->type() == ParameterValue::Type::MEASURE) { return val->value().convertToUnit(targetUnit); } return 0.0; } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a PROJ-based single operation. * * \note The operation might internally be a pipeline chaining several * operations. * The use of the SingleOperation modeling here is mostly to be able to get * the PROJ string as a parameter. * * @param properties Properties * @param PROJString the PROJ string. * @param sourceCRS source CRS (might be null). * @param targetCRS target CRS (might be null). * @param accuracies Vector of positional accuracy (might be empty). * @return the new instance */ SingleOperationNNPtr SingleOperation::createPROJBased( const util::PropertyMap &properties, const std::string &PROJString, const crs::CRSPtr &sourceCRS, const crs::CRSPtr &targetCRS, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return util::nn_static_pointer_cast<SingleOperation>( PROJBasedOperation::create(properties, PROJString, sourceCRS, targetCRS, accuracies)); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool SingleOperation::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { return _isEquivalentTo(other, criterion, dbContext, false); } bool SingleOperation::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext, bool inOtherDirection) const { auto otherSO = dynamic_cast<const SingleOperation *>(other); if (otherSO == nullptr || (criterion == util::IComparable::Criterion::STRICT && !ObjectUsage::_isEquivalentTo(other, criterion, dbContext))) { return false; } const int methodEPSGCode = d->method_->getEPSGCode(); const int otherMethodEPSGCode = otherSO->d->method_->getEPSGCode(); bool equivalentMethods = (criterion == util::IComparable::Criterion::EQUIVALENT && methodEPSGCode != 0 && methodEPSGCode == otherMethodEPSGCode) || d->method_->_isEquivalentTo(otherSO->d->method_.get(), criterion, dbContext); if (!equivalentMethods && criterion == util::IComparable::Criterion::EQUIVALENT) { if ((methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA && otherMethodEPSGCode == EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL) || (otherMethodEPSGCode == EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA && methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL) || (methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA && otherMethodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL) || (otherMethodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA && methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL) || (methodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL && otherMethodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL) || (otherMethodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL && methodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL)) { auto geodCRS = dynamic_cast<const crs::GeodeticCRS *>(sourceCRS().get()); auto otherGeodCRS = dynamic_cast<const crs::GeodeticCRS *>( otherSO->sourceCRS().get()); if (geodCRS && otherGeodCRS && geodCRS->ellipsoid()->isSphere() && otherGeodCRS->ellipsoid()->isSphere()) { equivalentMethods = true; } } } if (!equivalentMethods) { if (criterion == util::IComparable::Criterion::EQUIVALENT) { const auto isTOWGS84Transf = [](int code) { return code == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC || code == EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC || code == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC || code == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D || code == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D || code == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D || code == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D || code == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D || code == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D; }; // Translation vs (PV or CF) // or different PV vs CF convention if (isTOWGS84Transf(methodEPSGCode) && isTOWGS84Transf(otherMethodEPSGCode)) { auto transf = static_cast<const Transformation *>(this); auto otherTransf = static_cast<const Transformation *>(otherSO); auto params = transf->getTOWGS84Parameters(); auto otherParams = otherTransf->getTOWGS84Parameters(); assert(params.size() == 7); assert(otherParams.size() == 7); for (size_t i = 0; i < 7; i++) { if (std::fabs(params[i] - otherParams[i]) > 1e-10 * std::fabs(params[i])) { return false; } } return true; } // _1SP methods can sometimes be equivalent to _2SP ones // Check it by using convertToOtherMethod() if (methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP && otherMethodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP) { // Convert from 2SP to 1SP as the other direction has more // degree of liberties. return otherSO->_isEquivalentTo(this, criterion, dbContext); } else if ((methodEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_A && otherMethodEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_B) || (methodEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_B && otherMethodEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_A) || (methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP && otherMethodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP)) { auto conv = dynamic_cast<const Conversion *>(this); if (conv) { auto eqConv = conv->convertToOtherMethod(otherMethodEPSGCode); if (eqConv) { return eqConv->_isEquivalentTo(other, criterion, dbContext); } } } } return false; } const auto &values = d->parameterValues_; const auto &otherValues = otherSO->d->parameterValues_; const auto valuesSize = values.size(); const auto otherValuesSize = otherValues.size(); if (criterion == util::IComparable::Criterion::STRICT) { if (valuesSize != otherValuesSize) { return false; } for (size_t i = 0; i < valuesSize; i++) { if (!values[i]->_isEquivalentTo(otherValues[i].get(), criterion, dbContext)) { return false; } } return true; } std::vector<bool> candidateIndices(otherValuesSize, true); bool equivalent = true; bool foundMissingArgs = valuesSize != otherValuesSize; for (size_t i = 0; equivalent && i < valuesSize; i++) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>(values[i].get()); if (!opParamvalue) return false; equivalent = false; bool sameNameDifferentValue = false; for (size_t j = 0; j < otherValuesSize; j++) { if (candidateIndices[j] && values[i]->_isEquivalentTo(otherValues[j].get(), criterion, dbContext)) { candidateIndices[j] = false; equivalent = true; break; } else if (candidateIndices[j]) { auto otherOpParamvalue = dynamic_cast<const OperationParameterValue *>( otherValues[j].get()); if (!otherOpParamvalue) return false; sameNameDifferentValue = opParamvalue->parameter()->_isEquivalentTo( otherOpParamvalue->parameter().get(), criterion, dbContext); if (sameNameDifferentValue) { candidateIndices[j] = false; break; } } } if (!equivalent && methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP) { // For LCC_2SP, the standard parallels can be switched and // this will result in the same result. const int paramEPSGCode = opParamvalue->parameter()->getEPSGCode(); if (paramEPSGCode == EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL || paramEPSGCode == EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL) { auto value_1st = parameterValue( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL); auto value_2nd = parameterValue( EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL); if (value_1st && value_2nd) { equivalent = value_1st->_isEquivalentTo( otherSO ->parameterValue( EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL) .get(), criterion, dbContext) && value_2nd->_isEquivalentTo( otherSO ->parameterValue( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL) .get(), criterion, dbContext); } } } if (equivalent) { continue; } if (sameNameDifferentValue) { break; } // If there are parameters in this method not found in the other one, // check that they are set to a default neutral value, that is 1 // for scale, and 0 otherwise. foundMissingArgs = true; const auto &value = opParamvalue->parameterValue(); if (value->type() != ParameterValue::Type::MEASURE) { break; } if (value->value().unit().type() == common::UnitOfMeasure::Type::SCALE) { equivalent = value->value().getSIValue() == 1.0; } else { equivalent = value->value().getSIValue() == 0.0; } } // In the case the arguments don't perfectly match, try the reverse // check. if (equivalent && foundMissingArgs && !inOtherDirection) { return otherSO->_isEquivalentTo(this, criterion, dbContext, true); } // Equivalent formulations of 2SP can have different parameters // Then convert to 1SP and compare. if (!equivalent && methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP) { auto conv = dynamic_cast<const Conversion *>(this); auto otherConv = dynamic_cast<const Conversion *>(other); if (conv && otherConv) { auto thisAs1SP = conv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); auto otherAs1SP = otherConv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); if (thisAs1SP && otherAs1SP) { equivalent = thisAs1SP->_isEquivalentTo(otherAs1SP.get(), criterion, dbContext); } } } return equivalent; } //! @endcond // --------------------------------------------------------------------------- std::set<GridDescription> SingleOperation::gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const { std::set<GridDescription> res; for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &value = opParamvalue->parameterValue(); if (value->type() == ParameterValue::Type::FILENAME) { const auto gridNames = split(value->valueFile(), ","); for (const auto &gridName : gridNames) { GridDescription desc; desc.shortName = gridName; if (databaseContext) { databaseContext->lookForGridInfo( desc.shortName, considerKnownGridsAsAvailable, desc.fullName, desc.packageName, desc.url, desc.directDownload, desc.openLicense, desc.available); } res.insert(desc); } } } } return res; } // --------------------------------------------------------------------------- /** \brief Validate the parameters used by a coordinate operation. * * Return whether the method is known or not, or a list of missing or extra * parameters for the operations recognized by this implementation. */ std::list<std::string> SingleOperation::validateParameters() const { std::list<std::string> res; const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const auto methodEPSGCode = l_method->getEPSGCode(); const auto findMapping = [methodEPSGCode, &methodName]( const MethodMapping *mappings, size_t mappingCount) -> const MethodMapping * { if (methodEPSGCode != 0) { for (size_t i = 0; i < mappingCount; ++i) { const auto &mapping = mappings[i]; if (methodEPSGCode == mapping.epsg_code) { return &mapping; } } } for (size_t i = 0; i < mappingCount; ++i) { const auto &mapping = mappings[i]; if (metadata::Identifier::isEquivalentName(mapping.wkt2_name, methodName.c_str())) { return &mapping; } } return nullptr; }; size_t nProjectionMethodMappings = 0; const auto projectionMethodMappings = getProjectionMethodMappings(nProjectionMethodMappings); const MethodMapping *methodMapping = findMapping(projectionMethodMappings, nProjectionMethodMappings); if (methodMapping == nullptr) { size_t nOtherMethodMappings = 0; const auto otherMethodMappings = getOtherMethodMappings(nOtherMethodMappings); methodMapping = findMapping(otherMethodMappings, nOtherMethodMappings); } if (!methodMapping) { res.emplace_back("Unknown method " + methodName); return res; } if (methodMapping->wkt2_name != methodName) { if (metadata::Identifier::isEquivalentName(methodMapping->wkt2_name, methodName.c_str())) { std::string msg("Method name "); msg += methodName; msg += " is equivalent to official "; msg += methodMapping->wkt2_name; msg += " but not strictly equal"; res.emplace_back(msg); } else { std::string msg("Method name "); msg += methodName; msg += ", matched to "; msg += methodMapping->wkt2_name; msg += ", through its EPSG code has not an equivalent name"; res.emplace_back(msg); } } if (methodEPSGCode != 0 && methodEPSGCode != methodMapping->epsg_code) { std::string msg("Method of EPSG code "); msg += toString(methodEPSGCode); msg += " does not match official code ("; msg += toString(methodMapping->epsg_code); msg += ')'; res.emplace_back(msg); } // Check if expected parameters are found for (int i = 0; methodMapping->params && methodMapping->params[i] != nullptr; ++i) { const auto *paramMapping = methodMapping->params[i]; const OperationParameterValue *opv = nullptr; for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &parameter = opParamvalue->parameter(); if ((paramMapping->epsg_code != 0 && parameter->getEPSGCode() == paramMapping->epsg_code) || ci_equal(parameter->nameStr(), paramMapping->wkt2_name)) { opv = opParamvalue; break; } } } if (!opv) { if ((methodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL || methodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL) && paramMapping == &paramLatitudeNatOrigin) { // extension of EPSG used by GDAL/PROJ, so we should not // warn on its absence. continue; } std::string msg("Cannot find expected parameter "); msg += paramMapping->wkt2_name; res.emplace_back(msg); continue; } const auto &parameter = opv->parameter(); if (paramMapping->wkt2_name != parameter->nameStr()) { if (ci_equal(parameter->nameStr(), paramMapping->wkt2_name)) { std::string msg("Parameter name "); msg += parameter->nameStr(); msg += " is equivalent to official "; msg += paramMapping->wkt2_name; msg += " but not strictly equal"; res.emplace_back(msg); } else { std::string msg("Parameter name "); msg += parameter->nameStr(); msg += ", matched to "; msg += paramMapping->wkt2_name; msg += ", through its EPSG code has not an equivalent name"; res.emplace_back(msg); } } const auto paramEPSGCode = parameter->getEPSGCode(); if (paramEPSGCode != 0 && paramEPSGCode != paramMapping->epsg_code) { std::string msg("Parameter of EPSG code "); msg += toString(paramEPSGCode); msg += " does not match official code ("; msg += toString(paramMapping->epsg_code); msg += ')'; res.emplace_back(msg); } } // Check if there are extra parameters for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &parameter = opParamvalue->parameter(); if (!getMapping(methodMapping, parameter)) { std::string msg("Parameter "); msg += parameter->nameStr(); msg += " found but not expected for this method"; res.emplace_back(msg); } } } return res; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool SingleOperation::isLongitudeRotation() const { return method()->getEPSGCode() == EPSG_CODE_METHOD_LONGITUDE_ROTATION; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string nullString; static const std::string &_getNTv1Filename(const SingleOperation *op, bool allowInverse) { const auto &l_method = op->method(); const auto &methodName = l_method->nameStr(); if (l_method->getEPSGCode() == EPSG_CODE_METHOD_NTV1 || (allowInverse && ci_equal(methodName, INVERSE_OF + EPSG_NAME_METHOD_NTV1))) { const auto &fileParameter = op->parameterValue( EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } // static const std::string &_getNTv2Filename(const SingleOperation *op, bool allowInverse) { const auto &l_method = op->method(); if (l_method->getEPSGCode() == EPSG_CODE_METHOD_NTV2 || (allowInverse && ci_equal(l_method->nameStr(), INVERSE_OF + EPSG_NAME_METHOD_NTV2))) { const auto &fileParameter = op->parameterValue( EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const std::string &Transformation::getNTv2Filename() const { return _getNTv2Filename(this, false); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string &_getCTABLE2Filename(const SingleOperation *op, bool allowInverse) { const auto &l_method = op->method(); const auto &methodName = l_method->nameStr(); if (ci_equal(methodName, PROJ_WKT2_NAME_METHOD_CTABLE2) || (allowInverse && ci_equal(methodName, INVERSE_OF + PROJ_WKT2_NAME_METHOD_CTABLE2))) { const auto &fileParameter = op->parameterValue( EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string & _getHorizontalShiftGTIFFFilename(const SingleOperation *op, bool allowInverse) { const auto &l_method = op->method(); const auto &methodName = l_method->nameStr(); if (ci_equal(methodName, PROJ_WKT2_NAME_METHOD_HORIZONTAL_SHIFT_GTIFF) || ci_equal(methodName, PROJ_WKT2_NAME_METHOD_GENERAL_SHIFT_GTIFF) || (allowInverse && ci_equal(methodName, INVERSE_OF + PROJ_WKT2_NAME_METHOD_HORIZONTAL_SHIFT_GTIFF)) || (allowInverse && ci_equal(methodName, INVERSE_OF + PROJ_WKT2_NAME_METHOD_GENERAL_SHIFT_GTIFF))) { { const auto &fileParameter = op->parameterValue( EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } { const auto &fileParameter = op->parameterValue( PROJ_WKT2_PARAMETER_LATITUDE_LONGITUDE_ELLIPOISDAL_HEIGHT_DIFFERENCE_FILE, 0); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string & _getGeocentricTranslationFilename(const SingleOperation *op, bool allowInverse) { const auto &l_method = op->method(); const auto &methodName = l_method->nameStr(); if (l_method->getEPSGCode() == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN || (allowInverse && ci_equal( methodName, INVERSE_OF + EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN))) { const auto &fileParameter = op->parameterValue(EPSG_NAME_PARAMETER_GEOCENTRIC_TRANSLATION_FILE, EPSG_CODE_PARAMETER_GEOCENTRIC_TRANSLATION_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string & _getGeographic3DOffsetByVelocityGridFilename(const SingleOperation *op, bool allowInverse) { const auto &l_method = op->method(); const auto &methodName = l_method->nameStr(); if (l_method->getEPSGCode() == EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN || (allowInverse && ci_equal( methodName, INVERSE_OF + EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN))) { const auto &fileParameter = op->parameterValue( EPSG_NAME_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE, EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string & _getVerticalOffsetByVelocityGridFilename(const SingleOperation *op, bool allowInverse) { const auto &l_method = op->method(); const auto &methodName = l_method->nameStr(); if (l_method->getEPSGCode() == EPSG_CODE_METHOD_VERTICAL_OFFSET_BY_VELOCITY_GRID_NRCAN || (allowInverse && ci_equal( methodName, INVERSE_OF + EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN))) { const auto &fileParameter = op->parameterValue( EPSG_NAME_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE, EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const std::string & _getHeightToGeographic3DFilename(const SingleOperation *op, bool allowInverse) { const auto &methodName = op->method()->nameStr(); if (ci_equal(methodName, PROJ_WKT2_NAME_METHOD_HEIGHT_TO_GEOG3D) || (allowInverse && ci_equal(methodName, INVERSE_OF + PROJ_WKT2_NAME_METHOD_HEIGHT_TO_GEOG3D))) { const auto &fileParameter = op->parameterValue(EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME, EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool Transformation::isGeographic3DToGravityRelatedHeight( const OperationMethodNNPtr &method, bool allowInverse) { const auto &methodName = method->nameStr(); static const char *const methodCodes[] = { "1025", // Geographic3D to GravityRelatedHeight (EGM2008) "1030", // Geographic3D to GravityRelatedHeight (NZgeoid) "1045", // Geographic3D to GravityRelatedHeight (OSGM02-Ire) "1047", // Geographic3D to GravityRelatedHeight (Gravsoft) "1048", // Geographic3D to GravityRelatedHeight (Ausgeoid v2) "1050", // Geographic3D to GravityRelatedHeight (CI) "1059", // Geographic3D to GravityRelatedHeight (PNG) "1088", // Geog3D to Geog2D+GravityRelatedHeight (gtx) "1060", // Geographic3D to GravityRelatedHeight (CGG2013) "1072", // Geographic3D to GravityRelatedHeight (OSGM15-Ire) "1073", // Geographic3D to GravityRelatedHeight (IGN2009) "1081", // Geographic3D to GravityRelatedHeight (BEV AT) "1083", // Geog3D to Geog2D+Vertical (AUSGeoid v2) "1089", // Geog3D to Geog2D+GravityRelatedHeight (BEV AT) "1090", // Geog3D to Geog2D+GravityRelatedHeight (CGG 2013) "1091", // Geog3D to Geog2D+GravityRelatedHeight (CI) "1092", // Geog3D to Geog2D+GravityRelatedHeight (EGM2008) "1093", // Geog3D to Geog2D+GravityRelatedHeight (Gravsoft) "1094", // Geog3D to Geog2D+GravityRelatedHeight (IGN1997) "1095", // Geog3D to Geog2D+GravityRelatedHeight (IGN2009) "1096", // Geog3D to Geog2D+GravityRelatedHeight (OSGM15-Ire) "1097", // Geog3D to Geog2D+GravityRelatedHeight (OSGM-GB) "1098", // Geog3D to Geog2D+GravityRelatedHeight (SA 2010) "1100", // Geog3D to Geog2D+GravityRelatedHeight (PL txt) "1103", // Geog3D to Geog2D+GravityRelatedHeight (EGM) "1105", // Geog3D to Geog2D+GravityRelatedHeight (ITAL2005) "1109", // Geographic3D to Depth (Gravsoft) "1110", // Geog3D to Geog2D+Depth (Gravsoft) "1115", // Geog3D to Geog2D+Depth (txt) "1118", // Geog3D to Geog2D+GravityRelatedHeight (ISG) "1122", // Geog3D to Geog2D+Depth (gtx) "1124", // Geog3D to Geog2D+GravityRelatedHeight (gtg) "1126", // Vertical change by geoid grid difference (NRCan) "9661", // Geographic3D to GravityRelatedHeight (EGM) "9662", // Geographic3D to GravityRelatedHeight (Ausgeoid98) "9663", // Geographic3D to GravityRelatedHeight (OSGM-GB) "9664", // Geographic3D to GravityRelatedHeight (IGN1997) "9665", // Geographic3D to GravityRelatedHeight (US .gtx) "9635", // Geog3D to Geog2D+GravityRelatedHeight (US .gtx) }; if (ci_find(methodName, "Geographic3D to GravityRelatedHeight") == 0) { return true; } if (allowInverse && ci_find(methodName, INVERSE_OF + "Geographic3D to GravityRelatedHeight") == 0) { return true; } for (const auto &code : methodCodes) { for (const auto &idSrc : method->identifiers()) { const auto &srcAuthName = *(idSrc->codeSpace()); const auto &srcCode = idSrc->code(); if (ci_equal(srcAuthName, "EPSG") && srcCode == code) { return true; } if (allowInverse && ci_equal(srcAuthName, "INVERSE(EPSG)") && srcCode == code) { return true; } } } return false; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const std::string &Transformation::getHeightToGeographic3DFilename() const { const std::string &ret = _getHeightToGeographic3DFilename(this, false); if (!ret.empty()) return ret; if (isGeographic3DToGravityRelatedHeight(method(), false)) { const auto &fileParameter = parameterValue(EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME, EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { return fileParameter->valueFile(); } } return nullString; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static util::PropertyMap createSimilarPropertiesOperation(const CoordinateOperationNNPtr &obj) { util::PropertyMap map; // The domain(s) are unchanged addDomains(map, obj.get()); const std::string &forwardName = obj->nameStr(); if (!forwardName.empty()) { map.set(common::IdentifiedObject::NAME_KEY, forwardName); } const std::string &remarks = obj->remarks(); if (!remarks.empty()) { map.set(common::IdentifiedObject::REMARKS_KEY, remarks); } addModifiedIdentifier(map, obj.get(), false, true); return map; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static TransformationNNPtr createNTv1(const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { return Transformation::create( properties, sourceCRSIn, targetCRSIn, nullptr, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_NTV1), {OperationParameter::create( util::PropertyMap() .set(common::IdentifiedObject::NAME_KEY, EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE) .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE))}, {ParameterValue::createFilename(filename)}, accuracies); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static util::PropertyMap createSimilarPropertiesMethod(common::IdentifiedObjectNNPtr obj) { util::PropertyMap map; const std::string &forwardName = obj->nameStr(); if (!forwardName.empty()) { map.set(common::IdentifiedObject::NAME_KEY, forwardName); } { auto ar = util::ArrayOfBaseObject::create(); for (const auto &idSrc : obj->identifiers()) { const auto &srcAuthName = *(idSrc->codeSpace()); const auto &srcCode = idSrc->code(); auto idsProp = util::PropertyMap().set( metadata::Identifier::CODESPACE_KEY, srcAuthName); ar->add(metadata::Identifier::create(srcCode, idsProp)); } if (!ar->empty()) { map.set(common::IdentifiedObject::IDENTIFIERS_KEY, ar); } } return map; } //! @endcond // --------------------------------------------------------------------------- static bool isRegularVerticalGridMethod(int methodEPSGCode, bool &reverseOffsetSign) { if (methodEPSGCode == EPSG_CODE_METHOD_VERTICALGRID_NRCAN_BYN || methodEPSGCode == EPSG_CODE_METHOD_VERTICALCHANGE_BY_GEOID_GRID_DIFFERENCE_NRCAN) { // NRCAN vertical shift grids use a reverse convention from other // grids: the value in the grid is the value to subtract from the // source vertical CRS to get the target value. reverseOffsetSign = true; return true; } reverseOffsetSign = false; return methodEPSGCode == EPSG_CODE_METHOD_VERTICALGRID_NZLVD || methodEPSGCode == EPSG_CODE_METHOD_VERTICALGRID_BEV_AT || methodEPSGCode == EPSG_CODE_METHOD_VERTICALGRID_GTX || methodEPSGCode == EPSG_CODE_METHOD_VERTICALGRID_PL_TXT; } // --------------------------------------------------------------------------- /** \brief Return an equivalent transformation to the current one, but using * PROJ alternative grid names. */ TransformationNNPtr SingleOperation::substitutePROJAlternativeGridNames( io::DatabaseContextNNPtr databaseContext) const { auto self = NN_NO_CHECK(std::dynamic_pointer_cast<Transformation>( shared_from_this().as_nullable())); const auto &l_method = method(); const int methodEPSGCode = l_method->getEPSGCode(); std::string projFilename; std::string projGridFormat; bool inverseDirection = false; const auto &NTv1Filename = _getNTv1Filename(this, false); const auto &NTv2Filename = _getNTv2Filename(this, false); std::string lasFilename; if (methodEPSGCode == EPSG_CODE_METHOD_NADCON || methodEPSGCode == EPSG_CODE_METHOD_NADCON5_2D || methodEPSGCode == EPSG_CODE_METHOD_NADCON5_3D) { const auto &latitudeFileParameter = parameterValue(EPSG_NAME_PARAMETER_LATITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_DIFFERENCE_FILE); const auto &longitudeFileParameter = parameterValue(EPSG_NAME_PARAMETER_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LONGITUDE_DIFFERENCE_FILE); if (latitudeFileParameter && latitudeFileParameter->type() == ParameterValue::Type::FILENAME && longitudeFileParameter && longitudeFileParameter->type() == ParameterValue::Type::FILENAME) { lasFilename = latitudeFileParameter->valueFile(); } } const auto &horizontalGridName = !NTv1Filename.empty() ? NTv1Filename : !NTv2Filename.empty() ? NTv2Filename : lasFilename; const auto l_interpolationCRS = interpolationCRS(); if (!horizontalGridName.empty() && databaseContext->lookForGridAlternative( horizontalGridName, projFilename, projGridFormat, inverseDirection)) { if (horizontalGridName == projFilename) { if (inverseDirection) { throw util::UnsupportedOperationException( "Inverse direction for " + projFilename + " not supported"); } return self; } const auto l_sourceCRSNull = sourceCRS(); const auto l_targetCRSNull = targetCRS(); if (l_sourceCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing sourceCRS"); } if (l_targetCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing targetCRS"); } auto l_sourceCRS = NN_NO_CHECK(l_sourceCRSNull); auto l_targetCRS = NN_NO_CHECK(l_targetCRSNull); const auto &l_accuracies = coordinateOperationAccuracies(); if (projGridFormat == "GTiff") { auto parameters = std::vector<OperationParameterNNPtr>{ methodEPSGCode == EPSG_CODE_METHOD_NADCON5_3D ? OperationParameter::create(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, PROJ_WKT2_PARAMETER_LATITUDE_LONGITUDE_ELLIPOISDAL_HEIGHT_DIFFERENCE_FILE)) : createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE)}; auto methodProperties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, (methodEPSGCode == EPSG_CODE_METHOD_NADCON5_2D || methodEPSGCode == EPSG_CODE_METHOD_NADCON5_3D) ? PROJ_WKT2_NAME_METHOD_GENERAL_SHIFT_GTIFF : PROJ_WKT2_NAME_METHOD_HORIZONTAL_SHIFT_GTIFF); auto values = std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename(projFilename)}; if (inverseDirection) { return Transformation::create( createPropertiesForInverse(self.as_nullable().get(), true, false), l_targetCRS, l_sourceCRS, l_interpolationCRS, methodProperties, parameters, values, l_accuracies) ->inverseAsTransformation(); } else { return Transformation::create( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, l_interpolationCRS, methodProperties, parameters, values, l_accuracies); } } else if (projGridFormat == "NTv1") { if (inverseDirection) { return createNTv1(createPropertiesForInverse( self.as_nullable().get(), true, false), l_targetCRS, l_sourceCRS, projFilename, l_accuracies) ->inverseAsTransformation(); } else { return createNTv1(createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, projFilename, l_accuracies); } } else if (projGridFormat == "NTv2") { if (inverseDirection) { return Transformation::createNTv2( createPropertiesForInverse(self.as_nullable().get(), true, false), l_targetCRS, l_sourceCRS, projFilename, l_accuracies) ->inverseAsTransformation(); } else { return Transformation::createNTv2( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, projFilename, l_accuracies); } } else if (projGridFormat == "CTable2") { auto parameters = std::vector<OperationParameterNNPtr>{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE)}; auto methodProperties = util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, PROJ_WKT2_NAME_METHOD_CTABLE2); auto values = std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename(projFilename)}; if (inverseDirection) { return Transformation::create( createPropertiesForInverse(self.as_nullable().get(), true, false), l_targetCRS, l_sourceCRS, l_interpolationCRS, methodProperties, parameters, values, l_accuracies) ->inverseAsTransformation(); } else { return Transformation::create( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, l_interpolationCRS, methodProperties, parameters, values, l_accuracies); } } } if (Transformation::isGeographic3DToGravityRelatedHeight(method(), false)) { const auto &fileParameter = parameterValue(EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME, EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { const auto &filename = fileParameter->valueFile(); if (databaseContext->lookForGridAlternative( filename, projFilename, projGridFormat, inverseDirection)) { if (inverseDirection) { throw util::UnsupportedOperationException( "Inverse direction for " "Geographic3DToGravityRelatedHeight not supported"); } if (filename == projFilename) { return self; } const auto l_sourceCRSNull = sourceCRS(); const auto l_targetCRSNull = targetCRS(); if (l_sourceCRSNull == nullptr) { throw util::UnsupportedOperationException( "Missing sourceCRS"); } if (l_targetCRSNull == nullptr) { throw util::UnsupportedOperationException( "Missing targetCRS"); } auto l_sourceCRS = NN_NO_CHECK(l_sourceCRSNull); auto l_targetCRS = NN_NO_CHECK(l_targetCRSNull); auto parameters = std::vector<OperationParameterNNPtr>{ createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME)}; #ifdef disabled_for_now if (inverseDirection) { return Transformation::create( createPropertiesForInverse( self.as_nullable().get(), true, false), l_targetCRS, l_sourceCRS, l_interpolationCRS, createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()) ->inverseAsTransformation(); } else #endif { return Transformation::create( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, l_interpolationCRS, createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()); } } } } const auto &geocentricTranslationFilename = _getGeocentricTranslationFilename(this, false); if (!geocentricTranslationFilename.empty()) { if (databaseContext->lookForGridAlternative( geocentricTranslationFilename, projFilename, projGridFormat, inverseDirection)) { if (inverseDirection) { throw util::UnsupportedOperationException( "Inverse direction for " "GeocentricTranslation not supported"); } if (geocentricTranslationFilename == projFilename) { return self; } const auto l_sourceCRSNull = sourceCRS(); const auto l_targetCRSNull = targetCRS(); if (l_sourceCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing sourceCRS"); } if (l_targetCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing targetCRS"); } auto l_sourceCRS = NN_NO_CHECK(l_sourceCRSNull); auto l_targetCRS = NN_NO_CHECK(l_targetCRSNull); auto parameters = std::vector<OperationParameterNNPtr>{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_GEOCENTRIC_TRANSLATION_FILE)}; return Transformation::create( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, l_interpolationCRS, createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()); } } const auto &geographic3DOffsetByVelocityGridFilename = _getGeographic3DOffsetByVelocityGridFilename(this, false); if (!geographic3DOffsetByVelocityGridFilename.empty()) { if (databaseContext->lookForGridAlternative( geographic3DOffsetByVelocityGridFilename, projFilename, projGridFormat, inverseDirection)) { if (inverseDirection) { throw util::UnsupportedOperationException( "Inverse direction for " "Geographic3DOFffsetByVelocityGrid not supported"); } if (geographic3DOffsetByVelocityGridFilename == projFilename) { return self; } const auto l_sourceCRSNull = sourceCRS(); const auto l_targetCRSNull = targetCRS(); if (l_sourceCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing sourceCRS"); } if (l_targetCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing targetCRS"); } auto l_sourceCRS = NN_NO_CHECK(l_sourceCRSNull); auto l_targetCRS = NN_NO_CHECK(l_targetCRSNull); auto parameters = std::vector<OperationParameterNNPtr>{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE)}; return Transformation::create( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, l_interpolationCRS, createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()); } } const auto &verticalOffsetByVelocityGridFilename = _getVerticalOffsetByVelocityGridFilename(this, false); if (!verticalOffsetByVelocityGridFilename.empty()) { if (databaseContext->lookForGridAlternative( verticalOffsetByVelocityGridFilename, projFilename, projGridFormat, inverseDirection)) { if (inverseDirection) { throw util::UnsupportedOperationException( "Inverse direction for " "VerticalOffsetByVelocityGrid not supported"); } if (verticalOffsetByVelocityGridFilename == projFilename) { return self; } const auto l_sourceCRSNull = sourceCRS(); const auto l_targetCRSNull = targetCRS(); if (l_sourceCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing sourceCRS"); } if (l_targetCRSNull == nullptr) { throw util::UnsupportedOperationException("Missing targetCRS"); } auto l_sourceCRS = NN_NO_CHECK(l_sourceCRSNull); auto l_targetCRS = NN_NO_CHECK(l_targetCRSNull); auto parameters = std::vector<OperationParameterNNPtr>{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE)}; return Transformation::create( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, l_interpolationCRS, createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()); } } bool reverseOffsetSign = false; if (methodEPSGCode == EPSG_CODE_METHOD_VERTCON || isRegularVerticalGridMethod(methodEPSGCode, reverseOffsetSign)) { int parameterCode = EPSG_CODE_PARAMETER_VERTICAL_OFFSET_FILE; auto fileParameter = parameterValue( EPSG_NAME_PARAMETER_VERTICAL_OFFSET_FILE, parameterCode); if (!fileParameter) { parameterCode = EPSG_CODE_PARAMETER_GEOID_MODEL_DIFFERENCE_FILE; fileParameter = parameterValue( EPSG_NAME_PARAMETER_GEOID_MODEL_DIFFERENCE_FILE, parameterCode); } if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { const auto &filename = fileParameter->valueFile(); if (databaseContext->lookForGridAlternative( filename, projFilename, projGridFormat, inverseDirection)) { if (filename == projFilename) { if (inverseDirection) { throw util::UnsupportedOperationException( "Inverse direction for " + projFilename + " not supported"); } return self; } const auto l_sourceCRSNull = sourceCRS(); const auto l_targetCRSNull = targetCRS(); if (l_sourceCRSNull == nullptr) { throw util::UnsupportedOperationException( "Missing sourceCRS"); } if (l_targetCRSNull == nullptr) { throw util::UnsupportedOperationException( "Missing targetCRS"); } auto l_sourceCRS = NN_NO_CHECK(l_sourceCRSNull); auto l_targetCRS = NN_NO_CHECK(l_targetCRSNull); auto parameters = std::vector<OperationParameterNNPtr>{ createOpParamNameEPSGCode(parameterCode)}; if (inverseDirection) { return Transformation::create( createPropertiesForInverse( self.as_nullable().get(), true, false), l_targetCRS, l_sourceCRS, l_interpolationCRS, createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()) ->inverseAsTransformation(); } else { return Transformation::create( createSimilarPropertiesOperation(self), l_sourceCRS, l_targetCRS, l_interpolationCRS, createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()); } } } } return self; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ParameterValue::Private { ParameterValue::Type type_{ParameterValue::Type::STRING}; std::unique_ptr<common::Measure> measure_{}; std::unique_ptr<std::string> stringValue_{}; int integerValue_{}; bool booleanValue_{}; explicit Private(const common::Measure &valueIn) : type_(ParameterValue::Type::MEASURE), measure_(internal::make_unique<common::Measure>(valueIn)) {} Private(const std::string &stringValueIn, ParameterValue::Type typeIn) : type_(typeIn), stringValue_(internal::make_unique<std::string>(stringValueIn)) {} explicit Private(int integerValueIn) : type_(ParameterValue::Type::INTEGER), integerValue_(integerValueIn) {} explicit Private(bool booleanValueIn) : type_(ParameterValue::Type::BOOLEAN), booleanValue_(booleanValueIn) {} }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ParameterValue::~ParameterValue() = default; //! @endcond // --------------------------------------------------------------------------- ParameterValue::ParameterValue(const common::Measure &measureIn) : d(internal::make_unique<Private>(measureIn)) {} // --------------------------------------------------------------------------- ParameterValue::ParameterValue(const std::string &stringValueIn, ParameterValue::Type typeIn) : d(internal::make_unique<Private>(stringValueIn, typeIn)) {} // --------------------------------------------------------------------------- ParameterValue::ParameterValue(int integerValueIn) : d(internal::make_unique<Private>(integerValueIn)) {} // --------------------------------------------------------------------------- ParameterValue::ParameterValue(bool booleanValueIn) : d(internal::make_unique<Private>(booleanValueIn)) {} // --------------------------------------------------------------------------- /** \brief Instantiate a ParameterValue from a Measure (i.e. a value associated * with a * unit) * * @return a new ParameterValue. */ ParameterValueNNPtr ParameterValue::create(const common::Measure &measureIn) { return ParameterValue::nn_make_shared<ParameterValue>(measureIn); } // --------------------------------------------------------------------------- /** \brief Instantiate a ParameterValue from a string value. * * @return a new ParameterValue. */ ParameterValueNNPtr ParameterValue::create(const char *stringValueIn) { return ParameterValue::nn_make_shared<ParameterValue>( std::string(stringValueIn), ParameterValue::Type::STRING); } // --------------------------------------------------------------------------- /** \brief Instantiate a ParameterValue from a string value. * * @return a new ParameterValue. */ ParameterValueNNPtr ParameterValue::create(const std::string &stringValueIn) { return ParameterValue::nn_make_shared<ParameterValue>( stringValueIn, ParameterValue::Type::STRING); } // --------------------------------------------------------------------------- /** \brief Instantiate a ParameterValue from a filename. * * @return a new ParameterValue. */ ParameterValueNNPtr ParameterValue::createFilename(const std::string &stringValueIn) { return ParameterValue::nn_make_shared<ParameterValue>( stringValueIn, ParameterValue::Type::FILENAME); } // --------------------------------------------------------------------------- /** \brief Instantiate a ParameterValue from a integer value. * * @return a new ParameterValue. */ ParameterValueNNPtr ParameterValue::create(int integerValueIn) { return ParameterValue::nn_make_shared<ParameterValue>(integerValueIn); } // --------------------------------------------------------------------------- /** \brief Instantiate a ParameterValue from a boolean value. * * @return a new ParameterValue. */ ParameterValueNNPtr ParameterValue::create(bool booleanValueIn) { return ParameterValue::nn_make_shared<ParameterValue>(booleanValueIn); } // --------------------------------------------------------------------------- /** \brief Returns the type of a parameter value. * * @return the type. */ const ParameterValue::Type &ParameterValue::type() PROJ_PURE_DEFN { return d->type_; } // --------------------------------------------------------------------------- /** \brief Returns the value as a Measure (assumes type() == Type::MEASURE) * @return the value as a Measure. */ const common::Measure &ParameterValue::value() PROJ_PURE_DEFN { return *d->measure_; } // --------------------------------------------------------------------------- /** \brief Returns the value as a string (assumes type() == Type::STRING) * @return the value as a string. */ const std::string &ParameterValue::stringValue() PROJ_PURE_DEFN { return *d->stringValue_; } // --------------------------------------------------------------------------- /** \brief Returns the value as a filename (assumes type() == Type::FILENAME) * @return the value as a filename. */ const std::string &ParameterValue::valueFile() PROJ_PURE_DEFN { return *d->stringValue_; } // --------------------------------------------------------------------------- /** \brief Returns the value as a integer (assumes type() == Type::INTEGER) * @return the value as a integer. */ int ParameterValue::integerValue() PROJ_PURE_DEFN { return d->integerValue_; } // --------------------------------------------------------------------------- /** \brief Returns the value as a boolean (assumes type() == Type::BOOLEAN) * @return the value as a boolean. */ bool ParameterValue::booleanValue() PROJ_PURE_DEFN { return d->booleanValue_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ParameterValue::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; const auto &l_type = type(); if (l_type == Type::MEASURE) { const auto &l_value = value(); if (formatter->abridgedTransformation()) { const auto &unit = l_value.unit(); const auto &unitType = unit.type(); if (unitType == common::UnitOfMeasure::Type::LINEAR) { formatter->add(l_value.getSIValue()); } else if (unitType == common::UnitOfMeasure::Type::ANGULAR) { formatter->add( l_value.convertToUnit(common::UnitOfMeasure::ARC_SECOND)); } else if (unit == common::UnitOfMeasure::PARTS_PER_MILLION) { formatter->add(1.0 + l_value.value() * 1e-6); } else { formatter->add(l_value.value()); } } else { const auto &unit = l_value.unit(); if (isWKT2) { formatter->add(l_value.value()); } else { // In WKT1, as we don't output the natural unit, output to the // registered linear / angular unit. const auto &unitType = unit.type(); if (unitType == common::UnitOfMeasure::Type::LINEAR) { const auto &targetUnit = *(formatter->axisLinearUnit()); if (targetUnit.conversionToSI() == 0.0) { throw io::FormattingException( "cannot convert value to target linear unit"); } formatter->add(l_value.convertToUnit(targetUnit)); } else if (unitType == common::UnitOfMeasure::Type::ANGULAR) { const auto &targetUnit = *(formatter->axisAngularUnit()); if (targetUnit.conversionToSI() == 0.0) { throw io::FormattingException( "cannot convert value to target angular unit"); } formatter->add(l_value.convertToUnit(targetUnit)); } else { formatter->add(l_value.getSIValue()); } } if (isWKT2 && unit != common::UnitOfMeasure::NONE) { if (!formatter ->primeMeridianOrParameterUnitOmittedIfSameAsAxis() || (unit != common::UnitOfMeasure::SCALE_UNITY && unit != *(formatter->axisLinearUnit()) && unit != *(formatter->axisAngularUnit()))) { unit._exportToWKT(formatter); } } } } else if (l_type == Type::STRING || l_type == Type::FILENAME) { formatter->addQuotedString(stringValue()); } else if (l_type == Type::INTEGER) { formatter->add(integerValue()); } else { throw io::FormattingException("boolean parameter value not handled"); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool ParameterValue::_isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &) const { auto otherPV = dynamic_cast<const ParameterValue *>(other); if (otherPV == nullptr) { return false; } if (type() != otherPV->type()) { return false; } switch (type()) { case Type::MEASURE: { return value()._isEquivalentTo(otherPV->value(), criterion, 2e-10); } case Type::STRING: case Type::FILENAME: { return stringValue() == otherPV->stringValue(); } case Type::INTEGER: { return integerValue() == otherPV->integerValue(); } case Type::BOOLEAN: { return booleanValue() == otherPV->booleanValue(); } default: { assert(false); break; } } return true; } //! @endcond //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- InvalidOperation::InvalidOperation(const char *message) : Exception(message) {} // --------------------------------------------------------------------------- InvalidOperation::InvalidOperation(const std::string &message) : Exception(message) {} // --------------------------------------------------------------------------- InvalidOperation::InvalidOperation(const InvalidOperation &) = default; // --------------------------------------------------------------------------- InvalidOperation::~InvalidOperation() = default; //! @endcond // --------------------------------------------------------------------------- GeneralParameterValueNNPtr SingleOperation::createOperationParameterValueFromInterpolationCRS( int methodEPSGCode, int crsEPSGCode) { util::PropertyMap propertiesParameter; propertiesParameter.set( common::IdentifiedObject::NAME_KEY, methodEPSGCode == EPSG_CODE_METHOD_VERTICAL_OFFSET_AND_SLOPE ? EPSG_NAME_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS : EPSG_NAME_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS); propertiesParameter.set( metadata::Identifier::CODE_KEY, methodEPSGCode == EPSG_CODE_METHOD_VERTICAL_OFFSET_AND_SLOPE ? EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS : EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS); propertiesParameter.set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG); return OperationParameterValue::create( OperationParameter::create(propertiesParameter), ParameterValue::create(crsEPSGCode)); } // --------------------------------------------------------------------------- void SingleOperation::exportTransformationToWKT( io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { throw io::FormattingException( "Transformation can only be exported to WKT2"); } if (formatter->abridgedTransformation()) { formatter->startNode(io::WKTConstants::ABRIDGEDTRANSFORMATION, !identifiers().empty()); } else { formatter->startNode(io::WKTConstants::COORDINATEOPERATION, !identifiers().empty()); } formatter->addQuotedString(nameStr()); if (formatter->use2019Keywords()) { const auto &version = operationVersion(); if (version.has_value()) { formatter->startNode(io::WKTConstants::VERSION, false); formatter->addQuotedString(*version); formatter->endNode(); } } if (!formatter->abridgedTransformation()) { exportSourceCRSAndTargetCRSToWKT(this, formatter); } const auto &l_method = method(); l_method->_exportToWKT(formatter); bool hasInterpolationCRSParameter = false; for (const auto &paramValue : parameterValues()) { const auto opParamvalue = dynamic_cast<const OperationParameterValue *>(paramValue.get()); const int paramEPSGCode = opParamvalue ? opParamvalue->parameter()->getEPSGCode() : 0; if (paramEPSGCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS || paramEPSGCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS) { hasInterpolationCRSParameter = true; } paramValue->_exportToWKT(formatter, nullptr); } const auto l_interpolationCRS = interpolationCRS(); if (formatter->abridgedTransformation()) { // If we have an interpolation CRS that has a EPSG code, then // we can export it as a PARAMETER[] if (!hasInterpolationCRSParameter && l_interpolationCRS) { const auto code = l_interpolationCRS->getEPSGCode(); if (code != 0) { const auto methodEPSGCode = l_method->getEPSGCode(); createOperationParameterValueFromInterpolationCRS( methodEPSGCode, code) ->_exportToWKT(formatter, nullptr); } } } else { if (l_interpolationCRS) { formatter->startNode(io::WKTConstants::INTERPOLATIONCRS, false); interpolationCRS()->_exportToWKT(formatter); formatter->endNode(); } if (!coordinateOperationAccuracies().empty()) { formatter->startNode(io::WKTConstants::OPERATIONACCURACY, false); formatter->add(coordinateOperationAccuracies()[0]->value()); formatter->endNode(); } } ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // If crs is a geographic CRS, or a compound CRS of a geographic CRS, // or a compoundCRS of a bound CRS of a geographic CRS, return that // geographic CRS static crs::GeographicCRSPtr extractGeographicCRSIfGeographicCRSOrEquivalent(const crs::CRSNNPtr &crs) { auto geogCRS = util::nn_dynamic_pointer_cast<crs::GeographicCRS>(crs); if (!geogCRS) { auto compoundCRS = util::nn_dynamic_pointer_cast<crs::CompoundCRS>(crs); if (compoundCRS) { const auto &components = compoundCRS->componentReferenceSystems(); if (!components.empty()) { geogCRS = util::nn_dynamic_pointer_cast<crs::GeographicCRS>( components[0]); if (!geogCRS) { auto boundCRS = util::nn_dynamic_pointer_cast<crs::BoundCRS>( components[0]); if (boundCRS) { geogCRS = util::nn_dynamic_pointer_cast<crs::GeographicCRS>( boundCRS->baseCRS()); } } } } else { auto boundCRS = util::nn_dynamic_pointer_cast<crs::BoundCRS>(crs); if (boundCRS) { geogCRS = util::nn_dynamic_pointer_cast<crs::GeographicCRS>( boundCRS->baseCRS()); } } } return geogCRS; } // --------------------------------------------------------------------------- [[noreturn]] static void ThrowExceptionNotGeodeticGeographic(const char *trfrm_name) { throw io::FormattingException(concat("Can apply ", std::string(trfrm_name), " only to GeodeticCRS / " "GeographicCRS")); } // --------------------------------------------------------------------------- static void setupPROJGeodeticSourceCRS(io::PROJStringFormatter *formatter, const crs::CRSNNPtr &crs, bool addPushV3, const char *trfrm_name) { auto sourceCRSGeog = extractGeographicCRSIfGeographicCRSOrEquivalent(crs); if (sourceCRSGeog) { formatter->startInversion(); sourceCRSGeog->_exportToPROJString(formatter); formatter->stopInversion(); if (util::isOfExactType<crs::DerivedGeographicCRS>( *(sourceCRSGeog.get()))) { const auto derivedGeogCRS = dynamic_cast<const crs::DerivedGeographicCRS *>( sourceCRSGeog.get()); // The export of a DerivedGeographicCRS in non-CRS mode adds // unit conversion and axis swapping to the base CRS. // We must compensate for that formatter->startInversion(); formatter->startInversion(); derivedGeogCRS->baseCRS()->addAngularUnitConvertAndAxisSwap( formatter); formatter->stopInversion(); } if (addPushV3) { formatter->addStep("push"); formatter->addParam("v_3"); } formatter->addStep("cart"); sourceCRSGeog->ellipsoid()->_exportToPROJString(formatter); } else { auto sourceCRSGeod = dynamic_cast<const crs::GeodeticCRS *>(crs.get()); if (!sourceCRSGeod) { ThrowExceptionNotGeodeticGeographic(trfrm_name); } formatter->startInversion(); sourceCRSGeod->addGeocentricUnitConversionIntoPROJString(formatter); formatter->stopInversion(); } } // --------------------------------------------------------------------------- static void setupPROJGeodeticTargetCRS(io::PROJStringFormatter *formatter, const crs::CRSNNPtr &crs, bool addPopV3, const char *trfrm_name) { auto targetCRSGeog = extractGeographicCRSIfGeographicCRSOrEquivalent(crs); if (targetCRSGeog) { formatter->addStep("cart"); formatter->setCurrentStepInverted(true); targetCRSGeog->ellipsoid()->_exportToPROJString(formatter); if (addPopV3) { formatter->addStep("pop"); formatter->addParam("v_3"); } if (util::isOfExactType<crs::DerivedGeographicCRS>( *(targetCRSGeog.get()))) { // The export of a DerivedGeographicCRS in non-CRS mode adds // unit conversion and axis swapping to the base CRS. // We must compensate for that formatter->startInversion(); const auto derivedGeogCRS = dynamic_cast<const crs::DerivedGeographicCRS *>( targetCRSGeog.get()); derivedGeogCRS->baseCRS()->addAngularUnitConvertAndAxisSwap( formatter); } targetCRSGeog->_exportToPROJString(formatter); } else { auto targetCRSGeod = dynamic_cast<const crs::GeodeticCRS *>(crs.get()); if (!targetCRSGeod) { ThrowExceptionNotGeodeticGeographic(trfrm_name); } targetCRSGeod->addGeocentricUnitConversionIntoPROJString(formatter); } } //! @endcond // --------------------------------------------------------------------------- /* static */ void SingleOperation::exportToPROJStringChangeVerticalUnit( io::PROJStringFormatter *formatter, double convFactor) { const auto uom = common::UnitOfMeasure(std::string(), convFactor, common::UnitOfMeasure::Type::LINEAR) .exportToPROJString(); const std::string reverse_uom( convFactor == 0.0 ? std::string() : common::UnitOfMeasure(std::string(), 1.0 / convFactor, common::UnitOfMeasure::Type::LINEAR) .exportToPROJString()); if (uom == "m") { // do nothing } else if (!uom.empty()) { formatter->addStep("unitconvert"); formatter->addParam("z_in", uom); formatter->addParam("z_out", "m"); } else if (!reverse_uom.empty()) { formatter->addStep("unitconvert"); formatter->addParam("z_in", "m"); formatter->addParam("z_out", reverse_uom); } else if (fabs(convFactor - common::UnitOfMeasure::FOOT.conversionToSI() / common::UnitOfMeasure::US_FOOT.conversionToSI()) < 1e-10) { formatter->addStep("unitconvert"); formatter->addParam("z_in", "ft"); formatter->addParam("z_out", "us-ft"); } else if (fabs(convFactor - common::UnitOfMeasure::US_FOOT.conversionToSI() / common::UnitOfMeasure::FOOT.conversionToSI()) < 1e-10) { formatter->addStep("unitconvert"); formatter->addParam("z_in", "us-ft"); formatter->addParam("z_out", "ft"); } else { formatter->addStep("affine"); formatter->addParam("s33", convFactor); } } // --------------------------------------------------------------------------- bool SingleOperation::exportToPROJStringGeneric( io::PROJStringFormatter *formatter) const { const int methodEPSGCode = method()->getEPSGCode(); if (methodEPSGCode == EPSG_CODE_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION) { const double A0 = parameterValueMeasure(EPSG_CODE_PARAMETER_A0).value(); const double A1 = parameterValueMeasure(EPSG_CODE_PARAMETER_A1).value(); const double A2 = parameterValueMeasure(EPSG_CODE_PARAMETER_A2).value(); const double B0 = parameterValueMeasure(EPSG_CODE_PARAMETER_B0).value(); const double B1 = parameterValueMeasure(EPSG_CODE_PARAMETER_B1).value(); const double B2 = parameterValueMeasure(EPSG_CODE_PARAMETER_B2).value(); // Do not mess with axis unit and order for that transformation formatter->addStep("affine"); formatter->addParam("xoff", A0); formatter->addParam("s11", A1); formatter->addParam("s12", A2); formatter->addParam("yoff", B0); formatter->addParam("s21", B1); formatter->addParam("s22", B2); return true; } if (methodEPSGCode == EPSG_CODE_METHOD_SIMILARITY_TRANSFORMATION) { const double XT0 = parameterValueMeasure( EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT_TARGET_CRS) .value(); const double YT0 = parameterValueMeasure( EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT_TARGET_CRS) .value(); const double M = parameterValueMeasure( EPSG_CODE_PARAMETER_SCALE_FACTOR_FOR_SOURCE_CRS_AXES) .value(); const double q = parameterValueNumeric( EPSG_CODE_PARAMETER_ROTATION_ANGLE_OF_SOURCE_CRS_AXES, common::UnitOfMeasure::RADIAN); // Do not mess with axis unit and order for that transformation formatter->addStep("affine"); formatter->addParam("xoff", XT0); formatter->addParam("s11", M * cos(q)); formatter->addParam("s12", M * sin(q)); formatter->addParam("yoff", YT0); formatter->addParam("s21", -M * sin(q)); formatter->addParam("s22", M * cos(q)); return true; } if (isAxisOrderReversal(methodEPSGCode)) { formatter->addStep("axisswap"); formatter->addParam("order", "2,1"); auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRS().get()); auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRS().get()); if (sourceCRSGeog && targetCRSGeog) { const auto &unitSrc = sourceCRSGeog->coordinateSystem()->axisList()[0]->unit(); const auto &unitDst = targetCRSGeog->coordinateSystem()->axisList()[0]->unit(); if (!unitSrc._isEquivalentTo( unitDst, util::IComparable::Criterion::EQUIVALENT)) { formatter->addStep("unitconvert"); auto projUnit = unitSrc.exportToPROJString(); if (projUnit.empty()) { formatter->addParam("xy_in", unitSrc.conversionToSI()); } else { formatter->addParam("xy_in", projUnit); } projUnit = unitDst.exportToPROJString(); if (projUnit.empty()) { formatter->addParam("xy_out", unitDst.conversionToSI()); } else { formatter->addParam("xy_out", projUnit); } } } return true; } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC_GEOCENTRIC) { auto sourceCRSGeod = dynamic_cast<const crs::GeodeticCRS *>(sourceCRS().get()); auto targetCRSGeod = dynamic_cast<const crs::GeodeticCRS *>(targetCRS().get()); if (sourceCRSGeod && targetCRSGeod) { auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRSGeod); auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRSGeod); bool isSrcGeocentric = sourceCRSGeod->isGeocentric(); bool isSrcGeographic = sourceCRSGeog != nullptr; bool isTargetGeocentric = targetCRSGeod->isGeocentric(); bool isTargetGeographic = targetCRSGeog != nullptr; if ((isSrcGeocentric && isTargetGeographic) || (isSrcGeographic && isTargetGeocentric)) { formatter->startInversion(); sourceCRSGeod->_exportToPROJString(formatter); formatter->stopInversion(); targetCRSGeod->_exportToPROJString(formatter); return true; } } throw io::FormattingException("Invalid nature of source and/or " "targetCRS for Geographic/Geocentric " "conversion"); } if (methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT) { const double convFactor = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR); exportToPROJStringChangeVerticalUnit(formatter, convFactor); return true; } if (methodEPSGCode == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { formatter->addStep("axisswap"); formatter->addParam("order", "1,2,-3"); return true; } formatter->setCoordinateOperationOptimizations(true); bool positionVectorConvention = true; bool sevenParamsTransform = false; bool threeParamsTransform = false; bool fifteenParamsTransform = false; const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const auto paramCount = parameterValues().size(); const bool l_isTimeDependent = isTimeDependent(methodName); const bool isPositionVector = ci_find(methodName, "Position Vector") != std::string::npos || ci_find(methodName, "PV") != std::string::npos; const bool isCoordinateFrame = ci_find(methodName, "Coordinate Frame") != std::string::npos || ci_find(methodName, "CF") != std::string::npos; if ((paramCount == 7 && isCoordinateFrame && !l_isTimeDependent) || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D) { positionVectorConvention = false; sevenParamsTransform = true; } else if ( (paramCount == 15 && isCoordinateFrame && l_isTimeDependent) || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D) { positionVectorConvention = false; fifteenParamsTransform = true; } else if ((paramCount == 7 && isPositionVector && !l_isTimeDependent) || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D) { sevenParamsTransform = true; } else if ( (paramCount == 15 && isPositionVector && l_isTimeDependent) || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D) { fifteenParamsTransform = true; } else if ((paramCount == 3 && ci_find(methodName, "Geocentric translations") != std::string::npos) || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D) { threeParamsTransform = true; } if (threeParamsTransform || sevenParamsTransform || fifteenParamsTransform) { double x = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION); double y = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION); double z = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION); auto l_sourceCRS = sourceCRS(); auto l_targetCRS = targetCRS(); auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(l_sourceCRS.get()); auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(l_targetCRS.get()); const bool addPushPopV3 = ((sourceCRSGeog && sourceCRSGeog->coordinateSystem()->axisList().size() == 2) || (targetCRSGeog && targetCRSGeog->coordinateSystem()->axisList().size() == 2)); if (l_sourceCRS) { setupPROJGeodeticSourceCRS(formatter, NN_NO_CHECK(l_sourceCRS), addPushPopV3, "Helmert"); } formatter->addStep("helmert"); formatter->addParam("x", x); formatter->addParam("y", y); formatter->addParam("z", z); if (sevenParamsTransform || fifteenParamsTransform) { double rx = parameterValueNumeric(EPSG_CODE_PARAMETER_X_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND); double ry = parameterValueNumeric(EPSG_CODE_PARAMETER_Y_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND); double rz = parameterValueNumeric(EPSG_CODE_PARAMETER_Z_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND); double scaleDiff = parameterValueNumeric(EPSG_CODE_PARAMETER_SCALE_DIFFERENCE, common::UnitOfMeasure::PARTS_PER_MILLION); formatter->addParam("rx", rx); formatter->addParam("ry", ry); formatter->addParam("rz", rz); formatter->addParam("s", scaleDiff); if (fifteenParamsTransform) { double rate_x = parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION, common::UnitOfMeasure::METRE_PER_YEAR); double rate_y = parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION, common::UnitOfMeasure::METRE_PER_YEAR); double rate_z = parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION, common::UnitOfMeasure::METRE_PER_YEAR); double rate_rx = parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND_PER_YEAR); double rate_ry = parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND_PER_YEAR); double rate_rz = parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND_PER_YEAR); double rate_scaleDiff = parameterValueNumeric( EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE, common::UnitOfMeasure::PPM_PER_YEAR); double referenceEpochYear = parameterValueNumeric(EPSG_CODE_PARAMETER_REFERENCE_EPOCH, common::UnitOfMeasure::YEAR); formatter->addParam("dx", rate_x); formatter->addParam("dy", rate_y); formatter->addParam("dz", rate_z); formatter->addParam("drx", rate_rx); formatter->addParam("dry", rate_ry); formatter->addParam("drz", rate_rz); formatter->addParam("ds", rate_scaleDiff); formatter->addParam("t_epoch", referenceEpochYear); } if (positionVectorConvention) { formatter->addParam("convention", "position_vector"); } else { formatter->addParam("convention", "coordinate_frame"); } } if (l_targetCRS) { setupPROJGeodeticTargetCRS(formatter, NN_NO_CHECK(l_targetCRS), addPushPopV3, "Helmert"); } return true; } if (methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D) { positionVectorConvention = isPositionVector || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D; double x = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION); double y = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION); double z = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION); double rx = parameterValueNumeric(EPSG_CODE_PARAMETER_X_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND); double ry = parameterValueNumeric(EPSG_CODE_PARAMETER_Y_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND); double rz = parameterValueNumeric(EPSG_CODE_PARAMETER_Z_AXIS_ROTATION, common::UnitOfMeasure::ARC_SECOND); double scaleDiff = parameterValueNumeric(EPSG_CODE_PARAMETER_SCALE_DIFFERENCE, common::UnitOfMeasure::PARTS_PER_MILLION); double px = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT); double py = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT); double pz = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_ORDINATE_3_EVAL_POINT); bool addPushPopV3 = (methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D || methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D); auto l_sourceCRS = sourceCRS(); if (l_sourceCRS) { setupPROJGeodeticSourceCRS(formatter, NN_NO_CHECK(l_sourceCRS), addPushPopV3, "Molodensky-Badekas"); } formatter->addStep("molobadekas"); formatter->addParam("x", x); formatter->addParam("y", y); formatter->addParam("z", z); formatter->addParam("rx", rx); formatter->addParam("ry", ry); formatter->addParam("rz", rz); formatter->addParam("s", scaleDiff); formatter->addParam("px", px); formatter->addParam("py", py); formatter->addParam("pz", pz); if (positionVectorConvention) { formatter->addParam("convention", "position_vector"); } else { formatter->addParam("convention", "coordinate_frame"); } auto l_targetCRS = targetCRS(); if (l_targetCRS) { setupPROJGeodeticTargetCRS(formatter, NN_NO_CHECK(l_targetCRS), addPushPopV3, "Molodensky-Badekas"); } return true; } if (methodEPSGCode == EPSG_CODE_METHOD_MOLODENSKY || methodEPSGCode == EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY) { double x = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION); double y = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION); double z = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION); double da = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE); double df = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_FLATTENING_DIFFERENCE); auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRS().get()); if (!sourceCRSGeog) { throw io::FormattingException( "Can apply Molodensky only to GeographicCRS"); } auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRS().get()); if (!targetCRSGeog) { throw io::FormattingException( "Can apply Molodensky only to GeographicCRS"); } formatter->startInversion(); sourceCRSGeog->_exportToPROJString(formatter); formatter->stopInversion(); formatter->addStep("molodensky"); sourceCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->addParam("dx", x); formatter->addParam("dy", y); formatter->addParam("dz", z); formatter->addParam("da", da); formatter->addParam("df", df); if (ci_find(methodName, "Abridged") != std::string::npos || methodEPSGCode == EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY) { formatter->addParam("abridged"); } targetCRSGeog->_exportToPROJString(formatter); return true; } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS) { double offsetLat = parameterValueNumeric(EPSG_CODE_PARAMETER_LATITUDE_OFFSET, common::UnitOfMeasure::ARC_SECOND); double offsetLong = parameterValueNumeric(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET, common::UnitOfMeasure::ARC_SECOND); auto l_sourceCRS = sourceCRS(); auto sourceCRSGeog = l_sourceCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_sourceCRS)) : nullptr; if (!sourceCRSGeog) { throw io::FormattingException( "Can apply Geographic 2D offsets only to GeographicCRS"); } auto l_targetCRS = targetCRS(); auto targetCRSGeog = l_targetCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_targetCRS)) : nullptr; if (!targetCRSGeog) { throw io::FormattingException( "Can apply Geographic 2D offsets only to GeographicCRS"); } formatter->startInversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); if (offsetLat != 0.0 || offsetLong != 0.0) { formatter->addStep("geogoffset"); formatter->addParam("dlat", offsetLat); formatter->addParam("dlon", offsetLong); } targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); return true; } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS) { double offsetLat = parameterValueNumeric(EPSG_CODE_PARAMETER_LATITUDE_OFFSET, common::UnitOfMeasure::ARC_SECOND); double offsetLong = parameterValueNumeric(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET, common::UnitOfMeasure::ARC_SECOND); double offsetHeight = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_VERTICAL_OFFSET); auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRS().get()); if (!sourceCRSGeog) { auto boundCRS = dynamic_cast<const crs::BoundCRS *>(sourceCRS().get()); if (boundCRS) { sourceCRSGeog = dynamic_cast<crs::GeographicCRS *>( boundCRS->baseCRS().get()); } if (!sourceCRSGeog) { throw io::FormattingException( "Can apply Geographic 3D offsets only to GeographicCRS"); } } auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRS().get()); if (!targetCRSGeog) { auto boundCRS = dynamic_cast<const crs::BoundCRS *>(targetCRS().get()); if (boundCRS) { targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>( boundCRS->baseCRS().get()); } if (!targetCRSGeog) { throw io::FormattingException( "Can apply Geographic 3D offsets only to GeographicCRS"); } } formatter->startInversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); if (offsetLat != 0.0 || offsetLong != 0.0 || offsetHeight != 0.0) { formatter->addStep("geogoffset"); formatter->addParam("dlat", offsetLat); formatter->addParam("dlon", offsetLong); formatter->addParam("dh", offsetHeight); } targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); return true; } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS) { double offsetLat = parameterValueNumeric(EPSG_CODE_PARAMETER_LATITUDE_OFFSET, common::UnitOfMeasure::ARC_SECOND); double offsetLong = parameterValueNumeric(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET, common::UnitOfMeasure::ARC_SECOND); double offsetHeight = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_GEOID_UNDULATION); auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRS().get()); if (!sourceCRSGeog) { auto sourceCRSCompound = dynamic_cast<const crs::CompoundCRS *>(sourceCRS().get()); if (sourceCRSCompound) { sourceCRSGeog = sourceCRSCompound->extractGeographicCRS().get(); } if (!sourceCRSGeog) { throw io::FormattingException("Can apply Geographic 2D with " "height offsets only to " "GeographicCRS / CompoundCRS"); } } auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRS().get()); if (!targetCRSGeog) { auto targetCRSCompound = dynamic_cast<const crs::CompoundCRS *>(targetCRS().get()); if (targetCRSCompound) { targetCRSGeog = targetCRSCompound->extractGeographicCRS().get(); } if (!targetCRSGeog) { throw io::FormattingException("Can apply Geographic 2D with " "height offsets only to " "GeographicCRS / CompoundCRS"); } } formatter->startInversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); if (offsetLat != 0.0 || offsetLong != 0.0 || offsetHeight != 0.0) { formatter->addStep("geogoffset"); formatter->addParam("dlat", offsetLat); formatter->addParam("dlon", offsetLong); formatter->addParam("dh", offsetHeight); } targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); return true; } if (methodEPSGCode == EPSG_CODE_METHOD_VERTICAL_OFFSET) { const crs::CRS *srcCRS = sourceCRS().get(); const crs::CRS *tgtCRS = targetCRS().get(); const auto sourceCRSCompound = dynamic_cast<const crs::CompoundCRS *>(srcCRS); const auto targetCRSCompound = dynamic_cast<const crs::CompoundCRS *>(tgtCRS); if (sourceCRSCompound && targetCRSCompound && sourceCRSCompound->componentReferenceSystems()[0]->_isEquivalentTo( targetCRSCompound->componentReferenceSystems()[0].get(), util::IComparable::Criterion::EQUIVALENT)) { srcCRS = sourceCRSCompound->componentReferenceSystems()[1].get(); tgtCRS = targetCRSCompound->componentReferenceSystems()[1].get(); } auto sourceCRSVert = dynamic_cast<const crs::VerticalCRS *>(srcCRS); if (!sourceCRSVert) { throw io::FormattingException( "Can apply Vertical offset only to VerticalCRS"); } auto targetCRSVert = dynamic_cast<const crs::VerticalCRS *>(tgtCRS); if (!targetCRSVert) { throw io::FormattingException( "Can apply Vertical offset only to VerticalCRS"); } auto offsetHeight = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_VERTICAL_OFFSET); formatter->startInversion(); sourceCRSVert->addLinearUnitConvert(formatter); formatter->stopInversion(); formatter->addStep("geogoffset"); formatter->addParam("dh", offsetHeight); targetCRSVert->addLinearUnitConvert(formatter); return true; } if (methodEPSGCode == EPSG_CODE_METHOD_VERTICAL_OFFSET_AND_SLOPE) { const crs::CRS *srcCRS = sourceCRS().get(); const crs::CRS *tgtCRS = targetCRS().get(); const auto sourceCRSCompound = dynamic_cast<const crs::CompoundCRS *>(srcCRS); const auto targetCRSCompound = dynamic_cast<const crs::CompoundCRS *>(tgtCRS); if (sourceCRSCompound && targetCRSCompound && sourceCRSCompound->componentReferenceSystems()[0]->_isEquivalentTo( targetCRSCompound->componentReferenceSystems()[0].get(), util::IComparable::Criterion::EQUIVALENT)) { srcCRS = sourceCRSCompound->componentReferenceSystems()[1].get(); tgtCRS = targetCRSCompound->componentReferenceSystems()[1].get(); } auto sourceCRSVert = dynamic_cast<const crs::VerticalCRS *>(srcCRS); if (!sourceCRSVert) { throw io::FormattingException( "Can apply Vertical offset and slope only to VerticalCRS"); } auto targetCRSVert = dynamic_cast<const crs::VerticalCRS *>(tgtCRS); if (!targetCRSVert) { throw io::FormattingException( "Can apply Vertical offset and slope only to VerticalCRS"); } const auto latitudeEvaluationPoint = parameterValueNumeric(EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT, common::UnitOfMeasure::DEGREE); const auto longitudeEvaluationPoint = parameterValueNumeric(EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT, common::UnitOfMeasure::DEGREE); const auto offsetHeight = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_VERTICAL_OFFSET); const auto inclinationLatitude = parameterValueNumeric(EPSG_CODE_PARAMETER_INCLINATION_IN_LATITUDE, common::UnitOfMeasure::ARC_SECOND); const auto inclinationLongitude = parameterValueNumeric(EPSG_CODE_PARAMETER_INCLINATION_IN_LONGITUDE, common::UnitOfMeasure::ARC_SECOND); formatter->startInversion(); sourceCRSVert->addLinearUnitConvert(formatter); formatter->stopInversion(); formatter->addStep("vertoffset"); formatter->addParam("lat_0", latitudeEvaluationPoint); formatter->addParam("lon_0", longitudeEvaluationPoint); formatter->addParam("dh", offsetHeight); formatter->addParam("slope_lat", inclinationLatitude); formatter->addParam("slope_lon", inclinationLongitude); targetCRSVert->addLinearUnitConvert(formatter); return true; } // Substitute grid names with PROJ friendly names. if (formatter->databaseContext()) { auto alternate = substitutePROJAlternativeGridNames( NN_NO_CHECK(formatter->databaseContext())); auto self = NN_NO_CHECK(std::dynamic_pointer_cast<Transformation>( shared_from_this().as_nullable())); if (alternate != self) { alternate->_exportToPROJString(formatter); return true; } } const bool isMethodInverseOf = starts_with(methodName, INVERSE_OF); const auto &NTv1Filename = _getNTv1Filename(this, true); const auto &NTv2Filename = _getNTv2Filename(this, true); const auto &CTABLE2Filename = _getCTABLE2Filename(this, true); const auto &HorizontalShiftGTIFFFilename = _getHorizontalShiftGTIFFFilename(this, true); const auto &hGridShiftFilename = !HorizontalShiftGTIFFFilename.empty() ? HorizontalShiftGTIFFFilename : !NTv1Filename.empty() ? NTv1Filename : !NTv2Filename.empty() ? NTv2Filename : CTABLE2Filename; if (!hGridShiftFilename.empty()) { auto l_sourceCRS = sourceCRS(); auto sourceCRSGeog = l_sourceCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_sourceCRS)) : nullptr; if (!sourceCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } auto l_targetCRS = targetCRS(); auto targetCRSGeog = l_targetCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_targetCRS)) : nullptr; if (!targetCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } if (!formatter->omitHorizontalConversionInVertTransformation()) { formatter->startInversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); } if (isMethodInverseOf) { formatter->startInversion(); } if (methodName.find(PROJ_WKT2_NAME_METHOD_GENERAL_SHIFT_GTIFF) != std::string::npos) { formatter->addStep("gridshift"); if (sourceCRSGeog->coordinateSystem()->axisList().size() == 2 && parameterValue( PROJ_WKT2_PARAMETER_LATITUDE_LONGITUDE_ELLIPOISDAL_HEIGHT_DIFFERENCE_FILE, 0) != nullptr) { formatter->addParam("no_z_transform"); } } else formatter->addStep("hgridshift"); formatter->addParam("grids", hGridShiftFilename); if (isMethodInverseOf) { formatter->stopInversion(); } if (!formatter->omitHorizontalConversionInVertTransformation()) { targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); } return true; } const auto &geocentricTranslationFilename = _getGeocentricTranslationFilename(this, true); if (!geocentricTranslationFilename.empty()) { auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRS().get()); if (!sourceCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRS().get()); if (!targetCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } const auto &interpCRS = interpolationCRS(); if (!interpCRS) { throw io::FormattingException( "InterpolationCRS required " "for" " " EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN); } const bool interpIsSrc = interpCRS->_isEquivalentTo( sourceCRS().get(), util::IComparable::Criterion::EQUIVALENT); const bool interpIsTarget = interpCRS->_isEquivalentTo( targetCRS().get(), util::IComparable::Criterion::EQUIVALENT); if (!interpIsSrc && !interpIsTarget) { throw io::FormattingException( "For" " " EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN ", interpolation CRS should be the source or target CRS"); } formatter->startInversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); if (isMethodInverseOf) { formatter->startInversion(); } formatter->addStep("push"); formatter->addParam("v_3"); formatter->addStep("cart"); sourceCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->addStep("xyzgridshift"); formatter->addParam("grids", geocentricTranslationFilename); formatter->addParam("grid_ref", interpIsTarget ? "output_crs" : "input_crs"); (interpIsTarget ? targetCRSGeog : sourceCRSGeog) ->ellipsoid() ->_exportToPROJString(formatter); formatter->startInversion(); formatter->addStep("cart"); targetCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->stopInversion(); formatter->addStep("pop"); formatter->addParam("v_3"); if (isMethodInverseOf) { formatter->stopInversion(); } targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); return true; } const auto &geographic3DOffsetByVelocityGridFilename = _getGeographic3DOffsetByVelocityGridFilename(this, true); if (!geographic3DOffsetByVelocityGridFilename.empty()) { auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRS().get()); if (!sourceCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRS().get()); if (!targetCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } const auto &interpCRS = interpolationCRS(); if (!interpCRS) { throw io::FormattingException( "InterpolationCRS required " "for" " " EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN); } const bool interpIsSrc = interpCRS->_isEquivalentTo( sourceCRS()->demoteTo2D(std::string(), nullptr).get(), util::IComparable::Criterion::EQUIVALENT); const bool interpIsTarget = interpCRS->_isEquivalentTo( targetCRS()->demoteTo2D(std::string(), nullptr).get(), util::IComparable::Criterion::EQUIVALENT); if (!interpIsSrc && !interpIsTarget) { throw io::FormattingException( "For" " " EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN ", interpolation CRS should be the source or target CRS"); } formatter->startInversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); if (isMethodInverseOf) { formatter->startInversion(); } const bool addPushPopV3 = ((sourceCRSGeog && sourceCRSGeog->coordinateSystem()->axisList().size() == 2) || (targetCRSGeog && targetCRSGeog->coordinateSystem()->axisList().size() == 2)); if (addPushPopV3) { formatter->addStep("push"); formatter->addParam("v_3"); } formatter->addStep("cart"); sourceCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->addStep("deformation"); const std::string srcName(sourceCRS()->nameStr()); const std::string dstName(targetCRS()->nameStr()); const struct { const char *name; double epoch; } realizationEpochs[] = { {"NAD83(CSRS)v2", 1997.0}, {"NAD83(CSRS)v3", 1997.0}, {"NAD83(CSRS)v4", 2002.0}, {"NAD83(CSRS)v5", 2006.0}, {"NAD83(CSRS)v6", 2010.0}, {"NAD83(CSRS)v7", 2010.0}, {"NAD83(CSRS)v8", 2010.0}, }; double sourceYear = 0.0; double targetYear = 0.0; for (const auto &iter : realizationEpochs) { if (iter.name == srcName) sourceYear = iter.epoch; if (iter.name == dstName) targetYear = iter.epoch; } if (sourceYear == 0.0) { throw io::FormattingException( "For" " " EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN ", missing epoch for source CRS"); } if (targetYear == 0.0) { throw io::FormattingException( "For" " " EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN ", missing epoch for target CRS"); } formatter->addParam("dt", targetYear - sourceYear); formatter->addParam("grids", geographic3DOffsetByVelocityGridFilename); (interpIsTarget ? targetCRSGeog : sourceCRSGeog) ->ellipsoid() ->_exportToPROJString(formatter); formatter->startInversion(); formatter->addStep("cart"); targetCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->stopInversion(); if (addPushPopV3) { formatter->addStep("pop"); formatter->addParam("v_3"); } if (isMethodInverseOf) { formatter->stopInversion(); } targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); return true; } const auto &verticalOffsetByVelocityGridFilename = _getVerticalOffsetByVelocityGridFilename(this, true); if (!verticalOffsetByVelocityGridFilename.empty()) { const auto &interpCRS = interpolationCRS(); if (!interpCRS) { throw io::FormattingException( "InterpolationCRS required " "for" " " EPSG_NAME_METHOD_VERTICAL_OFFSET_BY_VELOCITY_GRID_NRCAN); } auto interpCRSGeog = dynamic_cast<const crs::GeographicCRS *>(interpCRS.get()); if (!interpCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to a GeographicCRS interpolation CRS")); } const auto vertSrc = dynamic_cast<const crs::VerticalCRS *>(sourceCRS().get()); if (!vertSrc) { throw io::FormattingException(concat( "Can apply ", methodName, " only to a source VerticalCRS")); } const auto &srcEpoch = vertSrc->datumNonNull(formatter->databaseContext())->anchorEpoch(); if (!srcEpoch.has_value()) { throw io::FormattingException( "For" " " EPSG_NAME_METHOD_VERTICAL_OFFSET_BY_VELOCITY_GRID_NRCAN ", missing epoch for source CRS"); } const auto vertDst = dynamic_cast<const crs::VerticalCRS *>(targetCRS().get()); if (!vertDst) { throw io::FormattingException(concat( "Can apply ", methodName, " only to a target VerticalCRS")); } const auto &dstEpoch = vertDst->datumNonNull(formatter->databaseContext())->anchorEpoch(); if (!dstEpoch.has_value()) { throw io::FormattingException( "For" " " EPSG_NAME_METHOD_VERTICAL_OFFSET_BY_VELOCITY_GRID_NRCAN ", missing epoch for target CRS"); } const double sourceYear = srcEpoch->convertToUnit(common::UnitOfMeasure::YEAR); const double targetYear = dstEpoch->convertToUnit(common::UnitOfMeasure::YEAR); if (isMethodInverseOf) { formatter->startInversion(); } formatter->addStep("push"); formatter->addParam("v_1"); formatter->addParam("v_2"); formatter->addStep("cart"); interpCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->addStep("deformation"); formatter->addParam("dt", targetYear - sourceYear); formatter->addParam("grids", verticalOffsetByVelocityGridFilename); interpCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->startInversion(); formatter->addStep("cart"); interpCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->stopInversion(); formatter->addStep("pop"); formatter->addParam("v_1"); formatter->addParam("v_2"); if (isMethodInverseOf) { formatter->stopInversion(); } return true; } const auto &heightFilename = _getHeightToGeographic3DFilename(this, true); if (!heightFilename.empty()) { auto l_targetCRS = targetCRS(); auto targetCRSGeog = l_targetCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_targetCRS)) : nullptr; if (!targetCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } if (!formatter->omitHorizontalConversionInVertTransformation()) { formatter->startInversion(); formatter->pushOmitZUnitConversion(); targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->popOmitZUnitConversion(); formatter->stopInversion(); } if (isMethodInverseOf) { formatter->startInversion(); } formatter->addStep("vgridshift"); formatter->addParam("grids", heightFilename); formatter->addParam("multiplier", 1.0); if (isMethodInverseOf) { formatter->stopInversion(); } if (!formatter->omitHorizontalConversionInVertTransformation()) { formatter->pushOmitZUnitConversion(); targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->popOmitZUnitConversion(); } return true; } if (Transformation::isGeographic3DToGravityRelatedHeight(method(), true)) { auto fileParameter = parameterValue(EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME, EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { const auto &filename = fileParameter->valueFile(); auto l_sourceCRS = sourceCRS(); auto sourceCRSGeog = l_sourceCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_sourceCRS)) : nullptr; if (!sourceCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } auto l_targetCRS = targetCRS(); auto targetVertCRS = l_targetCRS ? l_targetCRS->extractVerticalCRS() : nullptr; if (!targetVertCRS) { throw io::FormattingException( concat("Can apply ", methodName, " only to a target CRS that has a VerticalCRS")); } if (!formatter->omitHorizontalConversionInVertTransformation()) { formatter->startInversion(); formatter->pushOmitZUnitConversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->popOmitZUnitConversion(); formatter->stopInversion(); } bool doInversion = isMethodInverseOf; // The EPSG Geog3DToHeight is the reverse convention of PROJ ! doInversion = !doInversion; if (doInversion) { formatter->startInversion(); } // For Geographic3D to Depth methods, we rely on the vertical axis // direction instead of the name/code of the transformation method. if (targetVertCRS->coordinateSystem()->axisList()[0]->direction() == cs::AxisDirection::DOWN) { formatter->addStep("axisswap"); formatter->addParam("order", "1,2,-3"); } formatter->addStep("vgridshift"); formatter->addParam("grids", filename); formatter->addParam("multiplier", 1.0); if (doInversion) { formatter->stopInversion(); } if (!formatter->omitHorizontalConversionInVertTransformation()) { formatter->pushOmitZUnitConversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->popOmitZUnitConversion(); } return true; } } if (methodEPSGCode == EPSG_CODE_METHOD_VERTCON) { auto fileParameter = parameterValue(EPSG_NAME_PARAMETER_VERTICAL_OFFSET_FILE, EPSG_CODE_PARAMETER_VERTICAL_OFFSET_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { formatter->addStep("vgridshift"); formatter->addParam("grids", fileParameter->valueFile()); if (fileParameter->valueFile().find(".tif") != std::string::npos) { formatter->addParam("multiplier", 1.0); } else { // The vertcon grids go from NGVD 29 to NAVD 88, with units // in millimeter (see // https://github.com/OSGeo/proj.4/issues/1071), for gtx files formatter->addParam("multiplier", 0.001); } return true; } } bool reverseOffsetSign = false; if (isRegularVerticalGridMethod(methodEPSGCode, reverseOffsetSign)) { int parameterCode = EPSG_CODE_PARAMETER_VERTICAL_OFFSET_FILE; auto fileParameter = parameterValue( EPSG_NAME_PARAMETER_VERTICAL_OFFSET_FILE, parameterCode); if (!fileParameter) { parameterCode = EPSG_CODE_PARAMETER_GEOID_MODEL_DIFFERENCE_FILE; fileParameter = parameterValue( EPSG_NAME_PARAMETER_GEOID_MODEL_DIFFERENCE_FILE, parameterCode); } if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { formatter->addStep("vgridshift"); formatter->addParam("grids", fileParameter->valueFile()); formatter->addParam("multiplier", reverseOffsetSign ? -1.0 : 1.0); return true; } } if (isLongitudeRotation()) { double offsetDeg = parameterValueNumeric(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET, common::UnitOfMeasure::DEGREE); auto l_sourceCRS = sourceCRS(); auto sourceCRSGeog = l_sourceCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_sourceCRS)) : nullptr; if (!sourceCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName, " only to GeographicCRS")); } auto l_targetCRS = targetCRS(); auto targetCRSGeog = l_targetCRS ? extractGeographicCRSIfGeographicCRSOrEquivalent( NN_NO_CHECK(l_targetCRS)) : nullptr; if (!targetCRSGeog) { throw io::FormattingException( concat("Can apply ", methodName + " only to GeographicCRS")); } if (!sourceCRSGeog->ellipsoid()->_isEquivalentTo( targetCRSGeog->ellipsoid().get(), util::IComparable::Criterion::EQUIVALENT)) { // This is arguable if we should check this... throw io::FormattingException("Can apply Longitude rotation " "only to SRS with same " "ellipsoid"); } formatter->startInversion(); sourceCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); formatter->stopInversion(); bool done = false; if (offsetDeg != 0.0) { // Optimization: as we are doing nominally a +step=inv, // if the negation of the offset value is a well-known name, // then use forward case with this name. auto projPMName = datum::PrimeMeridian::getPROJStringWellKnownName( common::Angle(-offsetDeg)); if (!projPMName.empty()) { done = true; formatter->addStep("longlat"); sourceCRSGeog->ellipsoid()->_exportToPROJString(formatter); formatter->addParam("pm", projPMName); } } if (!done) { // To actually add the offset, we must use the reverse longlat // operation. formatter->startInversion(); formatter->addStep("longlat"); sourceCRSGeog->ellipsoid()->_exportToPROJString(formatter); datum::PrimeMeridian::create(util::PropertyMap(), common::Angle(offsetDeg)) ->_exportToPROJString(formatter); formatter->stopInversion(); } targetCRSGeog->addAngularUnitConvertAndAxisSwap(formatter); return true; } const char *prefix = "PROJ-based operation method: "; if (starts_with(method()->nameStr(), prefix)) { auto projString = method()->nameStr().substr(strlen(prefix)); try { formatter->ingestPROJString(projString); return true; } catch (const io::ParsingException &e) { throw io::FormattingException( std::string("ingestPROJString() failed: ") + e.what()); } } return false; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress InverseCoordinateOperation::~InverseCoordinateOperation() = default; // --------------------------------------------------------------------------- InverseCoordinateOperation::InverseCoordinateOperation( const CoordinateOperationNNPtr &forwardOperationIn, bool wktSupportsInversion) : forwardOperation_(forwardOperationIn), wktSupportsInversion_(wktSupportsInversion) {} // --------------------------------------------------------------------------- void InverseCoordinateOperation::setPropertiesFromForward() { setProperties( createPropertiesForInverse(forwardOperation_.get(), false, false)); setAccuracies(forwardOperation_->coordinateOperationAccuracies()); if (forwardOperation_->sourceCRS() && forwardOperation_->targetCRS()) { setCRSs(forwardOperation_.get(), true); } setHasBallparkTransformation( forwardOperation_->hasBallparkTransformation()); } // --------------------------------------------------------------------------- CoordinateOperationNNPtr InverseCoordinateOperation::inverse() const { return forwardOperation_; } // --------------------------------------------------------------------------- void InverseCoordinateOperation::_exportToPROJString( io::PROJStringFormatter *formatter) const { formatter->startInversion(); forwardOperation_->_exportToPROJString(formatter); formatter->stopInversion(); } // --------------------------------------------------------------------------- bool InverseCoordinateOperation::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherICO = dynamic_cast<const InverseCoordinateOperation *>(other); if (otherICO == nullptr || !ObjectUsage::_isEquivalentTo(other, criterion, dbContext)) { return false; } return inverse()->_isEquivalentTo(otherICO->inverse().get(), criterion, dbContext); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PointMotionOperation::~PointMotionOperation() = default; //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a point motion operation from a vector of * GeneralParameterValue. * * @param properties See \ref general_properties. At minimum the name should be * defined. * @param crsIn Source and target CRS. * @param methodIn Operation method. * @param values Vector of GeneralOperationParameterNNPtr. * @param accuracies Vector of positional accuracy (might be empty). * @return new PointMotionOperation. * @throws InvalidOperation */ PointMotionOperationNNPtr PointMotionOperation::create( const util::PropertyMap &properties, const crs::CRSNNPtr &crsIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) { if (methodIn->parameters().size() != values.size()) { throw InvalidOperation( "Inconsistent number of parameters and parameter values"); } auto pmo = PointMotionOperation::nn_make_shared<PointMotionOperation>( crsIn, methodIn, values, accuracies); pmo->assignSelf(pmo); pmo->setProperties(properties); const std::string l_name = pmo->nameStr(); auto pos = l_name.find(" from epoch "); if (pos != std::string::npos) { pos += strlen(" from epoch "); const auto pos2 = l_name.find(" to epoch ", pos); if (pos2 != std::string::npos) { const double sourceYear = std::stod(l_name.substr(pos, pos2 - pos)); const double targetYear = std::stod(l_name.substr(pos2 + strlen(" to epoch "))); pmo->setSourceCoordinateEpoch( util::optional<common::DataEpoch>(common::DataEpoch( common::Measure(sourceYear, common::UnitOfMeasure::YEAR)))); pmo->setTargetCoordinateEpoch( util::optional<common::DataEpoch>(common::DataEpoch( common::Measure(targetYear, common::UnitOfMeasure::YEAR)))); } } return pmo; } // --------------------------------------------------------------------------- /** \brief Instantiate a point motion operation and its OperationMethod. * * @param propertiesOperation The \ref general_properties of the * PointMotionOperation. * At minimum the name should be defined. * @param crsIn Source and target CRS. * @param propertiesOperationMethod The \ref general_properties of the * OperationMethod. * At minimum the name should be defined. * @param parameters Vector of parameters of the operation method. * @param values Vector of ParameterValueNNPtr. Constraint: * values.size() == parameters.size() * @param accuracies Vector of positional accuracy (might be empty). * @return new PointMotionOperation. * @throws InvalidOperation */ PointMotionOperationNNPtr PointMotionOperation::create( const util::PropertyMap &propertiesOperation, const crs::CRSNNPtr &crsIn, const util::PropertyMap &propertiesOperationMethod, const std::vector<OperationParameterNNPtr> &parameters, const std::vector<ParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) // throw InvalidOperation { OperationMethodNNPtr op( OperationMethod::create(propertiesOperationMethod, parameters)); if (parameters.size() != values.size()) { throw InvalidOperation( "Inconsistent number of parameters and parameter values"); } std::vector<GeneralParameterValueNNPtr> generalParameterValues; generalParameterValues.reserve(values.size()); for (size_t i = 0; i < values.size(); i++) { generalParameterValues.push_back( OperationParameterValue::create(parameters[i], values[i])); } return create(propertiesOperation, crsIn, op, generalParameterValues, accuracies); } // --------------------------------------------------------------------------- PointMotionOperation::PointMotionOperation( const crs::CRSNNPtr &crsIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) : SingleOperation(methodIn) { setParameterValues(values); setCRSs(crsIn, crsIn, nullptr); setAccuracies(accuracies); } // --------------------------------------------------------------------------- PointMotionOperation::PointMotionOperation(const PointMotionOperation &other) : CoordinateOperation(other), SingleOperation(other) {} // --------------------------------------------------------------------------- CoordinateOperationNNPtr PointMotionOperation::inverse() const { auto inverse = shallowClone(); if (sourceCoordinateEpoch().has_value()) { // Switch source and target epochs inverse->setSourceCoordinateEpoch(targetCoordinateEpoch()); inverse->setTargetCoordinateEpoch(sourceCoordinateEpoch()); auto l_name = inverse->nameStr(); auto pos = l_name.find(" from epoch "); if (pos != std::string::npos) l_name.resize(pos); const double sourceYear = getRoundedEpochInDecimalYear( inverse->sourceCoordinateEpoch()->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)); const double targetYear = getRoundedEpochInDecimalYear( inverse->targetCoordinateEpoch()->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)); l_name += " from epoch "; l_name += toString(sourceYear); l_name += " to epoch "; l_name += toString(targetYear); util::PropertyMap newProperties; newProperties.set(IdentifiedObject::NAME_KEY, l_name); inverse->setProperties(newProperties); } return inverse; } // --------------------------------------------------------------------------- /** \brief Return an equivalent transformation to the current one, but using * PROJ alternative grid names. */ PointMotionOperationNNPtr PointMotionOperation::substitutePROJAlternativeGridNames( io::DatabaseContextNNPtr databaseContext) const { auto self = NN_NO_CHECK(std::dynamic_pointer_cast<PointMotionOperation>( shared_from_this().as_nullable())); const auto &l_method = method(); const int methodEPSGCode = l_method->getEPSGCode(); std::string filename; if (methodEPSGCode == EPSG_CODE_METHOD_POINT_MOTION_BY_GRID_CANADA_NTV2_VEL) { const auto &fileParameter = parameterValue(EPSG_NAME_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE, EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { filename = fileParameter->valueFile(); } } std::string projFilename; std::string projGridFormat; bool inverseDirection = false; if (!filename.empty() && databaseContext->lookForGridAlternative( filename, projFilename, projGridFormat, inverseDirection)) { if (filename == projFilename) { return self; } auto parameters = std::vector<OperationParameterNNPtr>{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE)}; return PointMotionOperation::create( createSimilarPropertiesOperation(self), sourceCRS(), createSimilarPropertiesMethod(method()), parameters, {ParameterValue::createFilename(projFilename)}, coordinateOperationAccuracies()); } return self; } // --------------------------------------------------------------------------- /** \brief Return the source crs::CRS of the operation. * * @return the source CRS. */ const crs::CRSNNPtr &PointMotionOperation::sourceCRS() PROJ_PURE_DEFN { return CoordinateOperation::getPrivate()->strongRef_->sourceCRS_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress PointMotionOperationNNPtr PointMotionOperation::shallowClone() const { auto pmo = PointMotionOperation::nn_make_shared<PointMotionOperation>(*this); pmo->assignSelf(pmo); pmo->setCRSs(this, false); return pmo; } CoordinateOperationNNPtr PointMotionOperation::_shallowClone() const { return util::nn_static_pointer_cast<CoordinateOperation>(shallowClone()); } // --------------------------------------------------------------------------- PointMotionOperationNNPtr PointMotionOperation::cloneWithEpochs( const common::DataEpoch &sourceEpoch, const common::DataEpoch &targetEpoch) const { auto pmo = PointMotionOperation::nn_make_shared<PointMotionOperation>(*this); pmo->assignSelf(pmo); pmo->setCRSs(this, false); pmo->setSourceCoordinateEpoch( util::optional<common::DataEpoch>(sourceEpoch)); pmo->setTargetCoordinateEpoch( util::optional<common::DataEpoch>(targetEpoch)); const double sourceYear = getRoundedEpochInDecimalYear( sourceEpoch.coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)); const double targetYear = getRoundedEpochInDecimalYear( targetEpoch.coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)); auto l_name = nameStr(); l_name += " from epoch "; l_name += toString(sourceYear); l_name += " to epoch "; l_name += toString(targetYear); util::PropertyMap newProperties; newProperties.set(IdentifiedObject::NAME_KEY, l_name); pmo->setProperties(newProperties); return pmo; } // --------------------------------------------------------------------------- void PointMotionOperation::_exportToWKT(io::WKTFormatter *formatter) const { if (formatter->version() != io::WKTFormatter::Version::WKT2 || !formatter->use2019Keywords()) { throw io::FormattingException( "Transformation can only be exported to WKT2:2019"); } formatter->startNode(io::WKTConstants::POINTMOTIONOPERATION, !identifiers().empty()); formatter->addQuotedString(nameStr()); const auto &version = operationVersion(); if (version.has_value()) { formatter->startNode(io::WKTConstants::VERSION, false); formatter->addQuotedString(*version); formatter->endNode(); } auto l_sourceCRS = sourceCRS(); const bool canExportCRSId = !(formatter->idOnTopLevelOnly() && formatter->topLevelHasId()); const bool hasDomains = !domains().empty(); if (hasDomains) { formatter->pushDisableUsage(); } formatter->startNode(io::WKTConstants::SOURCECRS, false); if (canExportCRSId && !l_sourceCRS->identifiers().empty()) { // fake that top node has no id, so that the sourceCRS id is // considered formatter->pushHasId(false); l_sourceCRS->_exportToWKT(formatter); formatter->popHasId(); } else { l_sourceCRS->_exportToWKT(formatter); } formatter->endNode(); if (hasDomains) { formatter->popDisableUsage(); } const auto &l_method = method(); l_method->_exportToWKT(formatter); for (const auto &paramValue : parameterValues()) { paramValue->_exportToWKT(formatter, nullptr); } if (!coordinateOperationAccuracies().empty()) { formatter->startNode(io::WKTConstants::OPERATIONACCURACY, false); formatter->add(coordinateOperationAccuracies()[0]->value()); formatter->endNode(); } ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } // --------------------------------------------------------------------------- void PointMotionOperation::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(FormattingException) { if (formatter->convention() == io::PROJStringFormatter::Convention::PROJ_4) { throw io::FormattingException( "PointMotionOperation cannot be exported as a PROJ.4 string"); } const int methodEPSGCode = method()->getEPSGCode(); if (methodEPSGCode == EPSG_CODE_METHOD_POINT_MOTION_BY_GRID_CANADA_NTV2_VEL) { if (!sourceCoordinateEpoch().has_value()) { throw io::FormattingException( "CoordinateOperationNNPtr::_exportToPROJString() unimplemented " "when source coordinate epoch is missing"); } if (!targetCoordinateEpoch().has_value()) { throw io::FormattingException( "CoordinateOperationNNPtr::_exportToPROJString() unimplemented " "when target coordinate epoch is missing"); } auto l_sourceCRS = dynamic_cast<const crs::GeodeticCRS *>(sourceCRS().get()); if (!l_sourceCRS) { throw io::FormattingException("Can apply PointMotionOperation " "VelocityGrid only to GeodeticCRS"); } if (!l_sourceCRS->isGeocentric()) { formatter->startInversion(); l_sourceCRS->_exportToPROJString(formatter); formatter->stopInversion(); formatter->addStep("cart"); l_sourceCRS->ellipsoid()->_exportToPROJString(formatter); } else { formatter->startInversion(); l_sourceCRS->addGeocentricUnitConversionIntoPROJString(formatter); formatter->stopInversion(); } const double sourceYear = getRoundedEpochInDecimalYear( sourceCoordinateEpoch()->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)); const double targetYear = getRoundedEpochInDecimalYear( targetCoordinateEpoch()->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)); formatter->addStep("set"); formatter->addParam("v_4", sourceYear); formatter->addParam("omit_fwd"); formatter->addStep("deformation"); formatter->addParam("dt", targetYear - sourceYear); const auto &fileParameter = parameterValue(EPSG_NAME_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE, EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE); if (fileParameter && fileParameter->type() == ParameterValue::Type::FILENAME) { formatter->addParam("grids", fileParameter->valueFile()); } else { throw io::FormattingException( "CoordinateOperationNNPtr::_exportToPROJString(): missing " "velocity grid file parameter"); } l_sourceCRS->ellipsoid()->_exportToPROJString(formatter); formatter->addStep("set"); formatter->addParam("v_4", targetYear); formatter->addParam("omit_inv"); if (!l_sourceCRS->isGeocentric()) { formatter->startInversion(); formatter->addStep("cart"); l_sourceCRS->ellipsoid()->_exportToPROJString(formatter); formatter->stopInversion(); l_sourceCRS->_exportToPROJString(formatter); } else { l_sourceCRS->addGeocentricUnitConversionIntoPROJString(formatter); } } else { throw io::FormattingException( "CoordinateOperationNNPtr::_exportToPROJString() unimplemented for " "this method"); } } // --------------------------------------------------------------------------- void PointMotionOperation::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext(formatter->MakeObjectContext("PointMotionOperation", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("source_crs"); formatter->setAllowIDInImmediateChild(); sourceCRS()->_exportToJSON(formatter); writer->AddObjKey("method"); formatter->setOmitTypeInImmediateChild(); formatter->setAllowIDInImmediateChild(); method()->_exportToJSON(formatter); writer->AddObjKey("parameters"); { auto parametersContext(writer->MakeArrayContext(false)); for (const auto &genOpParamvalue : parameterValues()) { formatter->setAllowIDInImmediateChild(); formatter->setOmitTypeInImmediateChild(); genOpParamvalue->_exportToJSON(formatter); } } if (!coordinateOperationAccuracies().empty()) { writer->AddObjKey("accuracy"); writer->Add(coordinateOperationAccuracies()[0]->value()); } ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/concatenatedoperation.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/crs_internal.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "coordinateoperation_internal.hpp" #include "oputils.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // M_PI // clang-format on #include "proj_constants.h" #include "proj_json_streaming_writer.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <memory> #include <set> #include <string> #include <vector> using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ConcatenatedOperation::Private { std::vector<CoordinateOperationNNPtr> operations_{}; bool computedName_ = false; explicit Private(const std::vector<CoordinateOperationNNPtr> &operationsIn) : operations_(operationsIn) {} Private(const Private &) = default; }; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ConcatenatedOperation::~ConcatenatedOperation() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ConcatenatedOperation::ConcatenatedOperation(const ConcatenatedOperation &other) : CoordinateOperation(other), d(internal::make_unique<Private>(*(other.d))) {} //! @endcond // --------------------------------------------------------------------------- ConcatenatedOperation::ConcatenatedOperation( const std::vector<CoordinateOperationNNPtr> &operationsIn) : CoordinateOperation(), d(internal::make_unique<Private>(operationsIn)) {} // --------------------------------------------------------------------------- /** \brief Return the operation steps of the concatenated operation. * * @return the operation steps. */ const std::vector<CoordinateOperationNNPtr> & ConcatenatedOperation::operations() const { return d->operations_; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool areCRSMoreOrLessEquivalent(const crs::CRS *a, const crs::CRS *b) { const auto &aIds = a->identifiers(); const auto &bIds = b->identifiers(); if (aIds.size() == 1 && bIds.size() == 1 && aIds[0]->code() == bIds[0]->code() && *aIds[0]->codeSpace() == *bIds[0]->codeSpace()) { return true; } if (a->_isEquivalentTo(b, util::IComparable::Criterion::EQUIVALENT)) { return true; } // This is for example for EPSG:10146 which is EPSG:9471 // (INAGeoid2020 v1 height) // to EPSG:20036 (INAGeoid2020 v2 height), but chains // EPSG:9629 (SRGI2013 to SRGI2013 + INAGeoid2020 v1 height (1)) // with EPSG:10145 (SRGI2013 to SRGI2013 + INAGeoid2020 v2 height (1)) const auto compoundA = dynamic_cast<const crs::CompoundCRS *>(a); const auto compoundB = dynamic_cast<const crs::CompoundCRS *>(b); if (compoundA && !compoundB) return areCRSMoreOrLessEquivalent( compoundA->componentReferenceSystems()[1].get(), b); else if (!compoundA && compoundB) return areCRSMoreOrLessEquivalent( a, compoundB->componentReferenceSystems()[1].get()); return false; } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a ConcatenatedOperation * * @param properties See \ref general_properties. At minimum the name should * be * defined. * @param operationsIn Vector of the CoordinateOperation steps. * @param accuracies Vector of positional accuracy (might be empty). * @return new Transformation. * @throws InvalidOperation */ ConcatenatedOperationNNPtr ConcatenatedOperation::create( const util::PropertyMap &properties, const std::vector<CoordinateOperationNNPtr> &operationsIn, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies) // throw InvalidOperation { if (operationsIn.size() < 2) { throw InvalidOperation( "ConcatenatedOperation must have at least 2 operations"); } crs::CRSPtr lastTargetCRS; crs::CRSPtr interpolationCRS; bool interpolationCRSValid = true; for (size_t i = 0; i < operationsIn.size(); i++) { auto l_sourceCRS = operationsIn[i]->sourceCRS(); auto l_targetCRS = operationsIn[i]->targetCRS(); if (interpolationCRSValid) { auto subOpInterpCRS = operationsIn[i]->interpolationCRS(); if (interpolationCRS == nullptr) interpolationCRS = std::move(subOpInterpCRS); else if (subOpInterpCRS == nullptr || !(subOpInterpCRS->isEquivalentTo( interpolationCRS.get(), util::IComparable::Criterion::EQUIVALENT))) { interpolationCRS = nullptr; interpolationCRSValid = false; } } if (l_sourceCRS == nullptr || l_targetCRS == nullptr) { throw InvalidOperation("At least one of the operation lacks a " "source and/or target CRS"); } if (i >= 1) { if (!areCRSMoreOrLessEquivalent(l_sourceCRS.get(), lastTargetCRS.get())) { #ifdef DEBUG_CONCATENATED_OPERATION std::cerr << "Step " << i - 1 << ": " << operationsIn[i - 1]->nameStr() << std::endl; std::cerr << "Step " << i << ": " << operationsIn[i]->nameStr() << std::endl; { auto f(io::WKTFormatter::create( io::WKTFormatter::Convention::WKT2_2019)); std::cerr << "Source CRS of step " << i << ":" << std::endl; std::cerr << l_sourceCRS->exportToWKT(f.get()) << std::endl; } { auto f(io::WKTFormatter::create( io::WKTFormatter::Convention::WKT2_2019)); std::cerr << "Target CRS of step " << i - 1 << ":" << std::endl; std::cerr << lastTargetCRS->exportToWKT(f.get()) << std::endl; } #endif throw InvalidOperation( "Inconsistent chaining of CRS in operations"); } } lastTargetCRS = std::move(l_targetCRS); } // When chaining VerticalCRS -> GeographicCRS -> VerticalCRS, use // GeographicCRS as the interpolationCRS const auto l_sourceCRS = NN_NO_CHECK(operationsIn[0]->sourceCRS()); const auto l_targetCRS = NN_NO_CHECK(operationsIn.back()->targetCRS()); if (operationsIn.size() == 2 && interpolationCRS == nullptr && dynamic_cast<const crs::VerticalCRS *>(l_sourceCRS.get()) != nullptr && dynamic_cast<const crs::VerticalCRS *>(l_targetCRS.get()) != nullptr) { const auto geog1 = dynamic_cast<crs::GeographicCRS *>( operationsIn[0]->targetCRS().get()); const auto geog2 = dynamic_cast<crs::GeographicCRS *>( operationsIn[1]->sourceCRS().get()); if (geog1 != nullptr && geog2 != nullptr && geog1->_isEquivalentTo(geog2, util::IComparable::Criterion::EQUIVALENT)) { interpolationCRS = operationsIn[0]->targetCRS(); } } auto op = ConcatenatedOperation::nn_make_shared<ConcatenatedOperation>( operationsIn); op->assignSelf(op); op->setProperties(properties); op->setCRSs(l_sourceCRS, l_targetCRS, interpolationCRS); op->setAccuracies(accuracies); #ifdef DEBUG_CONCATENATED_OPERATION { auto f( io::WKTFormatter::create(io::WKTFormatter::Convention::WKT2_2019)); std::cerr << "ConcatenatedOperation::create()" << std::endl; std::cerr << op->exportToWKT(f.get()) << std::endl; } #endif return op; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- void ConcatenatedOperation::fixStepsDirection( const crs::CRSNNPtr &concatOpSourceCRS, const crs::CRSNNPtr &concatOpTargetCRS, std::vector<CoordinateOperationNNPtr> &operationsInOut, const io::DatabaseContextPtr & /*dbContext*/) { // Set of heuristics to assign CRS to steps, and possibly reverse them. const auto isGeographic = [](const crs::CRS *crs) -> bool { return dynamic_cast<const crs::GeographicCRS *>(crs) != nullptr; }; const auto isGeocentric = [](const crs::CRS *crs) -> bool { const auto geodCRS = dynamic_cast<const crs::GeodeticCRS *>(crs); return (geodCRS && geodCRS->isGeocentric()); }; // Apply axis order reversal operation on first operation if needed // to set CRSs on it if (operationsInOut.size() >= 1) { auto &op = operationsInOut.front(); auto l_sourceCRS = op->sourceCRS(); auto l_targetCRS = op->targetCRS(); auto conv = dynamic_cast<const Conversion *>(op.get()); if (conv && !l_sourceCRS && !l_targetCRS && isAxisOrderReversal(conv->method()->getEPSGCode())) { auto reversedCRS = concatOpSourceCRS->applyAxisOrderReversal( NORMALIZED_AXIS_ORDER_SUFFIX_STR); op->setCRSs(concatOpSourceCRS, reversedCRS, nullptr); } } // Apply axis order reversal operation on last operation if needed // to set CRSs on it if (operationsInOut.size() >= 2) { auto &op = operationsInOut.back(); auto l_sourceCRS = op->sourceCRS(); auto l_targetCRS = op->targetCRS(); auto conv = dynamic_cast<const Conversion *>(op.get()); if (conv && !l_sourceCRS && !l_targetCRS && isAxisOrderReversal(conv->method()->getEPSGCode())) { auto reversedCRS = concatOpTargetCRS->applyAxisOrderReversal( NORMALIZED_AXIS_ORDER_SUFFIX_STR); op->setCRSs(reversedCRS, concatOpTargetCRS, nullptr); } } // If the first operation is a transformation whose target CRS matches the // source CRS of the concatenated operation, then reverse it. if (operationsInOut.size() >= 2) { auto &op = operationsInOut.front(); auto l_sourceCRS = op->sourceCRS(); auto l_targetCRS = op->targetCRS(); if (l_sourceCRS && l_targetCRS && !areCRSMoreOrLessEquivalent(l_sourceCRS.get(), concatOpSourceCRS.get()) && areCRSMoreOrLessEquivalent(l_targetCRS.get(), concatOpSourceCRS.get())) { op = op->inverse(); } } // If the last operation is a transformation whose source CRS matches the // target CRS of the concatenated operation, then reverse it. if (operationsInOut.size() >= 2) { auto &op = operationsInOut.back(); auto l_sourceCRS = op->sourceCRS(); auto l_targetCRS = op->targetCRS(); if (l_sourceCRS && l_targetCRS && !areCRSMoreOrLessEquivalent(l_targetCRS.get(), concatOpTargetCRS.get()) && areCRSMoreOrLessEquivalent(l_sourceCRS.get(), concatOpTargetCRS.get())) { op = op->inverse(); } } const auto extractDerivedCRS = [](const crs::CRS *crs) -> const crs::DerivedCRS * { auto derivedCRS = dynamic_cast<const crs::DerivedCRS *>(crs); if (derivedCRS) return derivedCRS; auto compoundCRS = dynamic_cast<const crs::CompoundCRS *>(crs); if (compoundCRS) { derivedCRS = dynamic_cast<const crs::DerivedCRS *>( compoundCRS->componentReferenceSystems().front().get()); if (derivedCRS) return derivedCRS; } return nullptr; }; for (size_t i = 0; i < operationsInOut.size(); ++i) { auto &op = operationsInOut[i]; auto l_sourceCRS = op->sourceCRS(); auto l_targetCRS = op->targetCRS(); auto conv = dynamic_cast<const Conversion *>(op.get()); if (conv && i == 0 && !l_sourceCRS && !l_targetCRS) { if (auto derivedCRS = extractDerivedCRS(concatOpSourceCRS.get())) { if (i + 1 < operationsInOut.size()) { // use the sourceCRS of the next operation as our target CRS l_targetCRS = operationsInOut[i + 1]->sourceCRS(); // except if it looks like the next operation should // actually be reversed !!! if (l_targetCRS && !areCRSMoreOrLessEquivalent( l_targetCRS.get(), derivedCRS->baseCRS().get()) && operationsInOut[i + 1]->targetCRS() && areCRSMoreOrLessEquivalent( operationsInOut[i + 1]->targetCRS().get(), derivedCRS->baseCRS().get())) { l_targetCRS = operationsInOut[i + 1]->targetCRS(); } } if (!l_targetCRS) { l_targetCRS = derivedCRS->baseCRS().as_nullable(); } auto invConv = util::nn_dynamic_pointer_cast<InverseConversion>(op); auto nn_targetCRS = NN_NO_CHECK(l_targetCRS); if (invConv) { invConv->inverse()->setCRSs(nn_targetCRS, concatOpSourceCRS, nullptr); op->setCRSs(concatOpSourceCRS, nn_targetCRS, nullptr); } else { op->setCRSs(nn_targetCRS, concatOpSourceCRS, nullptr); op = op->inverse(); } } else if (i + 1 < operationsInOut.size()) { /* coverity[copy_paste_error] */ l_targetCRS = operationsInOut[i + 1]->sourceCRS(); if (l_targetCRS) { op->setCRSs(concatOpSourceCRS, NN_NO_CHECK(l_targetCRS), nullptr); } } } else if (conv && i + 1 == operationsInOut.size() && !l_sourceCRS && !l_targetCRS) { auto derivedCRS = extractDerivedCRS(concatOpTargetCRS.get()); if (derivedCRS) { if (i >= 1) { // use the targetCRS of the previous operation as our source // CRS l_sourceCRS = operationsInOut[i - 1]->targetCRS(); // except if it looks like the previous operation should // actually be reversed !!! if (l_sourceCRS && !areCRSMoreOrLessEquivalent( l_sourceCRS.get(), derivedCRS->baseCRS().get()) && operationsInOut[i - 1]->sourceCRS() && areCRSMoreOrLessEquivalent( operationsInOut[i - 1]->sourceCRS().get(), derivedCRS->baseCRS().get())) { l_sourceCRS = operationsInOut[i - 1]->sourceCRS(); operationsInOut[i - 1] = operationsInOut[i - 1]->inverse(); } } if (!l_sourceCRS) { l_sourceCRS = derivedCRS->baseCRS().as_nullable(); } op->setCRSs(NN_NO_CHECK(l_sourceCRS), concatOpTargetCRS, nullptr); } else if (i >= 1) { l_sourceCRS = operationsInOut[i - 1]->targetCRS(); if (l_sourceCRS) { derivedCRS = extractDerivedCRS(l_sourceCRS.get()); if (derivedCRS && conv->isEquivalentTo( derivedCRS->derivingConversion().get(), util::IComparable::Criterion::EQUIVALENT)) { op->setCRSs(concatOpTargetCRS, NN_NO_CHECK(l_sourceCRS), nullptr); op = op->inverse(); } op->setCRSs(NN_NO_CHECK(l_sourceCRS), concatOpTargetCRS, nullptr); } } } else if (conv && i > 0 && i < operationsInOut.size() - 1) { l_sourceCRS = operationsInOut[i - 1]->targetCRS(); l_targetCRS = operationsInOut[i + 1]->sourceCRS(); // For an intermediate conversion, use the target CRS of the // previous step and the source CRS of the next step if (l_sourceCRS && l_targetCRS) { // If the sourceCRS is a projectedCRS and the target a // geographic one, then we must inverse the operation. See // https://github.com/OSGeo/PROJ/issues/2817 if (dynamic_cast<const crs::ProjectedCRS *>( l_sourceCRS.get()) && dynamic_cast<const crs::GeographicCRS *>( l_targetCRS.get())) { op->setCRSs(NN_NO_CHECK(l_targetCRS), NN_NO_CHECK(l_sourceCRS), nullptr); op = op->inverse(); } else { op->setCRSs(NN_NO_CHECK(l_sourceCRS), NN_NO_CHECK(l_targetCRS), nullptr); } } else if (l_sourceCRS && l_targetCRS == nullptr && conv->method()->getEPSGCode() == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { // Needed for EPSG:7987 e.g. auto vertCRS = dynamic_cast<const crs::VerticalCRS *>(l_sourceCRS.get()); if (vertCRS && ends_with(l_sourceCRS->nameStr(), " height") && &vertCRS->coordinateSystem()->axisList()[0]->direction() == &cs::AxisDirection::UP) { op->setCRSs( NN_NO_CHECK(l_sourceCRS), crs::VerticalCRS::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, l_sourceCRS->nameStr().substr( 0, l_sourceCRS->nameStr().size() - strlen(" height")) + " depth"), vertCRS->datum(), vertCRS->datumEnsemble(), cs::VerticalCS::create( util::PropertyMap(), cs::CoordinateSystemAxis::create( util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "Gravity-related depth"), "D", cs::AxisDirection::DOWN, vertCRS->coordinateSystem() ->axisList()[0] ->unit()))), nullptr); } } } else if (!conv && l_sourceCRS && l_targetCRS) { // Transformations might be mentioned in their forward directions, // whereas we should instead use the reverse path. auto prevOpTarget = (i == 0) ? concatOpSourceCRS.as_nullable() : operationsInOut[i - 1]->targetCRS(); if (prevOpTarget == nullptr) { throw InvalidOperation( "Cannot determine targetCRS of operation at step " + toString(static_cast<int>(i))); } if (areCRSMoreOrLessEquivalent(l_sourceCRS.get(), prevOpTarget.get())) { // do nothing } else if (areCRSMoreOrLessEquivalent(l_targetCRS.get(), prevOpTarget.get())) { op = op->inverse(); } // Below is needed for EPSG:9103 which chains NAD83(2011) geographic // 2D with NAD83(2011) geocentric else if (l_sourceCRS->nameStr() == prevOpTarget->nameStr() && ((isGeographic(l_sourceCRS.get()) && isGeocentric(prevOpTarget.get())) || (isGeocentric(l_sourceCRS.get()) && isGeographic(prevOpTarget.get())))) { auto newOp(Conversion::createGeographicGeocentric( NN_NO_CHECK(prevOpTarget), NN_NO_CHECK(l_sourceCRS))); operationsInOut.insert(operationsInOut.begin() + i, newOp); } else if (l_targetCRS->nameStr() == prevOpTarget->nameStr() && ((isGeographic(l_targetCRS.get()) && isGeocentric(prevOpTarget.get())) || (isGeocentric(l_targetCRS.get()) && isGeographic(prevOpTarget.get())))) { auto newOp(Conversion::createGeographicGeocentric( NN_NO_CHECK(prevOpTarget), NN_NO_CHECK(l_targetCRS))); operationsInOut.insert(operationsInOut.begin() + i, newOp); // Particular case for https://github.com/OSGeo/PROJ/issues/3819 // where the antepenultimate transformation goes to A // (geographic 3D) // and the last transformation is a NADCON 3D // but between A (geographic 2D) to B (geographic 2D), and the // concatenated transformation target CRS is B (geographic 3D) // This is due to an oddity of the EPSG database that registers // the NADCON 3D transformation between the 2D geographic CRS // and not the 3D ones. } else if (i + 1 == operationsInOut.size() && l_sourceCRS->nameStr() == prevOpTarget->nameStr() && l_targetCRS->nameStr() == concatOpTargetCRS->nameStr() && isGeographic(l_targetCRS.get()) && isGeographic(concatOpTargetCRS.get()) && isGeographic(l_sourceCRS.get()) && isGeographic(prevOpTarget.get()) && dynamic_cast<const crs::GeographicCRS *>( prevOpTarget.get()) ->coordinateSystem() ->axisList() .size() == 3 && dynamic_cast<const crs::GeographicCRS *>( l_sourceCRS.get()) ->coordinateSystem() ->axisList() .size() == 2 && dynamic_cast<const crs::GeographicCRS *>( l_targetCRS.get()) ->coordinateSystem() ->axisList() .size() == 2) { const auto transf = dynamic_cast<const Transformation *>(op.get()); if (transf && (transf->method()->getEPSGCode() == EPSG_CODE_METHOD_NADCON5_3D || transf->parameterValue( PROJ_WKT2_PARAMETER_LATITUDE_LONGITUDE_ELLIPOISDAL_HEIGHT_DIFFERENCE_FILE, 0))) { op->setCRSs(NN_NO_CHECK(prevOpTarget), concatOpTargetCRS, nullptr); } } } } if (!operationsInOut.empty()) { auto l_sourceCRS = operationsInOut.front()->sourceCRS(); if (l_sourceCRS && !areCRSMoreOrLessEquivalent( l_sourceCRS.get(), concatOpSourceCRS.get())) { throw InvalidOperation("The source CRS of the first step of " "concatenated operation is not the same " "as the source CRS of the concatenated " "operation itself"); } auto l_targetCRS = operationsInOut.back()->targetCRS(); if (l_targetCRS && !areCRSMoreOrLessEquivalent( l_targetCRS.get(), concatOpTargetCRS.get())) { if (l_targetCRS->nameStr() == concatOpTargetCRS->nameStr() && ((isGeographic(l_targetCRS.get()) && isGeocentric(concatOpTargetCRS.get())) || (isGeocentric(l_targetCRS.get()) && isGeographic(concatOpTargetCRS.get())))) { auto newOp(Conversion::createGeographicGeocentric( NN_NO_CHECK(l_targetCRS), concatOpTargetCRS)); operationsInOut.push_back(newOp); } else { throw InvalidOperation("The target CRS of the last step of " "concatenated operation is not the same " "as the target CRS of the concatenated " "operation itself"); } } } } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a ConcatenatedOperation, or return a single * coordinate * operation. * * This computes its accuracy from the sum of its member operations, its * extent * * @param operationsIn Vector of the CoordinateOperation steps. * @param checkExtent Whether we should check the non-emptiness of the * intersection * of the extents of the operations * @throws InvalidOperation */ CoordinateOperationNNPtr ConcatenatedOperation::createComputeMetadata( const std::vector<CoordinateOperationNNPtr> &operationsIn, bool checkExtent) // throw InvalidOperation { util::PropertyMap properties; if (operationsIn.size() == 1) { return operationsIn[0]; } std::vector<CoordinateOperationNNPtr> flattenOps; bool hasBallparkTransformation = false; for (const auto &subOp : operationsIn) { hasBallparkTransformation |= subOp->hasBallparkTransformation(); auto subOpConcat = dynamic_cast<const ConcatenatedOperation *>(subOp.get()); if (subOpConcat) { auto subOps = subOpConcat->operations(); for (const auto &subSubOp : subOps) { flattenOps.emplace_back(subSubOp); } } else { flattenOps.emplace_back(subOp); } } // Remove consecutive inverse operations if (flattenOps.size() > 2) { std::vector<size_t> indices; for (size_t i = 0; i < flattenOps.size(); ++i) indices.push_back(i); while (true) { bool bHasChanged = false; for (size_t i = 0; i + 1 < indices.size(); ++i) { if (flattenOps[indices[i]]->_isEquivalentTo( flattenOps[indices[i + 1]]->inverse().get(), util::IComparable::Criterion::EQUIVALENT) && flattenOps[indices[i]]->sourceCRS()->_isEquivalentTo( flattenOps[indices[i + 1]]->targetCRS().get(), util::IComparable::Criterion::EQUIVALENT)) { indices.erase(indices.begin() + i, indices.begin() + i + 2); bHasChanged = true; break; } } // We bail out if indices.size() == 2, because potentially // the last 2 remaining ones could auto-cancel, and we would have // to have a special case for that (and this happens in practice). if (!bHasChanged || indices.size() <= 2) break; } if (indices.size() < flattenOps.size()) { std::vector<CoordinateOperationNNPtr> flattenOpsNew; for (size_t i = 0; i < indices.size(); ++i) { flattenOpsNew.emplace_back(flattenOps[indices[i]]); } flattenOps = std::move(flattenOpsNew); } } if (flattenOps.size() == 1) { return flattenOps[0]; } properties.set(common::IdentifiedObject::NAME_KEY, computeConcatenatedName(flattenOps)); bool emptyIntersection = false; auto extent = getExtent(flattenOps, false, emptyIntersection); if (checkExtent && emptyIntersection) { std::string msg( "empty intersection of area of validity of concatenated " "operations"); throw InvalidOperationEmptyIntersection(msg); } if (extent) { properties.set(common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, NN_NO_CHECK(extent)); } std::vector<metadata::PositionalAccuracyNNPtr> accuracies; const double accuracy = getAccuracy(flattenOps); if (accuracy >= 0.0) { accuracies.emplace_back( metadata::PositionalAccuracy::create(toString(accuracy))); } auto op = create(properties, flattenOps, accuracies); op->setHasBallparkTransformation(hasBallparkTransformation); op->d->computedName_ = true; return op; } // --------------------------------------------------------------------------- CoordinateOperationNNPtr ConcatenatedOperation::inverse() const { std::vector<CoordinateOperationNNPtr> inversedOperations; auto l_operations = operations(); inversedOperations.reserve(l_operations.size()); for (const auto &operation : l_operations) { inversedOperations.emplace_back(operation->inverse()); } std::reverse(inversedOperations.begin(), inversedOperations.end()); auto properties = createPropertiesForInverse(this, false, false); if (d->computedName_) { properties.set(common::IdentifiedObject::NAME_KEY, computeConcatenatedName(inversedOperations)); } auto op = create(properties, inversedOperations, coordinateOperationAccuracies()); op->d->computedName_ = d->computedName_; op->setHasBallparkTransformation(hasBallparkTransformation()); op->setSourceCoordinateEpoch(targetCoordinateEpoch()); op->setTargetCoordinateEpoch(sourceCoordinateEpoch()); return op; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ConcatenatedOperation::_exportToWKT(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2 || !formatter->use2019Keywords()) { throw io::FormattingException( "Transformation can only be exported to WKT2:2019"); } formatter->startNode(io::WKTConstants::CONCATENATEDOPERATION, !identifiers().empty()); formatter->addQuotedString(nameStr()); if (formatter->use2019Keywords()) { const auto &version = operationVersion(); if (version.has_value()) { formatter->startNode(io::WKTConstants::VERSION, false); formatter->addQuotedString(*version); formatter->endNode(); } } exportSourceCRSAndTargetCRSToWKT(this, formatter); const bool canExportOperationId = !(formatter->idOnTopLevelOnly() && formatter->topLevelHasId()); const bool hasDomains = !domains().empty(); if (hasDomains) { formatter->pushDisableUsage(); } for (const auto &operation : operations()) { formatter->startNode(io::WKTConstants::STEP, false); if (canExportOperationId && !operation->identifiers().empty()) { // fake that top node has no id, so that the operation id is // considered formatter->pushHasId(false); operation->_exportToWKT(formatter); formatter->popHasId(); } else { operation->_exportToWKT(formatter); } formatter->endNode(); } if (hasDomains) { formatter->popDisableUsage(); } if (!coordinateOperationAccuracies().empty()) { formatter->startNode(io::WKTConstants::OPERATIONACCURACY, false); formatter->add(coordinateOperationAccuracies()[0]->value()); formatter->endNode(); } ObjectUsage::baseExportToWKT(formatter); formatter->endNode(); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void ConcatenatedOperation::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext(formatter->MakeObjectContext("ConcatenatedOperation", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("source_crs"); formatter->setAllowIDInImmediateChild(); sourceCRS()->_exportToJSON(formatter); writer->AddObjKey("target_crs"); formatter->setAllowIDInImmediateChild(); targetCRS()->_exportToJSON(formatter); writer->AddObjKey("steps"); { auto parametersContext(writer->MakeArrayContext(false)); for (const auto &operation : operations()) { formatter->setAllowIDInImmediateChild(); operation->_exportToJSON(formatter); } } if (!coordinateOperationAccuracies().empty()) { writer->AddObjKey("accuracy"); writer->Add(coordinateOperationAccuracies()[0]->value()); } ObjectUsage::baseExportToJSON(formatter); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress CoordinateOperationNNPtr ConcatenatedOperation::_shallowClone() const { auto op = ConcatenatedOperation::nn_make_shared<ConcatenatedOperation>(*this); std::vector<CoordinateOperationNNPtr> ops; for (const auto &subOp : d->operations_) { ops.emplace_back(subOp->shallowClone()); } op->d->operations_ = std::move(ops); op->assignSelf(op); op->setCRSs(this, false); return util::nn_static_pointer_cast<CoordinateOperation>(op); } //! @endcond // --------------------------------------------------------------------------- void ConcatenatedOperation::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(FormattingException) { double sourceYear = sourceCoordinateEpoch().has_value() ? getRoundedEpochInDecimalYear( sourceCoordinateEpoch()->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)) : 0; double targetYear = targetCoordinateEpoch().has_value() ? getRoundedEpochInDecimalYear( targetCoordinateEpoch()->coordinateEpoch().convertToUnit( common::UnitOfMeasure::YEAR)) : 0; if (sourceYear > 0 && targetYear == 0) targetYear = sourceYear; else if (targetYear > 0 && sourceYear == 0) sourceYear = targetYear; if (sourceYear > 0) { formatter->addStep("set"); formatter->addParam("v_4", sourceYear); } for (const auto &operation : operations()) { operation->_exportToPROJString(formatter); } if (targetYear > 0) { formatter->addStep("set"); formatter->addParam("v_4", targetYear); } } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress bool ConcatenatedOperation::_isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const { auto otherCO = dynamic_cast<const ConcatenatedOperation *>(other); if (otherCO == nullptr || (criterion == util::IComparable::Criterion::STRICT && !ObjectUsage::_isEquivalentTo(other, criterion, dbContext))) { return false; } const auto &steps = operations(); const auto &otherSteps = otherCO->operations(); if (steps.size() != otherSteps.size()) { return false; } for (size_t i = 0; i < steps.size(); i++) { if (!steps[i]->_isEquivalentTo(otherSteps[i].get(), criterion, dbContext)) { return false; } } return true; } //! @endcond // --------------------------------------------------------------------------- std::set<GridDescription> ConcatenatedOperation::gridsNeeded( const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const { std::set<GridDescription> res; for (const auto &operation : operations()) { const auto l_gridsNeeded = operation->gridsNeeded( databaseContext, considerKnownGridsAsAvailable); for (const auto &gridDesc : l_gridsNeeded) { res.insert(gridDesc); } } return res; } // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/vectorofvaluesparams.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef VECTOROFVALUESPARAMS_HPP #define VECTOROFVALUESPARAMS_HPP #include "proj/coordinateoperation.hpp" #include "proj/util.hpp" // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct VectorOfValues : public std::vector<ParameterValueNNPtr> { VectorOfValues() : std::vector<ParameterValueNNPtr>() {} explicit VectorOfValues(std::initializer_list<ParameterValueNNPtr> list) : std::vector<ParameterValueNNPtr>(list) {} explicit VectorOfValues(std::initializer_list<common::Measure> list); VectorOfValues(const VectorOfValues &) = delete; VectorOfValues(VectorOfValues &&) = default; ~VectorOfValues(); }; VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3); VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4); VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4, const common::Measure &m5); VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4, const common::Measure &m5, const common::Measure &m6); VectorOfValues createParams(const common::Measure &m1, const common::Measure &m2, const common::Measure &m3, const common::Measure &m4, const common::Measure &m5, const common::Measure &m6, const common::Measure &m7); // --------------------------------------------------------------------------- struct VectorOfParameters : public std::vector<OperationParameterNNPtr> { VectorOfParameters() : std::vector<OperationParameterNNPtr>() {} explicit VectorOfParameters( std::initializer_list<OperationParameterNNPtr> list) : std::vector<OperationParameterNNPtr>(list) {} VectorOfParameters(const VectorOfParameters &) = delete; ~VectorOfParameters(); }; //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END #endif // VECTOROFVALUESPARAMS_HPP
hpp
PROJ
data/projects/PROJ/src/iso19111/operation/esriparammappings.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef ESRIPARAMMAPPINGS_HPP #define ESRIPARAMMAPPINGS_HPP #include "proj/coordinateoperation.hpp" #include "proj/util.hpp" #include "esriparammappings.hpp" #include <vector> // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct ESRIParamMapping { const char *esri_name; const char *wkt2_name; int epsg_code; const char *fixed_value; bool is_fixed_value; }; struct ESRIMethodMapping { const char *esri_name; const char *wkt2_name; int epsg_code; const ESRIParamMapping *const params; }; extern const ESRIParamMapping paramsESRI_Plate_Carree[]; extern const ESRIParamMapping paramsESRI_Equidistant_Cylindrical[]; extern const ESRIParamMapping paramsESRI_Gauss_Kruger[]; extern const ESRIParamMapping paramsESRI_Transverse_Mercator[]; extern const ESRIParamMapping paramsESRI_Hotine_Oblique_Mercator_Azimuth_Natural_Origin[]; extern const ESRIParamMapping paramsESRI_Rectified_Skew_Orthomorphic_Natural_Origin[]; extern const ESRIParamMapping paramsESRI_Hotine_Oblique_Mercator_Azimuth_Center[]; extern const ESRIParamMapping paramsESRI_Rectified_Skew_Orthomorphic_Center[]; const ESRIMethodMapping *getEsriMappings(size_t &nElts); std::vector<const ESRIMethodMapping *> getMappingsFromESRI(const std::string &esri_name); //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END #endif // ESRIPARAMMAPPINGS_HPP
hpp
PROJ
data/projects/PROJ/src/iso19111/operation/conversion.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj/internal/tracing.hpp" #include "coordinateoperation_internal.hpp" #include "esriparammappings.hpp" #include "operationmethod_private.hpp" #include "oputils.hpp" #include "parammappings.hpp" #include "vectorofvaluesparams.hpp" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // M_PI // clang-format on #include "proj_constants.h" #include "proj_json_streaming_writer.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <memory> #include <set> #include <string> #include <vector> using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { //! @cond Doxygen_Suppress constexpr double UTM_LATITUDE_OF_NATURAL_ORIGIN = 0.0; constexpr double UTM_SCALE_FACTOR = 0.9996; constexpr double UTM_FALSE_EASTING = 500000.0; constexpr double UTM_NORTH_FALSE_NORTHING = 0.0; constexpr double UTM_SOUTH_FALSE_NORTHING = 10000000.0; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct Conversion::Private {}; //! @endcond // --------------------------------------------------------------------------- Conversion::Conversion(const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values) : SingleOperation(methodIn), d(nullptr) { setParameterValues(values); } // --------------------------------------------------------------------------- Conversion::Conversion(const Conversion &other) : CoordinateOperation(other), SingleOperation(other), d(nullptr) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress Conversion::~Conversion() = default; //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ConversionNNPtr Conversion::shallowClone() const { auto conv = Conversion::nn_make_shared<Conversion>(*this); conv->assignSelf(conv); conv->setCRSs(this, false); return conv; } CoordinateOperationNNPtr Conversion::_shallowClone() const { return util::nn_static_pointer_cast<CoordinateOperation>(shallowClone()); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ConversionNNPtr Conversion::alterParametersLinearUnit(const common::UnitOfMeasure &unit, bool convertToNewUnit) const { std::vector<GeneralParameterValueNNPtr> newValues; bool changesDone = false; for (const auto &genOpParamvalue : parameterValues()) { bool updated = false; auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &paramValue = opParamvalue->parameterValue(); if (paramValue->type() == ParameterValue::Type::MEASURE) { const auto &measure = paramValue->value(); if (measure.unit().type() == common::UnitOfMeasure::Type::LINEAR) { if (!measure.unit()._isEquivalentTo( unit, util::IComparable::Criterion::EQUIVALENT)) { const double newValue = convertToNewUnit ? measure.convertToUnit(unit) : measure.value(); newValues.emplace_back(OperationParameterValue::create( opParamvalue->parameter(), ParameterValue::create( common::Measure(newValue, unit)))); updated = true; } } } } if (updated) { changesDone = true; } else { newValues.emplace_back(genOpParamvalue); } } if (changesDone) { auto conv = create(util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, "unknown"), method(), newValues); conv->setCRSs(this, false); return conv; } else { return NN_NO_CHECK( util::nn_dynamic_pointer_cast<Conversion>(shared_from_this())); } } //! @endcond // --------------------------------------------------------------------------- /** \brief Instantiate a Conversion from a vector of GeneralParameterValue. * * @param properties See \ref general_properties. At minimum the name should be * defined. * @param methodIn the operation method. * @param values the values. * @return a new Conversion. * @throws InvalidOperation */ ConversionNNPtr Conversion::create(const util::PropertyMap &properties, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values) // throw InvalidOperation { if (methodIn->parameters().size() != values.size()) { throw InvalidOperation( "Inconsistent number of parameters and parameter values"); } auto conv = Conversion::nn_make_shared<Conversion>(methodIn, values); conv->assignSelf(conv); conv->setProperties(properties); return conv; } // --------------------------------------------------------------------------- /** \brief Instantiate a Conversion and its OperationMethod * * @param propertiesConversion See \ref general_properties of the conversion. * At minimum the name should be defined. * @param propertiesOperationMethod See \ref general_properties of the operation * method. At minimum the name should be defined. * @param parameters the operation parameters. * @param values the operation values. Constraint: * values.size() == parameters.size() * @return a new Conversion. * @throws InvalidOperation */ ConversionNNPtr Conversion::create( const util::PropertyMap &propertiesConversion, const util::PropertyMap &propertiesOperationMethod, const std::vector<OperationParameterNNPtr> &parameters, const std::vector<ParameterValueNNPtr> &values) // throw InvalidOperation { OperationMethodNNPtr op( OperationMethod::create(propertiesOperationMethod, parameters)); if (parameters.size() != values.size()) { throw InvalidOperation( "Inconsistent number of parameters and parameter values"); } std::vector<GeneralParameterValueNNPtr> generalParameterValues; generalParameterValues.reserve(values.size()); for (size_t i = 0; i < values.size(); i++) { generalParameterValues.push_back( OperationParameterValue::create(parameters[i], values[i])); } return create(propertiesConversion, op, generalParameterValues); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- static util::PropertyMap getUTMConversionProperty(const util::PropertyMap &properties, int zone, bool north) { if (!properties.get(common::IdentifiedObject::NAME_KEY)) { std::string conversionName("UTM zone "); conversionName += toString(zone); conversionName += (north ? 'N' : 'S'); return createMapNameEPSGCode(conversionName, (north ? 16000 : 17000) + zone); } else { return properties; } } // --------------------------------------------------------------------------- static ConversionNNPtr createConversion(const util::PropertyMap &properties, const MethodMapping *mapping, const std::vector<ParameterValueNNPtr> &values) { std::vector<OperationParameterNNPtr> parameters; for (int i = 0; mapping->params != nullptr && mapping->params[i] != nullptr; i++) { const auto *param = mapping->params[i]; auto paramProperties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, param->wkt2_name); if (param->epsg_code != 0) { paramProperties .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, param->epsg_code); } auto parameter = OperationParameter::create(paramProperties); parameters.push_back(parameter); } auto methodProperties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, mapping->wkt2_name); if (mapping->epsg_code != 0) { methodProperties .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) .set(metadata::Identifier::CODE_KEY, mapping->epsg_code); } return Conversion::create( addDefaultNameIfNeeded(properties, mapping->wkt2_name), methodProperties, parameters, values); } //! @endcond // --------------------------------------------------------------------------- ConversionNNPtr Conversion::create(const util::PropertyMap &properties, int method_epsg_code, const std::vector<ParameterValueNNPtr> &values) { const MethodMapping *mapping = getMapping(method_epsg_code); assert(mapping); return createConversion(properties, mapping, values); } // --------------------------------------------------------------------------- ConversionNNPtr Conversion::create(const util::PropertyMap &properties, const char *method_wkt2_name, const std::vector<ParameterValueNNPtr> &values) { const MethodMapping *mapping = getMapping(method_wkt2_name); assert(mapping); return createConversion(properties, mapping, values); } // --------------------------------------------------------------------------- /** \brief Instantiate a * <a href="../../../operations/projections/utm.html"> * Universal Transverse Mercator</a> conversion. * * UTM is a family of conversions, of EPSG codes from 16001 to 16060 for the * northern hemisphere, and 17001 to 17060 for the southern hemisphere, * based on the Transverse Mercator projection method. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param zone UTM zone number between 1 and 60. * @param north true for UTM northern hemisphere, false for UTM southern * hemisphere. * @return a new Conversion. */ ConversionNNPtr Conversion::createUTM(const util::PropertyMap &properties, int zone, bool north) { if (zone < 1 || zone > 60) { throw InvalidOperation("Invalid zone number"); } return create( getUTMConversionProperty(properties, zone, north), EPSG_CODE_METHOD_TRANSVERSE_MERCATOR, createParams(common::Angle(UTM_LATITUDE_OF_NATURAL_ORIGIN), common::Angle(zone * 6.0 - 183.0), common::Scale(UTM_SCALE_FACTOR), common::Length(UTM_FALSE_EASTING), common::Length(north ? UTM_NORTH_FALSE_NORTHING : UTM_SOUTH_FALSE_NORTHING))); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/tmerc.html"> * Transverse Mercator</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9807/index.html"> * EPSG:9807</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createTransverseMercator( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/gstmerc.html"> * Gauss Schreiber Transverse Mercator</a> projection method. * * This method is also known as Gauss-Laborde Reunion. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createGaussSchreiberTransverseMercator( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_GAUSS_SCHREIBER_TRANSVERSE_MERCATOR, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/tmerc.html"> * Transverse Mercator South Orientated</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9808/index.html"> * EPSG:9808</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createTransverseMercatorSouthOriented( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/tpeqd.html"> * Two Point Equidistant</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFirstPoint Latitude of first point. * @param longitudeFirstPoint Longitude of first point. * @param latitudeSecondPoint Latitude of second point. * @param longitudeSeconPoint Longitude of second point. * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createTwoPointEquidistant(const util::PropertyMap &properties, const common::Angle &latitudeFirstPoint, const common::Angle &longitudeFirstPoint, const common::Angle &latitudeSecondPoint, const common::Angle &longitudeSeconPoint, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_TWO_POINT_EQUIDISTANT, createParams(latitudeFirstPoint, longitudeFirstPoint, latitudeSecondPoint, longitudeSeconPoint, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Tunisia Mapping Grid projection * method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9816/index.html"> * EPSG:9816</a>. * * \note There is currently no implementation of the method formulas in PROJ. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. * @deprecated. Use createTunisiaMiningGrid() instead */ ConversionNNPtr Conversion::createTunisiaMappingGrid( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_TUNISIA_MINING_GRID, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Tunisia Mining Grid projection * method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9816/index.html"> * EPSG:9816</a>. * * \note There is currently no implementation of the method formulas in PROJ. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. * @since 9.2 */ ConversionNNPtr Conversion::createTunisiaMiningGrid( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_TUNISIA_MINING_GRID, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/aea.html"> * Albers Conic Equal Area</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9822/index.html"> * EPSG:9822</a>. * * @note the order of arguments is conformant with the corresponding EPSG * mode and different than OGRSpatialReference::setACEA() of GDAL &lt;= 2.3 * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFalseOrigin See \ref latitude_false_origin * @param longitudeFalseOrigin See \ref longitude_false_origin * @param latitudeFirstParallel See \ref latitude_first_std_parallel * @param latitudeSecondParallel See \ref latitude_second_std_parallel * @param eastingFalseOrigin See \ref easting_false_origin * @param northingFalseOrigin See \ref northing_false_origin * @return a new Conversion. */ ConversionNNPtr Conversion::createAlbersEqualArea(const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin) { return create(properties, EPSG_CODE_METHOD_ALBERS_EQUAL_AREA, createParams(latitudeFalseOrigin, longitudeFalseOrigin, latitudeFirstParallel, latitudeSecondParallel, eastingFalseOrigin, northingFalseOrigin)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/lcc.html"> * Lambert Conic Conformal 1SP</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9801/index.html"> * EPSG:9801</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createLambertConicConformal_1SP( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/lcc.html"> * Lambert Conic Conformal 1SP Variant B</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1102/index.html"> * EPSG:1102</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeNatOrigin See \ref center_latitude * @param scale See \ref scale * @param latitudeFalseOrigin See \ref latitude_false_origin * @param longitudeFalseOrigin See \ref longitude_false_origin * @param eastingFalseOrigin See \ref easting_false_origin * @param northingFalseOrigin See \ref northing_false_origin * @return a new Conversion. * @since 9.2.1 */ ConversionNNPtr Conversion::createLambertConicConformal_1SP_VariantB( const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Scale &scale, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin) { return create(properties, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B, createParams(latitudeNatOrigin, scale, latitudeFalseOrigin, longitudeFalseOrigin, eastingFalseOrigin, northingFalseOrigin)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/lcc.html"> * Lambert Conic Conformal 2SP</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9802/index.html"> * EPSG:9802</a>. * * @note the order of arguments is conformant with the corresponding EPSG * mode and different than OGRSpatialReference::setLCC() of GDAL &lt;= 2.3 * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFalseOrigin See \ref latitude_false_origin * @param longitudeFalseOrigin See \ref longitude_false_origin * @param latitudeFirstParallel See \ref latitude_first_std_parallel * @param latitudeSecondParallel See \ref latitude_second_std_parallel * @param eastingFalseOrigin See \ref easting_false_origin * @param northingFalseOrigin See \ref northing_false_origin * @return a new Conversion. */ ConversionNNPtr Conversion::createLambertConicConformal_2SP( const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin) { return create(properties, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, createParams(latitudeFalseOrigin, longitudeFalseOrigin, latitudeFirstParallel, latitudeSecondParallel, eastingFalseOrigin, northingFalseOrigin)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/lcc.html"> * Lambert Conic Conformal (2SP Michigan)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1051/index.html"> * EPSG:1051</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFalseOrigin See \ref latitude_false_origin * @param longitudeFalseOrigin See \ref longitude_false_origin * @param latitudeFirstParallel See \ref latitude_first_std_parallel * @param latitudeSecondParallel See \ref latitude_second_std_parallel * @param eastingFalseOrigin See \ref easting_false_origin * @param northingFalseOrigin See \ref northing_false_origin * @param ellipsoidScalingFactor Ellipsoid scaling factor. * @return a new Conversion. */ ConversionNNPtr Conversion::createLambertConicConformal_2SP_Michigan( const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin, const common::Scale &ellipsoidScalingFactor) { return create(properties, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN, createParams(latitudeFalseOrigin, longitudeFalseOrigin, latitudeFirstParallel, latitudeSecondParallel, eastingFalseOrigin, northingFalseOrigin, ellipsoidScalingFactor)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/lcc.html"> * Lambert Conic Conformal (2SP Belgium)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9803/index.html"> * EPSG:9803</a>. * * \warning The formulas used currently in PROJ are, incorrectly, the ones of * the regular LCC_2SP method. * * @note the order of arguments is conformant with the corresponding EPSG * mode and different than OGRSpatialReference::setLCCB() of GDAL &lt;= 2.3 * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFalseOrigin See \ref latitude_false_origin * @param longitudeFalseOrigin See \ref longitude_false_origin * @param latitudeFirstParallel See \ref latitude_first_std_parallel * @param latitudeSecondParallel See \ref latitude_second_std_parallel * @param eastingFalseOrigin See \ref easting_false_origin * @param northingFalseOrigin See \ref northing_false_origin * @return a new Conversion. */ ConversionNNPtr Conversion::createLambertConicConformal_2SP_Belgium( const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin) { return create(properties, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM, createParams(latitudeFalseOrigin, longitudeFalseOrigin, latitudeFirstParallel, latitudeSecondParallel, eastingFalseOrigin, northingFalseOrigin)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/aeqd.html"> * Azimuthal Equidistant</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1125/index.html"> * EPSG:1125</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeNatOrigin See \ref center_latitude * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createAzimuthalEquidistant( const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_AZIMUTHAL_EQUIDISTANT, createParams(latitudeNatOrigin, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/aeqd.html"> * Guam Projection</a> method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9831/index.html"> * EPSG:9831</a>. * * @param properties See \ref general_properties of the conversion. If the name *is * not provided, it is automatically set. * @param latitudeNatOrigin See \ref center_latitude * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createGuamProjection( const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_GUAM_PROJECTION, createParams(latitudeNatOrigin, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/bonne.html"> * Bonne</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9827/index.html"> * EPSG:9827</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeNatOrigin See \ref center_latitude . PROJ calls its the * standard parallel 1. * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createBonne(const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_BONNE, createParams(latitudeNatOrigin, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/cea.html"> * Lambert Cylindrical Equal Area (Spherical)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9834/index.html"> * EPSG:9834</a>. * * \warning The PROJ cea computation code would select the ellipsoidal form if * a non-spherical ellipsoid is used for the base GeographicCRS. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFirstParallel See \ref latitude_first_std_parallel. * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createLambertCylindricalEqualAreaSpherical( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL, createParams(latitudeFirstParallel, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/cea.html"> * Lambert Cylindrical Equal Area (ellipsoidal form)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9835/index.html"> * EPSG:9835</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFirstParallel See \ref latitude_first_std_parallel. * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createLambertCylindricalEqualArea( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, createParams(latitudeFirstParallel, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/cass.html"> * Cassini-Soldner</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9806/index.html"> * EPSG:9806</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createCassiniSoldner( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_CASSINI_SOLDNER, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eqdc.html"> * Equidistant Conic</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1119/index.html"> * EPSG:1119</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFalseOrigin See \ref latitude_false_origin * @param longitudeFalseOrigin See \ref longitude_false_origin * @param latitudeFirstParallel See \ref latitude_first_std_parallel * @param latitudeSecondParallel See \ref latitude_second_std_parallel * @param eastingFalseOrigin See \ref easting_false_origin * @param northingFalseOrigin See \ref northing_false_origin * @return a new Conversion. */ ConversionNNPtr Conversion::createEquidistantConic(const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin) { return create(properties, EPSG_CODE_METHOD_EQUIDISTANT_CONIC, createParams(latitudeFalseOrigin, longitudeFalseOrigin, latitudeFirstParallel, latitudeSecondParallel, eastingFalseOrigin, northingFalseOrigin)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eck1.html"> * Eckert I</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEckertI(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_ECKERT_I, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eck2.html"> * Eckert II</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEckertII( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_ECKERT_II, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eck3.html"> * Eckert III</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEckertIII( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_ECKERT_III, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eck4.html"> * Eckert IV</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEckertIV( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_ECKERT_IV, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eck5.html"> * Eckert V</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEckertV(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_ECKERT_V, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eck6.html"> * Eckert VI</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEckertVI( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_ECKERT_VI, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eqc.html"> * Equidistant Cylindrical</a> projection method. * * This is also known as the Equirectangular method, and in the particular case * where the latitude of first parallel is 0. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1028/index.html"> * EPSG:1028</a>. * * @note This is the equivalent OGRSpatialReference::SetEquirectangular2( * 0.0, latitudeFirstParallel, falseEasting, falseNorthing ) of GDAL &lt;= 2.3, * where the lat_0 / center_latitude parameter is forced to 0. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFirstParallel See \ref latitude_first_std_parallel. * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEquidistantCylindrical( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL, createParams(latitudeFirstParallel, 0.0, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eqc.html"> * Equidistant Cylindrical (Spherical)</a> projection method. * * This is also known as the Equirectangular method, and in the particular case * where the latitude of first parallel is 0. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1029/index.html"> * EPSG:1029</a>. * * @note This is the equivalent OGRSpatialReference::SetEquirectangular2( * 0.0, latitudeFirstParallel, falseEasting, falseNorthing ) of GDAL &lt;= 2.3, * where the lat_0 / center_latitude parameter is forced to 0. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFirstParallel See \ref latitude_first_std_parallel. * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEquidistantCylindricalSpherical( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL, createParams(latitudeFirstParallel, 0.0, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/gall.html"> * Gall (Stereographic)</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createGall(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_GALL_STEREOGRAPHIC, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/goode.html"> * Goode Homolosine</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createGoodeHomolosine( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_GOODE_HOMOLOSINE, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/igh.html"> * Interrupted Goode Homolosine</a> projection method. * * There is no equivalent in EPSG. * * @note OGRSpatialReference::SetIGH() of GDAL &lt;= 2.3 assumes the 3 * projection * parameters to be zero and this is the nominal case. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createInterruptedGoodeHomolosine( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/geos.html"> * Geostationary Satellite View</a> projection method, * with the sweep angle axis of the viewing instrument being x * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param height Height of the view point above the Earth. * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createGeostationarySatelliteSweepX( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &height, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X, createParams(centerLong, height, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/geos.html"> * Geostationary Satellite View</a> projection method, * with the sweep angle axis of the viewing instrument being y. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param height Height of the view point above the Earth. * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createGeostationarySatelliteSweepY( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &height, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y, createParams(centerLong, height, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/gnom.html"> * Gnomonic</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createGnomonic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, PROJ_WKT2_NAME_METHOD_GNOMONIC, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/omerc.html"> * Hotine Oblique Mercator (Variant A)</a> projection method. * * This is the variant with the no_uoff parameter, which corresponds to * GDAL &gt;=2.3 Hotine_Oblique_Mercator projection. * In this variant, the false grid coordinates are * defined at the intersection of the initial line and the aposphere (the * equator on one of the intermediate surfaces inherent in the method), that is * at the natural origin of the coordinate system). * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9812/index.html"> * EPSG:9812</a>. * * \note In the case where azimuthInitialLine = angleFromRectifiedToSkrewGrid = * 90deg, this maps to the * <a href="../../../operations/projections/somerc.html"> * Swiss Oblique Mercator</a> formulas. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeProjectionCentre See \ref latitude_projection_centre * @param longitudeProjectionCentre See \ref longitude_projection_centre * @param azimuthInitialLine See \ref azimuth_initial_line * @param angleFromRectifiedToSkrewGrid See * \ref angle_from_recitfied_to_skrew_grid * @param scale See \ref scale_factor_initial_line * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createHotineObliqueMercatorVariantA( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeProjectionCentre, const common::Angle &azimuthInitialLine, const common::Angle &angleFromRectifiedToSkrewGrid, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, createParams(latitudeProjectionCentre, longitudeProjectionCentre, azimuthInitialLine, angleFromRectifiedToSkrewGrid, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/omerc.html"> * Hotine Oblique Mercator (Variant B)</a> projection method. * * This is the variant without the no_uoff parameter, which corresponds to * GDAL &gt;=2.3 Hotine_Oblique_Mercator_Azimuth_Center projection. * In this variant, the false grid coordinates are defined at the projection *centre. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9815/index.html"> * EPSG:9815</a>. * * \note In the case where azimuthInitialLine = angleFromRectifiedToSkrewGrid = * 90deg, this maps to the * <a href="../../../operations/projections/somerc.html"> * Swiss Oblique Mercator</a> formulas. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeProjectionCentre See \ref latitude_projection_centre * @param longitudeProjectionCentre See \ref longitude_projection_centre * @param azimuthInitialLine See \ref azimuth_initial_line * @param angleFromRectifiedToSkrewGrid See * \ref angle_from_recitfied_to_skrew_grid * @param scale See \ref scale_factor_initial_line * @param eastingProjectionCentre See \ref easting_projection_centre * @param northingProjectionCentre See \ref northing_projection_centre * @return a new Conversion. */ ConversionNNPtr Conversion::createHotineObliqueMercatorVariantB( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeProjectionCentre, const common::Angle &azimuthInitialLine, const common::Angle &angleFromRectifiedToSkrewGrid, const common::Scale &scale, const common::Length &eastingProjectionCentre, const common::Length &northingProjectionCentre) { return create( properties, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, createParams(latitudeProjectionCentre, longitudeProjectionCentre, azimuthInitialLine, angleFromRectifiedToSkrewGrid, scale, eastingProjectionCentre, northingProjectionCentre)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/omerc.html"> * Hotine Oblique Mercator Two Point Natural Origin</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeProjectionCentre See \ref latitude_projection_centre * @param latitudePoint1 Latitude of point 1. * @param longitudePoint1 Latitude of point 1. * @param latitudePoint2 Latitude of point 2. * @param longitudePoint2 Longitude of point 2. * @param scale See \ref scale_factor_initial_line * @param eastingProjectionCentre See \ref easting_projection_centre * @param northingProjectionCentre See \ref northing_projection_centre * @return a new Conversion. */ ConversionNNPtr Conversion::createHotineObliqueMercatorTwoPointNaturalOrigin( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &latitudePoint1, const common::Angle &longitudePoint1, const common::Angle &latitudePoint2, const common::Angle &longitudePoint2, const common::Scale &scale, const common::Length &eastingProjectionCentre, const common::Length &northingProjectionCentre) { return create( properties, PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN, { ParameterValue::create(latitudeProjectionCentre), ParameterValue::create(latitudePoint1), ParameterValue::create(longitudePoint1), ParameterValue::create(latitudePoint2), ParameterValue::create(longitudePoint2), ParameterValue::create(scale), ParameterValue::create(eastingProjectionCentre), ParameterValue::create(northingProjectionCentre), }); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/labrd.html"> * Laborde Oblique Mercator</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9813/index.html"> * EPSG:9813</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeProjectionCentre See \ref latitude_projection_centre * @param longitudeProjectionCentre See \ref longitude_projection_centre * @param azimuthInitialLine See \ref azimuth_initial_line * @param scale See \ref scale_factor_initial_line * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createLabordeObliqueMercator( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeProjectionCentre, const common::Angle &azimuthInitialLine, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_LABORDE_OBLIQUE_MERCATOR, createParams(latitudeProjectionCentre, longitudeProjectionCentre, azimuthInitialLine, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/imw_p.html"> * International Map of the World Polyconic</a> projection method. * * There is no equivalent in EPSG. * * @note the order of arguments is conformant with the corresponding EPSG * mode and different than OGRSpatialReference::SetIWMPolyconic() of GDAL &lt;= *2.3 * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param latitudeFirstParallel See \ref latitude_first_std_parallel * @param latitudeSecondParallel See \ref latitude_second_std_parallel * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createInternationalMapWorldPolyconic( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_INTERNATIONAL_MAP_WORLD_POLYCONIC, createParams(centerLong, latitudeFirstParallel, latitudeSecondParallel, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/krovak.html"> * Krovak (north oriented)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1041/index.html"> * EPSG:1041</a>. * * The coordinates are returned in the "GIS friendly" order: easting, northing. * This method is similar to createKrovak(), except that the later returns * projected values as southing, westing, where * southing(Krovak) = -northing(Krovak_North) and * westing(Krovak) = -easting(Krovak_North). * * @note The current PROJ implementation of Krovak hard-codes * colatitudeConeAxis = 30deg17'17.30311" * and latitudePseudoStandardParallel = 78deg30'N, which are the values used for * the ProjectedCRS S-JTSK (Ferro) / Krovak East North (EPSG:5221). * It also hard-codes the parameters of the Bessel ellipsoid typically used for * Krovak. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeProjectionCentre See \ref latitude_projection_centre * @param longitudeOfOrigin See \ref longitude_of_origin * @param colatitudeConeAxis See \ref colatitude_cone_axis * @param latitudePseudoStandardParallel See \ref *latitude_pseudo_standard_parallel * @param scaleFactorPseudoStandardParallel See \ref *scale_factor_pseudo_standard_parallel * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createKrovakNorthOriented( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeOfOrigin, const common::Angle &colatitudeConeAxis, const common::Angle &latitudePseudoStandardParallel, const common::Scale &scaleFactorPseudoStandardParallel, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_KROVAK_NORTH_ORIENTED, createParams(latitudeProjectionCentre, longitudeOfOrigin, colatitudeConeAxis, latitudePseudoStandardParallel, scaleFactorPseudoStandardParallel, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/krovak.html"> * Krovak</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9819/index.html"> * EPSG:9819</a>. * * The coordinates are returned in the historical order: southing, westing * This method is similar to createKrovakNorthOriented(), except that the later *returns * projected values as easting, northing, where * easting(Krovak_North) = -westing(Krovak) and * northing(Krovak_North) = -southing(Krovak). * * @note The current PROJ implementation of Krovak hard-codes * colatitudeConeAxis = 30deg17'17.30311" * and latitudePseudoStandardParallel = 78deg30'N, which are the values used for * the ProjectedCRS S-JTSK (Ferro) / Krovak East North (EPSG:5221). * It also hard-codes the parameters of the Bessel ellipsoid typically used for * Krovak. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeProjectionCentre See \ref latitude_projection_centre * @param longitudeOfOrigin See \ref longitude_of_origin * @param colatitudeConeAxis See \ref colatitude_cone_axis * @param latitudePseudoStandardParallel See \ref *latitude_pseudo_standard_parallel * @param scaleFactorPseudoStandardParallel See \ref *scale_factor_pseudo_standard_parallel * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createKrovak(const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeOfOrigin, const common::Angle &colatitudeConeAxis, const common::Angle &latitudePseudoStandardParallel, const common::Scale &scaleFactorPseudoStandardParallel, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_KROVAK, createParams(latitudeProjectionCentre, longitudeOfOrigin, colatitudeConeAxis, latitudePseudoStandardParallel, scaleFactorPseudoStandardParallel, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/laea.html"> * Lambert Azimuthal Equal Area</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9820/index.html"> * EPSG:9820</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeNatOrigin See \ref center_latitude * @param longitudeNatOrigin See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createLambertAzimuthalEqualArea( const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA, createParams(latitudeNatOrigin, longitudeNatOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/mill.html"> * Miller Cylindrical</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createMillerCylindrical( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_MILLER_CYLINDRICAL, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/merc.html"> * Mercator (variant A)</a> projection method. * * This is the A variant, also known as Mercator (1SP), defined with the scale * factor. Note that latitude of natural origin (centerLat) is a parameter, * but unused in the transformation formulas. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9804/index.html"> * EPSG:9804</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude . Should be 0. * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createMercatorVariantA( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_MERCATOR_VARIANT_A, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/merc.html"> * Mercator (variant B)</a> projection method. * * This is the B variant, also known as Mercator (2SP), defined with the * latitude of the first standard parallel (the second standard parallel is * implicitly the opposite value). The latitude of natural origin is fixed to * zero. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9805/index.html"> * EPSG:9805</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeFirstParallel See \ref latitude_first_std_parallel * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createMercatorVariantB( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, createParams(latitudeFirstParallel, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/webmerc.html"> * Popular Visualisation Pseudo Mercator</a> projection method. * * Also known as WebMercator. Mostly/only used for Projected CRS EPSG:3857 * (WGS 84 / Pseudo-Mercator) * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1024/index.html"> * EPSG:1024</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude . Usually 0 * @param centerLong See \ref center_longitude . Usually 0 * @param falseEasting See \ref false_easting . Usually 0 * @param falseNorthing See \ref false_northing . Usually 0 * @return a new Conversion. */ ConversionNNPtr Conversion::createPopularVisualisationPseudoMercator( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/merc.html"> * Mercator</a> projection method, using its spherical formulation * * When used with an ellipsoid, the radius used is the radius of the conformal * sphere at centerLat. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1026/Mercator-Spherical.html"> * EPSG:1026</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude . Usually 0 * @param centerLong See \ref center_longitude . Usually 0 * @param falseEasting See \ref false_easting . Usually 0 * @param falseNorthing See \ref false_northing . Usually 0 * @return a new Conversion. * @since 9.3 */ ConversionNNPtr Conversion::createMercatorSpherical( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_MERCATOR_SPHERICAL, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/moll.html"> * Mollweide</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createMollweide( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_MOLLWEIDE, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/nzmg.html"> * New Zealand Map Grid</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9811/index.html"> * EPSG:9811</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createNewZealandMappingGrid( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_NZMG, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/sterea.html"> * Oblique Stereographic (alternative)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9809/index.html"> * EPSG:9809</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createObliqueStereographic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_OBLIQUE_STEREOGRAPHIC, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/ortho.html"> * Orthographic</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9840/index.html"> * EPSG:9840</a>. * * \note Before PROJ 7.2, only the spherical formulation was implemented. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createOrthographic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_ORTHOGRAPHIC, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/poly.html"> * American Polyconic</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9818/index.html"> * EPSG:9818</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createAmericanPolyconic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, EPSG_CODE_METHOD_AMERICAN_POLYCONIC, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/stere.html"> * Polar Stereographic (Variant A)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9810/index.html"> * EPSG:9810</a>. * * This is the variant of polar stereographic defined with a scale factor. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude . Should be 90 deg ou -90 deg. * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createPolarStereographicVariantA( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/stere.html"> * Polar Stereographic (Variant B)</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9829/index.html"> * EPSG:9829</a>. * * This is the variant of polar stereographic defined with a latitude of * standard parallel. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeStandardParallel See \ref latitude_std_parallel * @param longitudeOfOrigin See \ref longitude_of_origin * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createPolarStereographicVariantB( const util::PropertyMap &properties, const common::Angle &latitudeStandardParallel, const common::Angle &longitudeOfOrigin, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, createParams(latitudeStandardParallel, longitudeOfOrigin, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/robin.html"> * Robinson</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createRobinson( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_ROBINSON, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/sinu.html"> * Sinusoidal</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createSinusoidal( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_SINUSOIDAL, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/stere.html"> * Stereographic</a> projection method. * * There is no equivalent in EPSG. This method implements the original "Oblique * Stereographic" method described in "Snyder's Map Projections - A Working *manual", * which is different from the "Oblique Stereographic (alternative)" method * implemented in createObliqueStereographic(). * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param scale See \ref scale * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createStereographic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC, createParams(centerLat, centerLong, scale, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/vandg.html"> * Van der Grinten</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createVanDerGrinten( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_VAN_DER_GRINTEN, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/wag1.html"> * Wagner I</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createWagnerI(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_WAGNER_I, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/wag2.html"> * Wagner II</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createWagnerII( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_WAGNER_II, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/wag3.html"> * Wagner III</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param latitudeTrueScale Latitude of true scale. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createWagnerIII( const util::PropertyMap &properties, const common::Angle &latitudeTrueScale, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_WAGNER_III, createParams(latitudeTrueScale, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/wag4.html"> * Wagner IV</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createWagnerIV( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_WAGNER_IV, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/wag5.html"> * Wagner V</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createWagnerV(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_WAGNER_V, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/wag6.html"> * Wagner VI</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createWagnerVI( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_WAGNER_VI, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/wag7.html"> * Wagner VII</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createWagnerVII( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, PROJ_WKT2_NAME_METHOD_WAGNER_VII, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/qsc.html"> * Quadrilateralized Spherical Cube</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLat See \ref center_latitude * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createQuadrilateralizedSphericalCube( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create( properties, PROJ_WKT2_NAME_METHOD_QUADRILATERALIZED_SPHERICAL_CUBE, createParams(centerLat, centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/sch.html"> * Spherical Cross-Track Height</a> projection method. * * There is no equivalent in EPSG. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param pegPointLat Peg point latitude. * @param pegPointLong Peg point longitude. * @param pegPointHeading Peg point heading. * @param pegPointHeight Peg point height. * @return a new Conversion. */ ConversionNNPtr Conversion::createSphericalCrossTrackHeight( const util::PropertyMap &properties, const common::Angle &pegPointLat, const common::Angle &pegPointLong, const common::Angle &pegPointHeading, const common::Length &pegPointHeight) { return create(properties, PROJ_WKT2_NAME_METHOD_SPHERICAL_CROSS_TRACK_HEIGHT, createParams(pegPointLat, pegPointLong, pegPointHeading, pegPointHeight)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/eqearth.html"> * Equal Earth</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1078/Equal-Earth.html"> * EPSG:1078</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param centerLong See \ref center_longitude * @param falseEasting See \ref false_easting * @param falseNorthing See \ref false_northing * @return a new Conversion. */ ConversionNNPtr Conversion::createEqualEarth( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_EQUAL_EARTH, createParams(centerLong, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the * <a href="../../../operations/projections/nsper.html"> * Vertical Perspective</a> projection method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9838/index.html"> * EPSG:9838</a>. * * The PROJ implementation of the EPSG Vertical Perspective has the current * limitations with respect to the method described in EPSG: * <ul> * <li> it is a 2D-only method, ignoring the ellipsoidal height of the point to * project.</li> * <li> it has only a spherical development.</li> * <li> the height of the topocentric origin is ignored, and thus assumed to be * 0.</li> * </ul> * * For completeness, PROJ adds the falseEasting and falseNorthing parameter, * which are not described in EPSG. They should usually be set to 0. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param topoOriginLat Latitude of topocentric origin * @param topoOriginLong Longitude of topocentric origin * @param topoOriginHeight Ellipsoidal height of topocentric origin. Ignored by * PROJ (that is assumed to be 0) * @param viewPointHeight Viewpoint height with respect to the * topocentric/mapping plane. In the case where topoOriginHeight = 0, this is * the height above the ellipsoid surface at topoOriginLat, topoOriginLong. * @param falseEasting See \ref false_easting . (not in EPSG) * @param falseNorthing See \ref false_northing . (not in EPSG) * @return a new Conversion. * * @since 6.3 */ ConversionNNPtr Conversion::createVerticalPerspective( const util::PropertyMap &properties, const common::Angle &topoOriginLat, const common::Angle &topoOriginLong, const common::Length &topoOriginHeight, const common::Length &viewPointHeight, const common::Length &falseEasting, const common::Length &falseNorthing) { return create(properties, EPSG_CODE_METHOD_VERTICAL_PERSPECTIVE, createParams(topoOriginLat, topoOriginLong, topoOriginHeight, viewPointHeight, falseEasting, falseNorthing)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Pole Rotation method, using * the conventions of the GRIB 1 and GRIB 2 data formats. * * Those are mentioned in the Note 2 of * https://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_doc/grib2_temp3-1.shtml * * Several conventions for the pole rotation method exists. * The parameters provided in this method are remapped to the PROJ ob_tran * operation with: * <pre> * +proj=ob_tran +o_proj=longlat +o_lon_p=-rotationAngle * +o_lat_p=-southPoleLatInUnrotatedCRS * +lon_0=southPoleLongInUnrotatedCRS * </pre> * * Another implementation of that convention is also in the netcdf-java library: * https://github.com/Unidata/netcdf-java/blob/3ce72c0cd167609ed8c69152bb4a004d1daa9273/cdm/core/src/main/java/ucar/unidata/geoloc/projection/RotatedLatLon.java * * The PROJ implementation of this method assumes a spherical ellipsoid. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param southPoleLatInUnrotatedCRS Latitude of the point from the unrotated * CRS, expressed in the unrotated CRS, that will become the south pole of the * rotated CRS. * @param southPoleLongInUnrotatedCRS Longitude of the point from the unrotated * CRS, expressed in the unrotated CRS, that will become the south pole of the * rotated CRS. * @param axisRotation The angle of rotation about the new polar * axis (measured clockwise when looking from the southern to the northern pole) * of the coordinate system, assuming the new axis to have been obtained by * first rotating the sphere through southPoleLongInUnrotatedCRS degrees about * the geographic polar axis and then rotating through * (90 + southPoleLatInUnrotatedCRS) degrees so that the southern pole moved * along the (previously rotated) Greenwich meridian. * @return a new Conversion. * * @since 7.0 */ ConversionNNPtr Conversion::createPoleRotationGRIBConvention( const util::PropertyMap &properties, const common::Angle &southPoleLatInUnrotatedCRS, const common::Angle &southPoleLongInUnrotatedCRS, const common::Angle &axisRotation) { return create(properties, PROJ_WKT2_NAME_METHOD_POLE_ROTATION_GRIB_CONVENTION, createParams(southPoleLatInUnrotatedCRS, southPoleLongInUnrotatedCRS, axisRotation)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Pole Rotation method, using * the conventions of the netCDF CF convention for the netCDF format. * * Those are mentioned in the Note 2 of * https://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#_rotated_pole * * Several conventions for the pole rotation method exists. * The parameters provided in this method are remapped to the PROJ ob_tran * operation with: * <pre> * +proj=ob_tran +o_proj=longlat +o_lon_p=northPoleGridLongitude * +o_lat_p=gridNorthPoleLatitude * +lon_0=180+gridNorthPoleLongitude * </pre> * * Another implementation of that convention is also in the netcdf-java library: * https://github.com/Unidata/netcdf-java/blob/3ce72c0cd167609ed8c69152bb4a004d1daa9273/cdm/core/src/main/java/ucar/unidata/geoloc/projection/RotatedPole.java * * The PROJ implementation of this method assumes a spherical ellipsoid. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param gridNorthPoleLatitude True latitude of the north pole of the rotated * grid * @param gridNorthPoleLongitude True longitude of the north pole of the rotated * grid. * @param northPoleGridLongitude Longitude of the true north pole in the rotated * grid. * @return a new Conversion. * * @since 8.2 */ ConversionNNPtr Conversion::createPoleRotationNetCDFCFConvention( const util::PropertyMap &properties, const common::Angle &gridNorthPoleLatitude, const common::Angle &gridNorthPoleLongitude, const common::Angle &northPoleGridLongitude) { return create(properties, PROJ_WKT2_NAME_METHOD_POLE_ROTATION_NETCDF_CF_CONVENTION, createParams(gridNorthPoleLatitude, gridNorthPoleLongitude, northPoleGridLongitude)); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Change of Vertical Unit * method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1069/index.html"> * EPSG:1069</a> [DEPRECATED]. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @param factor Conversion factor * @return a new Conversion. */ ConversionNNPtr Conversion::createChangeVerticalUnit(const util::PropertyMap &properties, const common::Scale &factor) { return create( properties, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT), VectorOfParameters{ createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR), }, VectorOfValues{ factor, }); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Change of Vertical Unit * method (without explicit conversion factor) * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1104/index.html"> * EPSG:1104</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @return a new Conversion. */ ConversionNNPtr Conversion::createChangeVerticalUnit(const util::PropertyMap &properties) { return create(properties, createMethodMapNameEPSGCode( EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR), VectorOfParameters{}, VectorOfValues{}); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Height Depth Reversal * method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_1068/index.html"> * EPSG:1068</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @return a new Conversion. * @since 6.3 */ ConversionNNPtr Conversion::createHeightDepthReversal(const util::PropertyMap &properties) { return create( properties, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL), {}, {}); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Axis order reversal method * * This swaps the longitude, latitude axis. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9843/index.html"> * EPSG:9843</a> for 2D or * <a href="https://epsg.org/coord-operation-method_9844/index.html"> * EPSG:9844</a> for Geographic3D horizontal. * * @param is3D Whether this should apply on 3D geographicCRS * @return a new Conversion. */ ConversionNNPtr Conversion::createAxisOrderReversal(bool is3D) { if (is3D) { return create(createMapNameEPSGCode(AXIS_ORDER_CHANGE_3D_NAME, 15499), createMethodMapNameEPSGCode( EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_3D), {}, {}); } return create( createMapNameEPSGCode(AXIS_ORDER_CHANGE_2D_NAME, 15498), createMethodMapNameEPSGCode(EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_2D), {}, {}); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion based on the Geographic/Geocentric method. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9602/index.html"> * EPSG:9602</a>. * * @param properties See \ref general_properties of the conversion. If the name * is not provided, it is automatically set. * @return a new Conversion. */ ConversionNNPtr Conversion::createGeographicGeocentric(const util::PropertyMap &properties) { return create( properties, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_GEOGRAPHIC_GEOCENTRIC), {}, {}); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress ConversionNNPtr Conversion::createGeographicGeocentric(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS) { auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, buildOpName("Conversion", sourceCRS, targetCRS)); auto conv = createGeographicGeocentric(properties); conv->setCRSs(sourceCRS, targetCRS, nullptr); return conv; } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion between a GeographicCRS and a spherical * planetocentric GeodeticCRS * * This method peforms conversion between geodetic latitude and geocentric * latitude * * @return a new Conversion. */ ConversionNNPtr Conversion::createGeographicGeocentricLatitude(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS) { auto properties = util::PropertyMap().set( common::IdentifiedObject::NAME_KEY, buildOpName("Conversion", sourceCRS, targetCRS)); auto conv = create( properties, PROJ_WKT2_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC_LATITUDE, {}); conv->setCRSs(sourceCRS, targetCRS, nullptr); return conv; } // --------------------------------------------------------------------------- InverseConversion::InverseConversion(const ConversionNNPtr &forward) : Conversion( OperationMethod::create(createPropertiesForInverse(forward->method()), forward->method()->parameters()), forward->parameterValues()), InverseCoordinateOperation(forward, true) { setPropertiesFromForward(); } // --------------------------------------------------------------------------- InverseConversion::~InverseConversion() = default; // --------------------------------------------------------------------------- ConversionNNPtr InverseConversion::inverseAsConversion() const { return NN_NO_CHECK( util::nn_dynamic_pointer_cast<Conversion>(forwardOperation_)); } // --------------------------------------------------------------------------- CoordinateOperationNNPtr InverseConversion::create(const ConversionNNPtr &forward) { auto conv = util::nn_make_shared<InverseConversion>(forward); conv->assignSelf(conv); return conv; } // --------------------------------------------------------------------------- CoordinateOperationNNPtr InverseConversion::_shallowClone() const { auto op = InverseConversion::nn_make_shared<InverseConversion>( inverseAsConversion()->shallowClone()); op->assignSelf(op); op->setCRSs(this, false); return util::nn_static_pointer_cast<CoordinateOperation>(op); } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool isAxisOrderReversal2D(int methodEPSGCode) { return methodEPSGCode == EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_2D; } static bool isAxisOrderReversal3D(int methodEPSGCode) { return methodEPSGCode == EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_3D; } bool isAxisOrderReversal(int methodEPSGCode) { return isAxisOrderReversal2D(methodEPSGCode) || isAxisOrderReversal3D(methodEPSGCode); } //! @endcond // --------------------------------------------------------------------------- CoordinateOperationNNPtr Conversion::inverse() const { const int methodEPSGCode = method()->getEPSGCode(); if (methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT) { const double convFactor = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR); if (convFactor == 0) { throw InvalidOperation("Invalid conversion factor"); } auto conv = createChangeVerticalUnit( createPropertiesForInverse(this, false, false), common::Scale(1.0 / convFactor)); conv->setCRSs(this, true); return conv; } if (methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR) { auto conv = createChangeVerticalUnit( createPropertiesForInverse(this, false, false)); conv->setCRSs(this, true); return conv; } const bool l_isAxisOrderReversal2D = isAxisOrderReversal2D(methodEPSGCode); const bool l_isAxisOrderReversal3D = isAxisOrderReversal3D(methodEPSGCode); if (l_isAxisOrderReversal2D || l_isAxisOrderReversal3D) { auto conv = createAxisOrderReversal(l_isAxisOrderReversal3D); conv->setCRSs(this, true); return conv; } if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC_GEOCENTRIC) { auto conv = createGeographicGeocentric( createPropertiesForInverse(this, false, false)); conv->setCRSs(this, true); return conv; } if (methodEPSGCode == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { auto conv = createHeightDepthReversal( createPropertiesForInverse(this, false, false)); conv->setCRSs(this, true); return conv; } if (method()->nameStr() == PROJ_WKT2_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC_LATITUDE) { auto conv = create(createPropertiesForInverse(this, false, false), PROJ_WKT2_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC_LATITUDE, {}); conv->setCRSs(this, true); return conv; } return InverseConversion::create(NN_NO_CHECK( util::nn_dynamic_pointer_cast<Conversion>(shared_from_this()))); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static double msfn(double phi, double e2) { const double sinphi = std::sin(phi); const double cosphi = std::cos(phi); return pj_msfn(sinphi, cosphi, e2); } // --------------------------------------------------------------------------- static double tsfn(double phi, double ec) { const double sinphi = std::sin(phi); return pj_tsfn(phi, sinphi, ec); } // --------------------------------------------------------------------------- // Function whose zeroes are the sin of the standard parallels of LCC_2SP static double lcc_1sp_to_2sp_f(double sinphi, double K, double ec, double n) { const double x = sinphi; const double ecx = ec * x; return (1 - x * x) / (1 - ecx * ecx) - K * K * std::pow((1.0 - x) / (1.0 + x) * std::pow((1.0 + ecx) / (1.0 - ecx), ec), n); } // --------------------------------------------------------------------------- // Find the sin of the standard parallels of LCC_2SP static double find_zero_lcc_1sp_to_2sp_f(double sinphi0, bool bNorth, double K, double ec) { double a, b; double f_a; if (bNorth) { // Look for zero above phi0 a = sinphi0; b = 1.0; // sin(North pole) f_a = 1.0; // some positive value, but we only care about the sign } else { // Look for zero below phi0 a = -1.0; // sin(South pole) b = sinphi0; f_a = -1.0; // minus infinity in fact, but we only care about the sign } // We use dichotomy search. lcc_1sp_to_2sp_f() is positive at sinphi_init, // has a zero in ]-1,sinphi0[ and ]sinphi0,1[ ranges for (int N = 0; N < 100; N++) { double c = (a + b) / 2; double f_c = lcc_1sp_to_2sp_f(c, K, ec, sinphi0); if (f_c == 0.0 || (b - a) < 1e-18) { return c; } if ((f_c > 0 && f_a > 0) || (f_c < 0 && f_a < 0)) { a = c; f_a = f_c; } else { b = c; } } return (a + b) / 2; } static inline double DegToRad(double x) { return x / 180.0 * M_PI; } static inline double RadToDeg(double x) { return x / M_PI * 180.0; } //! @endcond // --------------------------------------------------------------------------- /** * \brief Return an equivalent projection. * * Currently implemented: * <ul> * <li>EPSG_CODE_METHOD_MERCATOR_VARIANT_A (1SP) to * EPSG_CODE_METHOD_MERCATOR_VARIANT_B (2SP)</li> * <li>EPSG_CODE_METHOD_MERCATOR_VARIANT_B (2SP) to * EPSG_CODE_METHOD_MERCATOR_VARIANT_A (1SP)</li> * <li>EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP to * EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP</li> * <li>EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP to * EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP</li> * </ul> * * @param targetEPSGCode EPSG code of the target method. * @return new conversion, or nullptr */ ConversionPtr Conversion::convertToOtherMethod(int targetEPSGCode) const { const int current_epsg_code = method()->getEPSGCode(); if (current_epsg_code == targetEPSGCode) { return util::nn_dynamic_pointer_cast<Conversion>(shared_from_this()); } auto geogCRS = dynamic_cast<crs::GeodeticCRS *>(sourceCRS().get()); if (!geogCRS) { return nullptr; } const double e2 = geogCRS->ellipsoid()->squaredEccentricity(); if (e2 < 0) { return nullptr; } if (current_epsg_code == EPSG_CODE_METHOD_MERCATOR_VARIANT_A && targetEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_B && parameterValueNumericAsSI( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN) == 0.0) { const double k0 = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN); if (!(k0 > 0 && k0 <= 1.0 + 1e-10)) return nullptr; const double dfStdP1Lat = (k0 >= 1.0) ? 0.0 : std::acos(std::sqrt((1.0 - e2) / ((1.0 / (k0 * k0)) - e2))); auto latitudeFirstParallel = common::Angle( common::Angle(dfStdP1Lat, common::UnitOfMeasure::RADIAN) .convertToUnit(common::UnitOfMeasure::DEGREE), common::UnitOfMeasure::DEGREE); auto conv = createMercatorVariantB( util::PropertyMap(), latitudeFirstParallel, common::Angle(parameterValueMeasure( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN)), common::Length( parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_EASTING)), common::Length( parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_NORTHING))); conv->setCRSs(this, false); return conv.as_nullable(); } if (current_epsg_code == EPSG_CODE_METHOD_MERCATOR_VARIANT_B && targetEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_A) { const double phi1 = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL); if (!(std::fabs(phi1) < M_PI / 2)) return nullptr; const double k0 = msfn(phi1, e2); auto conv = createMercatorVariantA( util::PropertyMap(), common::Angle(0.0, common::UnitOfMeasure::DEGREE), common::Angle(parameterValueMeasure( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN)), common::Scale(k0, common::UnitOfMeasure::SCALE_UNITY), common::Length( parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_EASTING)), common::Length( parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_NORTHING))); conv->setCRSs(this, false); return conv.as_nullable(); } if (current_epsg_code == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP && targetEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP) { // Notations m0, t0, n, m1, t1, F are those of the EPSG guidance // "1.3.1.1 Lambert Conic Conformal (2SP)" and // "1.3.1.2 Lambert Conic Conformal (1SP)" and // or Snyder pages 106-109 auto latitudeOfOrigin = common::Angle(parameterValueMeasure( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN)); const double phi0 = latitudeOfOrigin.getSIValue(); const double k0 = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN); if (!(std::fabs(phi0) < M_PI / 2)) return nullptr; if (!(k0 > 0 && k0 <= 1.0 + 1e-10)) return nullptr; const double ec = std::sqrt(e2); const double m0 = msfn(phi0, e2); const double t0 = tsfn(phi0, ec); const double n = sin(phi0); if (std::fabs(n) < 1e-10) return nullptr; if (fabs(k0 - 1.0) <= 1e-10) { auto conv = createLambertConicConformal_2SP( util::PropertyMap(), latitudeOfOrigin, common::Angle(parameterValueMeasure( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN)), latitudeOfOrigin, latitudeOfOrigin, common::Length( parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_EASTING)), common::Length( parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_NORTHING))); conv->setCRSs(this, false); return conv.as_nullable(); } else { const double K = k0 * m0 / std::pow(t0, n); const double phi1 = std::asin(find_zero_lcc_1sp_to_2sp_f(n, true, K, ec)); const double phi2 = std::asin(find_zero_lcc_1sp_to_2sp_f(n, false, K, ec)); double phi1Deg = RadToDeg(phi1); double phi2Deg = RadToDeg(phi2); // Try to round to hundreth of degree if very close to it if (std::fabs(phi1Deg * 1000 - std::floor(phi1Deg * 1000 + 0.5)) < 1e-8) phi1Deg = floor(phi1Deg * 1000 + 0.5) / 1000; if (std::fabs(phi2Deg * 1000 - std::floor(phi2Deg * 1000 + 0.5)) < 1e-8) phi2Deg = std::floor(phi2Deg * 1000 + 0.5) / 1000; // The following improvement is too turn the LCC1SP equivalent of // EPSG:2154 to the real LCC2SP // If the computed latitude of origin is close to .0 or .5 degrees // then check if rounding it to it will get a false northing // close to an integer const double FN = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_FALSE_NORTHING); const double latitudeOfOriginDeg = latitudeOfOrigin.convertToUnit(common::UnitOfMeasure::DEGREE); if (std::fabs(latitudeOfOriginDeg * 2 - std::floor(latitudeOfOriginDeg * 2 + 0.5)) < 0.2) { const double dfRoundedLatOfOrig = std::floor(latitudeOfOriginDeg * 2 + 0.5) / 2; const double m1 = msfn(phi1, e2); const double t1 = tsfn(phi1, ec); const double F = m1 / (n * std::pow(t1, n)); const double a = geogCRS->ellipsoid()->semiMajorAxis().getSIValue(); const double tRoundedLatOfOrig = tsfn(DegToRad(dfRoundedLatOfOrig), ec); const double FN_correction = a * F * (std::pow(tRoundedLatOfOrig, n) - std::pow(t0, n)); const double FN_corrected = FN - FN_correction; const double FN_corrected_rounded = std::floor(FN_corrected + 0.5); if (std::fabs(FN_corrected - FN_corrected_rounded) < 1e-8) { auto conv = createLambertConicConformal_2SP( util::PropertyMap(), common::Angle(dfRoundedLatOfOrig, common::UnitOfMeasure::DEGREE), common::Angle(parameterValueMeasure( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN)), common::Angle(phi1Deg, common::UnitOfMeasure::DEGREE), common::Angle(phi2Deg, common::UnitOfMeasure::DEGREE), common::Length(parameterValueMeasure( EPSG_CODE_PARAMETER_FALSE_EASTING)), common::Length(FN_corrected_rounded)); conv->setCRSs(this, false); return conv.as_nullable(); } } auto conv = createLambertConicConformal_2SP( util::PropertyMap(), latitudeOfOrigin, common::Angle(parameterValueMeasure( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN)), common::Angle(phi1Deg, common::UnitOfMeasure::DEGREE), common::Angle(phi2Deg, common::UnitOfMeasure::DEGREE), common::Length( parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_EASTING)), common::Length(FN)); conv->setCRSs(this, false); return conv.as_nullable(); } } if (current_epsg_code == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP && targetEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP) { // Notations m0, t0, m1, t1, m2, t2 n, F are those of the EPSG guidance // "1.3.1.1 Lambert Conic Conformal (2SP)" and // "1.3.1.2 Lambert Conic Conformal (1SP)" and // or Snyder pages 106-109 const double phiF = parameterValueMeasure(EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN) .getSIValue(); const double phi1 = parameterValueMeasure(EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL) .getSIValue(); const double phi2 = parameterValueMeasure(EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL) .getSIValue(); if (!(std::fabs(phiF) < M_PI / 2)) return nullptr; if (!(std::fabs(phi1) < M_PI / 2)) return nullptr; if (!(std::fabs(phi2) < M_PI / 2)) return nullptr; const double ec = std::sqrt(e2); const double m1 = msfn(phi1, e2); const double m2 = msfn(phi2, e2); const double t1 = tsfn(phi1, ec); const double t2 = tsfn(phi2, ec); const double n_denom = std::log(t1) - std::log(t2); const double n = (std::fabs(n_denom) < 1e-10) ? std::sin(phi1) : (std::log(m1) - std::log(m2)) / n_denom; if (std::fabs(n) < 1e-10) return nullptr; const double F = m1 / (n * std::pow(t1, n)); const double phi0 = std::asin(n); const double m0 = msfn(phi0, e2); const double t0 = tsfn(phi0, ec); const double F0 = m0 / (n * std::pow(t0, n)); const double k0 = F / F0; const double a = geogCRS->ellipsoid()->semiMajorAxis().getSIValue(); const double tF = tsfn(phiF, ec); const double FN_correction = a * F * (std::pow(tF, n) - std::pow(t0, n)); double phi0Deg = RadToDeg(phi0); // Try to round to thousandth of degree if very close to it if (std::fabs(phi0Deg * 1000 - std::floor(phi0Deg * 1000 + 0.5)) < 1e-8) phi0Deg = std::floor(phi0Deg * 1000 + 0.5) / 1000; auto conv = createLambertConicConformal_1SP( util::PropertyMap(), common::Angle(phi0Deg, common::UnitOfMeasure::DEGREE), common::Angle(parameterValueMeasure( EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN)), common::Scale(k0), common::Length(parameterValueMeasure( EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN)), common::Length( parameterValueNumericAsSI( EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN) + (std::fabs(FN_correction) > 1e-8 ? FN_correction : 0))); conv->setCRSs(this, false); return conv.as_nullable(); } return nullptr; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static const ESRIMethodMapping *getESRIMapping(const std::string &wkt2_name, int epsg_code) { size_t nEsriMappings = 0; const auto esriMappings = getEsriMappings(nEsriMappings); for (size_t i = 0; i < nEsriMappings; ++i) { const auto &mapping = esriMappings[i]; if ((epsg_code != 0 && mapping.epsg_code == epsg_code) || ci_equal(wkt2_name, mapping.wkt2_name)) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- static void getESRIMethodNameAndParams(const Conversion *conv, const std::string &methodName, int methodEPSGCode, const char *&esriMethodName, const ESRIParamMapping *&esriParams) { esriParams = nullptr; esriMethodName = nullptr; const auto *esriMapping = getESRIMapping(methodName, methodEPSGCode); const auto l_targetCRS = conv->targetCRS(); if (esriMapping) { esriParams = esriMapping->params; esriMethodName = esriMapping->esri_name; if (esriMapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL || esriMapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL) { if (l_targetCRS && ci_find(l_targetCRS->nameStr(), "Plate Carree") != std::string::npos && conv->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN) == 0.0) { esriParams = paramsESRI_Plate_Carree; esriMethodName = "Plate_Carree"; } else { esriParams = paramsESRI_Equidistant_Cylindrical; esriMethodName = "Equidistant_Cylindrical"; } } else if (esriMapping->epsg_code == EPSG_CODE_METHOD_TRANSVERSE_MERCATOR) { if (ci_find(conv->nameStr(), "Gauss Kruger") != std::string::npos || (l_targetCRS && (ci_find(l_targetCRS->nameStr(), "Gauss") != std::string::npos || ci_find(l_targetCRS->nameStr(), "GK_") != std::string::npos))) { esriParams = paramsESRI_Gauss_Kruger; esriMethodName = "Gauss_Kruger"; } else { esriParams = paramsESRI_Transverse_Mercator; esriMethodName = "Transverse_Mercator"; } } else if (esriMapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A) { if (std::abs( conv->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE) - conv->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID)) < 1e-15) { esriParams = paramsESRI_Hotine_Oblique_Mercator_Azimuth_Natural_Origin; esriMethodName = "Hotine_Oblique_Mercator_Azimuth_Natural_Origin"; } else { esriParams = paramsESRI_Rectified_Skew_Orthomorphic_Natural_Origin; esriMethodName = "Rectified_Skew_Orthomorphic_Natural_Origin"; } } else if (esriMapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B) { if (std::abs( conv->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE) - conv->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID)) < 1e-15) { esriParams = paramsESRI_Hotine_Oblique_Mercator_Azimuth_Center; esriMethodName = "Hotine_Oblique_Mercator_Azimuth_Center"; } else { esriParams = paramsESRI_Rectified_Skew_Orthomorphic_Center; esriMethodName = "Rectified_Skew_Orthomorphic_Center"; } } else if (esriMapping->epsg_code == EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A) { // Quite empiric, but looking at pe_list_projcs.csv, the only // CRS that use Polar_Stereographic_Variant_A are EPSG:5041 and 5042 if (l_targetCRS && // EPSG:5041 (l_targetCRS->nameStr() == "WGS 84 / UPS North (E,N)" || // EPSG:5042 l_targetCRS->nameStr() == "WGS 84 / UPS South (E,N)")) { esriMethodName = "Polar_Stereographic_Variant_A"; } else { esriMethodName = "Stereographic"; } } else if (esriMapping->epsg_code == EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B) { if (conv->parameterValueNumericAsSI( EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL) > 0) { esriMethodName = "Stereographic_North_Pole"; } else { esriMethodName = "Stereographic_South_Pole"; } } } } // --------------------------------------------------------------------------- const char *Conversion::getESRIMethodName() const { const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const auto methodEPSGCode = l_method->getEPSGCode(); const ESRIParamMapping *esriParams = nullptr; const char *esriMethodName = nullptr; getESRIMethodNameAndParams(this, methodName, methodEPSGCode, esriMethodName, esriParams); return esriMethodName; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress const char *Conversion::getWKT1GDALMethodName() const { const auto &l_method = method(); const auto methodEPSGCode = l_method->getEPSGCode(); if (methodEPSGCode == EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR) { return "Mercator_1SP"; } const MethodMapping *mapping = getMapping(l_method.get()); return mapping ? mapping->wkt1_name : nullptr; } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Conversion::_exportToWKT(io::WKTFormatter *formatter) const { const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const auto methodEPSGCode = l_method->getEPSGCode(); const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2 && formatter->useESRIDialect()) { if (methodEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_A) { auto eqConv = convertToOtherMethod(EPSG_CODE_METHOD_MERCATOR_VARIANT_B); if (eqConv) { eqConv->_exportToWKT(formatter); return; } } } if (isWKT2) { formatter->startNode(formatter->useDerivingConversion() ? io::WKTConstants::DERIVINGCONVERSION : io::WKTConstants::CONVERSION, !identifiers().empty()); formatter->addQuotedString(nameStr()); } else { formatter->enter(); formatter->pushOutputUnit(false); formatter->pushOutputId(false); } #ifdef DEBUG_CONVERSION_ID if (sourceCRS() && targetCRS()) { formatter->startNode("SOURCECRS_ID", false); sourceCRS()->formatID(formatter); formatter->endNode(); formatter->startNode("TARGETCRS_ID", false); targetCRS()->formatID(formatter); formatter->endNode(); } #endif bool bAlreadyWritten = false; if (!isWKT2 && formatter->useESRIDialect()) { const ESRIParamMapping *esriParams = nullptr; const char *esriMethodName = nullptr; getESRIMethodNameAndParams(this, methodName, methodEPSGCode, esriMethodName, esriParams); if (esriMethodName && esriParams) { formatter->startNode(io::WKTConstants::PROJECTION, false); formatter->addQuotedString(esriMethodName); formatter->endNode(); for (int i = 0; esriParams[i].esri_name != nullptr; i++) { const auto &esriParam = esriParams[i]; formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString(esriParam.esri_name); if (esriParam.wkt2_name) { const auto &pv = parameterValue(esriParam.wkt2_name, esriParam.epsg_code); if (pv && pv->type() == ParameterValue::Type::MEASURE) { const auto &v = pv->value(); // as we don't output the natural unit, output // to the registered linear / angular unit. const auto &unitType = v.unit().type(); if (unitType == common::UnitOfMeasure::Type::LINEAR) { formatter->add(v.convertToUnit( *(formatter->axisLinearUnit()))); } else if (unitType == common::UnitOfMeasure::Type::ANGULAR) { const auto &angUnit = *(formatter->axisAngularUnit()); double val = v.convertToUnit(angUnit); if (angUnit == common::UnitOfMeasure::DEGREE) { if (val > 180.0) { val -= 360.0; } else if (val < -180.0) { val += 360.0; } } formatter->add(val); } else { formatter->add(v.getSIValue()); } } else if (ci_find(esriParam.esri_name, "scale") != std::string::npos) { formatter->add(1.0); } else { formatter->add(0.0); } } else { formatter->add(esriParam.fixed_value); } formatter->endNode(); } bAlreadyWritten = true; } } else if (!isWKT2) { if (methodEPSGCode == EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR) { const double latitudeOrigin = parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, common::UnitOfMeasure::DEGREE); if (latitudeOrigin != 0) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN); } bAlreadyWritten = true; formatter->startNode(io::WKTConstants::PROJECTION, false); formatter->addQuotedString("Mercator_1SP"); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("central_meridian"); const double centralMeridian = parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, common::UnitOfMeasure::DEGREE); formatter->add(centralMeridian); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("scale_factor"); formatter->add(1.0); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("false_easting"); const double falseEasting = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_FALSE_EASTING); formatter->add(falseEasting); formatter->endNode(); formatter->startNode(io::WKTConstants::PARAMETER, false); formatter->addQuotedString("false_northing"); const double falseNorthing = parameterValueNumericAsSI(EPSG_CODE_PARAMETER_FALSE_NORTHING); formatter->add(falseNorthing); formatter->endNode(); } else if (starts_with(methodName, "PROJ ")) { bAlreadyWritten = true; formatter->startNode(io::WKTConstants::PROJECTION, false); formatter->addQuotedString("custom_proj4"); formatter->endNode(); } } if (!bAlreadyWritten) { l_method->_exportToWKT(formatter); const MethodMapping *mapping = !isWKT2 ? getMapping(l_method.get()) : nullptr; bool hasInterpolationCRSParameter = false; for (const auto &genOpParamvalue : parameterValues()) { const auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); const int paramEPSGCode = opParamvalue ? opParamvalue->parameter()->getEPSGCode() : 0; // EPSG has normally no Latitude of natural origin for Equidistant // Cylindrical but PROJ can handle it, so output the parameter if // not zero if ((methodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL || methodEPSGCode == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL)) { if (paramEPSGCode == EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN) { const auto &paramValue = opParamvalue->parameterValue(); if (paramValue->type() == ParameterValue::Type::MEASURE) { const auto &measure = paramValue->value(); if (measure.getSIValue() == 0) { continue; } } } } // Same for false easting / false northing for Vertical Perspective else if (methodEPSGCode == EPSG_CODE_METHOD_VERTICAL_PERSPECTIVE) { if (paramEPSGCode == EPSG_CODE_PARAMETER_FALSE_EASTING || paramEPSGCode == EPSG_CODE_PARAMETER_FALSE_NORTHING) { const auto &paramValue = opParamvalue->parameterValue(); if (paramValue->type() == ParameterValue::Type::MEASURE) { const auto &measure = paramValue->value(); if (measure.getSIValue() == 0) { continue; } } } } if (paramEPSGCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS || paramEPSGCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS) { hasInterpolationCRSParameter = true; } genOpParamvalue->_exportToWKT(formatter, mapping); } // If we have an interpolation CRS that has a EPSG code, then // we can export it as a PARAMETER[] const auto l_interpolationCRS = interpolationCRS(); if (!hasInterpolationCRSParameter && l_interpolationCRS) { const auto code = l_interpolationCRS->getEPSGCode(); if (code != 0) { createOperationParameterValueFromInterpolationCRS( methodEPSGCode, code) ->_exportToWKT(formatter, mapping); } } } if (isWKT2) { if (formatter->outputId()) { formatID(formatter); } formatter->endNode(); } else { formatter->popOutputUnit(); formatter->popOutputId(); formatter->leave(); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Conversion::_exportToJSON( io::JSONFormatter *formatter) const // throw(FormattingException) { auto writer = formatter->writer(); auto objectContext( formatter->MakeObjectContext("Conversion", !identifiers().empty())); writer->AddObjKey("name"); const auto &l_name = nameStr(); if (l_name.empty()) { writer->Add("unnamed"); } else { writer->Add(l_name); } writer->AddObjKey("method"); formatter->setOmitTypeInImmediateChild(); formatter->setAllowIDInImmediateChild(); const auto &l_method = method(); l_method->_exportToJSON(formatter); const auto &l_parameterValues = parameterValues(); const auto l_interpolationCRS = interpolationCRS(); if (!l_parameterValues.empty() || l_interpolationCRS) { writer->AddObjKey("parameters"); { bool hasInterpolationCRSParameter = false; auto parametersContext(writer->MakeArrayContext(false)); for (const auto &genOpParamvalue : l_parameterValues) { const auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); const int paramEPSGCode = opParamvalue ? opParamvalue->parameter()->getEPSGCode() : 0; if (paramEPSGCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS || paramEPSGCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS) { hasInterpolationCRSParameter = true; } formatter->setAllowIDInImmediateChild(); formatter->setOmitTypeInImmediateChild(); genOpParamvalue->_exportToJSON(formatter); } // If we have an interpolation CRS that has a EPSG code, then // we can export it as a parameter if (!hasInterpolationCRSParameter && l_interpolationCRS) { const auto methodEPSGCode = l_method->getEPSGCode(); const auto code = l_interpolationCRS->getEPSGCode(); if (code != 0) { formatter->setAllowIDInImmediateChild(); formatter->setOmitTypeInImmediateChild(); createOperationParameterValueFromInterpolationCRS( methodEPSGCode, code) ->_exportToJSON(formatter); } } } } if (formatter->outputId()) { formatID(formatter); } } //! @endcond // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress static bool createPROJ4WebMercator(const Conversion *conv, io::PROJStringFormatter *formatter) { const double centralMeridian = conv->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, common::UnitOfMeasure::DEGREE); const double falseEasting = conv->parameterValueNumericAsSI(EPSG_CODE_PARAMETER_FALSE_EASTING); const double falseNorthing = conv->parameterValueNumericAsSI(EPSG_CODE_PARAMETER_FALSE_NORTHING); auto sourceCRS = conv->sourceCRS(); auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()); if (!geogCRS) { return false; } std::string units("m"); auto targetCRS = conv->targetCRS(); auto targetProjCRS = dynamic_cast<const crs::ProjectedCRS *>(targetCRS.get()); if (targetProjCRS) { const auto &axisList = targetProjCRS->coordinateSystem()->axisList(); const auto &unit = axisList[0]->unit(); if (!unit._isEquivalentTo(common::UnitOfMeasure::METRE, util::IComparable::Criterion::EQUIVALENT)) { auto projUnit = unit.exportToPROJString(); if (!projUnit.empty()) { units = std::move(projUnit); } else { return false; } } } formatter->addStep("merc"); const double a = geogCRS->ellipsoid()->semiMajorAxis().getSIValue(); formatter->addParam("a", a); formatter->addParam("b", a); formatter->addParam("lat_ts", 0.0); formatter->addParam("lon_0", centralMeridian); formatter->addParam("x_0", falseEasting); formatter->addParam("y_0", falseNorthing); formatter->addParam("k", 1.0); formatter->addParam("units", units); formatter->addParam("nadgrids", "@null"); if (targetProjCRS && targetProjCRS->hasOver()) { formatter->addParam("over"); } formatter->addParam("wktext"); formatter->addParam("no_defs"); return true; } // --------------------------------------------------------------------------- static bool createPROJExtensionFromCustomProj(const Conversion *conv, io::PROJStringFormatter *formatter, bool forExtensionNode) { const auto &methodName = conv->method()->nameStr(); assert(starts_with(methodName, "PROJ ")); auto tokens = split(methodName, ' '); formatter->addStep(tokens[1]); if (forExtensionNode) { auto sourceCRS = conv->sourceCRS(); auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()); if (!geogCRS) { return false; } geogCRS->addDatumInfoToPROJString(formatter); } for (size_t i = 2; i < tokens.size(); i++) { auto kv = split(tokens[i], '='); if (kv.size() == 2) { formatter->addParam(kv[0], kv[1]); } else { formatter->addParam(tokens[i]); } } for (const auto &genOpParamvalue : conv->parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &paramValue = opParamvalue->parameterValue(); if (paramValue->type() == ParameterValue::Type::MEASURE) { const auto &measure = paramValue->value(); const auto unitType = measure.unit().type(); if (unitType == common::UnitOfMeasure::Type::LINEAR) { formatter->addParam(paramName, measure.getSIValue()); } else if (unitType == common::UnitOfMeasure::Type::ANGULAR) { formatter->addParam( paramName, measure.convertToUnit(common::UnitOfMeasure::DEGREE)); } else { formatter->addParam(paramName, measure.value()); } } } } if (forExtensionNode) { formatter->addParam("wktext"); formatter->addParam("no_defs"); } return true; } //! @endcond // --------------------------------------------------------------------------- bool Conversion::addWKTExtensionNode(io::WKTFormatter *formatter) const { const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2; if (!isWKT2) { const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const int methodEPSGCode = l_method->getEPSGCode(); if (l_method->getPrivate()->projMethodOverride_ == "tmerc approx" || l_method->getPrivate()->projMethodOverride_ == "utm approx") { auto projFormatter = io::PROJStringFormatter::create(); projFormatter->setCRSExport(true); projFormatter->setUseApproxTMerc(true); formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4"); _exportToPROJString(projFormatter.get()); projFormatter->addParam("no_defs"); formatter->addQuotedString(projFormatter->toString()); formatter->endNode(); return true; } else if (methodEPSGCode == EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR || nameStr() == "Popular Visualisation Mercator") { auto projFormatter = io::PROJStringFormatter::create(); projFormatter->setCRSExport(true); if (createPROJ4WebMercator(this, projFormatter.get())) { formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4"); formatter->addQuotedString(projFormatter->toString()); formatter->endNode(); return true; } } else if (starts_with(methodName, "PROJ ")) { auto projFormatter = io::PROJStringFormatter::create(); projFormatter->setCRSExport(true); if (createPROJExtensionFromCustomProj(this, projFormatter.get(), true)) { formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4"); formatter->addQuotedString(projFormatter->toString()); formatter->endNode(); return true; } } else if (methodName == PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X) { auto projFormatter = io::PROJStringFormatter::create(); projFormatter->setCRSExport(true); formatter->startNode(io::WKTConstants::EXTENSION, false); formatter->addQuotedString("PROJ4"); _exportToPROJString(projFormatter.get()); projFormatter->addParam("no_defs"); formatter->addQuotedString(projFormatter->toString()); formatter->endNode(); return true; } } return false; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress void Conversion::_exportToPROJString( io::PROJStringFormatter *formatter) const // throw(FormattingException) { const auto &l_method = method(); const auto &methodName = l_method->nameStr(); const int methodEPSGCode = l_method->getEPSGCode(); const bool isZUnitConversion = methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT || methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR; const bool isAffineParametric = methodEPSGCode == EPSG_CODE_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION; const bool isSimilarity = methodEPSGCode == EPSG_CODE_METHOD_SIMILARITY_TRANSFORMATION; const bool isGeographicGeocentric = methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC_GEOCENTRIC; const bool isGeographicOffsets = methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS || methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS || methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS; const bool isHeightDepthReversal = methodEPSGCode == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL; const bool applySourceCRSModifiers = !isZUnitConversion && !isAffineParametric && !isSimilarity && !isAxisOrderReversal(methodEPSGCode) && !isGeographicGeocentric && !isGeographicOffsets && !isHeightDepthReversal; bool applyTargetCRSModifiers = applySourceCRSModifiers; if (formatter->getCRSExport()) { if (methodEPSGCode == EPSG_CODE_METHOD_GEOCENTRIC_TOPOCENTRIC || methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC_TOPOCENTRIC) { throw io::FormattingException("Transformation cannot be exported " "as a PROJ.4 string (but can be part " "of a PROJ pipeline)"); } } auto l_sourceCRS = sourceCRS(); auto l_targetCRS = targetCRS(); if (methodName == PROJ_WKT2_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC_LATITUDE) { const auto extractGeodeticCRSIfGeodeticCRSOrEquivalent = [](const crs::CRSPtr &crs) { auto geodCRS = std::dynamic_pointer_cast<crs::GeodeticCRS>(crs); if (!geodCRS) { auto compoundCRS = std::dynamic_pointer_cast<crs::CompoundCRS>(crs); if (compoundCRS) { const auto &components = compoundCRS->componentReferenceSystems(); if (!components.empty()) { geodCRS = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( components[0]); if (!geodCRS) { auto boundCRS = util::nn_dynamic_pointer_cast< crs::BoundCRS>(components[0]); if (boundCRS) { geodCRS = util::nn_dynamic_pointer_cast< crs::GeodeticCRS>(boundCRS->baseCRS()); } } } } else { auto boundCRS = std::dynamic_pointer_cast<crs::BoundCRS>(crs); if (boundCRS) { geodCRS = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( boundCRS->baseCRS()); } } } return geodCRS; }; auto sourceCRSGeod = dynamic_cast<const crs::GeodeticCRS *>( extractGeodeticCRSIfGeodeticCRSOrEquivalent(l_sourceCRS).get()); auto targetCRSGeod = dynamic_cast<const crs::GeodeticCRS *>( extractGeodeticCRSIfGeodeticCRSOrEquivalent(l_targetCRS).get()); if (sourceCRSGeod && targetCRSGeod) { auto sourceCRSGeog = dynamic_cast<const crs::GeographicCRS *>(sourceCRSGeod); auto targetCRSGeog = dynamic_cast<const crs::GeographicCRS *>(targetCRSGeod); bool isSrcGeocentricLat = sourceCRSGeod->isSphericalPlanetocentric(); bool isSrcGeographic = sourceCRSGeog != nullptr; bool isTargetGeocentricLat = targetCRSGeod->isSphericalPlanetocentric(); bool isTargetGeographic = targetCRSGeog != nullptr; if ((isSrcGeocentricLat && isTargetGeographic) || (isSrcGeographic && isTargetGeocentricLat)) { formatter->setOmitProjLongLatIfPossible(true); formatter->startInversion(); sourceCRSGeod->_exportToPROJString(formatter); formatter->stopInversion(); targetCRSGeod->_exportToPROJString(formatter); formatter->setOmitProjLongLatIfPossible(false); return; } } throw io::FormattingException("Invalid nature of source and/or " "targetCRS for Geographic latitude / " "Geocentric latitude" "conversion"); } crs::GeographicCRSPtr srcGeogCRS; if (!formatter->getCRSExport() && l_sourceCRS && applySourceCRSModifiers) { crs::CRSPtr horiz = l_sourceCRS; const auto compound = dynamic_cast<const crs::CompoundCRS *>(l_sourceCRS.get()); if (compound) { const auto &components = compound->componentReferenceSystems(); if (!components.empty()) { horiz = components.front().as_nullable(); const auto boundCRS = dynamic_cast<const crs::BoundCRS *>(horiz.get()); if (boundCRS) { horiz = boundCRS->baseCRS().as_nullable(); } } } auto srcGeodCRS = dynamic_cast<const crs::GeodeticCRS *>(horiz.get()); if (srcGeodCRS) { srcGeogCRS = std::dynamic_pointer_cast<crs::GeographicCRS>(horiz); } if (srcGeodCRS && (srcGeogCRS || srcGeodCRS->isSphericalPlanetocentric())) { formatter->setOmitProjLongLatIfPossible(true); formatter->startInversion(); srcGeodCRS->_exportToPROJString(formatter); formatter->stopInversion(); formatter->setOmitProjLongLatIfPossible(false); } auto projCRS = dynamic_cast<const crs::ProjectedCRS *>(horiz.get()); if (projCRS) { formatter->startInversion(); formatter->pushOmitZUnitConversion(); projCRS->addUnitConvertAndAxisSwap(formatter, false); formatter->popOmitZUnitConversion(); formatter->stopInversion(); } } const auto &convName = nameStr(); bool bConversionDone = false; bool bEllipsoidParametersDone = false; bool useApprox = false; if (methodEPSGCode == EPSG_CODE_METHOD_TRANSVERSE_MERCATOR) { // Check for UTM int zone = 0; bool north = true; useApprox = formatter->getUseApproxTMerc() || l_method->getPrivate()->projMethodOverride_ == "tmerc approx" || l_method->getPrivate()->projMethodOverride_ == "utm approx"; if (isUTM(zone, north)) { bConversionDone = true; formatter->addStep("utm"); if (useApprox) { formatter->addParam("approx"); } formatter->addParam("zone", zone); if (!north) { formatter->addParam("south"); } } } else if (methodEPSGCode == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A) { const double azimuth = parameterValueNumeric(EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, common::UnitOfMeasure::DEGREE); const double angleRectifiedToSkewGrid = parameterValueNumeric( EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, common::UnitOfMeasure::DEGREE); // Map to Swiss Oblique Mercator / somerc if (std::fabs(azimuth - 90) < 1e-4 && std::fabs(angleRectifiedToSkewGrid - 90) < 1e-4) { bConversionDone = true; formatter->addStep("somerc"); formatter->addParam( "lat_0", parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, common::UnitOfMeasure::DEGREE)); formatter->addParam( "lon_0", parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, common::UnitOfMeasure::DEGREE)); formatter->addParam( "k_0", parameterValueNumericAsSI( EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE)); formatter->addParam("x_0", parameterValueNumericAsSI( EPSG_CODE_PARAMETER_FALSE_EASTING)); formatter->addParam("y_0", parameterValueNumericAsSI( EPSG_CODE_PARAMETER_FALSE_NORTHING)); } } else if (methodEPSGCode == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B) { const double azimuth = parameterValueNumeric(EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, common::UnitOfMeasure::DEGREE); const double angleRectifiedToSkewGrid = parameterValueNumeric( EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, common::UnitOfMeasure::DEGREE); // Map to Swiss Oblique Mercator / somerc if (std::fabs(azimuth - 90) < 1e-4 && std::fabs(angleRectifiedToSkewGrid - 90) < 1e-4) { bConversionDone = true; formatter->addStep("somerc"); formatter->addParam( "lat_0", parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, common::UnitOfMeasure::DEGREE)); formatter->addParam( "lon_0", parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, common::UnitOfMeasure::DEGREE)); formatter->addParam( "k_0", parameterValueNumericAsSI( EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE)); formatter->addParam( "x_0", parameterValueNumericAsSI( EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE)); formatter->addParam( "y_0", parameterValueNumericAsSI( EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE)); } } else if (methodEPSGCode == EPSG_CODE_METHOD_KROVAK_NORTH_ORIENTED || methodEPSGCode == EPSG_CODE_METHOD_KROVAK_MODIFIED_NORTH_ORIENTED) { double colatitude = parameterValueNumeric(EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS, common::UnitOfMeasure::DEGREE); double latitudePseudoStandardParallel = parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, common::UnitOfMeasure::DEGREE); // 30deg 17' 17.30311'' = 30.28813975277777776 // 30deg 17' 17.303'' = 30.288139722222223 as used in GDAL WKT1 if (std::fabs(colatitude - 30.2881397) > 1e-7) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_COLATITUDE_CONE_AXIS); } if (std::fabs(latitudePseudoStandardParallel - 78.5) > 1e-8) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL); } } else if (methodEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_A) { double latitudeOrigin = parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, common::UnitOfMeasure::DEGREE); if (latitudeOrigin != 0) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN); } } else if (methodEPSGCode == EPSG_CODE_METHOD_MERCATOR_VARIANT_B) { const auto &scaleFactor = parameterValueMeasure(WKT1_SCALE_FACTOR, 0); if (scaleFactor.unit().type() != common::UnitOfMeasure::Type::UNKNOWN && std::fabs(scaleFactor.getSIValue() - 1.0) > 1e-10) { throw io::FormattingException( "Unexpected presence of scale factor in Mercator (variant B)"); } double latitudeOrigin = parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, common::UnitOfMeasure::DEGREE); if (latitudeOrigin != 0) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN); } } else if (methodEPSGCode == EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED) { // We map TMSO to tmerc with axis=wsu. This only works if false easting // and northings are zero, which is the case in practice for South // African and Namibian EPSG CRS const auto falseEasting = parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_EASTING, common::UnitOfMeasure::METRE); if (falseEasting != 0) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_FALSE_EASTING); } const auto falseNorthing = parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_NORTHING, common::UnitOfMeasure::METRE); if (falseNorthing != 0) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_FALSE_NORTHING); } // PROJ.4 specific hack for webmercator } else if (formatter->getCRSExport() && methodEPSGCode == EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR) { if (!createPROJ4WebMercator(this, formatter)) { throw io::FormattingException( std::string("Cannot export ") + EPSG_NAME_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR + " as PROJ.4 string outside of a ProjectedCRS context"); } bConversionDone = true; bEllipsoidParametersDone = true; applyTargetCRSModifiers = false; } else if (ci_equal(convName, "Popular Visualisation Mercator")) { if (formatter->getCRSExport()) { if (!createPROJ4WebMercator(this, formatter)) { throw io::FormattingException(concat( "Cannot export ", convName, " as PROJ.4 string outside of a ProjectedCRS context")); } applyTargetCRSModifiers = false; } else { formatter->addStep("webmerc"); if (l_sourceCRS) { datum::Ellipsoid::WGS84->_exportToPROJString(formatter); } } bConversionDone = true; bEllipsoidParametersDone = true; } else if (starts_with(methodName, "PROJ ")) { bConversionDone = true; createPROJExtensionFromCustomProj(this, formatter, false); } else if (ci_equal(methodName, PROJ_WKT2_NAME_METHOD_POLE_ROTATION_GRIB_CONVENTION)) { double southPoleLat = parameterValueNumeric( PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LATITUDE_GRIB_CONVENTION, common::UnitOfMeasure::DEGREE); double southPoleLong = parameterValueNumeric( PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LONGITUDE_GRIB_CONVENTION, common::UnitOfMeasure::DEGREE); double rotation = parameterValueNumeric( PROJ_WKT2_NAME_PARAMETER_AXIS_ROTATION_GRIB_CONVENTION, common::UnitOfMeasure::DEGREE); formatter->addStep("ob_tran"); formatter->addParam("o_proj", "longlat"); formatter->addParam("o_lon_p", -rotation); formatter->addParam("o_lat_p", -southPoleLat); formatter->addParam("lon_0", southPoleLong); bConversionDone = true; } else if (ci_equal( methodName, PROJ_WKT2_NAME_METHOD_POLE_ROTATION_NETCDF_CF_CONVENTION)) { double gridNorthPoleLatitude = parameterValueNumeric( PROJ_WKT2_NAME_PARAMETER_GRID_NORTH_POLE_LATITUDE_NETCDF_CONVENTION, common::UnitOfMeasure::DEGREE); double gridNorthPoleLongitude = parameterValueNumeric( PROJ_WKT2_NAME_PARAMETER_GRID_NORTH_POLE_LONGITUDE_NETCDF_CONVENTION, common::UnitOfMeasure::DEGREE); double northPoleGridLongitude = parameterValueNumeric( PROJ_WKT2_NAME_PARAMETER_NORTH_POLE_GRID_LONGITUDE_NETCDF_CONVENTION, common::UnitOfMeasure::DEGREE); formatter->addStep("ob_tran"); formatter->addParam("o_proj", "longlat"); formatter->addParam("o_lon_p", northPoleGridLongitude); formatter->addParam("o_lat_p", gridNorthPoleLatitude); formatter->addParam("lon_0", 180 + gridNorthPoleLongitude); bConversionDone = true; } else if (ci_equal(methodName, "Adams_Square_II")) { // Look for ESRI method and parameter names (to be opposed // to the OGC WKT2 names we use elsewhere, because there's no mapping // of those parameters to OGC WKT2) // We also reject non-default values for a number of parameters, // because they are not implemented on PROJ side. The subset we // support can handle ESRI:54098 WGS_1984_Adams_Square_II, but not // ESRI:54099 WGS_1984_Spilhaus_Ocean_Map_in_Square const double falseEasting = parameterValueNumeric( "False_Easting", common::UnitOfMeasure::METRE); const double falseNorthing = parameterValueNumeric( "False_Northing", common::UnitOfMeasure::METRE); const double scaleFactor = parameterValue("Scale_Factor", 0) ? parameterValueNumeric("Scale_Factor", common::UnitOfMeasure::SCALE_UNITY) : 1.0; const double azimuth = parameterValueNumeric("Azimuth", common::UnitOfMeasure::DEGREE); const double longitudeOfCenter = parameterValueNumeric( "Longitude_Of_Center", common::UnitOfMeasure::DEGREE); const double latitudeOfCenter = parameterValueNumeric( "Latitude_Of_Center", common::UnitOfMeasure::DEGREE); const double XYPlaneRotation = parameterValueNumeric( "XY_Plane_Rotation", common::UnitOfMeasure::DEGREE); if (scaleFactor != 1.0 || azimuth != 0.0 || latitudeOfCenter != 0.0 || XYPlaneRotation != 0.0) { throw io::FormattingException("Unsupported value for one or " "several parameters of " "Adams_Square_II"); } formatter->addStep("adams_ws2"); formatter->addParam("lon_0", longitudeOfCenter); formatter->addParam("x_0", falseEasting); formatter->addParam("y_0", falseNorthing); bConversionDone = true; } else if (ci_equal(methodName, PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_SQUARE) || ci_equal(methodName, PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_DIAMOND)) { const auto &scaleFactor = parameterValueMeasure( EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN); if (scaleFactor.unit().type() != common::UnitOfMeasure::Type::UNKNOWN && std::fabs(scaleFactor.getSIValue() - 1.0) > 1e-10) { throw io::FormattingException( "Only scale factor = 1 handled for Peirce Quincuncial"); } const auto &latitudeOfOriginDeg = parameterValueMeasure( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN); if (latitudeOfOriginDeg.unit().type() != common::UnitOfMeasure::Type::UNKNOWN && std::fabs(parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, common::UnitOfMeasure::DEGREE) - 90.0) > 1e-10) { throw io::FormattingException("Only latitude of natural origin = " "90 handled for Peirce Quincuncial"); } } else if (formatter->convention() == io::PROJStringFormatter::Convention::PROJ_5 && isZUnitConversion) { double convFactor; if (methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT) { convFactor = parameterValueNumericAsSI( EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR); } else { assert(methodEPSGCode == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR); const auto vertSrcCRS = dynamic_cast<const crs::VerticalCRS *>(l_sourceCRS.get()); const auto vertTgtCRS = dynamic_cast<const crs::VerticalCRS *>(l_targetCRS.get()); if (vertSrcCRS && vertTgtCRS) { const double convSrc = vertSrcCRS->coordinateSystem() ->axisList()[0] ->unit() .conversionToSI(); const double convDst = vertTgtCRS->coordinateSystem() ->axisList()[0] ->unit() .conversionToSI(); convFactor = convSrc / convDst; } else { throw io::FormattingException( "Export of " "EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR " "conversion to a PROJ string " "requires an input and output vertical CRS"); } } exportToPROJStringChangeVerticalUnit(formatter, convFactor); bConversionDone = true; bEllipsoidParametersDone = true; } else if (methodEPSGCode == EPSG_CODE_METHOD_GEOGRAPHIC_TOPOCENTRIC) { if (!srcGeogCRS) { throw io::FormattingException( "Export of Geographic/Topocentric conversion to a PROJ string " "requires an input geographic CRS"); } formatter->addStep("cart"); srcGeogCRS->ellipsoid()->_exportToPROJString(formatter); formatter->addStep("topocentric"); const auto latOrigin = parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN, common::UnitOfMeasure::DEGREE); const auto longOrigin = parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN, common::UnitOfMeasure::DEGREE); const auto heightOrigin = parameterValueNumeric( EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, common::UnitOfMeasure::METRE); formatter->addParam("lat_0", latOrigin); formatter->addParam("lon_0", longOrigin); formatter->addParam("h_0", heightOrigin); bConversionDone = true; } bool bAxisSpecFound = false; if (!bConversionDone) { const MethodMapping *mapping = getMapping(l_method.get()); if (mapping && mapping->proj_name_main) { formatter->addStep(mapping->proj_name_main); if (useApprox) { formatter->addParam("approx"); } if (mapping->proj_name_aux) { bool addAux = true; if (internal::starts_with(mapping->proj_name_aux, "axis=")) { if (mapping->epsg_code == EPSG_CODE_METHOD_KROVAK || mapping->epsg_code == EPSG_CODE_METHOD_KROVAK_MODIFIED) { auto projCRS = dynamic_cast<const crs::ProjectedCRS *>( l_targetCRS.get()); if (projCRS) { const auto &axisList = projCRS->coordinateSystem()->axisList(); if (axisList[0]->direction() == cs::AxisDirection::WEST && axisList[1]->direction() == cs::AxisDirection::SOUTH) { formatter->addParam("czech"); addAux = false; } } } bAxisSpecFound = true; } // No need to add explicit f=0 or R_A if the ellipsoid is a // sphere if (strcmp(mapping->proj_name_aux, "f=0") == 0 || strcmp(mapping->proj_name_aux, "R_A") == 0) { crs::CRS *horiz = l_sourceCRS.get(); const auto compound = dynamic_cast<const crs::CompoundCRS *>(horiz); if (compound) { const auto &components = compound->componentReferenceSystems(); if (!components.empty()) { horiz = components.front().get(); const auto boundCRS = dynamic_cast<const crs::BoundCRS *>(horiz); if (boundCRS) { horiz = boundCRS->baseCRS().get(); } } } auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(horiz); if (geogCRS && geogCRS->ellipsoid()->isSphere()) { addAux = false; } } if (addAux) { auto kv = split(mapping->proj_name_aux, '='); if (kv.size() == 2) { formatter->addParam(kv[0], kv[1]); } else { formatter->addParam(mapping->proj_name_aux); } } } if (mapping->epsg_code == EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B) { double latitudeStdParallel = parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL, common::UnitOfMeasure::DEGREE); formatter->addParam("lat_0", (latitudeStdParallel >= 0) ? 90.0 : -90.0); } for (int i = 0; mapping->params[i] != nullptr; i++) { const auto *param = mapping->params[i]; if (!param->proj_name) { continue; } const auto &value = parameterValueMeasure(param->wkt2_name, param->epsg_code); double valueConverted = 0; if (value == nullMeasure) { // Deal with missing values. In an ideal world, this would // not happen if (param->epsg_code == EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN) { valueConverted = 1.0; } if ((mapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A || mapping->epsg_code == EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B) && param->epsg_code == EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID) { // Do not use 0 as the default value for +gamma of // proj=omerc continue; } } else if (param->unit_type == common::UnitOfMeasure::Type::ANGULAR) { valueConverted = value.convertToUnit(common::UnitOfMeasure::DEGREE); } else { valueConverted = value.getSIValue(); } if (mapping->epsg_code == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP && strcmp(param->proj_name, "lat_1") == 0) { formatter->addParam(param->proj_name, valueConverted); formatter->addParam("lat_0", valueConverted); } else { formatter->addParam(param->proj_name, valueConverted); } } } else { if (!exportToPROJStringGeneric(formatter)) { throw io::FormattingException( concat("Unsupported conversion method: ", methodName)); } } } if (l_targetCRS && applyTargetCRSModifiers) { crs::CRS *horiz = l_targetCRS.get(); const auto compound = dynamic_cast<const crs::CompoundCRS *>(horiz); if (compound) { const auto &components = compound->componentReferenceSystems(); if (!components.empty()) { horiz = components.front().get(); } } auto derivedProjCRS = dynamic_cast<const crs::DerivedProjectedCRS *>(horiz); // horiz != nullptr: only to make clang static analyzer happy if (!bEllipsoidParametersDone && horiz != nullptr && derivedProjCRS == nullptr) { auto targetGeodCRS = horiz->extractGeodeticCRS(); auto targetGeogCRS = std::dynamic_pointer_cast<crs::GeographicCRS>(targetGeodCRS); if (targetGeogCRS) { if (formatter->getCRSExport()) { targetGeogCRS->addDatumInfoToPROJString(formatter); } else { targetGeogCRS->ellipsoid()->_exportToPROJString(formatter); targetGeogCRS->primeMeridian()->_exportToPROJString( formatter); } } else if (targetGeodCRS) { targetGeodCRS->ellipsoid()->_exportToPROJString(formatter); } } auto projCRS = dynamic_cast<const crs::ProjectedCRS *>(horiz); if (projCRS == nullptr) { auto boundCRS = dynamic_cast<const crs::BoundCRS *>(horiz); if (boundCRS) { projCRS = dynamic_cast<const crs::ProjectedCRS *>( boundCRS->baseCRS().get()); } } if (projCRS) { formatter->pushOmitZUnitConversion(); projCRS->addUnitConvertAndAxisSwap(formatter, bAxisSpecFound); formatter->popOmitZUnitConversion(); if (projCRS->hasOver()) { formatter->addParam("over"); } } else { if (derivedProjCRS) { formatter->pushOmitZUnitConversion(); derivedProjCRS->addUnitConvertAndAxisSwap(formatter); formatter->popOmitZUnitConversion(); } } auto derivedGeographicCRS = dynamic_cast<const crs::DerivedGeographicCRS *>(horiz); if (!formatter->getCRSExport() && derivedGeographicCRS) { formatter->setOmitProjLongLatIfPossible(true); derivedGeographicCRS->addAngularUnitConvertAndAxisSwap(formatter); formatter->setOmitProjLongLatIfPossible(false); } } } //! @endcond // --------------------------------------------------------------------------- /** \brief Return whether a conversion is a * <a href="../../../operations/projections/utm.html"> * Universal Transverse Mercator</a> conversion. * * @param[out] zone UTM zone number between 1 and 60. * @param[out] north true for UTM northern hemisphere, false for UTM southern * hemisphere. * @return true if it is a UTM conversion. */ bool Conversion::isUTM(int &zone, bool &north) const { zone = 0; north = true; if (method()->getEPSGCode() == EPSG_CODE_METHOD_TRANSVERSE_MERCATOR) { // Check for UTM bool bLatitudeNatOriginUTM = false; bool bScaleFactorUTM = false; bool bFalseEastingUTM = false; bool bFalseNorthingUTM = false; for (const auto &genOpParamvalue : parameterValues()) { auto opParamvalue = dynamic_cast<const OperationParameterValue *>( genOpParamvalue.get()); if (opParamvalue) { const auto epsg_code = opParamvalue->parameter()->getEPSGCode(); const auto &l_parameterValue = opParamvalue->parameterValue(); if (l_parameterValue->type() == ParameterValue::Type::MEASURE) { const auto &measure = l_parameterValue->value(); if (epsg_code == EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN && std::fabs(measure.value() - UTM_LATITUDE_OF_NATURAL_ORIGIN) < 1e-10) { bLatitudeNatOriginUTM = true; } else if ( (epsg_code == EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN || epsg_code == EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN) && measure.unit()._isEquivalentTo( common::UnitOfMeasure::DEGREE, util::IComparable::Criterion::EQUIVALENT)) { double dfZone = (measure.value() + 183.0) / 6.0; if (dfZone > 0.9 && dfZone < 60.1 && std::abs(dfZone - std::round(dfZone)) < 1e-10) { zone = static_cast<int>(std::lround(dfZone)); } } else if ( epsg_code == EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN && measure.unit()._isEquivalentTo( common::UnitOfMeasure::SCALE_UNITY, util::IComparable::Criterion::EQUIVALENT) && std::fabs(measure.value() - UTM_SCALE_FACTOR) < 1e-10) { bScaleFactorUTM = true; } else if (epsg_code == EPSG_CODE_PARAMETER_FALSE_EASTING && measure.value() == UTM_FALSE_EASTING && measure.unit()._isEquivalentTo( common::UnitOfMeasure::METRE, util::IComparable::Criterion::EQUIVALENT)) { bFalseEastingUTM = true; } else if (epsg_code == EPSG_CODE_PARAMETER_FALSE_NORTHING && measure.unit()._isEquivalentTo( common::UnitOfMeasure::METRE, util::IComparable::Criterion::EQUIVALENT)) { if (std::fabs(measure.value() - UTM_NORTH_FALSE_NORTHING) < 1e-10) { bFalseNorthingUTM = true; north = true; } else if (std::fabs(measure.value() - UTM_SOUTH_FALSE_NORTHING) < 1e-10) { bFalseNorthingUTM = true; north = false; } } } } } if (bLatitudeNatOriginUTM && zone > 0 && bScaleFactorUTM && bFalseEastingUTM && bFalseNorthingUTM) { return true; } } return false; } // --------------------------------------------------------------------------- /** \brief Return a Conversion object where some parameters are better * identified. * * @return a new Conversion. */ ConversionNNPtr Conversion::identify() const { auto newConversion = Conversion::nn_make_shared<Conversion>(*this); newConversion->assignSelf(newConversion); if (method()->getEPSGCode() == EPSG_CODE_METHOD_TRANSVERSE_MERCATOR) { // Check for UTM int zone = 0; bool north = true; if (isUTM(zone, north)) { newConversion->setProperties( getUTMConversionProperty(util::PropertyMap(), zone, north)); } } return newConversion; } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion with method Geographic 2D offsets * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9619/index.html"> * EPSG:9619</a>. * * @param properties See \ref general_properties of the conversion. * At minimum the name should be defined. * @param offsetLat Latitude offset to add. * @param offsetLong Longitude offset to add. * @return new conversion. */ ConversionNNPtr Conversion::createGeographic2DOffsets(const util::PropertyMap &properties, const common::Angle &offsetLat, const common::Angle &offsetLong) { return create( properties, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LATITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET)}, VectorOfValues{offsetLat, offsetLong}); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion with method Geographic 3D offsets * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9660/index.html"> * EPSG:9660</a>. * * @param properties See \ref general_properties of the Conversion. * At minimum the name should be defined. * @param offsetLat Latitude offset to add. * @param offsetLong Longitude offset to add. * @param offsetHeight Height offset to add. * @return new Conversion. */ ConversionNNPtr Conversion::createGeographic3DOffsets( const util::PropertyMap &properties, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight) { return create( properties, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LATITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_VERTICAL_OFFSET)}, VectorOfValues{offsetLat, offsetLong, offsetHeight}); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion with method Geographic 2D with * height * offsets * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9618/index.html"> * EPSG:9618</a>. * * @param properties See \ref general_properties of the Conversion. * At minimum the name should be defined. * @param offsetLat Latitude offset to add. * @param offsetLong Longitude offset to add. * @param offsetHeight Geoid undulation to add. * @return new Conversion. */ ConversionNNPtr Conversion::createGeographic2DWithHeightOffsets( const util::PropertyMap &properties, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight) { return create( properties, createMethodMapNameEPSGCode( EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS), VectorOfParameters{ createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LATITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_LONGITUDE_OFFSET), createOpParamNameEPSGCode(EPSG_CODE_PARAMETER_GEOID_UNDULATION)}, VectorOfValues{offsetLat, offsetLong, offsetHeight}); } // --------------------------------------------------------------------------- /** \brief Instantiate a conversion with method Vertical Offset. * * This method is defined as * <a href="https://epsg.org/coord-operation-method_9616/index.html"> * EPSG:9616</a>. * * @param properties See \ref general_properties of the Conversion. * At minimum the name should be defined. * @param offsetHeight Geoid undulation to add. * @return new Conversion. */ ConversionNNPtr Conversion::createVerticalOffset(const util::PropertyMap &properties, const common::Length &offsetHeight) { return create(properties, createMethodMapNameEPSGCode(EPSG_CODE_METHOD_VERTICAL_OFFSET), VectorOfParameters{createOpParamNameEPSGCode( EPSG_CODE_PARAMETER_VERTICAL_OFFSET)}, VectorOfValues{offsetHeight}); } // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/iso19111/operation/coordinateoperation_private.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef COORDINATEROPERATION_PRIVATE_HPP #define COORDINATEROPERATION_PRIVATE_HPP #include "proj/coordinateoperation.hpp" #include "proj/util.hpp" // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct CoordinateOperation::Private { util::optional<std::string> operationVersion_{}; std::vector<metadata::PositionalAccuracyNNPtr> coordinateOperationAccuracies_{}; std::weak_ptr<crs::CRS> sourceCRSWeak_{}; std::weak_ptr<crs::CRS> targetCRSWeak_{}; crs::CRSPtr interpolationCRS_{}; std::shared_ptr<util::optional<common::DataEpoch>> sourceCoordinateEpoch_{ std::make_shared<util::optional<common::DataEpoch>>()}; std::shared_ptr<util::optional<common::DataEpoch>> targetCoordinateEpoch_{ std::make_shared<util::optional<common::DataEpoch>>()}; bool hasBallparkTransformation_ = false; // do not set this for a ProjectedCRS.definingConversion struct CRSStrongRef { crs::CRSNNPtr sourceCRS_; crs::CRSNNPtr targetCRS_; CRSStrongRef(const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn) : sourceCRS_(sourceCRSIn), targetCRS_(targetCRSIn) {} }; std::unique_ptr<CRSStrongRef> strongRef_{}; Private() = default; Private(const Private &other) : operationVersion_(other.operationVersion_), coordinateOperationAccuracies_(other.coordinateOperationAccuracies_), sourceCRSWeak_(other.sourceCRSWeak_), targetCRSWeak_(other.targetCRSWeak_), interpolationCRS_(other.interpolationCRS_), sourceCoordinateEpoch_(other.sourceCoordinateEpoch_), targetCoordinateEpoch_(other.targetCoordinateEpoch_), hasBallparkTransformation_(other.hasBallparkTransformation_), strongRef_(other.strongRef_ ? internal::make_unique<CRSStrongRef>( *(other.strongRef_)) : nullptr) {} Private &operator=(const Private &) = delete; }; //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END #endif // COORDINATEROPERATION_PRIVATE_HPP
hpp
PROJ
data/projects/PROJ/src/iso19111/operation/coordinateoperation_internal.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #error This file should only be included from a PROJ cpp file #endif #ifndef COORDINATEOPERATION_INTERNAL_HH_INCLUDED #define COORDINATEOPERATION_INTERNAL_HH_INCLUDED #include "proj/coordinateoperation.hpp" #include <vector> //! @cond Doxygen_Suppress NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- bool isAxisOrderReversal(int methodEPSGCode); // --------------------------------------------------------------------------- class InverseCoordinateOperation; /** Shared pointer of InverseCoordinateOperation */ using InverseCoordinateOperationPtr = std::shared_ptr<InverseCoordinateOperation>; /** Non-null shared pointer of InverseCoordinateOperation */ using InverseCoordinateOperationNNPtr = util::nn<InverseCoordinateOperationPtr>; /** \brief Inverse operation of a CoordinateOperation. * * This is used when there is no straightforward way of building another * subclass of CoordinateOperation that models the inverse operation. */ class InverseCoordinateOperation : virtual public CoordinateOperation { public: InverseCoordinateOperation( const CoordinateOperationNNPtr &forwardOperationIn, bool wktSupportsInversion); ~InverseCoordinateOperation() override; void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; CoordinateOperationNNPtr inverse() const override; const CoordinateOperationNNPtr &forwardOperation() const { return forwardOperation_; } protected: CoordinateOperationNNPtr forwardOperation_; bool wktSupportsInversion_; void setPropertiesFromForward(); }; // --------------------------------------------------------------------------- /** \brief Inverse of a conversion. */ class InverseConversion : public Conversion, public InverseCoordinateOperation { public: explicit InverseConversion(const ConversionNNPtr &forward); ~InverseConversion() override; void _exportToWKT(io::WKTFormatter *formatter) const override { Conversion::_exportToWKT(formatter); } void _exportToJSON(io::JSONFormatter *formatter) const override { Conversion::_exportToJSON(formatter); } void _exportToPROJString(io::PROJStringFormatter *formatter) const override { InverseCoordinateOperation::_exportToPROJString(formatter); } bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override { return InverseCoordinateOperation::_isEquivalentTo(other, criterion, dbContext); } CoordinateOperationNNPtr inverse() const override { return InverseCoordinateOperation::inverse(); } ConversionNNPtr inverseAsConversion() const; #ifdef _MSC_VER // To avoid a warning C4250: 'osgeo::proj::operation::InverseConversion': // inherits // 'osgeo::proj::operation::SingleOperation::osgeo::proj::operation::SingleOperation::gridsNeeded' // via dominance std::set<GridDescription> gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const override { return SingleOperation::gridsNeeded(databaseContext, considerKnownGridsAsAvailable); } #endif static CoordinateOperationNNPtr create(const ConversionNNPtr &forward); CoordinateOperationNNPtr _shallowClone() const override; }; // --------------------------------------------------------------------------- /** \brief Inverse of a transformation. */ class InverseTransformation : public Transformation, public InverseCoordinateOperation { public: explicit InverseTransformation(const TransformationNNPtr &forward); ~InverseTransformation() override; void _exportToWKT(io::WKTFormatter *formatter) const override; void _exportToPROJString(io::PROJStringFormatter *formatter) const override { return InverseCoordinateOperation::_exportToPROJString(formatter); } void _exportToJSON(io::JSONFormatter *formatter) const override { Transformation::_exportToJSON(formatter); } bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override { return InverseCoordinateOperation::_isEquivalentTo(other, criterion, dbContext); } CoordinateOperationNNPtr inverse() const override { return InverseCoordinateOperation::inverse(); } TransformationNNPtr inverseAsTransformation() const; #ifdef _MSC_VER // To avoid a warning C4250: // 'osgeo::proj::operation::InverseTransformation': inherits // 'osgeo::proj::operation::SingleOperation::osgeo::proj::operation::SingleOperation::gridsNeeded' // via dominance std::set<GridDescription> gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const override { return SingleOperation::gridsNeeded(databaseContext, considerKnownGridsAsAvailable); } #endif static TransformationNNPtr create(const TransformationNNPtr &forward); CoordinateOperationNNPtr _shallowClone() const override; }; // --------------------------------------------------------------------------- class PROJBasedOperation; /** Shared pointer of PROJBasedOperation */ using PROJBasedOperationPtr = std::shared_ptr<PROJBasedOperation>; /** Non-null shared pointer of PROJBasedOperation */ using PROJBasedOperationNNPtr = util::nn<PROJBasedOperationPtr>; /** \brief A PROJ-string based coordinate operation. */ class PROJBasedOperation : public SingleOperation { public: ~PROJBasedOperation() override; void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) CoordinateOperationNNPtr inverse() const override; static PROJBasedOperationNNPtr create(const util::PropertyMap &properties, const std::string &PROJString, const crs::CRSPtr &sourceCRS, const crs::CRSPtr &targetCRS, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); static PROJBasedOperationNNPtr create(const util::PropertyMap &properties, const io::IPROJStringExportableNNPtr &projExportable, bool inverse, const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const crs::CRSPtr &interpolationCRS, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies, bool hasRoughTransformation); std::set<GridDescription> gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const override; protected: PROJBasedOperation(const PROJBasedOperation &) = default; explicit PROJBasedOperation(const OperationMethodNNPtr &methodIn); void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) CoordinateOperationNNPtr _shallowClone() const override; INLINED_MAKE_SHARED private: std::string projString_{}; io::IPROJStringExportablePtr projStringExportable_{}; bool inverse_ = false; }; // --------------------------------------------------------------------------- class InvalidOperationEmptyIntersection : public InvalidOperation { public: explicit InvalidOperationEmptyIntersection(const std::string &message); InvalidOperationEmptyIntersection( const InvalidOperationEmptyIntersection &other); ~InvalidOperationEmptyIntersection() override; }; } // namespace operation NS_PROJ_END //! @endcond #endif // COORDINATEOPERATION_INTERNAL_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/src/iso19111/operation/parammappings.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef PARAMMAPPINGS_HPP #define PARAMMAPPINGS_HPP #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/coordinateoperation.hpp" #include "proj/util.hpp" // --------------------------------------------------------------------------- NS_PROJ_START namespace operation { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress extern const char *WKT1_LATITUDE_OF_ORIGIN; extern const char *WKT1_CENTRAL_MERIDIAN; extern const char *WKT1_SCALE_FACTOR; extern const char *WKT1_FALSE_EASTING; extern const char *WKT1_FALSE_NORTHING; extern const char *WKT1_STANDARD_PARALLEL_1; extern const char *WKT1_STANDARD_PARALLEL_2; extern const char *WKT1_LATITUDE_OF_CENTER; extern const char *WKT1_LONGITUDE_OF_CENTER; extern const char *WKT1_AZIMUTH; extern const char *WKT1_RECTIFIED_GRID_ANGLE; struct ParamMapping { const char *wkt2_name; const int epsg_code; const char *wkt1_name; const common::UnitOfMeasure::Type unit_type; const char *proj_name; }; struct MethodMapping { const char *wkt2_name; const int epsg_code; const char *wkt1_name; const char *proj_name_main; const char *proj_name_aux; const ParamMapping *const *params; }; extern const ParamMapping paramLatitudeNatOrigin; const MethodMapping *getProjectionMethodMappings(size_t &nElts); const MethodMapping *getOtherMethodMappings(size_t &nElts); struct MethodNameCode { const char *name; int epsg_code; }; const MethodNameCode *getMethodNameCodes(size_t &nElts); struct ParamNameCode { const char *name; int epsg_code; }; const ParamNameCode *getParamNameCodes(size_t &nElts); const MethodMapping *getMapping(int epsg_code) noexcept; const MethodMapping *getMappingFromWKT1(const std::string &wkt1_name) noexcept; const MethodMapping *getMapping(const char *wkt2_name) noexcept; const MethodMapping *getMapping(const OperationMethod *method) noexcept; std::vector<const MethodMapping *> getMappingsFromPROJName(const std::string &projName); const ParamMapping *getMapping(const MethodMapping *mapping, const OperationParameterNNPtr &param); const ParamMapping *getMappingFromWKT1(const MethodMapping *mapping, const std::string &wkt1_name); //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END #endif // PARAMMAPPINGS_HPP
hpp
PROJ
data/projects/PROJ/src/iso19111/operation/parammappings.cpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "parammappings.hpp" #include "oputils.hpp" #include "proj_constants.h" #include "proj/internal/internal.hpp" NS_PROJ_START using namespace internal; namespace operation { //! @cond Doxygen_Suppress const char *WKT1_LATITUDE_OF_ORIGIN = "latitude_of_origin"; const char *WKT1_CENTRAL_MERIDIAN = "central_meridian"; const char *WKT1_SCALE_FACTOR = "scale_factor"; const char *WKT1_FALSE_EASTING = "false_easting"; const char *WKT1_FALSE_NORTHING = "false_northing"; const char *WKT1_STANDARD_PARALLEL_1 = "standard_parallel_1"; const char *WKT1_STANDARD_PARALLEL_2 = "standard_parallel_2"; const char *WKT1_LATITUDE_OF_CENTER = "latitude_of_center"; const char *WKT1_LONGITUDE_OF_CENTER = "longitude_of_center"; const char *WKT1_AZIMUTH = "azimuth"; const char *WKT1_RECTIFIED_GRID_ANGLE = "rectified_grid_angle"; static const char *lat_0 = "lat_0"; static const char *lat_1 = "lat_1"; static const char *lat_2 = "lat_2"; static const char *lat_ts = "lat_ts"; static const char *lon_0 = "lon_0"; static const char *lon_1 = "lon_1"; static const char *lon_2 = "lon_2"; static const char *lonc = "lonc"; static const char *alpha = "alpha"; static const char *gamma = "gamma"; static const char *k_0 = "k_0"; static const char *k = "k"; static const char *x_0 = "x_0"; static const char *y_0 = "y_0"; static const char *h = "h"; // --------------------------------------------------------------------------- const ParamMapping paramLatitudeNatOrigin = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongitudeNatOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, WKT1_CENTRAL_MERIDIAN, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramScaleFactor = { EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k_0}; static const ParamMapping paramScaleFactorK = { EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k}; static const ParamMapping paramFalseEasting = { EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, WKT1_FALSE_EASTING, common::UnitOfMeasure::Type::LINEAR, x_0}; static const ParamMapping paramFalseNorthing = { EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, WKT1_FALSE_NORTHING, common::UnitOfMeasure::Type::LINEAR, y_0}; static const ParamMapping paramLatitudeFalseOrigin = { EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongitudeFalseOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, WKT1_CENTRAL_MERIDIAN, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramEastingFalseOrigin = { EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, WKT1_FALSE_EASTING, common::UnitOfMeasure::Type::LINEAR, x_0}; static const ParamMapping paramNorthingFalseOrigin = { EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, WKT1_FALSE_NORTHING, common::UnitOfMeasure::Type::LINEAR, y_0}; static const ParamMapping paramLatitude1stStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, WKT1_STANDARD_PARALLEL_1, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping paramLatitude2ndStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, WKT1_STANDARD_PARALLEL_2, common::UnitOfMeasure::Type::ANGULAR, lat_2}; static const ParamMapping *const paramsNatOriginScale[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramScaleFactor, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsNatOriginScaleK[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramScaleFactorK, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatFirstPoint = { "Latitude of 1st point", 0, "Latitude_Of_1st_Point", common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping paramLongFirstPoint = { "Longitude of 1st point", 0, "Longitude_Of_1st_Point", common::UnitOfMeasure::Type::ANGULAR, lon_1}; static const ParamMapping paramLatSecondPoint = { "Latitude of 2nd point", 0, "Latitude_Of_2nd_Point", common::UnitOfMeasure::Type::ANGULAR, lat_2}; static const ParamMapping paramLongSecondPoint = { "Longitude of 2nd point", 0, "Longitude_Of_2nd_Point", common::UnitOfMeasure::Type::ANGULAR, lon_2}; static const ParamMapping *const paramsTPEQD[] = {&paramLatFirstPoint, &paramLongFirstPoint, &paramLatSecondPoint, &paramLongSecondPoint, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsTMG[] = { &paramLatitudeFalseOrigin, &paramLongitudeFalseOrigin, &paramEastingFalseOrigin, &paramNorthingFalseOrigin, nullptr}; static const ParamMapping paramLatFalseOriginLatOfCenter = { EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, WKT1_LATITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongFalseOriginLongOfCenter = { EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping *const paramsAEA_EQDC[] = { &paramLatFalseOriginLatOfCenter, &paramLongFalseOriginLongOfCenter, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramEastingFalseOrigin, &paramNorthingFalseOrigin, nullptr}; static const ParamMapping paramLatitudeNatOriginLCC1SP = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping *const paramsLCC1SP[] = { &paramLatitudeNatOriginLCC1SP, &paramLongitudeNatOrigin, &paramScaleFactor, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsLCC1SPVariantB[] = { &paramLatitudeNatOriginLCC1SP, &paramScaleFactor, &paramLatitudeFalseOrigin, &paramLongitudeFalseOrigin, &paramEastingFalseOrigin, &paramNorthingFalseOrigin, nullptr, }; static const ParamMapping *const paramsLCC2SP[] = { &paramLatitudeFalseOrigin, &paramLongitudeFalseOrigin, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramEastingFalseOrigin, &paramNorthingFalseOrigin, nullptr, }; static const ParamMapping paramEllipsoidScaleFactor = { EPSG_NAME_PARAMETER_ELLIPSOID_SCALE_FACTOR, EPSG_CODE_PARAMETER_ELLIPSOID_SCALE_FACTOR, nullptr, common::UnitOfMeasure::Type::SCALE, k_0}; static const ParamMapping *const paramsLCC2SPMichigan[] = { &paramLatitudeFalseOrigin, &paramLongitudeFalseOrigin, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramEastingFalseOrigin, &paramNorthingFalseOrigin, &paramEllipsoidScaleFactor, nullptr, }; static const ParamMapping paramLatNatLatCenter = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongNatLongCenter = { EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping *const paramsAEQD[]{ &paramLatNatLatCenter, &paramLongNatLongCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsNatOrigin[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatNatOriginLat1 = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_STANDARD_PARALLEL_1, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping *const paramsBonne[] = { &paramLatNatOriginLat1, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLat1stParallelLatTs = { EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, WKT1_STANDARD_PARALLEL_1, common::UnitOfMeasure::Type::ANGULAR, lat_ts}; static const ParamMapping *const paramsCEA[] = { &paramLat1stParallelLatTs, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsEQDC[] = {&paramLatNatLatCenter, &paramLongNatLongCenter, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsLongNatOrigin[] = { &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsEqc[] = { &paramLat1stParallelLatTs, &paramLatitudeNatOrigin, // extension of EPSG, but used by GDAL / PROJ &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramSatelliteHeight = { "Satellite Height", 0, "satellite_height", common::UnitOfMeasure::Type::LINEAR, h}; static const ParamMapping *const paramsGeos[] = { &paramLongitudeNatOrigin, &paramSatelliteHeight, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatCentreLatCenter = { EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, WKT1_LATITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLonCentreLonCenterLonc = { EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lonc}; static const ParamMapping paramAzimuth = { EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, WKT1_AZIMUTH, common::UnitOfMeasure::Type::ANGULAR, alpha}; static const ParamMapping paramAngleToSkewGrid = { EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, WKT1_RECTIFIED_GRID_ANGLE, common::UnitOfMeasure::Type::ANGULAR, gamma}; static const ParamMapping paramScaleFactorInitialLine = { EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k}; static const ParamMapping *const paramsHomVariantA[] = { &paramLatCentreLatCenter, &paramLonCentreLonCenterLonc, &paramAzimuth, &paramAngleToSkewGrid, &paramScaleFactorInitialLine, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramFalseEastingProjectionCentre = { EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE, WKT1_FALSE_EASTING, common::UnitOfMeasure::Type::LINEAR, x_0}; static const ParamMapping paramFalseNorthingProjectionCentre = { EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE, WKT1_FALSE_NORTHING, common::UnitOfMeasure::Type::LINEAR, y_0}; static const ParamMapping *const paramsHomVariantB[] = { &paramLatCentreLatCenter, &paramLonCentreLonCenterLonc, &paramAzimuth, &paramAngleToSkewGrid, &paramScaleFactorInitialLine, &paramFalseEastingProjectionCentre, &paramFalseNorthingProjectionCentre, nullptr}; static const ParamMapping paramLatPoint1 = { "Latitude of 1st point", 0, "latitude_of_point_1", common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping paramLongPoint1 = { "Longitude of 1st point", 0, "longitude_of_point_1", common::UnitOfMeasure::Type::ANGULAR, lon_1}; static const ParamMapping paramLatPoint2 = { "Latitude of 2nd point", 0, "latitude_of_point_2", common::UnitOfMeasure::Type::ANGULAR, lat_2}; static const ParamMapping paramLongPoint2 = { "Longitude of 2nd point", 0, "longitude_of_point_2", common::UnitOfMeasure::Type::ANGULAR, lon_2}; static const ParamMapping *const paramsHomTwoPoint[] = { &paramLatCentreLatCenter, &paramLatPoint1, &paramLongPoint1, &paramLatPoint2, &paramLongPoint2, &paramScaleFactorInitialLine, &paramFalseEastingProjectionCentre, &paramFalseNorthingProjectionCentre, nullptr}; static const ParamMapping *const paramsIMWP[] = { &paramLongitudeNatOrigin, &paramLatFirstPoint, &paramLatSecondPoint, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLongCentreLongCenter = { EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramColatitudeConeAxis = { EPSG_NAME_PARAMETER_COLATITUDE_CONE_AXIS, EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS, WKT1_AZIMUTH, common::UnitOfMeasure::Type::ANGULAR, "alpha"}; /* ignored by PROJ currently */ static const ParamMapping paramLatitudePseudoStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, "pseudo_standard_parallel_1", common::UnitOfMeasure::Type::ANGULAR, nullptr}; /* ignored by PROJ currently */ static const ParamMapping paramScaleFactorPseudoStdParallel = { EPSG_NAME_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k}; /* ignored by PROJ currently */ static const ParamMapping *const krovakParameters[] = { &paramLatCentreLatCenter, &paramLongCentreLongCenter, &paramColatitudeConeAxis, &paramLatitudePseudoStdParallel, &paramScaleFactorPseudoStdParallel, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsLaea[] = { &paramLatNatLatCenter, &paramLongNatLongCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsMiller[] = { &paramLongNatLongCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatMerc1SP = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, nullptr, // always set to zero, not to be exported in WKT1 common::UnitOfMeasure::Type::ANGULAR, nullptr}; // always set to zero, not to be exported in PROJ strings static const ParamMapping *const paramsMerc1SP[] = { &paramLatMerc1SP, &paramLongitudeNatOrigin, &paramScaleFactorK, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsMerc2SP[] = { &paramLat1stParallelLatTs, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsObliqueStereo[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramScaleFactorK, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_ts}; static const ParamMapping paramsLongOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, WKT1_CENTRAL_MERIDIAN, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping *const paramsPolarStereo[] = { &paramLatStdParallel, &paramsLongOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsLongNatOriginLongitudeCentre[] = { &paramLongNatLongCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatTrueScaleWag3 = { "Latitude of true scale", 0, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_ts}; static const ParamMapping *const paramsWag3[] = { &paramLatTrueScaleWag3, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramPegLat = { "Peg point latitude", 0, "peg_point_latitude", common::UnitOfMeasure::Type::ANGULAR, "plat_0"}; static const ParamMapping paramPegLong = { "Peg point longitude", 0, "peg_point_longitude", common::UnitOfMeasure::Type::ANGULAR, "plon_0"}; static const ParamMapping paramPegHeading = { "Peg point heading", 0, "peg_point_heading", common::UnitOfMeasure::Type::ANGULAR, "phdg_0"}; static const ParamMapping paramPegHeight = { "Peg point height", 0, "peg_point_height", common::UnitOfMeasure::Type::LINEAR, "h_0"}; static const ParamMapping *const paramsSch[] = { &paramPegLat, &paramPegLong, &paramPegHeading, &paramPegHeight, nullptr}; static const ParamMapping *const paramsWink1[] = { &paramLongitudeNatOrigin, &paramLat1stParallelLatTs, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsWink2[] = { &paramLongitudeNatOrigin, &paramLatitude1stStdParallel, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatLoxim = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping *const paramsLoxim[] = { &paramLatLoxim, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLongCentre = { EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramLabordeObliqueMercatorAzimuth = { EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, WKT1_AZIMUTH, common::UnitOfMeasure::Type::ANGULAR, "azi"}; static const ParamMapping *const paramsLabordeObliqueMercator[] = { &paramLatCentreLatCenter, &paramLongCentre, &paramLabordeObliqueMercatorAzimuth, &paramScaleFactorInitialLine, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatTopoOrigin = { EPSG_NAME_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongTopoOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramHeightTopoOrigin = { EPSG_NAME_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; // unsupported by PROJ right now static const ParamMapping paramViewpointHeight = { EPSG_NAME_PARAMETER_VIEWPOINT_HEIGHT, EPSG_CODE_PARAMETER_VIEWPOINT_HEIGHT, nullptr, common::UnitOfMeasure::Type::LINEAR, "h"}; static const ParamMapping *const paramsVerticalPerspective[] = { &paramLatTopoOrigin, &paramLongTopoOrigin, &paramHeightTopoOrigin, // unsupported by PROJ right now &paramViewpointHeight, &paramFalseEasting, // PROJ addition &paramFalseNorthing, // PROJ addition nullptr}; static const ParamMapping paramProjectionPlaneOriginHeight = { EPSG_NAME_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT, EPSG_CODE_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT, nullptr, common::UnitOfMeasure::Type::LINEAR, "h_0"}; static const ParamMapping *const paramsColombiaUrban[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, &paramProjectionPlaneOriginHeight, nullptr}; static const ParamMapping paramGeocentricXTopocentricOrigin = { EPSG_NAME_PARAMETER_GEOCENTRIC_X_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_GEOCENTRIC_X_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "X_0"}; static const ParamMapping paramGeocentricYTopocentricOrigin = { EPSG_NAME_PARAMETER_GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "Y_0"}; static const ParamMapping paramGeocentricZTopocentricOrigin = { EPSG_NAME_PARAMETER_GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "Z_0"}; static const ParamMapping *const paramsGeocentricTopocentric[] = { &paramGeocentricXTopocentricOrigin, &paramGeocentricYTopocentricOrigin, &paramGeocentricZTopocentricOrigin, nullptr}; static const ParamMapping paramHeightTopoOriginWithH0 = { EPSG_NAME_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "h_0"}; static const ParamMapping *const paramsGeographicTopocentric[] = { &paramLatTopoOrigin, &paramLongTopoOrigin, &paramHeightTopoOriginWithH0, nullptr}; static const MethodMapping projectionMethodMappings[] = { {EPSG_NAME_METHOD_TRANSVERSE_MERCATOR, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR, "Transverse_Mercator", "tmerc", nullptr, paramsNatOriginScaleK}, {EPSG_NAME_METHOD_TRANSVERSE_MERCATOR_3D, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_3D, "Transverse_Mercator", "tmerc", nullptr, paramsNatOriginScaleK}, {EPSG_NAME_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED, "Transverse_Mercator_South_Orientated", "tmerc", "axis=wsu", paramsNatOriginScaleK}, {PROJ_WKT2_NAME_METHOD_TWO_POINT_EQUIDISTANT, 0, "Two_Point_Equidistant", "tpeqd", nullptr, paramsTPEQD}, {EPSG_NAME_METHOD_TUNISIA_MINING_GRID, EPSG_CODE_METHOD_TUNISIA_MINING_GRID, "Tunisia_Mining_Grid", nullptr, nullptr, // no proj equivalent paramsTMG}, // Deprecated. Use EPSG_NAME_METHOD_TUNISIA_MINING_GRID instead {EPSG_NAME_METHOD_TUNISIA_MAPPING_GRID, EPSG_CODE_METHOD_TUNISIA_MAPPING_GRID, "Tunisia_Mapping_Grid", nullptr, nullptr, // no proj equivalent paramsTMG}, {EPSG_NAME_METHOD_ALBERS_EQUAL_AREA, EPSG_CODE_METHOD_ALBERS_EQUAL_AREA, "Albers_Conic_Equal_Area", "aea", nullptr, paramsAEA_EQDC}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_1SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP, "Lambert_Conformal_Conic_1SP", "lcc", nullptr, paramsLCC1SP}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B, nullptr, // no mapping to WKT1_GDAL "lcc", nullptr, paramsLCC1SPVariantB}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, "Lambert_Conformal_Conic_2SP", "lcc", nullptr, paramsLCC2SP}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN, nullptr, // no mapping to WKT1_GDAL "lcc", nullptr, paramsLCC2SPMichigan}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM, "Lambert_Conformal_Conic_2SP_Belgium", "lcc", nullptr, // FIXME: this is what is done in GDAL, but the formula of // LCC 2SP // Belgium in the EPSG 7.2 guidance is difference from the regular // LCC 2SP paramsLCC2SP}, {EPSG_NAME_METHOD_AZIMUTHAL_EQUIDISTANT, EPSG_CODE_METHOD_AZIMUTHAL_EQUIDISTANT, "Azimuthal_Equidistant", "aeqd", nullptr, paramsAEQD}, // We don't actually implement the Modified variant of Azimuthal Equidistant // but the exact one. The difference between both is neglectable in a few // hundred of kilometers away from the center of projection {EPSG_NAME_METHOD_MODIFIED_AZIMUTHAL_EQUIDISTANT, EPSG_CODE_METHOD_MODIFIED_AZIMUTHAL_EQUIDISTANT, "Azimuthal_Equidistant", "aeqd", nullptr, paramsAEQD}, {EPSG_NAME_METHOD_GUAM_PROJECTION, EPSG_CODE_METHOD_GUAM_PROJECTION, nullptr, // no mapping to GDAL WKT1 "aeqd", "guam", paramsNatOrigin}, {EPSG_NAME_METHOD_BONNE, EPSG_CODE_METHOD_BONNE, "Bonne", "bonne", nullptr, paramsBonne}, {PROJ_WKT2_NAME_METHOD_COMPACT_MILLER, 0, "Compact_Miller", "comill", nullptr, paramsLongNatOrigin}, {EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, "Cylindrical_Equal_Area", "cea", nullptr, paramsCEA}, {EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL, "Cylindrical_Equal_Area", "cea", "R_A", paramsCEA}, {EPSG_NAME_METHOD_CASSINI_SOLDNER, EPSG_CODE_METHOD_CASSINI_SOLDNER, "Cassini_Soldner", "cass", nullptr, paramsNatOrigin}, {EPSG_NAME_METHOD_HYPERBOLIC_CASSINI_SOLDNER, EPSG_CODE_METHOD_HYPERBOLIC_CASSINI_SOLDNER, nullptr, "cass", "hyperbolic", paramsNatOrigin}, // Definition to be put before PROJ_WKT2_NAME_METHOD_EQUIDISTANT_CONIC {EPSG_NAME_METHOD_EQUIDISTANT_CONIC, EPSG_CODE_METHOD_EQUIDISTANT_CONIC, "Equidistant_Conic", "eqdc", nullptr, paramsAEA_EQDC}, // Definition before EPSG codified it. To be put after entry for // EPSG_NAME_METHOD_EQUIDISTANT_CONIC {PROJ_WKT2_NAME_METHOD_EQUIDISTANT_CONIC, 0, "Equidistant_Conic", "eqdc", nullptr, paramsEQDC}, {PROJ_WKT2_NAME_METHOD_ECKERT_I, 0, "Eckert_I", "eck1", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_II, 0, "Eckert_II", "eck2", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_III, 0, "Eckert_III", "eck3", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_IV, 0, "Eckert_IV", "eck4", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_V, 0, "Eckert_V", "eck5", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_VI, 0, "Eckert_VI", "eck6", nullptr, paramsLongNatOrigin}, {EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL, "Equirectangular", "eqc", nullptr, paramsEqc}, {EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL, "Equirectangular", "eqc", nullptr, paramsEqc}, {PROJ_WKT2_NAME_METHOD_FLAT_POLAR_QUARTIC, 0, "Flat_Polar_Quartic", "mbtfpq", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_GALL_STEREOGRAPHIC, 0, "Gall_Stereographic", "gall", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_GOODE_HOMOLOSINE, 0, "Goode_Homolosine", "goode", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE, 0, "Interrupted_Goode_Homolosine", "igh", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE_OCEAN, 0, nullptr, "igh_o", nullptr, paramsLongNatOrigin}, // No proper WKT1 representation fr sweep=x {PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X, 0, nullptr, "geos", "sweep=x", paramsGeos}, {PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y, 0, "Geostationary_Satellite", "geos", nullptr, paramsGeos}, {PROJ_WKT2_NAME_METHOD_GAUSS_SCHREIBER_TRANSVERSE_MERCATOR, 0, "Gauss_Schreiber_Transverse_Mercator", "gstmerc", nullptr, paramsNatOriginScale}, {PROJ_WKT2_NAME_METHOD_GNOMONIC, 0, "Gnomonic", "gnom", nullptr, paramsNatOrigin}, {EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, "Hotine_Oblique_Mercator", "omerc", "no_uoff", paramsHomVariantA}, {EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, "Hotine_Oblique_Mercator_Azimuth_Center", "omerc", nullptr, paramsHomVariantB}, {PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN, 0, "Hotine_Oblique_Mercator_Two_Point_Natural_Origin", "omerc", nullptr, paramsHomTwoPoint}, {PROJ_WKT2_NAME_INTERNATIONAL_MAP_WORLD_POLYCONIC, 0, "International_Map_of_the_World_Polyconic", "imw_p", nullptr, paramsIMWP}, {EPSG_NAME_METHOD_KROVAK_NORTH_ORIENTED, EPSG_CODE_METHOD_KROVAK_NORTH_ORIENTED, "Krovak", "krovak", nullptr, krovakParameters}, {EPSG_NAME_METHOD_KROVAK, EPSG_CODE_METHOD_KROVAK, "Krovak", "krovak", "axis=swu", krovakParameters}, {EPSG_NAME_METHOD_KROVAK_MODIFIED_NORTH_ORIENTED, EPSG_CODE_METHOD_KROVAK_MODIFIED_NORTH_ORIENTED, nullptr, "mod_krovak", nullptr, krovakParameters}, {EPSG_NAME_METHOD_KROVAK_MODIFIED, EPSG_CODE_METHOD_KROVAK_MODIFIED, nullptr, "mod_krovak", "axis=swu", krovakParameters}, {EPSG_NAME_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA, EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA, "Lambert_Azimuthal_Equal_Area", "laea", nullptr, paramsLaea}, {EPSG_NAME_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL, EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL, "Lambert_Azimuthal_Equal_Area", "laea", "R_A", paramsLaea}, {PROJ_WKT2_NAME_METHOD_MILLER_CYLINDRICAL, 0, "Miller_Cylindrical", "mill", "R_A", paramsMiller}, {EPSG_NAME_METHOD_MERCATOR_VARIANT_A, EPSG_CODE_METHOD_MERCATOR_VARIANT_A, "Mercator_1SP", "merc", nullptr, paramsMerc1SP}, {EPSG_NAME_METHOD_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, "Mercator_2SP", "merc", nullptr, paramsMerc2SP}, {EPSG_NAME_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR, EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR, "Popular_Visualisation_Pseudo_Mercator", // particular case actually // handled manually "webmerc", nullptr, paramsNatOrigin}, {EPSG_NAME_METHOD_MERCATOR_SPHERICAL, EPSG_CODE_METHOD_MERCATOR_SPHERICAL, nullptr, "merc", "R_C", paramsNatOrigin}, {PROJ_WKT2_NAME_METHOD_MOLLWEIDE, 0, "Mollweide", "moll", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_NATURAL_EARTH, 0, "Natural_Earth", "natearth", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_NATURAL_EARTH_II, 0, "Natural_Earth_II", "natearth2", nullptr, paramsLongNatOrigin}, {EPSG_NAME_METHOD_NZMG, EPSG_CODE_METHOD_NZMG, "New_Zealand_Map_Grid", "nzmg", nullptr, paramsNatOrigin}, { EPSG_NAME_METHOD_OBLIQUE_STEREOGRAPHIC, EPSG_CODE_METHOD_OBLIQUE_STEREOGRAPHIC, "Oblique_Stereographic", "sterea", nullptr, paramsObliqueStereo, }, {EPSG_NAME_METHOD_ORTHOGRAPHIC, EPSG_CODE_METHOD_ORTHOGRAPHIC, "Orthographic", "ortho", nullptr, paramsNatOrigin}, {PROJ_WKT2_NAME_ORTHOGRAPHIC_SPHERICAL, 0, "Orthographic", "ortho", "f=0", paramsNatOrigin}, {PROJ_WKT2_NAME_METHOD_PATTERSON, 0, "Patterson", "patterson", nullptr, paramsLongNatOrigin}, {EPSG_NAME_METHOD_AMERICAN_POLYCONIC, EPSG_CODE_METHOD_AMERICAN_POLYCONIC, "Polyconic", "poly", nullptr, paramsNatOrigin}, {EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A, "Polar_Stereographic", "stere", nullptr, paramsObliqueStereo}, {EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, "Polar_Stereographic", "stere", nullptr, paramsPolarStereo}, {PROJ_WKT2_NAME_METHOD_ROBINSON, 0, "Robinson", "robin", nullptr, paramsLongNatOriginLongitudeCentre}, {PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_SQUARE, 0, nullptr, "peirce_q", "shape=square", paramsNatOriginScale}, {PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_DIAMOND, 0, nullptr, "peirce_q", "shape=diamond", paramsNatOriginScale}, {PROJ_WKT2_NAME_METHOD_SINUSOIDAL, 0, "Sinusoidal", "sinu", nullptr, paramsLongNatOriginLongitudeCentre}, {PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC, 0, "Stereographic", "stere", nullptr, paramsObliqueStereo}, {PROJ_WKT2_NAME_METHOD_TIMES, 0, "Times", "times", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_VAN_DER_GRINTEN, 0, "VanDerGrinten", "vandg", "R_A", paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_I, 0, "Wagner_I", "wag1", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_II, 0, "Wagner_II", "wag2", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_III, 0, "Wagner_III", "wag3", nullptr, paramsWag3}, {PROJ_WKT2_NAME_METHOD_WAGNER_IV, 0, "Wagner_IV", "wag4", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_V, 0, "Wagner_V", "wag5", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_VI, 0, "Wagner_VI", "wag6", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_VII, 0, "Wagner_VII", "wag7", nullptr, paramsLongNatOrigin}, {PROJ_WKT2_NAME_METHOD_QUADRILATERALIZED_SPHERICAL_CUBE, 0, "Quadrilateralized_Spherical_Cube", "qsc", nullptr, paramsNatOrigin}, {PROJ_WKT2_NAME_METHOD_SPHERICAL_CROSS_TRACK_HEIGHT, 0, "Spherical_Cross_Track_Height", "sch", nullptr, paramsSch}, // The following methods have just the WKT <--> PROJ string mapping, but // no setter. Similarly to GDAL {"Aitoff", 0, "Aitoff", "aitoff", nullptr, paramsLongNatOrigin}, {"Winkel I", 0, "Winkel_I", "wink1", nullptr, paramsWink1}, {"Winkel II", 0, "Winkel_II", "wink2", nullptr, paramsWink2}, {"Winkel Tripel", 0, "Winkel_Tripel", "wintri", nullptr, paramsWink2}, {"Craster Parabolic", 0, "Craster_Parabolic", "crast", nullptr, paramsLongNatOrigin}, {"Loximuthal", 0, "Loximuthal", "loxim", nullptr, paramsLoxim}, {"Quartic Authalic", 0, "Quartic_Authalic", "qua_aut", nullptr, paramsLongNatOrigin}, {"Transverse Cylindrical Equal Area", 0, "Transverse_Cylindrical_Equal_Area", "tcea", nullptr, paramsObliqueStereo}, {EPSG_NAME_METHOD_EQUAL_EARTH, EPSG_CODE_METHOD_EQUAL_EARTH, nullptr, "eqearth", nullptr, paramsLongNatOrigin}, {EPSG_NAME_METHOD_LABORDE_OBLIQUE_MERCATOR, EPSG_CODE_METHOD_LABORDE_OBLIQUE_MERCATOR, "Laborde_Oblique_Mercator", "labrd", nullptr, paramsLabordeObliqueMercator}, {EPSG_NAME_METHOD_VERTICAL_PERSPECTIVE, EPSG_CODE_METHOD_VERTICAL_PERSPECTIVE, nullptr, "nsper", nullptr, paramsVerticalPerspective}, {EPSG_NAME_METHOD_COLOMBIA_URBAN, EPSG_CODE_METHOD_COLOMBIA_URBAN, nullptr, "col_urban", nullptr, paramsColombiaUrban}, {EPSG_NAME_METHOD_GEOCENTRIC_TOPOCENTRIC, EPSG_CODE_METHOD_GEOCENTRIC_TOPOCENTRIC, nullptr, "topocentric", nullptr, paramsGeocentricTopocentric}, {EPSG_NAME_METHOD_GEOGRAPHIC_TOPOCENTRIC, EPSG_CODE_METHOD_GEOGRAPHIC_TOPOCENTRIC, nullptr, nullptr, nullptr, paramsGeographicTopocentric}, }; const MethodMapping *getProjectionMethodMappings(size_t &nElts) { nElts = sizeof(projectionMethodMappings) / sizeof(projectionMethodMappings[0]); return projectionMethodMappings; } #define METHOD_NAME_CODE(method) \ { EPSG_NAME_METHOD_##method, EPSG_CODE_METHOD_##method } const struct MethodNameCode methodNameCodesList[] = { // Projection methods METHOD_NAME_CODE(TRANSVERSE_MERCATOR), METHOD_NAME_CODE(TRANSVERSE_MERCATOR_SOUTH_ORIENTATED), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_1SP), METHOD_NAME_CODE(NZMG), METHOD_NAME_CODE(TUNISIA_MINING_GRID), METHOD_NAME_CODE(ALBERS_EQUAL_AREA), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_2SP), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN), METHOD_NAME_CODE(MODIFIED_AZIMUTHAL_EQUIDISTANT), METHOD_NAME_CODE(GUAM_PROJECTION), METHOD_NAME_CODE(BONNE), METHOD_NAME_CODE(LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL), METHOD_NAME_CODE(LAMBERT_CYLINDRICAL_EQUAL_AREA), METHOD_NAME_CODE(CASSINI_SOLDNER), METHOD_NAME_CODE(EQUIDISTANT_CYLINDRICAL), METHOD_NAME_CODE(EQUIDISTANT_CYLINDRICAL_SPHERICAL), METHOD_NAME_CODE(HOTINE_OBLIQUE_MERCATOR_VARIANT_A), METHOD_NAME_CODE(HOTINE_OBLIQUE_MERCATOR_VARIANT_B), METHOD_NAME_CODE(KROVAK_NORTH_ORIENTED), METHOD_NAME_CODE(KROVAK), METHOD_NAME_CODE(LAMBERT_AZIMUTHAL_EQUAL_AREA), METHOD_NAME_CODE(POPULAR_VISUALISATION_PSEUDO_MERCATOR), METHOD_NAME_CODE(MERCATOR_SPHERICAL), METHOD_NAME_CODE(MERCATOR_VARIANT_A), METHOD_NAME_CODE(MERCATOR_VARIANT_B), METHOD_NAME_CODE(OBLIQUE_STEREOGRAPHIC), METHOD_NAME_CODE(AMERICAN_POLYCONIC), METHOD_NAME_CODE(POLAR_STEREOGRAPHIC_VARIANT_A), METHOD_NAME_CODE(POLAR_STEREOGRAPHIC_VARIANT_B), METHOD_NAME_CODE(EQUAL_EARTH), METHOD_NAME_CODE(LABORDE_OBLIQUE_MERCATOR), METHOD_NAME_CODE(VERTICAL_PERSPECTIVE), METHOD_NAME_CODE(COLOMBIA_URBAN), // Other conversions METHOD_NAME_CODE(CHANGE_VERTICAL_UNIT), METHOD_NAME_CODE(CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR), METHOD_NAME_CODE(HEIGHT_DEPTH_REVERSAL), METHOD_NAME_CODE(AXIS_ORDER_REVERSAL_2D), METHOD_NAME_CODE(AXIS_ORDER_REVERSAL_3D), METHOD_NAME_CODE(GEOGRAPHIC_GEOCENTRIC), METHOD_NAME_CODE(GEOCENTRIC_TOPOCENTRIC), METHOD_NAME_CODE(GEOGRAPHIC_TOPOCENTRIC), // Transformations METHOD_NAME_CODE(LONGITUDE_ROTATION), METHOD_NAME_CODE(AFFINE_PARAMETRIC_TRANSFORMATION), METHOD_NAME_CODE(SIMILARITY_TRANSFORMATION), METHOD_NAME_CODE(COORDINATE_FRAME_GEOCENTRIC), METHOD_NAME_CODE(COORDINATE_FRAME_GEOGRAPHIC_2D), METHOD_NAME_CODE(COORDINATE_FRAME_GEOGRAPHIC_3D), METHOD_NAME_CODE(POSITION_VECTOR_GEOCENTRIC), METHOD_NAME_CODE(POSITION_VECTOR_GEOGRAPHIC_2D), METHOD_NAME_CODE(POSITION_VECTOR_GEOGRAPHIC_3D), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_GEOCENTRIC), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D), METHOD_NAME_CODE(TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC), METHOD_NAME_CODE(TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D), METHOD_NAME_CODE(TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D), METHOD_NAME_CODE(TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC), METHOD_NAME_CODE(TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D), METHOD_NAME_CODE(TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_CF_GEOCENTRIC), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_PV_GEOCENTRIC), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D), METHOD_NAME_CODE(MOLODENSKY), METHOD_NAME_CODE(ABRIDGED_MOLODENSKY), METHOD_NAME_CODE(GEOGRAPHIC2D_OFFSETS), METHOD_NAME_CODE(GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS), METHOD_NAME_CODE(GEOGRAPHIC3D_OFFSETS), METHOD_NAME_CODE(VERTICAL_OFFSET), METHOD_NAME_CODE(VERTICAL_OFFSET_AND_SLOPE), METHOD_NAME_CODE(NTV2), METHOD_NAME_CODE(NTV1), METHOD_NAME_CODE(NADCON), METHOD_NAME_CODE(NADCON5_2D), METHOD_NAME_CODE(NADCON5_3D), METHOD_NAME_CODE(VERTCON), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN), // PointMotionOperation METHOD_NAME_CODE(POINT_MOTION_BY_GRID_CANADA_NTV2_VEL), }; const MethodNameCode *getMethodNameCodes(size_t &nElts) { nElts = sizeof(methodNameCodesList) / sizeof(methodNameCodesList[0]); return methodNameCodesList; } #define PARAM_NAME_CODE(method) \ { EPSG_NAME_PARAMETER_##method, EPSG_CODE_PARAMETER_##method } const struct ParamNameCode paramNameCodes[] = { // Parameters of projection methods PARAM_NAME_CODE(COLATITUDE_CONE_AXIS), PARAM_NAME_CODE(LATITUDE_OF_NATURAL_ORIGIN), PARAM_NAME_CODE(LONGITUDE_OF_NATURAL_ORIGIN), PARAM_NAME_CODE(SCALE_FACTOR_AT_NATURAL_ORIGIN), PARAM_NAME_CODE(FALSE_EASTING), PARAM_NAME_CODE(FALSE_NORTHING), PARAM_NAME_CODE(LATITUDE_PROJECTION_CENTRE), PARAM_NAME_CODE(LONGITUDE_PROJECTION_CENTRE), PARAM_NAME_CODE(AZIMUTH_INITIAL_LINE), PARAM_NAME_CODE(ANGLE_RECTIFIED_TO_SKEW_GRID), PARAM_NAME_CODE(SCALE_FACTOR_INITIAL_LINE), PARAM_NAME_CODE(EASTING_PROJECTION_CENTRE), PARAM_NAME_CODE(NORTHING_PROJECTION_CENTRE), PARAM_NAME_CODE(LATITUDE_PSEUDO_STANDARD_PARALLEL), PARAM_NAME_CODE(SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL), PARAM_NAME_CODE(LATITUDE_FALSE_ORIGIN), PARAM_NAME_CODE(LONGITUDE_FALSE_ORIGIN), PARAM_NAME_CODE(LATITUDE_1ST_STD_PARALLEL), PARAM_NAME_CODE(LATITUDE_2ND_STD_PARALLEL), PARAM_NAME_CODE(EASTING_FALSE_ORIGIN), PARAM_NAME_CODE(NORTHING_FALSE_ORIGIN), PARAM_NAME_CODE(LATITUDE_STD_PARALLEL), PARAM_NAME_CODE(LONGITUDE_OF_ORIGIN), PARAM_NAME_CODE(ELLIPSOID_SCALE_FACTOR), PARAM_NAME_CODE(PROJECTION_PLANE_ORIGIN_HEIGHT), PARAM_NAME_CODE(GEOCENTRIC_X_TOPOCENTRIC_ORIGIN), PARAM_NAME_CODE(GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN), PARAM_NAME_CODE(GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN), // Parameters of transformations PARAM_NAME_CODE(SEMI_MAJOR_AXIS_DIFFERENCE), PARAM_NAME_CODE(FLATTENING_DIFFERENCE), PARAM_NAME_CODE(LATITUDE_LONGITUDE_DIFFERENCE_FILE), PARAM_NAME_CODE(GEOID_CORRECTION_FILENAME), PARAM_NAME_CODE(VERTICAL_OFFSET_FILE), PARAM_NAME_CODE(GEOID_MODEL_DIFFERENCE_FILE), PARAM_NAME_CODE(LATITUDE_DIFFERENCE_FILE), PARAM_NAME_CODE(LONGITUDE_DIFFERENCE_FILE), PARAM_NAME_CODE(UNIT_CONVERSION_SCALAR), PARAM_NAME_CODE(LATITUDE_OFFSET), PARAM_NAME_CODE(LONGITUDE_OFFSET), PARAM_NAME_CODE(VERTICAL_OFFSET), PARAM_NAME_CODE(GEOID_UNDULATION), PARAM_NAME_CODE(A0), PARAM_NAME_CODE(A1), PARAM_NAME_CODE(A2), PARAM_NAME_CODE(B0), PARAM_NAME_CODE(B1), PARAM_NAME_CODE(B2), PARAM_NAME_CODE(X_AXIS_TRANSLATION), PARAM_NAME_CODE(Y_AXIS_TRANSLATION), PARAM_NAME_CODE(Z_AXIS_TRANSLATION), PARAM_NAME_CODE(X_AXIS_ROTATION), PARAM_NAME_CODE(Y_AXIS_ROTATION), PARAM_NAME_CODE(Z_AXIS_ROTATION), PARAM_NAME_CODE(SCALE_DIFFERENCE), PARAM_NAME_CODE(RATE_X_AXIS_TRANSLATION), PARAM_NAME_CODE(RATE_Y_AXIS_TRANSLATION), PARAM_NAME_CODE(RATE_Z_AXIS_TRANSLATION), PARAM_NAME_CODE(RATE_X_AXIS_ROTATION), PARAM_NAME_CODE(RATE_Y_AXIS_ROTATION), PARAM_NAME_CODE(RATE_Z_AXIS_ROTATION), PARAM_NAME_CODE(RATE_SCALE_DIFFERENCE), PARAM_NAME_CODE(REFERENCE_EPOCH), PARAM_NAME_CODE(TRANSFORMATION_REFERENCE_EPOCH), PARAM_NAME_CODE(ORDINATE_1_EVAL_POINT), PARAM_NAME_CODE(ORDINATE_2_EVAL_POINT), PARAM_NAME_CODE(ORDINATE_3_EVAL_POINT), PARAM_NAME_CODE(GEOCENTRIC_TRANSLATION_FILE), PARAM_NAME_CODE(INCLINATION_IN_LATITUDE), PARAM_NAME_CODE(INCLINATION_IN_LONGITUDE), PARAM_NAME_CODE(EPSG_CODE_FOR_HORIZONTAL_CRS), PARAM_NAME_CODE(EPSG_CODE_FOR_INTERPOLATION_CRS), // Parameters of point motion operations PARAM_NAME_CODE(POINT_MOTION_VELOCITY_GRID_FILE), }; const ParamNameCode *getParamNameCodes(size_t &nElts) { nElts = sizeof(paramNameCodes) / sizeof(paramNameCodes[0]); return paramNameCodes; } static const ParamMapping paramUnitConversionScalar = { EPSG_NAME_PARAMETER_UNIT_CONVERSION_SCALAR, EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR, nullptr, common::UnitOfMeasure::Type::SCALE, nullptr}; static const ParamMapping *const paramsChangeVerticalUnit[] = { &paramUnitConversionScalar, nullptr}; static const ParamMapping paramLongitudeOffset = { EPSG_NAME_PARAMETER_LONGITUDE_OFFSET, EPSG_CODE_PARAMETER_LONGITUDE_OFFSET, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsLongitudeRotation[] = { &paramLongitudeOffset, nullptr}; static const ParamMapping paramA0 = { EPSG_NAME_PARAMETER_A0, EPSG_CODE_PARAMETER_A0, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramA1 = { EPSG_NAME_PARAMETER_A1, EPSG_CODE_PARAMETER_A1, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramA2 = { EPSG_NAME_PARAMETER_A2, EPSG_CODE_PARAMETER_A2, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramB0 = { EPSG_NAME_PARAMETER_B0, EPSG_CODE_PARAMETER_B0, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramB1 = { EPSG_NAME_PARAMETER_B1, EPSG_CODE_PARAMETER_B1, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramB2 = { EPSG_NAME_PARAMETER_B2, EPSG_CODE_PARAMETER_B2, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping *const paramsAffineParametricTransformation[] = { &paramA0, &paramA1, &paramA2, &paramB0, &paramB1, &paramB2, nullptr}; static const ParamMapping paramOrdinate1EvalPointTargetCRS = { EPSG_NAME_PARAMETER_ORDINATE_1_EVAL_POINT_TARGET_CRS, EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT_TARGET_CRS, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramOrdinate2EvalPointTargetCRS = { EPSG_NAME_PARAMETER_ORDINATE_2_EVAL_POINT_TARGET_CRS, EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT_TARGET_CRS, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramScaleFactorForSourceCRSAxes = { EPSG_NAME_PARAMETER_SCALE_FACTOR_FOR_SOURCE_CRS_AXES, EPSG_CODE_PARAMETER_SCALE_FACTOR_FOR_SOURCE_CRS_AXES, nullptr, common::UnitOfMeasure::Type::SCALE, nullptr}; static const ParamMapping paramRotationAngleOfSourceCRSAxes = { EPSG_NAME_PARAMETER_ROTATION_ANGLE_OF_SOURCE_CRS_AXES, EPSG_CODE_PARAMETER_ROTATION_ANGLE_OF_SOURCE_CRS_AXES, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsSimilarityTransformation[] = { &paramOrdinate1EvalPointTargetCRS, &paramOrdinate2EvalPointTargetCRS, &paramScaleFactorForSourceCRSAxes, &paramRotationAngleOfSourceCRSAxes, nullptr}; static const ParamMapping paramXTranslation = { EPSG_NAME_PARAMETER_X_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramYTranslation = { EPSG_NAME_PARAMETER_Y_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramZTranslation = { EPSG_NAME_PARAMETER_Z_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramXRotation = { EPSG_NAME_PARAMETER_X_AXIS_ROTATION, EPSG_CODE_PARAMETER_X_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramYRotation = { EPSG_NAME_PARAMETER_Y_AXIS_ROTATION, EPSG_CODE_PARAMETER_Y_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramZRotation = { EPSG_NAME_PARAMETER_Z_AXIS_ROTATION, EPSG_CODE_PARAMETER_Z_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramScaleDifference = { EPSG_NAME_PARAMETER_SCALE_DIFFERENCE, EPSG_CODE_PARAMETER_SCALE_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::SCALE, nullptr}; static const ParamMapping *const paramsHelmert3[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, nullptr}; static const ParamMapping *const paramsHelmert7[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramXRotation, &paramYRotation, &paramZRotation, &paramScaleDifference, nullptr}; static const ParamMapping paramRateXTranslation = { EPSG_NAME_PARAMETER_RATE_X_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateYTranslation = { EPSG_NAME_PARAMETER_RATE_Y_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateZTranslation = { EPSG_NAME_PARAMETER_RATE_Z_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateXRotation = { EPSG_NAME_PARAMETER_RATE_X_AXIS_ROTATION, EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateYRotation = { EPSG_NAME_PARAMETER_RATE_Y_AXIS_ROTATION, EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateZRotation = { EPSG_NAME_PARAMETER_RATE_Z_AXIS_ROTATION, EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateScaleDifference = { EPSG_NAME_PARAMETER_RATE_SCALE_DIFFERENCE, EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::SCALE, nullptr}; static const ParamMapping paramReferenceEpoch = { EPSG_NAME_PARAMETER_REFERENCE_EPOCH, EPSG_CODE_PARAMETER_REFERENCE_EPOCH, nullptr, common::UnitOfMeasure::Type::TIME, nullptr}; static const ParamMapping *const paramsHelmert15[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramXRotation, &paramYRotation, &paramZRotation, &paramScaleDifference, &paramRateXTranslation, &paramRateYTranslation, &paramRateZTranslation, &paramRateXRotation, &paramRateYRotation, &paramRateZRotation, &paramRateScaleDifference, &paramReferenceEpoch, nullptr}; static const ParamMapping paramOrdinate1EvalPoint = { EPSG_NAME_PARAMETER_ORDINATE_1_EVAL_POINT, EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramOrdinate2EvalPoint = { EPSG_NAME_PARAMETER_ORDINATE_2_EVAL_POINT, EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramOrdinate3EvalPoint = { EPSG_NAME_PARAMETER_ORDINATE_3_EVAL_POINT, EPSG_CODE_PARAMETER_ORDINATE_3_EVAL_POINT, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping *const paramsMolodenskyBadekas[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramXRotation, &paramYRotation, &paramZRotation, &paramScaleDifference, &paramOrdinate1EvalPoint, &paramOrdinate2EvalPoint, &paramOrdinate3EvalPoint, nullptr}; static const ParamMapping paramSemiMajorAxisDifference = { EPSG_NAME_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE, EPSG_CODE_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramFlatteningDifference = { EPSG_NAME_PARAMETER_FLATTENING_DIFFERENCE, EPSG_CODE_PARAMETER_FLATTENING_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsMolodensky[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramSemiMajorAxisDifference, &paramFlatteningDifference, nullptr}; static const ParamMapping paramLatitudeOffset = { EPSG_NAME_PARAMETER_LATITUDE_OFFSET, EPSG_CODE_PARAMETER_LATITUDE_OFFSET, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsGeographic2DOffsets[] = { &paramLatitudeOffset, &paramLongitudeOffset, nullptr}; static const ParamMapping paramGeoidUndulation = { EPSG_NAME_PARAMETER_GEOID_UNDULATION, EPSG_CODE_PARAMETER_GEOID_UNDULATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping *const paramsGeographic2DWithHeightOffsets[] = { &paramLatitudeOffset, &paramLongitudeOffset, &paramGeoidUndulation, nullptr}; static const ParamMapping paramVerticalOffset = { EPSG_NAME_PARAMETER_VERTICAL_OFFSET, EPSG_CODE_PARAMETER_VERTICAL_OFFSET, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping *const paramsGeographic3DOffsets[] = { &paramLatitudeOffset, &paramLongitudeOffset, &paramVerticalOffset, nullptr}; static const ParamMapping *const paramsVerticalOffsets[] = { &paramVerticalOffset, nullptr}; static const ParamMapping paramInclinationInLatitude = { EPSG_NAME_PARAMETER_INCLINATION_IN_LATITUDE, EPSG_CODE_PARAMETER_INCLINATION_IN_LATITUDE, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping paramInclinationInLongitude = { EPSG_NAME_PARAMETER_INCLINATION_IN_LONGITUDE, EPSG_CODE_PARAMETER_INCLINATION_IN_LONGITUDE, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsVerticalOffsetAndSlope[] = { &paramOrdinate1EvalPoint, &paramOrdinate2EvalPoint, &paramVerticalOffset, &paramInclinationInLatitude, &paramInclinationInLongitude, nullptr}; static const ParamMapping paramLatitudeLongitudeDifferenceFile = { EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsNTV2[] = { &paramLatitudeLongitudeDifferenceFile, nullptr}; static const ParamMapping paramGeocentricTranslationFile = { EPSG_NAME_PARAMETER_GEOCENTRIC_TRANSLATION_FILE, EPSG_CODE_PARAMETER_GEOCENTRIC_TRANSLATION_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsGeocentricTranslationGridInterpolationIGN[] = { &paramGeocentricTranslationFile, nullptr}; static const ParamMapping paramLatitudeDifferenceFile = { EPSG_NAME_PARAMETER_LATITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_DIFFERENCE_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping paramLongitudeDifferenceFile = { EPSG_NAME_PARAMETER_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LONGITUDE_DIFFERENCE_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsNADCON[] = { &paramLatitudeDifferenceFile, &paramLongitudeDifferenceFile, nullptr}; static const ParamMapping *const paramsNADCON5_2D[] = { &paramLatitudeDifferenceFile, &paramLongitudeDifferenceFile, nullptr}; static const ParamMapping paramEllipsoidalHeightDifference = { EPSG_NAME_PARAMETER_ELLIPSOIDAL_HEIGHT_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_DIFFERENCE_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsNADCON5_3D[] = { &paramLatitudeDifferenceFile, &paramLongitudeDifferenceFile, &paramEllipsoidalHeightDifference, nullptr}; static const ParamMapping paramVerticalOffsetFile = { EPSG_NAME_PARAMETER_VERTICAL_OFFSET_FILE, EPSG_CODE_PARAMETER_VERTICAL_OFFSET_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsVERTCON[] = {&paramVerticalOffsetFile, nullptr}; static const ParamMapping paramPointMotiionVelocityGridFile = { EPSG_NAME_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE, EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsPointMotionOperationByVelocityGrid[] = { &paramPointMotiionVelocityGridFile, nullptr}; static const ParamMapping paramSouthPoleLatGRIB = { PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LATITUDE_GRIB_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping paramSouthPoleLongGRIB = { PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LONGITUDE_GRIB_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping paramAxisRotationGRIB = { PROJ_WKT2_NAME_PARAMETER_AXIS_ROTATION_GRIB_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsPoleRotationGRIBConvention[] = { &paramSouthPoleLatGRIB, &paramSouthPoleLongGRIB, &paramAxisRotationGRIB, nullptr}; static const ParamMapping paramGridNorthPoleLatitudeNetCDF = { PROJ_WKT2_NAME_PARAMETER_GRID_NORTH_POLE_LATITUDE_NETCDF_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping paramGridNorthPoleLongitudeNetCDF = { PROJ_WKT2_NAME_PARAMETER_GRID_NORTH_POLE_LONGITUDE_NETCDF_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping paramNorthPoleGridLongitudeNetCDF = { PROJ_WKT2_NAME_PARAMETER_NORTH_POLE_GRID_LONGITUDE_NETCDF_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsPoleRotationNetCDFCFConvention[] = { &paramGridNorthPoleLatitudeNetCDF, &paramGridNorthPoleLongitudeNetCDF, &paramNorthPoleGridLongitudeNetCDF, nullptr}; static const MethodMapping otherMethodMappings[] = { {EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT, EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT, nullptr, nullptr, nullptr, paramsChangeVerticalUnit}, {EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR, EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_HEIGHT_DEPTH_REVERSAL, EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_AXIS_ORDER_REVERSAL_2D, EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_2D, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_AXIS_ORDER_REVERSAL_3D, EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_3D, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC, EPSG_CODE_METHOD_GEOGRAPHIC_GEOCENTRIC, nullptr, nullptr, nullptr, nullptr}, {PROJ_WKT2_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC_LATITUDE, 0, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_LONGITUDE_ROTATION, EPSG_CODE_METHOD_LONGITUDE_ROTATION, nullptr, nullptr, nullptr, paramsLongitudeRotation}, {EPSG_NAME_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION, EPSG_CODE_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION, nullptr, nullptr, nullptr, paramsAffineParametricTransformation}, {EPSG_NAME_METHOD_SIMILARITY_TRANSFORMATION, EPSG_CODE_METHOD_SIMILARITY_TRANSFORMATION, nullptr, nullptr, nullptr, paramsSimilarityTransformation}, {PROJ_WKT2_NAME_METHOD_POLE_ROTATION_GRIB_CONVENTION, 0, nullptr, nullptr, nullptr, paramsPoleRotationGRIBConvention}, {PROJ_WKT2_NAME_METHOD_POLE_ROTATION_NETCDF_CF_CONVENTION, 0, nullptr, nullptr, nullptr, paramsPoleRotationNetCDFCFConvention}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert3}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert3}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert3}, {EPSG_NAME_METHOD_COORDINATE_FRAME_GEOCENTRIC, EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D, EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D, EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_POSITION_VECTOR_GEOCENTRIC, EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D, EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D, EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC, EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D, EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D, EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC, EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D, EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D, EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOCENTRIC, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOCENTRIC, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY, EPSG_CODE_METHOD_MOLODENSKY, nullptr, nullptr, nullptr, paramsMolodensky}, {EPSG_NAME_METHOD_ABRIDGED_MOLODENSKY, EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY, nullptr, nullptr, nullptr, paramsMolodensky}, {EPSG_NAME_METHOD_GEOGRAPHIC2D_OFFSETS, EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS, nullptr, nullptr, nullptr, paramsGeographic2DOffsets}, {EPSG_NAME_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS, EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS, nullptr, nullptr, nullptr, paramsGeographic2DWithHeightOffsets}, {EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSETS, EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS, nullptr, nullptr, nullptr, paramsGeographic3DOffsets}, {EPSG_NAME_METHOD_VERTICAL_OFFSET, EPSG_CODE_METHOD_VERTICAL_OFFSET, nullptr, nullptr, nullptr, paramsVerticalOffsets}, {EPSG_NAME_METHOD_VERTICAL_OFFSET_AND_SLOPE, EPSG_CODE_METHOD_VERTICAL_OFFSET_AND_SLOPE, nullptr, nullptr, nullptr, paramsVerticalOffsetAndSlope}, {EPSG_NAME_METHOD_NTV2, EPSG_CODE_METHOD_NTV2, nullptr, nullptr, nullptr, paramsNTV2}, {EPSG_NAME_METHOD_NTV1, EPSG_CODE_METHOD_NTV1, nullptr, nullptr, nullptr, paramsNTV2}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN, nullptr, nullptr, nullptr, paramsGeocentricTranslationGridInterpolationIGN}, {EPSG_NAME_METHOD_NADCON, EPSG_CODE_METHOD_NADCON, nullptr, nullptr, nullptr, paramsNADCON}, {EPSG_NAME_METHOD_NADCON5_2D, EPSG_CODE_METHOD_NADCON5_2D, nullptr, nullptr, nullptr, paramsNADCON5_2D}, {EPSG_NAME_METHOD_NADCON5_3D, EPSG_CODE_METHOD_NADCON5_3D, nullptr, nullptr, nullptr, paramsNADCON5_3D}, {EPSG_NAME_METHOD_VERTCON, EPSG_CODE_METHOD_VERTCON, nullptr, nullptr, nullptr, paramsVERTCON}, {EPSG_NAME_METHOD_VERTCON_OLDNAME, EPSG_CODE_METHOD_VERTCON, nullptr, nullptr, nullptr, paramsVERTCON}, {EPSG_NAME_METHOD_POINT_MOTION_BY_GRID_CANADA_NTV2_VEL, EPSG_CODE_METHOD_POINT_MOTION_BY_GRID_CANADA_NTV2_VEL, nullptr, nullptr, nullptr, paramsPointMotionOperationByVelocityGrid}, }; const MethodMapping *getOtherMethodMappings(size_t &nElts) { nElts = sizeof(otherMethodMappings) / sizeof(otherMethodMappings[0]); return otherMethodMappings; } // --------------------------------------------------------------------------- PROJ_NO_INLINE const MethodMapping *getMapping(int epsg_code) noexcept { for (const auto &mapping : projectionMethodMappings) { if (mapping.epsg_code == epsg_code) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- const MethodMapping *getMapping(const OperationMethod *method) noexcept { const std::string &name(method->nameStr()); const int epsg_code = method->getEPSGCode(); for (const auto &mapping : projectionMethodMappings) { if ((epsg_code != 0 && mapping.epsg_code == epsg_code) || metadata::Identifier::isEquivalentName(mapping.wkt2_name, name.c_str())) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- const MethodMapping *getMappingFromWKT1(const std::string &wkt1_name) noexcept { // Unusual for a WKT1 projection name, but mentioned in OGC 12-063r5 C.4.2 if (ci_starts_with(wkt1_name, "UTM zone")) { return getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR); } for (const auto &mapping : projectionMethodMappings) { if (mapping.wkt1_name && metadata::Identifier::isEquivalentName( mapping.wkt1_name, wkt1_name.c_str())) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- const MethodMapping *getMapping(const char *wkt2_name) noexcept { for (const auto &mapping : projectionMethodMappings) { if (metadata::Identifier::isEquivalentName(mapping.wkt2_name, wkt2_name)) { return &mapping; } } for (const auto &mapping : otherMethodMappings) { if (metadata::Identifier::isEquivalentName(mapping.wkt2_name, wkt2_name)) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- std::vector<const MethodMapping *> getMappingsFromPROJName(const std::string &projName) { std::vector<const MethodMapping *> res; for (const auto &mapping : projectionMethodMappings) { if (mapping.proj_name_main && projName == mapping.proj_name_main) { res.push_back(&mapping); } } return res; } // --------------------------------------------------------------------------- const ParamMapping *getMapping(const MethodMapping *mapping, const OperationParameterNNPtr &param) { if (mapping->params == nullptr) { return nullptr; } // First try with id const int epsg_code = param->getEPSGCode(); if (epsg_code) { for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (paramMapping->epsg_code == epsg_code) { return paramMapping; } } } // then equivalent name const std::string &name = param->nameStr(); for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (metadata::Identifier::isEquivalentName(paramMapping->wkt2_name, name.c_str())) { return paramMapping; } } // and finally different name, but equivalent parameter for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (areEquivalentParameters(paramMapping->wkt2_name, name)) { return paramMapping; } } return nullptr; } // --------------------------------------------------------------------------- const ParamMapping *getMappingFromWKT1(const MethodMapping *mapping, const std::string &wkt1_name) { for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (paramMapping->wkt1_name && (metadata::Identifier::isEquivalentName(paramMapping->wkt1_name, wkt1_name.c_str()) || areEquivalentParameters(paramMapping->wkt1_name, wkt1_name))) { return paramMapping; } } return nullptr; } //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/apps/optargpm.h
/*********************************************************************** OPTARGPM - a header-only library for decoding PROJ.4 style command line options Thomas Knudsen, 2017-09-10 ************************************************************************ For PROJ.4 command line programs, we have a somewhat complex option decoding situation, since we have to navigate in a cocktail of classic single letter style options, prefixed by "-", GNU style long options prefixed by "--", transformation specification elements prefixed by "+", and input file names prefixed by "" (i.e. nothing). Hence, classic getopt.h style decoding does not cut the mustard, so this is an attempt to catch up and chop the ketchup. Since optargpm (for "optarg plus minus") does not belong, in any obvious way, in any systems development library, it is provided as a "header only" library. While this is conventional in C++, it is frowned at in plain C. But frown away - "header only" has its places, and this is one of them. By convention, we expect a command line to consist of the following elements: <operator/program name> [short ("-")/long ("--") options} [operator ("+") specs] [operands/input files] or less verbose: <operator> [options] [operator specs] [operands] or less abstract: proj -I --output=foo +proj=utm +zone=32 +ellps=GRS80 bar baz... Where Operator is proj Options are -I --output=foo Operator specs are +proj=utm +zone=32 +ellps=GRS80 Operands are bar baz While neither claiming to save the world, nor to hint at the "shape of jazz to come", at least optargpm has shown useful in constructing cs2cs style transformation filters. Supporting a wide range of option syntax, the getoptpm API is somewhat quirky, but also compact, consisting of one data type, 3(+2) functions, and one enumeration: OPTARGS Housekeeping data type. An instance of OPTARGS is conventionally called o or opt opt_parse (opt, argc, argv ...): The work horse: Define supported options; Split (argc, argv) into groups (options, op specs, operands); Parse option arguments. opt_given (o, option): The number of times <option> was given on the command line. (i.e. 0 if not given or option unsupported) opt_arg (o, option): A char pointer to the argument for <option> An additional function "opt_input_loop" implements a "read all operands sequentially" functionality, eliminating the need to handle open/close of a sequence of input files: enum OPTARGS_FILE_MODE: indicates whether to read operands in text (0) or binary (1) mode opt_input_loop (o, mode): When used as condition in a while loop, traverses all operands, giving the impression of reading just a single input file. Usage is probably easiest understood by a brief textbook style example: Consider a simple program taking the conventional "-v, -h, -o" options indicating "verbose output", "help please", and "output file specification", respectively. The "-v" and "-h" options are *flags*, taking no arguments, while the "-o" option is a *key*, taking a *value* argument, representing the output file name. The short options have long aliases: "--verbose", "--help" and "--output". Additionally, the long key "--hello", without any short counterpart, is supported. ------------------------------------------------------------------------------- int main(int argc, char **argv) { PJ *P; OPTARGS *o; FILE *out = stdout; char *longflags[] = {"v=verbose", "h=help", 0}; char *longkeys[] = {"o=output", "hello", 0}; o = opt_parse (argc, argv, "hv", "o", longflags, longkeys); if (nullptr==o) return nullptr; if (opt_given (o, "h")) { printf ("Usage: %s [-v|--verbose] [-h|--help] [-o|--output <filename>] [--hello=<name>] infile...", o->progname); exit (0); } if (opt_given (o, "v")) puts ("Feeling chatty today?"); if (opt_given (o, "hello")) { printf ("Hello, %s!\n", opt_arg(o, "hello")); exit (0); } if (opt_given (o, "o")) out = fopen (opt_arg (o, "output"), "rt"); // Note: "output" translates to "o" internally // Setup transformation P = proj_create_argv (0, o->pargc, o->pargv); // Loop over all lines of all input files while (opt_input_loop (o, optargs_file_format_text)) { char buf[1000]; int ret = fgets (buf, 1000, o->input); if (opt_eof (o)) { continue; } if (nullptr==ret) { fprintf (stderr, "Read error in record %d\n", (int) o->record_index); continue; } do_what_needs_to_be_done (buf); } return nullptr; } ------------------------------------------------------------------------------- Note how short aliases for longflags and longkeys are defined by prefixing an "o=", "h=" or "v=", respectively. This also means that it is possible to have more than one alias for each short option, e.g. longkeys = {"o=output", "o=banana", 0} would define both "--output" and "--banana" to be aliases for "-o". ************************************************************************ Thomas Knudsen, [email protected], 2016-05-25/2017-09-10 ************************************************************************ * Copyright (c) 2016, 2017 Thomas Knudsen * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ***********************************************************************/ #include <ctype.h> #include <errno.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /**************************************************************************************************/ struct OPTARGS; typedef struct OPTARGS OPTARGS; enum OPTARGS_FILE_FORMAT { optargs_file_format_text = 0, optargs_file_format_binary = 1 }; char *opt_filename(OPTARGS *opt); static int opt_eof(OPTARGS *opt); int opt_record(OPTARGS *opt); int opt_input_loop(OPTARGS *opt, int binary); static int opt_is_flag(OPTARGS *opt, int ordinal); static int opt_raise_flag(OPTARGS *opt, int ordinal); static int opt_ordinal(OPTARGS *opt, const char *option); int opt_given(OPTARGS *opt, const char *option); char *opt_arg(OPTARGS *opt, const char *option); const char *opt_strip_path(const char *full_name); OPTARGS *opt_parse(int argc, char **argv, const char *flags, const char *keys, const char **longflags, const char **longkeys); /**************************************************************************************************/ struct OPTARGS { int argc, margc, pargc, fargc; char **argv, **margv, **pargv, **fargv; FILE *input; int input_index; int record_index; const char *progname; /* argv[0], stripped from /path/to, if present */ char flaglevel[21]; /* if flag -f is specified n times, its optarg pointer is set to flaglevel + n */ char *optarg[256]; /* optarg[(int) 'f'] holds a pointer to the argument of option "-f" */ char *flags; /* a list of flag style options supported, e.g. "hv" (help and verbose) */ char *keys; /* a list of key/value style options supported, e.g. "o" (output) */ const char * *longflags; /* long flags, {"help", "verbose"}, or {"h=help", "v=verbose"}, to indicate homologous short options */ const char * *longkeys; /* e.g. {"output"} or {o=output"} to support --output=/path/to/output-file. In the latter case, */ /* all operations on "--output" gets redirected to "-o", so user code need * handle arguments to "-o" only */ }; /* name of file currently read from */ char *opt_filename(OPTARGS *opt) { if (nullptr == opt) return nullptr; if (0 == opt->fargc) return opt->flaglevel; return opt->fargv[opt->input_index]; } static int opt_eof(OPTARGS *opt) { if (nullptr == opt) return 1; return feof(opt->input); } /* record number of most recently read record */ int opt_record(OPTARGS *opt) { if (nullptr == opt) return 0; return opt->record_index + 1; } /* handle closing/opening of a "stream-of-streams" */ int opt_input_loop(OPTARGS *opt, int binary) { if (nullptr == opt) return 0; /* most common case: increment record index and read on */ if ((opt->input != nullptr) && !feof(opt->input)) { opt->record_index++; return 1; } opt->record_index = 0; /* no input files specified - read from stdin */ if ((0 == opt->fargc) && (nullptr == opt->input)) { opt->input = stdin; return 1; } /* if we're here, we have either reached eof on current input file. */ /* or not yet opened a file. If eof on stdin, we're done */ if (opt->input == stdin) return 0; /* end if no more input */ if (nullptr != opt->input) fclose(opt->input); if (opt->input_index >= opt->fargc) return 0; /* otherwise, open next input file */ opt->input = fopen(opt->fargv[opt->input_index++], binary ? "rb" : "rt"); if (nullptr != opt->input) return 1; /* ignore non-existing files - go on! */ return opt_input_loop(opt, binary); } /* return true if option with given ordinal is a flag, false if undefined or * key=value */ static int opt_is_flag(OPTARGS *opt, int ordinal) { if (opt->optarg[ordinal] < opt->flaglevel) return 0; if (opt->optarg[ordinal] > opt->flaglevel + 20) return 0; return 1; } static int opt_raise_flag(OPTARGS *opt, int ordinal) { if (opt->optarg[ordinal] < opt->flaglevel) return 1; if (opt->optarg[ordinal] > opt->flaglevel + 20) return 1; /* Max out at 20 */ if (opt->optarg[ordinal] == opt->flaglevel + 20) return 0; opt->optarg[ordinal]++; return 0; } /* Find the ordinal value of any (short or long) option */ static int opt_ordinal(OPTARGS *opt, const char *option) { int i; if (nullptr == opt) return 0; if (nullptr == option) return 0; if (0 == option[0]) return 0; /* An ordinary -o style short option */ if (strlen(option) == 1) { /* Undefined option? */ if (nullptr == opt->optarg[(int)option[0]]) return 0; return (int)option[0]; } /* --longname style long options are slightly harder */ for (i = 0; i < 64; i++) { const char **f = opt->longflags; if (nullptr == f) break; if (nullptr == f[i]) break; if (0 == strcmp(f[i], "END")) break; if (0 == strcmp(f[i], option)) return 128 + i; /* long alias? - return ordinal for corresponding short */ if ((strlen(f[i]) > 2) && (f[i][1] == '=') && (0 == strcmp(f[i] + 2, option))) { /* Undefined option? */ if (nullptr == opt->optarg[(int)f[i][0]]) return 0; return (int)f[i][0]; } } for (i = 0; i < 64; i++) { const char **v = opt->longkeys; if (nullptr == v) return 0; if (nullptr == v[i]) return 0; if (0 == strcmp(v[i], "END")) return 0; if (0 == strcmp(v[i], option)) return 192 + i; /* long alias? - return ordinal for corresponding short */ if ((strlen(v[i]) > 2) && (v[i][1] == '=') && (0 == strcmp(v[i] + 2, option))) { /* Undefined option? */ if (nullptr == opt->optarg[(int)v[i][0]]) return 0; return (int)v[i][0]; } } /* kill some potential compiler warnings about unused functions */ (void)opt_eof(nullptr); return 0; } /* Returns 0 if option was not given on command line, non-0 otherwise */ int opt_given(OPTARGS *opt, const char *option) { int ordinal = opt_ordinal(opt, option); if (0 == ordinal) return 0; /* For flags we return the number of times the flag was specified (mostly * for repeated -v(erbose) flags) */ if (opt_is_flag(opt, ordinal)) return (int)(opt->optarg[ordinal] - opt->flaglevel); return opt->argv[0] != opt->optarg[ordinal]; } /* Returns the argument to a given option */ char *opt_arg(OPTARGS *opt, const char *option) { int ordinal = opt_ordinal(opt, option); if (0 == ordinal) return nullptr; return opt->optarg[ordinal]; } const char *opt_strip_path(const char *full_name) { const char *last_path_delim, *stripped_name = full_name; last_path_delim = strrchr(stripped_name, '\\'); if (last_path_delim > stripped_name) stripped_name = last_path_delim + 1; last_path_delim = strrchr(stripped_name, '/'); if (last_path_delim > stripped_name) stripped_name = last_path_delim + 1; return stripped_name; } /* split command line options into options/flags ("-" style), projdefs ("+" * style) and input file args */ OPTARGS *opt_parse(int argc, char **argv, const char *flags, const char *keys, const char **longflags, const char **longkeys) { int i, j; int free_format; OPTARGS *o; if (argc == 0) return nullptr; o = (OPTARGS *)calloc(1, sizeof(OPTARGS)); if (nullptr == o) return nullptr; o->argc = argc; o->argv = argv; o->progname = opt_strip_path(argv[0]); /* Reset all flags */ for (i = 0; i < (int)strlen(flags); i++) o->optarg[(int)flags[i]] = o->flaglevel; /* Flag args for all argument taking options as "unset" */ for (i = 0; i < (int)strlen(keys); i++) o->optarg[(int)keys[i]] = argv[0]; /* Hence, undefined/illegal options have an argument of 0 */ /* long opts are handled similarly, but are mapped to the high bit character * range (above 128) */ o->longflags = longflags; o->longkeys = longkeys; /* check aliases, An end user should never experience this, but */ /* the developer should make sure that aliases are valid */ for (i = 0; longflags && longflags[i]; i++) { /* Go on if it does not look like an alias */ if (strlen(longflags[i]) < 3) continue; if ('=' != longflags[i][1]) continue; if (nullptr == strchr(flags, longflags[i][0])) { fprintf(stderr, "%s: Invalid alias - '%s'. Valid short flags are '%s'\n", o->progname, longflags[i], flags); free(o); return nullptr; } } for (i = 0; longkeys && longkeys[i]; i++) { /* Go on if it does not look like an alias */ if (strlen(longkeys[i]) < 3) continue; if ('=' != longkeys[i][1]) continue; if (nullptr == strchr(keys, longkeys[i][0])) { fprintf(stderr, "%s: Invalid alias - '%s'. Valid short flags are '%s'\n", o->progname, longkeys[i], keys); free(o); return nullptr; } } /* aside from counting the number of times a flag has been specified, we * also abuse the */ /* flaglevel array to provide a pseudo-filename for the case of reading from * stdin */ strcpy(o->flaglevel, "<stdin>"); for (i = 128; (longflags != nullptr) && (longflags[i - 128] != nullptr); i++) { if (i == 192) { free(o); fprintf(stderr, "Too many flag style long options\n"); return nullptr; } o->optarg[i] = o->flaglevel; } for (i = 192; (longkeys != nullptr) && (longkeys[i - 192] != nullptr); i++) { if (i == 256) { free(o); fprintf(stderr, "Too many value style long options\n"); return nullptr; } o->optarg[i] = argv[0]; } /* Now, set up the agrc/argv pairs, and interpret args */ o->argc = argc; o->argv = argv; /* Process all '-' and '--'-style options */ for (i = 1; i < argc; i++) { int arg_group_size = (int)strlen(argv[i]); if ('-' != argv[i][0]) break; if (nullptr == o->margv) o->margv = argv + i; o->margc++; for (j = 1; j < arg_group_size; j++) { int c = argv[i][j]; char cstring[2], *crepr = cstring; cstring[0] = (char)c; cstring[1] = 0; /* Long style flags and options (--long_opt_name, --long_opt_namr * arg, * --long_opt_name=arg) */ if (c == (int)'-') { char *equals; crepr = argv[i] + 2; /* We need to manipulate a bit to support gnu style --foo=bar * syntax. */ /* NOTE: This will segfault for read-only (const char * style) * storage, */ /* but since the canonical use case, int main (int argc, char * **argv), */ /* is non-const, we ignore this for now */ equals = strchr(crepr, '='); if (equals) *equals = 0; c = opt_ordinal(o, crepr); if (0 == c) { fprintf(stderr, "Invalid option \"%s\"\n", crepr); free(o); return nullptr; } /* inline (gnu) --foo=bar style arg */ if (equals) { *equals = '='; if (opt_is_flag(o, c)) { fprintf(stderr, "Option \"%s\" takes no arguments\n", crepr); free(o); return nullptr; } o->optarg[c] = equals + 1; break; } /* "outline" --foo bar style arg */ if (!opt_is_flag(o, c)) { if ((argc == i + 1) || ('+' == argv[i + 1][0]) || ('-' == argv[i + 1][0])) { fprintf(stderr, "Missing argument for option \"%s\"\n", crepr); free(o); return nullptr; } o->optarg[c] = argv[i + 1]; i++; /* eat the arg */ break; } if (!opt_is_flag(o, c)) { fprintf(stderr, "Expected flag style long option here, but got " "\"%s\"\n", crepr); free(o); return nullptr; } /* Flag style option, i.e. taking no arguments */ opt_raise_flag(o, c); break; } /* classic short options */ if (nullptr == o->optarg[c]) { fprintf(stderr, "Invalid option \"%s\"\n", crepr); free(o); return nullptr; } /* Flag style option, i.e. taking no arguments */ if (opt_is_flag(o, c)) { opt_raise_flag(o, c); continue; } /* options taking arguments */ /* argument separate (i.e. "-i 10") */ if (j + 1 == arg_group_size) { if ((argc == i + 1) || ('+' == argv[i + 1][0]) || ('-' == argv[i + 1][0])) { fprintf(stderr, "Bad or missing arg for option \"%s\"\n", crepr); free(o); return nullptr; } o->optarg[(int)c] = argv[i + 1]; i++; break; } /* Option arg inline (i.e. "-i10") */ o->optarg[c] = argv[i] + j + 1; break; } } /* Process all '+'-style options, starting from where '-'-style processing * ended */ o->pargv = argv + i; /* Is free format in use, instead of plus-style? */ free_format = 0; for (j = 1; j < argc; j++) { if (0 == strcmp("--", argv[j])) { free_format = j; break; } } if (free_format) { o->pargc = free_format - (o->margc + 1); o->fargc = argc - (free_format + 1); if (0 != o->fargc) o->fargv = argv + free_format + 1; return o; } for (/* empty */; i < argc; i++) { if ('-' == argv[i][0]) { free(o); fprintf(stderr, "+ and - style options must not be mixed\n"); return nullptr; } if ('+' != argv[i][0]) break; o->pargc++; } /* Handle input file names */ o->fargc = argc - i; if (0 != o->fargc) o->fargv = argv + i; return o; }
h
PROJ
data/projects/PROJ/src/apps/cct.cpp
/*********************************************************************** The cct 4D Transformation program ************************************************************************ cct is a 4D equivalent to the "proj" projection program. cct is an acronym meaning "Coordinate Conversion and Transformation". The acronym refers to definitions given in the OGC 08-015r2/ISO-19111 standard "Geographical Information -- Spatial Referencing by Coordinates", which defines two different classes of coordinate operations: *Coordinate Conversions*, which are coordinate operations where input and output datum are identical (e.g. conversion from geographical to cartesian coordinates) and *Coordinate Transformations*, which are coordinate operations where input and output datums differ (e.g. change of reference frame). cct, however, also refers to Carl Christian Tscherning (1942--2014), professor of Geodesy at the University of Copenhagen, mentor and advisor for a generation of Danish geodesists, colleague and collaborator for two generations of global geodesists, Secretary General for the International Association of Geodesy, IAG (1995--2007), fellow of the American Geophysical Union (1991), recipient of the IAG Levallois Medal (2007), the European Geosciences Union Vening Meinesz Medal (2008), and of numerous other honours. cct, or Christian, as he was known to most of us, was recognized for his good mood, his sharp wit, his tireless work, and his great commitment to the development of geodesy - both through his scientific contributions, comprising more than 250 publications, and by his mentoring and teaching of the next generations of geodesists. As Christian was an avid Fortran programmer, and a keen Unix connoisseur, he would have enjoyed to know that his initials would be used to name a modest Unix style transformation filter, hinting at the tireless aspect of his personality, which was certainly one of the reasons he accomplished so much, and meant so much to so many people. Hence, in honour of cct (the geodesist) this is cct (the program). ************************************************************************ Thomas Knudsen, [email protected], 2016-05-25/2017-10-26 ************************************************************************ * Copyright (c) 2016, 2017 Thomas Knudsen * Copyright (c) 2017, SDFE * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ***********************************************************************/ #include <ctype.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #include <fstream> // std::ifstream #include <iostream> #include "optargpm.h" #include "proj.h" #include "proj_internal.h" #include "proj_strtod.h" static void logger(void *data, int level, const char *msg); static void print(PJ_LOG_LEVEL log_level, const char *fmt, ...); /* Prototypes from functions in this file */ static const char *column(const char *buf, int n); static char *column(char *buf, int n); PJ_COORD parse_input_line(const char *buf, int *columns, double fixed_height, double fixed_time); static const char usage[] = { "--------------------------------------------------------------------------" "------\n" "Usage: %s [-options]... [+operator_specs]... infile...\n" "--------------------------------------------------------------------------" "------\n" "Options:\n" "--------------------------------------------------------------------------" "------\n" " -c x,y,z,t Specify input columns for (up to) 4 input " "parameters.\n" " Defaults to 1,2,3,4\n" " -d n Specify number of decimals in output.\n" " -I Do the inverse transformation\n" " -o /path/to/file Specify output file name\n" " -t value Provide a fixed t value for all input data (e.g. -t " "0)\n" " -z value Provide a fixed z value for all input data (e.g. -z " "0)\n" " -s n Skip n first lines of a infile\n" " -v Verbose: Provide non-essential informational " "output.\n" " Repeat -v for more verbosity (e.g. -vv)\n" "--------------------------------------------------------------------------" "------\n" "Long Options:\n" "--------------------------------------------------------------------------" "------\n" " --output Alias for -o\n" " --columns Alias for -c\n" " --decimals Alias for -d\n" " --height Alias for -z\n" " --time Alias for -t\n" " --verbose Alias for -v\n" " --inverse Alias for -I\n" " --skip-lines Alias for -s\n" " --help Alias for -h\n" " --version Print version number\n" "--------------------------------------------------------------------------" "------\n" "Operator Specs:\n" "--------------------------------------------------------------------------" "------\n" "The operator specs describe the action to be performed by cct, e.g:\n" "\n" " +proj=utm +ellps=GRS80 +zone=32\n" "\n" "instructs cct to convert input data to Universal Transverse Mercator, " "zone 32\n" "coordinates, based on the GRS80 ellipsoid.\n" "\n" "Hence, the command\n" "\n" " echo 12 55 | cct -z0 -t0 +proj=utm +zone=32 +ellps=GRS80\n" "\n" "Should give results comparable to the classic proj command\n" "\n" " echo 12 55 | proj +proj=utm +zone=32 +ellps=GRS80\n" "--------------------------------------------------------------------------" "------\n" "Examples:\n" "--------------------------------------------------------------------------" "------\n" "1. convert geographical input to UTM zone 32 on the GRS80 ellipsoid:\n" " cct +proj=utm +ellps=GRS80 +zone=32\n" "2. roundtrip accuracy check for the case above:\n" " cct +proj=pipeline +proj=utm +ellps=GRS80 +zone=32 +step +step +inv\n" "3. as (1) but specify input columns for longitude, latitude, height and " "time:\n" " cct -c 5,2,1,4 +proj=utm +ellps=GRS80 +zone=32\n" "4. as (1) but specify fixed height and time, hence needing only 2 cols in " "input:\n" " cct -t 0 -z 0 +proj=utm +ellps=GRS80 +zone=32\n" "--------------------------------------------------------------------------" "------\n"}; static void logger(void *data, int level, const char *msg) { FILE *stream; int log_tell = proj_log_level(PJ_DEFAULT_CTX, PJ_LOG_TELL); stream = (FILE *)data; /* if we use PJ_LOG_NONE we always want to print stuff to stream */ if (level == PJ_LOG_NONE) { fprintf(stream, "%s\n", msg); return; } /* otherwise only print if log level set by user is high enough or error */ if (level <= log_tell || level == PJ_LOG_ERROR) fprintf(stderr, "%s\n", msg); } FILE *fout; static void print(PJ_LOG_LEVEL log_level, const char *fmt, ...) { va_list args; char *msg_buf; va_start(args, fmt); const size_t msg_buf_size = 100000; msg_buf = (char *)malloc(msg_buf_size); if (msg_buf == nullptr) { va_end(args); return; } vsnprintf(msg_buf, msg_buf_size, fmt, args); logger((void *)fout, log_level, msg_buf); va_end(args); free(msg_buf); } int main(int argc, char **argv) { PJ *P = nullptr; PJ_COORD point; PJ_PROJ_INFO info; OPTARGS *o; char blank_comment[] = ""; char whitespace[] = " "; int i, nfields = 4, skip_lines = 0, verbose; double fixed_z = HUGE_VAL, fixed_time = HUGE_VAL; int decimals_angles = 10; int decimals_distances = 4; int columns_xyzt[] = {1, 2, 3, 4}; const char *longflags[] = {"v=verbose", "h=help", "I=inverse", "version", nullptr}; const char *longkeys[] = {"o=output", "c=columns", "d=decimals", "z=height", "t=time", "s=skip-lines", nullptr}; fout = stdout; pj_stderr_proj_lib_deprecation_warning(); /* coverity[tainted_data] */ o = opt_parse(argc, argv, "hvI", "cdozts", longflags, longkeys); if (nullptr == o) return 0; if (opt_given(o, "h") || argc == 1) { printf(usage, o->progname); return 0; } PJ_DIRECTION direction = opt_given(o, "I") ? PJ_INV : PJ_FWD; verbose = std::min(opt_given(o, "v"), 3); /* log level can't be larger than 3 */ if (verbose > 0) { proj_log_level(PJ_DEFAULT_CTX, static_cast<PJ_LOG_LEVEL>(verbose)); } proj_log_func(PJ_DEFAULT_CTX, (void *)fout, logger); if (opt_given(o, "version")) { print(PJ_LOG_NONE, "%s: %s", o->progname, pj_get_release()); return 0; } if (opt_given(o, "o")) fout = fopen(opt_arg(o, "output"), "wt"); if (nullptr == fout) { print(PJ_LOG_ERROR, "%s: Cannot open '%s' for output", o->progname, opt_arg(o, "output")); free(o); return 1; } print(PJ_LOG_TRACE, "%s: Running in very verbose mode", o->progname); if (opt_given(o, "z")) { fixed_z = proj_atof(opt_arg(o, "z")); nfields--; } if (opt_given(o, "t")) { fixed_time = proj_atof(opt_arg(o, "t")); nfields--; } if (opt_given(o, "d")) { int dec = atoi(opt_arg(o, "d")); decimals_angles = dec; decimals_distances = dec; } if (opt_given(o, "s")) { skip_lines = atoi(opt_arg(o, "s")); } if (opt_given(o, "c")) { int ncols; /* reset column numbers to ease comment output later on */ for (i = 0; i < 4; i++) columns_xyzt[i] = 0; /* cppcheck-suppress invalidscanf */ ncols = sscanf(opt_arg(o, "c"), "%d,%d,%d,%d", columns_xyzt, columns_xyzt + 1, columns_xyzt + 2, columns_xyzt + 3); if (ncols != nfields) { print(PJ_LOG_ERROR, "%s: Too few input columns given: '%s'", o->progname, opt_arg(o, "c")); free(o); if (stdout != fout) fclose(fout); return 1; } } /* Setup transformation */ if (o->pargc == 0 && o->fargc > 0) { std::string input(o->fargv[0]); if (!input.empty() && input[0] == '@') { std::ifstream fs; auto filename = input.substr(1); fs.open(filename, std::fstream::in | std::fstream::binary); if (!fs.is_open()) { std::cerr << "cannot open " << filename << std::endl; std::exit(1); } input.clear(); while (!fs.eof()) { char buffer[256]; fs.read(buffer, sizeof(buffer)); input.append(buffer, static_cast<size_t>(fs.gcount())); if (input.size() > 100 * 1000) { fs.close(); std::cerr << "too big file " << filename << std::endl; std::exit(1); } } fs.close(); } /* Assume we got a auth:code combination */ auto n = input.find(":"); if (n > 0) { std::string auth = input.substr(0, n); std::string code = input.substr(n + 1, input.length()); // Check that the authority matches one of the known ones auto authorityList = proj_get_authorities_from_database(nullptr); if (authorityList) { for (auto iter = authorityList; *iter; iter++) { if (*iter == auth) { P = proj_create_from_database( nullptr, auth.c_str(), code.c_str(), PJ_CATEGORY_COORDINATE_OPERATION, 0, nullptr); break; } } proj_string_list_destroy(authorityList); } } if (P == nullptr) { /* if we didn't get a auth:code combo we try to see if the input * matches */ /* anything else */ P = proj_create(nullptr, input.c_str()); if (P) { const auto type = proj_get_type(P); switch (type) { case PJ_TYPE_CONVERSION: case PJ_TYPE_TRANSFORMATION: case PJ_TYPE_CONCATENATED_OPERATION: case PJ_TYPE_OTHER_COORDINATE_OPERATION: // ok; break; default: print(PJ_LOG_ERROR, "%s: Input object is not a coordinate operation%s.", o->progname, proj_is_crs(P) ? ", but a CRS" : ""); free(o); proj_destroy(P); if (stdout != fout) fclose(fout); return 1; } } } /* If instantiating operation without +-options optargpm thinks the * input is */ /* a file, hence we move all o->fargv entries one place closer to the * start */ /* of the array. This effectively overwrites the input and only leaves a * list */ /* of files in o->fargv. */ o->fargc = o->fargc - 1; for (int j = 0; j < o->fargc; j++) { o->fargv[j] = o->fargv[j + 1]; } } else { P = proj_create_argv(nullptr, o->pargc, o->pargv); } if (nullptr == P) { print(PJ_LOG_ERROR, "%s: Bad transformation arguments - (%s)\n '%s -h' for help", o->progname, proj_errno_string(proj_errno(P)), o->progname); free(o); if (stdout != fout) fclose(fout); return 1; } info = proj_pj_info(P); print(PJ_LOG_TRACE, "Final: %s argc=%d pargc=%d", info.definition, argc, o->pargc); if (direction == PJ_INV) { /* fail if an inverse operation is not available */ if (!info.has_inverse) { print(PJ_LOG_ERROR, "Inverse operation not available"); if (stdout != fout) fclose(fout); return 1; } /* We have no API call for inverting an operation, so we brute force it. */ P->inverted = !(P->inverted); } direction = PJ_FWD; /* Allocate input buffer */ constexpr int BUFFER_SIZE = 10000; char *buf = static_cast<char *>(calloc(1, BUFFER_SIZE)); if (nullptr == buf) { print(PJ_LOG_ERROR, "%s: Out of memory", o->progname); proj_destroy(P); free(o); if (stdout != fout) fclose(fout); return 1; } /* Loop over all records of all input files */ int previous_index = -1; while (opt_input_loop(o, optargs_file_format_text)) { int err; char *bufptr = fgets(buf, BUFFER_SIZE - 1, o->input); if (opt_eof(o)) { continue; } if (nullptr == bufptr) { print(PJ_LOG_ERROR, "Read error in record %d", (int)o->record_index); continue; } const bool bFirstLine = o->input_index != previous_index; previous_index = o->input_index; if (bFirstLine && static_cast<uint8_t>(bufptr[0]) == 0xEF && static_cast<uint8_t>(bufptr[1]) == 0xBB && static_cast<uint8_t>(bufptr[2]) == 0xBF) { // Skip UTF-8 Byte Order Marker (BOM) bufptr += 3; } point = parse_input_line(bufptr, columns_xyzt, fixed_z, fixed_time); if (skip_lines > 0) { skip_lines--; continue; } /* if it's a comment or blank line, we reflect it */ const char *c = column(bufptr, 1); if (c && ((*c == '\0') || (*c == '#'))) { fprintf(fout, "%s", bufptr); continue; } if (HUGE_VAL == point.xyzt.x) { /* otherwise, it must be a syntax error */ print(PJ_LOG_NONE, "# Record %d UNREADABLE: %s", (int)o->record_index, bufptr); print(PJ_LOG_ERROR, "%s: Could not parse file '%s' line %d", o->progname, opt_filename(o), opt_record(o)); continue; } if (proj_angular_input(P, direction)) { point.lpzt.lam = proj_torad(point.lpzt.lam); point.lpzt.phi = proj_torad(point.lpzt.phi); } err = proj_errno_reset(P); /* coverity[returned_value] */ point = proj_trans(P, direction, point); if (HUGE_VAL == point.xyzt.x) { /* transformation error */ print(PJ_LOG_NONE, "# Record %d TRANSFORMATION ERROR: %s (%s)", (int)o->record_index, bufptr, proj_errno_string(proj_errno(P))); proj_errno_restore(P, err); continue; } proj_errno_restore(P, err); /* handle comment string */ char *comment = column(bufptr, nfields + 1); if (opt_given(o, "c")) { /* what number is the last coordinate column in the input data? */ int colmax = 0; for (i = 0; i < 4; i++) colmax = MAX(colmax, columns_xyzt[i]); comment = column(bufptr, colmax + 1); } /* remove the line feed from comment, as logger() above, invoked by print() below (output), will add one */ size_t len = strlen(comment); if (len >= 1) comment[len - 1] = '\0'; const char *comment_delimiter = *comment ? whitespace : blank_comment; /* Time to print the result */ /* use same arguments to printf format string for both radians and degrees; convert radians to degrees before printing */ if (proj_angular_output(P, direction) || proj_degree_output(P, direction)) { if (proj_angular_output(P, direction)) { point.lpzt.lam = proj_todeg(point.lpzt.lam); point.lpzt.phi = proj_todeg(point.lpzt.phi); } print(PJ_LOG_NONE, "%14.*f %14.*f %12.*f %12.4f%s%s", decimals_angles, point.xyzt.x, decimals_angles, point.xyzt.y, decimals_distances, point.xyzt.z, point.xyzt.t, comment_delimiter, comment); } else print(PJ_LOG_NONE, "%13.*f %13.*f %12.*f %12.4f%s%s", decimals_distances, point.xyzt.x, decimals_distances, point.xyzt.y, decimals_distances, point.xyzt.z, point.xyzt.t, comment_delimiter, comment); if (fout == stdout) fflush(stdout); } proj_destroy(P); if (stdout != fout) fclose(fout); free(o); free(buf); return 0; } /* return a pointer to the n'th column of buf */ static const char *column(const char *buf, int n) { int i; if (n <= 0) return buf; for (i = 0; i < n; i++) { while (isspace(*buf)) buf++; if (i == n - 1) break; while ((0 != *buf) && !isspace(*buf)) buf++; } return buf; } static char *column(char *buf, int n) { return const_cast<char *>(column(const_cast<const char *>(buf), n)); } /* column to double */ static double cold(const char *args, int col) { char *endp; double d; const char *target = column(args, col); d = proj_strtod(target, &endp); if (endp == target) return HUGE_VAL; return d; } PJ_COORD parse_input_line(const char *buf, int *columns, double fixed_height, double fixed_time) { PJ_COORD err = proj_coord(HUGE_VAL, HUGE_VAL, HUGE_VAL, HUGE_VAL); PJ_COORD result = err; int prev_errno = errno; errno = 0; result.xyzt.z = fixed_height; result.xyzt.t = fixed_time; result.xyzt.x = cold(buf, columns[0]); result.xyzt.y = cold(buf, columns[1]); if (result.xyzt.z == HUGE_VAL) result.xyzt.z = cold(buf, columns[2]); if (result.xyzt.t == HUGE_VAL) result.xyzt.t = cold(buf, columns[3]); if (0 != errno) return err; errno = prev_errno; return result; }
cpp
PROJ
data/projects/PROJ/src/apps/geod_interface.cpp
#include "geod_interface.h" #include "proj.h" #include "proj_internal.h" void geod_ini(void) { geod_init(&GlobalGeodesic, geod_a, geod_f); } void geod_pre(void) { double lat1 = phi1 / DEG_TO_RAD, lon1 = lam1 / DEG_TO_RAD, azi1 = al12 / DEG_TO_RAD; geod_lineinit(&GlobalGeodesicLine, &GlobalGeodesic, lat1, lon1, azi1, 0U); } void geod_for(void) { double s12 = geod_S, lat2, lon2, azi2; geod_position(&GlobalGeodesicLine, s12, &lat2, &lon2, &azi2); azi2 += azi2 >= 0 ? -180 : 180; /* Compute back azimuth */ phi2 = lat2 * DEG_TO_RAD; lam2 = lon2 * DEG_TO_RAD; al21 = azi2 * DEG_TO_RAD; } void geod_inv(void) { double lat1 = phi1 / DEG_TO_RAD, lon1 = lam1 / DEG_TO_RAD, lat2 = phi2 / DEG_TO_RAD, lon2 = lam2 / DEG_TO_RAD, azi1, azi2, s12; geod_inverse(&GlobalGeodesic, lat1, lon1, lat2, lon2, &s12, &azi1, &azi2); /* Compute back azimuth * map +/-0 -> -/+180; +/-180 -> -/+0 * this depends on abs(azi2) <= 180 */ azi2 = copysign(azi2 + copysign(180.0, -azi2), -azi2); al12 = azi1 * DEG_TO_RAD; al21 = azi2 * DEG_TO_RAD; geod_S = s12; }
cpp
PROJ
data/projects/PROJ/src/apps/geod_interface.h
#if !defined(GEOD_INTERFACE_H) #define GEOD_INTERFACE_H #include "geodesic.h" #ifdef __cplusplus extern "C" { #endif #ifndef GEOD_IN_GEOD_SET #define GEOD_EXTERN extern #else #define GEOD_EXTERN #endif GEOD_EXTERN struct geodesic { double A, FLAT, LAM1, PHI1, ALPHA12, LAM2, PHI2, ALPHA21, DIST; } GEODESIC; #define geod_a GEODESIC.A #define geod_f GEODESIC.FLAT #define lam1 GEODESIC.LAM1 #define phi1 GEODESIC.PHI1 #define al12 GEODESIC.ALPHA12 #define lam2 GEODESIC.LAM2 #define phi2 GEODESIC.PHI2 #define al21 GEODESIC.ALPHA21 #define geod_S GEODESIC.DIST GEOD_EXTERN struct geod_geodesic GlobalGeodesic; GEOD_EXTERN struct geod_geodesicline GlobalGeodesicLine; GEOD_EXTERN int n_alpha, n_S; GEOD_EXTERN double to_meter, fr_meter, del_alpha; void geod_set(int, char **); void geod_ini(void); void geod_pre(void); void geod_for(void); void geod_inv(void); #ifdef __cplusplus } #endif #endif
h
PROJ
data/projects/PROJ/src/apps/gie.cpp
/*********************************************************************** gie - The Geospatial Integrity Investigation Environment ************************************************************************ The Geospatial Integrity Investigation Environment "gie" is a modest regression testing environment for the PROJ.4 transformation library. Its primary design goal was to be able to replace those thousands of lines of regression testing code that are (at time of writing) part of PROJ.4, while not requiring any other kind of tooling than the same C compiler already employed for compiling the library. The basic functionality of the gie command language is implemented through just 3 command verbs: operation, which defines the PROJ.4 operation to test, accept, which defines the input coordinate to read, and expect, which defines the result to expect. E.g: operation +proj=utm +zone=32 +ellps=GRS80 accept 12 55 expect 691_875.632_14 6_098_907.825_05 Note that gie accepts the underscore ("_") as a thousands separator. It is not required (in fact, it is entirely ignored by the input routine), but it significantly improves the readability of the very long strings of numbers typically required in projected coordinates. By default, gie considers the EXPECTation met, if the result comes to within 0.5 mm of the expected. This default can be changed using the 'tolerance' command verb (and yes, I know, linguistically speaking, both "operation" and "tolerance" are nouns, not verbs). See the first few hundred lines of the "builtins.gie" test file for more details of the command verbs available (verbs of both the VERBal and NOUNistic persuation). -- But more importantly than being an acronym for "Geospatial Integrity Investigation Environment", gie were also the initials, user id, and USGS email address of Gerald Ian Evenden (1935--2016), the geospatial visionary, who, already in the 1980s, started what was to become the PROJ.4 of today. Gerald's clear vision was that map projections are *just special functions*. Some of them rather complex, most of them of two variables, but all of them *just special functions*, and not particularly more special than the sin(), cos(), tan(), and hypot() already available in the C standard library. And hence, according to Gerald, *they should not be particularly much harder to use*, for a programmer, than the sin()s, tan()s and hypot()s so readily available. Gerald's ingenuity also showed in the implementation of the vision, where he devised a comprehensive, yet simple, system of key-value pairs for parameterising a map projection, and the highly flexible PJ struct, storing run-time compiled versions of those key-value pairs, hence making a map projection function call, pj_fwd(PJ, point), as easy as a traditional function call like hypot(x,y). While today, we may have more formally well defined metadata systems (most prominent the OGC WKT2 representation), nothing comes close being as easily readable ("human compatible") as Gerald's key-value system. This system in particular, and the PROJ.4 system in general, was Gerald's great gift to anyone using and/or communicating about geodata. It is only reasonable to name a program, keeping an eye on the integrity of the PROJ.4 system, in honour of Gerald. So in honour, and hopefully also in the spirit, of Gerald Ian Evenden (1935--2016), this is the Geospatial Integrity Investigation Environment. ************************************************************************ Thomas Knudsen, [email protected], 2017-10-01/2017-10-08 ************************************************************************ * Copyright (c) 2017 Thomas Knudsen * Copyright (c) 2017, SDFE * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ***********************************************************************/ #include <ctype.h> #include <errno.h> #include <math.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proj.h" #include "proj_internal.h" #include "proj_strtod.h" #include <cmath> /* for isnan */ #include <math.h> #include "optargpm.h" /* Package for flexible format I/O - ffio */ typedef struct ffio { FILE *f; const char *const *tags; const char *tag; char *args; char *next_args; size_t n_tags; size_t args_size; size_t next_args_size; size_t argc; size_t lineno, next_lineno; size_t level; bool strict_mode; } ffio; static int get_inp(ffio *G); static int skip_to_next_tag(ffio *G); static int step_into_gie_block(ffio *G); static int nextline(ffio *G); static int at_end_delimiter(ffio *G); static const char *at_tag(ffio *G); static int at_decorative_element(ffio *G); static ffio *ffio_destroy(ffio *G); static ffio *ffio_create(const char *const *tags, size_t n_tags, size_t max_record_size); static const char *const gie_tags[] = { "<gie>", "operation", "crs_src", "crs_dst", "use_proj4_init_rules", "accept", "expect", "roundtrip", "banner", "verbose", "direction", "tolerance", "ignore", "require_grid", "echo", "skip", "</gie>", "<gie-strict>", "</gie-strict>", }; static const size_t n_gie_tags = sizeof gie_tags / sizeof gie_tags[0]; int main(int argc, char **argv); static int dispatch(const char *cmnd, const char *args); static int errmsg(int errlev, const char *msg, ...); static int errno_from_err_const(const char *err_const); static int list_err_codes(void); static int process_file(const char *fname); static const char *column(const char *buf, int n); static const char *err_const_from_errno(int err); #define SKIP -1 #define MAX_OPERATION 10000 typedef struct { char operation[MAX_OPERATION + 1]; char crs_dst[MAX_OPERATION + 1]; char crs_src[MAX_OPERATION + 1]; PJ *P; PJ_COORD a, b, e; PJ_DIRECTION dir; int verbosity; int skip; int op_id; int op_ok, op_ko, op_skip; int total_ok, total_ko, total_skip; int grand_ok, grand_ko, grand_skip; size_t operation_lineno; size_t dimensions_given, dimensions_given_at_last_accept; double tolerance; int use_proj4_init_rules; int ignore; int skip_test; const char *curr_file; FILE *fout; } gie_ctx; ffio *F = nullptr; static gie_ctx T; int tests = 0, succs = 0, succ_fails = 0, fail_fails = 0, succ_rtps = 0, fail_rtps = 0; static const char delim[] = {"-------------------------------------------------" "------------------------------\n"}; static const char usage[] = { "--------------------------------------------------------------------------" "------\n" "Usage: %s [-options]... infile...\n" "--------------------------------------------------------------------------" "------\n" "Options:\n" "--------------------------------------------------------------------------" "------\n" " -h Help: print this usage information\n" " -o /path/to/file Specify output file name\n" " -v Verbose: Provide non-essential informational " "output.\n" " Repeat -v for more verbosity (e.g. -vv)\n" " -q Quiet: Opposite of verbose. In quiet mode not even " "errors\n" " are reported. Only interaction is through the " "return code\n" " (0 on success, non-zero indicates number of FAILED " "tests)\n" " -l List the PROJ internal system error codes\n" "--------------------------------------------------------------------------" "------\n" "Long Options:\n" "--------------------------------------------------------------------------" "------\n" " --output Alias for -o\n" " --verbose Alias for -v\n" " --help Alias for -h\n" " --list Alias for -l\n" " --version Print version number\n" "--------------------------------------------------------------------------" "------\n" "Examples:\n" "--------------------------------------------------------------------------" "------\n" "1. Run all tests in file \"corner-cases.gie\", providing much extra " "information\n" " gie -vvvv corner-cases.gie\n" "2. Run all tests in files \"foo\" and \"bar\", providing info on failures " "only\n" " gie foo bar\n" "--------------------------------------------------------------------------" "------\n"}; int main(int argc, char **argv) { int i; const char *longflags[] = {"v=verbose", "q=quiet", "h=help", "l=list", "version", nullptr}; const char *longkeys[] = {"o=output", nullptr}; OPTARGS *o; memset(&T, 0, sizeof(T)); T.dir = PJ_FWD; T.verbosity = 1; T.tolerance = 5e-4; T.ignore = 5555; /* Error code that will not be issued by proj_create() */ T.use_proj4_init_rules = FALSE; /* coverity[tainted_data] */ o = opt_parse(argc, argv, "hlvq", "o", longflags, longkeys); if (nullptr == o) return 0; if (opt_given(o, "h") || argc == 1) { printf(usage, o->progname); free(o); return 0; } if (opt_given(o, "version")) { fprintf(stdout, "%s: %s\n", o->progname, pj_get_release()); free(o); return 0; } T.verbosity = opt_given(o, "q"); if (T.verbosity) T.verbosity = -1; if (T.verbosity != -1) T.verbosity = opt_given(o, "v") + 1; T.fout = stdout; if (opt_given(o, "o")) T.fout = fopen(opt_arg(o, "output"), "rt"); if (nullptr == T.fout) { fprintf(stderr, "%s: Cannot open '%s' for output\n", o->progname, opt_arg(o, "output")); free(o); return 1; } if (opt_given(o, "l")) { free(o); return list_err_codes(); } if (0 == o->fargc) { if (T.verbosity == -1) return -1; fprintf(T.fout, "Nothing to do\n"); free(o); return 0; } F = ffio_create(gie_tags, n_gie_tags, 1000); if (nullptr == F) { fprintf(stderr, "%s: No memory\n", o->progname); free(o); return 1; } for (i = 0; i < o->fargc; i++) { FILE *f = fopen(o->fargv[i], "rt"); if (f == nullptr) { fprintf(T.fout, "%sCannot open specified input file '%s' - bye!\n", delim, o->fargv[i]); return 1; } fclose(f); } for (i = 0; i < o->fargc; i++) process_file(o->fargv[i]); if (T.verbosity > 0) { if (o->fargc > 1) { fprintf( T.fout, "%sGrand total: %d. Success: %d, Skipped: %d, Failure: %d\n", delim, T.grand_ok + T.grand_ko + T.grand_skip, T.grand_ok, T.grand_skip, T.grand_ko); } fprintf(T.fout, "%s", delim); if (T.verbosity > 1) { fprintf(T.fout, "Failing roundtrips: %4d, Succeeding roundtrips: %4d\n", fail_rtps, succ_rtps); fprintf(T.fout, "Failing failures: %4d, Succeeding failures: %4d\n", fail_fails, succ_fails); fprintf( T.fout, "Internal counters: %4.4d(%4.4d)\n", tests, succs); fprintf(T.fout, "%s", delim); } } else if (T.grand_ko) fprintf(T.fout, "Failures: %d", T.grand_ko); if (stdout != T.fout) fclose(T.fout); free(o); ffio_destroy(F); return T.grand_ko; } static int another_failure(void) { T.op_ko++; T.total_ko++; proj_errno_reset(T.P); return 0; } static int another_skip(void) { T.op_skip++; T.total_skip++; return 0; } static int another_success(void) { T.op_ok++; T.total_ok++; proj_errno_reset(T.P); return 0; } static int another_succeeding_failure(void) { succ_fails++; return another_success(); } static int another_failing_failure(void) { fail_fails++; return another_failure(); } static int another_succeeding_roundtrip(void) { succ_rtps++; return another_success(); } static int another_failing_roundtrip(void) { fail_rtps++; return another_failure(); } static int process_file(const char *fname) { F->lineno = F->next_lineno = F->level = 0; T.op_ok = T.total_ok = 0; T.op_ko = T.total_ko = 0; T.op_skip = T.total_skip = 0; if (T.skip) { proj_destroy(T.P); T.P = nullptr; return 0; } /* We have already tested in main that the file exists */ F->f = fopen(fname, "rt"); if (T.verbosity > 0) fprintf(T.fout, "%sReading file '%s'\n", delim, fname); T.curr_file = fname; while (get_inp(F)) { if (SKIP == dispatch(F->tag, F->args)) { proj_destroy(T.P); T.P = nullptr; return 0; } } fclose(F->f); F->lineno = F->next_lineno = 0; T.grand_ok += T.total_ok; T.grand_ko += T.total_ko; T.grand_skip += T.grand_skip; if (T.verbosity > 0) { fprintf( T.fout, "%stotal: %2d tests succeeded, %2d tests skipped, %2d tests %s\n", delim, T.total_ok, T.total_skip, T.total_ko, T.total_ko ? "FAILED!" : "failed."); } if (F->level == 0) return errmsg(-3, "File '%s':Missing '<gie>' cmnd - bye!\n", fname); if (F->level && F->level % 2) { if (F->strict_mode) return errmsg(-4, "File '%s':Missing '</gie-strict>' cmnd - bye!\n", fname); else return errmsg(-4, "File '%s':Missing '</gie>' cmnd - bye!\n", fname); } return 0; } /*****************************************************************************/ const char *column(const char *buf, int n) { /***************************************************************************** Return a pointer to the n'th column of buf. Column numbers start at 0. ******************************************************************************/ int i; if (n <= 0) return buf; for (i = 0; i < n; i++) { while (isspace(*buf)) buf++; if (i == n - 1) break; while ((0 != *buf) && !isspace(*buf)) buf++; } return buf; } /*****************************************************************************/ static double strtod_scaled(const char *args, double default_scale) { /***************************************************************************** Interpret <args> as a numeric followed by a linear decadal prefix. Return the properly scaled numeric ******************************************************************************/ const double GRS80_DEG = 111319.4908; /* deg-to-m at equator of GRS80 */ char *endp; double s = proj_strtod(args, &endp); if (args == endp) return HUGE_VAL; const char *units = column(args, 2); if (0 == strcmp(units, "km")) s *= 1000; else if (0 == strcmp(units, "m")) s *= 1; else if (0 == strcmp(units, "dm")) s /= 10; else if (0 == strcmp(units, "cm")) s /= 100; else if (0 == strcmp(units, "mm")) s /= 1000; else if (0 == strcmp(units, "um")) s /= 1e6; else if (0 == strcmp(units, "nm")) s /= 1e9; else if (0 == strcmp(units, "rad")) s = GRS80_DEG * proj_todeg(s); else if (0 == strcmp(units, "deg")) s = GRS80_DEG * s; else s *= default_scale; return s; } static int banner(const char *args) { char dots[] = {"..."}, nodots[] = {""}, *thedots = nodots; if (strlen(args) > 70) thedots = dots; fprintf(T.fout, "%s%-70.70s%s\n", delim, args, thedots); return 0; } static int tolerance(const char *args) { T.tolerance = strtod_scaled(args, 1); if (HUGE_VAL == T.tolerance) { T.tolerance = 0.0005; return 1; } return 0; } static int use_proj4_init_rules(const char *args) { T.use_proj4_init_rules = strcmp(args, "true") == 0; return 0; } static int ignore(const char *args) { T.ignore = errno_from_err_const(column(args, 1)); return 0; } static int require_grid(const char *args) { PJ_GRID_INFO grid_info; const char *grid_filename = column(args, 1); grid_info = proj_grid_info(grid_filename); if (strlen(grid_info.filename) == 0) { if (T.verbosity > 1) { fprintf(T.fout, "Test skipped because of missing grid %s\n", grid_filename); } T.skip_test = 1; } return 0; } static int direction(const char *args) { const char *endp = args; while (isspace(*endp)) endp++; switch (*endp) { case 'F': case 'f': T.dir = PJ_FWD; break; case 'I': case 'i': case 'R': case 'r': T.dir = PJ_INV; break; default: return 1; } return 0; } static void finish_previous_operation(const char *args) { if (T.verbosity > 1 && T.op_id > 1 && T.op_ok + T.op_ko) fprintf(T.fout, "%s %d tests succeeded, %d tests skipped, %d tests %s\n", delim, T.op_ok, T.op_skip, T.op_ko, T.op_ko ? "FAILED!" : "failed."); (void)args; } /*****************************************************************************/ static int operation(const char *args) { /***************************************************************************** Define the operation to apply to the input data (in ISO 19100 lingo, an operation is the general term describing something that can be either a conversion or a transformation) ******************************************************************************/ T.op_id++; T.operation_lineno = F->lineno; strncpy(&(T.operation[0]), F->args, MAX_OPERATION); T.operation[MAX_OPERATION] = '\0'; if (T.verbosity > 1) { finish_previous_operation(F->args); banner(args); } T.op_ok = 0; T.op_ko = 0; T.op_skip = 0; T.skip_test = 0; direction("forward"); tolerance("0.5 mm"); ignore("pjd_err_dont_skip"); proj_errno_reset(T.P); if (T.P) proj_destroy(T.P); proj_errno_reset(nullptr); proj_context_use_proj4_init_rules(nullptr, T.use_proj4_init_rules); T.P = proj_create(nullptr, F->args); /* Checking that proj_create succeeds is first done at "expect" time, */ /* since we want to support "expect"ing specific error codes */ return 0; } static int crs_to_crs_operation() { T.op_id++; T.operation_lineno = F->lineno; if (T.verbosity > 1) { char buffer[80]; finish_previous_operation(F->args); snprintf(buffer, 80, "%-36.36s -> %-36.36s", T.crs_src, T.crs_dst); banner(buffer); } T.op_ok = 0; T.op_ko = 0; T.op_skip = 0; T.skip_test = 0; direction("forward"); tolerance("0.5 mm"); ignore("pjd_err_dont_skip"); proj_errno_reset(T.P); if (T.P) proj_destroy(T.P); proj_errno_reset(nullptr); proj_context_use_proj4_init_rules(nullptr, T.use_proj4_init_rules); T.P = proj_create_crs_to_crs(nullptr, T.crs_src, T.crs_dst, nullptr); strcpy(T.crs_src, ""); strcpy(T.crs_dst, ""); return 0; } static int crs_src(const char *args) { strncpy(&(T.crs_src[0]), F->args, MAX_OPERATION); T.crs_src[MAX_OPERATION] = '\0'; (void)args; if (strcmp(T.crs_src, "") != 0 && strcmp(T.crs_dst, "") != 0) { crs_to_crs_operation(); } return 0; } static int crs_dst(const char *args) { strncpy(&(T.crs_dst[0]), F->args, MAX_OPERATION); T.crs_dst[MAX_OPERATION] = '\0'; (void)args; if (strcmp(T.crs_src, "") != 0 && strcmp(T.crs_dst, "") != 0) { crs_to_crs_operation(); } return 0; } static PJ_COORD torad_coord(PJ *P, PJ_DIRECTION dir, PJ_COORD a) { size_t i, n; const char *axis = "enut"; paralist *l = pj_param_exists(P->params, "axis"); if (l && dir == PJ_INV) axis = l->param + strlen("axis="); n = strlen(axis); for (i = 0; i < n; i++) if (strchr("news", axis[i])) a.v[i] = proj_torad(a.v[i]); return a; } static PJ_COORD todeg_coord(PJ *P, PJ_DIRECTION dir, PJ_COORD a) { size_t i, n; const char *axis = "enut"; paralist *l = pj_param_exists(P->params, "axis"); if (l && dir == PJ_FWD) axis = l->param + strlen("axis="); n = strlen(axis); for (i = 0; i < n; i++) if (strchr("news", axis[i])) a.v[i] = proj_todeg(a.v[i]); return a; } /*****************************************************************************/ static PJ_COORD parse_coord(const char *args) { /***************************************************************************** Attempt to interpret args as a PJ_COORD. ******************************************************************************/ int i; char *endp; char *dmsendp; const char *prev = args; PJ_COORD a = proj_coord(0, 0, 0, 0); T.dimensions_given = 0; for (i = 0; i < 4; i++) { /* proj_strtod doesn't read values like 123d45'678W so we need a bit */ /* of help from proj_dmstor. proj_strtod effectively ignores what */ /* comes after "d", so we use that fact that when dms is larger than */ /* d the value was stated in "dms" form. */ /* This could be avoided if proj_dmstor used the same proj_strtod() */ /* as gie, but that is not the case (yet). When we remove projects.h */ /* from the public API we can change that. */ // Even Rouault: unsure about the above. Coordinates are not necessarily // geographic coordinates, and the roundtrip through radians for // big projected coordinates cause inaccuracies, that can cause // test failures when testing points at edge of grids. // For example 1501000.0 becomes 1501000.000000000233 double d = proj_strtod(prev, &endp); if (!std::isnan(d) && *endp != '\0' && !isspace(*endp)) { double dms = PJ_TODEG(proj_dmstor(prev, &dmsendp)); /* TODO: When projects.h is removed, call proj_dmstor() in all cases */ if (d != dms && fabs(d) < fabs(dms) && fabs(dms) < fabs(d) + 1) { d = dms; endp = dmsendp; } /* A number like -81d00'00.000 will be parsed correctly by both */ /* proj_strtod and proj_dmstor but only the latter will return */ /* the correct end-pointer. */ if (d == dms && endp != dmsendp) endp = dmsendp; } /* Break out if there were no more numerals */ if (prev == endp) return i > 1 ? a : proj_coord_error(); a.v[i] = d; prev = endp; T.dimensions_given++; } return a; } /*****************************************************************************/ static int accept(const char *args) { /***************************************************************************** Read ("ACCEPT") a 2, 3, or 4 dimensional input coordinate. ******************************************************************************/ T.a = parse_coord(args); if (T.verbosity > 3) fprintf(T.fout, "# %s\n", args); T.dimensions_given_at_last_accept = T.dimensions_given; return 0; } /*****************************************************************************/ static int roundtrip(const char *args) { /***************************************************************************** Check how far we go from the ACCEPTed point when doing successive back/forward transformation pairs. Without args, roundtrip defaults to 100 iterations: roundtrip With one arg, roundtrip will default to a tolerance of T.tolerance: roundtrip ntrips With two args: roundtrip ntrips tolerance Always returns 0. ******************************************************************************/ int ntrips; double d, r, ans; char *endp; PJ_COORD coo; if (nullptr == T.P) { if (T.ignore == proj_errno(T.P)) return another_skip(); return another_failure(); } ans = proj_strtod(args, &endp); if (endp == args) { /* Default to 100 iterations if not args. */ ntrips = 100; } else { if (ans < 1.0 || ans > 1000000.0) { errmsg(2, "Invalid number of roundtrips: %lf\n", ans); return another_failing_roundtrip(); } ntrips = (int)ans; } d = strtod_scaled(endp, 1); d = d == HUGE_VAL ? T.tolerance : d; /* input ("accepted") values - probably in degrees */ coo = proj_angular_input(T.P, T.dir) ? torad_coord(T.P, T.dir, T.a) : T.a; r = proj_roundtrip(T.P, T.dir, ntrips, &coo); if ((std::isnan(r) && std::isnan(d)) || r <= d) return another_succeeding_roundtrip(); if (T.verbosity > -1) { if (0 == T.op_ko && T.verbosity < 2) banner(T.operation); fprintf(T.fout, "%s", T.op_ko ? " -----\n" : delim); fprintf(T.fout, " FAILURE in %s(%d):\n", opt_strip_path(T.curr_file), (int)F->lineno); fprintf(T.fout, " roundtrip deviation: %.6f mm, expected: %.6f mm\n", 1000 * r, 1000 * d); } return another_failing_roundtrip(); } static int expect_message(double d, const char *args) { another_failure(); if (T.verbosity < 0) return 1; if (d > 1e6) d = 999999.999999; if (0 == T.op_ko && T.verbosity < 2) banner(T.operation); fprintf(T.fout, "%s", T.op_ko ? " -----\n" : delim); fprintf(T.fout, " FAILURE in %s(%d):\n", opt_strip_path(T.curr_file), (int)F->lineno); fprintf(T.fout, " expected: %s\n", args); fprintf(T.fout, " got: %.12f %.12f", T.b.xy.x, T.b.xy.y); if (T.b.xyzt.t != 0 || T.b.xyzt.z != 0) fprintf(T.fout, " %.9f", T.b.xyz.z); if (T.b.xyzt.t != 0) fprintf(T.fout, " %.9f", T.b.xyzt.t); fprintf(T.fout, "\n"); fprintf(T.fout, " deviation: %.6f mm, expected: %.6f mm\n", 1000 * d, 1000 * T.tolerance); return 1; } static int expect_message_cannot_parse(const char *args) { another_failure(); if (T.verbosity > -1) { if (0 == T.op_ko && T.verbosity < 2) banner(T.operation); fprintf(T.fout, "%s", T.op_ko ? " -----\n" : delim); fprintf(T.fout, " FAILURE in %s(%d):\n Too few args: %s\n", opt_strip_path(T.curr_file), (int)F->lineno, args); } return 1; } static int expect_failure_with_errno_message(int expected, int got) { another_failing_failure(); if (T.verbosity < 0) return 1; if (0 == T.op_ko && T.verbosity < 2) banner(T.operation); fprintf(T.fout, "%s", T.op_ko ? " -----\n" : delim); fprintf(T.fout, " FAILURE in %s(%d):\n", opt_strip_path(T.curr_file), (int)F->lineno); fprintf(T.fout, " got errno %s (%d): %s\n", err_const_from_errno(got), got, proj_errno_string(got)); fprintf(T.fout, " expected %s (%d): %s", err_const_from_errno(expected), expected, proj_errno_string(expected)); fprintf(T.fout, "\n"); return 1; } /* For test purposes, we want to call a transformation of the same */ /* dimensionality as the number of dimensions given in accept */ static PJ_COORD expect_trans_n_dim(const PJ_COORD &ci) { if (4 == T.dimensions_given_at_last_accept) return proj_trans(T.P, T.dir, ci); if (3 == T.dimensions_given_at_last_accept) return pj_approx_3D_trans(T.P, T.dir, ci); return pj_approx_2D_trans(T.P, T.dir, ci); } /*****************************************************************************/ static int expect(const char *args) { /***************************************************************************** Tell GIE what to expect, when transforming the ACCEPTed input ******************************************************************************/ PJ_COORD ci, co, ce; double d; int expect_failure = 0; int expect_failure_with_errno = 0; if (0 == strncmp(args, "failure", 7)) { expect_failure = 1; /* Option: Fail with an expected errno (syntax: expect failure errno * -33) */ if (0 == strncmp(column(args, 2), "errno", 5)) expect_failure_with_errno = errno_from_err_const(column(args, 3)); } if (T.ignore == proj_errno(T.P)) return another_skip(); if (nullptr == T.P) { /* If we expect failure, and fail, then it's a success... */ if (expect_failure) { /* Failed to fail correctly? */ if (expect_failure_with_errno && proj_errno(T.P) != expect_failure_with_errno) return expect_failure_with_errno_message( expect_failure_with_errno, proj_errno(T.P)); return another_succeeding_failure(); } /* Otherwise, it's a true failure */ banner(T.operation); errmsg(3, "%sInvalid operation definition in line no. %d:\n %s " "(errno=%s/%d)\n", delim, (int)T.operation_lineno, proj_errno_string(proj_errno(T.P)), err_const_from_errno(proj_errno(T.P)), proj_errno(T.P)); return another_failing_failure(); } /* We may still successfully fail even if the proj_create succeeded */ if (expect_failure) { proj_errno_reset(T.P); /* Try to carry out the operation - and expect failure */ ci = proj_angular_input(T.P, T.dir) ? torad_coord(T.P, T.dir, T.a) : T.a; co = expect_trans_n_dim(ci); if (expect_failure_with_errno) { if (proj_errno(T.P) == expect_failure_with_errno) return another_succeeding_failure(); // fprintf (T.fout, "errno=%d, expected=%d\n", proj_errno (T.P), // expect_failure_with_errno); banner(T.operation); errmsg(3, "%serrno=%s (%d), expected=%d at line %d\n", delim, err_const_from_errno(proj_errno(T.P)), proj_errno(T.P), expect_failure_with_errno, static_cast<int>(F->lineno)); return another_failing_failure(); } /* Succeeded in failing? - that's a success */ if (co.xyz.x == HUGE_VAL) return another_succeeding_failure(); /* Failed to fail? - that's a failure */ banner(T.operation); errmsg(3, "%sFailed to fail. Operation definition in line no. %d\n", delim, (int)T.operation_lineno); return another_failing_failure(); } if (T.verbosity > 3) { fprintf(T.fout, "%s\n", T.P->inverted ? "INVERTED" : "NOT INVERTED"); fprintf(T.fout, "%s\n", T.dir == 1 ? "forward" : "reverse"); fprintf(T.fout, "%s\n", proj_angular_input(T.P, T.dir) ? "angular in" : "linear in"); fprintf(T.fout, "%s\n", proj_angular_output(T.P, T.dir) ? "angular out" : "linear out"); fprintf(T.fout, "left: %d right: %d\n", T.P->left, T.P->right); } tests++; T.e = parse_coord(args); if (HUGE_VAL == T.e.v[0]) return expect_message_cannot_parse(args); /* expected angular values, probably in degrees */ ce = proj_angular_output(T.P, T.dir) ? torad_coord(T.P, T.dir, T.e) : T.e; if (T.verbosity > 3) fprintf(T.fout, "EXPECTS %.12f %.12f %.12f %.12f\n", ce.v[0], ce.v[1], ce.v[2], ce.v[3]); /* input ("accepted") values, also probably in degrees */ ci = proj_angular_input(T.P, T.dir) ? torad_coord(T.P, T.dir, T.a) : T.a; if (T.verbosity > 3) fprintf(T.fout, "ACCEPTS %.12f %.12f %.12f %.12f\n", ci.v[0], ci.v[1], ci.v[2], ci.v[3]); /* do the transformation, but mask off dimensions not given in expect-ation */ co = expect_trans_n_dim(ci); if (T.dimensions_given < 4) co.v[3] = 0; if (T.dimensions_given < 3) co.v[2] = 0; /* angular output from proj_trans comes in radians */ T.b = proj_angular_output(T.P, T.dir) ? todeg_coord(T.P, T.dir, co) : co; if (T.verbosity > 3) fprintf(T.fout, "GOT %.12f %.12f %.12f %.12f\n", co.v[0], co.v[1], co.v[2], co.v[3]); #if 0 /* We need to handle unusual axis orders - that'll be an item for version 5.1 */ if (T.P->axisswap) { ce = proj_trans (T.P->axisswap, T.dir, ce); co = proj_trans (T.P->axisswap, T.dir, co); } #endif if (std::isnan(co.v[0]) && std::isnan(ce.v[0])) { d = 0.0; } else if (proj_angular_output(T.P, T.dir)) { d = proj_lpz_dist(T.P, ce, co); } else { d = proj_xyz_dist(co, ce); } // Test written like that to handle NaN if (!(d <= T.tolerance)) return expect_message(d, args); succs++; another_success(); return 0; } /*****************************************************************************/ static int verbose(const char *args) { /***************************************************************************** Tell the system how noisy it should be ******************************************************************************/ int i = (int)proj_atof(args); /* if -q/--quiet flag has been given, we do nothing */ if (T.verbosity < 0) return 0; if (strlen(args)) T.verbosity = i; else T.verbosity++; return 0; } /*****************************************************************************/ static int echo(const char *args) { /***************************************************************************** Add user defined noise to the output stream ******************************************************************************/ fprintf(T.fout, "%s\n", args); return 0; } /*****************************************************************************/ static int skip(const char *args) { /***************************************************************************** Indicate that the remaining material should be skipped. Mostly for debugging. ******************************************************************************/ T.skip = 1; (void)args; F->level = 2; /* Silence complaints about missing </gie> element */ return 0; } static int dispatch(const char *cmnd, const char *args) { if (T.skip) return SKIP; if (0 == strcmp(cmnd, "operation")) return operation(args); if (0 == strcmp(cmnd, "crs_src")) return crs_src(args); if (0 == strcmp(cmnd, "crs_dst")) return crs_dst(args); if (T.skip_test) { if (0 == strcmp(cmnd, "expect")) return another_skip(); return 0; } if (0 == strcmp(cmnd, "accept")) return accept(args); if (0 == strcmp(cmnd, "expect")) return expect(args); if (0 == strcmp(cmnd, "roundtrip")) return roundtrip(args); if (0 == strcmp(cmnd, "banner")) return banner(args); if (0 == strcmp(cmnd, "verbose")) return verbose(args); if (0 == strcmp(cmnd, "direction")) return direction(args); if (0 == strcmp(cmnd, "tolerance")) return tolerance(args); if (0 == strcmp(cmnd, "ignore")) return ignore(args); if (0 == strcmp(cmnd, "require_grid")) return require_grid(args); if (0 == strcmp(cmnd, "echo")) return echo(args); if (0 == strcmp(cmnd, "skip")) return skip(args); if (0 == strcmp(cmnd, "use_proj4_init_rules")) return use_proj4_init_rules(args); return 0; } namespace { // anonymous namespace static const struct { /* cppcheck-suppress unusedStructMember */ const char *the_err_const; /* cppcheck-suppress unusedStructMember */ int the_errno; } lookup[] = { {"invalid_op", PROJ_ERR_INVALID_OP}, {"invalid_op_wrong_syntax", PROJ_ERR_INVALID_OP_WRONG_SYNTAX}, {"invalid_op_missing_arg", PROJ_ERR_INVALID_OP_MISSING_ARG}, {"invalid_op_illegal_arg_value", PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE}, {"invalid_op_mutually_exclusive_args", PROJ_ERR_INVALID_OP_MUTUALLY_EXCLUSIVE_ARGS}, {"invalid_op_file_not_found_or_invalid", PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID}, {"coord_transfm", PROJ_ERR_COORD_TRANSFM}, {"coord_transfm_invalid_coord", PROJ_ERR_COORD_TRANSFM_INVALID_COORD}, {"coord_transfm_outside_projection_domain", PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN}, {"coord_transfm_no_operation", PROJ_ERR_COORD_TRANSFM_NO_OPERATION}, {"coord_transfm_outside_grid", PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID}, {"coord_transfm_grid_at_nodata", PROJ_ERR_COORD_TRANSFM_GRID_AT_NODATA}, {"other", PROJ_ERR_OTHER}, {"api_misuse", PROJ_ERR_OTHER_API_MISUSE}, {"no_inverse_op", PROJ_ERR_OTHER_NO_INVERSE_OP}, {"network_error", PROJ_ERR_OTHER_NETWORK_ERROR}, }; } // anonymous namespace static int list_err_codes(void) { int i; const int n = sizeof lookup / sizeof lookup[0]; for (i = 0; i < n; i++) { fprintf(T.fout, "%25s (%2.2d): %s\n", lookup[i].the_err_const, lookup[i].the_errno, proj_errno_string(lookup[i].the_errno)); } return 0; } static const char *err_const_from_errno(int err) { size_t i; const size_t n = sizeof lookup / sizeof lookup[0]; for (i = 0; i < n; i++) { if (err == lookup[i].the_errno) return lookup[i].the_err_const; } return "unknown"; } static int errno_from_err_const(const char *err_const) { const size_t n = sizeof lookup / sizeof lookup[0]; size_t i, len; int ret; char tolower_err_const[100] = {}; /* Make a lower case copy for matching */ for (i = 0; i < 99; i++) { if (0 == err_const[i] || isspace(err_const[i])) break; tolower_err_const[i] = (char)tolower(err_const[i]); } tolower_err_const[i] = 0; /* If it looks numeric, return that numeric */ ret = (int)pj_atof(err_const); if (0 != ret) return ret; /* Else try to find a matching identifier */ len = strlen(tolower_err_const); for (i = 0; i < n; i++) { if (0 == strncmp(lookup[i].the_err_const, err_const, len)) return lookup[i].the_errno; } /* On failure, return something unlikely */ return 9999; } static int errmsg(int errlev, const char *msg, ...) { va_list args; va_start(args, msg); vfprintf(stdout, msg, args); va_end(args); if (errlev) errno = errlev; return errlev; } /**************************************************************************************** FFIO - Flexible format I/O FFIO provides functionality for reading proj style instruction strings written in a less strict format than usual: * Whitespace is generally allowed everywhere * Comments can be written inline, '#' style * ... or as free format blocks The overall mission of FFIO is to facilitate communications of geodetic parameters and test material in a format that is highly human readable, and provides ample room for comment, documentation, and test material. See the PROJ ".gie" test suites for examples of supported formatting. ****************************************************************************************/ /***************************************************************************************/ static ffio *ffio_create(const char *const *tags, size_t n_tags, size_t max_record_size) { /**************************************************************************************** Constructor for the ffio object. ****************************************************************************************/ ffio *G = static_cast<ffio *>(calloc(1, sizeof(ffio))); if (nullptr == G) return nullptr; if (0 == max_record_size) max_record_size = 1000; G->args = static_cast<char *>(calloc(1, 5 * max_record_size)); if (nullptr == G->args) { free(G); return nullptr; } G->next_args = static_cast<char *>(calloc(1, max_record_size)); if (nullptr == G->args) { free(G->args); free(G); return nullptr; } G->args_size = 5 * max_record_size; G->next_args_size = max_record_size; G->tags = tags; G->n_tags = n_tags; return G; } /***************************************************************************************/ static ffio *ffio_destroy(ffio *G) { /**************************************************************************************** Free all allocated associated memory, then free G itself. For extra RAII compliance, the file object should also be closed if still open, but this will require additional control logic, and ffio is a gie tool specific package, so we fall back to asserting that fclose has been called prior to ffio_destroy. ****************************************************************************************/ free(G->args); free(G->next_args); free(G); return nullptr; } /***************************************************************************************/ static int at_decorative_element(ffio *G) { /**************************************************************************************** A decorative element consists of a line of at least 5 consecutive identical chars, starting at buffer position 0: "-----", "=====", "*****", etc. A decorative element serves as a end delimiter for the current element, and continues until a gie command verb is found at the start of a line ****************************************************************************************/ int i; char *c; if (nullptr == G) return 0; c = G->next_args; if (nullptr == c) return 0; if (0 == c[0]) return 0; for (i = 1; i < 5; i++) if (c[i] != c[0]) return 0; return 1; } /***************************************************************************************/ static const char *at_tag(ffio *G) { /**************************************************************************************** A start of a new command serves as an end delimiter for the current command ****************************************************************************************/ size_t j; for (j = 0; j < G->n_tags; j++) if (strncmp(G->next_args, G->tags[j], strlen(G->tags[j])) == 0) return G->tags[j]; return nullptr; } /***************************************************************************************/ static int at_end_delimiter(ffio *G) { /**************************************************************************************** An instruction consists of everything from its introductory tag to its end delimiter. An end delimiter can be either the introductory tag of the next instruction, or a "decorative element", i.e. one of the "ascii art" style block delimiters typically used to mark up block comments in a free format file. ****************************************************************************************/ if (G == nullptr) return 0; if (at_decorative_element(G)) return 1; if (at_tag(G)) return 1; return 0; } /***************************************************************************************/ static int nextline(ffio *G) { /**************************************************************************************** Read next line of input file. Returns 1 on success, 0 on failure. ****************************************************************************************/ G->next_args[0] = 0; if (T.skip) return 0; if (nullptr == fgets(G->next_args, (int)G->next_args_size - 1, G->f)) return 0; if (feof(G->f)) return 0; pj_chomp(G->next_args); G->next_lineno++; return 1; } /***************************************************************************************/ static int step_into_gie_block(ffio *G) { /**************************************************************************************** Make sure we're inside a <gie>-block. Return 1 on success, 0 otherwise. ****************************************************************************************/ /* Already inside */ if (G->level % 2) return 1; while (strncmp(G->next_args, "<gie>", strlen("<gie>")) != 0 && strncmp(G->next_args, "<gie-strict>", strlen("<gie-strict>")) != 0) { if (0 == nextline(G)) return 0; } G->level++; if (strncmp(G->next_args, "<gie-strict>", strlen("<gie-strict>")) == 0) { G->strict_mode = true; return 0; } else { /* We're ready at the start - now step into the block */ return nextline(G); } } /***************************************************************************************/ static int skip_to_next_tag(ffio *G) { /**************************************************************************************** Skip forward to the next command tag. Return 1 on success, 0 otherwise. ****************************************************************************************/ const char *c; if (0 == step_into_gie_block(G)) return 0; c = at_tag(G); /* If not already there - get there */ while (!c) { if (0 == nextline(G)) return 0; c = at_tag(G); } /* If we reached the end of a <gie> block, locate the next and retry */ if (0 == strcmp(c, "</gie>")) { G->level++; if (feof(G->f)) return 0; if (0 == step_into_gie_block(G)) return 0; G->args[0] = 0; return skip_to_next_tag(G); } G->lineno = G->next_lineno; return 1; } /* Add the most recently read line of input to the block already stored. */ static int append_args(ffio *G) { size_t skip_chars = 0; size_t next_len = strlen(G->next_args); size_t args_len = strlen(G->args); const char *tag = at_tag(G); if (tag) skip_chars = strlen(tag); /* +2: 1 for the space separator and 1 for the NUL termination. */ if (G->args_size < args_len + next_len - skip_chars + 2) { char *p = static_cast<char *>(realloc(G->args, 2 * G->args_size)); if (nullptr == p) return 0; G->args = p; G->args_size = 2 * G->args_size; } G->args[args_len] = ' '; strcpy(G->args + args_len + 1, G->next_args + skip_chars); G->next_args[0] = 0; return 1; } /***************************************************************************************/ static int get_inp(ffio *G) { /**************************************************************************************** The primary command reader for gie. Reads a block of gie input, cleans up repeated whitespace etc. The block is stored in G->args. Returns 1 on success, 0 otherwise. ****************************************************************************************/ G->args[0] = 0; // Special parsing in strict_mode: // - All non-comment/decoration lines must start with a valid tag // - Commands split on several lines should be terminated with " \" if (G->strict_mode) { while (nextline(G)) { G->lineno = G->next_lineno; if (G->next_args[0] == 0 || at_decorative_element(G)) { continue; } G->tag = at_tag(G); if (nullptr == G->tag) { another_failure(); fprintf(T.fout, "unsupported command line %d: %s\n", (int)G->lineno, G->next_args); return 0; } append_args(G); pj_shrink(G->args); while (G->args[0] != '\0' && G->args[strlen(G->args) - 1] == '\\') { G->args[strlen(G->args) - 1] = 0; if (!nextline(G)) { return 0; } G->lineno = G->next_lineno; append_args(G); pj_shrink(G->args); } if (0 == strcmp(G->tag, "</gie-strict>")) { G->level++; G->strict_mode = false; } return 1; } return 0; } if (0 == skip_to_next_tag(G)) { // If we just entered <gie-strict>, re-enter to read the first command if (G->strict_mode) return get_inp(G); return 0; } G->tag = at_tag(G); if (nullptr == G->tag) return 0; do { append_args(G); if (0 == nextline(G)) return 0; } while (!at_end_delimiter(G)); pj_shrink(G->args); return 1; }
cpp
PROJ
data/projects/PROJ/src/apps/utils.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Utilities for command line arguments * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2019, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "utils.h" #include <stdlib.h> #include <string.h> bool validate_form_string_for_numbers(const char *formatString) { /* Only accepts '%[+]?[number]?[.]?[number]?[e|E|f|F|g|G]' */ bool valid = true; if (formatString[0] != '%') valid = false; else { const auto oformLen = strlen(formatString); for (int i = 1; i < static_cast<int>(oformLen) - 1; i++) { if (!(formatString[i] == '.' || formatString[i] == '+' || (formatString[i] >= '0' && formatString[i] <= '9'))) { valid = false; break; } } if (valid) { valid = formatString[oformLen - 1] == 'e' || formatString[oformLen - 1] == 'E' || formatString[oformLen - 1] == 'f' || formatString[oformLen - 1] == 'F' || formatString[oformLen - 1] == 'g' || formatString[oformLen - 1] == 'G'; } } return valid; } // Some older versions of mingw_w64 do not support the F formatter // GCC 7 might not be the exact version... #if defined(__MINGW32__) && __GNUC__ <= 7 #define MY_FPRINTF0(fmt0, fmt, ...) \ do { \ if (*ptr == 'e') \ fprintf(f, "%" fmt0 fmt "e", __VA_ARGS__); \ else if (*ptr == 'E') \ fprintf(f, "%" fmt0 fmt "E", __VA_ARGS__); \ else if (*ptr == 'f') \ fprintf(f, "%" fmt0 fmt "f", __VA_ARGS__); \ else if (*ptr == 'g') \ fprintf(f, "%" fmt0 fmt "g", __VA_ARGS__); \ else if (*ptr == 'G') \ fprintf(f, "%" fmt0 fmt "G", __VA_ARGS__); \ else { \ fprintf(stderr, "Wrong formatString '%s'\n", formatString); \ return; \ } \ ++ptr; \ } while (0) #else #define MY_FPRINTF0(fmt0, fmt, ...) \ do { \ if (*ptr == 'e') \ fprintf(f, "%" fmt0 fmt "e", __VA_ARGS__); \ else if (*ptr == 'E') \ fprintf(f, "%" fmt0 fmt "E", __VA_ARGS__); \ else if (*ptr == 'f') \ fprintf(f, "%" fmt0 fmt "f", __VA_ARGS__); \ else if (*ptr == 'F') \ fprintf(f, "%" fmt0 fmt "F", __VA_ARGS__); \ else if (*ptr == 'g') \ fprintf(f, "%" fmt0 fmt "g", __VA_ARGS__); \ else if (*ptr == 'G') \ fprintf(f, "%" fmt0 fmt "G", __VA_ARGS__); \ else { \ fprintf(stderr, "Wrong formatString '%s'\n", formatString); \ return; \ } \ ++ptr; \ } while (0) #endif #define MY_FPRINTF(fmt, ...) \ do { \ if (withPlus) \ MY_FPRINTF0("+", fmt, __VA_ARGS__); \ else \ MY_FPRINTF0("", fmt, __VA_ARGS__); \ } while (0) static int parseInt(const char *&ptr) { int val = 0; while (*ptr >= '0' && *ptr <= '9') { val = val * 10 + (*ptr - '0'); if (val > 1000) { return -1; } ++ptr; } return val; } // This function is a limited version of fprintf(f, formatString, val) where // formatString is a subset of formatting strings accepted by // validate_form_string_for_numbers(). // This methods makes CodeQL cpp/tainted-format-string check happy. void limited_fprintf_for_number(FILE *f, const char *formatString, double val) { const char *ptr = formatString; if (*ptr != '%') { fprintf(stderr, "Wrong formatString '%s'\n", formatString); return; } ++ptr; const bool withPlus = (*ptr == '+'); if (withPlus) { ++ptr; } if (*ptr >= '0' && *ptr <= '9') { const bool isLeadingZero = *ptr == '0'; const int w = parseInt(ptr); if (w < 0 || *ptr == 0) { fprintf(stderr, "Wrong formatString '%s'\n", formatString); return; } if (*ptr == '.') { ++ptr; if (*ptr >= '0' && *ptr <= '9') { const int p = parseInt(ptr); if (p < 0 || *ptr == 0) { fprintf(stderr, "Wrong formatString '%s'\n", formatString); return; } if (isLeadingZero) { MY_FPRINTF("0*.*", w, p, val); } else { MY_FPRINTF("*.*", w, p, val); } } else { if (isLeadingZero) { MY_FPRINTF("0*.", w, val); } else { MY_FPRINTF("*.", w, val); } } } else { if (isLeadingZero) { MY_FPRINTF("0*", w, val); } else { MY_FPRINTF("*", w, val); } } } else if (*ptr == '.') { ++ptr; if (*ptr >= '0' && *ptr <= '9') { const int p = parseInt(ptr); if (p < 0 || *ptr == 0) { fprintf(stderr, "Wrong formatString '%s'\n", formatString); return; } MY_FPRINTF(".*", p, val); } else { MY_FPRINTF(".", val); } } else { MY_FPRINTF("", val); } if (*ptr != 0) { fprintf(stderr, "Wrong formatString '%s'\n", formatString); return; } }
cpp
PROJ
data/projects/PROJ/src/apps/cs2cs.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Mainline program sort of like ``proj'' for converting between * two coordinate systems. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #define FROM_PROJ_CPP #include <ctype.h> #include <locale.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cassert> #include <iostream> #include <string> #include <vector> #include <proj/io.hpp> #include <proj/metadata.hpp> #include <proj/util.hpp> #include <proj/internal/internal.hpp> // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_experimental.h" #include "proj_internal.h" #include "emess.h" #include "utils.h" // clang-format on #define MAX_LINE 1000 static PJ *transformation = nullptr; static bool srcIsLongLat = false; static double srcToRadians = 0.0; static bool destIsLongLat = false; static double destToRadians = 0.0; static bool destIsLatLong = false; static int reversein = 0, /* != 0 reverse input arguments */ reverseout = 0, /* != 0 reverse output arguments */ echoin = 0, /* echo input data to output line */ tag = '#'; /* beginning of line tag character */ static const char *oform = nullptr; /* output format for x-y or decimal degrees */ static char oform_buffer[16]; /* buffer for oform when using -d */ static const char *oterr = "*\t*"; /* output line for unprojectable input */ static const char *usage = "%s\nusage: %s [-dDeEfIlrstvwW [args]]\n" " [[--area name_or_code] | [--bbox " "west_long,south_lat,east_long,north_lat]]\n" " [--authority {name}] [--3d]\n" " [--accuracy {accuracy}] [--only-best[=yes|=no]] " "[--no-ballpark]\n" " [--s_epoch {epoch}] [--t_epoch {epoch}]\n" " [+opt[=arg] ...] [+to +opt[=arg] ...] [file ...]\n"; static double (*informat)(const char *, char **); /* input data deformatter function */ using namespace NS_PROJ::io; using namespace NS_PROJ::metadata; using namespace NS_PROJ::util; using namespace NS_PROJ::internal; /************************************************************************/ /* process() */ /* */ /* File processing function. */ /************************************************************************/ static void process(FILE *fid) { char line[MAX_LINE + 3], *s, pline[40]; PJ_UV data; int nLineNumber = 0; while (true) { double z; ++nLineNumber; ++emess_dat.File_line; if (!(s = fgets(line, MAX_LINE, fid))) break; if (nLineNumber == 1 && static_cast<uint8_t>(s[0]) == 0xEF && static_cast<uint8_t>(s[1]) == 0xBB && static_cast<uint8_t>(s[2]) == 0xBF) { // Skip UTF-8 Byte Order Marker (BOM) s += 3; } const char *pszLineAfterBOM = s; if (!strchr(s, '\n')) { /* overlong line */ int c; (void)strcat(s, "\n"); /* gobble up to newline */ while ((c = fgetc(fid)) != EOF && c != '\n') ; } if (*s == tag) { fputs(line, stdout); continue; } if (reversein) { data.v = (*informat)(s, &s); data.u = (*informat)(s, &s); } else { data.u = (*informat)(s, &s); data.v = (*informat)(s, &s); } z = strtod(s, &s); /* To avoid breaking existing tests, we read what is a possible t */ /* component of the input and rewind the s-pointer so that the final */ /* output has consistent behavior, with or without t values. */ /* This is a bit of a hack, in most cases 4D coordinates will be */ /* written to STDOUT (except when using -E) but the output format */ /* specified with -f is not respected for the t component, rather it */ /* is forward verbatim from the input. */ char *before_time = s; double t = strtod(s, &s); if (s == before_time) t = HUGE_VAL; s = before_time; if (data.v == HUGE_VAL) data.u = HUGE_VAL; if (!*s && (s > line)) --s; /* assumed we gobbled \n */ if (echoin) { char temp; temp = *s; *s = '\0'; (void)fputs(pszLineAfterBOM, stdout); *s = temp; putchar('\t'); } if (data.u != HUGE_VAL) { if (srcIsLongLat && fabs(srcToRadians - M_PI / 180) < 1e-10) { /* dmstor gives values to radians. Convert now to the SRS unit */ data.u /= srcToRadians; data.v /= srcToRadians; } PJ_COORD coord; coord.xyzt.x = data.u; coord.xyzt.y = data.v; coord.xyzt.z = z; coord.xyzt.t = t; coord = proj_trans(transformation, PJ_FWD, coord); data.u = coord.xyz.x; data.v = coord.xyz.y; z = coord.xyz.z; } if (data.u == HUGE_VAL) /* error output */ fputs(oterr, stdout); else if (destIsLongLat && !oform) { /*ascii DMS output */ // rtodms() expect radians: convert from the output SRS unit data.u *= destToRadians; data.v *= destToRadians; if (destIsLatLong) { if (reverseout) { fputs(rtodms(pline, sizeof(pline), data.v, 'E', 'W'), stdout); putchar('\t'); fputs(rtodms(pline, sizeof(pline), data.u, 'N', 'S'), stdout); } else { fputs(rtodms(pline, sizeof(pline), data.u, 'N', 'S'), stdout); putchar('\t'); fputs(rtodms(pline, sizeof(pline), data.v, 'E', 'W'), stdout); } } else if (reverseout) { fputs(rtodms(pline, sizeof(pline), data.v, 'N', 'S'), stdout); putchar('\t'); fputs(rtodms(pline, sizeof(pline), data.u, 'E', 'W'), stdout); } else { fputs(rtodms(pline, sizeof(pline), data.u, 'E', 'W'), stdout); putchar('\t'); fputs(rtodms(pline, sizeof(pline), data.v, 'N', 'S'), stdout); } } else { /* x-y or decimal degree ascii output */ if (destIsLongLat) { data.v *= destToRadians * RAD_TO_DEG; data.u *= destToRadians * RAD_TO_DEG; } if (reverseout) { limited_fprintf_for_number(stdout, oform, data.v); putchar('\t'); limited_fprintf_for_number(stdout, oform, data.u); } else { limited_fprintf_for_number(stdout, oform, data.u); putchar('\t'); limited_fprintf_for_number(stdout, oform, data.v); } } putchar(' '); if (oform != nullptr) limited_fprintf_for_number(stdout, oform, z); else printf("%.3f", z); if (s) printf("%s", s); else printf("\n"); fflush(stdout); } } /************************************************************************/ /* instantiate_crs() */ /************************************************************************/ static PJ *instantiate_crs(const std::string &definition, bool &isLongLatCS, double &toRadians, bool &isLatFirst) { PJ *crs = proj_create(nullptr, pj_add_type_crs_if_needed(definition).c_str()); if (!crs) { return nullptr; } isLongLatCS = false; toRadians = 0.0; isLatFirst = false; auto type = proj_get_type(crs); if (type == PJ_TYPE_BOUND_CRS) { auto base = proj_get_source_crs(nullptr, crs); proj_destroy(crs); crs = base; type = proj_get_type(crs); } if (type == PJ_TYPE_GEOGRAPHIC_2D_CRS || type == PJ_TYPE_GEOGRAPHIC_3D_CRS || type == PJ_TYPE_GEODETIC_CRS) { auto cs = proj_crs_get_coordinate_system(nullptr, crs); assert(cs); const char *axisName = ""; proj_cs_get_axis_info(nullptr, cs, 0, &axisName, // name, nullptr, // abbrev nullptr, // direction &toRadians, nullptr, // unit name nullptr, // unit authority nullptr // unit code ); isLatFirst = NS_PROJ::internal::ci_find(std::string(axisName), "latitude") != std::string::npos; isLongLatCS = isLatFirst || NS_PROJ::internal::ci_find( std::string(axisName), "longitude") != std::string::npos; proj_destroy(cs); } return crs; } /************************************************************************/ /* get_geog_crs_proj_string_from_proj_crs() */ /************************************************************************/ static std::string get_geog_crs_proj_string_from_proj_crs(PJ *src, double &toRadians, bool &isLatFirst) { auto srcType = proj_get_type(src); if (srcType != PJ_TYPE_PROJECTED_CRS) { return std::string(); } auto base = proj_get_source_crs(nullptr, src); assert(base); auto baseType = proj_get_type(base); if (baseType != PJ_TYPE_GEOGRAPHIC_2D_CRS && baseType != PJ_TYPE_GEOGRAPHIC_3D_CRS) { proj_destroy(base); return std::string(); } auto cs = proj_crs_get_coordinate_system(nullptr, base); assert(cs); const char *axisName = ""; proj_cs_get_axis_info(nullptr, cs, 0, &axisName, // name, nullptr, // abbrev nullptr, // direction &toRadians, nullptr, // unit name nullptr, // unit authority nullptr // unit code ); isLatFirst = NS_PROJ::internal::ci_find(std::string(axisName), "latitude") != std::string::npos; proj_destroy(cs); auto retCStr = proj_as_proj_string(nullptr, base, PJ_PROJ_5, nullptr); std::string ret(retCStr ? retCStr : ""); proj_destroy(base); return ret; } // --------------------------------------------------------------------------- static bool is3DCRS(const PJ *crs) { auto type = proj_get_type(crs); if (type == PJ_TYPE_COMPOUND_CRS) return true; if (type == PJ_TYPE_GEOGRAPHIC_3D_CRS) return true; if (type == PJ_TYPE_GEODETIC_CRS || type == PJ_TYPE_PROJECTED_CRS || type == PJ_TYPE_DERIVED_PROJECTED_CRS) { auto cs = proj_crs_get_coordinate_system(nullptr, crs); assert(cs); const bool ret = proj_cs_get_axis_count(nullptr, cs) == 3; proj_destroy(cs); return ret; } return false; } /************************************************************************/ /* main() */ /************************************************************************/ int main(int argc, char **argv) { char *arg; char **eargv = argv; std::string fromStr; std::string toStr; FILE *fid; int eargc = 0, mon = 0; int have_to_flag = 0, inverse = 0; int use_env_locale = 0; pj_stderr_proj_lib_deprecation_warning(); if (argc == 0) { exit(1); } /* This is just to check that pj_init() is locale-safe */ /* Used by nad/testvarious */ if (getenv("PROJ_USE_ENV_LOCALE") != nullptr) use_env_locale = 1; /* Enable compatibility mode for init=epsg:XXXX by default */ if (getenv("PROJ_USE_PROJ4_INIT_RULES") == nullptr) { proj_context_use_proj4_init_rules(nullptr, true); } if ((emess_dat.Prog_name = strrchr(*argv, DIR_CHAR)) != nullptr) ++emess_dat.Prog_name; else emess_dat.Prog_name = *argv; inverse = !strncmp(emess_dat.Prog_name, "inv", 3); if (argc <= 1) { (void)fprintf(stderr, usage, pj_get_release(), emess_dat.Prog_name); exit(0); } // First pass to check if we have "cs2cs [-bla]* <SRC> <DEST> [<filename>]" // syntax bool isProj4StyleSyntax = false; for (int i = 1; i < argc; i++) { if (argv[i][0] == '+') { isProj4StyleSyntax = true; break; } } ExtentPtr bboxFilter; std::string area; const char *authority = nullptr; double accuracy = -1; bool allowBallpark = true; bool onlyBestSet = false; bool errorIfBestTransformationNotAvailable = false; bool promoteTo3D = false; std::string sourceEpoch; std::string targetEpoch; /* process run line arguments */ while (--argc > 0) { /* collect run line arguments */ ++argv; if (strcmp(*argv, "--area") == 0) { ++argv; --argc; if (argc == 0) { emess(1, "missing argument for --area"); std::exit(1); } area = *argv; } else if (strcmp(*argv, "--bbox") == 0) { ++argv; --argc; if (argc == 0) { emess(1, "missing argument for --bbox"); std::exit(1); } auto bboxStr(*argv); auto bbox(split(bboxStr, ',')); if (bbox.size() != 4) { std::cerr << "Incorrect number of values for option --bbox: " << bboxStr << std::endl; std::exit(1); } try { bboxFilter = Extent::createFromBBOX( c_locale_stod(bbox[0]), c_locale_stod(bbox[1]), c_locale_stod(bbox[2]), c_locale_stod(bbox[3])) .as_nullable(); } catch (const std::exception &e) { std::cerr << "Invalid value for option --bbox: " << bboxStr << ", " << e.what() << std::endl; std::exit(1); } } else if (strcmp(*argv, "--accuracy") == 0) { ++argv; --argc; if (argc == 0) { emess(1, "missing argument for --accuracy"); std::exit(1); } try { accuracy = c_locale_stod(*argv); } catch (const std::exception &e) { std::cerr << "Invalid value for option --accuracy: " << e.what() << std::endl; std::exit(1); } } else if (strcmp(*argv, "--authority") == 0) { ++argv; --argc; if (argc == 0) { emess(1, "missing argument for --authority"); std::exit(1); } authority = *argv; } else if (strcmp(*argv, "--no-ballpark") == 0) { allowBallpark = false; } else if (strcmp(*argv, "--only-best") == 0 || strcmp(*argv, "--only-best=yes") == 0) { onlyBestSet = true; errorIfBestTransformationNotAvailable = true; } else if (strcmp(*argv, "--only-best=no") == 0) { onlyBestSet = true; errorIfBestTransformationNotAvailable = false; } else if (strcmp(*argv, "--3d") == 0) { promoteTo3D = true; } else if (strcmp(*argv, "--s_epoch") == 0) { ++argv; --argc; if (argc == 0) { emess(1, "missing argument for --s_epoch"); std::exit(1); } sourceEpoch = *argv; } else if (strcmp(*argv, "--t_epoch") == 0) { ++argv; --argc; if (argc == 0) { emess(1, "missing argument for --t_epoch"); std::exit(1); } targetEpoch = *argv; } else if (**argv == '-') { for (arg = *argv;;) { switch (*++arg) { case '\0': /* position of "stdin" */ if (arg[-1] == '-') eargv[eargc++] = const_cast<char *>("-"); break; case 'v': /* monitor dump of initialization */ mon = 1; continue; case 'I': /* alt. method to spec inverse */ inverse = 1; continue; case 'E': /* echo ascii input to ascii output */ echoin = 1; continue; case 't': /* set col. one char */ if (arg[1]) tag = *++arg; else emess(1, "missing -t col. 1 tag"); continue; case 'l': /* list projections, ellipses or units */ if (!arg[1] || arg[1] == 'p' || arg[1] == 'P') { /* list projections */ const struct PJ_LIST *lp; int do_long = arg[1] == 'P', c; const char *str; for (lp = proj_list_operations(); lp->id; ++lp) { (void)printf("%s : ", lp->id); if (do_long) /* possibly multiline description */ (void)puts(*lp->descr); else { /* first line, only */ str = *lp->descr; while ((c = *str++) && c != '\n') putchar(c); putchar('\n'); } } } else if (arg[1] == '=') { /* list projection 'descr' */ const struct PJ_LIST *lp; arg += 2; for (lp = proj_list_operations(); lp->id; ++lp) if (!strcmp(lp->id, arg)) { (void)printf("%9s : %s\n", lp->id, *lp->descr); break; } } else if (arg[1] == 'e') { /* list ellipses */ const struct PJ_ELLPS *le; for (le = proj_list_ellps(); le->id; ++le) (void)printf("%9s %-16s %-16s %s\n", le->id, le->major, le->ell, le->name); } else if (arg[1] == 'u') { /* list units */ auto units = proj_get_units_from_database( nullptr, nullptr, "linear", false, nullptr); for (int i = 0; units && units[i]; i++) { if (units[i]->proj_short_name) { (void)printf("%12s %-20.15g %s\n", units[i]->proj_short_name, units[i]->conv_factor, units[i]->name); } } proj_unit_list_destroy(units); } else if (arg[1] == 'm') { /* list prime meridians */ (void)fprintf(stderr, "This list is no longer updated, and some values may " "conflict with other sources.\n"); const struct PJ_PRIME_MERIDIANS *lpm; for (lpm = proj_list_prime_meridians(); lpm->id; ++lpm) (void)printf("%12s %-30s\n", lpm->id, lpm->defn); } else emess(1, "invalid list option: l%c", arg[1]); exit(0); /* cppcheck-suppress duplicateBreak */ continue; /* artificial */ case 'e': /* error line alternative */ if (--argc <= 0) noargument: emess(1, "missing argument for -%c", *arg); oterr = *++argv; continue; case 'W': /* specify seconds precision */ case 'w': /* -W for constant field width */ { char c = arg[1]; // Check that the value is in the [0, 8] range if (c >= '0' && c <= '8' && ((arg[2] == 0 || !(arg[2] >= '0' && arg[2] <= '9')))) { set_rtodms(c - '0', *arg == 'W'); ++arg; } else emess(1, "-W argument missing or not in range [0,8]"); continue; } case 'f': /* alternate output format degrees or xy */ if (--argc <= 0) goto noargument; oform = *++argv; continue; case 'r': /* reverse input */ reversein = 1; continue; case 's': /* reverse output */ reverseout = 1; continue; case 'D': /* set debug level */ { if (--argc <= 0) goto noargument; int log_level = atoi(*++argv); if (log_level <= 0) { proj_log_level(pj_get_default_ctx(), PJ_LOG_NONE); } else if (log_level == 1) { proj_log_level(pj_get_default_ctx(), PJ_LOG_ERROR); } else if (log_level == 2) { proj_log_level(pj_get_default_ctx(), PJ_LOG_DEBUG); } else if (log_level == 3) { proj_log_level(pj_get_default_ctx(), PJ_LOG_TRACE); } else { proj_log_level(pj_get_default_ctx(), PJ_LOG_TELL); } continue; } case 'd': if (--argc <= 0) goto noargument; snprintf(oform_buffer, sizeof(oform_buffer), "%%.%df", atoi(*++argv)); oform = oform_buffer; break; default: emess(1, "invalid option: -%c", *arg); break; } break; } } else if (!isProj4StyleSyntax) { if (fromStr.empty()) fromStr = *argv; else if (toStr.empty()) toStr = *argv; else { /* assumed to be input file name(s) */ eargv[eargc++] = *argv; } } else if (strcmp(*argv, "+to") == 0) { have_to_flag = 1; } else if (**argv == '+') { /* + argument */ if (have_to_flag) { if (!toStr.empty()) toStr += ' '; toStr += *argv; } else { if (!fromStr.empty()) fromStr += ' '; fromStr += *argv; } } else if (!have_to_flag) { fromStr = *argv; } else if (toStr.empty()) { toStr = *argv; } else /* assumed to be input file name(s) */ eargv[eargc++] = *argv; } if (eargc == 0) /* if no specific files force sysin */ eargv[eargc++] = const_cast<char *>("-"); if (oform) { if (!validate_form_string_for_numbers(oform)) { emess(3, "invalid format string"); exit(0); } } if (bboxFilter && !area.empty()) { std::cerr << "ERROR: --bbox and --area are exclusive" << std::endl; std::exit(1); } PJ_AREA *pj_area = nullptr; if (!area.empty()) { DatabaseContextPtr dbContext; try { dbContext = DatabaseContext::create().as_nullable(); } catch (const std::exception &e) { std::cerr << "ERROR: Cannot create database connection: " << e.what() << std::endl; std::exit(1); } // Process area of use try { if (area.find(' ') == std::string::npos && area.find(':') != std::string::npos) { auto tokens = split(area, ':'); if (tokens.size() == 2) { const std::string &areaAuth = tokens[0]; const std::string &areaCode = tokens[1]; bboxFilter = AuthorityFactory::create( NN_NO_CHECK(dbContext), areaAuth) ->createExtent(areaCode) .as_nullable(); } } if (!bboxFilter) { auto authFactory = AuthorityFactory::create( NN_NO_CHECK(dbContext), std::string()); auto res = authFactory->listAreaOfUseFromName(area, false); if (res.size() == 1) { bboxFilter = AuthorityFactory::create( NN_NO_CHECK(dbContext), res.front().first) ->createExtent(res.front().second) .as_nullable(); } else { res = authFactory->listAreaOfUseFromName(area, true); if (res.size() == 1) { bboxFilter = AuthorityFactory::create(NN_NO_CHECK(dbContext), res.front().first) ->createExtent(res.front().second) .as_nullable(); } else if (res.empty()) { std::cerr << "No area of use matching provided name" << std::endl; std::exit(1); } else { std::cerr << "Several candidates area of use " "matching provided name :" << std::endl; for (const auto &candidate : res) { auto obj = AuthorityFactory::create(NN_NO_CHECK(dbContext), candidate.first) ->createExtent(candidate.second); std::cerr << " " << candidate.first << ":" << candidate.second << " : " << *obj->description() << std::endl; } std::exit(1); } } } } catch (const std::exception &e) { std::cerr << "Area of use retrieval failed: " << e.what() << std::endl; std::exit(1); } } if (bboxFilter) { auto geogElts = bboxFilter->geographicElements(); if (geogElts.size() == 1) { auto bbox = std::dynamic_pointer_cast<GeographicBoundingBox>( geogElts[0].as_nullable()); if (bbox) { pj_area = proj_area_create(); proj_area_set_bbox(pj_area, bbox->westBoundLongitude(), bbox->southBoundLatitude(), bbox->eastBoundLongitude(), bbox->northBoundLatitude()); if (bboxFilter->description().has_value()) { proj_area_set_name(pj_area, bboxFilter->description()->c_str()); } } } } /* * If the user has requested inverse, then just reverse the * coordinate systems. */ if (inverse) { std::swap(fromStr, toStr); } if (use_env_locale) { /* Set locale from environment */ setlocale(LC_ALL, ""); } if (fromStr.empty() && toStr.empty()) { emess(3, "missing source and target coordinate systems"); } proj_context_use_proj4_init_rules( nullptr, proj_context_get_use_proj4_init_rules(nullptr, TRUE)); PJ *src = nullptr; if (!fromStr.empty()) { bool ignored; src = instantiate_crs(fromStr, srcIsLongLat, srcToRadians, ignored); if (!src) { emess(3, "cannot instantiate source coordinate system"); } } PJ *dst = nullptr; if (!toStr.empty()) { dst = instantiate_crs(toStr, destIsLongLat, destToRadians, destIsLatLong); if (!dst) { emess(3, "cannot instantiate target coordinate system"); } } if (toStr.empty()) { assert(src); toStr = get_geog_crs_proj_string_from_proj_crs(src, destToRadians, destIsLatLong); if (toStr.empty()) { emess(3, "missing target CRS and source CRS is not a projected CRS"); } destIsLongLat = true; } else if (fromStr.empty()) { assert(dst); bool ignored; fromStr = get_geog_crs_proj_string_from_proj_crs(dst, srcToRadians, ignored); if (fromStr.empty()) { emess(3, "missing source CRS and target CRS is not a projected CRS"); } srcIsLongLat = true; } proj_destroy(src); proj_destroy(dst); src = proj_create(nullptr, pj_add_type_crs_if_needed(fromStr).c_str()); dst = proj_create(nullptr, pj_add_type_crs_if_needed(toStr).c_str()); if (promoteTo3D) { auto src3D = proj_crs_promote_to_3D(nullptr, nullptr, src); if (src3D) { proj_destroy(src); src = src3D; } auto dst3D = proj_crs_promote_to_3D(nullptr, nullptr, dst); if (dst3D) { proj_destroy(dst); dst = dst3D; } } else { // Auto-promote source/target CRS if it is specified by its name, // if it has a known 3D version of it and that the other CRS is 3D. // e.g cs2cs "WGS 84 + EGM96 height" "WGS 84" if (is3DCRS(dst) && !is3DCRS(src) && proj_get_id_code(src, 0) != nullptr && Identifier::isEquivalentName(fromStr.c_str(), proj_get_name(src))) { auto promoted = proj_crs_promote_to_3D(nullptr, nullptr, src); if (promoted) { if (proj_get_id_code(promoted, 0) != nullptr) { proj_destroy(src); src = promoted; } else { proj_destroy(promoted); } } } else if (is3DCRS(src) && !is3DCRS(dst) && proj_get_id_code(dst, 0) != nullptr && Identifier::isEquivalentName(toStr.c_str(), proj_get_name(dst))) { auto promoted = proj_crs_promote_to_3D(nullptr, nullptr, dst); if (promoted) { if (proj_get_id_code(promoted, 0) != nullptr) { proj_destroy(dst); dst = promoted; } else { proj_destroy(promoted); } } } } if (!sourceEpoch.empty()) { PJ *srcMetadata = nullptr; double sourceEpochDbl; try { sourceEpochDbl = c_locale_stod(sourceEpoch); } catch (const std::exception &e) { sourceEpochDbl = 0; emess(3, "%s", e.what()); } srcMetadata = proj_coordinate_metadata_create(nullptr, src, sourceEpochDbl); if (!srcMetadata) { emess(3, "cannot instantiate source coordinate system"); } proj_destroy(src); src = srcMetadata; } if (!targetEpoch.empty()) { PJ *dstMetadata = nullptr; double targetEpochDbl; try { targetEpochDbl = c_locale_stod(targetEpoch); } catch (const std::exception &e) { targetEpochDbl = 0; emess(3, "%s", e.what()); } dstMetadata = proj_coordinate_metadata_create(nullptr, dst, targetEpochDbl); if (!dstMetadata) { emess(3, "cannot instantiate target coordinate system"); } proj_destroy(dst); dst = dstMetadata; } std::string authorityOption; /* keep this variable in this outer scope ! */ std::string accuracyOption; /* keep this variable in this outer scope ! */ std::vector<const char *> options; if (authority) { authorityOption = "AUTHORITY="; authorityOption += authority; options.push_back(authorityOption.data()); } if (accuracy >= 0) { accuracyOption = "ACCURACY="; accuracyOption += toString(accuracy); options.push_back(accuracyOption.data()); } if (!allowBallpark) { options.push_back("ALLOW_BALLPARK=NO"); } if (onlyBestSet) { if (errorIfBestTransformationNotAvailable) { options.push_back("ONLY_BEST=YES"); } else { options.push_back("ONLY_BEST=NO"); } } options.push_back(nullptr); transformation = proj_create_crs_to_crs_from_pj(nullptr, src, dst, pj_area, options.data()); proj_destroy(src); proj_destroy(dst); proj_area_destroy(pj_area); if (!transformation) { emess(3, "cannot initialize transformation\ncause: %s", proj_errno_string(proj_context_errno(nullptr))); } if (use_env_locale) { /* Restore C locale to avoid issues in parsing/outputting numbers*/ setlocale(LC_ALL, "C"); } if (mon) { printf("%c ---- From Coordinate System ----\n", tag); printf("%s\n", fromStr.c_str()); printf("%c ---- To Coordinate System ----\n", tag); printf("%s\n", toStr.c_str()); } /* set input formatting control */ if (srcIsLongLat && fabs(srcToRadians - M_PI / 180) < 1e-10) informat = dmstor; else { informat = strtod; } if (!destIsLongLat && !oform) oform = "%.2f"; /* process input file list */ for (; eargc--; ++eargv) { if (**eargv == '-') { fid = stdin; emess_dat.File_name = const_cast<char *>("<stdin>"); } else { if ((fid = fopen(*eargv, "rt")) == nullptr) { emess(-2, "input file: %s", *eargv); continue; } emess_dat.File_name = *eargv; } emess_dat.File_line = 0; process(fid); fclose(fid); emess_dat.File_name = nullptr; } proj_destroy(transformation); proj_cleanup(); exit(0); /* normal completion */ }
cpp
PROJ
data/projects/PROJ/src/apps/proj.cpp
/* <<<< Cartographic projection filter program >>>> */ #include "proj.h" #include "emess.h" #include "proj_experimental.h" #include "proj_internal.h" #include "utils.h" #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <proj/crs.hpp> #include <vector> #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__WIN32__) #include <fcntl.h> #include <io.h> #define SET_BINARY_MODE(file) _setmode(_fileno(file), O_BINARY) #else #define SET_BINARY_MODE(file) #endif #define MAX_LINE 1000 #define PJ_INVERSE(P) (P->inv ? 1 : 0) static PJ *Proj = nullptr; static PJ *ProjForFactors = nullptr; static bool swapAxisCrs = false; static union { PJ_XY (*fwd)(PJ_LP, PJ *); PJ_LP (*inv)(PJ_XY, PJ *); } proj; static int reversein = 0, /* != 0 reverse input arguments */ reverseout = 0, /* != 0 reverse output arguments */ bin_in = 0, /* != 0 then binary input */ bin_out = 0, /* != 0 then binary output */ echoin = 0, /* echo input data to output line */ tag = '#', /* beginning of line tag character */ inverse = 0, /* != 0 then inverse projection */ prescale = 0, /* != 0 apply cartesian scale factor */ dofactors = 0, /* determine scale factors */ very_verby = 0, /* very verbose mode */ postscale = 0; static const char *oform = nullptr; /* output format for x-y or decimal degrees */ static char oform_buffer[16]; /* Buffer for oform when using -d */ static const char *oterr = "*\t*", /* output line for unprojectable input */ *usage = "%s\nusage: %s [-bdeEfiIlmorsStTvVwW [args]] [+opt[=arg] ...] " "[file ...]\n"; static PJ_FACTORS facs; static double (*informat)(const char *, char **), /* input data deformatter function */ fscale = 0.; /* cartesian scale factor */ /* file processing function */ static void process(FILE *fid) { char line[MAX_LINE + 3], *s = nullptr, pline[40]; PJ_COORD data; for (;;) { int facs_bad = 0; ++emess_dat.File_line; if (bin_in) { /* binary input */ if (fread(&data, sizeof(PJ_UV), 1, fid) != 1) break; } else { /* ascii input */ if (!(s = fgets(line, MAX_LINE, fid))) break; if (!strchr(s, '\n')) { /* overlong line */ int c; (void)strcat(s, "\n"); /* gobble up to newline */ while ((c = fgetc(fid)) != EOF && c != '\n') ; } if (*s == tag) { if (!bin_out) (void)fputs(line, stdout); continue; } if (reversein) { data.uv.v = (*informat)(s, &s); data.uv.u = (*informat)(s, &s); } else { data.uv.u = (*informat)(s, &s); data.uv.v = (*informat)(s, &s); } if (data.uv.v == HUGE_VAL) data.uv.u = HUGE_VAL; if (!*s && (s > line)) --s; /* assumed we gobbled \n */ if (!bin_out && echoin) { char t; t = *s; *s = '\0'; (void)fputs(line, stdout); *s = t; putchar('\t'); } } if (data.uv.u != HUGE_VAL) { PJ_COORD coord; coord.lp = data.lp; if (prescale) { data.uv.u *= fscale; data.uv.v *= fscale; } if (dofactors && !inverse) { facs = proj_factors(ProjForFactors, coord); facs_bad = proj_errno(ProjForFactors); } const auto xy = (*proj.fwd)(data.lp, Proj); data.xy = xy; if (dofactors && inverse) { facs = proj_factors(ProjForFactors, coord); facs_bad = proj_errno(ProjForFactors); } if (postscale && data.uv.u != HUGE_VAL) { data.uv.u *= fscale; data.uv.v *= fscale; } } if (bin_out) { /* binary output */ (void)fwrite(&data, sizeof(PJ_UV), 1, stdout); continue; } else if (data.uv.u == HUGE_VAL) /* error output */ (void)fputs(oterr, stdout); else if (inverse && !oform) { /*ascii DMS output */ if (reverseout) { (void)fputs(rtodms(pline, sizeof(pline), data.uv.v, 'N', 'S'), stdout); putchar('\t'); (void)fputs(rtodms(pline, sizeof(pline), data.uv.u, 'E', 'W'), stdout); } else { (void)fputs(rtodms(pline, sizeof(pline), data.uv.u, 'E', 'W'), stdout); putchar('\t'); (void)fputs(rtodms(pline, sizeof(pline), data.uv.v, 'N', 'S'), stdout); } } else { /* x-y or decimal degree ascii output, scale if warranted by output units */ if (inverse) { if (proj_angular_input(Proj, PJ_FWD)) { data.uv.v *= RAD_TO_DEG; data.uv.u *= RAD_TO_DEG; } } else { if (proj_angular_output(Proj, PJ_FWD)) { data.uv.v *= RAD_TO_DEG; data.uv.u *= RAD_TO_DEG; } } if (reverseout) { limited_fprintf_for_number(stdout, oform, data.uv.v); putchar('\t'); limited_fprintf_for_number(stdout, oform, data.uv.u); } else { limited_fprintf_for_number(stdout, oform, data.uv.u); putchar('\t'); limited_fprintf_for_number(stdout, oform, data.uv.v); } } /* print scale factor data */ if (dofactors) { if (!facs_bad) (void)printf("\t<%g %g %g %g %g %g>", facs.meridional_scale, facs.parallel_scale, facs.areal_scale, facs.angular_distortion * RAD_TO_DEG, facs.tissot_semimajor, facs.tissot_semiminor); else (void)fputs("\t<* * * * * *>", stdout); } (void)fputs(bin_in ? "\n" : s, stdout); fflush(stdout); } } /* file processing function --- verbosely */ static void vprocess(FILE *fid) { char line[MAX_LINE + 3], *s, pline[40]; PJ_LP dat_ll; PJ_XY dat_xy; int linvers; PJ_COORD coord; if (!oform) oform = "%.3f"; if (bin_in || bin_out) emess(1, "binary I/O not available in -V option"); for (;;) { proj_errno_reset(Proj); ++emess_dat.File_line; if (!(s = fgets(line, MAX_LINE, fid))) break; if (!strchr(s, '\n')) { /* overlong line */ int c; (void)strcat(s, "\n"); /* gobble up to newline */ while ((c = fgetc(fid)) != EOF && c != '\n') ; } if (*s == tag) { /* pass on data */ (void)fputs(s, stdout); continue; } /* check to override default input mode */ if (*s == 'I' || *s == 'i') { linvers = 1; ++s; } else linvers = inverse; if (linvers) { if (!PJ_INVERSE(Proj)) { emess(-1, "inverse for this projection not avail.\n"); continue; } dat_xy.x = strtod(s, &s); dat_xy.y = strtod(s, &s); if (dat_xy.x == HUGE_VAL || dat_xy.y == HUGE_VAL) { emess(-1, "lon-lat input conversion failure\n"); continue; } if (prescale) { dat_xy.x *= fscale; dat_xy.y *= fscale; } if (reversein) { PJ_XY temp = dat_xy; dat_xy.x = temp.y; dat_xy.y = temp.x; } dat_ll = pj_inv(dat_xy, Proj); } else { dat_ll.lam = proj_dmstor(s, &s); dat_ll.phi = proj_dmstor(s, &s); if (dat_ll.lam == HUGE_VAL || dat_ll.phi == HUGE_VAL) { emess(-1, "lon-lat input conversion failure\n"); continue; } if (reversein) { PJ_LP temp = dat_ll; dat_ll.lam = temp.phi; dat_ll.phi = temp.lam; } dat_xy = pj_fwd(dat_ll, Proj); if (postscale) { dat_xy.x *= fscale; dat_xy.y *= fscale; } } if (proj_context_errno(nullptr)) { emess(-1, "%s", proj_errno_string(proj_context_errno(nullptr))); continue; } if (!*s && (s > line)) --s; /* assumed we gobbled \n */ coord.lp = dat_ll; facs = proj_factors(ProjForFactors, coord); if (proj_errno(ProjForFactors)) { emess(-1, "failed to compute factors\n\n"); continue; } if (*s != '\n') (void)fputs(s, stdout); (void)fputs("Longitude: ", stdout); (void)fputs(proj_rtodms2(pline, sizeof(pline), dat_ll.lam, 'E', 'W'), stdout); (void)printf(" [ %.11g ]\n", dat_ll.lam * RAD_TO_DEG); (void)fputs("Latitude: ", stdout); (void)fputs(proj_rtodms2(pline, sizeof(pline), dat_ll.phi, 'N', 'S'), stdout); (void)printf(" [ %.11g ]\n", dat_ll.phi * RAD_TO_DEG); (void)fputs(swapAxisCrs ? "Northing (y): " : "Easting (x): ", stdout); limited_fprintf_for_number(stdout, oform, dat_xy.x); putchar('\n'); (void)fputs(swapAxisCrs ? "Easting (x): " : "Northing (y): ", stdout); limited_fprintf_for_number(stdout, oform, dat_xy.y); putchar('\n'); (void)printf("Meridian scale (h) : %.8f ( %.4g %% error )\n", facs.meridional_scale, (facs.meridional_scale - 1.) * 100.); (void)printf("Parallel scale (k) : %.8f ( %.4g %% error )\n", facs.parallel_scale, (facs.parallel_scale - 1.) * 100.); (void)printf("Areal scale (s): %.8f ( %.4g %% error )\n", facs.areal_scale, (facs.areal_scale - 1.) * 100.); (void)printf("Angular distortion (w): %.3f\n", facs.angular_distortion * RAD_TO_DEG); (void)printf("Meridian/Parallel angle: %.5f\n", facs.meridian_parallel_angle * RAD_TO_DEG); (void)printf("Convergence : "); (void)fputs( proj_rtodms2(pline, sizeof(pline), facs.meridian_convergence, 0, 0), stdout); (void)printf(" [ %.8f ]\n", facs.meridian_convergence * RAD_TO_DEG); (void)printf("Max-min (Tissot axis a-b) scale error: %.5f %.5f\n\n", facs.tissot_semimajor, facs.tissot_semiminor); fflush(stdout); } } int main(int argc, char **argv) { char *arg; std::vector<char *> argvVector; char **eargv = argv; FILE *fid; int eargc = 0, mon = 0; pj_stderr_proj_lib_deprecation_warning(); if (argc == 0) { exit(1); } if ((emess_dat.Prog_name = strrchr(*argv, DIR_CHAR)) != nullptr) ++emess_dat.Prog_name; else emess_dat.Prog_name = *argv; inverse = strncmp(emess_dat.Prog_name, "inv", 3) == 0 || strncmp(emess_dat.Prog_name, "lt-inv", 6) == 0; // older libtool have a lt- prefix if (argc <= 1) { (void)fprintf(stderr, usage, pj_get_release(), emess_dat.Prog_name); exit(0); } /* process run line arguments */ while (--argc > 0) { /* collect run line arguments */ if (**++argv == '-') for (arg = *argv;;) { switch (*++arg) { case '\0': /* position of "stdin" */ if (arg[-1] == '-') eargv[eargc++] = const_cast<char *>("-"); break; case 'b': /* binary I/O */ bin_in = bin_out = 1; continue; case 'v': /* monitor dump of initialization */ mon = 1; continue; case 'i': /* input binary */ bin_in = 1; continue; case 'o': /* output binary */ bin_out = 1; continue; case 'I': /* alt. method to spec inverse */ inverse = 1; continue; case 'E': /* echo ascii input to ascii output */ echoin = 1; continue; case 'V': /* very verbose processing mode */ very_verby = 1; mon = 1; continue; case 'S': /* compute scale factors */ dofactors = 1; continue; case 't': /* set col. one char */ if (arg[1]) tag = *++arg; else emess(1, "missing -t col. 1 tag"); continue; case 'l': /* list projections, ellipses or units */ if (!arg[1] || arg[1] == 'p' || arg[1] == 'P') { /* list projections */ const struct PJ_LIST *lp; int do_long = arg[1] == 'P', c; const char *str; for (lp = proj_list_operations(); lp->id; ++lp) { if (strcmp(lp->id, "latlong") == 0 || strcmp(lp->id, "longlat") == 0 || strcmp(lp->id, "geocent") == 0) continue; (void)printf("%s : ", lp->id); if (do_long) /* possibly multiline description */ (void)puts(*lp->descr); else { /* first line, only */ str = *lp->descr; while ((c = *str++) && c != '\n') putchar(c); putchar('\n'); } } } else if (arg[1] == '=') { /* list projection 'descr' */ const struct PJ_LIST *lp; arg += 2; for (lp = proj_list_operations(); lp->id; ++lp) if (!strcmp(lp->id, arg)) { (void)printf("%9s : %s\n", lp->id, *lp->descr); break; } } else if (arg[1] == 'e') { /* list ellipses */ const struct PJ_ELLPS *le; for (le = proj_list_ellps(); le->id; ++le) (void)printf("%9s %-16s %-16s %s\n", le->id, le->major, le->ell, le->name); } else if (arg[1] == 'u') { /* list units */ auto units = proj_get_units_from_database( nullptr, nullptr, "linear", false, nullptr); for (int i = 0; units && units[i]; i++) { if (units[i]->proj_short_name) { (void)printf("%12s %-20.15g %s\n", units[i]->proj_short_name, units[i]->conv_factor, units[i]->name); } } proj_unit_list_destroy(units); } else emess(1, "invalid list option: l%c", arg[1]); exit(0); /* cppcheck-suppress duplicateBreak */ continue; /* artificial */ case 'e': /* error line alternative */ if (--argc <= 0) noargument: emess(1, "missing argument for -%c", *arg); oterr = *++argv; continue; case 'm': /* cartesian multiplier */ if (--argc <= 0) goto noargument; postscale = 1; if (!strncmp("1/", *++argv, 2) || !strncmp("1:", *argv, 2)) { if ((fscale = atof((*argv) + 2)) == 0.) goto badscale; fscale = 1. / fscale; } else if ((fscale = atof(*argv)) == 0.) { badscale: emess(1, "invalid scale argument"); } continue; case 'W': /* specify seconds precision */ case 'w': /* -W for constant field width */ { int c = arg[1]; if (c != 0 && isdigit(c)) { set_rtodms(c - '0', *arg == 'W'); ++arg; } else emess(1, "-W argument missing or non-digit"); continue; } case 'f': /* alternate output format degrees or xy */ if (--argc <= 0) goto noargument; oform = *++argv; continue; case 'd': if (--argc <= 0) goto noargument; snprintf(oform_buffer, sizeof(oform_buffer), "%%.%df", atoi(*++argv)); oform = oform_buffer; break; case 'r': /* reverse input */ reversein = 1; continue; case 's': /* reverse output */ reverseout = 1; continue; default: emess(1, "invalid option: -%c", *arg); break; } break; } else if (**argv == '+') { /* + argument */ argvVector.push_back(*argv + 1); } else /* assumed to be input file name(s) */ eargv[eargc++] = *argv; } if (oform) { if (!validate_form_string_for_numbers(oform)) { emess(3, "invalid format string"); exit(0); } } /* done with parameter and control input */ if (inverse && postscale) { prescale = 1; postscale = 0; fscale = 1. / fscale; } proj_context_use_proj4_init_rules(nullptr, true); if (argvVector.empty() && eargc >= 1) { // Consider the next arg as a CRS, not a file. std::string ocrs = eargv[0]; eargv++; eargc--; // logic copied from proj_factors function // coverity[tainted_data] if (PJ *P = proj_create(nullptr, ocrs.c_str())) { auto type = proj_get_type(P); auto ctx = P->ctx; if (type == PJ_TYPE_COMPOUND_CRS) { auto horiz = proj_crs_get_sub_crs(ctx, P, 0); if (horiz) { if (proj_get_type(horiz) == PJ_TYPE_PROJECTED_CRS) { proj_destroy(P); P = horiz; type = proj_get_type(P); } else { proj_destroy(horiz); } } } if (type == PJ_TYPE_PROJECTED_CRS) { try { auto crs = dynamic_cast<const NS_PROJ::crs::ProjectedCRS *>( P->iso_obj.get()); auto &dir = crs->coordinateSystem()->axisList()[0]->direction(); swapAxisCrs = dir == NS_PROJ::cs::AxisDirection::NORTH || dir == NS_PROJ::cs::AxisDirection::SOUTH; } catch (...) { } auto geodetic_crs = proj_get_source_crs(ctx, P); assert(geodetic_crs); auto pm = proj_get_prime_meridian(ctx, geodetic_crs); double pm_longitude = 0; proj_prime_meridian_get_parameters(ctx, pm, &pm_longitude, nullptr, nullptr); proj_destroy(pm); PJ *geogCRSNormalized; auto cs = proj_create_ellipsoidal_2D_cs( ctx, PJ_ELLPS2D_LONGITUDE_LATITUDE, "Radian", 1.0); if (pm_longitude != 0) { auto ellipsoid = proj_get_ellipsoid(ctx, geodetic_crs); double semi_major_metre = 0; double inv_flattening = 0; proj_ellipsoid_get_parameters(ctx, ellipsoid, &semi_major_metre, nullptr, nullptr, &inv_flattening); geogCRSNormalized = proj_create_geographic_crs( ctx, "unname crs", "unnamed datum", proj_get_name(ellipsoid), semi_major_metre, inv_flattening, "reference prime meridian", 0, nullptr, 0, cs); proj_destroy(ellipsoid); } else { auto datum = proj_crs_get_datum(ctx, geodetic_crs); auto datum_ensemble = proj_crs_get_datum_ensemble(ctx, geodetic_crs); geogCRSNormalized = proj_create_geographic_crs_from_datum( ctx, "unnamed crs", datum ? datum : datum_ensemble, cs); proj_destroy(datum); proj_destroy(datum_ensemble); } proj_destroy(cs); Proj = proj_create_crs_to_crs_from_pj(ctx, geogCRSNormalized, P, nullptr, nullptr); auto conversion = proj_crs_get_coordoperation(ctx, P); auto projCS = proj_create_cartesian_2D_cs( ctx, PJ_CART2D_EASTING_NORTHING, "metre", 1.0); auto projCRSNormalized = proj_create_projected_crs( ctx, nullptr, geodetic_crs, conversion, projCS); assert(projCRSNormalized); proj_destroy(geodetic_crs); proj_destroy(conversion); proj_destroy(projCS); ProjForFactors = proj_create_crs_to_crs_from_pj( ctx, geogCRSNormalized, projCRSNormalized, nullptr, nullptr); proj_destroy(geogCRSNormalized); proj_destroy(projCRSNormalized); } else { emess(3, "CRS must be projected"); } proj_destroy(P); } else { emess(3, "CRS is not parseable"); } } if (eargc == 0) /* if no specific files force sysin */ eargv[eargc++] = const_cast<char *>("-"); // proj historically ignores any datum shift specifier, like nadgrids, // towgs84, etc argvVector.push_back(const_cast<char *>("break_cs2cs_recursion")); if (!Proj) { if (!(Proj = proj_create_argv(nullptr, static_cast<int>(argvVector.size()), argvVector.data()))) emess(3, "projection initialization failure\ncause: %s", proj_errno_string(proj_context_errno(nullptr))); ProjForFactors = Proj; } if (!proj_angular_input(Proj, PJ_FWD)) { emess(3, "can't initialize operations that take non-angular input " "coordinates. Try cct."); exit(0); } if (proj_angular_output(Proj, PJ_FWD)) { emess(3, "can't initialize operations that produce angular output " "coordinates"); exit(0); } // Ugly hack. See https://github.com/OSGeo/PROJ/issues/1782 if (Proj->right == PJ_IO_UNITS_WHATEVER && Proj->descr && strncmp(Proj->descr, "General Oblique Transformation", strlen("General Oblique Transformation")) == 0) { Proj->right = PJ_IO_UNITS_PROJECTED; } if (inverse) { if (!Proj->inv) emess(3, "inverse projection not available"); proj.inv = pj_inv; } else proj.fwd = pj_fwd; /* set input formatting control */ if (mon) { pj_pr_list(Proj); if (very_verby) { (void)printf("#Final Earth figure: "); if (Proj->es != 0.0) { (void)printf("ellipsoid\n# Major axis (a): "); limited_fprintf_for_number(stdout, oform ? oform : "%.3f", Proj->a); (void)printf("\n# 1/flattening: %.6f\n", 1. / (1. - sqrt(1. - Proj->es))); (void)printf("# squared eccentricity: %.12f\n", Proj->es); } else { (void)printf("sphere\n# Radius: "); limited_fprintf_for_number(stdout, oform ? oform : "%.3f", Proj->a); (void)putchar('\n'); } } } if (inverse) informat = strtod; else { informat = proj_dmstor; if (!oform) oform = "%.2f"; } if (bin_out) { SET_BINARY_MODE(stdout); } /* process input file list */ for (; eargc--; ++eargv) { if (**eargv == '-') { fid = stdin; emess_dat.File_name = const_cast<char *>("<stdin>"); if (bin_in) { SET_BINARY_MODE(stdin); } } else { if ((fid = fopen(*eargv, "rb")) == nullptr) { emess(-2, "input file: %s", *eargv); continue; } emess_dat.File_name = *eargv; } emess_dat.File_line = 0; if (very_verby) vprocess(fid); else process(fid); (void)fclose(fid); emess_dat.File_name = nullptr; } if (ProjForFactors && ProjForFactors != Proj) proj_destroy(ProjForFactors); if (Proj) proj_destroy(Proj); exit(0); /* normal completion */ }
cpp
PROJ
data/projects/PROJ/src/apps/emess.h
/* Error message processing header file */ #ifndef EMESS_H #define EMESS_H struct EMESS { char *File_name, /* input file name */ *Prog_name; /* name of program */ int File_line; /* approximate line read where error occurred */ }; #ifdef EMESS_ROUTINE /* use type */ /* for emess procedure */ struct EMESS emess_dat = {nullptr, nullptr, 0}; #else /* for for calling procedures */ extern struct EMESS emess_dat; #endif /* use type */ #if defined(__GNUC__) #define EMESS_PRINT_FUNC_FORMAT(format_idx, arg_idx) \ __attribute__((__format__(__printf__, format_idx, arg_idx))) #else #define EMESS_PRINT_FUNC_FORMAT(format_idx, arg_idx) #endif void emess(int, const char *, ...) EMESS_PRINT_FUNC_FORMAT(2, 3); #endif /* end EMESS_H */
h
PROJ
data/projects/PROJ/src/apps/emess.cpp
/* Error message processing */ #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE #endif #endif #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proj_config.h" #include "proj_internal.h" #define EMESS_ROUTINE #include "emess.h" void emess(int code, const char *fmt, ...) { va_list args; va_start(args, fmt); /* prefix program name, if given */ if (emess_dat.Prog_name != nullptr) { // For unit test purposes, allow PROJ_DISPLAY_PROGRAM_NAME=NO const char *pszDisplayProgramName = getenv("PROJ_DISPLAY_PROGRAM_NAME"); if (!(pszDisplayProgramName && strcmp(pszDisplayProgramName, "NO") == 0)) { (void)fprintf(stderr, "%s\n<%s>: ", pj_get_release(), emess_dat.Prog_name); } } /* print file name and line, if given */ if (emess_dat.File_name != nullptr && *emess_dat.File_name) { (void)fprintf(stderr, "while processing file: %s", emess_dat.File_name); if (emess_dat.File_line > 0) (void)fprintf(stderr, ", line %d\n", emess_dat.File_line); else (void)fputc('\n', stderr); } else putc('\n', stderr); /* if |code|==2, print errno code data */ if (code == 2 || code == -2) { int my_errno = errno; #ifdef HAVE_STRERROR const char *my_strerror = strerror(my_errno); #endif #ifndef HAVE_STRERROR const char *my_strerror = "<system mess. texts unavail.>"; #endif (void)fprintf(stderr, "Sys errno: %d: %s\n", my_errno, my_strerror); } /* post remainder of call data */ (void)vfprintf(stderr, fmt, args); va_end(args); /* die if code positive */ if (code > 0) { (void)fputs("\nprogram abnormally terminated\n", stderr); exit(code); } else putc('\n', stderr); }
cpp
PROJ
data/projects/PROJ/src/apps/proj_strtod.cpp
/*********************************************************************** proj_strtod: Convert string to double, accepting underscore separators Thomas Knudsen, 2017-01-17/09-19 ************************************************************************ Conventionally, PROJ.4 does not honor locale settings, consistently behaving as if LC_ALL=C. For this to work, we have, for many years, been using other solutions than the C standard library strtod/atof functions for converting strings to doubles. In the early versions of proj, iirc, a gnu version of strtod was used, mostly to work around cases where the same system library was used for C and Fortran linking, hence making strtod accept "D" and "d" as exponentiation indicators, following Fortran Double Precision constant syntax. This broke the proj angular syntax, accepting a "d" to mean "degree": 12d34'56", meaning 12 degrees 34 minutes and 56 seconds. With an explicit MIT licence, PROJ.4 could not include GPL code any longer, and apparently at some time, the GPL code was replaced by the current C port of a GDAL function (in pj_strtod.c), which reads the LC_NUMERIC setting and, behind the back of the user, momentarily changes the conventional '.' delimiter to whatever the locale requires, then calls the system supplied strtod. While this requires a minimum amount of coding, it only solves one problem, and not in a very generic way. Another problem, I would like to see solved, is the handling of underscores as generic delimiters. This is getting popular in a number of programming languages (Ada, C++, C#, D, Java, Julia, Perl 5, Python, Rust, etc. cf. e.g. https://www.python.org/dev/peps/pep-0515/), and in our case of handling numbers being in the order of magnitude of the Earth's dimensions, and a resolution of submillimetre, i.e. having 10 or more significant digits, splitting the "wall of digits" into smaller chunks is of immense value. Hence this reimplementation of strtod, which hardcodes '.' as indicator of numeric fractions, and accepts '_' anywhere in a numerical string sequence: So a typical northing value can be written 6_098_907.8250 m rather than 6098907.8250 m which, in my humble opinion, is well worth the effort. While writing this code, I took ample inspiration from Michael Ringgaard's strtod version over at http://www.jbox.dk/sanos/source/lib/strtod.c.html, and Yasuhiro Matsumoto's public domain version over at https://gist.github.com/mattn/1890186. The code below is, however, not copied from any of the two mentioned - it is a reimplementation, and probably suffers from its own set of bugs. So for now, it is intended not as a replacement of pj_strtod, but only as an experimental piece of code for use in an experimental new transformation program, cct. ************************************************************************ Thomas Knudsen, [email protected], 2017-01-17/2017-09-18 ************************************************************************ * Copyright (c) 2017 Thomas Knudsen & SDFE * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ***********************************************************************/ #define FROM_PROJ_CPP #include "proj_strtod.h" #include <ctype.h> #include <errno.h> #include <float.h> /* for HUGE_VAL */ #include <math.h> /* for pow() */ #include <stdlib.h> /* for abs */ #include <string.h> /* for strchr, strncmp */ #include <limits> #include "proj/internal/internal.hpp" using namespace NS_PROJ::internal; double proj_strtod(const char *str, char **endptr) { double number = 0, integral_part = 0; int exponent = 0; int fraction_is_nonzero = 0; int sign = 0; const char *p = str; int n = 0; int num_digits_total = 0; int num_digits_after_comma = 0; int num_prefixed_zeros = 0; if (nullptr == str) { errno = EFAULT; if (endptr) *endptr = nullptr; return HUGE_VAL; } /* First skip leading whitespace */ while (isspace(*p)) p++; /* Empty string? */ if (0 == *p) { if (endptr) *endptr = const_cast<char *>(str); return 0; } /* NaN */ if (ci_starts_with(p, "NaN")) { if (endptr) *endptr = const_cast<char *>(p + 3); return std::numeric_limits<double>::quiet_NaN(); } /* non-numeric? */ if (nullptr == strchr("0123456789+-._", *p)) { if (endptr) *endptr = const_cast<char *>(str); return 0; } /* Then handle optional prefixed sign and skip prefix zeros */ switch (*p) { case '-': sign = -1; p++; break; case '+': sign = 1; p++; break; default: if (isdigit(*p) || '_' == *p || '.' == *p) break; if (endptr) *endptr = const_cast<char *>(str); return 0; } /* stray sign, as in "+/-"? */ if (0 != sign && (nullptr == strchr("0123456789._", *p) || 0 == *p)) { if (endptr) *endptr = const_cast<char *>(str); return 0; } /* skip prefixed zeros before '.' */ while ('0' == *p || '_' == *p) p++; /* zero? */ if ((0 == *p) || nullptr == strchr("0123456789eE.", *p) || isspace(*p)) { if (endptr) *endptr = const_cast<char *>(p); return sign == -1 ? -0 : 0; } /* Now expect a (potentially zero-length) string of digits */ while (isdigit(*p) || ('_' == *p)) { if ('_' == *p) { p++; continue; } number = number * 10. + (*p - '0'); p++; num_digits_total++; } integral_part = number; /* Done? */ if (0 == *p) { if (endptr) *endptr = const_cast<char *>(p); if (sign == -1) return -number; return number; } /* Do we have a fractional part? */ if ('.' == *p) { p++; /* keep on skipping prefixed zeros (i.e. allow writing 1e-20 */ /* as 0.00000000000000000001 without losing precision) */ if (0 == integral_part) while ('0' == *p || '_' == *p) { if ('0' == *p) num_prefixed_zeros++; p++; } /* if the next character is nonnumeric, we have reached the end */ if (0 == *p || nullptr == strchr("_0123456789eE+-", *p)) { if (endptr) *endptr = const_cast<char *>(p); if (sign == -1) return -number; return number; } while (isdigit(*p) || '_' == *p) { /* Don't let pathologically long fractions destroy precision */ if ('_' == *p || num_digits_total > 17) { p++; continue; } number = number * 10. + (*p - '0'); if (*p != '0') fraction_is_nonzero = 1; p++; num_digits_total++; num_digits_after_comma++; } /* Avoid having long zero-tails (4321.000...000) destroy precision */ if (fraction_is_nonzero) exponent = -(num_digits_after_comma + num_prefixed_zeros); else number = integral_part; } /* end of fractional part */ /* non-digit */ if (0 == num_digits_total) { errno = EINVAL; if (endptr) *endptr = const_cast<char *>(p); return HUGE_VAL; } if (sign == -1) number = -number; /* Do we have an exponent part? */ while (*p == 'e' || *p == 'E') { p++; /* Just a stray "e", as in 100elephants? */ if (0 == *p || nullptr == strchr("0123456789+-_", *p)) { p--; break; } while ('_' == *p) p++; /* Does it have a sign? */ sign = 0; if ('-' == *p) sign = -1; if ('+' == *p) sign = +1; if (0 == sign) { if (!(isdigit(*p) || *p == '_')) { if (endptr) *endptr = const_cast<char *>(p); return HUGE_VAL; } } else p++; /* Go on and read the exponent */ n = 0; while (isdigit(*p) || '_' == *p) { if ('_' == *p) { p++; continue; } n = n * 10 + (*p - '0'); p++; } if (-1 == sign) n = -n; exponent += n; break; } if (endptr) *endptr = const_cast<char *>(p); if ((exponent < DBL_MIN_EXP) || (exponent > DBL_MAX_EXP)) { errno = ERANGE; return HUGE_VAL; } /* on some platforms pow() is very slow - so don't call it if exponent is * close to 0 */ if (0 == exponent) return number; if (abs(exponent) < 20) { double ex = 1; int absexp = exponent < 0 ? -exponent : exponent; while (absexp--) ex *= 10; number = exponent < 0 ? number / ex : number * ex; } else number *= pow(10.0, static_cast<double>(exponent)); return number; } double proj_atof(const char *str) { return proj_strtod(str, nullptr); } #ifdef TEST /* compile/run: gcc -DTEST -o proj_strtod_test proj_strtod.c && * proj_strtod_test */ #include <stdio.h> char *un_underscore(char *s) { static char u[1024]; int i, m, n; for (i = m = 0, n = strlen(s); i < n; i++) { if (s[i] == '_') { m++; continue; } u[i - m] = s[i]; } u[n - m] = 0; return u; } int thetest(char *s, int line) { char *endp, *endq, *u; double p, q; int errnop, errnoq, prev_errno; prev_errno = errno; u = un_underscore(s); errno = 0; p = proj_strtod(s, &endp); errnop = errno; errno = 0; q = strtod(u, &endq); errnoq = errno; errno = prev_errno; if (q == p && 0 == strcmp(endp, endq) && errnop == errnoq) return 0; errno = line; printf("Line: %3.3d - [%s] [%s]\n", line, s, u); printf("proj_strtod: %2d %.17g [%s]\n", errnop, p, endp); printf("libc_strtod: %2d %.17g [%s]\n", errnoq, q, endq); return 1; } #define test(s) thetest(s, __LINE__) int main(int argc, char **argv) { double res; char *endptr; errno = 0; test(""); test(" "); test(" abcde"); test(" edcba"); test("abcde"); test("edcba"); test("+"); test("-"); test("+ "); test("- "); test(" + "); test(" - "); test("e 1"); test("e1"); test("0 66"); test("1."); test("0."); test("1.0"); test("0.0"); test("1 "); test("0 "); test("-0 "); test("0_ "); test("0_"); test("1e"); test("_1.0"); test("_0.0"); test("1_.0"); test("0_.0"); test("1__.0"); test("0__.0"); test("1.__0"); test("0.__0"); test("1.0___"); test("0.0___"); test("1e2"); test("__123_456_789_._10_11_12"); test("1______"); test("1___e__2__"); test("-1"); test("-1.0"); test("-0"); test("-1e__-_2__rest"); test("0.00002"); test("0.00001"); test("-0.00002"); test("-0.00001"); test("-0.00001e-2"); test("-0.00001e2"); test("1e9999"); /* We expect this one to differ */ test("0." "000000000000000000000000000000000000000000000000000000000000000000000" "00" "0002"); if (errno) printf("First discrepancy in line %d\n", errno); if (argc < 2) return 0; res = proj_strtod(argv[1], &endptr); printf("res = %20.15g. Rest = [%s], errno = %d\n", res, endptr, (int)errno); return 0; } #endif
cpp
PROJ
data/projects/PROJ/src/apps/proj_strtod.h
/* Internal header for proj_strtod.c */ double proj_strtod(const char *str, char **endptr); double proj_atof(const char *str);
h
PROJ
data/projects/PROJ/src/apps/geod.cpp
/* <<<< Geodesic filter program >>>> */ #include "emess.h" #include "geod_interface.h" #include "proj.h" #include "proj_internal.h" #include "utils.h" #include <ctype.h> #include <stdio.h> #include <string.h> #define MAXLINE 200 #define MAX_PARGS 50 #define TAB putchar('\t') static int fullout = 0, /* output full set of geodesic values */ tag = '#', /* beginning of line tag character */ pos_azi = 0, /* output azimuths as positive values */ inverse = 0; /* != 0 then inverse geodesic */ static const char *oform = nullptr; /* output format for decimal degrees */ static const char *osform = "%.3f"; /* output format for S */ static char pline[50]; /* work string */ static const char *usage = "%s\nusage: %s [-afFIlptwW [args]] [+opt[=arg] ...] [file ...]\n"; static void printLL(double p, double l) { if (oform) { (void)limited_fprintf_for_number(stdout, oform, p * RAD_TO_DEG); TAB; (void)limited_fprintf_for_number(stdout, oform, l * RAD_TO_DEG); } else { (void)fputs(rtodms(pline, sizeof(pline), p, 'N', 'S'), stdout); TAB; (void)fputs(rtodms(pline, sizeof(pline), l, 'E', 'W'), stdout); } } static void do_arc(void) { double az; printLL(phi2, lam2); putchar('\n'); for (az = al12; n_alpha--;) { al12 = az = adjlon(az + del_alpha); geod_pre(); geod_for(); printLL(phi2, lam2); putchar('\n'); } } static void /* generate intermediate geodesic coordinates */ do_geod(void) { double phil, laml, del_S; phil = phi2; laml = lam2; printLL(phi1, lam1); putchar('\n'); for (geod_S = del_S = geod_S / n_S; --n_S; geod_S += del_S) { geod_for(); printLL(phi2, lam2); putchar('\n'); } printLL(phil, laml); putchar('\n'); } static void /* file processing function */ process(FILE *fid) { char line[MAXLINE + 3], *s; for (;;) { ++emess_dat.File_line; if (!(s = fgets(line, MAXLINE, fid))) break; if (!strchr(s, '\n')) { /* overlong line */ int c; strcat(s, "\n"); /* gobble up to newline */ while ((c = fgetc(fid)) != EOF && c != '\n') ; } if (*s == tag) { fputs(line, stdout); continue; } phi1 = dmstor(s, &s); lam1 = dmstor(s, &s); if (inverse) { phi2 = dmstor(s, &s); lam2 = dmstor(s, &s); geod_inv(); } else { al12 = dmstor(s, &s); geod_S = strtod(s, &s) * to_meter; geod_pre(); geod_for(); } if (!*s && (s > line)) --s; /* assumed we gobbled \n */ if (pos_azi) { if (al12 < 0.) al12 += M_TWOPI; if (al21 < 0.) al21 += M_TWOPI; } if (fullout) { printLL(phi1, lam1); TAB; printLL(phi2, lam2); TAB; if (oform) { (void)limited_fprintf_for_number(stdout, oform, al12 * RAD_TO_DEG); TAB; (void)limited_fprintf_for_number(stdout, oform, al21 * RAD_TO_DEG); TAB; (void)limited_fprintf_for_number(stdout, osform, geod_S * fr_meter); } else { (void)fputs(rtodms(pline, sizeof(pline), al12, 0, 0), stdout); TAB; (void)fputs(rtodms(pline, sizeof(pline), al21, 0, 0), stdout); TAB; (void)limited_fprintf_for_number(stdout, osform, geod_S * fr_meter); } } else if (inverse) if (oform) { (void)limited_fprintf_for_number(stdout, oform, al12 * RAD_TO_DEG); TAB; (void)limited_fprintf_for_number(stdout, oform, al21 * RAD_TO_DEG); TAB; (void)limited_fprintf_for_number(stdout, osform, geod_S * fr_meter); } else { (void)fputs(rtodms(pline, sizeof(pline), al12, 0, 0), stdout); TAB; (void)fputs(rtodms(pline, sizeof(pline), al21, 0, 0), stdout); TAB; (void)limited_fprintf_for_number(stdout, osform, geod_S * fr_meter); } else { printLL(phi2, lam2); TAB; if (oform) (void)limited_fprintf_for_number(stdout, oform, al21 * RAD_TO_DEG); else (void)fputs(rtodms(pline, sizeof(pline), al21, 0, 0), stdout); } (void)fputs(s, stdout); fflush(stdout); } } static char *pargv[MAX_PARGS]; static int pargc = 0; int main(int argc, char **argv) { char *arg, **eargv = argv; FILE *fid; static int eargc = 0, c; if (argc == 0) { exit(1); } if ((emess_dat.Prog_name = strrchr(*argv, '/')) != nullptr) ++emess_dat.Prog_name; else emess_dat.Prog_name = *argv; inverse = strncmp(emess_dat.Prog_name, "inv", 3) == 0 || strncmp(emess_dat.Prog_name, "lt-inv", 6) == 0; // older libtool have a lt- prefix if (argc <= 1) { (void)fprintf(stderr, usage, pj_get_release(), emess_dat.Prog_name); exit(0); } /* process run line arguments */ while (--argc > 0) { /* collect run line arguments */ if (**++argv == '-') for (arg = *argv;;) { switch (*++arg) { case '\0': /* position of "stdin" */ if (arg[-1] == '-') eargv[eargc++] = const_cast<char *>("-"); break; case 'a': /* output full set of values */ fullout = 1; continue; case 'I': /* alt. inverse spec. */ inverse = 1; continue; case 't': /* set col. one char */ if (arg[1]) tag = *++arg; else emess(1, "missing -t col. 1 tag"); continue; case 'W': /* specify seconds precision */ case 'w': /* -W for constant field width */ if ((c = arg[1]) && isdigit(c)) { set_rtodms(c - '0', *arg == 'W'); ++arg; } else emess(1, "-W argument missing or non-digit"); continue; case 'f': /* alternate output format degrees or xy */ if (--argc <= 0) noargument: emess(1, "missing argument for -%c", *arg); oform = *++argv; continue; case 'F': /* alternate output format degrees or xy */ if (--argc <= 0) goto noargument; osform = *++argv; continue; case 'l': if (!arg[1] || arg[1] == 'e') { /* list of ellipsoids */ const struct PJ_ELLPS *le; for (le = proj_list_ellps(); le->id; ++le) (void)printf("%9s %-16s %-16s %s\n", le->id, le->major, le->ell, le->name); } else if (arg[1] == 'u') { /* list of units */ auto units = proj_get_units_from_database( nullptr, nullptr, "linear", false, nullptr); for (int i = 0; units && units[i]; i++) { if (units[i]->proj_short_name) { (void)printf("%12s %-20.15g %s\n", units[i]->proj_short_name, units[i]->conv_factor, units[i]->name); } } proj_unit_list_destroy(units); } else emess(1, "invalid list option: l%c", arg[1]); exit(0); case 'p': /* output azimuths as positive */ pos_azi = 1; continue; default: emess(1, "invalid option: -%c", *arg); break; } break; } else if (**argv == '+') /* + argument */ if (pargc < MAX_PARGS) pargv[pargc++] = *argv + 1; else emess(1, "overflowed + argument table"); else /* assumed to be input file name(s) */ eargv[eargc++] = *argv; } /* done with parameter and control input */ geod_set(pargc, pargv); /* setup projection */ if ((n_alpha || n_S) && eargc) emess(1, "files specified for arc/geodesic mode"); if (n_alpha) do_arc(); else if (n_S) do_geod(); else { /* process input file list */ if (eargc == 0) /* if no specific files force sysin */ eargv[eargc++] = const_cast<char *>("-"); for (; eargc--; ++eargv) { if (**eargv == '-') { fid = stdin; emess_dat.File_name = const_cast<char *>("<stdin>"); } else { if ((fid = fopen(*eargv, "r")) == nullptr) { emess(-2, "input file: %s", *eargv); continue; } emess_dat.File_name = *eargv; } emess_dat.File_line = 0; process(fid); (void)fclose(fid); emess_dat.File_name = (char *)nullptr; } } exit(0); /* normal completion */ }
cpp
PROJ
data/projects/PROJ/src/apps/projsync.cpp
/****************************************************************************** * Project: PROJ * Purpose: Downloader tool * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2020, Even Rouault, <even.rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ //! @cond Doxygen_Suppress #define FROM_PROJ_CPP #include <cstdlib> #include <iostream> #include <limits> #include <set> #include <string> #include "filemanager.hpp" #include "proj.h" #include "proj_internal.h" #include "proj/internal/include_nlohmann_json.hpp" #include "proj/internal/internal.hpp" using json = nlohmann::json; using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- namespace { class ParsingException : public std::exception { std::string msg_; public: explicit ParsingException(const char *msg) : msg_(msg) {} const char *what() const noexcept override { return msg_.c_str(); } }; } // namespace // --------------------------------------------------------------------------- [[noreturn]] static void usage() { std::cerr << "usage: projsync " << std::endl; std::cerr << " [--endpoint URL]" << std::endl; std::cerr << " [--local-geojson-file FILENAME]" << std::endl; std::cerr << " ([--user-writable-directory] | " "[--system-directory] | [--target-dir DIRNAME])" << std::endl; std::cerr << " [--bbox west_long,south_lat,east_long,north_lat]" << std::endl; std::cerr << " [--spatial-test contains|intersects]" << std::endl; std::cerr << " [--source-id ID] [--area-of-use NAME]" << std::endl; std::cerr << " [--file NAME]" << std::endl; std::cerr << " [--all] [--exclude-world-coverage]" << std::endl; std::cerr << " [--quiet | --verbose] [--dry-run] [--list-files]" << std::endl; std::cerr << " [--no-version-filtering]" << std::endl; std::exit(1); } // --------------------------------------------------------------------------- static std::vector<double> get_bbox(const json &j) { std::vector<double> res; if (j.size() == 2 && j[0].is_number() && j[1].is_number()) { res.push_back(j[0].get<double>()); res.push_back(j[1].get<double>()); res.push_back(j[0].get<double>()); res.push_back(j[1].get<double>()); } else { for (const auto &obj : j) { if (obj.is_array()) { const auto subres = get_bbox(obj); if (subres.size() == 4) { if (res.empty()) { res = subres; } else { res[0] = std::min(res[0], subres[0]); res[1] = std::min(res[1], subres[1]); res[2] = std::max(res[2], subres[2]); res[3] = std::max(res[3], subres[3]); } } } } } return res; } // --------------------------------------------------------------------------- int main(int argc, char *argv[]) { pj_stderr_proj_lib_deprecation_warning(); auto ctx = pj_get_default_ctx(); std::string targetDir; std::string endpoint(proj_context_get_url_endpoint(ctx)); const std::string geojsonFile("files.geojson"); std::string queriedSourceId; std::string queriedAreaOfUse; bool listFiles = false; bool dryRun = false; bool hasQueriedBbox = false; double queried_west = 0.0; double queried_south = 0.0; double queried_east = 0.0; double queried_north = 0.0; bool intersects = true; bool quiet = false; bool verbose = false; bool includeWorldCoverage = true; bool queryAll = false; std::string queriedFilename; std::string files_geojson_local; bool versionFiltering = true; for (int i = 1; i < argc; i++) { std::string arg(argv[i]); if (arg == "--endpoint" && i + 1 < argc) { i++; endpoint = argv[i]; } else if (arg == "--user-writable-directory") { // do nothing } else if (arg == "--system-directory") { targetDir = pj_get_relative_share_proj(ctx); #ifdef PROJ_DATA if (targetDir.empty()) { targetDir = PROJ_DATA; } #endif } else if (arg == "--target-dir" && i + 1 < argc) { i++; targetDir = argv[i]; } else if (arg == "--local-geojson-file" && i + 1 < argc) { i++; files_geojson_local = argv[i]; } else if (arg == "--list-files") { listFiles = true; } else if (arg == "--source-id" && i + 1 < argc) { i++; queriedSourceId = argv[i]; } else if (arg == "--area-of-use" && i + 1 < argc) { i++; queriedAreaOfUse = argv[i]; } else if (arg == "--file" && i + 1 < argc) { i++; queriedFilename = argv[i]; } else if (arg == "--bbox" && i + 1 < argc) { i++; auto bboxStr(argv[i]); auto bbox(split(bboxStr, ',')); if (bbox.size() != 4) { std::cerr << "Incorrect number of values for option --bbox: " << bboxStr << std::endl; usage(); } try { queried_west = c_locale_stod(bbox[0]); queried_south = c_locale_stod(bbox[1]); queried_east = c_locale_stod(bbox[2]); queried_north = c_locale_stod(bbox[3]); } catch (const std::exception &e) { std::cerr << "Invalid value for option --bbox: " << bboxStr << ", " << e.what() << std::endl; usage(); } if (queried_west > 180 && queried_east > queried_west) { queried_west -= 360; queried_east -= 360; } else if (queried_west < -180 && queried_east > queried_west) { queried_west += 360; queried_east += 360; } else if (fabs(queried_west) < 180 && fabs(queried_east) < 180 && queried_east < queried_west) { queried_east += 360; } hasQueriedBbox = true; } else if (arg == "--spatial-test" && i + 1 < argc) { i++; const std::string value(argv[i]); if (ci_equal(value, "contains")) { intersects = false; } else if (ci_equal(value, "intersects")) { intersects = true; } else { std::cerr << "Unrecognized value for option --spatial-test: " << value << std::endl; usage(); } } else if (arg == "--dry-run") { dryRun = true; } else if (arg == "--exclude-world-coverage") { includeWorldCoverage = false; } else if (arg == "--all") { queryAll = true; } else if (arg == "--no-version-filtering") { versionFiltering = false; } else if (arg == "-q" || arg == "--quiet") { quiet = true; } else if (arg == "--verbose") { verbose = true; } else { usage(); } } if (!listFiles && queriedFilename.empty() && queriedSourceId.empty() && queriedAreaOfUse.empty() && !hasQueriedBbox && !queryAll) { std::cerr << "At least one of --list-files, --file, --source-id, " "--area-of-use, --bbox or --all must be specified." << std::endl << std::endl; usage(); } if (targetDir.empty()) { targetDir = proj_context_get_user_writable_directory(ctx, true); } else { if (targetDir.back() == '/') { targetDir.resize(targetDir.size() - 1); } // This is used by projsync() to determine where to write files. pj_context_set_user_writable_directory(ctx, targetDir); } if (!endpoint.empty() && endpoint.back() == '/') { endpoint.resize(endpoint.size() - 1); } if (!quiet && !listFiles) { std::cout << "Downloading from " << endpoint << " into " << targetDir << std::endl; } proj_context_set_enable_network(ctx, true); if (files_geojson_local.empty()) { const std::string files_geojson_url(endpoint + '/' + geojsonFile); if (!proj_download_file(ctx, files_geojson_url.c_str(), false, nullptr, nullptr)) { std::cerr << "Cannot download " << geojsonFile << std::endl; std::exit(1); } files_geojson_local = targetDir + '/' + geojsonFile; } auto file = NS_PROJ::FileManager::open(ctx, files_geojson_local.c_str(), NS_PROJ::FileAccess::READ_ONLY); if (!file) { std::cerr << "Cannot open " << files_geojson_local << std::endl; std::exit(1); } std::string text; while (true) { bool maxLenReached = false; bool eofReached = false; text += file->read_line(1000000, maxLenReached, eofReached); if (maxLenReached) { std::cerr << "Error while parsing " << geojsonFile << " : too long line" << std::endl; std::exit(1); } if (eofReached) break; } file.reset(); if (listFiles) { std::cout << "filename,area_of_use,source_id,file_size" << std::endl; } std::string proj_data_version_str; int proj_data_version_major = 0; int proj_data_version_minor = 0; { const char *proj_data_version = proj_context_get_database_metadata(ctx, "PROJ_DATA.VERSION"); if (proj_data_version) { proj_data_version_str = proj_data_version; const auto tokens = split(proj_data_version, '.'); if (tokens.size() >= 2) { proj_data_version_major = atoi(tokens[0].c_str()); proj_data_version_minor = atoi(tokens[1].c_str()); } } } try { const auto j = json::parse(text); bool foundMatchSourceIdCriterion = false; std::set<std::string> source_ids; bool foundMatchAreaOfUseCriterion = false; std::set<std::string> areas_of_use; bool foundMatchFileCriterion = false; std::set<std::string> files; if (!j.is_object() || !j.contains("features")) { throw ParsingException("no features member"); } std::vector<std::string> to_download; unsigned long long total_size_to_download = 0; const auto features = j["features"]; for (const auto &feat : features) { if (!feat.is_object()) { continue; } if (!feat.contains("properties")) { continue; } const auto properties = feat["properties"]; if (!properties.is_object()) { continue; } if (!properties.contains("name")) { continue; } const auto j_name = properties["name"]; if (!j_name.is_string()) { continue; } const auto name(j_name.get<std::string>()); if (versionFiltering && proj_data_version_major > 0 && properties.contains("version_added")) { const auto j_version_added = properties["version_added"]; if (j_version_added.is_string()) { const auto version_added( j_version_added.get<std::string>()); const auto tokens = split(version_added, '.'); if (tokens.size() >= 2) { int version_major = atoi(tokens[0].c_str()); int version_minor = atoi(tokens[1].c_str()); if (proj_data_version_major < version_major || (proj_data_version_major == version_major && proj_data_version_minor < version_minor)) { // File only useful for a later PROJ version if (verbose) { std::cout << "Skipping " << name << " as it is only useful starting " "with PROJ-data " << version_added << " and we are targeting " << proj_data_version_str << std::endl; } continue; } } } } if (versionFiltering && proj_data_version_major > 0 && properties.contains("version_removed")) { const auto j_version_removed = properties["version_removed"]; if (j_version_removed.is_string()) { const auto version_removed( j_version_removed.get<std::string>()); const auto tokens = split(version_removed, '.'); if (tokens.size() >= 2) { int version_major = atoi(tokens[0].c_str()); int version_minor = atoi(tokens[1].c_str()); if (proj_data_version_major > version_major || (proj_data_version_major == version_major && proj_data_version_minor >= version_minor)) { // File only useful for a previous PROJ version if (verbose) { std::cout << "Skipping " << name << " as it is no longer useful " "starting with PROJ-data " << version_removed << " and we are targeting " << proj_data_version_str << std::endl; } continue; } } } } files.insert(name); if (!properties.contains("source_id")) { continue; } const auto j_source_id = properties["source_id"]; if (!j_source_id.is_string()) { continue; } const auto source_id(j_source_id.get<std::string>()); source_ids.insert(source_id); std::string area_of_use; if (properties.contains("area_of_use")) { const auto j_area_of_use = properties["area_of_use"]; if (j_area_of_use.is_string()) { area_of_use = j_area_of_use.get<std::string>(); areas_of_use.insert(area_of_use); } } unsigned long long file_size = 0; if (properties.contains("file_size")) { const auto j_file_size = properties["file_size"]; if (j_file_size.type() == json::value_t::number_unsigned) { file_size = j_file_size.get<unsigned long long>(); } } const bool matchSourceId = queryAll || queriedSourceId.empty() || source_id.find(queriedSourceId) != std::string::npos; if (!queriedSourceId.empty() && source_id.find(queriedSourceId) != std::string::npos) { foundMatchSourceIdCriterion = true; } const bool matchAreaOfUse = queryAll || queriedAreaOfUse.empty() || area_of_use.find(queriedAreaOfUse) != std::string::npos; if (!queriedAreaOfUse.empty() && area_of_use.find(queriedAreaOfUse) != std::string::npos) { foundMatchAreaOfUseCriterion = true; } const bool matchFile = queryAll || queriedFilename.empty() || name.find(queriedFilename) != std::string::npos; if (!queriedFilename.empty() && name.find(queriedFilename) != std::string::npos) { foundMatchFileCriterion = true; } bool matchBbox = true; if (queryAll || hasQueriedBbox) { matchBbox = false; do { if (!feat.contains("geometry")) { if (queryAll) { matchBbox = true; } break; } const auto j_geometry = feat["geometry"]; if (!j_geometry.is_object()) { if (queryAll) { matchBbox = true; } break; } if (!j_geometry.contains("coordinates")) { break; } const auto j_coordinates = j_geometry["coordinates"]; if (!j_coordinates.is_array()) { break; } if (!j_geometry.contains("type")) { break; } const auto j_geometry_type = j_geometry["type"]; if (!j_geometry_type.is_string()) { break; } const auto geometry_type( j_geometry_type.get<std::string>()); std::vector<double> grid_bbox; if (geometry_type == "MultiPolygon") { std::vector<std::vector<double>> grid_bboxes; bool foundMinus180 = false; bool foundPlus180 = false; for (const auto &obj : j_coordinates) { if (obj.is_array()) { const auto tmp = get_bbox(obj); if (tmp.size() == 4) { if (tmp[0] == -180) foundMinus180 = true; else if (tmp[2] == 180) foundPlus180 = true; grid_bboxes.push_back(tmp); } } } for (auto &bbox : grid_bboxes) { if (foundMinus180 && foundPlus180 && bbox[0] == -180) { bbox[0] = 180; bbox[2] += 360; } if (grid_bbox.empty()) { grid_bbox = bbox; } else { grid_bbox[0] = std::min(grid_bbox[0], bbox[0]); grid_bbox[1] = std::min(grid_bbox[1], bbox[1]); grid_bbox[2] = std::max(grid_bbox[2], bbox[2]); grid_bbox[3] = std::max(grid_bbox[3], bbox[3]); } } } else { grid_bbox = get_bbox(j_coordinates); } if (grid_bbox.size() != 4) { break; } double grid_w = grid_bbox[0]; const double grid_s = grid_bbox[1]; double grid_e = grid_bbox[2]; const double grid_n = grid_bbox[3]; if (grid_e - grid_w > 359 && grid_n - grid_s > 179) { if (!includeWorldCoverage) { break; } grid_w = -std::numeric_limits<double>::max(); grid_e = std::numeric_limits<double>::max(); } else if (grid_e > 180 && queried_west < -180) { grid_w -= 360; grid_e -= 360; } if (queryAll) { matchBbox = true; break; } if (intersects) { if (queried_west < grid_e && grid_w < queried_east && queried_south < grid_n && grid_s < queried_north) { matchBbox = true; } } else { if (grid_w >= queried_west && grid_s >= queried_south && grid_e <= queried_east && grid_n <= queried_north) { matchBbox = true; } } } while (false); } if (matchFile && matchSourceId && matchAreaOfUse && matchBbox) { if (listFiles) { std::cout << name << "," << area_of_use << "," << source_id << "," << file_size << std::endl; continue; } const std::string resource_url( std::string(endpoint).append("/").append(name)); if (proj_is_download_needed(ctx, resource_url.c_str(), false)) { total_size_to_download += file_size; to_download.push_back(resource_url); } else { if (!quiet) { std::cout << resource_url << " already downloaded." << std::endl; } } } } if (!quiet && !listFiles && total_size_to_download > 0) { if (total_size_to_download > 1024 * 1024) std::cout << "Total size to download: " << total_size_to_download / (1024 * 1024) << " MB" << std::endl; else std::cout << "Total to download: " << total_size_to_download << " bytes" << std::endl; } for (size_t i = 0; i < to_download.size(); ++i) { const auto &url = to_download[i]; if (!quiet) { if (dryRun) { std::cout << "Would download "; } else { std::cout << "Downloading "; } std::cout << url << "... (" << i + 1 << " / " << to_download.size() << ")" << std::endl; } if (!dryRun && !proj_download_file(ctx, url.c_str(), false, nullptr, nullptr)) { std::cerr << "Cannot download " << url << std::endl; std::exit(1); } } if (!queriedSourceId.empty() && !foundMatchSourceIdCriterion) { std::cerr << "Warning: '" << queriedSourceId << "' is a unknown value for --source-id." << std::endl; std::cerr << "Known values are:" << std::endl; for (const auto &v : source_ids) { std::cerr << " " << v << std::endl; } std::exit(1); } if (!queriedAreaOfUse.empty() && !foundMatchAreaOfUseCriterion) { std::cerr << "Warning: '" << queriedAreaOfUse << "' is a unknown value for --area-of-use." << std::endl; std::cerr << "Known values are:" << std::endl; for (const auto &v : areas_of_use) { std::cerr << " " << v << std::endl; } std::exit(1); } if (!queriedFilename.empty() && !foundMatchFileCriterion) { std::cerr << "Warning: '" << queriedFilename << "' is a unknown value for --file." << std::endl; std::cerr << "Known values are:" << std::endl; for (const auto &v : files) { std::cerr << " " << v << std::endl; } std::exit(1); } } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << std::endl; std::exit(1); } return 0; } //! @endcond
cpp
PROJ
data/projects/PROJ/src/apps/geod_set.cpp
#define GEOD_IN_GEOD_SET #include <math.h> #include <stdlib.h> #include <string.h> #include "emess.h" #include "geod_interface.h" #include "proj.h" #include "proj_internal.h" void geod_set(int argc, char **argv) { paralist *start = nullptr, *curr; double es; char *name; /* put arguments into internal linked list */ if (argc <= 0) emess(1, "no arguments in initialization list"); start = curr = pj_mkparam(argv[0]); if (!curr) emess(1, "memory allocation failed"); for (int i = 1; curr != nullptr && i < argc; ++i) { curr->next = pj_mkparam(argv[i]); if (!curr->next) emess(1, "memory allocation failed"); curr = curr->next; } /* set elliptical parameters */ if (pj_ell_set(pj_get_default_ctx(), start, &geod_a, &es)) emess(1, "ellipse setup failure"); /* set units */ if ((name = pj_param(nullptr, start, "sunits").s) != nullptr) { bool unit_found = false; auto units = proj_get_units_from_database(nullptr, nullptr, "linear", false, nullptr); for (int i = 0; units && units[i]; i++) { if (units[i]->proj_short_name && strcmp(units[i]->proj_short_name, name) == 0) { unit_found = true; to_meter = units[i]->conv_factor; fr_meter = 1 / to_meter; } } proj_unit_list_destroy(units); if (!unit_found) emess(1, "%s unknown unit conversion id", name); } else to_meter = fr_meter = 1; geod_f = es / (1 + sqrt(1 - es)); geod_ini(); /* check if line or arc mode */ if (pj_param(nullptr, start, "tlat_1").i) { double del_S; phi1 = pj_param(nullptr, start, "rlat_1").f; lam1 = pj_param(nullptr, start, "rlon_1").f; if (pj_param(nullptr, start, "tlat_2").i) { phi2 = pj_param(nullptr, start, "rlat_2").f; lam2 = pj_param(nullptr, start, "rlon_2").f; geod_inv(); geod_pre(); } else if ((geod_S = pj_param(nullptr, start, "dS").f) != 0.) { al12 = pj_param(nullptr, start, "rA").f; geod_pre(); geod_for(); } else emess(1, "incomplete geodesic/arc info"); if ((n_alpha = pj_param(nullptr, start, "in_A").i) > 0) { if ((del_alpha = pj_param(nullptr, start, "rdel_A").f) == 0.0) emess(1, "del azimuth == 0"); } else if ((del_S = fabs(pj_param(nullptr, start, "ddel_S").f)) != 0.) { n_S = (int)(geod_S / del_S + .5); } else if ((n_S = pj_param(nullptr, start, "in_S").i) <= 0) emess(1, "no interval divisor selected"); } /* free up linked list */ for (; start; start = curr) { curr = start->next; free(start); } }
cpp
PROJ
data/projects/PROJ/src/apps/projinfo.cpp
/****************************************************************************** * * Project: PROJ * Purpose: projinfo utility * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ //! @cond Doxygen_Suppress #define FROM_PROJ_CPP #include <cstdlib> #include <fstream> // std::ifstream #include <iostream> #include <set> #include <utility> #include "proj.h" #include "proj_internal.h" #include <proj/common.hpp> #include <proj/coordinateoperation.hpp> #include <proj/coordinates.hpp> #include <proj/crs.hpp> #include <proj/io.hpp> #include <proj/metadata.hpp> #include <proj/util.hpp> #include "proj/internal/internal.hpp" // for split using namespace NS_PROJ::common; using namespace NS_PROJ::coordinates; using namespace NS_PROJ::crs; using namespace NS_PROJ::io; using namespace NS_PROJ::metadata; using namespace NS_PROJ::operation; using namespace NS_PROJ::util; using namespace NS_PROJ::internal; // --------------------------------------------------------------------------- namespace { // anonymous namespace struct OutputOptions { bool quiet = false; bool PROJ5 = false; bool WKT2_2019 = false; bool WKT2_2019_SIMPLIFIED = false; bool WKT2_2015 = false; bool WKT2_2015_SIMPLIFIED = false; bool WKT1_GDAL = false; bool WKT1_ESRI = false; bool PROJJSON = false; bool SQL = false; bool c_ify = false; bool singleLine = false; bool strict = true; bool ballparkAllowed = true; bool allowEllipsoidalHeightAsVerticalCRS = false; std::string outputAuthName{}; std::string outputCode{}; std::vector<std::string> allowedAuthorities{}; }; } // anonymous namespace // --------------------------------------------------------------------------- [[noreturn]] static void usage() { std::cerr << "usage: projinfo [-o formats] " "[-k crs|operation|datum|ensemble|ellipsoid] " "[--summary] [-q]" << std::endl << " ([--area name_or_code] | " "[--bbox west_long,south_lat,east_long,north_lat]) " << std::endl << " [--spatial-test contains|intersects]" << std::endl << " [--crs-extent-use none|both|intersection|smallest]" << std::endl << " [--grid-check " "none|discard_missing|sort|known_available] " << std::endl << " [--pivot-crs always|if_no_direct_transformation|" << "never|{auth:code[,auth:code]*}]" << std::endl << " [--show-superseded] [--hide-ballpark] " "[--accuracy {accuracy}]" << std::endl << " [--allow-ellipsoidal-height-as-vertical-crs]" << std::endl << " [--boundcrs-to-wgs84]" << std::endl << " [--authority name]" << std::endl << " [--main-db-path path] [--aux-db-path path]*" << std::endl << " [--identify] [--3d]" << std::endl << " [--output-id AUTH:CODE]" << std::endl << " [--c-ify] [--single-line]" << std::endl << " --searchpaths | --remote-data |" << std::endl << " --list-crs [list-crs-filter] |" << std::endl << " --dump-db-structure [{object_definition} | " "{object_reference}] |" << std::endl << " {object_definition} | {object_reference} |" << std::endl << " (-s {srs_def} [--s_epoch {epoch}] " "-t {srs_def} [--t_epoch {epoch}])" << std::endl; std::cerr << std::endl; std::cerr << "-o: formats is a comma separated combination of: " "all,default,PROJ,WKT_ALL,WKT2:2015,WKT2:2019,WKT1:GDAL," "WKT1:ESRI,PROJJSON,SQL" << std::endl; std::cerr << " Except 'all' and 'default', other format can be preceded " "by '-' to disable them" << std::endl; std::cerr << std::endl; std::cerr << "list-crs-filter is a comma separated combination of: " "allow_deprecated,geodetic,geocentric," << std::endl; std::cerr << "geographic,geographic_2d,geographic_3d,vertical,projected,compound" << std::endl; std::cerr << std::endl; std::cerr << "{object_definition} might be a PROJ string, a WKT string, " "a AUTHORITY:CODE, or urn:ogc:def:OBJECT_TYPE:AUTHORITY::CODE" << std::endl; std::exit(1); } // --------------------------------------------------------------------------- static std::string un_c_ify_string(const std::string &str) { std::string out(str); out = out.substr(1, out.size() - 2); out = replaceAll(out, "\\\"", "{ESCAPED_DOUBLE_QUOTE}"); out = replaceAll(out, "\\n\"", ""); out = replaceAll(out, "\"", ""); out = replaceAll(out, "{ESCAPED_DOUBLE_QUOTE}", "\""); return out; } // --------------------------------------------------------------------------- static std::string c_ify_string(const std::string &str) { std::string out(str); out = replaceAll(out, "\"", "{DOUBLE_QUOTE}"); out = replaceAll(out, "\n", "\\n\"\n\""); out = replaceAll(out, "{DOUBLE_QUOTE}", "\\\""); return "\"" + out + "\""; } // --------------------------------------------------------------------------- static ExtentPtr makeBboxFilter(DatabaseContextPtr dbContext, const std::string &bboxStr, const std::string &area, bool errorIfSeveralAreaMatches) { ExtentPtr bboxFilter = nullptr; if (!bboxStr.empty()) { auto bbox(split(bboxStr, ',')); if (bbox.size() != 4) { std::cerr << "Incorrect number of values for option --bbox: " << bboxStr << std::endl; usage(); } try { std::vector<double> bboxValues = { c_locale_stod(bbox[0]), c_locale_stod(bbox[1]), c_locale_stod(bbox[2]), c_locale_stod(bbox[3])}; bboxFilter = Extent::createFromBBOX(bboxValues[0], bboxValues[1], bboxValues[2], bboxValues[3]) .as_nullable(); } catch (const std::exception &e) { std::cerr << "Invalid value for option --bbox: " << bboxStr << ", " << e.what() << std::endl; usage(); } } else if (!area.empty()) { assert(dbContext); try { if (area.find(' ') == std::string::npos && area.find(':') != std::string::npos) { auto tokens = split(area, ':'); if (tokens.size() == 2) { const std::string &areaAuth = tokens[0]; const std::string &areaCode = tokens[1]; bboxFilter = AuthorityFactory::create( NN_NO_CHECK(dbContext), areaAuth) ->createExtent(areaCode) .as_nullable(); } } if (!bboxFilter) { auto authFactory = AuthorityFactory::create( NN_NO_CHECK(dbContext), std::string()); auto res = authFactory->listAreaOfUseFromName(area, false); if (res.size() == 1) { bboxFilter = AuthorityFactory::create( NN_NO_CHECK(dbContext), res.front().first) ->createExtent(res.front().second) .as_nullable(); } else { res = authFactory->listAreaOfUseFromName(area, true); if (res.size() == 1) { bboxFilter = AuthorityFactory::create(NN_NO_CHECK(dbContext), res.front().first) ->createExtent(res.front().second) .as_nullable(); } else if (res.empty()) { std::cerr << "No area of use matching provided name" << std::endl; std::exit(1); } else if (errorIfSeveralAreaMatches) { std::cerr << "Several candidates area of use " "matching provided name :" << std::endl; for (const auto &candidate : res) { auto obj = AuthorityFactory::create(NN_NO_CHECK(dbContext), candidate.first) ->createExtent(candidate.second); std::cerr << " " << candidate.first << ":" << candidate.second << " : " << *obj->description() << std::endl; } std::exit(1); } } } } catch (const std::exception &e) { std::cerr << "Area of use retrieval failed: " << e.what() << std::endl; std::exit(1); } } return bboxFilter; } static BaseObjectNNPtr buildObject( DatabaseContextPtr dbContext, const std::string &user_string, const std::string &epoch, const std::string &kind, const std::string &context, bool buildBoundCRSToWGS84, CoordinateOperationContext::IntermediateCRSUse allowUseIntermediateCRS, bool promoteTo3D, bool normalizeAxisOrder, bool quiet) { BaseObjectPtr obj; std::string l_user_string(user_string); if (!user_string.empty() && user_string[0] == '@') { std::ifstream fs; auto filename = user_string.substr(1); fs.open(filename, std::fstream::in | std::fstream::binary); if (!fs.is_open()) { std::cerr << context << ": cannot open " << filename << std::endl; std::exit(1); } l_user_string.clear(); while (!fs.eof()) { char buffer[256]; fs.read(buffer, sizeof(buffer)); l_user_string.append(buffer, static_cast<size_t>(fs.gcount())); if (l_user_string.size() > 1000 * 1000) { fs.close(); std::cerr << context << ": too big file" << std::endl; std::exit(1); } } fs.close(); } if (!l_user_string.empty() && l_user_string.back() == '\n') { l_user_string.resize(l_user_string.size() - 1); } if (!l_user_string.empty() && l_user_string.back() == '\r') { l_user_string.resize(l_user_string.size() - 1); } try { auto tokens = split(l_user_string, ':'); if (kind == "operation" && tokens.size() == 2) { auto urn = "urn:ogc:def:coordinateOperation:" + tokens[0] + "::" + tokens[1]; obj = createFromUserInput(urn, dbContext).as_nullable(); } else if ((kind == "ellipsoid" || kind == "datum" || kind == "ensemble") && tokens.size() == 2) { auto urn = "urn:ogc:def:" + kind + ":" + tokens[0] + "::" + tokens[1]; obj = createFromUserInput(urn, dbContext).as_nullable(); } else { // Convenience to be able to use C escaped strings... if (l_user_string.size() > 2 && l_user_string[0] == '"' && l_user_string.back() == '"' && l_user_string.find("\\\"") != std::string::npos) { l_user_string = un_c_ify_string(l_user_string); } WKTParser wktParser; if (wktParser.guessDialect(l_user_string) != WKTParser::WKTGuessedDialect::NOT_WKT) { wktParser.setStrict(false); wktParser.attachDatabaseContext(dbContext); obj = wktParser.createFromWKT(l_user_string).as_nullable(); if (!quiet) { auto warnings = wktParser.warningList(); if (!warnings.empty()) { for (const auto &str : warnings) { std::cerr << "Warning: " << str << std::endl; } } } } else if (dbContext && !kind.empty() && kind != "crs" && l_user_string.find(':') == std::string::npos) { std::vector<AuthorityFactory::ObjectType> allowedTypes; if (kind == "operation") allowedTypes.push_back( AuthorityFactory::ObjectType::COORDINATE_OPERATION); else if (kind == "ellipsoid") allowedTypes.push_back( AuthorityFactory::ObjectType::ELLIPSOID); else if (kind == "datum") allowedTypes.push_back(AuthorityFactory::ObjectType::DATUM); else if (kind == "ensemble") allowedTypes.push_back( AuthorityFactory::ObjectType::DATUM_ENSEMBLE); constexpr size_t limitResultCount = 10; auto factory = AuthorityFactory::create(NN_NO_CHECK(dbContext), std::string()); for (int pass = 0; pass <= 1; ++pass) { const bool approximateMatch = (pass == 1); auto res = factory->createObjectsFromName( l_user_string, allowedTypes, approximateMatch, limitResultCount); if (res.size() == 1) { obj = res.front().as_nullable(); } else { for (const auto &l_obj : res) { if (Identifier::isEquivalentName( l_obj->nameStr().c_str(), l_user_string.c_str())) { obj = l_obj.as_nullable(); break; } } if (obj) { break; } } if (res.size() > 1) { std::string msg("several objects matching this name: "); bool first = true; for (const auto &l_obj : res) { if (msg.size() > 200) { msg += ", ..."; break; } if (!first) { msg += ", "; } first = false; msg += l_obj->nameStr(); } std::cerr << context << ": " << msg << std::endl; std::exit(1); } } } else { obj = createFromUserInput(l_user_string, dbContext).as_nullable(); } } } catch (const std::exception &e) { std::cerr << context << ": parsing of user string failed: " << e.what() << std::endl; std::exit(1); } if (buildBoundCRSToWGS84) { auto crs = std::dynamic_pointer_cast<CRS>(obj); if (crs) { obj = crs->createBoundCRSToWGS84IfPossible(dbContext, allowUseIntermediateCRS) .as_nullable(); } } if (promoteTo3D) { auto crs = std::dynamic_pointer_cast<CRS>(obj); if (crs) { obj = crs->promoteTo3D(std::string(), dbContext).as_nullable(); } else { auto cm = std::dynamic_pointer_cast<CoordinateMetadata>(obj); if (cm) { obj = cm->promoteTo3D(std::string(), dbContext).as_nullable(); } } } if (normalizeAxisOrder) { auto crs = std::dynamic_pointer_cast<CRS>(obj); if (crs) { obj = crs->normalizeForVisualization().as_nullable(); } } if (!epoch.empty()) { auto crs = std::dynamic_pointer_cast<CRS>(obj); if (crs) { obj = CoordinateMetadata::create(NN_NO_CHECK(crs), std::stod(epoch), dbContext) .as_nullable(); } else { std::cerr << context << ": applying epoch to a non-CRS object" << std::endl; std::exit(1); } } return NN_NO_CHECK(obj); } // --------------------------------------------------------------------------- static void outputObject( DatabaseContextPtr dbContext, BaseObjectNNPtr obj, CoordinateOperationContext::IntermediateCRSUse allowUseIntermediateCRS, const OutputOptions &outputOpt) { auto identified = nn_dynamic_pointer_cast<IdentifiedObject>(obj); if (!outputOpt.quiet && identified && identified->isDeprecated()) { std::cout << "Warning: object is deprecated" << std::endl; auto crs = dynamic_cast<const CRS *>(obj.get()); if (crs && dbContext) { try { auto list = crs->getNonDeprecated(NN_NO_CHECK(dbContext)); if (!list.empty()) { std::cout << "Alternative non-deprecated CRS:" << std::endl; } for (const auto &altCRS : list) { const auto &ids = altCRS->identifiers(); if (!ids.empty()) { std::cout << " " << *(ids[0]->codeSpace()) << ":" << ids[0]->code() << std::endl; } } } catch (const std::exception &) { } } std::cout << std::endl; } const auto projStringExportable = nn_dynamic_pointer_cast<IPROJStringExportable>(obj); bool alreadyOutputted = false; if (projStringExportable) { if (outputOpt.PROJ5) { try { auto crs = nn_dynamic_pointer_cast<CRS>(obj); if (!outputOpt.quiet) { if (crs) { std::cout << "PROJ.4 string:" << std::endl; } else { std::cout << "PROJ string:" << std::endl; } } std::shared_ptr<IPROJStringExportable> objToExport; if (crs) { objToExport = nn_dynamic_pointer_cast<IPROJStringExportable>( crs->createBoundCRSToWGS84IfPossible( dbContext, allowUseIntermediateCRS)); } if (!objToExport) { objToExport = projStringExportable; } auto formatter = PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, dbContext); formatter->setMultiLine(!outputOpt.singleLine && crs == nullptr); std::cout << objToExport->exportToPROJString(formatter.get()) << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to PROJ string: " << e.what() << std::endl; } alreadyOutputted = true; } } auto wktExportable = nn_dynamic_pointer_cast<IWKTExportable>(obj); if (wktExportable) { if (outputOpt.WKT2_2015) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "WKT2:2015 string:" << std::endl; } auto formatter = WKTFormatter::create( WKTFormatter::Convention::WKT2_2015, dbContext); formatter->setMultiLine(!outputOpt.singleLine); formatter->setStrict(outputOpt.strict); auto wkt = wktExportable->exportToWKT(formatter.get()); if (outputOpt.c_ify) { wkt = c_ify_string(wkt); } std::cout << wkt << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to WKT2:2015: " << e.what() << std::endl; } alreadyOutputted = true; } if (outputOpt.WKT2_2015_SIMPLIFIED) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "WKT2:2015_SIMPLIFIED string:" << std::endl; } auto formatter = WKTFormatter::create( WKTFormatter::Convention::WKT2_2015_SIMPLIFIED, dbContext); if (outputOpt.singleLine) { formatter->setMultiLine(false); } formatter->setStrict(outputOpt.strict); auto wkt = wktExportable->exportToWKT(formatter.get()); if (outputOpt.c_ify) { wkt = c_ify_string(wkt); } std::cout << wkt << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to WKT2:2015_SIMPLIFIED: " << e.what() << std::endl; } alreadyOutputted = true; } if (outputOpt.WKT2_2019) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "WKT2:2019 string:" << std::endl; } auto formatter = WKTFormatter::create( WKTFormatter::Convention::WKT2_2019, dbContext); if (outputOpt.singleLine) { formatter->setMultiLine(false); } formatter->setStrict(outputOpt.strict); auto wkt = wktExportable->exportToWKT(formatter.get()); if (outputOpt.c_ify) { wkt = c_ify_string(wkt); } std::cout << wkt << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to WKT2:2019: " << e.what() << std::endl; } alreadyOutputted = true; } if (outputOpt.WKT2_2019_SIMPLIFIED) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "WKT2:2019_SIMPLIFIED string:" << std::endl; } auto formatter = WKTFormatter::create( WKTFormatter::Convention::WKT2_2019_SIMPLIFIED, dbContext); if (outputOpt.singleLine) { formatter->setMultiLine(false); } formatter->setStrict(outputOpt.strict); auto wkt = wktExportable->exportToWKT(formatter.get()); if (outputOpt.c_ify) { wkt = c_ify_string(wkt); } std::cout << wkt << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to WKT2:2019_SIMPLIFIED: " << e.what() << std::endl; } alreadyOutputted = true; } if (outputOpt.WKT1_GDAL && !nn_dynamic_pointer_cast<Conversion>(obj)) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "WKT1:GDAL string:" << std::endl; } auto formatter = WKTFormatter::create( WKTFormatter::Convention::WKT1_GDAL, dbContext); if (outputOpt.singleLine) { formatter->setMultiLine(false); } formatter->setStrict(outputOpt.strict); formatter->setAllowEllipsoidalHeightAsVerticalCRS( outputOpt.allowEllipsoidalHeightAsVerticalCRS); auto wkt = wktExportable->exportToWKT(formatter.get()); if (outputOpt.c_ify) { wkt = c_ify_string(wkt); } std::cout << wkt << std::endl; std::cout << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to WKT1:GDAL: " << e.what() << std::endl; } alreadyOutputted = true; } if (outputOpt.WKT1_ESRI && !nn_dynamic_pointer_cast<Conversion>(obj)) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "WKT1:ESRI string:" << std::endl; } auto formatter = WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, dbContext); formatter->setStrict(outputOpt.strict); auto wkt = wktExportable->exportToWKT(formatter.get()); if (outputOpt.c_ify) { wkt = c_ify_string(wkt); } std::cout << wkt << std::endl; std::cout << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to WKT1:ESRI: " << e.what() << std::endl; } alreadyOutputted = true; } } auto JSONExportable = nn_dynamic_pointer_cast<IJSONExportable>(obj); if (JSONExportable) { if (outputOpt.PROJJSON) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "PROJJSON:" << std::endl; } auto formatter(JSONFormatter::create(dbContext)); if (outputOpt.singleLine) { formatter->setMultiLine(false); } auto jsonString(JSONExportable->exportToJSON(formatter.get())); if (outputOpt.c_ify) { jsonString = c_ify_string(jsonString); } std::cout << jsonString << std::endl; } catch (const std::exception &e) { std::cerr << "Error when exporting to PROJJSON: " << e.what() << std::endl; } alreadyOutputted = true; } } if (identified && dbContext && outputOpt.SQL) { try { if (alreadyOutputted) { std::cout << std::endl; } if (!outputOpt.quiet) { std::cout << "SQL:" << std::endl; } dbContext->startInsertStatementsSession(); auto allowedAuthorities(outputOpt.allowedAuthorities); if (allowedAuthorities.empty()) { allowedAuthorities.emplace_back("EPSG"); allowedAuthorities.emplace_back("PROJ"); } const auto statements = dbContext->getInsertStatementsFor( NN_NO_CHECK(identified), outputOpt.outputAuthName, outputOpt.outputCode, false, allowedAuthorities); dbContext->stopInsertStatementsSession(); for (const auto &sql : statements) { std::cout << sql << std::endl; } } catch (const std::exception &e) { std::cerr << "Error when exporting to SQL: " << e.what() << std::endl; } // alreadyOutputted = true; } auto op = dynamic_cast<CoordinateOperation *>(obj.get()); if (!outputOpt.quiet && op && dbContext && getenv("PROJINFO_NO_GRID_CHECK") == nullptr) { try { auto setGrids = op->gridsNeeded(dbContext, false); bool firstWarning = true; for (const auto &grid : setGrids) { if (!grid.available) { if (firstWarning) { std::cout << std::endl; firstWarning = false; } std::cout << "Grid " << grid.shortName << " needed but not found on the system."; if (!grid.packageName.empty()) { std::cout << " Can be obtained from the " << grid.packageName << " package"; if (!grid.url.empty()) { std::cout << " at " << grid.url; } std::cout << ", or on CDN"; } else if (!grid.url.empty()) { std::cout << " Can be obtained at " << grid.url; } std::cout << std::endl; } } } catch (const std::exception &e) { std::cerr << "Error in gridsNeeded(): " << e.what() << std::endl; } } } // --------------------------------------------------------------------------- static void outputOperationSummary( const CoordinateOperationNNPtr &op, const DatabaseContextPtr &dbContext, CoordinateOperationContext::GridAvailabilityUse gridAvailabilityUse) { auto ids = op->identifiers(); if (!ids.empty()) { std::cout << *(ids[0]->codeSpace()) << ":" << ids[0]->code(); } else { std::cout << "unknown id"; } std::cout << ", "; const auto &name = op->nameStr(); if (!name.empty()) { std::cout << name; } else { std::cout << "unknown name"; } std::cout << ", "; const auto &accuracies = op->coordinateOperationAccuracies(); if (!accuracies.empty()) { std::cout << accuracies[0]->value() << " m"; } else { if (std::dynamic_pointer_cast<Conversion>(op.as_nullable())) { std::cout << "0 m"; } else { std::cout << "unknown accuracy"; } } std::cout << ", "; const auto &domains = op->domains(); if (!domains.empty() && domains[0]->domainOfValidity() && domains[0]->domainOfValidity()->description().has_value()) { std::cout << *(domains[0]->domainOfValidity()->description()); } else { std::cout << "unknown domain of validity"; } if (op->hasBallparkTransformation()) { std::cout << ", has ballpark transformation"; } if (dbContext && getenv("PROJINFO_NO_GRID_CHECK") == nullptr) { try { const auto setGrids = op->gridsNeeded(dbContext, false); for (const auto &grid : setGrids) { if (!grid.available) { std::cout << ", at least one grid missing"; if (gridAvailabilityUse == CoordinateOperationContext::GridAvailabilityUse:: KNOWN_AVAILABLE && !grid.packageName.empty()) { std::cout << " on the system, but available on CDN"; } break; } } } catch (const std::exception &) { } } std::cout << std::endl; } // --------------------------------------------------------------------------- static bool is3DCRS(const CRSPtr &crs) { if (dynamic_cast<CompoundCRS *>(crs.get())) return true; auto geodCRS = dynamic_cast<GeodeticCRS *>(crs.get()); if (geodCRS) return geodCRS->coordinateSystem()->axisList().size() == 3U; auto projCRS = dynamic_cast<ProjectedCRS *>(crs.get()); if (projCRS) return projCRS->coordinateSystem()->axisList().size() == 3U; return false; } // --------------------------------------------------------------------------- static void outputOperations( const DatabaseContextPtr &dbContext, const std::string &sourceCRSStr, const std::string &sourceEpoch, const std::string &targetCRSStr, const std::string &targetEpoch, const ExtentPtr &bboxFilter, CoordinateOperationContext::SpatialCriterion spatialCriterion, bool spatialCriterionExplicitlySpecified, CoordinateOperationContext::SourceTargetCRSExtentUse crsExtentUse, CoordinateOperationContext::GridAvailabilityUse gridAvailabilityUse, CoordinateOperationContext::IntermediateCRSUse allowUseIntermediateCRS, const std::vector<std::pair<std::string, std::string>> &pivots, const std::string &authority, bool usePROJGridAlternatives, bool showSuperseded, bool promoteTo3D, bool normalizeAxisOrder, double minimumAccuracy, const OutputOptions &outputOpt, bool summary) { auto sourceObj = buildObject( dbContext, sourceCRSStr, sourceEpoch, "crs", "source CRS", false, CoordinateOperationContext::IntermediateCRSUse::NEVER, promoteTo3D, normalizeAxisOrder, outputOpt.quiet); auto sourceCRS = nn_dynamic_pointer_cast<CRS>(sourceObj); CoordinateMetadataPtr sourceCoordinateMetadata; if (!sourceCRS) { sourceCoordinateMetadata = nn_dynamic_pointer_cast<CoordinateMetadata>(sourceObj); if (!sourceCoordinateMetadata) { std::cerr << "source CRS string is not a CRS or a CoordinateMetadata" << std::endl; std::exit(1); } if (!sourceCoordinateMetadata->coordinateEpoch().has_value()) { sourceCRS = sourceCoordinateMetadata->crs().as_nullable(); sourceCoordinateMetadata.reset(); } } auto targetObj = buildObject( dbContext, targetCRSStr, targetEpoch, "crs", "target CRS", false, CoordinateOperationContext::IntermediateCRSUse::NEVER, promoteTo3D, normalizeAxisOrder, outputOpt.quiet); auto targetCRS = nn_dynamic_pointer_cast<CRS>(targetObj); CoordinateMetadataPtr targetCoordinateMetadata; if (!targetCRS) { targetCoordinateMetadata = nn_dynamic_pointer_cast<CoordinateMetadata>(targetObj); if (!targetCoordinateMetadata) { std::cerr << "target CRS string is not a CRS or a CoordinateMetadata" << std::endl; std::exit(1); } if (!targetCoordinateMetadata->coordinateEpoch().has_value()) { targetCRS = targetCoordinateMetadata->crs().as_nullable(); targetCoordinateMetadata.reset(); } } // TODO: handle promotion of CoordinateMetadata if (sourceCRS && targetCRS && dbContext && !promoteTo3D) { // Auto-promote source/target CRS if it is specified by its name, // if it has a known 3D version of it and that the other CRS is 3D. // e.g projinfo -s "WGS 84 + EGM96 height" -t "WGS 84" if (is3DCRS(targetCRS) && !is3DCRS(sourceCRS) && !sourceCRS->identifiers().empty() && Identifier::isEquivalentName(sourceCRSStr.c_str(), sourceCRS->nameStr().c_str())) { auto promoted = sourceCRS->promoteTo3D(std::string(), dbContext).as_nullable(); if (!promoted->identifiers().empty()) { sourceCRS = std::move(promoted); } } else if (is3DCRS(sourceCRS) && !is3DCRS(targetCRS) && !targetCRS->identifiers().empty() && Identifier::isEquivalentName(targetCRSStr.c_str(), targetCRS->nameStr().c_str())) { auto promoted = targetCRS->promoteTo3D(std::string(), dbContext).as_nullable(); if (!promoted->identifiers().empty()) { targetCRS = std::move(promoted); } } } std::vector<CoordinateOperationNNPtr> list; size_t spatialCriterionPartialIntersectionResultCount = 0; bool spatialCriterionPartialIntersectionMoreRelevant = false; try { auto authFactory = dbContext ? AuthorityFactory::create(NN_NO_CHECK(dbContext), authority) .as_nullable() : nullptr; auto ctxt = CoordinateOperationContext::create(authFactory, bboxFilter, 0); const auto createOperations = [&]() { if (sourceCoordinateMetadata) { if (targetCoordinateMetadata) { return CoordinateOperationFactory::create() ->createOperations( NN_NO_CHECK(sourceCoordinateMetadata), NN_NO_CHECK(targetCoordinateMetadata), ctxt); } return CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(sourceCoordinateMetadata), NN_NO_CHECK(targetCRS), ctxt); } else if (targetCoordinateMetadata) { return CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCoordinateMetadata), ctxt); } else { return CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), ctxt); } }; ctxt->setSpatialCriterion(spatialCriterion); ctxt->setSourceAndTargetCRSExtentUse(crsExtentUse); ctxt->setGridAvailabilityUse(gridAvailabilityUse); ctxt->setAllowUseIntermediateCRS(allowUseIntermediateCRS); ctxt->setIntermediateCRS(pivots); ctxt->setUsePROJAlternativeGridNames(usePROJGridAlternatives); ctxt->setDiscardSuperseded(!showSuperseded); ctxt->setAllowBallparkTransformations(outputOpt.ballparkAllowed); if (minimumAccuracy >= 0) { ctxt->setDesiredAccuracy(minimumAccuracy); } list = createOperations(); if (!spatialCriterionExplicitlySpecified && spatialCriterion == CoordinateOperationContext::SpatialCriterion:: STRICT_CONTAINMENT) { try { ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion:: PARTIAL_INTERSECTION); auto list2 = createOperations(); spatialCriterionPartialIntersectionResultCount = list2.size(); if (spatialCriterionPartialIntersectionResultCount == 1 && list.size() == 1 && list2[0]->nameStr() != list[0]->nameStr()) { spatialCriterionPartialIntersectionMoreRelevant = true; } } catch (const std::exception &) { } } } catch (const std::exception &e) { std::cerr << "createOperations() failed with: " << e.what() << std::endl; std::exit(1); } if (outputOpt.quiet && !list.empty()) { outputObject(dbContext, list[0], allowUseIntermediateCRS, outputOpt); return; } std::cout << "Candidate operations found: " << list.size() << std::endl; if (spatialCriterionPartialIntersectionResultCount > list.size()) { std::cout << "Note: using '--spatial-test intersects' would bring " "more results (" << spatialCriterionPartialIntersectionResultCount << ")" << std::endl; } else if (spatialCriterionPartialIntersectionMoreRelevant) { std::cout << "Note: using '--spatial-test intersects' would bring " "more relevant results." << std::endl; } if (summary) { for (const auto &op : list) { outputOperationSummary(op, dbContext, gridAvailabilityUse); } } else { bool first = true; for (size_t i = 0; i < list.size(); ++i) { const auto &op = list[i]; if (!first) { std::cout << std::endl; } first = false; std::cout << "-------------------------------------" << std::endl; std::cout << "Operation No. " << (i + 1) << ":" << std::endl << std::endl; outputOperationSummary(op, dbContext, gridAvailabilityUse); std::cout << std::endl; outputObject(dbContext, op, allowUseIntermediateCRS, outputOpt); } } } // --------------------------------------------------------------------------- int main(int argc, char **argv) { pj_stderr_proj_lib_deprecation_warning(); if (argc == 1) { std::cerr << pj_get_release() << std::endl; usage(); } std::string user_string; bool user_string_specified = false; std::string sourceCRSStr; std::string sourceEpoch; std::string targetCRSStr; std::string targetEpoch; bool outputSwitchSpecified = false; OutputOptions outputOpt; std::string objectKind; bool summary = false; std::string bboxStr; std::string area; bool spatialCriterionExplicitlySpecified = false; CoordinateOperationContext::SpatialCriterion spatialCriterion = CoordinateOperationContext::SpatialCriterion::STRICT_CONTAINMENT; CoordinateOperationContext::SourceTargetCRSExtentUse crsExtentUse = CoordinateOperationContext::SourceTargetCRSExtentUse::SMALLEST; bool buildBoundCRSToWGS84 = false; CoordinateOperationContext::GridAvailabilityUse gridAvailabilityUse = proj_context_is_network_enabled(nullptr) ? CoordinateOperationContext::GridAvailabilityUse::KNOWN_AVAILABLE : CoordinateOperationContext::GridAvailabilityUse::USE_FOR_SORTING; CoordinateOperationContext::IntermediateCRSUse allowUseIntermediateCRS = CoordinateOperationContext::IntermediateCRSUse:: IF_NO_DIRECT_TRANSFORMATION; std::vector<std::pair<std::string, std::string>> pivots; bool usePROJGridAlternatives = true; std::string mainDBPath; std::vector<std::string> auxDBPath; bool guessDialect = false; std::string authority; bool identify = false; bool showSuperseded = false; bool promoteTo3D = false; bool normalizeAxisOrder = false; double minimumAccuracy = -1; bool outputAll = false; bool dumpDbStructure = false; std::string listCRSFilter; bool listCRSSpecified = false; for (int i = 1; i < argc; i++) { const std::string arg(argv[i]); if (arg == "-o" && i + 1 < argc) { outputSwitchSpecified = true; i++; const auto formats(split(argv[i], ',')); for (const auto &format : formats) { if (ci_equal(format, "all")) { outputAll = true; outputOpt.PROJ5 = true; outputOpt.WKT2_2019 = true; outputOpt.WKT2_2015 = true; outputOpt.WKT1_GDAL = true; outputOpt.WKT1_ESRI = true; outputOpt.PROJJSON = true; outputOpt.SQL = true; } else if (ci_equal(format, "default")) { outputOpt.PROJ5 = true; outputOpt.WKT2_2019 = true; outputOpt.WKT2_2015 = false; outputOpt.WKT1_GDAL = false; } else if (ci_equal(format, "PROJ")) { outputOpt.PROJ5 = true; } else if (ci_equal(format, "-PROJ")) { outputOpt.PROJ5 = false; } else if (ci_equal(format, "WKT_ALL") || ci_equal(format, "WKT-ALL")) { outputOpt.WKT2_2019 = true; outputOpt.WKT2_2015 = true; outputOpt.WKT1_GDAL = true; } else if (ci_equal(format, "-WKT_ALL") || ci_equal(format, "-WKT-ALL")) { outputOpt.WKT2_2019 = false; outputOpt.WKT2_2015 = false; outputOpt.WKT1_GDAL = false; } else if (ci_equal(format, "WKT2_2019") || ci_equal(format, "WKT2-2019") || ci_equal(format, "WKT2:2019") || /* legacy: undocumented */ ci_equal(format, "WKT2_2018") || ci_equal(format, "WKT2-2018") || ci_equal(format, "WKT2:2018")) { outputOpt.WKT2_2019 = true; } else if (ci_equal(format, "WKT2_2019_SIMPLIFIED") || ci_equal(format, "WKT2-2019_SIMPLIFIED") || ci_equal(format, "WKT2:2019_SIMPLIFIED") || /* legacy: undocumented */ ci_equal(format, "WKT2_2018_SIMPLIFIED") || ci_equal(format, "WKT2-2018_SIMPLIFIED") || ci_equal(format, "WKT2:2018_SIMPLIFIED")) { outputOpt.WKT2_2019_SIMPLIFIED = true; } else if (ci_equal(format, "-WKT2_2019") || ci_equal(format, "-WKT2-2019") || ci_equal(format, "-WKT2:2019") || /* legacy: undocumented */ ci_equal(format, "-WKT2_2018") || ci_equal(format, "-WKT2-2018") || ci_equal(format, "-WKT2:2018")) { outputOpt.WKT2_2019 = false; } else if (ci_equal(format, "WKT2_2015") || ci_equal(format, "WKT2-2015") || ci_equal(format, "WKT2:2015")) { outputOpt.WKT2_2015 = true; } else if (ci_equal(format, "WKT2_2015_SIMPLIFIED") || ci_equal(format, "WKT2-2015_SIMPLIFIED") || ci_equal(format, "WKT2:2015_SIMPLIFIED")) { outputOpt.WKT2_2015_SIMPLIFIED = true; } else if (ci_equal(format, "-WKT2_2015") || ci_equal(format, "-WKT2-2015") || ci_equal(format, "-WKT2:2015")) { outputOpt.WKT2_2015 = false; } else if (ci_equal(format, "WKT1_GDAL") || ci_equal(format, "WKT1-GDAL") || ci_equal(format, "WKT1:GDAL")) { outputOpt.WKT1_GDAL = true; } else if (ci_equal(format, "-WKT1_GDAL") || ci_equal(format, "-WKT1-GDAL") || ci_equal(format, "-WKT1:GDAL")) { outputOpt.WKT1_GDAL = false; } else if (ci_equal(format, "WKT1_ESRI") || ci_equal(format, "WKT1-ESRI") || ci_equal(format, "WKT1:ESRI")) { outputOpt.WKT1_ESRI = true; } else if (ci_equal(format, "-WKT1_ESRI") || ci_equal(format, "-WKT1-ESRI") || ci_equal(format, "-WKT1:ESRI")) { outputOpt.WKT1_ESRI = false; } else if (ci_equal(format, "PROJJSON")) { outputOpt.PROJJSON = true; } else if (ci_equal(format, "-PROJJSON")) { outputOpt.PROJJSON = false; } else if (ci_equal(format, "SQL")) { outputOpt.SQL = true; } else if (ci_equal(format, "-SQL")) { outputOpt.SQL = false; } else { std::cerr << "Unrecognized value for option -o: " << format << std::endl; usage(); } } } else if (arg == "--bbox" && i + 1 < argc) { i++; bboxStr = argv[i]; } else if (arg == "--accuracy" && i + 1 < argc) { i++; try { minimumAccuracy = c_locale_stod(argv[i]); } catch (const std::exception &e) { std::cerr << "Invalid value for option --accuracy: " << e.what() << std::endl; usage(); } } else if (arg == "--area" && i + 1 < argc) { i++; area = argv[i]; } else if (arg == "-k" && i + 1 < argc) { i++; std::string kind(argv[i]); if (ci_equal(kind, "crs") || ci_equal(kind, "srs")) { objectKind = "crs"; } else if (ci_equal(kind, "operation")) { objectKind = "operation"; } else if (ci_equal(kind, "ellipsoid")) { objectKind = "ellipsoid"; } else if (ci_equal(kind, "datum")) { objectKind = "datum"; } else if (ci_equal(kind, "ensemble")) { objectKind = "ensemble"; } else { std::cerr << "Unrecognized value for option -k: " << kind << std::endl; usage(); } } else if ((arg == "-s" || arg == "--source-crs") && i + 1 < argc) { i++; sourceCRSStr = argv[i]; } else if (arg == "--s_epoch" && i + 1 < argc) { i++; sourceEpoch = argv[i]; } else if ((arg == "-t" || arg == "--target-crs") && i + 1 < argc) { i++; targetCRSStr = argv[i]; } else if (arg == "--t_epoch" && i + 1 < argc) { i++; targetEpoch = argv[i]; } else if (arg == "-q" || arg == "--quiet") { outputOpt.quiet = true; } else if (arg == "--c-ify") { outputOpt.c_ify = true; } else if (arg == "--single-line") { outputOpt.singleLine = true; } else if (arg == "--summary") { summary = true; } else if (ci_equal(arg, "--boundcrs-to-wgs84")) { buildBoundCRSToWGS84 = true; // undocumented: only for debugging purposes } else if (ci_equal(arg, "--no-proj-grid-alternatives")) { usePROJGridAlternatives = false; } else if (arg == "--spatial-test" && i + 1 < argc) { i++; std::string value(argv[i]); spatialCriterionExplicitlySpecified = true; if (ci_equal(value, "contains")) { spatialCriterion = CoordinateOperationContext:: SpatialCriterion::STRICT_CONTAINMENT; } else if (ci_equal(value, "intersects")) { spatialCriterion = CoordinateOperationContext:: SpatialCriterion::PARTIAL_INTERSECTION; } else { std::cerr << "Unrecognized value for option --spatial-test: " << value << std::endl; usage(); } } else if (arg == "--crs-extent-use" && i + 1 < argc) { i++; std::string value(argv[i]); if (ci_equal(value, "NONE")) { crsExtentUse = CoordinateOperationContext::SourceTargetCRSExtentUse::NONE; } else if (ci_equal(value, "BOTH")) { crsExtentUse = CoordinateOperationContext::SourceTargetCRSExtentUse::BOTH; } else if (ci_equal(value, "INTERSECTION")) { crsExtentUse = CoordinateOperationContext:: SourceTargetCRSExtentUse::INTERSECTION; } else if (ci_equal(value, "SMALLEST")) { crsExtentUse = CoordinateOperationContext:: SourceTargetCRSExtentUse::SMALLEST; } else { std::cerr << "Unrecognized value for option --crs-extent-use: " << value << std::endl; usage(); } } else if (arg == "--grid-check" && i + 1 < argc) { i++; std::string value(argv[i]); if (ci_equal(value, "none")) { gridAvailabilityUse = CoordinateOperationContext:: GridAvailabilityUse::IGNORE_GRID_AVAILABILITY; } else if (ci_equal(value, "discard_missing")) { gridAvailabilityUse = CoordinateOperationContext:: GridAvailabilityUse::DISCARD_OPERATION_IF_MISSING_GRID; } else if (ci_equal(value, "sort")) { gridAvailabilityUse = CoordinateOperationContext:: GridAvailabilityUse::USE_FOR_SORTING; } else if (ci_equal(value, "known_available")) { gridAvailabilityUse = CoordinateOperationContext:: GridAvailabilityUse::KNOWN_AVAILABLE; } else { std::cerr << "Unrecognized value for option --grid-check: " << value << std::endl; usage(); } } else if (arg == "--pivot-crs" && i + 1 < argc) { i++; auto value(argv[i]); if (ci_equal(std::string(value), "always")) { allowUseIntermediateCRS = CoordinateOperationContext::IntermediateCRSUse::ALWAYS; } else if (ci_equal(std::string(value), "if_no_direct_transformation")) { allowUseIntermediateCRS = CoordinateOperationContext:: IntermediateCRSUse::IF_NO_DIRECT_TRANSFORMATION; } else if (ci_equal(std::string(value), "never")) { allowUseIntermediateCRS = CoordinateOperationContext::IntermediateCRSUse::NEVER; } else { auto splitValue(split(value, ',')); for (const auto &v : splitValue) { auto auth_code = split(v, ':'); if (auth_code.size() != 2) { std::cerr << "Unrecognized value for option --grid-check: " << value << std::endl; usage(); } pivots.emplace_back( std::make_pair(auth_code[0], auth_code[1])); } } } else if (arg == "--main-db-path" && i + 1 < argc) { i++; mainDBPath = argv[i]; } else if (arg == "--aux-db-path" && i + 1 < argc) { i++; auxDBPath.push_back(argv[i]); } else if (arg == "--guess-dialect") { guessDialect = true; } else if (arg == "--authority" && i + 1 < argc) { i++; authority = argv[i]; outputOpt.allowedAuthorities = split(authority, ','); } else if (arg == "--identify") { identify = true; } else if (arg == "--show-superseded") { showSuperseded = true; } else if (arg == "--lax") { outputOpt.strict = false; } else if (arg == "--allow-ellipsoidal-height-as-vertical-crs") { outputOpt.allowEllipsoidalHeightAsVerticalCRS = true; } else if (arg == "--hide-ballpark") { outputOpt.ballparkAllowed = false; } else if (ci_equal(arg, "--3d")) { promoteTo3D = true; } else if (ci_equal(arg, "--normalize-axis-order")) { // Undocumented for now normalizeAxisOrder = true; } else if (arg == "--output-id" && i + 1 < argc) { i++; const auto tokens = split(argv[i], ':'); if (tokens.size() != 2) { std::cerr << "Invalid value for option --output-id" << std::endl; usage(); } outputOpt.outputAuthName = tokens[0]; outputOpt.outputCode = tokens[1]; } else if (arg == "--dump-db-structure") { dumpDbStructure = true; } else if (arg == "--list-crs") { listCRSSpecified = true; if (i + 1 < argc && argv[i + 1][0] != '-') { i++; listCRSFilter = argv[i]; } } else if (ci_equal(arg, "--searchpaths")) { #ifdef _WIN32 constexpr char delim = ';'; #else constexpr char delim = ':'; #endif const auto paths = split(proj_info().searchpath, delim); for (const auto &path : paths) { std::cout << path << std::endl; } std::exit(0); } else if (ci_equal(arg, "--remote-data")) { #ifdef CURL_ENABLED if (proj_context_is_network_enabled(nullptr)) { std::cout << "Status: enabled" << std::endl; std::cout << "URL: " << proj_context_get_url_endpoint(nullptr) << std::endl; } else { std::cout << "Status: disabled" << std::endl; std::cout << "Reason: not enabled in proj.ini or " "PROJ_NETWORK=ON not specified" << std::endl; } #else std::cout << "Status: disabled" << std::endl; std::cout << "Reason: build without Curl support" << std::endl; #endif std::exit(0); } else if (arg == "-?" || arg == "--help") { usage(); } else if (arg[0] == '-') { std::cerr << "Unrecognized option: " << arg << std::endl; usage(); } else { if (!user_string_specified) { user_string_specified = true; user_string = arg; } else { std::cerr << "Too many parameters: " << arg << std::endl; usage(); } } } if (!bboxStr.empty() && !area.empty()) { std::cerr << "ERROR: --bbox and --area are exclusive" << std::endl; std::exit(1); } if (dumpDbStructure && user_string_specified && !outputSwitchSpecified) { // Implicit settings in --output-db-structure mode + object outputSwitchSpecified = true; outputOpt.SQL = true; outputOpt.quiet = true; } if (outputOpt.SQL && outputOpt.outputAuthName.empty()) { if (outputAll) { outputOpt.SQL = false; std::cerr << "WARNING: SQL output disable since " "--output-id AUTH:CODE has not been specified." << std::endl; } else { std::cerr << "ERROR: --output-id AUTH:CODE must be specified when " "SQL output is enabled." << std::endl; std::exit(1); } } DatabaseContextPtr dbContext; try { dbContext = DatabaseContext::create(mainDBPath, auxDBPath).as_nullable(); } catch (const std::exception &e) { if (!mainDBPath.empty() || !auxDBPath.empty() || !area.empty() || dumpDbStructure || listCRSSpecified) { std::cerr << "ERROR: Cannot create database connection: " << e.what() << std::endl; std::exit(1); } std::cerr << "WARNING: Cannot create database connection: " << e.what() << std::endl; } if (dumpDbStructure) { assert(dbContext); try { const auto structure = dbContext->getDatabaseStructure(); for (const auto &sql : structure) { std::cout << sql << std::endl; } } catch (const std::exception &e) { std::cerr << "ERROR: getDatabaseStructure() failed: " << e.what() << std::endl; std::exit(1); } } if (listCRSSpecified) { assert(dbContext); bool allow_deprecated = false; std::set<AuthorityFactory::ObjectType> types; auto tokens = split(listCRSFilter, ','); if (listCRSFilter.empty()) { tokens.clear(); } for (const auto &token : tokens) { if (ci_equal(token, "allow_deprecated")) { allow_deprecated = true; } else if (ci_equal(token, "geodetic")) { types.insert(AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS); types.insert(AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS); types.insert(AuthorityFactory::ObjectType::GEOCENTRIC_CRS); } else if (ci_equal(token, "geocentric")) { types.insert(AuthorityFactory::ObjectType::GEOCENTRIC_CRS); } else if (ci_equal(token, "geographic")) { types.insert(AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS); types.insert(AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS); } else if (ci_equal(token, "geographic_2d")) { types.insert(AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS); } else if (ci_equal(token, "geographic_3d")) { types.insert(AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS); } else if (ci_equal(token, "vertical")) { types.insert(AuthorityFactory::ObjectType::VERTICAL_CRS); } else if (ci_equal(token, "projected")) { types.insert(AuthorityFactory::ObjectType::PROJECTED_CRS); } else if (ci_equal(token, "compound")) { types.insert(AuthorityFactory::ObjectType::COMPOUND_CRS); } else { std::cerr << "Unrecognized value for option --list-crs: " << token << std::endl; usage(); } } const std::string areaLower = tolower(area); // If the area name has more than a single match, we // will do filtering on info.areaName auto bboxFilter = makeBboxFilter(dbContext, bboxStr, area, false); auto allowedAuthorities(outputOpt.allowedAuthorities); if (allowedAuthorities.empty()) { allowedAuthorities.emplace_back(std::string()); } for (const auto &auth_name : allowedAuthorities) { try { auto actualAuthNames = dbContext->getVersionedAuthoritiesFromName(auth_name); if (actualAuthNames.empty()) actualAuthNames.push_back(auth_name); for (const auto &actualAuthName : actualAuthNames) { auto factory = AuthorityFactory::create( NN_NO_CHECK(dbContext), actualAuthName); const auto list = factory->getCRSInfoList(); for (const auto &info : list) { if (!allow_deprecated && info.deprecated) { continue; } if (!types.empty() && types.find(info.type) == types.end()) { continue; } if (bboxFilter) { if (!info.bbox_valid) { continue; } auto crsExtent = Extent::createFromBBOX( info.west_lon_degree, info.south_lat_degree, info.east_lon_degree, info.north_lat_degree); if (spatialCriterion == CoordinateOperationContext::SpatialCriterion:: STRICT_CONTAINMENT) { if (!bboxFilter->contains(crsExtent)) { continue; } } else { if (!bboxFilter->intersects(crsExtent)) { continue; } } } else if (!area.empty() && tolower(info.areaName).find(areaLower) == std::string::npos) { continue; } std::cout << info.authName << ":" << info.code << " \"" << info.name << "\"" << (info.deprecated ? " [deprecated]" : "") << std::endl; } } } catch (const std::exception &e) { std::cerr << "ERROR: list-crs failed with: " << e.what() << std::endl; std::exit(1); } } } if (!sourceCRSStr.empty() && targetCRSStr.empty()) { std::cerr << "Source CRS specified, but missing target CRS" << std::endl; usage(); } else if (sourceCRSStr.empty() && !targetCRSStr.empty()) { std::cerr << "Target CRS specified, but missing source CRS" << std::endl; usage(); } else if (!sourceCRSStr.empty() && !targetCRSStr.empty()) { if (user_string_specified) { std::cerr << "Unused extra value" << std::endl; usage(); } } else if (!user_string_specified) { if (dumpDbStructure || listCRSSpecified) { std::exit(0); } std::cerr << "Missing user string" << std::endl; usage(); } if (!outputSwitchSpecified) { outputOpt.PROJ5 = true; outputOpt.WKT2_2019 = true; } if (outputOpt.quiet && (outputOpt.PROJ5 + outputOpt.WKT2_2019 + outputOpt.WKT2_2019_SIMPLIFIED + outputOpt.WKT2_2015 + outputOpt.WKT2_2015_SIMPLIFIED + outputOpt.WKT1_GDAL + outputOpt.WKT1_ESRI + outputOpt.PROJJSON + outputOpt.SQL) != 1) { std::cerr << "-q can only be used with a single output format" << std::endl; usage(); } if (!user_string.empty()) { try { auto obj(buildObject( dbContext, user_string, std::string(), objectKind, "input string", buildBoundCRSToWGS84, allowUseIntermediateCRS, promoteTo3D, normalizeAxisOrder, outputOpt.quiet)); if (guessDialect) { auto dialect = WKTParser().guessDialect(user_string); std::cout << "Guessed WKT dialect: "; if (dialect == WKTParser::WKTGuessedDialect::WKT2_2019) { std::cout << "WKT2_2019"; } else if (dialect == WKTParser::WKTGuessedDialect::WKT2_2015) { std::cout << "WKT2_2015"; } else if (dialect == WKTParser::WKTGuessedDialect::WKT1_GDAL) { std::cout << "WKT1_GDAL"; } else if (dialect == WKTParser::WKTGuessedDialect::WKT1_ESRI) { std::cout << "WKT1_ESRI"; } else { std::cout << "Not WKT / unknown"; } std::cout << std::endl; } outputObject(dbContext, obj, allowUseIntermediateCRS, outputOpt); if (identify) { auto crs = dynamic_cast<CRS *>(obj.get()); if (crs) { try { auto res = crs->identify( dbContext ? AuthorityFactory::create( NN_NO_CHECK(dbContext), authority) .as_nullable() : nullptr); std::cout << std::endl; std::cout << "Identification match count: " << res.size() << std::endl; for (const auto &pair : res) { const auto &identifiedCRS = pair.first; const auto &ids = identifiedCRS->identifiers(); if (!ids.empty()) { std::cout << *ids[0]->codeSpace() << ":" << ids[0]->code() << ": " << pair.second << " %" << std::endl; continue; } auto boundCRS = dynamic_cast<BoundCRS *>(identifiedCRS.get()); if (boundCRS && !boundCRS->baseCRS()->identifiers().empty()) { const auto &idsBase = boundCRS->baseCRS()->identifiers(); std::cout << "BoundCRS of " << *idsBase[0]->codeSpace() << ":" << idsBase[0]->code() << ": " << pair.second << " %" << std::endl; continue; } auto compoundCRS = dynamic_cast<CompoundCRS *>( identifiedCRS.get()); if (compoundCRS) { const auto &components = compoundCRS->componentReferenceSystems(); if (components.size() == 2 && !components[0]->identifiers().empty() && !components[1]->identifiers().empty()) { const auto &idH = components[0]->identifiers().front(); const auto &idV = components[1]->identifiers().front(); if (*idH->codeSpace() == *idV->codeSpace()) { std::cout << *idH->codeSpace() << ":" << idH->code() << '+' << idV->code() << ": " << pair.second << " %" << std::endl; continue; } } } std::cout << "un-identified CRS: " << pair.second << " %" << std::endl; } } catch (const std::exception &e) { std::cerr << "Identification failed: " << e.what() << std::endl; } } } } catch (const std::exception &e) { std::cerr << "buildObject failed: " << e.what() << std::endl; std::exit(1); } } else { auto bboxFilter = makeBboxFilter(dbContext, bboxStr, area, true); try { outputOperations(dbContext, sourceCRSStr, sourceEpoch, targetCRSStr, targetEpoch, bboxFilter, spatialCriterion, spatialCriterionExplicitlySpecified, crsExtentUse, gridAvailabilityUse, allowUseIntermediateCRS, pivots, authority, usePROJGridAlternatives, showSuperseded, promoteTo3D, normalizeAxisOrder, minimumAccuracy, outputOpt, summary); } catch (const std::exception &e) { std::cerr << "outputOperations() failed with: " << e.what() << std::endl; std::exit(1); } } return 0; } //! @endcond
cpp
PROJ
data/projects/PROJ/src/apps/utils.h
/****************************************************************************** * * Project: PROJ * Purpose: Utilities for command line arguments * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2019, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <stdio.h> bool validate_form_string_for_numbers(const char *formatString); void limited_fprintf_for_number(FILE *f, const char *formatString, double val);
h
PROJ
data/projects/PROJ/src/projections/mbtfpq.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(mbtfpq, "McBryde-Thomas Flat-Polar Quartic") "\n\tCyl, Sph"; #define NITER 20 #define EPS 1e-7 #define ONETOL 1.000001 #define C 1.70710678118654752440 #define RC 0.58578643762690495119 #define FYC 1.87475828462269495505 #define RYC 0.53340209679417701685 #define FXC 0.31245971410378249250 #define RXC 3.20041258076506210122 static PJ_XY mbtfpq_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; const double c = C * sin(lp.phi); for (int i = NITER; i; --i) { const double th1 = (sin(.5 * lp.phi) + sin(lp.phi) - c) / (.5 * cos(.5 * lp.phi) + cos(lp.phi)); lp.phi -= th1; if (fabs(th1) < EPS) break; } xy.x = FXC * lp.lam * (1.0 + 2. * cos(lp.phi) / cos(0.5 * lp.phi)); xy.y = FYC * sin(0.5 * lp.phi); return xy; } static PJ_LP mbtfpq_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double t; lp.phi = RYC * xy.y; if (fabs(lp.phi) > 1.) { if (fabs(lp.phi) > ONETOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else if (lp.phi < 0.) { t = -1.; lp.phi = -M_PI; } else { t = 1.; lp.phi = M_PI; } } else { t = lp.phi; lp.phi = 2. * asin(lp.phi); } lp.lam = RXC * xy.x / (1. + 2. * cos(lp.phi) / cos(0.5 * lp.phi)); lp.phi = RC * (t + sin(lp.phi)); if (fabs(lp.phi) > 1.) if (fabs(lp.phi) > ONETOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else lp.phi = lp.phi < 0. ? -M_HALFPI : M_HALFPI; else lp.phi = asin(lp.phi); return lp; } PJ *PJ_PROJECTION(mbtfpq) { P->es = 0.; P->inv = mbtfpq_s_inverse; P->fwd = mbtfpq_s_forward; return P; } #undef NITER #undef EPS #undef ONETOL #undef C #undef RC #undef FYC #undef RYC #undef FXC #undef RXC
cpp
PROJ
data/projects/PROJ/src/projections/patterson.cpp
/* * Copyright (c) 2014 Bojan Savric * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The Patterson Cylindrical projection was designed by Tom Patterson, US * National Park Service, in 2014, using Flex Projector. The polynomial * equations for the projection were developed by Bojan Savric, Oregon State * University, in collaboration with Tom Patterson and Bernhard Jenny, Oregon * State University. * * Java reference algorithm implemented by Bojan Savric in Java Map Projection * Library (a Java port of PROJ.4) in the file PattersonProjection.java. * * References: * Java Map Projection Library * https://github.com/OSUCartography/JMapProjLib * * Patterson Cylindrical Projection * http://shadedrelief.com/patterson/ * * Patterson, T., Savric, B., and Jenny, B. (2015). Cartographic Perspectives * (No.78). Describes the projection design and characteristics, and * developing the equations. doi:10.14714/CP78.1270 * https://doi.org/10.14714/CP78.1270 * * Port to PROJ.4 by Micah Cochran, 26 March 2016 */ #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(patterson, "Patterson Cylindrical") "\n\tCyl"; #define K1 1.0148 #define K2 0.23185 #define K3 -0.14499 #define K4 0.02406 #define C1 K1 #define C2 (5.0 * K2) #define C3 (7.0 * K3) #define C4 (9.0 * K4) #define EPS11 1.0e-11 #define MAX_Y 1.790857183 /* Not sure at all of the appropriate number for MAX_ITER... */ #define MAX_ITER 100 static PJ_XY patterson_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double phi2; (void)P; phi2 = lp.phi * lp.phi; xy.x = lp.lam; xy.y = lp.phi * (K1 + phi2 * phi2 * (K2 + phi2 * (K3 + K4 * phi2))); return xy; } static PJ_LP patterson_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double yc; int i; (void)P; yc = xy.y; /* make sure y is inside valid range */ if (xy.y > MAX_Y) { xy.y = MAX_Y; } else if (xy.y < -MAX_Y) { xy.y = -MAX_Y; } for (i = MAX_ITER; i; --i) { /* Newton-Raphson */ const double y2 = yc * yc; const double f = (yc * (K1 + y2 * y2 * (K2 + y2 * (K3 + K4 * y2)))) - xy.y; const double fder = C1 + y2 * y2 * (C2 + y2 * (C3 + C4 * y2)); const double tol = f / fder; yc -= tol; if (fabs(tol) < EPS11) { break; } } if (i == 0) proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.phi = yc; /* longitude */ lp.lam = xy.x; return lp; } PJ *PJ_PROJECTION(patterson) { P->es = 0.; P->inv = patterson_s_inverse; P->fwd = patterson_s_forward; return P; } #undef K1 #undef K2 #undef K3 #undef K4 #undef C1 #undef C2 #undef C3 #undef C4 #undef EPS11 #undef MAX_Y #undef MAX_ITER
cpp
PROJ
data/projects/PROJ/src/projections/denoy.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(denoy, "Denoyer Semi-Elliptical") "\n\tPCyl, no inv, Sph"; #define C0 0.95 #define C1 -0.08333333333333333333 #define C3 0.00166666666666666666 #define D1 0.9 #define D5 0.03 static PJ_XY denoy_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.y = lp.phi; xy.x = lp.lam; lp.lam = fabs(lp.lam); xy.x *= cos((C0 + lp.lam * (C1 + lp.lam * lp.lam * C3)) * (lp.phi * (D1 + D5 * lp.phi * lp.phi * lp.phi * lp.phi))); return xy; } PJ *PJ_PROJECTION(denoy) { P->es = 0.0; P->fwd = denoy_s_forward; return P; } #undef C0 #undef C1 #undef C3 #undef D1 #undef D5
cpp
PROJ
data/projects/PROJ/src/projections/bertin1953.cpp
/* Created by Jacques Bertin in 1953, this projection was the go-to choice of the French cartographic school when they wished to represent phenomena on a global scale. Formula designed by Philippe Rivière, 2017. https://visionscarto.net/bertin-projection-1953 Port to PROJ by Philippe Rivière, 21 September 2018 */ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(bertin1953, "Bertin 1953") "\n\tMisc Sph no inv."; namespace { // anonymous namespace struct pj_bertin1953 { double cos_delta_phi, sin_delta_phi, cos_delta_gamma, sin_delta_gamma, deltaLambda; }; } // anonymous namespace static PJ_XY bertin1953_s_forward(PJ_LP lp, PJ *P) { PJ_XY xy = {0.0, 0.0}; struct pj_bertin1953 *Q = static_cast<struct pj_bertin1953 *>(P->opaque); double fu = 1.4, k = 12., w = 1.68, d; /* Rotate */ double cosphi, x, y, z, z0; lp.lam += PJ_TORAD(-16.5); cosphi = cos(lp.phi); x = cos(lp.lam) * cosphi; y = sin(lp.lam) * cosphi; z = sin(lp.phi); z0 = z * Q->cos_delta_phi + x * Q->sin_delta_phi; lp.lam = atan2(y * Q->cos_delta_gamma - z0 * Q->sin_delta_gamma, x * Q->cos_delta_phi - z * Q->sin_delta_phi); z0 = z0 * Q->cos_delta_gamma + y * Q->sin_delta_gamma; lp.phi = asin(z0); lp.lam = adjlon(lp.lam); /* Adjust pre-projection */ if (lp.lam + lp.phi < -fu) { d = (lp.lam - lp.phi + 1.6) * (lp.lam + lp.phi + fu) / 8.; lp.lam += d; lp.phi -= 0.8 * d * sin(lp.phi + M_PI / 2.); } /* Project with Hammer (1.68,2) */ cosphi = cos(lp.phi); d = sqrt(2. / (1. + cosphi * cos(lp.lam / 2.))); xy.x = w * d * cosphi * sin(lp.lam / 2.); xy.y = d * sin(lp.phi); /* Adjust post-projection */ d = (1. - cos(lp.lam * lp.phi)) / k; if (xy.y < 0.) { xy.x *= 1. + d; } if (xy.y > 0.) { xy.y *= 1. + d / 1.5 * xy.x * xy.x; } return xy; } PJ *PJ_PROJECTION(bertin1953) { struct pj_bertin1953 *Q = static_cast<struct pj_bertin1953 *>( calloc(1, sizeof(struct pj_bertin1953))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->lam0 = 0; P->phi0 = PJ_TORAD(-42.); Q->cos_delta_phi = cos(P->phi0); Q->sin_delta_phi = sin(P->phi0); Q->cos_delta_gamma = 1.; Q->sin_delta_gamma = 0.; P->es = 0.; P->fwd = bertin1953_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/putp2.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(putp2, "Putnins P2") "\n\tPCyl, Sph"; #define C_x 1.89490 #define C_y 1.71848 #define C_p 0.6141848493043784 #define EPS 1e-10 #define NITER 10 #define PI_DIV_3 1.0471975511965977 static PJ_XY putp2_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; int i; (void)P; const double p = C_p * sin(lp.phi); const double phi_pow_2 = lp.phi * lp.phi; lp.phi *= 0.615709 + phi_pow_2 * (0.00909953 + phi_pow_2 * 0.0046292); for (i = NITER; i; --i) { const double c = cos(lp.phi); const double s = sin(lp.phi); const double V = (lp.phi + s * (c - 1.) - p) / (1. + c * (c - 1.) - s * s); lp.phi -= V; if (fabs(V) < EPS) break; } if (!i) lp.phi = lp.phi < 0 ? -PI_DIV_3 : PI_DIV_3; xy.x = C_x * lp.lam * (cos(lp.phi) - 0.5); xy.y = C_y * sin(lp.phi); return xy; } static PJ_LP putp2_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = aasin(P->ctx, xy.y / C_y); const double c = cos(lp.phi); lp.lam = xy.x / (C_x * (c - 0.5)); lp.phi = aasin(P->ctx, (lp.phi + sin(lp.phi) * (c - 1.)) / C_p); return lp; } PJ *PJ_PROJECTION(putp2) { P->es = 0.; P->inv = putp2_s_inverse; P->fwd = putp2_s_forward; return P; } #undef C_x #undef C_y #undef C_p #undef EPS #undef NITER #undef PI_DIV_3
cpp
PROJ
data/projects/PROJ/src/projections/gstmerc.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(gstmerc, "Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)") "\n\tCyl, Sph&Ell\n\tlat_0= lon_0= k_0="; namespace { // anonymous namespace struct pj_gstmerc_data { double lamc; double phic; double c; double n1; double n2; double XS; double YS; }; } // anonymous namespace static PJ_XY gstmerc_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_gstmerc_data *Q = static_cast<struct pj_gstmerc_data *>(P->opaque); double L, Ls, sinLs1, Ls1; L = Q->n1 * lp.lam; Ls = Q->c + Q->n1 * log(pj_tsfn(-lp.phi, -sin(lp.phi), P->e)); sinLs1 = sin(L) / cosh(Ls); Ls1 = log(pj_tsfn(-asin(sinLs1), -sinLs1, 0.0)); xy.x = (Q->XS + Q->n2 * Ls1) * P->ra; xy.y = (Q->YS + Q->n2 * atan(sinh(Ls) / cos(L))) * P->ra; return xy; } static PJ_LP gstmerc_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_gstmerc_data *Q = static_cast<struct pj_gstmerc_data *>(P->opaque); double L, LC, sinC; L = atan(sinh((xy.x * P->a - Q->XS) / Q->n2) / cos((xy.y * P->a - Q->YS) / Q->n2)); sinC = sin((xy.y * P->a - Q->YS) / Q->n2) / cosh((xy.x * P->a - Q->XS) / Q->n2); LC = log(pj_tsfn(-asin(sinC), -sinC, 0.0)); lp.lam = L / Q->n1; lp.phi = -pj_phi2(P->ctx, exp((LC - Q->c) / Q->n1), P->e); return lp; } PJ *PJ_PROJECTION(gstmerc) { struct pj_gstmerc_data *Q = static_cast<struct pj_gstmerc_data *>( calloc(1, sizeof(struct pj_gstmerc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->lamc = P->lam0; Q->n1 = sqrt(1 + P->es * pow(cos(P->phi0), 4.0) / (1 - P->es)); Q->phic = asin(sin(P->phi0) / Q->n1); Q->c = log(pj_tsfn(-Q->phic, -sin(P->phi0) / Q->n1, 0.0)) - Q->n1 * log(pj_tsfn(-P->phi0, -sin(P->phi0), P->e)); Q->n2 = P->k0 * P->a * sqrt(1 - P->es) / (1 - P->es * sin(P->phi0) * sin(P->phi0)); Q->XS = 0; Q->YS = -Q->n2 * Q->phic; P->inv = gstmerc_s_inverse; P->fwd = gstmerc_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/rouss.cpp
/* ** libproj -- library of cartographic projections ** ** Copyright (c) 2003, 2006 Gerald I. Evenden */ /* ** Permission is hereby granted, free of charge, to any person obtaining ** a copy of this software and associated documentation files (the ** "Software"), to deal in the Software without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Software, and to ** permit persons to whom the Software is furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_rouss_data { double s0; double A1, A2, A3, A4, A5, A6; double B1, B2, B3, B4, B5, B6, B7, B8; double C1, C2, C3, C4, C5, C6, C7, C8; double D1, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11; void *en; }; } // anonymous namespace PROJ_HEAD(rouss, "Roussilhe Stereographic") "\n\tAzi, Ell"; static PJ_XY rouss_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_rouss_data *Q = static_cast<struct pj_rouss_data *>(P->opaque); double s, al, cp, sp, al2, s2; cp = cos(lp.phi); sp = sin(lp.phi); s = proj_mdist(lp.phi, sp, cp, Q->en) - Q->s0; s2 = s * s; al = lp.lam * cp / sqrt(1. - P->es * sp * sp); al2 = al * al; xy.x = P->k0 * al * (1. + s2 * (Q->A1 + s2 * Q->A4) - al2 * (Q->A2 + s * Q->A3 + s2 * Q->A5 + al2 * Q->A6)); xy.y = P->k0 * (al2 * (Q->B1 + al2 * Q->B4) + s * (1. + al2 * (Q->B3 - al2 * Q->B6) + s2 * (Q->B2 + s2 * Q->B8) + s * al2 * (Q->B5 + s * Q->B7))); return xy; } static PJ_LP rouss_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_rouss_data *Q = static_cast<struct pj_rouss_data *>(P->opaque); double s, al, x = xy.x / P->k0, y = xy.y / P->k0, x2, y2; x2 = x * x; y2 = y * y; al = x * (1. - Q->C1 * y2 + x2 * (Q->C2 + Q->C3 * y - Q->C4 * x2 + Q->C5 * y2 - Q->C7 * x2 * y) + y2 * (Q->C6 * y2 - Q->C8 * x2 * y)); s = Q->s0 + y * (1. + y2 * (-Q->D2 + Q->D8 * y2)) + x2 * (-Q->D1 + y * (-Q->D3 + y * (-Q->D5 + y * (-Q->D7 + y * Q->D11))) + x2 * (Q->D4 + y * (Q->D6 + y * Q->D10) - x2 * Q->D9)); lp.phi = proj_inv_mdist(P->ctx, s, Q->en); s = sin(lp.phi); lp.lam = al * sqrt(1. - P->es * s * s) / cos(lp.phi); return lp; } static PJ *pj_rouss_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); if (static_cast<struct pj_rouss_data *>(P->opaque)->en) free(static_cast<struct pj_rouss_data *>(P->opaque)->en); return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } PJ *PJ_PROJECTION(rouss) { double N0, es2, t, t2, R_R0_2, R_R0_4; struct pj_rouss_data *Q = static_cast<struct pj_rouss_data *>( calloc(1, sizeof(struct pj_rouss_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (!((Q->en = proj_mdist_ini(P->es)))) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); es2 = sin(P->phi0); Q->s0 = proj_mdist(P->phi0, es2, cos(P->phi0), Q->en); t = 1. - (es2 = P->es * es2 * es2); N0 = 1. / sqrt(t); R_R0_2 = t * t / P->one_es; R_R0_4 = R_R0_2 * R_R0_2; t = tan(P->phi0); t2 = t * t; Q->C1 = Q->A1 = R_R0_2 / 4.; Q->C2 = Q->A2 = R_R0_2 * (2 * t2 - 1. - 2. * es2) / 12.; Q->A3 = R_R0_2 * t * (1. + 4. * t2) / (12. * N0); Q->A4 = R_R0_4 / 24.; Q->A5 = R_R0_4 * (-1. + t2 * (11. + 12. * t2)) / 24.; Q->A6 = R_R0_4 * (-2. + t2 * (11. - 2. * t2)) / 240.; Q->B1 = t / (2. * N0); Q->B2 = R_R0_2 / 12.; Q->B3 = R_R0_2 * (1. + 2. * t2 - 2. * es2) / 4.; Q->B4 = R_R0_2 * t * (2. - t2) / (24. * N0); Q->B5 = R_R0_2 * t * (5. + 4. * t2) / (8. * N0); Q->B6 = R_R0_4 * (-2. + t2 * (-5. + 6. * t2)) / 48.; Q->B7 = R_R0_4 * (5. + t2 * (19. + 12. * t2)) / 24.; Q->B8 = R_R0_4 / 120.; Q->C3 = R_R0_2 * t * (1. + t2) / (3. * N0); Q->C4 = R_R0_4 * (-3. + t2 * (34. + 22. * t2)) / 240.; Q->C5 = R_R0_4 * (4. + t2 * (13. + 12. * t2)) / 24.; Q->C6 = R_R0_4 / 16.; Q->C7 = R_R0_4 * t * (11. + t2 * (33. + t2 * 16.)) / (48. * N0); Q->C8 = R_R0_4 * t * (1. + t2 * 4.) / (36. * N0); Q->D1 = t / (2. * N0); Q->D2 = R_R0_2 / 12.; Q->D3 = R_R0_2 * (2 * t2 + 1. - 2. * es2) / 4.; Q->D4 = R_R0_2 * t * (1. + t2) / (8. * N0); Q->D5 = R_R0_2 * t * (1. + t2 * 2.) / (4. * N0); Q->D6 = R_R0_4 * (1. + t2 * (6. + t2 * 6.)) / 16.; Q->D7 = R_R0_4 * t2 * (3. + t2 * 4.) / 8.; Q->D8 = R_R0_4 / 80.; Q->D9 = R_R0_4 * t * (-21. + t2 * (178. - t2 * 26.)) / 720.; Q->D10 = R_R0_4 * t * (29. + t2 * (86. + t2 * 48.)) / (96. * N0); Q->D11 = R_R0_4 * t * (37. + t2 * 44.) / (96. * N0); P->fwd = rouss_e_forward; P->inv = rouss_e_inverse; P->destructor = pj_rouss_destructor; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/gins8.cpp
#include "proj.h" #include "proj_internal.h" PROJ_HEAD(gins8, "Ginsburg VIII (TsNIIGAiK)") "\n\tPCyl, Sph, no inv"; #define Cl 0.000952426 #define Cp 0.162388 #define C12 0.08333333333333333 static PJ_XY gins8_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double t = lp.phi * lp.phi; (void)P; xy.y = lp.phi * (1. + t * C12); xy.x = lp.lam * (1. - Cp * t); t = lp.lam * lp.lam; xy.x *= (0.87 - Cl * t * t); return xy; } PJ *PJ_PROJECTION(gins8) { P->es = 0.0; P->inv = nullptr; P->fwd = gins8_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/igh_o.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(igh_o, "Interrupted Goode Homolosine Oceanic View") "\n\tPCyl, Sph"; /* This projection is a variant of the Interrupted Goode Homolosine projection that emphasizes ocean areas. The projection is a compilation of 12 separate sub-projections. Sinusoidal projections are found near the equator and Mollweide projections are found at higher latitudes. The transition between the two occurs at 40 degrees latitude and is represented by `igh_o_phi_boundary`. Each sub-projection is assigned an integer label numbered 1 through 12. Most of this code contains logic to assign the labels based on latitude (phi) and longitude (lam) regions. Original Reference: J. Paul Goode (1925) THE HOMOLOSINE PROJECTION: A NEW DEVICE FOR PORTRAYING THE EARTH'S SURFACE ENTIRE, Annals of the Association of American Geographers, 15:3, 119-125, DOI: 10.1080/00045602509356949 */ C_NAMESPACE PJ *pj_sinu(PJ *), *pj_moll(PJ *); /* Transition from sinusoidal to Mollweide projection Latitude (phi): 40deg 44' 11.8" */ constexpr double igh_o_phi_boundary = (40 + 44 / 60. + 11.8 / 3600.) * DEG_TO_RAD; namespace pj_igh_o_ns { struct pj_igh_o_data { struct PJconsts *pj[12]; double dy0; }; constexpr double d10 = 10 * DEG_TO_RAD; constexpr double d20 = 20 * DEG_TO_RAD; constexpr double d40 = 40 * DEG_TO_RAD; constexpr double d50 = 50 * DEG_TO_RAD; constexpr double d60 = 60 * DEG_TO_RAD; constexpr double d90 = 90 * DEG_TO_RAD; constexpr double d100 = 100 * DEG_TO_RAD; constexpr double d110 = 110 * DEG_TO_RAD; constexpr double d140 = 140 * DEG_TO_RAD; constexpr double d150 = 150 * DEG_TO_RAD; constexpr double d160 = 160 * DEG_TO_RAD; constexpr double d130 = 130 * DEG_TO_RAD; constexpr double d180 = 180 * DEG_TO_RAD; constexpr double EPSLN = 1.e-10; /* allow a little 'slack' on zone edge positions */ } // namespace pj_igh_o_ns /* Assign an integer index representing each of the 12 sub-projection zones based on latitude (phi) and longitude (lam) ranges. */ static PJ_XY igh_o_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ using namespace pj_igh_o_ns; PJ_XY xy; struct pj_igh_o_data *Q = static_cast<struct pj_igh_o_data *>(P->opaque); int z; if (lp.phi >= igh_o_phi_boundary) { if (lp.lam <= -d90) z = 1; else if (lp.lam >= d60) z = 3; else z = 2; } else if (lp.phi >= 0) { if (lp.lam <= -d90) z = 4; else if (lp.lam >= d60) z = 6; else z = 5; } else if (lp.phi >= -igh_o_phi_boundary) { if (lp.lam <= -d60) z = 7; else if (lp.lam >= d90) z = 9; else z = 8; } else { if (lp.lam <= -d60) z = 10; else if (lp.lam >= d90) z = 12; else z = 11; } lp.lam -= Q->pj[z - 1]->lam0; xy = Q->pj[z - 1]->fwd(lp, Q->pj[z - 1]); xy.x += Q->pj[z - 1]->x0; xy.y += Q->pj[z - 1]->y0; return xy; } static PJ_LP igh_o_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ using namespace pj_igh_o_ns; PJ_LP lp = {0.0, 0.0}; struct pj_igh_o_data *Q = static_cast<struct pj_igh_o_data *>(P->opaque); const double y90 = Q->dy0 + sqrt(2.0); /* lt=90 corresponds to y=y0+sqrt(2) */ int z = 0; if (xy.y > y90 + EPSLN || xy.y < -y90 + EPSLN) /* 0 */ z = 0; else if (xy.y >= igh_o_phi_boundary) if (xy.x <= -d90) z = 1; else if (xy.x >= d60) z = 3; else z = 2; else if (xy.y >= 0) if (xy.x <= -d90) z = 4; else if (xy.x >= d60) z = 6; else z = 5; else if (xy.y >= -igh_o_phi_boundary) { if (xy.x <= -d60) z = 7; else if (xy.x >= d90) z = 9; else z = 8; } else { if (xy.x <= -d60) z = 10; else if (xy.x >= d90) z = 12; else z = 11; } if (z) { bool ok = false; xy.x -= Q->pj[z - 1]->x0; xy.y -= Q->pj[z - 1]->y0; lp = Q->pj[z - 1]->inv(xy, Q->pj[z - 1]); lp.lam += Q->pj[z - 1]->lam0; switch (z) { /* Plot projectable ranges with exetension lobes in zones 1 & 3 */ case 1: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d90 + EPSLN) || ((lp.lam >= d160 - EPSLN && lp.lam <= d180 + EPSLN) && (lp.phi >= d50 - EPSLN && lp.phi <= d90 + EPSLN)); break; case 2: ok = (lp.lam >= -d90 - EPSLN && lp.lam <= d60 + EPSLN); break; case 3: ok = (lp.lam >= d60 - EPSLN && lp.lam <= d180 + EPSLN) || ((lp.lam >= -d180 - EPSLN && lp.lam <= -d160 + EPSLN) && (lp.phi >= d50 - EPSLN && lp.phi <= d90 + EPSLN)); break; case 4: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d90 + EPSLN); break; case 5: ok = (lp.lam >= -d90 - EPSLN && lp.lam <= d60 + EPSLN); break; case 6: ok = (lp.lam >= d60 - EPSLN && lp.lam <= d180 + EPSLN); break; case 7: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d60 + EPSLN); break; case 8: ok = (lp.lam >= -d60 - EPSLN && lp.lam <= d90 + EPSLN); break; case 9: ok = (lp.lam >= d90 - EPSLN && lp.lam <= d180 + EPSLN); break; case 10: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d60 + EPSLN); break; case 11: ok = (lp.lam >= -d60 - EPSLN && lp.lam <= d90 + EPSLN) || ((lp.lam >= d90 - EPSLN && lp.lam <= d100 + EPSLN) && (lp.phi >= -d90 - EPSLN && lp.phi <= -d40 + EPSLN)); break; case 12: ok = (lp.lam >= d90 - EPSLN && lp.lam <= d180 + EPSLN); break; } z = (!ok ? 0 : z); /* projectable? */ } if (!z) lp.lam = HUGE_VAL; if (!z) lp.phi = HUGE_VAL; return lp; } static PJ *pj_igh_o_destructor(PJ *P, int errlev) { using namespace pj_igh_o_ns; int i; if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); struct pj_igh_o_data *Q = static_cast<struct pj_igh_o_data *>(P->opaque); for (i = 0; i < 12; ++i) { if (Q->pj[i]) Q->pj[i]->destructor(Q->pj[i], errlev); } return pj_default_destructor(P, errlev); } /* Zones: -180 -90 60 180 +---------+----------------+-------------+ Zones 1,2,3,10,11 & 12: |1 |2 |3 | Mollweide projection | | | | +---------+----------------+-------------+ Zones 4,5,6,7,8 & 9: |4 |5 |6 | Sinusoidal projection | | | | 0 +---------+--+-------------+--+----------+ |7 |8 |9 | | | | | +------------+----------------+----------+ |10 |11 |12 | | | | | +------------+----------------+----------+ -180 -60 90 180 */ static bool pj_igh_o_setup_zone(PJ *P, struct pj_igh_o_ns::pj_igh_o_data *Q, int n, PJ *(*proj_ptr)(PJ *), double x_0, double y_0, double lon_0) { if (!(Q->pj[n - 1] = proj_ptr(nullptr))) return false; if (!(Q->pj[n - 1] = proj_ptr(Q->pj[n - 1]))) return false; Q->pj[n - 1]->ctx = P->ctx; Q->pj[n - 1]->x0 = x_0; Q->pj[n - 1]->y0 = y_0; Q->pj[n - 1]->lam0 = lon_0; return true; } PJ *PJ_PROJECTION(igh_o) { using namespace pj_igh_o_ns; PJ_XY xy1, xy4; PJ_LP lp = {0, igh_o_phi_boundary}; struct pj_igh_o_data *Q = static_cast<struct pj_igh_o_data *>( calloc(1, sizeof(struct pj_igh_o_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* sinusoidal zones */ if (!pj_igh_o_setup_zone(P, Q, 4, pj_sinu, -d140, 0, -d140) || !pj_igh_o_setup_zone(P, Q, 5, pj_sinu, -d10, 0, -d10) || !pj_igh_o_setup_zone(P, Q, 6, pj_sinu, d130, 0, d130) || !pj_igh_o_setup_zone(P, Q, 7, pj_sinu, -d110, 0, -d110) || !pj_igh_o_setup_zone(P, Q, 8, pj_sinu, d20, 0, d20) || !pj_igh_o_setup_zone(P, Q, 9, pj_sinu, d150, 0, d150)) { return pj_igh_o_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } /* mollweide zones */ if (!pj_igh_o_setup_zone(P, Q, 1, pj_moll, -d140, 0, -d140)) { return pj_igh_o_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } /* y0 ? */ xy1 = Q->pj[0]->fwd(lp, Q->pj[0]); /* zone 1 */ xy4 = Q->pj[3]->fwd(lp, Q->pj[3]); /* zone 4 */ /* y0 + xy1.y = xy4.y for lt = 40d44'11.8" */ Q->dy0 = xy4.y - xy1.y; Q->pj[0]->y0 = Q->dy0; /* mollweide zones (cont'd) */ if (!pj_igh_o_setup_zone(P, Q, 2, pj_moll, -d10, Q->dy0, -d10) || !pj_igh_o_setup_zone(P, Q, 3, pj_moll, d130, Q->dy0, d130) || !pj_igh_o_setup_zone(P, Q, 10, pj_moll, -d110, -Q->dy0, -d110) || !pj_igh_o_setup_zone(P, Q, 11, pj_moll, d20, -Q->dy0, d20) || !pj_igh_o_setup_zone(P, Q, 12, pj_moll, d150, -Q->dy0, d150)) { return pj_igh_o_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } P->inv = igh_o_s_inverse; P->fwd = igh_o_s_forward; P->destructor = pj_igh_o_destructor; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/crast.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(crast, "Craster Parabolic (Putnins P4)") "\n\tPCyl, Sph"; #define XM 0.97720502380583984317 #define RXM 1.02332670794648848847 #define YM 3.06998012383946546542 #define RYM 0.32573500793527994772 #define THIRD 0.333333333333333333 static PJ_XY crast_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; lp.phi *= THIRD; xy.x = XM * lp.lam * (2. * cos(lp.phi + lp.phi) - 1.); xy.y = YM * sin(lp.phi); return xy; } static PJ_LP crast_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; lp.phi = 3. * asin(xy.y * RYM); lp.lam = xy.x * RXM / (2. * cos((lp.phi + lp.phi) * THIRD) - 1); return lp; } PJ *PJ_PROJECTION(crast) { P->es = 0.0; P->inv = crast_s_inverse; P->fwd = crast_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/gall.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(gall, "Gall (Gall Stereographic)") "\n\tCyl, Sph"; #define YF 1.70710678118654752440 #define XF 0.70710678118654752440 #define RYF 0.58578643762690495119 #define RXF 1.41421356237309504880 static PJ_XY gall_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = XF * lp.lam; xy.y = YF * tan(.5 * lp.phi); return xy; } static PJ_LP gall_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; lp.lam = RXF * xy.x; lp.phi = 2. * atan(xy.y * RYF); return lp; } PJ *PJ_PROJECTION(gall) { P->es = 0.0; P->inv = gall_s_inverse; P->fwd = gall_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/nicol.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(nicol, "Nicolosi Globular") "\n\tMisc Sph, no inv"; #define EPS 1e-10 static PJ_XY nicol_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; if (fabs(lp.lam) < EPS) { xy.x = 0; xy.y = lp.phi; } else if (fabs(lp.phi) < EPS) { xy.x = lp.lam; xy.y = 0.; } else if (fabs(fabs(lp.lam) - M_HALFPI) < EPS) { xy.x = lp.lam * cos(lp.phi); xy.y = M_HALFPI * sin(lp.phi); } else if (fabs(fabs(lp.phi) - M_HALFPI) < EPS) { xy.x = 0; xy.y = lp.phi; } else { double tb, c, d, m, n, r2, sp; tb = M_HALFPI / lp.lam - lp.lam / M_HALFPI; c = lp.phi / M_HALFPI; d = (1 - c * c) / ((sp = sin(lp.phi)) - c); r2 = tb / d; r2 *= r2; m = (tb * sp / d - 0.5 * tb) / (1. + r2); n = (sp / r2 + 0.5 * d) / (1. + 1. / r2); xy.x = cos(lp.phi); xy.x = sqrt(m * m + xy.x * xy.x / (1. + r2)); xy.x = M_HALFPI * (m + (lp.lam < 0. ? -xy.x : xy.x)); xy.y = sqrt(n * n - (sp * sp / r2 + d * sp - 1.) / (1. + 1. / r2)); xy.y = M_HALFPI * (n + (lp.phi < 0. ? xy.y : -xy.y)); } return (xy); } PJ *PJ_PROJECTION(nicol) { P->es = 0.; P->fwd = nicol_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/eck5.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(eck5, "Eckert V") "\n\tPCyl, Sph"; #define XF 0.44101277172455148219 #define RXF 2.26750802723822639137 #define YF 0.88202554344910296438 #define RYF 1.13375401361911319568 static PJ_XY eck5_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = XF * (1. + cos(lp.phi)) * lp.lam; xy.y = YF * lp.phi; return xy; } static PJ_LP eck5_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; lp.phi = RYF * xy.y; lp.lam = RXF * xy.x / (1. + cos(lp.phi)); return lp; } PJ *PJ_PROJECTION(eck5) { P->es = 0.0; P->inv = eck5_s_inverse; P->fwd = eck5_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/qsc.cpp
/* * This implements the Quadrilateralized Spherical Cube (QSC) projection. * * Copyright (c) 2011, 2012 Martin Lambers <[email protected]> * * The QSC projection was introduced in: * [OL76] * E.M. O'Neill and R.E. Laubscher, "Extended Studies of a Quadrilateralized * Spherical Cube Earth Data Base", Naval Environmental Prediction Research * Facility Tech. Report NEPRF 3-76 (CSC), May 1976. * * The preceding shift from an ellipsoid to a sphere, which allows to apply * this projection to ellipsoids as used in the Ellipsoidal Cube Map model, * is described in * [LK12] * M. Lambers and A. Kolb, "Ellipsoidal Cube Maps for Accurate Rendering of * Planetary-Scale Terrain Data", Proc. Pacific Graphics (Short Papers), Sep. * 2012 * * You have to choose one of the following projection centers, * corresponding to the centers of the six cube faces: * phi0 = 0.0, lam0 = 0.0 ("front" face) * phi0 = 0.0, lam0 = 90.0 ("right" face) * phi0 = 0.0, lam0 = 180.0 ("back" face) * phi0 = 0.0, lam0 = -90.0 ("left" face) * phi0 = 90.0 ("top" face) * phi0 = -90.0 ("bottom" face) * Other projection centers will not work! * * In the projection code below, each cube face is handled differently. * See the computation of the face parameter in the PROJECTION(qsc) function * and the handling of different face values (FACE_*) in the forward and * inverse projections. * * Furthermore, the projection is originally only defined for theta angles * between (-1/4 * PI) and (+1/4 * PI) on the current cube face. This area * of definition is named pj_qsc_ns::AREA_0 in the projection code below. The * other three areas of a cube face are handled by rotation of * pj_qsc_ns::AREA_0. */ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" /* The six cube faces. */ namespace pj_qsc_ns { enum Face { FACE_FRONT = 0, FACE_RIGHT = 1, FACE_BACK = 2, FACE_LEFT = 3, FACE_TOP = 4, FACE_BOTTOM = 5 }; } namespace { // anonymous namespace struct pj_qsc_data { enum pj_qsc_ns::Face face; double a_squared; double b; double one_minus_f; double one_minus_f_squared; }; } // anonymous namespace PROJ_HEAD(qsc, "Quadrilateralized Spherical Cube") "\n\tAzi, Sph"; #define EPS10 1.e-10 /* The four areas on a cube face. AREA_0 is the area of definition, * the other three areas are counted counterclockwise. */ namespace pj_qsc_ns { enum Area { AREA_0 = 0, AREA_1 = 1, AREA_2 = 2, AREA_3 = 3 }; } /* Helper function for forward projection: compute the theta angle * and determine the area number. */ static double qsc_fwd_equat_face_theta(double phi, double y, double x, enum pj_qsc_ns::Area *area) { double theta; if (phi < EPS10) { *area = pj_qsc_ns::AREA_0; theta = 0.0; } else { theta = atan2(y, x); if (fabs(theta) <= M_FORTPI) { *area = pj_qsc_ns::AREA_0; } else if (theta > M_FORTPI && theta <= M_HALFPI + M_FORTPI) { *area = pj_qsc_ns::AREA_1; theta -= M_HALFPI; } else if (theta > M_HALFPI + M_FORTPI || theta <= -(M_HALFPI + M_FORTPI)) { *area = pj_qsc_ns::AREA_2; theta = (theta >= 0.0 ? theta - M_PI : theta + M_PI); } else { *area = pj_qsc_ns::AREA_3; theta += M_HALFPI; } } return theta; } /* Helper function: shift the longitude. */ static double qsc_shift_longitude_origin(double longitude, double offset) { double slon = longitude + offset; if (slon < -M_PI) { slon += M_TWOPI; } else if (slon > +M_PI) { slon -= M_TWOPI; } return slon; } static PJ_XY qsc_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_qsc_data *Q = static_cast<struct pj_qsc_data *>(P->opaque); double lat, longitude; double theta, phi; double t, mu; /* nu; */ enum pj_qsc_ns::Area area; /* Convert the geodetic latitude to a geocentric latitude. * This corresponds to the shift from the ellipsoid to the sphere * described in [LK12]. */ if (P->es != 0.0) { lat = atan(Q->one_minus_f_squared * tan(lp.phi)); } else { lat = lp.phi; } /* Convert the input lat, longitude into theta, phi as used by QSC. * This depends on the cube face and the area on it. * For the top and bottom face, we can compute theta and phi * directly from phi, lam. For the other faces, we must use * unit sphere cartesian coordinates as an intermediate step. */ longitude = lp.lam; if (Q->face == pj_qsc_ns::FACE_TOP) { phi = M_HALFPI - lat; if (longitude >= M_FORTPI && longitude <= M_HALFPI + M_FORTPI) { area = pj_qsc_ns::AREA_0; theta = longitude - M_HALFPI; } else if (longitude > M_HALFPI + M_FORTPI || longitude <= -(M_HALFPI + M_FORTPI)) { area = pj_qsc_ns::AREA_1; theta = (longitude > 0.0 ? longitude - M_PI : longitude + M_PI); } else if (longitude > -(M_HALFPI + M_FORTPI) && longitude <= -M_FORTPI) { area = pj_qsc_ns::AREA_2; theta = longitude + M_HALFPI; } else { area = pj_qsc_ns::AREA_3; theta = longitude; } } else if (Q->face == pj_qsc_ns::FACE_BOTTOM) { phi = M_HALFPI + lat; if (longitude >= M_FORTPI && longitude <= M_HALFPI + M_FORTPI) { area = pj_qsc_ns::AREA_0; theta = -longitude + M_HALFPI; } else if (longitude < M_FORTPI && longitude >= -M_FORTPI) { area = pj_qsc_ns::AREA_1; theta = -longitude; } else if (longitude < -M_FORTPI && longitude >= -(M_HALFPI + M_FORTPI)) { area = pj_qsc_ns::AREA_2; theta = -longitude - M_HALFPI; } else { area = pj_qsc_ns::AREA_3; theta = (longitude > 0.0 ? -longitude + M_PI : -longitude - M_PI); } } else { double q, r, s; double sinlat, coslat; double sinlon, coslon; if (Q->face == pj_qsc_ns::FACE_RIGHT) { longitude = qsc_shift_longitude_origin(longitude, +M_HALFPI); } else if (Q->face == pj_qsc_ns::FACE_BACK) { longitude = qsc_shift_longitude_origin(longitude, +M_PI); } else if (Q->face == pj_qsc_ns::FACE_LEFT) { longitude = qsc_shift_longitude_origin(longitude, -M_HALFPI); } sinlat = sin(lat); coslat = cos(lat); sinlon = sin(longitude); coslon = cos(longitude); q = coslat * coslon; r = coslat * sinlon; s = sinlat; if (Q->face == pj_qsc_ns::FACE_FRONT) { phi = acos(q); theta = qsc_fwd_equat_face_theta(phi, s, r, &area); } else if (Q->face == pj_qsc_ns::FACE_RIGHT) { phi = acos(r); theta = qsc_fwd_equat_face_theta(phi, s, -q, &area); } else if (Q->face == pj_qsc_ns::FACE_BACK) { phi = acos(-q); theta = qsc_fwd_equat_face_theta(phi, s, -r, &area); } else if (Q->face == pj_qsc_ns::FACE_LEFT) { phi = acos(-r); theta = qsc_fwd_equat_face_theta(phi, s, q, &area); } else { /* Impossible */ phi = theta = 0.0; area = pj_qsc_ns::AREA_0; } } /* Compute mu and nu for the area of definition. * For mu, see Eq. (3-21) in [OL76], but note the typos: * compare with Eq. (3-14). For nu, see Eq. (3-38). */ mu = atan((12.0 / M_PI) * (theta + acos(sin(theta) * cos(M_FORTPI)) - M_HALFPI)); t = sqrt((1.0 - cos(phi)) / (cos(mu) * cos(mu)) / (1.0 - cos(atan(1.0 / cos(theta))))); /* nu = atan(t); We don't really need nu, just t, see below. */ /* Apply the result to the real area. */ if (area == pj_qsc_ns::AREA_1) { mu += M_HALFPI; } else if (area == pj_qsc_ns::AREA_2) { mu += M_PI; } else if (area == pj_qsc_ns::AREA_3) { mu += M_PI_HALFPI; } /* Now compute x, y from mu and nu */ /* t = tan(nu); */ xy.x = t * cos(mu); xy.y = t * sin(mu); return xy; } static PJ_LP qsc_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_qsc_data *Q = static_cast<struct pj_qsc_data *>(P->opaque); double mu, nu, cosmu, tannu; double tantheta, theta, cosphi, phi; double t; int area; /* Convert the input x, y to the mu and nu angles as used by QSC. * This depends on the area of the cube face. */ nu = atan(sqrt(xy.x * xy.x + xy.y * xy.y)); mu = atan2(xy.y, xy.x); if (xy.x >= 0.0 && xy.x >= fabs(xy.y)) { area = pj_qsc_ns::AREA_0; } else if (xy.y >= 0.0 && xy.y >= fabs(xy.x)) { area = pj_qsc_ns::AREA_1; mu -= M_HALFPI; } else if (xy.x < 0.0 && -xy.x >= fabs(xy.y)) { area = pj_qsc_ns::AREA_2; mu = (mu < 0.0 ? mu + M_PI : mu - M_PI); } else { area = pj_qsc_ns::AREA_3; mu += M_HALFPI; } /* Compute phi and theta for the area of definition. * The inverse projection is not described in the original paper, but some * good hints can be found here (as of 2011-12-14): * http://fits.gsfc.nasa.gov/fitsbits/saf.93/saf.9302 * (search for "Message-Id: <9302181759.AA25477 at fits.cv.nrao.edu>") */ t = (M_PI / 12.0) * tan(mu); tantheta = sin(t) / (cos(t) - (1.0 / sqrt(2.0))); theta = atan(tantheta); cosmu = cos(mu); tannu = tan(nu); cosphi = 1.0 - cosmu * cosmu * tannu * tannu * (1.0 - cos(atan(1.0 / cos(theta)))); if (cosphi < -1.0) { cosphi = -1.0; } else if (cosphi > +1.0) { cosphi = +1.0; } /* Apply the result to the real area on the cube face. * For the top and bottom face, we can compute phi and lam directly. * For the other faces, we must use unit sphere cartesian coordinates * as an intermediate step. */ if (Q->face == pj_qsc_ns::FACE_TOP) { phi = acos(cosphi); lp.phi = M_HALFPI - phi; if (area == pj_qsc_ns::AREA_0) { lp.lam = theta + M_HALFPI; } else if (area == pj_qsc_ns::AREA_1) { lp.lam = (theta < 0.0 ? theta + M_PI : theta - M_PI); } else if (area == pj_qsc_ns::AREA_2) { lp.lam = theta - M_HALFPI; } else /* area == pj_qsc_ns::AREA_3 */ { lp.lam = theta; } } else if (Q->face == pj_qsc_ns::FACE_BOTTOM) { phi = acos(cosphi); lp.phi = phi - M_HALFPI; if (area == pj_qsc_ns::AREA_0) { lp.lam = -theta + M_HALFPI; } else if (area == pj_qsc_ns::AREA_1) { lp.lam = -theta; } else if (area == pj_qsc_ns::AREA_2) { lp.lam = -theta - M_HALFPI; } else /* area == pj_qsc_ns::AREA_3 */ { lp.lam = (theta < 0.0 ? -theta - M_PI : -theta + M_PI); } } else { /* Compute phi and lam via cartesian unit sphere coordinates. */ double q, r, s; q = cosphi; t = q * q; if (t >= 1.0) { s = 0.0; } else { s = sqrt(1.0 - t) * sin(theta); } t += s * s; if (t >= 1.0) { r = 0.0; } else { r = sqrt(1.0 - t); } /* Rotate q,r,s into the correct area. */ if (area == pj_qsc_ns::AREA_1) { t = r; r = -s; s = t; } else if (area == pj_qsc_ns::AREA_2) { r = -r; s = -s; } else if (area == pj_qsc_ns::AREA_3) { t = r; r = s; s = -t; } /* Rotate q,r,s into the correct cube face. */ if (Q->face == pj_qsc_ns::FACE_RIGHT) { t = q; q = -r; r = t; } else if (Q->face == pj_qsc_ns::FACE_BACK) { q = -q; r = -r; } else if (Q->face == pj_qsc_ns::FACE_LEFT) { t = q; q = r; r = -t; } /* Now compute phi and lam from the unit sphere coordinates. */ lp.phi = acos(-s) - M_HALFPI; lp.lam = atan2(r, q); if (Q->face == pj_qsc_ns::FACE_RIGHT) { lp.lam = qsc_shift_longitude_origin(lp.lam, -M_HALFPI); } else if (Q->face == pj_qsc_ns::FACE_BACK) { lp.lam = qsc_shift_longitude_origin(lp.lam, -M_PI); } else if (Q->face == pj_qsc_ns::FACE_LEFT) { lp.lam = qsc_shift_longitude_origin(lp.lam, +M_HALFPI); } } /* Apply the shift from the sphere to the ellipsoid as described * in [LK12]. */ if (P->es != 0.0) { int invert_sign; double tanphi, xa; invert_sign = (lp.phi < 0.0 ? 1 : 0); tanphi = tan(lp.phi); xa = Q->b / sqrt(tanphi * tanphi + Q->one_minus_f_squared); lp.phi = atan(sqrt(P->a * P->a - xa * xa) / (Q->one_minus_f * xa)); if (invert_sign) { lp.phi = -lp.phi; } } return lp; } PJ *PJ_PROJECTION(qsc) { struct pj_qsc_data *Q = static_cast<struct pj_qsc_data *>( calloc(1, sizeof(struct pj_qsc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->inv = qsc_e_inverse; P->fwd = qsc_e_forward; /* Determine the cube face from the center of projection. */ if (P->phi0 >= M_HALFPI - M_FORTPI / 2.0) { Q->face = pj_qsc_ns::FACE_TOP; } else if (P->phi0 <= -(M_HALFPI - M_FORTPI / 2.0)) { Q->face = pj_qsc_ns::FACE_BOTTOM; } else if (fabs(P->lam0) <= M_FORTPI) { Q->face = pj_qsc_ns::FACE_FRONT; } else if (fabs(P->lam0) <= M_HALFPI + M_FORTPI) { Q->face = (P->lam0 > 0.0 ? pj_qsc_ns::FACE_RIGHT : pj_qsc_ns::FACE_LEFT); } else { Q->face = pj_qsc_ns::FACE_BACK; } /* Fill in useful values for the ellipsoid <-> sphere shift * described in [LK12]. */ if (P->es != 0.0) { Q->a_squared = P->a * P->a; Q->b = P->a * sqrt(1.0 - P->es); Q->one_minus_f = 1.0 - (P->a - Q->b) / P->a; Q->one_minus_f_squared = Q->one_minus_f * Q->one_minus_f; } return P; } #undef EPS10
cpp
PROJ
data/projects/PROJ/src/projections/ob_tran.cpp
#include <errno.h> #include <math.h> #include <stddef.h> #include <string.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_ob_tran_data { struct PJconsts *link; double lamp; double cphip, sphip; }; } // anonymous namespace PROJ_HEAD(ob_tran, "General Oblique Transformation") "\n\tMisc Sph" "\n\to_proj= plus parameters for projection" "\n\to_lat_p= o_lon_p= (new pole) or" "\n\to_alpha= o_lon_c= o_lat_c= or" "\n\to_lon_1= o_lat_1= o_lon_2= o_lat_2="; #define TOL 1e-10 static PJ_XY o_forward(PJ_LP lp, PJ *P) { /* spheroid */ struct pj_ob_tran_data *Q = static_cast<struct pj_ob_tran_data *>(P->opaque); double coslam, sinphi, cosphi; coslam = cos(lp.lam); sinphi = sin(lp.phi); cosphi = cos(lp.phi); /* Formula (5-8b) of Snyder's "Map projections: a working manual" */ lp.lam = adjlon(aatan2(cosphi * sin(lp.lam), Q->sphip * cosphi * coslam + Q->cphip * sinphi) + Q->lamp); /* Formula (5-7) */ lp.phi = aasin(P->ctx, Q->sphip * sinphi - Q->cphip * cosphi * coslam); return Q->link->fwd(lp, Q->link); } static PJ_XY t_forward(PJ_LP lp, PJ *P) { /* spheroid */ struct pj_ob_tran_data *Q = static_cast<struct pj_ob_tran_data *>(P->opaque); double cosphi, coslam; cosphi = cos(lp.phi); coslam = cos(lp.lam); lp.lam = adjlon(aatan2(cosphi * sin(lp.lam), sin(lp.phi)) + Q->lamp); lp.phi = aasin(P->ctx, -cosphi * coslam); return Q->link->fwd(lp, Q->link); } static PJ_LP o_inverse(PJ_XY xy, PJ *P) { /* spheroid */ struct pj_ob_tran_data *Q = static_cast<struct pj_ob_tran_data *>(P->opaque); double coslam, sinphi, cosphi; PJ_LP lp = Q->link->inv(xy, Q->link); if (lp.lam != HUGE_VAL) { lp.lam -= Q->lamp; coslam = cos(lp.lam); sinphi = sin(lp.phi); cosphi = cos(lp.phi); /* Formula (5-9) */ lp.phi = aasin(P->ctx, Q->sphip * sinphi + Q->cphip * cosphi * coslam); /* Formula (5-10b) */ lp.lam = aatan2(cosphi * sin(lp.lam), Q->sphip * cosphi * coslam - Q->cphip * sinphi); } return lp; } static PJ_LP t_inverse(PJ_XY xy, PJ *P) { /* spheroid */ struct pj_ob_tran_data *Q = static_cast<struct pj_ob_tran_data *>(P->opaque); double cosphi, t; PJ_LP lp = Q->link->inv(xy, Q->link); if (lp.lam != HUGE_VAL) { cosphi = cos(lp.phi); t = lp.lam - Q->lamp; lp.lam = aatan2(cosphi * sin(t), -sin(lp.phi)); lp.phi = aasin(P->ctx, cosphi * cos(t)); } return lp; } static PJ *destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); if (static_cast<struct pj_ob_tran_data *>(P->opaque)->link) static_cast<struct pj_ob_tran_data *>(P->opaque)->link->destructor( static_cast<struct pj_ob_tran_data *>(P->opaque)->link, errlev); return pj_default_destructor(P, errlev); } /*********************************************************************** These functions are modified versions of the functions "argc_params" and "argv_params" from PJ_pipeline.c Basically, they do the somewhat backwards stunt of turning the paralist representation of the +args back into the original +argv, +argc representation accepted by pj_init_ctx(). This, however, also begs the question of whether we really need the paralist linked list representation, or if we could do with a simpler null-terminated argv style array? This would simplfy some code, and keep memory allocations more localized. ***********************************************************************/ typedef struct { int argc; char **argv; } ARGS; /* count the number of args in the linked list <params> */ static size_t paralist_params_argc(paralist *params) { size_t argc = 0; for (; params != nullptr; params = params->next) argc++; return argc; } /* turn paralist into argc/argv style argument list */ static ARGS ob_tran_target_params(paralist *params) { int i = 0; ARGS args = {0, nullptr}; size_t argc = paralist_params_argc(params); if (argc < 2) return args; /* all args except the proj=ob_tran */ args.argv = static_cast<char **>(calloc(argc - 1, sizeof(char *))); if (nullptr == args.argv) return args; /* Copy all args *except* the proj=ob_tran or inv arg to the argv array */ for (i = 0; params != nullptr; params = params->next) { if (0 == strcmp(params->param, "proj=ob_tran") || 0 == strcmp(params->param, "inv")) continue; args.argv[i++] = params->param; } args.argc = i; /* Then convert the o_proj=xxx element to proj=xxx */ for (i = 0; i < args.argc; i++) { if (0 != strncmp(args.argv[i], "o_proj=", 7)) continue; args.argv[i] += 2; if (strcmp(args.argv[i], "proj=ob_tran") == 0) { free(args.argv); args.argc = 0; args.argv = nullptr; } break; } return args; } PJ *PJ_PROJECTION(ob_tran) { double phip; ARGS args; PJ *R; /* projection to rotate */ struct pj_ob_tran_data *Q = static_cast<struct pj_ob_tran_data *>( calloc(1, sizeof(struct pj_ob_tran_data))); if (nullptr == Q) return destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = destructor; /* get name of projection to be translated */ if (pj_param(P->ctx, P->params, "so_proj").s == nullptr) { proj_log_error(P, _("Missing parameter: o_proj")); return destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } /* Create the target projection object to rotate */ args = ob_tran_target_params(P->params); /* avoid endless recursion */ if (args.argv == nullptr) { proj_log_error(P, _("Failed to find projection to be rotated")); return destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } R = pj_create_argv_internal(P->ctx, args.argc, args.argv); free(args.argv); if (nullptr == R) { proj_log_error(P, _("Projection to be rotated is unknown")); return destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } // Transfer the used flag from the R object to the P object for (auto p = P->params; p; p = p->next) { if (!p->used) { for (auto r = R->params; r; r = r->next) { if (r->used && strcmp(r->param, p->param) == 0) { p->used = 1; break; } } } } Q->link = R; if (pj_param(P->ctx, P->params, "to_alpha").i) { double lamc, phic, alpha; lamc = pj_param(P->ctx, P->params, "ro_lon_c").f; phic = pj_param(P->ctx, P->params, "ro_lat_c").f; alpha = pj_param(P->ctx, P->params, "ro_alpha").f; if (fabs(fabs(phic) - M_HALFPI) <= TOL) { proj_log_error( P, _("Invalid value for lat_c: |lat_c| should be < 90°")); return destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->lamp = lamc + aatan2(-cos(alpha), -sin(alpha) * sin(phic)); phip = aasin(P->ctx, cos(phic) * sin(alpha)); } else if (pj_param(P->ctx, P->params, "to_lat_p") .i) { /* specified new pole */ Q->lamp = pj_param(P->ctx, P->params, "ro_lon_p").f; phip = pj_param(P->ctx, P->params, "ro_lat_p").f; } else { /* specified new "equator" points */ double lam1, lam2, phi1, phi2, con; lam1 = pj_param(P->ctx, P->params, "ro_lon_1").f; phi1 = pj_param(P->ctx, P->params, "ro_lat_1").f; lam2 = pj_param(P->ctx, P->params, "ro_lon_2").f; phi2 = pj_param(P->ctx, P->params, "ro_lat_2").f; con = fabs(phi1); if (fabs(phi1) > M_HALFPI - TOL) { proj_log_error( P, _("Invalid value for lat_1: |lat_1| should be < 90°")); return destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(phi2) > M_HALFPI - TOL) { proj_log_error( P, _("Invalid value for lat_2: |lat_2| should be < 90°")); return destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(phi1 - phi2) < TOL) { proj_log_error( P, _("Invalid value for lat_1 and lat_2: lat_1 should be " "different from lat_2")); return destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (con < TOL) { proj_log_error(P, _("Invalid value for lat_1: lat_1 should be " "different from zero")); return destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->lamp = atan2(cos(phi1) * sin(phi2) * cos(lam1) - sin(phi1) * cos(phi2) * cos(lam2), sin(phi1) * cos(phi2) * sin(lam2) - cos(phi1) * sin(phi2) * sin(lam1)); phip = atan(-cos(Q->lamp - lam1) / tan(phi1)); } if (fabs(phip) > TOL) { /* oblique */ Q->cphip = cos(phip); Q->sphip = sin(phip); P->fwd = Q->link->fwd ? o_forward : nullptr; P->inv = Q->link->inv ? o_inverse : nullptr; } else { /* transverse */ P->fwd = Q->link->fwd ? t_forward : nullptr; P->inv = Q->link->inv ? t_inverse : nullptr; } /* Support some rather speculative test cases, where the rotated projection */ /* is actually latlong. We do not want scaling in that case... */ if (Q->link->right == PJ_IO_UNITS_RADIANS) P->right = PJ_IO_UNITS_WHATEVER; return P; } #undef TOL
cpp
PROJ
data/projects/PROJ/src/projections/boggs.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(boggs, "Boggs Eumorphic") "\n\tPCyl, no inv, Sph"; #define NITER 20 #define EPS 1e-7 #define FXC 2.00276 #define FXC2 1.11072 #define FYC 0.49931 static PJ_XY boggs_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double theta, th1, c; int i; (void)P; theta = lp.phi; if (fabs(fabs(lp.phi) - M_HALFPI) < EPS) xy.x = 0.; else { c = sin(theta) * M_PI; for (i = NITER; i; --i) { th1 = (theta + sin(theta) - c) / (1. + cos(theta)); theta -= th1; if (fabs(th1) < EPS) break; } theta *= 0.5; xy.x = FXC * lp.lam / (1. / cos(lp.phi) + FXC2 / cos(theta)); } xy.y = FYC * (lp.phi + M_SQRT2 * sin(theta)); return (xy); } PJ *PJ_PROJECTION(boggs) { P->es = 0.; P->fwd = boggs_s_forward; return P; } #undef NITER #undef EPS #undef FXC #undef FXC2 #undef FYC
cpp
PROJ
data/projects/PROJ/src/projections/bonne.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(bonne, "Bonne (Werner lat_1=90)") "\n\tConic Sph&Ell\n\tlat_1="; #define EPS10 1e-10 namespace { // anonymous namespace struct pj_bonne_data { double phi1; double cphi1; double am1; double m1; double *en; }; } // anonymous namespace static PJ_XY bonne_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_bonne_data *Q = static_cast<struct pj_bonne_data *>(P->opaque); double rh, E, c; E = sin(lp.phi); c = cos(lp.phi); rh = Q->am1 + Q->m1 - pj_mlfn(lp.phi, E, c, Q->en); if (fabs(rh) > EPS10) { E = c * lp.lam / (rh * sqrt(1. - P->es * E * E)); xy.x = rh * sin(E); xy.y = Q->am1 - rh * cos(E); } else { xy.x = 0.; xy.y = 0.; } return xy; } static PJ_XY bonne_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_bonne_data *Q = static_cast<struct pj_bonne_data *>(P->opaque); double E, rh; rh = Q->cphi1 + Q->phi1 - lp.phi; if (fabs(rh) > EPS10) { E = lp.lam * cos(lp.phi) / rh; xy.x = rh * sin(E); xy.y = Q->cphi1 - rh * cos(E); } else xy.x = xy.y = 0.; return xy; } static PJ_LP bonne_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_bonne_data *Q = static_cast<struct pj_bonne_data *>(P->opaque); xy.y = Q->cphi1 - xy.y; const double rh = copysign(hypot(xy.x, xy.y), Q->phi1); lp.phi = Q->cphi1 + Q->phi1 - rh; const double abs_phi = fabs(lp.phi); if (abs_phi > M_HALFPI) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } if (M_HALFPI - abs_phi <= EPS10) lp.lam = 0.; else { const double lm = rh / cos(lp.phi); if (Q->phi1 > 0) { lp.lam = lm * atan2(xy.x, xy.y); } else { lp.lam = lm * atan2(-xy.x, -xy.y); } } return lp; } static PJ_LP bonne_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_bonne_data *Q = static_cast<struct pj_bonne_data *>(P->opaque); xy.y = Q->am1 - xy.y; const double rh = copysign(hypot(xy.x, xy.y), Q->phi1); lp.phi = pj_inv_mlfn(Q->am1 + Q->m1 - rh, Q->en); const double abs_phi = fabs(lp.phi); if (abs_phi < M_HALFPI) { const double sinphi = sin(lp.phi); const double lm = rh * sqrt(1. - P->es * sinphi * sinphi) / cos(lp.phi); if (Q->phi1 > 0) { lp.lam = lm * atan2(xy.x, xy.y); } else { lp.lam = lm * atan2(-xy.x, -xy.y); } } else if (abs_phi - M_HALFPI <= EPS10) lp.lam = 0.; else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } return lp; } static PJ *pj_bonne_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_bonne_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(bonne) { double c; struct pj_bonne_data *Q = static_cast<struct pj_bonne_data *>( calloc(1, sizeof(struct pj_bonne_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_bonne_destructor; Q->phi1 = pj_param(P->ctx, P->params, "rlat_1").f; if (fabs(Q->phi1) < EPS10) { proj_log_error(P, _("Invalid value for lat_1: |lat_1| should be > 0")); return pj_bonne_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (P->es != 0.0) { Q->en = pj_enfn(P->n); if (nullptr == Q->en) return pj_bonne_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->am1 = sin(Q->phi1); c = cos(Q->phi1); Q->m1 = pj_mlfn(Q->phi1, Q->am1, c, Q->en); Q->am1 = c / (sqrt(1. - P->es * Q->am1 * Q->am1) * Q->am1); P->inv = bonne_e_inverse; P->fwd = bonne_e_forward; } else { if (fabs(Q->phi1) + EPS10 >= M_HALFPI) Q->cphi1 = 0.; else Q->cphi1 = 1. / tan(Q->phi1); P->inv = bonne_s_inverse; P->fwd = bonne_s_forward; } return P; } #undef EPS10
cpp
PROJ
data/projects/PROJ/src/projections/healpix.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the HEALPix and rHEALPix projections. * For background see *<http://code.scenzgrid.org/index.php/p/scenzgrid-py/source/tree/master/docs/rhealpix_dggs.pdf>. * Authors: Alex Raichev ([email protected]) * Michael Speth ([email protected]) * Notes: Raichev implemented these projections in Python and * Speth translated them into C here. ****************************************************************************** * Copyright (c) 2001, Thomas Flemming, [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substcounteral portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(healpix, "HEALPix") "\n\tSph&Ell\n\trot_xy="; PROJ_HEAD(rhealpix, "rHEALPix") "\n\tSph&Ell\n\tnorth_square= south_square="; /* Matrix for counterclockwise rotation by pi/2: */ #define R1 \ { \ {0, -1}, { 1, 0 } \ } /* Matrix for counterclockwise rotation by pi: */ #define R2 \ { \ {-1, 0}, { 0, -1 } \ } /* Matrix for counterclockwise rotation by 3*pi/2: */ #define R3 \ { \ {0, 1}, { -1, 0 } \ } /* Identity matrix */ #define IDENT \ { \ {1, 0}, { 0, 1 } \ } /* IDENT, R1, R2, R3, R1 inverse, R2 inverse, R3 inverse:*/ #define ROT \ { IDENT, R1, R2, R3, R3, R2, R1 } /* Fuzz to handle rounding errors: */ #define EPS 1e-15 namespace { // anonymous namespace struct pj_healpix_data { int north_square; int south_square; double rot_xy; double qp; double *apa; }; } // anonymous namespace typedef struct { int cn; /* An integer 0--3 indicating the position of the polar cap. */ double x, y; /* Coordinates of the pole point (point of most extreme latitude on the polar caps). */ enum Region { north, south, equatorial } region; } CapMap; static const double rot[7][2][2] = ROT; /** * Returns the sign of the double. * @param v the parameter whose sign is returned. * @return 1 for positive number, -1 for negative, and 0 for zero. **/ static double sign(double v) { return v > 0 ? 1 : (v < 0 ? -1 : 0); } static PJ_XY rotate(PJ_XY p, double angle) { PJ_XY result; result.x = p.x * cos(angle) - p.y * sin(angle); result.y = p.y * cos(angle) + p.x * sin(angle); return result; } /** * Return the index of the matrix in ROT. * @param index ranges from -3 to 3. */ static int get_rotate_index(int index) { switch (index) { case 0: return 0; case 1: return 1; case 2: return 2; case 3: return 3; case -1: return 4; case -2: return 5; case -3: return 6; } return 0; } /** * Return 1 if point (testx, testy) lies in the interior of the polygon * determined by the vertices in vert, and return 0 otherwise. * See http://paulbourke.net/geometry/polygonmesh/ for more details. * @param nvert the number of vertices in the polygon. * @param vert the (x, y)-coordinates of the polygon's vertices **/ static int pnpoly(int nvert, double vert[][2], double testx, double testy) { int i; int counter = 0; double xinters; PJ_XY p1, p2; /* Check for boundary cases */ for (i = 0; i < nvert; i++) { if (testx == vert[i][0] && testy == vert[i][1]) { return 1; } } p1.x = vert[0][0]; p1.y = vert[0][1]; for (i = 1; i < nvert; i++) { p2.x = vert[i % nvert][0]; p2.y = vert[i % nvert][1]; if (testy > MIN(p1.y, p2.y) && testy <= MAX(p1.y, p2.y) && testx <= MAX(p1.x, p2.x) && p1.y != p2.y) { xinters = (testy - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x; if (p1.x == p2.x || testx <= xinters) counter++; } p1 = p2; } if (counter % 2 == 0) { return 0; } else { return 1; } } /** * Return 1 if (x, y) lies in (the interior or boundary of) the image of the * HEALPix projection (in case proj=0) or in the image the rHEALPix projection * (in case proj=1), and return 0 otherwise. * @param north_square the position of the north polar square (rHEALPix only) * @param south_square the position of the south polar square (rHEALPix only) **/ static int in_image(double x, double y, int proj, int north_square, int south_square) { if (proj == 0) { double healpixVertsJit[][2] = {{-M_PI - EPS, M_FORTPI}, {-3 * M_FORTPI, M_HALFPI + EPS}, {-M_HALFPI, M_FORTPI + EPS}, {-M_FORTPI, M_HALFPI + EPS}, {0.0, M_FORTPI + EPS}, {M_FORTPI, M_HALFPI + EPS}, {M_HALFPI, M_FORTPI + EPS}, {3 * M_FORTPI, M_HALFPI + EPS}, {M_PI + EPS, M_FORTPI}, {M_PI + EPS, -M_FORTPI}, {3 * M_FORTPI, -M_HALFPI - EPS}, {M_HALFPI, -M_FORTPI - EPS}, {M_FORTPI, -M_HALFPI - EPS}, {0.0, -M_FORTPI - EPS}, {-M_FORTPI, -M_HALFPI - EPS}, {-M_HALFPI, -M_FORTPI - EPS}, {-3 * M_FORTPI, -M_HALFPI - EPS}, {-M_PI - EPS, -M_FORTPI}, {-M_PI - EPS, M_FORTPI}}; return pnpoly((int)sizeof(healpixVertsJit) / sizeof(healpixVertsJit[0]), healpixVertsJit, x, y); } else { /** * We need to assign the array this way because the input is * dynamic (north_square and south_square vars are unknown at * compile time). **/ double rhealpixVertsJit[][2] = { {-M_PI - EPS, M_FORTPI + EPS}, {-M_PI + north_square * M_HALFPI - EPS, M_FORTPI + EPS}, {-M_PI + north_square * M_HALFPI - EPS, 3 * M_FORTPI + EPS}, {-M_PI + (north_square + 1.0) * M_HALFPI + EPS, 3 * M_FORTPI + EPS}, {-M_PI + (north_square + 1.0) * M_HALFPI + EPS, M_FORTPI + EPS}, {M_PI + EPS, M_FORTPI + EPS}, {M_PI + EPS, -M_FORTPI - EPS}, {-M_PI + (south_square + 1.0) * M_HALFPI + EPS, -M_FORTPI - EPS}, {-M_PI + (south_square + 1.0) * M_HALFPI + EPS, -3 * M_FORTPI - EPS}, {-M_PI + south_square * M_HALFPI - EPS, -3 * M_FORTPI - EPS}, {-M_PI + south_square * M_HALFPI - EPS, -M_FORTPI - EPS}, {-M_PI - EPS, -M_FORTPI - EPS}}; return pnpoly((int)sizeof(rhealpixVertsJit) / sizeof(rhealpixVertsJit[0]), rhealpixVertsJit, x, y); } } /** * Return the authalic latitude of latitude alpha (if inverse=0) or * return the approximate latitude of authalic latitude alpha (if inverse=1). * P contains the relevant ellipsoid parameters. **/ static double auth_lat(PJ *P, double alpha, int inverse) { struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); if (inverse == 0) { /* Authalic latitude. */ double q = pj_qsfn(sin(alpha), P->e, 1.0 - P->es); double qp = Q->qp; double ratio = q / qp; if (fabs(ratio) > 1) { /* Rounding error. */ ratio = sign(ratio); } return asin(ratio); } else { /* Approximation to inverse authalic latitude. */ return pj_authlat(alpha, Q->apa); } } /** * Return the HEALPix projection of the longitude-latitude point lp on * the unit sphere. **/ static PJ_XY healpix_sphere(PJ_LP lp) { double lam = lp.lam; double phi = lp.phi; double phi0 = asin(2.0 / 3.0); PJ_XY xy; /* equatorial region */ if (fabs(phi) <= phi0) { xy.x = lam; xy.y = 3 * M_PI / 8 * sin(phi); } else { double lamc; double sigma = sqrt(3 * (1 - fabs(sin(phi)))); double cn = floor(2 * lam / M_PI + 2); if (cn >= 4) { cn = 3; } lamc = -3 * M_FORTPI + M_HALFPI * cn; xy.x = lamc + (lam - lamc) * sigma; xy.y = sign(phi) * M_FORTPI * (2 - sigma); } return xy; } /** * Return the inverse of healpix_sphere(). **/ static PJ_LP healpix_spherhealpix_e_inverse(PJ_XY xy) { PJ_LP lp; double x = xy.x; double y = xy.y; double y0 = M_FORTPI; /* Equatorial region. */ if (fabs(y) <= y0) { lp.lam = x; lp.phi = asin(8 * y / (3 * M_PI)); } else if (fabs(y) < M_HALFPI) { double cn = floor(2 * x / M_PI + 2); double xc, tau; if (cn >= 4) { cn = 3; } xc = -3 * M_FORTPI + M_HALFPI * cn; tau = 2.0 - 4 * fabs(y) / M_PI; lp.lam = xc + (x - xc) / tau; lp.phi = sign(y) * asin(1.0 - pow(tau, 2) / 3.0); } else { lp.lam = -M_PI; lp.phi = sign(y) * M_HALFPI; } return (lp); } /** * Return the vector sum a + b, where a and b are 2-dimensional vectors. * @param ret holds a + b. **/ static void vector_add(const double a[2], const double b[2], double *ret) { int i; for (i = 0; i < 2; i++) { ret[i] = a[i] + b[i]; } } /** * Return the vector difference a - b, where a and b are 2-dimensional vectors. * @param ret holds a - b. **/ static void vector_sub(const double a[2], const double b[2], double *ret) { int i; for (i = 0; i < 2; i++) { ret[i] = a[i] - b[i]; } } /** * Return the 2 x 1 matrix product a*b, where a is a 2 x 2 matrix and * b is a 2 x 1 matrix. * @param ret holds a*b. **/ static void dot_product(const double a[2][2], const double b[2], double *ret) { int i, j; int length = 2; for (i = 0; i < length; i++) { ret[i] = 0; for (j = 0; j < length; j++) { ret[i] += a[i][j] * b[j]; } } } /** * Return the number of the polar cap, the pole point coordinates, and * the region that (x, y) lies in. * If inverse=0, then assume (x,y) lies in the image of the HEALPix * projection of the unit sphere. * If inverse=1, then assume (x,y) lies in the image of the * (north_square, south_square)-rHEALPix projection of the unit sphere. **/ static CapMap get_cap(double x, double y, int north_square, int south_square, int inverse) { CapMap capmap; double c; capmap.x = x; capmap.y = y; if (inverse == 0) { if (y > M_FORTPI) { capmap.region = CapMap::north; c = M_HALFPI; } else if (y < -M_FORTPI) { capmap.region = CapMap::south; c = -M_HALFPI; } else { capmap.region = CapMap::equatorial; capmap.cn = 0; return capmap; } /* polar region */ if (x < -M_HALFPI) { capmap.cn = 0; capmap.x = (-3 * M_FORTPI); capmap.y = c; } else if (x >= -M_HALFPI && x < 0) { capmap.cn = 1; capmap.x = -M_FORTPI; capmap.y = c; } else if (x >= 0 && x < M_HALFPI) { capmap.cn = 2; capmap.x = M_FORTPI; capmap.y = c; } else { capmap.cn = 3; capmap.x = 3 * M_FORTPI; capmap.y = c; } } else { if (y > M_FORTPI) { capmap.region = CapMap::north; capmap.x = -3 * M_FORTPI + north_square * M_HALFPI; capmap.y = M_HALFPI; x = x - north_square * M_HALFPI; } else if (y < -M_FORTPI) { capmap.region = CapMap::south; capmap.x = -3 * M_FORTPI + south_square * M_HALFPI; capmap.y = -M_HALFPI; x = x - south_square * M_HALFPI; } else { capmap.region = CapMap::equatorial; capmap.cn = 0; return capmap; } /* Polar Region, find the HEALPix polar cap number that x, y moves to when rHEALPix polar square is disassembled. */ if (capmap.region == CapMap::north) { if (y >= -x - M_FORTPI - EPS && y < x + 5 * M_FORTPI - EPS) { capmap.cn = (north_square + 1) % 4; } else if (y > -x - M_FORTPI + EPS && y >= x + 5 * M_FORTPI - EPS) { capmap.cn = (north_square + 2) % 4; } else if (y <= -x - M_FORTPI + EPS && y > x + 5 * M_FORTPI + EPS) { capmap.cn = (north_square + 3) % 4; } else { capmap.cn = north_square; } } else /* if (capmap.region == CapMap::south) */ { if (y <= x + M_FORTPI + EPS && y > -x - 5 * M_FORTPI + EPS) { capmap.cn = (south_square + 1) % 4; } else if (y < x + M_FORTPI - EPS && y <= -x - 5 * M_FORTPI + EPS) { capmap.cn = (south_square + 2) % 4; } else if (y >= x + M_FORTPI - EPS && y < -x - 5 * M_FORTPI - EPS) { capmap.cn = (south_square + 3) % 4; } else { capmap.cn = south_square; } } } return capmap; } /** * Rearrange point (x, y) in the HEALPix projection by * combining the polar caps into two polar squares. * Put the north polar square in position north_square and * the south polar square in position south_square. * If inverse=1, then uncombine the polar caps. * @param north_square integer between 0 and 3. * @param south_square integer between 0 and 3. **/ static PJ_XY combine_caps(double x, double y, int north_square, int south_square, int inverse) { PJ_XY xy; double vector[2]; double v_min_c[2]; double ret_dot[2]; const double(*tmpRot)[2]; int pole = 0; CapMap capmap = get_cap(x, y, north_square, south_square, inverse); if (capmap.region == CapMap::equatorial) { xy.x = capmap.x; xy.y = capmap.y; return xy; } double v[] = {x, y}; double c[] = {capmap.x, capmap.y}; if (inverse == 0) { /* Rotate (x, y) about its polar cap tip and then translate it to north_square or south_square. */ if (capmap.region == CapMap::north) { pole = north_square; tmpRot = rot[get_rotate_index(capmap.cn - pole)]; } else { pole = south_square; tmpRot = rot[get_rotate_index(-1 * (capmap.cn - pole))]; } } else { /* Inverse function. Unrotate (x, y) and then translate it back. */ /* disassemble */ if (capmap.region == CapMap::north) { pole = north_square; tmpRot = rot[get_rotate_index(-1 * (capmap.cn - pole))]; } else { pole = south_square; tmpRot = rot[get_rotate_index(capmap.cn - pole)]; } } vector_sub(v, c, v_min_c); dot_product(tmpRot, v_min_c, ret_dot); { double a[] = {-3 * M_FORTPI + ((inverse == 0) ? pole : capmap.cn) * M_HALFPI, ((capmap.region == CapMap::north) ? 1 : -1) * M_HALFPI}; vector_add(ret_dot, a, vector); } xy.x = vector[0]; xy.y = vector[1]; return xy; } static PJ_XY s_healpix_forward(PJ_LP lp, PJ *P) { /* sphere */ (void)P; struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); return rotate(healpix_sphere(lp), -Q->rot_xy); } static PJ_XY e_healpix_forward(PJ_LP lp, PJ *P) { /* ellipsoid */ lp.phi = auth_lat(P, lp.phi, 0); struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); return rotate(healpix_sphere(lp), -Q->rot_xy); } static PJ_LP s_healpix_inverse(PJ_XY xy, PJ *P) { /* sphere */ struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); xy = rotate(xy, Q->rot_xy); /* Check whether (x, y) lies in the HEALPix image */ if (in_image(xy.x, xy.y, 0, 0, 0) == 0) { PJ_LP lp; lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } return healpix_spherhealpix_e_inverse(xy); } static PJ_LP e_healpix_inverse(PJ_XY xy, PJ *P) { /* ellipsoid */ PJ_LP lp = {0.0, 0.0}; struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); xy = rotate(xy, Q->rot_xy); /* Check whether (x, y) lies in the HEALPix image. */ if (in_image(xy.x, xy.y, 0, 0, 0) == 0) { lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } lp = healpix_spherhealpix_e_inverse(xy); lp.phi = auth_lat(P, lp.phi, 1); return lp; } static PJ_XY s_rhealpix_forward(PJ_LP lp, PJ *P) { /* sphere */ struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); PJ_XY xy = healpix_sphere(lp); return combine_caps(xy.x, xy.y, Q->north_square, Q->south_square, 0); } static PJ_XY e_rhealpix_forward(PJ_LP lp, PJ *P) { /* ellipsoid */ struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); PJ_XY xy; lp.phi = auth_lat(P, lp.phi, 0); xy = healpix_sphere(lp); return combine_caps(xy.x, xy.y, Q->north_square, Q->south_square, 0); } static PJ_LP s_rhealpix_inverse(PJ_XY xy, PJ *P) { /* sphere */ struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); /* Check whether (x, y) lies in the rHEALPix image. */ if (in_image(xy.x, xy.y, 1, Q->north_square, Q->south_square) == 0) { PJ_LP lp; lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } xy = combine_caps(xy.x, xy.y, Q->north_square, Q->south_square, 1); return healpix_spherhealpix_e_inverse(xy); } static PJ_LP e_rhealpix_inverse(PJ_XY xy, PJ *P) { /* ellipsoid */ struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>(P->opaque); PJ_LP lp = {0.0, 0.0}; /* Check whether (x, y) lies in the rHEALPix image. */ if (in_image(xy.x, xy.y, 1, Q->north_square, Q->south_square) == 0) { lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } xy = combine_caps(xy.x, xy.y, Q->north_square, Q->south_square, 1); lp = healpix_spherhealpix_e_inverse(xy); lp.phi = auth_lat(P, lp.phi, 1); return lp; } static PJ *pj_healpix_data_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_healpix_data *>(P->opaque)->apa); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(healpix) { struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>( calloc(1, sizeof(struct pj_healpix_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_healpix_data_destructor; double angle = pj_param(P->ctx, P->params, "drot_xy").f; Q->rot_xy = PJ_TORAD(angle); if (P->es != 0.0) { Q->apa = pj_authset(P->es); /* For auth_lat(). */ if (nullptr == Q->apa) return pj_healpix_data_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->qp = pj_qsfn(1.0, P->e, P->one_es); /* For auth_lat(). */ P->a = P->a * sqrt(0.5 * Q->qp); /* Set P->a to authalic radius. */ pj_calc_ellipsoid_params( P, P->a, P->es); /* Ensure we have a consistent parameter set */ P->fwd = e_healpix_forward; P->inv = e_healpix_inverse; } else { P->fwd = s_healpix_forward; P->inv = s_healpix_inverse; } return P; } PJ *PJ_PROJECTION(rhealpix) { struct pj_healpix_data *Q = static_cast<struct pj_healpix_data *>( calloc(1, sizeof(struct pj_healpix_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_healpix_data_destructor; Q->north_square = pj_param(P->ctx, P->params, "inorth_square").i; Q->south_square = pj_param(P->ctx, P->params, "isouth_square").i; /* Check for valid north_square and south_square inputs. */ if (Q->north_square < 0 || Q->north_square > 3) { proj_log_error( P, _("Invalid value for north_square: it should be in [0,3] range.")); return pj_healpix_data_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (Q->south_square < 0 || Q->south_square > 3) { proj_log_error( P, _("Invalid value for south_square: it should be in [0,3] range.")); return pj_healpix_data_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (P->es != 0.0) { Q->apa = pj_authset(P->es); /* For auth_lat(). */ if (nullptr == Q->apa) return pj_healpix_data_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->qp = pj_qsfn(1.0, P->e, P->one_es); /* For auth_lat(). */ P->a = P->a * sqrt(0.5 * Q->qp); /* Set P->a to authalic radius. */ P->ra = 1.0 / P->a; P->fwd = e_rhealpix_forward; P->inv = e_rhealpix_inverse; } else { P->fwd = s_rhealpix_forward; P->inv = s_rhealpix_inverse; } return P; } #undef R1 #undef R2 #undef R3 #undef IDENT #undef ROT #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/omerc.cpp
/* ** Copyright (c) 2003, 2006 Gerald I. Evenden */ /* ** Permission is hereby granted, free of charge, to any person obtaining ** a copy of this software and associated documentation files (the ** "Software"), to deal in the Software without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Software, and to ** permit persons to whom the Software is furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(omerc, "Oblique Mercator") "\n\tCyl, Sph&Ell no_rot\n\t" "alpha= [gamma=] [no_off] lonc= or\n\t lon_1= lat_1= lon_2= lat_2="; namespace { // anonymous namespace struct pj_omerc_data { double A, B, E, AB, ArB, BrA, rB, singam, cosgam, sinrot, cosrot; double v_pole_n, v_pole_s, u_0; int no_rot; }; } // anonymous namespace #define TOL 1.e-7 #define EPS 1.e-10 static PJ_XY omerc_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_omerc_data *Q = static_cast<struct pj_omerc_data *>(P->opaque); double u, v; if (fabs(fabs(lp.phi) - M_HALFPI) > EPS) { const double W = Q->E / pow(pj_tsfn(lp.phi, sin(lp.phi), P->e), Q->B); const double one_div_W = 1. / W; const double S = .5 * (W - one_div_W); const double T = .5 * (W + one_div_W); const double V = sin(Q->B * lp.lam); const double U = (S * Q->singam - V * Q->cosgam) / T; if (fabs(fabs(U) - 1.0) < EPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } v = 0.5 * Q->ArB * log((1. - U) / (1. + U)); const double temp = cos(Q->B * lp.lam); if (fabs(temp) < TOL) { u = Q->A * lp.lam; } else { u = Q->ArB * atan2((S * Q->cosgam + V * Q->singam), temp); } } else { v = lp.phi > 0 ? Q->v_pole_n : Q->v_pole_s; u = Q->ArB * lp.phi; } if (Q->no_rot) { xy.x = u; xy.y = v; } else { u -= Q->u_0; xy.x = v * Q->cosrot + u * Q->sinrot; xy.y = u * Q->cosrot - v * Q->sinrot; } return xy; } static PJ_LP omerc_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_omerc_data *Q = static_cast<struct pj_omerc_data *>(P->opaque); double u, v, Qp, Sp, Tp, Vp, Up; if (Q->no_rot) { v = xy.y; u = xy.x; } else { v = xy.x * Q->cosrot - xy.y * Q->sinrot; u = xy.y * Q->cosrot + xy.x * Q->sinrot + Q->u_0; } Qp = exp(-Q->BrA * v); if (Qp == 0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().lp; } Sp = .5 * (Qp - 1. / Qp); Tp = .5 * (Qp + 1. / Qp); Vp = sin(Q->BrA * u); Up = (Vp * Q->cosgam + Sp * Q->singam) / Tp; if (fabs(fabs(Up) - 1.) < EPS) { lp.lam = 0.; lp.phi = Up < 0. ? -M_HALFPI : M_HALFPI; } else { lp.phi = Q->E / sqrt((1. + Up) / (1. - Up)); if ((lp.phi = pj_phi2(P->ctx, pow(lp.phi, 1. / Q->B), P->e)) == HUGE_VAL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } lp.lam = -Q->rB * atan2((Sp * Q->cosgam - Vp * Q->singam), cos(Q->BrA * u)); } return lp; } PJ *PJ_PROJECTION(omerc) { double con, com, cosph0, D, F, H, L, sinph0, p, J, gamma = 0, gamma0, lamc = 0, lam1 = 0, lam2 = 0, phi1 = 0, phi2 = 0, alpha_c = 0; int alp, gam, no_off = 0; struct pj_omerc_data *Q = static_cast<struct pj_omerc_data *>( calloc(1, sizeof(struct pj_omerc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->no_rot = pj_param(P->ctx, P->params, "bno_rot").i; if ((alp = pj_param(P->ctx, P->params, "talpha").i) != 0) alpha_c = pj_param(P->ctx, P->params, "ralpha").f; if ((gam = pj_param(P->ctx, P->params, "tgamma").i) != 0) gamma = pj_param(P->ctx, P->params, "rgamma").f; if (alp || gam) { lamc = pj_param(P->ctx, P->params, "rlonc").f; no_off = /* For libproj4 compatibility */ pj_param(P->ctx, P->params, "tno_off").i /* for backward compatibility */ || pj_param(P->ctx, P->params, "tno_uoff").i; if (no_off) { /* Mark the parameter as used, so that the pj_get_def() return them */ pj_param(P->ctx, P->params, "sno_uoff"); pj_param(P->ctx, P->params, "sno_off"); } } else { lam1 = pj_param(P->ctx, P->params, "rlon_1").f; phi1 = pj_param(P->ctx, P->params, "rlat_1").f; lam2 = pj_param(P->ctx, P->params, "rlon_2").f; phi2 = pj_param(P->ctx, P->params, "rlat_2").f; con = fabs(phi1); if (fabs(phi1) > M_HALFPI - TOL) { proj_log_error( P, _("Invalid value for lat_1: |lat_1| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(phi2) > M_HALFPI - TOL) { proj_log_error( P, _("Invalid value for lat_2: |lat_2| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(phi1 - phi2) <= TOL) { proj_log_error(P, _("Invalid value for lat_1/lat_2: lat_1 should be " "different from lat_2")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (con <= TOL) { proj_log_error( P, _("Invalid value for lat_1: lat_1 should be different from 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(fabs(P->phi0) - M_HALFPI) <= TOL) { proj_log_error( P, _("Invalid value for lat_0: |lat_0| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (pj_param(P->ctx, P->params, "rlon_0").i) { proj_log_trace(P, _("lon_0 is ignored.")); } com = sqrt(P->one_es); if (fabs(P->phi0) > EPS) { sinph0 = sin(P->phi0); cosph0 = cos(P->phi0); con = 1. - P->es * sinph0 * sinph0; Q->B = cosph0 * cosph0; Q->B = sqrt(1. + P->es * Q->B * Q->B / P->one_es); Q->A = Q->B * P->k0 * com / con; D = Q->B * com / (cosph0 * sqrt(con)); if ((F = D * D - 1.) <= 0.) F = 0.; else { F = sqrt(F); if (P->phi0 < 0.) F = -F; } Q->E = F += D; Q->E *= pow(pj_tsfn(P->phi0, sinph0, P->e), Q->B); } else { Q->B = 1. / com; Q->A = P->k0; Q->E = D = F = 1.; } if (alp || gam) { if (alp) { gamma0 = aasin(P->ctx, sin(alpha_c) / D); if (!gam) gamma = alpha_c; } else { gamma0 = gamma; alpha_c = aasin(P->ctx, D * sin(gamma0)); if (proj_errno(P) != 0) { // For a sphere, |gamma| must be <= 90 - |lat_0| // On an ellipsoid, this is very slightly above proj_log_error(P, ("Invalid value for gamma: given lat_0 value, " "|gamma| should be <= " + std::to_string(asin(1. / D) / M_PI * 180) + "°") .c_str()); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (fabs(fabs(P->phi0) - M_HALFPI) <= TOL) { proj_log_error( P, _("Invalid value for lat_0: |lat_0| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->lam0 = lamc - aasin(P->ctx, .5 * (F - 1. / F) * tan(gamma0)) / Q->B; } else { H = pow(pj_tsfn(phi1, sin(phi1), P->e), Q->B); L = pow(pj_tsfn(phi2, sin(phi2), P->e), Q->B); F = Q->E / H; p = (L - H) / (L + H); if (p == 0) { // Not quite, but es is very close to 1... proj_log_error(P, _("Invalid value for eccentricity")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } J = Q->E * Q->E; J = (J - L * H) / (J + L * H); if ((con = lam1 - lam2) < -M_PI) lam2 -= M_TWOPI; else if (con > M_PI) lam2 += M_TWOPI; P->lam0 = adjlon(.5 * (lam1 + lam2) - atan(J * tan(.5 * Q->B * (lam1 - lam2)) / p) / Q->B); const double denom = F - 1. / F; if (denom == 0) { proj_log_error(P, _("Invalid value for eccentricity")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } gamma0 = atan(2. * sin(Q->B * adjlon(lam1 - P->lam0)) / denom); gamma = alpha_c = aasin(P->ctx, D * sin(gamma0)); } Q->singam = sin(gamma0); Q->cosgam = cos(gamma0); Q->sinrot = sin(gamma); Q->cosrot = cos(gamma); Q->BrA = 1. / (Q->ArB = Q->A * (Q->rB = 1. / Q->B)); Q->AB = Q->A * Q->B; if (no_off) Q->u_0 = 0; else { Q->u_0 = fabs(Q->ArB * atan(sqrt(D * D - 1.) / cos(alpha_c))); if (P->phi0 < 0.) Q->u_0 = -Q->u_0; } F = 0.5 * gamma0; Q->v_pole_n = Q->ArB * log(tan(M_FORTPI - F)); Q->v_pole_s = Q->ArB * log(tan(M_FORTPI + F)); P->inv = omerc_e_inverse; P->fwd = omerc_e_forward; return P; } #undef TOL #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/wink2.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(wink2, "Winkel II") "\n\tPCyl, Sph\n\tlat_1="; namespace { // anonymous namespace struct pj_wink2_data { double cosphi1; }; } // anonymous namespace #define MAX_ITER 10 #define LOOP_TOL 1e-7 static PJ_XY wink2_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; int i; xy.y = lp.phi * M_TWO_D_PI; const double k = M_PI * sin(lp.phi); lp.phi *= 1.8; for (i = MAX_ITER; i; --i) { const double V = (lp.phi + sin(lp.phi) - k) / (1. + cos(lp.phi)); lp.phi -= V; if (fabs(V) < LOOP_TOL) break; } if (!i) lp.phi = (lp.phi < 0.) ? -M_HALFPI : M_HALFPI; else lp.phi *= 0.5; xy.x = 0.5 * lp.lam * (cos(lp.phi) + static_cast<struct pj_wink2_data *>(P->opaque)->cosphi1); xy.y = M_FORTPI * (sin(lp.phi) + xy.y); return xy; } static PJ_LP wink2_s_inverse(PJ_XY xy, PJ *P) { PJ_LP lpInit; lpInit.phi = xy.y; lpInit.lam = xy.x; constexpr double deltaXYTolerance = 1e-10; return pj_generic_inverse_2d(xy, P, lpInit, deltaXYTolerance); } PJ *PJ_PROJECTION(wink2) { struct pj_wink2_data *Q = static_cast<struct pj_wink2_data *>( calloc(1, sizeof(struct pj_wink2_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; static_cast<struct pj_wink2_data *>(P->opaque)->cosphi1 = cos(pj_param(P->ctx, P->params, "rlat_1").f); P->es = 0.; P->fwd = wink2_s_forward; P->inv = wink2_s_inverse; return P; } #undef MAX_ITER #undef LOOP_TOL
cpp
PROJ
data/projects/PROJ/src/projections/vandg.cpp
// Changes to handle +over are: Copyright 2011-2014 Morelli Informatik #include "proj.h" #include "proj_internal.h" PROJ_HEAD(vandg, "van der Grinten (I)") "\n\tMisc Sph"; #define TOL 1.e-10 #define THIRD .33333333333333333333 #define C2_27 .07407407407407407407 // 2/27 #define PI4_3 4.18879020478639098458 // 4*pi/3 #define PISQ 9.86960440108935861869 // pi^2 #define TPISQ 19.73920880217871723738 // 2*pi^2 #define HPISQ 4.93480220054467930934 // pi^2/2 static PJ_XY vandg_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double al, al2, g, g2, p2; // Comments tie this formulation to Snyder (1987), p. 241. p2 = fabs(lp.phi / M_HALFPI); // sin(theta) from (29-6) if ((p2 - TOL) > 1.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } int sign = 1; if (P->over && fabs(lp.lam) > M_PI) sign = -1; if (p2 > 1.) p2 = 1.; if (fabs(lp.phi) <= TOL) { xy.x = lp.lam; xy.y = 0.; } else if (fabs(lp.lam) <= TOL || fabs(p2 - 1.) < TOL) { xy.x = 0.; xy.y = M_PI * tan(.5 * asin(p2)); if (lp.phi < 0.) xy.y = -xy.y; } else { al = .5 * sign * fabs(M_PI / lp.lam - lp.lam / M_PI); // A from (29-3) al2 = al * al; // A^2 g = sqrt(1. - p2 * p2); // cos(theta) g = g / (p2 + g - 1.); // G from (29-4) g2 = g * g; // G^2 p2 = g * (2. / p2 - 1.); // P from (29-5) p2 = p2 * p2; // P^2 { // Force floating-point computations done on 80 bit on // i386 to go back to 64 bit. This is to avoid the test failures // of // https://github.com/OSGeo/PROJ/issues/1906#issuecomment-583168348 // The choice of p2 is completely arbitrary. volatile double p2_tmp = p2; p2 = p2_tmp; } xy.x = g - p2; // G - P^2 g = p2 + al2; // P^2 + A^2 // (29-1) xy.x = M_PI * fabs(al * xy.x + sqrt(al2 * xy.x * xy.x - g * (g2 - p2))) / g; if (lp.lam < 0.) xy.x = -xy.x; xy.y = fabs(xy.x / M_PI); // y from (29-2) has been expressed in terms of x here xy.y = 1. - xy.y * (xy.y + 2. * al); if (xy.y < -TOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } if (xy.y < 0.) xy.y = 0.; else xy.y = sqrt(xy.y) * (lp.phi < 0. ? -M_PI : M_PI); } return xy; } static PJ_LP vandg_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double t, c0, c1, c2, c3, al, r2, r, m, d, ay, x2, y2; // Comments tie this formulation to Snyder (1987), p. 242. x2 = xy.x * xy.x; // pi^2 * X^2 if ((ay = fabs(xy.y)) < TOL) { lp.phi = 0.; t = x2 * x2 + TPISQ * (x2 + HPISQ); lp.lam = fabs(xy.x) <= TOL ? 0. : .5 * (x2 - PISQ + sqrt(t)) / xy.x; return (lp); } y2 = xy.y * xy.y; // pi^2 * Y^2 r = x2 + y2; // pi^2 * (X^2+Y^2) r2 = r * r; // pi^4 * (X^2+Y^2)^2 c1 = -M_PI * ay * (r + PISQ); // pi^4 * c1 (29-11) // pi^4 * c3 (29-13) c3 = r2 + M_TWOPI * (ay * r + M_PI * (y2 + M_PI * (ay + M_HALFPI))); c2 = c1 + PISQ * (r - 3. * y2); // pi^4 * c2 (29-12) c0 = M_PI * ay; // pi^2 * Y c2 /= c3; // c2/c3 al = c1 / c3 - THIRD * c2 * c2; // a1 (29-15) m = 2. * sqrt(-THIRD * al); // m1 (29-16) d = C2_27 * c2 * c2 * c2 + (c0 * c0 - THIRD * c2 * c1) / c3; // d (29-14) const double al_mul_m = al * m; // a1*m1 if (fabs(al_mul_m) < 1e-16) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().lp; } d = 3. * d / al_mul_m; // cos(3*theta1) (29-17) t = fabs(d); if ((t - TOL) <= 1.) { d = t > 1. ? (d > 0. ? 0. : M_PI) : acos(d); // 3*theta1 (29-17) if (r > PISQ) { // This code path is triggered for coordinates generated in the // forward path when |long|>180deg and +over d = M_TWOPI - d; } // (29-18) but change pi/3 to 4*pi/3 to flip sign of cos lp.phi = M_PI * (m * cos(d * THIRD + PI4_3) - THIRD * c2); if (xy.y < 0.) lp.phi = -lp.phi; t = r2 + TPISQ * (x2 - y2 + HPISQ); lp.lam = fabs(xy.x) <= TOL ? 0. : .5 * (r - PISQ + (t <= 0. ? 0. : sqrt(t))) / xy.x; } else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } return lp; } PJ *PJ_PROJECTION(vandg) { P->es = 0.; P->inv = vandg_s_inverse; P->fwd = vandg_s_forward; return P; } #undef TOL #undef THIRD #undef C2_27 #undef PI4_3 #undef PISQ #undef TPISQ #undef HPISQ
cpp
PROJ
data/projects/PROJ/src/projections/tmerc.cpp
/* * Transverse Mercator implementations * * In this file two transverse mercator implementations are found. One of Gerald * Evenden/John Snyder origin and one of Knud Poder/Karsten Engsager origin. The * former is regarded as "approximate" in the following and the latter is * "exact". This word choice has been made to distinguish between the two * algorithms, where the Evenden/Snyder implementation is the faster, less * accurate implementation and the Poder/Engsager algorithm is a slightly * slower, but more accurate implementation. */ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" #include <math.h> PROJ_HEAD(tmerc, "Transverse Mercator") "\n\tCyl, Sph&Ell\n\tapprox"; PROJ_HEAD(etmerc, "Extended Transverse Mercator") "\n\tCyl, Sph"; PROJ_HEAD(utm, "Universal Transverse Mercator (UTM)") "\n\tCyl, Ell\n\tzone= south approx"; namespace { // anonymous namespace // Approximate: Evenden/Snyder struct EvendenSnyder { double esp; double ml0; double *en; }; // More exact: Poder/Engsager struct PoderEngsager { double Qn; /* Merid. quad., scaled to the projection */ double Zb; /* Radius vector in polar coord. systems */ double cgb[6]; /* Constants for Gauss -> Geo lat */ double cbg[6]; /* Constants for Geo lat -> Gauss */ double utg[6]; /* Constants for transv. merc. -> geo */ double gtu[6]; /* Constants for geo -> transv. merc. */ }; struct tmerc_data { EvendenSnyder approx; PoderEngsager exact; }; } // anonymous namespace /* Constants for "approximate" transverse mercator */ #define EPS10 1.e-10 #define FC1 1. #define FC2 .5 #define FC3 .16666666666666666666 #define FC4 .08333333333333333333 #define FC5 .05 #define FC6 .03333333333333333333 #define FC7 .02380952380952380952 #define FC8 .01785714285714285714 /* Constant for "exact" transverse mercator */ #define PROJ_ETMERC_ORDER 6 /*****************************************************************************/ // // Approximate Transverse Mercator functions // /*****************************************************************************/ static PJ_XY approx_e_fwd(PJ_LP lp, PJ *P) { PJ_XY xy = {0.0, 0.0}; const auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->approx); double al, als, n, cosphi, sinphi, t; /* * Fail if our longitude is more than 90 degrees from the * central meridian since the results are essentially garbage. * Is error -20 really an appropriate return value? * * http://trac.osgeo.org/proj/ticket/5 */ if (lp.lam < -M_HALFPI || lp.lam > M_HALFPI) { xy.x = HUGE_VAL; xy.y = HUGE_VAL; proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } sinphi = sin(lp.phi); cosphi = cos(lp.phi); t = fabs(cosphi) > 1e-10 ? sinphi / cosphi : 0.; t *= t; al = cosphi * lp.lam; als = al * al; al /= sqrt(1. - P->es * sinphi * sinphi); n = Q->esp * cosphi * cosphi; xy.x = P->k0 * al * (FC1 + FC3 * als * (1. - t + n + FC5 * als * (5. + t * (t - 18.) + n * (14. - 58. * t) + FC7 * als * (61. + t * (t * (179. - t) - 479.))))); xy.y = P->k0 * (pj_mlfn(lp.phi, sinphi, cosphi, Q->en) - Q->ml0 + sinphi * al * lp.lam * FC2 * (1. + FC4 * als * (5. - t + n * (9. + 4. * n) + FC6 * als * (61. + t * (t - 58.) + n * (270. - 330 * t) + FC8 * als * (1385. + t * (t * (543. - t) - 3111.)))))); return (xy); } static PJ_XY tmerc_spherical_fwd(PJ_LP lp, PJ *P) { PJ_XY xy = {0.0, 0.0}; double b, cosphi; const auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->approx); cosphi = cos(lp.phi); b = cosphi * sin(lp.lam); if (fabs(fabs(b) - 1.) <= EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.x = Q->ml0 * log((1. + b) / (1. - b)); xy.y = cosphi * cos(lp.lam) / sqrt(1. - b * b); b = fabs(xy.y); if (cosphi == 1 && (lp.lam < -M_HALFPI || lp.lam > M_HALFPI)) { /* Helps to be able to roundtrip |longitudes| > 90 at lat=0 */ /* We could also map to -M_PI ... */ xy.y = M_PI; } else if (b >= 1.) { if ((b - 1.) > EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } else xy.y = 0.; } else xy.y = acos(xy.y); if (lp.phi < 0.) xy.y = -xy.y; xy.y = Q->esp * (xy.y - P->phi0); return xy; } static PJ_LP approx_e_inv(PJ_XY xy, PJ *P) { PJ_LP lp = {0.0, 0.0}; const auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->approx); lp.phi = pj_inv_mlfn(Q->ml0 + xy.y / P->k0, Q->en); if (fabs(lp.phi) >= M_HALFPI) { lp.phi = xy.y < 0. ? -M_HALFPI : M_HALFPI; lp.lam = 0.; } else { double sinphi = sin(lp.phi), cosphi = cos(lp.phi); double t = fabs(cosphi) > 1e-10 ? sinphi / cosphi : 0.; const double n = Q->esp * cosphi * cosphi; double con = 1. - P->es * sinphi * sinphi; const double d = xy.x * sqrt(con) / P->k0; con *= t; t *= t; const double ds = d * d; lp.phi -= (con * ds / (1. - P->es)) * FC2 * (1. - ds * FC4 * (5. + t * (3. - 9. * n) + n * (1. - 4 * n) - ds * FC6 * (61. + t * (90. - 252. * n + 45. * t) + 46. * n - ds * FC8 * (1385. + t * (3633. + t * (4095. + 1575. * t)))))); lp.lam = d * (FC1 - ds * FC3 * (1. + 2. * t + n - ds * FC5 * (5. + t * (28. + 24. * t + 8. * n) + 6. * n - ds * FC7 * (61. + t * (662. + t * (1320. + 720. * t)))))) / cosphi; } return lp; } static PJ_LP tmerc_spherical_inv(PJ_XY xy, PJ *P) { PJ_LP lp = {0.0, 0.0}; double h, g; const auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->approx); h = exp(xy.x / Q->esp); if (h == 0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().lp; } g = .5 * (h - 1. / h); /* D, as in equation 8-8 of USGS "Map Projections - A Working Manual" */ const double D = P->phi0 + xy.y / Q->esp; h = cos(D); lp.phi = asin(sqrt((1. - h * h) / (1. + g * g))); /* Make sure that phi is on the correct hemisphere when false northing is * used */ lp.phi = copysign(lp.phi, D); lp.lam = (g != 0.0 || h != 0.0) ? atan2(g, h) : 0.; return lp; } static PJ *destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct tmerc_data *>(P->opaque)->approx.en); return pj_default_destructor(P, errlev); } static PJ *setup_approx(PJ *P) { auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->approx); if (P->es != 0.0) { if (!(Q->en = pj_enfn(P->n))) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->ml0 = pj_mlfn(P->phi0, sin(P->phi0), cos(P->phi0), Q->en); Q->esp = P->es / (1. - P->es); } else { Q->esp = P->k0; Q->ml0 = .5 * Q->esp; } return P; } /*****************************************************************************/ // // Exact Transverse Mercator functions // // // The code in this file is largly based upon procedures: // // Written by: Knud Poder and Karsten Engsager // // Based on math from: R.Koenig and K.H. Weise, "Mathematische // Grundlagen der hoeheren Geodaesie und Kartographie, // Springer-Verlag, Berlin/Goettingen" Heidelberg, 1951. // // Modified and used here by permission of Reference Networks // Division, Kort og Matrikelstyrelsen (KMS), Copenhagen, Denmark // /*****************************************************************************/ /* Helper functions for "exact" transverse mercator */ inline static double gatg(const double *p1, int len_p1, double B, double cos_2B, double sin_2B) { double h = 0, h1, h2 = 0; const double two_cos_2B = 2 * cos_2B; const double *p = p1 + len_p1; h1 = *--p; while (p - p1) { h = -h2 + two_cos_2B * h1 + *--p; h2 = h1; h1 = h; } return (B + h * sin_2B); } /* Complex Clenshaw summation */ inline static double clenS(const double *a, int size, double sin_arg_r, double cos_arg_r, double sinh_arg_i, double cosh_arg_i, double *R, double *I) { double r, i, hr, hr1, hr2, hi, hi1, hi2; /* arguments */ const double *p = a + size; r = 2 * cos_arg_r * cosh_arg_i; i = -2 * sin_arg_r * sinh_arg_i; /* summation loop */ hi1 = hr1 = hi = 0; hr = *--p; for (; a - p;) { hr2 = hr1; hi2 = hi1; hr1 = hr; hi1 = hi; hr = -hr2 + r * hr1 - i * hi1 + *--p; hi = -hi2 + i * hr1 + r * hi1; } r = sin_arg_r * cosh_arg_i; i = cos_arg_r * sinh_arg_i; *R = r * hr - i * hi; *I = r * hi + i * hr; return *R; } /* Real Clenshaw summation */ static double clens(const double *a, int size, double arg_r) { double r, hr, hr1, hr2, cos_arg_r; const double *p = a + size; cos_arg_r = cos(arg_r); r = 2 * cos_arg_r; /* summation loop */ hr1 = 0; hr = *--p; for (; a - p;) { hr2 = hr1; hr1 = hr; hr = -hr2 + r * hr1 + *--p; } return sin(arg_r) * hr; } /* Ellipsoidal, forward */ static PJ_XY exact_e_fwd(PJ_LP lp, PJ *P) { PJ_XY xy = {0.0, 0.0}; const auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->exact); /* ell. LAT, LNG -> Gaussian LAT, LNG */ double Cn = gatg(Q->cbg, PROJ_ETMERC_ORDER, lp.phi, cos(2 * lp.phi), sin(2 * lp.phi)); /* Gaussian LAT, LNG -> compl. sph. LAT */ const double sin_Cn = sin(Cn); const double cos_Cn = cos(Cn); const double sin_Ce = sin(lp.lam); const double cos_Ce = cos(lp.lam); const double cos_Cn_cos_Ce = cos_Cn * cos_Ce; Cn = atan2(sin_Cn, cos_Cn_cos_Ce); const double inv_denom_tan_Ce = 1. / hypot(sin_Cn, cos_Cn_cos_Ce); const double tan_Ce = sin_Ce * cos_Cn * inv_denom_tan_Ce; #if 0 // Variant of the above: found not to be measurably faster const double sin_Ce_cos_Cn = sin_Ce*cos_Cn; const double denom = sqrt(1 - sin_Ce_cos_Cn * sin_Ce_cos_Cn); const double tan_Ce = sin_Ce_cos_Cn / denom; #endif /* compl. sph. N, E -> ell. norm. N, E */ double Ce = asinh(tan_Ce); /* Replaces: Ce = log(tan(FORTPI + Ce*0.5)); */ /* * Non-optimized version: * const double sin_arg_r = sin(2*Cn); * const double cos_arg_r = cos(2*Cn); * * Given: * sin(2 * Cn) = 2 sin(Cn) cos(Cn) * sin(atan(y)) = y / sqrt(1 + y^2) * cos(atan(y)) = 1 / sqrt(1 + y^2) * ==> sin(2 * Cn) = 2 tan_Cn / (1 + tan_Cn^2) * * cos(2 * Cn) = 2cos^2(Cn) - 1 * = 2 / (1 + tan_Cn^2) - 1 */ const double two_inv_denom_tan_Ce = 2 * inv_denom_tan_Ce; const double two_inv_denom_tan_Ce_square = two_inv_denom_tan_Ce * inv_denom_tan_Ce; const double tmp_r = cos_Cn_cos_Ce * two_inv_denom_tan_Ce_square; const double sin_arg_r = sin_Cn * tmp_r; const double cos_arg_r = cos_Cn_cos_Ce * tmp_r - 1; /* * Non-optimized version: * const double sinh_arg_i = sinh(2*Ce); * const double cosh_arg_i = cosh(2*Ce); * * Given * sinh(2 * Ce) = 2 sinh(Ce) cosh(Ce) * sinh(asinh(y)) = y * cosh(asinh(y)) = sqrt(1 + y^2) * ==> sinh(2 * Ce) = 2 tan_Ce sqrt(1 + tan_Ce^2) * * cosh(2 * Ce) = 2cosh^2(Ce) - 1 * = 2 * (1 + tan_Ce^2) - 1 * * and 1+tan_Ce^2 = 1 + sin_Ce^2 * cos_Cn^2 / (sin_Cn^2 + cos_Cn^2 * * cos_Ce^2) = (sin_Cn^2 + cos_Cn^2 * cos_Ce^2 + sin_Ce^2 * cos_Cn^2) / * (sin_Cn^2 + cos_Cn^2 * cos_Ce^2) = 1. / (sin_Cn^2 + cos_Cn^2 * cos_Ce^2) * = inv_denom_tan_Ce^2 * */ const double sinh_arg_i = tan_Ce * two_inv_denom_tan_Ce; const double cosh_arg_i = two_inv_denom_tan_Ce_square - 1; double dCn, dCe; Cn += clenS(Q->gtu, PROJ_ETMERC_ORDER, sin_arg_r, cos_arg_r, sinh_arg_i, cosh_arg_i, &dCn, &dCe); Ce += dCe; if (fabs(Ce) <= 2.623395162778) { xy.y = Q->Qn * Cn + Q->Zb; /* Northing */ xy.x = Q->Qn * Ce; /* Easting */ } else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); xy.x = xy.y = HUGE_VAL; } return xy; } /* Ellipsoidal, inverse */ static PJ_LP exact_e_inv(PJ_XY xy, PJ *P) { PJ_LP lp = {0.0, 0.0}; const auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->exact); /* normalize N, E */ double Cn = (xy.y - Q->Zb) / Q->Qn; double Ce = xy.x / Q->Qn; if (fabs(Ce) <= 2.623395162778) { /* 150 degrees */ /* norm. N, E -> compl. sph. LAT, LNG */ const double sin_arg_r = sin(2 * Cn); const double cos_arg_r = cos(2 * Cn); // const double sinh_arg_i = sinh(2*Ce); // const double cosh_arg_i = cosh(2*Ce); const double exp_2_Ce = exp(2 * Ce); const double half_inv_exp_2_Ce = 0.5 / exp_2_Ce; const double sinh_arg_i = 0.5 * exp_2_Ce - half_inv_exp_2_Ce; const double cosh_arg_i = 0.5 * exp_2_Ce + half_inv_exp_2_Ce; double dCn_ignored, dCe; Cn += clenS(Q->utg, PROJ_ETMERC_ORDER, sin_arg_r, cos_arg_r, sinh_arg_i, cosh_arg_i, &dCn_ignored, &dCe); Ce += dCe; /* compl. sph. LAT -> Gaussian LAT, LNG */ const double sin_Cn = sin(Cn); const double cos_Cn = cos(Cn); #if 0 // Non-optimized version: double sin_Ce, cos_Ce; Ce = atan (sinh (Ce)); // Replaces: Ce = 2*(atan(exp(Ce)) - FORTPI); sin_Ce = sin (Ce); cos_Ce = cos (Ce); Ce = atan2 (sin_Ce, cos_Ce*cos_Cn); Cn = atan2 (sin_Cn*cos_Ce, hypot (sin_Ce, cos_Ce*cos_Cn)); #else /* * One can divide both member of Ce = atan2(...) by cos_Ce, which * gives: Ce = atan2 (tan_Ce, cos_Cn) = atan2(sinh(Ce), cos_Cn) * * and the same for Cn = atan2(...) * Cn = atan2 (sin_Cn, hypot (sin_Ce, cos_Ce*cos_Cn)/cos_Ce) * = atan2 (sin_Cn, hypot (sin_Ce/cos_Ce, cos_Cn)) * = atan2 (sin_Cn, hypot (tan_Ce, cos_Cn)) * = atan2 (sin_Cn, hypot (sinhCe, cos_Cn)) */ const double sinhCe = sinh(Ce); Ce = atan2(sinhCe, cos_Cn); const double modulus_Ce = hypot(sinhCe, cos_Cn); Cn = atan2(sin_Cn, modulus_Ce); #endif /* Gaussian LAT, LNG -> ell. LAT, LNG */ // Optimization of the computation of cos(2*Cn) and sin(2*Cn) const double tmp = 2 * modulus_Ce / (sinhCe * sinhCe + 1); const double sin_2_Cn = sin_Cn * tmp; const double cos_2_Cn = tmp * modulus_Ce - 1.; // const double cos_2_Cn = cos(2 * Cn); // const double sin_2_Cn = sin(2 * Cn); lp.phi = gatg(Q->cgb, PROJ_ETMERC_ORDER, Cn, cos_2_Cn, sin_2_Cn); lp.lam = Ce; } else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.phi = lp.lam = HUGE_VAL; } return lp; } static PJ *setup_exact(PJ *P) { auto *Q = &(static_cast<struct tmerc_data *>(P->opaque)->exact); assert(P->es > 0); /* third flattening */ const double n = P->n; double np = n; /* COEF. OF TRIG SERIES GEO <-> GAUSS */ /* cgb := Gaussian -> Geodetic, KW p190 - 191 (61) - (62) */ /* cbg := Geodetic -> Gaussian, KW p186 - 187 (51) - (52) */ /* PROJ_ETMERC_ORDER = 6th degree : Engsager and Poder: ICC2007 */ Q->cgb[0] = n * (2 + n * (-2 / 3.0 + n * (-2 + n * (116 / 45.0 + n * (26 / 45.0 + n * (-2854 / 675.0)))))); Q->cbg[0] = n * (-2 + n * (2 / 3.0 + n * (4 / 3.0 + n * (-82 / 45.0 + n * (32 / 45.0 + n * (4642 / 4725.0)))))); np *= n; Q->cgb[1] = np * (7 / 3.0 + n * (-8 / 5.0 + n * (-227 / 45.0 + n * (2704 / 315.0 + n * (2323 / 945.0))))); Q->cbg[1] = np * (5 / 3.0 + n * (-16 / 15.0 + n * (-13 / 9.0 + n * (904 / 315.0 + n * (-1522 / 945.0))))); np *= n; /* n^5 coeff corrected from 1262/105 -> -1262/105 */ Q->cgb[2] = np * (56 / 15.0 + n * (-136 / 35.0 + n * (-1262 / 105.0 + n * (73814 / 2835.0)))); Q->cbg[2] = np * (-26 / 15.0 + n * (34 / 21.0 + n * (8 / 5.0 + n * (-12686 / 2835.0)))); np *= n; /* n^5 coeff corrected from 322/35 -> 332/35 */ Q->cgb[3] = np * (4279 / 630.0 + n * (-332 / 35.0 + n * (-399572 / 14175.0))); Q->cbg[3] = np * (1237 / 630.0 + n * (-12 / 5.0 + n * (-24832 / 14175.0))); np *= n; Q->cgb[4] = np * (4174 / 315.0 + n * (-144838 / 6237.0)); Q->cbg[4] = np * (-734 / 315.0 + n * (109598 / 31185.0)); np *= n; Q->cgb[5] = np * (601676 / 22275.0); Q->cbg[5] = np * (444337 / 155925.0); /* Constants of the projections */ /* Transverse Mercator (UTM, ITM, etc) */ np = n * n; /* Norm. mer. quad, K&W p.50 (96), p.19 (38b), p.5 (2) */ Q->Qn = P->k0 / (1 + n) * (1 + np * (1 / 4.0 + np * (1 / 64.0 + np / 256.0))); /* coef of trig series */ /* utg := ell. N, E -> sph. N, E, KW p194 (65) */ /* gtu := sph. N, E -> ell. N, E, KW p196 (69) */ Q->utg[0] = n * (-0.5 + n * (2 / 3.0 + n * (-37 / 96.0 + n * (1 / 360.0 + n * (81 / 512.0 + n * (-96199 / 604800.0)))))); Q->gtu[0] = n * (0.5 + n * (-2 / 3.0 + n * (5 / 16.0 + n * (41 / 180.0 + n * (-127 / 288.0 + n * (7891 / 37800.0)))))); Q->utg[1] = np * (-1 / 48.0 + n * (-1 / 15.0 + n * (437 / 1440.0 + n * (-46 / 105.0 + n * (1118711 / 3870720.0))))); Q->gtu[1] = np * (13 / 48.0 + n * (-3 / 5.0 + n * (557 / 1440.0 + n * (281 / 630.0 + n * (-1983433 / 1935360.0))))); np *= n; Q->utg[2] = np * (-17 / 480.0 + n * (37 / 840.0 + n * (209 / 4480.0 + n * (-5569 / 90720.0)))); Q->gtu[2] = np * (61 / 240.0 + n * (-103 / 140.0 + n * (15061 / 26880.0 + n * (167603 / 181440.0)))); np *= n; Q->utg[3] = np * (-4397 / 161280.0 + n * (11 / 504.0 + n * (830251 / 7257600.0))); Q->gtu[3] = np * (49561 / 161280.0 + n * (-179 / 168.0 + n * (6601661 / 7257600.0))); np *= n; Q->utg[4] = np * (-4583 / 161280.0 + n * (108847 / 3991680.0)); Q->gtu[4] = np * (34729 / 80640.0 + n * (-3418889 / 1995840.0)); np *= n; Q->utg[5] = np * (-20648693 / 638668800.0); Q->gtu[5] = np * (212378941 / 319334400.0); /* Gaussian latitude value of the origin latitude */ const double Z = gatg(Q->cbg, PROJ_ETMERC_ORDER, P->phi0, cos(2 * P->phi0), sin(2 * P->phi0)); /* Origin northing minus true northing at the origin latitude */ /* i.e. true northing = N - P->Zb */ Q->Zb = -Q->Qn * (Z + clens(Q->gtu, PROJ_ETMERC_ORDER, 2 * Z)); return P; } static PJ_XY auto_e_fwd(PJ_LP lp, PJ *P) { if (fabs(lp.lam) > 3 * DEG_TO_RAD) return exact_e_fwd(lp, P); else return approx_e_fwd(lp, P); } static PJ_LP auto_e_inv(PJ_XY xy, PJ *P) { // For k = 1 and long = 3 (from central meridian), // At lat = 0, we get x ~= 0.052, y = 0 // At lat = 90, we get x = 0, y ~= 1.57 // And the shape of this x=f(y) frontier curve is very very roughly a // parabola. Hence: if (fabs(xy.x) > 0.053 - 0.022 * xy.y * xy.y) return exact_e_inv(xy, P); else return approx_e_inv(xy, P); } static PJ *setup(PJ *P, TMercAlgo eAlg) { struct tmerc_data *Q = static_cast<struct tmerc_data *>(calloc(1, sizeof(struct tmerc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (P->es == 0) eAlg = TMercAlgo::EVENDEN_SNYDER; switch (eAlg) { case TMercAlgo::EVENDEN_SNYDER: { P->destructor = destructor; if (!setup_approx(P)) return nullptr; if (P->es == 0) { P->inv = tmerc_spherical_inv; P->fwd = tmerc_spherical_fwd; } else { P->inv = approx_e_inv; P->fwd = approx_e_fwd; } break; } case TMercAlgo::PODER_ENGSAGER: { setup_exact(P); P->inv = exact_e_inv; P->fwd = exact_e_fwd; break; } case TMercAlgo::AUTO: { P->destructor = destructor; if (!setup_approx(P)) return nullptr; setup_exact(P); P->inv = auto_e_inv; P->fwd = auto_e_fwd; break; } } return P; } static bool getAlgoFromParams(PJ *P, TMercAlgo &algo) { if (pj_param(P->ctx, P->params, "bapprox").i) { algo = TMercAlgo::EVENDEN_SNYDER; return true; } const char *algStr = pj_param(P->ctx, P->params, "salgo").s; if (algStr) { if (strcmp(algStr, "evenden_snyder") == 0) { algo = TMercAlgo::EVENDEN_SNYDER; return true; } if (strcmp(algStr, "poder_engsager") == 0) { algo = TMercAlgo::PODER_ENGSAGER; return true; } if (strcmp(algStr, "auto") == 0) { algo = TMercAlgo::AUTO; // Don't return so that we can run a later validity check } else { proj_log_error(P, "unknown value for +algo"); return false; } } else { pj_load_ini(P->ctx); // if not already done proj_context_errno_set( P->ctx, 0); // reset error in case proj.ini couldn't be found algo = P->ctx->defaultTmercAlgo; } // We haven't worked on the criterion on inverse transformation // when phi0 != 0 or if k0 is not close to 1 or for very oblate // ellipsoid (es > 0.1 is ~ rf < 200) if (algo == TMercAlgo::AUTO && (P->es > 0.1 || P->phi0 != 0 || fabs(P->k0 - 1) > 0.01)) { algo = TMercAlgo::PODER_ENGSAGER; } return true; } /*****************************************************************************/ // // Operation Setups // /*****************************************************************************/ PJ *PJ_PROJECTION(tmerc) { /* exact transverse mercator only exists in ellipsoidal form, */ /* use approximate version if +a sphere is requested */ TMercAlgo algo; if (!getAlgoFromParams(P, algo)) { proj_log_error(P, _("Invalid value for algo")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } return setup(P, algo); } PJ *PJ_PROJECTION(etmerc) { if (P->es == 0.0) { proj_log_error( P, _("Invalid value for eccentricity: it should not be zero")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } return setup(P, TMercAlgo::PODER_ENGSAGER); } /* UTM uses the Poder/Engsager implementation for the underlying projection */ /* UNLESS +approx is set in which case the Evenden/Snyder implementation is * used. */ PJ *PJ_PROJECTION(utm) { long zone; if (P->es == 0.0) { proj_log_error( P, _("Invalid value for eccentricity: it should not be zero")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (P->lam0 < -1000.0 || P->lam0 > 1000.0) { proj_log_error(P, _("Invalid value for lon_0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->y0 = pj_param(P->ctx, P->params, "bsouth").i ? 10000000. : 0.; P->x0 = 500000.; if (pj_param(P->ctx, P->params, "tzone").i) /* zone input ? */ { zone = pj_param(P->ctx, P->params, "izone").i; if (zone > 0 && zone <= 60) --zone; else { proj_log_error(P, _("Invalid value for zone")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } else /* nearest central meridian input */ { zone = lround((floor((adjlon(P->lam0) + M_PI) * 30. / M_PI))); if (zone < 0) zone = 0; else if (zone >= 60) zone = 59; } P->lam0 = (zone + .5) * M_PI / 30. - M_PI; P->k0 = 0.9996; P->phi0 = 0.; TMercAlgo algo; if (!getAlgoFromParams(P, algo)) { proj_log_error(P, _("Invalid value for algo")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } return setup(P, algo); }
cpp
PROJ
data/projects/PROJ/src/projections/calcofi.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(calcofi, "Cal Coop Ocean Fish Invest Lines/Stations") "\n\tCyl, Sph&Ell"; /* Conversions for the California Cooperative Oceanic Fisheries Investigations Line/Station coordinate system following the algorithm of: Eber, L.E., and R.P. Hewitt. 1979. Conversion algorithms for the CalCOFI station grid. California Cooperative Oceanic Fisheries Investigations Reports 20:135-137. (corrected for typographical errors). http://www.calcofi.org/publications/calcofireports/v20/Vol_20_Eber___Hewitt.pdf They assume 1 unit of CalCOFI Line == 1/5 degree in longitude or meridional units at reference point O, and similarly 1 unit of CalCOFI Station == 1/15 of a degree at O. By convention, CalCOFI Line/Station conversions use Clarke 1866 but we use whatever ellipsoid is provided. */ #define EPS10 1.e-10 #define DEG_TO_LINE 5 #define DEG_TO_STATION 15 #define LINE_TO_RAD 0.0034906585039886592 #define STATION_TO_RAD 0.0011635528346628863 #define PT_O_LINE 80 /* reference point O is at line 80, */ #define PT_O_STATION 60 /* station 60, */ #define PT_O_LAMBDA -2.1144663887911301 /* long -121.15 and */ #define PT_O_PHI 0.59602993955606354 /* lat 34.15 */ #define ROTATION_ANGLE 0.52359877559829882 /*CalCOFI angle of 30 deg in rad */ static PJ_XY calcofi_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; double oy; /* pt O y value in Mercator */ double l1; /* l1 and l2 are distances calculated using trig that sum to the east/west distance between point O and point xy */ double l2; double ry; /* r is the point on the same station as o (60) and the same line as xy xy, r, o form a right triangle */ if (fabs(fabs(lp.phi) - M_HALFPI) <= EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.x = lp.lam; xy.y = -log(pj_tsfn(lp.phi, sin(lp.phi), P->e)); /* Mercator transform xy*/ oy = -log(pj_tsfn(PT_O_PHI, sin(PT_O_PHI), P->e)); l1 = (xy.y - oy) * tan(ROTATION_ANGLE); l2 = -xy.x - l1 + PT_O_LAMBDA; ry = l2 * cos(ROTATION_ANGLE) * sin(ROTATION_ANGLE) + xy.y; ry = pj_phi2(P->ctx, exp(-ry), P->e); /*inverse Mercator*/ xy.x = PT_O_LINE - RAD_TO_DEG * (ry - PT_O_PHI) * DEG_TO_LINE / cos(ROTATION_ANGLE); xy.y = PT_O_STATION + RAD_TO_DEG * (ry - lp.phi) * DEG_TO_STATION / sin(ROTATION_ANGLE); /* set a = 1, x0 = 0, and y0 = 0 so that no further unit adjustments are done */ return xy; } static PJ_XY calcofi_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double oy; double l1; double l2; double ry; if (fabs(fabs(lp.phi) - M_HALFPI) <= EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.x = lp.lam; xy.y = log(tan(M_FORTPI + .5 * lp.phi)); oy = log(tan(M_FORTPI + .5 * PT_O_PHI)); l1 = (xy.y - oy) * tan(ROTATION_ANGLE); l2 = -xy.x - l1 + PT_O_LAMBDA; ry = l2 * cos(ROTATION_ANGLE) * sin(ROTATION_ANGLE) + xy.y; ry = M_HALFPI - 2. * atan(exp(-ry)); xy.x = PT_O_LINE - RAD_TO_DEG * (ry - PT_O_PHI) * DEG_TO_LINE / cos(ROTATION_ANGLE); xy.y = PT_O_STATION + RAD_TO_DEG * (ry - lp.phi) * DEG_TO_STATION / sin(ROTATION_ANGLE); return xy; } static PJ_LP calcofi_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; double ry; /* y value of point r */ double oymctr; /* Mercator-transformed y value of point O */ double rymctr; /* Mercator-transformed ry */ double xymctr; /* Mercator-transformed xy.y */ double l1; double l2; ry = PT_O_PHI - LINE_TO_RAD * (xy.x - PT_O_LINE) * cos(ROTATION_ANGLE); lp.phi = ry - STATION_TO_RAD * (xy.y - PT_O_STATION) * sin(ROTATION_ANGLE); oymctr = -log(pj_tsfn(PT_O_PHI, sin(PT_O_PHI), P->e)); rymctr = -log(pj_tsfn(ry, sin(ry), P->e)); xymctr = -log(pj_tsfn(lp.phi, sin(lp.phi), P->e)); l1 = (xymctr - oymctr) * tan(ROTATION_ANGLE); l2 = (rymctr - xymctr) / (cos(ROTATION_ANGLE) * sin(ROTATION_ANGLE)); lp.lam = PT_O_LAMBDA - (l1 + l2); return lp; } static PJ_LP calcofi_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double ry; double oymctr; double rymctr; double xymctr; double l1; double l2; (void)P; ry = PT_O_PHI - LINE_TO_RAD * (xy.x - PT_O_LINE) * cos(ROTATION_ANGLE); lp.phi = ry - STATION_TO_RAD * (xy.y - PT_O_STATION) * sin(ROTATION_ANGLE); oymctr = log(tan(M_FORTPI + .5 * PT_O_PHI)); rymctr = log(tan(M_FORTPI + .5 * ry)); xymctr = log(tan(M_FORTPI + .5 * lp.phi)); l1 = (xymctr - oymctr) * tan(ROTATION_ANGLE); l2 = (rymctr - xymctr) / (cos(ROTATION_ANGLE) * sin(ROTATION_ANGLE)); lp.lam = PT_O_LAMBDA - (l1 + l2); return lp; } PJ *PJ_PROJECTION(calcofi) { P->opaque = nullptr; /* if the user has specified +lon_0 or +k0 for some reason, we're going to ignore it so that xy is consistent with point O */ P->lam0 = 0; P->ra = 1; P->a = 1; P->x0 = 0; P->y0 = 0; P->over = 1; if (P->es != 0.0) { /* ellipsoid */ P->inv = calcofi_e_inverse; P->fwd = calcofi_e_forward; } else { /* sphere */ P->inv = calcofi_s_inverse; P->fwd = calcofi_s_forward; } return P; }
cpp
PROJ
data/projects/PROJ/src/projections/som.cpp
/****************************************************************************** * This implements the Space Oblique Mercator (SOM) projection, used by the * Multi-angle Imaging SpectroRadiometer (MISR) products, from the NASA EOS *Terra platform among others (e.g. ASTER). * * This code was originally developed for the Landsat SOM projection with the * following parameters set for Landsat satellites 1, 2, and 3: * * inclination angle = 99.092 degrees * period of revolution = 103.2669323 minutes * ascending longitude = 128.87 degrees - (360 / 251) * path_number * * or for Landsat satellites greater than 3: * * inclination angle = 98.2 degrees * period of revolution = 98.8841202 minutes * ascending longitude = 129.3 degrees - (360 / 233) * path_number * * For the MISR path based SOM projection, the code is identical to that of *Landsat SOM with the following parameter changes: * * inclination angle = 98.30382 degrees * period of revolution = 98.88 minutes * ascending longitude = 129.3056 degrees - (360 / 233) * path_number * * and the following code used for Landsat: * * Q->rlm = PI * (1. / 248. + .5161290322580645); * * changed to: * * Q->rlm = 0 * * For the generic SOM projection, the code is identical to the above for MISR * except that the following parameters are now taken as input rather than *derived from path number: * * inclination angle * period of revolution * ascending longitude * * The change of Q->rlm = 0 is kept. * *****************************************************************************/ /* based upon Snyder and Linck, USGS-NMD */ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(som, "Space Oblique Mercator") "\n\tCyl, Sph&Ell\n\tinc_angle= ps_rev= asc_lon= "; PROJ_HEAD(misrsom, "Space oblique for MISR") "\n\tCyl, Sph&Ell\n\tpath="; PROJ_HEAD(lsat, "Space oblique for LANDSAT") "\n\tCyl, Sph&Ell\n\tlsat= path="; #define TOL 1e-7 namespace { // anonymous namespace struct pj_som_data { double a2, a4, b, c1, c3; double q, t, u, w, p22, sa, ca, xj, rlm, rlm2; double alf; }; } // anonymous namespace static void seraz0(double lam, double mult, PJ *P) { struct pj_som_data *Q = static_cast<struct pj_som_data *>(P->opaque); double sdsq, h, s, fc, sd, sq, d_1 = 0; lam *= DEG_TO_RAD; sd = sin(lam); sdsq = sd * sd; s = Q->p22 * Q->sa * cos(lam) * sqrt((1. + Q->t * sdsq) / ((1. + Q->w * sdsq) * (1. + Q->q * sdsq))); d_1 = 1. + Q->q * sdsq; h = sqrt((1. + Q->q * sdsq) / (1. + Q->w * sdsq)) * ((1. + Q->w * sdsq) / (d_1 * d_1) - Q->p22 * Q->ca); sq = sqrt(Q->xj * Q->xj + s * s); fc = mult * (h * Q->xj - s * s) / sq; Q->b += fc; Q->a2 += fc * cos(lam + lam); Q->a4 += fc * cos(lam * 4.); fc = mult * s * (h + Q->xj) / sq; Q->c1 += fc * cos(lam); Q->c3 += fc * cos(lam * 3.); } static PJ_XY som_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_som_data *Q = static_cast<struct pj_som_data *>(P->opaque); int l, nn; double lamt = 0.0, xlam, sdsq, c, d, s, lamdp = 0.0, phidp, lampp, tanph; double lamtp, cl, sd, sp, sav, tanphi; if (lp.phi > M_HALFPI) lp.phi = M_HALFPI; else if (lp.phi < -M_HALFPI) lp.phi = -M_HALFPI; if (lp.phi >= 0.) lampp = M_HALFPI; else lampp = M_PI_HALFPI; tanphi = tan(lp.phi); for (nn = 0;;) { double fac; sav = lampp; lamtp = lp.lam + Q->p22 * lampp; cl = cos(lamtp); if (cl < 0) fac = lampp + sin(lampp) * M_HALFPI; else fac = lampp - sin(lampp) * M_HALFPI; for (l = 50; l >= 0; --l) { lamt = lp.lam + Q->p22 * sav; c = cos(lamt); if (fabs(c) < TOL) lamt -= TOL; xlam = (P->one_es * tanphi * Q->sa + sin(lamt) * Q->ca) / c; lamdp = atan(xlam) + fac; if (fabs(fabs(sav) - fabs(lamdp)) < TOL) break; sav = lamdp; } if (!l || ++nn >= 3 || (lamdp > Q->rlm && lamdp < Q->rlm2)) break; if (lamdp <= Q->rlm) lampp = M_TWOPI_HALFPI; else if (lamdp >= Q->rlm2) lampp = M_HALFPI; } if (l) { sp = sin(lp.phi); phidp = aasin( P->ctx, (P->one_es * Q->ca * sp - Q->sa * cos(lp.phi) * sin(lamt)) / sqrt(1. - P->es * sp * sp)); tanph = log(tan(M_FORTPI + .5 * phidp)); sd = sin(lamdp); sdsq = sd * sd; s = Q->p22 * Q->sa * cos(lamdp) * sqrt((1. + Q->t * sdsq) / ((1. + Q->w * sdsq) * (1. + Q->q * sdsq))); d = sqrt(Q->xj * Q->xj + s * s); xy.x = Q->b * lamdp + Q->a2 * sin(2. * lamdp) + Q->a4 * sin(lamdp * 4.) - tanph * s / d; xy.y = Q->c1 * sd + Q->c3 * sin(lamdp * 3.) + tanph * Q->xj / d; } else xy.x = xy.y = HUGE_VAL; return xy; } static PJ_LP som_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_som_data *Q = static_cast<struct pj_som_data *>(P->opaque); int nn; double lamt, sdsq, s, lamdp, phidp, sppsq, dd, sd, sl, fac, scl, sav, spp; lamdp = xy.x / Q->b; nn = 50; do { sav = lamdp; sd = sin(lamdp); sdsq = sd * sd; s = Q->p22 * Q->sa * cos(lamdp) * sqrt((1. + Q->t * sdsq) / ((1. + Q->w * sdsq) * (1. + Q->q * sdsq))); lamdp = xy.x + xy.y * s / Q->xj - Q->a2 * sin(2. * lamdp) - Q->a4 * sin(lamdp * 4.) - s / Q->xj * (Q->c1 * sin(lamdp) + Q->c3 * sin(lamdp * 3.)); lamdp /= Q->b; } while (fabs(lamdp - sav) >= TOL && --nn); sl = sin(lamdp); fac = exp(sqrt(1. + s * s / Q->xj / Q->xj) * (xy.y - Q->c1 * sl - Q->c3 * sin(lamdp * 3.))); phidp = 2. * (atan(fac) - M_FORTPI); dd = sl * sl; if (fabs(cos(lamdp)) < TOL) lamdp -= TOL; spp = sin(phidp); sppsq = spp * spp; const double denom = 1. - sppsq * (1. + Q->u); if (denom == 0.0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().lp; } lamt = atan( ((1. - sppsq * P->rone_es) * tan(lamdp) * Q->ca - spp * Q->sa * sqrt((1. + Q->q * dd) * (1. - sppsq) - sppsq * Q->u) / cos(lamdp)) / denom); sl = lamt >= 0. ? 1. : -1.; scl = cos(lamdp) >= 0. ? 1. : -1; lamt -= M_HALFPI * (1. - scl) * sl; lp.lam = lamt - Q->p22 * lamdp; if (fabs(Q->sa) < TOL) lp.phi = aasin(P->ctx, spp / sqrt(P->one_es * P->one_es + P->es * sppsq)); else lp.phi = atan((tan(lamdp) * cos(lamt) - Q->ca * sin(lamt)) / (P->one_es * Q->sa)); return lp; } static PJ *som_setup(PJ *P) { double esc, ess, lam; struct pj_som_data *Q = static_cast<struct pj_som_data *>(P->opaque); Q->sa = sin(Q->alf); Q->ca = cos(Q->alf); if (fabs(Q->ca) < 1e-9) Q->ca = 1e-9; esc = P->es * Q->ca * Q->ca; ess = P->es * Q->sa * Q->sa; Q->w = (1. - esc) * P->rone_es; Q->w = Q->w * Q->w - 1.; Q->q = ess * P->rone_es; Q->t = ess * (2. - P->es) * P->rone_es * P->rone_es; Q->u = esc * P->rone_es; Q->xj = P->one_es * P->one_es * P->one_es; Q->rlm2 = Q->rlm + M_TWOPI; Q->a2 = Q->a4 = Q->b = Q->c1 = Q->c3 = 0.; seraz0(0., 1., P); for (lam = 9.; lam <= 81.0001; lam += 18.) seraz0(lam, 4., P); for (lam = 18; lam <= 72.0001; lam += 18.) seraz0(lam, 2., P); seraz0(90., 1., P); Q->a2 /= 30.; Q->a4 /= 60.; Q->b /= 30.; Q->c1 /= 15.; Q->c3 /= 45.; P->inv = som_e_inverse; P->fwd = som_e_forward; return P; } PJ *PJ_PROJECTION(som) { struct pj_som_data *Q = static_cast<struct pj_som_data *>( calloc(1, sizeof(struct pj_som_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; // ascending longitude (radians) P->lam0 = pj_param(P->ctx, P->params, "rasc_lon").f; if (P->lam0 < -M_TWOPI || P->lam0 > M_TWOPI) { proj_log_error(P, _("Invalid value for ascending longitude: should be in " "[-2pi, 2pi] range")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } // inclination angle (radians) Q->alf = pj_param(P->ctx, P->params, "rinc_angle").f; if (Q->alf < 0 || Q->alf > M_PI) { proj_log_error(P, _("Invalid value for inclination angle: should be in " "[0, pi] range")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } // period of revolution (day / rev) Q->p22 = pj_param(P->ctx, P->params, "dps_rev").f; if (Q->p22 < 0) { proj_log_error(P, _("Number of days per rotation should be positive")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->rlm = 0; return som_setup(P); } PJ *PJ_PROJECTION(misrsom) { int path; struct pj_som_data *Q = static_cast<struct pj_som_data *>( calloc(1, sizeof(struct pj_som_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; path = pj_param(P->ctx, P->params, "ipath").i; if (path <= 0 || path > 233) { proj_log_error( P, _("Invalid value for path: path should be in [1, 233] range")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->lam0 = DEG_TO_RAD * 129.3056 - M_TWOPI / 233. * path; Q->alf = 98.30382 * DEG_TO_RAD; Q->p22 = 98.88 / 1440.0; Q->rlm = 0; return som_setup(P); } PJ *PJ_PROJECTION(lsat) { int land, path; struct pj_som_data *Q = static_cast<struct pj_som_data *>( calloc(1, sizeof(struct pj_som_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; land = pj_param(P->ctx, P->params, "ilsat").i; if (land <= 0 || land > 5) { proj_log_error( P, _("Invalid value for lsat: lsat should be in [1, 5] range")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } path = pj_param(P->ctx, P->params, "ipath").i; const int maxPathVal = (land <= 3 ? 251 : 233); if (path <= 0 || path > maxPathVal) { proj_log_error( P, _("Invalid value for path: path should be in [1, %d] range"), maxPathVal); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (land <= 3) { P->lam0 = DEG_TO_RAD * 128.87 - M_TWOPI / 251. * path; Q->p22 = 103.2669323; Q->alf = DEG_TO_RAD * 99.092; } else { P->lam0 = DEG_TO_RAD * 129.3 - M_TWOPI / 233. * path; Q->p22 = 98.8841202; Q->alf = DEG_TO_RAD * 98.2; } Q->p22 /= 1440.; Q->rlm = M_PI * (1. / 248. + .5161290322580645); return som_setup(P); } #undef TOL
cpp
PROJ
data/projects/PROJ/src/projections/times.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the Times projection. * Author: Kristian Evers <[email protected]> * ****************************************************************************** * Copyright (c) 2016, Kristian Evers * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ***************************************************************************** * Based on description of the Times Projection in * * Flattening the Earth, Snyder, J.P., 1993, p.213-214. *****************************************************************************/ #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(times, "Times") "\n\tCyl, Sph"; static PJ_XY times_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ double T, S, S2; PJ_XY xy = {0.0, 0.0}; (void)P; T = tan(lp.phi / 2.0); S = sin(M_FORTPI * T); S2 = S * S; xy.x = lp.lam * (0.74482 - 0.34588 * S2); xy.y = 1.70711 * T; return xy; } static PJ_LP times_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ double T, S, S2; PJ_LP lp = {0.0, 0.0}; (void)P; T = xy.y / 1.70711; S = sin(M_FORTPI * T); S2 = S * S; lp.lam = xy.x / (0.74482 - 0.34588 * S2); lp.phi = 2 * atan(T); return lp; } PJ *PJ_PROJECTION(times) { P->es = 0.0; P->inv = times_s_inverse; P->fwd = times_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/goode.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(goode, "Goode Homolosine") "\n\tPCyl, Sph"; #define Y_COR 0.05280 #define PHI_LIM 0.71093078197902358062 C_NAMESPACE PJ *pj_sinu(PJ *), *pj_moll(PJ *); namespace { // anonymous namespace struct pj_goode_data { PJ *sinu; PJ *moll; }; } // anonymous namespace static PJ_XY goode_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy; struct pj_goode_data *Q = static_cast<struct pj_goode_data *>(P->opaque); if (fabs(lp.phi) <= PHI_LIM) xy = Q->sinu->fwd(lp, Q->sinu); else { xy = Q->moll->fwd(lp, Q->moll); xy.y -= lp.phi >= 0.0 ? Y_COR : -Y_COR; } return xy; } static PJ_LP goode_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp; struct pj_goode_data *Q = static_cast<struct pj_goode_data *>(P->opaque); if (fabs(xy.y) <= PHI_LIM) lp = Q->sinu->inv(xy, Q->sinu); else { xy.y += xy.y >= 0.0 ? Y_COR : -Y_COR; lp = Q->moll->inv(xy, Q->moll); } return lp; } static PJ *goode_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); proj_destroy(static_cast<struct pj_goode_data *>(P->opaque)->sinu); proj_destroy(static_cast<struct pj_goode_data *>(P->opaque)->moll); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(goode) { struct pj_goode_data *Q = static_cast<struct pj_goode_data *>( calloc(1, sizeof(struct pj_goode_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = goode_destructor; P->es = 0.; Q->sinu = pj_sinu(nullptr); Q->moll = pj_moll(nullptr); if (Q->sinu == nullptr || Q->moll == nullptr) return goode_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->sinu->es = 0.; Q->sinu->ctx = P->ctx; Q->moll->ctx = P->ctx; Q->sinu = pj_sinu(Q->sinu); Q->moll = pj_moll(Q->moll); if (Q->sinu == nullptr || Q->moll == nullptr) return goode_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->fwd = goode_s_forward; P->inv = goode_s_inverse; return P; } #undef Y_COR #undef PHI_LIM
cpp
PROJ
data/projects/PROJ/src/projections/eck3.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(eck3, "Eckert III") "\n\tPCyl, Sph"; PROJ_HEAD(putp1, "Putnins P1") "\n\tPCyl, Sph"; PROJ_HEAD(wag6, "Wagner VI") "\n\tPCyl, Sph"; PROJ_HEAD(kav7, "Kavrayskiy VII") "\n\tPCyl, Sph"; namespace { // anonymous namespace struct pj_opaque { double C_x, C_y, A, B; }; } // anonymous namespace static PJ_XY eck3_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); xy.y = Q->C_y * lp.phi; xy.x = Q->C_x * lp.lam * (Q->A + asqrt(1. - Q->B * lp.phi * lp.phi)); return xy; } static PJ_LP eck3_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); double denominator; lp.phi = xy.y / Q->C_y; denominator = (Q->C_x * (Q->A + asqrt(1. - Q->B * lp.phi * lp.phi))); if (denominator == 0.0) lp.lam = HUGE_VAL; else lp.lam = xy.x / denominator; return lp; } static PJ *setup(PJ *P) { P->es = 0.; P->inv = eck3_s_inverse; P->fwd = eck3_s_forward; return P; } PJ *PJ_PROJECTION(eck3) { struct pj_opaque *Q = static_cast<struct pj_opaque *>(calloc(1, sizeof(struct pj_opaque))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->C_x = 0.42223820031577120149; Q->C_y = 0.84447640063154240298; Q->A = 1.0; Q->B = 0.4052847345693510857755; return setup(P); } PJ *PJ_PROJECTION(kav7) { struct pj_opaque *Q = static_cast<struct pj_opaque *>(calloc(1, sizeof(struct pj_opaque))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* Defined twice in original code - Using 0.866..., * but leaving the other one here as a safety measure. * Q->C_x = 0.2632401569273184856851; */ Q->C_x = 0.8660254037844; Q->C_y = 1.; Q->A = 0.; Q->B = 0.30396355092701331433; return setup(P); } PJ *PJ_PROJECTION(wag6) { struct pj_opaque *Q = static_cast<struct pj_opaque *>(calloc(1, sizeof(struct pj_opaque))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->C_x = 0.94745; Q->C_y = 0.94745; Q->A = 0.0; Q->B = 0.30396355092701331433; return setup(P); } PJ *PJ_PROJECTION(putp1) { struct pj_opaque *Q = static_cast<struct pj_opaque *>(calloc(1, sizeof(struct pj_opaque))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->C_x = 1.89490; Q->C_y = 0.94745; Q->A = -0.5; Q->B = 0.30396355092701331433; return setup(P); }
cpp
PROJ
data/projects/PROJ/src/projections/airy.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the airy (Airy) projection. * Author: Gerald Evenden (1995) * Thomas Knudsen (2016) - revise/add regression tests * ****************************************************************************** * Copyright (c) 1995, Gerald Evenden * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #include "proj.h" #include "proj_internal.h" #include <errno.h> PROJ_HEAD(airy, "Airy") "\n\tMisc Sph, no inv\n\tno_cut lat_b="; namespace { // anonymous namespace enum Mode { N_POLE = 0, S_POLE = 1, EQUIT = 2, OBLIQ = 3 }; } // anonymous namespace namespace { // anonymous namespace struct pj_airy { double p_halfpi; double sinph0; double cosph0; double Cb; enum Mode mode; int no_cut; /* do not cut at hemisphere limit */ }; } // anonymous namespace #define EPS 1.e-10 static PJ_XY airy_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_airy *Q = static_cast<struct pj_airy *>(P->opaque); double sinlam, coslam, cosphi, sinphi, t, s, Krho, cosz; sinlam = sin(lp.lam); coslam = cos(lp.lam); switch (Q->mode) { case EQUIT: case OBLIQ: sinphi = sin(lp.phi); cosphi = cos(lp.phi); cosz = cosphi * coslam; if (Q->mode == OBLIQ) cosz = Q->sinph0 * sinphi + Q->cosph0 * cosz; if (!Q->no_cut && cosz < -EPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } s = 1. - cosz; if (fabs(s) > EPS) { t = 0.5 * (1. + cosz); if (t == 0) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } Krho = -log(t) / s - Q->Cb / t; } else Krho = 0.5 - Q->Cb; xy.x = Krho * cosphi * sinlam; if (Q->mode == OBLIQ) xy.y = Krho * (Q->cosph0 * sinphi - Q->sinph0 * cosphi * coslam); else xy.y = Krho * sinphi; break; case S_POLE: case N_POLE: lp.phi = fabs(Q->p_halfpi - lp.phi); if (!Q->no_cut && (lp.phi - EPS) > M_HALFPI) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } lp.phi *= 0.5; if (lp.phi > EPS) { t = tan(lp.phi); Krho = -2. * (log(cos(lp.phi)) / t + t * Q->Cb); xy.x = Krho * sinlam; xy.y = Krho * coslam; if (Q->mode == N_POLE) xy.y = -xy.y; } else xy.x = xy.y = 0.; } return xy; } PJ *PJ_PROJECTION(airy) { double beta; struct pj_airy *Q = static_cast<struct pj_airy *>(calloc(1, sizeof(struct pj_airy))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->no_cut = pj_param(P->ctx, P->params, "bno_cut").i; beta = 0.5 * (M_HALFPI - pj_param(P->ctx, P->params, "rlat_b").f); if (fabs(beta) < EPS) Q->Cb = -0.5; else { Q->Cb = 1. / tan(beta); Q->Cb *= Q->Cb * log(cos(beta)); } if (fabs(fabs(P->phi0) - M_HALFPI) < EPS) if (P->phi0 < 0.) { Q->p_halfpi = -M_HALFPI; Q->mode = S_POLE; } else { Q->p_halfpi = M_HALFPI; Q->mode = N_POLE; } else { if (fabs(P->phi0) < EPS) Q->mode = EQUIT; else { Q->mode = OBLIQ; Q->sinph0 = sin(P->phi0); Q->cosph0 = cos(P->phi0); } } P->fwd = airy_s_forward; P->es = 0.; return P; } #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/lcc.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(lcc, "Lambert Conformal Conic") "\n\tConic, Sph&Ell\n\tlat_1= and lat_2= or lat_0, k_0="; #define EPS10 1.e-10 namespace { // anonymous namespace struct pj_lcc_data { double phi1; double phi2; double n; double rho0; double c; }; } // anonymous namespace static PJ_XY lcc_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0., 0.}; struct pj_lcc_data *Q = static_cast<struct pj_lcc_data *>(P->opaque); double rho; if (fabs(fabs(lp.phi) - M_HALFPI) < EPS10) { if ((lp.phi * Q->n) <= 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } rho = 0.; } else { rho = Q->c * (P->es != 0. ? pow(pj_tsfn(lp.phi, sin(lp.phi), P->e), Q->n) : pow(tan(M_FORTPI + .5 * lp.phi), -Q->n)); } lp.lam *= Q->n; xy.x = P->k0 * (rho * sin(lp.lam)); xy.y = P->k0 * (Q->rho0 - rho * cos(lp.lam)); return xy; } static PJ_LP lcc_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0., 0.}; struct pj_lcc_data *Q = static_cast<struct pj_lcc_data *>(P->opaque); double rho; xy.x /= P->k0; xy.y /= P->k0; xy.y = Q->rho0 - xy.y; rho = hypot(xy.x, xy.y); if (rho != 0.) { if (Q->n < 0.) { rho = -rho; xy.x = -xy.x; xy.y = -xy.y; } if (P->es != 0.) { lp.phi = pj_phi2(P->ctx, pow(rho / Q->c, 1. / Q->n), P->e); if (lp.phi == HUGE_VAL) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } } else lp.phi = 2. * atan(pow(Q->c / rho, 1. / Q->n)) - M_HALFPI; lp.lam = atan2(xy.x, xy.y) / Q->n; } else { lp.lam = 0.; lp.phi = Q->n > 0. ? M_HALFPI : -M_HALFPI; } return lp; } PJ *PJ_PROJECTION(lcc) { double cosphi, sinphi; int secant; struct pj_lcc_data *Q = static_cast<struct pj_lcc_data *>( calloc(1, sizeof(struct pj_lcc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->phi1 = pj_param(P->ctx, P->params, "rlat_1").f; if (pj_param(P->ctx, P->params, "tlat_2").i) Q->phi2 = pj_param(P->ctx, P->params, "rlat_2").f; else { Q->phi2 = Q->phi1; if (!pj_param(P->ctx, P->params, "tlat_0").i) P->phi0 = Q->phi1; } if (fabs(Q->phi1 + Q->phi2) < EPS10) { proj_log_error(P, _("Invalid value for lat_1 and lat_2: |lat_1 + " "lat_2| should be > 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->n = sinphi = sin(Q->phi1); cosphi = cos(Q->phi1); if (fabs(cosphi) < EPS10 || fabs(Q->phi1) >= M_PI_2) { proj_log_error(P, _("Invalid value for lat_1: |lat_1| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(cos(Q->phi2)) < EPS10 || fabs(Q->phi2) >= M_PI_2) { proj_log_error(P, _("Invalid value for lat_2: |lat_2| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } secant = fabs(Q->phi1 - Q->phi2) >= EPS10; if (P->es != 0.) { double ml1, m1; m1 = pj_msfn(sinphi, cosphi, P->es); ml1 = pj_tsfn(Q->phi1, sinphi, P->e); if (secant) { /* secant cone */ sinphi = sin(Q->phi2); Q->n = log(m1 / pj_msfn(sinphi, cos(Q->phi2), P->es)); if (Q->n == 0) { // Not quite, but es is very close to 1... proj_log_error(P, _("Invalid value for eccentricity")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } const double ml2 = pj_tsfn(Q->phi2, sinphi, P->e); const double denom = log(ml1 / ml2); if (denom == 0) { // Not quite, but es is very close to 1... proj_log_error(P, _("Invalid value for eccentricity")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->n /= denom; } Q->rho0 = m1 * pow(ml1, -Q->n) / Q->n; Q->c = Q->rho0; Q->rho0 *= (fabs(fabs(P->phi0) - M_HALFPI) < EPS10) ? 0. : pow(pj_tsfn(P->phi0, sin(P->phi0), P->e), Q->n); } else { if (secant) Q->n = log(cosphi / cos(Q->phi2)) / log(tan(M_FORTPI + .5 * Q->phi2) / tan(M_FORTPI + .5 * Q->phi1)); if (Q->n == 0) { // Likely reason is that phi1 / phi2 are too close to zero. // Can be reproduced with +proj=lcc +a=1 +lat_2=.0000001 proj_log_error( P, _("Invalid value for lat_1 and lat_2: |lat_1 + lat_2| " "should be > 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->c = cosphi * pow(tan(M_FORTPI + .5 * Q->phi1), Q->n) / Q->n; Q->rho0 = (fabs(fabs(P->phi0) - M_HALFPI) < EPS10) ? 0. : Q->c * pow(tan(M_FORTPI + .5 * P->phi0), -Q->n); } P->inv = lcc_e_inverse; P->fwd = lcc_e_forward; return P; } #undef EPS10
cpp
PROJ
data/projects/PROJ/src/projections/sterea.cpp
/* ** libproj -- library of cartographic projections ** ** Copyright (c) 2003 Gerald I. Evenden */ /* ** Permission is hereby granted, free of charge, to any person obtaining ** a copy of this software and associated documentation files (the ** "Software"), to deal in the Software without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Software, and to ** permit persons to whom the Software is furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> namespace { // anonymous namespace struct pj_opaque { double phic0; double cosc0, sinc0; double R2; void *en; }; } // anonymous namespace PROJ_HEAD(sterea, "Oblique Stereographic Alternative") "\n\tAzimuthal, Sph&Ell"; static PJ_XY sterea_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); double cosc, sinc, cosl, k; lp = pj_gauss(P->ctx, lp, Q->en); sinc = sin(lp.phi); cosc = cos(lp.phi); cosl = cos(lp.lam); const double denom = 1. + Q->sinc0 * sinc + Q->cosc0 * cosc * cosl; if (denom == 0.0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } k = P->k0 * Q->R2 / denom; xy.x = k * cosc * sin(lp.lam); xy.y = k * (Q->cosc0 * sinc - Q->sinc0 * cosc * cosl); return xy; } static PJ_LP sterea_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); double rho, c, sinc, cosc; xy.x /= P->k0; xy.y /= P->k0; if ((rho = hypot(xy.x, xy.y)) != 0.0) { c = 2. * atan2(rho, Q->R2); sinc = sin(c); cosc = cos(c); lp.phi = asin(cosc * Q->sinc0 + xy.y * sinc * Q->cosc0 / rho); lp.lam = atan2(xy.x * sinc, rho * Q->cosc0 * cosc - xy.y * Q->sinc0 * sinc); } else { lp.phi = Q->phic0; lp.lam = 0.; } return pj_inv_gauss(P->ctx, lp, Q->en); } static PJ *destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_opaque *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(sterea) { double R; struct pj_opaque *Q = static_cast<struct pj_opaque *>(calloc(1, sizeof(struct pj_opaque))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->en = pj_gauss_ini(P->e, P->phi0, &(Q->phic0), &R); if (nullptr == Q->en) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->sinc0 = sin(Q->phic0); Q->cosc0 = cos(Q->phic0); Q->R2 = 2. * R; P->inv = sterea_e_inverse; P->fwd = sterea_e_forward; P->destructor = destructor; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/merc.cpp
#include <float.h> #include <math.h> #include "proj.h" #include "proj_internal.h" #include <math.h> PROJ_HEAD(merc, "Mercator") "\n\tCyl, Sph&Ell\n\tlat_ts="; PROJ_HEAD(webmerc, "Web Mercator / Pseudo Mercator") "\n\tCyl, Ell\n\t"; static PJ_XY merc_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = P->k0 * lp.lam; // Instead of calling tan and sin, call sin and cos which the compiler // optimizes to a single call to sincos. double sphi = sin(lp.phi); double cphi = cos(lp.phi); xy.y = P->k0 * (asinh(sphi / cphi) - P->e * atanh(P->e * sphi)); return xy; } static PJ_XY merc_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = P->k0 * lp.lam; xy.y = P->k0 * asinh(tan(lp.phi)); return xy; } static PJ_LP merc_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = atan(pj_sinhpsi2tanphi(P->ctx, sinh(xy.y / P->k0), P->e)); lp.lam = xy.x / P->k0; return lp; } static PJ_LP merc_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = atan(sinh(xy.y / P->k0)); lp.lam = xy.x / P->k0; return lp; } PJ *PJ_PROJECTION(merc) { double phits = 0.0; int is_phits; if ((is_phits = pj_param(P->ctx, P->params, "tlat_ts").i)) { phits = fabs(pj_param(P->ctx, P->params, "rlat_ts").f); if (phits >= M_HALFPI) { proj_log_error( P, _("Invalid value for lat_ts: |lat_ts| should be <= 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (P->es != 0.0) { /* ellipsoid */ if (is_phits) P->k0 = pj_msfn(sin(phits), cos(phits), P->es); P->inv = merc_e_inverse; P->fwd = merc_e_forward; } else { /* sphere */ if (is_phits) P->k0 = cos(phits); P->inv = merc_s_inverse; P->fwd = merc_s_forward; } return P; } PJ *PJ_PROJECTION(webmerc) { /* Overriding k_0 with fixed parameter */ P->k0 = 1.0; P->inv = merc_s_inverse; P->fwd = merc_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/moll.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(moll, "Mollweide") "\n\tPCyl, Sph"; PROJ_HEAD(wag4, "Wagner IV") "\n\tPCyl, Sph"; PROJ_HEAD(wag5, "Wagner V") "\n\tPCyl, Sph"; #define MAX_ITER 30 #define LOOP_TOL 1e-7 namespace { // anonymous namespace struct pj_moll_data { double C_x, C_y, C_p; }; } // anonymous namespace static PJ_XY moll_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_moll_data *Q = static_cast<struct pj_moll_data *>(P->opaque); int i; const double k = Q->C_p * sin(lp.phi); for (i = MAX_ITER; i; --i) { const double V = (lp.phi + sin(lp.phi) - k) / (1. + cos(lp.phi)); lp.phi -= V; if (fabs(V) < LOOP_TOL) break; } if (!i) lp.phi = (lp.phi < 0.) ? -M_HALFPI : M_HALFPI; else lp.phi *= 0.5; xy.x = Q->C_x * lp.lam * cos(lp.phi); xy.y = Q->C_y * sin(lp.phi); return xy; } static PJ_LP moll_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_moll_data *Q = static_cast<struct pj_moll_data *>(P->opaque); lp.phi = aasin(P->ctx, xy.y / Q->C_y); lp.lam = xy.x / (Q->C_x * cos(lp.phi)); if (fabs(lp.lam) < M_PI) { lp.phi += lp.phi; lp.phi = aasin(P->ctx, (lp.phi + sin(lp.phi)) / Q->C_p); } else { lp.lam = lp.phi = HUGE_VAL; } return lp; } static PJ *setup(PJ *P, double p) { struct pj_moll_data *Q = static_cast<struct pj_moll_data *>(P->opaque); double r, sp, p2 = p + p; P->es = 0; sp = sin(p); r = sqrt(M_TWOPI * sp / (p2 + sin(p2))); Q->C_x = 2. * r / M_PI; Q->C_y = r / sp; Q->C_p = p2 + sin(p2); P->inv = moll_s_inverse; P->fwd = moll_s_forward; return P; } PJ *PJ_PROJECTION(moll) { struct pj_moll_data *Q = static_cast<struct pj_moll_data *>( calloc(1, sizeof(struct pj_moll_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; return setup(P, M_HALFPI); } PJ *PJ_PROJECTION(wag4) { struct pj_moll_data *Q = static_cast<struct pj_moll_data *>( calloc(1, sizeof(struct pj_moll_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; return setup(P, M_PI / 3.); } PJ *PJ_PROJECTION(wag5) { struct pj_moll_data *Q = static_cast<struct pj_moll_data *>( calloc(1, sizeof(struct pj_moll_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->es = 0; Q->C_x = 0.90977; Q->C_y = 1.65014; Q->C_p = 3.00896; P->inv = moll_s_inverse; P->fwd = moll_s_forward; return P; } #undef MAX_ITER #undef LOOP_TOL
cpp
PROJ
data/projects/PROJ/src/projections/robin.cpp
#include "proj.h" #include "proj_internal.h" #include <math.h> PROJ_HEAD(robin, "Robinson") "\n\tPCyl, Sph"; #define V(C, z) (C.c0 + z * (C.c1 + z * (C.c2 + z * C.c3))) #define DV(C, z) (C.c1 + 2 * z * C.c2 + z * z * 3. * C.c3) /* note: following terms based upon 5 deg. intervals in degrees. Some background on these coefficients is available at: http://article.gmane.org/gmane.comp.gis.proj-4.devel/6039 http://trac.osgeo.org/proj/ticket/113 */ namespace { // anonymous namespace struct COEFS { float c0, c1, c2, c3; }; } // anonymous namespace static const struct COEFS X[] = { {1.0f, 2.2199e-17f, -7.15515e-05f, 3.1103e-06f}, {0.9986f, -0.000482243f, -2.4897e-05f, -1.3309e-06f}, {0.9954f, -0.00083103f, -4.48605e-05f, -9.86701e-07f}, {0.99f, -0.00135364f, -5.9661e-05f, 3.6777e-06f}, {0.9822f, -0.00167442f, -4.49547e-06f, -5.72411e-06f}, {0.973f, -0.00214868f, -9.03571e-05f, 1.8736e-08f}, {0.96f, -0.00305085f, -9.00761e-05f, 1.64917e-06f}, {0.9427f, -0.00382792f, -6.53386e-05f, -2.6154e-06f}, {0.9216f, -0.00467746f, -0.00010457f, 4.81243e-06f}, {0.8962f, -0.00536223f, -3.23831e-05f, -5.43432e-06f}, {0.8679f, -0.00609363f, -0.000113898f, 3.32484e-06f}, {0.835f, -0.00698325f, -6.40253e-05f, 9.34959e-07f}, {0.7986f, -0.00755338f, -5.00009e-05f, 9.35324e-07f}, {0.7597f, -0.00798324f, -3.5971e-05f, -2.27626e-06f}, {0.7186f, -0.00851367f, -7.01149e-05f, -8.6303e-06f}, {0.6732f, -0.00986209f, -0.000199569f, 1.91974e-05f}, {0.6213f, -0.010418f, 8.83923e-05f, 6.24051e-06f}, {0.5722f, -0.00906601f, 0.000182f, 6.24051e-06f}, {0.5322f, -0.00677797f, 0.000275608f, 6.24051e-06f}}; static const struct COEFS Y[] = { {-5.20417e-18f, 0.0124f, 1.21431e-18f, -8.45284e-11f}, {0.062f, 0.0124f, -1.26793e-09f, 4.22642e-10f}, {0.124f, 0.0124f, 5.07171e-09f, -1.60604e-09f}, {0.186f, 0.0123999f, -1.90189e-08f, 6.00152e-09f}, {0.248f, 0.0124002f, 7.10039e-08f, -2.24e-08f}, {0.31f, 0.0123992f, -2.64997e-07f, 8.35986e-08f}, {0.372f, 0.0124029f, 9.88983e-07f, -3.11994e-07f}, {0.434f, 0.0123893f, -3.69093e-06f, -4.35621e-07f}, {0.4958f, 0.0123198f, -1.02252e-05f, -3.45523e-07f}, {0.5571f, 0.0121916f, -1.54081e-05f, -5.82288e-07f}, {0.6176f, 0.0119938f, -2.41424e-05f, -5.25327e-07f}, {0.6769f, 0.011713f, -3.20223e-05f, -5.16405e-07f}, {0.7346f, 0.0113541f, -3.97684e-05f, -6.09052e-07f}, {0.7903f, 0.0109107f, -4.89042e-05f, -1.04739e-06f}, {0.8435f, 0.0103431f, -6.4615e-05f, -1.40374e-09f}, {0.8936f, 0.00969686f, -6.4636e-05f, -8.547e-06f}, {0.9394f, 0.00840947f, -0.000192841f, -4.2106e-06f}, {0.9761f, 0.00616527f, -0.000256f, -4.2106e-06f}, {1.0f, 0.00328947f, -0.000319159f, -4.2106e-06f}}; #define FXC 0.8487 #define FYC 1.3523 #define C1 11.45915590261646417544 #define RC1 0.08726646259971647884 #define NODES 18 #define ONEEPS 1.000001 #define EPS 1e-10 /* Not sure at all of the appropriate number for MAX_ITER... */ #define MAX_ITER 100 static PJ_XY robin_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; long i; double dphi; (void)P; dphi = fabs(lp.phi); i = isnan(lp.phi) ? -1 : lround(floor(dphi * C1 + 1e-15)); if (i < 0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } if (i >= NODES) i = NODES; dphi = RAD_TO_DEG * (dphi - RC1 * i); xy.x = V(X[i], dphi) * FXC * lp.lam; xy.y = V(Y[i], dphi) * FYC; if (lp.phi < 0.) xy.y = -xy.y; return xy; } static PJ_LP robin_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double t; struct COEFS T; int iters; lp.lam = xy.x / FXC; lp.phi = fabs(xy.y / FYC); if (lp.phi >= 1.) { /* simple pathologic cases */ if (lp.phi > ONEEPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { lp.phi = xy.y < 0. ? -M_HALFPI : M_HALFPI; lp.lam /= X[NODES].c0; } } else { /* general problem */ /* in Y space, reduce to table interval */ long i = isnan(lp.phi) ? -1 : lround(floor(lp.phi * NODES)); if (i < 0 || i >= NODES) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } for (;;) { if (Y[i].c0 > lp.phi) --i; else if (Y[i + 1].c0 <= lp.phi) ++i; else break; } T = Y[i]; /* first guess, linear interp */ t = 5. * (lp.phi - T.c0) / (Y[i + 1].c0 - T.c0); for (iters = MAX_ITER; iters; --iters) { /* Newton-Raphson */ const double t1 = (V(T, t) - lp.phi) / DV(T, t); t -= t1; if (fabs(t1) < EPS) break; } if (iters == 0) proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.phi = (5 * i + t) * DEG_TO_RAD; if (xy.y < 0.) lp.phi = -lp.phi; lp.lam /= V(X[i], t); if (fabs(lp.lam) > M_PI) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp = proj_coord_error().lp; } } return lp; } PJ *PJ_PROJECTION(robin) { P->es = 0.; P->inv = robin_s_inverse; P->fwd = robin_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/geos.cpp
/* ** libproj -- library of cartographic projections ** ** Copyright (c) 2004 Gerald I. Evenden ** Copyright (c) 2012 Martin Raspaud ** ** See also (section 4.4.3.2): ** https://www.cgms-info.org/documents/pdf_cgms_03.pdf ** ** Permission is hereby granted, free of charge, to any person obtaining ** a copy of this software and associated documentation files (the ** "Software"), to deal in the Software without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Software, and to ** permit persons to whom the Software is furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <errno.h> #include <math.h> #include <stddef.h> #include "proj.h" #include "proj_internal.h" #include <math.h> namespace { // anonymous namespace struct pj_geos_data { double h; double radius_p; double radius_p2; double radius_p_inv2; double radius_g; double radius_g_1; double C; int flip_axis; }; } // anonymous namespace PROJ_HEAD(geos, "Geostationary Satellite View") "\n\tAzi, Sph&Ell\n\th="; static PJ_XY geos_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_geos_data *Q = static_cast<struct pj_geos_data *>(P->opaque); double Vx, Vy, Vz, tmp; /* Calculation of the three components of the vector from satellite to ** position on earth surface (long,lat).*/ tmp = cos(lp.phi); Vx = cos(lp.lam) * tmp; Vy = sin(lp.lam) * tmp; Vz = sin(lp.phi); /* Check visibility*/ /* Calculation based on view angles from satellite.*/ tmp = Q->radius_g - Vx; if (Q->flip_axis) { xy.x = Q->radius_g_1 * atan(Vy / hypot(Vz, tmp)); xy.y = Q->radius_g_1 * atan(Vz / tmp); } else { xy.x = Q->radius_g_1 * atan(Vy / tmp); xy.y = Q->radius_g_1 * atan(Vz / hypot(Vy, tmp)); } return xy; } static PJ_XY geos_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_geos_data *Q = static_cast<struct pj_geos_data *>(P->opaque); double r, Vx, Vy, Vz, tmp; /* Calculation of geocentric latitude. */ lp.phi = atan(Q->radius_p2 * tan(lp.phi)); /* Calculation of the three components of the vector from satellite to ** position on earth surface (long,lat).*/ r = (Q->radius_p) / hypot(Q->radius_p * cos(lp.phi), sin(lp.phi)); Vx = r * cos(lp.lam) * cos(lp.phi); Vy = r * sin(lp.lam) * cos(lp.phi); Vz = r * sin(lp.phi); /* Check visibility. */ if (((Q->radius_g - Vx) * Vx - Vy * Vy - Vz * Vz * Q->radius_p_inv2) < 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } /* Calculation based on view angles from satellite. */ tmp = Q->radius_g - Vx; if (Q->flip_axis) { xy.x = Q->radius_g_1 * atan(Vy / hypot(Vz, tmp)); xy.y = Q->radius_g_1 * atan(Vz / tmp); } else { xy.x = Q->radius_g_1 * atan(Vy / tmp); xy.y = Q->radius_g_1 * atan(Vz / hypot(Vy, tmp)); } return xy; } static PJ_LP geos_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_geos_data *Q = static_cast<struct pj_geos_data *>(P->opaque); double Vx, Vy, Vz, a, b, k; /* Setting three components of vector from satellite to position.*/ Vx = -1.0; if (Q->flip_axis) { Vz = tan(xy.y / Q->radius_g_1); Vy = tan(xy.x / Q->radius_g_1) * sqrt(1.0 + Vz * Vz); } else { Vy = tan(xy.x / Q->radius_g_1); Vz = tan(xy.y / Q->radius_g_1) * sqrt(1.0 + Vy * Vy); } /* Calculation of terms in cubic equation and determinant.*/ a = Vy * Vy + Vz * Vz + Vx * Vx; b = 2 * Q->radius_g * Vx; const double det = (b * b) - 4 * a * Q->C; if (det < 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } /* Calculation of three components of vector from satellite to position.*/ k = (-b - sqrt(det)) / (2 * a); Vx = Q->radius_g + k * Vx; Vy *= k; Vz *= k; /* Calculation of longitude and latitude.*/ lp.lam = atan2(Vy, Vx); lp.phi = atan(Vz * cos(lp.lam) / Vx); return lp; } static PJ_LP geos_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_geos_data *Q = static_cast<struct pj_geos_data *>(P->opaque); double Vx, Vy, Vz, a, b, k; /* Setting three components of vector from satellite to position.*/ Vx = -1.0; if (Q->flip_axis) { Vz = tan(xy.y / Q->radius_g_1); Vy = tan(xy.x / Q->radius_g_1) * hypot(1.0, Vz); } else { Vy = tan(xy.x / Q->radius_g_1); Vz = tan(xy.y / Q->radius_g_1) * hypot(1.0, Vy); } /* Calculation of terms in cubic equation and determinant.*/ a = Vz / Q->radius_p; a = Vy * Vy + a * a + Vx * Vx; b = 2 * Q->radius_g * Vx; const double det = (b * b) - 4 * a * Q->C; if (det < 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } /* Calculation of three components of vector from satellite to position.*/ k = (-b - sqrt(det)) / (2. * a); Vx = Q->radius_g + k * Vx; Vy *= k; Vz *= k; /* Calculation of longitude and latitude.*/ lp.lam = atan2(Vy, Vx); lp.phi = atan(Vz * cos(lp.lam) / Vx); lp.phi = atan(Q->radius_p_inv2 * tan(lp.phi)); return lp; } PJ *PJ_PROJECTION(geos) { char *sweep_axis; struct pj_geos_data *Q = static_cast<struct pj_geos_data *>( calloc(1, sizeof(struct pj_geos_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->h = pj_param(P->ctx, P->params, "dh").f; sweep_axis = pj_param(P->ctx, P->params, "ssweep").s; if (sweep_axis == nullptr) Q->flip_axis = 0; else { if ((sweep_axis[0] != 'x' && sweep_axis[0] != 'y') || sweep_axis[1] != '\0') { proj_log_error( P, _("Invalid value for sweep: it should be equal to x or y.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (sweep_axis[0] == 'x') Q->flip_axis = 1; else Q->flip_axis = 0; } Q->radius_g_1 = Q->h / P->a; if (Q->radius_g_1 <= 0 || Q->radius_g_1 > 1e10) { proj_log_error(P, _("Invalid value for h.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->radius_g = 1. + Q->radius_g_1; Q->C = Q->radius_g * Q->radius_g - 1.0; if (P->es != 0.0) { Q->radius_p = sqrt(P->one_es); Q->radius_p2 = P->one_es; Q->radius_p_inv2 = P->rone_es; P->inv = geos_e_inverse; P->fwd = geos_e_forward; } else { Q->radius_p = Q->radius_p2 = Q->radius_p_inv2 = 1.0; P->inv = geos_s_inverse; P->fwd = geos_s_forward; } return P; }
cpp
PROJ
data/projects/PROJ/src/projections/lcca.cpp
/***************************************************************************** Lambert Conformal Conic Alternative ----------------------------------- This is Gerald Evenden's 2003 implementation of an alternative "almost" LCC, which has been in use historically, but which should NOT be used for new projects - i.e: use this implementation if you need interoperability with old data represented in this projection, but not in any other case. The code was originally discussed on the PROJ.4 mailing list in a thread archived over at http://lists.maptools.org/pipermail/proj/2003-March/000644.html It was discussed again in the thread starting at http://lists.maptools.org/pipermail/proj/2017-October/007828.html and continuing at http://lists.maptools.org/pipermail/proj/2017-November/007831.html which prompted Clifford J. Mugnier to add these clarifying notes: The French Army Truncated Cubic Lambert (partially conformal) Conic projection is the Legal system for the projection in France between the late 1800s and 1948 when the French Legislature changed the law to recognize the fully conformal version. It was (might still be in one or two North African prior French Colonies) used in North Africa in Algeria, Tunisia, & Morocco, as well as in Syria during the Levant. Last time I have seen it used was about 30+ years ago in Algeria when it was used to define Lease Block boundaries for Petroleum Exploration & Production. (signed) Clifford J. Mugnier, c.p., c.m.s. Chief of Geodesy LSU Center for GeoInformatics Dept. of Civil Engineering LOUISIANA STATE UNIVERSITY *****************************************************************************/ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(lcca, "Lambert Conformal Conic Alternative") "\n\tConic, Sph&Ell\n\tlat_0="; #define MAX_ITER 10 #define DEL_TOL 1e-12 namespace { // anonymous namespace struct pj_lcca_data { double *en; double r0, l, M0; double C; }; } // anonymous namespace static double fS(double S, double C) { /* func to compute dr */ return S * (1. + S * S * C); } static double fSp(double S, double C) { /* deriv of fs */ return 1. + 3. * S * S * C; } static PJ_XY lcca_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_lcca_data *Q = static_cast<struct pj_lcca_data *>(P->opaque); double S, r, dr; S = pj_mlfn(lp.phi, sin(lp.phi), cos(lp.phi), Q->en) - Q->M0; dr = fS(S, Q->C); r = Q->r0 - dr; const double lam_mul_l = lp.lam * Q->l; xy.x = P->k0 * (r * sin(lam_mul_l)); xy.y = P->k0 * (Q->r0 - r * cos(lam_mul_l)); return xy; } static PJ_LP lcca_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_lcca_data *Q = static_cast<struct pj_lcca_data *>(P->opaque); double theta, dr, S, dif; int i; xy.x /= P->k0; xy.y /= P->k0; theta = atan2(xy.x, Q->r0 - xy.y); dr = xy.y - xy.x * tan(0.5 * theta); lp.lam = theta / Q->l; S = dr; for (i = MAX_ITER; i; --i) { S -= (dif = (fS(S, Q->C) - dr) / fSp(S, Q->C)); if (fabs(dif) < DEL_TOL) break; } if (!i) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } lp.phi = pj_inv_mlfn(S + Q->M0, Q->en); return lp; } static PJ *pj_lcca_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_lcca_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(lcca) { double s2p0, N0, R0, tan0; struct pj_lcca_data *Q = static_cast<struct pj_lcca_data *>( calloc(1, sizeof(struct pj_lcca_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; (Q->en = pj_enfn(P->n)); if (!Q->en) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); if (P->phi0 == 0.) { proj_log_error( P, _("Invalid value for lat_0: it should be different from 0.")); return pj_lcca_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->l = sin(P->phi0); Q->M0 = pj_mlfn(P->phi0, Q->l, cos(P->phi0), Q->en); s2p0 = Q->l * Q->l; R0 = 1. / (1. - P->es * s2p0); N0 = sqrt(R0); R0 *= P->one_es * N0; tan0 = tan(P->phi0); Q->r0 = N0 / tan0; Q->C = 1. / (6. * R0 * N0); P->inv = lcca_e_inverse; P->fwd = lcca_e_forward; P->destructor = pj_lcca_destructor; return P; } #undef MAX_ITER #undef DEL_TOL
cpp
PROJ
data/projects/PROJ/src/projections/lask.cpp
#include "proj.h" #include "proj_internal.h" PROJ_HEAD(lask, "Laskowski") "\n\tMisc Sph, no inv"; #define a10 0.975534 #define a12 -0.119161 #define a32 -0.0143059 #define a14 -0.0547009 #define b01 1.00384 #define b21 0.0802894 #define b03 0.0998909 #define b41 0.000199025 #define b23 -0.0285500 #define b05 -0.0491032 static PJ_XY lask_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double l2, p2; (void)P; l2 = lp.lam * lp.lam; p2 = lp.phi * lp.phi; xy.x = lp.lam * (a10 + p2 * (a12 + l2 * a32 + p2 * a14)); xy.y = lp.phi * (b01 + l2 * (b21 + p2 * b23 + l2 * b41) + p2 * (b03 + p2 * b05)); return xy; } PJ *PJ_PROJECTION(lask) { P->fwd = lask_s_forward; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/hatano.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(hatano, "Hatano Asymmetrical Equal Area") "\n\tPCyl, Sph"; #define NITER 20 #define EPS 1e-7 #define ONETOL 1.000001 #define CN 2.67595 #define CSz 2.43763 #define RCN 0.37369906014686373063 #define RCS 0.41023453108141924738 #define FYCN 1.75859 #define FYCS 1.93052 #define RYCN 0.56863737426006061674 #define RYCS 0.51799515156538134803 #define FXC 0.85 #define RXC 1.17647058823529411764 static PJ_XY hatano_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; int i; (void)P; const double c = sin(lp.phi) * (lp.phi < 0. ? CSz : CN); for (i = NITER; i; --i) { const double th1 = (lp.phi + sin(lp.phi) - c) / (1. + cos(lp.phi)); lp.phi -= th1; if (fabs(th1) < EPS) break; } xy.x = FXC * lp.lam * cos(lp.phi *= .5); xy.y = sin(lp.phi) * (lp.phi < 0. ? FYCS : FYCN); return xy; } static PJ_LP hatano_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double th; th = xy.y * (xy.y < 0. ? RYCS : RYCN); if (fabs(th) > 1.) { if (fabs(th) > ONETOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { th = th > 0. ? M_HALFPI : -M_HALFPI; } } else { th = asin(th); } lp.lam = RXC * xy.x / cos(th); th += th; lp.phi = (th + sin(th)) * (xy.y < 0. ? RCS : RCN); if (fabs(lp.phi) > 1.) { if (fabs(lp.phi) > ONETOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { lp.phi = lp.phi > 0. ? M_HALFPI : -M_HALFPI; } } else { lp.phi = asin(lp.phi); } return (lp); } PJ *PJ_PROJECTION(hatano) { P->es = 0.; P->inv = hatano_s_inverse; P->fwd = hatano_s_forward; return P; } #undef NITER #undef EPS #undef ONETOL #undef CN #undef CSz #undef RCN #undef RCS #undef FYCN #undef FYCS #undef RYCN #undef RYCS #undef FXC #undef RXC
cpp
PROJ
data/projects/PROJ/src/projections/imoll.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(imoll, "Interrupted Mollweide") "\n\tPCyl, Sph"; /* This projection is a compilation of 6 separate sub-projections. It is related to the Interrupted Goode Homolosine projection, but uses Mollweide at all latitudes. Each sub-projection is assigned an integer label numbered 1 through 6. Most of this code contains logic to assign the labels based on latitude (phi) and longitude (lam) regions. The code is adapted from igh.cpp. Original Reference: J. Paul Goode (1919) STUDIES IN PROJECTIONS: ADAPTING THE HOMOLOGRAPHIC PROJECTION TO THE PORTRAYAL OF THE EARTH'S ENTIRE SURFACE, Bul. Geog. SOC.Phila., Vol. XWIJNO.3. July, 1919, pp. 103-113. */ C_NAMESPACE PJ *pj_moll(PJ *); namespace pj_imoll_ns { struct pj_imoll_data { struct PJconsts *pj[6]; }; constexpr double d20 = 20 * DEG_TO_RAD; constexpr double d30 = 30 * DEG_TO_RAD; constexpr double d40 = 40 * DEG_TO_RAD; constexpr double d60 = 60 * DEG_TO_RAD; constexpr double d80 = 80 * DEG_TO_RAD; constexpr double d100 = 100 * DEG_TO_RAD; constexpr double d140 = 140 * DEG_TO_RAD; constexpr double d160 = 160 * DEG_TO_RAD; constexpr double d180 = 180 * DEG_TO_RAD; constexpr double EPSLN = 1.e-10; /* allow a little 'slack' on zone edge positions */ } // namespace pj_imoll_ns /* Assign an integer index representing each of the 6 sub-projection zones based on latitude (phi) and longitude (lam) ranges. */ static PJ_XY imoll_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ using namespace pj_imoll_ns; PJ_XY xy; struct pj_imoll_data *Q = static_cast<struct pj_imoll_data *>(P->opaque); int z; if (lp.phi >= 0) { /* 1|2 */ z = (lp.lam <= -d40 ? 1 : 2); } else { /* 3|4|5|6 */ if (lp.lam <= -d100) z = 3; /* 3 */ else if (lp.lam <= -d20) z = 4; /* 4 */ else if (lp.lam <= d80) z = 5; /* 5 */ else z = 6; /* 6 */ } lp.lam -= Q->pj[z - 1]->lam0; xy = Q->pj[z - 1]->fwd(lp, Q->pj[z - 1]); xy.x += Q->pj[z - 1]->x0; xy.y += Q->pj[z - 1]->y0; return xy; } static PJ_LP imoll_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ using namespace pj_imoll_ns; PJ_LP lp = {0.0, 0.0}; struct pj_imoll_data *Q = static_cast<struct pj_imoll_data *>(P->opaque); const double y90 = sqrt(2.0); /* lt=90 corresponds to y=sqrt(2) */ int z = 0; if (xy.y > y90 + EPSLN || xy.y < -y90 + EPSLN) /* 0 */ z = 0; else if (xy.y >= 0) z = (xy.x <= -d40 ? 1 : 2); /* 1|2 */ else { if (xy.x <= -d100) z = 3; /* 3 */ else if (xy.x <= -d20) z = 4; /* 4 */ else if (xy.x <= d80) z = 5; /* 5 */ else z = 6; /* 6 */ } if (z) { bool ok = false; xy.x -= Q->pj[z - 1]->x0; xy.y -= Q->pj[z - 1]->y0; lp = Q->pj[z - 1]->inv(xy, Q->pj[z - 1]); lp.lam += Q->pj[z - 1]->lam0; switch (z) { case 1: ok = ((lp.lam >= -d180 - EPSLN && lp.lam <= -d40 + EPSLN) && (lp.phi >= 0.0 - EPSLN)); break; case 2: ok = ((lp.lam >= -d40 - EPSLN && lp.lam <= d180 + EPSLN) && (lp.phi >= 0.0 - EPSLN)); break; case 3: ok = ((lp.lam >= -d180 - EPSLN && lp.lam <= -d100 + EPSLN) && (lp.phi <= 0.0 + EPSLN)); break; case 4: ok = ((lp.lam >= -d100 - EPSLN && lp.lam <= -d20 + EPSLN) && (lp.phi <= 0.0 + EPSLN)); break; case 5: ok = ((lp.lam >= -d20 - EPSLN && lp.lam <= d80 + EPSLN) && (lp.phi <= 0.0 + EPSLN)); break; case 6: ok = ((lp.lam >= d80 - EPSLN && lp.lam <= d180 + EPSLN) && (lp.phi <= 0.0 + EPSLN)); break; } z = (!ok ? 0 : z); /* projectable? */ } if (!z) lp.lam = HUGE_VAL; if (!z) lp.phi = HUGE_VAL; return lp; } static PJ *pj_imoll_destructor(PJ *P, int errlev) { using namespace pj_imoll_ns; int i; if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); struct pj_imoll_data *Q = static_cast<struct pj_imoll_data *>(P->opaque); for (i = 0; i < 6; ++i) { if (Q->pj[i]) Q->pj[i]->destructor(Q->pj[i], errlev); } return pj_default_destructor(P, errlev); } /* Zones: -180 -40 180 +--------------+-------------------------+ |1 |2 | | | | | | | | | | | | | 0 +-------+------+-+-----------+-----------+ |3 |4 |5 |6 | | | | | | | | | | | | | | | | | | | | | +-------+--------+-----------+-----------+ -180 -100 -20 80 180 */ static bool setup_zone(PJ *P, struct pj_imoll_ns::pj_imoll_data *Q, int n, PJ *(*proj_ptr)(PJ *), double x_0, double y_0, double lon_0) { if (!(Q->pj[n - 1] = proj_ptr(nullptr))) return false; if (!(Q->pj[n - 1] = proj_ptr(Q->pj[n - 1]))) return false; Q->pj[n - 1]->ctx = P->ctx; Q->pj[n - 1]->x0 = x_0; Q->pj[n - 1]->y0 = y_0; Q->pj[n - 1]->lam0 = lon_0; return true; } static double compute_zone_offset(struct pj_imoll_ns::pj_imoll_data *Q, int zone1, int zone2, double lam, double phi1, double phi2) { PJ_LP lp1, lp2; PJ_XY xy1, xy2; lp1.lam = lam - (Q->pj[zone1 - 1]->lam0); lp1.phi = phi1; lp2.lam = lam - (Q->pj[zone2 - 1]->lam0); lp2.phi = phi2; xy1 = Q->pj[zone1 - 1]->fwd(lp1, Q->pj[zone1 - 1]); xy2 = Q->pj[zone2 - 1]->fwd(lp2, Q->pj[zone2 - 1]); return (xy2.x + Q->pj[zone2 - 1]->x0) - (xy1.x + Q->pj[zone1 - 1]->x0); } PJ *PJ_PROJECTION(imoll) { using namespace pj_imoll_ns; struct pj_imoll_data *Q = static_cast<struct pj_imoll_data *>( calloc(1, sizeof(struct pj_imoll_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* Setup zones */ if (!setup_zone(P, Q, 1, pj_moll, -d100, 0, -d100) || !setup_zone(P, Q, 2, pj_moll, d30, 0, d30) || !setup_zone(P, Q, 3, pj_moll, -d160, 0, -d160) || !setup_zone(P, Q, 4, pj_moll, -d60, 0, -d60) || !setup_zone(P, Q, 5, pj_moll, d20, 0, d20) || !setup_zone(P, Q, 6, pj_moll, d140, 0, d140)) { return pj_imoll_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } /* Adjust zones */ /* Match 3 (south) to 1 (north) */ Q->pj[2]->x0 += compute_zone_offset(Q, 3, 1, -d160, 0.0 - EPSLN, 0.0 + EPSLN); /* Match 2 (north-east) to 1 (north-west) */ Q->pj[1]->x0 += compute_zone_offset(Q, 2, 1, -d40, 0.0 + EPSLN, 0.0 + EPSLN); /* Match 4 (south) to 1 (north) */ Q->pj[3]->x0 += compute_zone_offset(Q, 4, 1, -d100, 0.0 - EPSLN, 0.0 + EPSLN); /* Match 5 (south) to 2 (north) */ Q->pj[4]->x0 += compute_zone_offset(Q, 5, 2, -d20, 0.0 - EPSLN, 0.0 + EPSLN); /* Match 6 (south) to 2 (north) */ Q->pj[5]->x0 += compute_zone_offset(Q, 6, 2, d80, 0.0 - EPSLN, 0.0 + EPSLN); P->inv = imoll_s_inverse; P->fwd = imoll_s_forward; P->destructor = pj_imoll_destructor; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/sts.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(kav5, "Kavrayskiy V") "\n\tPCyl, Sph"; PROJ_HEAD(qua_aut, "Quartic Authalic") "\n\tPCyl, Sph"; PROJ_HEAD(fouc, "Foucaut") "\n\tPCyl, Sph"; PROJ_HEAD(mbt_s, "McBryde-Thomas Flat-Polar Sine (No. 1)") "\n\tPCyl, Sph"; namespace { // anonymous namespace struct pj_sts { double C_x, C_y, C_p; int tan_mode; }; } // anonymous namespace static PJ_XY sts_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_sts *Q = static_cast<struct pj_sts *>(P->opaque); xy.x = Q->C_x * lp.lam * cos(lp.phi); xy.y = Q->C_y; lp.phi *= Q->C_p; const double c = cos(lp.phi); if (Q->tan_mode) { xy.x *= c * c; xy.y *= tan(lp.phi); } else { xy.x /= c; xy.y *= sin(lp.phi); } return xy; } static PJ_LP sts_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_sts *Q = static_cast<struct pj_sts *>(P->opaque); xy.y /= Q->C_y; lp.phi = Q->tan_mode ? atan(xy.y) : aasin(P->ctx, xy.y); const double c = cos(lp.phi); lp.phi /= Q->C_p; lp.lam = xy.x / (Q->C_x * cos(lp.phi)); if (Q->tan_mode) lp.lam /= c * c; else lp.lam *= c; return lp; } static PJ *setup(PJ *P, double p, double q, int mode) { P->es = 0.; P->inv = sts_s_inverse; P->fwd = sts_s_forward; static_cast<struct pj_sts *>(P->opaque)->C_x = q / p; static_cast<struct pj_sts *>(P->opaque)->C_y = p; static_cast<struct pj_sts *>(P->opaque)->C_p = 1 / q; static_cast<struct pj_sts *>(P->opaque)->tan_mode = mode; return P; } PJ *PJ_PROJECTION(fouc) { struct pj_sts *Q = static_cast<struct pj_sts *>(calloc(1, sizeof(struct pj_sts))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; return setup(P, 2., 2., 1); } PJ *PJ_PROJECTION(kav5) { struct pj_sts *Q = static_cast<struct pj_sts *>(calloc(1, sizeof(struct pj_sts))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; return setup(P, 1.50488, 1.35439, 0); } PJ *PJ_PROJECTION(qua_aut) { struct pj_sts *Q = static_cast<struct pj_sts *>(calloc(1, sizeof(struct pj_sts))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; return setup(P, 2., 2., 0); } PJ *PJ_PROJECTION(mbt_s) { struct pj_sts *Q = static_cast<struct pj_sts *>(calloc(1, sizeof(struct pj_sts))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; return setup(P, 1.48875, 1.36509, 0); }
cpp
PROJ
data/projects/PROJ/src/projections/vandg2.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_vandg2 { int vdg3; }; } // anonymous namespace PROJ_HEAD(vandg2, "van der Grinten II") "\n\tMisc Sph, no inv"; PROJ_HEAD(vandg3, "van der Grinten III") "\n\tMisc Sph, no inv"; #define TOL 1e-10 static PJ_XY vandg2_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_vandg2 *Q = static_cast<struct pj_vandg2 *>(P->opaque); double x1, at, bt, ct; bt = fabs(M_TWO_D_PI * lp.phi); ct = 1. - bt * bt; if (ct < 0.) ct = 0.; else ct = sqrt(ct); if (fabs(lp.lam) < TOL) { xy.x = 0.; xy.y = M_PI * (lp.phi < 0. ? -bt : bt) / (1. + ct); } else { at = 0.5 * fabs(M_PI / lp.lam - lp.lam / M_PI); if (Q->vdg3) { x1 = bt / (1. + ct); xy.x = M_PI * (sqrt(at * at + 1. - x1 * x1) - at); xy.y = M_PI * x1; } else { x1 = (ct * sqrt(1. + at * at) - at * ct * ct) / (1. + at * at * bt * bt); xy.x = M_PI * x1; xy.y = M_PI * sqrt(1. - x1 * (x1 + 2. * at) + TOL); } if (lp.lam < 0.) xy.x = -xy.x; if (lp.phi < 0.) xy.y = -xy.y; } return xy; } PJ *PJ_PROJECTION(vandg2) { struct pj_vandg2 *Q = static_cast<struct pj_vandg2 *>(calloc(1, sizeof(struct pj_vandg2))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->vdg3 = 0; P->fwd = vandg2_s_forward; return P; } PJ *PJ_PROJECTION(vandg3) { struct pj_vandg2 *Q = static_cast<struct pj_vandg2 *>(calloc(1, sizeof(struct pj_vandg2))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->vdg3 = 1; P->es = 0.; P->fwd = vandg2_s_forward; return P; } #undef TOL
cpp
PROJ
data/projects/PROJ/src/projections/laea.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(laea, "Lambert Azimuthal Equal Area") "\n\tAzi, Sph&Ell"; namespace pj_laea_ns { enum Mode { N_POLE = 0, S_POLE = 1, EQUIT = 2, OBLIQ = 3 }; } namespace { // anonymous namespace struct pj_laea_data { double sinb1; double cosb1; double xmf; double ymf; double mmf; double qp; double dd; double rq; double *apa; enum pj_laea_ns::Mode mode; }; } // anonymous namespace #define EPS10 1.e-10 static PJ_XY laea_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_laea_data *Q = static_cast<struct pj_laea_data *>(P->opaque); double coslam, sinlam, sinphi, q, sinb = 0.0, cosb = 0.0, b = 0.0; coslam = cos(lp.lam); sinlam = sin(lp.lam); sinphi = sin(lp.phi); q = pj_qsfn(sinphi, P->e, P->one_es); if (Q->mode == pj_laea_ns::OBLIQ || Q->mode == pj_laea_ns::EQUIT) { sinb = q / Q->qp; const double cosb2 = 1. - sinb * sinb; cosb = cosb2 > 0 ? sqrt(cosb2) : 0; } switch (Q->mode) { case pj_laea_ns::OBLIQ: b = 1. + Q->sinb1 * sinb + Q->cosb1 * cosb * coslam; break; case pj_laea_ns::EQUIT: b = 1. + cosb * coslam; break; case pj_laea_ns::N_POLE: b = M_HALFPI + lp.phi; q = Q->qp - q; break; case pj_laea_ns::S_POLE: b = lp.phi - M_HALFPI; q = Q->qp + q; break; } if (fabs(b) < EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } switch (Q->mode) { case pj_laea_ns::OBLIQ: b = sqrt(2. / b); xy.y = Q->ymf * b * (Q->cosb1 * sinb - Q->sinb1 * cosb * coslam); goto eqcon; break; case pj_laea_ns::EQUIT: b = sqrt(2. / (1. + cosb * coslam)); xy.y = b * sinb * Q->ymf; eqcon: xy.x = Q->xmf * b * cosb * sinlam; break; case pj_laea_ns::N_POLE: case pj_laea_ns::S_POLE: if (q >= 1e-15) { b = sqrt(q); xy.x = b * sinlam; xy.y = coslam * (Q->mode == pj_laea_ns::S_POLE ? b : -b); } else xy.x = xy.y = 0.; break; } return xy; } static PJ_XY laea_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_laea_data *Q = static_cast<struct pj_laea_data *>(P->opaque); double coslam, cosphi, sinphi; sinphi = sin(lp.phi); cosphi = cos(lp.phi); coslam = cos(lp.lam); switch (Q->mode) { case pj_laea_ns::EQUIT: xy.y = 1. + cosphi * coslam; goto oblcon; case pj_laea_ns::OBLIQ: xy.y = 1. + Q->sinb1 * sinphi + Q->cosb1 * cosphi * coslam; oblcon: if (xy.y <= EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.y = sqrt(2. / xy.y); xy.x = xy.y * cosphi * sin(lp.lam); xy.y *= Q->mode == pj_laea_ns::EQUIT ? sinphi : Q->cosb1 * sinphi - Q->sinb1 * cosphi * coslam; break; case pj_laea_ns::N_POLE: coslam = -coslam; PROJ_FALLTHROUGH; case pj_laea_ns::S_POLE: if (fabs(lp.phi + P->phi0) < EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.y = M_FORTPI - lp.phi * .5; xy.y = 2. * (Q->mode == pj_laea_ns::S_POLE ? cos(xy.y) : sin(xy.y)); xy.x = xy.y * sin(lp.lam); xy.y *= coslam; break; } return xy; } static PJ_LP laea_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_laea_data *Q = static_cast<struct pj_laea_data *>(P->opaque); double cCe, sCe, q, rho, ab = 0.0; switch (Q->mode) { case pj_laea_ns::EQUIT: case pj_laea_ns::OBLIQ: { xy.x /= Q->dd; xy.y *= Q->dd; rho = hypot(xy.x, xy.y); if (rho < EPS10) { lp.lam = 0.; lp.phi = P->phi0; return lp; } const double asin_argument = .5 * rho / Q->rq; if (asin_argument > 1) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } sCe = 2. * asin(asin_argument); cCe = cos(sCe); sCe = sin(sCe); xy.x *= sCe; if (Q->mode == pj_laea_ns::OBLIQ) { ab = cCe * Q->sinb1 + xy.y * sCe * Q->cosb1 / rho; xy.y = rho * Q->cosb1 * cCe - xy.y * Q->sinb1 * sCe; } else { ab = xy.y * sCe / rho; xy.y = rho * cCe; } break; } case pj_laea_ns::N_POLE: xy.y = -xy.y; PROJ_FALLTHROUGH; case pj_laea_ns::S_POLE: q = (xy.x * xy.x + xy.y * xy.y); if (q == 0.0) { lp.lam = 0.; lp.phi = P->phi0; return (lp); } ab = 1. - q / Q->qp; if (Q->mode == pj_laea_ns::S_POLE) ab = -ab; break; } lp.lam = atan2(xy.x, xy.y); lp.phi = pj_authlat(asin(ab), Q->apa); return lp; } static PJ_LP laea_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_laea_data *Q = static_cast<struct pj_laea_data *>(P->opaque); double cosz = 0.0, rh, sinz = 0.0; rh = hypot(xy.x, xy.y); if ((lp.phi = rh * .5) > 1.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } lp.phi = 2. * asin(lp.phi); if (Q->mode == pj_laea_ns::OBLIQ || Q->mode == pj_laea_ns::EQUIT) { sinz = sin(lp.phi); cosz = cos(lp.phi); } switch (Q->mode) { case pj_laea_ns::EQUIT: lp.phi = fabs(rh) <= EPS10 ? 0. : asin(xy.y * sinz / rh); xy.x *= sinz; xy.y = cosz * rh; break; case pj_laea_ns::OBLIQ: lp.phi = fabs(rh) <= EPS10 ? P->phi0 : asin(cosz * Q->sinb1 + xy.y * sinz * Q->cosb1 / rh); xy.x *= sinz * Q->cosb1; xy.y = (cosz - sin(lp.phi) * Q->sinb1) * rh; break; case pj_laea_ns::N_POLE: xy.y = -xy.y; lp.phi = M_HALFPI - lp.phi; break; case pj_laea_ns::S_POLE: lp.phi -= M_HALFPI; break; } lp.lam = (xy.y == 0. && (Q->mode == pj_laea_ns::EQUIT || Q->mode == pj_laea_ns::OBLIQ)) ? 0. : atan2(xy.x, xy.y); return (lp); } static PJ *pj_laea_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_laea_data *>(P->opaque)->apa); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(laea) { double t; struct pj_laea_data *Q = static_cast<struct pj_laea_data *>( calloc(1, sizeof(struct pj_laea_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_laea_destructor; t = fabs(P->phi0); if (t > M_HALFPI + EPS10) { proj_log_error(P, _("Invalid value for lat_0: |lat_0| should be <= 90°")); return pj_laea_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(t - M_HALFPI) < EPS10) Q->mode = P->phi0 < 0. ? pj_laea_ns::S_POLE : pj_laea_ns::N_POLE; else if (fabs(t) < EPS10) Q->mode = pj_laea_ns::EQUIT; else Q->mode = pj_laea_ns::OBLIQ; if (P->es != 0.0) { double sinphi; P->e = sqrt(P->es); Q->qp = pj_qsfn(1., P->e, P->one_es); Q->mmf = .5 / (1. - P->es); Q->apa = pj_authset(P->es); if (nullptr == Q->apa) return pj_laea_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); switch (Q->mode) { case pj_laea_ns::N_POLE: case pj_laea_ns::S_POLE: Q->dd = 1.; break; case pj_laea_ns::EQUIT: Q->dd = 1. / (Q->rq = sqrt(.5 * Q->qp)); Q->xmf = 1.; Q->ymf = .5 * Q->qp; break; case pj_laea_ns::OBLIQ: Q->rq = sqrt(.5 * Q->qp); sinphi = sin(P->phi0); Q->sinb1 = pj_qsfn(sinphi, P->e, P->one_es) / Q->qp; Q->cosb1 = sqrt(1. - Q->sinb1 * Q->sinb1); Q->dd = cos(P->phi0) / (sqrt(1. - P->es * sinphi * sinphi) * Q->rq * Q->cosb1); Q->ymf = (Q->xmf = Q->rq) / Q->dd; Q->xmf *= Q->dd; break; } P->inv = laea_e_inverse; P->fwd = laea_e_forward; } else { if (Q->mode == pj_laea_ns::OBLIQ) { Q->sinb1 = sin(P->phi0); Q->cosb1 = cos(P->phi0); } P->inv = laea_s_inverse; P->fwd = laea_s_forward; } return P; }
cpp
PROJ
data/projects/PROJ/src/projections/gn_sinu.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(gn_sinu, "General Sinusoidal Series") "\n\tPCyl, Sph\n\tm= n="; PROJ_HEAD(sinu, "Sinusoidal (Sanson-Flamsteed)") "\n\tPCyl, Sph&Ell"; PROJ_HEAD(eck6, "Eckert VI") "\n\tPCyl, Sph"; PROJ_HEAD(mbtfps, "McBryde-Thomas Flat-Polar Sinusoidal") "\n\tPCyl, Sph"; #define EPS10 1e-10 #define MAX_ITER 8 #define LOOP_TOL 1e-7 namespace { // anonymous namespace struct pj_gn_sinu_data { double *en; double m, n, C_x, C_y; }; } // anonymous namespace static PJ_XY gn_sinu_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; const double s = sin(lp.phi); const double c = cos(lp.phi); xy.y = pj_mlfn(lp.phi, s, c, static_cast<struct pj_gn_sinu_data *>(P->opaque)->en); xy.x = lp.lam * c / sqrt(1. - P->es * s * s); return xy; } static PJ_LP gn_sinu_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; double s; lp.phi = pj_inv_mlfn(xy.y, static_cast<struct pj_gn_sinu_data *>(P->opaque)->en); s = fabs(lp.phi); if (s < M_HALFPI) { s = sin(lp.phi); lp.lam = xy.x * sqrt(1. - P->es * s * s) / cos(lp.phi); } else if ((s - EPS10) < M_HALFPI) { lp.lam = 0.; } else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); } return lp; } static PJ_XY gn_sinu_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_gn_sinu_data *Q = static_cast<struct pj_gn_sinu_data *>(P->opaque); if (Q->m == 0.0) lp.phi = Q->n != 1. ? aasin(P->ctx, Q->n * sin(lp.phi)) : lp.phi; else { int i; const double k = Q->n * sin(lp.phi); for (i = MAX_ITER; i; --i) { const double V = (Q->m * lp.phi + sin(lp.phi) - k) / (Q->m + cos(lp.phi)); lp.phi -= V; if (fabs(V) < LOOP_TOL) break; } if (!i) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } } xy.x = Q->C_x * lp.lam * (Q->m + cos(lp.phi)); xy.y = Q->C_y * lp.phi; return xy; } static PJ_LP gn_sinu_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_gn_sinu_data *Q = static_cast<struct pj_gn_sinu_data *>(P->opaque); xy.y /= Q->C_y; lp.phi = (Q->m != 0.0) ? aasin(P->ctx, (Q->m * xy.y + sin(xy.y)) / Q->n) : (Q->n != 1. ? aasin(P->ctx, sin(xy.y) / Q->n) : xy.y); lp.lam = xy.x / (Q->C_x * (Q->m + cos(xy.y))); return lp; } static PJ *pj_gn_sinu_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_gn_sinu_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } /* for spheres, only */ static void pj_gn_sinu_setup(PJ *P) { struct pj_gn_sinu_data *Q = static_cast<struct pj_gn_sinu_data *>(P->opaque); P->es = 0; P->inv = gn_sinu_s_inverse; P->fwd = gn_sinu_s_forward; Q->C_y = sqrt((Q->m + 1.) / Q->n); Q->C_x = Q->C_y / (Q->m + 1.); } PJ *PJ_PROJECTION(sinu) { struct pj_gn_sinu_data *Q = static_cast<struct pj_gn_sinu_data *>( calloc(1, sizeof(struct pj_gn_sinu_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_gn_sinu_destructor; if (!(Q->en = pj_enfn(P->n))) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); if (P->es != 0.0) { P->inv = gn_sinu_e_inverse; P->fwd = gn_sinu_e_forward; } else { Q->n = 1.; Q->m = 0.; pj_gn_sinu_setup(P); } return P; } PJ *PJ_PROJECTION(eck6) { struct pj_gn_sinu_data *Q = static_cast<struct pj_gn_sinu_data *>( calloc(1, sizeof(struct pj_gn_sinu_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_gn_sinu_destructor; Q->m = 1.; Q->n = 2.570796326794896619231321691; pj_gn_sinu_setup(P); return P; } PJ *PJ_PROJECTION(mbtfps) { struct pj_gn_sinu_data *Q = static_cast<struct pj_gn_sinu_data *>( calloc(1, sizeof(struct pj_gn_sinu_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_gn_sinu_destructor; Q->m = 0.5; Q->n = 1.785398163397448309615660845; pj_gn_sinu_setup(P); return P; } PJ *PJ_PROJECTION(gn_sinu) { struct pj_gn_sinu_data *Q = static_cast<struct pj_gn_sinu_data *>( calloc(1, sizeof(struct pj_gn_sinu_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_gn_sinu_destructor; if (!pj_param(P->ctx, P->params, "tn").i) { proj_log_error(P, _("Missing parameter n.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (!pj_param(P->ctx, P->params, "tm").i) { proj_log_error(P, _("Missing parameter m.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->n = pj_param(P->ctx, P->params, "dn").f; Q->m = pj_param(P->ctx, P->params, "dm").f; if (Q->n <= 0) { proj_log_error(P, _("Invalid value for n: it should be > 0.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (Q->m < 0) { proj_log_error(P, _("Invalid value for m: it should be >= 0.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } pj_gn_sinu_setup(P); return P; }
cpp
PROJ
data/projects/PROJ/src/projections/stere.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(stere, "Stereographic") "\n\tAzi, Sph&Ell\n\tlat_ts="; PROJ_HEAD(ups, "Universal Polar Stereographic") "\n\tAzi, Ell\n\tsouth"; namespace { // anonymous namespace enum Mode { S_POLE = 0, N_POLE = 1, OBLIQ = 2, EQUIT = 3 }; } // anonymous namespace namespace { // anonymous namespace struct pj_stere { double phits; double sinX1; double cosX1; double akm1; enum Mode mode; }; } // anonymous namespace #define sinph0 static_cast<struct pj_stere *>(P->opaque)->sinX1 #define cosph0 static_cast<struct pj_stere *>(P->opaque)->cosX1 #define EPS10 1.e-10 #define TOL 1.e-8 #define NITER 8 #define CONV 1.e-10 static double ssfn_(double phit, double sinphi, double eccen) { sinphi *= eccen; return (tan(.5 * (M_HALFPI + phit)) * pow((1. - sinphi) / (1. + sinphi), .5 * eccen)); } static PJ_XY stere_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_stere *Q = static_cast<struct pj_stere *>(P->opaque); double coslam, sinlam, sinX = 0.0, cosX = 0.0, A = 0.0, sinphi; coslam = cos(lp.lam); sinlam = sin(lp.lam); sinphi = sin(lp.phi); if (Q->mode == OBLIQ || Q->mode == EQUIT) { const double X = 2. * atan(ssfn_(lp.phi, sinphi, P->e)) - M_HALFPI; sinX = sin(X); cosX = cos(X); } switch (Q->mode) { case OBLIQ: { const double denom = Q->cosX1 * (1. + Q->sinX1 * sinX + Q->cosX1 * cosX * coslam); if (denom == 0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } A = Q->akm1 / denom; xy.y = A * (Q->cosX1 * sinX - Q->sinX1 * cosX * coslam); xy.x = A * cosX; break; } case EQUIT: /* avoid zero division */ if (1. + cosX * coslam == 0.0) { xy.y = HUGE_VAL; } else { A = Q->akm1 / (1. + cosX * coslam); xy.y = A * sinX; } xy.x = A * cosX; break; case S_POLE: lp.phi = -lp.phi; coslam = -coslam; sinphi = -sinphi; PROJ_FALLTHROUGH; case N_POLE: if (fabs(lp.phi - M_HALFPI) < 1e-15) xy.x = 0; else xy.x = Q->akm1 * pj_tsfn(lp.phi, sinphi, P->e); xy.y = -xy.x * coslam; break; } xy.x = xy.x * sinlam; return xy; } static PJ_XY stere_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_stere *Q = static_cast<struct pj_stere *>(P->opaque); double sinphi, cosphi, coslam, sinlam; sinphi = sin(lp.phi); cosphi = cos(lp.phi); coslam = cos(lp.lam); sinlam = sin(lp.lam); switch (Q->mode) { case EQUIT: xy.y = 1. + cosphi * coslam; goto oblcon; case OBLIQ: xy.y = 1. + sinph0 * sinphi + cosph0 * cosphi * coslam; oblcon: if (xy.y <= EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.y = Q->akm1 / xy.y; xy.x = xy.y * cosphi * sinlam; xy.y *= (Q->mode == EQUIT) ? sinphi : cosph0 * sinphi - sinph0 * cosphi * coslam; break; case N_POLE: coslam = -coslam; lp.phi = -lp.phi; PROJ_FALLTHROUGH; case S_POLE: if (fabs(lp.phi - M_HALFPI) < TOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.y = Q->akm1 * tan(M_FORTPI + .5 * lp.phi); xy.x = sinlam * xy.y; xy.y *= coslam; break; } return xy; } static PJ_LP stere_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_stere *Q = static_cast<struct pj_stere *>(P->opaque); double cosphi, sinphi, tp = 0.0, phi_l = 0.0, rho, halfe = 0.0, halfpi = 0.0; rho = hypot(xy.x, xy.y); switch (Q->mode) { case OBLIQ: case EQUIT: tp = 2. * atan2(rho * Q->cosX1, Q->akm1); cosphi = cos(tp); sinphi = sin(tp); if (rho == 0.0) phi_l = asin(cosphi * Q->sinX1); else phi_l = asin(cosphi * Q->sinX1 + (xy.y * sinphi * Q->cosX1 / rho)); tp = tan(.5 * (M_HALFPI + phi_l)); xy.x *= sinphi; xy.y = rho * Q->cosX1 * cosphi - xy.y * Q->sinX1 * sinphi; halfpi = M_HALFPI; halfe = .5 * P->e; break; case N_POLE: xy.y = -xy.y; PROJ_FALLTHROUGH; case S_POLE: tp = -rho / Q->akm1; phi_l = M_HALFPI - 2. * atan(tp); halfpi = -M_HALFPI; halfe = -.5 * P->e; break; } for (int i = NITER; i > 0; --i) { sinphi = P->e * sin(phi_l); lp.phi = 2. * atan(tp * pow((1. + sinphi) / (1. - sinphi), halfe)) - halfpi; if (fabs(phi_l - lp.phi) < CONV) { if (Q->mode == S_POLE) lp.phi = -lp.phi; lp.lam = (xy.x == 0. && xy.y == 0.) ? 0. : atan2(xy.x, xy.y); return lp; } phi_l = lp.phi; } proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } static PJ_LP stere_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_stere *Q = static_cast<struct pj_stere *>(P->opaque); double c, sinc, cosc; const double rh = hypot(xy.x, xy.y); c = 2. * atan(rh / Q->akm1); sinc = sin(c); cosc = cos(c); lp.lam = 0.; switch (Q->mode) { case EQUIT: if (fabs(rh) <= EPS10) lp.phi = 0.; else lp.phi = asin(xy.y * sinc / rh); if (cosc != 0. || xy.x != 0.) lp.lam = atan2(xy.x * sinc, cosc * rh); break; case OBLIQ: if (fabs(rh) <= EPS10) lp.phi = P->phi0; else lp.phi = asin(cosc * sinph0 + xy.y * sinc * cosph0 / rh); c = cosc - sinph0 * sin(lp.phi); if (c != 0. || xy.x != 0.) lp.lam = atan2(xy.x * sinc * cosph0, c * rh); break; case N_POLE: xy.y = -xy.y; PROJ_FALLTHROUGH; case S_POLE: if (fabs(rh) <= EPS10) lp.phi = P->phi0; else lp.phi = asin(Q->mode == S_POLE ? -cosc : cosc); lp.lam = (xy.x == 0. && xy.y == 0.) ? 0. : atan2(xy.x, xy.y); break; } return lp; } static PJ *stere_setup(PJ *P) { /* general initialization */ double t; struct pj_stere *Q = static_cast<struct pj_stere *>(P->opaque); if (fabs((t = fabs(P->phi0)) - M_HALFPI) < EPS10) Q->mode = P->phi0 < 0. ? S_POLE : N_POLE; else Q->mode = t > EPS10 ? OBLIQ : EQUIT; Q->phits = fabs(Q->phits); if (P->es != 0.0) { double X; switch (Q->mode) { case N_POLE: case S_POLE: if (fabs(Q->phits - M_HALFPI) < EPS10) Q->akm1 = 2. * P->k0 / sqrt(pow(1 + P->e, 1 + P->e) * pow(1 - P->e, 1 - P->e)); else { t = sin(Q->phits); Q->akm1 = cos(Q->phits) / pj_tsfn(Q->phits, t, P->e); t *= P->e; Q->akm1 /= sqrt(1. - t * t); } break; case EQUIT: case OBLIQ: t = sin(P->phi0); X = 2. * atan(ssfn_(P->phi0, t, P->e)) - M_HALFPI; t *= P->e; Q->akm1 = 2. * P->k0 * cos(P->phi0) / sqrt(1. - t * t); Q->sinX1 = sin(X); Q->cosX1 = cos(X); break; } P->inv = stere_e_inverse; P->fwd = stere_e_forward; } else { switch (Q->mode) { case OBLIQ: sinph0 = sin(P->phi0); cosph0 = cos(P->phi0); PROJ_FALLTHROUGH; case EQUIT: Q->akm1 = 2. * P->k0; break; case S_POLE: case N_POLE: Q->akm1 = fabs(Q->phits - M_HALFPI) >= EPS10 ? cos(Q->phits) / tan(M_FORTPI - .5 * Q->phits) : 2. * P->k0; break; } P->inv = stere_s_inverse; P->fwd = stere_s_forward; } return P; } PJ *PJ_PROJECTION(stere) { struct pj_stere *Q = static_cast<struct pj_stere *>(calloc(1, sizeof(struct pj_stere))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->phits = pj_param(P->ctx, P->params, "tlat_ts").i ? pj_param(P->ctx, P->params, "rlat_ts").f : M_HALFPI; return stere_setup(P); } PJ *PJ_PROJECTION(ups) { struct pj_stere *Q = static_cast<struct pj_stere *>(calloc(1, sizeof(struct pj_stere))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* International Ellipsoid */ P->phi0 = pj_param(P->ctx, P->params, "bsouth").i ? -M_HALFPI : M_HALFPI; if (P->es == 0.0) { proj_log_error( P, _("Invalid value for es: only ellipsoidal formulation supported")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->k0 = .994; P->x0 = 2000000.; P->y0 = 2000000.; Q->phits = M_HALFPI; P->lam0 = 0.; return stere_setup(P); } #undef sinph0 #undef cosph0 #undef EPS10 #undef TOL #undef NITER #undef CONV
cpp
PROJ
data/projects/PROJ/src/projections/sconics.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> namespace pj_sconics_ns { enum Type { EULER = 0, MURD1 = 1, MURD2 = 2, MURD3 = 3, PCONIC = 4, TISSOT = 5, VITK1 = 6 }; } namespace { // anonymous namespace struct pj_sconics_data { double n; double rho_c; double rho_0; double sig; double c1, c2; enum pj_sconics_ns::Type type; }; } // anonymous namespace #define EPS10 1.e-10 #define EPS 1e-10 #define LINE2 "\n\tConic, Sph\n\tlat_1= and lat_2=" PROJ_HEAD(euler, "Euler") LINE2; PROJ_HEAD(murd1, "Murdoch I") LINE2; PROJ_HEAD(murd2, "Murdoch II") LINE2; PROJ_HEAD(murd3, "Murdoch III") LINE2; PROJ_HEAD(pconic, "Perspective Conic") LINE2; PROJ_HEAD(tissot, "Tissot") LINE2; PROJ_HEAD(vitk1, "Vitkovsky I") LINE2; /* get common factors for simple conics */ static int phi12(PJ *P, double *del) { double p1, p2; int err = 0; if (!pj_param(P->ctx, P->params, "tlat_1").i) { proj_log_error(P, _("Missing parameter: lat_1 should be specified")); err = PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE; } else if (!pj_param(P->ctx, P->params, "tlat_2").i) { proj_log_error(P, _("Missing parameter: lat_2 should be specified")); err = PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE; } else { p1 = pj_param(P->ctx, P->params, "rlat_1").f; p2 = pj_param(P->ctx, P->params, "rlat_2").f; *del = 0.5 * (p2 - p1); const double sig = 0.5 * (p2 + p1); static_cast<struct pj_sconics_data *>(P->opaque)->sig = sig; err = (fabs(*del) < EPS || fabs(sig) < EPS) ? PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE : 0; if (err) { proj_log_error( P, _("Illegal value for lat_1 and lat_2: |lat_1 - lat_2| " "and |lat_1 + lat_2| should be > 0")); } } return err; } static PJ_XY sconics_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_sconics_data *Q = static_cast<struct pj_sconics_data *>(P->opaque); double rho; switch (Q->type) { case pj_sconics_ns::MURD2: rho = Q->rho_c + tan(Q->sig - lp.phi); break; case pj_sconics_ns::PCONIC: rho = Q->c2 * (Q->c1 - tan(lp.phi - Q->sig)); break; default: rho = Q->rho_c - lp.phi; break; } xy.x = rho * sin(lp.lam *= Q->n); xy.y = Q->rho_0 - rho * cos(lp.lam); return xy; } static PJ_LP sconics_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, (and ellipsoidal?) inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_sconics_data *Q = static_cast<struct pj_sconics_data *>(P->opaque); double rho; xy.y = Q->rho_0 - xy.y; rho = hypot(xy.x, xy.y); if (Q->n < 0.) { rho = -rho; xy.x = -xy.x; xy.y = -xy.y; } lp.lam = atan2(xy.x, xy.y) / Q->n; switch (Q->type) { case pj_sconics_ns::PCONIC: lp.phi = atan(Q->c1 - rho / Q->c2) + Q->sig; break; case pj_sconics_ns::MURD2: lp.phi = Q->sig - atan(rho - Q->rho_c); break; default: lp.phi = Q->rho_c - rho; } return lp; } static PJ *pj_sconics_setup(PJ *P, enum pj_sconics_ns::Type type) { double del, cs; int err; struct pj_sconics_data *Q = static_cast<struct pj_sconics_data *>( calloc(1, sizeof(struct pj_sconics_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->type = type; err = phi12(P, &del); if (err) return pj_default_destructor(P, err); switch (Q->type) { case pj_sconics_ns::TISSOT: Q->n = sin(Q->sig); cs = cos(del); Q->rho_c = Q->n / cs + cs / Q->n; Q->rho_0 = sqrt((Q->rho_c - 2 * sin(P->phi0)) / Q->n); break; case pj_sconics_ns::MURD1: Q->rho_c = sin(del) / (del * tan(Q->sig)) + Q->sig; Q->rho_0 = Q->rho_c - P->phi0; Q->n = sin(Q->sig); break; case pj_sconics_ns::MURD2: Q->rho_c = (cs = sqrt(cos(del))) / tan(Q->sig); Q->rho_0 = Q->rho_c + tan(Q->sig - P->phi0); Q->n = sin(Q->sig) * cs; break; case pj_sconics_ns::MURD3: Q->rho_c = del / (tan(Q->sig) * tan(del)) + Q->sig; Q->rho_0 = Q->rho_c - P->phi0; Q->n = sin(Q->sig) * sin(del) * tan(del) / (del * del); break; case pj_sconics_ns::EULER: Q->n = sin(Q->sig) * sin(del) / del; del *= 0.5; Q->rho_c = del / (tan(del) * tan(Q->sig)) + Q->sig; Q->rho_0 = Q->rho_c - P->phi0; break; case pj_sconics_ns::PCONIC: Q->n = sin(Q->sig); Q->c2 = cos(del); Q->c1 = 1. / tan(Q->sig); del = P->phi0 - Q->sig; if (fabs(del) - EPS10 >= M_HALFPI) { proj_log_error( P, _("Invalid value for lat_0/lat_1/lat_2: |lat_0 - 0.5 * " "(lat_1 + lat_2)| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->rho_0 = Q->c2 * (Q->c1 - tan(del)); break; case pj_sconics_ns::VITK1: cs = tan(del); Q->n = cs * sin(Q->sig) / del; Q->rho_c = del / (cs * tan(Q->sig)) + Q->sig; Q->rho_0 = Q->rho_c - P->phi0; break; } P->inv = sconics_s_inverse; P->fwd = sconics_s_forward; P->es = 0; return (P); } PJ *PJ_PROJECTION(euler) { return pj_sconics_setup(P, pj_sconics_ns::EULER); } PJ *PJ_PROJECTION(tissot) { return pj_sconics_setup(P, pj_sconics_ns::TISSOT); } PJ *PJ_PROJECTION(murd1) { return pj_sconics_setup(P, pj_sconics_ns::MURD1); } PJ *PJ_PROJECTION(murd2) { return pj_sconics_setup(P, pj_sconics_ns::MURD2); } PJ *PJ_PROJECTION(murd3) { return pj_sconics_setup(P, pj_sconics_ns::MURD3); } PJ *PJ_PROJECTION(pconic) { return pj_sconics_setup(P, pj_sconics_ns::PCONIC); } PJ *PJ_PROJECTION(vitk1) { return pj_sconics_setup(P, pj_sconics_ns::VITK1); } #undef EPS10 #undef EPS #undef LINE2
cpp
PROJ
data/projects/PROJ/src/projections/somerc.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(somerc, "Swiss. Obl. Mercator") "\n\tCyl, Ell\n\tFor CH1903"; namespace { // anonymous namespace struct pj_somerc { double K, c, hlf_e, kR, cosp0, sinp0; }; } // anonymous namespace #define EPS 1.e-10 #define NITER 6 static PJ_XY somerc_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; double phip, lamp, phipp, lampp, sp, cp; struct pj_somerc *Q = static_cast<struct pj_somerc *>(P->opaque); sp = P->e * sin(lp.phi); phip = 2. * atan(exp(Q->c * (log(tan(M_FORTPI + 0.5 * lp.phi)) - Q->hlf_e * log((1. + sp) / (1. - sp))) + Q->K)) - M_HALFPI; lamp = Q->c * lp.lam; cp = cos(phip); phipp = aasin(P->ctx, Q->cosp0 * sin(phip) - Q->sinp0 * cp * cos(lamp)); lampp = aasin(P->ctx, cp * sin(lamp) / cos(phipp)); xy.x = Q->kR * lampp; xy.y = Q->kR * log(tan(M_FORTPI + 0.5 * phipp)); return xy; } static PJ_LP somerc_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_somerc *Q = static_cast<struct pj_somerc *>(P->opaque); double phip, lamp, phipp, lampp, cp, esp, con, delp; int i; phipp = 2. * (atan(exp(xy.y / Q->kR)) - M_FORTPI); lampp = xy.x / Q->kR; cp = cos(phipp); phip = aasin(P->ctx, Q->cosp0 * sin(phipp) + Q->sinp0 * cp * cos(lampp)); lamp = aasin(P->ctx, cp * sin(lampp) / cos(phip)); con = (Q->K - log(tan(M_FORTPI + 0.5 * phip))) / Q->c; for (i = NITER; i; --i) { esp = P->e * sin(phip); delp = (con + log(tan(M_FORTPI + 0.5 * phip)) - Q->hlf_e * log((1. + esp) / (1. - esp))) * (1. - esp * esp) * cos(phip) * P->rone_es; phip -= delp; if (fabs(delp) < EPS) break; } if (i) { lp.phi = phip; lp.lam = lamp / Q->c; } else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } return (lp); } PJ *PJ_PROJECTION(somerc) { double cp, phip0, sp; struct pj_somerc *Q = static_cast<struct pj_somerc *>(calloc(1, sizeof(struct pj_somerc))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->hlf_e = 0.5 * P->e; cp = cos(P->phi0); cp *= cp; Q->c = sqrt(1 + P->es * cp * cp * P->rone_es); sp = sin(P->phi0); Q->sinp0 = sp / Q->c; phip0 = aasin(P->ctx, Q->sinp0); Q->cosp0 = cos(phip0); sp *= P->e; Q->K = log(tan(M_FORTPI + 0.5 * phip0)) - Q->c * (log(tan(M_FORTPI + 0.5 * P->phi0)) - Q->hlf_e * log((1. + sp) / (1. - sp))); Q->kR = P->k0 * sqrt(P->one_es) / (1. - sp * sp); P->inv = somerc_e_inverse; P->fwd = somerc_e_forward; return P; } #undef EPS #undef NITER
cpp
PROJ
data/projects/PROJ/src/projections/wag7.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(wag7, "Wagner VII") "\n\tMisc Sph, no inv"; static PJ_XY wag7_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; /* Shut up compiler warnnings about unused P */ xy.y = 0.90630778703664996 * sin(lp.phi); const double theta = asin(xy.y); const double ct = cos(theta); lp.lam /= 3.; xy.x = 2.66723 * ct * sin(lp.lam); const double D = 1 / (sqrt(0.5 * (1 + ct * cos(lp.lam)))); xy.y *= 1.24104 * D; xy.x *= D; return (xy); } PJ *PJ_PROJECTION(wag7) { P->fwd = wag7_s_forward; P->inv = nullptr; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/collg.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(collg, "Collignon") "\n\tPCyl, Sph"; #define FXC 1.12837916709551257390 #define FYC 1.77245385090551602729 #define ONEEPS 1.0000001 static PJ_XY collg_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.y = 1. - sin(lp.phi); if (xy.y <= 0.) xy.y = 0.; else xy.y = sqrt(xy.y); xy.x = FXC * lp.lam * xy.y; xy.y = FYC * (1. - xy.y); return (xy); } static PJ_LP collg_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = xy.y / FYC - 1.; lp.phi = 1. - lp.phi * lp.phi; if (fabs(lp.phi) < 1.) lp.phi = asin(lp.phi); else if (fabs(lp.phi) > ONEEPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { lp.phi = lp.phi < 0. ? -M_HALFPI : M_HALFPI; } lp.lam = 1. - sin(lp.phi); if (lp.lam <= 0.) lp.lam = 0.; else lp.lam = xy.x / (FXC * sqrt(lp.lam)); return (lp); } PJ *PJ_PROJECTION(collg) { P->es = 0.0; P->inv = collg_s_inverse; P->fwd = collg_s_forward; return P; } #undef FXC #undef FYC #undef ONEEPS
cpp
PROJ
data/projects/PROJ/src/projections/putp4p.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_putp4p_data { double C_x, C_y; }; } // anonymous namespace PROJ_HEAD(putp4p, "Putnins P4'") "\n\tPCyl, Sph"; PROJ_HEAD(weren, "Werenskiold I") "\n\tPCyl, Sph"; static PJ_XY putp4p_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_putp4p_data *Q = static_cast<struct pj_putp4p_data *>(P->opaque); lp.phi = aasin(P->ctx, 0.883883476 * sin(lp.phi)); xy.x = Q->C_x * lp.lam * cos(lp.phi); lp.phi *= 0.333333333333333; xy.x /= cos(lp.phi); xy.y = Q->C_y * sin(lp.phi); return xy; } static PJ_LP putp4p_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_putp4p_data *Q = static_cast<struct pj_putp4p_data *>(P->opaque); lp.phi = aasin(P->ctx, xy.y / Q->C_y); lp.lam = xy.x * cos(lp.phi) / Q->C_x; lp.phi *= 3.; lp.lam /= cos(lp.phi); lp.phi = aasin(P->ctx, 1.13137085 * sin(lp.phi)); return lp; } PJ *PJ_PROJECTION(putp4p) { struct pj_putp4p_data *Q = static_cast<struct pj_putp4p_data *>( calloc(1, sizeof(struct pj_putp4p_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->C_x = 0.874038744; Q->C_y = 3.883251825; P->es = 0.; P->inv = putp4p_s_inverse; P->fwd = putp4p_s_forward; return P; } PJ *PJ_PROJECTION(weren) { struct pj_putp4p_data *Q = static_cast<struct pj_putp4p_data *>( calloc(1, sizeof(struct pj_putp4p_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->C_x = 1.; Q->C_y = 4.442882938; P->es = 0.; P->inv = putp4p_s_inverse; P->fwd = putp4p_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/ocea.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(ocea, "Oblique Cylindrical Equal Area") "\n\tCyl, Sph" "lonc= alpha= or\n\tlat_1= lat_2= lon_1= lon_2="; namespace { // anonymous namespace struct pj_ocea { double rok; double rtk; double sinphi; double cosphi; }; } // anonymous namespace static PJ_XY ocea_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_ocea *Q = static_cast<struct pj_ocea *>(P->opaque); double t; xy.y = sin(lp.lam); t = cos(lp.lam); xy.x = atan((tan(lp.phi) * Q->cosphi + Q->sinphi * xy.y) / t); if (t < 0.) xy.x += M_PI; xy.x *= Q->rtk; xy.y = Q->rok * (Q->sinphi * sin(lp.phi) - Q->cosphi * cos(lp.phi) * xy.y); return xy; } static PJ_LP ocea_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_ocea *Q = static_cast<struct pj_ocea *>(P->opaque); xy.y /= Q->rok; xy.x /= Q->rtk; const double t = sqrt(1. - xy.y * xy.y); const double s = sin(xy.x); lp.phi = asin(xy.y * Q->sinphi + t * Q->cosphi * s); lp.lam = atan2(t * Q->sinphi * s - xy.y * Q->cosphi, t * cos(xy.x)); return lp; } PJ *PJ_PROJECTION(ocea) { double phi_1, phi_2, lam_1, lam_2, lonz, alpha; struct pj_ocea *Q = static_cast<struct pj_ocea *>(calloc(1, sizeof(struct pj_ocea))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->rok = 1. / P->k0; Q->rtk = P->k0; double lam_p, phi_p; /*If the keyword "alpha" is found in the sentence then use 1point+1azimuth*/ if (pj_param(P->ctx, P->params, "talpha").i) { /*Define Pole of oblique transformation from 1 point & 1 azimuth*/ // ERO: I've added M_PI so that the alpha is the angle from point 1 to // point 2 from the North in a clockwise direction (to be consistent // with omerc behavior) alpha = M_PI + pj_param(P->ctx, P->params, "ralpha").f; lonz = pj_param(P->ctx, P->params, "rlonc").f; /*Equation 9-8 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/ // Actually slightliy modified to use atan2(), as it is suggested by // Snyder for equation 9-1, but this is not mentioned here lam_p = atan2(-cos(alpha), -sin(P->phi0) * sin(alpha)) + lonz; /*Equation 9-7 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/ phi_p = asin(cos(P->phi0) * sin(alpha)); /*If the keyword "alpha" is NOT found in the sentence then use 2points*/ } else { /*Define Pole of oblique transformation from 2 points*/ phi_1 = pj_param(P->ctx, P->params, "rlat_1").f; phi_2 = pj_param(P->ctx, P->params, "rlat_2").f; lam_1 = pj_param(P->ctx, P->params, "rlon_1").f; lam_2 = pj_param(P->ctx, P->params, "rlon_2").f; /*Equation 9-1 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/ lam_p = atan2(cos(phi_1) * sin(phi_2) * cos(lam_1) - sin(phi_1) * cos(phi_2) * cos(lam_2), sin(phi_1) * cos(phi_2) * sin(lam_2) - cos(phi_1) * sin(phi_2) * sin(lam_1)); /* take care of P->lam0 wrap-around when +lam_1=-90*/ if (lam_1 == -M_HALFPI) lam_p = -lam_p; /*Equation 9-2 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/ double cos_lamp_m_minus_lam_1 = cos(lam_p - lam_1); double tan_phi_1 = tan(phi_1); if (tan_phi_1 == 0.0) { // Not sure if we want to support this case, but at least this // avoids a division by zero, and gives the same result as the below // atan() phi_p = (cos_lamp_m_minus_lam_1 >= 0.0) ? -M_HALFPI : M_HALFPI; } else { phi_p = atan(-cos_lamp_m_minus_lam_1 / tan_phi_1); } } P->lam0 = lam_p + M_HALFPI; Q->cosphi = cos(phi_p); Q->sinphi = sin(phi_p); P->inv = ocea_s_inverse; P->fwd = ocea_s_forward; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/wag3.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(wag3, "Wagner III") "\n\tPCyl, Sph\n\tlat_ts="; #define TWOTHIRD 0.6666666666666666666667 namespace { // anonymous namespace struct pj_wag3 { double C_x; }; } // anonymous namespace static PJ_XY wag3_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = static_cast<struct pj_wag3 *>(P->opaque)->C_x * lp.lam * cos(TWOTHIRD * lp.phi); xy.y = lp.phi; return xy; } static PJ_LP wag3_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = xy.y; lp.lam = xy.x / (static_cast<struct pj_wag3 *>(P->opaque)->C_x * cos(TWOTHIRD * lp.phi)); return lp; } PJ *PJ_PROJECTION(wag3) { double ts; struct pj_wag3 *Q = static_cast<struct pj_wag3 *>(calloc(1, sizeof(struct pj_wag3))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; ts = pj_param(P->ctx, P->params, "rlat_ts").f; static_cast<struct pj_wag3 *>(P->opaque)->C_x = cos(ts) / cos(2. * ts / 3.); P->es = 0.; P->inv = wag3_s_inverse; P->fwd = wag3_s_forward; return P; } #undef TWOTHIRD
cpp
PROJ
data/projects/PROJ/src/projections/aeqd.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the aeqd (Azimuthal Equidistant) projection. * Author: Gerald Evenden * ****************************************************************************** * Copyright (c) 1995, Gerald Evenden * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #include "geodesic.h" #include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> namespace pj_aeqd_ns { enum Mode { N_POLE = 0, S_POLE = 1, EQUIT = 2, OBLIQ = 3 }; } namespace { // anonymous namespace struct pj_aeqd_data { double sinph0; double cosph0; double *en; double M1; double N1; double Mp; double He; double G; enum ::pj_aeqd_ns::Mode mode; struct geod_geodesic g; }; } // anonymous namespace PROJ_HEAD(aeqd, "Azimuthal Equidistant") "\n\tAzi, Sph&Ell\n\tlat_0 guam"; #define EPS10 1.e-10 #define TOL 1.e-14 static PJ *destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_aeqd_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } static PJ_XY e_guam_fwd(PJ_LP lp, PJ *P) { /* Guam elliptical */ PJ_XY xy = {0.0, 0.0}; struct pj_aeqd_data *Q = static_cast<struct pj_aeqd_data *>(P->opaque); double cosphi, sinphi, t; cosphi = cos(lp.phi); sinphi = sin(lp.phi); t = 1. / sqrt(1. - P->es * sinphi * sinphi); xy.x = lp.lam * cosphi * t; xy.y = pj_mlfn(lp.phi, sinphi, cosphi, Q->en) - Q->M1 + .5 * lp.lam * lp.lam * cosphi * sinphi * t; return xy; } static PJ_XY aeqd_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_aeqd_data *Q = static_cast<struct pj_aeqd_data *>(P->opaque); double coslam, cosphi, sinphi, rho; double azi1, azi2, s12; double lat1, lon1, lat2, lon2; coslam = cos(lp.lam); switch (Q->mode) { case pj_aeqd_ns::N_POLE: coslam = -coslam; PROJ_FALLTHROUGH; case pj_aeqd_ns::S_POLE: cosphi = cos(lp.phi); sinphi = sin(lp.phi); rho = fabs(Q->Mp - pj_mlfn(lp.phi, sinphi, cosphi, Q->en)); xy.x = rho * sin(lp.lam); xy.y = rho * coslam; break; case pj_aeqd_ns::EQUIT: case pj_aeqd_ns::OBLIQ: if (fabs(lp.lam) < EPS10 && fabs(lp.phi - P->phi0) < EPS10) { xy.x = xy.y = 0.; break; } lat1 = P->phi0 / DEG_TO_RAD; lon1 = 0; lat2 = lp.phi / DEG_TO_RAD; lon2 = lp.lam / DEG_TO_RAD; geod_inverse(&Q->g, lat1, lon1, lat2, lon2, &s12, &azi1, &azi2); azi1 *= DEG_TO_RAD; xy.x = s12 * sin(azi1); xy.y = s12 * cos(azi1); break; } return xy; } static PJ_XY aeqd_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_aeqd_data *Q = static_cast<struct pj_aeqd_data *>(P->opaque); if (Q->mode == pj_aeqd_ns::EQUIT) { const double cosphi = cos(lp.phi); const double sinphi = sin(lp.phi); const double coslam = cos(lp.lam); const double sinlam = sin(lp.lam); xy.y = cosphi * coslam; if (fabs(fabs(xy.y) - 1.) < TOL) { if (xy.y < 0.) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } else return aeqd_e_forward(lp, P); } else { xy.y = acos(xy.y); xy.y /= sin(xy.y); xy.x = xy.y * cosphi * sinlam; xy.y *= sinphi; } } else if (Q->mode == pj_aeqd_ns::OBLIQ) { const double cosphi = cos(lp.phi); const double sinphi = sin(lp.phi); const double coslam = cos(lp.lam); const double sinlam = sin(lp.lam); const double cosphi_x_coslam = cosphi * coslam; xy.y = Q->sinph0 * sinphi + Q->cosph0 * cosphi_x_coslam; if (fabs(fabs(xy.y) - 1.) < TOL) { if (xy.y < 0.) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } else return aeqd_e_forward(lp, P); } else { xy.y = acos(xy.y); xy.y /= sin(xy.y); xy.x = xy.y * cosphi * sinlam; xy.y *= Q->cosph0 * sinphi - Q->sinph0 * cosphi_x_coslam; } } else { double coslam = cos(lp.lam); double sinlam = sin(lp.lam); if (Q->mode == pj_aeqd_ns::N_POLE) { lp.phi = -lp.phi; coslam = -coslam; } if (fabs(lp.phi - M_HALFPI) < EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.y = (M_HALFPI + lp.phi); xy.x = xy.y * sinlam; xy.y *= coslam; } return xy; } static PJ_LP e_guam_inv(PJ_XY xy, PJ *P) { /* Guam elliptical */ PJ_LP lp = {0.0, 0.0}; struct pj_aeqd_data *Q = static_cast<struct pj_aeqd_data *>(P->opaque); double x2, t = 0.0; int i; x2 = 0.5 * xy.x * xy.x; lp.phi = P->phi0; for (i = 0; i < 3; ++i) { t = P->e * sin(lp.phi); t = sqrt(1. - t * t); lp.phi = pj_inv_mlfn(Q->M1 + xy.y - x2 * tan(lp.phi) * t, Q->en); } lp.lam = xy.x * t / cos(lp.phi); return lp; } static PJ_LP aeqd_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_aeqd_data *Q = static_cast<struct pj_aeqd_data *>(P->opaque); double azi1, azi2, s12, lat1, lon1, lat2, lon2; if ((s12 = hypot(xy.x, xy.y)) < EPS10) { lp.phi = P->phi0; lp.lam = 0.; return (lp); } if (Q->mode == pj_aeqd_ns::OBLIQ || Q->mode == pj_aeqd_ns::EQUIT) { lat1 = P->phi0 / DEG_TO_RAD; lon1 = 0; azi1 = atan2(xy.x, xy.y) / DEG_TO_RAD; // Clockwise from north geod_direct(&Q->g, lat1, lon1, azi1, s12, &lat2, &lon2, &azi2); lp.phi = lat2 * DEG_TO_RAD; lp.lam = lon2 * DEG_TO_RAD; } else { /* Polar */ lp.phi = pj_inv_mlfn( Q->mode == pj_aeqd_ns::N_POLE ? Q->Mp - s12 : Q->Mp + s12, Q->en); lp.lam = atan2(xy.x, Q->mode == pj_aeqd_ns::N_POLE ? -xy.y : xy.y); } return lp; } static PJ_LP aeqd_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_aeqd_data *Q = static_cast<struct pj_aeqd_data *>(P->opaque); double cosc, c_rh, sinc; c_rh = hypot(xy.x, xy.y); if (c_rh > M_PI) { if (c_rh - EPS10 > M_PI) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } c_rh = M_PI; } else if (c_rh < EPS10) { lp.phi = P->phi0; lp.lam = 0.; return (lp); } if (Q->mode == pj_aeqd_ns::OBLIQ || Q->mode == pj_aeqd_ns::EQUIT) { sinc = sin(c_rh); cosc = cos(c_rh); if (Q->mode == pj_aeqd_ns::EQUIT) { lp.phi = aasin(P->ctx, xy.y * sinc / c_rh); xy.x *= sinc; xy.y = cosc * c_rh; } else { lp.phi = aasin(P->ctx, cosc * Q->sinph0 + xy.y * sinc * Q->cosph0 / c_rh); xy.y = (cosc - Q->sinph0 * sin(lp.phi)) * c_rh; xy.x *= sinc * Q->cosph0; } lp.lam = xy.y == 0. ? 0. : atan2(xy.x, xy.y); } else if (Q->mode == pj_aeqd_ns::N_POLE) { lp.phi = M_HALFPI - c_rh; lp.lam = atan2(xy.x, -xy.y); } else { lp.phi = c_rh - M_HALFPI; lp.lam = atan2(xy.x, xy.y); } return lp; } PJ *PJ_PROJECTION(aeqd) { struct pj_aeqd_data *Q = static_cast<struct pj_aeqd_data *>( calloc(1, sizeof(struct pj_aeqd_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = destructor; geod_init(&Q->g, 1, P->f); if (fabs(fabs(P->phi0) - M_HALFPI) < EPS10) { Q->mode = P->phi0 < 0. ? pj_aeqd_ns::S_POLE : pj_aeqd_ns::N_POLE; Q->sinph0 = P->phi0 < 0. ? -1. : 1.; Q->cosph0 = 0.; } else if (fabs(P->phi0) < EPS10) { Q->mode = pj_aeqd_ns::EQUIT; Q->sinph0 = 0.; Q->cosph0 = 1.; } else { Q->mode = pj_aeqd_ns::OBLIQ; Q->sinph0 = sin(P->phi0); Q->cosph0 = cos(P->phi0); } if (P->es == 0.0) { P->inv = aeqd_s_inverse; P->fwd = aeqd_s_forward; } else { if (!(Q->en = pj_enfn(P->n))) return pj_default_destructor(P, 0); if (pj_param(P->ctx, P->params, "bguam").i) { Q->M1 = pj_mlfn(P->phi0, Q->sinph0, Q->cosph0, Q->en); P->inv = e_guam_inv; P->fwd = e_guam_fwd; } else { switch (Q->mode) { case pj_aeqd_ns::N_POLE: Q->Mp = pj_mlfn(M_HALFPI, 1., 0., Q->en); break; case pj_aeqd_ns::S_POLE: Q->Mp = pj_mlfn(-M_HALFPI, -1., 0., Q->en); break; case pj_aeqd_ns::EQUIT: case pj_aeqd_ns::OBLIQ: Q->N1 = 1. / sqrt(1. - P->es * Q->sinph0 * Q->sinph0); Q->He = P->e / sqrt(P->one_es); Q->G = Q->sinph0 * Q->He; Q->He *= Q->cosph0; break; } P->inv = aeqd_e_inverse; P->fwd = aeqd_e_forward; } } return P; } #undef EPS10 #undef TOL
cpp
PROJ
data/projects/PROJ/src/projections/labrd.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(labrd, "Laborde") "\n\tCyl, Sph\n\tSpecial for Madagascar\n\tlat_0="; #define EPS 1.e-10 namespace { // anonymous namespace struct pj_opaque { double kRg, p0s, A, C, Ca, Cb, Cc, Cd; }; } // anonymous namespace static PJ_XY labrd_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); double V1, V2, ps, sinps, cosps, sinps2, cosps2; double I1, I2, I3, I4, I5, I6, x2, y2, t; V1 = Q->A * log(tan(M_FORTPI + .5 * lp.phi)); t = P->e * sin(lp.phi); V2 = .5 * P->e * Q->A * log((1. + t) / (1. - t)); ps = 2. * (atan(exp(V1 - V2 + Q->C)) - M_FORTPI); I1 = ps - Q->p0s; cosps = cos(ps); cosps2 = cosps * cosps; sinps = sin(ps); sinps2 = sinps * sinps; I4 = Q->A * cosps; I2 = .5 * Q->A * I4 * sinps; I3 = I2 * Q->A * Q->A * (5. * cosps2 - sinps2) / 12.; I6 = I4 * Q->A * Q->A; I5 = I6 * (cosps2 - sinps2) / 6.; I6 *= Q->A * Q->A * (5. * cosps2 * cosps2 + sinps2 * (sinps2 - 18. * cosps2)) / 120.; t = lp.lam * lp.lam; xy.x = Q->kRg * lp.lam * (I4 + t * (I5 + t * I6)); xy.y = Q->kRg * (I1 + t * (I2 + t * I3)); x2 = xy.x * xy.x; y2 = xy.y * xy.y; V1 = 3. * xy.x * y2 - xy.x * x2; V2 = xy.y * y2 - 3. * x2 * xy.y; xy.x += Q->Ca * V1 + Q->Cb * V2; xy.y += Q->Ca * V2 - Q->Cb * V1; return xy; } static PJ_LP labrd_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); /* t = 0.0 optimization is to avoid a false positive cppcheck warning */ /* (cppcheck git beaf29c15867984aa3c2a15cf15bd7576ccde2b3). Might no */ /* longer be necessary with later versions. */ double x2, y2, V1, V2, V3, V4, t = 0.0, t2, ps, pe, tpe, s; double I7, I8, I9, I10, I11, d, Re; int i; x2 = xy.x * xy.x; y2 = xy.y * xy.y; V1 = 3. * xy.x * y2 - xy.x * x2; V2 = xy.y * y2 - 3. * x2 * xy.y; V3 = xy.x * (5. * y2 * y2 + x2 * (-10. * y2 + x2)); V4 = xy.y * (5. * x2 * x2 + y2 * (-10. * x2 + y2)); xy.x += -Q->Ca * V1 - Q->Cb * V2 + Q->Cc * V3 + Q->Cd * V4; xy.y += Q->Cb * V1 - Q->Ca * V2 - Q->Cd * V3 + Q->Cc * V4; ps = Q->p0s + xy.y / Q->kRg; pe = ps + P->phi0 - Q->p0s; for (i = 20; i; --i) { V1 = Q->A * log(tan(M_FORTPI + .5 * pe)); tpe = P->e * sin(pe); V2 = .5 * P->e * Q->A * log((1. + tpe) / (1. - tpe)); t = ps - 2. * (atan(exp(V1 - V2 + Q->C)) - M_FORTPI); pe += t; if (fabs(t) < EPS) break; } t = P->e * sin(pe); t = 1. - t * t; Re = P->one_es / (t * sqrt(t)); t = tan(ps); t2 = t * t; s = Q->kRg * Q->kRg; d = Re * P->k0 * Q->kRg; I7 = t / (2. * d); I8 = t * (5. + 3. * t2) / (24. * d * s); d = cos(ps) * Q->kRg * Q->A; I9 = 1. / d; d *= s; I10 = (1. + 2. * t2) / (6. * d); I11 = (5. + t2 * (28. + 24. * t2)) / (120. * d * s); x2 = xy.x * xy.x; lp.phi = pe + x2 * (-I7 + I8 * x2); lp.lam = xy.x * (I9 + x2 * (-I10 + x2 * I11)); return lp; } PJ *PJ_PROJECTION(labrd) { double Az, sinp, R, N, t; struct pj_opaque *Q = static_cast<struct pj_opaque *>(calloc(1, sizeof(struct pj_opaque))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (P->phi0 == 0.) { proj_log_error( P, _("Invalid value for lat_0: lat_0 should be different from 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Az = pj_param(P->ctx, P->params, "razi").f; sinp = sin(P->phi0); t = 1. - P->es * sinp * sinp; N = 1. / sqrt(t); R = P->one_es * N / t; Q->kRg = P->k0 * sqrt(N * R); Q->p0s = atan(sqrt(R / N) * tan(P->phi0)); Q->A = sinp / sin(Q->p0s); t = P->e * sinp; Q->C = .5 * P->e * Q->A * log((1. + t) / (1. - t)) + -Q->A * log(tan(M_FORTPI + .5 * P->phi0)) + log(tan(M_FORTPI + .5 * Q->p0s)); t = Az + Az; Q->Cb = 1. / (12. * Q->kRg * Q->kRg); Q->Ca = (1. - cos(t)) * Q->Cb; Q->Cb *= sin(t); Q->Cc = 3. * (Q->Ca * Q->Ca - Q->Cb * Q->Cb); Q->Cd = 6. * Q->Ca * Q->Cb; P->inv = labrd_e_inverse; P->fwd = labrd_e_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/eqc.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_eqc_data { double rc; }; } // anonymous namespace PROJ_HEAD(eqc, "Equidistant Cylindrical (Plate Carree)") "\n\tCyl, Sph\n\tlat_ts=[, lat_0=0]"; static PJ_XY eqc_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_eqc_data *Q = static_cast<struct pj_eqc_data *>(P->opaque); xy.x = Q->rc * lp.lam; xy.y = lp.phi - P->phi0; return xy; } static PJ_LP eqc_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_eqc_data *Q = static_cast<struct pj_eqc_data *>(P->opaque); lp.lam = xy.x / Q->rc; lp.phi = xy.y + P->phi0; return lp; } PJ *PJ_PROJECTION(eqc) { struct pj_eqc_data *Q = static_cast<struct pj_eqc_data *>( calloc(1, sizeof(struct pj_eqc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if ((Q->rc = cos(pj_param(P->ctx, P->params, "rlat_ts").f)) <= 0.) { proj_log_error( P, _("Invalid value for lat_ts: |lat_ts| should be <= 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->inv = eqc_s_inverse; P->fwd = eqc_s_forward; P->es = 0.; return P; }
cpp