repo_name
stringclasses
10 values
file_path
stringlengths
29
222
content
stringlengths
24
926k
extention
stringclasses
5 values
rticonnextdds-usecases
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/src/TrackGui/FlightInfo.h
/* * (c) 2021 Copyright, Real-Time Innovations, Inc. (RTI) All rights reserved. * * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are * subject to this license. The software is provided "as is", with no warranty * of any type, including any warranty for fitness for any purpose. RTI is * under no obligation to maintain or support the software. RTI shall not be * liable for any incidental or consequential damages arising out of the use or * inability to use the software. */ #ifndef FLIGHT_INFO_H #define FLIGHT_INFO_H #include "wx/setup.h" #include "../Generated/AirTrafficControl.hpp" // ------------------------------------------------------------------------- // // // FlightInfo: // This type represents all the information available about a particular // flight, including current track position and flight plan. // // In this example using the data types generated as a part of the network // infrastructure. It is just as likely that this would be a data type created // by the application that represents the applications model of a flight type. // // ------------------------------------------------------------------------- // struct FlightInfo { com::atc::generated::Track _track; com::atc::generated::FlightPlan _plan; }; #endif
h
rticonnextdds-usecases
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/resource/gui/resource.h
/* * (c) 2021 Copyright, Real-Time Innovations, Inc. (RTI) * All rights reserved. * * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the Software solely in combination with RTI Connext DDS. Licensee * may redistribute copies of the Software provided that all such copies are * subject to this License. The Software is provided "as is", with no warranty * of any type, including any warranty for fitness for any purpose. RTI is * under no obligation to maintain or support the Software. RTI shall not be * liable for any incidental or consequential damages arising out of the use or * inability to use the Software. For purposes of clarity, nothing in this * License prevents Licensee from using alternate versions of DDS, provided * that Licensee may not combine or link such alternate versions of DDS with * the Software. */ #ifndef IDC_STATIC #define IDC_STATIC (-1) #endif #define IDI_ICON1 100
h
PROJ
data/projects/PROJ/examples/EPSG_4326_to_32631.cpp
/******************************************************************************* Example code that illustrates how to convert between two CRS Note: This file is in-lined in the documentation. Any changes must be reflected in docs/source/development/quickstart.rst *******************************************************************************/ #include <cassert> #include <cmath> // for HUGE_VAL #include <iomanip> // for std::setprecision() #include <iostream> #include "proj/coordinateoperation.hpp" #include "proj/crs.hpp" #include "proj/io.hpp" #include "proj/util.hpp" // for nn_dynamic_pointer_cast using namespace NS_PROJ::crs; using namespace NS_PROJ::io; using namespace NS_PROJ::operation; using namespace NS_PROJ::util; int main(void) { auto dbContext = DatabaseContext::create(); // Instantiate a generic authority factory, that is not tied to a particular // authority, to be able to get transformations registered by different // authorities. This can only be used for CoordinateOperationContext. auto authFactory = AuthorityFactory::create(dbContext, std::string()); // Create a coordinate operation context, that can be customized to ammend // the way coordinate operations are computed. Here we ask for default // settings. auto coord_op_ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); // Instantiate a authority factory for EPSG related objects. auto authFactoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); // Instantiate source CRS from EPSG code auto sourceCRS = authFactoryEPSG->createCoordinateReferenceSystem("4326"); // Instantiate target CRS from PROJ.4 string (commented out, the equivalent // from the EPSG code) // auto targetCRS = // authFactoryEPSG->createCoordinateReferenceSystem("32631"); auto targetCRS = NN_CHECK_THROW(nn_dynamic_pointer_cast<CRS>(createFromUserInput( "+proj=utm +zone=31 +datum=WGS84 +type=crs", dbContext))); // List operations available to transform from EPSG:4326 // (WGS 84 latitude/longitude) to EPSG:32631 (WGS 84 / UTM zone 31N). auto list = CoordinateOperationFactory::create()->createOperations( sourceCRS, targetCRS, coord_op_ctxt); // Check that we got a non-empty list of operations // The list is sorted from the most relevant to the less relevant one. // Cf // https://proj.org/operations/operations_computation.html#filtering-and-sorting-of-coordinate-operations // for more details on the sorting of those operations. // For a transformation between a projected CRS and its base CRS, like // we do here, there will be only one operation. assert(!list.empty()); // Create an execution context (must only be used by one thread at a time) PJ_CONTEXT *ctx = proj_context_create(); // Create a coordinate transformer from the first operation of the list auto transformer = list[0]->coordinateTransformer(ctx); // Perform the coordinate transformation. PJ_COORD c = {{ 49.0, // latitude in degree 2.0, // longitude in degree 0.0, // z ordinate. unused HUGE_VAL // time ordinate. unused }}; c = transformer->transform(c); // Display result std::cout << std::fixed << std::setprecision(3); std::cout << "Easting: " << c.v[0] << std::endl; // should be 426857.988 std::cout << "Northing: " << c.v[1] << std::endl; // should be 5427937.523 // Destroy execution context proj_context_destroy(ctx); return 0; }
cpp
PROJ
data/projects/PROJ/examples/crs_to_geodetic.c
/******************************************************************************* Example code that illustrates how to convert between a CRS and geodetic coordnates for that CRS. Note: This file is in-lined in the documentation. Any changes must be reflected in docs/source/development/quickstart.rst *******************************************************************************/ #include <math.h> #include <proj.h> #include <stdio.h> int main(void) { /* Create the context. */ /* You may set C=PJ_DEFAULT_CTX if you are sure you will */ /* use PJ objects from only one thread */ PJ_CONTEXT *C = proj_context_create(); /* Create a projection. */ PJ *P = proj_create(C, "+proj=utm +zone=32 +datum=WGS84 +type=crs"); if (0 == P) { fprintf(stderr, "Failed to create transformation object.\n"); return 1; } /* Get the geodetic CRS for that projection. */ PJ *G = proj_crs_get_geodetic_crs(C, P); /* Create the transform from geodetic to projected coordinates.*/ PJ_AREA *A = NULL; const char *const *options = NULL; PJ *G2P = proj_create_crs_to_crs_from_pj(C, G, P, A, options); /* Longitude and latitude of Copenhagen, in degrees. */ double lon = 12.0, lat = 55.0; /* Prepare the input */ PJ_COORD c_in; c_in.lpzt.z = 0.0; c_in.lpzt.t = HUGE_VAL; // important only for time-dependent projections c_in.lp.lam = lon; c_in.lp.phi = lat; printf("Input longitude: %g, latitude: %g (degrees)\n", c_in.lp.lam, c_in.lp.phi); /* Compute easting and northing */ PJ_COORD c_out = proj_trans(G2P, PJ_FWD, c_in); printf("Output easting: %g, northing: %g (meters)\n", c_out.enu.e, c_out.enu.n); /* Apply the inverse transform */ PJ_COORD c_inv = proj_trans(G2P, PJ_INV, c_out); printf("Inverse applied. Longitude: %g, latitude: %g (degrees)\n", c_inv.lp.lam, c_inv.lp.phi); /* Clean up */ proj_destroy(P); proj_destroy(G); proj_destroy(G2P); proj_context_destroy(C); /* may be omitted in the single threaded case */ return 0; }
c
PROJ
data/projects/PROJ/examples/pj_obs_api_mini_demo.c
/******************************************************************************* Simple example code demonstrating use of the proj.h API for 2D coordinate transformations. Note: This file is in-lined in the documentation. Any changes must be reflected in docs/source/development/quickstart.rst Thomas Knudsen, 2016-10-30/2017-07-06 *******************************************************************************/ #include <proj.h> #include <stdio.h> int main(void) { PJ_CONTEXT *C; PJ *P; PJ *norm; PJ_COORD a, b; /* or you may set C=PJ_DEFAULT_CTX if you are sure you will */ /* use PJ objects from only one thread */ C = proj_context_create(); P = proj_create_crs_to_crs( C, "EPSG:4326", "+proj=utm +zone=32 +datum=WGS84", /* or EPSG:32632 */ NULL); if (0 == P) { fprintf(stderr, "Failed to create transformation object.\n"); return 1; } /* This will ensure that the order of coordinates for the input CRS */ /* will be longitude, latitude, whereas EPSG:4326 mandates latitude, */ /* longitude */ norm = proj_normalize_for_visualization(C, P); if (0 == norm) { fprintf(stderr, "Failed to normalize transformation object.\n"); return 1; } proj_destroy(P); P = norm; /* a coordinate union representing Copenhagen: 55d N, 12d E */ /* Given that we have used proj_normalize_for_visualization(), the order */ /* of coordinates is longitude, latitude, and values are expressed in */ /* degrees. */ a = proj_coord(12, 55, 0, 0); /* transform to UTM zone 32, then back to geographical */ b = proj_trans(P, PJ_FWD, a); printf("easting: %.3f, northing: %.3f\n", b.enu.e, b.enu.n); b = proj_trans(P, PJ_INV, b); printf("longitude: %g, latitude: %g\n", b.lp.lam, b.lp.phi); /* Clean up */ proj_destroy(P); proj_context_destroy(C); /* may be omitted in the single threaded case */ return 0; }
c
PROJ
data/projects/PROJ/src/wkt1_parser.cpp
/****************************************************************************** * Project: PROJ * Purpose: WKT1 parser grammar * Author: Even Rouault, <even dot rouault at mines dash paris dot org> * ****************************************************************************** * Copyright (c) 2013, Even Rouault <even dot rouault at mines-paris dot org> * * 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 <algorithm> #include <cstring> #include <string> #include "wkt1_parser.h" #include "wkt_parser.hpp" using namespace NS_PROJ::internal; //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- struct pj_wkt1_parse_context : public pj_wkt_parse_context {}; // --------------------------------------------------------------------------- void pj_wkt1_error(pj_wkt1_parse_context *context, const char *msg) { pj_wkt_error(context, msg); } // --------------------------------------------------------------------------- std::string pj_wkt1_parse(const std::string &wkt) { pj_wkt1_parse_context context; context.pszInput = wkt.c_str(); context.pszLastSuccess = wkt.c_str(); context.pszNext = wkt.c_str(); if (pj_wkt1_parse(&context) != 0) { return context.errorMsg; } return std::string(); } // --------------------------------------------------------------------------- typedef struct { const char *pszToken; int nTokenVal; } osr_cs_wkt_tokens; #define PAIR(X) \ { \ #X, T_##X \ } static const osr_cs_wkt_tokens tokens[] = { PAIR(PARAM_MT), PAIR(PARAMETER), PAIR(CONCAT_MT), PAIR(INVERSE_MT), PAIR(PASSTHROUGH_MT), PAIR(PROJCS), PAIR(PROJECTION), PAIR(GEOGCS), PAIR(DATUM), PAIR(SPHEROID), PAIR(PRIMEM), PAIR(UNIT), PAIR(GEOCCS), PAIR(AUTHORITY), PAIR(VERT_CS), PAIR(VERTCS), PAIR(VERT_DATUM), PAIR(VDATUM), PAIR(COMPD_CS), PAIR(AXIS), PAIR(TOWGS84), PAIR(FITTED_CS), PAIR(LOCAL_CS), PAIR(LOCAL_DATUM), PAIR(LINUNIT), PAIR(EXTENSION)}; // --------------------------------------------------------------------------- int pj_wkt1_lex(YYSTYPE * /*pNode */, pj_wkt1_parse_context *context) { size_t i; const char *pszInput = context->pszNext; /* -------------------------------------------------------------------- */ /* Skip white space. */ /* -------------------------------------------------------------------- */ while (*pszInput == ' ' || *pszInput == '\t' || *pszInput == 10 || *pszInput == 13) pszInput++; context->pszLastSuccess = pszInput; if (*pszInput == '\0') { context->pszNext = pszInput; return EOF; } /* -------------------------------------------------------------------- */ /* Recognize node names. */ /* -------------------------------------------------------------------- */ if (isalpha(*pszInput)) { for (i = 0; i < sizeof(tokens) / sizeof(tokens[0]); i++) { if (ci_starts_with(pszInput, tokens[i].pszToken) && !isalpha(pszInput[strlen(tokens[i].pszToken)])) { context->pszNext = pszInput + strlen(tokens[i].pszToken); return tokens[i].nTokenVal; } } } /* -------------------------------------------------------------------- */ /* Recognize double quoted strings. */ /* -------------------------------------------------------------------- */ if (*pszInput == '"') { pszInput++; while (*pszInput != '\0' && *pszInput != '"') pszInput++; if (*pszInput == '\0') { context->pszNext = pszInput; return EOF; } context->pszNext = pszInput + 1; return T_STRING; } /* -------------------------------------------------------------------- */ /* Recognize numerical values. */ /* -------------------------------------------------------------------- */ if (((*pszInput == '-' || *pszInput == '+') && pszInput[1] >= '0' && pszInput[1] <= '9') || (*pszInput >= '0' && *pszInput <= '9')) { if (*pszInput == '-' || *pszInput == '+') pszInput++; // collect non-decimal part of number while (*pszInput >= '0' && *pszInput <= '9') pszInput++; // collect decimal places. if (*pszInput == '.') { pszInput++; while (*pszInput >= '0' && *pszInput <= '9') pszInput++; } // collect exponent if (*pszInput == 'e' || *pszInput == 'E') { pszInput++; if (*pszInput == '-' || *pszInput == '+') pszInput++; while (*pszInput >= '0' && *pszInput <= '9') pszInput++; } context->pszNext = pszInput; return T_NUMBER; } /* -------------------------------------------------------------------- */ /* Recognize identifiers. */ /* -------------------------------------------------------------------- */ if ((*pszInput >= 'A' && *pszInput <= 'Z') || (*pszInput >= 'a' && *pszInput <= 'z')) { pszInput++; while ((*pszInput >= 'A' && *pszInput <= 'Z') || (*pszInput >= 'a' && *pszInput <= 'z')) pszInput++; context->pszNext = pszInput; return T_IDENTIFIER; } /* -------------------------------------------------------------------- */ /* Handle special tokens. */ /* -------------------------------------------------------------------- */ context->pszNext = pszInput + 1; return *pszInput; } //! @endcond
cpp
PROJ
data/projects/PROJ/src/mutex.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Mutex (thread lock) functions. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2009, 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. *****************************************************************************/ #include <mutex> #include "proj.h" #include "proj_internal.h" static std::recursive_mutex core_lock; /************************************************************************/ /* pj_acquire_lock() */ /* */ /* Acquire the PROJ.4 lock. */ /************************************************************************/ void pj_acquire_lock() { core_lock.lock(); } /************************************************************************/ /* pj_release_lock() */ /* */ /* Release the PROJ.4 lock. */ /************************************************************************/ void pj_release_lock() { core_lock.unlock(); }
cpp
PROJ
data/projects/PROJ/src/gauss.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 <math.h> #include <stdlib.h> #include "proj.h" #include "proj_internal.h" #define MAX_ITER 20 namespace { // anonymous namespace struct GAUSS { double C; double K; double e; double ratexp; }; } // anonymous namespace #define DEL_TOL 1e-14 static double srat(double esinp, double ratexp) { return (pow((1. - esinp) / (1. + esinp), ratexp)); } void *pj_gauss_ini(double e, double phi0, double *chi, double *rc) { double sphi, cphi, es; struct GAUSS *en; if ((en = (struct GAUSS *)malloc(sizeof(struct GAUSS))) == nullptr) return (nullptr); es = e * e; en->e = e; sphi = sin(phi0); cphi = cos(phi0); cphi *= cphi; *rc = sqrt(1. - es) / (1. - es * sphi * sphi); en->C = sqrt(1. + es * cphi * cphi / (1. - es)); if (en->C == 0.0) { free(en); return nullptr; } *chi = asin(sphi / en->C); en->ratexp = 0.5 * en->C * e; double srat_val = srat(en->e * sphi, en->ratexp); if (srat_val == 0.0) { free(en); return nullptr; } if (.5 * phi0 + M_FORTPI < 1e-10) { en->K = 1.0 / srat_val; } else { en->K = tan(.5 * *chi + M_FORTPI) / (pow(tan(.5 * phi0 + M_FORTPI), en->C) * srat_val); } return ((void *)en); } PJ_LP pj_gauss(PJ_CONTEXT *ctx, PJ_LP elp, const void *data) { const struct GAUSS *en = (const struct GAUSS *)data; PJ_LP slp; (void)ctx; slp.phi = 2. * atan(en->K * pow(tan(.5 * elp.phi + M_FORTPI), en->C) * srat(en->e * sin(elp.phi), en->ratexp)) - M_HALFPI; slp.lam = en->C * (elp.lam); return (slp); } PJ_LP pj_inv_gauss(PJ_CONTEXT *ctx, PJ_LP slp, const void *data) { const struct GAUSS *en = (const struct GAUSS *)data; PJ_LP elp; double num; int i; elp.lam = slp.lam / en->C; num = pow(tan(.5 * slp.phi + M_FORTPI) / en->K, 1. / en->C); for (i = MAX_ITER; i; --i) { elp.phi = 2. * atan(num * srat(en->e * sin(slp.phi), -.5 * en->e)) - M_HALFPI; if (fabs(elp.phi - slp.phi) < DEL_TOL) break; slp.phi = elp.phi; } /* convergence failed */ if (!i) proj_context_errno_set( ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return (elp); }
cpp
PROJ
data/projects/PROJ/src/adjlon.cpp
/* reduce argument to range +/- PI */ #include <math.h> #include "proj.h" #include "proj_internal.h" double adjlon(double longitude) { /* Let longitude slightly overshoot, to avoid spurious sign switching at the * date line */ if (fabs(longitude) < M_PI + 1e-12) return longitude; /* adjust to 0..2pi range */ longitude += M_PI; /* remove integral # of 'revolutions'*/ longitude -= M_TWOPI * floor(longitude / M_TWOPI); /* adjust back to -pi..pi range */ longitude -= M_PI; return longitude; }
cpp
PROJ
data/projects/PROJ/src/proj.h
/****************************************************************************** * Project: PROJ.4 * Purpose: Revised, experimental API for PROJ.4, intended as the foundation * for added geodetic functionality. * * The original proj API (defined previously in projects.h) has grown * organically over the years, but it has also grown somewhat messy. * * The same has happened with the newer high level API (defined in * proj_api.h): To support various historical objectives, proj_api.h * contains a rather complex combination of conditional defines and * typedefs. Probably for good (historical) reasons, which are not * always evident from today's perspective. * * This is an evolving attempt at creating a re-rationalized API * with primary design goals focused on sanitizing the namespaces. * Hence, all symbols exposed are being moved to the proj_ namespace, * while all data types are being moved to the PJ_ namespace. * * Please note that this API is *orthogonal* to the previous APIs: * Apart from some inclusion guards, projects.h and proj_api.h are not * touched - if you do not include proj.h, the projects and proj_api * APIs should work as they always have. * * A few implementation details: * * Apart from the namespacing efforts, I'm trying to eliminate three * proj_api elements, which I have found especially confusing. * * FIRST and foremost, I try to avoid typedef'ing away pointer * semantics. I agree that it can be occasionally useful, but I * prefer having the pointer nature of function arguments being * explicitly visible. * * Hence, projCtx has been replaced by PJ_CONTEXT *. * and projPJ has been replaced by PJ * * * SECOND, I try to eliminate cases of information hiding implemented * by redefining data types to void pointers. * * I prefer using a combination of forward declarations and typedefs. * Hence: * typedef void *projCtx; * Has been replaced by: * struct projCtx_t; * typedef struct projCtx_t PJ_CONTEXT; * This makes it possible for the calling program to know that the * PJ_CONTEXT data type exists, and handle pointers to that data type * without having any idea about its internals. * * (obviously, in this example, struct projCtx_t should also be * renamed struct pj_ctx some day, but for backwards compatibility * it remains as-is for now). * * THIRD, I try to eliminate implicit type punning. Hence this API * introduces the PJ_COORD union data type, for generic 4D coordinate * handling. * * PJ_COORD makes it possible to make explicit the previously used * "implicit type punning", where a XY is turned into a LP by * re#defining both as UV, behind the back of the user. * * The PJ_COORD union is used for storing 1D, 2D, 3D and 4D *coordinates. * * The bare essentials API presented here follows the PROJ.4 * convention of sailing the coordinate to be reprojected, up on * the stack ("call by value"), and symmetrically returning the * result on the stack. Although the PJ_COORD object is twice as large * as the traditional XY and LP objects, timing results have shown the * overhead to be very reasonable. * * Contexts and thread safety * -------------------------- * * After a year of experiments (and previous experience from the * trlib transformation library) it has become clear that the * context subsystem is unavoidable in a multi-threaded world. * Hence, instead of hiding it away, we move it into the limelight, * highly recommending (but not formally requiring) the bracketing * of any code block calling PROJ.4 functions with calls to * proj_context_create(...)/proj_context_destroy() * * Legacy single threaded code need not do anything, but *may* * implement a bit of future compatibility by using the backward * compatible call proj_context_create(0), which will not create * a new context, but simply provide a pointer to the default one. * * See proj_4D_api_test.c for examples of how to use the API. * * Author: Thomas Knudsen, <[email protected]> * Benefitting from a large number of comments and suggestions * by (primarily) Kristian Evers and Even Rouault. * ****************************************************************************** * Copyright (c) 2016, 2017, Thomas Knudsen / SDFE * Copyright (c) 2018, Even Rouault * * 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 COORD 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 PROJ_H #define PROJ_H #include <stddef.h> /* For size_t */ #ifdef ACCEPT_USE_OF_DEPRECATED_PROJ_API_H #error "The proj_api.h header has been removed from PROJ with version 8.0.0" #endif #ifdef PROJ_RENAME_SYMBOLS #include "proj_symbol_rename.h" #endif #ifdef __cplusplus extern "C" { #endif /** * \file proj.h * * C API new generation */ /*! @cond Doxygen_Suppress */ #ifndef PROJ_DLL #if defined(_MSC_VER) #ifdef PROJ_MSVC_DLL_EXPORT #define PROJ_DLL __declspec(dllexport) #else #define PROJ_DLL __declspec(dllimport) #endif #elif defined(__GNUC__) #define PROJ_DLL __attribute__((visibility("default"))) #else #define PROJ_DLL #endif #endif #ifdef PROJ_SUPPRESS_DEPRECATION_MESSAGE #define PROJ_DEPRECATED(decl, msg) decl #elif defined(__has_extension) #if __has_extension(attribute_deprecated_with_message) #define PROJ_DEPRECATED(decl, msg) decl __attribute__((deprecated(msg))) #elif defined(__GNUC__) #define PROJ_DEPRECATED(decl, msg) decl __attribute__((deprecated)) #else #define PROJ_DEPRECATED(decl, msg) decl #endif #elif defined(__GNUC__) #define PROJ_DEPRECATED(decl, msg) decl __attribute__((deprecated)) #elif defined(_MSVC_VER) #define PROJ_DEPRECATED(decl, msg) __declspec(deprecated(msg)) decl #else #define PROJ_DEPRECATED(decl, msg) decl #endif /* The version numbers should be updated with every release! **/ #define PROJ_VERSION_MAJOR 9 #define PROJ_VERSION_MINOR 5 #define PROJ_VERSION_PATCH 0 /* Note: the following 3 defines have been introduced in PROJ 8.0.1 */ /* Macro to compute a PROJ version number from its components */ #define PROJ_COMPUTE_VERSION(maj, min, patch) \ ((maj)*10000 + (min)*100 + (patch)) /* Current PROJ version from the above version numbers */ #define PROJ_VERSION_NUMBER \ PROJ_COMPUTE_VERSION(PROJ_VERSION_MAJOR, PROJ_VERSION_MINOR, \ PROJ_VERSION_PATCH) /* Macro that returns true if the current PROJ version is at least the version * specified by (maj,min,patch) */ #define PROJ_AT_LEAST_VERSION(maj, min, patch) \ (PROJ_VERSION_NUMBER >= PROJ_COMPUTE_VERSION(maj, min, patch)) extern char const PROJ_DLL pj_release[]; /* global release id string */ /* first forward declare everything needed */ /* Data type for generic geodetic 3D data plus epoch information */ union PJ_COORD; typedef union PJ_COORD PJ_COORD; struct PJ_AREA; typedef struct PJ_AREA PJ_AREA; struct P5_FACTORS { /* Common designation */ double meridional_scale; /* h */ double parallel_scale; /* k */ double areal_scale; /* s */ double angular_distortion; /* omega */ double meridian_parallel_angle; /* theta-prime */ double meridian_convergence; /* alpha */ double tissot_semimajor; /* a */ double tissot_semiminor; /* b */ double dx_dlam, dx_dphi; double dy_dlam, dy_dphi; }; typedef struct P5_FACTORS PJ_FACTORS; /* Data type for projection/transformation information */ struct PJconsts; typedef struct PJconsts PJ; /* the PJ object herself */ /* Data type for library level information */ struct PJ_INFO; typedef struct PJ_INFO PJ_INFO; struct PJ_PROJ_INFO; typedef struct PJ_PROJ_INFO PJ_PROJ_INFO; struct PJ_GRID_INFO; typedef struct PJ_GRID_INFO PJ_GRID_INFO; struct PJ_INIT_INFO; typedef struct PJ_INIT_INFO PJ_INIT_INFO; /* Data types for list of operations, ellipsoids, datums and units used in * PROJ.4 */ struct PJ_LIST { const char *id; /* projection keyword */ PJ *(*proj)(PJ *); /* projection entry point */ const char *const *descr; /* description text */ }; typedef struct PJ_LIST PJ_OPERATIONS; struct PJ_ELLPS { const char *id; /* ellipse keyword name */ const char *major; /* a= value */ const char *ell; /* elliptical parameter */ const char *name; /* comments */ }; typedef struct PJ_ELLPS PJ_ELLPS; struct PJ_UNITS { const char *id; /* units keyword */ const char *to_meter; /* multiply by value to get meters */ const char *name; /* comments */ double factor; /* to_meter factor in actual numbers */ }; typedef struct PJ_UNITS PJ_UNITS; struct PJ_PRIME_MERIDIANS { const char *id; /* prime meridian keyword */ const char *defn; /* offset from greenwich in DMS format. */ }; typedef struct PJ_PRIME_MERIDIANS PJ_PRIME_MERIDIANS; /* Geodetic, mostly spatiotemporal coordinate types */ typedef struct { double x, y, z, t; } PJ_XYZT; typedef struct { double u, v, w, t; } PJ_UVWT; typedef struct { double lam, phi, z, t; } PJ_LPZT; typedef struct { double o, p, k; } PJ_OPK; /* Rotations: omega, phi, kappa */ typedef struct { double e, n, u; } PJ_ENU; /* East, North, Up */ typedef struct { double s, a1, a2; } PJ_GEOD; /* Geodesic length, fwd azi, rev azi */ /* Classic proj.4 pair/triplet types - moved into the PJ_ name space */ typedef struct { double u, v; } PJ_UV; typedef struct { double x, y; } PJ_XY; typedef struct { double lam, phi; } PJ_LP; typedef struct { double x, y, z; } PJ_XYZ; typedef struct { double u, v, w; } PJ_UVW; typedef struct { double lam, phi, z; } PJ_LPZ; /* Avoid preprocessor renaming and implicit type-punning: Use a union to make it * explicit */ union PJ_COORD { double v[4]; /* First and foremost, it really is "just 4 numbers in a vector" */ PJ_XYZT xyzt; PJ_UVWT uvwt; PJ_LPZT lpzt; PJ_GEOD geod; PJ_OPK opk; PJ_ENU enu; PJ_XYZ xyz; PJ_UVW uvw; PJ_LPZ lpz; PJ_XY xy; PJ_UV uv; PJ_LP lp; }; struct PJ_INFO { int major; /* Major release number */ int minor; /* Minor release number */ int patch; /* Patch level */ const char *release; /* Release info. Version + date */ const char *version; /* Full version number */ const char *searchpath; /* Paths where init and grid files are */ /* looked for. Paths are separated by */ /* semi-colons on Windows, and colons */ /* on non-Windows platforms. */ const char *const *paths; size_t path_count; }; struct PJ_PROJ_INFO { const char *id; /* Name of the projection in question */ const char *description; /* Description of the projection */ const char *definition; /* Projection definition */ int has_inverse; /* 1 if an inverse mapping exists, 0 otherwise */ double accuracy; /* Expected accuracy of the transformation. -1 if unknown. */ }; struct PJ_GRID_INFO { char gridname[32]; /* name of grid */ char filename[260]; /* full path to grid */ char format[8]; /* file format of grid */ PJ_LP lowerleft; /* Coordinates of lower left corner */ PJ_LP upperright; /* Coordinates of upper right corner */ int n_lon, n_lat; /* Grid size */ double cs_lon, cs_lat; /* Cell size of grid */ }; struct PJ_INIT_INFO { char name[32]; /* name of init file */ char filename[260]; /* full path to the init file. */ char version[32]; /* version of the init file */ char origin[32]; /* origin of the file, e.g. EPSG */ char lastupdate[16]; /* Date of last update in YYYY-MM-DD format */ }; typedef enum PJ_LOG_LEVEL { PJ_LOG_NONE = 0, PJ_LOG_ERROR = 1, PJ_LOG_DEBUG = 2, PJ_LOG_TRACE = 3, PJ_LOG_TELL = 4, PJ_LOG_DEBUG_MAJOR = 2, /* for proj_api.h compatibility */ PJ_LOG_DEBUG_MINOR = 3 /* for proj_api.h compatibility */ } PJ_LOG_LEVEL; typedef void (*PJ_LOG_FUNCTION)(void *, int, const char *); /* The context type - properly namespaced synonym for pj_ctx */ struct pj_ctx; typedef struct pj_ctx PJ_CONTEXT; /* A P I */ /** * The objects returned by the functions defined in this section have minimal * interaction with the functions of the * \ref iso19111_functions section, and vice versa. See its introduction * paragraph for more details. */ /* Functionality for handling thread contexts */ #ifdef __cplusplus #define PJ_DEFAULT_CTX nullptr #else #define PJ_DEFAULT_CTX 0 #endif PJ_CONTEXT PROJ_DLL *proj_context_create(void); PJ_CONTEXT PROJ_DLL *proj_context_destroy(PJ_CONTEXT *ctx); PJ_CONTEXT PROJ_DLL *proj_context_clone(PJ_CONTEXT *ctx); /** Callback to resolve a filename to a full path */ typedef const char *(*proj_file_finder)(PJ_CONTEXT *ctx, const char *, void *user_data); /*! @endcond */ void PROJ_DLL proj_context_set_file_finder(PJ_CONTEXT *ctx, proj_file_finder finder, void *user_data); void PROJ_DLL proj_context_set_search_paths(PJ_CONTEXT *ctx, int count_paths, const char *const *paths); void PROJ_DLL proj_context_set_ca_bundle_path(PJ_CONTEXT *ctx, const char *path); /*! @cond Doxygen_Suppress */ void PROJ_DLL proj_context_use_proj4_init_rules(PJ_CONTEXT *ctx, int enable); int PROJ_DLL proj_context_get_use_proj4_init_rules(PJ_CONTEXT *ctx, int from_legacy_code_path); /*! @endcond */ /** Opaque structure for PROJ for a file handle. Implementations might cast it * to their structure/class of choice. */ typedef struct PROJ_FILE_HANDLE PROJ_FILE_HANDLE; /** Open access / mode */ typedef enum PROJ_OPEN_ACCESS { /** Read-only access. Equivalent to "rb" */ PROJ_OPEN_ACCESS_READ_ONLY, /** Read-update access. File should be created if not existing. Equivalent to "r+b" */ PROJ_OPEN_ACCESS_READ_UPDATE, /** Create access. File should be truncated to 0-byte if already existing. Equivalent to "w+b" */ PROJ_OPEN_ACCESS_CREATE } PROJ_OPEN_ACCESS; /** File API callbacks */ typedef struct PROJ_FILE_API { /** Version of this structure. Should be set to 1 currently. */ int version; /** Open file. Return NULL if error */ PROJ_FILE_HANDLE *(*open_cbk)(PJ_CONTEXT *ctx, const char *filename, PROJ_OPEN_ACCESS access, void *user_data); /** Read sizeBytes into buffer from current position and return number of * bytes read */ size_t (*read_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, void *buffer, size_t sizeBytes, void *user_data); /** Write sizeBytes into buffer from current position and return number of * bytes written */ size_t (*write_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, const void *buffer, size_t sizeBytes, void *user_data); /** Seek to offset using whence=SEEK_SET/SEEK_CUR/SEEK_END. Return TRUE in * case of success */ int (*seek_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, long long offset, int whence, void *user_data); /** Return current file position */ unsigned long long (*tell_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, void *user_data); /** Close file */ void (*close_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, void *user_data); /** Return TRUE if a file exists */ int (*exists_cbk)(PJ_CONTEXT *ctx, const char *filename, void *user_data); /** Return TRUE if directory exists or could be created */ int (*mkdir_cbk)(PJ_CONTEXT *ctx, const char *filename, void *user_data); /** Return TRUE if file could be removed */ int (*unlink_cbk)(PJ_CONTEXT *ctx, const char *filename, void *user_data); /** Return TRUE if file could be renamed */ int (*rename_cbk)(PJ_CONTEXT *ctx, const char *oldPath, const char *newPath, void *user_data); } PROJ_FILE_API; int PROJ_DLL proj_context_set_fileapi(PJ_CONTEXT *ctx, const PROJ_FILE_API *fileapi, void *user_data); void PROJ_DLL proj_context_set_sqlite3_vfs_name(PJ_CONTEXT *ctx, const char *name); /** Opaque structure for PROJ for a network handle. Implementations might cast * it to their structure/class of choice. */ typedef struct PROJ_NETWORK_HANDLE PROJ_NETWORK_HANDLE; /** Network access: open callback * * Should try to read the size_to_read first bytes at the specified offset of * the file given by URL url, * and write them to buffer. *out_size_read should be updated with the actual * amount of bytes read (== size_to_read if the file is larger than * size_to_read). During this read, the implementation should make sure to store * the HTTP headers from the server response to be able to respond to * proj_network_get_header_value_cbk_type callback. * * error_string_max_size should be the maximum size that can be written into * the out_error_string buffer (including terminating nul character). * * @return a non-NULL opaque handle in case of success. */ typedef PROJ_NETWORK_HANDLE *(*proj_network_open_cbk_type)( PJ_CONTEXT *ctx, const char *url, unsigned long long offset, size_t size_to_read, void *buffer, size_t *out_size_read, size_t error_string_max_size, char *out_error_string, void *user_data); /** Network access: close callback */ typedef void (*proj_network_close_cbk_type)(PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, void *user_data); /** Network access: get HTTP headers */ typedef const char *(*proj_network_get_header_value_cbk_type)( PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, const char *header_name, void *user_data); /** Network access: read range * * Read size_to_read bytes from handle, starting at offset, into * buffer. * During this read, the implementation should make sure to store the HTTP * headers from the server response to be able to respond to * proj_network_get_header_value_cbk_type callback. * * error_string_max_size should be the maximum size that can be written into * the out_error_string buffer (including terminating nul character). * * @return the number of bytes actually read (0 in case of error) */ typedef size_t (*proj_network_read_range_type)( PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, unsigned long long offset, size_t size_to_read, void *buffer, size_t error_string_max_size, char *out_error_string, void *user_data); int PROJ_DLL proj_context_set_network_callbacks( PJ_CONTEXT *ctx, proj_network_open_cbk_type open_cbk, proj_network_close_cbk_type close_cbk, proj_network_get_header_value_cbk_type get_header_value_cbk, proj_network_read_range_type read_range_cbk, void *user_data); int PROJ_DLL proj_context_set_enable_network(PJ_CONTEXT *ctx, int enabled); int PROJ_DLL proj_context_is_network_enabled(PJ_CONTEXT *ctx); void PROJ_DLL proj_context_set_url_endpoint(PJ_CONTEXT *ctx, const char *url); const char PROJ_DLL *proj_context_get_url_endpoint(PJ_CONTEXT *ctx); const char PROJ_DLL *proj_context_get_user_writable_directory(PJ_CONTEXT *ctx, int create); void PROJ_DLL proj_grid_cache_set_enable(PJ_CONTEXT *ctx, int enabled); void PROJ_DLL proj_grid_cache_set_filename(PJ_CONTEXT *ctx, const char *fullname); void PROJ_DLL proj_grid_cache_set_max_size(PJ_CONTEXT *ctx, int max_size_MB); void PROJ_DLL proj_grid_cache_set_ttl(PJ_CONTEXT *ctx, int ttl_seconds); void PROJ_DLL proj_grid_cache_clear(PJ_CONTEXT *ctx); int PROJ_DLL proj_is_download_needed(PJ_CONTEXT *ctx, const char *url_or_filename, int ignore_ttl_setting); int PROJ_DLL proj_download_file(PJ_CONTEXT *ctx, const char *url_or_filename, int ignore_ttl_setting, int (*progress_cbk)(PJ_CONTEXT *, double pct, void *user_data), void *user_data); /*! @cond Doxygen_Suppress */ /* Manage the transformation definition object PJ */ PJ PROJ_DLL *proj_create(PJ_CONTEXT *ctx, const char *definition); PJ PROJ_DLL *proj_create_argv(PJ_CONTEXT *ctx, int argc, char **argv); PJ PROJ_DLL *proj_create_crs_to_crs(PJ_CONTEXT *ctx, const char *source_crs, const char *target_crs, PJ_AREA *area); PJ PROJ_DLL *proj_create_crs_to_crs_from_pj(PJ_CONTEXT *ctx, const PJ *source_crs, const PJ *target_crs, PJ_AREA *area, const char *const *options); /*! @endcond */ PJ PROJ_DLL *proj_normalize_for_visualization(PJ_CONTEXT *ctx, const PJ *obj); /*! @cond Doxygen_Suppress */ void PROJ_DLL proj_assign_context(PJ *pj, PJ_CONTEXT *ctx); PJ PROJ_DLL *proj_destroy(PJ *P); PJ_AREA PROJ_DLL *proj_area_create(void); void PROJ_DLL proj_area_set_bbox(PJ_AREA *area, double west_lon_degree, double south_lat_degree, double east_lon_degree, double north_lat_degree); void PROJ_DLL proj_area_set_name(PJ_AREA *area, const char *name); void PROJ_DLL proj_area_destroy(PJ_AREA *area); /* Apply transformation to observation - in forward or inverse direction */ enum PJ_DIRECTION { PJ_FWD = 1, /* Forward */ PJ_IDENT = 0, /* Do nothing */ PJ_INV = -1 /* Inverse */ }; typedef enum PJ_DIRECTION PJ_DIRECTION; int PROJ_DLL proj_angular_input(PJ *P, enum PJ_DIRECTION dir); int PROJ_DLL proj_angular_output(PJ *P, enum PJ_DIRECTION dir); int PROJ_DLL proj_degree_input(PJ *P, enum PJ_DIRECTION dir); int PROJ_DLL proj_degree_output(PJ *P, enum PJ_DIRECTION dir); PJ_COORD PROJ_DLL proj_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coord); PJ PROJ_DLL *proj_trans_get_last_used_operation(PJ *P); int PROJ_DLL proj_trans_array(PJ *P, PJ_DIRECTION direction, size_t n, PJ_COORD *coord); size_t PROJ_DLL proj_trans_generic(PJ *P, PJ_DIRECTION direction, double *x, size_t sx, size_t nx, double *y, size_t sy, size_t ny, double *z, size_t sz, size_t nz, double *t, size_t st, size_t nt); /*! @endcond */ int PROJ_DLL proj_trans_bounds(PJ_CONTEXT *context, PJ *P, PJ_DIRECTION direction, double xmin, double ymin, double xmax, double ymax, double *out_xmin, double *out_ymin, double *out_xmax, double *out_ymax, int densify_pts); /*! @cond Doxygen_Suppress */ /* Initializers */ PJ_COORD PROJ_DLL proj_coord(double x, double y, double z, double t); /* Measure internal consistency - in forward or inverse direction */ double PROJ_DLL proj_roundtrip(PJ *P, PJ_DIRECTION direction, int n, PJ_COORD *coord); /* Geodesic distance between two points with angular 2D coordinates */ double PROJ_DLL proj_lp_dist(const PJ *P, PJ_COORD a, PJ_COORD b); /* The geodesic distance AND the vertical offset */ double PROJ_DLL proj_lpz_dist(const PJ *P, PJ_COORD a, PJ_COORD b); /* Euclidean distance between two points with linear 2D coordinates */ double PROJ_DLL proj_xy_dist(PJ_COORD a, PJ_COORD b); /* Euclidean distance between two points with linear 3D coordinates */ double PROJ_DLL proj_xyz_dist(PJ_COORD a, PJ_COORD b); /* Geodesic distance (in meter) + fwd and rev azimuth between two points on the * ellipsoid */ PJ_COORD PROJ_DLL proj_geod(const PJ *P, PJ_COORD a, PJ_COORD b); /* PROJ error codes */ /** Error codes typically related to coordinate operation initialization * Note: some of them can also be emitted during coordinate transformation, * like PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID in case the resource * loading is deferred until it is really needed. */ #define PROJ_ERR_INVALID_OP \ 1024 /* other/unspecified error related to coordinate operation \ initialization */ #define PROJ_ERR_INVALID_OP_WRONG_SYNTAX \ (PROJ_ERR_INVALID_OP + \ 1) /* invalid pipeline structure, missing +proj argument, etc */ #define PROJ_ERR_INVALID_OP_MISSING_ARG \ (PROJ_ERR_INVALID_OP + 2) /* missing required operation parameter */ #define PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE \ (PROJ_ERR_INVALID_OP + \ 3) /* one of the operation parameter has an illegal value */ #define PROJ_ERR_INVALID_OP_MUTUALLY_EXCLUSIVE_ARGS \ (PROJ_ERR_INVALID_OP + 4) /* mutually exclusive arguments */ #define PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID \ (PROJ_ERR_INVALID_OP + 5) /* file not found (particular case of \ PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE) */ /** Error codes related to transformation on a specific coordinate */ #define PROJ_ERR_COORD_TRANSFM \ 2048 /* other error related to coordinate transformation */ #define PROJ_ERR_COORD_TRANSFM_INVALID_COORD \ (PROJ_ERR_COORD_TRANSFM + 1) /* for e.g lat > 90deg */ #define PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN \ (PROJ_ERR_COORD_TRANSFM + \ 2) /* coordinate is outside of the projection domain. e.g approximate \ mercator with |longitude - lon_0| > 90deg, or iterative convergence \ method failed */ #define PROJ_ERR_COORD_TRANSFM_NO_OPERATION \ (PROJ_ERR_COORD_TRANSFM + \ 3) /* no operation found, e.g if no match the required accuracy, or if \ ballpark transformations were asked to not be used and they would \ be only such candidate */ #define PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID \ (PROJ_ERR_COORD_TRANSFM + \ 4) /* point to transform falls outside grid or subgrid */ #define PROJ_ERR_COORD_TRANSFM_GRID_AT_NODATA \ (PROJ_ERR_COORD_TRANSFM + \ 5) /* point to transform falls in a grid cell that evaluates to nodata */ #define PROJ_ERR_COORD_TRANSFM_NO_CONVERGENCE \ (PROJ_ERR_COORD_TRANSFM + 6) /* iterative convergence method fail */ /** Other type of errors */ #define PROJ_ERR_OTHER 4096 #define PROJ_ERR_OTHER_API_MISUSE \ (PROJ_ERR_OTHER + 1) /* error related to a misuse of PROJ API */ #define PROJ_ERR_OTHER_NO_INVERSE_OP \ (PROJ_ERR_OTHER + 2) /* no inverse method available */ #define PROJ_ERR_OTHER_NETWORK_ERROR \ (PROJ_ERR_OTHER + 3) /* failure when accessing a network resource */ /* Set or read error level */ int PROJ_DLL proj_context_errno(PJ_CONTEXT *ctx); int PROJ_DLL proj_errno(const PJ *P); int PROJ_DLL proj_errno_set(const PJ *P, int err); int PROJ_DLL proj_errno_reset(const PJ *P); int PROJ_DLL proj_errno_restore(const PJ *P, int err); const char PROJ_DLL * proj_errno_string(int err); /* deprecated. use proj_context_errno_string() */ const char PROJ_DLL *proj_context_errno_string(PJ_CONTEXT *ctx, int err); PJ_LOG_LEVEL PROJ_DLL proj_log_level(PJ_CONTEXT *ctx, PJ_LOG_LEVEL log_level); void PROJ_DLL proj_log_func(PJ_CONTEXT *ctx, void *app_data, PJ_LOG_FUNCTION logf); /* Scaling and angular distortion factors */ PJ_FACTORS PROJ_DLL proj_factors(PJ *P, PJ_COORD lp); /* Info functions - get information about various PROJ.4 entities */ PJ_INFO PROJ_DLL proj_info(void); PJ_PROJ_INFO PROJ_DLL proj_pj_info(PJ *P); PJ_GRID_INFO PROJ_DLL proj_grid_info(const char *gridname); PJ_INIT_INFO PROJ_DLL proj_init_info(const char *initname); /* List functions: */ /* Get lists of operations, ellipsoids, units and prime meridians. */ const PJ_OPERATIONS PROJ_DLL *proj_list_operations(void); const PJ_ELLPS PROJ_DLL *proj_list_ellps(void); PROJ_DEPRECATED(const PJ_UNITS PROJ_DLL *proj_list_units(void), "Deprecated by proj_get_units_from_database"); PROJ_DEPRECATED(const PJ_UNITS PROJ_DLL *proj_list_angular_units(void), "Deprecated by proj_get_units_from_database"); const PJ_PRIME_MERIDIANS PROJ_DLL *proj_list_prime_meridians(void); /* These are trivial, and while occasionally useful in real code, primarily here * to */ /* simplify demo code, and in acknowledgement of the proj-internal discrepancy * between */ /* angular units expected by classical proj, and by Charles Karney's geodesics * subsystem */ double PROJ_DLL proj_torad(double angle_in_degrees); double PROJ_DLL proj_todeg(double angle_in_radians); double PROJ_DLL proj_dmstor(const char *is, char **rs); PROJ_DEPRECATED(char PROJ_DLL *proj_rtodms(char *s, double r, int pos, int neg), "Deprecated by proj_rtodms2"); char PROJ_DLL *proj_rtodms2(char *s, size_t sizeof_s, double r, int pos, int neg); void PROJ_DLL proj_cleanup(void); /*! @endcond */ /* ------------------------------------------------------------------------- */ /* Binding in C of C++ API */ /* ------------------------------------------------------------------------- */ /** @defgroup iso19111_types Data types for ISO19111 C API * Data types for ISO19111 C API * @{ */ /** \brief Type representing a NULL terminated list of NULL-terminate strings. */ typedef char **PROJ_STRING_LIST; /** \brief Guessed WKT "dialect". */ typedef enum { /** \ref WKT2_2019 */ PJ_GUESSED_WKT2_2019, /** Deprecated alias for PJ_GUESSED_WKT2_2019 */ PJ_GUESSED_WKT2_2018 = PJ_GUESSED_WKT2_2019, /** \ref WKT2_2015 */ PJ_GUESSED_WKT2_2015, /** \ref WKT1 */ PJ_GUESSED_WKT1_GDAL, /** ESRI variant of WKT1 */ PJ_GUESSED_WKT1_ESRI, /** Not WKT / unrecognized */ PJ_GUESSED_NOT_WKT } PJ_GUESSED_WKT_DIALECT; /** \brief Object category. */ typedef enum { PJ_CATEGORY_ELLIPSOID, PJ_CATEGORY_PRIME_MERIDIAN, PJ_CATEGORY_DATUM, PJ_CATEGORY_CRS, PJ_CATEGORY_COORDINATE_OPERATION, PJ_CATEGORY_DATUM_ENSEMBLE } PJ_CATEGORY; /** \brief Object type. */ typedef enum { PJ_TYPE_UNKNOWN, PJ_TYPE_ELLIPSOID, PJ_TYPE_PRIME_MERIDIAN, PJ_TYPE_GEODETIC_REFERENCE_FRAME, PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME, PJ_TYPE_VERTICAL_REFERENCE_FRAME, PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME, PJ_TYPE_DATUM_ENSEMBLE, /** Abstract type, not returned by proj_get_type() */ PJ_TYPE_CRS, PJ_TYPE_GEODETIC_CRS, PJ_TYPE_GEOCENTRIC_CRS, /** proj_get_type() will never return that type, but * PJ_TYPE_GEOGRAPHIC_2D_CRS or PJ_TYPE_GEOGRAPHIC_3D_CRS. */ PJ_TYPE_GEOGRAPHIC_CRS, PJ_TYPE_GEOGRAPHIC_2D_CRS, PJ_TYPE_GEOGRAPHIC_3D_CRS, PJ_TYPE_VERTICAL_CRS, PJ_TYPE_PROJECTED_CRS, PJ_TYPE_COMPOUND_CRS, PJ_TYPE_TEMPORAL_CRS, PJ_TYPE_ENGINEERING_CRS, PJ_TYPE_BOUND_CRS, PJ_TYPE_OTHER_CRS, PJ_TYPE_CONVERSION, PJ_TYPE_TRANSFORMATION, PJ_TYPE_CONCATENATED_OPERATION, PJ_TYPE_OTHER_COORDINATE_OPERATION, PJ_TYPE_TEMPORAL_DATUM, PJ_TYPE_ENGINEERING_DATUM, PJ_TYPE_PARAMETRIC_DATUM, PJ_TYPE_DERIVED_PROJECTED_CRS, PJ_TYPE_COORDINATE_METADATA, } PJ_TYPE; /** Comparison criterion. */ typedef enum { /** All properties are identical. */ PJ_COMP_STRICT, /** The objects are equivalent for the purpose of coordinate * operations. They can differ by the name of their objects, * identifiers, other metadata. * Parameters may be expressed in different units, provided that the * value is (with some tolerance) the same once expressed in a * common unit. */ PJ_COMP_EQUIVALENT, /** Same as EQUIVALENT, relaxed with an exception that the axis order * of the base CRS of a DerivedCRS/ProjectedCRS or the axis order of * a GeographicCRS is ignored. Only to be used * with DerivedCRS/ProjectedCRS/GeographicCRS */ PJ_COMP_EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS, } PJ_COMPARISON_CRITERION; /** \brief WKT version. */ typedef enum { /** cf osgeo::proj::io::WKTFormatter::Convention::WKT2 */ PJ_WKT2_2015, /** cf osgeo::proj::io::WKTFormatter::Convention::WKT2_SIMPLIFIED */ PJ_WKT2_2015_SIMPLIFIED, /** cf osgeo::proj::io::WKTFormatter::Convention::WKT2_2019 */ PJ_WKT2_2019, /** Deprecated alias for PJ_WKT2_2019 */ PJ_WKT2_2018 = PJ_WKT2_2019, /** cf osgeo::proj::io::WKTFormatter::Convention::WKT2_2019_SIMPLIFIED */ PJ_WKT2_2019_SIMPLIFIED, /** Deprecated alias for PJ_WKT2_2019 */ PJ_WKT2_2018_SIMPLIFIED = PJ_WKT2_2019_SIMPLIFIED, /** cf osgeo::proj::io::WKTFormatter::Convention::WKT1_GDAL */ PJ_WKT1_GDAL, /** cf osgeo::proj::io::WKTFormatter::Convention::WKT1_ESRI */ PJ_WKT1_ESRI } PJ_WKT_TYPE; /** Specify how source and target CRS extent should be used to restrict * candidate operations (only taken into account if no explicit area of * interest is specified. */ typedef enum { /** Ignore CRS extent */ PJ_CRS_EXTENT_NONE, /** Test coordinate operation extent against both CRS extent. */ PJ_CRS_EXTENT_BOTH, /** Test coordinate operation extent against the intersection of both CRS extent. */ PJ_CRS_EXTENT_INTERSECTION, /** Test coordinate operation against the smallest of both CRS extent. */ PJ_CRS_EXTENT_SMALLEST } PROJ_CRS_EXTENT_USE; /** Describe how grid availability is used. */ typedef enum { /** Grid availability is only used for sorting results. Operations * where some grids are missing will be sorted last. */ PROJ_GRID_AVAILABILITY_USED_FOR_SORTING, /** Completely discard an operation if a required grid is missing. */ PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID, /** Ignore grid availability at all. Results will be presented as if * all grids were available. */ PROJ_GRID_AVAILABILITY_IGNORED, /** Results will be presented as if grids known to PROJ (that is * registered in the grid_alternatives table of its database) were * available. Used typically when networking is enabled. */ PROJ_GRID_AVAILABILITY_KNOWN_AVAILABLE, } PROJ_GRID_AVAILABILITY_USE; /** \brief PROJ string version. */ typedef enum { /** cf osgeo::proj::io::PROJStringFormatter::Convention::PROJ_5 */ PJ_PROJ_5, /** cf osgeo::proj::io::PROJStringFormatter::Convention::PROJ_4 */ PJ_PROJ_4 } PJ_PROJ_STRING_TYPE; /** Spatial criterion to restrict candidate operations. */ typedef enum { /** The area of validity of transforms should strictly contain the * are of interest. */ PROJ_SPATIAL_CRITERION_STRICT_CONTAINMENT, /** The area of validity of transforms should at least intersect the * area of interest. */ PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION } PROJ_SPATIAL_CRITERION; /** Describe if and how intermediate CRS should be used */ typedef enum { /** Always search for intermediate CRS. */ PROJ_INTERMEDIATE_CRS_USE_ALWAYS, /** Only attempt looking for intermediate CRS if there is no direct * transformation available. */ PROJ_INTERMEDIATE_CRS_USE_IF_NO_DIRECT_TRANSFORMATION, /* Do not attempt looking for intermediate CRS. */ PROJ_INTERMEDIATE_CRS_USE_NEVER, } PROJ_INTERMEDIATE_CRS_USE; /** Type of coordinate system. */ typedef enum { PJ_CS_TYPE_UNKNOWN, PJ_CS_TYPE_CARTESIAN, PJ_CS_TYPE_ELLIPSOIDAL, PJ_CS_TYPE_VERTICAL, PJ_CS_TYPE_SPHERICAL, PJ_CS_TYPE_ORDINAL, PJ_CS_TYPE_PARAMETRIC, PJ_CS_TYPE_DATETIMETEMPORAL, PJ_CS_TYPE_TEMPORALCOUNT, PJ_CS_TYPE_TEMPORALMEASURE } PJ_COORDINATE_SYSTEM_TYPE; /** \brief Structure given overall description of a CRS. * * This structure may grow over time, and should not be directly allocated by * client code. */ typedef struct { /** Authority name. */ char *auth_name; /** Object code. */ char *code; /** Object name. */ char *name; /** Object type. */ PJ_TYPE type; /** Whether the object is deprecated */ int deprecated; /** Whereas the west_lon_degree, south_lat_degree, east_lon_degree and * north_lat_degree fields are valid. */ int bbox_valid; /** Western-most longitude of the area of use, in degrees. */ double west_lon_degree; /** Southern-most latitude of the area of use, in degrees. */ double south_lat_degree; /** Eastern-most longitude of the area of use, in degrees. */ double east_lon_degree; /** Northern-most latitude of the area of use, in degrees. */ double north_lat_degree; /** Name of the area of use. */ char *area_name; /** Name of the projection method for a projected CRS. Might be NULL even *for projected CRS in some cases. */ char *projection_method_name; /** Name of the celestial body of the CRS (e.g. "Earth"). * @since 8.1 */ char *celestial_body_name; } PROJ_CRS_INFO; /** \brief Structure describing optional parameters for proj_get_crs_list(); * * This structure may grow over time, and should not be directly allocated by * client code. */ typedef struct { /** Array of allowed object types. Should be NULL if all types are allowed*/ const PJ_TYPE *types; /** Size of types. Should be 0 if all types are allowed*/ size_t typesCount; /** If TRUE and bbox_valid == TRUE, then only CRS whose area of use * entirely contains the specified bounding box will be returned. * If FALSE and bbox_valid == TRUE, then only CRS whose area of use * intersects the specified bounding box will be returned. */ int crs_area_of_use_contains_bbox; /** To set to TRUE so that west_lon_degree, south_lat_degree, * east_lon_degree and north_lat_degree fields are taken into account. */ int bbox_valid; /** Western-most longitude of the area of use, in degrees. */ double west_lon_degree; /** Southern-most latitude of the area of use, in degrees. */ double south_lat_degree; /** Eastern-most longitude of the area of use, in degrees. */ double east_lon_degree; /** Northern-most latitude of the area of use, in degrees. */ double north_lat_degree; /** Whether deprecated objects are allowed. Default to FALSE. */ int allow_deprecated; /** Celestial body of the CRS (e.g. "Earth"). The default value, NULL, * means no restriction * @since 8.1 */ const char *celestial_body_name; } PROJ_CRS_LIST_PARAMETERS; /** \brief Structure given description of a unit. * * This structure may grow over time, and should not be directly allocated by * client code. * @since 7.1 */ typedef struct { /** Authority name. */ char *auth_name; /** Object code. */ char *code; /** Object name. For example "metre", "US survey foot", etc. */ char *name; /** Category of the unit: one of "linear", "linear_per_time", "angular", * "angular_per_time", "scale", "scale_per_time" or "time" */ char *category; /** Conversion factor to apply to transform from that unit to the * corresponding SI unit (metre for "linear", radian for "angular", etc.). * It might be 0 in some cases to indicate no known conversion factor. */ double conv_factor; /** PROJ short name, like "m", "ft", "us-ft", etc... Might be NULL */ char *proj_short_name; /** Whether the object is deprecated */ int deprecated; } PROJ_UNIT_INFO; /** \brief Structure given description of a celestial body. * * This structure may grow over time, and should not be directly allocated by * client code. * @since 8.1 */ typedef struct { /** Authority name. */ char *auth_name; /** Object name. For example "Earth" */ char *name; } PROJ_CELESTIAL_BODY_INFO; /**@}*/ /** * \defgroup iso19111_functions Binding in C of basic methods from the C++ API * Functions for ISO19111 C API * * The PJ* objects returned by proj_create_from_wkt(), * proj_create_from_database() and other functions in that section * will have generally minimal interaction with the functions declared in the * upper section of this header file (calling those functions on those objects * will either return an error or default/nonsensical values). The exception is * for ISO19111 objects of type CoordinateOperation that can be exported as a * valid PROJ pipeline. In this case, the PJ objects will work for example with * proj_trans_generic(). * Conversely, objects returned by proj_create() and proj_create_argv(), which * are not of type CRS, will return an error when used with functions of this * section. * @{ */ /*! @cond Doxygen_Suppress */ typedef struct PJ_OBJ_LIST PJ_OBJ_LIST; /*! @endcond */ void PROJ_DLL proj_string_list_destroy(PROJ_STRING_LIST list); void PROJ_DLL proj_context_set_autoclose_database(PJ_CONTEXT *ctx, int autoclose); int PROJ_DLL proj_context_set_database_path(PJ_CONTEXT *ctx, const char *dbPath, const char *const *auxDbPaths, const char *const *options); const char PROJ_DLL *proj_context_get_database_path(PJ_CONTEXT *ctx); const char PROJ_DLL *proj_context_get_database_metadata(PJ_CONTEXT *ctx, const char *key); PROJ_STRING_LIST PROJ_DLL proj_context_get_database_structure( PJ_CONTEXT *ctx, const char *const *options); PJ_GUESSED_WKT_DIALECT PROJ_DLL proj_context_guess_wkt_dialect(PJ_CONTEXT *ctx, const char *wkt); PJ PROJ_DLL *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); PJ PROJ_DLL *proj_create_from_database(PJ_CONTEXT *ctx, const char *auth_name, const char *code, PJ_CATEGORY category, int usePROJAlternativeGridNames, const char *const *options); int PROJ_DLL 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); int PROJ_DLL 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); PJ PROJ_DLL *proj_clone(PJ_CONTEXT *ctx, const PJ *obj); PJ_OBJ_LIST PROJ_DLL * 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); PJ_TYPE PROJ_DLL proj_get_type(const PJ *obj); int PROJ_DLL proj_is_deprecated(const PJ *obj); PJ_OBJ_LIST PROJ_DLL *proj_get_non_deprecated(PJ_CONTEXT *ctx, const PJ *obj); int PROJ_DLL proj_is_equivalent_to(const PJ *obj, const PJ *other, PJ_COMPARISON_CRITERION criterion); int PROJ_DLL proj_is_equivalent_to_with_ctx(PJ_CONTEXT *ctx, const PJ *obj, const PJ *other, PJ_COMPARISON_CRITERION criterion); int PROJ_DLL proj_is_crs(const PJ *obj); const char PROJ_DLL *proj_get_name(const PJ *obj); const char PROJ_DLL *proj_get_id_auth_name(const PJ *obj, int index); const char PROJ_DLL *proj_get_id_code(const PJ *obj, int index); const char PROJ_DLL *proj_get_remarks(const PJ *obj); int PROJ_DLL proj_get_domain_count(const PJ *obj); const char PROJ_DLL *proj_get_scope(const PJ *obj); const char PROJ_DLL *proj_get_scope_ex(const PJ *obj, int domainIdx); int PROJ_DLL 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); int PROJ_DLL 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); const char PROJ_DLL *proj_as_wkt(PJ_CONTEXT *ctx, const PJ *obj, PJ_WKT_TYPE type, const char *const *options); const char PROJ_DLL *proj_as_proj_string(PJ_CONTEXT *ctx, const PJ *obj, PJ_PROJ_STRING_TYPE type, const char *const *options); const char PROJ_DLL *proj_as_projjson(PJ_CONTEXT *ctx, const PJ *obj, const char *const *options); PJ PROJ_DLL *proj_get_source_crs(PJ_CONTEXT *ctx, const PJ *obj); PJ PROJ_DLL *proj_get_target_crs(PJ_CONTEXT *ctx, const PJ *obj); PJ_OBJ_LIST PROJ_DLL *proj_identify(PJ_CONTEXT *ctx, const PJ *obj, const char *auth_name, const char *const *options, int **out_confidence); PROJ_STRING_LIST PROJ_DLL proj_get_geoid_models_from_database( PJ_CONTEXT *ctx, const char *auth_name, const char *code, const char *const *options); void PROJ_DLL proj_int_list_destroy(int *list); /* ------------------------------------------------------------------------- */ PROJ_STRING_LIST PROJ_DLL proj_get_authorities_from_database(PJ_CONTEXT *ctx); PROJ_STRING_LIST PROJ_DLL proj_get_codes_from_database(PJ_CONTEXT *ctx, const char *auth_name, PJ_TYPE type, int allow_deprecated); PROJ_CELESTIAL_BODY_INFO PROJ_DLL **proj_get_celestial_body_list_from_database( PJ_CONTEXT *ctx, const char *auth_name, int *out_result_count); void PROJ_DLL proj_celestial_body_list_destroy(PROJ_CELESTIAL_BODY_INFO **list); PROJ_CRS_LIST_PARAMETERS PROJ_DLL *proj_get_crs_list_parameters_create(void); void PROJ_DLL proj_get_crs_list_parameters_destroy(PROJ_CRS_LIST_PARAMETERS *params); PROJ_CRS_INFO PROJ_DLL ** proj_get_crs_info_list_from_database(PJ_CONTEXT *ctx, const char *auth_name, const PROJ_CRS_LIST_PARAMETERS *params, int *out_result_count); void PROJ_DLL proj_crs_info_list_destroy(PROJ_CRS_INFO **list); PROJ_UNIT_INFO PROJ_DLL **proj_get_units_from_database(PJ_CONTEXT *ctx, const char *auth_name, const char *category, int allow_deprecated, int *out_result_count); void PROJ_DLL proj_unit_list_destroy(PROJ_UNIT_INFO **list); /* ------------------------------------------------------------------------- */ /*! @cond Doxygen_Suppress */ typedef struct PJ_INSERT_SESSION PJ_INSERT_SESSION; /*! @endcond */ PJ_INSERT_SESSION PROJ_DLL *proj_insert_object_session_create(PJ_CONTEXT *ctx); void PROJ_DLL proj_insert_object_session_destroy(PJ_CONTEXT *ctx, PJ_INSERT_SESSION *session); PROJ_STRING_LIST PROJ_DLL 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); char PROJ_DLL *proj_suggests_code_for(PJ_CONTEXT *ctx, const PJ *object, const char *authority, int numeric_code, const char *const *options); void PROJ_DLL proj_string_destroy(char *str); /* ------------------------------------------------------------------------- */ /*! @cond Doxygen_Suppress */ typedef struct PJ_OPERATION_FACTORY_CONTEXT PJ_OPERATION_FACTORY_CONTEXT; /*! @endcond */ PJ_OPERATION_FACTORY_CONTEXT PROJ_DLL * proj_create_operation_factory_context(PJ_CONTEXT *ctx, const char *authority); void PROJ_DLL proj_operation_factory_context_destroy(PJ_OPERATION_FACTORY_CONTEXT *ctx); void PROJ_DLL proj_operation_factory_context_set_desired_accuracy( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, double accuracy); void PROJ_DLL 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); void PROJ_DLL proj_operation_factory_context_set_area_of_interest_name( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, const char *area_name); void PROJ_DLL proj_operation_factory_context_set_crs_extent_use( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_CRS_EXTENT_USE use); void PROJ_DLL proj_operation_factory_context_set_spatial_criterion( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_SPATIAL_CRITERION criterion); void PROJ_DLL proj_operation_factory_context_set_grid_availability_use( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_GRID_AVAILABILITY_USE use); void PROJ_DLL proj_operation_factory_context_set_use_proj_alternative_grid_names( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, int usePROJNames); void PROJ_DLL proj_operation_factory_context_set_allow_use_intermediate_crs( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, PROJ_INTERMEDIATE_CRS_USE use); void PROJ_DLL 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); void PROJ_DLL proj_operation_factory_context_set_discard_superseded( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, int discard); void PROJ_DLL proj_operation_factory_context_set_allow_ballpark_transformations( PJ_CONTEXT *ctx, PJ_OPERATION_FACTORY_CONTEXT *factory_ctx, int allow); /* ------------------------------------------------------------------------- */ PJ_OBJ_LIST PROJ_DLL * proj_create_operations(PJ_CONTEXT *ctx, const PJ *source_crs, const PJ *target_crs, const PJ_OPERATION_FACTORY_CONTEXT *operationContext); int PROJ_DLL proj_list_get_count(const PJ_OBJ_LIST *result); PJ PROJ_DLL *proj_list_get(PJ_CONTEXT *ctx, const PJ_OBJ_LIST *result, int index); void PROJ_DLL proj_list_destroy(PJ_OBJ_LIST *result); int PROJ_DLL proj_get_suggested_operation(PJ_CONTEXT *ctx, PJ_OBJ_LIST *operations, PJ_DIRECTION direction, PJ_COORD coord); /* ------------------------------------------------------------------------- */ int PROJ_DLL proj_crs_is_derived(PJ_CONTEXT *ctx, const PJ *crs); PJ PROJ_DLL *proj_crs_get_geodetic_crs(PJ_CONTEXT *ctx, const PJ *crs); PJ PROJ_DLL *proj_crs_get_horizontal_datum(PJ_CONTEXT *ctx, const PJ *crs); PJ PROJ_DLL *proj_crs_get_sub_crs(PJ_CONTEXT *ctx, const PJ *crs, int index); PJ PROJ_DLL *proj_crs_get_datum(PJ_CONTEXT *ctx, const PJ *crs); PJ PROJ_DLL *proj_crs_get_datum_ensemble(PJ_CONTEXT *ctx, const PJ *crs); PJ PROJ_DLL *proj_crs_get_datum_forced(PJ_CONTEXT *ctx, const PJ *crs); int PROJ_DLL proj_crs_has_point_motion_operation(PJ_CONTEXT *ctx, const PJ *crs); int PROJ_DLL proj_datum_ensemble_get_member_count(PJ_CONTEXT *ctx, const PJ *datum_ensemble); double PROJ_DLL proj_datum_ensemble_get_accuracy(PJ_CONTEXT *ctx, const PJ *datum_ensemble); PJ PROJ_DLL *proj_datum_ensemble_get_member(PJ_CONTEXT *ctx, const PJ *datum_ensemble, int member_index); double PROJ_DLL proj_dynamic_datum_get_frame_reference_epoch(PJ_CONTEXT *ctx, const PJ *datum); PJ PROJ_DLL *proj_crs_get_coordinate_system(PJ_CONTEXT *ctx, const PJ *crs); PJ_COORDINATE_SYSTEM_TYPE PROJ_DLL proj_cs_get_type(PJ_CONTEXT *ctx, const PJ *cs); int PROJ_DLL proj_cs_get_axis_count(PJ_CONTEXT *ctx, const PJ *cs); int PROJ_DLL 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); PJ PROJ_DLL *proj_get_ellipsoid(PJ_CONTEXT *ctx, const PJ *obj); int PROJ_DLL 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); const char PROJ_DLL *proj_get_celestial_body_name(PJ_CONTEXT *ctx, const PJ *obj); PJ PROJ_DLL *proj_get_prime_meridian(PJ_CONTEXT *ctx, const PJ *obj); int PROJ_DLL 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); PJ PROJ_DLL *proj_crs_get_coordoperation(PJ_CONTEXT *ctx, const PJ *crs); int PROJ_DLL 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); int PROJ_DLL proj_coordoperation_is_instantiable(PJ_CONTEXT *ctx, const PJ *coordoperation); int PROJ_DLL proj_coordoperation_has_ballpark_transformation( PJ_CONTEXT *ctx, const PJ *coordoperation); int PROJ_DLL proj_coordoperation_get_param_count(PJ_CONTEXT *ctx, const PJ *coordoperation); int PROJ_DLL proj_coordoperation_get_param_index(PJ_CONTEXT *ctx, const PJ *coordoperation, const char *name); int PROJ_DLL 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); int PROJ_DLL proj_coordoperation_get_grid_used_count(PJ_CONTEXT *ctx, const PJ *coordoperation); int PROJ_DLL 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); double PROJ_DLL proj_coordoperation_get_accuracy(PJ_CONTEXT *ctx, const PJ *obj); int PROJ_DLL proj_coordoperation_get_towgs84_values( PJ_CONTEXT *ctx, const PJ *coordoperation, double *out_values, int value_count, int emit_error_if_incompatible); PJ PROJ_DLL *proj_coordoperation_create_inverse(PJ_CONTEXT *ctx, const PJ *obj); int PROJ_DLL proj_concatoperation_get_step_count(PJ_CONTEXT *ctx, const PJ *concatoperation); PJ PROJ_DLL *proj_concatoperation_get_step(PJ_CONTEXT *ctx, const PJ *concatoperation, int i_step); PJ PROJ_DLL *proj_coordinate_metadata_create(PJ_CONTEXT *ctx, const PJ *crs, double epoch); double PROJ_DLL proj_coordinate_metadata_get_epoch(PJ_CONTEXT *ctx, const PJ *obj); /**@}*/ /* ------------------------------------------------------------------------- */ /* Binding in C of advanced methods from the C++ API */ /* */ /* Manual construction of CRS objects. */ /* ------------------------------------------------------------------------- */ /** * \defgroup iso19111_advanced_types C types for advanced methods from the C++ * API * @{ */ /** Type of unit of measure. */ typedef enum { /** Angular unit of measure */ PJ_UT_ANGULAR, /** Linear unit of measure */ PJ_UT_LINEAR, /** Scale unit of measure */ PJ_UT_SCALE, /** Time unit of measure */ PJ_UT_TIME, /** Parametric unit of measure */ PJ_UT_PARAMETRIC } PJ_UNIT_TYPE; /** \brief Axis description. */ typedef struct { /** Axis name. */ char *name; /** Axis abbreviation. */ char *abbreviation; /** Axis direction. */ char *direction; /** Axis unit name. */ char *unit_name; /** Conversion factor to SI of the unit. */ double unit_conv_factor; /** Type of unit */ PJ_UNIT_TYPE unit_type; } PJ_AXIS_DESCRIPTION; /** Type of Cartesian 2D coordinate system. */ typedef enum { /** Easting-Norting */ PJ_CART2D_EASTING_NORTHING, /** Northing-Easting */ PJ_CART2D_NORTHING_EASTING, /** North Pole Easting/SOUTH-Norting/SOUTH */ PJ_CART2D_NORTH_POLE_EASTING_SOUTH_NORTHING_SOUTH, /** South Pole Easting/NORTH-Norting/NORTH */ PJ_CART2D_SOUTH_POLE_EASTING_NORTH_NORTHING_NORTH, /** Westing-southing */ PJ_CART2D_WESTING_SOUTHING, } PJ_CARTESIAN_CS_2D_TYPE; /** Type of Ellipsoidal 2D coordinate system. */ typedef enum { /** Longitude-Latitude */ PJ_ELLPS2D_LONGITUDE_LATITUDE, /** Latitude-Longitude */ PJ_ELLPS2D_LATITUDE_LONGITUDE, } PJ_ELLIPSOIDAL_CS_2D_TYPE; /** Type of Ellipsoidal 3D coordinate system. */ typedef enum { /** Longitude-Latitude-Height(up) */ PJ_ELLPS3D_LONGITUDE_LATITUDE_HEIGHT, /** Latitude-Longitude-Height(up) */ PJ_ELLPS3D_LATITUDE_LONGITUDE_HEIGHT, } PJ_ELLIPSOIDAL_CS_3D_TYPE; /** \brief Description of a parameter value for a Conversion. */ typedef struct { /** Parameter name. */ const char *name; /** Parameter authority name. */ const char *auth_name; /** Parameter code. */ const char *code; /** Parameter value. */ double value; /** Name of unit in which parameter value is expressed. */ const char *unit_name; /** Conversion factor to SI of the unit. */ double unit_conv_factor; /** Type of unit */ PJ_UNIT_TYPE unit_type; } PJ_PARAM_DESCRIPTION; /**@}*/ /** * \defgroup iso19111_advanced_functions Binding in C of advanced methods from * the C++ API * @{ */ PJ PROJ_DLL *proj_create_cs(PJ_CONTEXT *ctx, PJ_COORDINATE_SYSTEM_TYPE type, int axis_count, const PJ_AXIS_DESCRIPTION *axis); PJ PROJ_DLL *proj_create_cartesian_2D_cs(PJ_CONTEXT *ctx, PJ_CARTESIAN_CS_2D_TYPE type, const char *unit_name, double unit_conv_factor); PJ PROJ_DLL *proj_create_ellipsoidal_2D_cs(PJ_CONTEXT *ctx, PJ_ELLIPSOIDAL_CS_2D_TYPE type, const char *unit_name, double unit_conv_factor); PJ PROJ_DLL * 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); PJ_OBJ_LIST PROJ_DLL *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); PJ PROJ_DLL *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_units_conv, PJ *ellipsoidal_cs); PJ PROJ_DLL *proj_create_geographic_crs_from_datum(PJ_CONTEXT *ctx, const char *crs_name, PJ *datum_or_datum_ensemble, PJ *ellipsoidal_cs); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *proj_create_derived_geographic_crs(PJ_CONTEXT *ctx, const char *crs_name, const PJ *base_geographic_crs, const PJ *conversion, const PJ *ellipsoidal_cs); int PROJ_DLL proj_is_derived_crs(PJ_CONTEXT *ctx, const PJ *crs); PJ PROJ_DLL *proj_alter_name(PJ_CONTEXT *ctx, const PJ *obj, const char *name); PJ PROJ_DLL *proj_alter_id(PJ_CONTEXT *ctx, const PJ *obj, const char *auth_name, const char *code); PJ PROJ_DLL *proj_crs_alter_geodetic_crs(PJ_CONTEXT *ctx, const PJ *obj, const PJ *new_geod_crs); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *proj_crs_promote_to_3D(PJ_CONTEXT *ctx, const char *crs_3D_name, const PJ *crs_2D); PJ PROJ_DLL * 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); PJ PROJ_DLL *proj_crs_demote_to_2D(PJ_CONTEXT *ctx, const char *crs_2D_name, const PJ *crs_3D); PJ PROJ_DLL *proj_create_engineering_crs(PJ_CONTEXT *ctx, const char *crsName); PJ PROJ_DLL *proj_create_vertical_crs(PJ_CONTEXT *ctx, const char *crs_name, const char *datum_name, const char *linear_units, double linear_units_conv); PJ PROJ_DLL *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); PJ PROJ_DLL *proj_create_compound_crs(PJ_CONTEXT *ctx, const char *crs_name, PJ *horiz_crs, PJ *vert_crs); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL * proj_convert_conversion_to_other_method(PJ_CONTEXT *ctx, const PJ *conversion, int new_method_epsg_code, const char *new_method_name); PJ PROJ_DLL *proj_create_projected_crs(PJ_CONTEXT *ctx, const char *crs_name, const PJ *geodetic_crs, const PJ *conversion, const PJ *coordinate_system); PJ PROJ_DLL *proj_crs_create_bound_crs(PJ_CONTEXT *ctx, const PJ *base_crs, const PJ *hub_crs, const PJ *transformation); PJ PROJ_DLL *proj_crs_create_bound_crs_to_WGS84(PJ_CONTEXT *ctx, const PJ *crs, const char *const *options); PJ PROJ_DLL *proj_crs_create_bound_vertical_crs(PJ_CONTEXT *ctx, const PJ *vert_crs, const PJ *hub_geographic_3D_crs, const char *grid_name); /* BEGIN: Generated by scripts/create_c_api_projections.py*/ PJ PROJ_DLL *proj_create_conversion_utm(PJ_CONTEXT *ctx, int zone, int north); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL * 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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); PJ PROJ_DLL *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); /* END: Generated by scripts/create_c_api_projections.py*/ /**@}*/ #ifdef __cplusplus } #endif #endif /* ndef PROJ_H */
h
PROJ
data/projects/PROJ/src/ellps.cpp
/* definition of standard geoids */ #include <stddef.h> #include "proj.h" #include "proj_internal.h" static const struct PJ_ELLPS pj_ellps[] = { {"MERIT", "a=6378137.0", "rf=298.257", "MERIT 1983"}, {"SGS85", "a=6378136.0", "rf=298.257", "Soviet Geodetic System 85"}, {"GRS80", "a=6378137.0", "rf=298.257222101", "GRS 1980(IUGG, 1980)"}, {"IAU76", "a=6378140.0", "rf=298.257", "IAU 1976"}, {"airy", "a=6377563.396", "rf=299.3249646", "Airy 1830"}, {"APL4.9", "a=6378137.0", "rf=298.25", "Appl. Physics. 1965"}, {"NWL9D", "a=6378145.0", "rf=298.25", "Naval Weapons Lab., 1965"}, {"mod_airy", "a=6377340.189", "b=6356034.446", "Modified Airy"}, {"andrae", "a=6377104.43", "rf=300.0", "Andrae 1876 (Den., Iclnd.)"}, {"danish", "a=6377019.2563", "rf=300.0", "Andrae 1876 (Denmark, Iceland)"}, {"aust_SA", "a=6378160.0", "rf=298.25", "Australian Natl & S. Amer. 1969"}, {"GRS67", "a=6378160.0", "rf=298.2471674270", "GRS 67(IUGG 1967)"}, {"GSK2011", "a=6378136.5", "rf=298.2564151", "GSK-2011"}, {"bessel", "a=6377397.155", "rf=299.1528128", "Bessel 1841"}, {"bess_nam", "a=6377483.865", "rf=299.1528128", "Bessel 1841 (Namibia)"}, {"clrk66", "a=6378206.4", "b=6356583.8", "Clarke 1866"}, {"clrk80", "a=6378249.145", "rf=293.4663", "Clarke 1880 mod."}, {"clrk80ign", "a=6378249.2", "rf=293.4660212936269", "Clarke 1880 (IGN)."}, {"CPM", "a=6375738.7", "rf=334.29", "Comm. des Poids et Mesures 1799"}, {"delmbr", "a=6376428.", "rf=311.5", "Delambre 1810 (Belgium)"}, {"engelis", "a=6378136.05", "rf=298.2566", "Engelis 1985"}, {"evrst30", "a=6377276.345", "rf=300.8017", "Everest 1830"}, {"evrst48", "a=6377304.063", "rf=300.8017", "Everest 1948"}, {"evrst56", "a=6377301.243", "rf=300.8017", "Everest 1956"}, {"evrst69", "a=6377295.664", "rf=300.8017", "Everest 1969"}, {"evrstSS", "a=6377298.556", "rf=300.8017", "Everest (Sabah & Sarawak)"}, {"fschr60", "a=6378166.", "rf=298.3", "Fischer (Mercury Datum) 1960"}, {"fschr60m", "a=6378155.", "rf=298.3", "Modified Fischer 1960"}, {"fschr68", "a=6378150.", "rf=298.3", "Fischer 1968"}, {"helmert", "a=6378200.", "rf=298.3", "Helmert 1906"}, {"hough", "a=6378270.0", "rf=297.", "Hough"}, {"intl", "a=6378388.0", "rf=297.", "International 1924 (Hayford 1909, 1910)"}, {"krass", "a=6378245.0", "rf=298.3", "Krassovsky, 1942"}, {"kaula", "a=6378163.", "rf=298.24", "Kaula 1961"}, {"lerch", "a=6378139.", "rf=298.257", "Lerch 1979"}, {"mprts", "a=6397300.", "rf=191.", "Maupertius 1738"}, {"new_intl", "a=6378157.5", "b=6356772.2", "New International 1967"}, {"plessis", "a=6376523.", "b=6355863.", "Plessis 1817 (France)"}, {"PZ90", "a=6378136.0", "rf=298.25784", "PZ-90"}, {"SEasia", "a=6378155.0", "b=6356773.3205", "Southeast Asia"}, {"walbeck", "a=6376896.0", "b=6355834.8467", "Walbeck"}, {"WGS60", "a=6378165.0", "rf=298.3", "WGS 60"}, {"WGS66", "a=6378145.0", "rf=298.25", "WGS 66"}, {"WGS72", "a=6378135.0", "rf=298.26", "WGS 72"}, {"WGS84", "a=6378137.0", "rf=298.257223563", "WGS 84"}, {"sphere", "a=6370997.0", "b=6370997.0", "Normal Sphere (r=6370997)"}, {nullptr, nullptr, nullptr, nullptr}}; const PJ_ELLPS *proj_list_ellps(void) { return pj_ellps; }
cpp
PROJ
data/projects/PROJ/src/phi2.cpp
/* Determine latitude angle phi-2. */ #include <algorithm> #include <limits> #include <math.h> #include "proj.h" #include "proj_internal.h" double pj_sinhpsi2tanphi(PJ_CONTEXT *ctx, const double taup, const double e) { /**************************************************************************** * Convert tau' = sinh(psi) = tan(chi) to tau = tan(phi). The code is taken * from GeographicLib::Math::tauf(taup, e). * * Here * phi = geographic latitude (radians) * psi is the isometric latitude * psi = asinh(tan(phi)) - e * atanh(e * sin(phi)) * = asinh(tan(chi)) * chi is the conformal latitude * * The representation of latitudes via their tangents, tan(phi) and *tan(chi), maintains full *relative* accuracy close to latitude = 0 and +/- *pi/2. This is sometimes important, e.g., to compute the scale of the *transverse Mercator projection which involves cos(phi)/cos(chi) tan(phi) * * From Karney (2011), Eq. 7, * * tau' = sinh(psi) = sinh(asinh(tan(phi)) - e * atanh(e * sin(phi))) * = tan(phi) * cosh(e * atanh(e * sin(phi))) - * sec(phi) * sinh(e * atanh(e * sin(phi))) * = tau * sqrt(1 + sigma^2) - sqrt(1 + tau^2) * sigma * where * sigma = sinh(e * atanh( e * tau / sqrt(1 + tau^2) )) * * For e small, * * tau' = (1 - e^2) * tau * * The relation tau'(tau) can therefore by reliably inverted by Newton's * method with * * tau = tau' / (1 - e^2) * * as an initial guess. Newton's method requires dtau'/dtau. Noting that * * dsigma/dtau = e^2 * sqrt(1 + sigma^2) / * (sqrt(1 + tau^2) * (1 + (1 - e^2) * tau^2)) * d(sqrt(1 + tau^2))/dtau = tau / sqrt(1 + tau^2) * * we have * * dtau'/dtau = (1 - e^2) * sqrt(1 + tau'^2) * sqrt(1 + tau^2) / * (1 + (1 - e^2) * tau^2) * * This works fine unless tau^2 and tau'^2 overflows. This may be partially * cured by writing, e.g., sqrt(1 + tau^2) as hypot(1, tau). However, nan * will still be generated with tau' = inf, since (inf - inf) will appear in * the Newton iteration. * * If we note that for sufficiently large |tau|, i.e., |tau| >= 2/sqrt(eps), * sqrt(1 + tau^2) = |tau| and * * tau' = exp(- e * atanh(e)) * tau * * So * * tau = exp(e * atanh(e)) * tau' * * can be returned unless |tau| >= 2/sqrt(eps); this then avoids overflow * problems for large tau' and returns the correct result for tau' = +/-inf * and nan. * * Newton's method usually take 2 iterations to converge to double precision * accuracy (for WGS84 flattening). However only 1 iteration is needed for * |chi| < 3.35 deg. In addition, only 1 iteration is needed for |chi| > * 89.18 deg (tau' > 70), if tau = exp(e * atanh(e)) * tau' is used as the * starting guess. ****************************************************************************/ constexpr int numit = 5; // min iterations = 1, max iterations = 2; mean = 1.954 static const double rooteps = sqrt(std::numeric_limits<double>::epsilon()); static const double tol = rooteps / 10; // the criterion for Newton's method static const double tmax = 2 / rooteps; // threshold for large arg limit exact const double e2m = 1 - e * e; const double stol = tol * std::max(1.0, fabs(taup)); // The initial guess. 70 corresponds to chi = 89.18 deg (see above) double tau = fabs(taup) > 70 ? taup * exp(e * atanh(e)) : taup / e2m; if (!(fabs(tau) < tmax)) // handles +/-inf and nan and e = 1 return tau; // If we need to deal with e > 1, then we could include: // if (e2m < 0) return std::numeric_limits<double>::quiet_NaN(); int i = numit; for (; i; --i) { double tau1 = sqrt(1 + tau * tau); double sig = sinh(e * atanh(e * tau / tau1)); double taupa = sqrt(1 + sig * sig) * tau - sig * tau1; double dtau = ((taup - taupa) * (1 + e2m * (tau * tau)) / (e2m * tau1 * sqrt(1 + taupa * taupa))); tau += dtau; if (!(fabs(dtau) >= stol)) // backwards test to allow nans to succeed. break; } if (i == 0) proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return tau; } /*****************************************************************************/ double pj_phi2(PJ_CONTEXT *ctx, const double ts0, const double e) { /**************************************************************************** * Determine latitude angle phi-2. * Inputs: * ts = exp(-psi) where psi is the isometric latitude (dimensionless) * this variable is defined in Snyder (1987), Eq. (7-10) * e = eccentricity of the ellipsoid (dimensionless) * Output: * phi = geographic latitude (radians) * Here isometric latitude is defined by * psi = log( tan(pi/4 + phi/2) * * ( (1 - e*sin(phi)) / (1 + e*sin(phi)) )^(e/2) ) * = asinh(tan(phi)) - e * atanh(e * sin(phi)) * = asinh(tan(chi)) * chi = conformal latitude * * This routine converts t = exp(-psi) to * * tau' = tan(chi) = sinh(psi) = (1/t - t)/2 * * returns atan(sinpsi2tanphi(tau')) ***************************************************************************/ return atan(pj_sinhpsi2tanphi(ctx, (1 / ts0 - ts0) / 2, e)); }
cpp
PROJ
data/projects/PROJ/src/inv.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Inverse operation invocation * Author: Thomas Knudsen, [email protected], 2018-01-02 * Based on material from Gerald Evenden (original pj_inv) * and Piyush Agram (original pj_inv3d) * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * Copyright (c) 2018, 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. *****************************************************************************/ #include <errno.h> #include <math.h> #include "proj_internal.h" #include <math.h> #define INPUT_UNITS P->right #define OUTPUT_UNITS P->left static void inv_prepare(PJ *P, PJ_COORD &coo) { if (coo.v[0] == HUGE_VAL || coo.v[1] == HUGE_VAL || coo.v[2] == HUGE_VAL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); coo = proj_coord_error(); return; } /* The helmert datum shift will choke unless it gets a sensible 4D * coordinate */ if (HUGE_VAL == coo.v[2] && P->helmert) coo.v[2] = 0.0; if (HUGE_VAL == coo.v[3] && P->helmert) coo.v[3] = 0.0; if (P->axisswap) coo = proj_trans(P->axisswap, PJ_INV, coo); /* Handle remaining possible input types */ switch (INPUT_UNITS) { case PJ_IO_UNITS_WHATEVER: break; case PJ_IO_UNITS_DEGREES: break; /* de-scale and de-offset */ case PJ_IO_UNITS_CARTESIAN: coo.xyz.x *= P->to_meter; coo.xyz.y *= P->to_meter; coo.xyz.z *= P->to_meter; if (P->is_geocent) { coo = proj_trans(P->cart, PJ_INV, coo); } break; case PJ_IO_UNITS_PROJECTED: case PJ_IO_UNITS_CLASSIC: coo.xyz.x = P->to_meter * coo.xyz.x - P->x0; coo.xyz.y = P->to_meter * coo.xyz.y - P->y0; coo.xyz.z = P->vto_meter * coo.xyz.z - P->z0; if (INPUT_UNITS == PJ_IO_UNITS_PROJECTED) return; /* Classic proj.4 functions expect plane coordinates in units of the * semimajor axis */ /* Multiplying by ra, rather than dividing by a because the CalCOFI * projection */ /* stomps on a and hence (apparently) depends on this to roundtrip * correctly */ /* (CalCOFI avoids further scaling by stomping - but a better solution * is possible) */ coo.xyz.x *= P->ra; coo.xyz.y *= P->ra; break; case PJ_IO_UNITS_RADIANS: coo.lpz.z = P->vto_meter * coo.lpz.z - P->z0; break; } } static void inv_finalize(PJ *P, PJ_COORD &coo) { if (coo.xyz.x == HUGE_VAL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); coo = proj_coord_error(); } if (OUTPUT_UNITS == PJ_IO_UNITS_RADIANS) { /* Distance from central meridian, taking system zero meridian into * account */ coo.lp.lam = coo.lp.lam + P->from_greenwich + P->lam0; /* adjust longitude to central meridian */ if (0 == P->over) coo.lpz.lam = adjlon(coo.lpz.lam); if (P->vgridshift) coo = proj_trans(P->vgridshift, PJ_INV, coo); /* Go geometric from orthometric */ if (coo.lp.lam == HUGE_VAL) return; if (P->hgridshift) coo = proj_trans(P->hgridshift, PJ_FWD, coo); else if (P->helmert || (P->cart_wgs84 != nullptr && P->cart != nullptr)) { coo = proj_trans(P->cart, PJ_FWD, coo); /* Go cartesian in local frame */ if (P->helmert) coo = proj_trans(P->helmert, PJ_FWD, coo); /* Step into WGS84 */ coo = proj_trans(P->cart_wgs84, PJ_INV, coo); /* Go back to angular using WGS84 ellps */ } if (coo.lp.lam == HUGE_VAL) return; /* If input latitude was geocentrical, convert back to geocentrical */ if (P->geoc) coo = pj_geocentric_latitude(P, PJ_FWD, coo); } } static inline PJ_COORD error_or_coord(PJ *P, PJ_COORD coord, int last_errno) { if (P->ctx->last_errno) return proj_coord_error(); P->ctx->last_errno = last_errno; return coord; } PJ_LP pj_inv(PJ_XY xy, PJ *P) { PJ_COORD coo = {{0, 0, 0, 0}}; coo.xy = xy; const int last_errno = P->ctx->last_errno; P->ctx->last_errno = 0; if (!P->skip_inv_prepare) inv_prepare(P, coo); if (HUGE_VAL == coo.v[0]) return proj_coord_error().lp; /* Do the transformation, using the lowest dimensional transformer available */ if (P->inv) { const auto lp = P->inv(coo.xy, P); coo.lp = lp; } else if (P->inv3d) { const auto lpz = P->inv3d(coo.xyz, P); coo.lpz = lpz; } else if (P->inv4d) P->inv4d(coo, P); else { proj_errno_set(P, PROJ_ERR_OTHER_NO_INVERSE_OP); return proj_coord_error().lp; } if (HUGE_VAL == coo.v[0]) return proj_coord_error().lp; if (!P->skip_inv_finalize) inv_finalize(P, coo); return error_or_coord(P, coo, last_errno).lp; } PJ_LPZ pj_inv3d(PJ_XYZ xyz, PJ *P) { PJ_COORD coo = {{0, 0, 0, 0}}; coo.xyz = xyz; const int last_errno = P->ctx->last_errno; P->ctx->last_errno = 0; if (!P->skip_inv_prepare) inv_prepare(P, coo); if (HUGE_VAL == coo.v[0]) return proj_coord_error().lpz; /* Do the transformation, using the lowest dimensional transformer feasible */ if (P->inv3d) { const auto lpz = P->inv3d(coo.xyz, P); coo.lpz = lpz; } else if (P->inv4d) P->inv4d(coo, P); else if (P->inv) { const auto lp = P->inv(coo.xy, P); coo.lp = lp; } else { proj_errno_set(P, PROJ_ERR_OTHER_NO_INVERSE_OP); return proj_coord_error().lpz; } if (HUGE_VAL == coo.v[0]) return proj_coord_error().lpz; if (!P->skip_inv_finalize) inv_finalize(P, coo); return error_or_coord(P, coo, last_errno).lpz; } bool pj_inv4d(PJ_COORD &coo, PJ *P) { const int last_errno = P->ctx->last_errno; P->ctx->last_errno = 0; if (!P->skip_inv_prepare) inv_prepare(P, coo); if (HUGE_VAL == coo.v[0]) { coo = proj_coord_error(); return false; } /* Call the highest dimensional converter available */ if (P->inv4d) P->inv4d(coo, P); else if (P->inv3d) { const auto lpz = P->inv3d(coo.xyz, P); coo.lpz = lpz; } else if (P->inv) { const auto lp = P->inv(coo.xy, P); coo.lp = lp; } else { proj_errno_set(P, PROJ_ERR_OTHER_NO_INVERSE_OP); coo = proj_coord_error(); return false; } if (HUGE_VAL == coo.v[0]) { coo = proj_coord_error(); return false; } if (!P->skip_inv_finalize) inv_finalize(P, coo); if (P->ctx->last_errno) { coo = proj_coord_error(); return false; } P->ctx->last_errno = last_errno; return true; }
cpp
PROJ
data/projects/PROJ/src/strtod.cpp
/****************************************************************************** * * Derived from GDAL port/cpl_strtod.cpp * Purpose: Functions to convert ASCII string to floating point number. * Author: Andrey Kiselev, [email protected]. * ****************************************************************************** * Copyright (c) 2006, Andrey Kiselev * Copyright (c) 2008-2012, Even Rouault <even dot rouault at mines-paris dot *org> * * 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 <locale.h> #include <stdlib.h> #include <string.h> #include "proj.h" #include "proj_config.h" #include "proj_internal.h" /************************************************************************/ /* pj_atof() */ /************************************************************************/ /** * Converts ASCII string to floating point number. * * This function converts the initial portion of the string pointed to * by nptr to double floating point representation. The behavior is the * same as * * pj_strtod(nptr, nullptr); * * This function does the same as standard atof(3), but does not take * locale in account. That means, the decimal delimiter is always '.' * (decimal point). * * @param nptr Pointer to string to convert. * * @return Converted value. */ double pj_atof(const char *nptr) { return pj_strtod(nptr, nullptr); } /************************************************************************/ /* replace_point_by_locale_point() */ /************************************************************************/ static char *replace_point_by_locale_point(const char *pszNumber, char point) { #if !defined(HAVE_LOCALECONV) #if defined(_MSC_VER) /* Visual C++ */ #pragma message("localeconv not available") #else #warning "localeconv not available" #endif static char byPoint = 0; if (byPoint == 0) { char szBuf[16]; snprintf(szBuf, sizeof(szBuf), "%.1f", 1.0); byPoint = szBuf[1]; } if (point != byPoint) { const char *pszPoint = strchr(pszNumber, point); if (pszPoint) { char *pszNew = pj_strdup(pszNumber); if (!pszNew) return nullptr; pszNew[pszPoint - pszNumber] = byPoint; return pszNew; } } return nullptr; #else const struct lconv *poLconv = localeconv(); if (poLconv && poLconv->decimal_point && poLconv->decimal_point[0] != '\0') { char byPoint = poLconv->decimal_point[0]; if (point != byPoint) { const char *pszLocalePoint = strchr(pszNumber, byPoint); const char *pszPoint = strchr(pszNumber, point); if (pszPoint || pszLocalePoint) { char *pszNew = pj_strdup(pszNumber); if (!pszNew) return nullptr; if (pszLocalePoint) pszNew[pszLocalePoint - pszNumber] = ' '; if (pszPoint) pszNew[pszPoint - pszNumber] = byPoint; return pszNew; } } } return nullptr; #endif } /************************************************************************/ /* pj_strtod() */ /************************************************************************/ /** * Converts ASCII string to floating point number. * * This function converts the initial portion of the string pointed to * by nptr to double floating point representation. This function does the * same as standard strtod(3), but does not take locale in account and use * decimal point. * * @param nptr Pointer to string to convert. * @param endptr If is not NULL, a pointer to the character after the last * character used in the conversion is stored in the location referenced * by endptr. * * @return Converted value. */ double pj_strtod(const char *nptr, char **endptr) { /* -------------------------------------------------------------------- */ /* We are implementing a simple method here: copy the input string */ /* into the temporary buffer, replace the specified decimal delimiter (.) */ /* with the one taken from locale settings (ex ',') and then use standard * strtod() */ /* on that buffer. */ /* -------------------------------------------------------------------- */ char *pszNumber = replace_point_by_locale_point(nptr, '.'); if (pszNumber) { char *pszNumberEnd; double dfValue = strtod(pszNumber, &pszNumberEnd); int nError = errno; if (endptr) { ptrdiff_t offset = pszNumberEnd - pszNumber; *endptr = const_cast<char *>(nptr + offset); } free(pszNumber); errno = nError; return dfValue; } else { return strtod(nptr, endptr); } }
cpp
PROJ
data/projects/PROJ/src/rtodms.cpp
/* Convert radian argument to DMS ascii format */ #include <math.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include "proj.h" #include "proj_internal.h" /* ** RES is fractional second figures ** RES60 = 60 * RES ** CONV = 180 * 3600 * RES / PI (radians to RES seconds) */ static double RES = 1000., RES60 = 60000., CONV = 206264806.24709635516; static char format[50] = "%dd%d'%.3f\"%c"; static int dolong = 0; void set_rtodms(int fract, int con_w) { int i; if (fract >= 0 && fract < 9) { RES = 1.; /* following not very elegant, but used infrequently */ for (i = 0; i < fract; ++i) RES *= 10.; RES60 = RES * 60.; CONV = 180. * 3600. * RES / M_PI; if (!con_w) (void)snprintf(format, sizeof(format), "%%dd%%d'%%.%df\"%%c", fract); else (void)snprintf(format, sizeof(format), "%%dd%%02d'%%0%d.%df\"%%c", fract + 2 + (fract ? 1 : 0), fract); dolong = con_w; } } char *rtodms(char *s, size_t sizeof_s, double r, int pos, int neg) { int deg, min, sign; char *ss = s; double sec; size_t sizeof_ss = sizeof_s; if (r < 0) { r = -r; if (!pos) { if (sizeof_s == 1) { *s = 0; return s; } sizeof_ss--; *ss++ = '-'; sign = 0; } else sign = neg; } else sign = pos; r = floor(r * CONV + .5); sec = fmod(r / RES, 60.); r = floor(r / RES60); min = (int)fmod(r, 60.); r = floor(r / 60.); deg = (int)r; if (dolong) (void)snprintf(ss, sizeof_ss, format, deg, min, sec, sign); else if (sec != 0.0) { char *p, *q; /* double prime + pos/neg suffix (if included) + NUL */ size_t suffix_len = sign ? 3 : 2; (void)snprintf(ss, sizeof_ss, format, deg, min, sec, sign); /* Replace potential decimal comma by decimal point for non C locale */ for (p = ss; *p != '\0'; ++p) { if (*p == ',') { *p = '.'; break; } } if (suffix_len > strlen(ss)) return s; for (q = p = ss + strlen(ss) - suffix_len; *p == '0'; --p) ; if (*p != '.') ++p; if (++q != p) (void)memmove(p, q, suffix_len); } else if (min) (void)snprintf(ss, sizeof_ss, "%dd%d'%c", deg, min, sign); else (void)snprintf(ss, sizeof_ss, "%dd%c", deg, sign); return s; }
cpp
PROJ
data/projects/PROJ/src/ell_set.cpp
/* set ellipsoid parameters a and es */ #include <math.h> #include <stddef.h> #include <string.h> #include "proj.h" #include "proj_internal.h" /* Prototypes of the pj_ellipsoid helper functions */ static int ellps_ellps(PJ *P); static int ellps_size(PJ *P); static int ellps_shape(PJ *P); static int ellps_spherification(PJ *P); static paralist *pj_get_param(paralist *list, const char *key); static char *pj_param_value(paralist *list); static const PJ_ELLPS *pj_find_ellps(const char *name); /***************************************************************************************/ int pj_ellipsoid(PJ *P) { /**************************************************************************************** This is a replacement for the classic PROJ pj_ell_set function. The main difference is that pj_ellipsoid augments the PJ object with a copy of the exact tags used to define its related ellipsoid. This makes it possible to let a new PJ object inherit the geometrical properties of an existing one. A complete ellipsoid definition comprises a size (primary) and a shape (secondary) parameter. Size parameters supported are: R, defining the radius of a spherical planet a, defining the semimajor axis of an ellipsoidal planet Shape parameters supported are: rf, the reverse flattening of the ellipsoid f, the flattening of the ellipsoid es, the eccentricity squared e, the eccentricity b, the semiminor axis The ellps=xxx parameter provides both size and shape for a number of built in ellipsoid definitions. The ellipsoid definition may be augmented with a spherification flag, turning the ellipsoid into a sphere with features defined by the ellipsoid. Spherification parameters supported are: R_A, which gives a sphere with the same surface area as the ellipsoid R_V, which gives a sphere with the same volume as the ellipsoid R_a, which gives a sphere with R = (a + b)/2 (arithmetic mean) R_g, which gives a sphere with R = sqrt(a*b) (geometric mean) R_h, which gives a sphere with R = 2*a*b/(a+b) (harmonic mean) R_lat_a=phi, which gives a sphere with R being the arithmetic mean of of the corresponding ellipsoid at latitude phi. R_lat_g=phi, which gives a sphere with R being the geometric mean of of the corresponding ellipsoid at latitude phi. R_C, which gives a sphere with the radius of the conformal sphere at phi0. If R is given as size parameter, any shape and spherification parameters given are ignored. If size and shape are given as ellps=xxx, later shape and size parameters are are taken into account as modifiers for the built in ellipsoid definition. While this may seem strange, it is in accordance with historical PROJ behavior. It can e.g. be used to define coordinates on the ellipsoid scaled to unit semimajor axis by specifying "+ellps=xxx +a=1" ****************************************************************************************/ int err = proj_errno_reset(P); const char *empty = {""}; free(P->def_size); P->def_size = nullptr; free(P->def_shape); P->def_shape = nullptr; free(P->def_spherification); P->def_spherification = nullptr; free(P->def_ellps); P->def_ellps = nullptr; /* Specifying R overrules everything */ if (pj_get_param(P->params, "R")) { if (0 != ellps_size(P)) return 1; pj_calc_ellipsoid_params(P, P->a, 0); if (proj_errno(P)) return 1; return proj_errno_restore(P, err); } /* If an ellps argument is specified, start by using that */ if (0 != ellps_ellps(P)) return 1; /* We may overwrite the size */ if (0 != ellps_size(P)) return 2; /* We may also overwrite the shape */ if (0 != ellps_shape(P)) return 3; /* When we're done with it, we compute all related ellipsoid parameters */ pj_calc_ellipsoid_params(P, P->a, P->es); /* And finally, we may turn it into a sphere */ if (0 != ellps_spherification(P)) return 4; proj_log_trace(P, "pj_ellipsoid - final: a=%.3f f=1/%7.3f, errno=%d", P->a, P->f != 0 ? 1 / P->f : 0, proj_errno(P)); proj_log_trace(P, "pj_ellipsoid - final: %s %s %s %s", P->def_size ? P->def_size : empty, P->def_shape ? P->def_shape : empty, P->def_spherification ? P->def_spherification : empty, P->def_ellps ? P->def_ellps : empty); if (proj_errno(P)) return 5; /* success */ return proj_errno_restore(P, err); } /***************************************************************************************/ static int ellps_ellps(PJ *P) { /***************************************************************************************/ const PJ_ELLPS *ellps; paralist *par = nullptr; char *name; int err; /* Sail home if ellps=xxx is not specified */ par = pj_get_param(P->params, "ellps"); if (nullptr == par) return 0; /* Then look up the right size and shape parameters from the builtin list */ if (strlen(par->param) < 7) { proj_log_error(P, _("Invalid value for +ellps")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } name = par->param + 6; ellps = pj_find_ellps(name); if (nullptr == ellps) { proj_log_error(P, _("Unrecognized value for +ellps")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* Now, get things ready for ellps_size/ellps_shape, make them do their * thing */ err = proj_errno_reset(P); paralist *new_params = pj_mkparam(ellps->major); if (nullptr == new_params) return proj_errno_set(P, PROJ_ERR_OTHER /*ENOMEM*/); new_params->next = pj_mkparam(ellps->ell); if (nullptr == new_params->next) { free(new_params); return proj_errno_set(P, PROJ_ERR_OTHER /*ENOMEM*/); } paralist *old_params = P->params; P->params = new_params; { PJ empty_PJ; pj_inherit_ellipsoid_def(&empty_PJ, P); } ellps_size(P); ellps_shape(P); P->params = old_params; free(new_params->next); free(new_params); if (proj_errno(P)) return proj_errno(P); /* Finally update P and sail home */ P->def_ellps = pj_strdup(par->param); par->used = 1; return proj_errno_restore(P, err); } /***************************************************************************************/ static int ellps_size(PJ *P) { /***************************************************************************************/ paralist *par = nullptr; int a_was_set = 0; free(P->def_size); P->def_size = nullptr; /* A size parameter *must* be given, but may have been given as ellps prior */ if (P->a != 0) a_was_set = 1; /* Check which size key is specified */ par = pj_get_param(P->params, "R"); if (nullptr == par) par = pj_get_param(P->params, "a"); if (nullptr == par) { if (a_was_set) return 0; if (P->need_ellps) proj_log_error(P, _("Major axis not given")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } P->def_size = pj_strdup(par->param); par->used = 1; P->a = pj_atof(pj_param_value(par)); if (P->a <= 0) { proj_log_error(P, _("Invalid value for major axis")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (HUGE_VAL == P->a) { proj_log_error(P, _("Invalid value for major axis")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if ('R' == par->param[0]) { P->es = P->f = P->e = P->rf = 0; P->b = P->a; } return 0; } /***************************************************************************************/ static int ellps_shape(PJ *P) { /***************************************************************************************/ const char *keys[] = {"rf", "f", "es", "e", "b"}; paralist *par = nullptr; size_t i, len; par = nullptr; len = sizeof(keys) / sizeof(char *); free(P->def_shape); P->def_shape = nullptr; /* Check which shape key is specified */ for (i = 0; i < len; i++) { par = pj_get_param(P->params, keys[i]); if (par) break; } /* Not giving a shape parameter means selecting a sphere, unless shape */ /* has been selected previously via ellps=xxx */ if (nullptr == par && P->es != 0) return 0; if (nullptr == par && P->es == 0) { P->es = P->f = 0; P->b = P->a; return 0; } P->def_shape = pj_strdup(par->param); par->used = 1; P->es = P->f = P->b = P->e = P->rf = 0; switch (i) { /* reverse flattening, rf */ case 0: P->rf = pj_atof(pj_param_value(par)); if (HUGE_VAL == P->rf || P->rf <= 0) { proj_log_error(P, _("Invalid value for rf. Should be > 0")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->f = 1 / P->rf; P->es = 2 * P->f - P->f * P->f; break; /* flattening, f */ case 1: P->f = pj_atof(pj_param_value(par)); if (HUGE_VAL == P->f || P->f < 0) { proj_log_error(P, _("Invalid value for f. Should be >= 0")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->rf = P->f != 0.0 ? 1.0 / P->f : HUGE_VAL; P->es = 2 * P->f - P->f * P->f; break; /* eccentricity squared, es */ case 2: P->es = pj_atof(pj_param_value(par)); if (HUGE_VAL == P->es || P->es < 0 || P->es >= 1) { proj_log_error(P, _("Invalid value for es. Should be in [0,1[ range")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } break; /* eccentricity, e */ case 3: P->e = pj_atof(pj_param_value(par)); if (HUGE_VAL == P->e || P->e < 0 || P->e >= 1) { proj_log_error(P, _("Invalid value for e. Should be in [0,1[ range")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->es = P->e * P->e; break; /* semiminor axis, b */ case 4: P->b = pj_atof(pj_param_value(par)); if (HUGE_VAL == P->b || P->b <= 0) { proj_log_error(P, _("Invalid value for b. Should be > 0")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (P->b == P->a) break; P->f = (P->a - P->b) / P->a; P->es = 2 * P->f - P->f * P->f; break; default: // shouldn't happen return PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE; } // Written that way to catch NaN if (!(P->es >= 0)) { proj_log_error(P, _("Invalid eccentricity")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } return 0; } /* series coefficients for calculating ellipsoid-equivalent spheres */ static const double SIXTH = 1 / 6.; static const double RA4 = 17 / 360.; static const double RA6 = 67 / 3024.; static const double RV4 = 5 / 72.; static const double RV6 = 55 / 1296.; /***************************************************************************************/ static int ellps_spherification(PJ *P) { /***************************************************************************************/ const char *keys[] = {"R_A", "R_V", "R_a", "R_g", "R_h", "R_lat_a", "R_lat_g", "R_C"}; size_t len, i; paralist *par = nullptr; double t; char *v, *endp; len = sizeof(keys) / sizeof(char *); /* Check which spherification key is specified */ for (i = 0; i < len; i++) { par = pj_get_param(P->params, keys[i]); if (par) break; } /* No spherification specified? Then we're done */ if (i == len) return 0; /* Store definition */ P->def_spherification = pj_strdup(par->param); par->used = 1; switch (i) { /* R_A - a sphere with same area as ellipsoid */ case 0: P->a *= 1. - P->es * (SIXTH + P->es * (RA4 + P->es * RA6)); break; /* R_V - a sphere with same volume as ellipsoid */ case 1: P->a *= 1. - P->es * (SIXTH + P->es * (RV4 + P->es * RV6)); break; /* R_a - a sphere with R = the arithmetic mean of the ellipsoid */ case 2: P->a = (P->a + P->b) / 2; break; /* R_g - a sphere with R = the geometric mean of the ellipsoid */ case 3: P->a = sqrt(P->a * P->b); break; /* R_h - a sphere with R = the harmonic mean of the ellipsoid */ case 4: if (P->a + P->b == 0) return proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); P->a = (2 * P->a * P->b) / (P->a + P->b); break; /* R_lat_a - a sphere with R = the arithmetic mean of the ellipsoid at given * latitude */ case 5: /* R_lat_g - a sphere with R = the geometric mean of the ellipsoid at given * latitude */ case 6: v = pj_param_value(par); t = proj_dmstor(v, &endp); if (fabs(t) > M_HALFPI) { proj_log_error( P, _("Invalid value for lat_g. |lat_g| should be <= 90°")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } t = sin(t); t = 1 - P->es * t * t; if (t == 0.) { proj_log_error(P, _("Invalid eccentricity")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (i == 5) /* arithmetic */ P->a *= (1. - P->es + t) / (2 * t * sqrt(t)); else /* geometric */ P->a *= sqrt(1 - P->es) / t; break; /* R_C - a sphere with R = radius of conformal sphere, taken at a * latitude that is phi0 (note: at least for mercator. for other * projection methods, this could be phi1) * Formula from IOGP Publication 373-7-2 – Geomatics Guidance Note number 7, * part 2 1.1 Ellipsoid parameters */ case 7: t = sin(P->phi0); t = 1 - P->es * t * t; if (t == 0.) { proj_log_error(P, _("Invalid eccentricity")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->a *= sqrt(1 - P->es) / t; break; } if (P->a <= 0.) { proj_log_error(P, _("Invalid or missing major axis")); return proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* Clean up the ellipsoidal parameters to reflect the sphere */ P->es = P->e = P->f = 0; P->rf = HUGE_VAL; P->b = P->a; pj_calc_ellipsoid_params(P, P->a, 0); return 0; } /* locate parameter in list */ static paralist *pj_get_param(paralist *list, const char *key) { size_t l = strlen(key); while (list && !(0 == strncmp(list->param, key, l) && (0 == list->param[l] || list->param[l] == '='))) list = list->next; return list; } static char *pj_param_value(paralist *list) { char *key, *value; if (nullptr == list) return nullptr; key = list->param; value = strchr(key, '='); /* a flag (i.e. a key without value) has its own name (key) as value */ return value ? value + 1 : key; } static const PJ_ELLPS *pj_find_ellps(const char *name) { int i; const char *s; const PJ_ELLPS *ellps; if (nullptr == name) return nullptr; ellps = proj_list_ellps(); /* Search through internal ellipsoid list for name */ for (i = 0; (s = ellps[i].id) && strcmp(name, s); ++i) ; if (nullptr == s) return nullptr; return ellps + i; } /**************************************************************************************/ void pj_inherit_ellipsoid_def(const PJ *src, PJ *dst) { /*************************************************************************************** Brute force copy the ellipsoidal parameters from src to dst. This code was written before the actual ellipsoid setup parameters were kept available in the PJ->def_xxx elements. ***************************************************************************************/ /* The linear parameters */ dst->a = src->a; dst->b = src->b; dst->ra = src->ra; dst->rb = src->rb; /* The eccentricities */ dst->alpha = src->alpha; dst->e = src->e; dst->es = src->es; dst->e2 = src->e2; dst->e2s = src->e2s; dst->e3 = src->e3; dst->e3s = src->e3s; dst->one_es = src->one_es; dst->rone_es = src->rone_es; /* The flattenings */ dst->f = src->f; dst->f2 = src->f2; dst->n = src->n; dst->rf = src->rf; dst->rf2 = src->rf2; dst->rn = src->rn; /* This one's for GRS80 */ dst->J = src->J; /* es and a before any +proj related adjustment */ dst->es_orig = src->es_orig; dst->a_orig = src->a_orig; } /***************************************************************************************/ int pj_calc_ellipsoid_params(PJ *P, double a, double es) { /**************************************************************************************** Calculate a large number of ancillary ellipsoidal parameters, in addition to the two traditional PROJ defining parameters: Semimajor axis, a, and the eccentricity squared, es. Most of these parameters are fairly cheap to compute in comparison to the overall effort involved in initializing a PJ object. They may, however, take a substantial part of the time taken in computing an individual point transformation. So by providing them up front, we can amortize the (already modest) cost over all transformations carried out over the entire lifetime of a PJ object, rather than incur that cost for every single transformation. Most of the parameter calculations here are based on the "angular eccentricity", i.e. the angle, measured from the semiminor axis, of a line going from the north pole to one of the foci of the ellipsoid - or in other words: The arc sine of the eccentricity. The formulae used are mostly taken from: Richard H. Rapp: Geometric Geodesy, Part I, (178 pp, 1991). Columbus, Ohio: Dept. of Geodetic Science and Surveying, Ohio State University. ****************************************************************************************/ P->a = a; P->es = es; /* Compute some ancillary ellipsoidal parameters */ if (P->e == 0) P->e = sqrt(P->es); /* eccentricity */ P->alpha = asin(P->e); /* angular eccentricity */ /* second eccentricity */ P->e2 = tan(P->alpha); P->e2s = P->e2 * P->e2; /* third eccentricity */ P->e3 = (0 != P->alpha) ? sin(P->alpha) / sqrt(2 - sin(P->alpha) * sin(P->alpha)) : 0; P->e3s = P->e3 * P->e3; /* flattening */ if (0 == P->f) P->f = 1 - cos(P->alpha); /* = 1 - sqrt (1 - PIN->es); */ if (!(P->f >= 0.0 && P->f < 1.0)) { proj_log_error(P, _("Invalid eccentricity")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE; } P->rf = P->f != 0.0 ? 1.0 / P->f : HUGE_VAL; /* second flattening */ P->f2 = (cos(P->alpha) != 0) ? 1 / cos(P->alpha) - 1 : 0; P->rf2 = P->f2 != 0.0 ? 1 / P->f2 : HUGE_VAL; /* third flattening */ P->n = pow(tan(P->alpha / 2), 2); P->rn = P->n != 0.0 ? 1 / P->n : HUGE_VAL; /* ...and a few more */ if (0 == P->b) P->b = (1 - P->f) * P->a; P->rb = 1. / P->b; P->ra = 1. / P->a; P->one_es = 1. - P->es; if (P->one_es == 0.) { proj_log_error(P, _("Invalid eccentricity")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE; } P->rone_es = 1. / P->one_es; return 0; } /**************************************************************************************/ int pj_ell_set(PJ_CONTEXT *ctx, paralist *pl, double *a, double *es) { /*************************************************************************************** Initialize ellipsoidal parameters by emulating the original ellipsoid setup function by Gerald Evenden, through a call to pj_ellipsoid ***************************************************************************************/ PJ B; int ret; B.ctx = ctx; B.params = pl; ret = pj_ellipsoid(&B); if (ret) return ret; *a = B.a; *es = B.es; return 0; }
cpp
PROJ
data/projects/PROJ/src/grids.hpp
/****************************************************************************** * Project: PROJ * Purpose: Grid management * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2019, 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. *****************************************************************************/ #ifndef GRIDS_HPP_INCLUDED #define GRIDS_HPP_INCLUDED #include <memory> #include <vector> #include "proj.h" #include "proj/util.hpp" NS_PROJ_START struct ExtentAndRes { bool isGeographic; // whether extent and resolutions are in a geographic or // projected CRS double west; // in radian for geographic, in CRS units otherwise double south; // in radian for geographic, in CRS units otherwise double east; // in radian for geographic, in CRS units otherwise double north; // in radian for geographic, in CRS units otherwise double resX; // in radian for geographic, in CRS units otherwise double resY; // in radian for geographic, in CRS units otherwise double invResX; // = 1 / resX; double invResY; // = 1 / resY; void computeInvRes(); bool fullWorldLongitude() const; bool contains(const ExtentAndRes &other) const; bool intersects(const ExtentAndRes &other) const; }; // --------------------------------------------------------------------------- class PROJ_GCC_DLL Grid { protected: std::string m_name; int m_width; int m_height; ExtentAndRes m_extent; Grid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn); public: PROJ_FOR_TEST virtual ~Grid(); PROJ_FOR_TEST int width() const { return m_width; } PROJ_FOR_TEST int height() const { return m_height; } PROJ_FOR_TEST const ExtentAndRes &extentAndRes() const { return m_extent; } PROJ_FOR_TEST const std::string &name() const { return m_name; } virtual const std::string &metadataItem(const std::string &key, int sample = -1) const = 0; PROJ_FOR_TEST virtual bool isNullGrid() const { return false; } PROJ_FOR_TEST virtual bool hasChanged() const = 0; }; // --------------------------------------------------------------------------- class PROJ_GCC_DLL VerticalShiftGrid : public Grid { protected: std::vector<std::unique_ptr<VerticalShiftGrid>> m_children{}; public: PROJ_FOR_TEST VerticalShiftGrid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn); PROJ_FOR_TEST ~VerticalShiftGrid() override; PROJ_FOR_TEST const VerticalShiftGrid *gridAt(double longitude, double lat) const; PROJ_FOR_TEST virtual bool isNodata(float /*val*/, double /* multiplier */) const = 0; // x = 0 is western-most column, y = 0 is southern-most line PROJ_FOR_TEST virtual bool valueAt(int x, int y, float &out) const = 0; PROJ_FOR_TEST virtual void reassign_context(PJ_CONTEXT *ctx) = 0; }; // --------------------------------------------------------------------------- class PROJ_GCC_DLL VerticalShiftGridSet { protected: std::string m_name{}; std::string m_format{}; std::vector<std::unique_ptr<VerticalShiftGrid>> m_grids{}; VerticalShiftGridSet(); public: PROJ_FOR_TEST virtual ~VerticalShiftGridSet(); PROJ_FOR_TEST static std::unique_ptr<VerticalShiftGridSet> open(PJ_CONTEXT *ctx, const std::string &filename); PROJ_FOR_TEST const std::string &name() const { return m_name; } PROJ_FOR_TEST const std::string &format() const { return m_format; } PROJ_FOR_TEST const std::vector<std::unique_ptr<VerticalShiftGrid>> & grids() const { return m_grids; } PROJ_FOR_TEST const VerticalShiftGrid *gridAt(double longitude, double lat) const; PROJ_FOR_TEST virtual void reassign_context(PJ_CONTEXT *ctx); PROJ_FOR_TEST virtual bool reopen(PJ_CONTEXT *ctx); }; // --------------------------------------------------------------------------- class PROJ_GCC_DLL HorizontalShiftGrid : public Grid { protected: std::vector<std::unique_ptr<HorizontalShiftGrid>> m_children{}; public: PROJ_FOR_TEST HorizontalShiftGrid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn); PROJ_FOR_TEST ~HorizontalShiftGrid() override; PROJ_FOR_TEST const HorizontalShiftGrid *gridAt(double longitude, double lat) const; // x = 0 is western-most column, y = 0 is southern-most line PROJ_FOR_TEST virtual bool valueAt(int x, int y, bool compensateNTConvention, float &longShift, float &latShift) const = 0; PROJ_FOR_TEST virtual void reassign_context(PJ_CONTEXT *ctx) = 0; }; // --------------------------------------------------------------------------- class PROJ_GCC_DLL HorizontalShiftGridSet { protected: std::string m_name{}; std::string m_format{}; std::vector<std::unique_ptr<HorizontalShiftGrid>> m_grids{}; HorizontalShiftGridSet(); public: PROJ_FOR_TEST virtual ~HorizontalShiftGridSet(); PROJ_FOR_TEST static std::unique_ptr<HorizontalShiftGridSet> open(PJ_CONTEXT *ctx, const std::string &filename); PROJ_FOR_TEST const std::string &name() const { return m_name; } PROJ_FOR_TEST const std::string &format() const { return m_format; } PROJ_FOR_TEST const std::vector<std::unique_ptr<HorizontalShiftGrid>> & grids() const { return m_grids; } PROJ_FOR_TEST const HorizontalShiftGrid *gridAt(double longitude, double lat) const; PROJ_FOR_TEST virtual void reassign_context(PJ_CONTEXT *ctx); PROJ_FOR_TEST virtual bool reopen(PJ_CONTEXT *ctx); }; // --------------------------------------------------------------------------- class PROJ_GCC_DLL GenericShiftGrid : public Grid { protected: std::vector<std::unique_ptr<GenericShiftGrid>> m_children{}; public: PROJ_FOR_TEST GenericShiftGrid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn); PROJ_FOR_TEST ~GenericShiftGrid() override; PROJ_FOR_TEST const GenericShiftGrid *gridAt(double x, double y) const; virtual const std::string &type() const = 0; PROJ_FOR_TEST virtual std::string unit(int sample) const = 0; PROJ_FOR_TEST virtual std::string description(int sample) const = 0; PROJ_FOR_TEST virtual int samplesPerPixel() const = 0; // x = 0 is western-most column, y = 0 is southern-most line PROJ_FOR_TEST virtual bool valueAt(int x, int y, int sample, float &out) const = 0; PROJ_FOR_TEST virtual bool valuesAt(int x_start, int y_start, int x_count, int y_count, int sample_count, const int *sample_idx, float *out, bool &nodataFound) const; PROJ_FOR_TEST virtual void reassign_context(PJ_CONTEXT *ctx) = 0; }; // --------------------------------------------------------------------------- class PROJ_GCC_DLL GenericShiftGridSet { protected: std::string m_name{}; std::string m_format{}; std::vector<std::unique_ptr<GenericShiftGrid>> m_grids{}; GenericShiftGridSet(); public: PROJ_FOR_TEST virtual ~GenericShiftGridSet(); PROJ_FOR_TEST static std::unique_ptr<GenericShiftGridSet> open(PJ_CONTEXT *ctx, const std::string &filename); PROJ_FOR_TEST const std::string &name() const { return m_name; } PROJ_FOR_TEST const std::string &format() const { return m_format; } PROJ_FOR_TEST const std::vector<std::unique_ptr<GenericShiftGrid>> & grids() const { return m_grids; } PROJ_FOR_TEST const GenericShiftGrid *gridAt(double x, double y) const; PROJ_FOR_TEST const GenericShiftGrid *gridAt(const std::string &type, double x, double y) const; PROJ_FOR_TEST virtual void reassign_context(PJ_CONTEXT *ctx); PROJ_FOR_TEST virtual bool reopen(PJ_CONTEXT *ctx); }; // --------------------------------------------------------------------------- typedef std::vector<std::unique_ptr<HorizontalShiftGridSet>> ListOfHGrids; typedef std::vector<std::unique_ptr<VerticalShiftGridSet>> ListOfVGrids; typedef std::vector<std::unique_ptr<GenericShiftGridSet>> ListOfGenericGrids; ListOfVGrids pj_vgrid_init(PJ *P, const char *grids); ListOfHGrids pj_hgrid_init(PJ *P, const char *grids); ListOfGenericGrids pj_generic_grid_init(PJ *P, const char *grids); PJ_LP pj_hgrid_value(PJ *P, const ListOfHGrids &grids, PJ_LP lp); double pj_vgrid_value(PJ *P, const ListOfVGrids &, PJ_LP lp, double vmultiplier); PJ_LP pj_hgrid_apply(PJ_CONTEXT *ctx, const ListOfHGrids &grids, PJ_LP lp, PJ_DIRECTION direction); const GenericShiftGrid *pj_find_generic_grid(const ListOfGenericGrids &grids, const PJ_LP &input, GenericShiftGridSet *&gridSetOut); bool pj_bilinear_interpolation_three_samples( PJ_CONTEXT *ctx, const GenericShiftGrid *grid, const PJ_LP &lp, int idx1, int idx2, int idx3, double &v1, double &v2, double &v3, bool &must_retry); NS_PROJ_END #endif // GRIDS_HPP_INCLUDED
hpp
PROJ
data/projects/PROJ/src/proj_internal.h
/****************************************************************************** * Project: PROJ.4 * Purpose: Internal plumbing for the PROJ.4 library. * * Author: Thomas Knudsen, <[email protected]> * ****************************************************************************** * Copyright (c) 2016, 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 COORD 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 PROJ_INTERNAL_H #define PROJ_INTERNAL_H #ifndef __cplusplus #error "proj_internal.h can only be included from a C++ file" #endif #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 /* enable predefined math constants M_* for MS Visual Studio */ #if defined(_MSC_VER) || defined(_WIN32) #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #endif // Use "PROJ_FALLTHROUGH;" to annotate deliberate fall-through in switches, // use it analogously to "break;". The trailing semi-colon is required. #if !defined(PROJ_FALLTHROUGH) && defined(__has_cpp_attribute) #if __cplusplus >= 201703L && __has_cpp_attribute(fallthrough) #define PROJ_FALLTHROUGH [[fallthrough]] #elif __cplusplus >= 201103L && __has_cpp_attribute(gnu::fallthrough) #define PROJ_FALLTHROUGH [[gnu::fallthrough]] #elif __cplusplus >= 201103L && __has_cpp_attribute(clang::fallthrough) #define PROJ_FALLTHROUGH [[clang::fallthrough]] #endif #endif #ifndef PROJ_FALLTHROUGH #define PROJ_FALLTHROUGH ((void)0) #endif /* standard inclusions */ #include <limits.h> #include <math.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include <string> #include <vector> #include "proj.h" #ifdef PROJ_RENAME_SYMBOLS #include "proj_symbol_rename.h" #endif #define STATIC_ASSERT(COND) ((void)sizeof(char[(COND) ? 1 : -1])) #ifndef PJ_TODEG #define PJ_TODEG(rad) ((rad)*180.0 / M_PI) #endif #ifndef PJ_TORAD #define PJ_TORAD(deg) ((deg)*M_PI / 180.0) #endif /* Maximum latitudinal overshoot accepted */ #define PJ_EPS_LAT 1e-12 #define C_NAMESPACE extern "C" #define C_NAMESPACE_VAR extern "C" #ifndef NULL #define NULL 0 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #ifndef MAX #define MIN(a, b) ((a < b) ? a : b) #define MAX(a, b) ((a > b) ? a : b) #endif #ifndef ABS #define ABS(x) ((x < 0) ? (-1 * (x)) : x) #endif /* maximum path/filename */ #ifndef MAX_PATH_FILENAME #define MAX_PATH_FILENAME 1024 #endif /* If we still haven't got M_PI*, we rely on our own defines. * For example, this is necessary when compiling with gcc and * the -ansi flag. */ #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_1_PI #define M_1_PI 0.318309886183790671538 #endif #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 #endif #ifndef M_PI_4 #define M_PI_4 0.78539816339744830962 #endif #ifndef M_2_PI #define M_2_PI 0.63661977236758134308 #endif /* M_SQRT2 might be missing */ #ifndef M_SQRT2 #define M_SQRT2 1.41421356237309504880 #endif /* some more useful math constants and aliases */ #define M_FORTPI M_PI_4 /* pi/4 */ #define M_HALFPI M_PI_2 /* pi/2 */ #define M_PI_HALFPI 4.71238898038468985769 /* 1.5*pi */ #ifndef M_TWOPI #define M_TWOPI 6.28318530717958647693 /* 2*pi */ #endif #define M_TWO_D_PI M_2_PI /* 2/pi */ #define M_TWOPI_HALFPI 7.85398163397448309616 /* 2.5*pi */ /* maximum tag id length for +init and default files */ #ifndef ID_TAG_MAX #define ID_TAG_MAX 50 #endif /* Use WIN32 as a standard windows 32 bit declaration */ #if defined(_WIN32) && !defined(WIN32) #define WIN32 #endif #if defined(_WINDOWS) && !defined(WIN32) #define WIN32 #endif /* directory delimiter for DOS support */ #ifdef WIN32 #define DIR_CHAR '\\' #else #define DIR_CHAR '/' #endif enum pj_io_units { PJ_IO_UNITS_WHATEVER = 0, /* Doesn't matter (or depends on pipeline neighbours) */ PJ_IO_UNITS_CLASSIC = 1, /* Scaled meters (right), projected system */ PJ_IO_UNITS_PROJECTED = 2, /* Meters, projected system */ PJ_IO_UNITS_CARTESIAN = 3, /* Meters, 3D cartesian system */ PJ_IO_UNITS_RADIANS = 4, /* Radians */ PJ_IO_UNITS_DEGREES = 5, /* Degrees */ }; enum pj_io_units pj_left(PJ *P); enum pj_io_units pj_right(PJ *P); PJ_COORD PROJ_DLL proj_coord_error(void); void proj_context_errno_set(PJ_CONTEXT *ctx, int err); void PROJ_DLL proj_context_set(PJ *P, PJ_CONTEXT *ctx); void proj_context_inherit(PJ *parent, PJ *child); struct projCppContext; /* not sure why we need to export it, but mingw needs it */ void PROJ_DLL proj_context_delete_cpp_context(struct projCppContext *cppContext); bool pj_fwd4d(PJ_COORD &coo, PJ *P); bool pj_inv4d(PJ_COORD &coo, PJ *P); PJ_COORD PROJ_DLL pj_approx_2D_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coo); PJ_COORD PROJ_DLL pj_approx_3D_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coo); /* Provision for gettext translatable strings */ #define _(str) (str) void PROJ_DLL proj_log_error(const PJ *P, const char *fmt, ...); void proj_log_debug(PJ *P, const char *fmt, ...); void proj_log_trace(PJ *P, const char *fmt, ...); void proj_context_log_debug(PJ_CONTEXT *ctx, const char *fmt, ...); int pj_ellipsoid(PJ *); void pj_inherit_ellipsoid_def(const PJ *src, PJ *dst); int pj_calc_ellipsoid_params(PJ *P, double a, double es); /* Geographical to geocentric latitude - another of the "simple, but useful" */ PJ_COORD pj_geocentric_latitude(const PJ *P, PJ_DIRECTION direction, PJ_COORD coord); char PROJ_DLL *pj_chomp(char *c); char PROJ_DLL *pj_shrink(char *c); size_t pj_trim_argc(char *args); char **pj_trim_argv(size_t argc, char *args); char *pj_make_args(size_t argc, char **argv); typedef struct { double r, i; } COMPLEX; /* Forward declarations and typedefs for stuff needed inside the PJ object */ struct PJconsts; union PJ_COORD; struct geod_geodesic; struct ARG_list; struct PJ_REGION_S; typedef struct PJ_REGION_S PJ_Region; typedef struct ARG_list paralist; /* parameter list */ #ifndef PROJ_H typedef struct PJconsts PJ; /* the PJ object herself */ typedef union PJ_COORD PJ_COORD; #endif struct PJ_REGION_S { double ll_long; /* lower left corner coordinates (radians) */ double ll_lat; double ur_long; /* upper right corner coordinates (radians) */ double ur_lat; }; struct PJ_AREA { bool bbox_set = false; double west_lon_degree = 0; double south_lat_degree = 0; double east_lon_degree = 0; double north_lat_degree = 0; std::string name{}; }; /***************************************************************************** Some function types that are especially useful when working with PJs ****************************************************************************** PJ_CONSTRUCTOR: A function taking a pointer-to-PJ as arg, and returning a pointer-to-PJ. Historically called twice: First with a 0 argument, to allocate memory, second with the first return value as argument, for actual setup. PJ_DESTRUCTOR: A function taking a pointer-to-PJ and an integer as args, then first handling the deallocation of the PJ, afterwards handing the integer over to the error reporting subsystem, and finally returning a null pointer in support of the "return free (P)" (aka "get the hell out of here") idiom. PJ_OPERATOR: A function taking a reference to a PJ_COORD and a pointer-to-PJ as args, applying the PJ to the PJ_COORD, and modifying in-place the passed PJ_COORD. *****************************************************************************/ typedef PJ *(*PJ_CONSTRUCTOR)(PJ *); typedef PJ *(*PJ_DESTRUCTOR)(PJ *, int); typedef void (*PJ_OPERATOR)(PJ_COORD &, PJ *); /****************************************************************************/ /* datum_type values */ #define PJD_UNKNOWN 0 #define PJD_3PARAM 1 #define PJD_7PARAM 2 #define PJD_GRIDSHIFT 3 #define PJD_WGS84 4 /* WGS84 (or anything considered equivalent) */ struct PJCoordOperation { public: int idxInOriginalList; // [min|max][x|y]Src define the bounding box of the area of validity of // the transformation, expressed in the source CRS. Except if the source // CRS is a geocentric one, in which case the bounding box is defined in // a geographic lon,lat CRS (pjSrcGeocentricToLonLat will have to be used // on input coordinates in the forward direction) double minxSrc = 0.0; double minySrc = 0.0; double maxxSrc = 0.0; double maxySrc = 0.0; // [min|max][x|y]Dst define the bounding box of the area of validity of // the transformation, expressed in the target CRS. Except if the target // CRS is a geocentric one, in which case the bounding box is defined in // a geographic lon,lat CRS (pjDstGeocentricToLonLat will have to be used // on input coordinates in the inverse direction) double minxDst = 0.0; double minyDst = 0.0; double maxxDst = 0.0; double maxyDst = 0.0; PJ *pj = nullptr; std::string name{}; double accuracy = -1.0; double pseudoArea = 0.0; std::string areaName{}; bool isOffshore = false; bool isUnknownAreaName = false; bool isPriorityOp = false; bool srcIsLonLatDegree = false; bool srcIsLatLonDegree = false; bool dstIsLonLatDegree = false; bool dstIsLatLonDegree = false; // pjSrcGeocentricToLonLat is defined if the source CRS of pj is geocentric // and in that case it transforms from those geocentric coordinates to // geographic ones in lon, lat order PJ *pjSrcGeocentricToLonLat = nullptr; // pjDstGeocentricToLonLat is defined if the target CRS of pj is geocentric // and in that case it transforms from those geocentric coordinates to // geographic ones in lon, lat order PJ *pjDstGeocentricToLonLat = nullptr; PJCoordOperation(int idxInOriginalListIn, double minxSrcIn, double minySrcIn, double maxxSrcIn, double maxySrcIn, double minxDstIn, double minyDstIn, double maxxDstIn, double maxyDstIn, PJ *pjIn, const std::string &nameIn, double accuracyIn, double pseudoAreaIn, const char *areaName, const PJ *pjSrcGeocentricToLonLatIn, const PJ *pjDstGeocentricToLonLatIn); PJCoordOperation(const PJCoordOperation &) = delete; PJCoordOperation(PJ_CONTEXT *ctx, const PJCoordOperation &other) : idxInOriginalList(other.idxInOriginalList), minxSrc(other.minxSrc), minySrc(other.minySrc), maxxSrc(other.maxxSrc), maxySrc(other.maxySrc), minxDst(other.minxDst), minyDst(other.minyDst), maxxDst(other.maxxDst), maxyDst(other.maxyDst), pj(proj_clone(ctx, other.pj)), name(std::move(other.name)), accuracy(other.accuracy), pseudoArea(other.pseudoArea), areaName(other.areaName), isOffshore(other.isOffshore), isUnknownAreaName(other.isUnknownAreaName), isPriorityOp(other.isPriorityOp), srcIsLonLatDegree(other.srcIsLonLatDegree), srcIsLatLonDegree(other.srcIsLatLonDegree), dstIsLonLatDegree(other.dstIsLonLatDegree), dstIsLatLonDegree(other.dstIsLatLonDegree), pjSrcGeocentricToLonLat( other.pjSrcGeocentricToLonLat ? proj_clone(ctx, other.pjSrcGeocentricToLonLat) : nullptr), pjDstGeocentricToLonLat( other.pjDstGeocentricToLonLat ? proj_clone(ctx, other.pjDstGeocentricToLonLat) : nullptr) {} PJCoordOperation(PJCoordOperation &&other) : idxInOriginalList(other.idxInOriginalList), minxSrc(other.minxSrc), minySrc(other.minySrc), maxxSrc(other.maxxSrc), maxySrc(other.maxySrc), minxDst(other.minxDst), minyDst(other.minyDst), maxxDst(other.maxxDst), maxyDst(other.maxyDst), name(std::move(other.name)), accuracy(other.accuracy), pseudoArea(other.pseudoArea), areaName(std::move(other.areaName)), isOffshore(other.isOffshore), isUnknownAreaName(other.isUnknownAreaName), isPriorityOp(other.isPriorityOp), srcIsLonLatDegree(other.srcIsLonLatDegree), srcIsLatLonDegree(other.srcIsLatLonDegree), dstIsLonLatDegree(other.dstIsLonLatDegree), dstIsLatLonDegree(other.dstIsLatLonDegree) { pj = other.pj; other.pj = nullptr; pjSrcGeocentricToLonLat = other.pjSrcGeocentricToLonLat; other.pjSrcGeocentricToLonLat = nullptr; pjDstGeocentricToLonLat = other.pjDstGeocentricToLonLat; other.pjDstGeocentricToLonLat = nullptr; } PJCoordOperation &operator=(const PJCoordOperation &) = delete; bool operator==(const PJCoordOperation &other) const { return idxInOriginalList == other.idxInOriginalList && minxSrc == other.minxSrc && minySrc == other.minySrc && maxxSrc == other.maxxSrc && maxySrc == other.maxySrc && minxDst == other.minxDst && minyDst == other.minyDst && maxxDst == other.maxxDst && maxyDst == other.maxyDst && name == other.name && proj_is_equivalent_to(pj, other.pj, PJ_COMP_STRICT) && accuracy == other.accuracy && areaName == other.areaName; } bool operator!=(const PJCoordOperation &other) const { return !(operator==(other)); } ~PJCoordOperation(); bool isInstantiable() const; private: static constexpr int INSTANTIABLE_STATUS_UNKNOWN = -1; // must be different from 0(=false) and 1(=true) mutable int isInstantiableCached = INSTANTIABLE_STATUS_UNKNOWN; }; enum class TMercAlgo { AUTO, // Poder/Engsager if far from central meridian, otherwise // Evenden/Snyder EVENDEN_SNYDER, PODER_ENGSAGER, }; /* base projection data structure */ struct PJconsts { /************************************************************************************* G E N E R A L P A R A M E T E R S T R U C T ************************************************************************************** TODO: Need some description here - especially about the thread context... This is the struct behind the PJ typedef **************************************************************************************/ PJ_CONTEXT *ctx = nullptr; const char *short_name = nullptr; /* From pj_list.h */ const char *descr = nullptr; /* From pj_list.h or individual PJ_*.c file */ paralist *params = nullptr; /* Parameter list */ char *def_full = nullptr; /* Full textual definition (usually 0 - set by proj_pj_info) */ PJconsts *parent = nullptr; /* Parent PJ of pipeline steps - nullptr if not a pipeline step */ /* For debugging / logging purposes */ char *def_size = nullptr; /* Shape and size parameters extracted from params */ char *def_shape = nullptr; char *def_spherification = nullptr; char *def_ellps = nullptr; struct geod_geodesic *geod = nullptr; /* For geodesic computations */ void *opaque = nullptr; /* Projection specific parameters, Defined in PJ_*.c */ int inverted = 0; /* Tell high level API functions to swap inv/fwd */ /************************************************************************************* F U N C T I O N P O I N T E R S ************************************************************************************** For projection xxx, these are pointers to functions in the corresponding PJ_xxx.c file. pj_init() delegates the setup of these to pj_projection_specific_setup_xxx(), a name which is currently hidden behind the magic curtain of the PROJECTION macro. **************************************************************************************/ PJ_XY (*fwd)(PJ_LP, PJ *) = nullptr; PJ_LP (*inv)(PJ_XY, PJ *) = nullptr; PJ_XYZ (*fwd3d)(PJ_LPZ, PJ *) = nullptr; PJ_LPZ (*inv3d)(PJ_XYZ, PJ *) = nullptr; PJ_OPERATOR fwd4d = nullptr; PJ_OPERATOR inv4d = nullptr; PJ_DESTRUCTOR destructor = nullptr; void (*reassign_context)(PJ *, PJ_CONTEXT *) = nullptr; /************************************************************************************* E L L I P S O I D P A R A M E T E R S ************************************************************************************** Despite YAGNI, we add a large number of ellipsoidal shape parameters, which are not yet set up in pj_init. They are, however, inexpensive to compute, compared to the overall time taken for setting up the complex PJ object (cf. e.g. https://en.wikipedia.org/wiki/Angular_eccentricity). But during single point projections it will often be a useful thing to have these readily available without having to recompute at every pj_fwd / pj_inv call. With this wide selection, we should be ready for quite a number of geodetic algorithms, without having to incur further ABI breakage. **************************************************************************************/ /* The linear parameters */ double a = 0.0; /* semimajor axis (radius if eccentricity==0) */ double b = 0.0; /* semiminor axis */ double ra = 0.0; /* 1/a */ double rb = 0.0; /* 1/b */ /* The eccentricities */ double alpha = 0.0; /* angular eccentricity */ double e = 0.0; /* first eccentricity */ double es = 0.0; /* first eccentricity squared */ double e2 = 0.0; /* second eccentricity */ double e2s = 0.0; /* second eccentricity squared */ double e3 = 0.0; /* third eccentricity */ double e3s = 0.0; /* third eccentricity squared */ double one_es = 0.0; /* 1 - e^2 */ double rone_es = 0.0; /* 1/one_es */ /* The flattenings */ double f = 0.0; /* first flattening */ double f2 = 0.0; /* second flattening */ double n = 0.0; /* third flattening */ double rf = 0.0; /* 1/f */ double rf2 = 0.0; /* 1/f2 */ double rn = 0.0; /* 1/n */ /* This one's for GRS80 */ double J = 0.0; /* "Dynamic form factor" */ double es_orig = 0.0; /* es and a before any +proj related adjustment */ double a_orig = 0.0; /************************************************************************************* C O O R D I N A T E H A N D L I N G **************************************************************************************/ int over = 0; /* Over-range flag */ int geoc = 0; /* Geocentric latitude flag */ int is_latlong = 0; /* proj=latlong ... not really a projection at all */ int is_geocent = 0; /* proj=geocent ... not really a projection at all */ int need_ellps = 0; /* 0 for operations that are purely cartesian */ int skip_fwd_prepare = 0; int skip_fwd_finalize = 0; int skip_inv_prepare = 0; int skip_inv_finalize = 0; enum pj_io_units left = PJ_IO_UNITS_WHATEVER; /* Flags for input/output coordinate types */ enum pj_io_units right = PJ_IO_UNITS_WHATEVER; /* These PJs are used for implementing cs2cs style coordinate handling in * the 4D API */ PJ *axisswap = nullptr; PJ *cart = nullptr; PJ *cart_wgs84 = nullptr; PJ *helmert = nullptr; PJ *hgridshift = nullptr; PJ *vgridshift = nullptr; /************************************************************************************* C A R T O G R A P H I C O F F S E T S **************************************************************************************/ double lam0 = 0.0; /* central meridian */ double phi0 = 0.0; /* central parallel */ double x0 = 0.0; /* false easting */ double y0 = 0.0; /* false northing */ double z0 = 0.0; /* height origin */ double t0 = 0.0; /* time origin */ /************************************************************************************* S C A L I N G **************************************************************************************/ double k0 = 0.0; /* General scaling factor - e.g. the 0.9996 of UTM */ double to_meter = 0.0, fr_meter = 0.0; /* Plane coordinate scaling. Internal unit [m] */ double vto_meter = 0.0, vfr_meter = 0.0; /* Vertical scaling. Internal unit [m] */ /************************************************************************************* D A T U M S A N D H E I G H T S Y S T E M S ************************************************************************************** It may be possible, and meaningful, to move the list parts of this up to the PJ_CONTEXT level. **************************************************************************************/ int datum_type = PJD_UNKNOWN; /* PJD_UNKNOWN/3PARAM/7PARAM/GRIDSHIFT/WGS84 */ double datum_params[7] = {0, 0, 0, 0, 0, 0, 0}; /* Parameters for 3PARAM and 7PARAM */ int has_geoid_vgrids = 0; /* used by legacy transform.cpp */ void *hgrids_legacy = nullptr; /* used by legacy transform.cpp. Is a pointer to a ListOfHGrids* */ void *vgrids_legacy = nullptr; /* used by legacy transform.cpp. Is a pointer to a ListOfVGrids* */ double from_greenwich = 0.0; /* prime meridian offset (in radians) */ double long_wrap_center = 0.0; /* 0.0 for -180 to 180, actually in radians*/ int is_long_wrap_set = 0; char axis[4] = {0, 0, 0, 0}; /* Axis order, pj_transform/pj_adjust_axis */ /************************************************************************************* ISO-19111 interface **************************************************************************************/ NS_PROJ::util::BaseObjectPtr iso_obj{}; bool iso_obj_is_coordinate_operation = false; double coordinateEpoch = 0; bool hasCoordinateEpoch = false; // cached results mutable std::string lastWKT{}; mutable std::string lastPROJString{}; mutable std::string lastJSONString{}; mutable bool gridsNeededAsked = false; mutable std::vector<NS_PROJ::operation::GridDescription> gridsNeeded{}; // cache pj_get_type() result to help for repeated calls to proj_factors() mutable PJ_TYPE type = PJ_TYPE_UNKNOWN; /************************************************************************************* proj_create_crs_to_crs() alternative coordinate operations **************************************************************************************/ std::vector<PJCoordOperation> alternativeCoordinateOperations{}; int iCurCoordOp = -1; bool errorIfBestTransformationNotAvailable = false; bool warnIfBestTransformationNotAvailable = true; /* to remove in PROJ 10? */ bool skipNonInstantiable = true; /************************************************************************************* E N D O F G E N E R A L P A R A M E T E R S T R U C T **************************************************************************************/ PJconsts(); PJconsts(const PJconsts &) = delete; PJconsts &operator=(const PJconsts &) = delete; }; /* Parameter list (a copy of the +proj=... etc. parameters) */ struct ARG_list { paralist *next; char used; #if (defined(__GNUC__) && __GNUC__ >= 8) || \ (defined(__clang__) && __clang_major__ >= 9) char param[]; /* variable-length member */ /* Safer to use [] for gcc 8. See https://github.com/OSGeo/proj.4/pull/1087 */ /* and https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86914 */ #else char param[1]; /* variable-length member */ #endif }; typedef union { double f; int i; char *s; } PROJVALUE; struct PJ_DATUMS { const char *id; /* datum keyword */ const char *defn; /* ie. "to_wgs84=..." */ const char *ellipse_id; /* ie from ellipse table */ const char *comments; /* EPSG code, etc */ }; struct DERIVS { double x_l, x_p; /* derivatives of x for lambda-phi */ double y_l, y_p; /* derivatives of y for lambda-phi */ }; struct FACTORS { struct DERIVS der; double h, k; /* meridional, parallel scales */ double omega, thetap; /* angular distortion, theta prime */ double conv; /* convergence */ double s; /* areal scale factor */ double a, b; /* max-min scale error */ int code; /* always 0 */ }; // Legacy struct projFileAPI_t; struct projCppContext; struct projNetworkCallbacksAndData { bool enabled = false; proj_network_open_cbk_type open = nullptr; proj_network_close_cbk_type close = nullptr; proj_network_get_header_value_cbk_type get_header_value = nullptr; proj_network_read_range_type read_range = nullptr; void *user_data = nullptr; }; struct projGridChunkCache { bool enabled = true; std::string filename{}; long long max_size = 300 * 1024 * 1024; int ttl = 86400; // 1 day }; struct projFileApiCallbackAndData { PROJ_FILE_HANDLE *(*open_cbk)(PJ_CONTEXT *ctx, const char *filename, PROJ_OPEN_ACCESS access, void *user_data) = nullptr; size_t (*read_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, void *buffer, size_t size, void *user_data) = nullptr; size_t (*write_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, const void *buffer, size_t size, void *user_data) = nullptr; int (*seek_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, long long offset, int whence, void *user_data) = nullptr; unsigned long long (*tell_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, void *user_data) = nullptr; void (*close_cbk)(PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *, void *user_data) = nullptr; int (*exists_cbk)(PJ_CONTEXT *ctx, const char *filename, void *user_data) = nullptr; int (*mkdir_cbk)(PJ_CONTEXT *ctx, const char *filename, void *user_data) = nullptr; int (*unlink_cbk)(PJ_CONTEXT *ctx, const char *filename, void *user_data) = nullptr; int (*rename_cbk)(PJ_CONTEXT *ctx, const char *oldPath, const char *newPath, void *user_data) = nullptr; void *user_data = nullptr; }; /* proj thread context */ struct pj_ctx { std::string lastFullErrorMessage{}; // used by proj_context_errno_string int last_errno = 0; int debug_level = PJ_LOG_ERROR; bool errorIfBestTransformationNotAvailableDefault = false; bool warnIfBestTransformationNotAvailableDefault = true; void (*logger)(void *, int, const char *) = nullptr; void *logger_app_data = nullptr; struct projCppContext *cpp_context = nullptr; /* internal context for C++ code */ int use_proj4_init_rules = -1; /* -1 = unknown, 0 = no, 1 = yes */ bool forceOver = false; int epsg_file_exists = -1; /* -1 = unknown, 0 = no, 1 = yes */ std::string env_var_proj_data{}; // content of PROJ_DATA (or legacy PROJ_LIB) // environment variable. Use // Filemanager::getProjDataEnvVar() to access std::vector<std::string> search_paths{}; const char **c_compat_paths = nullptr; // same, but for projinfo usage const char *(*file_finder)(PJ_CONTEXT *, const char *, void *user_data) = nullptr; void *file_finder_user_data = nullptr; bool defer_grid_opening = false; // set transiently by pj_obj_create() projFileApiCallbackAndData fileApi{}; std::string custom_sqlite3_vfs_name{}; std::string user_writable_directory{}; // BEGIN ini file settings bool iniFileLoaded = false; std::string endpoint{}; projNetworkCallbacksAndData networking{}; std::string ca_bundle_path{}; projGridChunkCache gridChunkCache{}; TMercAlgo defaultTmercAlgo = TMercAlgo::PODER_ENGSAGER; // can be overridden by content of proj.ini // END ini file settings int projStringParserCreateFromPROJStringRecursionCounter = 0; // to avoid potential infinite recursion in // PROJStringParser::createFromPROJString() int pipelineInitRecursiongCounter = 0; // to avoid potential infinite recursion in pipeline.cpp pj_ctx() = default; pj_ctx(const pj_ctx &); ~pj_ctx(); pj_ctx &operator=(const pj_ctx &) = delete; projCppContext *get_cpp_context(); void set_search_paths(const std::vector<std::string> &search_paths_in); void set_ca_bundle_path(const std::string &ca_bundle_path_in); static pj_ctx createDefault(); }; #ifndef DO_NOT_DEFINE_PROJ_HEAD #define PROJ_HEAD(name, desc) static const char des_##name[] = desc #define OPERATION(name, NEED_ELLPS) \ \ pj_projection_specific_setup_##name(PJ *P); \ C_NAMESPACE PJ *pj_##name(PJ *P); \ \ C_NAMESPACE_VAR const char *const pj_s_##name = des_##name; \ \ C_NAMESPACE PJ *pj_##name(PJ *P) { \ if (P) \ return pj_projection_specific_setup_##name(P); \ P = pj_new(); \ if (nullptr == P) \ return nullptr; \ P->short_name = #name; \ P->descr = des_##name; \ P->need_ellps = NEED_ELLPS; \ P->left = PJ_IO_UNITS_RADIANS; \ P->right = PJ_IO_UNITS_CLASSIC; \ return P; \ } \ \ PJ *pj_projection_specific_setup_##name(PJ *P) /* In ISO19000 lingo, an operation is either a conversion or a transformation */ #define PJ_CONVERSION(name, need_ellps) OPERATION(name, need_ellps) #define PJ_TRANSFORMATION(name, need_ellps) OPERATION(name, need_ellps) /* In PROJ.4 a projection is a conversion taking angular input and giving scaled * linear output */ #define PJ_PROJECTION(name) PJ_CONVERSION(name, 1) #endif /* DO_NOT_DEFINE_PROJ_HEAD */ /* procedure prototypes */ double PROJ_DLL dmstor(const char *, char **); double dmstor_ctx(PJ_CONTEXT *ctx, const char *, char **); void PROJ_DLL set_rtodms(int, int); char PROJ_DLL *rtodms(char *, size_t, double, int, int); double PROJ_DLL adjlon(double); double aacos(PJ_CONTEXT *, double); double aasin(PJ_CONTEXT *, double); double asqrt(double); double aatan2(double, double); PROJVALUE PROJ_DLL pj_param(PJ_CONTEXT *ctx, paralist *, const char *); paralist PROJ_DLL *pj_param_exists(paralist *list, const char *parameter); paralist PROJ_DLL *pj_mkparam(const char *); paralist *pj_mkparam_ws(const char *str, const char **next_str); int PROJ_DLL pj_ell_set(PJ_CONTEXT *ctx, paralist *, double *, double *); int pj_datum_set(PJ_CONTEXT *, paralist *, PJ *); int pj_angular_units_set(paralist *, PJ *); paralist *pj_clone_paralist(const paralist *); paralist *pj_search_initcache(const char *filekey); void pj_insert_initcache(const char *filekey, const paralist *list); paralist *pj_expand_init(PJ_CONTEXT *ctx, paralist *init); void *free_params(PJ_CONTEXT *ctx, paralist *start, int errlev); double *pj_enfn(double); double pj_mlfn(double, double, double, const double *); double pj_inv_mlfn(double, const double *); double pj_qsfn(double, double, double); double pj_tsfn(double, double, double); double pj_msfn(double, double, double); double PROJ_DLL pj_phi2(PJ_CONTEXT *, const double, const double); double pj_sinhpsi2tanphi(PJ_CONTEXT *, const double, const double); double *pj_authset(double); double pj_authlat(double, double *); COMPLEX pj_zpoly1(COMPLEX, const COMPLEX *, int); COMPLEX pj_zpolyd1(COMPLEX, const COMPLEX *, int, COMPLEX *); int pj_deriv(PJ_LP, double, const PJ *, struct DERIVS *); int pj_factors(PJ_LP, const PJ *, double, struct FACTORS *); void *proj_mdist_ini(double); double proj_mdist(double, double, double, const void *); double proj_inv_mdist(PJ_CONTEXT *ctx, double, const void *); void *pj_gauss_ini(double, double, double *, double *); PJ_LP pj_gauss(PJ_CONTEXT *, PJ_LP, const void *); PJ_LP pj_inv_gauss(PJ_CONTEXT *, PJ_LP, const void *); const struct PJ_DATUMS PROJ_DLL *pj_get_datums_ref(void); PJ *pj_new(void); PJ *pj_default_destructor(PJ *P, int errlev); double PROJ_DLL pj_atof(const char *nptr); double pj_strtod(const char *nptr, char **endptr); void pj_freeup_plain(PJ *P); PJ *pj_init_ctx_with_allow_init_epsg(PJ_CONTEXT *ctx, int argc, char **argv, int allow_init_epsg); std::string PROJ_DLL pj_add_type_crs_if_needed(const std::string &str); std::string pj_double_quote_string_param_if_needed(const std::string &str); PJ *pj_create_internal(PJ_CONTEXT *ctx, const char *definition); PJ *pj_create_argv_internal(PJ_CONTEXT *ctx, int argc, char **argv); // For use by projinfo void pj_load_ini(PJ_CONTEXT *ctx); // Exported for testing purposes only std::string PROJ_DLL pj_context_get_grid_cache_filename(PJ_CONTEXT *ctx); // For use by projsync void PROJ_DLL pj_context_set_user_writable_directory(PJ_CONTEXT *ctx, const std::string &path); std::string PROJ_DLL pj_get_relative_share_proj(PJ_CONTEXT *ctx); std::vector<PJCoordOperation> pj_create_prepared_operations(PJ_CONTEXT *ctx, const PJ *source_crs, const PJ *target_crs, PJ_OBJ_LIST *op_list); int pj_get_suggested_operation(PJ_CONTEXT *ctx, const std::vector<PJCoordOperation> &opList, const int iExcluded[2], bool skipNonInstantiable, PJ_DIRECTION direction, PJ_COORD coord); const PJ_UNITS *pj_list_linear_units(); const PJ_UNITS *pj_list_angular_units(); void pj_clear_hgridshift_knowngrids_cache(); void pj_clear_vgridshift_knowngrids_cache(); void pj_clear_gridshift_knowngrids_cache(); void pj_clear_sqlite_cache(); PJ_LP pj_generic_inverse_2d(PJ_XY xy, PJ *P, PJ_LP lpInitial, double deltaXYTolerance); PJ *pj_obj_create(PJ_CONTEXT *ctx, const NS_PROJ::util::BaseObjectNNPtr &objIn); /*****************************************************************************/ /* */ /* proj_api.h */ /* */ /* The rest of this header file includes what used to be "proj_api.h" */ /* */ /*****************************************************************************/ /* pj_init() and similar functions can be used with a non-C locale */ /* Can be detected too at runtime if the symbol pj_atof exists */ #define PJ_LOCALE_SAFE 1 #define RAD_TO_DEG 57.295779513082321 #define DEG_TO_RAD .017453292519943296 extern char const PROJ_DLL pj_release[]; /* global release id string */ /* procedure prototypes */ PJ_CONTEXT PROJ_DLL *pj_get_default_ctx(void); PJ_CONTEXT *pj_get_ctx(PJ *); PJ_XY PROJ_DLL pj_fwd(PJ_LP, PJ *); PJ_LP PROJ_DLL pj_inv(PJ_XY, PJ *); PJ_XYZ pj_fwd3d(PJ_LPZ, PJ *); PJ_LPZ pj_inv3d(PJ_XYZ, PJ *); void pj_clear_initcache(void); void PROJ_DLL pj_pr_list(PJ *); /* used by proj.cpp */ char *pj_get_def(PJ *, int); int pj_has_inverse(PJ *); char *pj_strdup(const char *str); const char PROJ_DLL *pj_get_release(void); void pj_acquire_lock(void); void pj_release_lock(void); bool pj_log_active(PJ_CONTEXT *ctx, int level); void pj_log(PJ_CONTEXT *ctx, int level, const char *fmt, ...); void pj_stderr_logger(void *, int, const char *); int pj_find_file(PJ_CONTEXT *ctx, const char *short_filename, char *out_full_filename, size_t out_full_filename_size); // To remove when PROJ_LIB definitely goes away void PROJ_DLL pj_stderr_proj_lib_deprecation_warning(); #endif /* ndef PROJ_INTERNAL_H */
h
PROJ
data/projects/PROJ/src/proj_json_streaming_writer.cpp
/****************************************************************************** * * Project: CPL - Common Portability Library * Purpose: JSon streaming writer * Author: Even Rouault, even.rouault at spatialys.com * ****************************************************************************** * Copyright (c) 2019, 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 */ #include <limits> #include <string> #include <vector> #include "proj_json_streaming_writer.hpp" #include <cmath> #include <sqlite3.h> #include <stdarg.h> #include <string.h> #define CPLAssert(x) \ do { \ } while (0) #define CPLIsNan std::isnan #define CPLIsInf std::isinf #define CPL_FRMT_GIB "%lld" #define CPL_FRMT_GUIB "%llu" typedef std::uint64_t GUIntBig; static std::string CPLSPrintf(const char *fmt, ...) { std::string res; res.resize(256); va_list list; va_start(list, fmt); sqlite3_vsnprintf(256, &res[0], fmt, list); va_end(list); res.resize(strlen(&res[0])); return res; } NS_PROJ_START CPLJSonStreamingWriter::CPLJSonStreamingWriter( SerializationFuncType pfnSerializationFunc, void *pUserData) : m_pfnSerializationFunc(pfnSerializationFunc), m_pUserData(pUserData) {} CPLJSonStreamingWriter::~CPLJSonStreamingWriter() { CPLAssert(m_nLevel == 0); CPLAssert(m_states.empty()); } void CPLJSonStreamingWriter::Print(const std::string &text) { if (m_pfnSerializationFunc) { m_pfnSerializationFunc(text.c_str(), m_pUserData); } else { m_osStr += text; } } void CPLJSonStreamingWriter::SetIndentationSize(int nSpaces) { CPLAssert(m_nLevel == 0); m_osIndent.clear(); m_osIndent.resize(nSpaces, ' '); } void CPLJSonStreamingWriter::IncIndent() { m_nLevel++; if (m_bPretty) m_osIndentAcc += m_osIndent; } void CPLJSonStreamingWriter::DecIndent() { CPLAssert(m_nLevel > 0); m_nLevel--; if (m_bPretty) m_osIndentAcc.resize(m_osIndentAcc.size() - m_osIndent.size()); } std::string CPLJSonStreamingWriter::FormatString(const std::string &str) { std::string ret; ret += '"'; for (char ch : str) { switch (ch) { case '"': ret += "\\\""; break; case '\\': ret += "\\\\"; break; case '\b': ret += "\\b"; break; case '\f': ret += "\\f"; break; case '\n': ret += "\\n"; break; case '\r': ret += "\\r"; break; case '\t': ret += "\\t"; break; default: if (static_cast<unsigned char>(ch) < ' ') ret += CPLSPrintf("\\u%04X", ch); else ret += ch; break; } } ret += '"'; return ret; } void CPLJSonStreamingWriter::EmitCommaIfNeeded() { if (m_bWaitForValue) { m_bWaitForValue = false; } else if (!m_states.empty()) { if (!m_states.back().bFirstChild) { Print(","); if (m_bPretty && !m_bNewLineEnabled) Print(" "); } if (m_bPretty && m_bNewLineEnabled) { Print("\n"); Print(m_osIndentAcc); } m_states.back().bFirstChild = false; } } void CPLJSonStreamingWriter::StartObj() { EmitCommaIfNeeded(); Print("{"); IncIndent(); m_states.emplace_back(State(true)); } void CPLJSonStreamingWriter::EndObj() { CPLAssert(!m_bWaitForValue); CPLAssert(!m_states.empty()); CPLAssert(m_states.back().bIsObj); DecIndent(); if (!m_states.back().bFirstChild) { if (m_bPretty && m_bNewLineEnabled) { Print("\n"); Print(m_osIndentAcc); } } m_states.pop_back(); Print("}"); } void CPLJSonStreamingWriter::StartArray() { EmitCommaIfNeeded(); Print("["); IncIndent(); m_states.emplace_back(State(false)); } void CPLJSonStreamingWriter::EndArray() { CPLAssert(!m_states.empty()); CPLAssert(!m_states.back().bIsObj); DecIndent(); if (!m_states.back().bFirstChild) { if (m_bPretty && m_bNewLineEnabled) { Print("\n"); Print(m_osIndentAcc); } } m_states.pop_back(); Print("]"); } void CPLJSonStreamingWriter::AddObjKey(const std::string &key) { CPLAssert(!m_states.empty()); CPLAssert(m_states.back().bIsObj); CPLAssert(!m_bWaitForValue); EmitCommaIfNeeded(); Print(FormatString(key)); Print(m_bPretty ? ": " : ":"); m_bWaitForValue = true; } void CPLJSonStreamingWriter::Add(bool bVal) { EmitCommaIfNeeded(); Print(bVal ? "true" : "false"); } void CPLJSonStreamingWriter::Add(const std::string &str) { EmitCommaIfNeeded(); Print(FormatString(str)); } void CPLJSonStreamingWriter::Add(const char *pszStr) { EmitCommaIfNeeded(); Print(FormatString(pszStr)); } void CPLJSonStreamingWriter::AddUnquoted(const char *pszStr) { EmitCommaIfNeeded(); Print(pszStr); } void CPLJSonStreamingWriter::Add(GIntBig nVal) { EmitCommaIfNeeded(); Print(CPLSPrintf(CPL_FRMT_GIB, nVal)); } void CPLJSonStreamingWriter::Add(GUInt64 nVal) { EmitCommaIfNeeded(); Print(CPLSPrintf(CPL_FRMT_GUIB, static_cast<GUIntBig>(nVal))); } void CPLJSonStreamingWriter::Add(float fVal, int nPrecision) { EmitCommaIfNeeded(); if (CPLIsNan(fVal)) { Print("\"NaN\""); } else if (CPLIsInf(fVal)) { Print(fVal > 0 ? "\"Infinity\"" : "\"-Infinity\""); } else { char szFormatting[10]; snprintf(szFormatting, sizeof(szFormatting), "%%.%dg", nPrecision); Print(CPLSPrintf(szFormatting, fVal)); } } void CPLJSonStreamingWriter::Add(double dfVal, int nPrecision) { EmitCommaIfNeeded(); if (CPLIsNan(dfVal)) { Print("\"NaN\""); } else if (CPLIsInf(dfVal)) { Print(dfVal > 0 ? "\"Infinity\"" : "\"-Infinity\""); } else if (dfVal >= std::numeric_limits<int>::min() && dfVal <= std::numeric_limits<int>::max() && static_cast<int>(dfVal) == dfVal) { // Avoid rounding issues on some platforms like armel, with numbers // like 2005. See https://github.com/OSGeo/PROJ/issues/3297 Print(CPLSPrintf("%d", static_cast<int>(dfVal))); } else { char szFormatting[10]; snprintf(szFormatting, sizeof(szFormatting), "%%.%dg", nPrecision); Print(CPLSPrintf(szFormatting, dfVal)); } } void CPLJSonStreamingWriter::AddNull() { EmitCommaIfNeeded(); Print("null"); } NS_PROJ_END /*! @endcond */
cpp
PROJ
data/projects/PROJ/src/sqlite3_utils.hpp
/****************************************************************************** * Project: PROJ * Purpose: SQLite3 related utilities * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2019, 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. *****************************************************************************/ #ifndef SQLITE3_HPP_INCLUDED #define SQLITE3_HPP_INCLUDED #include <memory> #include <sqlite3.h> #include "proj.h" #include "proj/util.hpp" NS_PROJ_START //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- struct pj_sqlite3_vfs : public sqlite3_vfs { std::string namePtr{}; bool fakeSync = false; bool fakeLock = false; }; // --------------------------------------------------------------------------- class SQLite3VFS { pj_sqlite3_vfs *vfs_ = nullptr; explicit SQLite3VFS(pj_sqlite3_vfs *vfs); SQLite3VFS(const SQLite3VFS &) = delete; SQLite3VFS &operator=(const SQLite3VFS &) = delete; public: ~SQLite3VFS(); static std::unique_ptr<SQLite3VFS> create(bool fakeSync, bool fakeLock, bool skipStatJournalAndWAL); const char *name() const; sqlite3_vfs *raw() { return vfs_; } }; // --------------------------------------------------------------------------- class SQLiteStatement { sqlite3_stmt *hStmt = nullptr; int iBindIdx = 1; int iResIdx = 0; SQLiteStatement(const SQLiteStatement &) = delete; SQLiteStatement &operator=(const SQLiteStatement &) = delete; public: explicit SQLiteStatement(sqlite3_stmt *hStmtIn); ~SQLiteStatement() { sqlite3_finalize(hStmt); } int execute() { return sqlite3_step(hStmt); } void bindNull() { sqlite3_bind_null(hStmt, iBindIdx); iBindIdx++; } void bindText(const char *txt) { sqlite3_bind_text(hStmt, iBindIdx, txt, -1, nullptr); iBindIdx++; } void bindInt64(sqlite3_int64 v) { sqlite3_bind_int64(hStmt, iBindIdx, v); iBindIdx++; } void bindBlob(const void *blob, size_t blob_size) { sqlite3_bind_blob(hStmt, iBindIdx, blob, static_cast<int>(blob_size), nullptr); iBindIdx++; } const char *getText() { auto ret = sqlite3_column_text(hStmt, iResIdx); iResIdx++; return reinterpret_cast<const char *>(ret); } sqlite3_int64 getInt64() { auto ret = sqlite3_column_int64(hStmt, iResIdx); iResIdx++; return ret; } const void *getBlob(int &size) { size = sqlite3_column_bytes(hStmt, iResIdx); auto ret = sqlite3_column_blob(hStmt, iResIdx); iResIdx++; return ret; } void reset() { sqlite3_reset(hStmt); iBindIdx = 1; iResIdx = 0; } void resetResIndex() { iResIdx = 0; } }; //! @endcond Doxygen_Suppress NS_PROJ_END #endif // SQLITE3_HPP_INCLUDED
hpp
PROJ
data/projects/PROJ/src/networkfilemanager.cpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to network access and caching * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2019-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. *****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #define LRU11_DO_NOT_DEFINE_OUT_OF_CLASS_METHODS #if !defined(_WIN32) && !defined(__APPLE__) && !defined(_GNU_SOURCE) // For usleep() on Cygwin #define _GNU_SOURCE #endif #include <stdlib.h> #include <algorithm> #include <limits> #include <mutex> #include <string> #include "filemanager.hpp" #include "proj.h" #include "proj/internal/internal.hpp" #include "proj/internal/lru_cache.hpp" #include "proj_internal.h" #include "sqlite3_utils.hpp" #ifdef CURL_ENABLED #include <curl/curl.h> #include <sqlite3.h> // for sqlite3_snprintf #endif #include <sys/stat.h> #ifdef _WIN32 #include <shlobj.h> #else #include <sys/types.h> #include <unistd.h> #endif #if defined(_WIN32) #include <windows.h> #elif defined(__MACH__) && defined(__APPLE__) #include <mach-o/dyld.h> #elif defined(__FreeBSD__) #include <sys/sysctl.h> #include <sys/types.h> #endif #include <time.h> //! @cond Doxygen_Suppress #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) using namespace NS_PROJ::internal; NS_PROJ_START // --------------------------------------------------------------------------- static void sleep_ms(int ms) { #ifdef _WIN32 Sleep(ms); #else usleep(ms * 1000); #endif } // --------------------------------------------------------------------------- constexpr size_t DOWNLOAD_CHUNK_SIZE = 16 * 1024; constexpr int MAX_CHUNKS = 64; struct FileProperties { unsigned long long size = 0; time_t lastChecked = 0; std::string lastModified{}; std::string etag{}; }; class NetworkChunkCache { public: void insert(PJ_CONTEXT *ctx, const std::string &url, unsigned long long chunkIdx, std::vector<unsigned char> &&data); std::shared_ptr<std::vector<unsigned char>> get(PJ_CONTEXT *ctx, const std::string &url, unsigned long long chunkIdx); std::shared_ptr<std::vector<unsigned char>> get(PJ_CONTEXT *ctx, const std::string &url, unsigned long long chunkIdx, FileProperties &props); void clearMemoryCache(); static void clearDiskChunkCache(PJ_CONTEXT *ctx); private: struct Key { std::string url; unsigned long long chunkIdx; Key(const std::string &urlIn, unsigned long long chunkIdxIn) : url(urlIn), chunkIdx(chunkIdxIn) {} bool operator==(const Key &other) const { return url == other.url && chunkIdx == other.chunkIdx; } }; struct KeyHasher { std::size_t operator()(const Key &k) const { return std::hash<std::string>{}(k.url) ^ (std::hash<unsigned long long>{}(k.chunkIdx) << 1); } }; lru11::Cache< Key, std::shared_ptr<std::vector<unsigned char>>, std::mutex, std::unordered_map< Key, typename std::list<lru11::KeyValuePair< Key, std::shared_ptr<std::vector<unsigned char>>>>::iterator, KeyHasher>> cache_{MAX_CHUNKS}; }; // --------------------------------------------------------------------------- static NetworkChunkCache gNetworkChunkCache{}; // --------------------------------------------------------------------------- class NetworkFilePropertiesCache { public: void insert(PJ_CONTEXT *ctx, const std::string &url, FileProperties &props); bool tryGet(PJ_CONTEXT *ctx, const std::string &url, FileProperties &props); void clearMemoryCache(); private: lru11::Cache<std::string, FileProperties, std::mutex> cache_{}; }; // --------------------------------------------------------------------------- static NetworkFilePropertiesCache gNetworkFileProperties{}; // --------------------------------------------------------------------------- class DiskChunkCache { PJ_CONTEXT *ctx_ = nullptr; std::string path_{}; sqlite3 *hDB_ = nullptr; std::unique_ptr<SQLite3VFS> vfs_{}; explicit DiskChunkCache(PJ_CONTEXT *ctx, const std::string &path); bool initialize(); void commitAndClose(); bool createDBStructure(); bool checkConsistency(); bool get_links(sqlite3_int64 chunk_id, sqlite3_int64 &link_id, sqlite3_int64 &prev, sqlite3_int64 &next, sqlite3_int64 &head, sqlite3_int64 &tail); bool update_links_of_prev_and_next_links(sqlite3_int64 prev, sqlite3_int64 next); bool update_linked_chunks(sqlite3_int64 link_id, sqlite3_int64 prev, sqlite3_int64 next); bool update_linked_chunks_head_tail(sqlite3_int64 head, sqlite3_int64 tail); DiskChunkCache(const DiskChunkCache &) = delete; DiskChunkCache &operator=(const DiskChunkCache &) = delete; public: static std::unique_ptr<DiskChunkCache> open(PJ_CONTEXT *ctx); ~DiskChunkCache(); sqlite3 *handle() { return hDB_; } std::unique_ptr<SQLiteStatement> prepare(const char *sql); bool move_to_head(sqlite3_int64 chunk_id); bool move_to_tail(sqlite3_int64 chunk_id); void closeAndUnlink(); }; // --------------------------------------------------------------------------- static bool pj_context_get_grid_cache_is_enabled(PJ_CONTEXT *ctx) { pj_load_ini(ctx); return ctx->gridChunkCache.enabled; } // --------------------------------------------------------------------------- static long long pj_context_get_grid_cache_max_size(PJ_CONTEXT *ctx) { pj_load_ini(ctx); return ctx->gridChunkCache.max_size; } // --------------------------------------------------------------------------- static int pj_context_get_grid_cache_ttl(PJ_CONTEXT *ctx) { pj_load_ini(ctx); return ctx->gridChunkCache.ttl; } // --------------------------------------------------------------------------- std::unique_ptr<DiskChunkCache> DiskChunkCache::open(PJ_CONTEXT *ctx) { if (!pj_context_get_grid_cache_is_enabled(ctx)) { return nullptr; } const auto cachePath = pj_context_get_grid_cache_filename(ctx); if (cachePath.empty()) { return nullptr; } auto diskCache = std::unique_ptr<DiskChunkCache>(new DiskChunkCache(ctx, cachePath)); if (!diskCache->initialize()) diskCache.reset(); return diskCache; } // --------------------------------------------------------------------------- DiskChunkCache::DiskChunkCache(PJ_CONTEXT *ctx, const std::string &path) : ctx_(ctx), path_(path) {} // --------------------------------------------------------------------------- bool DiskChunkCache::initialize() { std::string vfsName; if (ctx_->custom_sqlite3_vfs_name.empty()) { vfs_ = SQLite3VFS::create(true, false, false); if (vfs_ == nullptr) { return false; } vfsName = vfs_->name(); } else { vfsName = ctx_->custom_sqlite3_vfs_name; } sqlite3_open_v2(path_.c_str(), &hDB_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, vfsName.c_str()); if (!hDB_) { pj_log(ctx_, PJ_LOG_ERROR, "Cannot open %s", path_.c_str()); return false; } // Cannot run more than 30 times / a bit more than one second. for (int i = 0;; i++) { int ret = sqlite3_exec(hDB_, "BEGIN EXCLUSIVE", nullptr, nullptr, nullptr); if (ret == SQLITE_OK) { break; } if (ret != SQLITE_BUSY) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); sqlite3_close(hDB_); hDB_ = nullptr; return false; } const char *max_iters = getenv("PROJ_LOCK_MAX_ITERS"); if (i >= (max_iters && max_iters[0] ? atoi(max_iters) : 30)) { // A bit more than 1 second pj_log(ctx_, PJ_LOG_ERROR, "Cannot take exclusive lock on %s", path_.c_str()); sqlite3_close(hDB_); hDB_ = nullptr; return false; } pj_log(ctx_, PJ_LOG_TRACE, "Lock taken on cache. Waiting a bit..."); // Retry every 5 ms for 50 ms, then every 10 ms for 100 ms, then // every 100 ms sleep_ms(i < 10 ? 5 : i < 20 ? 10 : 100); } char **pasResult = nullptr; int nRows = 0; int nCols = 0; sqlite3_get_table(hDB_, "SELECT 1 FROM sqlite_master WHERE name = 'properties'", &pasResult, &nRows, &nCols, nullptr); sqlite3_free_table(pasResult); if (nRows == 0) { if (!createDBStructure()) { sqlite3_close(hDB_); hDB_ = nullptr; return false; } } if (getenv("PROJ_CHECK_CACHE_CONSISTENCY")) { checkConsistency(); } return true; } // --------------------------------------------------------------------------- static const char *cache_db_structure_sql = "CREATE TABLE properties(" " url TEXT PRIMARY KEY NOT NULL," " lastChecked TIMESTAMP NOT NULL," " fileSize INTEGER NOT NULL," " lastModified TEXT," " etag TEXT" ");" "CREATE TABLE downloaded_file_properties(" " url TEXT PRIMARY KEY NOT NULL," " lastChecked TIMESTAMP NOT NULL," " fileSize INTEGER NOT NULL," " lastModified TEXT," " etag TEXT" ");" "CREATE TABLE chunk_data(" " id INTEGER PRIMARY KEY AUTOINCREMENT CHECK (id > 0)," " data BLOB NOT NULL" ");" "CREATE TABLE chunks(" " id INTEGER PRIMARY KEY AUTOINCREMENT CHECK (id > 0)," " url TEXT NOT NULL," " offset INTEGER NOT NULL," " data_id INTEGER NOT NULL," " data_size INTEGER NOT NULL," " CONSTRAINT fk_chunks_url FOREIGN KEY (url) REFERENCES properties(url)," " CONSTRAINT fk_chunks_data FOREIGN KEY (data_id) REFERENCES chunk_data(id)" ");" "CREATE INDEX idx_chunks ON chunks(url, offset);" "CREATE TABLE linked_chunks(" " id INTEGER PRIMARY KEY AUTOINCREMENT CHECK (id > 0)," " chunk_id INTEGER NOT NULL," " prev INTEGER," " next INTEGER," " CONSTRAINT fk_links_chunkid FOREIGN KEY (chunk_id) REFERENCES chunks(id)," " CONSTRAINT fk_links_prev FOREIGN KEY (prev) REFERENCES linked_chunks(id)," " CONSTRAINT fk_links_next FOREIGN KEY (next) REFERENCES linked_chunks(id)" ");" "CREATE INDEX idx_linked_chunks_chunk_id ON linked_chunks(chunk_id);" "CREATE TABLE linked_chunks_head_tail(" " head INTEGER," " tail INTEGER," " CONSTRAINT lht_head FOREIGN KEY (head) REFERENCES linked_chunks(id)," " CONSTRAINT lht_tail FOREIGN KEY (tail) REFERENCES linked_chunks(id)" ");" "INSERT INTO linked_chunks_head_tail VALUES (NULL, NULL);"; bool DiskChunkCache::createDBStructure() { pj_log(ctx_, PJ_LOG_TRACE, "Creating cache DB structure"); if (sqlite3_exec(hDB_, cache_db_structure_sql, nullptr, nullptr, nullptr) != SQLITE_OK) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } return true; } // --------------------------------------------------------------------------- // Used by checkConsistency() and insert() #define INVALIDATED_SQL_LITERAL "'invalidated'" bool DiskChunkCache::checkConsistency() { auto stmt = prepare("SELECT * FROM chunk_data WHERE id NOT IN (SELECT " "data_id FROM chunks)"); if (!stmt) { return false; } if (stmt->execute() != SQLITE_DONE) { fprintf(stderr, "Rows in chunk_data not referenced by chunks.\n"); return false; } stmt = prepare("SELECT * FROM chunks WHERE id NOT IN (SELECT chunk_id FROM " "linked_chunks)"); if (!stmt) { return false; } if (stmt->execute() != SQLITE_DONE) { fprintf(stderr, "Rows in chunks not referenced by linked_chunks.\n"); return false; } stmt = prepare("SELECT * FROM chunks WHERE url <> " INVALIDATED_SQL_LITERAL " AND url " "NOT IN (SELECT url FROM properties)"); if (!stmt) { return false; } if (stmt->execute() != SQLITE_DONE) { fprintf(stderr, "url values in chunks not referenced by properties.\n"); return false; } stmt = prepare("SELECT head, tail FROM linked_chunks_head_tail"); if (!stmt) { return false; } if (stmt->execute() != SQLITE_ROW) { fprintf(stderr, "linked_chunks_head_tail empty.\n"); return false; } const auto head = stmt->getInt64(); const auto tail = stmt->getInt64(); if (stmt->execute() != SQLITE_DONE) { fprintf(stderr, "linked_chunks_head_tail has more than one row.\n"); return false; } stmt = prepare("SELECT COUNT(*) FROM linked_chunks"); if (!stmt) { return false; } if (stmt->execute() != SQLITE_ROW) { fprintf(stderr, "linked_chunks_head_tail empty.\n"); return false; } const auto count_linked_chunks = stmt->getInt64(); if (head) { auto id = head; std::set<sqlite3_int64> visitedIds; stmt = prepare("SELECT next FROM linked_chunks WHERE id = ?"); if (!stmt) { return false; } while (true) { visitedIds.insert(id); stmt->reset(); stmt->bindInt64(id); if (stmt->execute() != SQLITE_ROW) { fprintf(stderr, "cannot find linked_chunks.id = %d.\n", static_cast<int>(id)); return false; } auto next = stmt->getInt64(); if (next == 0) { if (id != tail) { fprintf(stderr, "last item when following next is not tail.\n"); return false; } break; } if (visitedIds.find(next) != visitedIds.end()) { fprintf(stderr, "found cycle on linked_chunks.next = %d.\n", static_cast<int>(next)); return false; } id = next; } if (visitedIds.size() != static_cast<size_t>(count_linked_chunks)) { fprintf(stderr, "ghost items in linked_chunks when following next.\n"); return false; } } else if (count_linked_chunks) { fprintf(stderr, "linked_chunks_head_tail.head = NULL but linked_chunks " "not empty.\n"); return false; } if (tail) { auto id = tail; std::set<sqlite3_int64> visitedIds; stmt = prepare("SELECT prev FROM linked_chunks WHERE id = ?"); if (!stmt) { return false; } while (true) { visitedIds.insert(id); stmt->reset(); stmt->bindInt64(id); if (stmt->execute() != SQLITE_ROW) { fprintf(stderr, "cannot find linked_chunks.id = %d.\n", static_cast<int>(id)); return false; } auto prev = stmt->getInt64(); if (prev == 0) { if (id != head) { fprintf(stderr, "last item when following prev is not head.\n"); return false; } break; } if (visitedIds.find(prev) != visitedIds.end()) { fprintf(stderr, "found cycle on linked_chunks.prev = %d.\n", static_cast<int>(prev)); return false; } id = prev; } if (visitedIds.size() != static_cast<size_t>(count_linked_chunks)) { fprintf(stderr, "ghost items in linked_chunks when following prev.\n"); return false; } } else if (count_linked_chunks) { fprintf(stderr, "linked_chunks_head_tail.tail = NULL but linked_chunks " "not empty.\n"); return false; } fprintf(stderr, "check ok\n"); return true; } // --------------------------------------------------------------------------- void DiskChunkCache::commitAndClose() { if (hDB_) { if (sqlite3_exec(hDB_, "COMMIT", nullptr, nullptr, nullptr) != SQLITE_OK) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); } sqlite3_close(hDB_); hDB_ = nullptr; } } // --------------------------------------------------------------------------- DiskChunkCache::~DiskChunkCache() { commitAndClose(); } // --------------------------------------------------------------------------- void DiskChunkCache::closeAndUnlink() { commitAndClose(); if (vfs_) { vfs_->raw()->xDelete(vfs_->raw(), path_.c_str(), 0); } } // --------------------------------------------------------------------------- std::unique_ptr<SQLiteStatement> DiskChunkCache::prepare(const char *sql) { sqlite3_stmt *hStmt = nullptr; sqlite3_prepare_v2(hDB_, sql, -1, &hStmt, nullptr); if (!hStmt) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return nullptr; } return std::unique_ptr<SQLiteStatement>(new SQLiteStatement(hStmt)); } // --------------------------------------------------------------------------- bool DiskChunkCache::get_links(sqlite3_int64 chunk_id, sqlite3_int64 &link_id, sqlite3_int64 &prev, sqlite3_int64 &next, sqlite3_int64 &head, sqlite3_int64 &tail) { auto stmt = prepare("SELECT id, prev, next FROM linked_chunks WHERE chunk_id = ?"); if (!stmt) return false; stmt->bindInt64(chunk_id); { const auto ret = stmt->execute(); if (ret != SQLITE_ROW) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } } link_id = stmt->getInt64(); prev = stmt->getInt64(); next = stmt->getInt64(); stmt = prepare("SELECT head, tail FROM linked_chunks_head_tail"); { const auto ret = stmt->execute(); if (ret != SQLITE_ROW) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } } head = stmt->getInt64(); tail = stmt->getInt64(); return true; } // --------------------------------------------------------------------------- bool DiskChunkCache::update_links_of_prev_and_next_links(sqlite3_int64 prev, sqlite3_int64 next) { if (prev) { auto stmt = prepare("UPDATE linked_chunks SET next = ? WHERE id = ?"); if (!stmt) return false; if (next) stmt->bindInt64(next); else stmt->bindNull(); stmt->bindInt64(prev); const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } } if (next) { auto stmt = prepare("UPDATE linked_chunks SET prev = ? WHERE id = ?"); if (!stmt) return false; if (prev) stmt->bindInt64(prev); else stmt->bindNull(); stmt->bindInt64(next); const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } } return true; } // --------------------------------------------------------------------------- bool DiskChunkCache::update_linked_chunks(sqlite3_int64 link_id, sqlite3_int64 prev, sqlite3_int64 next) { auto stmt = prepare("UPDATE linked_chunks SET prev = ?, next = ? WHERE id = ?"); if (!stmt) return false; if (prev) stmt->bindInt64(prev); else stmt->bindNull(); if (next) stmt->bindInt64(next); else stmt->bindNull(); stmt->bindInt64(link_id); const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } return true; } // --------------------------------------------------------------------------- bool DiskChunkCache::update_linked_chunks_head_tail(sqlite3_int64 head, sqlite3_int64 tail) { auto stmt = prepare("UPDATE linked_chunks_head_tail SET head = ?, tail = ?"); if (!stmt) return false; if (head) stmt->bindInt64(head); else stmt->bindNull(); // shouldn't happen normally if (tail) stmt->bindInt64(tail); else stmt->bindNull(); // shouldn't happen normally const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } return true; } // --------------------------------------------------------------------------- bool DiskChunkCache::move_to_head(sqlite3_int64 chunk_id) { sqlite3_int64 link_id = 0; sqlite3_int64 prev = 0; sqlite3_int64 next = 0; sqlite3_int64 head = 0; sqlite3_int64 tail = 0; if (!get_links(chunk_id, link_id, prev, next, head, tail)) { return false; } if (link_id == head) { return true; } if (!update_links_of_prev_and_next_links(prev, next)) { return false; } if (head) { auto stmt = prepare("UPDATE linked_chunks SET prev = ? WHERE id = ?"); if (!stmt) return false; stmt->bindInt64(link_id); stmt->bindInt64(head); const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } } return update_linked_chunks(link_id, 0, head) && update_linked_chunks_head_tail(link_id, (link_id == tail) ? prev : tail); } // --------------------------------------------------------------------------- bool DiskChunkCache::move_to_tail(sqlite3_int64 chunk_id) { sqlite3_int64 link_id = 0; sqlite3_int64 prev = 0; sqlite3_int64 next = 0; sqlite3_int64 head = 0; sqlite3_int64 tail = 0; if (!get_links(chunk_id, link_id, prev, next, head, tail)) { return false; } if (link_id == tail) { return true; } if (!update_links_of_prev_and_next_links(prev, next)) { return false; } if (tail) { auto stmt = prepare("UPDATE linked_chunks SET next = ? WHERE id = ?"); if (!stmt) return false; stmt->bindInt64(link_id); stmt->bindInt64(tail); const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx_, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB_)); return false; } } return update_linked_chunks(link_id, tail, 0) && update_linked_chunks_head_tail((link_id == head) ? next : head, link_id); } // --------------------------------------------------------------------------- void NetworkChunkCache::insert(PJ_CONTEXT *ctx, const std::string &url, unsigned long long chunkIdx, std::vector<unsigned char> &&data) { auto dataPtr(std::make_shared<std::vector<unsigned char>>(std::move(data))); cache_.insert(Key(url, chunkIdx), dataPtr); auto diskCache = DiskChunkCache::open(ctx); if (!diskCache) return; auto hDB = diskCache->handle(); // Always insert DOWNLOAD_CHUNK_SIZE bytes to avoid fragmentation std::vector<unsigned char> blob(*dataPtr); assert(blob.size() <= DOWNLOAD_CHUNK_SIZE); blob.resize(DOWNLOAD_CHUNK_SIZE); // Check if there is an existing entry for that URL and offset auto stmt = diskCache->prepare( "SELECT id, data_id FROM chunks WHERE url = ? AND offset = ?"); if (!stmt) return; stmt->bindText(url.c_str()); stmt->bindInt64(chunkIdx * DOWNLOAD_CHUNK_SIZE); const auto mainRet = stmt->execute(); if (mainRet == SQLITE_ROW) { const auto chunk_id = stmt->getInt64(); const auto data_id = stmt->getInt64(); stmt = diskCache->prepare("UPDATE chunk_data SET data = ? WHERE id = ?"); if (!stmt) return; stmt->bindBlob(blob.data(), blob.size()); stmt->bindInt64(data_id); { const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } diskCache->move_to_head(chunk_id); return; } else if (mainRet != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } // Lambda to recycle an existing entry that was either invalidated, or // least recently used. const auto reuseExistingEntry = [ctx, &blob, &diskCache, hDB, &url, chunkIdx, &dataPtr](std::unique_ptr<SQLiteStatement> &stmtIn) { const auto chunk_id = stmtIn->getInt64(); const auto data_id = stmtIn->getInt64(); if (data_id <= 0) { pj_log(ctx, PJ_LOG_ERROR, "data_id <= 0"); return; } auto l_stmt = diskCache->prepare( "UPDATE chunk_data SET data = ? WHERE id = ?"); if (!l_stmt) return; l_stmt->bindBlob(blob.data(), blob.size()); l_stmt->bindInt64(data_id); { const auto ret2 = l_stmt->execute(); if (ret2 != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } l_stmt = diskCache->prepare("UPDATE chunks SET url = ?, " "offset = ?, data_size = ?, data_id = ? " "WHERE id = ?"); if (!l_stmt) return; l_stmt->bindText(url.c_str()); l_stmt->bindInt64(chunkIdx * DOWNLOAD_CHUNK_SIZE); l_stmt->bindInt64(dataPtr->size()); l_stmt->bindInt64(data_id); l_stmt->bindInt64(chunk_id); { const auto ret2 = l_stmt->execute(); if (ret2 != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } diskCache->move_to_head(chunk_id); }; // Find if there is an invalidated chunk we can reuse stmt = diskCache->prepare( "SELECT id, data_id FROM chunks " "WHERE id = (SELECT tail FROM linked_chunks_head_tail) AND " "url = " INVALIDATED_SQL_LITERAL); if (!stmt) return; { const auto ret = stmt->execute(); if (ret == SQLITE_ROW) { reuseExistingEntry(stmt); return; } else if (ret != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } // Check if we have not reached the max size of the cache stmt = diskCache->prepare("SELECT COUNT(*) FROM chunks"); if (!stmt) return; { const auto ret = stmt->execute(); if (ret != SQLITE_ROW) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } const auto max_size = pj_context_get_grid_cache_max_size(ctx); if (max_size > 0 && static_cast<long long>(stmt->getInt64() * DOWNLOAD_CHUNK_SIZE) >= max_size) { stmt = diskCache->prepare( "SELECT id, data_id FROM chunks " "WHERE id = (SELECT tail FROM linked_chunks_head_tail)"); if (!stmt) return; const auto ret = stmt->execute(); if (ret != SQLITE_ROW) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } reuseExistingEntry(stmt); return; } // Otherwise just append a new entry stmt = diskCache->prepare("INSERT INTO chunk_data(data) VALUES (?)"); if (!stmt) return; stmt->bindBlob(blob.data(), blob.size()); { const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } const auto chunk_data_id = sqlite3_last_insert_rowid(hDB); stmt = diskCache->prepare("INSERT INTO chunks(url, offset, data_id, " "data_size) VALUES (?,?,?,?)"); if (!stmt) return; stmt->bindText(url.c_str()); stmt->bindInt64(chunkIdx * DOWNLOAD_CHUNK_SIZE); stmt->bindInt64(chunk_data_id); stmt->bindInt64(dataPtr->size()); { const auto ret = stmt->execute(); if (ret != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } const auto chunk_id = sqlite3_last_insert_rowid(hDB); stmt = diskCache->prepare( "INSERT INTO linked_chunks(chunk_id, prev, next) VALUES (?,NULL,NULL)"); if (!stmt) return; stmt->bindInt64(chunk_id); if (stmt->execute() != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } stmt = diskCache->prepare("SELECT head FROM linked_chunks_head_tail"); if (!stmt) return; if (stmt->execute() != SQLITE_ROW) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } if (stmt->getInt64() == 0) { stmt = diskCache->prepare( "UPDATE linked_chunks_head_tail SET head = ?, tail = ?"); if (!stmt) return; stmt->bindInt64(chunk_id); stmt->bindInt64(chunk_id); if (stmt->execute() != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } diskCache->move_to_head(chunk_id); } // --------------------------------------------------------------------------- std::shared_ptr<std::vector<unsigned char>> NetworkChunkCache::get(PJ_CONTEXT *ctx, const std::string &url, unsigned long long chunkIdx) { std::shared_ptr<std::vector<unsigned char>> ret; if (cache_.tryGet(Key(url, chunkIdx), ret)) { return ret; } auto diskCache = DiskChunkCache::open(ctx); if (!diskCache) return ret; auto hDB = diskCache->handle(); auto stmt = diskCache->prepare( "SELECT chunks.id, chunks.data_size, chunk_data.data FROM chunks " "JOIN chunk_data ON chunks.id = chunk_data.id " "WHERE chunks.url = ? AND chunks.offset = ?"); if (!stmt) return ret; stmt->bindText(url.c_str()); stmt->bindInt64(chunkIdx * DOWNLOAD_CHUNK_SIZE); const auto mainRet = stmt->execute(); if (mainRet == SQLITE_ROW) { const auto chunk_id = stmt->getInt64(); const auto data_size = stmt->getInt64(); int blob_size = 0; const void *blob = stmt->getBlob(blob_size); if (blob_size < data_size) { pj_log(ctx, PJ_LOG_ERROR, "blob_size=%d < data_size for chunk_id=%d", blob_size, static_cast<int>(chunk_id)); return ret; } if (data_size > static_cast<sqlite3_int64>(DOWNLOAD_CHUNK_SIZE)) { pj_log(ctx, PJ_LOG_ERROR, "data_size > DOWNLOAD_CHUNK_SIZE"); return ret; } ret.reset(new std::vector<unsigned char>()); ret->assign(reinterpret_cast<const unsigned char *>(blob), reinterpret_cast<const unsigned char *>(blob) + static_cast<size_t>(data_size)); cache_.insert(Key(url, chunkIdx), ret); if (!diskCache->move_to_head(chunk_id)) return ret; } else if (mainRet != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); } return ret; } // --------------------------------------------------------------------------- std::shared_ptr<std::vector<unsigned char>> NetworkChunkCache::get(PJ_CONTEXT *ctx, const std::string &url, unsigned long long chunkIdx, FileProperties &props) { if (!gNetworkFileProperties.tryGet(ctx, url, props)) { return nullptr; } return get(ctx, url, chunkIdx); } // --------------------------------------------------------------------------- void NetworkChunkCache::clearMemoryCache() { cache_.clear(); } // --------------------------------------------------------------------------- void NetworkChunkCache::clearDiskChunkCache(PJ_CONTEXT *ctx) { auto diskCache = DiskChunkCache::open(ctx); if (!diskCache) return; diskCache->closeAndUnlink(); } // --------------------------------------------------------------------------- void NetworkFilePropertiesCache::insert(PJ_CONTEXT *ctx, const std::string &url, FileProperties &props) { time(&props.lastChecked); cache_.insert(url, props); auto diskCache = DiskChunkCache::open(ctx); if (!diskCache) return; auto hDB = diskCache->handle(); auto stmt = diskCache->prepare("SELECT fileSize, lastModified, etag " "FROM properties WHERE url = ?"); if (!stmt) return; stmt->bindText(url.c_str()); if (stmt->execute() == SQLITE_ROW) { FileProperties cachedProps; cachedProps.size = stmt->getInt64(); const char *lastModified = stmt->getText(); cachedProps.lastModified = lastModified ? lastModified : std::string(); const char *etag = stmt->getText(); cachedProps.etag = etag ? etag : std::string(); if (props.size != cachedProps.size || props.lastModified != cachedProps.lastModified || props.etag != cachedProps.etag) { // If cached properties don't match recent fresh ones, invalidate // cached chunks stmt = diskCache->prepare("SELECT id FROM chunks WHERE url = ?"); if (!stmt) return; stmt->bindText(url.c_str()); std::vector<sqlite3_int64> ids; while (stmt->execute() == SQLITE_ROW) { ids.emplace_back(stmt->getInt64()); stmt->resetResIndex(); } for (const auto id : ids) { diskCache->move_to_tail(id); } stmt = diskCache->prepare( "UPDATE chunks SET url = " INVALIDATED_SQL_LITERAL ", " "offset = -1, data_size = 0 WHERE url = ?"); if (!stmt) return; stmt->bindText(url.c_str()); if (stmt->execute() != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } stmt = diskCache->prepare("UPDATE properties SET lastChecked = ?, " "fileSize = ?, lastModified = ?, etag = ? " "WHERE url = ?"); if (!stmt) return; stmt->bindInt64(props.lastChecked); stmt->bindInt64(props.size); if (props.lastModified.empty()) stmt->bindNull(); else stmt->bindText(props.lastModified.c_str()); if (props.etag.empty()) stmt->bindNull(); else stmt->bindText(props.etag.c_str()); stmt->bindText(url.c_str()); if (stmt->execute() != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } else { stmt = diskCache->prepare("INSERT INTO properties (url, lastChecked, " "fileSize, lastModified, etag) VALUES " "(?,?,?,?,?)"); if (!stmt) return; stmt->bindText(url.c_str()); stmt->bindInt64(props.lastChecked); stmt->bindInt64(props.size); if (props.lastModified.empty()) stmt->bindNull(); else stmt->bindText(props.lastModified.c_str()); if (props.etag.empty()) stmt->bindNull(); else stmt->bindText(props.etag.c_str()); if (stmt->execute() != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return; } } } // --------------------------------------------------------------------------- bool NetworkFilePropertiesCache::tryGet(PJ_CONTEXT *ctx, const std::string &url, FileProperties &props) { if (cache_.tryGet(url, props)) { return true; } auto diskCache = DiskChunkCache::open(ctx); if (!diskCache) return false; auto stmt = diskCache->prepare("SELECT lastChecked, fileSize, lastModified, etag " "FROM properties WHERE url = ?"); if (!stmt) return false; stmt->bindText(url.c_str()); if (stmt->execute() != SQLITE_ROW) { return false; } props.lastChecked = static_cast<time_t>(stmt->getInt64()); props.size = stmt->getInt64(); const char *lastModified = stmt->getText(); props.lastModified = lastModified ? lastModified : std::string(); const char *etag = stmt->getText(); props.etag = etag ? etag : std::string(); const auto ttl = pj_context_get_grid_cache_ttl(ctx); if (ttl > 0) { time_t curTime; time(&curTime); if (curTime > props.lastChecked + ttl) { props = FileProperties(); return false; } } cache_.insert(url, props); return true; } // --------------------------------------------------------------------------- void NetworkFilePropertiesCache::clearMemoryCache() { cache_.clear(); } // --------------------------------------------------------------------------- class NetworkFile : public File { PJ_CONTEXT *m_ctx; std::string m_url; PROJ_NETWORK_HANDLE *m_handle; unsigned long long m_pos = 0; size_t m_nBlocksToDownload = 1; unsigned long long m_lastDownloadedOffset; FileProperties m_props; proj_network_close_cbk_type m_closeCbk; bool m_hasChanged = false; NetworkFile(const NetworkFile &) = delete; NetworkFile &operator=(const NetworkFile &) = delete; protected: NetworkFile(PJ_CONTEXT *ctx, const std::string &url, PROJ_NETWORK_HANDLE *handle, unsigned long long lastDownloadOffset, const FileProperties &props) : File(url), m_ctx(ctx), m_url(url), m_handle(handle), m_lastDownloadedOffset(lastDownloadOffset), m_props(props), m_closeCbk(ctx->networking.close) {} public: ~NetworkFile() override; size_t read(void *buffer, size_t sizeBytes) override; size_t write(const void *, size_t) override { return 0; } bool seek(unsigned long long offset, int whence) override; unsigned long long tell() override; void reassign_context(PJ_CONTEXT *ctx) override; bool hasChanged() const override { return m_hasChanged; } static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename); static bool get_props_from_headers(PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, FileProperties &props); }; // --------------------------------------------------------------------------- bool NetworkFile::get_props_from_headers(PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, FileProperties &props) { const char *contentRange = ctx->networking.get_header_value( ctx, handle, "Content-Range", ctx->networking.user_data); if (contentRange) { const char *slash = strchr(contentRange, '/'); if (slash) { props.size = std::stoull(slash + 1); const char *lastModified = ctx->networking.get_header_value( ctx, handle, "Last-Modified", ctx->networking.user_data); if (lastModified) props.lastModified = lastModified; const char *etag = ctx->networking.get_header_value( ctx, handle, "ETag", ctx->networking.user_data); if (etag) props.etag = etag; return true; } } return false; } // --------------------------------------------------------------------------- std::unique_ptr<File> NetworkFile::open(PJ_CONTEXT *ctx, const char *filename) { FileProperties props; if (gNetworkChunkCache.get(ctx, filename, 0, props)) { return std::unique_ptr<File>(new NetworkFile( ctx, filename, nullptr, std::numeric_limits<unsigned long long>::max(), props)); } else { std::vector<unsigned char> buffer(DOWNLOAD_CHUNK_SIZE); size_t size_read = 0; std::string errorBuffer; errorBuffer.resize(1024); auto handle = ctx->networking.open( ctx, filename, 0, buffer.size(), buffer.data(), &size_read, errorBuffer.size(), &errorBuffer[0], ctx->networking.user_data); if (!handle) { errorBuffer.resize(strlen(errorBuffer.data())); pj_log(ctx, PJ_LOG_ERROR, "Cannot open %s: %s", filename, errorBuffer.c_str()); proj_context_errno_set(ctx, PROJ_ERR_OTHER_NETWORK_ERROR); } else if (get_props_from_headers(ctx, handle, props)) { gNetworkFileProperties.insert(ctx, filename, props); buffer.resize(size_read); gNetworkChunkCache.insert(ctx, filename, 0, std::move(buffer)); return std::unique_ptr<File>( new NetworkFile(ctx, filename, handle, size_read, props)); } else { ctx->networking.close(ctx, handle, ctx->networking.user_data); } return std::unique_ptr<File>(nullptr); } } // --------------------------------------------------------------------------- std::unique_ptr<File> pj_network_file_open(PJ_CONTEXT *ctx, const char *filename) { return NetworkFile::open(ctx, filename); } // --------------------------------------------------------------------------- size_t NetworkFile::read(void *buffer, size_t sizeBytes) { if (sizeBytes == 0) return 0; auto iterOffset = m_pos; while (sizeBytes) { const auto chunkIdxToDownload = iterOffset / DOWNLOAD_CHUNK_SIZE; const auto offsetToDownload = chunkIdxToDownload * DOWNLOAD_CHUNK_SIZE; std::vector<unsigned char> region; auto pChunk = gNetworkChunkCache.get(m_ctx, m_url, chunkIdxToDownload); if (pChunk != nullptr) { region = *pChunk; } else { if (offsetToDownload == m_lastDownloadedOffset) { // In case of consecutive reads (of small size), we use a // heuristic that we will read the file sequentially, so // we double the requested size to decrease the number of // client/server roundtrips. if (m_nBlocksToDownload < 100) m_nBlocksToDownload *= 2; } else { // Random reads. Cancel the above heuristics. m_nBlocksToDownload = 1; } // Ensure that we will request at least the number of blocks // to satisfy the remaining buffer size to read. const auto endOffsetToDownload = ((iterOffset + sizeBytes + DOWNLOAD_CHUNK_SIZE - 1) / DOWNLOAD_CHUNK_SIZE) * DOWNLOAD_CHUNK_SIZE; const auto nMinBlocksToDownload = static_cast<size_t>( (endOffsetToDownload - offsetToDownload) / DOWNLOAD_CHUNK_SIZE); if (m_nBlocksToDownload < nMinBlocksToDownload) m_nBlocksToDownload = nMinBlocksToDownload; // Avoid reading already cached data. // Note: this might get evicted if concurrent reads are done, but // this should not cause bugs. Just missed optimization. for (size_t i = 1; i < m_nBlocksToDownload; i++) { if (gNetworkChunkCache.get(m_ctx, m_url, chunkIdxToDownload + i) != nullptr) { m_nBlocksToDownload = i; break; } } if (m_nBlocksToDownload > MAX_CHUNKS) m_nBlocksToDownload = MAX_CHUNKS; region.resize(m_nBlocksToDownload * DOWNLOAD_CHUNK_SIZE); size_t nRead = 0; std::string errorBuffer; errorBuffer.resize(1024); if (!m_handle) { m_handle = m_ctx->networking.open( m_ctx, m_url.c_str(), offsetToDownload, m_nBlocksToDownload * DOWNLOAD_CHUNK_SIZE, &region[0], &nRead, errorBuffer.size(), &errorBuffer[0], m_ctx->networking.user_data); if (!m_handle) { proj_context_errno_set(m_ctx, PROJ_ERR_OTHER_NETWORK_ERROR); return 0; } } else { nRead = m_ctx->networking.read_range( m_ctx, m_handle, offsetToDownload, m_nBlocksToDownload * DOWNLOAD_CHUNK_SIZE, &region[0], errorBuffer.size(), &errorBuffer[0], m_ctx->networking.user_data); } if (nRead == 0) { errorBuffer.resize(strlen(errorBuffer.data())); if (!errorBuffer.empty()) { pj_log(m_ctx, PJ_LOG_ERROR, "Cannot read in %s: %s", m_url.c_str(), errorBuffer.c_str()); } proj_context_errno_set(m_ctx, PROJ_ERR_OTHER_NETWORK_ERROR); return 0; } if (!m_hasChanged) { FileProperties props; if (get_props_from_headers(m_ctx, m_handle, props)) { if (props.size != m_props.size || props.lastModified != m_props.lastModified || props.etag != m_props.etag) { gNetworkFileProperties.insert(m_ctx, m_url, props); gNetworkChunkCache.clearMemoryCache(); m_hasChanged = true; } } } region.resize(nRead); m_lastDownloadedOffset = offsetToDownload + nRead; const auto nChunks = (region.size() + DOWNLOAD_CHUNK_SIZE - 1) / DOWNLOAD_CHUNK_SIZE; for (size_t i = 0; i < nChunks; i++) { std::vector<unsigned char> chunk( region.data() + i * DOWNLOAD_CHUNK_SIZE, region.data() + std::min((i + 1) * DOWNLOAD_CHUNK_SIZE, region.size())); gNetworkChunkCache.insert(m_ctx, m_url, chunkIdxToDownload + i, std::move(chunk)); } } const size_t nToCopy = static_cast<size_t>( std::min(static_cast<unsigned long long>(sizeBytes), region.size() - (iterOffset - offsetToDownload))); memcpy(buffer, region.data() + iterOffset - offsetToDownload, nToCopy); buffer = static_cast<char *>(buffer) + nToCopy; iterOffset += nToCopy; sizeBytes -= nToCopy; if (region.size() < static_cast<size_t>(DOWNLOAD_CHUNK_SIZE) && sizeBytes != 0) { break; } } size_t nRead = static_cast<size_t>(iterOffset - m_pos); m_pos = iterOffset; return nRead; } // --------------------------------------------------------------------------- bool NetworkFile::seek(unsigned long long offset, int whence) { if (whence == SEEK_SET) { m_pos = offset; } else if (whence == SEEK_CUR) { m_pos += offset; } else { if (offset != 0) return false; m_pos = m_props.size; } return true; } // --------------------------------------------------------------------------- unsigned long long NetworkFile::tell() { return m_pos; } // --------------------------------------------------------------------------- NetworkFile::~NetworkFile() { if (m_handle) { m_ctx->networking.close(m_ctx, m_handle, m_ctx->networking.user_data); } } // --------------------------------------------------------------------------- void NetworkFile::reassign_context(PJ_CONTEXT *ctx) { m_ctx = ctx; if (m_closeCbk != m_ctx->networking.close) { pj_log(m_ctx, PJ_LOG_ERROR, "Networking close callback has changed following context " "reassignment ! This is highly suspicious"); } } // --------------------------------------------------------------------------- #ifdef CURL_ENABLED struct CurlFileHandle { std::string m_url; CURL *m_handle; std::string m_headers{}; std::string m_lastval{}; std::string m_useragent{}; char m_szCurlErrBuf[CURL_ERROR_SIZE + 1] = {}; CurlFileHandle(const CurlFileHandle &) = delete; CurlFileHandle &operator=(const CurlFileHandle &) = delete; explicit CurlFileHandle(PJ_CONTEXT *ctx, const char *url, CURL *handle); ~CurlFileHandle(); static PROJ_NETWORK_HANDLE * open(PJ_CONTEXT *, const char *url, unsigned long long offset, size_t size_to_read, void *buffer, size_t *out_size_read, size_t error_string_max_size, char *out_error_string, void *); }; // --------------------------------------------------------------------------- static std::string GetExecutableName() { #if defined(__linux) std::string path; path.resize(1024); const auto ret = readlink("/proc/self/exe", &path[0], path.size()); if (ret > 0) { path.resize(ret); const auto pos = path.rfind('/'); if (pos != std::string::npos) { path = path.substr(pos + 1); } return path; } #elif defined(_WIN32) std::string path; path.resize(1024); if (GetModuleFileNameA(nullptr, &path[0], static_cast<DWORD>(path.size()))) { path.resize(strlen(path.c_str())); const auto pos = path.rfind('\\'); if (pos != std::string::npos) { path = path.substr(pos + 1); } return path; } #elif defined(__MACH__) && defined(__APPLE__) std::string path; path.resize(1024); uint32_t size = static_cast<uint32_t>(path.size()); if (_NSGetExecutablePath(&path[0], &size) == 0) { path.resize(strlen(path.c_str())); const auto pos = path.rfind('/'); if (pos != std::string::npos) { path = path.substr(pos + 1); } return path; } #elif defined(__FreeBSD__) int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; std::string path; path.resize(1024); size_t size = path.size(); if (sysctl(mib, 4, &path[0], &size, nullptr, 0) == 0) { path.resize(strlen(path.c_str())); const auto pos = path.rfind('/'); if (pos != std::string::npos) { path = path.substr(pos + 1); } return path; } #endif return std::string(); } // --------------------------------------------------------------------------- static void checkRet(PJ_CONTEXT *ctx, CURLcode code, int line) { if (code != CURLE_OK) { pj_log(ctx, PJ_LOG_ERROR, "curl_easy_setopt at line %d failed", line); } } #define CHECK_RET(ctx, code) checkRet(ctx, code, __LINE__) // --------------------------------------------------------------------------- static std::string pj_context_get_bundle_path(PJ_CONTEXT *ctx) { pj_load_ini(ctx); return ctx->ca_bundle_path; } // --------------------------------------------------------------------------- CurlFileHandle::CurlFileHandle(PJ_CONTEXT *ctx, const char *url, CURL *handle) : m_url(url), m_handle(handle) { CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_URL, m_url.c_str())); if (getenv("PROJ_CURL_VERBOSE")) CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_VERBOSE, 1)); // CURLOPT_SUPPRESS_CONNECT_HEADERS is defined in curl 7.54.0 or newer. #if LIBCURL_VERSION_NUM >= 0x073600 CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L)); #endif // Enable following redirections. Requires libcurl 7.10.1 at least. CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1)); CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 10)); if (getenv("PROJ_UNSAFE_SSL")) { CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L)); CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L)); } #if defined(SSL_OPTIONS) // https://curl.se/libcurl/c/CURLOPT_SSL_OPTIONS.html auto ssl_options = static_cast<long>(SSL_OPTIONS); CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_SSL_OPTIONS, ssl_options)); #endif const auto ca_bundle_path = pj_context_get_bundle_path(ctx); if (!ca_bundle_path.empty()) { CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_CAINFO, ca_bundle_path.c_str())); } CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, m_szCurlErrBuf)); if (getenv("PROJ_NO_USERAGENT") == nullptr) { m_useragent = "PROJ " STR(PROJ_VERSION_MAJOR) "." STR( PROJ_VERSION_MINOR) "." STR(PROJ_VERSION_PATCH); const auto exeName = GetExecutableName(); if (!exeName.empty()) { m_useragent = exeName + " using " + m_useragent; } CHECK_RET(ctx, curl_easy_setopt(handle, CURLOPT_USERAGENT, m_useragent.data())); } } // --------------------------------------------------------------------------- CurlFileHandle::~CurlFileHandle() { curl_easy_cleanup(m_handle); } // --------------------------------------------------------------------------- static size_t pj_curl_write_func(void *buffer, size_t count, size_t nmemb, void *req) { const size_t nSize = count * nmemb; auto pStr = static_cast<std::string *>(req); if (pStr->size() + nSize > pStr->capacity()) { // to avoid servers not honouring Range to cause excessive memory // allocation return 0; } pStr->append(static_cast<const char *>(buffer), nSize); return nmemb; } // --------------------------------------------------------------------------- static double GetNewRetryDelay(int response_code, double dfOldDelay, const char *pszErrBuf, const char *pszCurlError) { if (response_code == 429 || response_code == 500 || (response_code >= 502 && response_code <= 504) || // S3 sends some client timeout errors as 400 Client Error (response_code == 400 && pszErrBuf && strstr(pszErrBuf, "RequestTimeout")) || (pszCurlError && strstr(pszCurlError, "Connection timed out"))) { // Use an exponential backoff factor of 2 plus some random jitter // We don't care about cryptographic quality randomness, hence: // coverity[dont_call] return dfOldDelay * (2 + rand() * 0.5 / RAND_MAX); } else { return 0; } } // --------------------------------------------------------------------------- constexpr double MIN_RETRY_DELAY_MS = 500; constexpr double MAX_RETRY_DELAY_MS = 60000; PROJ_NETWORK_HANDLE *CurlFileHandle::open(PJ_CONTEXT *ctx, const char *url, unsigned long long offset, size_t size_to_read, void *buffer, size_t *out_size_read, size_t error_string_max_size, char *out_error_string, void *) { CURL *hCurlHandle = curl_easy_init(); if (!hCurlHandle) return nullptr; auto file = std::unique_ptr<CurlFileHandle>( new CurlFileHandle(ctx, url, hCurlHandle)); double oldDelay = MIN_RETRY_DELAY_MS; std::string headers; std::string body; char szBuffer[128]; sqlite3_snprintf(sizeof(szBuffer), szBuffer, "%llu-%llu", offset, offset + size_to_read - 1); while (true) { CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, szBuffer)); headers.clear(); headers.reserve(16 * 1024); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA, &headers)); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION, pj_curl_write_func)); body.clear(); body.reserve(size_to_read); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &body)); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION, pj_curl_write_func)); file->m_szCurlErrBuf[0] = '\0'; curl_easy_perform(hCurlHandle); long response_code = 0; curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA, nullptr)); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION, nullptr)); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, nullptr)); CHECK_RET( ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION, nullptr)); if (response_code == 0 || response_code >= 300) { const double delay = GetNewRetryDelay(static_cast<int>(response_code), oldDelay, body.c_str(), file->m_szCurlErrBuf); if (delay != 0 && delay < MAX_RETRY_DELAY_MS) { pj_log(ctx, PJ_LOG_TRACE, "Got a HTTP %ld error. Retrying in %d ms", response_code, static_cast<int>(delay)); sleep_ms(static_cast<int>(delay)); oldDelay = delay; } else { if (out_error_string) { if (file->m_szCurlErrBuf[0]) { snprintf(out_error_string, error_string_max_size, "%s", file->m_szCurlErrBuf); } else { snprintf(out_error_string, error_string_max_size, "HTTP error %ld: %s", response_code, body.c_str()); } } return nullptr; } } else { break; } } if (out_error_string && error_string_max_size) { out_error_string[0] = '\0'; } if (!body.empty()) { memcpy(buffer, body.data(), std::min(size_to_read, body.size())); } *out_size_read = std::min(size_to_read, body.size()); file->m_headers = std::move(headers); return reinterpret_cast<PROJ_NETWORK_HANDLE *>(file.release()); } // --------------------------------------------------------------------------- static void pj_curl_close(PJ_CONTEXT *, PROJ_NETWORK_HANDLE *handle, void * /*user_data*/) { delete reinterpret_cast<CurlFileHandle *>(handle); } // --------------------------------------------------------------------------- static size_t pj_curl_read_range(PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *raw_handle, unsigned long long offset, size_t size_to_read, void *buffer, size_t error_string_max_size, char *out_error_string, void *) { auto handle = reinterpret_cast<CurlFileHandle *>(raw_handle); auto hCurlHandle = handle->m_handle; double oldDelay = MIN_RETRY_DELAY_MS; std::string headers; std::string body; char szBuffer[128]; sqlite3_snprintf(sizeof(szBuffer), szBuffer, "%llu-%llu", offset, offset + size_to_read - 1); while (true) { CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, szBuffer)); headers.clear(); headers.reserve(16 * 1024); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA, &headers)); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION, pj_curl_write_func)); body.clear(); body.reserve(size_to_read); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &body)); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION, pj_curl_write_func)); handle->m_szCurlErrBuf[0] = '\0'; curl_easy_perform(hCurlHandle); long response_code = 0; curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code); CHECK_RET(ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, nullptr)); CHECK_RET( ctx, curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION, nullptr)); if (response_code == 0 || response_code >= 300) { const double delay = GetNewRetryDelay(static_cast<int>(response_code), oldDelay, body.c_str(), handle->m_szCurlErrBuf); if (delay != 0 && delay < MAX_RETRY_DELAY_MS) { pj_log(ctx, PJ_LOG_TRACE, "Got a HTTP %ld error. Retrying in %d ms", response_code, static_cast<int>(delay)); sleep_ms(static_cast<int>(delay)); oldDelay = delay; } else { if (out_error_string) { if (handle->m_szCurlErrBuf[0]) { snprintf(out_error_string, error_string_max_size, "%s", handle->m_szCurlErrBuf); } else { snprintf(out_error_string, error_string_max_size, "HTTP error %ld: %s", response_code, body.c_str()); } } return 0; } } else { break; } } if (out_error_string && error_string_max_size) { out_error_string[0] = '\0'; } if (!body.empty()) { memcpy(buffer, body.data(), std::min(size_to_read, body.size())); } handle->m_headers = std::move(headers); return std::min(size_to_read, body.size()); } // --------------------------------------------------------------------------- static const char *pj_curl_get_header_value(PJ_CONTEXT *, PROJ_NETWORK_HANDLE *raw_handle, const char *header_name, void *) { auto handle = reinterpret_cast<CurlFileHandle *>(raw_handle); auto pos = ci_find(handle->m_headers, header_name); if (pos == std::string::npos) return nullptr; pos += strlen(header_name); const char *c_str = handle->m_headers.c_str(); if (c_str[pos] == ':') pos++; while (c_str[pos] == ' ') pos++; auto posEnd = pos; while (c_str[posEnd] != '\r' && c_str[posEnd] != '\n' && c_str[posEnd] != '\0') posEnd++; handle->m_lastval = handle->m_headers.substr(pos, posEnd - pos); return handle->m_lastval.c_str(); } #else // --------------------------------------------------------------------------- static PROJ_NETWORK_HANDLE * no_op_network_open(PJ_CONTEXT *, const char * /* url */, unsigned long long, /* offset */ size_t, /* size to read */ void *, /* buffer to update with bytes read*/ size_t *, /* output: size actually read */ size_t error_string_max_size, char *out_error_string, void * /*user_data*/) { if (out_error_string) { snprintf(out_error_string, error_string_max_size, "%s", "Network functionality not available"); } return nullptr; } // --------------------------------------------------------------------------- static void no_op_network_close(PJ_CONTEXT *, PROJ_NETWORK_HANDLE *, void * /*user_data*/) {} #endif // --------------------------------------------------------------------------- void FileManager::fillDefaultNetworkInterface(PJ_CONTEXT *ctx) { #ifdef CURL_ENABLED ctx->networking.open = CurlFileHandle::open; ctx->networking.close = pj_curl_close; ctx->networking.read_range = pj_curl_read_range; ctx->networking.get_header_value = pj_curl_get_header_value; #else ctx->networking.open = no_op_network_open; ctx->networking.close = no_op_network_close; #endif } // --------------------------------------------------------------------------- void FileManager::clearMemoryCache() { gNetworkChunkCache.clearMemoryCache(); gNetworkFileProperties.clearMemoryCache(); } NS_PROJ_END //! @endcond // --------------------------------------------------------------------------- #ifdef WIN32 static const char nfm_dir_chars[] = "/\\"; #else static const char nfm_dir_chars[] = "/"; #endif static bool nfm_is_tilde_slash(const char *name) { return *name == '~' && strchr(nfm_dir_chars, name[1]); } static bool nfm_is_rel_or_absolute_filename(const char *name) { return strchr(nfm_dir_chars, *name) || (*name == '.' && strchr(nfm_dir_chars, name[1])) || (!strncmp(name, "..", 2) && strchr(nfm_dir_chars, name[2])) || (name[0] != '\0' && name[1] == ':' && strchr(nfm_dir_chars, name[2])); } static std::string build_url(PJ_CONTEXT *ctx, const char *name) { if (!nfm_is_tilde_slash(name) && !nfm_is_rel_or_absolute_filename(name) && !starts_with(name, "http://") && !starts_with(name, "https://")) { std::string remote_file(proj_context_get_url_endpoint(ctx)); if (!remote_file.empty()) { if (remote_file.back() != '/') { remote_file += '/'; } remote_file += name; } return remote_file; } return name; } // --------------------------------------------------------------------------- /** Define a custom set of callbacks for network access. * * All callbacks should be provided (non NULL pointers). * * @param ctx PROJ context, or NULL * @param open_cbk Callback to open a remote file given its URL * @param close_cbk Callback to close a remote file. * @param get_header_value_cbk Callback to get HTTP headers * @param read_range_cbk Callback to read a range of bytes inside a remote file. * @param user_data Arbitrary pointer provided by the user, and passed to the * above callbacks. May be NULL. * @return TRUE in case of success. * @since 7.0 */ int proj_context_set_network_callbacks( PJ_CONTEXT *ctx, proj_network_open_cbk_type open_cbk, proj_network_close_cbk_type close_cbk, proj_network_get_header_value_cbk_type get_header_value_cbk, proj_network_read_range_type read_range_cbk, void *user_data) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } if (!open_cbk || !close_cbk || !get_header_value_cbk || !read_range_cbk) { return false; } ctx->networking.open = open_cbk; ctx->networking.close = close_cbk; ctx->networking.get_header_value = get_header_value_cbk; ctx->networking.read_range = read_range_cbk; ctx->networking.user_data = user_data; return true; } // --------------------------------------------------------------------------- /** Enable or disable network access. * * This overrides the default endpoint in the PROJ configuration file or with * the PROJ_NETWORK environment variable. * * @param ctx PROJ context, or NULL * @param enable TRUE if network access is allowed. * @return TRUE if network access is possible. That is either libcurl is * available, or an alternate interface has been set. * @since 7.0 */ int proj_context_set_enable_network(PJ_CONTEXT *ctx, int enable) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } // Load ini file, now so as to override its network settings pj_load_ini(ctx); ctx->networking.enabled = enable != FALSE; #ifdef CURL_ENABLED return ctx->networking.enabled; #else return ctx->networking.enabled && ctx->networking.open != NS_PROJ::no_op_network_open; #endif } // --------------------------------------------------------------------------- /** Return if network access is enabled. * * @param ctx PROJ context, or NULL * @return TRUE if network access has been enabled * @since 7.0 */ int proj_context_is_network_enabled(PJ_CONTEXT *ctx) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } pj_load_ini(ctx); return ctx->networking.enabled; } // --------------------------------------------------------------------------- /** Define the URL endpoint to query for remote grids. * * This overrides the default endpoint in the PROJ configuration file or with * the PROJ_NETWORK_ENDPOINT environment variable. * * @param ctx PROJ context, or NULL * @param url Endpoint URL. Must NOT be NULL. * @since 7.0 */ void proj_context_set_url_endpoint(PJ_CONTEXT *ctx, const char *url) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } // Load ini file, now so as to override its network settings pj_load_ini(ctx); ctx->endpoint = url; } // --------------------------------------------------------------------------- /** Enable or disable the local cache of grid chunks * * This overrides the setting in the PROJ configuration file. * * @param ctx PROJ context, or NULL * @param enabled TRUE if the cache is enabled. * @since 7.0 */ void proj_grid_cache_set_enable(PJ_CONTEXT *ctx, int enabled) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } // Load ini file, now so as to override its settings pj_load_ini(ctx); ctx->gridChunkCache.enabled = enabled != FALSE; } // --------------------------------------------------------------------------- /** Override, for the considered context, the path and file of the local * cache of grid chunks. * * @param ctx PROJ context, or NULL * @param fullname Full name to the cache (encoded in UTF-8). If set to NULL, * caching will be disabled. * @since 7.0 */ void proj_grid_cache_set_filename(PJ_CONTEXT *ctx, const char *fullname) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } // Load ini file, now so as to override its settings pj_load_ini(ctx); ctx->gridChunkCache.filename = fullname ? fullname : std::string(); } // --------------------------------------------------------------------------- /** Override, for the considered context, the maximum size of the local * cache of grid chunks. * * @param ctx PROJ context, or NULL * @param max_size_MB Maximum size, in mega-bytes (1024*1024 bytes), or * negative value to set unlimited size. * @since 7.0 */ void proj_grid_cache_set_max_size(PJ_CONTEXT *ctx, int max_size_MB) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } // Load ini file, now so as to override its settings pj_load_ini(ctx); ctx->gridChunkCache.max_size = max_size_MB < 0 ? -1 : static_cast<long long>(max_size_MB) * 1024 * 1024; if (max_size_MB == 0) { // For debug purposes only const char *env_var = getenv("PROJ_GRID_CACHE_MAX_SIZE_BYTES"); if (env_var && env_var[0] != '\0') { ctx->gridChunkCache.max_size = atoi(env_var); } } } // --------------------------------------------------------------------------- /** Override, for the considered context, the time-to-live delay for * re-checking if the cached properties of files are still up-to-date. * * @param ctx PROJ context, or NULL * @param ttl_seconds Delay in seconds. Use negative value for no expiration. * @since 7.0 */ void proj_grid_cache_set_ttl(PJ_CONTEXT *ctx, int ttl_seconds) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } // Load ini file, now so as to override its settings pj_load_ini(ctx); ctx->gridChunkCache.ttl = ttl_seconds; } // --------------------------------------------------------------------------- /** Clear the local cache of grid chunks. * * @param ctx PROJ context, or NULL * @since 7.0 */ void proj_grid_cache_clear(PJ_CONTEXT *ctx) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } NS_PROJ::gNetworkChunkCache.clearDiskChunkCache(ctx); } // --------------------------------------------------------------------------- /** Return if a file must be downloaded or is already available in the * PROJ user-writable directory. * * The file will be determinted to have to be downloaded if it does not exist * yet in the user-writable directory, or if it is determined that a more recent * version exists. To determine if a more recent version exists, PROJ will * use the "downloaded_file_properties" table of its grid cache database. * Consequently files manually placed in the user-writable * directory without using this function would be considered as * non-existing/obsolete and would be unconditionally downloaded again. * * This function can only be used if networking is enabled, and either * the default curl network API or a custom one have been installed. * * @param ctx PROJ context, or NULL * @param url_or_filename URL or filename (without directory component) * @param ignore_ttl_setting If set to FALSE, PROJ will only check the * recentness of an already downloaded file, if * the delay between the last time it has been * verified and the current time exceeds the TTL * setting. This can save network accesses. * If set to TRUE, PROJ will unconditionally * check from the server the recentness of the file. * @return TRUE if the file must be downloaded with proj_download_file() * @since 7.0 */ int proj_is_download_needed(PJ_CONTEXT *ctx, const char *url_or_filename, int ignore_ttl_setting) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } if (!proj_context_is_network_enabled(ctx)) { pj_log(ctx, PJ_LOG_ERROR, "Networking capabilities are not enabled"); return false; } const auto url(build_url(ctx, url_or_filename)); const char *filename = strrchr(url.c_str(), '/'); if (filename == nullptr) return false; const auto localFilename( std::string(proj_context_get_user_writable_directory(ctx, false)) + filename); auto f = NS_PROJ::FileManager::open(ctx, localFilename.c_str(), NS_PROJ::FileAccess::READ_ONLY); if (!f) { return true; } f.reset(); auto diskCache = NS_PROJ::DiskChunkCache::open(ctx); if (!diskCache) return false; auto stmt = diskCache->prepare("SELECT lastChecked, fileSize, lastModified, etag " "FROM downloaded_file_properties WHERE url = ?"); if (!stmt) return true; stmt->bindText(url.c_str()); if (stmt->execute() != SQLITE_ROW) { return true; } NS_PROJ::FileProperties cachedProps; cachedProps.lastChecked = static_cast<time_t>(stmt->getInt64()); cachedProps.size = stmt->getInt64(); const char *lastModified = stmt->getText(); cachedProps.lastModified = lastModified ? lastModified : std::string(); const char *etag = stmt->getText(); cachedProps.etag = etag ? etag : std::string(); if (!ignore_ttl_setting) { const auto ttl = NS_PROJ::pj_context_get_grid_cache_ttl(ctx); if (ttl > 0) { time_t curTime; time(&curTime); if (curTime > cachedProps.lastChecked + ttl) { unsigned char dummy; size_t size_read = 0; std::string errorBuffer; errorBuffer.resize(1024); auto handle = ctx->networking.open( ctx, url.c_str(), 0, 1, &dummy, &size_read, errorBuffer.size(), &errorBuffer[0], ctx->networking.user_data); if (!handle) { errorBuffer.resize(strlen(errorBuffer.data())); pj_log(ctx, PJ_LOG_ERROR, "Cannot open %s: %s", url.c_str(), errorBuffer.c_str()); return false; } NS_PROJ::FileProperties props; if (!NS_PROJ::NetworkFile::get_props_from_headers(ctx, handle, props)) { ctx->networking.close(ctx, handle, ctx->networking.user_data); return false; } ctx->networking.close(ctx, handle, ctx->networking.user_data); if (props.size != cachedProps.size || props.lastModified != cachedProps.lastModified || props.etag != cachedProps.etag) { return true; } stmt = diskCache->prepare( "UPDATE downloaded_file_properties SET lastChecked = ? " "WHERE url = ?"); if (!stmt) return false; stmt->bindInt64(curTime); stmt->bindText(url.c_str()); if (stmt->execute() != SQLITE_DONE) { auto hDB = diskCache->handle(); pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return false; } } } } return false; } // --------------------------------------------------------------------------- /** Download a file in the PROJ user-writable directory. * * The file will only be downloaded if it does not exist yet in the * user-writable directory, or if it is determined that a more recent * version exists. To determine if a more recent version exists, PROJ will * use the "downloaded_file_properties" table of its grid cache database. * Consequently files manually placed in the user-writable * directory without using this function would be considered as * non-existing/obsolete and would be unconditionally downloaded again. * * This function can only be used if networking is enabled, and either * the default curl network API or a custom one have been installed. * * @param ctx PROJ context, or NULL * @param url_or_filename URL or filename (without directory component) * @param ignore_ttl_setting If set to FALSE, PROJ will only check the * recentness of an already downloaded file, if * the delay between the last time it has been * verified and the current time exceeds the TTL * setting. This can save network accesses. * If set to TRUE, PROJ will unconditionally * check from the server the recentness of the file. * @param progress_cbk Progress callback, or NULL. * The passed percentage is in the [0, 1] range. * The progress callback must return TRUE * if download must be continued. * @param user_data User data to provide to the progress callback, or NULL * @return TRUE if the download was successful (or not needed) * @since 7.0 */ int proj_download_file(PJ_CONTEXT *ctx, const char *url_or_filename, int ignore_ttl_setting, int (*progress_cbk)(PJ_CONTEXT *, double pct, void *user_data), void *user_data) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } if (!proj_context_is_network_enabled(ctx)) { pj_log(ctx, PJ_LOG_ERROR, "Networking capabilities are not enabled"); return false; } if (!proj_is_download_needed(ctx, url_or_filename, ignore_ttl_setting)) { return true; } const auto url(build_url(ctx, url_or_filename)); const char *filename = strrchr(url.c_str(), '/'); if (filename == nullptr) return false; const auto localFilename( std::string(proj_context_get_user_writable_directory(ctx, true)) + filename); #ifdef _WIN32 const int nPID = GetCurrentProcessId(); #else const int nPID = getpid(); #endif char szUniqueSuffix[128]; snprintf(szUniqueSuffix, sizeof(szUniqueSuffix), "%d_%p", nPID, static_cast<const void *>(&url)); const auto localFilenameTmp(localFilename + szUniqueSuffix); auto f = NS_PROJ::FileManager::open(ctx, localFilenameTmp.c_str(), NS_PROJ::FileAccess::CREATE); if (!f) { pj_log(ctx, PJ_LOG_ERROR, "Cannot create %s", localFilenameTmp.c_str()); return false; } constexpr size_t FULL_FILE_CHUNK_SIZE = 1024 * 1024; std::vector<unsigned char> buffer(FULL_FILE_CHUNK_SIZE); // For testing purposes only const char *env_var_PROJ_FULL_FILE_CHUNK_SIZE = getenv("PROJ_FULL_FILE_CHUNK_SIZE"); if (env_var_PROJ_FULL_FILE_CHUNK_SIZE && env_var_PROJ_FULL_FILE_CHUNK_SIZE[0] != '\0') { buffer.resize(atoi(env_var_PROJ_FULL_FILE_CHUNK_SIZE)); } size_t size_read = 0; std::string errorBuffer; errorBuffer.resize(1024); auto handle = ctx->networking.open( ctx, url.c_str(), 0, buffer.size(), &buffer[0], &size_read, errorBuffer.size(), &errorBuffer[0], ctx->networking.user_data); if (!handle) { errorBuffer.resize(strlen(errorBuffer.data())); pj_log(ctx, PJ_LOG_ERROR, "Cannot open %s: %s", url.c_str(), errorBuffer.c_str()); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilenameTmp.c_str()); return false; } time_t curTime; time(&curTime); NS_PROJ::FileProperties props; if (!NS_PROJ::NetworkFile::get_props_from_headers(ctx, handle, props)) { ctx->networking.close(ctx, handle, ctx->networking.user_data); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilenameTmp.c_str()); return false; } if (size_read == 0) { pj_log(ctx, PJ_LOG_ERROR, "Did not get as many bytes as expected"); ctx->networking.close(ctx, handle, ctx->networking.user_data); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilenameTmp.c_str()); return false; } if (f->write(buffer.data(), size_read) != size_read) { pj_log(ctx, PJ_LOG_ERROR, "Write error"); ctx->networking.close(ctx, handle, ctx->networking.user_data); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilenameTmp.c_str()); return false; } unsigned long long totalDownloaded = size_read; while (totalDownloaded < props.size) { if (totalDownloaded + buffer.size() > props.size) { buffer.resize(static_cast<size_t>(props.size - totalDownloaded)); } errorBuffer.resize(1024); size_read = ctx->networking.read_range( ctx, handle, totalDownloaded, buffer.size(), &buffer[0], errorBuffer.size(), &errorBuffer[0], ctx->networking.user_data); if (size_read < buffer.size()) { pj_log(ctx, PJ_LOG_ERROR, "Did not get as many bytes as expected"); ctx->networking.close(ctx, handle, ctx->networking.user_data); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilenameTmp.c_str()); return false; } if (f->write(buffer.data(), size_read) != size_read) { pj_log(ctx, PJ_LOG_ERROR, "Write error"); ctx->networking.close(ctx, handle, ctx->networking.user_data); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilenameTmp.c_str()); return false; } totalDownloaded += size_read; if (progress_cbk && !progress_cbk(ctx, double(totalDownloaded) / props.size, user_data)) { ctx->networking.close(ctx, handle, ctx->networking.user_data); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilenameTmp.c_str()); return false; } } ctx->networking.close(ctx, handle, ctx->networking.user_data); f.reset(); NS_PROJ::FileManager::unlink(ctx, localFilename.c_str()); if (!NS_PROJ::FileManager::rename(ctx, localFilenameTmp.c_str(), localFilename.c_str())) { pj_log(ctx, PJ_LOG_ERROR, "Cannot rename %s to %s", localFilenameTmp.c_str(), localFilename.c_str()); return false; } auto diskCache = NS_PROJ::DiskChunkCache::open(ctx); if (!diskCache) return false; auto stmt = diskCache->prepare("SELECT lastChecked, fileSize, lastModified, etag " "FROM downloaded_file_properties WHERE url = ?"); if (!stmt) return false; stmt->bindText(url.c_str()); props.lastChecked = curTime; auto hDB = diskCache->handle(); if (stmt->execute() == SQLITE_ROW) { stmt = diskCache->prepare( "UPDATE downloaded_file_properties SET lastChecked = ?, " "fileSize = ?, lastModified = ?, etag = ? " "WHERE url = ?"); if (!stmt) return false; stmt->bindInt64(props.lastChecked); stmt->bindInt64(props.size); if (props.lastModified.empty()) stmt->bindNull(); else stmt->bindText(props.lastModified.c_str()); if (props.etag.empty()) stmt->bindNull(); else stmt->bindText(props.etag.c_str()); stmt->bindText(url.c_str()); if (stmt->execute() != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return false; } } else { stmt = diskCache->prepare( "INSERT INTO downloaded_file_properties (url, lastChecked, " "fileSize, lastModified, etag) VALUES " "(?,?,?,?,?)"); if (!stmt) return false; stmt->bindText(url.c_str()); stmt->bindInt64(props.lastChecked); stmt->bindInt64(props.size); if (props.lastModified.empty()) stmt->bindNull(); else stmt->bindText(props.lastModified.c_str()); if (props.etag.empty()) stmt->bindNull(); else stmt->bindText(props.etag.c_str()); if (stmt->execute() != SQLITE_DONE) { pj_log(ctx, PJ_LOG_ERROR, "%s", sqlite3_errmsg(hDB)); return false; } } return true; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- std::string pj_context_get_grid_cache_filename(PJ_CONTEXT *ctx) { pj_load_ini(ctx); if (!ctx->gridChunkCache.filename.empty()) { return ctx->gridChunkCache.filename; } const std::string path(proj_context_get_user_writable_directory(ctx, true)); ctx->gridChunkCache.filename = path + "/cache.db"; return ctx->gridChunkCache.filename; } //! @endcond
cpp
PROJ
data/projects/PROJ/src/proj_experimental.h
/****************************************************************************** * * Project: PROJ * Purpose: Experimental 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 PROJ_EXPERIMENTAL_H #define PROJ_EXPERIMENTAL_H #ifdef __cplusplus extern "C" { #endif #include "proj.h" /** * \file proj_experimental.h * * Experimental C API (none currently) * * \warning * This API has been considered now to be experimental, and may change or * be removed in the future. */ #ifdef __cplusplus } #endif #endif /* ndef PROJ_EXPERIMENTAL_H */
h
PROJ
data/projects/PROJ/src/list.cpp
/* Projection System: default list of projections */ #define DO_NOT_DEFINE_PROJ_HEAD #include "proj.h" #include "proj_internal.h" /* Generate prototypes for projection functions */ #define PROJ_HEAD(id, name) \ extern "C" struct PJconsts *pj_##id(struct PJconsts *); #include "pj_list.h" #undef PROJ_HEAD /* Generate extern declarations for description strings */ #define PROJ_HEAD(id, name) extern "C" const char *const pj_s_##id; #include "pj_list.h" #undef PROJ_HEAD /* Generate the null-terminated list of projection functions with associated * mnemonics and descriptions */ #define PROJ_HEAD(id, name) {#id, pj_##id, &pj_s_##id}, const struct PJ_LIST pj_list[] = { #include "pj_list.h" {nullptr, nullptr, nullptr}, }; #undef PROJ_HEAD const PJ_OPERATIONS *proj_list_operations(void) { return pj_list; }
cpp
PROJ
data/projects/PROJ/src/4D_api.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implement a (currently minimalistic) proj API based primarily * on the PJ_COORD 4D geodetic spatiotemporal data type. * * Author: Thomas Knudsen, [email protected], 2016-06-09/2016-11-06 * ****************************************************************************** * Copyright (c) 2016, 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 <assert.h> #include <errno.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef _MSC_VER #include <strings.h> #endif #include <algorithm> #include <limits> #include "filemanager.hpp" #include "geodesic.h" #include "grids.hpp" #include "proj.h" #include "proj_experimental.h" #include "proj_internal.h" #include <cmath> /* for isnan */ #include <math.h> #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" using namespace NS_PROJ::internal; /* Initialize PJ_COORD struct */ PJ_COORD proj_coord(double x, double y, double z, double t) { PJ_COORD res; res.v[0] = x; res.v[1] = y; res.v[2] = z; res.v[3] = t; return res; } static PJ_DIRECTION opposite_direction(PJ_DIRECTION dir) { return static_cast<PJ_DIRECTION>(-dir); } /*****************************************************************************/ int proj_angular_input(PJ *P, enum PJ_DIRECTION dir) { /****************************************************************************** Returns 1 if the operator P expects angular input coordinates when operating in direction dir, 0 otherwise. dir: {PJ_FWD, PJ_INV} ******************************************************************************/ if (PJ_FWD == dir) return pj_left(P) == PJ_IO_UNITS_RADIANS; return pj_right(P) == PJ_IO_UNITS_RADIANS; } /*****************************************************************************/ int proj_angular_output(PJ *P, enum PJ_DIRECTION dir) { /****************************************************************************** Returns 1 if the operator P provides angular output coordinates when operating in direction dir, 0 otherwise. dir: {PJ_FWD, PJ_INV} ******************************************************************************/ return proj_angular_input(P, opposite_direction(dir)); } /*****************************************************************************/ int proj_degree_input(PJ *P, enum PJ_DIRECTION dir) { /****************************************************************************** Returns 1 if the operator P expects degree input coordinates when operating in direction dir, 0 otherwise. dir: {PJ_FWD, PJ_INV} ******************************************************************************/ if (PJ_FWD == dir) return pj_left(P) == PJ_IO_UNITS_DEGREES; return pj_right(P) == PJ_IO_UNITS_DEGREES; } /*****************************************************************************/ int proj_degree_output(PJ *P, enum PJ_DIRECTION dir) { /****************************************************************************** Returns 1 if the operator P provides degree output coordinates when operating in direction dir, 0 otherwise. dir: {PJ_FWD, PJ_INV} ******************************************************************************/ return proj_degree_input(P, opposite_direction(dir)); } /* Geodesic distance (in meter) + fwd and rev azimuth between two points on the * ellipsoid */ PJ_COORD proj_geod(const PJ *P, PJ_COORD a, PJ_COORD b) { PJ_COORD c; if (!P->geod) { return proj_coord_error(); } /* Note: the geodesic code takes arguments in degrees */ geod_inverse(P->geod, PJ_TODEG(a.lpz.phi), PJ_TODEG(a.lpz.lam), PJ_TODEG(b.lpz.phi), PJ_TODEG(b.lpz.lam), c.v, c.v + 1, c.v + 2); // cppcheck-suppress uninitvar return c; } /* Geodesic distance (in meter) between two points with angular 2D coordinates */ double proj_lp_dist(const PJ *P, PJ_COORD a, PJ_COORD b) { double s12, azi1, azi2; /* Note: the geodesic code takes arguments in degrees */ if (!P->geod) { return HUGE_VAL; } geod_inverse(P->geod, PJ_TODEG(a.lpz.phi), PJ_TODEG(a.lpz.lam), PJ_TODEG(b.lpz.phi), PJ_TODEG(b.lpz.lam), &s12, &azi1, &azi2); return s12; } /* The geodesic distance AND the vertical offset */ double proj_lpz_dist(const PJ *P, PJ_COORD a, PJ_COORD b) { if (HUGE_VAL == a.lpz.lam || HUGE_VAL == b.lpz.lam) return HUGE_VAL; return hypot(proj_lp_dist(P, a, b), a.lpz.z - b.lpz.z); } /* Euclidean distance between two points with linear 2D coordinates */ double proj_xy_dist(PJ_COORD a, PJ_COORD b) { return hypot(a.xy.x - b.xy.x, a.xy.y - b.xy.y); } /* Euclidean distance between two points with linear 3D coordinates */ double proj_xyz_dist(PJ_COORD a, PJ_COORD b) { return hypot(proj_xy_dist(a, b), a.xyz.z - b.xyz.z); } static bool inline coord_is_all_nans(PJ_COORD coo) { return std::isnan(coo.v[0]) && std::isnan(coo.v[1]) && std::isnan(coo.v[2]) && std::isnan(coo.v[3]); } static bool inline coord_has_nans(PJ_COORD coo) { return std::isnan(coo.v[0]) || std::isnan(coo.v[1]) || std::isnan(coo.v[2]) || std::isnan(coo.v[3]); } /* Measure numerical deviation after n roundtrips fwd-inv (or inv-fwd) */ double proj_roundtrip(PJ *P, PJ_DIRECTION direction, int n, PJ_COORD *coord) { int i; PJ_COORD t, org; if (nullptr == P) return HUGE_VAL; if (n < 1) { proj_log_error(P, _("n should be >= 1")); proj_errno_set(P, PROJ_ERR_OTHER_API_MISUSE); return HUGE_VAL; } /* in the first half-step, we generate the output value */ org = *coord; *coord = proj_trans(P, direction, org); t = *coord; /* now we take n-1 full steps in inverse direction: We are */ /* out of phase due to the half step already taken */ for (i = 0; i < n - 1; i++) t = proj_trans(P, direction, proj_trans(P, opposite_direction(direction), t)); /* finally, we take the last half-step */ t = proj_trans(P, opposite_direction(direction), t); /* if we start with any NaN, we expect all NaN as output */ if (coord_has_nans(org) && coord_is_all_nans(t)) { return 0.0; } /* checking for angular *input* since we do a roundtrip, and end where we * begin */ if (proj_angular_input(P, direction)) return proj_lpz_dist(P, org, t); return proj_xyz_dist(org, t); } /**************************************************************************************/ int pj_get_suggested_operation(PJ_CONTEXT *, const std::vector<PJCoordOperation> &opList, const int iExcluded[2], bool skipNonInstantiable, PJ_DIRECTION direction, PJ_COORD coord) /**************************************************************************************/ { const auto normalizeLongitude = [](double x) { if (x > 180.0) { x -= 360.0; if (x > 180.0) x = fmod(x + 180.0, 360.0) - 180.0; } else if (x < -180.0) { x += 360.0; if (x < -180.0) x = fmod(x + 180.0, 360.0) - 180.0; } return x; }; // Select the operations that match the area of use // and has the best accuracy. int iBest = -1; double bestAccuracy = std::numeric_limits<double>::max(); const int nOperations = static_cast<int>(opList.size()); for (int i = 0; i < nOperations; i++) { if (i == iExcluded[0] || i == iExcluded[1]) { continue; } const auto &alt = opList[i]; bool spatialCriterionOK = false; if (direction == PJ_FWD) { if (alt.pjSrcGeocentricToLonLat) { if (alt.minxSrc == -180 && alt.minySrc == -90 && alt.maxxSrc == 180 && alt.maxySrc == 90) { spatialCriterionOK = true; } else { PJ_COORD tmp = coord; pj_fwd4d(tmp, alt.pjSrcGeocentricToLonLat); if (tmp.xyzt.x >= alt.minxSrc && tmp.xyzt.y >= alt.minySrc && tmp.xyzt.x <= alt.maxxSrc && tmp.xyzt.y <= alt.maxySrc) { spatialCriterionOK = true; } } } else if (coord.xyzt.x >= alt.minxSrc && coord.xyzt.y >= alt.minySrc && coord.xyzt.x <= alt.maxxSrc && coord.xyzt.y <= alt.maxySrc) { spatialCriterionOK = true; } else if (alt.srcIsLonLatDegree && coord.xyzt.y >= alt.minySrc && coord.xyzt.y <= alt.maxySrc) { const double normalizedLon = normalizeLongitude(coord.xyzt.x); if (normalizedLon >= alt.minxSrc && normalizedLon <= alt.maxxSrc) { spatialCriterionOK = true; } } else if (alt.srcIsLatLonDegree && coord.xyzt.x >= alt.minxSrc && coord.xyzt.x <= alt.maxxSrc) { const double normalizedLon = normalizeLongitude(coord.xyzt.y); if (normalizedLon >= alt.minySrc && normalizedLon <= alt.maxySrc) { spatialCriterionOK = true; } } } else { if (alt.pjDstGeocentricToLonLat) { if (alt.minxDst == -180 && alt.minyDst == -90 && alt.maxxDst == 180 && alt.maxyDst == 90) { spatialCriterionOK = true; } else { PJ_COORD tmp = coord; pj_fwd4d(tmp, alt.pjDstGeocentricToLonLat); if (tmp.xyzt.x >= alt.minxDst && tmp.xyzt.y >= alt.minyDst && tmp.xyzt.x <= alt.maxxDst && tmp.xyzt.y <= alt.maxyDst) { spatialCriterionOK = true; } } } else if (coord.xyzt.x >= alt.minxDst && coord.xyzt.y >= alt.minyDst && coord.xyzt.x <= alt.maxxDst && coord.xyzt.y <= alt.maxyDst) { spatialCriterionOK = true; } else if (alt.dstIsLonLatDegree && coord.xyzt.y >= alt.minyDst && coord.xyzt.y <= alt.maxyDst) { const double normalizedLon = normalizeLongitude(coord.xyzt.x); if (normalizedLon >= alt.minxDst && normalizedLon <= alt.maxxDst) { spatialCriterionOK = true; } } else if (alt.dstIsLatLonDegree && coord.xyzt.x >= alt.minxDst && coord.xyzt.x <= alt.maxxDst) { const double normalizedLon = normalizeLongitude(coord.xyzt.y); if (normalizedLon >= alt.minyDst && normalizedLon <= alt.maxyDst) { spatialCriterionOK = true; } } } if (spatialCriterionOK) { // The offshore test is for the "Test bug 245 (use +datum=carthage)" // of testvarious. The long=10 lat=34 point belongs both to the // onshore and offshore Tunisia area of uses, but is slightly // onshore. So in a general way, prefer a onshore area to a // offshore one. if (iBest < 0 || (((alt.accuracy >= 0 && alt.accuracy < bestAccuracy) || // If two operations have the same accuracy, use // the one that has the smallest area (alt.accuracy == bestAccuracy && alt.pseudoArea < opList[iBest].pseudoArea && !(alt.isUnknownAreaName && !opList[iBest].isUnknownAreaName) && !opList[iBest].isPriorityOp)) && !alt.isOffshore)) { if (skipNonInstantiable && !alt.isInstantiable()) { continue; } iBest = i; bestAccuracy = alt.accuracy; } } } return iBest; } //! @cond Doxygen_Suppress /**************************************************************************************/ PJCoordOperation::~PJCoordOperation() { /**************************************************************************************/ proj_destroy(pj); proj_destroy(pjSrcGeocentricToLonLat); proj_destroy(pjDstGeocentricToLonLat); } /**************************************************************************************/ bool PJCoordOperation::isInstantiable() const { /**************************************************************************************/ if (isInstantiableCached == INSTANTIABLE_STATUS_UNKNOWN) isInstantiableCached = proj_coordoperation_is_instantiable(pj->ctx, pj); return (isInstantiableCached == 1); } //! @endcond /**************************************************************************************/ static void warnAboutMissingGrid(PJ *P) /**************************************************************************************/ { std::string msg("Attempt to use coordinate operation "); msg += proj_get_name(P); msg += " failed."; int gridUsed = proj_coordoperation_get_grid_used_count(P->ctx, P); for (int i = 0; i < gridUsed; ++i) { const char *gridName = ""; int available = FALSE; if (proj_coordoperation_get_grid_used(P->ctx, P, i, &gridName, nullptr, nullptr, nullptr, nullptr, nullptr, &available) && !available) { msg += " Grid "; msg += gridName; msg += " is not available. " "Consult https://proj.org/resource_files.html for guidance."; } } if (!P->errorIfBestTransformationNotAvailable && P->warnIfBestTransformationNotAvailable) { msg += " This might become an error in a future PROJ major release. " "Set the ONLY_BEST option to YES or NO. " "This warning will no longer be emitted (for the current " "transformation instance)."; P->warnIfBestTransformationNotAvailable = false; } pj_log(P->ctx, P->errorIfBestTransformationNotAvailable ? PJ_LOG_ERROR : PJ_LOG_DEBUG, msg.c_str()); } /**************************************************************************************/ PJ_COORD proj_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coord) { /*************************************************************************************** Apply the transformation P to the coordinate coord, preferring the 4D interfaces if available. See also pj_approx_2D_trans and pj_approx_3D_trans in pj_internal.c, which work similarly, but prefers the 2D resp. 3D interfaces if available. ***************************************************************************************/ if (nullptr == P || direction == PJ_IDENT) return coord; if (P->inverted) direction = opposite_direction(direction); if (P->iso_obj != nullptr && !P->iso_obj_is_coordinate_operation) { pj_log(P->ctx, PJ_LOG_ERROR, "Object is not a coordinate operation"); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return proj_coord_error(); } if (!P->alternativeCoordinateOperations.empty()) { constexpr int N_MAX_RETRY = 2; int iExcluded[N_MAX_RETRY] = {-1, -1}; bool skipNonInstantiable = P->skipNonInstantiable && !P->warnIfBestTransformationNotAvailable && !P->errorIfBestTransformationNotAvailable; const int nOperations = static_cast<int>(P->alternativeCoordinateOperations.size()); // We may need several attempts. For example the point at // long=-111.5 lat=45.26 falls into the bounding box of the Canadian // ntv2_0.gsb grid, except that it is not in any of the subgrids, being // in the US. We thus need another retry that will select the conus // grid. for (int iRetry = 0; iRetry <= N_MAX_RETRY; iRetry++) { // Do a first pass and select the operations that match the area of // use and has the best accuracy. int iBest = pj_get_suggested_operation( P->ctx, P->alternativeCoordinateOperations, iExcluded, skipNonInstantiable, direction, coord); if (iBest < 0) { break; } if (iRetry > 0) { const int oldErrno = proj_errno_reset(P); if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_DEBUG) { pj_log(P->ctx, PJ_LOG_DEBUG, proj_context_errno_string(P->ctx, oldErrno)); } pj_log(P->ctx, PJ_LOG_DEBUG, "Did not result in valid result. " "Attempting a retry with another operation."); } const auto &alt = P->alternativeCoordinateOperations[iBest]; if (P->iCurCoordOp != iBest) { if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_DEBUG) { std::string msg("Using coordinate operation "); msg += alt.name; pj_log(P->ctx, PJ_LOG_DEBUG, msg.c_str()); } P->iCurCoordOp = iBest; } PJ_COORD res = coord; if (alt.pj->hasCoordinateEpoch) coord.xyzt.t = alt.pj->coordinateEpoch; if (direction == PJ_FWD) pj_fwd4d(res, alt.pj); else pj_inv4d(res, alt.pj); if (proj_errno(alt.pj) == PROJ_ERR_OTHER_NETWORK_ERROR) { return proj_coord_error(); } if (res.xyzt.x != HUGE_VAL) { return res; } else if (P->errorIfBestTransformationNotAvailable || P->warnIfBestTransformationNotAvailable) { warnAboutMissingGrid(alt.pj); if (P->errorIfBestTransformationNotAvailable) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_NO_OPERATION); return res; } P->warnIfBestTransformationNotAvailable = false; skipNonInstantiable = true; } if (iRetry == N_MAX_RETRY) { break; } iExcluded[iRetry] = iBest; } // In case we did not find an operation whose area of use is compatible // with the input coordinate, then goes through again the list, and // use the first operation that does not require grids. NS_PROJ::io::DatabaseContextPtr dbContext; try { if (P->ctx->cpp_context) { dbContext = P->ctx->cpp_context->getDatabaseContext().as_nullable(); } } catch (const std::exception &) { } for (int i = 0; i < nOperations; i++) { const auto &alt = P->alternativeCoordinateOperations[i]; auto coordOperation = dynamic_cast<NS_PROJ::operation::CoordinateOperation *>( alt.pj->iso_obj.get()); if (coordOperation) { if (coordOperation->gridsNeeded(dbContext, true).empty()) { if (P->iCurCoordOp != i) { if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_DEBUG) { std::string msg("Using coordinate operation "); msg += alt.name; msg += " as a fallback due to lack of more " "appropriate operations"; pj_log(P->ctx, PJ_LOG_DEBUG, msg.c_str()); } P->iCurCoordOp = i; } if (direction == PJ_FWD) { pj_fwd4d(coord, alt.pj); } else { pj_inv4d(coord, alt.pj); } return coord; } } } proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_NO_OPERATION); return proj_coord_error(); } P->iCurCoordOp = 0; // dummy value, to be used by proj_trans_get_last_used_operation() if (P->hasCoordinateEpoch) coord.xyzt.t = P->coordinateEpoch; if (coord_has_nans(coord)) coord.v[0] = coord.v[1] = coord.v[2] = coord.v[3] = std::numeric_limits<double>::quiet_NaN(); else if (direction == PJ_FWD) pj_fwd4d(coord, P); else pj_inv4d(coord, P); return coord; } /*****************************************************************************/ PJ *proj_trans_get_last_used_operation(PJ *P) /****************************************************************************** Return the operation used during the last invocation of proj_trans(). This is especially useful when P has been created with proj_create_crs_to_crs() and has several alternative operations. The returned object must be freed with proj_destroy(). ******************************************************************************/ { if (nullptr == P || P->iCurCoordOp < 0) return nullptr; if (P->alternativeCoordinateOperations.empty()) return proj_clone(P->ctx, P); return proj_clone(P->ctx, P->alternativeCoordinateOperations[P->iCurCoordOp].pj); } /*****************************************************************************/ int proj_trans_array(PJ *P, PJ_DIRECTION direction, size_t n, PJ_COORD *coord) { /****************************************************************************** Batch transform an array of PJ_COORD. Performs transformation on all points, even if errors occur on some points. Individual points that fail to transform will have their components set to HUGE_VAL Returns 0 if all coordinates are transformed without error, otherwise returns a precise error number if all coordinates that fail to transform for the same reason, or a generic error code if they fail for different reasons. ******************************************************************************/ size_t i; int retErrno = 0; bool hasSetRetErrno = false; bool sameRetErrno = true; for (i = 0; i < n; i++) { proj_context_errno_set(P->ctx, 0); coord[i] = proj_trans(P, direction, coord[i]); int thisErrno = proj_errno(P); if (thisErrno != 0) { if (!hasSetRetErrno) { retErrno = thisErrno; hasSetRetErrno = true; } else if (sameRetErrno && retErrno != thisErrno) { sameRetErrno = false; retErrno = PROJ_ERR_COORD_TRANSFM; } } } proj_context_errno_set(P->ctx, retErrno); return retErrno; } /*************************************************************************************/ size_t proj_trans_generic(PJ *P, PJ_DIRECTION direction, double *x, size_t sx, size_t nx, double *y, size_t sy, size_t ny, double *z, size_t sz, size_t nz, double *t, size_t st, size_t nt) { /************************************************************************************** Transform a series of coordinates, where the individual coordinate dimension may be represented by an array that is either 1. fully populated 2. a null pointer and/or a length of zero, which will be treated as a fully populated array of zeroes 3. of length one, i.e. a constant, which will be treated as a fully populated array of that constant value The strides, sx, sy, sz, st, represent the step length, in bytes, between consecutive elements of the corresponding array. This makes it possible for proj_transform to handle transformation of a large class of application specific data structures, without necessarily understanding the data structure format, as in: typedef struct {double x, y; int quality_level; char surveyor_name[134];} XYQS; XYQS survey[345]; double height = 23.45; PJ *P = {...}; size_t stride = sizeof (XYQS); ... proj_transform ( P, PJ_INV, sizeof(XYQS), &(survey[0].x), stride, 345, (* We have 345 eastings *) &(survey[0].y), stride, 345, (* ...and 345 northings. *) &height, 1, (* The height is the constant 23.45 m *) 0, 0 (* and the time is the constant 0.00 s *) ); This is similar to the inner workings of the pj_transform function, but the stride functionality has been generalized to work for any size of basic unit, not just a fixed number of doubles. In most cases, the stride will be identical for x, y,z, and t, since they will typically be either individual arrays (stride = sizeof(double)), or strided views into an array of application specific data structures (stride = sizeof (...)). But in order to support cases where x, y, z, and t come from heterogeneous sources, individual strides, sx, sy, sz, st, are used. Caveat: Since proj_transform does its work *in place*, this means that even the supposedly constants (i.e. length 1 arrays) will return from the call in altered state. Hence, remember to reinitialize between repeated calls. Return value: Number of transformations completed. **************************************************************************************/ PJ_COORD coord = {{0, 0, 0, 0}}; size_t i, nmin; double null_broadcast = 0; double invalid_time = HUGE_VAL; if (nullptr == P) return 0; if (P->inverted) direction = opposite_direction(direction); /* ignore lengths of null arrays */ if (nullptr == x) nx = 0; if (nullptr == y) ny = 0; if (nullptr == z) nz = 0; if (nullptr == t) nt = 0; /* and make the nullities point to some real world memory for broadcasting * nulls */ if (0 == nx) x = &null_broadcast; if (0 == ny) y = &null_broadcast; if (0 == nz) z = &null_broadcast; if (0 == nt) t = &invalid_time; /* nothing to do? */ if (0 == nx + ny + nz + nt) return 0; /* arrays of length 1 are constants, which we broadcast along the longer * arrays */ /* so we need to find the length of the shortest non-unity array to figure * out */ /* how many coordinate pairs we must transform */ nmin = (nx > 1) ? nx : (ny > 1) ? ny : (nz > 1) ? nz : (nt > 1) ? nt : 1; if ((nx > 1) && (nx < nmin)) nmin = nx; if ((ny > 1) && (ny < nmin)) nmin = ny; if ((nz > 1) && (nz < nmin)) nmin = nz; if ((nt > 1) && (nt < nmin)) nmin = nt; /* Check validity of direction flag */ switch (direction) { case PJ_FWD: case PJ_INV: break; case PJ_IDENT: return nmin; } /* Arrays of length==0 are broadcast as the constant 0 */ /* Arrays of length==1 are broadcast as their single value */ /* Arrays of length >1 are iterated over (for the first nmin values) */ /* The slightly convolved incremental indexing is used due */ /* to the stride, which may be any size supported by the platform */ for (i = 0; i < nmin; i++) { coord.xyzt.x = *x; coord.xyzt.y = *y; coord.xyzt.z = *z; coord.xyzt.t = *t; coord = proj_trans(P, direction, coord); /* in all full length cases, we overwrite the input with the output, */ /* and step on to the next element. */ /* The casts are somewhat funky, but they compile down to no-ops and */ /* they tell compilers and static analyzers that we know what we do */ if (nx > 1) { *x = coord.xyzt.x; x = (double *)((void *)(((char *)x) + sx)); } if (ny > 1) { *y = coord.xyzt.y; y = (double *)((void *)(((char *)y) + sy)); } if (nz > 1) { *z = coord.xyzt.z; z = (double *)((void *)(((char *)z) + sz)); } if (nt > 1) { *t = coord.xyzt.t; t = (double *)((void *)(((char *)t) + st)); } } /* Last time around, we update the length 1 cases with their transformed * alter egos */ if (nx == 1) *x = coord.xyzt.x; if (ny == 1) *y = coord.xyzt.y; if (nz == 1) *z = coord.xyzt.z; if (nt == 1) *t = coord.xyzt.t; return i; } /*************************************************************************************/ PJ_COORD pj_geocentric_latitude(const PJ *P, PJ_DIRECTION direction, PJ_COORD coord) { /************************************************************************************** Convert geographical latitude to geocentric (or the other way round if direction = PJ_INV) The conversion involves a call to the tangent function, which goes through the roof at the poles, so very close (the last centimeter) to the poles no conversion takes place and the input latitude is copied directly to the output. Fortunately, the geocentric latitude converges to the geographical at the poles, so the difference is negligible. For the spherical case, the geographical latitude equals the geocentric, and consequently, the input is copied directly to the output. **************************************************************************************/ const double limit = M_HALFPI - 1e-9; PJ_COORD res = coord; if ((coord.lp.phi > limit) || (coord.lp.phi < -limit) || (P->es == 0)) return res; if (direction == PJ_FWD) res.lp.phi = atan(P->one_es * tan(coord.lp.phi)); else res.lp.phi = atan(P->rone_es * tan(coord.lp.phi)); return res; } double proj_torad(double angle_in_degrees) { return PJ_TORAD(angle_in_degrees); } double proj_todeg(double angle_in_radians) { return PJ_TODEG(angle_in_radians); } double proj_dmstor(const char *is, char **rs) { return dmstor(is, rs); } char *proj_rtodms(char *s, double r, int pos, int neg) { // 40 is the size used for the buffer in proj.cpp size_t arbitrary_size = 40; return rtodms(s, arbitrary_size, r, pos, neg); } char *proj_rtodms2(char *s, size_t sizeof_s, double r, int pos, int neg) { return rtodms(s, sizeof_s, r, pos, neg); } /*************************************************************************************/ static PJ *skip_prep_fin(PJ *P) { /************************************************************************************** Skip prepare and finalize function for the various "helper operations" added to P when in cs2cs compatibility mode. **************************************************************************************/ P->skip_fwd_prepare = 1; P->skip_fwd_finalize = 1; P->skip_inv_prepare = 1; P->skip_inv_finalize = 1; return P; } /*************************************************************************************/ static int cs2cs_emulation_setup(PJ *P) { /************************************************************************************** If any cs2cs style modifiers are given (axis=..., towgs84=..., ) create the 4D API equivalent operations, so the preparation and finalization steps in the pj_inv/pj_fwd invocators can emulate the behavior of pj_transform and the cs2cs app. Returns 1 on success, 0 on failure **************************************************************************************/ PJ *Q; paralist *p; int do_cart = 0; if (nullptr == P) return 0; /* Don't recurse when calling proj_create (which calls us back) */ if (pj_param_exists(P->params, "break_cs2cs_recursion")) return 1; /* Swap axes? */ p = pj_param_exists(P->params, "axis"); const bool disable_grid_presence_check = pj_param_exists(P->params, "disable_grid_presence_check") != nullptr; /* Don't axisswap if data are already in "enu" order */ if (p && (0 != strcmp("enu", p->param))) { size_t def_size = 100 + strlen(P->axis); char *def = static_cast<char *>(malloc(def_size)); if (nullptr == def) return 0; snprintf(def, def_size, "break_cs2cs_recursion proj=axisswap axis=%s", P->axis); Q = pj_create_internal(P->ctx, def); free(def); if (nullptr == Q) return 0; P->axisswap = skip_prep_fin(Q); } /* Geoid grid(s) given? */ p = pj_param_exists(P->params, "geoidgrids"); if (!disable_grid_presence_check && p && strlen(p->param) > strlen("geoidgrids=")) { char *gridnames = p->param + strlen("geoidgrids="); size_t def_size = 100 + 2 * strlen(gridnames); char *def = static_cast<char *>(malloc(def_size)); if (nullptr == def) return 0; snprintf(def, def_size, "break_cs2cs_recursion proj=vgridshift grids=%s", pj_double_quote_string_param_if_needed(gridnames).c_str()); Q = pj_create_internal(P->ctx, def); free(def); if (nullptr == Q) return 0; P->vgridshift = skip_prep_fin(Q); } /* Datum shift grid(s) given? */ p = pj_param_exists(P->params, "nadgrids"); if (!disable_grid_presence_check && p && strlen(p->param) > strlen("nadgrids=")) { char *gridnames = p->param + strlen("nadgrids="); size_t def_size = 100 + 2 * strlen(gridnames); char *def = static_cast<char *>(malloc(def_size)); if (nullptr == def) return 0; snprintf(def, def_size, "break_cs2cs_recursion proj=hgridshift grids=%s", pj_double_quote_string_param_if_needed(gridnames).c_str()); Q = pj_create_internal(P->ctx, def); free(def); if (nullptr == Q) return 0; P->hgridshift = skip_prep_fin(Q); } /* We ignore helmert if we have grid shift */ p = P->hgridshift ? nullptr : pj_param_exists(P->params, "towgs84"); while (p) { const char *const s = p->param; const double *const d = P->datum_params; /* We ignore null helmert shifts (common in auto-translated resource * files, e.g. epsg) */ if (0 == d[0] && 0 == d[1] && 0 == d[2] && 0 == d[3] && 0 == d[4] && 0 == d[5] && 0 == d[6]) { /* If the current ellipsoid is not WGS84, then make sure the */ /* change in ellipsoid is still done. */ if (!(fabs(P->a_orig - 6378137.0) < 1e-8 && fabs(P->es_orig - 0.0066943799901413) < 1e-15)) { do_cart = 1; } break; } const size_t n = strlen(s); if (n <= 8) /* 8==strlen ("towgs84=") */ return 0; const size_t def_max_size = 100 + n; std::string def; def.reserve(def_max_size); def += "break_cs2cs_recursion proj=helmert exact "; def += s; def += " convention=position_vector"; Q = pj_create_internal(P->ctx, def.c_str()); if (nullptr == Q) return 0; pj_inherit_ellipsoid_def(P, Q); P->helmert = skip_prep_fin(Q); break; } /* We also need cartesian/geographical transformations if we are working in */ /* geocentric/cartesian space or we need to do a Helmert transform. */ if (P->is_geocent || P->helmert || do_cart) { char def[150]; snprintf(def, sizeof(def), "break_cs2cs_recursion proj=cart a=%40.20g es=%40.20g", P->a_orig, P->es_orig); { /* In case the current locale does not use dot but comma as decimal */ /* separator, replace it with dot, so that proj_atof() behaves */ /* correctly. */ /* TODO later: use C++ ostringstream with * imbue(std::locale::classic()) */ /* to be locale unaware */ char *next_pos; for (next_pos = def; (next_pos = strchr(next_pos, ',')) != nullptr; next_pos++) { *next_pos = '.'; } } Q = pj_create_internal(P->ctx, def); if (nullptr == Q) return 0; P->cart = skip_prep_fin(Q); if (!P->is_geocent) { snprintf(def, sizeof(def), "break_cs2cs_recursion proj=cart ellps=WGS84"); Q = pj_create_internal(P->ctx, def); if (nullptr == Q) return 0; P->cart_wgs84 = skip_prep_fin(Q); } } return 1; } /*************************************************************************************/ PJ *pj_create_internal(PJ_CONTEXT *ctx, const char *definition) { /*************************************************************************************/ /************************************************************************************** Create a new PJ object in the context ctx, using the given definition. If ctx==0, the default context is used, if definition==0, or invalid, a null-pointer is returned. The definition may use '+' as argument start indicator, as in "+proj=utm +zone=32", or leave it out, as in "proj=utm zone=32". It may even use free formatting "proj = utm; zone =32 ellps= GRS80". Note that the semicolon separator is allowed, but not required. **************************************************************************************/ char *args, **argv; size_t argc, n; if (nullptr == ctx) ctx = pj_get_default_ctx(); /* Make a copy that we can manipulate */ n = strlen(definition); args = (char *)malloc(n + 1); if (nullptr == args) { proj_context_errno_set(ctx, PROJ_ERR_OTHER /*ENOMEM*/); return nullptr; } strcpy(args, definition); argc = pj_trim_argc(args); if (argc == 0) { free(args); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_MISSING_ARG); return nullptr; } argv = pj_trim_argv(argc, args); if (!argv) { free(args); proj_context_errno_set(ctx, PROJ_ERR_OTHER /*ENOMEM*/); return nullptr; } PJ *P = pj_create_argv_internal(ctx, (int)argc, argv); free(argv); free(args); return P; } /*************************************************************************************/ PJ *proj_create_argv(PJ_CONTEXT *ctx, int argc, char **argv) { /************************************************************************************** Create a new PJ object in the context ctx, using the given definition argument array argv. If ctx==0, the default context is used, if definition==0, or invalid, a null-pointer is returned. The definition arguments may use '+' as argument start indicator, as in {"+proj=utm", "+zone=32"}, or leave it out, as in {"proj=utm", "zone=32"}. **************************************************************************************/ if (nullptr == ctx) ctx = pj_get_default_ctx(); if (nullptr == argv) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_MISSING_ARG); return nullptr; } /* We assume that free format is used, and build a full proj_create * compatible string */ char *c = pj_make_args(argc, argv); if (nullptr == c) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP /* ENOMEM */); return nullptr; } PJ *P = proj_create(ctx, c); free((char *)c); return P; } /*************************************************************************************/ PJ *pj_create_argv_internal(PJ_CONTEXT *ctx, int argc, char **argv) { /************************************************************************************** For use by pipeline init function. **************************************************************************************/ if (nullptr == ctx) ctx = pj_get_default_ctx(); if (nullptr == argv) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_MISSING_ARG); return nullptr; } /* ...and let pj_init_ctx do the hard work */ /* New interface: forbid init=epsg:XXXX syntax by default */ const int allow_init_epsg = proj_context_get_use_proj4_init_rules(ctx, FALSE); PJ *P = pj_init_ctx_with_allow_init_epsg(ctx, argc, argv, allow_init_epsg); /* Support cs2cs-style modifiers */ int ret = cs2cs_emulation_setup(P); if (0 == ret) return proj_destroy(P); return P; } /** Create an area of use */ PJ_AREA *proj_area_create(void) { return new PJ_AREA(); } /** Assign a bounding box to an area of use. */ void proj_area_set_bbox(PJ_AREA *area, double west_lon_degree, double south_lat_degree, double east_lon_degree, double north_lat_degree) { area->bbox_set = TRUE; area->west_lon_degree = west_lon_degree; area->south_lat_degree = south_lat_degree; area->east_lon_degree = east_lon_degree; area->north_lat_degree = north_lat_degree; } /** Assign the name of an area of use. */ void proj_area_set_name(PJ_AREA *area, const char *name) { area->name = name; } /** Free an area of use */ void proj_area_destroy(PJ_AREA *area) { delete area; } /************************************************************************/ /* proj_context_use_proj4_init_rules() */ /************************************************************************/ void proj_context_use_proj4_init_rules(PJ_CONTEXT *ctx, int enable) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } ctx->use_proj4_init_rules = enable; } /************************************************************************/ /* EQUAL() */ /************************************************************************/ static int EQUAL(const char *a, const char *b) { #ifdef _MSC_VER return _stricmp(a, b) == 0; #else return strcasecmp(a, b) == 0; #endif } /************************************************************************/ /* proj_context_get_use_proj4_init_rules() */ /************************************************************************/ int proj_context_get_use_proj4_init_rules(PJ_CONTEXT *ctx, int from_legacy_code_path) { const char *val = getenv("PROJ_USE_PROJ4_INIT_RULES"); if (ctx == nullptr) { ctx = pj_get_default_ctx(); } if (val) { if (EQUAL(val, "yes") || EQUAL(val, "on") || EQUAL(val, "true")) { return TRUE; } if (EQUAL(val, "no") || EQUAL(val, "off") || EQUAL(val, "false")) { return FALSE; } pj_log(ctx, PJ_LOG_ERROR, "Invalid value for PROJ_USE_PROJ4_INIT_RULES"); } if (ctx->use_proj4_init_rules >= 0) { return ctx->use_proj4_init_rules; } return from_legacy_code_path; } /** Adds a " +type=crs" suffix to a PROJ string (if it is a PROJ string) */ std::string pj_add_type_crs_if_needed(const std::string &str) { std::string ret(str); if ((starts_with(str, "proj=") || starts_with(str, "+proj=") || starts_with(str, "+init=") || starts_with(str, "+title=")) && str.find("type=crs") == std::string::npos) { ret += " +type=crs"; } return ret; } // --------------------------------------------------------------------------- static double simple_min(const double *data, const int arr_len) { double min_value = data[0]; for (int iii = 1; iii < arr_len; iii++) { if (data[iii] < min_value) min_value = data[iii]; } return min_value; } // --------------------------------------------------------------------------- static double simple_max(const double *data, const int arr_len) { double max_value = data[0]; for (int iii = 1; iii < arr_len; iii++) { if ((data[iii] > max_value || max_value == HUGE_VAL) && data[iii] != HUGE_VAL) max_value = data[iii]; } return max_value; } // --------------------------------------------------------------------------- static int find_previous_index(const int iii, const double *data, const int arr_len) { // find index of nearest valid previous value if exists int prev_iii = iii - 1; if (prev_iii == -1) // handle wraparound prev_iii = arr_len - 1; while (data[prev_iii] == HUGE_VAL && prev_iii != iii) { prev_iii--; if (prev_iii == -1) // handle wraparound prev_iii = arr_len - 1; } return prev_iii; } // --------------------------------------------------------------------------- /****************************************************************************** Handles the case when longitude values cross the antimeridian when calculating the minimum. Note: The data array must be in a linear ring. Note: This requires a densified ring with at least 2 additional points per edge to correctly handle global extents. If only 1 additional point: | | |RL--x0--|RL-- | | -180 180|-180 If they are evenly spaced and it crosses the antimeridian: x0 - L = 180 R - x0 = -180 For example: Let R = -179.9, x0 = 0.1, L = -179.89 x0 - L = 0.1 - -179.9 = 180 R - x0 = -179.89 - 0.1 ~= -180 This is the same in the case when it didn't cross the antimeridian. If you have 2 additional points: | | |RL--x0--x1--|RL-- | | -180 180|-180 If they are evenly spaced and it crosses the antimeridian: x0 - L = 120 x1 - x0 = 120 R - x1 = -240 For example: Let R = -179.9, x0 = -59.9, x1 = 60.1 L = -179.89 x0 - L = 59.9 - -179.9 = 120 x1 - x0 = 60.1 - 59.9 = 120 R - x1 = -179.89 - 60.1 ~= -240 However, if they are evenly spaced and it didn't cross the antimeridian: x0 - L = 120 x1 - x0 = 120 R - x1 = 120 From this, we have a delta that is guaranteed to be significantly large enough to tell the difference reguarless of the direction the antimeridian was crossed. However, even though the spacing was even in the source projection, it isn't guaranteed in the target geographic projection. So, instead of 240, 200 is used as it significantly larger than 120 to be sure that the antimeridian was crossed but smalller than 240 to account for possible irregularities in distances when re-projecting. Also, 200 ensures latitudes are ignored for axis order handling. ******************************************************************************/ static double antimeridian_min(const double *data, const int arr_len) { double positive_min = HUGE_VAL; double min_value = HUGE_VAL; int crossed_meridian_count = 0; bool positive_meridian = false; for (int iii = 0; iii < arr_len; iii++) { if (data[iii] == HUGE_VAL) continue; int prev_iii = find_previous_index(iii, data, arr_len); // check if crossed meridian double delta = data[prev_iii] - data[iii]; // 180 -> -180 if (delta >= 200 && delta != HUGE_VAL) { if (crossed_meridian_count == 0) positive_min = min_value; crossed_meridian_count++; positive_meridian = false; // -180 -> 180 } else if (delta <= -200 && delta != HUGE_VAL) { if (crossed_meridian_count == 0) positive_min = data[iii]; crossed_meridian_count++; positive_meridian = true; } // positive meridian side min if (positive_meridian && data[iii] < positive_min) positive_min = data[iii]; // track general min value if (data[iii] < min_value) min_value = data[iii]; } if (crossed_meridian_count == 2) return positive_min; else if (crossed_meridian_count == 4) // bounds extends beyond -180/180 return -180; return min_value; } // --------------------------------------------------------------------------- // Handles the case when longitude values cross the antimeridian // when calculating the minimum. // Note: The data array must be in a linear ring. // Note: This requires a densified ring with at least 2 additional // points per edge to correctly handle global extents. // See antimeridian_min docstring for reasoning. static double antimeridian_max(const double *data, const int arr_len) { double negative_max = -HUGE_VAL; double max_value = -HUGE_VAL; bool negative_meridian = false; int crossed_meridian_count = 0; for (int iii = 0; iii < arr_len; iii++) { if (data[iii] == HUGE_VAL) continue; int prev_iii = find_previous_index(iii, data, arr_len); // check if crossed meridian double delta = data[prev_iii] - data[iii]; // 180 -> -180 if (delta >= 200 && delta != HUGE_VAL) { if (crossed_meridian_count == 0) negative_max = data[iii]; crossed_meridian_count++; negative_meridian = true; // -180 -> 180 } else if (delta <= -200 && delta != HUGE_VAL) { if (crossed_meridian_count == 0) negative_max = max_value; negative_meridian = false; crossed_meridian_count++; } // negative meridian side max if (negative_meridian && (data[iii] > negative_max || negative_max == HUGE_VAL) && data[iii] != HUGE_VAL) negative_max = data[iii]; // track general max value if ((data[iii] > max_value || max_value == HUGE_VAL) && data[iii] != HUGE_VAL) max_value = data[iii]; } if (crossed_meridian_count == 2) return negative_max; else if (crossed_meridian_count == 4) // bounds extends beyond -180/180 return 180; return max_value; } // --------------------------------------------------------------------------- // Check if the original projected bounds contains // the north pole. // This assumes that the destination CRS is geographic. static bool contains_north_pole(PJ *projobj, PJ_DIRECTION pj_direction, const double xmin, const double ymin, const double xmax, const double ymax, bool lon_lat_order) { double pole_y = 90; double pole_x = 0; if (!lon_lat_order) { pole_y = 0; pole_x = 90; } proj_trans_generic(projobj, opposite_direction(pj_direction), &pole_x, sizeof(double), 1, &pole_y, sizeof(double), 1, nullptr, sizeof(double), 0, nullptr, sizeof(double), 0); if (xmin < pole_x && pole_x < xmax && ymax > pole_y && pole_y > ymin) return true; return false; } // --------------------------------------------------------------------------- // Check if the original projected bounds contains // the south pole. // This assumes that the destination CRS is geographic. static bool contains_south_pole(PJ *projobj, PJ_DIRECTION pj_direction, const double xmin, const double ymin, const double xmax, const double ymax, bool lon_lat_order) { double pole_y = -90; double pole_x = 0; if (!lon_lat_order) { pole_y = 0; pole_x = -90; } proj_trans_generic(projobj, opposite_direction(pj_direction), &pole_x, sizeof(double), 1, &pole_y, sizeof(double), 1, nullptr, sizeof(double), 0, nullptr, sizeof(double), 0); if (xmin < pole_x && pole_x < xmax && ymax > pole_y && pole_y > ymin) return true; return false; } // --------------------------------------------------------------------------- // Check if the target CRS of the transformation // has the longitude latitude axis order. // This assumes that the destination CRS is geographic. static int target_crs_lon_lat_order(PJ_CONTEXT *transformer_ctx, PJ *transformer_pj, PJ_DIRECTION pj_direction) { PJ *target_crs = nullptr; if (pj_direction == PJ_FWD) target_crs = proj_get_target_crs(transformer_ctx, transformer_pj); else if (pj_direction == PJ_INV) target_crs = proj_get_source_crs(transformer_ctx, transformer_pj); if (target_crs == nullptr) { proj_context_log_debug(transformer_ctx, "Unable to retrieve target CRS"); return -1; } PJ *coord_system_pj = proj_crs_get_coordinate_system(transformer_ctx, target_crs); proj_destroy(target_crs); if (coord_system_pj == nullptr) { proj_context_log_debug(transformer_ctx, "Unable to get target CRS coordinate system."); return -1; } const char *abbrev = nullptr; int success = proj_cs_get_axis_info(transformer_ctx, coord_system_pj, 0, nullptr, &abbrev, nullptr, nullptr, nullptr, nullptr, nullptr); proj_destroy(coord_system_pj); if (success != 1) return -1; return strcmp(abbrev, "lon") == 0 || strcmp(abbrev, "Lon") == 0; } // --------------------------------------------------------------------------- /** \brief Transform boundary, * * Transform boundary densifying the edges to account for nonlinear * transformations along these edges and extracting the outermost bounds. * * If the destination CRS is geographic, the first axis is longitude, * and xmax < xmin then the bounds crossed the antimeridian. * In this scenario there are two polygons, one on each side of the * antimeridian. The first polygon should be constructed with (xmin, ymin, 180, * ymax) and the second with (-180, ymin, xmax, ymax). * * If the destination CRS is geographic, the first axis is latitude, * and ymax < ymin then the bounds crossed the antimeridian. * In this scenario there are two polygons, one on each side of the * antimeridian. The first polygon should be constructed with (ymin, xmin, ymax, * 180) and the second with (ymin, -180, ymax, xmax). * * @param context The PJ_CONTEXT object. * @param P The PJ object representing the transformation. * @param direction The direction of the transformation. * @param xmin Minimum bounding coordinate of the first axis in source CRS * (target CRS if direction is inverse). * @param ymin Minimum bounding coordinate of the second axis in source CRS. * (target CRS if direction is inverse). * @param xmax Maximum bounding coordinate of the first axis in source CRS. * (target CRS if direction is inverse). * @param ymax Maximum bounding coordinate of the second axis in source CRS. * (target CRS if direction is inverse). * @param out_xmin Minimum bounding coordinate of the first axis in target CRS * (source CRS if direction is inverse). * @param out_ymin Minimum bounding coordinate of the second axis in target CRS. * (source CRS if direction is inverse). * @param out_xmax Maximum bounding coordinate of the first axis in target CRS. * (source CRS if direction is inverse). * @param out_ymax Maximum bounding coordinate of the second axis in target CRS. * (source CRS if direction is inverse). * @param densify_pts Recommended to use 21. This is the number of points * to use to densify the bounding polygon in the transformation. * @return an integer. 1 if successful. 0 if failures encountered. * @since 8.2 */ int proj_trans_bounds(PJ_CONTEXT *context, PJ *P, PJ_DIRECTION direction, const double xmin, const double ymin, const double xmax, const double ymax, double *out_xmin, double *out_ymin, double *out_xmax, double *out_ymax, const int densify_pts) { *out_xmin = HUGE_VAL; *out_ymin = HUGE_VAL; *out_xmax = HUGE_VAL; *out_ymax = HUGE_VAL; if (P == nullptr) { proj_log_error(P, _("NULL P object not allowed.")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return false; } if (densify_pts < 0 || densify_pts > 10000) { proj_log_error(P, _("densify_pts must be between 0-10000.")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return false; } PJ_PROJ_INFO pj_info = proj_pj_info(P); if (pj_info.id == nullptr) { proj_log_error(P, _("NULL transformation not allowed,")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return false; } if (strcmp(pj_info.id, "noop") == 0 || direction == PJ_IDENT) { *out_xmin = xmin; *out_xmax = xmax; *out_ymin = ymin; *out_ymax = ymax; return true; } bool degree_output = proj_degree_output(P, direction) != 0; bool degree_input = proj_degree_input(P, direction) != 0; if (degree_output && densify_pts < 2) { proj_log_error( P, _("densify_pts must be at least 2 if the output is geographic.")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return false; } int side_pts = densify_pts + 1; // add one because we are densifying const int boundary_len = side_pts * 4; std::vector<double> x_boundary_array; std::vector<double> y_boundary_array; try { x_boundary_array.resize(boundary_len); y_boundary_array.resize(boundary_len); } catch (const std::exception &e) // memory allocation failure { proj_log_error(P, e.what()); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return false; } double delta_x = 0; double delta_y = 0; bool north_pole_in_bounds = false; bool south_pole_in_bounds = false; bool input_lon_lat_order = false; bool output_lon_lat_order = false; if (degree_input) { int in_order_lon_lat = target_crs_lon_lat_order(context, P, opposite_direction(direction)); if (in_order_lon_lat == -1) return false; input_lon_lat_order = in_order_lon_lat != 0; } if (degree_output) { int out_order_lon_lat = target_crs_lon_lat_order(context, P, direction); if (out_order_lon_lat == -1) return false; output_lon_lat_order = out_order_lon_lat != 0; north_pole_in_bounds = contains_north_pole( P, direction, xmin, ymin, xmax, ymax, output_lon_lat_order); south_pole_in_bounds = contains_south_pole( P, direction, xmin, ymin, xmax, ymax, output_lon_lat_order); } if (degree_input && xmax < xmin) { if (!input_lon_lat_order) { proj_log_error(P, _("latitude max < latitude min.")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return false; } // handle antimeridian delta_x = (xmax - xmin + 360.0) / side_pts; } else { delta_x = (xmax - xmin) / side_pts; } if (degree_input && ymax < ymin) { if (input_lon_lat_order) { proj_log_error(P, _("latitude max < latitude min.")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return false; } // handle antimeridian delta_y = (ymax - ymin + 360.0) / side_pts; } else { delta_y = (ymax - ymin) / side_pts; } // build densified bounding box // Note: must be a linear ring for antimeridian logic for (int iii = 0; iii < side_pts; iii++) { // xmin boundary y_boundary_array[iii] = ymax - iii * delta_y; x_boundary_array[iii] = xmin; // ymin boundary y_boundary_array[iii + side_pts] = ymin; x_boundary_array[iii + side_pts] = xmin + iii * delta_x; // xmax boundary y_boundary_array[iii + side_pts * 2] = ymin + iii * delta_y; x_boundary_array[iii + side_pts * 2] = xmax; // ymax boundary y_boundary_array[iii + side_pts * 3] = ymax; x_boundary_array[iii + side_pts * 3] = xmax - iii * delta_x; } proj_trans_generic(P, direction, &x_boundary_array[0], sizeof(double), boundary_len, &y_boundary_array[0], sizeof(double), boundary_len, nullptr, 0, 0, nullptr, 0, 0); if (!degree_output) { *out_xmin = simple_min(&x_boundary_array[0], boundary_len); *out_xmax = simple_max(&x_boundary_array[0], boundary_len); *out_ymin = simple_min(&y_boundary_array[0], boundary_len); *out_ymax = simple_max(&y_boundary_array[0], boundary_len); } else if (north_pole_in_bounds && output_lon_lat_order) { *out_xmin = -180; *out_ymin = simple_min(&y_boundary_array[0], boundary_len); *out_xmax = 180; *out_ymax = 90; } else if (north_pole_in_bounds) { *out_xmin = simple_min(&x_boundary_array[0], boundary_len); *out_ymin = -180; *out_xmax = 90; *out_ymax = 180; } else if (south_pole_in_bounds && output_lon_lat_order) { *out_xmin = -180; *out_ymin = -90; *out_xmax = 180; *out_ymax = simple_max(&y_boundary_array[0], boundary_len); } else if (south_pole_in_bounds) { *out_xmin = -90; *out_ymin = -180; *out_xmax = simple_max(&x_boundary_array[0], boundary_len); *out_ymax = 180; } else if (output_lon_lat_order) { *out_xmin = antimeridian_min(&x_boundary_array[0], boundary_len); *out_xmax = antimeridian_max(&x_boundary_array[0], boundary_len); *out_ymin = simple_min(&y_boundary_array[0], boundary_len); *out_ymax = simple_max(&y_boundary_array[0], boundary_len); } else { *out_xmin = simple_min(&x_boundary_array[0], boundary_len); *out_xmax = simple_max(&x_boundary_array[0], boundary_len); *out_ymin = antimeridian_min(&y_boundary_array[0], boundary_len); *out_ymax = antimeridian_max(&y_boundary_array[0], boundary_len); } return true; } /*****************************************************************************/ static void reproject_bbox(PJ *pjGeogToCrs, double west_lon, double south_lat, double east_lon, double north_lat, double &minx, double &miny, double &maxx, double &maxy) { /*****************************************************************************/ minx = -std::numeric_limits<double>::max(); miny = -std::numeric_limits<double>::max(); maxx = std::numeric_limits<double>::max(); maxy = std::numeric_limits<double>::max(); if (!(west_lon == -180.0 && east_lon == 180.0 && south_lat == -90.0 && north_lat == 90.0)) { minx = -minx; miny = -miny; maxx = -maxx; maxy = -maxy; constexpr int N_STEPS = 20; constexpr int N_STEPS_P1 = N_STEPS + 1; constexpr int XY_SIZE = N_STEPS_P1 * 4; std::vector<double> x(XY_SIZE); std::vector<double> y(XY_SIZE); const double step_lon = (east_lon - west_lon) / N_STEPS; const double step_lat = (north_lat - south_lat) / N_STEPS; for (int j = 0; j <= N_STEPS; j++) { x[j] = west_lon + j * step_lon; y[j] = south_lat; x[N_STEPS_P1 + j] = x[j]; y[N_STEPS_P1 + j] = north_lat; x[N_STEPS_P1 * 2 + j] = west_lon; y[N_STEPS_P1 * 2 + j] = south_lat + j * step_lat; x[N_STEPS_P1 * 3 + j] = east_lon; y[N_STEPS_P1 * 3 + j] = y[N_STEPS_P1 * 2 + j]; } proj_trans_generic(pjGeogToCrs, PJ_FWD, &x[0], sizeof(double), XY_SIZE, &y[0], sizeof(double), XY_SIZE, nullptr, 0, 0, nullptr, 0, 0); for (int j = 0; j < XY_SIZE; j++) { if (x[j] != HUGE_VAL && y[j] != HUGE_VAL) { minx = std::min(minx, x[j]); miny = std::min(miny, y[j]); maxx = std::max(maxx, x[j]); maxy = std::max(maxy, y[j]); } } } } /*****************************************************************************/ static PJ *add_coord_op_to_list( int idxInOriginalList, PJ *op, double west_lon, double south_lat, double east_lon, double north_lat, PJ *pjGeogToSrc, PJ *pjGeogToDst, const PJ *pjSrcGeocentricToLonLat, const PJ *pjDstGeocentricToLonLat, const char *areaName, std::vector<PJCoordOperation> &altCoordOps) { /*****************************************************************************/ double minxSrc; double minySrc; double maxxSrc; double maxySrc; double minxDst; double minyDst; double maxxDst; double maxyDst; double w = west_lon / 180 * M_PI; double s = south_lat / 180 * M_PI; double e = east_lon / 180 * M_PI; double n = north_lat / 180 * M_PI; if (w > e) { e += 2 * M_PI; } // Integrate cos(lat) between south_lat and north_lat const double pseudoArea = (e - w) * (std::sin(n) - std::sin(s)); if (pjSrcGeocentricToLonLat) { minxSrc = west_lon; minySrc = south_lat; maxxSrc = east_lon; maxySrc = north_lat; } else { reproject_bbox(pjGeogToSrc, west_lon, south_lat, east_lon, north_lat, minxSrc, minySrc, maxxSrc, maxySrc); } if (pjDstGeocentricToLonLat) { minxDst = west_lon; minyDst = south_lat; maxxDst = east_lon; maxyDst = north_lat; } else { reproject_bbox(pjGeogToDst, west_lon, south_lat, east_lon, north_lat, minxDst, minyDst, maxxDst, maxyDst); } if (minxSrc <= maxxSrc && minxDst <= maxxDst) { const char *c_name = proj_get_name(op); std::string name(c_name ? c_name : ""); const double accuracy = proj_coordoperation_get_accuracy(op->ctx, op); altCoordOps.emplace_back( idxInOriginalList, minxSrc, minySrc, maxxSrc, maxySrc, minxDst, minyDst, maxxDst, maxyDst, op, name, accuracy, pseudoArea, areaName, pjSrcGeocentricToLonLat, pjDstGeocentricToLonLat); op = nullptr; } return op; } namespace { struct ObjectKeeper { PJ *m_obj = nullptr; explicit ObjectKeeper(PJ *obj) : m_obj(obj) {} ~ObjectKeeper() { proj_destroy(m_obj); } ObjectKeeper(const ObjectKeeper &) = delete; ObjectKeeper &operator=(const ObjectKeeper &) = delete; }; } // namespace /*****************************************************************************/ static PJ *create_operation_to_geog_crs(PJ_CONTEXT *ctx, const PJ *crs) { /*****************************************************************************/ std::unique_ptr<ObjectKeeper> keeper; if (proj_get_type(crs) == PJ_TYPE_COORDINATE_METADATA) { auto tmp = proj_get_source_crs(ctx, crs); assert(tmp); keeper.reset(new ObjectKeeper(tmp)); crs = tmp; } (void)keeper; // Create a geographic 2D long-lat degrees CRS that is related to the // CRS auto geodetic_crs = proj_crs_get_geodetic_crs(ctx, crs); if (!geodetic_crs) { proj_context_log_debug(ctx, "Cannot find geodetic CRS matching CRS"); return nullptr; } auto geodetic_crs_type = proj_get_type(geodetic_crs); if (geodetic_crs_type == PJ_TYPE_GEOCENTRIC_CRS || geodetic_crs_type == PJ_TYPE_GEOGRAPHIC_2D_CRS || geodetic_crs_type == PJ_TYPE_GEOGRAPHIC_3D_CRS) { auto datum = proj_crs_get_datum_forced(ctx, geodetic_crs); assert(datum); auto cs = proj_create_ellipsoidal_2D_cs( ctx, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); auto ellps = proj_get_ellipsoid(ctx, datum); proj_destroy(datum); double semi_major_metre = 0; double inv_flattening = 0; proj_ellipsoid_get_parameters(ctx, ellps, &semi_major_metre, nullptr, nullptr, &inv_flattening); // It is critical to set the prime meridian to 0 auto temp = proj_create_geographic_crs( ctx, "unnamed crs", "unnamed datum", proj_get_name(ellps), semi_major_metre, inv_flattening, "Reference prime meridian", 0, nullptr, 0, cs); proj_destroy(ellps); proj_destroy(cs); proj_destroy(geodetic_crs); geodetic_crs = temp; geodetic_crs_type = proj_get_type(geodetic_crs); } if (geodetic_crs_type != PJ_TYPE_GEOGRAPHIC_2D_CRS) { // Shouldn't happen proj_context_log_debug(ctx, "Cannot find geographic CRS matching CRS"); proj_destroy(geodetic_crs); return nullptr; } // Create the transformation from this geographic 2D CRS to the source CRS auto operation_ctx = proj_create_operation_factory_context(ctx, nullptr); proj_operation_factory_context_set_spatial_criterion( ctx, operation_ctx, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( ctx, operation_ctx, PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID); auto target_crs_2D = proj_crs_demote_to_2D(ctx, nullptr, crs); auto op_list_to_geodetic = proj_create_operations(ctx, geodetic_crs, target_crs_2D, operation_ctx); proj_destroy(target_crs_2D); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(geodetic_crs); const int nOpCount = op_list_to_geodetic == nullptr ? 0 : proj_list_get_count(op_list_to_geodetic); if (nOpCount == 0) { proj_context_log_debug( ctx, "Cannot compute transformation from geographic CRS to CRS"); proj_list_destroy(op_list_to_geodetic); return nullptr; } PJ *opGeogToCrs = nullptr; // Use in priority operations *without* grids for (int i = 0; i < nOpCount; i++) { auto op = proj_list_get(ctx, op_list_to_geodetic, i); assert(op); if (proj_coordoperation_get_grid_used_count(ctx, op) == 0) { opGeogToCrs = op; break; } proj_destroy(op); } if (opGeogToCrs == nullptr) { opGeogToCrs = proj_list_get(ctx, op_list_to_geodetic, 0); assert(opGeogToCrs); } proj_list_destroy(op_list_to_geodetic); return opGeogToCrs; } /*****************************************************************************/ static PJ *create_operation_geocentric_crs_to_geog_crs(PJ_CONTEXT *ctx, const PJ *geocentric_crs) /*****************************************************************************/ { assert(proj_get_type(geocentric_crs) == PJ_TYPE_GEOCENTRIC_CRS); auto datum = proj_crs_get_datum_forced(ctx, geocentric_crs); assert(datum); auto cs = proj_create_ellipsoidal_2D_cs(ctx, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); auto ellps = proj_get_ellipsoid(ctx, datum); proj_destroy(datum); double semi_major_metre = 0; double inv_flattening = 0; proj_ellipsoid_get_parameters(ctx, ellps, &semi_major_metre, nullptr, nullptr, &inv_flattening); // It is critical to set the prime meridian to 0 auto lon_lat_crs = proj_create_geographic_crs( ctx, "unnamed crs", "unnamed datum", proj_get_name(ellps), semi_major_metre, inv_flattening, "Reference prime meridian", 0, nullptr, 0, cs); proj_destroy(ellps); proj_destroy(cs); // Create the transformation from this geocentric CRS to the lon-lat one auto operation_ctx = proj_create_operation_factory_context(ctx, nullptr); proj_operation_factory_context_set_spatial_criterion( ctx, operation_ctx, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( ctx, operation_ctx, PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID); auto op_list = proj_create_operations(ctx, geocentric_crs, lon_lat_crs, operation_ctx); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(lon_lat_crs); const int nOpCount = op_list == nullptr ? 0 : proj_list_get_count(op_list); if (nOpCount != 1) { proj_context_log_debug(ctx, "Cannot compute transformation from " "geocentric CRS to geographic CRS"); proj_list_destroy(op_list); return nullptr; } auto op = proj_list_get(ctx, op_list, 0); assert(op); proj_list_destroy(op_list); return op; } /*****************************************************************************/ PJ *proj_create_crs_to_crs(PJ_CONTEXT *ctx, const char *source_crs, const char *target_crs, PJ_AREA *area) { /****************************************************************************** Create a transformation pipeline between two known coordinate reference systems. See docs/source/development/reference/functions.rst ******************************************************************************/ if (!ctx) { ctx = pj_get_default_ctx(); } PJ *src; PJ *dst; try { std::string source_crs_modified(pj_add_type_crs_if_needed(source_crs)); std::string target_crs_modified(pj_add_type_crs_if_needed(target_crs)); src = proj_create(ctx, source_crs_modified.c_str()); if (!src) { proj_context_log_debug(ctx, "Cannot instantiate source_crs"); return nullptr; } dst = proj_create(ctx, target_crs_modified.c_str()); if (!dst) { proj_context_log_debug(ctx, "Cannot instantiate target_crs"); proj_destroy(src); return nullptr; } } catch (const std::exception &) { return nullptr; } auto ret = proj_create_crs_to_crs_from_pj(ctx, src, dst, area, nullptr); proj_destroy(src); proj_destroy(dst); return ret; } /*****************************************************************************/ std::vector<PJCoordOperation> pj_create_prepared_operations(PJ_CONTEXT *ctx, const PJ *source_crs, const PJ *target_crs, PJ_OBJ_LIST *op_list) /*****************************************************************************/ { PJ *pjGeogToSrc = nullptr; PJ *pjSrcGeocentricToLonLat = nullptr; if (proj_get_type(source_crs) == PJ_TYPE_GEOCENTRIC_CRS) { pjSrcGeocentricToLonLat = create_operation_geocentric_crs_to_geog_crs(ctx, source_crs); if (!pjSrcGeocentricToLonLat) { // shouldn't happen return {}; } } else { pjGeogToSrc = create_operation_to_geog_crs(ctx, source_crs); if (!pjGeogToSrc) { proj_context_log_debug( ctx, "Cannot create transformation from geographic " "CRS of source CRS to source CRS"); return {}; } } PJ *pjGeogToDst = nullptr; PJ *pjDstGeocentricToLonLat = nullptr; if (proj_get_type(target_crs) == PJ_TYPE_GEOCENTRIC_CRS) { pjDstGeocentricToLonLat = create_operation_geocentric_crs_to_geog_crs(ctx, target_crs); if (!pjDstGeocentricToLonLat) { // shouldn't happen proj_destroy(pjSrcGeocentricToLonLat); proj_destroy(pjGeogToSrc); return {}; } } else { pjGeogToDst = create_operation_to_geog_crs(ctx, target_crs); if (!pjGeogToDst) { proj_context_log_debug( ctx, "Cannot create transformation from geographic " "CRS of target CRS to target CRS"); proj_destroy(pjSrcGeocentricToLonLat); proj_destroy(pjGeogToSrc); return {}; } } try { std::vector<PJCoordOperation> preparedOpList; // Iterate over source->target candidate transformations and reproject // their long-lat bounding box into the source CRS. const auto op_count = proj_list_get_count(op_list); for (int i = 0; i < op_count; i++) { auto op = proj_list_get(ctx, op_list, i); assert(op); double west_lon = 0.0; double south_lat = 0.0; double east_lon = 0.0; double north_lat = 0.0; const char *areaName = nullptr; if (!proj_get_area_of_use(ctx, op, &west_lon, &south_lat, &east_lon, &north_lat, &areaName)) { west_lon = -180; south_lat = -90; east_lon = 180; north_lat = 90; } if (west_lon <= east_lon) { op = add_coord_op_to_list( i, op, west_lon, south_lat, east_lon, north_lat, pjGeogToSrc, pjGeogToDst, pjSrcGeocentricToLonLat, pjDstGeocentricToLonLat, areaName, preparedOpList); } else { auto op_clone = proj_clone(ctx, op); op = add_coord_op_to_list( i, op, west_lon, south_lat, 180, north_lat, pjGeogToSrc, pjGeogToDst, pjSrcGeocentricToLonLat, pjDstGeocentricToLonLat, areaName, preparedOpList); op_clone = add_coord_op_to_list( i, op_clone, -180, south_lat, east_lon, north_lat, pjGeogToSrc, pjGeogToDst, pjSrcGeocentricToLonLat, pjDstGeocentricToLonLat, areaName, preparedOpList); proj_destroy(op_clone); } proj_destroy(op); } proj_destroy(pjGeogToSrc); proj_destroy(pjGeogToDst); proj_destroy(pjSrcGeocentricToLonLat); proj_destroy(pjDstGeocentricToLonLat); return preparedOpList; } catch (const std::exception &) { proj_destroy(pjGeogToSrc); proj_destroy(pjGeogToDst); proj_destroy(pjSrcGeocentricToLonLat); proj_destroy(pjDstGeocentricToLonLat); return {}; } } // --------------------------------------------------------------------------- //! @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 /*****************************************************************************/ PJ *proj_create_crs_to_crs_from_pj(PJ_CONTEXT *ctx, const PJ *source_crs, const PJ *target_crs, PJ_AREA *area, const char *const *options) { /****************************************************************************** Create a transformation pipeline between two known coordinate reference systems. See docs/source/development/reference/functions.rst ******************************************************************************/ if (!ctx) { ctx = pj_get_default_ctx(); } pj_load_ini( ctx); // to set ctx->errorIfBestTransformationNotAvailableDefault const char *authority = nullptr; double accuracy = -1; bool allowBallparkTransformations = true; bool forceOver = false; bool warnIfBestTransformationNotAvailable = ctx->warnIfBestTransformationNotAvailableDefault; bool errorIfBestTransformationNotAvailable = ctx->errorIfBestTransformationNotAvailableDefault; for (auto iter = options; iter && iter[0]; ++iter) { const char *value; if ((value = getOptionValue(*iter, "AUTHORITY="))) { authority = value; } else if ((value = getOptionValue(*iter, "ACCURACY="))) { accuracy = pj_atof(value); } else if ((value = getOptionValue(*iter, "ALLOW_BALLPARK="))) { if (ci_equal(value, "yes")) allowBallparkTransformations = true; else if (ci_equal(value, "no")) allowBallparkTransformations = false; else { ctx->logger(ctx->logger_app_data, PJ_LOG_ERROR, "Invalid value for ALLOW_BALLPARK option."); return nullptr; } } else if ((value = getOptionValue(*iter, "ONLY_BEST="))) { warnIfBestTransformationNotAvailable = false; if (ci_equal(value, "yes")) errorIfBestTransformationNotAvailable = true; else if (ci_equal(value, "no")) errorIfBestTransformationNotAvailable = false; else { ctx->logger(ctx->logger_app_data, PJ_LOG_ERROR, "Invalid value for ONLY_BEST option."); return nullptr; } } else if ((value = getOptionValue(*iter, "FORCE_OVER="))) { if (ci_equal(value, "yes")) { forceOver = true; } } else { std::string msg("Unknown option :"); msg += *iter; ctx->logger(ctx->logger_app_data, PJ_LOG_ERROR, msg.c_str()); return nullptr; } } auto operation_ctx = proj_create_operation_factory_context(ctx, authority); if (!operation_ctx) { return nullptr; } proj_operation_factory_context_set_allow_ballpark_transformations( ctx, operation_ctx, allowBallparkTransformations); if (accuracy >= 0) { proj_operation_factory_context_set_desired_accuracy(ctx, operation_ctx, accuracy); } if (area && area->bbox_set) { proj_operation_factory_context_set_area_of_interest( ctx, operation_ctx, area->west_lon_degree, area->south_lat_degree, area->east_lon_degree, area->north_lat_degree); if (!area->name.empty()) { proj_operation_factory_context_set_area_of_interest_name( ctx, operation_ctx, area->name.c_str()); } } proj_operation_factory_context_set_spatial_criterion( ctx, operation_ctx, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( ctx, operation_ctx, (errorIfBestTransformationNotAvailable || warnIfBestTransformationNotAvailable || proj_context_is_network_enabled(ctx)) ? PROJ_GRID_AVAILABILITY_KNOWN_AVAILABLE : PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID); auto op_list = proj_create_operations(ctx, source_crs, target_crs, operation_ctx); proj_operation_factory_context_destroy(operation_ctx); if (!op_list) { return nullptr; } auto op_count = proj_list_get_count(op_list); if (op_count == 0) { proj_list_destroy(op_list); proj_context_log_debug(ctx, "No operation found matching criteria"); return nullptr; } ctx->forceOver = forceOver; const int old_debug_level = ctx->debug_level; if (errorIfBestTransformationNotAvailable || warnIfBestTransformationNotAvailable) ctx->debug_level = PJ_LOG_NONE; PJ *P = proj_list_get(ctx, op_list, 0); ctx->debug_level = old_debug_level; assert(P); if (P != nullptr) { P->errorIfBestTransformationNotAvailable = errorIfBestTransformationNotAvailable; P->warnIfBestTransformationNotAvailable = warnIfBestTransformationNotAvailable; P->skipNonInstantiable = warnIfBestTransformationNotAvailable; } const bool mayNeedToReRunWithDiscardMissing = (errorIfBestTransformationNotAvailable || warnIfBestTransformationNotAvailable) && !proj_context_is_network_enabled(ctx); int singleOpIsInstanciable = -1; if (P != nullptr && op_count == 1 && mayNeedToReRunWithDiscardMissing) { singleOpIsInstanciable = proj_coordoperation_is_instantiable(ctx, P); } const auto backup_errno = proj_context_errno(ctx); if (P == nullptr || (op_count == 1 && (!mayNeedToReRunWithDiscardMissing || errorIfBestTransformationNotAvailable || singleOpIsInstanciable == static_cast<int>(true)))) { proj_list_destroy(op_list); ctx->forceOver = false; if (P != nullptr && (errorIfBestTransformationNotAvailable || warnIfBestTransformationNotAvailable)) { if (singleOpIsInstanciable < 0) { singleOpIsInstanciable = proj_coordoperation_is_instantiable(ctx, P); } if (!singleOpIsInstanciable) { warnAboutMissingGrid(P); if (errorIfBestTransformationNotAvailable) { proj_destroy(P); return nullptr; } } } if (P != nullptr) { P->over = forceOver; } return P; } else if (op_count == 1 && mayNeedToReRunWithDiscardMissing && !singleOpIsInstanciable) { warnAboutMissingGrid(P); } if (errorIfBestTransformationNotAvailable || warnIfBestTransformationNotAvailable) ctx->debug_level = PJ_LOG_NONE; auto preparedOpList = pj_create_prepared_operations(ctx, source_crs, target_crs, op_list); ctx->debug_level = old_debug_level; ctx->forceOver = false; proj_list_destroy(op_list); if (preparedOpList.empty()) { proj_destroy(P); return nullptr; } bool foundInstanciableAndNonBallpark = false; for (auto &op : preparedOpList) { op.pj->over = forceOver; op.pj->errorIfBestTransformationNotAvailable = errorIfBestTransformationNotAvailable; op.pj->warnIfBestTransformationNotAvailable = warnIfBestTransformationNotAvailable; if (mayNeedToReRunWithDiscardMissing && !foundInstanciableAndNonBallpark) { if (!proj_coordoperation_has_ballpark_transformation(op.pj->ctx, op.pj) && op.isInstantiable()) { foundInstanciableAndNonBallpark = true; } } } if (mayNeedToReRunWithDiscardMissing && !foundInstanciableAndNonBallpark) { // Re-run proj_create_operations with // PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID // Can happen for example for NAD27->NAD83 transformation when we // have no grid and thus have fallback to Helmert transformation and // a WGS84 intermediate. operation_ctx = proj_create_operation_factory_context(ctx, authority); if (operation_ctx) { proj_operation_factory_context_set_allow_ballpark_transformations( ctx, operation_ctx, allowBallparkTransformations); if (accuracy >= 0) { proj_operation_factory_context_set_desired_accuracy( ctx, operation_ctx, accuracy); } if (area && area->bbox_set) { proj_operation_factory_context_set_area_of_interest( ctx, operation_ctx, area->west_lon_degree, area->south_lat_degree, area->east_lon_degree, area->north_lat_degree); if (!area->name.empty()) { proj_operation_factory_context_set_area_of_interest_name( ctx, operation_ctx, area->name.c_str()); } } proj_operation_factory_context_set_spatial_criterion( ctx, operation_ctx, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( ctx, operation_ctx, PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID); op_list = proj_create_operations(ctx, source_crs, target_crs, operation_ctx); proj_operation_factory_context_destroy(operation_ctx); if (op_list) { ctx->forceOver = forceOver; ctx->debug_level = PJ_LOG_NONE; auto preparedOpList2 = pj_create_prepared_operations( ctx, source_crs, target_crs, op_list); ctx->debug_level = old_debug_level; ctx->forceOver = false; proj_list_destroy(op_list); if (!preparedOpList2.empty()) { // Append new lists of operations to previous one std::vector<PJCoordOperation> newOpList; for (auto &&op : preparedOpList) { if (!proj_coordoperation_has_ballpark_transformation( op.pj->ctx, op.pj)) { newOpList.emplace_back(std::move(op)); } } for (auto &&op : preparedOpList2) { op.pj->over = forceOver; op.pj->errorIfBestTransformationNotAvailable = errorIfBestTransformationNotAvailable; op.pj->warnIfBestTransformationNotAvailable = warnIfBestTransformationNotAvailable; newOpList.emplace_back(std::move(op)); } preparedOpList = std::move(newOpList); } else { // We get there in "cs2cs --only-best --no-ballpark // EPSG:4326+3855 EPSG:4979" use case, where the initial // create_operations returned 1 operation, and the retry // with // PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID // returned 0. if (op_count == 1 && errorIfBestTransformationNotAvailable) { if (singleOpIsInstanciable < 0) { singleOpIsInstanciable = proj_coordoperation_is_instantiable(ctx, P); } if (!singleOpIsInstanciable) { proj_destroy(P); proj_context_errno_set(ctx, backup_errno); return nullptr; } } } } } } // If there's finally juste a single result, return it directly if (preparedOpList.size() == 1) { auto retP = preparedOpList[0].pj; preparedOpList[0].pj = nullptr; proj_destroy(P); return retP; } P->alternativeCoordinateOperations = std::move(preparedOpList); // The returned P is rather dummy P->descr = "Set of coordinate operations"; P->over = forceOver; P->iso_obj = nullptr; P->fwd = nullptr; P->inv = nullptr; P->fwd3d = nullptr; P->inv3d = nullptr; P->fwd4d = nullptr; P->inv4d = nullptr; return P; } /*****************************************************************************/ int proj_errno(const PJ *P) { /****************************************************************************** Read an error level from the context of a PJ. ******************************************************************************/ return proj_context_errno(pj_get_ctx((PJ *)P)); } /*****************************************************************************/ int proj_context_errno(PJ_CONTEXT *ctx) { /****************************************************************************** Read an error directly from a context, without going through a PJ belonging to that context. ******************************************************************************/ if (nullptr == ctx) ctx = pj_get_default_ctx(); return ctx->last_errno; } /*****************************************************************************/ int proj_errno_set(const PJ *P, int err) { /****************************************************************************** Set context-errno, bubble it up to the thread local errno, return err ******************************************************************************/ /* Use proj_errno_reset to explicitly clear the error status */ if (0 == err) return 0; /* For P==0 err goes to the default context */ proj_context_errno_set(pj_get_ctx((PJ *)P), err); errno = err; return err; } /*****************************************************************************/ int proj_errno_restore(const PJ *P, int err) { /****************************************************************************** Use proj_errno_restore when the current function succeeds, but the error flag was set on entry, and stored/reset using proj_errno_reset in order to monitor for new errors. See usage example under proj_errno_reset () ******************************************************************************/ if (0 == err) return 0; proj_errno_set(P, err); return 0; } /*****************************************************************************/ int proj_errno_reset(const PJ *P) { /****************************************************************************** Clears errno in the context and thread local levels through the low level pj_ctx interface. Returns the previous value of the errno, for convenient reset/restore operations: int foo (PJ *P) { // errno may be set on entry, but we need to reset it to be able to // check for errors from "do_something_with_P(P)" int last_errno = proj_errno_reset (P); // local failure if (0==P) return proj_errno_set (P, 42); // call to function that may fail do_something_with_P (P); // failure in do_something_with_P? - keep latest error status if (proj_errno(P)) return proj_errno (P); // success - restore previous error status, return 0 return proj_errno_restore (P, last_errno); } ******************************************************************************/ int last_errno; last_errno = proj_errno(P); proj_context_errno_set(pj_get_ctx((PJ *)P), 0); errno = 0; return last_errno; } /* Create a new context based on the default context */ PJ_CONTEXT *proj_context_create(void) { return new (std::nothrow) pj_ctx(*pj_get_default_ctx()); } PJ_CONTEXT *proj_context_destroy(PJ_CONTEXT *ctx) { if (nullptr == ctx) return nullptr; /* Trying to free the default context is a no-op (since it is statically * allocated) */ if (pj_get_default_ctx() == ctx) return nullptr; delete ctx; return nullptr; } /*****************************************************************************/ static char *path_append(char *buf, const char *app, size_t *buf_size) { /****************************************************************************** Helper for proj_info() below. Append app to buf, separated by a semicolon. Also handle allocation of longer buffer if needed. Returns buffer and adjusts *buf_size through provided pointer arg. ******************************************************************************/ char *p; size_t len, applen = 0, buflen = 0; #ifdef _WIN32 const char *delim = ";"; #else const char *delim = ":"; #endif /* Nothing to do? */ if (nullptr == app) return buf; applen = strlen(app); if (0 == applen) return buf; /* Start checking whether buf is long enough */ if (nullptr != buf) buflen = strlen(buf); len = buflen + applen + strlen(delim) + 1; /* "pj_realloc", so to speak */ if (*buf_size < len) { p = static_cast<char *>(calloc(2 * len, sizeof(char))); if (nullptr == p) { free(buf); return nullptr; } *buf_size = 2 * len; if (buf != nullptr) strcpy(p, buf); free(buf); buf = p; } assert(buf); /* Only append a delimiter if something's already there */ if (0 != buflen) strcat(buf, delim); strcat(buf, app); return buf; } static const char *empty = {""}; static char version[64] = {""}; static PJ_INFO info = {0, 0, 0, nullptr, nullptr, nullptr, nullptr, 0}; /*****************************************************************************/ PJ_INFO proj_info(void) { /****************************************************************************** Basic info about the current instance of the PROJ.4 library. Returns PJ_INFO struct. ******************************************************************************/ size_t buf_size = 0; char *buf = nullptr; pj_acquire_lock(); info.major = PROJ_VERSION_MAJOR; info.minor = PROJ_VERSION_MINOR; info.patch = PROJ_VERSION_PATCH; /* A normal version string is xx.yy.zz which is 8 characters long and there is room for 64 bytes in the version string. */ snprintf(version, sizeof(version), "%d.%d.%d", info.major, info.minor, info.patch); info.version = version; info.release = pj_get_release(); /* build search path string */ auto ctx = pj_get_default_ctx(); if (ctx->search_paths.empty()) { const auto searchpaths = pj_get_default_searchpaths(ctx); for (const auto &path : searchpaths) { buf = path_append(buf, path.c_str(), &buf_size); } } else { for (const auto &path : ctx->search_paths) { buf = path_append(buf, path.c_str(), &buf_size); } } if (info.searchpath != empty) free(const_cast<char *>(info.searchpath)); info.searchpath = buf ? buf : empty; info.paths = ctx->c_compat_paths; info.path_count = static_cast<int>(ctx->search_paths.size()); pj_release_lock(); return info; } /*****************************************************************************/ PJ_PROJ_INFO proj_pj_info(PJ *P) { /****************************************************************************** Basic info about a particular instance of a projection object. Returns PJ_PROJ_INFO struct. ******************************************************************************/ PJ_PROJ_INFO pjinfo; char *def; memset(&pjinfo, 0, sizeof(PJ_PROJ_INFO)); pjinfo.accuracy = -1.0; if (nullptr == P) return pjinfo; /* coordinate operation description */ if (!P->alternativeCoordinateOperations.empty()) { if (P->iCurCoordOp >= 0) { P = P->alternativeCoordinateOperations[P->iCurCoordOp].pj; } else { PJ *candidateOp = nullptr; // If there's just a single coordinate operation which is // instanciable, use it. for (const auto &op : P->alternativeCoordinateOperations) { if (op.isInstantiable()) { if (candidateOp == nullptr) { candidateOp = op.pj; } else { candidateOp = nullptr; break; } } } if (candidateOp) { P = candidateOp; } else { pjinfo.id = "unknown"; pjinfo.description = "unavailable until proj_trans is called"; pjinfo.definition = "unavailable until proj_trans is called"; return pjinfo; } } } /* projection id */ if (pj_param(P->ctx, P->params, "tproj").i) pjinfo.id = pj_param(P->ctx, P->params, "sproj").s; pjinfo.description = P->descr; if (P->iso_obj) { auto identifiedObj = dynamic_cast<NS_PROJ::common::IdentifiedObject *>(P->iso_obj.get()); if (identifiedObj) { pjinfo.description = identifiedObj->nameStr().c_str(); } } // accuracy if (P->iso_obj) { auto conv = dynamic_cast<const NS_PROJ::operation::Conversion *>( P->iso_obj.get()); if (conv) { pjinfo.accuracy = 0.0; } else { auto op = dynamic_cast<const NS_PROJ::operation::CoordinateOperation *>( P->iso_obj.get()); if (op) { const auto &accuracies = op->coordinateOperationAccuracies(); if (!accuracies.empty()) { try { pjinfo.accuracy = std::stod(accuracies[0]->value()); } catch (const std::exception &) { } } } } } /* projection definition */ if (P->def_full) def = P->def_full; else def = pj_get_def(P, 0); /* pj_get_def takes a non-const PJ pointer */ if (nullptr == def) pjinfo.definition = empty; else pjinfo.definition = pj_shrink(def); /* Make proj_destroy clean this up eventually */ P->def_full = def; pjinfo.has_inverse = pj_has_inverse(P); return pjinfo; } /*****************************************************************************/ PJ_GRID_INFO proj_grid_info(const char *gridname) { /****************************************************************************** Information about a named datum grid. Returns PJ_GRID_INFO struct. ******************************************************************************/ PJ_GRID_INFO grinfo; /*PJ_CONTEXT *ctx = proj_context_create(); */ PJ_CONTEXT *ctx = pj_get_default_ctx(); memset(&grinfo, 0, sizeof(PJ_GRID_INFO)); const auto fillGridInfo = [&grinfo, ctx, gridname](const NS_PROJ::Grid &grid, const std::string &format) { const auto &extent = grid.extentAndRes(); /* name of grid */ strncpy(grinfo.gridname, gridname, sizeof(grinfo.gridname) - 1); /* full path of grid */ if (!pj_find_file(ctx, gridname, grinfo.filename, sizeof(grinfo.filename) - 1)) { // Can happen when using a remote grid grinfo.filename[0] = 0; } /* grid format */ strncpy(grinfo.format, format.c_str(), sizeof(grinfo.format) - 1); /* grid size */ grinfo.n_lon = grid.width(); grinfo.n_lat = grid.height(); /* cell size */ grinfo.cs_lon = extent.resX; grinfo.cs_lat = extent.resY; /* bounds of grid */ grinfo.lowerleft.lam = extent.west; grinfo.lowerleft.phi = extent.south; grinfo.upperright.lam = extent.east; grinfo.upperright.phi = extent.north; }; { const auto gridSet = NS_PROJ::VerticalShiftGridSet::open(ctx, gridname); if (gridSet) { const auto &grids = gridSet->grids(); if (!grids.empty()) { const auto &grid = grids.front(); fillGridInfo(*grid, gridSet->format()); return grinfo; } } } { const auto gridSet = NS_PROJ::HorizontalShiftGridSet::open(ctx, gridname); if (gridSet) { const auto &grids = gridSet->grids(); if (!grids.empty()) { const auto &grid = grids.front(); fillGridInfo(*grid, gridSet->format()); return grinfo; } } } strcpy(grinfo.format, "missing"); return grinfo; } /*****************************************************************************/ PJ_INIT_INFO proj_init_info(const char *initname) { /****************************************************************************** Information about a named init file. Maximum length of initname is 64. Returns PJ_INIT_INFO struct. If the init file is not found all members of the return struct are set to the empty string. If the init file is found, but the metadata is missing, the value is set to "Unknown". ******************************************************************************/ int file_found; char param[80], key[74]; paralist *start, *next; PJ_INIT_INFO ininfo; PJ_CONTEXT *ctx = pj_get_default_ctx(); memset(&ininfo, 0, sizeof(PJ_INIT_INFO)); file_found = pj_find_file(ctx, initname, ininfo.filename, sizeof(ininfo.filename)); if (!file_found || strlen(initname) > 64) { if (strcmp(initname, "epsg") == 0 || strcmp(initname, "EPSG") == 0) { const char *val; proj_context_errno_set(ctx, 0); strncpy(ininfo.name, initname, sizeof(ininfo.name) - 1); strcpy(ininfo.origin, "EPSG"); val = proj_context_get_database_metadata(ctx, "EPSG.VERSION"); if (val) { strncpy(ininfo.version, val, sizeof(ininfo.version) - 1); } val = proj_context_get_database_metadata(ctx, "EPSG.DATE"); if (val) { strncpy(ininfo.lastupdate, val, sizeof(ininfo.lastupdate) - 1); } return ininfo; } if (strcmp(initname, "IGNF") == 0) { const char *val; proj_context_errno_set(ctx, 0); strncpy(ininfo.name, initname, sizeof(ininfo.name) - 1); strcpy(ininfo.origin, "IGNF"); val = proj_context_get_database_metadata(ctx, "IGNF.VERSION"); if (val) { strncpy(ininfo.version, val, sizeof(ininfo.version) - 1); } val = proj_context_get_database_metadata(ctx, "IGNF.DATE"); if (val) { strncpy(ininfo.lastupdate, val, sizeof(ininfo.lastupdate) - 1); } return ininfo; } return ininfo; } /* The initial memset (0) makes strncpy safe here */ strncpy(ininfo.name, initname, sizeof(ininfo.name) - 1); strcpy(ininfo.origin, "Unknown"); strcpy(ininfo.version, "Unknown"); strcpy(ininfo.lastupdate, "Unknown"); strncpy(key, initname, 64); /* make room for ":metadata\0" at the end */ key[64] = 0; memcpy(key + strlen(key), ":metadata", 9 + 1); strcpy(param, "+init="); /* The +strlen(param) avoids a cppcheck false positive warning */ strncat(param + strlen(param), key, sizeof(param) - 1 - strlen(param)); start = pj_mkparam(param); pj_expand_init(ctx, start); if (pj_param(ctx, start, "tversion").i) strncpy(ininfo.version, pj_param(ctx, start, "sversion").s, sizeof(ininfo.version) - 1); if (pj_param(ctx, start, "torigin").i) strncpy(ininfo.origin, pj_param(ctx, start, "sorigin").s, sizeof(ininfo.origin) - 1); if (pj_param(ctx, start, "tlastupdate").i) strncpy(ininfo.lastupdate, pj_param(ctx, start, "slastupdate").s, sizeof(ininfo.lastupdate) - 1); for (; start; start = next) { next = start->next; free(start); } return ininfo; } /*****************************************************************************/ PJ_FACTORS proj_factors(PJ *P, PJ_COORD lp) { /****************************************************************************** Cartographic characteristics at point lp. Characteristics include meridian, parallel and areal scales, angular distortion, meridian/parallel, meridian convergence and scale error. returns PJ_FACTORS. If unsuccessful, error number is set and the struct returned contains NULL data. ******************************************************************************/ PJ_FACTORS factors = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; struct FACTORS f; if (nullptr == P) return factors; const auto type = proj_get_type(P); if (type == PJ_TYPE_COMPOUND_CRS) { auto ctx = P->ctx; auto horiz = proj_crs_get_sub_crs(ctx, P, 0); if (horiz) { auto ret = proj_factors(horiz, lp); proj_destroy(horiz); return ret; } } if (type == PJ_TYPE_PROJECTED_CRS) { // If it is a projected CRS, then compute the factors on the conversion // associated to it. We need to start from a temporary geographic CRS // using the same datum as the one of the projected CRS, and with // input coordinates being in longitude, latitude order in radian, // to be consistent with the expectations of the lp input parameter. // We also need to create a modified projected CRS with a normalized // easting/northing axis order in metre, so the resulting operation is // just a single step pipeline with no axisswap or unitconvert steps. auto ctx = P->ctx; 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); 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); auto newOp = proj_create_crs_to_crs_from_pj( ctx, geogCRSNormalized, projCRSNormalized, nullptr, nullptr); proj_destroy(geogCRSNormalized); proj_destroy(projCRSNormalized); assert(newOp); // For debugging: // printf("%s\n", proj_as_proj_string(ctx, newOp, PJ_PROJ_5, nullptr)); auto ret = proj_factors(newOp, lp); proj_destroy(newOp); return ret; } if (type != PJ_TYPE_CONVERSION && type != PJ_TYPE_TRANSFORMATION && type != PJ_TYPE_CONCATENATED_OPERATION && type != PJ_TYPE_OTHER_COORDINATE_OPERATION) { proj_log_error(P, _("Invalid type for P object")); proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return factors; } if (pj_factors(lp.lp, P, 0.0, &f)) return factors; factors.meridional_scale = f.h; factors.parallel_scale = f.k; factors.areal_scale = f.s; factors.angular_distortion = f.omega; factors.meridian_parallel_angle = f.thetap; factors.meridian_convergence = f.conv; factors.tissot_semimajor = f.a; factors.tissot_semiminor = f.b; /* Raw derivatives, for completeness's sake */ factors.dx_dlam = f.der.x_l; factors.dx_dphi = f.der.x_p; factors.dy_dlam = f.der.y_l; factors.dy_dphi = f.der.y_p; return factors; } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // Returns true if the passed operation uses NADCON5 grids for NAD83 to // NAD83(HARN) static bool isSpecialCaseForNAD83_to_NAD83HARN(const std::string &opName) { return opName.find("NAD83 to NAD83(HARN) (47)") != std::string::npos || opName.find("NAD83 to NAD83(HARN) (48)") != std::string::npos || opName.find("NAD83 to NAD83(HARN) (49)") != std::string::npos || opName.find("NAD83 to NAD83(HARN) (50)") != std::string::npos; } // Returns true if the passed operation uses "GDA94 to WGS 84 (1)", which // is the null transformation static bool isSpecialCaseForGDA94_to_WGS84(const std::string &opName) { return opName.find("GDA94 to WGS 84 (1)") != std::string::npos; } // Returns true if the passed operation uses "GDA2020 to WGS 84 (2)", which // is the null transformation static bool isSpecialCaseForWGS84_to_GDA2020(const std::string &opName) { return opName.find("GDA2020 to WGS 84 (2)") != std::string::npos; } PJCoordOperation::PJCoordOperation( int idxInOriginalListIn, double minxSrcIn, double minySrcIn, double maxxSrcIn, double maxySrcIn, double minxDstIn, double minyDstIn, double maxxDstIn, double maxyDstIn, PJ *pjIn, const std::string &nameIn, double accuracyIn, double pseudoAreaIn, const char *areaNameIn, const PJ *pjSrcGeocentricToLonLatIn, const PJ *pjDstGeocentricToLonLatIn) : idxInOriginalList(idxInOriginalListIn), minxSrc(minxSrcIn), minySrc(minySrcIn), maxxSrc(maxxSrcIn), maxySrc(maxySrcIn), minxDst(minxDstIn), minyDst(minyDstIn), maxxDst(maxxDstIn), maxyDst(maxyDstIn), pj(pjIn), name(nameIn), accuracy(accuracyIn), pseudoArea(pseudoAreaIn), areaName(areaNameIn ? areaNameIn : ""), isOffshore(areaName.find("- offshore") != std::string::npos), isUnknownAreaName(areaName.empty() || areaName == "unknown"), isPriorityOp(isSpecialCaseForNAD83_to_NAD83HARN(name) || isSpecialCaseForGDA94_to_WGS84(name) || isSpecialCaseForWGS84_to_GDA2020(name)), pjSrcGeocentricToLonLat(pjSrcGeocentricToLonLatIn ? proj_clone(pjSrcGeocentricToLonLatIn->ctx, pjSrcGeocentricToLonLatIn) : nullptr), pjDstGeocentricToLonLat(pjDstGeocentricToLonLatIn ? proj_clone(pjDstGeocentricToLonLatIn->ctx, pjDstGeocentricToLonLatIn) : nullptr) { const auto IsLonLatOrLatLon = [](const PJ *crs, bool &isLonLatDegreeOut, bool &isLatLonDegreeOut) { const auto eType = proj_get_type(crs); if (eType == PJ_TYPE_GEOGRAPHIC_2D_CRS || eType == PJ_TYPE_GEOGRAPHIC_3D_CRS) { const auto cs = proj_crs_get_coordinate_system(crs->ctx, crs); const char *direction = ""; double conv_factor = 0; constexpr double EPS = 1e-14; if (proj_cs_get_axis_info(crs->ctx, cs, 0, nullptr, nullptr, &direction, &conv_factor, nullptr, nullptr, nullptr) && ci_equal(direction, "East")) { isLonLatDegreeOut = fabs(conv_factor - M_PI / 180) < EPS; } else if (proj_cs_get_axis_info(crs->ctx, cs, 1, nullptr, nullptr, &direction, &conv_factor, nullptr, nullptr, nullptr) && ci_equal(direction, "East")) { isLatLonDegreeOut = fabs(conv_factor - M_PI / 180) < EPS; } proj_destroy(cs); } }; const auto source = proj_get_source_crs(pj->ctx, pj); if (source) { IsLonLatOrLatLon(source, srcIsLonLatDegree, srcIsLatLonDegree); proj_destroy(source); } const auto target = proj_get_target_crs(pj->ctx, pj); if (target) { IsLonLatOrLatLon(target, dstIsLonLatDegree, dstIsLatLonDegree); proj_destroy(target); } } //! @endcond
cpp
PROJ
data/projects/PROJ/src/wkt_parser.cpp
/****************************************************************************** * Project: PROJ * Purpose: WKT parser common routines * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2018 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. ****************************************************************************/ #include "wkt_parser.hpp" #include <algorithm> #include <string> // --------------------------------------------------------------------------- void pj_wkt_error(pj_wkt_parse_context *context, const char *msg) { context->errorMsg = "Parsing error : "; context->errorMsg += msg; context->errorMsg += ". Error occurred around:\n"; std::string ctxtMsg; const int n = static_cast<int>(context->pszLastSuccess - context->pszInput); int start_i = std::max(0, n - 40); for (int i = start_i; i < n + 40 && context->pszInput[i]; i++) { if (context->pszInput[i] == '\r' || context->pszInput[i] == '\n') { if (i > n) { break; } else { ctxtMsg.clear(); start_i = i + 1; } } else { ctxtMsg += context->pszInput[i]; } } context->errorMsg += ctxtMsg; context->errorMsg += '\n'; for (int i = start_i; i < n; i++) context->errorMsg += ' '; context->errorMsg += '^'; }
cpp
PROJ
data/projects/PROJ/src/ctx.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the PJ_CONTEXT thread context object. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2010, 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. *****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include <errno.h> #include <stdlib.h> #include <string.h> #include <new> #include "filemanager.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj_experimental.h" #include "proj_internal.h" /************************************************************************/ /* pj_get_ctx() */ /************************************************************************/ PJ_CONTEXT *pj_get_ctx(PJ *pj) { if (nullptr == pj) return pj_get_default_ctx(); if (nullptr == pj->ctx) return pj_get_default_ctx(); return pj->ctx; } /************************************************************************/ /* proj_assign_context() */ /************************************************************************/ /** \brief Re-assign a context to a PJ* object. * * This may be useful if the PJ* has been created with a context that is * thread-specific, and is later used in another thread. In that case, * the user may want to assign another thread-specific context to the * object. */ void proj_assign_context(PJ *pj, PJ_CONTEXT *ctx) { if (pj == nullptr) return; pj->ctx = ctx; if (pj->reassign_context) { pj->reassign_context(pj, ctx); } for (const auto &alt : pj->alternativeCoordinateOperations) { proj_assign_context(alt.pj, ctx); } } /************************************************************************/ /* createDefault() */ /************************************************************************/ pj_ctx pj_ctx::createDefault() { pj_ctx ctx; ctx.debug_level = PJ_LOG_ERROR; ctx.logger = pj_stderr_logger; NS_PROJ::FileManager::fillDefaultNetworkInterface(&ctx); const char *projDebug = getenv("PROJ_DEBUG"); if (projDebug != nullptr) { if (NS_PROJ::internal::ci_equal(projDebug, "ON")) { ctx.debug_level = PJ_LOG_DEBUG; } else if (NS_PROJ::internal::ci_equal(projDebug, "OFF")) { ctx.debug_level = PJ_LOG_ERROR; } else if (projDebug[0] == '-' || (projDebug[0] >= '0' && projDebug[0] <= '9')) { const int debugLevel = atoi(projDebug); // Negative debug levels mean that we first start logging when errno // is set Cf // https://github.com/OSGeo/PROJ/commit/1c1d04b45d76366f54e104f9346879fd48bfde8e // This isn't documented for now. Not totally sure we really want // that... if (debugLevel >= -PJ_LOG_TRACE) ctx.debug_level = debugLevel; else ctx.debug_level = PJ_LOG_TRACE; } else { fprintf(stderr, "Invalid value for PROJ_DEBUG: %s\n", projDebug); } } return ctx; } /**************************************************************************/ /* get_cpp_context() */ /**************************************************************************/ projCppContext *pj_ctx::get_cpp_context() { if (cpp_context == nullptr) { cpp_context = new projCppContext(this); } return cpp_context; } /************************************************************************/ /* set_search_paths() */ /************************************************************************/ void pj_ctx::set_search_paths(const std::vector<std::string> &search_paths_in) { search_paths = search_paths_in; delete[] c_compat_paths; c_compat_paths = nullptr; if (!search_paths.empty()) { c_compat_paths = new const char *[search_paths.size()]; for (size_t i = 0; i < search_paths.size(); ++i) { c_compat_paths[i] = search_paths[i].c_str(); } } } /**************************************************************************/ /* set_ca_bundle_path() */ /**************************************************************************/ void pj_ctx::set_ca_bundle_path(const std::string &ca_bundle_path_in) { ca_bundle_path = ca_bundle_path_in; } /************************************************************************/ /* pj_ctx(const pj_ctx& other) */ /************************************************************************/ pj_ctx::pj_ctx(const pj_ctx &other) : lastFullErrorMessage(std::string()), last_errno(0), debug_level(other.debug_level), errorIfBestTransformationNotAvailableDefault( other.errorIfBestTransformationNotAvailableDefault), warnIfBestTransformationNotAvailableDefault( other.warnIfBestTransformationNotAvailableDefault), logger(other.logger), logger_app_data(other.logger_app_data), cpp_context(other.cpp_context ? other.cpp_context->clone(this) : nullptr), use_proj4_init_rules(other.use_proj4_init_rules), forceOver(other.forceOver), epsg_file_exists(other.epsg_file_exists), env_var_proj_data(other.env_var_proj_data), file_finder(other.file_finder), file_finder_user_data(other.file_finder_user_data), defer_grid_opening(false), custom_sqlite3_vfs_name(other.custom_sqlite3_vfs_name), user_writable_directory(other.user_writable_directory), // BEGIN ini file settings iniFileLoaded(other.iniFileLoaded), endpoint(other.endpoint), networking(other.networking), ca_bundle_path(other.ca_bundle_path), gridChunkCache(other.gridChunkCache), defaultTmercAlgo(other.defaultTmercAlgo), // END ini file settings projStringParserCreateFromPROJStringRecursionCounter(0), pipelineInitRecursiongCounter(0) { set_search_paths(other.search_paths); } /************************************************************************/ /* pj_get_default_ctx() */ /************************************************************************/ PJ_CONTEXT *pj_get_default_ctx() { // C++11 rules guarantee a thread-safe instantiation. static pj_ctx default_context(pj_ctx::createDefault()); return &default_context; } /************************************************************************/ /* ~pj_ctx() */ /************************************************************************/ pj_ctx::~pj_ctx() { delete[] c_compat_paths; proj_context_delete_cpp_context(cpp_context); } /************************************************************************/ /* proj_context_clone() */ /* Create a new context based on a custom context */ /************************************************************************/ PJ_CONTEXT *proj_context_clone(PJ_CONTEXT *ctx) { if (nullptr == ctx) return proj_context_create(); return new (std::nothrow) pj_ctx(*ctx); }
cpp
PROJ
data/projects/PROJ/src/pj_list.h
#ifdef DO_PJ_LIST_ID static const char PJ_LIST_H_ID[] = "@(#)pj_list.h 4.5 95/08/09 GIE REL"; #endif /* Full list of current projections for Tue Jan 11 12:27:04 EST 1994 ** ** Copy this file and retain only appropriate lines for subset list */ PROJ_HEAD(adams_hemi, "Adams Hemisphere in a Square") PROJ_HEAD(adams_ws1, "Adams World in a Square I") PROJ_HEAD(adams_ws2, "Adams World in a Square II") PROJ_HEAD(aea, "Albers Equal Area") PROJ_HEAD(aeqd, "Azimuthal Equidistant") PROJ_HEAD(affine, "Affine transformation") PROJ_HEAD(airy, "Airy") PROJ_HEAD(aitoff, "Aitoff") PROJ_HEAD(alsk, "Modified Stereographic of Alaska") PROJ_HEAD(apian, "Apian Globular I") PROJ_HEAD(august, "August Epicycloidal") PROJ_HEAD(axisswap, "Axis ordering") PROJ_HEAD(bacon, "Bacon Globular") PROJ_HEAD(bertin1953, "Bertin 1953") PROJ_HEAD(bipc, "Bipolar conic of western hemisphere") PROJ_HEAD(boggs, "Boggs Eumorphic") PROJ_HEAD(bonne, "Bonne (Werner lat_1=90)") PROJ_HEAD(calcofi, "Cal Coop Ocean Fish Invest Lines/Stations") PROJ_HEAD(cart, "Geodetic/cartesian conversions") PROJ_HEAD(cass, "Cassini") PROJ_HEAD(cc, "Central Cylindrical") PROJ_HEAD(ccon, "Central Conic") PROJ_HEAD(cea, "Equal Area Cylindrical") PROJ_HEAD(chamb, "Chamberlin Trimetric") PROJ_HEAD(collg, "Collignon") PROJ_HEAD(col_urban, "Colombia Urban") PROJ_HEAD(comill, "Compact Miller") PROJ_HEAD(crast, "Craster Parabolic (Putnins P4)") PROJ_HEAD(defmodel, "Deformation model") PROJ_HEAD(deformation, "Kinematic grid shift") PROJ_HEAD(denoy, "Denoyer Semi-Elliptical") PROJ_HEAD(eck1, "Eckert I") PROJ_HEAD(eck2, "Eckert II") PROJ_HEAD(eck3, "Eckert III") PROJ_HEAD(eck4, "Eckert IV") PROJ_HEAD(eck5, "Eckert V") PROJ_HEAD(eck6, "Eckert VI") PROJ_HEAD(eqearth, "Equal Earth") PROJ_HEAD(eqc, "Equidistant Cylindrical (Plate Carree)") PROJ_HEAD(eqdc, "Equidistant Conic") PROJ_HEAD(euler, "Euler") PROJ_HEAD(etmerc, "Extended Transverse Mercator") PROJ_HEAD(fahey, "Fahey") PROJ_HEAD(fouc, "Foucaut") PROJ_HEAD(fouc_s, "Foucaut Sinusoidal") PROJ_HEAD(gall, "Gall (Gall Stereographic)") PROJ_HEAD(geoc, "Geocentric Latitude") PROJ_HEAD(geocent, "Geocentric") PROJ_HEAD(geogoffset, "Geographic Offset") PROJ_HEAD(geos, "Geostationary Satellite View") PROJ_HEAD(gins8, "Ginsburg VIII (TsNIIGAiK)") PROJ_HEAD(gn_sinu, "General Sinusoidal Series") PROJ_HEAD(gnom, "Gnomonic") PROJ_HEAD(goode, "Goode Homolosine") PROJ_HEAD(gridshift, "Generic grid shift") PROJ_HEAD(gs48, "Modified Stereographic of 48 U.S.") PROJ_HEAD(gs50, "Modified Stereographic of 50 U.S.") PROJ_HEAD(guyou, "Guyou") PROJ_HEAD(hammer, "Hammer & Eckert-Greifendorff") PROJ_HEAD(hatano, "Hatano Asymmetrical Equal Area") PROJ_HEAD(healpix, "HEALPix") PROJ_HEAD(rhealpix, "rHEALPix") PROJ_HEAD(helmert, "3- and 7-parameter Helmert shift") PROJ_HEAD(hgridshift, "Horizontal grid shift") PROJ_HEAD(horner, "Horner polynomial evaluation") PROJ_HEAD(igh, "Interrupted Goode Homolosine") PROJ_HEAD(igh_o, "Interrupted Goode Homolosine Oceanic View") PROJ_HEAD(imoll, "Interrupted Mollweide") PROJ_HEAD(imoll_o, "Interrupted Mollweide Oceanic View") PROJ_HEAD(imw_p, "International Map of the World Polyconic") PROJ_HEAD(isea, "Icosahedral Snyder Equal Area") PROJ_HEAD(kav5, "Kavrayskiy V") PROJ_HEAD(kav7, "Kavrayskiy VII") PROJ_HEAD(krovak, "Krovak") PROJ_HEAD(labrd, "Laborde") PROJ_HEAD(laea, "Lambert Azimuthal Equal Area") PROJ_HEAD(lagrng, "Lagrange") PROJ_HEAD(larr, "Larrivee") PROJ_HEAD(lask, "Laskowski") PROJ_HEAD(lonlat, "Lat/long (Geodetic)") PROJ_HEAD(latlon, "Lat/long (Geodetic alias)") PROJ_HEAD(latlong, "Lat/long (Geodetic alias)") PROJ_HEAD(longlat, "Lat/long (Geodetic alias)") PROJ_HEAD(lcc, "Lambert Conformal Conic") PROJ_HEAD(lcca, "Lambert Conformal Conic Alternative") PROJ_HEAD(leac, "Lambert Equal Area Conic") PROJ_HEAD(lee_os, "Lee Oblated Stereographic") PROJ_HEAD(loxim, "Loximuthal") PROJ_HEAD(lsat, "Space oblique for LANDSAT") PROJ_HEAD(mbt_s, "McBryde-Thomas Flat-Polar Sine") PROJ_HEAD(mbt_fps, "McBryde-Thomas Flat-Pole Sine (No. 2)") PROJ_HEAD(mbtfpp, "McBride-Thomas Flat-Polar Parabolic") PROJ_HEAD(mbtfpq, "McBryde-Thomas Flat-Polar Quartic") PROJ_HEAD(mbtfps, "McBryde-Thomas Flat-Polar Sinusoidal") PROJ_HEAD(merc, "Mercator") PROJ_HEAD(mil_os, "Miller Oblated Stereographic") PROJ_HEAD(mill, "Miller Cylindrical") PROJ_HEAD(misrsom, "Space oblique for MISR") PROJ_HEAD(mod_krovak, "Modified Krovak") PROJ_HEAD(moll, "Mollweide") PROJ_HEAD(molobadekas, "Molodensky-Badekas transform") /* implemented in PJ_helmert.c */ PROJ_HEAD(molodensky, "Molodensky transform") PROJ_HEAD(murd1, "Murdoch I") PROJ_HEAD(murd2, "Murdoch II") PROJ_HEAD(murd3, "Murdoch III") PROJ_HEAD(natearth, "Natural Earth") PROJ_HEAD(natearth2, "Natural Earth II") PROJ_HEAD(nell, "Nell") PROJ_HEAD(nell_h, "Nell-Hammer") PROJ_HEAD(nicol, "Nicolosi Globular") PROJ_HEAD(nsper, "Near-sided perspective") PROJ_HEAD(nzmg, "New Zealand Map Grid") PROJ_HEAD(noop, "No operation") PROJ_HEAD(ob_tran, "General Oblique Transformation") PROJ_HEAD(ocea, "Oblique Cylindrical Equal Area") PROJ_HEAD(oea, "Oblated Equal Area") PROJ_HEAD(omerc, "Oblique Mercator") PROJ_HEAD(ortel, "Ortelius Oval") PROJ_HEAD(ortho, "Orthographic") PROJ_HEAD(pconic, "Perspective Conic") PROJ_HEAD(patterson, "Patterson Cylindrical") PROJ_HEAD(peirce_q, "Peirce Quincuncial") PROJ_HEAD(pipeline, "Transformation pipeline manager") PROJ_HEAD(poly, "Polyconic (American)") PROJ_HEAD(pop, "Retrieve coordinate value from pipeline stack") PROJ_HEAD(push, "Save coordinate value on pipeline stack") PROJ_HEAD(putp1, "Putnins P1") PROJ_HEAD(putp2, "Putnins P2") PROJ_HEAD(putp3, "Putnins P3") PROJ_HEAD(putp3p, "Putnins P3'") PROJ_HEAD(putp4p, "Putnins P4'") PROJ_HEAD(putp5, "Putnins P5") PROJ_HEAD(putp5p, "Putnins P5'") PROJ_HEAD(putp6, "Putnins P6") PROJ_HEAD(putp6p, "Putnins P6'") PROJ_HEAD(qua_aut, "Quartic Authalic") PROJ_HEAD(qsc, "Quadrilateralized Spherical Cube") PROJ_HEAD(robin, "Robinson") PROJ_HEAD(rouss, "Roussilhe Stereographic") PROJ_HEAD(rpoly, "Rectangular Polyconic") PROJ_HEAD(s2, "S2") PROJ_HEAD(sch, "Spherical Cross-track Height") PROJ_HEAD(set, "Set coordinate value") PROJ_HEAD(sinu, "Sinusoidal (Sanson-Flamsteed)") PROJ_HEAD(som, "Space Oblique Mercator") PROJ_HEAD(somerc, "Swiss. Obl. Mercator") PROJ_HEAD(stere, "Stereographic") PROJ_HEAD(sterea, "Oblique Stereographic Alternative") PROJ_HEAD(gstmerc, "Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)") PROJ_HEAD(tcc, "Transverse Central Cylindrical") PROJ_HEAD(tcea, "Transverse Cylindrical Equal Area") PROJ_HEAD(times, "Times Projection") PROJ_HEAD(tinshift, "Triangulation based transformation") PROJ_HEAD(tissot, "Tissot Conic") PROJ_HEAD(tmerc, "Transverse Mercator") PROJ_HEAD(tobmerc, "Tobler-Mercator") PROJ_HEAD(topocentric, "Geocentric/Topocentric conversion") PROJ_HEAD(tpeqd, "Two Point Equidistant") PROJ_HEAD(tpers, "Tilted perspective") PROJ_HEAD(unitconvert, "Unit conversion") PROJ_HEAD(ups, "Universal Polar Stereographic") PROJ_HEAD(urm5, "Urmaev V") PROJ_HEAD(urmfps, "Urmaev Flat-Polar Sinusoidal") PROJ_HEAD(utm, "Universal Transverse Mercator (UTM)") PROJ_HEAD(vandg, "van der Grinten (I)") PROJ_HEAD(vandg2, "van der Grinten II") PROJ_HEAD(vandg3, "van der Grinten III") PROJ_HEAD(vandg4, "van der Grinten IV") PROJ_HEAD(vertoffset, "Vertical Offset and Slope") PROJ_HEAD(vitk1, "Vitkovsky I") PROJ_HEAD(vgridshift, "Vertical grid shift") PROJ_HEAD(wag1, "Wagner I (Kavrayskiy VI)") PROJ_HEAD(wag2, "Wagner II") PROJ_HEAD(wag3, "Wagner III") PROJ_HEAD(wag4, "Wagner IV") PROJ_HEAD(wag5, "Wagner V") PROJ_HEAD(wag6, "Wagner VI") PROJ_HEAD(wag7, "Wagner VII") PROJ_HEAD(webmerc, "Web Mercator / Pseudo Mercator") PROJ_HEAD(weren, "Werenskiold I") PROJ_HEAD(wink1, "Winkel I") PROJ_HEAD(wink2, "Winkel II") PROJ_HEAD(wintri, "Winkel Tripel") PROJ_HEAD(xyzgridshift, "XYZ grid shift")
h
PROJ
data/projects/PROJ/src/aasincos.cpp
/* arc sin, cosine, tan2 and sqrt that will NOT fail */ #include <math.h> #include "proj.h" #include "proj_internal.h" #define ONE_TOL 1.00000000000001 #define ATOL 1e-50 double aasin(PJ_CONTEXT *ctx, double v) { double av; if ((av = fabs(v)) >= 1.) { if (av > ONE_TOL) proj_context_errno_set( ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return (v < 0. ? -M_HALFPI : M_HALFPI); } return asin(v); } double aacos(PJ_CONTEXT *ctx, double v) { double av; if ((av = fabs(v)) >= 1.) { if (av > ONE_TOL) proj_context_errno_set( ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return (v < 0. ? M_PI : 0.); } return acos(v); } double asqrt(double v) { return ((v <= 0) ? 0. : sqrt(v)); } double aatan2(double n, double d) { return ((fabs(n) < ATOL && fabs(d) < ATOL) ? 0. : atan2(n, d)); }
cpp
PROJ
data/projects/PROJ/src/pipeline.cpp
/******************************************************************************* Transformation pipeline manager Thomas Knudsen, 2016-05-20/2016-11-20 ******************************************************************************** Geodetic transformations are typically organized in a number of steps. For example, a datum shift could be carried out through these steps: 1. Convert (latitude, longitude, ellipsoidal height) to 3D geocentric cartesian coordinates (X, Y, Z) 2. Transform the (X, Y, Z) coordinates to the new datum, using a 7 parameter Helmert transformation. 3. Convert (X, Y, Z) back to (latitude, longitude, ellipsoidal height) If the height system used is orthometric, rather than ellipsoidal, another step is needed at each end of the process: 1. Add the local geoid undulation (N) to the orthometric height to obtain the ellipsoidal (i.e. geometric) height. 2. Convert (latitude, longitude, ellipsoidal height) to 3D geocentric cartesian coordinates (X, Y, Z) 3. Transform the (X, Y, Z) coordinates to the new datum, using a 7 parameter Helmert transformation. 4. Convert (X, Y, Z) back to (latitude, longitude, ellipsoidal height) 5. Subtract the local geoid undulation (N) from the ellipsoidal height to obtain the orthometric height. Additional steps can be added for e.g. change of vertical datum, so the list can grow fairly long. None of the steps are, however, particularly complex, and data flow is strictly from top to bottom. Hence, in principle, the first example above could be implemented using Unix pipelines: cat my_coordinates | geographic_to_xyz | helmert | xyz_to_geographic > my_transformed_coordinates in the grand tradition of Software Tools [1]. The proj pipeline driver implements a similar concept: Stringing together a number of steps, feeding the output of one step to the input of the next. It is a very powerful concept, that increases the range of relevance of the proj.4 system substantially. It is, however, not a particularly intrusive addition to the PROJ.4 code base: The implementation is by and large completed by adding an extra projection called "pipeline" (i.e. this file), which handles all business, and a small amount of added functionality in the pj_init code, implementing support for multilevel, embedded pipelines. Syntactically, the pipeline system introduces the "+step" keyword (which indicates the start of each transformation step), and reintroduces the +inv keyword (indicating that a given transformation step should run in reverse, i.e. forward, when the pipeline is executed in inverse direction, and vice versa). Hence, the first transformation example above, can be implemented as: +proj=pipeline +step proj=cart +step proj=helmert <ARGS> +step proj=cart +inv Where <ARGS> indicate the Helmert arguments: 3 translations (+x=..., +y=..., +z=...), 3 rotations (+rx=..., +ry=..., +rz=...) and a scale factor (+s=...). Following geodetic conventions, the rotations are given in arcseconds, and the scale factor is given as parts-per-million. [1] B. W. Kernighan & P. J. Plauger: Software tools. Reading, Massachusetts, Addison-Wesley, 1976, 338 pp. ******************************************************************************** Thomas Knudsen, [email protected], 2016-05-20 ******************************************************************************** * Copyright (c) 2016, 2017, 2018 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. * ********************************************************************************/ #include <math.h> #include <stack> #include <stddef.h> #include <string.h> #include <vector> #include "geodesic.h" #include "proj.h" #include "proj_internal.h" PROJ_HEAD(pipeline, "Transformation pipeline manager"); PROJ_HEAD(pop, "Retrieve coordinate value from pipeline stack"); PROJ_HEAD(push, "Save coordinate value on pipeline stack"); /* Projection specific elements for the PJ object */ namespace { // anonymous namespace struct Step { PJ *pj = nullptr; bool omit_fwd = false; bool omit_inv = false; Step(PJ *pjIn, bool omitFwdIn, bool omitInvIn) : pj(pjIn), omit_fwd(omitFwdIn), omit_inv(omitInvIn) {} Step(Step &&other) : pj(std::move(other.pj)), omit_fwd(other.omit_fwd), omit_inv(other.omit_inv) { other.pj = nullptr; } Step(const Step &) = delete; Step &operator=(const Step &) = delete; ~Step() { proj_destroy(pj); } }; struct Pipeline { char **argv = nullptr; char **current_argv = nullptr; std::vector<Step> steps{}; std::stack<double> stack[4]; }; struct PushPop { bool v1; bool v2; bool v3; bool v4; }; } // anonymous namespace static void pipeline_forward_4d(PJ_COORD &point, PJ *P); static void pipeline_reverse_4d(PJ_COORD &point, PJ *P); static PJ_XYZ pipeline_forward_3d(PJ_LPZ lpz, PJ *P); static PJ_LPZ pipeline_reverse_3d(PJ_XYZ xyz, PJ *P); static PJ_XY pipeline_forward(PJ_LP lp, PJ *P); static PJ_LP pipeline_reverse(PJ_XY xy, PJ *P); static void pipeline_reassign_context(PJ *P, PJ_CONTEXT *ctx) { auto pipeline = static_cast<struct Pipeline *>(P->opaque); for (auto &step : pipeline->steps) proj_assign_context(step.pj, ctx); } static void pipeline_forward_4d(PJ_COORD &point, PJ *P) { auto pipeline = static_cast<struct Pipeline *>(P->opaque); for (auto &step : pipeline->steps) { if (!step.omit_fwd) { if (!step.pj->inverted) pj_fwd4d(point, step.pj); else pj_inv4d(point, step.pj); if (point.xyzt.x == HUGE_VAL) { break; } } } } static void pipeline_reverse_4d(PJ_COORD &point, PJ *P) { auto pipeline = static_cast<struct Pipeline *>(P->opaque); for (auto iterStep = pipeline->steps.rbegin(); iterStep != pipeline->steps.rend(); ++iterStep) { const auto &step = *iterStep; if (!step.omit_inv) { if (step.pj->inverted) pj_fwd4d(point, step.pj); else pj_inv4d(point, step.pj); if (point.xyzt.x == HUGE_VAL) { break; } } } } static PJ_XYZ pipeline_forward_3d(PJ_LPZ lpz, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.lpz = lpz; auto pipeline = static_cast<struct Pipeline *>(P->opaque); for (auto &step : pipeline->steps) { if (!step.omit_fwd) { point = pj_approx_3D_trans(step.pj, PJ_FWD, point); if (point.xyzt.x == HUGE_VAL) { break; } } } return point.xyz; } static PJ_LPZ pipeline_reverse_3d(PJ_XYZ xyz, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.xyz = xyz; auto pipeline = static_cast<struct Pipeline *>(P->opaque); for (auto iterStep = pipeline->steps.rbegin(); iterStep != pipeline->steps.rend(); ++iterStep) { const auto &step = *iterStep; if (!step.omit_inv) { point = proj_trans(step.pj, PJ_INV, point); if (point.xyzt.x == HUGE_VAL) { break; } } } return point.lpz; } static PJ_XY pipeline_forward(PJ_LP lp, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.lp = lp; auto pipeline = static_cast<struct Pipeline *>(P->opaque); for (auto &step : pipeline->steps) { if (!step.omit_fwd) { point = pj_approx_2D_trans(step.pj, PJ_FWD, point); if (point.xyzt.x == HUGE_VAL) { break; } } } return point.xy; } static PJ_LP pipeline_reverse(PJ_XY xy, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.xy = xy; auto pipeline = static_cast<struct Pipeline *>(P->opaque); for (auto iterStep = pipeline->steps.rbegin(); iterStep != pipeline->steps.rend(); ++iterStep) { const auto &step = *iterStep; if (!step.omit_inv) { point = pj_approx_2D_trans(step.pj, PJ_INV, point); if (point.xyzt.x == HUGE_VAL) { break; } } } return point.lp; } static PJ *destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); auto pipeline = static_cast<struct Pipeline *>(P->opaque); free(pipeline->argv); free(pipeline->current_argv); delete pipeline; P->opaque = nullptr; return pj_default_destructor(P, errlev); } /* count the number of args in pipeline definition, and mark all args as used */ static size_t argc_params(paralist *params) { size_t argc = 0; for (; params != nullptr; params = params->next) { argc++; params->used = 1; } return ++argc; /* one extra for the sentinel */ } /* Sentinel for argument list */ static const char *argv_sentinel = "step"; /* turn paralist into argc/argv style argument list */ static char **argv_params(paralist *params, size_t argc) { char **argv; size_t i = 0; argv = static_cast<char **>(calloc(argc, sizeof(char *))); if (nullptr == argv) return nullptr; for (; params != nullptr; params = params->next) argv[i++] = params->param; argv[i++] = const_cast<char *>(argv_sentinel); return argv; } /* Being the special operator that the pipeline is, we have to handle the */ /* ellipsoid differently than usual. In general, the pipeline operation does */ /* not need an ellipsoid, but in some cases it is beneficial nonetheless. */ /* Unfortunately we can't use the normal ellipsoid setter in pj_init, since */ /* it adds a +ellps parameter to the global args if nothing else is specified*/ /* This is problematic since that ellipsoid spec is then passed on to the */ /* pipeline children. This is rarely what we want, so here we implement our */ /* own logic instead. If an ellipsoid is set in the global args, it is used */ /* as the pipeline ellipsoid. Otherwise we use GRS80 parameters as default. */ /* At last we calculate the rest of the ellipsoid parameters and */ /* re-initialize P->geod. */ static void set_ellipsoid(PJ *P) { paralist *cur, *attachment; int err = proj_errno_reset(P); /* Break the linked list after the global args */ attachment = nullptr; for (cur = P->params; cur != nullptr; cur = cur->next) /* cur->next will always be non 0 given argv_sentinel presence, */ /* but this is far from being obvious for a static analyzer */ if (cur->next != nullptr && strcmp(argv_sentinel, cur->next->param) == 0) { attachment = cur->next; cur->next = nullptr; break; } /* Check if there's any ellipsoid specification in the global params. */ /* If not, use GRS80 as default */ if (0 != pj_ellipsoid(P)) { P->a = 6378137.0; P->f = 1.0 / 298.257222101; P->es = 2 * P->f - P->f * P->f; /* reset an "unerror": In this special use case, the errno is */ /* not an error signal, but just a reply from pj_ellipsoid, */ /* telling us that "No - there was no ellipsoid definition in */ /* the PJ you provided". */ proj_errno_reset(P); } P->a_orig = P->a; P->es_orig = P->es; if (pj_calc_ellipsoid_params(P, P->a, P->es) == 0) geod_init(P->geod, P->a, P->f); /* Re-attach the dangling list */ /* Note: cur will always be non 0 given argv_sentinel presence, */ /* but this is far from being obvious for a static analyzer */ if (cur != nullptr) cur->next = attachment; proj_errno_restore(P, err); } PJ *OPERATION(pipeline, 0) { int i, nsteps = 0, argc; int i_pipeline = -1, i_first_step = -1, i_current_step; char **argv, **current_argv; if (P->ctx->pipelineInitRecursiongCounter == 5) { // Can happen for a string like: // proj=pipeline step "x="""," u=" proj=pipeline step ste=""[" u=" // proj=pipeline step ste="[" u=" proj=pipeline step ste="[" u=" // proj=pipeline step ste="[" u=" proj=pipeline step ste="[" u=" // proj=pipeline step ste="[" u=" proj=pipeline step ste="[" u=" // proj=pipeline step ste="[" u=" proj=pipeline p step ste="[" u=" // proj=pipeline step ste="[" u=" proj=pipeline step ste="[" u=" // proj=pipeline step ste="[" u=" proj=pipeline step ""x=""""""""""" // Probably an issue with the quoting handling code // But doesn't hurt to add an extra safety check proj_log_error(P, _("Pipeline: too deep recursion")); return destructor( P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); /* ERROR: nested pipelines */ } P->fwd4d = pipeline_forward_4d; P->inv4d = pipeline_reverse_4d; P->fwd3d = pipeline_forward_3d; P->inv3d = pipeline_reverse_3d; P->fwd = pipeline_forward; P->inv = pipeline_reverse; P->destructor = destructor; P->reassign_context = pipeline_reassign_context; /* Currently, the pipeline driver is a raw bit mover, enabling other * operations */ /* to collaborate efficiently. All prep/fin stuff is done at the step * levels. */ P->skip_fwd_prepare = 1; P->skip_fwd_finalize = 1; P->skip_inv_prepare = 1; P->skip_inv_finalize = 1; P->opaque = new (std::nothrow) Pipeline(); if (nullptr == P->opaque) return destructor(P, PROJ_ERR_INVALID_OP /* ENOMEM */); argc = (int)argc_params(P->params); auto pipeline = static_cast<struct Pipeline *>(P->opaque); pipeline->argv = argv = argv_params(P->params, argc); if (nullptr == argv) return destructor(P, PROJ_ERR_INVALID_OP /* ENOMEM */); pipeline->current_argv = current_argv = static_cast<char **>(calloc(argc, sizeof(char *))); if (nullptr == current_argv) return destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); /* Do some syntactical sanity checking */ for (i = 0; i < argc && argv[i] != nullptr; i++) { if (0 == strcmp(argv_sentinel, argv[i])) { if (-1 == i_pipeline) { proj_log_error(P, _("Pipeline: +step before +proj=pipeline")); return destructor(P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); } if (0 == nsteps) i_first_step = i; nsteps++; continue; } if (0 == strcmp("proj=pipeline", argv[i])) { if (-1 != i_pipeline) { proj_log_error(P, _("Pipeline: Nesting only allowed when child " "pipelines are wrapped in '+init's")); return destructor( P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); /* ERROR: nested pipelines */ } i_pipeline = i; } else if (0 == nsteps && 0 == strncmp(argv[i], "proj=", 5)) { // Non-sensical to have proj= in the general pipeline parameters. // Would not be a big issue in itself, but this makes bad // performance in parsing hostile pipelines more likely, such as the // one of // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=41290 proj_log_error( P, _("Pipeline: proj= operator before first step not allowed")); return destructor(P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); } else if (0 == nsteps && 0 == strncmp(argv[i], "o_proj=", 7)) { // Same as above. proj_log_error( P, _("Pipeline: o_proj= operator before first step not allowed")); return destructor(P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); } } nsteps--; /* Last instance of +step is just a sentinel */ if (-1 == i_pipeline) return destructor( P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); /* ERROR: no pipeline def */ if (0 == nsteps) return destructor( P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); /* ERROR: no pipeline def */ set_ellipsoid(P); /* Now loop over all steps, building a new set of arguments for each init */ i_current_step = i_first_step; for (i = 0; i < nsteps; i++) { int j; int current_argc = 0; int err; PJ *next_step = nullptr; /* Build a set of setup args for the current step */ proj_log_trace(P, "Pipeline: Building arg list for step no. %d", i); /* First add the step specific args */ for (j = i_current_step + 1; 0 != strcmp("step", argv[j]); j++) current_argv[current_argc++] = argv[j]; i_current_step = j; /* Then add the global args */ for (j = i_pipeline + 1; 0 != strcmp("step", argv[j]); j++) current_argv[current_argc++] = argv[j]; proj_log_trace(P, "Pipeline: init - %s, %d", current_argv[0], current_argc); for (j = 1; j < current_argc; j++) proj_log_trace(P, " %s", current_argv[j]); err = proj_errno_reset(P); P->ctx->pipelineInitRecursiongCounter++; next_step = pj_create_argv_internal(P->ctx, current_argc, current_argv); P->ctx->pipelineInitRecursiongCounter--; proj_log_trace(P, "Pipeline: Step %d (%s) at %p", i, current_argv[0], next_step); if (nullptr == next_step) { /* The step init failed, but possibly without setting errno. If so, * we say "malformed" */ int err_to_report = proj_errno(P); if (0 == err_to_report) err_to_report = PROJ_ERR_INVALID_OP_WRONG_SYNTAX; proj_log_error(P, _("Pipeline: Bad step definition: %s (%s)"), current_argv[0], proj_context_errno_string(P->ctx, err_to_report)); return destructor(P, err_to_report); /* ERROR: bad pipeline def */ } next_step->parent = P; proj_errno_restore(P, err); /* Is this step inverted? */ for (j = 0; j < current_argc; j++) { if (0 == strcmp("inv", current_argv[j])) { /* if +inv exists in both global and local args the forward * operation should be used */ next_step->inverted = next_step->inverted == 0 ? 1 : 0; } } bool omit_fwd = pj_param(P->ctx, next_step->params, "bomit_fwd").i != 0; bool omit_inv = pj_param(P->ctx, next_step->params, "bomit_inv").i != 0; pipeline->steps.emplace_back(next_step, omit_fwd, omit_inv); proj_log_trace(P, "Pipeline at [%p]: step at [%p] (%s) done", P, next_step, current_argv[0]); } /* Require a forward path through the pipeline */ for (auto &step : pipeline->steps) { PJ *Q = step.pj; if (step.omit_fwd) { continue; } if (Q->inverted) { if (Q->inv || Q->inv3d || Q->inv4d) { continue; } proj_log_error( P, _("Pipeline: Inverse operation for %s is not available"), Q->short_name); return destructor(P, PROJ_ERR_OTHER_NO_INVERSE_OP); } else { if (Q->fwd || Q->fwd3d || Q->fwd4d) { continue; } proj_log_error( P, _("Pipeline: Forward operation for %s is not available"), Q->short_name); return destructor(P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); } } /* determine if an inverse operation is possible */ for (auto &step : pipeline->steps) { PJ *Q = step.pj; if (step.omit_inv || pj_has_inverse(Q)) { continue; } else { P->inv = nullptr; P->inv3d = nullptr; P->inv4d = nullptr; break; } } /* Replace PJ_IO_UNITS_WHATEVER with input/output units of neighbouring * steps where */ /* it make sense. It does in most cases but not always, for instance */ /* proj=pipeline step proj=unitconvert xy_in=deg xy_out=rad step ... */ /* where the left-hand side units of the first step shouldn't be changed to * RADIANS */ /* as it will result in deg->rad conversions in cs2cs and other * applications. */ for (i = nsteps - 2; i >= 0; --i) { auto pj = pipeline->steps[i].pj; if (pj_left(pj) == PJ_IO_UNITS_WHATEVER && pj_right(pj) == PJ_IO_UNITS_WHATEVER) { const auto right_pj = pipeline->steps[i + 1].pj; const auto right_pj_left = pj_left(right_pj); const auto right_pj_right = pj_right(right_pj); if (right_pj_left != right_pj_right || right_pj_left != PJ_IO_UNITS_WHATEVER) { pj->left = right_pj_left; pj->right = right_pj_left; } } } for (i = 1; i < nsteps; i++) { auto pj = pipeline->steps[i].pj; if (pj_left(pj) == PJ_IO_UNITS_WHATEVER && pj_right(pj) == PJ_IO_UNITS_WHATEVER) { const auto left_pj = pipeline->steps[i - 1].pj; const auto left_pj_left = pj_left(left_pj); const auto left_pj_right = pj_right(left_pj); if (left_pj_left != left_pj_right || left_pj_right != PJ_IO_UNITS_WHATEVER) { pj->left = left_pj_right; pj->right = left_pj_right; } } } /* Check that units between each steps match each other, fail if they don't */ for (i = 0; i + 1 < nsteps; i++) { enum pj_io_units curr_step_output = pj_right(pipeline->steps[i].pj); enum pj_io_units next_step_input = pj_left(pipeline->steps[i + 1].pj); if (curr_step_output == PJ_IO_UNITS_WHATEVER || next_step_input == PJ_IO_UNITS_WHATEVER) continue; if (curr_step_output != next_step_input) { proj_log_error( P, _("Pipeline: Mismatched units between step %d and %d"), i + 1, i + 2); return destructor(P, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); } } proj_log_trace( P, "Pipeline: %d steps built. Determining i/o characteristics", nsteps); /* Determine forward input (= reverse output) data type */ P->left = pj_left(pipeline->steps.front().pj); /* Now, correspondingly determine forward output (= reverse input) data type */ P->right = pj_right(pipeline->steps.back().pj); return P; } static void push(PJ_COORD &point, PJ *P) { if (P->parent == nullptr) return; struct Pipeline *pipeline = static_cast<struct Pipeline *>(P->parent->opaque); struct PushPop *pushpop = static_cast<struct PushPop *>(P->opaque); if (pushpop->v1) pipeline->stack[0].push(point.v[0]); if (pushpop->v2) pipeline->stack[1].push(point.v[1]); if (pushpop->v3) pipeline->stack[2].push(point.v[2]); if (pushpop->v4) pipeline->stack[3].push(point.v[3]); } static void pop(PJ_COORD &point, PJ *P) { if (P->parent == nullptr) return; struct Pipeline *pipeline = static_cast<struct Pipeline *>(P->parent->opaque); struct PushPop *pushpop = static_cast<struct PushPop *>(P->opaque); if (pushpop->v1 && !pipeline->stack[0].empty()) { point.v[0] = pipeline->stack[0].top(); pipeline->stack[0].pop(); } if (pushpop->v2 && !pipeline->stack[1].empty()) { point.v[1] = pipeline->stack[1].top(); pipeline->stack[1].pop(); } if (pushpop->v3 && !pipeline->stack[2].empty()) { point.v[2] = pipeline->stack[2].top(); pipeline->stack[2].pop(); } if (pushpop->v4 && !pipeline->stack[3].empty()) { point.v[3] = pipeline->stack[3].top(); pipeline->stack[3].pop(); } } static PJ *setup_pushpop(PJ *P) { auto pushpop = static_cast<struct PushPop *>(calloc(1, sizeof(struct PushPop))); P->opaque = pushpop; if (nullptr == P->opaque) return destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); if (pj_param_exists(P->params, "v_1")) pushpop->v1 = true; if (pj_param_exists(P->params, "v_2")) pushpop->v2 = true; if (pj_param_exists(P->params, "v_3")) pushpop->v3 = true; if (pj_param_exists(P->params, "v_4")) pushpop->v4 = true; P->left = PJ_IO_UNITS_WHATEVER; P->right = PJ_IO_UNITS_WHATEVER; return P; } PJ *OPERATION(push, 0) { P->fwd4d = push; P->inv4d = pop; return setup_pushpop(P); } PJ *OPERATION(pop, 0) { P->inv4d = push; P->fwd4d = pop; return setup_pushpop(P); }
cpp
PROJ
data/projects/PROJ/src/tsfn.cpp
/* determine small t */ #include "proj.h" #include "proj_internal.h" #include <math.h> double pj_tsfn(double phi, double sinphi, double e) { /**************************************************************************** * Determine function ts(phi) defined in Snyder (1987), Eq. (7-10) * Inputs: * phi = geographic latitude (radians) * e = eccentricity of the ellipsoid (dimensionless) * Output: * ts = exp(-psi) where psi is the isometric latitude (dimensionless) * = 1 / (tan(chi) + sec(chi)) * Here isometric latitude is defined by * psi = log( tan(pi/4 + phi/2) * * ( (1 - e*sin(phi)) / (1 + e*sin(phi)) )^(e/2) ) * = asinh(tan(phi)) - e * atanh(e * sin(phi)) * = asinh(tan(chi)) * chi = conformal latitude ***************************************************************************/ double cosphi = cos(phi); // exp(-asinh(tan(phi))) = 1 / (tan(phi) + sec(phi)) // = cos(phi) / (1 + sin(phi)) good for phi > 0 // = (1 - sin(phi)) / cos(phi) good for phi < 0 return exp(e * atanh(e * sinphi)) * (sinphi > 0 ? cosphi / (1 + sinphi) : (1 - sinphi) / cosphi); }
cpp
PROJ
data/projects/PROJ/src/qsfn.cpp
/* determine small q */ #include "proj.h" #include "proj_internal.h" #include <math.h> #define EPSILON 1.0e-7 double pj_qsfn(double sinphi, double e, double one_es) { double con, div1, div2; if (e >= EPSILON) { con = e * sinphi; div1 = 1.0 - con * con; div2 = 1.0 + con; /* avoid zero division, fail gracefully */ if (div1 == 0.0 || div2 == 0.0) return HUGE_VAL; return (one_es * (sinphi / div1 - (.5 / e) * log((1. - con) / div2))); } else return (sinphi + sinphi); }
cpp
PROJ
data/projects/PROJ/src/auth.cpp
/* determine latitude from authalic latitude */ #include <math.h> #include <stddef.h> #include "proj.h" #include "proj_internal.h" #define P00 .33333333333333333333 /* 1 / 3 */ #define P01 .17222222222222222222 /* 31 / 180 */ #define P02 .10257936507936507937 /* 517 / 5040 */ #define P10 .06388888888888888888 /* 23 / 360 */ #define P11 .06640211640211640212 /* 251 / 3780 */ #define P20 .01677689594356261023 /* 761 / 45360 */ #define APA_SIZE 3 double *pj_authset(double es) { double t, *APA; if ((APA = (double *)malloc(APA_SIZE * sizeof(double))) != nullptr) { APA[0] = es * P00; t = es * es; APA[0] += t * P01; APA[1] = t * P10; t *= es; APA[0] += t * P02; APA[1] += t * P11; APA[2] = t * P20; } return APA; } double pj_authlat(double beta, double *APA) { double t = beta + beta; return (beta + APA[0] * sin(t) + APA[1] * sin(t + t) + APA[2] * sin(t + t + t)); }
cpp
PROJ
data/projects/PROJ/src/proj_constants.h
/****************************************************************************** * * Project: PROJ * Purpose: Constants * 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 PROJ_CONSTANTS_INCLUDED #define PROJ_CONSTANTS_INCLUDED /* Projection methods */ #define EPSG_NAME_METHOD_TRANSVERSE_MERCATOR "Transverse Mercator" #define EPSG_CODE_METHOD_TRANSVERSE_MERCATOR 9807 #define EPSG_NAME_METHOD_TRANSVERSE_MERCATOR_3D "Transverse Mercator (3D)" #define EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_3D 1111 #define EPSG_NAME_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED \ "Transverse Mercator (South Orientated)" #define EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED 9808 #define PROJ_WKT2_NAME_METHOD_TWO_POINT_EQUIDISTANT "Two Point Equidistant" #define EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_1SP \ "Lambert Conic Conformal (1SP)" #define EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP 9801 #define EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B \ "Lambert Conic Conformal (1SP variant B)" #define EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B 1102 #define EPSG_NAME_METHOD_NZMG "New Zealand Map Grid" #define EPSG_CODE_METHOD_NZMG 9811 /* Deprecated because of wrong name. Use EPSG_xxx_METHOD_TUNISIA_MINING_GRID * instead */ #define EPSG_NAME_METHOD_TUNISIA_MAPPING_GRID "Tunisia Mapping Grid" #define EPSG_CODE_METHOD_TUNISIA_MAPPING_GRID 9816 #define EPSG_NAME_METHOD_TUNISIA_MINING_GRID "Tunisia Mining Grid" #define EPSG_CODE_METHOD_TUNISIA_MINING_GRID 9816 #define EPSG_NAME_METHOD_ALBERS_EQUAL_AREA "Albers Equal Area" #define EPSG_CODE_METHOD_ALBERS_EQUAL_AREA 9822 #define EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP \ "Lambert Conic Conformal (2SP)" #define EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP 9802 #define EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM \ "Lambert Conic Conformal (2SP Belgium)" #define EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM 9803 #define EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN \ "Lambert Conic Conformal (2SP Michigan)" #define EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN 1051 #define EPSG_NAME_METHOD_AZIMUTHAL_EQUIDISTANT "Azimuthal Equidistant" #define EPSG_CODE_METHOD_AZIMUTHAL_EQUIDISTANT 1125 #define EPSG_NAME_METHOD_MODIFIED_AZIMUTHAL_EQUIDISTANT \ "Modified Azimuthal Equidistant" #define EPSG_CODE_METHOD_MODIFIED_AZIMUTHAL_EQUIDISTANT 9832 #define EPSG_NAME_METHOD_GUAM_PROJECTION "Guam Projection" #define EPSG_CODE_METHOD_GUAM_PROJECTION 9831 #define EPSG_NAME_METHOD_BONNE "Bonne" #define EPSG_CODE_METHOD_BONNE 9827 #define PROJ_WKT2_NAME_METHOD_COMPACT_MILLER "Compact Miller" #define EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL \ "Lambert Cylindrical Equal Area (Spherical)" #define EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL 9834 #define EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA \ "Lambert Cylindrical Equal Area" #define EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA 9835 #define EPSG_NAME_METHOD_CASSINI_SOLDNER "Cassini-Soldner" #define EPSG_CODE_METHOD_CASSINI_SOLDNER 9806 #define EPSG_NAME_METHOD_HYPERBOLIC_CASSINI_SOLDNER "Hyperbolic Cassini-Soldner" #define EPSG_CODE_METHOD_HYPERBOLIC_CASSINI_SOLDNER 9833 #define PROJ_WKT2_NAME_METHOD_EQUIDISTANT_CONIC "Equidistant Conic" #define EPSG_NAME_METHOD_EQUIDISTANT_CONIC "Equidistant Conic" #define EPSG_CODE_METHOD_EQUIDISTANT_CONIC 1119 #define PROJ_WKT2_NAME_METHOD_ECKERT_I "Eckert I" #define PROJ_WKT2_NAME_METHOD_ECKERT_II "Eckert II" #define PROJ_WKT2_NAME_METHOD_ECKERT_III "Eckert III" #define PROJ_WKT2_NAME_METHOD_ECKERT_IV "Eckert IV" #define PROJ_WKT2_NAME_METHOD_ECKERT_V "Eckert V" #define PROJ_WKT2_NAME_METHOD_ECKERT_VI "Eckert VI" #define EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL "Equidistant Cylindrical" #define EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL 1028 #define EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL \ "Equidistant Cylindrical (Spherical)" #define EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL 1029 #define PROJ_WKT2_NAME_METHOD_FLAT_POLAR_QUARTIC "Flat Polar Quartic" #define PROJ_WKT2_NAME_METHOD_GALL_STEREOGRAPHIC "Gall Stereographic" #define PROJ_WKT2_NAME_METHOD_GOODE_HOMOLOSINE "Goode Homolosine" #define PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE \ "Interrupted Goode Homolosine" #define PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE_OCEAN \ "Interrupted Goode Homolosine Ocean" #define PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X \ "Geostationary Satellite (Sweep X)" #define PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y \ "Geostationary Satellite (Sweep Y)" #define PROJ_WKT2_NAME_METHOD_GAUSS_SCHREIBER_TRANSVERSE_MERCATOR \ "Gauss Schreiber Transverse Mercator" #define PROJ_WKT2_NAME_METHOD_GNOMONIC "Gnomonic" #define EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A \ "Hotine Oblique Mercator (variant A)" #define EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A 9812 #define EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B \ "Hotine Oblique Mercator (variant B)" #define EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B 9815 #define PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN \ "Hotine Oblique Mercator Two Point Natural Origin" #define PROJ_WKT2_NAME_INTERNATIONAL_MAP_WORLD_POLYCONIC \ "International Map of the World Polyconic" #define EPSG_NAME_METHOD_KROVAK_NORTH_ORIENTED "Krovak (North Orientated)" #define EPSG_CODE_METHOD_KROVAK_NORTH_ORIENTED 1041 #define EPSG_NAME_METHOD_KROVAK "Krovak" #define EPSG_CODE_METHOD_KROVAK 9819 #define EPSG_NAME_METHOD_KROVAK_MODIFIED "Krovak Modified" #define EPSG_CODE_METHOD_KROVAK_MODIFIED 1042 #define EPSG_NAME_METHOD_KROVAK_MODIFIED_NORTH_ORIENTED \ "Krovak Modified (North Orientated)" #define EPSG_CODE_METHOD_KROVAK_MODIFIED_NORTH_ORIENTED 1043 #define EPSG_NAME_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA \ "Lambert Azimuthal Equal Area" #define EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA 9820 #define EPSG_NAME_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL \ "Lambert Azimuthal Equal Area (Spherical)" #define EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL 1027 #define PROJ_WKT2_NAME_METHOD_MILLER_CYLINDRICAL "Miller Cylindrical" #define EPSG_CODE_METHOD_MERCATOR_VARIANT_A 9804 #define EPSG_NAME_METHOD_MERCATOR_VARIANT_A "Mercator (variant A)" #define EPSG_CODE_METHOD_MERCATOR_VARIANT_B 9805 #define EPSG_NAME_METHOD_MERCATOR_VARIANT_B "Mercator (variant B)" #define EPSG_NAME_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR \ "Popular Visualisation Pseudo Mercator" #define EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR 1024 #define EPSG_NAME_METHOD_MERCATOR_SPHERICAL "Mercator (Spherical)" #define EPSG_CODE_METHOD_MERCATOR_SPHERICAL 1026 #define PROJ_WKT2_NAME_METHOD_MOLLWEIDE "Mollweide" #define PROJ_WKT2_NAME_METHOD_NATURAL_EARTH "Natural Earth" #define PROJ_WKT2_NAME_METHOD_NATURAL_EARTH_II "Natural Earth II" #define EPSG_NAME_METHOD_OBLIQUE_STEREOGRAPHIC "Oblique Stereographic" #define EPSG_CODE_METHOD_OBLIQUE_STEREOGRAPHIC 9809 #define EPSG_NAME_METHOD_ORTHOGRAPHIC "Orthographic" #define EPSG_CODE_METHOD_ORTHOGRAPHIC 9840 #define PROJ_WKT2_NAME_ORTHOGRAPHIC_SPHERICAL "Orthographic (Spherical)" #define PROJ_WKT2_NAME_METHOD_PATTERSON "Patterson" #define EPSG_NAME_METHOD_AMERICAN_POLYCONIC "American Polyconic" #define EPSG_CODE_METHOD_AMERICAN_POLYCONIC 9818 #define EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A \ "Polar Stereographic (variant A)" #define EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A 9810 #define EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B \ "Polar Stereographic (variant B)" #define EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B 9829 #define PROJ_WKT2_NAME_METHOD_ROBINSON "Robinson" #define PROJ_WKT2_NAME_METHOD_SINUSOIDAL "Sinusoidal" #define PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC "Stereographic" #define PROJ_WKT2_NAME_METHOD_TIMES "Times" #define PROJ_WKT2_NAME_METHOD_VAN_DER_GRINTEN "Van Der Grinten" #define PROJ_WKT2_NAME_METHOD_WAGNER_I "Wagner I" #define PROJ_WKT2_NAME_METHOD_WAGNER_II "Wagner II" #define PROJ_WKT2_NAME_METHOD_WAGNER_III "Wagner III" #define PROJ_WKT2_NAME_METHOD_WAGNER_IV "Wagner IV" #define PROJ_WKT2_NAME_METHOD_WAGNER_V "Wagner V" #define PROJ_WKT2_NAME_METHOD_WAGNER_VI "Wagner VI" #define PROJ_WKT2_NAME_METHOD_WAGNER_VII "Wagner VII" #define PROJ_WKT2_NAME_METHOD_QUADRILATERALIZED_SPHERICAL_CUBE \ "Quadrilateralized Spherical Cube" #define PROJ_WKT2_NAME_METHOD_S2 "S2" #define PROJ_WKT2_NAME_METHOD_SPHERICAL_CROSS_TRACK_HEIGHT \ "Spherical Cross-Track Height" #define EPSG_NAME_METHOD_EQUAL_EARTH "Equal Earth" #define EPSG_CODE_METHOD_EQUAL_EARTH 1078 #define EPSG_NAME_METHOD_LABORDE_OBLIQUE_MERCATOR "Laborde Oblique Mercator" #define EPSG_CODE_METHOD_LABORDE_OBLIQUE_MERCATOR 9813 #define EPSG_NAME_METHOD_VERTICAL_PERSPECTIVE "Vertical Perspective" #define EPSG_CODE_METHOD_VERTICAL_PERSPECTIVE 9838 #define PROJ_WKT2_NAME_METHOD_POLE_ROTATION_GRIB_CONVENTION \ "Pole rotation (GRIB convention)" #define PROJ_WKT2_NAME_METHOD_POLE_ROTATION_NETCDF_CF_CONVENTION \ "Pole rotation (netCDF CF convention)" #define EPSG_CODE_METHOD_COLOMBIA_URBAN 1052 #define EPSG_NAME_METHOD_COLOMBIA_URBAN "Colombia Urban" #define PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_SQUARE \ "Peirce Quincuncial (Square)" #define PROJ_WKT2_NAME_METHOD_PEIRCE_QUINCUNCIAL_DIAMOND \ "Peirce Quincuncial (Diamond)" /* ------------------------------------------------------------------------ */ /* Projection parameters */ #define EPSG_NAME_PARAMETER_COLATITUDE_CONE_AXIS "Co-latitude of cone axis" #define EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS 1036 #define EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN \ "Latitude of natural origin" #define EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN 8801 #define EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN \ "Longitude of natural origin" #define EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN 8802 #define EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN \ "Scale factor at natural origin" #define EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN 8805 #define EPSG_NAME_PARAMETER_FALSE_EASTING "False easting" #define EPSG_CODE_PARAMETER_FALSE_EASTING 8806 #define EPSG_NAME_PARAMETER_FALSE_NORTHING "False northing" #define EPSG_CODE_PARAMETER_FALSE_NORTHING 8807 #define EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE \ "Latitude of projection centre" #define EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE 8811 #define EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE \ "Longitude of projection centre" #define EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE 8812 #define EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE "Azimuth of initial line" #define EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE 8813 #define EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID \ "Angle from Rectified to Skew Grid" #define EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID 8814 #define EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE \ "Scale factor on initial line" #define EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE 8815 #define EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE \ "Easting at projection centre" #define EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE 8816 #define EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE \ "Northing at projection centre" #define EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE 8817 #define EPSG_NAME_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL \ "Latitude of pseudo standard parallel" #define EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL 8818 #define EPSG_NAME_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL \ "Scale factor on pseudo standard parallel" #define EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL 8819 #define EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN "Latitude of false origin" #define EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN 8821 #define EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN "Longitude of false origin" #define EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN 8822 #define EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL \ "Latitude of 1st standard parallel" #define EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL 8823 #define EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL \ "Latitude of 2nd standard parallel" #define EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL 8824 #define EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN "Easting at false origin" #define EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN 8826 #define EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN "Northing at false origin" #define EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN 8827 #define EPSG_NAME_PARAMETER_LATITUDE_STD_PARALLEL \ "Latitude of standard parallel" #define EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL 8832 #define EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN "Longitude of origin" #define EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN 8833 #define EPSG_NAME_PARAMETER_ELLIPSOID_SCALE_FACTOR "Ellipsoid scaling factor" #define EPSG_CODE_PARAMETER_ELLIPSOID_SCALE_FACTOR 1038 #define EPSG_NAME_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN \ "Latitude of topocentric origin" #define EPSG_CODE_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN 8834 #define EPSG_NAME_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN \ "Longitude of topocentric origin" #define EPSG_CODE_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN 8835 #define EPSG_NAME_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN \ "Ellipsoidal height of topocentric origin" #define EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN 8836 #define EPSG_NAME_PARAMETER_VIEWPOINT_HEIGHT "Viewpoint height" #define EPSG_CODE_PARAMETER_VIEWPOINT_HEIGHT 8840 #define EPSG_NAME_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT \ "Projection plane origin height" #define EPSG_CODE_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT 1039 /* ------------------------------------------------------------------------ */ /* Other conversions and transformations */ #define EPSG_NAME_METHOD_COORDINATE_FRAME_GEOCENTRIC \ "Coordinate Frame rotation (geocentric domain)" #define EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC 1032 #define EPSG_NAME_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D \ "Coordinate Frame rotation (geog2D domain)" #define EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D 9607 #define EPSG_NAME_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D \ "Coordinate Frame rotation (geog3D domain)" #define EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D 1038 #define EPSG_NAME_METHOD_POSITION_VECTOR_GEOCENTRIC \ "Position Vector transformation (geocentric domain)" #define EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC 1033 #define EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D \ "Position Vector transformation (geog2D domain)" #define EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D 9606 #define EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D \ "Position Vector transformation (geog3D domain)" #define EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D 1037 #define EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC \ "Geocentric translations (geocentric domain)" #define EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC 1031 #define EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D \ "Geocentric translations (geog2D domain)" #define EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D 9603 #define EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D \ "Geocentric translations (geog3D domain)" #define EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D 1035 #define EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC \ "Time-dependent Position Vector tfm (geocentric)" #define EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC 1053 #define EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D \ "Time-dependent Position Vector tfm (geog2D)" #define EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D 1054 #define EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D \ "Time-dependent Position Vector tfm (geog3D)" #define EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D 1055 #define EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC \ "Time-dependent Coordinate Frame rotation geocen)" #define EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC 1056 #define EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D \ "Time-dependent Coordinate Frame rotation (geog2D)" #define EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D 1057 #define EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D \ "Time-dependent Coordinate Frame rotation (geog3D)" #define EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D 1058 #define EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOCENTRIC \ "Molodensky-Badekas (CF geocentric domain)" #define EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOCENTRIC 1034 #define EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC \ "Molodensky-Badekas (PV geocentric domain)" #define EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC 1061 #define EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D \ "Molodensky-Badekas (CF geog3D domain)" #define EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D 1039 #define EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D \ "Molodensky-Badekas (PV geog3D domain)" #define EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D 1062 #define EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D \ "Molodensky-Badekas (CF geog2D domain)" #define EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D 9636 #define EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D \ "Molodensky-Badekas (PV geog2D domain)" #define EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D 1063 #define EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION 8605 #define EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION 8606 #define EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION 8607 #define EPSG_CODE_PARAMETER_X_AXIS_ROTATION 8608 #define EPSG_CODE_PARAMETER_Y_AXIS_ROTATION 8609 #define EPSG_CODE_PARAMETER_Z_AXIS_ROTATION 8610 #define EPSG_CODE_PARAMETER_SCALE_DIFFERENCE 8611 #define EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION 1040 #define EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION 1041 #define EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION 1042 #define EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION 1043 #define EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION 1044 #define EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION 1045 #define EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE 1046 #define EPSG_CODE_PARAMETER_REFERENCE_EPOCH 1047 #define EPSG_CODE_PARAMETER_TRANSFORMATION_REFERENCE_EPOCH 1049 #define EPSG_NAME_PARAMETER_X_AXIS_TRANSLATION "X-axis translation" #define EPSG_NAME_PARAMETER_Y_AXIS_TRANSLATION "Y-axis translation" #define EPSG_NAME_PARAMETER_Z_AXIS_TRANSLATION "Z-axis translation" #define EPSG_NAME_PARAMETER_X_AXIS_ROTATION "X-axis rotation" #define EPSG_NAME_PARAMETER_Y_AXIS_ROTATION "Y-axis rotation" #define EPSG_NAME_PARAMETER_Z_AXIS_ROTATION "Z-axis rotation" #define EPSG_NAME_PARAMETER_SCALE_DIFFERENCE "Scale difference" #define EPSG_NAME_PARAMETER_RATE_X_AXIS_TRANSLATION \ "Rate of change of X-axis translation" #define EPSG_NAME_PARAMETER_RATE_Y_AXIS_TRANSLATION \ "Rate of change of Y-axis translation" #define EPSG_NAME_PARAMETER_RATE_Z_AXIS_TRANSLATION \ "Rate of change of Z-axis translation" #define EPSG_NAME_PARAMETER_RATE_X_AXIS_ROTATION \ "Rate of change of X-axis rotation" #define EPSG_NAME_PARAMETER_RATE_Y_AXIS_ROTATION \ "Rate of change of Y-axis rotation" #define EPSG_NAME_PARAMETER_RATE_Z_AXIS_ROTATION \ "Rate of change of Z-axis rotation" #define EPSG_NAME_PARAMETER_RATE_SCALE_DIFFERENCE \ "Rate of change of Scale difference" #define EPSG_NAME_PARAMETER_REFERENCE_EPOCH "Parameter reference epoch" #define EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT 8617 #define EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT 8618 #define EPSG_CODE_PARAMETER_ORDINATE_3_EVAL_POINT 8667 #define EPSG_NAME_PARAMETER_ORDINATE_1_EVAL_POINT \ "Ordinate 1 of evaluation point" #define EPSG_NAME_PARAMETER_ORDINATE_2_EVAL_POINT \ "Ordinate 2 of evaluation point" #define EPSG_NAME_PARAMETER_ORDINATE_3_EVAL_POINT \ "Ordinate 3 of evaluation point" #define EPSG_NAME_PARAMETER_TRANSFORMATION_REFERENCE_EPOCH \ "Transformation reference epoch" #define EPSG_NAME_METHOD_MOLODENSKY "Molodensky" #define EPSG_CODE_METHOD_MOLODENSKY 9604 #define EPSG_NAME_METHOD_ABRIDGED_MOLODENSKY "Abridged Molodensky" #define EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY 9605 #define EPSG_CODE_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE 8654 #define EPSG_CODE_PARAMETER_FLATTENING_DIFFERENCE 8655 #define EPSG_NAME_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE \ "Semi-major axis length difference" #define EPSG_NAME_PARAMETER_FLATTENING_DIFFERENCE "Flattening difference" #define PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LATITUDE_GRIB_CONVENTION \ "Latitude of the southern pole (GRIB convention)" #define PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LONGITUDE_GRIB_CONVENTION \ "Longitude of the southern pole (GRIB convention)" #define PROJ_WKT2_NAME_PARAMETER_AXIS_ROTATION_GRIB_CONVENTION \ "Axis rotation (GRIB convention)" #define PROJ_WKT2_NAME_PARAMETER_GRID_NORTH_POLE_LATITUDE_NETCDF_CONVENTION \ "Grid north pole latitude (netCDF CF convention)" #define PROJ_WKT2_NAME_PARAMETER_GRID_NORTH_POLE_LONGITUDE_NETCDF_CONVENTION \ "Grid north pole longitude (netCDF CF convention)" #define PROJ_WKT2_NAME_PARAMETER_NORTH_POLE_GRID_LONGITUDE_NETCDF_CONVENTION \ "North pole grid longitude (netCDF CF convention)" /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_NTV1 9614 #define EPSG_NAME_METHOD_NTV1 "NTv1" #define EPSG_CODE_METHOD_NTV2 9615 #define EPSG_NAME_METHOD_NTV2 "NTv2" #define EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE 8656 #define EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE \ "Latitude and longitude difference file" #define EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME \ "Geoid (height correction) model file" #define EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME 8666 #define EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN \ "Geocentric translation by Grid Interpolation (IGN)" #define EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN 1087 #define EPSG_CODE_PARAMETER_GEOCENTRIC_TRANSLATION_FILE 8727 #define EPSG_NAME_PARAMETER_GEOCENTRIC_TRANSLATION_FILE \ "Geocentric translation file" #define EPSG_NAME_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS \ "EPSG code for Interpolation CRS" #define EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS 1048 /* ------------------------------------------------------------------------ */ #define EPSG_NAME_METHOD_POINT_MOTION_BY_GRID_CANADA_NTV2_VEL \ "Point motion by grid (Canada NTv2_Vel)" #define EPSG_CODE_METHOD_POINT_MOTION_BY_GRID_CANADA_NTV2_VEL 1070 #define EPSG_CODE_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE 1050 #define EPSG_NAME_PARAMETER_POINT_MOTION_VELOCITY_GRID_FILE \ "Point motion velocity grid file" /* ------------------------------------------------------------------------ */ #define EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN \ "Geographic3D Offset by velocity grid (NRCan byn)" #define EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSET_BY_VELOCITY_GRID_NRCAN 1114 /* ------------------------------------------------------------------------ */ #define EPSG_NAME_METHOD_VERTICAL_OFFSET_BY_VELOCITY_GRID_NRCAN \ "Vertical Offset by velocity grid (NRCan NTv2_Vel)" #define EPSG_CODE_METHOD_VERTICAL_OFFSET_BY_VELOCITY_GRID_NRCAN 1113 /* ------------------------------------------------------------------------ */ #define PROJ_WKT2_NAME_METHOD_HEIGHT_TO_GEOG3D \ "GravityRelatedHeight to Geographic3D" #define PROJ_WKT2_NAME_METHOD_CTABLE2 "CTABLE2" #define PROJ_WKT2_NAME_METHOD_HORIZONTAL_SHIFT_GTIFF "HORIZONTAL_SHIFT_GTIFF" #define PROJ_WKT2_NAME_METHOD_GENERAL_SHIFT_GTIFF "GENERAL_SHIFT_GTIFF" #define PROJ_WKT2_PARAMETER_LATITUDE_LONGITUDE_ELLIPOISDAL_HEIGHT_DIFFERENCE_FILE \ "Latitude, longitude and ellipsoidal height difference file" /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_VERTCON 9658 #define EPSG_NAME_METHOD_VERTCON_OLDNAME "VERTCON" #define EPSG_NAME_METHOD_VERTCON \ "Vertical Offset by Grid Interpolation (VERTCON)" #define EPSG_CODE_METHOD_VERTICALGRID_NZLVD 1071 #define EPSG_NAME_METHOD_VERTICALGRID_NZLVD \ "Vertical Offset by Grid Interpolation (NZLVD)" #define EPSG_CODE_METHOD_VERTICALGRID_BEV_AT 1080 #define EPSG_NAME_METHOD_VERTICALGRID_BEV_AT \ "Vertical Offset by Grid Interpolation (BEV AT)" #define EPSG_CODE_METHOD_VERTICALGRID_GTX 1084 #define EPSG_NAME_METHOD_VERTICALGRID_GTX \ "Vertical Offset by Grid Interpolation (gtx)" #define EPSG_CODE_METHOD_VERTICALGRID_PL_TXT 1101 #define EPSG_NAME_METHOD_VERTICALGRID_PL_TXT \ "Vertical Offset by Grid Interpolation (PL txt)" /* has been deprecated by * EPSG_CODE_METHOD_VERTICALCHANGE_BY_GEOID_GRID_DIFFERENCE_NRCAN */ #define EPSG_CODE_METHOD_VERTICALGRID_NRCAN_BYN 1112 #define EPSG_NAME_METHOD_VERTICALGRID_NRCAN_BYN \ "Vertical Offset by Grid Interpolation (NRCan byn)" #define EPSG_NAME_PARAMETER_VERTICAL_OFFSET_FILE "Vertical offset file" #define EPSG_CODE_PARAMETER_VERTICAL_OFFSET_FILE 8732 #define EPSG_CODE_METHOD_VERTICALCHANGE_BY_GEOID_GRID_DIFFERENCE_NRCAN 1126 #define EPSG_NAME_METHOD_VERTICALCHANGE_BY_GEOID_GRID_DIFFERENCE_NRCAN \ "Vertical change by geoid grid difference (NRCan)" #define EPSG_NAME_PARAMETER_GEOID_MODEL_DIFFERENCE_FILE \ "Geoid model difference file" #define EPSG_CODE_PARAMETER_GEOID_MODEL_DIFFERENCE_FILE 1063 /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_NADCON 9613 #define EPSG_NAME_METHOD_NADCON "NADCON" #define EPSG_NAME_PARAMETER_LATITUDE_DIFFERENCE_FILE "Latitude difference file" #define EPSG_CODE_PARAMETER_LATITUDE_DIFFERENCE_FILE 8657 #define EPSG_NAME_PARAMETER_LONGITUDE_DIFFERENCE_FILE \ "Longitude difference file" #define EPSG_CODE_PARAMETER_LONGITUDE_DIFFERENCE_FILE 8658 #define EPSG_CODE_METHOD_NADCON5_2D 1074 #define EPSG_NAME_METHOD_NADCON5_2D "NADCON5 (2D)" #define EPSG_NAME_PARAMETER_ELLIPSOIDAL_HEIGHT_DIFFERENCE_FILE \ "Ellipsoidal height difference file" #define EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_DIFFERENCE_FILE 1058 #define EPSG_CODE_METHOD_NADCON5_3D 1075 #define EPSG_NAME_METHOD_NADCON5_3D "NADCON5 (3D)" /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT 1069 #define EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT "Change of Vertical Unit" #define EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR 1104 #define EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR \ "Change of Vertical Unit" #define EPSG_NAME_PARAMETER_UNIT_CONVERSION_SCALAR "Unit conversion scalar" #define EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR 1051 /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_LONGITUDE_ROTATION 9601 #define EPSG_NAME_METHOD_LONGITUDE_ROTATION "Longitude rotation" #define EPSG_CODE_METHOD_VERTICAL_OFFSET 9616 #define EPSG_NAME_METHOD_VERTICAL_OFFSET "Vertical Offset" #define EPSG_CODE_METHOD_VERTICAL_OFFSET_AND_SLOPE 1046 #define EPSG_NAME_METHOD_VERTICAL_OFFSET_AND_SLOPE "Vertical Offset and Slope" #define EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS 9619 #define EPSG_NAME_METHOD_GEOGRAPHIC2D_OFFSETS "Geographic2D offsets" #define EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS 9618 #define EPSG_NAME_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS \ "Geographic2D with Height Offsets" #define EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS 9660 #define EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSETS "Geographic3D offsets" #define EPSG_CODE_METHOD_GEOGRAPHIC_GEOCENTRIC 9602 #define EPSG_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC \ "Geographic/geocentric conversions" #define EPSG_NAME_PARAMETER_LATITUDE_OFFSET "Latitude offset" #define EPSG_CODE_PARAMETER_LATITUDE_OFFSET 8601 #define EPSG_NAME_PARAMETER_LONGITUDE_OFFSET "Longitude offset" #define EPSG_CODE_PARAMETER_LONGITUDE_OFFSET 8602 #define EPSG_NAME_PARAMETER_VERTICAL_OFFSET "Vertical Offset" #define EPSG_CODE_PARAMETER_VERTICAL_OFFSET 8603 #define EPSG_NAME_PARAMETER_GEOID_UNDULATION "Geoid undulation" #define EPSG_CODE_PARAMETER_GEOID_UNDULATION 8604 #define EPSG_NAME_PARAMETER_INCLINATION_IN_LATITUDE "Inclination in latitude" #define EPSG_CODE_PARAMETER_INCLINATION_IN_LATITUDE 8730 #define EPSG_NAME_PARAMETER_INCLINATION_IN_LONGITUDE "Inclination in longitude" #define EPSG_CODE_PARAMETER_INCLINATION_IN_LONGITUDE 8731 #define EPSG_NAME_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS \ "EPSG code for Horizontal CRS" #define EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS 1037 /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION 9624 #define EPSG_NAME_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION \ "Affine parametric transformation" #define EPSG_NAME_PARAMETER_A0 "A0" #define EPSG_CODE_PARAMETER_A0 8623 #define EPSG_NAME_PARAMETER_A1 "A1" #define EPSG_CODE_PARAMETER_A1 8624 #define EPSG_NAME_PARAMETER_A2 "A2" #define EPSG_CODE_PARAMETER_A2 8625 #define EPSG_NAME_PARAMETER_B0 "B0" #define EPSG_CODE_PARAMETER_B0 8639 #define EPSG_NAME_PARAMETER_B1 "B1" #define EPSG_CODE_PARAMETER_B1 8640 #define EPSG_NAME_PARAMETER_B2 "B2" #define EPSG_CODE_PARAMETER_B2 8641 /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_SIMILARITY_TRANSFORMATION 9621 #define EPSG_NAME_METHOD_SIMILARITY_TRANSFORMATION "Similarity transformation" #define EPSG_NAME_PARAMETER_ORDINATE_1_EVAL_POINT_TARGET_CRS \ "Ordinate 1 of evaluation point in target CRS" #define EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT_TARGET_CRS 8621 #define EPSG_NAME_PARAMETER_ORDINATE_2_EVAL_POINT_TARGET_CRS \ "Ordinate 2 of evaluation point in target CRS" #define EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT_TARGET_CRS 8622 #define EPSG_NAME_PARAMETER_SCALE_FACTOR_FOR_SOURCE_CRS_AXES \ "Scale factor for source CRS axes" #define EPSG_CODE_PARAMETER_SCALE_FACTOR_FOR_SOURCE_CRS_AXES 1061 #define EPSG_NAME_PARAMETER_ROTATION_ANGLE_OF_SOURCE_CRS_AXES \ "Rotation angle of source CRS axes" #define EPSG_CODE_PARAMETER_ROTATION_ANGLE_OF_SOURCE_CRS_AXES 8614 /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_2D 9843 #define EPSG_NAME_METHOD_AXIS_ORDER_REVERSAL_2D "Axis Order Reversal (2D)" #define EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_3D 9844 #define EPSG_NAME_METHOD_AXIS_ORDER_REVERSAL_3D \ "Axis Order Reversal (Geographic3D horizontal)" /* ------------------------------------------------------------------------ */ #define EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL 1068 #define EPSG_NAME_METHOD_HEIGHT_DEPTH_REVERSAL "Height Depth Reversal" /* ------------------------------------------------------------------------ */ #define EPSG_NAME_METHOD_GEOCENTRIC_TOPOCENTRIC \ "Geocentric/topocentric conversions" #define EPSG_CODE_METHOD_GEOCENTRIC_TOPOCENTRIC 9836 #define EPSG_NAME_PARAMETER_GEOCENTRIC_X_TOPOCENTRIC_ORIGIN \ "Geocentric X of topocentric origin" #define EPSG_CODE_PARAMETER_GEOCENTRIC_X_TOPOCENTRIC_ORIGIN 8837 #define EPSG_NAME_PARAMETER_GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN \ "Geocentric Y of topocentric origin" #define EPSG_CODE_PARAMETER_GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN 8838 #define EPSG_NAME_PARAMETER_GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN \ "Geocentric Z of topocentric origin" #define EPSG_CODE_PARAMETER_GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN 8839 /* ------------------------------------------------------------------------ */ #define EPSG_NAME_METHOD_GEOGRAPHIC_TOPOCENTRIC \ "Geographic/topocentric conversions" #define EPSG_CODE_METHOD_GEOGRAPHIC_TOPOCENTRIC 9837 /* ------------------------------------------------------------------------ */ #define PROJ_WKT2_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC_LATITUDE \ "Geographic latitude / Geocentric latitude" #endif /* PROJ_CONSTANTS_INCLUDED */
h
PROJ
data/projects/PROJ/src/proj_mdist.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. */ /* Computes distance from equator along the meridian to latitude phi ** and inverse on unit ellipsoid. ** Precision commensurate with double precision. */ #include <math.h> #include <stdlib.h> #include "proj.h" #include "proj_internal.h" #define MAX_ITER 20 #define TOL 1e-14 namespace { // anonymous namespace struct MDIST { int nb; double es; double E; double b[1]; }; } // anonymous namespace void *proj_mdist_ini(double es) { double numf, numfi, twon1, denf, denfi, ens, T, twon; double den, El = 1., Es = 1.; double E[MAX_ITER] = {1.}; struct MDIST *b; int i, j; /* generate E(e^2) and its terms E[] */ ens = es; numf = twon1 = denfi = 1.; denf = 1.; twon = 4.; for (i = 1; i < MAX_ITER; ++i) { numf *= (twon1 * twon1); den = twon * denf * denf * twon1; T = numf / den; Es -= (E[i] = T * ens); ens *= es; twon *= 4.; denf *= ++denfi; twon1 += 2.; if (Es == El) /* jump out if no change */ break; El = Es; } if ((b = (struct MDIST *)malloc(sizeof(struct MDIST) + (i * sizeof(double)))) == nullptr) return (nullptr); b->nb = i - 1; b->es = es; b->E = Es; /* generate b_n coefficients--note: collapse with prefix ratios */ b->b[0] = Es = 1. - Es; numf = denf = 1.; numfi = 2.; denfi = 3.; for (j = 1; j < i; ++j) { Es -= E[j]; numf *= numfi; denf *= denfi; b->b[j] = Es * numf / denf; numfi += 2.; denfi += 2.; } return (b); } double proj_mdist(double phi, double sphi, double cphi, const void *data) { const struct MDIST *b = (const struct MDIST *)data; double sc, sum, sphi2, D; int i; sc = sphi * cphi; sphi2 = sphi * sphi; D = phi * b->E - b->es * sc / sqrt(1. - b->es * sphi2); sum = b->b[i = b->nb]; while (i) sum = b->b[--i] + sphi2 * sum; return (D + sc * sum); } double proj_inv_mdist(PJ_CONTEXT *ctx, double dist, const void *data) { const struct MDIST *b = (const struct MDIST *)data; double s, t, phi, k; int i; k = 1. / (1. - b->es); i = MAX_ITER; phi = dist; while (i--) { s = sin(phi); t = 1. - b->es * s * s; phi -= t = (proj_mdist(phi, s, cos(phi), b) - dist) * (t * sqrt(t)) * k; if (fabs(t) < TOL) /* that is no change */ return phi; } /* convergence failed */ proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return phi; }
cpp
PROJ
data/projects/PROJ/src/grids.cpp
/****************************************************************************** * Project: PROJ * Purpose: Grid management * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam <[email protected]> * Copyright (c) 2019, 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. *****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #define LRU11_DO_NOT_DEFINE_OUT_OF_CLASS_METHODS #include "grids.hpp" #include "filemanager.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/lru_cache.hpp" #include "proj_internal.h" #ifdef TIFF_ENABLED #include "tiffio.h" #endif #include <algorithm> #include <cmath> #include <cstdint> NS_PROJ_START using namespace internal; /************************************************************************/ /* swap_words() */ /* */ /* Convert the byte order of the given word(s) in place. */ /************************************************************************/ static const int byte_order_test = 1; #define IS_LSB (1 == ((const unsigned char *)(&byte_order_test))[0]) static void swap_words(void *dataIn, size_t word_size, size_t word_count) { unsigned char *data = static_cast<unsigned char *>(dataIn); for (size_t word = 0; word < word_count; word++) { for (size_t i = 0; i < word_size / 2; i++) { unsigned char t; t = data[i]; data[i] = data[word_size - i - 1]; data[word_size - i - 1] = t; } data += word_size; } } // --------------------------------------------------------------------------- void ExtentAndRes::computeInvRes() { invResX = 1.0 / resX; invResY = 1.0 / resY; } // --------------------------------------------------------------------------- bool ExtentAndRes::fullWorldLongitude() const { return isGeographic && east - west + resX >= 2 * M_PI - 1e-10; } // --------------------------------------------------------------------------- bool ExtentAndRes::contains(const ExtentAndRes &other) const { return other.west >= west && other.east <= east && other.south >= south && other.north <= north; } // --------------------------------------------------------------------------- bool ExtentAndRes::intersects(const ExtentAndRes &other) const { return other.west < east && west <= other.west && other.south < north && south <= other.north; } // --------------------------------------------------------------------------- Grid::Grid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn) : m_name(nameIn), m_width(widthIn), m_height(heightIn), m_extent(extentIn) { } // --------------------------------------------------------------------------- Grid::~Grid() = default; // --------------------------------------------------------------------------- VerticalShiftGrid::VerticalShiftGrid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn) : Grid(nameIn, widthIn, heightIn, extentIn) {} // --------------------------------------------------------------------------- VerticalShiftGrid::~VerticalShiftGrid() = default; // --------------------------------------------------------------------------- static ExtentAndRes globalExtent() { ExtentAndRes extent; extent.isGeographic = true; extent.west = -M_PI; extent.south = -M_PI / 2; extent.east = M_PI; extent.north = M_PI / 2; extent.resX = M_PI; extent.resY = M_PI / 2; extent.computeInvRes(); return extent; } // --------------------------------------------------------------------------- static const std::string emptyString; class NullVerticalShiftGrid : public VerticalShiftGrid { public: NullVerticalShiftGrid() : VerticalShiftGrid("null", 3, 3, globalExtent()) {} bool isNullGrid() const override { return true; } bool valueAt(int, int, float &out) const override; bool isNodata(float, double) const override { return false; } void reassign_context(PJ_CONTEXT *) override {} bool hasChanged() const override { return false; } const std::string &metadataItem(const std::string &, int) const override { return emptyString; } }; // --------------------------------------------------------------------------- bool NullVerticalShiftGrid::valueAt(int, int, float &out) const { out = 0.0f; return true; } // --------------------------------------------------------------------------- class FloatLineCache { private: typedef uint64_t Key; lru11::Cache<Key, std::vector<float>, lru11::NullLock> cache_; public: explicit FloatLineCache(size_t maxSize) : cache_(maxSize) {} void insert(uint32_t subgridIdx, uint32_t lineNumber, const std::vector<float> &data); const std::vector<float> *get(uint32_t subgridIdx, uint32_t lineNumber); }; // --------------------------------------------------------------------------- void FloatLineCache::insert(uint32_t subgridIdx, uint32_t lineNumber, const std::vector<float> &data) { cache_.insert((static_cast<uint64_t>(subgridIdx) << 32) | lineNumber, data); } // --------------------------------------------------------------------------- const std::vector<float> *FloatLineCache::get(uint32_t subgridIdx, uint32_t lineNumber) { return cache_.getPtr((static_cast<uint64_t>(subgridIdx) << 32) | lineNumber); } // --------------------------------------------------------------------------- class GTXVerticalShiftGrid : public VerticalShiftGrid { PJ_CONTEXT *m_ctx; std::unique_ptr<File> m_fp; std::unique_ptr<FloatLineCache> m_cache; mutable std::vector<float> m_buffer{}; GTXVerticalShiftGrid(const GTXVerticalShiftGrid &) = delete; GTXVerticalShiftGrid &operator=(const GTXVerticalShiftGrid &) = delete; public: explicit GTXVerticalShiftGrid(PJ_CONTEXT *ctx, std::unique_ptr<File> &&fp, const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn, std::unique_ptr<FloatLineCache> &&cache) : VerticalShiftGrid(nameIn, widthIn, heightIn, extentIn), m_ctx(ctx), m_fp(std::move(fp)), m_cache(std::move(cache)) {} ~GTXVerticalShiftGrid() override; bool valueAt(int x, int y, float &out) const override; bool isNodata(float val, double multiplier) const override; const std::string &metadataItem(const std::string &, int) const override { return emptyString; } static GTXVerticalShiftGrid *open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &name); void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; m_fp->reassign_context(ctx); } bool hasChanged() const override { return m_fp->hasChanged(); } }; // --------------------------------------------------------------------------- GTXVerticalShiftGrid::~GTXVerticalShiftGrid() = default; // --------------------------------------------------------------------------- GTXVerticalShiftGrid *GTXVerticalShiftGrid::open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &name) { unsigned char header[40]; /* -------------------------------------------------------------------- */ /* Read the header. */ /* -------------------------------------------------------------------- */ if (fp->read(header, sizeof(header)) != sizeof(header)) { pj_log(ctx, PJ_LOG_ERROR, _("Cannot read grid header")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } /* -------------------------------------------------------------------- */ /* Regularize fields of interest and extract. */ /* -------------------------------------------------------------------- */ if (IS_LSB) { swap_words(header + 0, 8, 4); swap_words(header + 32, 4, 2); } double xorigin, yorigin, xstep, ystep; int rows, columns; memcpy(&yorigin, header + 0, 8); memcpy(&xorigin, header + 8, 8); memcpy(&ystep, header + 16, 8); memcpy(&xstep, header + 24, 8); memcpy(&rows, header + 32, 4); memcpy(&columns, header + 36, 4); if (columns <= 0 || rows <= 0 || xorigin < -360 || xorigin > 360 || yorigin < -90 || yorigin > 90) { pj_log(ctx, PJ_LOG_ERROR, _("gtx file header has invalid extents, corrupt?")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } /* some GTX files come in 0-360 and we shift them back into the expected -180 to 180 range if possible. This does not solve problems with grids spanning the dateline. */ if (xorigin >= 180.0) xorigin -= 360.0; if (xorigin >= 0.0 && xorigin + xstep * columns > 180.0) { pj_log(ctx, PJ_LOG_DEBUG, "This GTX spans the dateline! This will cause problems."); } ExtentAndRes extent; extent.isGeographic = true; extent.west = xorigin * DEG_TO_RAD; extent.south = yorigin * DEG_TO_RAD; extent.resX = xstep * DEG_TO_RAD; extent.resY = ystep * DEG_TO_RAD; extent.east = (xorigin + xstep * (columns - 1)) * DEG_TO_RAD; extent.north = (yorigin + ystep * (rows - 1)) * DEG_TO_RAD; extent.computeInvRes(); // Cache up to 1 megapixel per GTX file const int maxLinesInCache = 1024 * 1024 / columns; auto cache = internal::make_unique<FloatLineCache>(maxLinesInCache); return new GTXVerticalShiftGrid(ctx, std::move(fp), name, columns, rows, extent, std::move(cache)); } // --------------------------------------------------------------------------- bool GTXVerticalShiftGrid::valueAt(int x, int y, float &out) const { assert(x >= 0 && y >= 0 && x < m_width && y < m_height); const std::vector<float> *pBuffer = m_cache->get(0, y); if (pBuffer == nullptr) { try { m_buffer.resize(m_width); } catch (const std::exception &e) { pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); return false; } const size_t nLineSizeInBytes = sizeof(float) * m_width; m_fp->seek(40 + nLineSizeInBytes * static_cast<unsigned long long>(y)); if (m_fp->read(&m_buffer[0], nLineSizeInBytes) != nLineSizeInBytes) { proj_context_errno_set( m_ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return false; } if (IS_LSB) { swap_words(&m_buffer[0], sizeof(float), m_width); } out = m_buffer[x]; try { m_cache->insert(0, y, m_buffer); } catch (const std::exception &e) { // Should normally not happen pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); } } else { out = (*pBuffer)[x]; } return true; } // --------------------------------------------------------------------------- bool GTXVerticalShiftGrid::isNodata(float val, double multiplier) const { /* nodata? */ /* GTX official nodata value if -88.88880f, but some grids also */ /* use other big values for nodata (e.g naptrans2008.gtx has */ /* nodata values like -2147479936), so test them too */ return val * multiplier > 1000 || val * multiplier < -1000 || val == -88.88880f; } // --------------------------------------------------------------------------- VerticalShiftGridSet::VerticalShiftGridSet() = default; // --------------------------------------------------------------------------- VerticalShiftGridSet::~VerticalShiftGridSet() = default; // --------------------------------------------------------------------------- static bool IsTIFF(size_t header_size, const unsigned char *header) { // Test combinations of signature for ClassicTIFF/BigTIFF little/big endian return header_size >= 4 && (((header[0] == 'I' && header[1] == 'I') || (header[0] == 'M' && header[1] == 'M')) && ((header[2] == 0x2A && header[3] == 0) || (header[3] == 0x2A && header[2] == 0) || (header[2] == 0x2B && header[3] == 0) || (header[3] == 0x2B && header[2] == 0))); } #ifdef TIFF_ENABLED // --------------------------------------------------------------------------- enum class TIFFDataType { Int16, UInt16, Int32, UInt32, Float32, Float64 }; // --------------------------------------------------------------------------- constexpr uint16_t TIFFTAG_GEOPIXELSCALE = 33550; constexpr uint16_t TIFFTAG_GEOTIEPOINTS = 33922; constexpr uint16_t TIFFTAG_GEOTRANSMATRIX = 34264; constexpr uint16_t TIFFTAG_GEOKEYDIRECTORY = 34735; constexpr uint16_t TIFFTAG_GEODOUBLEPARAMS = 34736; constexpr uint16_t TIFFTAG_GEOASCIIPARAMS = 34737; #ifndef TIFFTAG_GDAL_METADATA // Starting with libtiff > 4.1.0, those symbolic names are #define in tiff.h constexpr uint16_t TIFFTAG_GDAL_METADATA = 42112; constexpr uint16_t TIFFTAG_GDAL_NODATA = 42113; #endif // --------------------------------------------------------------------------- class BlockCache { public: void insert(uint32_t ifdIdx, uint32_t blockNumber, const std::vector<unsigned char> &data); const std::vector<unsigned char> *get(uint32_t ifdIdx, uint32_t blockNumber); private: typedef uint64_t Key; static constexpr int NUM_BLOCKS_AT_CROSSING_TILES = 4; static constexpr int MAX_SAMPLE_COUNT = 3; lru11::Cache<Key, std::vector<unsigned char>, lru11::NullLock> cache_{ NUM_BLOCKS_AT_CROSSING_TILES * MAX_SAMPLE_COUNT}; }; // --------------------------------------------------------------------------- void BlockCache::insert(uint32_t ifdIdx, uint32_t blockNumber, const std::vector<unsigned char> &data) { cache_.insert((static_cast<uint64_t>(ifdIdx) << 32) | blockNumber, data); } // --------------------------------------------------------------------------- const std::vector<unsigned char> *BlockCache::get(uint32_t ifdIdx, uint32_t blockNumber) { return cache_.getPtr((static_cast<uint64_t>(ifdIdx) << 32) | blockNumber); } // --------------------------------------------------------------------------- class GTiffGrid : public Grid { PJ_CONTEXT *m_ctx; // owned by the belonging GTiffDataset TIFF *m_hTIFF; // owned by the belonging GTiffDataset BlockCache &m_cache; // owned by the belonging GTiffDataset File *m_fp; // owned by the belonging GTiffDataset uint32_t m_ifdIdx; TIFFDataType m_dt; uint16_t m_samplesPerPixel; uint16_t m_planarConfig; // set to -1 if m_samplesPerPixel == 1 bool m_bottomUp; toff_t m_dirOffset; bool m_tiled; uint32_t m_blockWidth = 0; uint32_t m_blockHeight = 0; mutable std::vector<unsigned char> m_buffer{}; mutable uint32_t m_bufferBlockId = std::numeric_limits<uint32_t>::max(); unsigned m_blocksPerRow = 0; unsigned m_blocksPerCol = 0; unsigned m_blocks = 0; std::vector<double> m_adfOffset{}; std::vector<double> m_adfScale{}; std::map<std::pair<int, std::string>, std::string> m_metadata{}; bool m_hasNodata = false; bool m_blockIs256Pixel = false; bool m_isSingleBlock = false; float m_noData = 0.0f; uint32_t m_subfileType = 0; GTiffGrid(const GTiffGrid &) = delete; GTiffGrid &operator=(const GTiffGrid &) = delete; template <class T> float readValue(const std::vector<unsigned char> &buffer, uint32_t offsetInBlock, uint16_t sample) const; public: GTiffGrid(PJ_CONTEXT *ctx, TIFF *hTIFF, BlockCache &cache, File *fp, uint32_t ifdIdx, const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn, TIFFDataType dtIn, uint16_t samplesPerPixelIn, uint16_t planarConfig, bool bottomUpIn); ~GTiffGrid() override; uint16_t samplesPerPixel() const { return m_samplesPerPixel; } bool valueAt(uint16_t sample, int x, int y, float &out) const; bool valuesAt(int x_start, int y_start, int x_count, int y_count, int sample_count, const int *sample_idx, float *out, bool &nodataFound) const; bool isNodata(float val) const; const std::string &metadataItem(const std::string &key, int sample = -1) const override; uint32_t subfileType() const { return m_subfileType; } void reassign_context(PJ_CONTEXT *ctx) { m_ctx = ctx; } bool hasChanged() const override { return m_fp->hasChanged(); } }; // --------------------------------------------------------------------------- GTiffGrid::GTiffGrid(PJ_CONTEXT *ctx, TIFF *hTIFF, BlockCache &cache, File *fp, uint32_t ifdIdx, const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn, TIFFDataType dtIn, uint16_t samplesPerPixelIn, uint16_t planarConfig, bool bottomUpIn) : Grid(nameIn, widthIn, heightIn, extentIn), m_ctx(ctx), m_hTIFF(hTIFF), m_cache(cache), m_fp(fp), m_ifdIdx(ifdIdx), m_dt(dtIn), m_samplesPerPixel(samplesPerPixelIn), m_planarConfig(samplesPerPixelIn == 1 ? static_cast<uint16_t>(-1) : planarConfig), m_bottomUp(bottomUpIn), m_dirOffset(TIFFCurrentDirOffset(hTIFF)), m_tiled(TIFFIsTiled(hTIFF) != 0) { if (m_tiled) { TIFFGetField(m_hTIFF, TIFFTAG_TILEWIDTH, &m_blockWidth); TIFFGetField(m_hTIFF, TIFFTAG_TILELENGTH, &m_blockHeight); } else { m_blockWidth = widthIn; TIFFGetField(m_hTIFF, TIFFTAG_ROWSPERSTRIP, &m_blockHeight); if (m_blockHeight > static_cast<unsigned>(m_height)) m_blockHeight = m_height; } m_blockIs256Pixel = (m_blockWidth == 256) && (m_blockHeight == 256); m_isSingleBlock = (m_blockWidth == static_cast<uint32_t>(m_width)) && (m_blockHeight == static_cast<uint32_t>(m_height)); TIFFGetField(m_hTIFF, TIFFTAG_SUBFILETYPE, &m_subfileType); m_blocksPerRow = (m_width + m_blockWidth - 1) / m_blockWidth; m_blocksPerCol = (m_height + m_blockHeight - 1) / m_blockHeight; m_blocks = m_blocksPerRow * m_blocksPerCol; const char *text = nullptr; // Poor-man XML parsing of TIFFTAG_GDAL_METADATA tag. Hopefully good // enough for our purposes. if (TIFFGetField(m_hTIFF, TIFFTAG_GDAL_METADATA, &text)) { const char *ptr = text; while (true) { ptr = strstr(ptr, "<Item "); if (ptr == nullptr) break; const char *endTag = strchr(ptr, '>'); if (endTag == nullptr) break; const char *endValue = strchr(endTag, '<'); if (endValue == nullptr) break; std::string tag; tag.append(ptr, endTag - ptr); std::string value; value.append(endTag + 1, endValue - (endTag + 1)); std::string gridName; auto namePos = tag.find("name=\""); if (namePos == std::string::npos) break; { namePos += strlen("name=\""); const auto endQuote = tag.find('"', namePos); if (endQuote == std::string::npos) break; gridName = tag.substr(namePos, endQuote - namePos); } const auto samplePos = tag.find("sample=\""); int sample = -1; if (samplePos != std::string::npos) { sample = atoi(tag.c_str() + samplePos + strlen("sample=\"")); } m_metadata[std::pair<int, std::string>(sample, gridName)] = value; auto rolePos = tag.find("role=\""); if (rolePos != std::string::npos) { rolePos += strlen("role=\""); const auto endQuote = tag.find('"', rolePos); if (endQuote == std::string::npos) break; const auto role = tag.substr(rolePos, endQuote - rolePos); if (role == "offset") { if (sample >= 0 && static_cast<unsigned>(sample) <= m_samplesPerPixel) { try { if (m_adfOffset.empty()) { m_adfOffset.resize(m_samplesPerPixel); m_adfScale.resize(m_samplesPerPixel, 1); } m_adfOffset[sample] = c_locale_stod(value); } catch (const std::exception &) { } } } else if (role == "scale") { if (sample >= 0 && static_cast<unsigned>(sample) <= m_samplesPerPixel) { try { if (m_adfOffset.empty()) { m_adfOffset.resize(m_samplesPerPixel); m_adfScale.resize(m_samplesPerPixel, 1); } m_adfScale[sample] = c_locale_stod(value); } catch (const std::exception &) { } } } } ptr = endValue + 1; } } if (TIFFGetField(m_hTIFF, TIFFTAG_GDAL_NODATA, &text)) { try { m_noData = static_cast<float>(c_locale_stod(text)); m_hasNodata = true; } catch (const std::exception &) { } } auto oIter = m_metadata.find(std::pair<int, std::string>(-1, "grid_name")); if (oIter != m_metadata.end()) { m_name += ", " + oIter->second; } } // --------------------------------------------------------------------------- GTiffGrid::~GTiffGrid() = default; // --------------------------------------------------------------------------- template <class T> float GTiffGrid::readValue(const std::vector<unsigned char> &buffer, uint32_t offsetInBlock, uint16_t sample) const { const auto ptr = reinterpret_cast<const T *>(buffer.data()); assert(offsetInBlock < buffer.size() / sizeof(T)); const auto val = ptr[offsetInBlock]; if ((!m_hasNodata || static_cast<float>(val) != m_noData) && sample < m_adfScale.size()) { double scale = m_adfScale[sample]; double offset = m_adfOffset[sample]; return static_cast<float>(val * scale + offset); } else { return static_cast<float>(val); } } // --------------------------------------------------------------------------- bool GTiffGrid::valueAt(uint16_t sample, int x, int yFromBottom, float &out) const { assert(x >= 0 && yFromBottom >= 0 && x < m_width && yFromBottom < m_height); assert(sample < m_samplesPerPixel); // All non-TIFF grids have the first rows in the file being the one // corresponding to the southern-most row. In GeoTIFF, the convention is // *generally* different (when m_bottomUp == false), TIFF being an // image-oriented image. If m_bottomUp == true, then we had GeoTIFF hints // that the first row of the image is the southern-most. const int yTIFF = m_bottomUp ? yFromBottom : m_height - 1 - yFromBottom; int blockXOff; int blockYOff; uint32_t blockId; if (m_blockIs256Pixel) { const int blockX = x / 256; blockXOff = x % 256; const int blockY = yTIFF / 256; blockYOff = yTIFF % 256; blockId = blockY * m_blocksPerRow + blockX; } else if (m_isSingleBlock) { blockXOff = x; blockYOff = yTIFF; blockId = 0; } else { const int blockX = x / m_blockWidth; blockXOff = x % m_blockWidth; const int blockY = yTIFF / m_blockHeight; blockYOff = yTIFF % m_blockHeight; blockId = blockY * m_blocksPerRow + blockX; } if (m_planarConfig == PLANARCONFIG_SEPARATE) { blockId += sample * m_blocks; } const std::vector<unsigned char> *pBuffer = blockId == m_bufferBlockId ? &m_buffer : m_cache.get(m_ifdIdx, blockId); if (pBuffer == nullptr) { if (TIFFCurrentDirOffset(m_hTIFF) != m_dirOffset && !TIFFSetSubDirectory(m_hTIFF, m_dirOffset)) { return false; } if (m_buffer.empty()) { const auto blockSize = static_cast<size_t>( m_tiled ? TIFFTileSize64(m_hTIFF) : TIFFStripSize64(m_hTIFF)); try { m_buffer.resize(blockSize); } catch (const std::exception &e) { pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); return false; } } if (m_tiled) { if (TIFFReadEncodedTile(m_hTIFF, blockId, m_buffer.data(), m_buffer.size()) == -1) { return false; } } else { if (TIFFReadEncodedStrip(m_hTIFF, blockId, m_buffer.data(), m_buffer.size()) == -1) { return false; } } pBuffer = &m_buffer; try { m_cache.insert(m_ifdIdx, blockId, m_buffer); m_bufferBlockId = blockId; } catch (const std::exception &e) { // Should normally not happen pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); } } uint32_t offsetInBlock; if (m_blockIs256Pixel) offsetInBlock = blockXOff + blockYOff * 256U; else offsetInBlock = blockXOff + blockYOff * m_blockWidth; if (m_planarConfig == PLANARCONFIG_CONTIG) offsetInBlock = offsetInBlock * m_samplesPerPixel + sample; switch (m_dt) { case TIFFDataType::Int16: out = readValue<short>(*pBuffer, offsetInBlock, sample); break; case TIFFDataType::UInt16: out = readValue<unsigned short>(*pBuffer, offsetInBlock, sample); break; case TIFFDataType::Int32: out = readValue<int>(*pBuffer, offsetInBlock, sample); break; case TIFFDataType::UInt32: out = readValue<unsigned int>(*pBuffer, offsetInBlock, sample); break; case TIFFDataType::Float32: out = readValue<float>(*pBuffer, offsetInBlock, sample); break; case TIFFDataType::Float64: out = readValue<double>(*pBuffer, offsetInBlock, sample); break; } return true; } // --------------------------------------------------------------------------- bool GTiffGrid::valuesAt(int x_start, int y_start, int x_count, int y_count, int sample_count, const int *sample_idx, float *out, bool &nodataFound) const { const auto getTIFFRow = [this](int y) { return m_bottomUp ? y : m_height - 1 - y; }; nodataFound = false; if (m_blockIs256Pixel && m_planarConfig == PLANARCONFIG_CONTIG && m_dt == TIFFDataType::Float32 && (x_start / 256) == (x_start + x_count - 1) / 256 && getTIFFRow(y_start) / 256 == getTIFFRow(y_start + y_count - 1) / 256 && !m_hasNodata && m_adfScale.empty() && (sample_count == 1 || (sample_count == 2 && sample_idx[1] == sample_idx[0] + 1) || (sample_count == 3 && sample_idx[1] == sample_idx[0] + 1 && sample_idx[2] == sample_idx[0] + 2))) { const int yTIFF = m_bottomUp ? y_start : m_height - (y_start + y_count); int blockXOff; int blockYOff; uint32_t blockId; const int blockX = x_start / 256; blockXOff = x_start % 256; const int blockY = yTIFF / 256; blockYOff = yTIFF % 256; blockId = blockY * m_blocksPerRow + blockX; const std::vector<unsigned char> *pBuffer = blockId == m_bufferBlockId ? &m_buffer : m_cache.get(m_ifdIdx, blockId); if (pBuffer == nullptr) { if (TIFFCurrentDirOffset(m_hTIFF) != m_dirOffset && !TIFFSetSubDirectory(m_hTIFF, m_dirOffset)) { return false; } if (m_buffer.empty()) { const auto blockSize = static_cast<size_t>(m_tiled ? TIFFTileSize64(m_hTIFF) : TIFFStripSize64(m_hTIFF)); try { m_buffer.resize(blockSize); } catch (const std::exception &e) { pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); return false; } } if (m_tiled) { if (TIFFReadEncodedTile(m_hTIFF, blockId, m_buffer.data(), m_buffer.size()) == -1) { return false; } } else { if (TIFFReadEncodedStrip(m_hTIFF, blockId, m_buffer.data(), m_buffer.size()) == -1) { return false; } } pBuffer = &m_buffer; try { m_cache.insert(m_ifdIdx, blockId, m_buffer); m_bufferBlockId = blockId; } catch (const std::exception &e) { // Should normally not happen pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); } } uint32_t offsetInBlockStart = blockXOff + blockYOff * 256U; if (sample_count == m_samplesPerPixel) { const int sample_count_mul_x_count = sample_count * x_count; for (int y = 0; y < y_count; ++y) { uint32_t offsetInBlock = (offsetInBlockStart + 256 * (m_bottomUp ? y : y_count - 1 - y)) * m_samplesPerPixel + sample_idx[0]; memcpy(out, reinterpret_cast<const float *>(pBuffer->data()) + offsetInBlock, sample_count_mul_x_count * sizeof(float)); out += sample_count_mul_x_count; } } else { switch (sample_count) { case 1: for (int y = 0; y < y_count; ++y) { uint32_t offsetInBlock = (offsetInBlockStart + 256 * (m_bottomUp ? y : y_count - 1 - y)) * m_samplesPerPixel + sample_idx[0]; const float *in_ptr = reinterpret_cast<const float *>(pBuffer->data()) + offsetInBlock; for (int x = 0; x < x_count; ++x) { memcpy(out, in_ptr, sample_count * sizeof(float)); in_ptr += m_samplesPerPixel; out += sample_count; } } break; case 2: for (int y = 0; y < y_count; ++y) { uint32_t offsetInBlock = (offsetInBlockStart + 256 * (m_bottomUp ? y : y_count - 1 - y)) * m_samplesPerPixel + sample_idx[0]; const float *in_ptr = reinterpret_cast<const float *>(pBuffer->data()) + offsetInBlock; for (int x = 0; x < x_count; ++x) { memcpy(out, in_ptr, sample_count * sizeof(float)); in_ptr += m_samplesPerPixel; out += sample_count; } } break; case 3: for (int y = 0; y < y_count; ++y) { uint32_t offsetInBlock = (offsetInBlockStart + 256 * (m_bottomUp ? y : y_count - 1 - y)) * m_samplesPerPixel + sample_idx[0]; const float *in_ptr = reinterpret_cast<const float *>(pBuffer->data()) + offsetInBlock; for (int x = 0; x < x_count; ++x) { memcpy(out, in_ptr, sample_count * sizeof(float)); in_ptr += m_samplesPerPixel; out += sample_count; } } break; } } return true; } for (int y = y_start; y < y_start + y_count; ++y) { for (int x = x_start; x < x_start + x_count; ++x) { for (int isample = 0; isample < sample_count; ++isample) { if (!valueAt(static_cast<uint16_t>(sample_idx[isample]), x, y, *out)) return false; if (isNodata(*out)) { nodataFound = true; } ++out; } } } return true; } // --------------------------------------------------------------------------- bool GTiffGrid::isNodata(float val) const { return (m_hasNodata && val == m_noData) || std::isnan(val); } // --------------------------------------------------------------------------- const std::string &GTiffGrid::metadataItem(const std::string &key, int sample) const { auto iter = m_metadata.find(std::pair<int, std::string>(sample, key)); if (iter == m_metadata.end()) { return emptyString; } return iter->second; } // --------------------------------------------------------------------------- class GTiffDataset { PJ_CONTEXT *m_ctx; std::unique_ptr<File> m_fp; TIFF *m_hTIFF = nullptr; bool m_hasNextGrid = false; uint32_t m_ifdIdx = 0; toff_t m_nextDirOffset = 0; std::string m_filename{}; BlockCache m_cache{}; GTiffDataset(const GTiffDataset &) = delete; GTiffDataset &operator=(const GTiffDataset &) = delete; // libtiff I/O routines static tsize_t tiffReadProc(thandle_t fd, tdata_t buf, tsize_t size) { GTiffDataset *self = static_cast<GTiffDataset *>(fd); return self->m_fp->read(buf, size); } static tsize_t tiffWriteProc(thandle_t, tdata_t, tsize_t) { assert(false); return 0; } static toff_t tiffSeekProc(thandle_t fd, toff_t off, int whence) { GTiffDataset *self = static_cast<GTiffDataset *>(fd); if (self->m_fp->seek(off, whence)) return static_cast<toff_t>(self->m_fp->tell()); else return static_cast<toff_t>(-1); } static int tiffCloseProc(thandle_t) { // done in destructor return 0; } static toff_t tiffSizeProc(thandle_t fd) { GTiffDataset *self = static_cast<GTiffDataset *>(fd); const auto old_off = self->m_fp->tell(); self->m_fp->seek(0, SEEK_END); const auto file_size = static_cast<toff_t>(self->m_fp->tell()); self->m_fp->seek(old_off); return file_size; } static int tiffMapProc(thandle_t, tdata_t *, toff_t *) { return (0); } static void tiffUnmapProc(thandle_t, tdata_t, toff_t) {} public: GTiffDataset(PJ_CONTEXT *ctx, std::unique_ptr<File> &&fp) : m_ctx(ctx), m_fp(std::move(fp)) {} virtual ~GTiffDataset(); bool openTIFF(const std::string &filename); std::unique_ptr<GTiffGrid> nextGrid(); void reassign_context(PJ_CONTEXT *ctx) { m_ctx = ctx; m_fp->reassign_context(ctx); } }; // --------------------------------------------------------------------------- GTiffDataset::~GTiffDataset() { if (m_hTIFF) TIFFClose(m_hTIFF); } // --------------------------------------------------------------------------- class OneTimeTIFFTagInit { static TIFFExtendProc ParentExtender; // Function called by libtiff when initializing a TIFF directory static void GTiffTagExtender(TIFF *tif) { static const TIFFFieldInfo xtiffFieldInfo[] = { // GeoTIFF tags {TIFFTAG_GEOPIXELSCALE, -1, -1, TIFF_DOUBLE, FIELD_CUSTOM, TRUE, TRUE, const_cast<char *>("GeoPixelScale")}, {TIFFTAG_GEOTIEPOINTS, -1, -1, TIFF_DOUBLE, FIELD_CUSTOM, TRUE, TRUE, const_cast<char *>("GeoTiePoints")}, {TIFFTAG_GEOTRANSMATRIX, -1, -1, TIFF_DOUBLE, FIELD_CUSTOM, TRUE, TRUE, const_cast<char *>("GeoTransformationMatrix")}, {TIFFTAG_GEOKEYDIRECTORY, -1, -1, TIFF_SHORT, FIELD_CUSTOM, TRUE, TRUE, const_cast<char *>("GeoKeyDirectory")}, {TIFFTAG_GEODOUBLEPARAMS, -1, -1, TIFF_DOUBLE, FIELD_CUSTOM, TRUE, TRUE, const_cast<char *>("GeoDoubleParams")}, {TIFFTAG_GEOASCIIPARAMS, -1, -1, TIFF_ASCII, FIELD_CUSTOM, TRUE, FALSE, const_cast<char *>("GeoASCIIParams")}, // GDAL tags {TIFFTAG_GDAL_METADATA, -1, -1, TIFF_ASCII, FIELD_CUSTOM, TRUE, FALSE, const_cast<char *>("GDALMetadata")}, {TIFFTAG_GDAL_NODATA, -1, -1, TIFF_ASCII, FIELD_CUSTOM, TRUE, FALSE, const_cast<char *>("GDALNoDataValue")}, }; if (ParentExtender) (*ParentExtender)(tif); TIFFMergeFieldInfo(tif, xtiffFieldInfo, sizeof(xtiffFieldInfo) / sizeof(xtiffFieldInfo[0])); } public: OneTimeTIFFTagInit() { assert(ParentExtender == nullptr); // Install our TIFF tag extender ParentExtender = TIFFSetTagExtender(GTiffTagExtender); } }; TIFFExtendProc OneTimeTIFFTagInit::ParentExtender = nullptr; // --------------------------------------------------------------------------- bool GTiffDataset::openTIFF(const std::string &filename) { static OneTimeTIFFTagInit oneTimeTIFFTagInit; m_hTIFF = TIFFClientOpen(filename.c_str(), "r", static_cast<thandle_t>(this), GTiffDataset::tiffReadProc, GTiffDataset::tiffWriteProc, GTiffDataset::tiffSeekProc, GTiffDataset::tiffCloseProc, GTiffDataset::tiffSizeProc, GTiffDataset::tiffMapProc, GTiffDataset::tiffUnmapProc); m_filename = filename; m_hasNextGrid = true; return m_hTIFF != nullptr; } // --------------------------------------------------------------------------- std::unique_ptr<GTiffGrid> GTiffDataset::nextGrid() { if (!m_hasNextGrid) return nullptr; if (m_nextDirOffset) { TIFFSetSubDirectory(m_hTIFF, m_nextDirOffset); } uint32_t width = 0; uint32_t height = 0; TIFFGetField(m_hTIFF, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(m_hTIFF, TIFFTAG_IMAGELENGTH, &height); if (width == 0 || height == 0 || width > INT_MAX || height > INT_MAX) { pj_log(m_ctx, PJ_LOG_ERROR, _("Invalid image size")); return nullptr; } uint16_t samplesPerPixel = 0; if (!TIFFGetField(m_hTIFF, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel)) { pj_log(m_ctx, PJ_LOG_ERROR, _("Missing SamplesPerPixel tag")); return nullptr; } if (samplesPerPixel == 0) { pj_log(m_ctx, PJ_LOG_ERROR, _("Invalid SamplesPerPixel value")); return nullptr; } uint16_t bitsPerSample = 0; if (!TIFFGetField(m_hTIFF, TIFFTAG_BITSPERSAMPLE, &bitsPerSample)) { pj_log(m_ctx, PJ_LOG_ERROR, _("Missing BitsPerSample tag")); return nullptr; } uint16_t planarConfig = 0; if (!TIFFGetField(m_hTIFF, TIFFTAG_PLANARCONFIG, &planarConfig)) { pj_log(m_ctx, PJ_LOG_ERROR, _("Missing PlanarConfig tag")); return nullptr; } uint16_t sampleFormat = 0; if (!TIFFGetField(m_hTIFF, TIFFTAG_SAMPLEFORMAT, &sampleFormat)) { pj_log(m_ctx, PJ_LOG_ERROR, _("Missing SampleFormat tag")); return nullptr; } TIFFDataType dt; if (sampleFormat == SAMPLEFORMAT_INT && bitsPerSample == 16) dt = TIFFDataType::Int16; else if (sampleFormat == SAMPLEFORMAT_UINT && bitsPerSample == 16) dt = TIFFDataType::UInt16; else if (sampleFormat == SAMPLEFORMAT_INT && bitsPerSample == 32) dt = TIFFDataType::Int32; else if (sampleFormat == SAMPLEFORMAT_UINT && bitsPerSample == 32) dt = TIFFDataType::UInt32; else if (sampleFormat == SAMPLEFORMAT_IEEEFP && bitsPerSample == 32) dt = TIFFDataType::Float32; else if (sampleFormat == SAMPLEFORMAT_IEEEFP && bitsPerSample == 64) dt = TIFFDataType::Float64; else { pj_log(m_ctx, PJ_LOG_ERROR, _("Unsupported combination of SampleFormat " "and BitsPerSample values")); return nullptr; } uint16_t photometric = PHOTOMETRIC_MINISBLACK; if (!TIFFGetField(m_hTIFF, TIFFTAG_PHOTOMETRIC, &photometric)) photometric = PHOTOMETRIC_MINISBLACK; if (photometric != PHOTOMETRIC_MINISBLACK) { pj_log(m_ctx, PJ_LOG_ERROR, _("Unsupported Photometric value")); return nullptr; } uint16_t compression = COMPRESSION_NONE; if (!TIFFGetField(m_hTIFF, TIFFTAG_COMPRESSION, &compression)) compression = COMPRESSION_NONE; if (compression != COMPRESSION_NONE && !TIFFIsCODECConfigured(compression)) { pj_log(m_ctx, PJ_LOG_ERROR, _("Cannot open TIFF file due to missing codec.")); return nullptr; } // We really don't want to try dealing with old-JPEG images if (compression == COMPRESSION_OJPEG) { pj_log(m_ctx, PJ_LOG_ERROR, _("Unsupported compression method.")); return nullptr; } const auto blockSize = TIFFIsTiled(m_hTIFF) ? TIFFTileSize64(m_hTIFF) : TIFFStripSize64(m_hTIFF); if (blockSize == 0 || blockSize > 64 * 1024 * 2014) { pj_log(m_ctx, PJ_LOG_ERROR, _("Unsupported block size.")); return nullptr; } unsigned short count = 0; unsigned short *geokeys = nullptr; bool pixelIsArea = false; ExtentAndRes extent; extent.isGeographic = true; if (!TIFFGetField(m_hTIFF, TIFFTAG_GEOKEYDIRECTORY, &count, &geokeys)) { pj_log(m_ctx, PJ_LOG_TRACE, "No GeoKeys tag"); } else { if (count < 4 || (count % 4) != 0) { pj_log(m_ctx, PJ_LOG_ERROR, _("Wrong number of values in GeoKeys tag")); return nullptr; } if (geokeys[0] != 1) { pj_log(m_ctx, PJ_LOG_ERROR, _("Unsupported GeoTIFF major version")); return nullptr; } // We only know that we support GeoTIFF 1.0 and 1.1 at that time if (geokeys[1] != 1 || geokeys[2] > 1) { pj_log(m_ctx, PJ_LOG_TRACE, "GeoTIFF %d.%d possibly not handled", geokeys[1], geokeys[2]); } for (unsigned int i = 4; i + 3 < count; i += 4) { constexpr unsigned short GTModelTypeGeoKey = 1024; constexpr unsigned short ModelTypeProjected = 1; constexpr unsigned short ModelTypeGeographic = 2; constexpr unsigned short GTRasterTypeGeoKey = 1025; constexpr unsigned short RasterPixelIsArea = 1; // constexpr unsigned short RasterPixelIsPoint = 2; if (geokeys[i] == GTModelTypeGeoKey) { if (geokeys[i + 3] == ModelTypeProjected) { extent.isGeographic = false; } else if (geokeys[i + 3] != ModelTypeGeographic) { pj_log(m_ctx, PJ_LOG_ERROR, _("Only GTModelTypeGeoKey = " "ModelTypeGeographic or ModelTypeProjected are " "supported")); return nullptr; } } else if (geokeys[i] == GTRasterTypeGeoKey) { if (geokeys[i + 3] == RasterPixelIsArea) { pixelIsArea = true; } } } } double hRes = 0; double vRes = 0; double west = 0; double north = 0; double *matrix = nullptr; if (TIFFGetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX, &count, &matrix) && count == 16) { // If using GDAL to produce a bottom-up georeferencing, it will produce // a GeoTransformationMatrix, since negative values in GeoPixelScale // have historically been implementation bugs. if (matrix[1] != 0 || matrix[4] != 0) { pj_log(m_ctx, PJ_LOG_ERROR, _("Rotational terms not supported in " "GeoTransformationMatrix tag")); return nullptr; } west = matrix[3]; hRes = matrix[0]; north = matrix[7]; vRes = -matrix[5]; // negation to simulate GeoPixelScale convention } else { double *geopixelscale = nullptr; if (TIFFGetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE, &count, &geopixelscale) != 1) { pj_log(m_ctx, PJ_LOG_ERROR, _("No GeoPixelScale tag")); return nullptr; } if (count != 3) { pj_log(m_ctx, PJ_LOG_ERROR, _("Wrong number of values in GeoPixelScale tag")); return nullptr; } hRes = geopixelscale[0]; vRes = geopixelscale[1]; double *geotiepoints = nullptr; if (TIFFGetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS, &count, &geotiepoints) != 1) { pj_log(m_ctx, PJ_LOG_ERROR, _("No GeoTiePoints tag")); return nullptr; } if (count != 6) { pj_log(m_ctx, PJ_LOG_ERROR, _("Wrong number of values in GeoTiePoints tag")); return nullptr; } west = geotiepoints[3] - geotiepoints[0] * hRes; north = geotiepoints[4] + geotiepoints[1] * vRes; } if (pixelIsArea) { west += 0.5 * hRes; north -= 0.5 * vRes; } const double mulFactor = extent.isGeographic ? DEG_TO_RAD : 1; extent.west = west * mulFactor; extent.north = north * mulFactor; extent.resX = hRes * mulFactor; extent.resY = fabs(vRes) * mulFactor; extent.east = (west + hRes * (width - 1)) * mulFactor; extent.south = (north - vRes * (height - 1)) * mulFactor; extent.computeInvRes(); if (vRes < 0) { std::swap(extent.north, extent.south); } if (!((!extent.isGeographic || (fabs(extent.west) <= 4 * M_PI && fabs(extent.east) <= 4 * M_PI && fabs(extent.north) <= M_PI + 1e-5 && fabs(extent.south) <= M_PI + 1e-5)) && extent.west < extent.east && extent.south < extent.north && extent.resX > 1e-10 && extent.resY > 1e-10)) { pj_log(m_ctx, PJ_LOG_ERROR, _("Inconsistent georeferencing for %s"), m_filename.c_str()); return nullptr; } auto ret = std::unique_ptr<GTiffGrid>(new GTiffGrid( m_ctx, m_hTIFF, m_cache, m_fp.get(), m_ifdIdx, m_filename, width, height, extent, dt, samplesPerPixel, planarConfig, vRes < 0)); m_ifdIdx++; m_hasNextGrid = TIFFReadDirectory(m_hTIFF) != 0; m_nextDirOffset = TIFFCurrentDirOffset(m_hTIFF); return ret; } // --------------------------------------------------------------------------- class GTiffVGridShiftSet : public VerticalShiftGridSet { std::unique_ptr<GTiffDataset> m_GTiffDataset; GTiffVGridShiftSet(PJ_CONTEXT *ctx, std::unique_ptr<File> &&fp) : m_GTiffDataset(new GTiffDataset(ctx, std::move(fp))) {} public: ~GTiffVGridShiftSet() override; static std::unique_ptr<GTiffVGridShiftSet> open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename); void reassign_context(PJ_CONTEXT *ctx) override { VerticalShiftGridSet::reassign_context(ctx); if (m_GTiffDataset) { m_GTiffDataset->reassign_context(ctx); } } bool reopen(PJ_CONTEXT *ctx) override { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s has changed. Re-loading it", m_name.c_str()); m_grids.clear(); m_GTiffDataset.reset(); auto fp = FileManager::open_resource_file(ctx, m_name.c_str()); if (!fp) { return false; } auto newGS = open(ctx, std::move(fp), m_name); if (newGS) { m_grids = std::move(newGS->m_grids); m_GTiffDataset = std::move(newGS->m_GTiffDataset); } return !m_grids.empty(); } }; #endif // TIFF_ENABLED // --------------------------------------------------------------------------- template <class GridType, class GenericGridType> static void insertIntoHierarchy(PJ_CONTEXT *ctx, std::unique_ptr<GridType> &&grid, const std::string &gridName, const std::string &parentName, std::vector<std::unique_ptr<GenericGridType>> &topGrids, std::map<std::string, GridType *> &mapGrids) { const auto &extent = grid->extentAndRes(); // If we have one or both of grid_name and parent_grid_name, try to use // the names to recreate the hierarchy if (!gridName.empty()) { if (mapGrids.find(gridName) != mapGrids.end()) { pj_log(ctx, PJ_LOG_DEBUG, "Several grids called %s found!", gridName.c_str()); } mapGrids[gridName] = grid.get(); } if (!parentName.empty()) { auto iter = mapGrids.find(parentName); if (iter == mapGrids.end()) { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s refers to non-existing parent %s. " "Using bounding-box method.", gridName.c_str(), parentName.c_str()); } else { if (iter->second->extentAndRes().contains(extent)) { iter->second->m_children.emplace_back(std::move(grid)); return; } else { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s refers to parent %s, but its extent is " "not included in it. Using bounding-box method.", gridName.c_str(), parentName.c_str()); } } } else if (!gridName.empty()) { topGrids.emplace_back(std::move(grid)); return; } const std::string &type = grid->metadataItem("TYPE"); // Fallback to analyzing spatial extents for (const auto &candidateParent : topGrids) { if (!type.empty() && candidateParent->metadataItem("TYPE") != type) { continue; } const auto &candidateParentExtent = candidateParent->extentAndRes(); if (candidateParentExtent.contains(extent)) { static_cast<GridType *>(candidateParent.get()) ->insertGrid(ctx, std::move(grid)); return; } else if (candidateParentExtent.intersects(extent)) { pj_log(ctx, PJ_LOG_DEBUG, "Partially intersecting grids found!"); } } topGrids.emplace_back(std::move(grid)); } #ifdef TIFF_ENABLED // --------------------------------------------------------------------------- class GTiffVGrid : public VerticalShiftGrid { friend void insertIntoHierarchy<GTiffVGrid, VerticalShiftGrid>( PJ_CONTEXT *ctx, std::unique_ptr<GTiffVGrid> &&grid, const std::string &gridName, const std::string &parentName, std::vector<std::unique_ptr<VerticalShiftGrid>> &topGrids, std::map<std::string, GTiffVGrid *> &mapGrids); std::unique_ptr<GTiffGrid> m_grid; uint16_t m_idxSample; public: GTiffVGrid(std::unique_ptr<GTiffGrid> &&grid, uint16_t idxSample); ~GTiffVGrid() override; bool valueAt(int x, int y, float &out) const override { return m_grid->valueAt(m_idxSample, x, y, out); } bool isNodata(float val, double /* multiplier */) const override { return m_grid->isNodata(val); } const std::string &metadataItem(const std::string &key, int sample = -1) const override { return m_grid->metadataItem(key, sample); } void insertGrid(PJ_CONTEXT *ctx, std::unique_ptr<GTiffVGrid> &&subgrid); void reassign_context(PJ_CONTEXT *ctx) override { m_grid->reassign_context(ctx); } bool hasChanged() const override { return m_grid->hasChanged(); } }; // --------------------------------------------------------------------------- GTiffVGridShiftSet::~GTiffVGridShiftSet() = default; // --------------------------------------------------------------------------- GTiffVGrid::GTiffVGrid(std::unique_ptr<GTiffGrid> &&grid, uint16_t idxSample) : VerticalShiftGrid(grid->name(), grid->width(), grid->height(), grid->extentAndRes()), m_grid(std::move(grid)), m_idxSample(idxSample) {} // --------------------------------------------------------------------------- GTiffVGrid::~GTiffVGrid() = default; // --------------------------------------------------------------------------- void GTiffVGrid::insertGrid(PJ_CONTEXT *ctx, std::unique_ptr<GTiffVGrid> &&subgrid) { bool gridInserted = false; const auto &extent = subgrid->extentAndRes(); for (const auto &candidateParent : m_children) { const auto &candidateParentExtent = candidateParent->extentAndRes(); if (candidateParentExtent.contains(extent)) { static_cast<GTiffVGrid *>(candidateParent.get()) ->insertGrid(ctx, std::move(subgrid)); gridInserted = true; break; } else if (candidateParentExtent.intersects(extent)) { pj_log(ctx, PJ_LOG_DEBUG, "Partially intersecting grids found!"); } } if (!gridInserted) { m_children.emplace_back(std::move(subgrid)); } } // --------------------------------------------------------------------------- std::unique_ptr<GTiffVGridShiftSet> GTiffVGridShiftSet::open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename) { auto set = std::unique_ptr<GTiffVGridShiftSet>( new GTiffVGridShiftSet(ctx, std::move(fp))); set->m_name = filename; set->m_format = "gtiff"; if (!set->m_GTiffDataset->openTIFF(filename)) { return nullptr; } uint16_t idxSample = 0; std::map<std::string, GTiffVGrid *> mapGrids; for (int ifd = 0;; ++ifd) { auto grid = set->m_GTiffDataset->nextGrid(); if (!grid) { if (ifd == 0) { return nullptr; } break; } const auto subfileType = grid->subfileType(); if (subfileType != 0 && subfileType != FILETYPE_PAGE) { if (ifd == 0) { pj_log(ctx, PJ_LOG_ERROR, _("Invalid subfileType")); return nullptr; } else { pj_log(ctx, PJ_LOG_DEBUG, "Ignoring IFD %d as it has a unsupported subfileType", ifd); continue; } } // Identify the index of the vertical correction bool foundDescriptionForAtLeastOneSample = false; bool foundDescriptionForShift = false; for (int i = 0; i < static_cast<int>(grid->samplesPerPixel()); ++i) { const auto &desc = grid->metadataItem("DESCRIPTION", i); if (!desc.empty()) { foundDescriptionForAtLeastOneSample = true; } if (desc == "geoid_undulation" || desc == "vertical_offset" || desc == "hydroid_height" || desc == "ellipsoidal_height_offset") { idxSample = static_cast<uint16_t>(i); foundDescriptionForShift = true; } } if (foundDescriptionForAtLeastOneSample) { if (!foundDescriptionForShift) { if (ifd > 0) { // Assuming that extra IFD without our channel of interest // can be ignored // One could imagine to put the accuracy values in separate // IFD for example pj_log(ctx, PJ_LOG_DEBUG, "Ignoring IFD %d as it has no " "geoid_undulation/vertical_offset/hydroid_height/" "ellipsoidal_height_offset channel", ifd); continue; } else { pj_log(ctx, PJ_LOG_DEBUG, "IFD 0 has channel descriptions, but no " "geoid_undulation/vertical_offset/hydroid_height/" "ellipsoidal_height_offset channel"); return nullptr; } } } if (idxSample >= grid->samplesPerPixel()) { pj_log(ctx, PJ_LOG_ERROR, _("Invalid sample index")); return nullptr; } const std::string &gridName = grid->metadataItem("grid_name"); const std::string &parentName = grid->metadataItem("parent_grid_name"); auto vgrid = internal::make_unique<GTiffVGrid>(std::move(grid), idxSample); insertIntoHierarchy(ctx, std::move(vgrid), gridName, parentName, set->m_grids, mapGrids); } return set; } #endif // TIFF_ENABLED // --------------------------------------------------------------------------- std::unique_ptr<VerticalShiftGridSet> VerticalShiftGridSet::open(PJ_CONTEXT *ctx, const std::string &filename) { if (filename == "null") { auto set = std::unique_ptr<VerticalShiftGridSet>(new VerticalShiftGridSet()); set->m_name = filename; set->m_format = "null"; set->m_grids.push_back(std::unique_ptr<NullVerticalShiftGrid>( new NullVerticalShiftGrid())); return set; } auto fp = FileManager::open_resource_file(ctx, filename.c_str()); if (!fp) { return nullptr; } const auto &actualName(fp->name()); if (ends_with(actualName, "gtx") || ends_with(actualName, "GTX")) { auto grid = GTXVerticalShiftGrid::open(ctx, std::move(fp), actualName); if (!grid) { return nullptr; } auto set = std::unique_ptr<VerticalShiftGridSet>(new VerticalShiftGridSet()); set->m_name = actualName; set->m_format = "gtx"; set->m_grids.push_back(std::unique_ptr<VerticalShiftGrid>(grid)); return set; } /* -------------------------------------------------------------------- */ /* Load a header, to determine the file type. */ /* -------------------------------------------------------------------- */ unsigned char header[4]; size_t header_size = fp->read(header, sizeof(header)); if (header_size != sizeof(header)) { return nullptr; } fp->seek(0); if (IsTIFF(header_size, header)) { #ifdef TIFF_ENABLED auto set = std::unique_ptr<VerticalShiftGridSet>( GTiffVGridShiftSet::open(ctx, std::move(fp), actualName)); if (!set) proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return set; #else pj_log(ctx, PJ_LOG_ERROR, _("TIFF grid, but TIFF support disabled in this build")); return nullptr; #endif } pj_log(ctx, PJ_LOG_ERROR, "Unrecognized vertical grid format for filename '%s'", filename.c_str()); return nullptr; } // --------------------------------------------------------------------------- bool VerticalShiftGridSet::reopen(PJ_CONTEXT *ctx) { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s has changed. Re-loading it", m_name.c_str()); auto newGS = open(ctx, m_name); m_grids.clear(); if (newGS) { m_grids = std::move(newGS->m_grids); } return !m_grids.empty(); } // --------------------------------------------------------------------------- static bool isPointInExtent(double x, double y, const ExtentAndRes &extent, double eps = 0) { if (!(y + eps >= extent.south && y - eps <= extent.north)) return false; if (extent.fullWorldLongitude()) return true; if (extent.isGeographic) { if (x + eps < extent.west) x += 2 * M_PI; else if (x - eps > extent.east) x -= 2 * M_PI; } if (!(x + eps >= extent.west && x - eps <= extent.east)) return false; return true; } // --------------------------------------------------------------------------- const VerticalShiftGrid *VerticalShiftGrid::gridAt(double longitude, double lat) const { for (const auto &child : m_children) { const auto &extentChild = child->extentAndRes(); if (isPointInExtent(longitude, lat, extentChild)) { return child->gridAt(longitude, lat); } } return this; } // --------------------------------------------------------------------------- const VerticalShiftGrid *VerticalShiftGridSet::gridAt(double longitude, double lat) const { for (const auto &grid : m_grids) { if (grid->isNullGrid()) { return grid.get(); } const auto &extent = grid->extentAndRes(); if (isPointInExtent(longitude, lat, extent)) { return grid->gridAt(longitude, lat); } } return nullptr; } // --------------------------------------------------------------------------- void VerticalShiftGridSet::reassign_context(PJ_CONTEXT *ctx) { for (const auto &grid : m_grids) { grid->reassign_context(ctx); } } // --------------------------------------------------------------------------- HorizontalShiftGrid::HorizontalShiftGrid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn) : Grid(nameIn, widthIn, heightIn, extentIn) {} // --------------------------------------------------------------------------- HorizontalShiftGrid::~HorizontalShiftGrid() = default; // --------------------------------------------------------------------------- HorizontalShiftGridSet::HorizontalShiftGridSet() = default; // --------------------------------------------------------------------------- HorizontalShiftGridSet::~HorizontalShiftGridSet() = default; // --------------------------------------------------------------------------- class NullHorizontalShiftGrid : public HorizontalShiftGrid { public: NullHorizontalShiftGrid() : HorizontalShiftGrid("null", 3, 3, globalExtent()) {} bool isNullGrid() const override { return true; } bool valueAt(int, int, bool, float &longShift, float &latShift) const override; void reassign_context(PJ_CONTEXT *) override {} bool hasChanged() const override { return false; } const std::string &metadataItem(const std::string &, int) const override { return emptyString; } }; // --------------------------------------------------------------------------- bool NullHorizontalShiftGrid::valueAt(int, int, bool, float &longShift, float &latShift) const { longShift = 0.0f; latShift = 0.0f; return true; } // --------------------------------------------------------------------------- static double to_double(const void *data) { double d; memcpy(&d, data, sizeof(d)); return d; } // --------------------------------------------------------------------------- class NTv1Grid : public HorizontalShiftGrid { PJ_CONTEXT *m_ctx; std::unique_ptr<File> m_fp; NTv1Grid(const NTv1Grid &) = delete; NTv1Grid &operator=(const NTv1Grid &) = delete; public: explicit NTv1Grid(PJ_CONTEXT *ctx, std::unique_ptr<File> &&fp, const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn) : HorizontalShiftGrid(nameIn, widthIn, heightIn, extentIn), m_ctx(ctx), m_fp(std::move(fp)) {} ~NTv1Grid() override; bool valueAt(int, int, bool, float &longShift, float &latShift) const override; static NTv1Grid *open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename); void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; m_fp->reassign_context(ctx); } bool hasChanged() const override { return m_fp->hasChanged(); } const std::string &metadataItem(const std::string &, int) const override { return emptyString; } }; // --------------------------------------------------------------------------- NTv1Grid::~NTv1Grid() = default; // --------------------------------------------------------------------------- NTv1Grid *NTv1Grid::open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename) { unsigned char header[192]; /* -------------------------------------------------------------------- */ /* Read the header. */ /* -------------------------------------------------------------------- */ if (fp->read(header, sizeof(header)) != sizeof(header)) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } /* -------------------------------------------------------------------- */ /* Regularize fields of interest. */ /* -------------------------------------------------------------------- */ if (IS_LSB) { swap_words(header + 8, sizeof(int), 1); swap_words(header + 24, sizeof(double), 1); swap_words(header + 40, sizeof(double), 1); swap_words(header + 56, sizeof(double), 1); swap_words(header + 72, sizeof(double), 1); swap_words(header + 88, sizeof(double), 1); swap_words(header + 104, sizeof(double), 1); } if (*((int *)(header + 8)) != 12) { pj_log(ctx, PJ_LOG_ERROR, _("NTv1 grid shift file has wrong record count, corrupt?")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } ExtentAndRes extent; extent.isGeographic = true; extent.west = -to_double(header + 72) * DEG_TO_RAD; extent.south = to_double(header + 24) * DEG_TO_RAD; extent.east = -to_double(header + 56) * DEG_TO_RAD; extent.north = to_double(header + 40) * DEG_TO_RAD; extent.resX = to_double(header + 104) * DEG_TO_RAD; extent.resY = to_double(header + 88) * DEG_TO_RAD; extent.computeInvRes(); if (!(fabs(extent.west) <= 4 * M_PI && fabs(extent.east) <= 4 * M_PI && fabs(extent.north) <= M_PI + 1e-5 && fabs(extent.south) <= M_PI + 1e-5 && extent.west < extent.east && extent.south < extent.north && extent.resX > 1e-10 && extent.resY > 1e-10)) { pj_log(ctx, PJ_LOG_ERROR, _("Inconsistent georeferencing for %s"), filename.c_str()); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } const int columns = static_cast<int>( fabs((extent.east - extent.west) * extent.invResX + 0.5) + 1); const int rows = static_cast<int>( fabs((extent.north - extent.south) * extent.invResY + 0.5) + 1); return new NTv1Grid(ctx, std::move(fp), filename, columns, rows, extent); } // --------------------------------------------------------------------------- bool NTv1Grid::valueAt(int x, int y, bool compensateNTConvention, float &longShift, float &latShift) const { assert(x >= 0 && y >= 0 && x < m_width && y < m_height); double two_doubles[2]; // NTv1 is organized from east to west ! m_fp->seek(192 + 2 * sizeof(double) * (y * m_width + m_width - 1 - x)); if (m_fp->read(&two_doubles[0], sizeof(two_doubles)) != sizeof(two_doubles)) { proj_context_errno_set(m_ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return false; } if (IS_LSB) { swap_words(&two_doubles[0], sizeof(double), 2); } /* convert seconds to radians */ latShift = static_cast<float>(two_doubles[0] * ((M_PI / 180.0) / 3600.0)); // west longitude positive convention ! longShift = (compensateNTConvention ? -1 : 1) * static_cast<float>(two_doubles[1] * ((M_PI / 180.0) / 3600.0)); return true; } // --------------------------------------------------------------------------- class CTable2Grid : public HorizontalShiftGrid { PJ_CONTEXT *m_ctx; std::unique_ptr<File> m_fp; CTable2Grid(const CTable2Grid &) = delete; CTable2Grid &operator=(const CTable2Grid &) = delete; public: CTable2Grid(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn) : HorizontalShiftGrid(nameIn, widthIn, heightIn, extentIn), m_ctx(ctx), m_fp(std::move(fp)) {} ~CTable2Grid() override; bool valueAt(int, int, bool, float &longShift, float &latShift) const override; static CTable2Grid *open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename); void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; m_fp->reassign_context(ctx); } bool hasChanged() const override { return m_fp->hasChanged(); } const std::string &metadataItem(const std::string &, int) const override { return emptyString; } }; // --------------------------------------------------------------------------- CTable2Grid::~CTable2Grid() = default; // --------------------------------------------------------------------------- CTable2Grid *CTable2Grid::open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename) { unsigned char header[160]; /* -------------------------------------------------------------------- */ /* Read the header. */ /* -------------------------------------------------------------------- */ if (fp->read(header, sizeof(header)) != sizeof(header)) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } /* -------------------------------------------------------------------- */ /* Regularize fields of interest. */ /* -------------------------------------------------------------------- */ if (!IS_LSB) { swap_words(header + 96, sizeof(double), 4); swap_words(header + 128, sizeof(int), 2); } ExtentAndRes extent; extent.isGeographic = true; static_assert(sizeof(extent.west) == 8, "wrong sizeof"); static_assert(sizeof(extent.south) == 8, "wrong sizeof"); static_assert(sizeof(extent.resX) == 8, "wrong sizeof"); static_assert(sizeof(extent.resY) == 8, "wrong sizeof"); memcpy(&extent.west, header + 96, 8); memcpy(&extent.south, header + 104, 8); memcpy(&extent.resX, header + 112, 8); memcpy(&extent.resY, header + 120, 8); if (!(fabs(extent.west) <= 4 * M_PI && fabs(extent.south) <= M_PI + 1e-5 && extent.resX > 1e-10 && extent.resY > 1e-10)) { pj_log(ctx, PJ_LOG_ERROR, _("Inconsistent georeferencing for %s"), filename.c_str()); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } int width; int height; memcpy(&width, header + 128, 4); memcpy(&height, header + 132, 4); if (width <= 0 || height <= 0) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } extent.east = extent.west + (width - 1) * extent.resX; extent.north = extent.south + (height - 1) * extent.resX; extent.computeInvRes(); return new CTable2Grid(ctx, std::move(fp), filename, width, height, extent); } // --------------------------------------------------------------------------- bool CTable2Grid::valueAt(int x, int y, bool compensateNTConvention, float &longShift, float &latShift) const { assert(x >= 0 && y >= 0 && x < m_width && y < m_height); float two_floats[2]; m_fp->seek(160 + 2 * sizeof(float) * (y * m_width + x)); if (m_fp->read(&two_floats[0], sizeof(two_floats)) != sizeof(two_floats)) { proj_context_errno_set(m_ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return false; } if (!IS_LSB) { swap_words(&two_floats[0], sizeof(float), 2); } latShift = two_floats[1]; // west longitude positive convention ! longShift = (compensateNTConvention ? -1 : 1) * two_floats[0]; return true; } // --------------------------------------------------------------------------- class NTv2GridSet : public HorizontalShiftGridSet { std::unique_ptr<File> m_fp; std::unique_ptr<FloatLineCache> m_cache{}; NTv2GridSet(const NTv2GridSet &) = delete; NTv2GridSet &operator=(const NTv2GridSet &) = delete; explicit NTv2GridSet(std::unique_ptr<File> &&fp) : m_fp(std::move(fp)) {} public: ~NTv2GridSet() override; static std::unique_ptr<NTv2GridSet> open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename); void reassign_context(PJ_CONTEXT *ctx) override { HorizontalShiftGridSet::reassign_context(ctx); m_fp->reassign_context(ctx); } }; // --------------------------------------------------------------------------- class NTv2Grid : public HorizontalShiftGrid { friend class NTv2GridSet; PJ_CONTEXT *m_ctx; // owned by the parent NTv2GridSet File *m_fp; // owned by the parent NTv2GridSet FloatLineCache *m_cache = nullptr; // owned by the parent NTv2GridSet uint32_t m_gridIdx; unsigned long long m_offset; bool m_mustSwap; mutable std::vector<float> m_buffer{}; NTv2Grid(const NTv2Grid &) = delete; NTv2Grid &operator=(const NTv2Grid &) = delete; public: NTv2Grid(const std::string &nameIn, PJ_CONTEXT *ctx, File *fp, uint32_t gridIdx, unsigned long long offsetIn, bool mustSwapIn, int widthIn, int heightIn, const ExtentAndRes &extentIn) : HorizontalShiftGrid(nameIn, widthIn, heightIn, extentIn), m_ctx(ctx), m_fp(fp), m_gridIdx(gridIdx), m_offset(offsetIn), m_mustSwap(mustSwapIn) {} bool valueAt(int, int, bool, float &longShift, float &latShift) const override; const std::string &metadataItem(const std::string &, int) const override { return emptyString; } void setCache(FloatLineCache *cache) { m_cache = cache; } void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; m_fp->reassign_context(ctx); } bool hasChanged() const override { return m_fp->hasChanged(); } }; // --------------------------------------------------------------------------- bool NTv2Grid::valueAt(int x, int y, bool compensateNTConvention, float &longShift, float &latShift) const { assert(x >= 0 && y >= 0 && x < m_width && y < m_height); const std::vector<float> *pBuffer = m_cache->get(m_gridIdx, y); if (pBuffer == nullptr) { try { m_buffer.resize(4 * m_width); } catch (const std::exception &e) { pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); return false; } const size_t nLineSizeInBytes = 4 * sizeof(float) * m_width; // there are 4 components: lat shift, long shift, lat error, long error m_fp->seek(m_offset + nLineSizeInBytes * static_cast<unsigned long long>(y)); if (m_fp->read(&m_buffer[0], nLineSizeInBytes) != nLineSizeInBytes) { proj_context_errno_set( m_ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return false; } // Remove lat and long error for (int i = 1; i < m_width; ++i) { m_buffer[2 * i] = m_buffer[4 * i]; m_buffer[2 * i + 1] = m_buffer[4 * i + 1]; } m_buffer.resize(2 * m_width); if (m_mustSwap) { swap_words(&m_buffer[0], sizeof(float), 2 * m_width); } // NTv2 is organized from east to west ! for (int i = 0; i < m_width / 2; ++i) { std::swap(m_buffer[2 * i], m_buffer[2 * (m_width - 1 - i)]); std::swap(m_buffer[2 * i + 1], m_buffer[2 * (m_width - 1 - i) + 1]); } try { m_cache->insert(m_gridIdx, y, m_buffer); } catch (const std::exception &e) { // Should normally not happen pj_log(m_ctx, PJ_LOG_ERROR, _("Exception %s"), e.what()); } } const std::vector<float> &buffer = pBuffer ? *pBuffer : m_buffer; /* convert seconds to radians */ latShift = static_cast<float>(buffer[2 * x] * ((M_PI / 180.0) / 3600.0)); // west longitude positive convention ! longShift = (compensateNTConvention ? -1 : 1) * static_cast<float>(buffer[2 * x + 1] * ((M_PI / 180.0) / 3600.0)); return true; } // --------------------------------------------------------------------------- NTv2GridSet::~NTv2GridSet() = default; // --------------------------------------------------------------------------- std::unique_ptr<NTv2GridSet> NTv2GridSet::open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename) { File *fpRaw = fp.get(); auto set = std::unique_ptr<NTv2GridSet>(new NTv2GridSet(std::move(fp))); set->m_name = filename; set->m_format = "ntv2"; char header[11 * 16]; /* -------------------------------------------------------------------- */ /* Read the header. */ /* -------------------------------------------------------------------- */ if (fpRaw->read(header, sizeof(header)) != sizeof(header)) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } constexpr int OFFSET_GS_TYPE = 56; if (memcmp(header + OFFSET_GS_TYPE, "SECONDS", 7) != 0) { pj_log(ctx, PJ_LOG_ERROR, _("Only GS_TYPE=SECONDS is supported")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } const bool must_swap = (header[8] == 11) ? !IS_LSB : IS_LSB; constexpr int OFFSET_NUM_SUBFILES = 8 + 32; if (must_swap) { // swap_words( header+8, 4, 1 ); // swap_words( header+8+16, 4, 1 ); swap_words(header + OFFSET_NUM_SUBFILES, 4, 1); // swap_words( header+8+7*16, 8, 1 ); // swap_words( header+8+8*16, 8, 1 ); // swap_words( header+8+9*16, 8, 1 ); // swap_words( header+8+10*16, 8, 1 ); } /* -------------------------------------------------------------------- */ /* Get the subfile count out ... all we really use for now. */ /* -------------------------------------------------------------------- */ unsigned int num_subfiles; memcpy(&num_subfiles, header + OFFSET_NUM_SUBFILES, 4); std::map<std::string, NTv2Grid *> mapGrids; /* ==================================================================== */ /* Step through the subfiles, creating a grid for each. */ /* ==================================================================== */ int largestLine = 1; for (unsigned subfile = 0; subfile < num_subfiles; subfile++) { // Read header if (fpRaw->read(header, sizeof(header)) != sizeof(header)) { proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } if (strncmp(header, "SUB_NAME", 8) != 0) { proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } // Byte swap interesting fields if needed. constexpr int OFFSET_GS_COUNT = 8 + 16 * 10; constexpr int OFFSET_SOUTH_LAT = 8 + 16 * 4; if (must_swap) { // 6 double values: south, north, east, west, resY, // resX for (int i = 0; i < 6; i++) { swap_words(header + OFFSET_SOUTH_LAT + 16 * i, sizeof(double), 1); } swap_words(header + OFFSET_GS_COUNT, sizeof(int), 1); } std::string gridName; gridName.append(header + 8, 8); ExtentAndRes extent; extent.isGeographic = true; extent.south = to_double(header + OFFSET_SOUTH_LAT) * DEG_TO_RAD / 3600.0; /* S_LAT */ extent.north = to_double(header + OFFSET_SOUTH_LAT + 16) * DEG_TO_RAD / 3600.0; /* N_LAT */ extent.east = -to_double(header + OFFSET_SOUTH_LAT + 16 * 2) * DEG_TO_RAD / 3600.0; /* E_LONG */ extent.west = -to_double(header + OFFSET_SOUTH_LAT + 16 * 3) * DEG_TO_RAD / 3600.0; /* W_LONG */ extent.resY = to_double(header + OFFSET_SOUTH_LAT + 16 * 4) * DEG_TO_RAD / 3600.0; extent.resX = to_double(header + OFFSET_SOUTH_LAT + 16 * 5) * DEG_TO_RAD / 3600.0; extent.computeInvRes(); if (!(fabs(extent.west) <= 4 * M_PI && fabs(extent.east) <= 4 * M_PI && fabs(extent.north) <= M_PI + 1e-5 && fabs(extent.south) <= M_PI + 1e-5 && extent.west < extent.east && extent.south < extent.north && extent.resX > 1e-10 && extent.resY > 1e-10)) { pj_log(ctx, PJ_LOG_ERROR, _("Inconsistent georeferencing for %s"), filename.c_str()); proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } const int columns = static_cast<int>( fabs((extent.east - extent.west) * extent.invResX + 0.5) + 1); const int rows = static_cast<int>( fabs((extent.north - extent.south) * extent.invResY + 0.5) + 1); if (columns > largestLine) largestLine = columns; pj_log(ctx, PJ_LOG_TRACE, "NTv2 %s %dx%d: LL=(%.9g,%.9g) UR=(%.9g,%.9g)", gridName.c_str(), columns, rows, extent.west * RAD_TO_DEG, extent.south * RAD_TO_DEG, extent.east * RAD_TO_DEG, extent.north * RAD_TO_DEG); unsigned int gs_count; memcpy(&gs_count, header + OFFSET_GS_COUNT, 4); if (gs_count / columns != static_cast<unsigned>(rows)) { pj_log(ctx, PJ_LOG_ERROR, _("GS_COUNT(%u) does not match expected cells (%dx%d)"), gs_count, columns, rows); proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return nullptr; } const auto offset = fpRaw->tell(); auto grid = std::unique_ptr<NTv2Grid>(new NTv2Grid( std::string(filename).append(", ").append(gridName), ctx, fpRaw, subfile, offset, must_swap, columns, rows, extent)); std::string parentName; parentName.assign(header + 24, 8); auto iter = mapGrids.find(parentName); auto gridPtr = grid.get(); if (iter == mapGrids.end()) { set->m_grids.emplace_back(std::move(grid)); } else { iter->second->m_children.emplace_back(std::move(grid)); } mapGrids[gridName] = gridPtr; // Skip grid data. 4 components of size float fpRaw->seek(static_cast<unsigned long long>(gs_count) * 4 * 4, SEEK_CUR); } // Cache up to 1 megapixel per NTv2 file const int maxLinesInCache = 1024 * 1024 / largestLine; set->m_cache = internal::make_unique<FloatLineCache>(maxLinesInCache); for (const auto &kv : mapGrids) { kv.second->setCache(set->m_cache.get()); } return set; } #ifdef TIFF_ENABLED // --------------------------------------------------------------------------- class GTiffHGridShiftSet : public HorizontalShiftGridSet { std::unique_ptr<GTiffDataset> m_GTiffDataset; GTiffHGridShiftSet(PJ_CONTEXT *ctx, std::unique_ptr<File> &&fp) : m_GTiffDataset(new GTiffDataset(ctx, std::move(fp))) {} public: ~GTiffHGridShiftSet() override; static std::unique_ptr<GTiffHGridShiftSet> open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename); void reassign_context(PJ_CONTEXT *ctx) override { HorizontalShiftGridSet::reassign_context(ctx); if (m_GTiffDataset) { m_GTiffDataset->reassign_context(ctx); } } bool reopen(PJ_CONTEXT *ctx) override { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s has changed. Re-loading it", m_name.c_str()); m_grids.clear(); m_GTiffDataset.reset(); auto fp = FileManager::open_resource_file(ctx, m_name.c_str()); if (!fp) { return false; } auto newGS = open(ctx, std::move(fp), m_name); if (newGS) { m_grids = std::move(newGS->m_grids); m_GTiffDataset = std::move(newGS->m_GTiffDataset); } return !m_grids.empty(); } }; // --------------------------------------------------------------------------- class GTiffHGrid : public HorizontalShiftGrid { friend void insertIntoHierarchy<GTiffHGrid, HorizontalShiftGrid>( PJ_CONTEXT *ctx, std::unique_ptr<GTiffHGrid> &&grid, const std::string &gridName, const std::string &parentName, std::vector<std::unique_ptr<HorizontalShiftGrid>> &topGrids, std::map<std::string, GTiffHGrid *> &mapGrids); std::unique_ptr<GTiffGrid> m_grid; uint16_t m_idxLatShift; uint16_t m_idxLongShift; double m_convFactorToRadian; bool m_positiveEast; public: GTiffHGrid(std::unique_ptr<GTiffGrid> &&grid, uint16_t idxLatShift, uint16_t idxLongShift, double convFactorToRadian, bool positiveEast); ~GTiffHGrid() override; bool valueAt(int x, int y, bool, float &longShift, float &latShift) const override; const std::string &metadataItem(const std::string &key, int sample = -1) const override { return m_grid->metadataItem(key, sample); } void insertGrid(PJ_CONTEXT *ctx, std::unique_ptr<GTiffHGrid> &&subgrid); void reassign_context(PJ_CONTEXT *ctx) override { m_grid->reassign_context(ctx); } bool hasChanged() const override { return m_grid->hasChanged(); } }; // --------------------------------------------------------------------------- GTiffHGridShiftSet::~GTiffHGridShiftSet() = default; // --------------------------------------------------------------------------- GTiffHGrid::GTiffHGrid(std::unique_ptr<GTiffGrid> &&grid, uint16_t idxLatShift, uint16_t idxLongShift, double convFactorToRadian, bool positiveEast) : HorizontalShiftGrid(grid->name(), grid->width(), grid->height(), grid->extentAndRes()), m_grid(std::move(grid)), m_idxLatShift(idxLatShift), m_idxLongShift(idxLongShift), m_convFactorToRadian(convFactorToRadian), m_positiveEast(positiveEast) {} // --------------------------------------------------------------------------- GTiffHGrid::~GTiffHGrid() = default; // --------------------------------------------------------------------------- bool GTiffHGrid::valueAt(int x, int y, bool, float &longShift, float &latShift) const { if (!m_grid->valueAt(m_idxLatShift, x, y, latShift) || !m_grid->valueAt(m_idxLongShift, x, y, longShift)) { return false; } // From arc-seconds to radians latShift = static_cast<float>(latShift * m_convFactorToRadian); longShift = static_cast<float>(longShift * m_convFactorToRadian); if (!m_positiveEast) { longShift = -longShift; } return true; } // --------------------------------------------------------------------------- void GTiffHGrid::insertGrid(PJ_CONTEXT *ctx, std::unique_ptr<GTiffHGrid> &&subgrid) { bool gridInserted = false; const auto &extent = subgrid->extentAndRes(); for (const auto &candidateParent : m_children) { const auto &candidateParentExtent = candidateParent->extentAndRes(); if (candidateParentExtent.contains(extent)) { static_cast<GTiffHGrid *>(candidateParent.get()) ->insertGrid(ctx, std::move(subgrid)); gridInserted = true; break; } else if (candidateParentExtent.intersects(extent)) { pj_log(ctx, PJ_LOG_DEBUG, "Partially intersecting grids found!"); } } if (!gridInserted) { m_children.emplace_back(std::move(subgrid)); } } // --------------------------------------------------------------------------- std::unique_ptr<GTiffHGridShiftSet> GTiffHGridShiftSet::open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename) { auto set = std::unique_ptr<GTiffHGridShiftSet>( new GTiffHGridShiftSet(ctx, std::move(fp))); set->m_name = filename; set->m_format = "gtiff"; if (!set->m_GTiffDataset->openTIFF(filename)) { return nullptr; } // Defaults inspired from NTv2 uint16_t idxLatShift = 0; uint16_t idxLongShift = 1; constexpr double ARC_SECOND_TO_RADIAN = (M_PI / 180.0) / 3600.0; double convFactorToRadian = ARC_SECOND_TO_RADIAN; bool positiveEast = true; std::map<std::string, GTiffHGrid *> mapGrids; for (int ifd = 0;; ++ifd) { auto grid = set->m_GTiffDataset->nextGrid(); if (!grid) { if (ifd == 0) { return nullptr; } break; } const auto subfileType = grid->subfileType(); if (subfileType != 0 && subfileType != FILETYPE_PAGE) { if (ifd == 0) { pj_log(ctx, PJ_LOG_ERROR, _("Invalid subfileType")); return nullptr; } else { pj_log(ctx, PJ_LOG_DEBUG, _("Ignoring IFD %d as it has a unsupported subfileType"), ifd); continue; } } if (grid->samplesPerPixel() < 2) { if (ifd == 0) { pj_log(ctx, PJ_LOG_ERROR, _("At least 2 samples per pixel needed")); return nullptr; } else { pj_log(ctx, PJ_LOG_DEBUG, _("Ignoring IFD %d as it has not at least 2 samples"), ifd); continue; } } // Identify the index of the latitude and longitude offset channels bool foundDescriptionForAtLeastOneSample = false; bool foundDescriptionForLatOffset = false; bool foundDescriptionForLongOffset = false; for (int i = 0; i < static_cast<int>(grid->samplesPerPixel()); ++i) { const auto &desc = grid->metadataItem("DESCRIPTION", i); if (!desc.empty()) { foundDescriptionForAtLeastOneSample = true; } if (desc == "latitude_offset") { idxLatShift = static_cast<uint16_t>(i); foundDescriptionForLatOffset = true; } else if (desc == "longitude_offset") { idxLongShift = static_cast<uint16_t>(i); foundDescriptionForLongOffset = true; } } if (foundDescriptionForAtLeastOneSample) { if (!foundDescriptionForLongOffset && !foundDescriptionForLatOffset) { if (ifd > 0) { // Assuming that extra IFD without // longitude_offset/latitude_offset can be ignored // One could imagine to put the accuracy values in separate // IFD for example pj_log(ctx, PJ_LOG_DEBUG, "Ignoring IFD %d as it has no " "longitude_offset/latitude_offset channel", ifd); continue; } else { pj_log(ctx, PJ_LOG_DEBUG, "IFD 0 has channel descriptions, but no " "longitude_offset/latitude_offset channel"); return nullptr; } } } if (foundDescriptionForLatOffset && !foundDescriptionForLongOffset) { pj_log( ctx, PJ_LOG_ERROR, _("Found latitude_offset channel, but not longitude_offset")); return nullptr; } else if (foundDescriptionForLongOffset && !foundDescriptionForLatOffset) { pj_log( ctx, PJ_LOG_ERROR, _("Found longitude_offset channel, but not latitude_offset")); return nullptr; } if (idxLatShift >= grid->samplesPerPixel() || idxLongShift >= grid->samplesPerPixel()) { pj_log(ctx, PJ_LOG_ERROR, _("Invalid sample index")); return nullptr; } if (foundDescriptionForLongOffset) { const std::string &positiveValue = grid->metadataItem("positive_value", idxLongShift); if (!positiveValue.empty()) { if (positiveValue == "west") { positiveEast = false; } else if (positiveValue == "east") { positiveEast = true; } else { pj_log(ctx, PJ_LOG_ERROR, _("Unsupported value %s for 'positive_value'"), positiveValue.c_str()); return nullptr; } } } // Identify their unit { const auto &unitLatShift = grid->metadataItem("UNITTYPE", idxLatShift); const auto &unitLongShift = grid->metadataItem("UNITTYPE", idxLongShift); if (unitLatShift != unitLongShift) { pj_log(ctx, PJ_LOG_ERROR, _("Different unit for longitude and latitude offset")); return nullptr; } if (!unitLatShift.empty()) { if (unitLatShift == "arc-second" || unitLatShift == "arc-seconds per year") { convFactorToRadian = ARC_SECOND_TO_RADIAN; } else if (unitLatShift == "radian") { convFactorToRadian = 1.0; } else if (unitLatShift == "degree") { convFactorToRadian = M_PI / 180.0; } else { pj_log(ctx, PJ_LOG_ERROR, _("Unsupported unit %s"), unitLatShift.c_str()); return nullptr; } } } const std::string &gridName = grid->metadataItem("grid_name"); const std::string &parentName = grid->metadataItem("parent_grid_name"); auto hgrid = internal::make_unique<GTiffHGrid>( std::move(grid), idxLatShift, idxLongShift, convFactorToRadian, positiveEast); insertIntoHierarchy(ctx, std::move(hgrid), gridName, parentName, set->m_grids, mapGrids); } return set; } #endif // TIFF_ENABLED // --------------------------------------------------------------------------- std::unique_ptr<HorizontalShiftGridSet> HorizontalShiftGridSet::open(PJ_CONTEXT *ctx, const std::string &filename) { if (filename == "null") { auto set = std::unique_ptr<HorizontalShiftGridSet>( new HorizontalShiftGridSet()); set->m_name = filename; set->m_format = "null"; set->m_grids.push_back(std::unique_ptr<NullHorizontalShiftGrid>( new NullHorizontalShiftGrid())); return set; } auto fp = FileManager::open_resource_file(ctx, filename.c_str()); if (!fp) { return nullptr; } const auto &actualName(fp->name()); char header[160]; /* -------------------------------------------------------------------- */ /* Load a header, to determine the file type. */ /* -------------------------------------------------------------------- */ size_t header_size = fp->read(header, sizeof(header)); if (header_size != sizeof(header)) { /* some files may be smaller that sizeof(header), eg 160, so */ ctx->last_errno = 0; /* don't treat as a persistent error */ pj_log(ctx, PJ_LOG_DEBUG, "pj_gridinfo_init: short header read of %d bytes", (int)header_size); } fp->seek(0); /* -------------------------------------------------------------------- */ /* Determine file type. */ /* -------------------------------------------------------------------- */ if (header_size >= 144 + 16 && strncmp(header + 0, "HEADER", 6) == 0 && strncmp(header + 96, "W GRID", 6) == 0 && strncmp(header + 144, "TO NAD83 ", 16) == 0) { auto grid = NTv1Grid::open(ctx, std::move(fp), actualName); if (!grid) { return nullptr; } auto set = std::unique_ptr<HorizontalShiftGridSet>( new HorizontalShiftGridSet()); set->m_name = actualName; set->m_format = "ntv1"; set->m_grids.push_back(std::unique_ptr<HorizontalShiftGrid>(grid)); return set; } else if (header_size >= 9 && strncmp(header + 0, "CTABLE V2", 9) == 0) { auto grid = CTable2Grid::open(ctx, std::move(fp), actualName); if (!grid) { return nullptr; } auto set = std::unique_ptr<HorizontalShiftGridSet>( new HorizontalShiftGridSet()); set->m_name = actualName; set->m_format = "ctable2"; set->m_grids.push_back(std::unique_ptr<HorizontalShiftGrid>(grid)); return set; } else if (header_size >= 48 + 7 && strncmp(header + 0, "NUM_OREC", 8) == 0 && strncmp(header + 48, "GS_TYPE", 7) == 0) { return NTv2GridSet::open(ctx, std::move(fp), actualName); } else if (IsTIFF(header_size, reinterpret_cast<const unsigned char *>(header))) { #ifdef TIFF_ENABLED auto set = std::unique_ptr<HorizontalShiftGridSet>( GTiffHGridShiftSet::open(ctx, std::move(fp), actualName)); if (!set) proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return set; #else pj_log(ctx, PJ_LOG_ERROR, _("TIFF grid, but TIFF support disabled in this build")); return nullptr; #endif } pj_log(ctx, PJ_LOG_ERROR, "Unrecognized horizontal grid format for filename '%s'", filename.c_str()); return nullptr; } // --------------------------------------------------------------------------- bool HorizontalShiftGridSet::reopen(PJ_CONTEXT *ctx) { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s has changed. Re-loading it", m_name.c_str()); auto newGS = open(ctx, m_name); m_grids.clear(); if (newGS) { m_grids = std::move(newGS->m_grids); } return !m_grids.empty(); } // --------------------------------------------------------------------------- #define REL_TOLERANCE_HGRIDSHIFT 1e-5 const HorizontalShiftGrid *HorizontalShiftGrid::gridAt(double longitude, double lat) const { for (const auto &child : m_children) { const auto &extentChild = child->extentAndRes(); const double epsilon = (extentChild.resX + extentChild.resY) * REL_TOLERANCE_HGRIDSHIFT; if (isPointInExtent(longitude, lat, extentChild, epsilon)) { return child->gridAt(longitude, lat); } } return this; } // --------------------------------------------------------------------------- const HorizontalShiftGrid *HorizontalShiftGridSet::gridAt(double longitude, double lat) const { for (const auto &grid : m_grids) { if (grid->isNullGrid()) { return grid.get(); } const auto &extent = grid->extentAndRes(); const double epsilon = (extent.resX + extent.resY) * REL_TOLERANCE_HGRIDSHIFT; if (isPointInExtent(longitude, lat, extent, epsilon)) { return grid->gridAt(longitude, lat); } } return nullptr; } // --------------------------------------------------------------------------- void HorizontalShiftGridSet::reassign_context(PJ_CONTEXT *ctx) { for (const auto &grid : m_grids) { grid->reassign_context(ctx); } } #ifdef TIFF_ENABLED // --------------------------------------------------------------------------- class GTiffGenericGridShiftSet : public GenericShiftGridSet { std::unique_ptr<GTiffDataset> m_GTiffDataset; GTiffGenericGridShiftSet(PJ_CONTEXT *ctx, std::unique_ptr<File> &&fp) : m_GTiffDataset(new GTiffDataset(ctx, std::move(fp))) {} public: ~GTiffGenericGridShiftSet() override; static std::unique_ptr<GTiffGenericGridShiftSet> open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename); void reassign_context(PJ_CONTEXT *ctx) override { GenericShiftGridSet::reassign_context(ctx); if (m_GTiffDataset) { m_GTiffDataset->reassign_context(ctx); } } bool reopen(PJ_CONTEXT *ctx) override { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s has changed. Re-loading it", m_name.c_str()); m_grids.clear(); m_GTiffDataset.reset(); auto fp = FileManager::open_resource_file(ctx, m_name.c_str()); if (!fp) { return false; } auto newGS = open(ctx, std::move(fp), m_name); if (newGS) { m_grids = std::move(newGS->m_grids); m_GTiffDataset = std::move(newGS->m_GTiffDataset); } return !m_grids.empty(); } }; // --------------------------------------------------------------------------- class GTiffGenericGrid final : public GenericShiftGrid { friend void insertIntoHierarchy<GTiffGenericGrid, GenericShiftGrid>( PJ_CONTEXT *ctx, std::unique_ptr<GTiffGenericGrid> &&grid, const std::string &gridName, const std::string &parentName, std::vector<std::unique_ptr<GenericShiftGrid>> &topGrids, std::map<std::string, GTiffGenericGrid *> &mapGrids); std::unique_ptr<GTiffGrid> m_grid; const GenericShiftGrid *m_firstGrid = nullptr; mutable std::string m_type{}; mutable bool m_bTypeSet = false; public: GTiffGenericGrid(std::unique_ptr<GTiffGrid> &&grid); ~GTiffGenericGrid() override; bool valueAt(int x, int y, int sample, float &out) const override; bool valuesAt(int x_start, int y_start, int x_count, int y_count, int sample_count, const int *sample_idx, float *out, bool &nodataFound) const override; int samplesPerPixel() const override { return m_grid->samplesPerPixel(); } std::string unit(int sample) const override { return metadataItem("UNITTYPE", sample); } std::string description(int sample) const override { return metadataItem("DESCRIPTION", sample); } const std::string &metadataItem(const std::string &key, int sample = -1) const override { const std::string &ret = m_grid->metadataItem(key, sample); if (ret.empty() && m_firstGrid) { return m_firstGrid->metadataItem(key, sample); } return ret; } const std::string &type() const override { if (!m_bTypeSet) { m_bTypeSet = true; m_type = metadataItem("TYPE"); } return m_type; } void setFirstGrid(const GenericShiftGrid *firstGrid) { m_firstGrid = firstGrid; } void insertGrid(PJ_CONTEXT *ctx, std::unique_ptr<GTiffGenericGrid> &&subgrid); void reassign_context(PJ_CONTEXT *ctx) override { m_grid->reassign_context(ctx); } bool hasChanged() const override { return m_grid->hasChanged(); } private: GTiffGenericGrid(const GTiffGenericGrid &) = delete; GTiffGenericGrid &operator=(const GTiffGenericGrid &) = delete; }; // --------------------------------------------------------------------------- GTiffGenericGridShiftSet::~GTiffGenericGridShiftSet() = default; // --------------------------------------------------------------------------- GTiffGenericGrid::GTiffGenericGrid(std::unique_ptr<GTiffGrid> &&grid) : GenericShiftGrid(grid->name(), grid->width(), grid->height(), grid->extentAndRes()), m_grid(std::move(grid)) {} // --------------------------------------------------------------------------- GTiffGenericGrid::~GTiffGenericGrid() = default; // --------------------------------------------------------------------------- bool GTiffGenericGrid::valueAt(int x, int y, int sample, float &out) const { if (sample < 0 || static_cast<unsigned>(sample) >= m_grid->samplesPerPixel()) return false; return m_grid->valueAt(static_cast<uint16_t>(sample), x, y, out); } // --------------------------------------------------------------------------- bool GTiffGenericGrid::valuesAt(int x_start, int y_start, int x_count, int y_count, int sample_count, const int *sample_idx, float *out, bool &nodataFound) const { return m_grid->valuesAt(x_start, y_start, x_count, y_count, sample_count, sample_idx, out, nodataFound); } // --------------------------------------------------------------------------- void GTiffGenericGrid::insertGrid(PJ_CONTEXT *ctx, std::unique_ptr<GTiffGenericGrid> &&subgrid) { bool gridInserted = false; const auto &extent = subgrid->extentAndRes(); for (const auto &candidateParent : m_children) { const auto &candidateParentExtent = candidateParent->extentAndRes(); if (candidateParentExtent.contains(extent)) { static_cast<GTiffGenericGrid *>(candidateParent.get()) ->insertGrid(ctx, std::move(subgrid)); gridInserted = true; break; } else if (candidateParentExtent.intersects(extent)) { pj_log(ctx, PJ_LOG_DEBUG, "Partially intersecting grids found!"); } } if (!gridInserted) { m_children.emplace_back(std::move(subgrid)); } } #endif // TIFF_ENABLED // --------------------------------------------------------------------------- class NullGenericShiftGrid : public GenericShiftGrid { public: NullGenericShiftGrid() : GenericShiftGrid("null", 3, 3, globalExtent()) {} bool isNullGrid() const override { return true; } bool valueAt(int, int, int, float &out) const override; const std::string &type() const override { return emptyString; } int samplesPerPixel() const override { return 0; } std::string unit(int) const override { return std::string(); } std::string description(int) const override { return std::string(); } const std::string &metadataItem(const std::string &, int) const override { return emptyString; } void reassign_context(PJ_CONTEXT *) override {} bool hasChanged() const override { return false; } }; // --------------------------------------------------------------------------- bool NullGenericShiftGrid::valueAt(int, int, int, float &out) const { out = 0.0f; return true; } // --------------------------------------------------------------------------- #ifdef TIFF_ENABLED std::unique_ptr<GTiffGenericGridShiftSet> GTiffGenericGridShiftSet::open(PJ_CONTEXT *ctx, std::unique_ptr<File> fp, const std::string &filename) { auto set = std::unique_ptr<GTiffGenericGridShiftSet>( new GTiffGenericGridShiftSet(ctx, std::move(fp))); set->m_name = filename; set->m_format = "gtiff"; if (!set->m_GTiffDataset->openTIFF(filename)) { return nullptr; } std::map<std::string, GTiffGenericGrid *> mapGrids; for (int ifd = 0;; ++ifd) { auto grid = set->m_GTiffDataset->nextGrid(); if (!grid) { if (ifd == 0) { return nullptr; } break; } const auto subfileType = grid->subfileType(); if (subfileType != 0 && subfileType != FILETYPE_PAGE) { if (ifd == 0) { pj_log(ctx, PJ_LOG_ERROR, _("Invalid subfileType")); return nullptr; } else { pj_log(ctx, PJ_LOG_DEBUG, _("Ignoring IFD %d as it has a unsupported subfileType"), ifd); continue; } } const std::string &gridName = grid->metadataItem("grid_name"); const std::string &parentName = grid->metadataItem("parent_grid_name"); auto ggrid = internal::make_unique<GTiffGenericGrid>(std::move(grid)); if (!set->m_grids.empty() && ggrid->metadataItem("TYPE").empty() && !set->m_grids[0]->metadataItem("TYPE").empty()) { ggrid->setFirstGrid(set->m_grids[0].get()); } insertIntoHierarchy(ctx, std::move(ggrid), gridName, parentName, set->m_grids, mapGrids); } return set; } #endif // TIFF_ENABLED // --------------------------------------------------------------------------- GenericShiftGrid::GenericShiftGrid(const std::string &nameIn, int widthIn, int heightIn, const ExtentAndRes &extentIn) : Grid(nameIn, widthIn, heightIn, extentIn) {} // --------------------------------------------------------------------------- GenericShiftGrid::~GenericShiftGrid() = default; // --------------------------------------------------------------------------- bool GenericShiftGrid::valuesAt(int x_start, int y_start, int x_count, int y_count, int sample_count, const int *sample_idx, float *out, bool &nodataFound) const { nodataFound = false; for (int y = y_start; y < y_start + y_count; ++y) { for (int x = x_start; x < x_start + x_count; ++x) { for (int isample = 0; isample < sample_count; ++isample) { if (!valueAt(x, y, sample_idx[isample], *out)) return false; ++out; } } } return true; } // --------------------------------------------------------------------------- GenericShiftGridSet::GenericShiftGridSet() = default; // --------------------------------------------------------------------------- GenericShiftGridSet::~GenericShiftGridSet() = default; // --------------------------------------------------------------------------- std::unique_ptr<GenericShiftGridSet> GenericShiftGridSet::open(PJ_CONTEXT *ctx, const std::string &filename) { if (filename == "null") { auto set = std::unique_ptr<GenericShiftGridSet>(new GenericShiftGridSet()); set->m_name = filename; set->m_format = "null"; set->m_grids.push_back( std::unique_ptr<NullGenericShiftGrid>(new NullGenericShiftGrid())); return set; } auto fp = FileManager::open_resource_file(ctx, filename.c_str()); if (!fp) { return nullptr; } /* -------------------------------------------------------------------- */ /* Load a header, to determine the file type. */ /* -------------------------------------------------------------------- */ unsigned char header[4]; size_t header_size = fp->read(header, sizeof(header)); if (header_size != sizeof(header)) { return nullptr; } fp->seek(0); if (IsTIFF(header_size, header)) { #ifdef TIFF_ENABLED const std::string actualName(fp->name()); auto set = std::unique_ptr<GenericShiftGridSet>( GTiffGenericGridShiftSet::open(ctx, std::move(fp), actualName)); if (!set) proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return set; #else pj_log(ctx, PJ_LOG_ERROR, _("TIFF grid, but TIFF support disabled in this build")); return nullptr; #endif } pj_log(ctx, PJ_LOG_ERROR, "Unrecognized generic grid format for filename '%s'", filename.c_str()); return nullptr; } // --------------------------------------------------------------------------- bool GenericShiftGridSet::reopen(PJ_CONTEXT *ctx) { pj_log(ctx, PJ_LOG_DEBUG, "Grid %s has changed. Re-loading it", m_name.c_str()); auto newGS = open(ctx, m_name); m_grids.clear(); if (newGS) { m_grids = std::move(newGS->m_grids); } return !m_grids.empty(); } // --------------------------------------------------------------------------- const GenericShiftGrid *GenericShiftGrid::gridAt(double x, double y) const { for (const auto &child : m_children) { const auto &extentChild = child->extentAndRes(); if (isPointInExtent(x, y, extentChild)) { return child->gridAt(x, y); } } return this; } // --------------------------------------------------------------------------- const GenericShiftGrid *GenericShiftGridSet::gridAt(double x, double y) const { for (const auto &grid : m_grids) { if (grid->isNullGrid()) { return grid.get(); } const auto &extent = grid->extentAndRes(); if (isPointInExtent(x, y, extent)) { return grid->gridAt(x, y); } } return nullptr; } // --------------------------------------------------------------------------- const GenericShiftGrid *GenericShiftGridSet::gridAt(const std::string &type, double x, double y) const { for (const auto &grid : m_grids) { if (grid->isNullGrid()) { return grid.get(); } if (grid->type() != type) { continue; } const auto &extent = grid->extentAndRes(); if (isPointInExtent(x, y, extent)) { return grid->gridAt(x, y); } } return nullptr; } // --------------------------------------------------------------------------- void GenericShiftGridSet::reassign_context(PJ_CONTEXT *ctx) { for (const auto &grid : m_grids) { grid->reassign_context(ctx); } } // --------------------------------------------------------------------------- ListOfGenericGrids pj_generic_grid_init(PJ *P, const char *gridkey) { std::string key("s"); key += gridkey; const char *gridnames = pj_param(P->ctx, P->params, key.c_str()).s; if (gridnames == nullptr) return {}; auto listOfGridNames = internal::split(std::string(gridnames), ','); ListOfGenericGrids grids; for (const auto &gridnameStr : listOfGridNames) { const char *gridname = gridnameStr.c_str(); bool canFail = false; if (gridname[0] == '@') { canFail = true; gridname++; } auto gridSet = GenericShiftGridSet::open(P->ctx, gridname); if (!gridSet) { if (!canFail) { if (proj_context_errno(P->ctx) != PROJ_ERR_OTHER_NETWORK_ERROR) { proj_context_errno_set( P->ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } return {}; } proj_context_errno_set(P->ctx, 0); // don't treat as a persistent error } else { grids.emplace_back(std::move(gridSet)); } } return grids; } // --------------------------------------------------------------------------- static const HorizontalShiftGrid * findGrid(const ListOfHGrids &grids, const PJ_LP &input, HorizontalShiftGridSet *&gridSetOut) { for (const auto &gridset : grids) { auto grid = gridset->gridAt(input.lam, input.phi); if (grid) { gridSetOut = gridset.get(); return grid; } } return nullptr; } // --------------------------------------------------------------------------- static ListOfHGrids getListOfGridSets(PJ_CONTEXT *ctx, const char *grids) { ListOfHGrids list; auto listOfGrids = internal::split(std::string(grids), ','); for (const auto &grid : listOfGrids) { const char *gridname = grid.c_str(); bool canFail = false; if (gridname[0] == '@') { canFail = true; gridname++; } auto gridSet = HorizontalShiftGridSet::open(ctx, gridname); if (!gridSet) { if (!canFail) { if (proj_context_errno(ctx) != PROJ_ERR_OTHER_NETWORK_ERROR) { proj_context_errno_set( ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } return {}; } proj_context_errno_set(ctx, 0); // don't treat as a persistent error } else { list.emplace_back(std::move(gridSet)); } } return list; } /**********************************************/ ListOfHGrids pj_hgrid_init(PJ *P, const char *gridkey) { /********************************************** Initizalize and populate list of horizontal grids. Takes a PJ-object and the plus-parameter name that is used in the proj-string to specify the grids to load, e.g. "+grids". The + should be left out here. Returns the number of loaded grids. ***********************************************/ std::string key("s"); key += gridkey; const char *grids = pj_param(P->ctx, P->params, key.c_str()).s; if (grids == nullptr) return {}; return getListOfGridSets(P->ctx, grids); } // --------------------------------------------------------------------------- typedef struct { int32_t lam, phi; } ILP; // Apply bilinear interpolation for horizontal shift grids static PJ_LP pj_hgrid_interpolate(PJ_LP t, const HorizontalShiftGrid *grid, bool compensateNTConvention) { PJ_LP val, frct; ILP indx; int in; const auto &extent = grid->extentAndRes(); t.lam /= extent.resX; indx.lam = std::isnan(t.lam) ? 0 : (int32_t)lround(floor(t.lam)); t.phi /= extent.resY; indx.phi = std::isnan(t.phi) ? 0 : (int32_t)lround(floor(t.phi)); frct.lam = t.lam - indx.lam; frct.phi = t.phi - indx.phi; val.lam = val.phi = HUGE_VAL; if (indx.lam < 0) { if (indx.lam == -1 && frct.lam > 1 - 10 * REL_TOLERANCE_HGRIDSHIFT) { ++indx.lam; frct.lam = 0.; } else return val; } else if ((in = indx.lam + 1) >= grid->width()) { if (in == grid->width() && frct.lam < 10 * REL_TOLERANCE_HGRIDSHIFT) { --indx.lam; frct.lam = 1.; } else return val; } if (indx.phi < 0) { if (indx.phi == -1 && frct.phi > 1 - 10 * REL_TOLERANCE_HGRIDSHIFT) { ++indx.phi; frct.phi = 0.; } else return val; } else if ((in = indx.phi + 1) >= grid->height()) { if (in == grid->height() && frct.phi < 10 * REL_TOLERANCE_HGRIDSHIFT) { --indx.phi; frct.phi = 1.; } else return val; } float f00Long = 0, f00Lat = 0; float f10Long = 0, f10Lat = 0; float f01Long = 0, f01Lat = 0; float f11Long = 0, f11Lat = 0; if (!grid->valueAt(indx.lam, indx.phi, compensateNTConvention, f00Long, f00Lat) || !grid->valueAt(indx.lam + 1, indx.phi, compensateNTConvention, f10Long, f10Lat) || !grid->valueAt(indx.lam, indx.phi + 1, compensateNTConvention, f01Long, f01Lat) || !grid->valueAt(indx.lam + 1, indx.phi + 1, compensateNTConvention, f11Long, f11Lat)) { return val; } double m10 = frct.lam; double m11 = m10; double m01 = 1. - frct.lam; double m00 = m01; m11 *= frct.phi; m01 *= frct.phi; frct.phi = 1. - frct.phi; m00 *= frct.phi; m10 *= frct.phi; val.lam = m00 * f00Long + m10 * f10Long + m01 * f01Long + m11 * f11Long; val.phi = m00 * f00Lat + m10 * f10Lat + m01 * f01Lat + m11 * f11Lat; return val; } // --------------------------------------------------------------------------- #define MAX_ITERATIONS 10 #define TOL 1e-12 static PJ_LP pj_hgrid_apply_internal(PJ_CONTEXT *ctx, PJ_LP in, PJ_DIRECTION direction, const HorizontalShiftGrid *grid, HorizontalShiftGridSet *gridset, const ListOfHGrids &grids, bool &shouldRetry) { PJ_LP t, tb, del, dif; int i = MAX_ITERATIONS; const double toltol = TOL * TOL; shouldRetry = false; if (in.lam == HUGE_VAL) return in; /* normalize input to ll origin */ tb = in; const auto *extent = &(grid->extentAndRes()); const double epsilon = (extent->resX + extent->resY) * REL_TOLERANCE_HGRIDSHIFT; tb.lam -= extent->west; if (tb.lam + epsilon < 0) tb.lam += 2 * M_PI; else if (tb.lam - epsilon > extent->east - extent->west) tb.lam -= 2 * M_PI; tb.phi -= extent->south; t = pj_hgrid_interpolate(tb, grid, true); if (grid->hasChanged()) { shouldRetry = gridset->reopen(ctx); return t; } if (t.lam == HUGE_VAL) return t; if (direction == PJ_FWD) { in.lam += t.lam; in.phi += t.phi; return in; } t.lam = tb.lam - t.lam; t.phi = tb.phi - t.phi; do { del = pj_hgrid_interpolate(t, grid, true); if (grid->hasChanged()) { shouldRetry = gridset->reopen(ctx); return t; } /* We can possibly go outside of the initial guessed grid, so try */ /* to fetch a new grid into which iterate... */ if (del.lam == HUGE_VAL) { PJ_LP lp; lp.lam = t.lam + extent->west; lp.phi = t.phi + extent->south; auto newGrid = findGrid(grids, lp, gridset); if (newGrid == nullptr || newGrid == grid || newGrid->isNullGrid()) break; pj_log(ctx, PJ_LOG_TRACE, "Switching from grid %s to grid %s", grid->name().c_str(), newGrid->name().c_str()); grid = newGrid; extent = &(grid->extentAndRes()); t.lam = lp.lam - extent->west; t.phi = lp.phi - extent->south; tb = in; tb.lam -= extent->west; if (tb.lam + epsilon < 0) tb.lam += 2 * M_PI; else if (tb.lam - epsilon > extent->east - extent->west) tb.lam -= 2 * M_PI; tb.phi -= extent->south; dif.lam = std::numeric_limits<double>::max(); dif.phi = std::numeric_limits<double>::max(); continue; } dif.lam = t.lam + del.lam - tb.lam; dif.phi = t.phi + del.phi - tb.phi; t.lam -= dif.lam; t.phi -= dif.phi; } while (--i && (dif.lam * dif.lam + dif.phi * dif.phi > toltol)); /* prob. slightly faster than hypot() */ if (i == 0) { pj_log(ctx, PJ_LOG_TRACE, "Inverse grid shift iterator failed to converge.\n"); proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); t.lam = t.phi = HUGE_VAL; return t; } /* and again: pj_log and ctx->errno */ if (del.lam == HUGE_VAL) { pj_log(ctx, PJ_LOG_TRACE, "Inverse grid shift iteration failed, presumably at " "grid edge.\nUsing first approximation.\n"); } in.lam = adjlon(t.lam + extent->west); in.phi = t.phi + extent->south; return in; } // --------------------------------------------------------------------------- PJ_LP pj_hgrid_apply(PJ_CONTEXT *ctx, const ListOfHGrids &grids, PJ_LP lp, PJ_DIRECTION direction) { PJ_LP out; out.lam = HUGE_VAL; out.phi = HUGE_VAL; while (true) { HorizontalShiftGridSet *gridset = nullptr; const auto grid = findGrid(grids, lp, gridset); if (!grid) { proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return out; } if (grid->isNullGrid()) { return lp; } bool shouldRetry = false; out = pj_hgrid_apply_internal(ctx, lp, direction, grid, gridset, grids, shouldRetry); if (!shouldRetry) { break; } } if (out.lam == HUGE_VAL || out.phi == HUGE_VAL) proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return out; } /********************************************/ /* proj_hgrid_value() */ /* */ /* Return coordinate offset in grid */ /********************************************/ PJ_LP pj_hgrid_value(PJ *P, const ListOfHGrids &grids, PJ_LP lp) { PJ_LP out = proj_coord_error().lp; HorizontalShiftGridSet *gridset = nullptr; const auto grid = findGrid(grids, lp, gridset); if (!grid) { proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return out; } /* normalize input to ll origin */ const auto &extent = grid->extentAndRes(); if (!extent.isGeographic) { pj_log(P->ctx, PJ_LOG_ERROR, _("Can only handle grids referenced in a geographic CRS")); proj_context_errno_set(P->ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return out; } const double epsilon = (extent.resX + extent.resY) * REL_TOLERANCE_HGRIDSHIFT; lp.lam -= extent.west; if (lp.lam + epsilon < 0) lp.lam += 2 * M_PI; else if (lp.lam - epsilon > extent.east - extent.west) lp.lam -= 2 * M_PI; lp.phi -= extent.south; out = pj_hgrid_interpolate(lp, grid, false); if (grid->hasChanged()) { if (gridset->reopen(P->ctx)) { return pj_hgrid_value(P, grids, lp); } out.lam = HUGE_VAL; out.phi = HUGE_VAL; } if (out.lam == HUGE_VAL || out.phi == HUGE_VAL) { proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); } return out; } // --------------------------------------------------------------------------- static double read_vgrid_value(PJ_CONTEXT *ctx, const ListOfVGrids &grids, const PJ_LP &input, const double vmultiplier) { /* do not deal with NaN coordinates */ /* cppcheck-suppress duplicateExpression */ if (std::isnan(input.phi) || std::isnan(input.lam)) { return HUGE_VAL; } VerticalShiftGridSet *curGridset = nullptr; const VerticalShiftGrid *grid = nullptr; for (const auto &gridset : grids) { grid = gridset->gridAt(input.lam, input.phi); if (grid) { curGridset = gridset.get(); break; } } if (!grid) { proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return HUGE_VAL; } if (grid->isNullGrid()) { return 0; } const auto &extent = grid->extentAndRes(); if (!extent.isGeographic) { pj_log(ctx, PJ_LOG_ERROR, _("Can only handle grids referenced in a geographic CRS")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return HUGE_VAL; } /* Interpolation of a location within the grid */ double grid_x = (input.lam - extent.west) * extent.invResX; if (input.lam < extent.west) { if (extent.fullWorldLongitude()) { // The first fmod goes to ]-lim, lim[ range // So we add lim again to be in ]0, 2*lim[ and fmod again grid_x = fmod(fmod(grid_x + grid->width(), grid->width()) + grid->width(), grid->width()); } else { grid_x = (input.lam + 2 * M_PI - extent.west) * extent.invResX; } } else if (input.lam > extent.east) { if (extent.fullWorldLongitude()) { // The first fmod goes to ]-lim, lim[ range // So we add lim again to be in ]0, 2*lim[ and fmod again grid_x = fmod(fmod(grid_x + grid->width(), grid->width()) + grid->width(), grid->width()); } else { grid_x = (input.lam - 2 * M_PI - extent.west) * extent.invResX; } } double grid_y = (input.phi - extent.south) * extent.invResY; int grid_ix = static_cast<int>(lround(floor(grid_x))); if (!(grid_ix >= 0 && grid_ix < grid->width())) { // in the unlikely case we end up here... pj_log(ctx, PJ_LOG_ERROR, _("grid_ix not in grid")); proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return HUGE_VAL; } int grid_iy = static_cast<int>(lround(floor(grid_y))); assert(grid_iy >= 0 && grid_iy < grid->height()); grid_x -= grid_ix; grid_y -= grid_iy; int grid_ix2 = grid_ix + 1; if (grid_ix2 >= grid->width()) { if (extent.fullWorldLongitude()) { grid_ix2 = 0; } else { grid_ix2 = grid->width() - 1; } } int grid_iy2 = grid_iy + 1; if (grid_iy2 >= grid->height()) grid_iy2 = grid->height() - 1; float value_a = 0; float value_b = 0; float value_c = 0; float value_d = 0; bool error = (!grid->valueAt(grid_ix, grid_iy, value_a) || !grid->valueAt(grid_ix2, grid_iy, value_b) || !grid->valueAt(grid_ix, grid_iy2, value_c) || !grid->valueAt(grid_ix2, grid_iy2, value_d)); if (grid->hasChanged()) { if (curGridset->reopen(ctx)) { return read_vgrid_value(ctx, grids, input, vmultiplier); } error = true; } if (error) { return HUGE_VAL; } double value = 0.0; const double grid_x_y = grid_x * grid_y; const bool a_valid = !grid->isNodata(value_a, vmultiplier); const bool b_valid = !grid->isNodata(value_b, vmultiplier); const bool c_valid = !grid->isNodata(value_c, vmultiplier); const bool d_valid = !grid->isNodata(value_d, vmultiplier); const int countValid = static_cast<int>(a_valid) + static_cast<int>(b_valid) + static_cast<int>(c_valid) + static_cast<int>(d_valid); if (countValid == 4) { { double weight = 1.0 - grid_x - grid_y + grid_x_y; value = value_a * weight; } { double weight = grid_x - grid_x_y; value += value_b * weight; } { double weight = grid_y - grid_x_y; value += value_c * weight; } { double weight = grid_x_y; value += value_d * weight; } } else if (countValid == 0) { proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_GRID_AT_NODATA); value = HUGE_VAL; } else { double total_weight = 0.0; if (a_valid) { double weight = 1.0 - grid_x - grid_y + grid_x_y; value = value_a * weight; total_weight = weight; } if (b_valid) { double weight = grid_x - grid_x_y; value += value_b * weight; total_weight += weight; } if (c_valid) { double weight = grid_y - grid_x_y; value += value_c * weight; total_weight += weight; } if (d_valid) { double weight = grid_x_y; value += value_d * weight; total_weight += weight; } value /= total_weight; } return value * vmultiplier; } /**********************************************/ ListOfVGrids pj_vgrid_init(PJ *P, const char *gridkey) { /********************************************** Initizalize and populate gridlist. Takes a PJ-object and the plus-parameter name that is used in the proj-string to specify the grids to load, e.g. "+grids". The + should be left out here. Returns the number of loaded grids. ***********************************************/ std::string key("s"); key += gridkey; const char *gridnames = pj_param(P->ctx, P->params, key.c_str()).s; if (gridnames == nullptr) return {}; auto listOfGridNames = internal::split(std::string(gridnames), ','); ListOfVGrids grids; for (const auto &gridnameStr : listOfGridNames) { const char *gridname = gridnameStr.c_str(); bool canFail = false; if (gridname[0] == '@') { canFail = true; gridname++; } auto gridSet = VerticalShiftGridSet::open(P->ctx, gridname); if (!gridSet) { if (!canFail) { if (proj_context_errno(P->ctx) != PROJ_ERR_OTHER_NETWORK_ERROR) { proj_context_errno_set( P->ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } return {}; } proj_context_errno_set(P->ctx, 0); // don't treat as a persistent error } else { grids.emplace_back(std::move(gridSet)); } } return grids; } /***********************************************/ double pj_vgrid_value(PJ *P, const ListOfVGrids &grids, PJ_LP lp, double vmultiplier) { /*********************************************** Read grid value at position lp in grids loaded with proj_grid_init. Returns the grid value of the given coordinate. ************************************************/ double value; value = read_vgrid_value(P->ctx, grids, lp, vmultiplier); if (pj_log_active(P->ctx, PJ_LOG_TRACE)) { proj_log_trace(P, "proj_vgrid_value: (%f, %f) = %f", lp.lam * RAD_TO_DEG, lp.phi * RAD_TO_DEG, value); } return value; } // --------------------------------------------------------------------------- const GenericShiftGrid *pj_find_generic_grid(const ListOfGenericGrids &grids, const PJ_LP &input, GenericShiftGridSet *&gridSetOut) { for (const auto &gridset : grids) { auto grid = gridset->gridAt(input.lam, input.phi); if (grid) { gridSetOut = gridset.get(); return grid; } } return nullptr; } // --------------------------------------------------------------------------- // Used by +proj=deformation and +proj=xyzgridshift to do bilinear interpolation // on 3 sample values per node. bool pj_bilinear_interpolation_three_samples( PJ_CONTEXT *ctx, const GenericShiftGrid *grid, const PJ_LP &lp, int idx1, int idx2, int idx3, double &v1, double &v2, double &v3, bool &must_retry) { must_retry = false; if (grid->isNullGrid()) { v1 = 0.0; v2 = 0.0; v3 = 0.0; return true; } const auto &extent = grid->extentAndRes(); if (!extent.isGeographic) { pj_log(ctx, PJ_LOG_ERROR, "Can only handle grids referenced in a geographic CRS"); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); return false; } // From a input location lp, determine the grid cell into which it falls, // by identifying the lower-left x,y of it (ix, iy), and the upper-right // (ix2, iy2) double grid_x = (lp.lam - extent.west) * extent.invResX; // Special case for grids with world extent, and dealing with wrap-around if (lp.lam < extent.west) { grid_x = (lp.lam + 2 * M_PI - extent.west) * extent.invResX; } else if (lp.lam > extent.east) { grid_x = (lp.lam - 2 * M_PI - extent.west) * extent.invResX; } double grid_y = (lp.phi - extent.south) * extent.invResY; int ix = static_cast<int>(grid_x); int iy = static_cast<int>(grid_y); int ix2 = std::min(ix + 1, grid->width() - 1); int iy2 = std::min(iy + 1, grid->height() - 1); float dx1 = 0.0f, dy1 = 0.0f, dz1 = 0.0f; float dx2 = 0.0f, dy2 = 0.0f, dz2 = 0.0f; float dx3 = 0.0f, dy3 = 0.0f, dz3 = 0.0f; float dx4 = 0.0f, dy4 = 0.0f, dz4 = 0.0f; bool error = (!grid->valueAt(ix, iy, idx1, dx1) || !grid->valueAt(ix, iy, idx2, dy1) || !grid->valueAt(ix, iy, idx3, dz1) || !grid->valueAt(ix2, iy, idx1, dx2) || !grid->valueAt(ix2, iy, idx2, dy2) || !grid->valueAt(ix2, iy, idx3, dz2) || !grid->valueAt(ix, iy2, idx1, dx3) || !grid->valueAt(ix, iy2, idx2, dy3) || !grid->valueAt(ix, iy2, idx3, dz3) || !grid->valueAt(ix2, iy2, idx1, dx4) || !grid->valueAt(ix2, iy2, idx2, dy4) || !grid->valueAt(ix2, iy2, idx3, dz4)); if (grid->hasChanged()) { must_retry = true; return false; } if (error) { return false; } // Bilinear interpolation double frct_lam = grid_x - ix; double frct_phi = grid_y - iy; double m10 = frct_lam; double m11 = m10; double m01 = 1. - frct_lam; double m00 = m01; m11 *= frct_phi; m01 *= frct_phi; frct_phi = 1. - frct_phi; m00 *= frct_phi; m10 *= frct_phi; v1 = m00 * dx1 + m10 * dx2 + m01 * dx3 + m11 * dx4; v2 = m00 * dy1 + m10 * dy2 + m01 * dy3 + m11 * dy4; v3 = m00 * dz1 + m10 * dz2 + m01 * dz3 + m11 * dz4; return true; } NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/wkt2_generated_parser.h
/* A Bison parser, made by GNU Bison 3.5.1. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ #ifndef YY_PJ_WKT2_WKT2_GENERATED_PARSER_H_INCLUDED # define YY_PJ_WKT2_WKT2_GENERATED_PARSER_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int pj_wkt2_debug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { END = 0, T_PROJECTION = 258, T_DATUM = 259, T_SPHEROID = 260, T_PRIMEM = 261, T_UNIT = 262, T_AXIS = 263, T_PARAMETER = 264, T_GEODCRS = 265, T_LENGTHUNIT = 266, T_ANGLEUNIT = 267, T_SCALEUNIT = 268, T_TIMEUNIT = 269, T_ELLIPSOID = 270, T_CS = 271, T_ID = 272, T_PROJCRS = 273, T_BASEGEODCRS = 274, T_MERIDIAN = 275, T_BEARING = 276, T_ORDER = 277, T_ANCHOR = 278, T_ANCHOREPOCH = 279, T_CONVERSION = 280, T_METHOD = 281, T_REMARK = 282, T_GEOGCRS = 283, T_BASEGEOGCRS = 284, T_SCOPE = 285, T_AREA = 286, T_BBOX = 287, T_CITATION = 288, T_URI = 289, T_VERTCRS = 290, T_VDATUM = 291, T_GEOIDMODEL = 292, T_COMPOUNDCRS = 293, T_PARAMETERFILE = 294, T_COORDINATEOPERATION = 295, T_SOURCECRS = 296, T_TARGETCRS = 297, T_INTERPOLATIONCRS = 298, T_OPERATIONACCURACY = 299, T_CONCATENATEDOPERATION = 300, T_STEP = 301, T_BOUNDCRS = 302, T_ABRIDGEDTRANSFORMATION = 303, T_DERIVINGCONVERSION = 304, T_TDATUM = 305, T_CALENDAR = 306, T_TIMEORIGIN = 307, T_TIMECRS = 308, T_VERTICALEXTENT = 309, T_TIMEEXTENT = 310, T_USAGE = 311, T_DYNAMIC = 312, T_FRAMEEPOCH = 313, T_MODEL = 314, T_VELOCITYGRID = 315, T_ENSEMBLE = 316, T_MEMBER = 317, T_ENSEMBLEACCURACY = 318, T_DERIVEDPROJCRS = 319, T_BASEPROJCRS = 320, T_EDATUM = 321, T_ENGCRS = 322, T_PDATUM = 323, T_PARAMETRICCRS = 324, T_PARAMETRICUNIT = 325, T_BASEVERTCRS = 326, T_BASEENGCRS = 327, T_BASEPARAMCRS = 328, T_BASETIMECRS = 329, T_EPOCH = 330, T_COORDEPOCH = 331, T_COORDINATEMETADATA = 332, T_POINTMOTIONOPERATION = 333, T_VERSION = 334, T_AXISMINVALUE = 335, T_AXISMAXVALUE = 336, T_RANGEMEANING = 337, T_exact = 338, T_wraparound = 339, T_GEODETICCRS = 340, T_GEODETICDATUM = 341, T_PROJECTEDCRS = 342, T_PRIMEMERIDIAN = 343, T_GEOGRAPHICCRS = 344, T_TRF = 345, T_VERTICALCRS = 346, T_VERTICALDATUM = 347, T_VRF = 348, T_TIMEDATUM = 349, T_TEMPORALQUANTITY = 350, T_ENGINEERINGDATUM = 351, T_ENGINEERINGCRS = 352, T_PARAMETRICDATUM = 353, T_AFFINE = 354, T_CARTESIAN = 355, T_CYLINDRICAL = 356, T_ELLIPSOIDAL = 357, T_LINEAR = 358, T_PARAMETRIC = 359, T_POLAR = 360, T_SPHERICAL = 361, T_VERTICAL = 362, T_TEMPORAL = 363, T_TEMPORALCOUNT = 364, T_TEMPORALMEASURE = 365, T_ORDINAL = 366, T_TEMPORALDATETIME = 367, T_NORTH = 368, T_NORTHNORTHEAST = 369, T_NORTHEAST = 370, T_EASTNORTHEAST = 371, T_EAST = 372, T_EASTSOUTHEAST = 373, T_SOUTHEAST = 374, T_SOUTHSOUTHEAST = 375, T_SOUTH = 376, T_SOUTHSOUTHWEST = 377, T_SOUTHWEST = 378, T_WESTSOUTHWEST = 379, T_WEST = 380, T_WESTNORTHWEST = 381, T_NORTHWEST = 382, T_NORTHNORTHWEST = 383, T_UP = 384, T_DOWN = 385, T_GEOCENTRICX = 386, T_GEOCENTRICY = 387, T_GEOCENTRICZ = 388, T_COLUMNPOSITIVE = 389, T_COLUMNNEGATIVE = 390, T_ROWPOSITIVE = 391, T_ROWNEGATIVE = 392, T_DISPLAYRIGHT = 393, T_DISPLAYLEFT = 394, T_DISPLAYUP = 395, T_DISPLAYDOWN = 396, T_FORWARD = 397, T_AFT = 398, T_PORT = 399, T_STARBOARD = 400, T_CLOCKWISE = 401, T_COUNTERCLOCKWISE = 402, T_TOWARDS = 403, T_AWAYFROM = 404, T_FUTURE = 405, T_PAST = 406, T_UNSPECIFIED = 407, T_STRING = 408, T_UNSIGNED_INTEGER_DIFFERENT_ONE_TWO_THREE = 409 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif int pj_wkt2_parse (pj_wkt2_parse_context *context); #endif /* !YY_PJ_WKT2_WKT2_GENERATED_PARSER_H_INCLUDED */
h
PROJ
data/projects/PROJ/src/msfn.cpp
/* determine constant small m */ #include "proj.h" #include "proj_internal.h" #include <math.h> double pj_msfn(double sinphi, double cosphi, double es) { return (cosphi / sqrt(1. - es * sinphi * sinphi)); }
cpp
PROJ
data/projects/PROJ/src/quadtree.hpp
/****************************************************************************** * Project: PROJ * Purpose: Implementation of quadtree building and searching functions. * Derived from shapelib, mapserver and GDAL implementations * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 1999-2008, Frank Warmerdam * Copyright (c) 2008-2020, Even Rouault <even dot 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. *****************************************************************************/ #ifndef QUADTREE_HPP #define QUADTREE_HPP #include "proj/util.hpp" #include <functional> #include <vector> //! @cond Doxygen_Suppress NS_PROJ_START namespace QuadTree { /* -------------------------------------------------------------------- */ /* If the following is 0.5, psNodes will be split in half. If it */ /* is 0.6 then each apSubNode will contain 60% of the parent */ /* psNode, with 20% representing overlap. This can be help to */ /* prevent small objects on a boundary from shifting too high */ /* up the hQuadTree. */ /* -------------------------------------------------------------------- */ constexpr double DEFAULT_SPLIT_RATIO = 0.55; /** Describe a rectangle */ struct RectObj { double minx = 0; /**< Minimum x */ double miny = 0; /**< Minimum y */ double maxx = 0; /**< Maximum x */ double maxy = 0; /**< Maximum y */ /* Returns whether this rectangle is contained by other */ inline bool isContainedBy(const RectObj &other) const { return minx >= other.minx && maxx <= other.maxx && miny >= other.miny && maxy <= other.maxy; } /* Returns whether this rectangles overlaps other */ inline bool overlaps(const RectObj &other) const { return minx <= other.maxx && maxx >= other.minx && miny <= other.maxy && maxy >= other.miny; } /* Returns whether this rectangles contains the specified point */ inline bool contains(double x, double y) const { return minx <= x && maxx >= x && miny <= y && maxy >= y; } /* Return whether this rectangles is different from other */ inline bool operator!=(const RectObj &other) const { return minx != other.minx || miny != other.miny || maxx != other.maxx || maxy != other.maxy; } }; /** Quadtree */ template <class Feature> class QuadTree { struct Node { RectObj rect{}; /* area covered by this psNode */ /* list of shapes stored at this node. */ std::vector<std::pair<Feature, RectObj>> features{}; std::vector<Node> subnodes{}; explicit Node(const RectObj &rectIn) : rect(rectIn) {} }; Node root{}; unsigned nBucketCapacity = 8; double dfSplitRatio = DEFAULT_SPLIT_RATIO; public: /** Construct a new quadtree with the global bounds of all objects to be * inserted */ explicit QuadTree(const RectObj &globalBounds) : root(globalBounds) {} /** Add a new feature, with its bounds specified in featureBounds */ void insert(const Feature &feature, const RectObj &featureBounds) { insert(root, feature, featureBounds); } #ifdef UNUSED /** Retrieve all features whose bounds intersects aoiRect */ void search(const RectObj &aoiRect, std::vector<std::reference_wrapper<const Feature>> &features) const { search(root, aoiRect, features); } #endif /** Retrieve all features whose bounds contains (x,y) */ void search(double x, double y, std::vector<Feature> &features) const { search(root, x, y, features); } private: void splitBounds(const RectObj &in, RectObj &out1, RectObj &out2) { // The output bounds will be very similar to the input bounds, // so just copy over to start. out1 = in; out2 = in; // Split in X direction. if ((in.maxx - in.minx) > (in.maxy - in.miny)) { const double range = in.maxx - in.minx; out1.maxx = in.minx + range * dfSplitRatio; out2.minx = in.maxx - range * dfSplitRatio; } // Otherwise split in Y direction. else { const double range = in.maxy - in.miny; out1.maxy = in.miny + range * dfSplitRatio; out2.miny = in.maxy - range * dfSplitRatio; } } void insert(Node &node, const Feature &feature, const RectObj &featureBounds) { if (node.subnodes.empty()) { // If we have reached the max bucket capacity, try to insert // in a subnode if possible. if (node.features.size() >= nBucketCapacity) { RectObj half1; RectObj half2; RectObj quad1; RectObj quad2; RectObj quad3; RectObj quad4; splitBounds(node.rect, half1, half2); splitBounds(half1, quad1, quad2); splitBounds(half2, quad3, quad4); if (node.rect != quad1 && node.rect != quad2 && node.rect != quad3 && node.rect != quad4 && (featureBounds.isContainedBy(quad1) || featureBounds.isContainedBy(quad2) || featureBounds.isContainedBy(quad3) || featureBounds.isContainedBy(quad4))) { node.subnodes.reserve(4); node.subnodes.emplace_back(Node(quad1)); node.subnodes.emplace_back(Node(quad2)); node.subnodes.emplace_back(Node(quad3)); node.subnodes.emplace_back(Node(quad4)); auto features = std::move(node.features); node.features.clear(); for (auto &pair : features) { insert(node, pair.first, pair.second); } /* recurse back on this psNode now that it has apSubNodes */ insert(node, feature, featureBounds); return; } } } else { // If we have sub nodes, then consider whether this object will // fit in them. for (auto &subnode : node.subnodes) { if (featureBounds.isContainedBy(subnode.rect)) { insert(subnode, feature, featureBounds); return; } } } // If none of that worked, just add it to this nodes list. node.features.push_back( std::pair<Feature, RectObj>(feature, featureBounds)); } #ifdef UNUSED void search(const Node &node, const RectObj &aoiRect, std::vector<std::reference_wrapper<const Feature>> &features) const { // Does this node overlap the area of interest at all? If not, // return without adding to the list at all. if (!node.rect.overlaps(aoiRect)) return; // Add the local features to the list. for (const auto &pair : node.features) { if (pair.second.overlaps(aoiRect)) { features.push_back( std::reference_wrapper<const Feature>(pair.first)); } } // Recurse to subnodes if they exist. for (const auto &subnode : node.subnodes) { search(subnode, aoiRect, features); } } #endif void search(const Node &node, double x, double y, std::vector<Feature> &features) const { // Does this node overlap the area of interest at all? If not, // return without adding to the list at all. if (!node.rect.contains(x, y)) return; // Add the local features to the list. for (const auto &pair : node.features) { if (pair.second.contains(x, y)) { features.push_back(pair.first); } } // Recurse to subnodes if they exist. for (const auto &subnode : node.subnodes) { search(subnode, x, y, features); } } }; } // namespace QuadTree NS_PROJ_END //! @endcond #endif // QUADTREE_HPP
hpp
PROJ
data/projects/PROJ/src/generic_inverse.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Generic method to compute inverse projection from forward method * 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 "proj_internal.h" #include <algorithm> #include <cmath> /** Compute (lam, phi) corresponding to input (xy.x, xy.y) for projection P. * * Uses Newton-Raphson method, extended to 2D variables, that is using * inversion of the Jacobian 2D matrix of partial derivatives. The derivatives * are estimated numerically from the P->fwd method evaluated at close points. * * Note: thresholds used have been verified to work with adams_ws2 and wink2 * * Starts with initial guess provided by user in lpInitial */ PJ_LP pj_generic_inverse_2d(PJ_XY xy, PJ *P, PJ_LP lpInitial, double deltaXYTolerance) { PJ_LP lp = lpInitial; double deriv_lam_X = 0; double deriv_lam_Y = 0; double deriv_phi_X = 0; double deriv_phi_Y = 0; for (int i = 0; i < 15; i++) { PJ_XY xyApprox = P->fwd(lp, P); const double deltaX = xyApprox.x - xy.x; const double deltaY = xyApprox.y - xy.y; if (fabs(deltaX) < deltaXYTolerance && fabs(deltaY) < deltaXYTolerance) { return lp; } if (i == 0 || fabs(deltaX) > 1e-6 || fabs(deltaY) > 1e-6) { // Compute Jacobian matrix (only if we aren't close to the final // result to speed things a bit) PJ_LP lp2; PJ_XY xy2; const double dLam = lp.lam > 0 ? -1e-6 : 1e-6; lp2.lam = lp.lam + dLam; lp2.phi = lp.phi; xy2 = P->fwd(lp2, P); const double deriv_X_lam = (xy2.x - xyApprox.x) / dLam; const double deriv_Y_lam = (xy2.y - xyApprox.y) / dLam; const double dPhi = lp.phi > 0 ? -1e-6 : 1e-6; lp2.lam = lp.lam; lp2.phi = lp.phi + dPhi; xy2 = P->fwd(lp2, P); const double deriv_X_phi = (xy2.x - xyApprox.x) / dPhi; const double deriv_Y_phi = (xy2.y - xyApprox.y) / dPhi; // Inverse of Jacobian matrix const double det = deriv_X_lam * deriv_Y_phi - deriv_X_phi * deriv_Y_lam; if (det != 0) { deriv_lam_X = deriv_Y_phi / det; deriv_lam_Y = -deriv_X_phi / det; deriv_phi_X = -deriv_Y_lam / det; deriv_phi_Y = deriv_X_lam / det; } } if (xy.x != 0) { // Limit the amplitude of correction to avoid overshoots due to // bad initial guess const double delta_lam = std::max( std::min(deltaX * deriv_lam_X + deltaY * deriv_lam_Y, 0.3), -0.3); lp.lam -= delta_lam; if (lp.lam < -M_PI) lp.lam = -M_PI; else if (lp.lam > M_PI) lp.lam = M_PI; } if (xy.y != 0) { const double delta_phi = std::max( std::min(deltaX * deriv_phi_X + deltaY * deriv_phi_Y, 0.3), -0.3); lp.phi -= delta_phi; if (lp.phi < -M_HALFPI) lp.phi = -M_HALFPI; else if (lp.phi > M_HALFPI) lp.phi = M_HALFPI; } } proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; }
cpp
PROJ
data/projects/PROJ/src/proj_symbol_rename.h
/* This is a generated file by create_proj_symbol_rename.sh. *DO NOT EDIT * MANUALLY !* */ #ifndef PROJ_SYMBOL_RENAME_H #define PROJ_SYMBOL_RENAME_H #define geod_direct internal_geod_direct #define geod_directline internal_geod_directline #define geod_gendirect internal_geod_gendirect #define geod_gendirectline internal_geod_gendirectline #define geod_geninverse internal_geod_geninverse #define geod_genposition internal_geod_genposition #define geod_gensetdistance internal_geod_gensetdistance #define geod_init internal_geod_init #define geod_inverse internal_geod_inverse #define geod_inverseline internal_geod_inverseline #define geod_lineinit internal_geod_lineinit #define geod_polygon_addedge internal_geod_polygon_addedge #define geod_polygon_addpoint internal_geod_polygon_addpoint #define geod_polygonarea internal_geod_polygonarea #define geod_polygon_clear internal_geod_polygon_clear #define geod_polygon_compute internal_geod_polygon_compute #define geod_polygon_init internal_geod_polygon_init #define geod_polygon_testedge internal_geod_polygon_testedge #define geod_polygon_testpoint internal_geod_polygon_testpoint #define geod_position internal_geod_position #define geod_setdistance internal_geod_setdistance #define proj_alter_id internal_proj_alter_id #define proj_alter_name internal_proj_alter_name #define proj_angular_input internal_proj_angular_input #define proj_angular_output internal_proj_angular_output #define proj_area_create internal_proj_area_create #define proj_area_destroy internal_proj_area_destroy #define proj_area_set_bbox internal_proj_area_set_bbox #define proj_area_set_name internal_proj_area_set_name #define proj_as_projjson internal_proj_as_projjson #define proj_as_proj_string internal_proj_as_proj_string #define proj_assign_context internal_proj_assign_context #define proj_as_wkt internal_proj_as_wkt #define proj_celestial_body_list_destroy \ internal_proj_celestial_body_list_destroy #define proj_cleanup internal_proj_cleanup #define proj_clone internal_proj_clone #define proj_concatoperation_get_step internal_proj_concatoperation_get_step #define proj_concatoperation_get_step_count \ internal_proj_concatoperation_get_step_count #define proj_context_clone internal_proj_context_clone #define proj_context_create internal_proj_context_create #define proj_context_destroy internal_proj_context_destroy #define proj_context_errno internal_proj_context_errno #define proj_context_errno_string internal_proj_context_errno_string #define proj_context_get_database_metadata \ internal_proj_context_get_database_metadata #define proj_context_get_database_path internal_proj_context_get_database_path #define proj_context_get_database_structure \ internal_proj_context_get_database_structure #define proj_context_get_url_endpoint internal_proj_context_get_url_endpoint #define proj_context_get_use_proj4_init_rules \ internal_proj_context_get_use_proj4_init_rules #define proj_context_get_user_writable_directory \ internal_proj_context_get_user_writable_directory #define proj_context_guess_wkt_dialect internal_proj_context_guess_wkt_dialect #define proj_context_is_network_enabled internal_proj_context_is_network_enabled #define proj_context_set_autoclose_database \ internal_proj_context_set_autoclose_database #define proj_context_set_ca_bundle_path internal_proj_context_set_ca_bundle_path #define proj_context_set_database_path internal_proj_context_set_database_path #define proj_context_set_enable_network internal_proj_context_set_enable_network #define proj_context_set_fileapi internal_proj_context_set_fileapi #define proj_context_set_file_finder internal_proj_context_set_file_finder #define proj_context_set_network_callbacks \ internal_proj_context_set_network_callbacks #define proj_context_set_search_paths internal_proj_context_set_search_paths #define proj_context_set_sqlite3_vfs_name \ internal_proj_context_set_sqlite3_vfs_name #define proj_context_set_url_endpoint internal_proj_context_set_url_endpoint #define proj_context_use_proj4_init_rules \ internal_proj_context_use_proj4_init_rules #define proj_convert_conversion_to_other_method \ internal_proj_convert_conversion_to_other_method #define proj_coord internal_proj_coord #define proj_coordinate_metadata_get_epoch \ internal_proj_coordinate_metadata_get_epoch #define proj_coordoperation_create_inverse \ internal_proj_coordoperation_create_inverse #define proj_coordoperation_get_accuracy \ internal_proj_coordoperation_get_accuracy #define proj_coordoperation_get_grid_used \ internal_proj_coordoperation_get_grid_used #define proj_coordoperation_get_grid_used_count \ internal_proj_coordoperation_get_grid_used_count #define proj_coordoperation_get_method_info \ internal_proj_coordoperation_get_method_info #define proj_coordoperation_get_param internal_proj_coordoperation_get_param #define proj_coordoperation_get_param_count \ internal_proj_coordoperation_get_param_count #define proj_coordoperation_get_param_index \ internal_proj_coordoperation_get_param_index #define proj_coordoperation_get_towgs84_values \ internal_proj_coordoperation_get_towgs84_values #define proj_coordoperation_has_ballpark_transformation \ internal_proj_coordoperation_has_ballpark_transformation #define proj_coordoperation_is_instantiable \ internal_proj_coordoperation_is_instantiable #define proj_create internal_proj_create #define proj_create_argv internal_proj_create_argv #define proj_create_cartesian_2D_cs internal_proj_create_cartesian_2D_cs #define proj_create_compound_crs internal_proj_create_compound_crs #define proj_create_conversion internal_proj_create_conversion #define proj_create_conversion_albers_equal_area \ internal_proj_create_conversion_albers_equal_area #define proj_create_conversion_american_polyconic \ internal_proj_create_conversion_american_polyconic #define proj_create_conversion_azimuthal_equidistant \ internal_proj_create_conversion_azimuthal_equidistant #define proj_create_conversion_bonne internal_proj_create_conversion_bonne #define proj_create_conversion_cassini_soldner \ internal_proj_create_conversion_cassini_soldner #define proj_create_conversion_eckert_i internal_proj_create_conversion_eckert_i #define proj_create_conversion_eckert_ii \ internal_proj_create_conversion_eckert_ii #define proj_create_conversion_eckert_iii \ internal_proj_create_conversion_eckert_iii #define proj_create_conversion_eckert_iv \ internal_proj_create_conversion_eckert_iv #define proj_create_conversion_eckert_v internal_proj_create_conversion_eckert_v #define proj_create_conversion_eckert_vi \ internal_proj_create_conversion_eckert_vi #define proj_create_conversion_equal_earth \ internal_proj_create_conversion_equal_earth #define proj_create_conversion_equidistant_conic \ internal_proj_create_conversion_equidistant_conic #define proj_create_conversion_equidistant_cylindrical \ internal_proj_create_conversion_equidistant_cylindrical #define proj_create_conversion_equidistant_cylindrical_spherical \ internal_proj_create_conversion_equidistant_cylindrical_spherical #define proj_create_conversion_gall internal_proj_create_conversion_gall #define proj_create_conversion_gauss_schreiber_transverse_mercator \ internal_proj_create_conversion_gauss_schreiber_transverse_mercator #define proj_create_conversion_geostationary_satellite_sweep_x \ internal_proj_create_conversion_geostationary_satellite_sweep_x #define proj_create_conversion_geostationary_satellite_sweep_y \ internal_proj_create_conversion_geostationary_satellite_sweep_y #define proj_create_conversion_gnomonic internal_proj_create_conversion_gnomonic #define proj_create_conversion_goode_homolosine \ internal_proj_create_conversion_goode_homolosine #define proj_create_conversion_guam_projection \ internal_proj_create_conversion_guam_projection #define proj_create_conversion_hotine_oblique_mercator_two_point_natural_origin \ internal_proj_create_conversion_hotine_oblique_mercator_two_point_natural_origin #define proj_create_conversion_hotine_oblique_mercator_variant_a \ internal_proj_create_conversion_hotine_oblique_mercator_variant_a #define proj_create_conversion_hotine_oblique_mercator_variant_b \ internal_proj_create_conversion_hotine_oblique_mercator_variant_b #define proj_create_conversion_international_map_world_polyconic \ internal_proj_create_conversion_international_map_world_polyconic #define proj_create_conversion_interrupted_goode_homolosine \ internal_proj_create_conversion_interrupted_goode_homolosine #define proj_create_conversion_krovak internal_proj_create_conversion_krovak #define proj_create_conversion_krovak_north_oriented \ internal_proj_create_conversion_krovak_north_oriented #define proj_create_conversion_laborde_oblique_mercator \ internal_proj_create_conversion_laborde_oblique_mercator #define proj_create_conversion_lambert_azimuthal_equal_area \ internal_proj_create_conversion_lambert_azimuthal_equal_area #define proj_create_conversion_lambert_conic_conformal_1sp \ internal_proj_create_conversion_lambert_conic_conformal_1sp #define proj_create_conversion_lambert_conic_conformal_2sp \ internal_proj_create_conversion_lambert_conic_conformal_2sp #define proj_create_conversion_lambert_conic_conformal_2sp_belgium \ internal_proj_create_conversion_lambert_conic_conformal_2sp_belgium #define proj_create_conversion_lambert_conic_conformal_2sp_michigan \ internal_proj_create_conversion_lambert_conic_conformal_2sp_michigan #define proj_create_conversion_lambert_cylindrical_equal_area \ internal_proj_create_conversion_lambert_cylindrical_equal_area #define proj_create_conversion_lambert_cylindrical_equal_area_spherical \ internal_proj_create_conversion_lambert_cylindrical_equal_area_spherical #define proj_create_conversion_mercator_variant_a \ internal_proj_create_conversion_mercator_variant_a #define proj_create_conversion_mercator_variant_b \ internal_proj_create_conversion_mercator_variant_b #define proj_create_conversion_miller_cylindrical \ internal_proj_create_conversion_miller_cylindrical #define proj_create_conversion_mollweide \ internal_proj_create_conversion_mollweide #define proj_create_conversion_new_zealand_mapping_grid \ internal_proj_create_conversion_new_zealand_mapping_grid #define proj_create_conversion_oblique_stereographic \ internal_proj_create_conversion_oblique_stereographic #define proj_create_conversion_orthographic \ internal_proj_create_conversion_orthographic #define proj_create_conversion_polar_stereographic_variant_a \ internal_proj_create_conversion_polar_stereographic_variant_a #define proj_create_conversion_polar_stereographic_variant_b \ internal_proj_create_conversion_polar_stereographic_variant_b #define proj_create_conversion_pole_rotation_grib_convention \ internal_proj_create_conversion_pole_rotation_grib_convention #define proj_create_conversion_pole_rotation_netcdf_cf_convention \ internal_proj_create_conversion_pole_rotation_netcdf_cf_convention #define proj_create_conversion_popular_visualisation_pseudo_mercator \ internal_proj_create_conversion_popular_visualisation_pseudo_mercator #define proj_create_conversion_quadrilateralized_spherical_cube \ internal_proj_create_conversion_quadrilateralized_spherical_cube #define proj_create_conversion_robinson internal_proj_create_conversion_robinson #define proj_create_conversion_sinusoidal \ internal_proj_create_conversion_sinusoidal #define proj_create_conversion_spherical_cross_track_height \ internal_proj_create_conversion_spherical_cross_track_height #define proj_create_conversion_stereographic \ internal_proj_create_conversion_stereographic #define proj_create_conversion_transverse_mercator \ internal_proj_create_conversion_transverse_mercator #define proj_create_conversion_transverse_mercator_south_oriented \ internal_proj_create_conversion_transverse_mercator_south_oriented #define proj_create_conversion_tunisia_mapping_grid \ internal_proj_create_conversion_tunisia_mapping_grid #define proj_create_conversion_tunisia_mining_grid \ internal_proj_create_conversion_tunisia_mining_grid #define proj_create_conversion_two_point_equidistant \ internal_proj_create_conversion_two_point_equidistant #define proj_create_conversion_utm internal_proj_create_conversion_utm #define proj_create_conversion_van_der_grinten \ internal_proj_create_conversion_van_der_grinten #define proj_create_conversion_vertical_perspective \ internal_proj_create_conversion_vertical_perspective #define proj_create_conversion_wagner_i internal_proj_create_conversion_wagner_i #define proj_create_conversion_wagner_ii \ internal_proj_create_conversion_wagner_ii #define proj_create_conversion_wagner_iii \ internal_proj_create_conversion_wagner_iii #define proj_create_conversion_wagner_iv \ internal_proj_create_conversion_wagner_iv #define proj_create_conversion_wagner_v internal_proj_create_conversion_wagner_v #define proj_create_conversion_wagner_vi \ internal_proj_create_conversion_wagner_vi #define proj_create_conversion_wagner_vii \ internal_proj_create_conversion_wagner_vii #define proj_create_crs_to_crs internal_proj_create_crs_to_crs #define proj_create_crs_to_crs_from_pj internal_proj_create_crs_to_crs_from_pj #define proj_create_cs internal_proj_create_cs #define proj_create_derived_geographic_crs \ internal_proj_create_derived_geographic_crs #define proj_create_ellipsoidal_2D_cs internal_proj_create_ellipsoidal_2D_cs #define proj_create_ellipsoidal_3D_cs internal_proj_create_ellipsoidal_3D_cs #define proj_create_engineering_crs internal_proj_create_engineering_crs #define proj_create_from_database internal_proj_create_from_database #define proj_create_from_name internal_proj_create_from_name #define proj_create_from_wkt internal_proj_create_from_wkt #define proj_create_geocentric_crs internal_proj_create_geocentric_crs #define proj_create_geocentric_crs_from_datum \ internal_proj_create_geocentric_crs_from_datum #define proj_create_geographic_crs internal_proj_create_geographic_crs #define proj_create_geographic_crs_from_datum \ internal_proj_create_geographic_crs_from_datum #define proj_create_operation_factory_context \ internal_proj_create_operation_factory_context #define proj_create_operations internal_proj_create_operations #define proj_create_projected_crs internal_proj_create_projected_crs #define proj_create_transformation internal_proj_create_transformation #define proj_create_vertical_crs internal_proj_create_vertical_crs #define proj_create_vertical_crs_ex internal_proj_create_vertical_crs_ex #define proj_crs_alter_cs_angular_unit internal_proj_crs_alter_cs_angular_unit #define proj_crs_alter_cs_linear_unit internal_proj_crs_alter_cs_linear_unit #define proj_crs_alter_geodetic_crs internal_proj_crs_alter_geodetic_crs #define proj_crs_alter_parameters_linear_unit \ internal_proj_crs_alter_parameters_linear_unit #define proj_crs_create_bound_crs internal_proj_crs_create_bound_crs #define proj_crs_create_bound_crs_to_WGS84 \ internal_proj_crs_create_bound_crs_to_WGS84 #define proj_crs_create_bound_vertical_crs \ internal_proj_crs_create_bound_vertical_crs #define proj_crs_create_projected_3D_crs_from_2D \ internal_proj_crs_create_projected_3D_crs_from_2D #define proj_crs_demote_to_2D internal_proj_crs_demote_to_2D #define proj_crs_get_coordinate_system internal_proj_crs_get_coordinate_system #define proj_crs_get_coordoperation internal_proj_crs_get_coordoperation #define proj_crs_get_datum internal_proj_crs_get_datum #define proj_crs_get_datum_ensemble internal_proj_crs_get_datum_ensemble #define proj_crs_get_datum_forced internal_proj_crs_get_datum_forced #define proj_crs_get_geodetic_crs internal_proj_crs_get_geodetic_crs #define proj_crs_get_horizontal_datum internal_proj_crs_get_horizontal_datum #define proj_crs_get_sub_crs internal_proj_crs_get_sub_crs #define proj_crs_info_list_destroy internal_proj_crs_info_list_destroy #define proj_crs_is_derived internal_proj_crs_is_derived #define proj_crs_promote_to_3D internal_proj_crs_promote_to_3D #define proj_cs_get_axis_count internal_proj_cs_get_axis_count #define proj_cs_get_axis_info internal_proj_cs_get_axis_info #define proj_cs_get_type internal_proj_cs_get_type #define proj_datum_ensemble_get_accuracy \ internal_proj_datum_ensemble_get_accuracy #define proj_datum_ensemble_get_member internal_proj_datum_ensemble_get_member #define proj_datum_ensemble_get_member_count \ internal_proj_datum_ensemble_get_member_count #define proj_degree_input internal_proj_degree_input #define proj_degree_output internal_proj_degree_output #define proj_destroy internal_proj_destroy #define proj_dmstor internal_proj_dmstor #define proj_download_file internal_proj_download_file #define proj_dynamic_datum_get_frame_reference_epoch \ internal_proj_dynamic_datum_get_frame_reference_epoch #define proj_ellipsoid_get_parameters internal_proj_ellipsoid_get_parameters #define proj_errno internal_proj_errno #define proj_errno_reset internal_proj_errno_reset #define proj_errno_restore internal_proj_errno_restore #define proj_errno_set internal_proj_errno_set #define proj_errno_string internal_proj_errno_string #define proj_factors internal_proj_factors #define proj_geod internal_proj_geod #define proj_get_area_of_use internal_proj_get_area_of_use #define proj_get_authorities_from_database \ internal_proj_get_authorities_from_database #define proj_get_celestial_body_list_from_database \ internal_proj_get_celestial_body_list_from_database #define proj_get_celestial_body_name internal_proj_get_celestial_body_name #define proj_get_codes_from_database internal_proj_get_codes_from_database #define proj_get_crs_info_list_from_database \ internal_proj_get_crs_info_list_from_database #define proj_get_crs_list_parameters_create \ internal_proj_get_crs_list_parameters_create #define proj_get_crs_list_parameters_destroy \ internal_proj_get_crs_list_parameters_destroy #define proj_get_ellipsoid internal_proj_get_ellipsoid #define proj_get_geoid_models_from_database \ internal_proj_get_geoid_models_from_database #define proj_get_id_auth_name internal_proj_get_id_auth_name #define proj_get_id_code internal_proj_get_id_code #define proj_get_insert_statements internal_proj_get_insert_statements #define proj_get_name internal_proj_get_name #define proj_get_non_deprecated internal_proj_get_non_deprecated #define proj_get_prime_meridian internal_proj_get_prime_meridian #define proj_get_remarks internal_proj_get_remarks #define proj_get_scope internal_proj_get_scope #define proj_get_source_crs internal_proj_get_source_crs #define proj_get_suggested_operation internal_proj_get_suggested_operation #define proj_get_target_crs internal_proj_get_target_crs #define proj_get_type internal_proj_get_type #define proj_get_units_from_database internal_proj_get_units_from_database #define proj_grid_cache_clear internal_proj_grid_cache_clear #define proj_grid_cache_set_enable internal_proj_grid_cache_set_enable #define proj_grid_cache_set_filename internal_proj_grid_cache_set_filename #define proj_grid_cache_set_max_size internal_proj_grid_cache_set_max_size #define proj_grid_cache_set_ttl internal_proj_grid_cache_set_ttl #define proj_grid_get_info_from_database \ internal_proj_grid_get_info_from_database #define proj_grid_info internal_proj_grid_info #define proj_identify internal_proj_identify #define proj_info internal_proj_info #define proj_init_info internal_proj_init_info #define proj_insert_object_session_create \ internal_proj_insert_object_session_create #define proj_insert_object_session_destroy \ internal_proj_insert_object_session_destroy #define proj_int_list_destroy internal_proj_int_list_destroy #define proj_is_crs internal_proj_is_crs #define proj_is_deprecated internal_proj_is_deprecated #define proj_is_derived_crs internal_proj_is_derived_crs #define proj_is_download_needed internal_proj_is_download_needed #define proj_is_equivalent_to internal_proj_is_equivalent_to #define proj_is_equivalent_to_with_ctx internal_proj_is_equivalent_to_with_ctx #define proj_list_angular_units internal_proj_list_angular_units #define proj_list_destroy internal_proj_list_destroy #define proj_list_ellps internal_proj_list_ellps #define proj_list_get internal_proj_list_get #define proj_list_get_count internal_proj_list_get_count #define proj_list_operations internal_proj_list_operations #define proj_list_prime_meridians internal_proj_list_prime_meridians #define proj_list_units internal_proj_list_units #define proj_log_func internal_proj_log_func #define proj_log_level internal_proj_log_level #define proj_lp_dist internal_proj_lp_dist #define proj_lpz_dist internal_proj_lpz_dist #define proj_normalize_for_visualization \ internal_proj_normalize_for_visualization #define proj_operation_factory_context_destroy \ internal_proj_operation_factory_context_destroy #define proj_operation_factory_context_set_allow_ballpark_transformations \ internal_proj_operation_factory_context_set_allow_ballpark_transformations #define proj_operation_factory_context_set_allowed_intermediate_crs \ internal_proj_operation_factory_context_set_allowed_intermediate_crs #define proj_operation_factory_context_set_allow_use_intermediate_crs \ internal_proj_operation_factory_context_set_allow_use_intermediate_crs #define proj_operation_factory_context_set_area_of_interest \ internal_proj_operation_factory_context_set_area_of_interest #define proj_operation_factory_context_set_area_of_interest_name \ internal_proj_operation_factory_context_set_area_of_interest_name #define proj_operation_factory_context_set_crs_extent_use \ internal_proj_operation_factory_context_set_crs_extent_use #define proj_operation_factory_context_set_desired_accuracy \ internal_proj_operation_factory_context_set_desired_accuracy #define proj_operation_factory_context_set_discard_superseded \ internal_proj_operation_factory_context_set_discard_superseded #define proj_operation_factory_context_set_grid_availability_use \ internal_proj_operation_factory_context_set_grid_availability_use #define proj_operation_factory_context_set_spatial_criterion \ internal_proj_operation_factory_context_set_spatial_criterion #define proj_operation_factory_context_set_use_proj_alternative_grid_names \ internal_proj_operation_factory_context_set_use_proj_alternative_grid_names #define proj_pj_info internal_proj_pj_info #define proj_prime_meridian_get_parameters \ internal_proj_prime_meridian_get_parameters #define proj_query_geodetic_crs_from_datum \ internal_proj_query_geodetic_crs_from_datum #define proj_roundtrip internal_proj_roundtrip #define proj_rtodms internal_proj_rtodms #define proj_rtodms2 internal_proj_rtodms2 #define proj_string_destroy internal_proj_string_destroy #define proj_string_list_destroy internal_proj_string_list_destroy #define proj_suggests_code_for internal_proj_suggests_code_for #define proj_todeg internal_proj_todeg #define proj_torad internal_proj_torad #define proj_trans internal_proj_trans #define proj_trans_array internal_proj_trans_array #define proj_trans_bounds internal_proj_trans_bounds #define proj_trans_generic internal_proj_trans_generic #define proj_trans_get_last_used_operation \ internal_proj_trans_get_last_used_operation #define proj_unit_list_destroy internal_proj_unit_list_destroy #define proj_uom_get_info_from_database internal_proj_uom_get_info_from_database #define proj_xy_dist internal_proj_xy_dist #define proj_xyz_dist internal_proj_xyz_dist #define pj_release internal_pj_release #endif /* PROJ_SYMBOL_RENAME_H */
h
PROJ
data/projects/PROJ/src/wkt1_parser.h
/****************************************************************************** * Project: PROJ * Purpose: WKT1 parser grammar * Author: Even Rouault, <even dot rouault at mines dash paris dot org> * ****************************************************************************** * Copyright (c) 2013, Even Rouault <even dot rouault at mines-paris dot org> * * 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 PJ_WKT1_PARSER_H_INCLUDED #define PJ_WKT1_PARSER_H_INCLUDED #ifndef DOXYGEN_SKIP #ifdef __cplusplus extern "C" { #endif typedef struct pj_wkt1_parse_context pj_wkt1_parse_context; #include "wkt1_generated_parser.h" void pj_wkt1_error(pj_wkt1_parse_context *context, const char *msg); int pj_wkt1_lex(YYSTYPE *pNode, pj_wkt1_parse_context *context); int pj_wkt1_parse(pj_wkt1_parse_context *context); #ifdef __cplusplus } std::string pj_wkt1_parse(const std::string &wkt); #endif #endif /* #ifndef DOXYGEN_SKIP */ #endif /* PJ_WKT1_PARSER_H_INCLUDED */
h
PROJ
data/projects/PROJ/src/units.cpp
/* definition of standard cartesian units */ #include <stddef.h> #include "proj.h" #include "proj_internal.h" /* Field 2 that contains the multiplier to convert named units to meters ** may be expressed by either a simple floating point constant or a ** numerator/denomenator values (e.g. 1/1000) */ static const struct PJ_UNITS pj_units[] = { {"km", "1000", "Kilometer", 1000.0}, {"m", "1", "Meter", 1.0}, {"dm", "1/10", "Decimeter", 0.1}, {"cm", "1/100", "Centimeter", 0.01}, {"mm", "1/1000", "Millimeter", 0.001}, {"kmi", "1852", "International Nautical Mile", 1852.0}, {"in", "0.0254", "International Inch", 0.0254}, {"ft", "0.3048", "International Foot", 0.3048}, {"yd", "0.9144", "International Yard", 0.9144}, {"mi", "1609.344", "International Statute Mile", 1609.344}, {"fath", "1.8288", "International Fathom", 1.8288}, {"ch", "20.1168", "International Chain", 20.1168}, {"link", "0.201168", "International Link", 0.201168}, {"us-in", "1/39.37", "U.S. Surveyor's Inch", 100 / 3937.0}, {"us-ft", "0.304800609601219", "U.S. Surveyor's Foot", 1200 / 3937.0}, {"us-yd", "0.914401828803658", "U.S. Surveyor's Yard", 3600 / 3937.0}, {"us-ch", "20.11684023368047", "U.S. Surveyor's Chain", 79200 / 3937.0}, {"us-mi", "1609.347218694437", "U.S. Surveyor's Statute Mile", 6336000 / 3937.0}, {"ind-yd", "0.91439523", "Indian Yard", 0.91439523}, {"ind-ft", "0.30479841", "Indian Foot", 0.30479841}, {"ind-ch", "20.11669506", "Indian Chain", 20.11669506}, {nullptr, nullptr, nullptr, 0.0}}; // For internal use const PJ_UNITS *pj_list_linear_units() { return pj_units; } const PJ_UNITS *proj_list_units() { return pj_units; } /* M_PI / 200 */ #define GRAD_TO_RAD 0.015707963267948967 const struct PJ_UNITS pj_angular_units[] = { {"rad", "1.0", "Radian", 1.0}, {"deg", "0.017453292519943296", "Degree", DEG_TO_RAD}, {"grad", "0.015707963267948967", "Grad", GRAD_TO_RAD}, {nullptr, nullptr, nullptr, 0.0}}; // For internal use const PJ_UNITS *pj_list_angular_units() { return pj_angular_units; } const PJ_UNITS *proj_list_angular_units() { return pj_angular_units; }
cpp
PROJ
data/projects/PROJ/src/init.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Initialize projection object from string definition. Includes * pj_init(), and pj_init_plus() function. * Author: Gerald Evenden, Frank Warmerdam <[email protected]> * ****************************************************************************** * Copyright (c) 1995, Gerald Evenden * Copyright (c) 2002, Frank Warmerdam <[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 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 <stddef.h> #include <stdio.h> #include <string.h> #include "filemanager.hpp" #include "geodesic.h" #include "proj.h" #include "proj_internal.h" #include <math.h> /**************************************************************************************/ static paralist *string_to_paralist(PJ_CONTEXT *ctx, char *definition) { /*************************************************************************************** Convert a string (presumably originating from get_init_string) to a paralist. ***************************************************************************************/ const char *c = definition; paralist *first = nullptr, *last = nullptr; while (*c) { /* Keep a handle to the start of the list, so we have something to * return */ auto param = pj_mkparam_ws(c, &c); if (nullptr == param) { free_params(ctx, first, PROJ_ERR_OTHER /*ENOMEM*/); return nullptr; } if (nullptr == last) { first = param; } else { last->next = param; } last = param; } return first; } /**************************************************************************************/ static char *get_init_string(PJ_CONTEXT *ctx, const char *name) { /*************************************************************************************** Read a section of an init file. Return its contents as a plain character string. It is the duty of the caller to free the memory allocated for the string. ***************************************************************************************/ #define MAX_LINE_LENGTH 1000 size_t current_buffer_size = 5 * (MAX_LINE_LENGTH + 1); char *fname, *section; const char *key; char *buffer = nullptr; size_t n; fname = static_cast<char *>(malloc(MAX_PATH_FILENAME + ID_TAG_MAX + 3)); if (nullptr == fname) { return nullptr; } /* Support "init=file:section", "+init=file:section", and "file:section" * format */ key = strstr(name, "init="); if (nullptr == key) key = name; else key += 5; if (MAX_PATH_FILENAME + ID_TAG_MAX + 2 < strlen(key)) { free(fname); return nullptr; } memmove(fname, key, strlen(key) + 1); /* Locate the name of the section we search for */ section = strrchr(fname, ':'); if (nullptr == section) { pj_log(ctx, PJ_LOG_ERROR, _("Missing colon in +init")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); free(fname); return nullptr; } *section = 0; section++; n = strlen(section); pj_log(ctx, PJ_LOG_TRACE, "get_init_string: searching for section [%s] in init file [%s]", section, fname); auto file = NS_PROJ::FileManager::open_resource_file(ctx, fname); if (nullptr == file) { pj_log(ctx, PJ_LOG_ERROR, _("Cannot open %s"), fname); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); free(fname); return nullptr; } /* Search for section in init file */ std::string line; for (;;) { bool eofReached = false; bool maxLenReached = false; line = file->read_line(MAX_LINE_LENGTH, maxLenReached, eofReached); /* End of file? */ if (maxLenReached || eofReached) { pj_log(ctx, PJ_LOG_ERROR, _("Invalid content for %s"), fname); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); free(fname); return nullptr; } /* At start of right section? */ pj_chomp(&line[0]); if ('<' != line[0]) continue; if (strlen(line.c_str()) < n + 2) continue; if (line[n + 1] != '>') continue; if (0 == strncmp(line.data() + 1, section, n)) break; } /* We're at the first line of the right section - copy line to buffer */ buffer = static_cast<char *>(malloc(current_buffer_size)); if (nullptr == buffer) { free(fname); return nullptr; } /* Skip the "<section>" indicator, and copy the rest of the line over */ strcpy(buffer, line.data() + strlen(section) + 2); /* Copy the remaining lines of the section to buffer */ for (;;) { char *end_i_cator; size_t next_length, buffer_length; /* Did the section end somewhere in the most recently read line? */ end_i_cator = strchr(buffer, '<'); if (end_i_cator) { *end_i_cator = 0; break; } bool eofReached = false; bool maxLenReached = false; line = file->read_line(MAX_LINE_LENGTH, maxLenReached, eofReached); /* End of file? - done! */ if (maxLenReached || eofReached) break; /* Otherwise, handle the line. It MAY be the start of the next section, */ /* but that will be handled at the start of next trip through the loop */ buffer_length = strlen(buffer); pj_chomp(&line[0]); /* Remove '#' style comments */ next_length = strlen(line.data()) + buffer_length + 2; if (next_length > current_buffer_size) { char *b = static_cast<char *>(malloc(2 * current_buffer_size)); if (nullptr == b) { free(buffer); buffer = nullptr; break; } strcpy(b, buffer); current_buffer_size *= 2; free(buffer); buffer = b; } buffer[buffer_length] = ' '; strcpy(buffer + buffer_length + 1, line.data()); } free(fname); if (nullptr == buffer) return nullptr; pj_shrink(buffer); pj_log(ctx, PJ_LOG_TRACE, "key=%s, value: [%s]", key, buffer); return buffer; } /************************************************************************/ static paralist *get_init(PJ_CONTEXT *ctx, const char *key, int allow_init_epsg) { /************************************************************************* Expand key from buffer or (if not in buffer) from init file *************************************************************************/ const char *xkey; char *definition = nullptr; paralist *init_items = nullptr; if (!ctx) { ctx = pj_get_default_ctx(); } /* support "init=file:section", "+init=file:section", and "file:section" * format */ xkey = strstr(key, "init="); if (nullptr == xkey) xkey = key; else xkey += 5; pj_log(ctx, PJ_LOG_TRACE, "get_init: searching cache for key: [%s]", xkey); /* Is file/key pair already in cache? */ init_items = pj_search_initcache(xkey); if (init_items) return init_items; if ((strncmp(xkey, "epsg:", 5) == 0 || strncmp(xkey, "IGNF:", 5) == 0)) { char unused[256]; char initname[5]; int exists; strncpy(initname, xkey, 4); initname[4] = 0; if (strncmp(xkey, "epsg:", 5) == 0) { exists = ctx->epsg_file_exists; if (exists < 0) { exists = pj_find_file(ctx, initname, unused, sizeof(unused)); ctx->epsg_file_exists = exists; } } else { exists = pj_find_file(ctx, initname, unused, sizeof(unused)); } if (!exists) { char szInitStr[7 + 64]; PJ *src; const char *proj_string; proj_context_errno_set(ctx, 0); if (!allow_init_epsg) { pj_log(ctx, PJ_LOG_TRACE, "%s expansion disallowed", xkey); return nullptr; } if (strlen(xkey) > 64) { return nullptr; } strcpy(szInitStr, "+init="); strcat(szInitStr, xkey); auto old_proj4_init_rules = ctx->use_proj4_init_rules; ctx->use_proj4_init_rules = true; src = proj_create(ctx, szInitStr); ctx->use_proj4_init_rules = old_proj4_init_rules; if (!src) { return nullptr; } proj_string = proj_as_proj_string(ctx, src, PJ_PROJ_4, nullptr); if (!proj_string) { proj_destroy(src); return nullptr; } definition = (char *)calloc(1, strlen(proj_string) + 1); if (definition) { strcpy(definition, proj_string); } proj_destroy(src); } } if (!definition) { /* If not, we must read it from file */ pj_log(ctx, PJ_LOG_TRACE, "get_init: searching on in init files for [%s]", xkey); definition = get_init_string(ctx, xkey); } if (nullptr == definition) return nullptr; init_items = string_to_paralist(ctx, definition); if (init_items) pj_log(ctx, PJ_LOG_TRACE, "get_init: got [%s], paralist[0,1]: [%s,%s]", definition, init_items->param, init_items->next ? init_items->next->param : "(empty)"); free(definition); if (nullptr == init_items) return nullptr; /* We found it in file - now insert into the cache, before returning */ pj_insert_initcache(xkey, init_items); return init_items; } static void append_default_ellipsoid_to_paralist(paralist *start) { if (nullptr == start) return; /* Set defaults, unless inhibited (either explicitly through a "no_defs" * token */ /* or implicitly, because we are initializing a pipeline) */ if (pj_param_exists(start, "no_defs")) return; auto proj = pj_param_exists(start, "proj"); if (nullptr == proj) return; if (strlen(proj->param) < 6) return; if (0 == strcmp("pipeline", proj->param + 5)) return; /* Don't default ellipse if datum, ellps or any ellipsoid information is set */ if (pj_param_exists(start, "datum")) return; if (pj_param_exists(start, "ellps")) return; if (pj_param_exists(start, "a")) return; if (pj_param_exists(start, "b")) return; if (pj_param_exists(start, "rf")) return; if (pj_param_exists(start, "f")) return; if (pj_param_exists(start, "e")) return; if (pj_param_exists(start, "es")) return; /* Locate end of start-list */ paralist *last = nullptr; for (last = start; last->next; last = last->next) ; /* If we're here, it's OK to append the current default item */ last->next = pj_mkparam("ellps=GRS80"); } /*****************************************************************************/ static paralist *pj_expand_init_internal(PJ_CONTEXT *ctx, paralist *init, int allow_init_epsg) { /****************************************************************************** Append expansion of <key> to the paralist <init>. The expansion is appended, rather than inserted at <init>'s place, since <init> may contain overrides to the expansion. These must take precedence, and hence come first in the expanded list. Consider e.g. the key 'foo:bar' which (hypothetically) expands to 'proj=utm zone=32 ellps=GRS80', i.e. a UTM projection on the GRS80 ellipsoid. The expression 'init=foo:bar ellps=intl' will then expand to: 'init=foo:bar ellps=intl proj=utm zone=32 ellps=GRS80', where 'ellps=intl' precedes 'ellps=GRS80', and hence takes precedence, turning the expansion into an UTM projection on the Hayford ellipsoid. Note that 'init=foo:bar' stays in the list. It is ignored after expansion. ******************************************************************************/ paralist *last; paralist *expn; /* Nowhere to start? */ if (nullptr == init) return nullptr; expn = get_init(ctx, init->param, allow_init_epsg); /* Nothing in expansion? */ if (nullptr == expn) return nullptr; /* Locate the end of the list */ for (last = init; last && last->next; last = last->next) ; /* Then append and return */ last->next = expn; return init; } paralist *pj_expand_init(PJ_CONTEXT *ctx, paralist *init) { return pj_expand_init_internal(ctx, init, TRUE); } /************************************************************************/ /* pj_init() */ /* */ /* Main entry point for initialing a PJ projections */ /* definition. Note that the projection specific function is */ /* called to do the initial allocation so it can be created */ /* large enough to hold projection specific parameters. */ /************************************************************************/ static PJ_CONSTRUCTOR locate_constructor(const char *name) { int i; const char *s; const PJ_OPERATIONS *operations; operations = proj_list_operations(); for (i = 0; (s = operations[i].id) && strcmp(name, s); ++i) ; if (nullptr == s) return nullptr; return (PJ_CONSTRUCTOR)operations[i].proj; } PJ *pj_init_ctx_with_allow_init_epsg(PJ_CONTEXT *ctx, int argc, char **argv, int allow_init_epsg) { const char *s; char *name; PJ_CONSTRUCTOR proj; paralist *curr, *init, *start; int i; int err; PJ *PIN = nullptr; int n_pipelines = 0; int n_inits = 0; const PJ_UNITS *units; const PJ_PRIME_MERIDIANS *prime_meridians; if (nullptr == ctx) ctx = pj_get_default_ctx(); ctx->last_errno = 0; if (argc <= 0) { pj_log(ctx, PJ_LOG_ERROR, _("No arguments")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_MISSING_ARG); return nullptr; } /* count occurrences of pipelines and inits */ for (i = 0; i < argc; ++i) { if (!strcmp(argv[i], "+proj=pipeline") || !strcmp(argv[i], "proj=pipeline")) n_pipelines++; if (!strncmp(argv[i], "+init=", 6) || !strncmp(argv[i], "init=", 5)) n_inits++; } /* can't have nested pipelines directly */ if (n_pipelines > 1) { pj_log(ctx, PJ_LOG_ERROR, _("Nested pipelines are not supported")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); return nullptr; } /* don't allow more than one +init in non-pipeline operations */ if (n_pipelines == 0 && n_inits > 1) { pj_log(ctx, PJ_LOG_ERROR, _("Too many inits")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); return nullptr; } /* put arguments into internal linked list */ start = curr = pj_mkparam(argv[0]); if (!curr) { free_params(ctx, start, PROJ_ERR_OTHER /*ENOMEM*/); return nullptr; } for (i = 1; i < argc; ++i) { curr->next = pj_mkparam(argv[i]); if (!curr->next) { free_params(ctx, start, PROJ_ERR_OTHER /*ENOMEM*/); return nullptr; } curr = curr->next; } /* Only expand '+init's in non-pipeline operations. '+init's in pipelines * are */ /* expanded in the individual pipeline steps during pipeline initialization. */ /* Potentially this leads to many nested pipelines, which shouldn't be a */ /* problem when '+init's are expanded as late as possible. */ init = pj_param_exists(start, "init"); if (init && n_pipelines == 0) { init = pj_expand_init_internal(ctx, init, allow_init_epsg); if (!init) { free_params(ctx, start, PROJ_ERR_INVALID_OP_WRONG_SYNTAX); return nullptr; } } if (ctx->last_errno) { free_params(ctx, start, ctx->last_errno); return nullptr; } /* Find projection selection */ curr = pj_param_exists(start, "proj"); if (nullptr == curr) { pj_log(ctx, PJ_LOG_ERROR, _("Missing proj")); free_params(ctx, start, PROJ_ERR_INVALID_OP_MISSING_ARG); return nullptr; } name = curr->param; if (strlen(name) < 6) { pj_log(ctx, PJ_LOG_ERROR, _("Invalid value for proj")); free_params(ctx, start, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return nullptr; } name += 5; proj = locate_constructor(name); if (nullptr == proj) { pj_log(ctx, PJ_LOG_ERROR, _("Unknown projection")); free_params(ctx, start, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return nullptr; } append_default_ellipsoid_to_paralist(start); /* Allocate projection structure */ PIN = proj(nullptr); if (nullptr == PIN) { free_params(ctx, start, PROJ_ERR_OTHER /*ENOMEM*/); return nullptr; } PIN->ctx = ctx; PIN->params = start; PIN->is_latlong = 0; PIN->is_geocent = 0; PIN->is_long_wrap_set = 0; PIN->long_wrap_center = 0.0; strcpy(PIN->axis, "enu"); /* Set datum parameters. Similarly to +init parameters we want to expand */ /* +datum parameters as late as possible when dealing with pipelines. */ /* otherwise only the first occurrence of +datum will be expanded and that */ if (n_pipelines == 0) { if (pj_datum_set(ctx, start, PIN)) return pj_default_destructor(PIN, proj_errno(PIN)); } err = pj_ellipsoid(PIN); if (err) { /* Didn't get an ellps, but doesn't need one: Get a free WGS84 */ if (PIN->need_ellps) { pj_log(ctx, PJ_LOG_ERROR, _("pj_init_ctx: Must specify ellipsoid or sphere")); return pj_default_destructor(PIN, proj_errno(PIN)); } else { if (PIN->a == 0) proj_errno_reset(PIN); PIN->f = 1.0 / 298.257223563; PIN->a = 6378137.0; PIN->es = PIN->f * (2 - PIN->f); } } PIN->a_orig = PIN->a; PIN->es_orig = PIN->es; if (pj_calc_ellipsoid_params(PIN, PIN->a, PIN->es)) return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); /* Now that we have ellipse information check for WGS84 datum */ if (PIN->datum_type == PJD_3PARAM && PIN->datum_params[0] == 0.0 && PIN->datum_params[1] == 0.0 && PIN->datum_params[2] == 0.0 && PIN->a == 6378137.0 && ABS(PIN->es - 0.006694379990) < 0.000000000050) /*WGS84/GRS80*/ { PIN->datum_type = PJD_WGS84; } /* Set PIN->geoc coordinate system */ PIN->geoc = (PIN->es != 0.0 && pj_param(ctx, start, "bgeoc").i); /* Over-ranging flag */ PIN->over = pj_param(ctx, start, "bover").i; if (ctx->forceOver) { PIN->over = ctx->forceOver; } /* Vertical datum geoid grids */ PIN->has_geoid_vgrids = pj_param(ctx, start, "tgeoidgrids").i; if (PIN->has_geoid_vgrids) /* we need to mark it as used. */ pj_param(ctx, start, "sgeoidgrids"); /* Longitude center for wrapping */ PIN->is_long_wrap_set = pj_param(ctx, start, "tlon_wrap").i; if (PIN->is_long_wrap_set) { PIN->long_wrap_center = pj_param(ctx, start, "rlon_wrap").f; /* Don't accept excessive values otherwise we might perform badly */ /* when correcting longitudes around it */ /* The test is written this way to error on long_wrap_center "=" NaN */ if (!(fabs(PIN->long_wrap_center) < 10 * M_TWOPI)) { proj_log_error(PIN, _("Invalid value for lon_wrap")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } /* Axis orientation */ if ((pj_param(ctx, start, "saxis").s) != nullptr) { const char *axis_legal = "ewnsud"; const char *axis_arg = pj_param(ctx, start, "saxis").s; if (strlen(axis_arg) != 3) { proj_log_error(PIN, _("Invalid value for axis")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (strchr(axis_legal, axis_arg[0]) == nullptr || strchr(axis_legal, axis_arg[1]) == nullptr || strchr(axis_legal, axis_arg[2]) == nullptr) { proj_log_error(PIN, _("Invalid value for axis")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* TODO: it would be nice to validate we don't have on axis repeated */ strcpy(PIN->axis, axis_arg); } /* Central meridian */ PIN->lam0 = pj_param(ctx, start, "rlon_0").f; /* Central latitude */ PIN->phi0 = pj_param(ctx, start, "rlat_0").f; if (fabs(PIN->phi0) > M_HALFPI) { proj_log_error(PIN, _("Invalid value for lat_0: |lat_0| should be <= 90°")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* False easting and northing */ PIN->x0 = pj_param(ctx, start, "dx_0").f; PIN->y0 = pj_param(ctx, start, "dy_0").f; PIN->z0 = pj_param(ctx, start, "dz_0").f; PIN->t0 = pj_param(ctx, start, "dt_0").f; /* General scaling factor */ if (pj_param(ctx, start, "tk_0").i) PIN->k0 = pj_param(ctx, start, "dk_0").f; else if (pj_param(ctx, start, "tk").i) PIN->k0 = pj_param(ctx, start, "dk").f; else PIN->k0 = 1.; if (PIN->k0 <= 0.) { proj_log_error(PIN, _("Invalid value for k/k_0: it should be > 0")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* Set units */ units = pj_list_linear_units(); s = nullptr; if ((name = pj_param(ctx, start, "sunits").s) != nullptr) { for (i = 0; (s = units[i].id) && strcmp(name, s); ++i) ; if (!s) { proj_log_error(PIN, _("Invalid value for units")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } s = units[i].to_meter; } if (s || (s = pj_param(ctx, start, "sto_meter").s)) { char *end_ptr = const_cast<char *>(s); PIN->to_meter = pj_strtod(s, &end_ptr); s = end_ptr; if (*s == '/') { /* ratio number */ ++s; double denom = pj_strtod(s, nullptr); if (denom == 0.0) { proj_log_error(PIN, _("Invalid value for to_meter donominator")); return pj_default_destructor( PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } PIN->to_meter /= denom; } if (PIN->to_meter <= 0.0) { proj_log_error(PIN, _("Invalid value for to_meter")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } PIN->fr_meter = 1 / PIN->to_meter; } else PIN->to_meter = PIN->fr_meter = 1.; /* Set vertical units */ s = nullptr; if ((name = pj_param(ctx, start, "svunits").s) != nullptr) { for (i = 0; (s = units[i].id) && strcmp(name, s); ++i) ; if (!s) { proj_log_error(PIN, _("Invalid value for vunits")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } s = units[i].to_meter; } if (s || (s = pj_param(ctx, start, "svto_meter").s)) { char *end_ptr = const_cast<char *>(s); PIN->vto_meter = pj_strtod(s, &end_ptr); s = end_ptr; if (*s == '/') { /* ratio number */ ++s; double denom = pj_strtod(s, nullptr); if (denom == 0.0) { proj_log_error(PIN, _("Invalid value for vto_meter donominator")); return pj_default_destructor( PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } PIN->vto_meter /= denom; } if (PIN->vto_meter <= 0.0) { proj_log_error(PIN, _("Invalid value for vto_meter")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } PIN->vfr_meter = 1. / PIN->vto_meter; } else { PIN->vto_meter = PIN->to_meter; PIN->vfr_meter = PIN->fr_meter; } /* Prime meridian */ prime_meridians = proj_list_prime_meridians(); s = nullptr; if ((name = pj_param(ctx, start, "spm").s) != nullptr) { const char *value = nullptr; char *next_str = nullptr; for (i = 0; prime_meridians[i].id != nullptr; ++i) { if (strcmp(name, prime_meridians[i].id) == 0) { value = prime_meridians[i].defn; break; } } if (value == nullptr && (dmstor_ctx(ctx, name, &next_str) != 0.0 || *name == '0') && *next_str == '\0') value = name; if (!value) { proj_log_error(PIN, _("Invalid value for pm")); return pj_default_destructor(PIN, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } PIN->from_greenwich = dmstor_ctx(ctx, value, nullptr); } else PIN->from_greenwich = 0.0; /* Private object for the geodesic functions */ PIN->geod = static_cast<struct geod_geodesic *>( calloc(1, sizeof(struct geod_geodesic))); if (nullptr == PIN->geod) return pj_default_destructor(PIN, PROJ_ERR_OTHER /*ENOMEM*/); geod_init(PIN->geod, PIN->a, PIN->f); /* Projection specific initialization */ err = proj_errno_reset(PIN); PIN = proj(PIN); if (proj_errno(PIN)) { proj_destroy(PIN); return nullptr; } proj_errno_restore(PIN, err); return PIN; }
cpp
PROJ
data/projects/PROJ/src/wkt1_generated_parser.c
/* A Bison parser, made by GNU Bison 3.5.1. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.5.1" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Substitute the variable and function names. */ #define yyparse pj_wkt1_parse #define yylex pj_wkt1_lex #define yyerror pj_wkt1_error #define yydebug pj_wkt1_debug /* #define yynerrs pj_wkt1_nerrs */ /* First part of user prologue. */ /****************************************************************************** * Project: PROJ * Purpose: WKT1 parser grammar * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2013-2018 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. ****************************************************************************/ #include "wkt1_parser.h" # ifndef YY_CAST # ifdef __cplusplus # define YY_CAST(Type, Val) static_cast<Type> (Val) # define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val) # else # define YY_CAST(Type, Val) ((Type) (Val)) # define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) # endif # endif # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* Use api.header.include to #include this header instead of duplicating it here. */ #ifndef YY_PJ_WKT1_WKT1_GENERATED_PARSER_H_INCLUDED # define YY_PJ_WKT1_WKT1_GENERATED_PARSER_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int pj_wkt1_debug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { END = 0, T_PARAM_MT = 258, T_CONCAT_MT = 259, T_INVERSE_MT = 260, T_PASSTHROUGH_MT = 261, T_PROJCS = 262, T_PROJECTION = 263, T_GEOGCS = 264, T_DATUM = 265, T_SPHEROID = 266, T_PRIMEM = 267, T_UNIT = 268, T_LINUNIT = 269, T_GEOCCS = 270, T_AUTHORITY = 271, T_VERT_CS = 272, T_VERTCS = 273, T_VERT_DATUM = 274, T_VDATUM = 275, T_COMPD_CS = 276, T_AXIS = 277, T_TOWGS84 = 278, T_FITTED_CS = 279, T_LOCAL_CS = 280, T_LOCAL_DATUM = 281, T_PARAMETER = 282, T_EXTENSION = 283, T_STRING = 284, T_NUMBER = 285, T_IDENTIFIER = 286 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif int pj_wkt1_parse (pj_wkt1_parse_context *context); #endif /* !YY_PJ_WKT1_WKT1_GENERATED_PARSER_H_INCLUDED */ #ifdef short # undef short #endif /* On compilers that do not define __PTRDIFF_MAX__ etc., make sure <limits.h> and (if available) <stdint.h> are included so that the code can choose integer types of a good width. */ #ifndef __PTRDIFF_MAX__ # include <limits.h> /* INFRINGES ON USER NAME SPACE */ # if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stdint.h> /* INFRINGES ON USER NAME SPACE */ # define YY_STDINT_H # endif #endif /* Narrow types that promote to a signed type and that can represent a signed or unsigned integer of at least N bits. In tables they can save space and decrease cache pressure. Promoting to a signed type helps avoid bugs in integer arithmetic. */ #ifdef __INT_LEAST8_MAX__ typedef __INT_LEAST8_TYPE__ yytype_int8; #elif defined YY_STDINT_H typedef int_least8_t yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef __INT_LEAST16_MAX__ typedef __INT_LEAST16_TYPE__ yytype_int16; #elif defined YY_STDINT_H typedef int_least16_t yytype_int16; #else typedef short yytype_int16; #endif #if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ typedef __UINT_LEAST8_TYPE__ yytype_uint8; #elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \ && UINT_LEAST8_MAX <= INT_MAX) typedef uint_least8_t yytype_uint8; #elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX typedef unsigned char yytype_uint8; #else typedef short yytype_uint8; #endif #if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ typedef __UINT_LEAST16_TYPE__ yytype_uint16; #elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \ && UINT_LEAST16_MAX <= INT_MAX) typedef uint_least16_t yytype_uint16; #elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX typedef unsigned short yytype_uint16; #else typedef int yytype_uint16; #endif #ifndef YYPTRDIFF_T # if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__ # define YYPTRDIFF_T __PTRDIFF_TYPE__ # define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__ # elif defined PTRDIFF_MAX # ifndef ptrdiff_t # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # endif # define YYPTRDIFF_T ptrdiff_t # define YYPTRDIFF_MAXIMUM PTRDIFF_MAX # else # define YYPTRDIFF_T long # define YYPTRDIFF_MAXIMUM LONG_MAX # endif #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM \ YY_CAST (YYPTRDIFF_T, \ (YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \ ? YYPTRDIFF_MAXIMUM \ : YY_CAST (YYSIZE_T, -1))) #define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X)) /* Stored state numbers (used for stacks). */ typedef yytype_int16 yy_state_t; /* State numbers in computations. */ typedef int yy_state_fast_t; #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE_PURE # if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) # else # define YY_ATTRIBUTE_PURE # endif #endif #ifndef YY_ATTRIBUTE_UNUSED # if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) # else # define YY_ATTRIBUTE_UNUSED # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ # define YY_IGNORE_USELESS_CAST_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") # define YY_IGNORE_USELESS_CAST_END \ _Pragma ("GCC diagnostic pop") #endif #ifndef YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_END #endif #define YY_ASSERT(E) ((void) (0 && (E))) #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yy_state_t yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYPTRDIFF_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / YYSIZEOF (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYPTRDIFF_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 32 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 255 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 37 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 72 /* YYNRULES -- Number of rules. */ #define YYNRULES 114 /* YYNSTATES -- Number of states. */ #define YYNSTATES 289 #define YYUNDEFTOK 2 #define YYMAXUTOK 286 /* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM as returned by yylex, with out-of-bounds checking. */ #define YYTRANSLATE(YYX) \ (0 <= (YYX) && (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex. */ static const yytype_int8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 33, 35, 2, 2, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 32, 2, 34, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_int16 yyrline[] = { 0, 81, 81, 93, 93, 96, 99, 99, 102, 102, 102, 102, 105, 108, 110, 111, 114, 116, 117, 120, 123, 127, 132, 132, 132, 132, 132, 132, 135, 136, 139, 139, 143, 147, 148, 151, 152, 154, 155, 156, 157, 159, 160, 163, 166, 169, 174, 176, 177, 178, 179, 180, 183, 185, 186, 187, 188, 191, 195, 202, 202, 205, 208, 211, 214, 217, 220, 223, 226, 227, 228, 229, 232, 235, 238, 239, 242, 244, 245, 246, 249, 251, 251, 254, 256, 257, 258, 261, 264, 267, 272, 272, 274, 277, 282, 285, 287, 290, 293, 296, 299, 302, 305, 308, 311, 314, 317, 320, 323, 326, 328, 330, 331, 332, 335 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 1 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "\"end of string\"", "error", "$undefined", "\"PARAM_MT\"", "\"CONCAT_MT\"", "\"INVERSE_MT\"", "\"PASSTHROUGH_MT\"", "\"PROJCS\"", "\"PROJECTION\"", "\"GEOGCS\"", "\"DATUM\"", "\"SPHEROID\"", "\"PRIMEM\"", "\"UNIT\"", "\"LINUNIT\"", "\"GEOCCS\"", "\"AUTHORITY\"", "\"VERT_CS\"", "\"VERTCS\"", "\"VERT_DATUM\"", "\"VDATUM\"", "\"COMPD_CS\"", "\"AXIS\"", "\"TOWGS84\"", "\"FITTED_CS\"", "\"LOCAL_CS\"", "\"LOCAL_DATUM\"", "\"PARAMETER\"", "\"EXTENSION\"", "\"string\"", "\"number\"", "\"identifier\"", "'['", "'('", "']'", "')'", "','", "$accept", "input", "begin_node", "begin_node_name", "end_node", "math_transform", "param_mt", "parameter", "opt_parameter_list", "concat_mt", "opt_math_transform_list", "inv_mt", "passthrough_mt", "integer", "coordinate_system", "horz_cs_with_opt_esri_vertcs", "horz_cs", "projected_cs", "opt_parameter_list_linear_unit", "parameter_list_linear_unit", "opt_twin_axis_extension_authority", "opt_authority", "extension", "projection", "geographic_cs", "linunit", "opt_linunit_or_twin_axis_extension_authority", "datum", "opt_towgs84_authority_extension", "spheroid", "semi_major_axis", "inverse_flattening", "prime_meridian", "longitude", "angular_unit", "linear_unit", "unit", "conversion_factor", "geocentric_cs", "opt_three_axis_extension_authority", "three_axis", "authority", "vert_cs", "esri_vert_cs", "opt_axis_authority", "vert_datum", "vdatum_or_datum", "vdatum", "opt_extension_authority", "datum_type", "compd_cs", "head_cs", "tail_cs", "twin_axis", "axis", "towgs84", "towgs84_parameters", "three_parameters", "seven_parameters", "dx", "dy", "dz", "ex", "ey", "ez", "ppm", "fitted_cs", "to_base", "base_cs", "local_cs", "opt_axis_list_authority", "local_datum", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_int16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 91, 40, 93, 41, 44 }; # endif #define YYPACT_NINF (-131) #define yypact_value_is_default(Yyn) \ ((Yyn) == YYPACT_NINF) #define YYTABLE_NINF (-1) #define yytable_value_is_error(Yyn) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 97, 33, 33, 33, 33, 33, 33, 33, 33, 10, -131, -131, 2, -131, -131, -131, -131, -131, -131, -131, -131, -131, -131, 40, 12, 38, 47, 69, 93, 95, 96, 89, -131, 117, -131, 102, 126, 126, 123, 1, 22, 135, -131, -131, 119, -131, -131, 107, 33, 110, 111, 33, 113, 33, -131, 114, -131, -131, 115, 33, 33, 33, 33, -131, -131, -131, -131, -131, 118, 33, 121, 150, 125, 147, 147, 127, 149, 55, 6, 91, 128, 135, 135, 136, 97, 129, 149, 33, 131, 157, 33, 134, 137, 141, 33, 138, -131, -131, 33, 139, 55, -131, -131, -131, -131, 140, 145, 55, 142, 55, -131, 143, -131, 55, 141, 144, 151, 6, 33, 152, 153, 149, 149, -131, 140, 154, 18, 55, 155, 6, -131, 19, 55, 128, -131, 135, 55, -131, 135, -131, 151, 159, 161, 55, 156, 158, 75, 55, 163, 160, -131, 162, 55, 165, 33, 33, -131, 151, -131, 169, -131, -131, 33, 151, -131, -131, -131, 142, -131, 55, 55, 164, -131, -131, 65, 55, 171, 33, 151, -131, 140, -131, -131, 151, 14, 55, 65, 55, -131, -131, 151, 166, 167, -131, 55, 170, -131, -131, -131, -131, 18, 55, 151, -131, 140, 172, -131, -131, 173, 175, -131, -131, 55, 33, 151, 151, -131, 140, -131, 151, 140, -131, 174, -131, 55, 178, 181, -131, 184, -131, 164, -131, -131, -131, 159, 98, -131, 55, -131, -131, 179, -131, 180, -131, -131, -131, -131, -131, 159, -131, 55, 55, 55, -131, -131, -131, -131, 151, -131, 187, 165, 182, -131, -131, -131, 55, -131, 183, 151, 159, -131, 190, 55, -131, -131, 185, -131, 192, -131, 188, 193, -131, 189, 196, -131, 191, 198, -131, -131 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_int8 yydefact[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 22, 28, 31, 30, 23, 24, 75, 25, 26, 27, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 110, 29, 0, 0, 0, 0, 0, 0, 0, 82, 0, 81, 89, 0, 0, 0, 0, 0, 107, 8, 9, 10, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 64, 83, 0, 0, 0, 34, 33, 90, 91, 84, 0, 0, 17, 0, 21, 0, 108, 0, 0, 0, 41, 0, 0, 53, 0, 0, 0, 87, 84, 0, 0, 0, 0, 0, 76, 0, 0, 14, 12, 0, 0, 19, 0, 106, 41, 0, 0, 0, 37, 0, 0, 0, 0, 47, 63, 68, 0, 0, 0, 0, 79, 41, 74, 0, 35, 36, 0, 41, 86, 88, 15, 17, 16, 0, 0, 111, 42, 44, 0, 0, 0, 0, 41, 56, 84, 52, 62, 41, 0, 0, 0, 0, 80, 66, 41, 0, 0, 78, 0, 0, 85, 18, 20, 114, 0, 0, 41, 40, 84, 0, 32, 58, 0, 0, 55, 54, 0, 0, 41, 41, 51, 84, 45, 41, 84, 71, 0, 67, 0, 0, 0, 13, 0, 112, 111, 109, 39, 38, 0, 0, 99, 0, 96, 95, 0, 61, 0, 50, 48, 49, 70, 69, 0, 65, 0, 0, 0, 113, 92, 60, 59, 41, 94, 0, 0, 0, 73, 93, 43, 0, 100, 0, 41, 0, 57, 0, 0, 72, 101, 97, 46, 0, 102, 0, 0, 103, 0, 0, 104, 0, 0, 105, 98 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -131, -131, -47, -2, -68, -58, -131, 79, 53, -131, 62, -131, -131, -131, 130, -131, 194, -131, 116, 101, -131, -120, -130, -131, -27, -131, -131, 16, -131, -131, -131, -131, 168, -131, -131, -51, -60, -29, -131, -131, -131, -124, 176, 199, -131, -131, -131, -131, -107, 122, -131, -131, -131, 51, -114, -131, -131, -131, -131, -131, -131, -131, -131, -131, -131, -131, -131, -131, -131, -131, 7, -131 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 9, 23, 24, 45, 63, 64, 99, 107, 65, 136, 66, 67, 111, 10, 11, 12, 13, 100, 101, 175, 143, 163, 88, 14, 215, 185, 49, 147, 119, 208, 257, 91, 183, 149, 102, 96, 190, 15, 187, 220, 156, 16, 17, 127, 52, 55, 56, 132, 124, 18, 58, 105, 204, 205, 180, 237, 238, 239, 240, 267, 275, 279, 282, 285, 288, 19, 68, 113, 20, 201, 70 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 25, 26, 27, 28, 29, 30, 31, 164, 47, 97, 32, 48, 157, 81, 82, 83, 178, 152, 172, 94, 170, 53, 179, 108, 109, 95, 115, 171, 213, 1, 154, 2, 130, 98, 154, 154, 155, 193, 33, 134, 155, 137, 162, 196, 202, 139, 72, 162, 35, 75, 203, 77, 103, 50, 214, 54, 219, 80, 210, 158, 216, 150, 221, 212, 165, 21, 22, 85, 168, 34, 224, 151, 222, 211, 36, 173, 229, 167, 161, 181, 169, 154, 232, 37, 188, 116, 230, 155, 120, 42, 43, 154, 125, 162, 243, 244, 128, 233, 177, 246, 2, 198, 199, 162, 1, 38, 2, 206, 4, 5, 245, 2, 3, 247, 4, 5, 145, 218, 6, 223, 254, 7, 8, 42, 43, 44, 227, 255, 256, 39, 209, 40, 41, 231, 261, 5, 48, 265, 59, 60, 61, 62, 51, 71, 241, 69, 73, 74, 272, 76, 78, 79, 191, 192, 84, 273, 249, 86, 87, 90, 195, 89, 94, 93, 106, 114, 110, 117, 118, 258, 121, 123, 98, 122, 126, 129, 131, 154, 135, 138, 141, 155, 262, 263, 264, 133, 166, 142, 146, 148, 153, 159, 174, 182, 176, 189, 184, 270, 186, 194, 200, 207, 225, 226, 276, 236, 228, 250, 234, 235, 248, 242, 251, 252, 112, 259, 260, 266, 269, 271, 274, 277, 278, 281, 280, 283, 284, 286, 287, 197, 160, 268, 46, 144, 57, 217, 140, 253, 0, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 104 }; static const yytype_int16 yycheck[] = { 2, 3, 4, 5, 6, 7, 8, 131, 35, 77, 0, 10, 126, 60, 61, 62, 146, 124, 142, 13, 140, 20, 146, 81, 82, 76, 86, 141, 14, 7, 16, 9, 100, 27, 16, 16, 22, 157, 36, 107, 22, 109, 28, 163, 174, 113, 48, 28, 36, 51, 174, 53, 79, 37, 184, 39, 186, 59, 178, 127, 184, 121, 186, 183, 132, 32, 33, 69, 136, 29, 190, 122, 186, 180, 36, 143, 200, 135, 129, 147, 138, 16, 202, 36, 152, 87, 200, 22, 90, 34, 35, 16, 94, 28, 214, 215, 98, 204, 23, 219, 9, 169, 170, 28, 7, 36, 9, 175, 17, 18, 217, 9, 15, 220, 17, 18, 118, 185, 21, 187, 234, 24, 25, 34, 35, 36, 194, 29, 30, 36, 177, 36, 36, 201, 248, 18, 10, 257, 3, 4, 5, 6, 19, 36, 212, 26, 36, 36, 268, 36, 36, 36, 154, 155, 36, 269, 224, 36, 8, 12, 162, 36, 13, 36, 36, 36, 30, 36, 11, 237, 36, 30, 27, 36, 36, 36, 36, 16, 36, 36, 36, 22, 250, 251, 252, 106, 133, 36, 36, 36, 36, 36, 36, 30, 36, 30, 36, 265, 36, 30, 36, 30, 36, 36, 272, 30, 36, 29, 36, 36, 36, 213, 31, 29, 84, 36, 36, 30, 36, 36, 30, 36, 30, 30, 36, 36, 30, 36, 30, 167, 129, 260, 33, 117, 40, 184, 114, 230, -1, -1, -1, -1, 74, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 79 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_int8 yystos[] = { 0, 7, 9, 15, 17, 18, 21, 24, 25, 38, 51, 52, 53, 54, 61, 75, 79, 80, 87, 103, 106, 32, 33, 39, 40, 40, 40, 40, 40, 40, 40, 40, 0, 36, 29, 36, 36, 36, 36, 36, 36, 36, 34, 35, 36, 41, 80, 61, 10, 64, 64, 19, 82, 20, 64, 83, 84, 53, 88, 3, 4, 5, 6, 42, 43, 46, 48, 49, 104, 26, 108, 36, 40, 36, 36, 40, 36, 40, 36, 36, 40, 39, 39, 39, 36, 40, 36, 8, 60, 36, 12, 69, 69, 36, 13, 72, 73, 41, 27, 44, 55, 56, 72, 61, 79, 89, 36, 45, 42, 42, 30, 50, 51, 105, 36, 73, 40, 36, 11, 66, 40, 36, 36, 30, 86, 40, 36, 81, 40, 36, 41, 36, 85, 44, 41, 36, 47, 41, 36, 41, 86, 36, 36, 58, 55, 40, 36, 65, 36, 71, 73, 72, 85, 36, 16, 22, 78, 91, 41, 36, 56, 72, 28, 59, 78, 41, 45, 42, 41, 42, 58, 91, 78, 41, 36, 57, 36, 23, 59, 78, 92, 41, 30, 70, 36, 63, 36, 76, 41, 30, 74, 40, 40, 58, 30, 40, 58, 47, 41, 41, 36, 107, 59, 78, 90, 91, 41, 30, 67, 39, 58, 85, 58, 14, 59, 62, 78, 90, 41, 59, 77, 78, 91, 41, 58, 36, 36, 41, 36, 78, 91, 41, 58, 85, 36, 36, 30, 93, 94, 95, 96, 41, 40, 58, 58, 85, 58, 85, 36, 41, 29, 31, 29, 107, 91, 29, 30, 68, 41, 36, 36, 91, 41, 41, 41, 58, 30, 97, 74, 36, 41, 36, 58, 91, 30, 98, 41, 36, 30, 99, 36, 30, 100, 36, 30, 101, 36, 30, 102 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_int8 yyr1[] = { 0, 37, 38, 39, 39, 40, 41, 41, 42, 42, 42, 42, 43, 44, 45, 45, 46, 47, 47, 48, 49, 50, 51, 51, 51, 51, 51, 51, 52, 52, 53, 53, 54, 55, 55, 56, 56, 57, 57, 57, 57, 58, 58, 59, 60, 61, 62, 63, 63, 63, 63, 63, 64, 65, 65, 65, 65, 66, 67, 68, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 76, 76, 77, 78, 79, 79, 80, 81, 81, 81, 82, 83, 83, 84, 85, 85, 85, 86, 87, 88, 89, 89, 90, 91, 92, 93, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 106, 107, 107, 107, 108 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_int8 yyr2[] = { 0, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 5, 0, 3, 5, 0, 3, 4, 6, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 10, 1, 1, 3, 3, 0, 3, 3, 2, 0, 2, 5, 4, 10, 6, 0, 3, 3, 3, 2, 6, 0, 3, 3, 2, 8, 1, 1, 1, 6, 1, 1, 1, 6, 1, 10, 0, 3, 3, 2, 5, 5, 8, 1, 7, 0, 3, 2, 6, 1, 1, 3, 0, 3, 2, 1, 8, 1, 1, 1, 3, 5, 4, 1, 1, 5, 13, 1, 1, 1, 1, 1, 1, 1, 7, 1, 1, 10, 3, 0, 2, 3, 6 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, pj_wkt1_parse_context *context) { FILE *yyoutput = yyo; YYUSE (yyoutput); YYUSE (context); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyo, yytoknum[yytype], *yyvaluep); # endif YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, pj_wkt1_parse_context *context) { YYFPRINTF (yyo, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); yy_symbol_value_print (yyo, yytype, yyvaluep, context); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp, int yyrule, pj_wkt1_parse_context *context) { int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[+yyssp[yyi + 1 - yynrhs]], &yyvsp[(yyi + 1) - (yynrhs)] , context); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule, context); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen(S) (YY_CAST (YYPTRDIFF_T, strlen (S))) # else /* Return the length of YYSTR. */ static YYPTRDIFF_T yystrlen (const char *yystr) { YYPTRDIFF_T yylen; for (yylen = 0; yystr && yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYPTRDIFF_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYPTRDIFF_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; else goto append; append: default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (yyres) return (YYPTRDIFF_T)(yystpcpy (yyres, yystr) - yyres); else return yystrlen (yystr); } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYPTRDIFF_T *yymsg_alloc, char **yymsg, yy_state_t *yyssp, int yytoken) { enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat: reported tokens (one for the "unexpected", one per "expected"). */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Actual size of YYARG. */ int yycount = 0; /* Cumulated lengths of YYARG. */ YYPTRDIFF_T yysize = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[+*yyssp]; YYPTRDIFF_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); yysize = yysize0; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYPTRDIFF_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) yysize = yysize1; else return 2; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { /* Don't count the "%s"s in the final size, but reserve room for the terminator. */ YYPTRDIFF_T yysize1 = yysize + (yystrlen (yyformat) - 2 * yycount) + 1; if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) yysize = yysize1; else return 2; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { ++yyp; ++yyformat; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, pj_wkt1_parse_context *context) { YYUSE (yyvaluep); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (pj_wkt1_parse_context *context) { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ /* int yynerrs; */ yy_state_fast_t yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yy_state_t yyssa[YYINITDEPTH]; yy_state_t *yyss; yy_state_t *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYPTRDIFF_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYPTRDIFF_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; /* yynerrs = 0; */ yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; /*--------------------------------------------------------------------. | yysetstate -- set current state (the top of the stack) to yystate. | `--------------------------------------------------------------------*/ yysetstate: YYDPRINTF ((stderr, "Entering state %d\n", yystate)); YY_ASSERT (0 <= yystate && yystate < YYNSTATES); YY_IGNORE_USELESS_CAST_BEGIN *yyssp = YY_CAST (yy_state_t, yystate); YY_IGNORE_USELESS_CAST_END if (yyss + yystacksize - 1 <= yyssp) #if !defined yyoverflow && !defined YYSTACK_RELOCATE goto yyexhaustedlab; #else { /* Get the current used size of the three stacks, in elements. */ YYPTRDIFF_T yysize = (YYPTRDIFF_T)(yyssp - yyss + 1); # if defined yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ yy_state_t *yyss1 = yyss; YYSTYPE *yyvs1 = yyvs; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * YYSIZEOF (*yyssp), &yyvs1, yysize * YYSIZEOF (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } # else /* defined YYSTACK_RELOCATE */ /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yy_state_t *yyss1 = yyss; union yyalloc *yyptr = YY_CAST (union yyalloc *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize)))); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YY_IGNORE_USELESS_CAST_BEGIN YYDPRINTF ((stderr, "Stack size increased to %ld\n", YY_CAST (long, yystacksize))); YY_IGNORE_USELESS_CAST_END if (yyss + yystacksize - 1 <= yyssp) YYABORT; } #endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, context); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Discard the shifted token. */ yychar = YYEMPTY; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { /* ++yynerrs; */ #if ! YYERROR_VERBOSE yyerror (context, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = YY_CAST (char *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, yymsg_alloc))); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (context, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, context); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ #if 0 yyerrorlab: /* Pacify compilers when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (0) YYERROR; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ #endif yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif /*-----------------------------------------------------. | yyreturn -- parsing is finished, return the result. | `-----------------------------------------------------*/ yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, context); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[+*yyssp], yyvsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; }
c
PROJ
data/projects/PROJ/src/fwd.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Forward operation invocation * Author: Thomas Knudsen, [email protected], 2018-01-02 * Based on material from Gerald Evenden (original pj_fwd) * and Piyush Agram (original pj_fwd3d) * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * Copyright (c) 2018, 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. *****************************************************************************/ #include <errno.h> #include <math.h> #include "proj_internal.h" #include <math.h> #define INPUT_UNITS P->left #define OUTPUT_UNITS P->right static void fwd_prepare(PJ *P, PJ_COORD &coo) { if (HUGE_VAL == coo.v[0] || HUGE_VAL == coo.v[1] || HUGE_VAL == coo.v[2]) { coo = proj_coord_error(); return; } /* The helmert datum shift will choke unless it gets a sensible 4D * coordinate */ if (HUGE_VAL == coo.v[2] && P->helmert) coo.v[2] = 0.0; if (HUGE_VAL == coo.v[3] && P->helmert) coo.v[3] = 0.0; /* Check validity of angular input coordinates */ if (INPUT_UNITS == PJ_IO_UNITS_RADIANS) { double t; /* check for latitude or longitude over-range */ t = (coo.lp.phi < 0 ? -coo.lp.phi : coo.lp.phi) - M_HALFPI; if (t > PJ_EPS_LAT) { proj_log_error(P, _("Invalid latitude")); proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_INVALID_COORD); coo = proj_coord_error(); return; } if (coo.lp.lam > 10 || coo.lp.lam < -10) { proj_log_error(P, _("Invalid longitude")); proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_INVALID_COORD); coo = proj_coord_error(); return; } /* Clamp latitude to -90..90 degree range */ if (coo.lp.phi > M_HALFPI) coo.lp.phi = M_HALFPI; if (coo.lp.phi < -M_HALFPI) coo.lp.phi = -M_HALFPI; /* If input latitude is geocentrical, convert to geographical */ if (P->geoc) coo = pj_geocentric_latitude(P, PJ_INV, coo); /* Ensure longitude is in the -pi:pi range */ if (0 == P->over) coo.lp.lam = adjlon(coo.lp.lam); if (P->hgridshift) coo = proj_trans(P->hgridshift, PJ_INV, coo); else if (P->helmert || (P->cart_wgs84 != nullptr && P->cart != nullptr)) { coo = proj_trans(P->cart_wgs84, PJ_FWD, coo); /* Go cartesian in WGS84 frame */ if (P->helmert) coo = proj_trans(P->helmert, PJ_INV, coo); /* Step into local frame */ coo = proj_trans(P->cart, PJ_INV, coo); /* Go back to angular using local ellps */ } if (coo.lp.lam == HUGE_VAL) return; if (P->vgridshift) coo = proj_trans(P->vgridshift, PJ_FWD, coo); /* Go orthometric from geometric */ /* Distance from central meridian, taking system zero meridian into * account */ coo.lp.lam = (coo.lp.lam - P->from_greenwich) - P->lam0; /* Ensure longitude is in the -pi:pi range */ if (0 == P->over) coo.lp.lam = adjlon(coo.lp.lam); return; } /* We do not support gridshifts on cartesian input */ if (INPUT_UNITS == PJ_IO_UNITS_CARTESIAN && P->helmert) coo = proj_trans(P->helmert, PJ_INV, coo); return; } static void fwd_finalize(PJ *P, PJ_COORD &coo) { switch (OUTPUT_UNITS) { /* Handle false eastings/northings and non-metric linear units */ case PJ_IO_UNITS_CARTESIAN: if (P->is_geocent) { coo = proj_trans(P->cart, PJ_FWD, coo); } coo.xyz.x *= P->fr_meter; coo.xyz.y *= P->fr_meter; coo.xyz.z *= P->fr_meter; break; /* Classic proj.4 functions return plane coordinates in units of the * semimajor axis */ case PJ_IO_UNITS_CLASSIC: coo.xy.x *= P->a; coo.xy.y *= P->a; PROJ_FALLTHROUGH; /* to continue processing in common with PJ_IO_UNITS_PROJECTED */ case PJ_IO_UNITS_PROJECTED: coo.xyz.x = P->fr_meter * (coo.xyz.x + P->x0); coo.xyz.y = P->fr_meter * (coo.xyz.y + P->y0); coo.xyz.z = P->vfr_meter * (coo.xyz.z + P->z0); break; case PJ_IO_UNITS_WHATEVER: break; case PJ_IO_UNITS_DEGREES: break; case PJ_IO_UNITS_RADIANS: coo.lpz.z = P->vfr_meter * (coo.lpz.z + P->z0); if (P->is_long_wrap_set) { if (coo.lpz.lam != HUGE_VAL) { coo.lpz.lam = P->long_wrap_center + adjlon(coo.lpz.lam - P->long_wrap_center); } } break; } if (P->axisswap) coo = proj_trans(P->axisswap, PJ_FWD, coo); } static inline PJ_COORD error_or_coord(PJ *P, PJ_COORD coord, int last_errno) { if (P->ctx->last_errno) return proj_coord_error(); P->ctx->last_errno = last_errno; return coord; } PJ_XY pj_fwd(PJ_LP lp, PJ *P) { PJ_COORD coo = {{0, 0, 0, 0}}; coo.lp = lp; const int last_errno = P->ctx->last_errno; P->ctx->last_errno = 0; if (!P->skip_fwd_prepare) fwd_prepare(P, coo); if (HUGE_VAL == coo.v[0] || HUGE_VAL == coo.v[1]) return proj_coord_error().xy; /* Do the transformation, using the lowest dimensional transformer available */ if (P->fwd) { const auto xy = P->fwd(coo.lp, P); coo.xy = xy; } else if (P->fwd3d) { const auto xyz = P->fwd3d(coo.lpz, P); coo.xyz = xyz; } else if (P->fwd4d) P->fwd4d(coo, P); else { proj_errno_set(P, PROJ_ERR_OTHER_NO_INVERSE_OP); return proj_coord_error().xy; } if (HUGE_VAL == coo.v[0]) return proj_coord_error().xy; if (!P->skip_fwd_finalize) fwd_finalize(P, coo); return error_or_coord(P, coo, last_errno).xy; } PJ_XYZ pj_fwd3d(PJ_LPZ lpz, PJ *P) { PJ_COORD coo = {{0, 0, 0, 0}}; coo.lpz = lpz; const int last_errno = P->ctx->last_errno; P->ctx->last_errno = 0; if (!P->skip_fwd_prepare) fwd_prepare(P, coo); if (HUGE_VAL == coo.v[0]) return proj_coord_error().xyz; /* Do the transformation, using the lowest dimensional transformer feasible */ if (P->fwd3d) { const auto xyz = P->fwd3d(coo.lpz, P); coo.xyz = xyz; } else if (P->fwd4d) P->fwd4d(coo, P); else if (P->fwd) { const auto xy = P->fwd(coo.lp, P); coo.xy = xy; } else { proj_errno_set(P, PROJ_ERR_OTHER_NO_INVERSE_OP); return proj_coord_error().xyz; } if (HUGE_VAL == coo.v[0]) return proj_coord_error().xyz; if (!P->skip_fwd_finalize) fwd_finalize(P, coo); return error_or_coord(P, coo, last_errno).xyz; } bool pj_fwd4d(PJ_COORD &coo, PJ *P) { const int last_errno = P->ctx->last_errno; P->ctx->last_errno = 0; if (!P->skip_fwd_prepare) fwd_prepare(P, coo); if (HUGE_VAL == coo.v[0]) { coo = proj_coord_error(); return false; } /* Call the highest dimensional converter available */ if (P->fwd4d) P->fwd4d(coo, P); else if (P->fwd3d) { const auto xyz = P->fwd3d(coo.lpz, P); coo.xyz = xyz; } else if (P->fwd) { const auto xy = P->fwd(coo.lp, P); coo.xy = xy; } else { proj_errno_set(P, PROJ_ERR_OTHER_NO_INVERSE_OP); coo = proj_coord_error(); return false; } if (HUGE_VAL == coo.v[0]) { coo = proj_coord_error(); return false; } if (!P->skip_fwd_finalize) fwd_finalize(P, coo); if (P->ctx->last_errno) { coo = proj_coord_error(); return false; } P->ctx->last_errno = last_errno; return true; }
cpp
PROJ
data/projects/PROJ/src/internal.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: This is primarily material originating from pj_obs_api.c * (now proj_4D_api.c), that does not fit into the API * category. Hence this pile of tubings and fittings for * PROJ.4 internal plumbing. * * Author: Thomas Knudsen, [email protected], 2017-07-05 * ****************************************************************************** * Copyright (c) 2016, 2017, 2018, 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 <ctype.h> #include <errno.h> #include <math.h> #include <stdarg.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "geodesic.h" #include "proj_internal.h" #include "proj/internal/internal.hpp" using namespace NS_PROJ::internal; enum pj_io_units pj_left(PJ *P) { enum pj_io_units u = P->inverted ? P->right : P->left; if (u == PJ_IO_UNITS_CLASSIC) return PJ_IO_UNITS_PROJECTED; return u; } enum pj_io_units pj_right(PJ *P) { enum pj_io_units u = P->inverted ? P->left : P->right; if (u == PJ_IO_UNITS_CLASSIC) return PJ_IO_UNITS_PROJECTED; return u; } /* Work around non-constness of MSVC HUGE_VAL by providing functions rather than * constants */ PJ_COORD proj_coord_error(void) { PJ_COORD c; c.v[0] = c.v[1] = c.v[2] = c.v[3] = HUGE_VAL; return c; } /**************************************************************************************/ PJ_COORD pj_approx_2D_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coo) { /*************************************************************************************** Behave mostly as proj_trans, but attempt to use 2D interfaces only. Used in gie.c, to enforce testing 2D code, and by PJ_pipeline.c to implement chained calls starting out with a call to its 2D interface. ***************************************************************************************/ if (nullptr == P) return coo; if (P->inverted) direction = static_cast<PJ_DIRECTION>(-direction); switch (direction) { case PJ_FWD: { const auto xy = pj_fwd(coo.lp, P); coo.xy = xy; return coo; } case PJ_INV: { const auto lp = pj_inv(coo.xy, P); coo.lp = lp; return coo; } case PJ_IDENT: break; } return coo; } /**************************************************************************************/ PJ_COORD pj_approx_3D_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coo) { /*************************************************************************************** Companion to pj_approx_2D_trans. Behave mostly as proj_trans, but attempt to use 3D interfaces only. Used in gie.c, to enforce testing 3D code, and by PJ_pipeline.c to implement chained calls starting out with a call to its 3D interface. ***************************************************************************************/ if (nullptr == P) return coo; if (P->inverted) direction = static_cast<PJ_DIRECTION>(-direction); switch (direction) { case PJ_FWD: { const auto xyz = pj_fwd3d(coo.lpz, P); coo.xyz = xyz; return coo; } case PJ_INV: { const auto lpz = pj_inv3d(coo.xyz, P); coo.lpz = lpz; return coo; } case PJ_IDENT: break; } return coo; } /**************************************************************************************/ int pj_has_inverse(PJ *P) { /*************************************************************************************** Check if a a PJ has an inverse. ***************************************************************************************/ return ((P->inverted && (P->fwd || P->fwd3d || P->fwd4d)) || (P->inv || P->inv3d || P->inv4d)); } /* Move P to a new context - or to the default context if 0 is specified */ void proj_context_set(PJ *P, PJ_CONTEXT *ctx) { if (nullptr == ctx) ctx = pj_get_default_ctx(); proj_assign_context(P, ctx); } void proj_context_inherit(PJ *parent, PJ *child) { if (nullptr == parent) proj_assign_context(child, pj_get_default_ctx()); else proj_assign_context(child, pj_get_ctx(parent)); } /*****************************************************************************/ char *pj_chomp(char *c) { /****************************************************************************** Strip pre- and postfix whitespace. Inline comments (indicated by '#') are considered whitespace. ******************************************************************************/ size_t i, n; char *comment; char *start = c; if (nullptr == c) return nullptr; comment = strchr(c, '#'); if (comment) *comment = 0; n = strlen(c); if (0 == n) return c; /* Eliminate postfix whitespace */ for (i = n - 1; (i > 0) && (isspace(c[i]) || ';' == c[i]); i--) c[i] = 0; /* Find start of non-whitespace */ while (0 != *start && (';' == *start || isspace(*start))) start++; n = strlen(start); if (0 == n) { c[0] = 0; return c; } memmove(c, start, n + 1); return c; } /*****************************************************************************/ char *pj_shrink(char *c) { /****************************************************************************** Collapse repeated whitespace. Remove '+' and ';'. Make ',' and '=' greedy, consuming their surrounding whitespace. ******************************************************************************/ size_t i, j, n; /* Flag showing that a whitespace (ws) has been written after last non-ws */ bool ws = false; if (nullptr == c) return nullptr; pj_chomp(c); n = strlen(c); if (n == 0) return c; /* First collapse repeated whitespace (including +/;) */ i = 0; bool in_string = false; for (j = 0; j < n; j++) { if (in_string) { if (c[j] == '"' && c[j + 1] == '"') { c[i++] = c[j]; j++; } else if (c[j] == '"') { in_string = false; } c[i++] = c[j]; continue; } /* Eliminate prefix '+', only if preceded by whitespace */ /* (i.e. keep it in 1.23e+08) */ if ((i > 0) && ('+' == c[j]) && ws) c[j] = ' '; if ((i == 0) && ('+' == c[j])) c[j] = ' '; // Detect a string beginning after '=' if (c[j] == '"' && i > 0 && c[i - 1] == '=') { in_string = true; ws = false; c[i++] = c[j]; continue; } if (isspace(c[j]) || ';' == c[j]) { if (false == ws && (i > 0)) c[i++] = ' '; ws = true; continue; } else { ws = false; c[i++] = c[j]; } } c[i] = 0; n = strlen(c); /* Then make ',' and '=' greedy */ i = 0; for (j = 0; j < n; j++) { if (i == 0) { c[i++] = c[j]; continue; } /* Skip space before '='/',' */ if ('=' == c[j] || ',' == c[j]) { if (c[i - 1] == ' ') c[i - 1] = c[j]; else c[i++] = c[j]; continue; } if (' ' == c[j] && ('=' == c[i - 1] || ',' == c[i - 1])) continue; c[i++] = c[j]; } c[i] = 0; return c; } /*****************************************************************************/ size_t pj_trim_argc(char *args) { /****************************************************************************** Trim all unnecessary whitespace (and non-essential syntactic tokens) from the argument string, args, and count its number of elements. ******************************************************************************/ size_t i, m, n; pj_shrink(args); n = strlen(args); if (n == 0) return 0; bool in_string = false; for (i = m = 0; i < n; i++) { if (in_string) { if (args[i] == '"' && args[i + 1] == '"') { i++; } else if (args[i] == '"') { in_string = false; } } else if (args[i] == '=' && args[i + 1] == '"') { i++; in_string = true; } else if (' ' == args[i]) { args[i] = 0; m++; } } return m + 1; } static void unquote_string(char *param_str) { size_t len = strlen(param_str); // Remove leading and terminating spaces after equal sign const char *equal = strstr(param_str, "=\""); if (equal && equal - param_str + 1 >= 2 && param_str[len - 1] == '"') { size_t dst = equal + 1 - param_str; size_t src = dst + 1; for (; param_str[src]; dst++, src++) { if (param_str[src] == '"') { if (param_str[src + 1] == '"') { src++; } else { break; } } param_str[dst] = param_str[src]; } param_str[dst] = '\0'; } } /*****************************************************************************/ char **pj_trim_argv(size_t argc, char *args) { /****************************************************************************** Create an argv-style array from elements placed in the argument string, args. args is a trimmed string as returned by pj_trim_argc(), and argc is the number of trimmed strings found (i.e. the return value of pj_trim_args()). Hence, int argc = pj_trim_argc (args); char **argv = pj_trim_argv (argc, args); will produce a classic style (argc, argv) pair from a string of whitespace separated args. No new memory is allocated for storing the individual args (they stay in the args string), but for the pointers to the args a new array is allocated and returned. It is the duty of the caller to free this array. ******************************************************************************/ if (nullptr == args) return nullptr; if (0 == argc) return nullptr; /* turn the input string into an array of strings */ char **argv = (char **)calloc(argc, sizeof(char *)); if (nullptr == argv) return nullptr; for (size_t i = 0, j = 0; j < argc; j++) { argv[j] = args + i; char *str = argv[j]; size_t nLen = strlen(str); i += nLen + 1; unquote_string(str); } return argv; } /*****************************************************************************/ std::string pj_double_quote_string_param_if_needed(const std::string &str) { /*****************************************************************************/ if (str.find(' ') == std::string::npos) { return str; } std::string ret; ret += '"'; ret += replaceAll(str, "\"", "\"\""); ret += '"'; return ret; } /*****************************************************************************/ char *pj_make_args(size_t argc, char **argv) { /****************************************************************************** pj_make_args is the inverse of the pj_trim_argc/pj_trim_argv combo: It converts free format command line input to something proj_create can consume. Allocates, and returns, an array of char, large enough to hold a whitespace separated copy of the args in argv. It is the duty of the caller to free this array. ******************************************************************************/ try { std::string s; for (size_t i = 0; i < argc; i++) { const char *equal = strchr(argv[i], '='); if (equal) { s += std::string(argv[i], equal - argv[i] + 1); s += pj_double_quote_string_param_if_needed(equal + 1); } else { s += argv[i]; } s += ' '; } char *p = pj_strdup(s.c_str()); return pj_shrink(p); } catch (const std::exception &) { return nullptr; } } /*****************************************************************************/ void proj_context_errno_set(PJ_CONTEXT *ctx, int err) { /****************************************************************************** Raise an error directly on a context, without going through a PJ belonging to that context. ******************************************************************************/ if (nullptr == ctx) ctx = pj_get_default_ctx(); ctx->last_errno = err; if (err == 0) return; errno = err; }
cpp
PROJ
data/projects/PROJ/src/datum_set.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Apply datum definition to PJ structure from initialization string. * 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. *****************************************************************************/ #include <string.h> #include "proj.h" #include "proj_internal.h" /* SEC_TO_RAD = Pi/180/3600 */ #define SEC_TO_RAD 4.84813681109535993589914102357e-6 /************************************************************************/ /* pj_datum_set() */ /************************************************************************/ int pj_datum_set(PJ_CONTEXT *ctx, paralist *pl, PJ *projdef) { const char *name, *towgs84, *nadgrids; projdef->datum_type = PJD_UNKNOWN; /* -------------------------------------------------------------------- */ /* Is there a datum definition in the parameters list? If so, */ /* add the defining values to the parameter list. Note that */ /* this will append the ellipse definition as well as the */ /* towgs84= and related parameters. It should also be pointed */ /* out that the addition is permanent rather than temporary */ /* like most other keyword expansion so that the ellipse */ /* definition will last into the pj_ell_set() function called */ /* after this one. */ /* -------------------------------------------------------------------- */ if ((name = pj_param(ctx, pl, "sdatum").s) != nullptr) { paralist *curr; const char *s; int i; /* find the end of the list, so we can add to it */ for (curr = pl; curr && curr->next; curr = curr->next) { } /* cannot happen in practice, but makes static analyzers happy */ if (!curr) return -1; /* find the datum definition */ const struct PJ_DATUMS *pj_datums = pj_get_datums_ref(); for (i = 0; (s = pj_datums[i].id) && strcmp(name, s); ++i) { } if (!s) { pj_log(ctx, PJ_LOG_ERROR, _("Unknown value for datum")); proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return 1; } if (pj_datums[i].ellipse_id && strlen(pj_datums[i].ellipse_id) > 0) { char entry[100]; strcpy(entry, "ellps="); strncpy(entry + strlen(entry), pj_datums[i].ellipse_id, sizeof(entry) - 1 - strlen(entry)); entry[sizeof(entry) - 1] = '\0'; auto param = pj_mkparam(entry); if (nullptr == param) { proj_context_errno_set(ctx, PROJ_ERR_OTHER /*ENOMEM*/); return 1; } curr->next = param; curr = param; } if (pj_datums[i].defn && strlen(pj_datums[i].defn) > 0) { auto param = pj_mkparam(pj_datums[i].defn); if (nullptr == param) { proj_context_errno_set(ctx, PROJ_ERR_OTHER /*ENOMEM*/); return 1; } curr->next = param; /* curr = param; */ } } /* -------------------------------------------------------------------- */ /* Check for nadgrids parameter. */ /* -------------------------------------------------------------------- */ nadgrids = pj_param(ctx, pl, "snadgrids").s; if (nadgrids != nullptr) { /* We don't actually save the value separately. It will continue to exist int he param list for use in pj_apply_gridshift.c */ projdef->datum_type = PJD_GRIDSHIFT; } /* -------------------------------------------------------------------- */ /* Check for towgs84 parameter. */ /* -------------------------------------------------------------------- */ else if ((towgs84 = pj_param(ctx, pl, "stowgs84").s) != nullptr) { int parm_count = 0; const char *s; memset(projdef->datum_params, 0, sizeof(double) * 7); /* parse out the parameters */ for (s = towgs84; *s != '\0' && parm_count < 7;) { projdef->datum_params[parm_count++] = pj_atof(s); while (*s != '\0' && *s != ',') s++; if (*s == ',') s++; } if (projdef->datum_params[3] != 0.0 || projdef->datum_params[4] != 0.0 || projdef->datum_params[5] != 0.0 || projdef->datum_params[6] != 0.0) { projdef->datum_type = PJD_7PARAM; /* transform from arc seconds to radians */ projdef->datum_params[3] *= SEC_TO_RAD; projdef->datum_params[4] *= SEC_TO_RAD; projdef->datum_params[5] *= SEC_TO_RAD; /* transform from parts per million to scaling factor */ projdef->datum_params[6] = (projdef->datum_params[6] / 1000000.0) + 1; } else projdef->datum_type = PJD_3PARAM; /* Note that pj_init() will later switch datum_type to PJD_WGS84 if shifts are all zero, and ellipsoid is WGS84 or GRS80 */ } return 0; }
cpp
PROJ
data/projects/PROJ/src/factors.cpp
/* projection scale factors */ #include "proj.h" #include "proj_internal.h" #include <math.h> #include <errno.h> #ifndef DEFAULT_H #define DEFAULT_H 1e-5 /* radian default for numeric h */ #endif #define EPS 1.0e-12 int pj_factors(PJ_LP lp, const PJ *P, double h, struct FACTORS *fac) { double cosphi, t, n, r; int err; PJ_COORD coo = {{0, 0, 0, 0}}; coo.lp = lp; /* Failing the 3 initial checks will most likely be due to */ /* earlier errors, so we leave errno alone */ if (nullptr == fac) return 1; if (nullptr == P) return 1; if (HUGE_VAL == lp.lam) return 1; /* But from here, we're ready to make our own mistakes */ err = proj_errno_reset(P); /* Indicate that all factors are numerical approximations */ fac->code = 0; /* Check for latitude or longitude overange */ if ((fabs(lp.phi) - M_HALFPI) > EPS) { proj_log_error(P, _("Invalid latitude")); proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_INVALID_COORD); return 1; } if (fabs(lp.lam) > 10.) { proj_log_error(P, _("Invalid longitude")); proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_INVALID_COORD); return 1; } /* Set a reasonable step size for the numerical derivatives */ h = fabs(h); if (h < EPS) h = DEFAULT_H; /* If input latitudes are geocentric, convert to geographic */ if (P->geoc) lp = pj_geocentric_latitude(P, PJ_INV, coo).lp; /* If latitude + one step overshoots the pole, move it slightly inside, */ /* so the numerical derivative still exists */ if (fabs(lp.phi) > (M_HALFPI - h)) lp.phi = lp.phi < 0. ? -(M_HALFPI - h) : (M_HALFPI - h); /* Longitudinal distance from central meridian */ lp.lam -= P->lam0; if (!P->over) lp.lam = adjlon(lp.lam); /* Derivatives */ if (pj_deriv(lp, h, P, &(fac->der))) { proj_log_error(P, _("Invalid latitude or longitude")); proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_INVALID_COORD); return 1; } /* Scale factors */ cosphi = cos(lp.phi); fac->h = hypot(fac->der.x_p, fac->der.y_p); fac->k = hypot(fac->der.x_l, fac->der.y_l) / cosphi; if (P->es != 0.0) { t = sin(lp.phi); t = 1. - P->es * t * t; n = sqrt(t); fac->h *= t * n / P->one_es; fac->k *= n; r = t * t / P->one_es; } else r = 1.; /* Convergence */ fac->conv = -atan2(fac->der.x_p, fac->der.y_p); /* Areal scale factor */ fac->s = (fac->der.y_p * fac->der.x_l - fac->der.x_p * fac->der.y_l) * r / cosphi; /* Meridian-parallel angle (theta prime) */ fac->thetap = aasin(P->ctx, fac->s / (fac->h * fac->k)); /* Tissot ellipse axis */ t = fac->k * fac->k + fac->h * fac->h; fac->a = sqrt(t + 2. * fac->s); t = t - 2. * fac->s; t = t > 0 ? sqrt(t) : 0; fac->b = 0.5 * (fac->a - t); fac->a = 0.5 * (fac->a + t); /* Angular distortion */ fac->omega = 2. * aasin(P->ctx, (fac->a - fac->b) / (fac->a + fac->b)); proj_errno_restore(P, err); return 0; }
cpp
PROJ
data/projects/PROJ/src/wkt1_generated_parser.h
/* A Bison parser, made by GNU Bison 3.5.1. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ #ifndef YY_PJ_WKT1_WKT1_GENERATED_PARSER_H_INCLUDED # define YY_PJ_WKT1_WKT1_GENERATED_PARSER_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int pj_wkt1_debug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { END = 0, T_PARAM_MT = 258, T_CONCAT_MT = 259, T_INVERSE_MT = 260, T_PASSTHROUGH_MT = 261, T_PROJCS = 262, T_PROJECTION = 263, T_GEOGCS = 264, T_DATUM = 265, T_SPHEROID = 266, T_PRIMEM = 267, T_UNIT = 268, T_LINUNIT = 269, T_GEOCCS = 270, T_AUTHORITY = 271, T_VERT_CS = 272, T_VERTCS = 273, T_VERT_DATUM = 274, T_VDATUM = 275, T_COMPD_CS = 276, T_AXIS = 277, T_TOWGS84 = 278, T_FITTED_CS = 279, T_LOCAL_CS = 280, T_LOCAL_DATUM = 281, T_PARAMETER = 282, T_EXTENSION = 283, T_STRING = 284, T_NUMBER = 285, T_IDENTIFIER = 286 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif int pj_wkt1_parse (pj_wkt1_parse_context *context); #endif /* !YY_PJ_WKT1_WKT1_GENERATED_PARSER_H_INCLUDED */
h
PROJ
data/projects/PROJ/src/filemanager.hpp
/****************************************************************************** * Project: PROJ * Purpose: File manager * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2019, 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. *****************************************************************************/ #ifndef FILEMANAGER_HPP_INCLUDED #define FILEMANAGER_HPP_INCLUDED #include <memory> #include <string> #include <vector> #include "proj.h" #include "proj/util.hpp" //! @cond Doxygen_Suppress NS_PROJ_START class File; enum class FileAccess { READ_ONLY, // "rb" READ_UPDATE, // "r+b" CREATE, // "w+b" }; class FileManager { private: FileManager() = delete; public: // "Low-level" interface. static PROJ_DLL std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename, FileAccess access); static PROJ_DLL bool exists(PJ_CONTEXT *ctx, const char *filename); static bool mkdir(PJ_CONTEXT *ctx, const char *filename); static bool unlink(PJ_CONTEXT *ctx, const char *filename); static bool rename(PJ_CONTEXT *ctx, const char *oldPath, const char *newPath); static std::string getProjDataEnvVar(PJ_CONTEXT *ctx); // "High-level" interface, honoring PROJ_DATA and the like. static std::unique_ptr<File> open_resource_file(PJ_CONTEXT *ctx, const char *name, char *out_full_filename = nullptr, size_t out_full_filename_size = 0); static void fillDefaultNetworkInterface(PJ_CONTEXT *ctx); static void clearMemoryCache(); }; // --------------------------------------------------------------------------- class File { protected: std::string name_; std::string readLineBuffer_{}; bool eofReadLine_ = false; explicit File(const std::string &filename); public: virtual PROJ_DLL ~File(); virtual size_t read(void *buffer, size_t sizeBytes) = 0; virtual size_t write(const void *buffer, size_t sizeBytes) = 0; virtual bool seek(unsigned long long offset, int whence = SEEK_SET) = 0; virtual unsigned long long tell() = 0; virtual void reassign_context(PJ_CONTEXT *ctx) = 0; virtual bool hasChanged() const = 0; std::string PROJ_DLL read_line(size_t maxLen, bool &maxLenReached, bool &eofReached); const std::string &name() const { return name_; } }; // --------------------------------------------------------------------------- std::unique_ptr<File> pj_network_file_open(PJ_CONTEXT *ctx, const char *filename); NS_PROJ_END // Exported for projsync std::vector<std::string> PROJ_DLL pj_get_default_searchpaths(PJ_CONTEXT *ctx); //! @endcond Doxygen_Suppress #endif // FILEMANAGER_HPP_INCLUDED
hpp
PROJ
data/projects/PROJ/src/initcache.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: init file definition cache. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2009, 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. *****************************************************************************/ #include <assert.h> #include <string.h> #include "proj.h" #include "proj_internal.h" static int cache_count = 0; static int cache_alloc = 0; static char **cache_key = nullptr; static paralist **cache_paralist = nullptr; /************************************************************************/ /* pj_clone_paralist() */ /* */ /* Allocate a copy of a parameter list. */ /************************************************************************/ paralist *pj_clone_paralist(const paralist *list) { paralist *list_copy = nullptr, *next_copy = nullptr; for (; list != nullptr; list = list->next) { paralist *newitem = (paralist *)malloc(sizeof(paralist) + strlen(list->param)); assert(newitem); newitem->used = 0; newitem->next = nullptr; strcpy(newitem->param, list->param); if (next_copy) next_copy->next = newitem; else list_copy = newitem; next_copy = newitem; } return list_copy; } /************************************************************************/ /* pj_clear_initcache() */ /* */ /* Clear out all memory held in the init file cache. */ /************************************************************************/ void pj_clear_initcache() { if (cache_alloc > 0) { int i; pj_acquire_lock(); for (i = 0; i < cache_count; i++) { paralist *n, *t = cache_paralist[i]; free(cache_key[i]); /* free parameter list elements */ for (; t != nullptr; t = n) { n = t->next; free(t); } } free(cache_key); free(cache_paralist); cache_count = 0; cache_alloc = 0; cache_key = nullptr; cache_paralist = nullptr; pj_release_lock(); } } /************************************************************************/ /* pj_search_initcache() */ /* */ /* Search for a matching definition in the init cache. */ /************************************************************************/ paralist *pj_search_initcache(const char *filekey) { int i; paralist *result = nullptr; pj_acquire_lock(); for (i = 0; result == nullptr && i < cache_count; i++) { if (strcmp(filekey, cache_key[i]) == 0) { result = pj_clone_paralist(cache_paralist[i]); } } pj_release_lock(); return result; } /************************************************************************/ /* pj_insert_initcache() */ /* */ /* Insert a paralist definition in the init file cache. */ /************************************************************************/ void pj_insert_initcache(const char *filekey, const paralist *list) { pj_acquire_lock(); /* ** Grow list if required. */ if (cache_count == cache_alloc) { char **cache_key_new; paralist **cache_paralist_new; cache_alloc = cache_alloc * 2 + 15; cache_key_new = (char **)malloc(sizeof(char *) * cache_alloc); assert(cache_key_new); if (cache_key && cache_count) { memcpy(cache_key_new, cache_key, sizeof(char *) * cache_count); } free(cache_key); cache_key = cache_key_new; cache_paralist_new = (paralist **)malloc(sizeof(paralist *) * cache_alloc); assert(cache_paralist_new); if (cache_paralist && cache_count) { memcpy(cache_paralist_new, cache_paralist, sizeof(paralist *) * cache_count); } free(cache_paralist); cache_paralist = cache_paralist_new; } /* ** Duplicate the filekey and paralist, and insert in cache. */ cache_key[cache_count] = (char *)malloc(strlen(filekey) + 1); assert(cache_key[cache_count]); strcpy(cache_key[cache_count], filekey); cache_paralist[cache_count] = pj_clone_paralist(list); cache_count++; pj_release_lock(); }
cpp
PROJ
data/projects/PROJ/src/wkt2_generated_parser.c
/* A Bison parser, made by GNU Bison 3.5.1. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.5.1" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Substitute the variable and function names. */ #define yyparse pj_wkt2_parse #define yylex pj_wkt2_lex #define yyerror pj_wkt2_error #define yydebug pj_wkt2_debug #define yynerrs pj_wkt2_nerrs /* First part of user prologue. */ /****************************************************************************** * Project: PROJ * Purpose: WKT2 parser grammar * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2018 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. ****************************************************************************/ #include "wkt2_parser.h" # ifndef YY_CAST # ifdef __cplusplus # define YY_CAST(Type, Val) static_cast<Type> (Val) # define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val) # else # define YY_CAST(Type, Val) ((Type) (Val)) # define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) # endif # endif # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* Use api.header.include to #include this header instead of duplicating it here. */ #ifndef YY_PJ_WKT2_WKT2_GENERATED_PARSER_H_INCLUDED # define YY_PJ_WKT2_WKT2_GENERATED_PARSER_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int pj_wkt2_debug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { END = 0, T_PROJECTION = 258, T_DATUM = 259, T_SPHEROID = 260, T_PRIMEM = 261, T_UNIT = 262, T_AXIS = 263, T_PARAMETER = 264, T_GEODCRS = 265, T_LENGTHUNIT = 266, T_ANGLEUNIT = 267, T_SCALEUNIT = 268, T_TIMEUNIT = 269, T_ELLIPSOID = 270, T_CS = 271, T_ID = 272, T_PROJCRS = 273, T_BASEGEODCRS = 274, T_MERIDIAN = 275, T_BEARING = 276, T_ORDER = 277, T_ANCHOR = 278, T_ANCHOREPOCH = 279, T_CONVERSION = 280, T_METHOD = 281, T_REMARK = 282, T_GEOGCRS = 283, T_BASEGEOGCRS = 284, T_SCOPE = 285, T_AREA = 286, T_BBOX = 287, T_CITATION = 288, T_URI = 289, T_VERTCRS = 290, T_VDATUM = 291, T_GEOIDMODEL = 292, T_COMPOUNDCRS = 293, T_PARAMETERFILE = 294, T_COORDINATEOPERATION = 295, T_SOURCECRS = 296, T_TARGETCRS = 297, T_INTERPOLATIONCRS = 298, T_OPERATIONACCURACY = 299, T_CONCATENATEDOPERATION = 300, T_STEP = 301, T_BOUNDCRS = 302, T_ABRIDGEDTRANSFORMATION = 303, T_DERIVINGCONVERSION = 304, T_TDATUM = 305, T_CALENDAR = 306, T_TIMEORIGIN = 307, T_TIMECRS = 308, T_VERTICALEXTENT = 309, T_TIMEEXTENT = 310, T_USAGE = 311, T_DYNAMIC = 312, T_FRAMEEPOCH = 313, T_MODEL = 314, T_VELOCITYGRID = 315, T_ENSEMBLE = 316, T_MEMBER = 317, T_ENSEMBLEACCURACY = 318, T_DERIVEDPROJCRS = 319, T_BASEPROJCRS = 320, T_EDATUM = 321, T_ENGCRS = 322, T_PDATUM = 323, T_PARAMETRICCRS = 324, T_PARAMETRICUNIT = 325, T_BASEVERTCRS = 326, T_BASEENGCRS = 327, T_BASEPARAMCRS = 328, T_BASETIMECRS = 329, T_EPOCH = 330, T_COORDEPOCH = 331, T_COORDINATEMETADATA = 332, T_POINTMOTIONOPERATION = 333, T_VERSION = 334, T_AXISMINVALUE = 335, T_AXISMAXVALUE = 336, T_RANGEMEANING = 337, T_exact = 338, T_wraparound = 339, T_GEODETICCRS = 340, T_GEODETICDATUM = 341, T_PROJECTEDCRS = 342, T_PRIMEMERIDIAN = 343, T_GEOGRAPHICCRS = 344, T_TRF = 345, T_VERTICALCRS = 346, T_VERTICALDATUM = 347, T_VRF = 348, T_TIMEDATUM = 349, T_TEMPORALQUANTITY = 350, T_ENGINEERINGDATUM = 351, T_ENGINEERINGCRS = 352, T_PARAMETRICDATUM = 353, T_AFFINE = 354, T_CARTESIAN = 355, T_CYLINDRICAL = 356, T_ELLIPSOIDAL = 357, T_LINEAR = 358, T_PARAMETRIC = 359, T_POLAR = 360, T_SPHERICAL = 361, T_VERTICAL = 362, T_TEMPORAL = 363, T_TEMPORALCOUNT = 364, T_TEMPORALMEASURE = 365, T_ORDINAL = 366, T_TEMPORALDATETIME = 367, T_NORTH = 368, T_NORTHNORTHEAST = 369, T_NORTHEAST = 370, T_EASTNORTHEAST = 371, T_EAST = 372, T_EASTSOUTHEAST = 373, T_SOUTHEAST = 374, T_SOUTHSOUTHEAST = 375, T_SOUTH = 376, T_SOUTHSOUTHWEST = 377, T_SOUTHWEST = 378, T_WESTSOUTHWEST = 379, T_WEST = 380, T_WESTNORTHWEST = 381, T_NORTHWEST = 382, T_NORTHNORTHWEST = 383, T_UP = 384, T_DOWN = 385, T_GEOCENTRICX = 386, T_GEOCENTRICY = 387, T_GEOCENTRICZ = 388, T_COLUMNPOSITIVE = 389, T_COLUMNNEGATIVE = 390, T_ROWPOSITIVE = 391, T_ROWNEGATIVE = 392, T_DISPLAYRIGHT = 393, T_DISPLAYLEFT = 394, T_DISPLAYUP = 395, T_DISPLAYDOWN = 396, T_FORWARD = 397, T_AFT = 398, T_PORT = 399, T_STARBOARD = 400, T_CLOCKWISE = 401, T_COUNTERCLOCKWISE = 402, T_TOWARDS = 403, T_AWAYFROM = 404, T_FUTURE = 405, T_PAST = 406, T_UNSPECIFIED = 407, T_STRING = 408, T_UNSIGNED_INTEGER_DIFFERENT_ONE_TWO_THREE = 409 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif int pj_wkt2_parse (pj_wkt2_parse_context *context); #endif /* !YY_PJ_WKT2_WKT2_GENERATED_PARSER_H_INCLUDED */ #ifdef short # undef short #endif /* On compilers that do not define __PTRDIFF_MAX__ etc., make sure <limits.h> and (if available) <stdint.h> are included so that the code can choose integer types of a good width. */ #ifndef __PTRDIFF_MAX__ # include <limits.h> /* INFRINGES ON USER NAME SPACE */ # if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stdint.h> /* INFRINGES ON USER NAME SPACE */ # define YY_STDINT_H # endif #endif /* Narrow types that promote to a signed type and that can represent a signed or unsigned integer of at least N bits. In tables they can save space and decrease cache pressure. Promoting to a signed type helps avoid bugs in integer arithmetic. */ #ifdef __INT_LEAST8_MAX__ typedef __INT_LEAST8_TYPE__ yytype_int8; #elif defined YY_STDINT_H typedef int_least8_t yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef __INT_LEAST16_MAX__ typedef __INT_LEAST16_TYPE__ yytype_int16; #elif defined YY_STDINT_H typedef int_least16_t yytype_int16; #else typedef short yytype_int16; #endif #if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ typedef __UINT_LEAST8_TYPE__ yytype_uint8; #elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \ && UINT_LEAST8_MAX <= INT_MAX) typedef uint_least8_t yytype_uint8; #elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX typedef unsigned char yytype_uint8; #else typedef short yytype_uint8; #endif #if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ typedef __UINT_LEAST16_TYPE__ yytype_uint16; #elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \ && UINT_LEAST16_MAX <= INT_MAX) typedef uint_least16_t yytype_uint16; #elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX typedef unsigned short yytype_uint16; #else typedef int yytype_uint16; #endif #ifndef YYPTRDIFF_T # if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__ # define YYPTRDIFF_T __PTRDIFF_TYPE__ # define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__ # elif defined PTRDIFF_MAX # ifndef ptrdiff_t # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # endif # define YYPTRDIFF_T ptrdiff_t # define YYPTRDIFF_MAXIMUM PTRDIFF_MAX # else # define YYPTRDIFF_T long # define YYPTRDIFF_MAXIMUM LONG_MAX # endif #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM \ YY_CAST (YYPTRDIFF_T, \ (YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \ ? YYPTRDIFF_MAXIMUM \ : YY_CAST (YYSIZE_T, -1))) #define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X)) /* Stored state numbers (used for stacks). */ typedef yytype_int16 yy_state_t; /* State numbers in computations. */ typedef int yy_state_fast_t; #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE_PURE # if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) # else # define YY_ATTRIBUTE_PURE # endif #endif #ifndef YY_ATTRIBUTE_UNUSED # if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) # else # define YY_ATTRIBUTE_UNUSED # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ # define YY_IGNORE_USELESS_CAST_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") # define YY_IGNORE_USELESS_CAST_END \ _Pragma ("GCC diagnostic pop") #endif #ifndef YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_END #endif #define YY_ASSERT(E) ((void) (0 && (E))) #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yy_state_t yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYPTRDIFF_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / YYSIZEOF (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYPTRDIFF_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 106 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 3343 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 170 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 367 /* YYNRULES -- Number of rules. */ #define YYNRULES 732 /* YYNSTATES -- Number of states. */ #define YYNSTATES 1496 #define YYUNDEFTOK 2 #define YYMAXUTOK 409 /* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM as returned by yylex, with out-of-bounds checking. */ #define YYTRANSLATE(YYX) \ (0 <= (YYX) && (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 166, 168, 2, 160, 169, 161, 155, 2, 2, 157, 158, 159, 2, 2, 2, 2, 2, 2, 162, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 156, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 163, 2, 2, 2, 2, 2, 164, 165, 2, 167, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_int16 yyrline[] = { 0, 213, 213, 213, 213, 213, 213, 213, 214, 214, 214, 215, 218, 218, 219, 219, 219, 220, 222, 222, 226, 230, 230, 232, 234, 236, 236, 238, 238, 240, 242, 244, 246, 248, 248, 250, 250, 252, 252, 252, 252, 254, 254, 258, 260, 264, 265, 266, 268, 268, 270, 272, 274, 276, 280, 281, 284, 285, 287, 289, 291, 294, 295, 296, 298, 300, 302, 302, 304, 307, 308, 310, 310, 315, 315, 317, 317, 319, 321, 323, 327, 328, 331, 332, 333, 335, 335, 336, 339, 340, 344, 345, 346, 350, 351, 352, 353, 355, 359, 361, 364, 366, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 404, 406, 408, 412, 417, 419, 421, 423, 425, 429, 434, 435, 437, 439, 441, 445, 449, 451, 451, 453, 453, 458, 463, 464, 465, 466, 467, 468, 469, 471, 473, 475, 475, 477, 477, 479, 481, 483, 485, 487, 489, 493, 495, 499, 499, 502, 505, 510, 510, 510, 510, 510, 513, 518, 518, 518, 518, 521, 525, 526, 528, 544, 548, 549, 551, 551, 553, 553, 559, 559, 561, 563, 570, 570, 570, 570, 572, 579, 580, 581, 582, 584, 591, 592, 593, 594, 596, 603, 610, 611, 612, 614, 616, 616, 616, 616, 616, 616, 616, 616, 616, 618, 618, 620, 620, 622, 622, 622, 624, 629, 635, 640, 643, 646, 647, 648, 649, 650, 651, 652, 653, 654, 657, 658, 659, 660, 661, 662, 663, 664, 667, 668, 669, 670, 671, 672, 673, 674, 677, 678, 681, 682, 683, 684, 685, 689, 690, 691, 692, 693, 694, 695, 696, 697, 700, 701, 702, 703, 706, 707, 708, 709, 712, 713, 716, 717, 718, 723, 724, 727, 728, 729, 730, 731, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 771, 774, 776, 778, 780, 782, 785, 786, 787, 788, 790, 791, 792, 793, 794, 796, 797, 799, 800, 802, 803, 804, 804, 806, 822, 822, 824, 832, 833, 835, 836, 838, 846, 847, 849, 851, 853, 858, 859, 861, 863, 865, 867, 869, 871, 873, 878, 882, 884, 887, 890, 891, 892, 894, 895, 897, 902, 903, 905, 905, 907, 911, 911, 911, 913, 913, 915, 923, 932, 940, 950, 951, 953, 955, 955, 957, 957, 960, 961, 965, 971, 972, 973, 975, 975, 977, 979, 981, 985, 990, 990, 992, 995, 996, 1001, 1002, 1004, 1009, 1009, 1009, 1011, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1022, 1025, 1027, 1029, 1032, 1034, 1034, 1034, 1038, 1044, 1044, 1048, 1048, 1049, 1049, 1051, 1056, 1057, 1058, 1059, 1060, 1062, 1068, 1073, 1079, 1081, 1083, 1085, 1089, 1095, 1096, 1097, 1099, 1101, 1103, 1107, 1107, 1109, 1111, 1116, 1117, 1118, 1120, 1122, 1124, 1126, 1130, 1130, 1132, 1138, 1145, 1145, 1148, 1155, 1156, 1157, 1158, 1159, 1161, 1162, 1163, 1165, 1169, 1171, 1173, 1173, 1177, 1182, 1182, 1182, 1186, 1191, 1191, 1193, 1197, 1197, 1199, 1200, 1201, 1202, 1206, 1211, 1213, 1217, 1217, 1221, 1226, 1228, 1232, 1233, 1234, 1235, 1236, 1238, 1238, 1240, 1243, 1245, 1245, 1247, 1249, 1251, 1255, 1261, 1262, 1263, 1264, 1266, 1268, 1272, 1277, 1279, 1282, 1288, 1289, 1290, 1292, 1296, 1302, 1302, 1302, 1302, 1302, 1302, 1306, 1311, 1313, 1318, 1318, 1319, 1321, 1321, 1323, 1330, 1330, 1332, 1339, 1339, 1341, 1348, 1355, 1360, 1361, 1362, 1364, 1370, 1375, 1383, 1389, 1391, 1393, 1399, 1401, 1401, 1402, 1402, 1406, 1412, 1412, 1414, 1419, 1425, 1430, 1436, 1441, 1446, 1452, 1457, 1462, 1468, 1473, 1478, 1484, 1484, 1485, 1485, 1486, 1486, 1487, 1487, 1488, 1488, 1489, 1489, 1492, 1492, 1494, 1495, 1496, 1498, 1500, 1504, 1507, 1507, 1510, 1511, 1512, 1514, 1518, 1519, 1521, 1523, 1523, 1524, 1524, 1525, 1525, 1525, 1526, 1527, 1527, 1528, 1528, 1529, 1529, 1531, 1531, 1532, 1532, 1533, 1534, 1534, 1538, 1542, 1543, 1546, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1559, 1561, 1563, 1566, 1568, 1570, 1572, 1574, 1576, 1578, 1580, 1582, 1584, 1589, 1593, 1594, 1597, 1602, 1603, 1604, 1605, 1606, 1608, 1613, 1618, 1619, 1622, 1628, 1628, 1628, 1628, 1630, 1631, 1632, 1633, 1635, 1637, 1642, 1648, 1650, 1655, 1656, 1659, 1667, 1668, 1669, 1670, 1672, 1674 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 1 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "\"end of string\"", "error", "$undefined", "\"PROJECTION\"", "\"DATUM\"", "\"SPHEROID\"", "\"PRIMEM\"", "\"UNIT\"", "\"AXIS\"", "\"PARAMETER\"", "\"GEODCRS\"", "\"LENGTHUNIT\"", "\"ANGLEUNIT\"", "\"SCALEUNIT\"", "\"TIMEUNIT\"", "\"ELLIPSOID\"", "\"CS\"", "\"ID\"", "\"PROJCRS\"", "\"BASEGEODCRS\"", "\"MERIDIAN\"", "\"BEARING\"", "\"ORDER\"", "\"ANCHOR\"", "\"ANCHOREPOCH\"", "\"CONVERSION\"", "\"METHOD\"", "\"REMARK\"", "\"GEOGCRS\"", "\"BASEGEOGCRS\"", "\"SCOPE\"", "\"AREA\"", "\"BBOX\"", "\"CITATION\"", "\"URI\"", "\"VERTCRS\"", "\"VDATUM\"", "\"GEOIDMODEL\"", "\"COMPOUNDCRS\"", "\"PARAMETERFILE\"", "\"COORDINATEOPERATION\"", "\"SOURCECRS\"", "\"TARGETCRS\"", "\"INTERPOLATIONCRS\"", "\"OPERATIONACCURACY\"", "\"CONCATENATEDOPERATION\"", "\"STEP\"", "\"BOUNDCRS\"", "\"ABRIDGEDTRANSFORMATION\"", "\"DERIVINGCONVERSION\"", "\"TDATUM\"", "\"CALENDAR\"", "\"TIMEORIGIN\"", "\"TIMECRS\"", "\"VERTICALEXTENT\"", "\"TIMEEXTENT\"", "\"USAGE\"", "\"DYNAMIC\"", "\"FRAMEEPOCH\"", "\"MODEL\"", "\"VELOCITYGRID\"", "\"ENSEMBLE\"", "\"MEMBER\"", "\"ENSEMBLEACCURACY\"", "\"DERIVEDPROJCRS\"", "\"BASEPROJCRS\"", "\"EDATUM\"", "\"ENGCRS\"", "\"PDATUM\"", "\"PARAMETRICCRS\"", "\"PARAMETRICUNIT\"", "\"BASEVERTCRS\"", "\"BASEENGCRS\"", "\"BASEPARAMCRS\"", "\"BASETIMECRS\"", "\"EPOCH\"", "\"COORDEPOCH\"", "\"COORDINATEMETADATA\"", "\"POINTMOTIONOPERATION\"", "\"VERSION\"", "\"AXISMINVALUE\"", "\"AXISMAXVALUE\"", "\"RANGEMEANING\"", "\"exact\"", "\"wraparound\"", "\"GEODETICCRS\"", "\"GEODETICDATUM\"", "\"PROJECTEDCRS\"", "\"PRIMEMERIDIAN\"", "\"GEOGRAPHICCRS\"", "\"TRF\"", "\"VERTICALCRS\"", "\"VERTICALDATUM\"", "\"VRF\"", "\"TIMEDATUM\"", "\"TEMPORALQUANTITY\"", "\"ENGINEERINGDATUM\"", "\"ENGINEERINGCRS\"", "\"PARAMETRICDATUM\"", "\"affine\"", "\"Cartesian\"", "\"cylindrical\"", "\"ellipsoidal\"", "\"linear\"", "\"parametric\"", "\"polar\"", "\"spherical\"", "\"vertical\"", "\"temporal\"", "\"temporalCount\"", "\"temporalMeasure\"", "\"ordinal\"", "\"temporalDateTime\"", "\"north\"", "\"northNorthEast\"", "\"northEast\"", "\"eastNorthEast\"", "\"east\"", "\"eastSouthEast\"", "\"southEast\"", "\"southSouthEast\"", "\"south\"", "\"southSouthWest\"", "\"southWest\"", "\"westSouthWest\"", "\"west\"", "\"westNorthWest\"", "\"northWest\"", "\"northNorthWest\"", "\"up\"", "\"down\"", "\"geocentricX\"", "\"geocentricY\"", "\"geocentricZ\"", "\"columnPositive\"", "\"columnNegative\"", "\"rowPositive\"", "\"rowNegative\"", "\"displayRight\"", "\"displayLeft\"", "\"displayUp\"", "\"displayDown\"", "\"forward\"", "\"aft\"", "\"port\"", "\"starboard\"", "\"clockwise\"", "\"counterClockwise\"", "\"towards\"", "\"awayFrom\"", "\"future\"", "\"part\"", "\"unspecified\"", "\"string\"", "\"unsigned integer\"", "'.'", "'E'", "'1'", "'2'", "'3'", "'+'", "'-'", "':'", "'T'", "'Z'", "'['", "'('", "']'", "')'", "','", "$accept", "input", "datum", "crs", "period", "number", "signed_numeric_literal_with_sign", "signed_numeric_literal", "unsigned_numeric_literal", "opt_sign", "approximate_numeric_literal", "mantissa", "exponent", "signed_integer", "exact_numeric_literal", "opt_period_unsigned_integer", "unsigned_integer", "sign", "colon", "hyphen", "datetime", "opt_24_hour_clock", "year", "month", "day", "_24_hour_clock", "opt_colon_minute_colon_second_time_zone_designator", "opt_colon_second_time_zone_designator", "time_designator", "hour", "minute", "second_time_zone_designator", "seconds_integer", "seconds_fraction", "time_zone_designator", "utc_designator", "local_time_zone_designator", "opt_colon_minute", "left_delimiter", "right_delimiter", "wkt_separator", "quoted_latin_text", "quoted_unicode_text", "opt_separator_scope_extent_identifier_remark", "no_opt_separator_scope_extent_identifier_remark", "opt_identifier_list_remark", "scope_extent_opt_identifier_list_opt_remark", "scope_extent_opt_identifier_list_remark", "usage_list_opt_identifier_list_remark", "usage", "usage_keyword", "scope", "scope_keyword", "scope_text_description", "extent", "extent_opt_identifier_list_remark", "area_description", "area_description_keyword", "area_text_description", "geographic_bounding_box", "geographic_bounding_box_keyword", "lower_left_latitude", "lower_left_longitude", "upper_right_latitude", "upper_right_longitude", "vertical_extent", "opt_separator_length_unit", "vertical_extent_keyword", "vertical_extent_minimum_height", "vertical_extent_maximum_height", "temporal_extent", "temporal_extent_keyword", "temporal_extent_start", "temporal_extent_end", "identifier", "opt_version_authority_citation_uri", "identifier_keyword", "authority_name", "authority_unique_identifier", "version", "authority_citation", "citation_keyword", "citation", "id_uri", "uri_keyword", "uri", "remark", "remark_keyword", "unit", "spatial_unit", "angle_or_length_or_parametric_or_scale_unit", "angle_or_length_or_parametric_or_scale_unit_keyword", "angle_or_length_or_scale_unit", "angle_or_length_or_scale_unit_keyword", "angle_unit", "opt_separator_identifier_list", "length_unit", "time_unit", "opt_separator_conversion_factor_identifier_list", "angle_unit_keyword", "length_unit_keyword", "time_unit_keyword", "unit_name", "conversion_factor", "coordinate_system_scope_extent_identifier_remark", "spatial_cs_scope_extent_identifier_remark", "opt_separator_spatial_axis_list_opt_separator_cs_unit_scope_extent_identifier_remark", "wkt2015temporal_cs_scope_extent_identifier_remark", "opt_separator_cs_unit_scope_extent_identifier_remark", "temporalcountmeasure_cs_scope_extent_identifier_remark", "ordinaldatetime_cs_scope_extent_identifier_remark", "opt_separator_ordinaldatetime_axis_list_scope_extent_identifier_remark", "cs_keyword", "spatial_cs_type", "temporalcountmeasure_cs_type", "ordinaldatetime_cs_type", "dimension", "spatial_axis", "temporalcountmeasure_axis", "ordinaldatetime_axis", "axis_keyword", "axis_name_abbrev", "axis_direction_opt_axis_order_spatial_unit_identifier_list", "north_south_options_spatial_unit", "clockwise_counter_clockwise_options_spatial_unit", "axis_direction_except_n_s_cw_ccw_opt_axis_spatial_unit_identifier_list", "axis_direction_except_n_s_cw_ccw_opt_axis_spatial_unit_identifier_list_options", "axis_direction_opt_axis_order_identifier_list", "north_south_options", "clockwise_counter_clockwise_options", "axis_direction_except_n_s_cw_ccw_opt_axis_identifier_list", "axis_direction_except_n_s_cw_ccw_opt_axis_identifier_list_options", "opt_separator_axis_time_unit_identifier_list", "axis_direction_except_n_s_cw_ccw_opt_axis_time_unit_identifier_list_options", "axis_direction_except_n_s_cw_ccw", "meridian", "meridian_keyword", "bearing", "bearing_keyword", "axis_order", "axis_order_keyword", "axis_range_opt_separator_identifier_list", "opt_separator_axis_range_opt_separator_identifier_list", "axis_minimum_value", "axis_minimum_value_keyword", "axis_maximum_value", "axis_maximum_value_keyword", "axis_range_meaning", "axis_range_meaning_keyword", "axis_range_meaning_value", "cs_unit", "datum_ensemble", "geodetic_datum_ensemble_without_pm", "datum_ensemble_member_list_ellipsoid_accuracy_identifier_list", "opt_separator_datum_ensemble_identifier_list", "vertical_datum_ensemble", "datum_ensemble_member_list_accuracy_identifier_list", "datum_ensemble_keyword", "datum_ensemble_name", "datum_ensemble_member", "opt_datum_ensemble_member_identifier_list", "datum_ensemble_member_keyword", "datum_ensemble_member_name", "datum_ensemble_member_identifier", "datum_ensemble_accuracy", "datum_ensemble_accuracy_keyword", "accuracy", "datum_ensemble_identifier", "dynamic_crs", "dynamic_crs_keyword", "frame_reference_epoch", "frame_reference_epoch_keyword", "reference_epoch", "opt_separator_deformation_model_id", "deformation_model_id", "opt_separator_identifier", "deformation_model_id_keyword", "deformation_model_name", "geodetic_crs", "geographic_crs", "static_geodetic_crs", "dynamic_geodetic_crs", "static_geographic_crs", "dynamic_geographic_crs", "opt_prime_meridian_coordinate_system_scope_extent_identifier_remark", "crs_name", "geodetic_crs_keyword", "geographic_crs_keyword", "geodetic_reference_frame_or_geodetic_datum_ensemble_without_pm", "ellipsoid", "opt_separator_length_unit_identifier_list", "ellipsoid_keyword", "ellipsoid_name", "semi_major_axis", "inverse_flattening", "prime_meridian", "prime_meridian_keyword", "prime_meridian_name", "irm_longitude_opt_separator_identifier_list", "geodetic_reference_frame_with_opt_pm", "geodetic_reference_frame_without_pm", "geodetic_reference_frame_keyword", "datum_name", "opt_separator_datum_anchor_anchor_epoch_identifier_list", "datum_anchor", "datum_anchor_keyword", "datum_anchor_description", "datum_anchor_epoch", "datum_anchor_epoch_keyword", "anchor_epoch", "projected_crs", "projected_crs_keyword", "base_geodetic_crs", "base_static_geodetic_crs", "opt_separator_pm_ellipsoidal_cs_unit_opt_separator_identifier_list", "base_dynamic_geodetic_crs", "base_static_geographic_crs", "base_dynamic_geographic_crs", "base_geodetic_crs_keyword", "base_geographic_crs_keyword", "base_crs_name", "ellipsoidal_cs_unit", "map_projection", "opt_separator_parameter_list_identifier_list", "map_projection_keyword", "map_projection_name", "map_projection_method", "map_projection_method_keyword", "map_projection_method_name", "map_projection_parameter", "opt_separator_param_unit_identifier_list", "parameter_keyword", "parameter_name", "parameter_value", "map_projection_parameter_unit", "vertical_crs", "static_vertical_crs", "dynamic_vertical_crs", "vertical_reference_frame_or_vertical_datum_ensemble", "vertical_cs_opt_geoid_model_id_scope_extent_identifier_remark", "opt_separator_cs_unit_opt_geoid_model_id_scope_extent_identifier_remark", "opt_geoid_model_id_list_opt_separator_scope_extent_identifier_remark", "geoid_model_id", "geoid_model_keyword", "geoid_model_name", "vertical_crs_keyword", "vertical_reference_frame", "vertical_reference_frame_keyword", "engineering_crs", "engineering_crs_keyword", "engineering_datum", "engineering_datum_keyword", "opt_separator_datum_anchor_identifier_list", "parametric_crs", "parametric_crs_keyword", "parametric_datum", "parametric_datum_keyword", "temporal_crs", "temporal_crs_keyword", "temporal_datum", "opt_separator_temporal_datum_end", "temporal_datum_keyword", "temporal_origin", "temporal_origin_keyword", "temporal_origin_description", "calendar", "calendar_keyword", "calendar_identifier", "deriving_conversion", "opt_separator_parameter_or_parameter_file_identifier_list", "deriving_conversion_keyword", "deriving_conversion_name", "operation_method", "operation_method_keyword", "operation_method_name", "operation_parameter", "opt_separator_parameter_unit_identifier_list", "parameter_unit", "length_or_angle_or_scale_or_time_or_parametric_unit", "length_or_angle_or_scale_or_time_or_parametric_unit_keyword", "operation_parameter_file", "parameter_file_keyword", "parameter_file_name", "derived_geodetic_crs", "derived_geographic_crs", "derived_static_geod_crs", "base_static_geod_crs_or_base_static_geog_crs", "derived_dynamic_geod_crs", "base_dynamic_geod_crs_or_base_dynamic_geog_crs", "derived_static_geog_crs", "derived_dynamic_geog_crs", "base_static_geod_crs", "opt_separator_pm_opt_separator_identifier_list", "base_dynamic_geod_crs", "base_static_geog_crs", "base_dynamic_geog_crs", "derived_projected_crs", "derived_projected_crs_keyword", "derived_crs_name", "base_projected_crs", "base_projected_crs_keyword", "base_geodetic_geographic_crs", "derived_vertical_crs", "base_vertical_crs", "base_static_vertical_crs", "base_dynamic_vertical_crs", "base_vertical_crs_keyword", "derived_engineering_crs", "base_engineering_crs", "base_engineering_crs_keyword", "derived_parametric_crs", "base_parametric_crs", "base_parametric_crs_keyword", "derived_temporal_crs", "base_temporal_crs", "base_temporal_crs_keyword", "compound_crs", "single_crs", "single_crs_or_bound_crs", "opt_wkt_separator_single_crs_list_opt_separator_scope_extent_identifier_remark", "compound_crs_keyword", "compound_crs_name", "metadata_coordinate_epoch", "coordinate_epoch_keyword", "coordinate_epoch", "coordinate_metadata", "coordinate_metadata_crs", "coordinate_metadata_keyword", "static_crs_coordinate_metadata", "dynamic_crs_coordinate_metadata", "coordinate_operation", "coordinate_operation_next", "coordinate_operation_end", "opt_parameter_or_parameter_file_list_opt_interpolation_crs_opt_operation_accuracy_opt_separator_scope_extent_identifier_remark", "operation_keyword", "operation_name", "operation_version", "operation_version_keyword", "operation_version_text", "source_crs", "source_crs_keyword", "target_crs", "target_crs_keyword", "interpolation_crs", "interpolation_crs_keyword", "operation_accuracy", "operation_accuracy_keyword", "point_motion_operation", "point_motion_operation_next", "point_motion_operation_end", "opt_parameter_or_parameter_file_list_opt_operation_accuracy_opt_separator_scope_extent_identifier_remark", "point_motion_keyword", "concatenated_operation", "concatenated_operation_next", "concatenated_operation_end", "step", "opt_concatenated_operation_end", "concatenated_operation_keyword", "step_keyword", "bound_crs", "bound_crs_keyword", "abridged_coordinate_transformation", "abridged_coordinate_transformation_next", "abridged_coordinate_transformation_end", "opt_end_abridged_coordinate_transformation", "abridged_transformation_keyword", "abridged_transformation_parameter", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_int16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 46, 69, 49, 50, 51, 43, 45, 58, 84, 90, 91, 40, 93, 41, 44 }; # endif #define YYPACT_NINF (-1255) #define yypact_value_is_default(Yyn) \ ((Yyn) == YYPACT_NINF) #define YYTABLE_NINF (-673) #define yytable_value_is_error(Yyn) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 2583, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, 139, -1255, -1255, -1255, 315, -1255, -1255, -1255, 315, -1255, -1255, -1255, -1255, -1255, -1255, 315, 315, -1255, 315, -1255, -59, 315, -1255, 315, -1255, 315, -1255, -1255, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, -1255, -1255, -1255, -1255, -1255, -1255, 315, -1255, -1255, -1255, -1255, -1255, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, 315, -1255, -1255, -1255, 6, 6, 6, 6, 6, -1255, 86, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 994, 6, 6, 6, 184, -1255, -1255, -59, -1255, -59, -1255, -59, -59, -1255, -59, -1255, -1255, -1255, 315, -1255, -59, -59, -1255, -59, -59, -59, -59, -59, -59, -59, -59, -59, -1255, -59, -1255, -59, -1255, -1255, -1255, -1255, 17, -1255, -1255, -1255, -1255, -1255, 116, 132, 215, -1255, -1255, -1255, -1255, 403, -1255, -59, -1255, -59, -59, -59, -1255, -59, 315, 1465, 180, 87, 87, 624, 6, 195, 362, 110, 317, 461, 403, 37, 280, 403, 322, 403, 64, 165, 403, 294, 1211, -1255, -1255, -1255, 477, 190, -1255, -1255, 190, -1255, -1255, 190, -1255, -1255, 365, 994, -1255, -1255, -1255, -1255, -1255, -1255, -1255, 454, -1255, -1255, -1255, -1255, 269, 278, 290, 624, -1255, -59, -1255, -59, 315, -1255, -1255, -1255, -1255, 315, -59, 315, -59, -1255, 315, 315, -59, -59, -1255, -1255, -1255, -1255, -59, -59, -59, -59, -1255, -59, -1255, -59, -59, -59, -1255, -1255, -1255, -1255, 315, 315, -1255, -1255, -59, 315, -1255, -1255, 315, -59, -59, -1255, -59, -1255, -1255, 315, -1255, -1255, -59, -59, 315, -59, 315, -1255, -1255, -59, -59, 315, -59, -59, -1255, -1255, -59, -59, 315, -1255, -1255, -59, -59, 315, -1255, -1255, -59, -59, 315, -59, 315, -1255, -1255, -59, 315, -1255, -59, -1255, -1255, -1255, -1255, 315, -1255, -59, 315, -59, -59, -59, -59, -59, -1255, -59, 315, 403, -1255, 455, 454, -1255, -1255, 338, 403, 145, 403, 403, 6, 6, 71, 399, 79, 6, 6, 413, 413, 71, 79, 413, 413, 624, 455, 403, 440, 6, 6, 248, 403, 6, 6, 96, 473, 413, 6, 453, -1255, 175, 6, 453, 454, 473, 413, 6, -1255, 453, 473, 413, 6, 473, 413, 6, -1255, -1255, 700, 100, -1255, 6, 413, 6, 1211, 454, 184, -1255, 6, 365, 184, -1255, 451, 184, -1255, 365, 452, 994, -1255, 454, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -59, -59, 315, -1255, 315, -1255, -1255, -59, -59, 315, -59, -1255, -1255, -1255, -59, -59, -59, -1255, -59, 315, -1255, -1255, -1255, -1255, -1255, -1255, 315, 403, -59, -1255, -59, -59, -1255, -59, 315, -59, -59, 403, -59, -59, -1255, -59, -59, 624, 403, -1255, -59, -59, -59, -1255, -59, -59, 315, -1255, -1255, -59, -59, -59, 315, 403, -59, -59, -59, -59, -59, -1255, 403, -59, 290, 403, 403, -59, -59, -59, 403, -59, -59, 403, -59, -59, -1255, -1255, 131, -1255, 403, -59, -1255, 403, -59, -59, -59, 290, 403, -1255, 403, -59, -1255, -59, 315, -59, -1255, -59, 315, 403, -1255, 472, 475, 6, 6, -1255, -1255, 453, -1255, 1303, 450, 453, 403, 180, 79, 622, 403, 454, 1308, -1255, 473, 80, 80, 473, 6, 473, 79, -1255, 473, 473, 431, 403, 504, -1255, -1255, -1255, 473, 80, 80, -1255, -1255, 6, 403, 180, 473, 1228, -1255, 473, 196, -1255, -1255, 453, -1255, -1255, 454, -1255, -1255, 473, 289, -1255, -1255, 473, 288, -1255, 473, 135, -1255, -1255, 454, -1255, -1255, 454, -1255, -1255, -1255, 473, 362, 1459, 403, 454, -1255, -1255, 451, 1561, 403, 6, 474, 1309, 403, 6, -1255, -59, -1255, -1255, 403, -1255, 403, -1255, -59, -1255, 403, -59, -1255, -59, -1255, -59, 403, -1255, -1255, -1255, 315, -1255, 290, 403, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -59, -1255, -1255, -1255, -1255, -59, -59, -59, -1255, -59, -59, -59, -59, 403, -1255, -59, 403, 403, 403, 403, -1255, -1255, -59, -59, 315, -1255, -1255, -1255, -59, 315, 403, -59, -59, -59, -59, -1255, -59, -1255, -59, 403, -59, 403, -59, -59, -59, -1255, 403, -59, 403, -59, 403, -59, 274, 379, -1255, 908, 403, -1255, -1255, -1255, -1255, -59, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -59, 315, -59, 315, -1255, -59, 315, -59, 315, -59, 315, -59, 315, -59, -1255, 315, -59, -1255, -1255, -59, -1255, -1255, -1255, 315, -59, -59, 315, -59, 315, -1255, -1255, -59, -1255, 315, -1255, -1255, -59, 475, -1255, -1255, -1255, -1255, -1255, -1255, 157, -1255, 6, 454, -1255, 488, 488, 488, 488, 71, 83, 403, 71, 403, -1255, 451, -1255, -1255, -1255, -1255, -1255, -1255, 6, -1255, 6, -1255, 71, 299, 403, 71, 403, 455, 634, -1255, 488, -1255, 96, 403, -1255, -1255, 403, -1255, 403, -1255, 403, -1255, 454, -1255, -1255, 454, 454, -1255, 395, -1255, -1255, -1255, -1255, 440, 107, 532, 283, -1255, 6, 385, -1255, 6, 487, -1255, 1303, 113, -1255, 1303, 381, -1255, 700, -1255, 432, -1255, 1328, 403, 6, -1255, -1255, 6, -1255, 1303, 453, 403, 321, 101, -1255, -1255, -1255, -59, -1255, -59, -1255, -1255, -1255, -1255, -59, -59, -59, -59, -59, -59, -59, -1255, -59, -1255, -59, -1255, -59, -59, -59, -59, -1255, -59, -59, -1255, -59, -1255, -1255, -59, -59, -59, -59, -1255, -1255, -1255, -1255, -1255, 418, 395, -1255, 908, 454, -1255, -59, -1255, -59, -1255, -59, -1255, -59, -1255, -1255, 403, -59, -59, -59, -1255, 403, -59, -59, -1255, -59, -59, -1255, -59, -1255, -1255, -59, -1255, 403, -1255, -1255, -59, -59, -59, 315, -59, -1255, -59, -59, 403, -1255, -1255, -1255, -1255, -1255, -1255, 403, -59, -59, 403, 403, 403, 403, 403, 403, -1255, -1255, 403, 189, 403, 624, 624, 403, -1255, 504, -1255, -1255, 403, 733, 403, 403, 403, -1255, -1255, 454, -1255, -1255, -1255, 403, -1255, 397, -1255, -1255, 487, -1255, 113, -1255, -1255, -1255, 113, -1255, -1255, 1303, -1255, 1303, 700, -1255, -1255, -1255, 1259, -1255, 994, -1255, 455, 6, -1255, -59, 1129, 403, 451, -1255, -1255, -59, -59, -59, -59, -1255, -1255, -59, -59, -59, -1255, -1255, -59, -59, -1255, -59, -1255, -1255, -1255, -1255, -1255, -59, -1255, 315, -59, -1255, -59, -1255, -1255, -1255, 944, -1255, 403, -59, -59, -59, -1255, -59, -59, -59, -59, -1255, -59, -1255, -59, -1255, -1255, 403, -59, 403, -59, -1255, -59, 474, -1255, 315, -59, -59, -1255, 587, 587, 587, 587, -1255, -1255, -1255, 403, 403, -1255, -1255, 6, -1255, 587, 959, -1255, -1255, 428, 687, 555, 113, -1255, -1255, -1255, -1255, 1303, 366, 403, -1255, -1255, -1255, 351, 403, 403, 315, 6, -1255, -1255, -1255, -59, 315, -59, 315, -59, -59, 315, -1255, -1255, -59, -59, 435, 959, -1255, -59, -59, -1255, -59, -1255, -1255, -59, -1255, -59, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -59, -59, -1255, 315, -1255, -1255, 321, -59, 860, -1255, 6, 537, -1255, 6, -1255, 1080, -1255, 6, 624, 849, -1255, -1255, 687, 555, 555, -1255, 1303, -1255, -1255, 6, 403, 455, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, 315, -1255, 315, -59, -1255, -59, -1255, -59, -59, -59, -1255, -59, -59, -59, -1255, -1255, -59, -59, 315, -59, -1255, -1255, -1255, -1255, 403, -59, -59, -59, 6, 6, 1309, 1778, -1255, -1255, 2693, -1255, 2922, 403, 904, -1255, 904, -1255, 6, 555, -1255, 624, 403, 1162, 403, 403, -59, -59, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -59, -59, -59, -59, -59, 403, -1255, -59, -59, -59, -59, -59, 403, -1255, -59, -1255, -59, -1255, -59, -1255, -59, -1255, -59, -1255, -1255, -59, 315, -1255, -1255, 624, 403, 98, 403, 566, 566, 717, 717, -1255, 495, 650, 566, 710, 710, -1255, 262, -1255, -1255, 403, -1255, -1255, 321, -59, -1255, -1255, -1255, -1255, -59, -59, -1255, -59, 315, -1255, -59, 315, -59, 315, -1255, -1255, -59, -59, -1255, -59, 315, -59, -1255, -1255, -59, -59, -1255, -59, 315, -59, -1255, -59, -59, -1255, -59, -1255, -59, -1255, -59, -59, -1255, -59, -1255, -59, -59, -1255, -59, -1255, -59, -1255, -1255, 403, 403, -1255, 671, -1255, 74, -1255, 454, 84, -1255, 1303, -1255, 1303, -1255, -1255, 900, -1255, 1303, 526, -1255, -1255, -1255, 900, -1255, 1303, 526, -1255, -1255, -1255, 393, -1255, -1255, 201, -1255, -1255, -1255, 201, -1255, -1255, -1255, -1255, -59, -1255, -59, -59, -59, 403, -59, 403, 403, -59, -59, -59, -59, -59, -59, 403, -59, -59, -59, -59, -1255, 84, -1255, -1255, -1255, -1255, 94, -1255, -1255, -1255, -1255, 526, -1255, 442, -1255, -1255, 526, -1255, -1255, -1255, -1255, -1255, -1255, -59, -1255, -59, 315, -59, 403, -59, 94, -1255, -1255, 670, -1255, -1255, -1255, -59, -1255, -1255, 403, -1255, -1255 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_int16 yydefact[] = { 0, 439, 426, 415, 425, 161, 460, 483, 417, 515, 518, 640, 684, 719, 722, 544, 537, 376, 599, 525, 522, 534, 532, 651, 706, 416, 441, 461, 418, 440, 516, 520, 519, 545, 526, 523, 535, 0, 4, 5, 2, 0, 13, 366, 367, 0, 623, 405, 403, 404, 406, 407, 0, 0, 3, 0, 12, 436, 0, 625, 0, 11, 0, 627, 497, 498, 0, 14, 0, 629, 0, 15, 0, 631, 0, 16, 0, 633, 0, 17, 0, 624, 580, 578, 579, 581, 582, 626, 0, 628, 630, 632, 634, 19, 18, 0, 7, 0, 8, 0, 9, 0, 10, 0, 6, 0, 1, 73, 74, 0, 0, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 78, 162, 0, 377, 0, 414, 0, 0, 427, 0, 431, 432, 437, 0, 442, 0, 0, 484, 0, 0, 443, 0, 527, 0, 527, 0, 539, 600, 0, 641, 0, 652, 666, 653, 667, 654, 655, 669, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 0, 649, 0, 685, 0, 0, 0, 690, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 75, 76, 648, 0, 0, 673, 675, 0, 697, 699, 0, 707, 709, 0, 0, 40, 20, 37, 38, 39, 41, 42, 0, 163, 21, 22, 26, 0, 25, 35, 0, 164, 154, 381, 0, 0, 475, 476, 389, 420, 0, 0, 0, 0, 419, 0, 0, 0, 0, 584, 587, 585, 588, 0, 0, 0, 0, 428, 0, 433, 0, 443, 0, 462, 463, 464, 465, 0, 0, 487, 486, 480, 0, 612, 502, 0, 0, 0, 501, 0, 608, 609, 0, 452, 455, 190, 444, 0, 445, 0, 517, 615, 0, 0, 0, 190, 528, 524, 618, 0, 0, 0, 533, 621, 0, 0, 0, 551, 547, 190, 190, 0, 190, 0, 538, 602, 0, 0, 635, 0, 636, 643, 644, 650, 0, 687, 0, 0, 0, 0, 0, 0, 0, 692, 0, 0, 0, 34, 27, 0, 33, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 447, 0, 0, 0, 0, 0, 0, 0, 529, 0, 0, 0, 0, 0, 0, 0, 543, 542, 0, 0, 540, 0, 0, 0, 0, 0, 0, 674, 0, 0, 0, 698, 0, 0, 708, 0, 0, 0, 689, 0, 29, 31, 28, 36, 168, 171, 165, 166, 155, 158, 0, 160, 0, 153, 385, 0, 371, 0, 0, 368, 373, 382, 379, 0, 0, 391, 395, 0, 223, 413, 204, 205, 206, 207, 0, 0, 0, 477, 0, 0, 558, 0, 0, 0, 0, 0, 0, 0, 429, 422, 190, 0, 0, 438, 0, 0, 0, 493, 190, 480, 0, 479, 488, 190, 0, 0, 0, 0, 0, 0, 190, 190, 446, 453, 0, 190, 456, 0, 0, 0, 0, 190, 0, 0, 0, 0, 0, 0, 50, 548, 48, 549, 0, 190, 552, 0, 0, 0, 637, 645, 0, 688, 0, 0, 561, 701, 0, 0, 731, 80, 0, 0, 32, 0, 0, 0, 0, 370, 375, 0, 374, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 408, 0, 0, 0, 0, 0, 0, 0, 410, 0, 0, 0, 0, 0, 435, 24, 430, 0, 0, 0, 481, 482, 0, 0, 0, 0, 0, 499, 0, 0, 191, 449, 0, 451, 448, 457, 454, 521, 0, 0, 530, 531, 0, 0, 536, 0, 0, 44, 58, 0, 45, 49, 0, 546, 541, 550, 0, 0, 0, 0, 646, 642, 686, 0, 0, 0, 0, 0, 0, 0, 0, 691, 156, 159, 169, 0, 172, 0, 387, 371, 386, 0, 371, 383, 379, 378, 0, 0, 400, 401, 396, 0, 388, 392, 0, 224, 225, 226, 227, 228, 229, 230, 231, 232, 0, 233, 234, 235, 236, 0, 0, 0, 412, 0, 592, 0, 592, 0, 559, 0, 0, 0, 0, 0, 199, 198, 190, 190, 0, 421, 197, 196, 190, 0, 0, 0, 467, 0, 467, 494, 0, 485, 0, 0, 0, 0, 0, 190, 190, 458, 0, 190, 0, 190, 0, 190, 48, 0, 59, 0, 0, 603, 604, 605, 606, 0, 174, 100, 133, 136, 144, 148, 98, 639, 82, 88, 89, 93, 0, 85, 0, 92, 85, 0, 85, 0, 85, 0, 85, 0, 85, 84, 0, 637, 622, 647, 677, 576, 696, 705, 0, 701, 701, 0, 80, 0, 700, 562, 398, 720, 0, 81, 721, 0, 0, 167, 170, 372, 384, 369, 380, 0, 409, 0, 393, 390, 0, 0, 0, 0, 0, 0, 0, 0, 0, 583, 0, 586, 411, 589, 590, 424, 423, 0, 434, 0, 459, 0, 0, 0, 0, 0, 27, 0, 500, 0, 607, 0, 0, 450, 613, 0, 616, 0, 619, 0, 46, 0, 43, 68, 0, 0, 53, 71, 55, 66, 67, 598, 0, 0, 0, 0, 91, 0, 0, 117, 0, 0, 118, 0, 0, 119, 0, 0, 120, 0, 83, 0, 638, 0, 0, 0, 702, 703, 0, 704, 0, 0, 0, 0, 0, 723, 725, 157, 0, 402, 398, 394, 237, 238, 239, 190, 190, 190, 190, 592, 190, 190, 591, 592, 596, 554, 202, 0, 0, 467, 190, 478, 190, 190, 466, 467, 473, 495, 490, 0, 190, 190, 610, 614, 617, 620, 52, 48, 71, 60, 0, 0, 70, 190, 96, 85, 94, 0, 90, 85, 87, 101, 0, 85, 85, 85, 134, 0, 85, 85, 137, 0, 85, 145, 0, 149, 150, 0, 79, 0, 694, 683, 677, 677, 80, 0, 80, 676, 0, 0, 0, 399, 560, 713, 714, 711, 712, 0, 727, 0, 0, 0, 0, 0, 0, 0, 594, 593, 0, 0, 0, 0, 0, 0, 471, 0, 468, 470, 0, 0, 0, 0, 0, 47, 69, 0, 54, 57, 72, 0, 95, 0, 86, 99, 0, 121, 0, 122, 123, 132, 0, 124, 125, 0, 126, 0, 0, 173, 678, 679, 0, 680, 0, 682, 27, 0, 695, 0, 0, 0, 0, 724, 397, 0, 0, 0, 0, 595, 597, 190, 554, 554, 553, 203, 190, 190, 472, 190, 474, 188, 186, 185, 187, 190, 496, 0, 190, 489, 0, 611, 64, 56, 0, 601, 0, 102, 103, 104, 105, 85, 85, 85, 85, 138, 0, 146, 142, 151, 152, 0, 80, 0, 564, 577, 398, 0, 730, 0, 727, 727, 726, 0, 0, 0, 0, 557, 555, 556, 0, 0, 469, 491, 0, 492, 0, 0, 63, 97, 0, 0, 0, 0, 127, 128, 129, 130, 0, 0, 0, 147, 681, 693, 0, 0, 0, 0, 0, 729, 728, 243, 214, 0, 209, 0, 80, 220, 0, 192, 189, 0, 504, 65, 0, 61, 106, 107, 108, 109, 110, 111, 85, 139, 0, 143, 141, 574, 569, 570, 571, 572, 573, 190, 190, 567, 0, 563, 575, 0, 0, 0, 213, 0, 0, 208, 0, 218, 0, 219, 0, 0, 0, 503, 62, 0, 0, 0, 131, 0, 566, 565, 0, 0, 27, 183, 180, 179, 182, 200, 181, 201, 217, 365, 175, 177, 0, 176, 0, 215, 244, 0, 212, 209, 80, 0, 222, 220, 0, 190, 513, 508, 80, 509, 0, 112, 113, 114, 115, 140, 0, 194, 715, 190, 0, 0, 0, 0, 211, 210, 0, 221, 0, 0, 0, 505, 0, 507, 0, 0, 135, 0, 0, 0, 0, 0, 0, 194, 216, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 299, 246, 248, 250, 252, 0, 245, 270, 278, 280, 282, 284, 0, 277, 294, 184, 509, 511, 509, 514, 398, 116, 190, 568, 718, 80, 0, 710, 732, 0, 0, 0, 0, 0, 0, 0, 0, 240, 0, 0, 0, 0, 0, 242, 0, 506, 510, 0, 195, 717, 0, 190, 193, 347, 358, 360, 190, 352, 300, 352, 0, 302, 190, 0, 190, 0, 241, 343, 190, 190, 247, 190, 0, 190, 249, 345, 190, 190, 251, 190, 0, 190, 253, 190, 352, 271, 352, 273, 190, 279, 190, 190, 281, 190, 283, 190, 190, 285, 190, 295, 352, 298, 512, 0, 0, 301, 0, 305, 0, 303, 0, 0, 348, 0, 349, 0, 254, 261, 0, 258, 0, 0, 260, 262, 269, 0, 266, 0, 0, 268, 272, 276, 0, 274, 286, 0, 288, 289, 290, 0, 292, 293, 296, 297, 715, 178, 190, 190, 352, 0, 190, 0, 0, 190, 190, 0, 190, 190, 190, 0, 190, 352, 190, 190, 716, 0, 353, 354, 304, 346, 0, 350, 357, 359, 257, 0, 255, 0, 259, 265, 0, 263, 344, 267, 275, 287, 291, 190, 362, 190, 0, 190, 0, 190, 0, 355, 351, 0, 256, 342, 264, 190, 363, 364, 0, 356, 361 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -1255, -1255, -1255, -223, -237, -172, -1255, 244, -193, 297, -1255, -1255, -1255, -1255, -1255, -1255, -94, -336, -652, -87, -785, -635, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -553, -253, -1255, -1255, -1255, -867, -1255, -1255, -246, -45, 1461, 501, 2101, -1255, -755, -578, -599, -1255, -1255, -166, -1255, -1255, -154, -1255, -1255, -1255, -142, -294, -1255, -1255, -796, -1255, -1255, -1255, -1255, -1255, -776, -1255, -1255, -1255, -1255, -757, -1255, -1255, -1255, 503, -1255, -1255, -1255, -1255, -1255, 177, -1255, -1255, -501, -1255, -1255, -767, -1255, -1255, -793, -1255, -1255, -1255, -1255, -572, 1647, -392, -1222, -528, -1255, -1255, -1255, -773, -921, -42, -1255, -481, -1255, -1255, -1255, -1255, -476, -330, 162, -1255, -1255, -470, -1004, -346, -417, -982, -794, -1255, -768, -568, -1255, -1255, -1255, -1255, -567, -1255, -1255, -1255, -1255, -711, -556, -1255, -571, -1255, -1202, -1255, -761, -1254, -1028, -1255, -1088, -1255, -709, -1255, -1255, -878, -1255, 780, -416, -298, 589, -430, 73, -60, -334, 149, -1255, -1255, -1255, 249, -1255, -62, -1255, -148, -1255, -1255, -1255, -1255, -1255, -1255, -850, -1255, -1255, -1255, -1255, 676, 677, 681, 684, -272, 510, -1255, -1255, -91, 62, -1255, -1255, -1255, -1255, -1255, -97, -1255, -1255, -1255, -1255, 19, -1255, 590, 541, 612, -1255, -1255, 434, -1255, -1255, 689, -1255, -1255, -1255, -634, -1255, -1255, -1255, 626, 629, 222, -151, 2, 344, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -358, -795, -941, -1255, -1255, 704, 706, -1255, 251, -1255, -723, -600, -1255, -1255, -1255, -197, -1255, 709, -1255, -163, -1255, 690, 713, -1255, -171, -1255, 721, -1255, -179, -1255, -1255, 443, -1255, -1255, -1255, -1255, -1255, 306, -270, -1255, -1255, -377, -1255, -1255, -781, -1255, -1255, -1255, -1255, -762, -1255, -1255, 726, -1255, -1255, 669, -1255, 673, -1255, -1255, 252, -613, 253, 258, 261, 736, -1255, -1255, -1255, -1255, -1255, 753, -1255, -1255, -1255, -1255, 755, -1255, -1255, 756, -1255, -1255, 759, -1255, -1255, 760, -175, -352, 143, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, -1255, 898, -1255, 559, -160, -1255, -120, -187, -1255, -1255, -68, -1255, 181, -1255, -1255, -1255, -814, -1255, -1255, -1255, 557, 35, 902, -1255, -1255, 563, -1087, -524, -1255, -999, 910, -1255, -1255, -1255, -41, -286, -1255, -1255 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 37, 38, 39, 236, 640, 238, 903, 239, 480, 240, 241, 429, 430, 242, 354, 243, 244, 917, 609, 518, 610, 519, 717, 913, 611, 832, 992, 612, 833, 916, 1057, 1058, 1138, 834, 835, 836, 918, 109, 216, 388, 466, 945, 629, 771, 842, 734, 735, 736, 737, 738, 739, 740, 928, 1060, 741, 742, 743, 933, 744, 745, 937, 1070, 1148, 1224, 746, 1114, 747, 940, 1072, 748, 749, 943, 1075, 499, 357, 41, 136, 246, 437, 438, 439, 635, 440, 441, 637, 751, 752, 1197, 1198, 1199, 1200, 1050, 1051, 897, 389, 687, 1201, 1246, 693, 688, 1202, 893, 1040, 458, 459, 1169, 460, 1166, 461, 462, 1173, 463, 669, 670, 671, 881, 1128, 1126, 1131, 1129, 1205, 1294, 1359, 1367, 1295, 1374, 1301, 1378, 1383, 1302, 1388, 1321, 1347, 1289, 1360, 1361, 1368, 1369, 1362, 1349, 1350, 1396, 1351, 1352, 1353, 1354, 1478, 1479, 1493, 1203, 42, 253, 359, 549, 44, 360, 254, 138, 248, 553, 249, 451, 644, 445, 446, 641, 639, 255, 256, 455, 456, 654, 557, 650, 868, 651, 876, 46, 47, 48, 49, 50, 51, 464, 140, 52, 53, 257, 447, 572, 55, 143, 272, 478, 465, 147, 274, 481, 56, 258, 58, 149, 203, 300, 301, 503, 302, 303, 506, 59, 60, 276, 277, 809, 278, 279, 280, 259, 260, 467, 899, 959, 381, 62, 152, 285, 286, 492, 488, 986, 760, 700, 904, 1052, 63, 64, 65, 291, 496, 1177, 1241, 1217, 1218, 1309, 66, 67, 68, 69, 70, 71, 72, 206, 73, 74, 75, 76, 77, 78, 79, 211, 80, 324, 325, 521, 326, 327, 524, 960, 976, 471, 679, 964, 535, 768, 761, 1119, 1158, 1159, 1160, 762, 763, 1080, 81, 82, 83, 261, 84, 262, 85, 86, 263, 792, 264, 265, 266, 87, 88, 162, 330, 331, 725, 89, 293, 294, 295, 296, 90, 307, 308, 91, 314, 315, 92, 319, 320, 93, 94, 333, 619, 95, 164, 337, 338, 529, 96, 182, 97, 183, 184, 961, 219, 220, 860, 99, 186, 340, 341, 531, 342, 191, 348, 349, 950, 951, 764, 765, 100, 222, 223, 625, 962, 102, 225, 226, 963, 1248, 103, 770, 334, 105, 538, 871, 872, 1025, 539, 1085 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 110, 692, 61, 271, 292, 350, 353, 111, 112, 865, 113, 187, 188, 116, 547, 117, 431, 118, 146, 57, 237, 119, 489, 120, 444, 121, 966, 122, 546, 123, 318, 124, 894, 125, 343, 126, 313, 345, 332, 431, 733, 306, 633, 127, 534, 952, 759, 267, 929, 993, 128, 355, 129, 290, 130, 495, 131, 1041, 132, 719, 133, 527, 54, 794, 811, 190, 954, 831, 930, 955, 941, 934, 922, 45, 926, 1, 1187, 926, 948, 1078, 926, 826, 1121, 926, 1, 144, 926, 931, 1193, 144, 935, 1, 144, 938, 1398, 457, 1136, 949, 1346, 474, 5, 5, 197, 19, 268, 1127, 250, 1127, 1132, 305, 114, 5, 1193, 283, 15, 5, 251, 5, 1348, 1420, 1342, 1422, 1370, 1370, 5, 1375, 1380, 533, 1385, 1385, 5, 1389, 10, 34, 726, 1432, 284, 252, 317, 106, 726, 17, 351, 845, 252, 848, 228, 851, 17, 854, 2, 856, 322, 344, 1343, 1344, 346, 26, 33, 134, 4, 29, 2, 732, 1207, 1344, 26, 145, 731, 1195, 29, 145, 4, 26, 145, 1437, 1477, 29, 1343, 1344, 339, 477, 5, 1457, 435, 15, -668, 494, 31, 32, 1132, 1102, 5, 1195, 1036, 1017, 1473, 1019, 486, 298, 2, 1062, 1076, 540, 361, 1443, 5, 247, 443, 362, 4, 364, 1447, 1037, 366, 367, 321, 322, 5, 247, 646, 1063, 1451, 1342, 1065, 189, 1452, 1073, 757, 33, 1120, 189, 10, 926, 1139, 926, 378, 379, 332, 926, 1064, 382, 247, 1066, 383, 1067, 756, 1227, 1315, 1068, 702, 387, 1392, 252, 1213, 495, 391, 486, 393, 432, 275, 979, 1084, 396, 991, 5, 753, 984, 595, 339, 401, 1178, 971, 873, 289, 404, 974, 914, 989, 5, 407, 947, 410, 647, 1342, -670, 412, 575, 31, 32, 1208, 620, 607, 414, 608, 681, 417, 5, 1216, 505, 5, -671, 452, 297, 426, 144, 690, 1436, 1140, 1436, 726, 691, 1439, 517, 728, 729, 5, 882, 883, 884, 528, 1116, 996, 493, 1311, 1135, 998, 1164, 1141, 1143, 1001, 1003, 1004, 1436, 541, 1007, 1008, 730, 731, 1010, 926, 777, 1343, 1344, 779, 906, 7, 1142, 1144, 1145, 1146, 344, 507, 10, 346, 19, 21, 511, 1151, 329, 514, 12, 1152, 1153, 1154, 1155, 1476, 1435, 5, 1435, 469, 433, 434, 684, 252, 1171, 1209, 685, 17, 483, 1212, 250, 453, 830, -672, 34, 36, 145, 287, 473, 21, 251, 707, 1435, 544, 312, 545, 1340, 5, 24, 1189, 550, 5, 1219, 1190, 1191, 1192, 347, 726, 31, 32, 558, 726, 1225, 673, 675, 784, 729, 559, 891, 36, 1156, 1220, 1221, 1222, 352, 565, 715, 728, 729, 695, 697, 713, 1314, -30, -51, 711, 608, 684, 730, 731, 706, 685, 332, 582, 230, 1082, 874, 5, 690, 586, 730, 731, 1233, 691, 1250, 1251, 454, 546, 1336, 729, 1239, 469, 1194, 653, 7, 1108, 1109, 1110, 1111, 5, 674, 676, 1343, 1344, 547, 431, 533, 5, 905, 107, 108, 730, 731, 297, 298, 1310, 696, 698, 457, 626, 134, 229, 230, 630, 231, 232, 233, 234, 235, 537, 709, 1189, 40, 5, 433, 1190, 1191, 1192, 434, 773, 690, 5, 443, 726, 716, 691, 1342, 718, 672, 769, 5, 677, 1296, 680, 1303, 755, 682, 683, 1358, 1358, 1366, 1366, 1189, 1373, 694, 1358, 1190, 1191, 1192, 607, 730, 731, 5, 1189, 1125, 705, 1182, 1190, 1191, 1192, 1193, 335, 336, 5, 1363, 710, 828, 115, 1338, 712, 1381, 727, 714, 726, 1194, 1376, 727, 728, 729, 214, 215, 1390, 1189, 720, 1343, 1344, 1190, 1191, 1192, 830, 608, 1334, 5, 1335, 944, 1356, 1196, 1342, 468, 1206, 730, 731, 732, 1210, 1125, 1194, -59, 1215, 532, 484, 485, -59, -59, -59, 536, 783, 1194, 229, 498, 731, 231, 232, 233, 1442, 234, 235, 1445, 509, 479, 907, 1446, 141, 513, 1449, 718, 516, 150, 1450, 153, 827, 155, 1195, 157, 526, 159, 1194, 192, 1305, 193, 1307, 194, 195, 803, 196, 878, 879, 880, 805, 428, 198, 199, 1252, 200, 201, 202, 204, 205, 207, 205, 209, 210, 1306, 212, 994, 213, 1083, 5, 990, 1313, 1356, 1480, 1342, 920, 470, 472, 1482, 936, 475, 476, 939, 648, 649, 965, 431, 217, 923, 218, 221, 224, 877, 227, 497, 840, 887, 843, 247, 443, 846, 924, 849, 508, 852, 1061, 855, 299, 512, 857, 309, 515, 154, 898, 156, 323, 158, 861, 160, 525, 864, 632, 866, 1149, 830, 1319, 1189, 869, 1232, 5, 1190, 1191, 1192, 1364, 1342, 912, 5, 1235, 718, 915, 1364, 1342, 1045, 730, 731, 1130, 1046, 1047, 1048, 356, 704, 358, 5, 1343, 1344, 1491, 1492, 1211, 363, 1371, 365, 1384, 1384, 517, 368, 369, 1386, 830, 1092, 1093, 370, 371, 372, 373, 1379, 374, 1490, 375, 202, 377, 229, 230, 43, 231, 232, 233, 1039, 1039, 380, 1194, 1014, 1015, 288, 384, 385, 780, 386, 1077, 862, 863, 1123, 1124, 642, 390, 830, 392, 956, 165, 166, 394, 395, 885, 167, 398, 889, 168, 399, 400, 376, 310, 169, 402, 403, 1101, 718, 915, 501, 281, 895, 408, 282, 901, 1043, 411, 581, 170, 413, 171, 703, 1069, 172, 1071, 919, 415, 173, 418, 419, 421, 422, 424, 208, 425, 174, 522, 431, 134, 229, 175, 1189, 231, 232, 233, 1190, 1191, 1192, 1193, 269, 176, 5, 1189, 270, 721, 722, 1190, 1191, 1192, 1193, 723, 726, 5, 724, 727, 728, 729, 177, 487, 178, 179, 1214, 726, 180, 181, 727, 728, 729, 500, 1481, 504, 858, 1056, 98, 416, 420, 510, 101, 730, 731, 732, 1018, 1189, 423, 1453, 104, 1190, 1191, 1192, 730, 731, 732, 5, 517, 1194, 0, 5, 1342, 0, 1027, 0, 0, 0, 0, 0, 1194, 726, 0, 0, 727, 728, 729, 0, 542, 543, 1147, 1214, 0, 0, 1195, 358, 548, 0, 551, 0, 0, 0, 552, 554, 555, 1195, 556, 0, 730, 731, 732, 0, 0, 0, 718, 0, 561, 0, 562, 563, 1194, 564, 0, 566, 567, 0, 569, 570, 0, 571, 573, 0, 1039, 0, 577, 578, 579, 0, 0, 380, 0, 0, 0, 0, 584, 585, 0, 0, 588, 589, 0, 0, 592, 0, 3, 0, 1098, 1137, 0, 598, 599, 1223, 6, 602, 603, 0, 605, 606, 0, 0, 0, 0, 8, 0, 0, 0, 616, 617, 618, 9, 0, 0, 11, 623, 0, 624, 0, 627, 1122, 628, 0, 0, 0, 0, 718, 0, 0, 16, 0, 0, 0, 638, 1039, 0, 0, 643, 0, 0, 18, 0, 0, 20, 229, 22, 0, 231, 232, 233, 234, 235, 828, 0, 829, 0, 686, 0, 1163, 0, 0, 25, 0, 27, 1167, 28, 1170, 30, 0, 1174, 1125, 0, 0, 35, 0, 0, 0, 708, 0, 5, 229, 230, 0, 231, 232, 233, 234, 235, 0, 726, 829, 0, 727, 728, 729, 229, 0, 1186, 231, 232, 233, 234, 235, 750, 0, 829, 0, 1039, 0, 750, 0, 0, 0, 750, 0, 774, 730, 731, 732, 0, 486, 0, 548, 0, 0, 548, 0, 552, 5, 781, 0, 0, 0, 0, 0, 0, 0, 1228, 726, 1229, 0, 727, 728, 729, 0, 0, 0, 786, 0, 0, 757, 0, 787, 788, 789, 1242, 790, 791, 793, 791, 0, 5, 796, 0, 0, 730, 731, 732, 0, 0, 0, 726, 0, 0, 727, 728, 729, 0, 807, 808, 810, 808, 0, 812, 0, 813, 0, 815, 758, 817, 769, 0, 0, 0, 0, 0, 0, 0, 730, 731, 732, 0, 0, 3, 0, 0, 0, 0, 838, 0, 0, 6, 1440, 0, 1441, 0, 0, 0, 0, 1444, 839, 8, 841, 0, 0, 844, 1448, 847, 9, 850, 0, 853, 0, 853, 0, 0, 618, 0, 0, 859, 14, 0, 0, 0, 624, 624, 16, 628, 0, 0, 0, 867, 1339, 0, 0, 0, 870, 18, 5, 0, 20, 0, 22, 0, 0, 0, 0, 0, 726, 0, 0, 727, 728, 729, 0, 0, 886, 0, 25, 0, 27, 0, 28, 0, 30, 758, 1399, 1438, 0, 1402, 35, 1404, 0, 896, 0, 730, 731, 732, 1409, 0, 0, 0, 0, 0, 0, 0, 1416, 0, 5, 655, 656, 657, 658, 659, 660, 661, 662, 663, 726, 486, 0, 727, 728, 729, 921, 0, 925, 5, 0, 925, 0, 0, 925, 0, 0, 925, 0, 726, 925, 0, 727, 728, 729, 0, 750, 730, 731, 732, 0, 757, 0, 0, 957, 946, 758, 0, 0, 781, 0, 867, 0, 0, 0, 0, 730, 731, 732, 0, 791, 0, 0, 0, 791, 0, 975, 0, 977, 978, 808, 0, 0, 981, 0, 0, 808, 0, 0, 985, 813, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 0, 853, 0, 997, 0, 853, 0, 0, 0, 1000, 1002, 853, 0, 1486, 1006, 853, 0, 1009, 853, 0, 1011, 0, 0, 1012, 0, 0, 0, 0, 859, 859, 1016, 0, 628, 0, 1020, 1021, 229, 230, 0, 231, 232, 233, 234, 235, 1024, 1026, 0, 0, 3, 0, 0, 0, 0, 0, 0, 5, 6, 1035, 0, 0, 0, 0, 0, 0, 0, 726, 8, 1049, 727, 728, 729, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 925, 0, 925, 14, 0, 0, 925, 0, 0, 16, 730, 731, 732, 0, 0, 0, 750, 0, 0, 0, 18, 1081, 0, 20, 750, 22, 0, 1087, 1088, 1089, 1090, 0, 0, 0, 975, 975, 0, 0, 0, 0, 0, 25, 0, 27, 0, 28, 0, 30, 0, 0, 0, 0, 1100, 35, 0, 0, 0, 0, 0, 1104, 1105, 1106, 0, 1107, 853, 853, 853, 486, 1112, 0, 1113, 0, 0, 0, 628, 5, 1118, 0, 867, 0, 0, 0, 1024, 1024, 0, 726, 0, 0, 727, 728, 729, 0, 0, 0, 0, 0, 0, 757, 0, 0, 0, 0, 758, 0, 0, 0, 0, 925, 0, 0, 0, 0, 730, 731, 732, 134, 229, 230, 1157, 231, 232, 233, 234, 235, 1165, 0, 1168, 0, 628, 1172, 0, 0, 0, 1175, 1176, 0, 0, 0, 1179, 1180, 0, 1181, 0, 0, 853, 0, 1183, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 304, 1188, 0, 311, 750, 316, 0, 750, 328, 0, 0, 750, 0, 0, 0, 750, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1230, 0, 1231, 0, 1168, 628, 1234, 0, 1172, 1236, 0, 0, 0, 1238, 1240, 0, 1243, 0, 0, 0, 0, 0, 1245, 1247, 0, 0, 0, 0, 0, 750, 0, 0, 0, 0, 0, 0, 0, 750, 0, 750, 0, 0, 0, 0, 0, 0, 750, 1318, 1245, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1320, 1322, 1323, 1324, 1325, 0, 0, 1327, 1328, 1329, 1330, 1331, 0, 0, 1333, 0, 1240, 0, 1240, 0, 867, 427, 0, 0, 0, 628, 0, 0, 442, 0, 448, 449, 0, 1345, 0, 1357, 1357, 1365, 1365, 0, 1372, 1377, 1357, 1382, 1382, 0, 1387, 482, 0, 0, 0, 0, 490, 0, 0, 0, 0, 1395, 0, 1397, 0, 0, 1400, 0, 0, 0, 0, 0, 0, 0, 0, 1407, 0, 1410, 0, 0, 0, 0, 0, 1414, 0, 1417, 0, 0, 1395, 0, 1421, 0, 0, 0, 1424, 0, 0, 0, 0, 1428, 0, 0, 0, 0, 1395, 0, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 0, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 0, 560, 1284, 1285, 1286, 1287, 1288, 0, 0, 0, 1247, 568, 1454, 0, 1395, 0, 1459, 0, 576, 0, 1464, 1466, 0, 0, 1469, 0, 0, 1395, 0, 0, 0, 0, 397, 587, 0, 0, 0, 0, 0, 0, 593, 0, 0, 596, 597, 0, 405, 406, 601, 409, 0, 604, 0, 1483, 0, 0, 0, 0, 613, 0, 0, 615, 0, 0, 0, 0, 621, 0, 622, 0, 0, 0, 0, 0, 0, 0, 0, 631, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 645, 0, 0, 0, 652, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 689, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 701, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 754, 0, 0, 0, 0, 0, 766, 0, 0, 0, 772, 0, 0, 0, 0, 0, 775, 0, 776, 0, 0, 0, 778, 0, 0, 0, 0, 0, 782, 0, 0, 0, 0, 0, 0, 785, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 574, 0, 0, 0, 0, 0, 0, 0, 580, 0, 0, 0, 795, 583, 0, 797, 798, 799, 800, 0, 590, 591, 0, 0, 0, 594, 0, 0, 0, 806, 0, 600, 0, 0, 0, 0, 0, 0, 814, 0, 816, 0, 0, 614, 0, 820, 0, 822, 0, 824, 0, 0, 0, 0, 0, 837, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135, 137, 139, 139, 142, 0, 0, 148, 139, 151, 139, 148, 139, 148, 139, 148, 139, 148, 161, 163, 0, 185, 185, 185, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 888, 0, 890, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 900, 0, 902, 0, 0, 0, 0, 0, 0, 908, 0, 0, 909, 0, 910, 0, 911, 0, 0, 0, 0, 0, 0, 245, 0, 0, 0, 0, 273, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 953, 0, 0, 0, 0, 0, 0, 0, 958, 0, 0, 0, 801, 802, 0, 0, 0, 0, 804, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 818, 819, 0, 0, 821, 0, 823, 0, 825, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 999, 0, 0, 0, 0, 1005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1022, 0, 0, 0, 0, 0, 0, 1023, 0, 0, 1028, 1029, 1030, 1031, 1032, 1033, 0, 0, 1034, 0, 1038, 0, 0, 1042, 0, 0, 0, 0, 1044, 0, 1053, 1054, 1055, 0, 0, 0, 0, 0, 0, 1059, 436, 0, 0, 0, 0, 450, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 491, 137, 0, 1086, 0, 0, 0, 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 520, 0, 0, 523, 0, 0, 0, 0, 0, 0, 530, 0, 0, 1103, 0, 0, 0, 0, 0, 0, 967, 968, 969, 970, 0, 972, 973, 0, 1115, 0, 1117, 0, 0, 0, 0, 980, 0, 982, 983, 0, 0, 0, 0, 0, 0, 987, 988, 1133, 1134, 0, 0, 0, 0, 0, 0, 0, 0, 0, 995, 0, 0, 0, 0, 0, 0, 0, 0, 1150, 0, 0, 0, 0, 1161, 1162, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 5, 6, 0, 0, 0, 0, 0, 0, 7, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 10, 0, 11, 0, 12, 0, 0, 0, 0, 13, 0, 14, 0, 0, 15, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 17, 634, 636, 18, 1226, 19, 20, 21, 22, 0, 0, 0, 0, 0, 0, 0, 23, 24, 0, 0, 0, 0, 678, 0, 25, 26, 27, 0, 28, 29, 30, 31, 32, 33, 0, 34, 35, 36, 1091, 699, 0, 1244, 0, 1094, 1095, 0, 1096, 0, 0, 0, 0, 0, 1097, 0, 1304, 1099, 0, 0, 0, 0, 0, 0, 0, 1312, 0, 1316, 1317, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 767, 0, 0, 0, 185, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1326, 0, 0, 0, 0, 0, 0, 1332, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1341, 0, 1355, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1391, 0, 0, 0, 0, 0, 0, 1184, 1185, 1290, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1291, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1292, 1293, 1284, 1285, 1286, 1287, 1288, 0, 0, 0, 0, 0, 0, 0, 1433, 1434, 0, 0, 0, 0, 0, 1237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1249, 0, 0, 0, 0, 0, 0, 0, 0, 0, 875, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1458, 0, 1461, 1462, 0, 892, 0, 892, 0, 0, 1471, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1488, 0, 927, 0, 0, 932, 0, 0, 0, 0, 0, 0, 1495, 0, 942, 0, 1337, 0, 0, 0, 699, 0, 0, 699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1393, 0, 0, 0, 0, 1394, 0, 0, 0, 0, 0, 1401, 0, 1403, 0, 0, 0, 1405, 1406, 0, 1408, 0, 1411, 0, 0, 1412, 1413, 0, 1415, 0, 1418, 0, 1419, 0, 0, 0, 0, 1423, 0, 1425, 1426, 0, 1427, 0, 1429, 1430, 0, 1431, 1297, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1298, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1299, 1300, 1284, 1285, 1286, 1287, 1288, 0, 0, 0, 0, 0, 0, 0, 1455, 1456, 0, 0, 1460, 0, 0, 1463, 1465, 0, 1467, 1468, 1470, 0, 1472, 0, 1474, 1475, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1074, 0, 0, 0, 0, 0, 0, 0, 0, 1079, 1484, 0, 1485, 0, 1487, 0, 1489, 0, 0, 0, 0, 0, 0, 0, 1494, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 892, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1204, 0, 0, 1204, 0, 0, 0, 1204, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 892, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 892, 892, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1308 }; static const yytype_int16 yycheck[] = { 45, 573, 0, 196, 201, 228, 243, 52, 53, 764, 55, 131, 132, 58, 444, 60, 352, 62, 115, 0, 192, 66, 380, 68, 358, 70, 876, 72, 444, 74, 209, 76, 805, 78, 221, 80, 207, 224, 213, 375, 618, 204, 543, 88, 421, 859, 624, 195, 844, 916, 95, 244, 97, 201, 99, 385, 101, 978, 103, 612, 105, 413, 0, 676, 698, 133, 861, 719, 844, 864, 855, 847, 839, 0, 841, 4, 1163, 844, 859, 1020, 847, 716, 1081, 850, 4, 6, 853, 844, 14, 6, 847, 4, 6, 850, 1348, 16, 1100, 859, 1320, 371, 17, 17, 147, 66, 195, 1087, 19, 1089, 1090, 72, 169, 17, 14, 3, 50, 17, 29, 17, 1320, 1373, 22, 1375, 1324, 1325, 17, 1327, 1328, 26, 1330, 1331, 17, 1333, 36, 96, 27, 1389, 26, 57, 74, 0, 27, 61, 236, 742, 57, 744, 191, 746, 61, 748, 5, 750, 52, 221, 80, 81, 224, 86, 94, 153, 15, 90, 5, 56, 1168, 81, 86, 88, 55, 95, 90, 88, 15, 86, 88, 1397, 82, 90, 80, 81, 79, 374, 17, 1437, 356, 50, 169, 384, 92, 93, 1172, 1058, 17, 95, 975, 950, 1450, 952, 9, 24, 5, 997, 1016, 426, 249, 1407, 17, 62, 63, 254, 15, 256, 1414, 975, 259, 260, 51, 52, 17, 62, 554, 997, 1424, 22, 1000, 41, 1428, 1012, 39, 94, 1080, 41, 36, 1000, 1101, 1002, 281, 282, 413, 1006, 997, 286, 62, 1000, 289, 1002, 623, 1188, 1247, 1006, 584, 296, 1339, 57, 1175, 585, 301, 9, 303, 353, 198, 895, 1024, 308, 916, 17, 618, 901, 505, 79, 315, 1138, 885, 774, 201, 320, 889, 830, 913, 17, 325, 859, 327, 555, 22, 169, 331, 480, 92, 93, 1168, 528, 161, 338, 163, 567, 341, 17, 1176, 393, 17, 169, 362, 23, 349, 6, 7, 1395, 1104, 1397, 27, 12, 1400, 407, 31, 32, 17, 787, 788, 789, 414, 1076, 921, 383, 1245, 1098, 925, 1122, 1104, 1105, 929, 930, 931, 1421, 428, 934, 935, 54, 55, 938, 1107, 639, 80, 81, 642, 815, 25, 1104, 1105, 1106, 1107, 419, 394, 36, 422, 66, 68, 399, 7, 65, 402, 40, 11, 12, 13, 14, 1454, 1395, 17, 1397, 49, 33, 34, 7, 57, 1130, 1170, 11, 61, 377, 1174, 19, 363, 719, 169, 96, 98, 88, 71, 370, 68, 29, 589, 1421, 439, 73, 441, 1318, 17, 78, 7, 446, 17, 1179, 11, 12, 13, 42, 27, 92, 93, 456, 27, 1186, 562, 563, 653, 32, 463, 796, 98, 70, 1179, 1180, 1181, 156, 471, 606, 31, 32, 578, 579, 603, 1247, 156, 161, 599, 163, 7, 54, 55, 589, 11, 618, 489, 155, 1024, 781, 17, 7, 495, 54, 55, 1208, 12, 1228, 1229, 58, 874, 1309, 32, 1216, 49, 70, 558, 25, 1065, 1066, 1067, 1068, 17, 562, 563, 80, 81, 905, 812, 26, 17, 813, 165, 166, 54, 55, 23, 24, 1243, 578, 579, 16, 535, 153, 154, 155, 539, 157, 158, 159, 160, 161, 48, 595, 7, 0, 17, 33, 11, 12, 13, 34, 630, 7, 17, 63, 27, 609, 12, 22, 612, 561, 46, 17, 564, 1234, 566, 1236, 620, 569, 570, 1322, 1323, 1324, 1325, 7, 1327, 577, 1329, 11, 12, 13, 161, 54, 55, 17, 7, 8, 588, 1146, 11, 12, 13, 14, 75, 76, 17, 1323, 598, 162, 57, 1314, 602, 1329, 30, 605, 27, 70, 1327, 30, 31, 32, 167, 168, 1333, 7, 616, 80, 81, 11, 12, 13, 916, 163, 1305, 17, 1307, 153, 20, 1165, 22, 367, 1168, 54, 55, 56, 1172, 8, 70, 162, 1176, 418, 378, 379, 167, 168, 169, 424, 651, 70, 154, 387, 55, 157, 158, 159, 1407, 160, 161, 1410, 396, 375, 817, 1414, 112, 401, 1417, 719, 404, 117, 1421, 119, 717, 121, 95, 123, 412, 125, 70, 136, 1238, 138, 1240, 140, 141, 688, 143, 157, 158, 159, 693, 352, 149, 150, 1230, 152, 153, 154, 155, 156, 157, 158, 159, 160, 1240, 162, 917, 164, 1024, 17, 914, 1247, 20, 1464, 22, 839, 368, 369, 1469, 849, 372, 373, 852, 59, 60, 870, 1020, 184, 840, 186, 187, 188, 784, 190, 386, 738, 791, 740, 62, 63, 743, 841, 745, 395, 747, 997, 749, 202, 400, 752, 205, 403, 120, 808, 122, 210, 124, 760, 126, 411, 763, 542, 765, 1113, 1058, 1251, 7, 770, 1207, 17, 11, 12, 13, 21, 22, 827, 17, 1211, 830, 831, 21, 22, 7, 54, 55, 1089, 11, 12, 13, 246, 586, 248, 17, 80, 81, 83, 84, 1172, 255, 1325, 257, 1330, 1331, 855, 261, 262, 1331, 1101, 1036, 1037, 267, 268, 269, 270, 1328, 272, 1483, 274, 275, 276, 154, 155, 0, 157, 158, 159, 977, 978, 285, 70, 948, 949, 201, 290, 291, 644, 293, 1018, 761, 762, 1084, 1085, 551, 300, 1138, 302, 866, 129, 129, 306, 307, 790, 129, 310, 793, 129, 313, 314, 275, 205, 129, 318, 319, 1058, 916, 917, 390, 199, 807, 326, 199, 810, 981, 330, 488, 129, 333, 129, 585, 1009, 129, 1011, 838, 340, 129, 342, 343, 344, 345, 346, 158, 348, 129, 408, 1188, 153, 154, 129, 7, 157, 158, 159, 11, 12, 13, 14, 195, 129, 17, 7, 195, 617, 617, 11, 12, 13, 14, 617, 27, 17, 617, 30, 31, 32, 129, 380, 129, 129, 37, 27, 129, 129, 30, 31, 32, 390, 1466, 392, 753, 991, 0, 340, 343, 398, 0, 54, 55, 56, 951, 7, 345, 1433, 0, 11, 12, 13, 54, 55, 56, 17, 1012, 70, -1, 17, 22, -1, 965, -1, -1, -1, -1, -1, 70, 27, -1, -1, 30, 31, 32, -1, 437, 438, 1112, 37, -1, -1, 95, 444, 445, -1, 447, -1, -1, -1, 451, 452, 453, 95, 455, -1, 54, 55, 56, -1, -1, -1, 1058, -1, 465, -1, 467, 468, 70, 470, -1, 472, 473, -1, 475, 476, -1, 478, 479, -1, 1175, -1, 483, 484, 485, -1, -1, 488, -1, -1, -1, -1, 493, 494, -1, -1, 497, 498, -1, -1, 501, -1, 10, -1, 1051, 1101, -1, 508, 509, 1183, 18, 512, 513, -1, 515, 516, -1, -1, -1, -1, 28, -1, -1, -1, 525, 526, 527, 35, -1, -1, 38, 532, -1, 534, -1, 536, 1083, 538, -1, -1, -1, -1, 1138, -1, -1, 53, -1, -1, -1, 548, 1245, -1, -1, 552, -1, -1, 64, -1, -1, 67, 154, 69, -1, 157, 158, 159, 160, 161, 162, -1, 164, -1, 571, -1, 1121, -1, -1, 85, -1, 87, 1127, 89, 1129, 91, -1, 1132, 8, -1, -1, 97, -1, -1, -1, 592, -1, 17, 154, 155, -1, 157, 158, 159, 160, 161, -1, 27, 164, -1, 30, 31, 32, 154, -1, 1160, 157, 158, 159, 160, 161, 618, -1, 164, -1, 1318, -1, 624, -1, -1, -1, 628, -1, 632, 54, 55, 56, -1, 9, -1, 639, -1, -1, 642, -1, 644, 17, 646, -1, -1, -1, -1, -1, -1, -1, 1200, 27, 1202, -1, 30, 31, 32, -1, -1, -1, 664, -1, -1, 39, -1, 669, 670, 671, 1218, 673, 674, 675, 676, -1, 17, 679, -1, -1, 54, 55, 56, -1, -1, -1, 27, -1, -1, 30, 31, 32, -1, 695, 696, 697, 698, -1, 700, -1, 702, -1, 704, 44, 706, 46, -1, -1, -1, -1, -1, -1, -1, 54, 55, 56, -1, -1, 10, -1, -1, -1, -1, 725, -1, -1, 18, 1402, -1, 1404, -1, -1, -1, -1, 1409, 737, 28, 739, -1, -1, 742, 1416, 744, 35, 746, -1, 748, -1, 750, -1, -1, 753, -1, -1, 756, 47, -1, -1, -1, 761, 762, 53, 764, -1, -1, -1, 768, 1315, -1, -1, -1, 773, 64, 17, -1, 67, -1, 69, -1, -1, -1, -1, -1, 27, -1, -1, 30, 31, 32, -1, -1, 791, -1, 85, -1, 87, -1, 89, -1, 91, 44, 1349, 1399, -1, 1352, 97, 1354, -1, 808, -1, 54, 55, 56, 1361, -1, -1, -1, -1, -1, -1, -1, 1369, -1, 17, 99, 100, 101, 102, 103, 104, 105, 106, 107, 27, 9, -1, 30, 31, 32, 839, -1, 841, 17, -1, 844, -1, -1, 847, -1, -1, 850, -1, 27, 853, -1, 30, 31, 32, -1, 859, 54, 55, 56, -1, 39, -1, -1, 867, 43, 44, -1, -1, 874, -1, 876, -1, -1, -1, -1, 54, 55, 56, -1, 885, -1, -1, -1, 889, -1, 891, -1, 893, 894, 895, -1, -1, 898, -1, -1, 901, -1, -1, 904, 905, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, 921, -1, 923, -1, 925, -1, -1, -1, 929, 930, 931, -1, 1479, 934, 935, -1, 937, 938, -1, 940, -1, -1, 943, -1, -1, -1, -1, 948, 949, 950, -1, 952, -1, 954, 955, 154, 155, -1, 157, 158, 159, 160, 161, 964, 965, -1, -1, 10, -1, -1, -1, -1, -1, -1, 17, 18, 975, -1, -1, -1, -1, -1, -1, -1, 27, 28, 985, 30, 31, 32, -1, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, 1000, -1, 1002, 47, -1, -1, 1006, -1, -1, 53, 54, 55, 56, -1, -1, -1, 1016, -1, -1, -1, 64, 1023, -1, 67, 1024, 69, -1, 1029, 1030, 1031, 1032, -1, -1, -1, 1036, 1037, -1, -1, -1, -1, -1, 85, -1, 87, -1, 89, -1, 91, -1, -1, -1, -1, 1054, 97, -1, -1, -1, -1, -1, 1061, 1062, 1063, -1, 1065, 1066, 1067, 1068, 9, 1070, -1, 1072, -1, -1, -1, 1076, 17, 1078, -1, 1080, -1, -1, -1, 1084, 1085, -1, 27, -1, -1, 30, 31, 32, -1, -1, -1, -1, -1, -1, 39, -1, -1, -1, -1, 44, -1, -1, -1, -1, 1107, -1, -1, -1, -1, 54, 55, 56, 153, 154, 155, 1118, 157, 158, 159, 160, 161, 1126, -1, 1128, -1, 1130, 1131, -1, -1, -1, 1135, 1136, -1, -1, -1, 1140, 1141, -1, 1143, -1, -1, 1146, -1, 1148, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 203, 1164, -1, 206, 1165, 208, -1, 1168, 211, -1, -1, 1172, -1, -1, -1, 1176, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1203, -1, 1205, -1, 1207, 1208, 1209, -1, 1211, 1212, -1, -1, -1, 1216, 1217, -1, 1219, -1, -1, -1, -1, -1, 1225, 1226, -1, -1, -1, -1, -1, 1230, -1, -1, -1, -1, -1, -1, -1, 1238, -1, 1240, -1, -1, -1, -1, -1, -1, 1247, 1250, 1251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1289, 1290, 1291, 1292, 1293, -1, -1, 1296, 1297, 1298, 1299, 1300, -1, -1, 1303, -1, 1305, -1, 1307, -1, 1309, 350, -1, -1, -1, 1314, -1, -1, 357, -1, 359, 360, -1, 1320, -1, 1322, 1323, 1324, 1325, -1, 1327, 1328, 1329, 1330, 1331, -1, 1333, 376, -1, -1, -1, -1, 381, -1, -1, -1, -1, 1346, -1, 1348, -1, -1, 1351, -1, -1, -1, -1, -1, -1, -1, -1, 1360, -1, 1362, -1, -1, -1, -1, -1, 1368, -1, 1370, -1, -1, 1373, -1, 1375, -1, -1, -1, 1379, -1, -1, -1, -1, 1384, -1, -1, -1, -1, 1389, -1, 114, 115, 116, 117, 118, 119, 120, -1, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, -1, 464, 148, 149, 150, 151, 152, -1, -1, -1, 1433, 474, 1435, -1, 1437, -1, 1439, -1, 481, -1, 1443, 1444, -1, -1, 1447, -1, -1, 1450, -1, -1, -1, -1, 309, 496, -1, -1, -1, -1, -1, -1, 503, -1, -1, 506, 507, -1, 323, 324, 511, 326, -1, 514, -1, 1476, -1, -1, -1, -1, 521, -1, -1, 524, -1, -1, -1, -1, 529, -1, 531, -1, -1, -1, -1, -1, -1, -1, -1, 540, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 553, -1, -1, -1, 557, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 572, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 583, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 619, -1, -1, -1, -1, -1, 625, -1, -1, -1, 629, -1, -1, -1, -1, -1, 635, -1, 637, -1, -1, -1, 641, -1, -1, -1, -1, -1, 647, -1, -1, -1, -1, -1, -1, 654, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 479, -1, -1, -1, -1, -1, -1, -1, 487, -1, -1, -1, 677, 492, -1, 680, 681, 682, 683, -1, 499, 500, -1, -1, -1, 504, -1, -1, -1, 694, -1, 510, -1, -1, -1, -1, -1, -1, 703, -1, 705, -1, -1, 522, -1, 710, -1, 712, -1, 714, -1, -1, -1, -1, -1, 720, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 109, 110, 111, 112, 113, -1, -1, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, -1, 130, 131, 132, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 792, -1, 794, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 809, -1, 811, -1, -1, -1, -1, -1, -1, 818, -1, -1, 821, -1, 823, -1, 825, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, 197, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 860, -1, -1, -1, -1, -1, -1, -1, 868, -1, -1, -1, 686, 687, -1, -1, -1, -1, 692, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 707, 708, -1, -1, 711, -1, 713, -1, 715, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 928, -1, -1, -1, -1, 933, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 945, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 956, -1, -1, -1, -1, -1, -1, 963, -1, -1, 966, 967, 968, 969, 970, 971, -1, -1, 974, -1, 976, -1, -1, 979, -1, -1, -1, -1, 984, -1, 986, 987, 988, -1, -1, -1, -1, -1, -1, 995, 356, -1, -1, -1, -1, 361, 362, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 382, 383, -1, 1025, -1, -1, -1, -1, -1, 391, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 407, -1, -1, 410, -1, -1, -1, -1, -1, -1, 417, -1, -1, 1060, -1, -1, -1, -1, -1, -1, 881, 882, 883, 884, -1, 886, 887, -1, 1075, -1, 1077, -1, -1, -1, -1, 896, -1, 898, 899, -1, -1, -1, -1, -1, -1, 906, 907, 1094, 1095, -1, -1, -1, -1, -1, -1, -1, -1, -1, 919, -1, -1, -1, -1, -1, -1, -1, -1, 1114, -1, -1, -1, -1, 1119, 1120, -1, -1, -1, -1, -1, 4, 5, -1, -1, -1, -1, 10, -1, -1, -1, -1, 15, -1, 17, 18, -1, -1, -1, -1, -1, -1, 25, -1, -1, 28, -1, -1, -1, -1, -1, -1, 35, 36, -1, 38, -1, 40, -1, -1, -1, -1, 45, -1, 47, -1, -1, 50, -1, -1, 53, -1, -1, -1, -1, -1, -1, -1, 61, 544, 545, 64, 1187, 66, 67, 68, 69, -1, -1, -1, -1, -1, -1, -1, 77, 78, -1, -1, -1, -1, 565, -1, 85, 86, 87, -1, 89, 90, 91, 92, 93, 94, -1, 96, 97, 98, 1035, 582, -1, 1224, -1, 1040, 1041, -1, 1043, -1, -1, -1, -1, -1, 1049, -1, 1237, 1052, -1, -1, -1, -1, -1, -1, -1, 1246, -1, 1248, 1249, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 626, -1, -1, -1, 630, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1294, -1, -1, -1, -1, -1, -1, 1301, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1319, -1, 1321, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1336, -1, -1, -1, -1, -1, -1, 1157, 1158, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, -1, -1, -1, -1, -1, -1, -1, 1392, 1393, -1, -1, -1, -1, -1, 1213, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1227, -1, -1, -1, -1, -1, -1, -1, -1, -1, 783, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1438, -1, 1440, 1441, -1, 803, -1, 805, -1, -1, 1448, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1481, -1, 843, -1, -1, 846, -1, -1, -1, -1, -1, -1, 1493, -1, 855, -1, 1311, -1, -1, -1, 861, -1, -1, 864, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1340, -1, -1, -1, -1, 1345, -1, -1, -1, -1, -1, 1351, -1, 1353, -1, -1, -1, 1357, 1358, -1, 1360, -1, 1362, -1, -1, 1365, 1366, -1, 1368, -1, 1370, -1, 1372, -1, -1, -1, -1, 1377, -1, 1379, 1380, -1, 1382, -1, 1384, 1385, -1, 1387, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, -1, -1, -1, -1, -1, -1, -1, 1435, 1436, -1, -1, 1439, -1, -1, 1442, 1443, -1, 1445, 1446, 1447, -1, 1449, -1, 1451, 1452, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1012, -1, -1, -1, -1, -1, -1, -1, -1, 1021, 1476, -1, 1478, -1, 1480, -1, 1482, -1, -1, -1, -1, -1, -1, -1, 1490, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1098, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1122, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1167, -1, -1, 1170, -1, -1, -1, 1174, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1186, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1228, 1229, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1242 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_int16 yystos[] = { 0, 4, 5, 10, 15, 17, 18, 25, 28, 35, 36, 38, 40, 45, 47, 50, 53, 61, 64, 66, 67, 68, 69, 77, 78, 85, 86, 87, 89, 90, 91, 92, 93, 94, 96, 97, 98, 171, 172, 173, 244, 246, 321, 322, 325, 327, 348, 349, 350, 351, 352, 353, 356, 357, 359, 361, 369, 370, 371, 380, 381, 392, 394, 405, 406, 407, 415, 416, 417, 418, 419, 420, 421, 423, 424, 425, 426, 427, 428, 429, 431, 453, 454, 455, 457, 459, 460, 466, 467, 472, 477, 480, 483, 486, 487, 490, 495, 497, 500, 504, 517, 521, 522, 527, 529, 530, 0, 165, 166, 208, 208, 208, 208, 208, 169, 210, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 153, 211, 247, 211, 328, 211, 355, 355, 211, 362, 6, 88, 365, 366, 211, 372, 355, 211, 395, 355, 372, 355, 372, 355, 372, 355, 372, 211, 468, 211, 491, 350, 351, 352, 353, 380, 406, 407, 418, 423, 427, 453, 466, 472, 477, 480, 483, 486, 496, 498, 499, 211, 505, 505, 505, 41, 509, 510, 210, 210, 210, 210, 210, 208, 210, 210, 210, 210, 210, 373, 210, 210, 422, 210, 422, 210, 210, 430, 210, 210, 167, 168, 209, 210, 210, 501, 502, 210, 518, 519, 210, 523, 524, 210, 208, 154, 155, 157, 158, 159, 160, 161, 174, 175, 176, 178, 180, 181, 184, 186, 187, 211, 248, 62, 329, 331, 19, 29, 57, 322, 327, 338, 339, 358, 370, 388, 389, 456, 458, 461, 463, 464, 465, 338, 358, 456, 458, 178, 363, 211, 367, 359, 382, 383, 385, 386, 387, 388, 389, 3, 26, 396, 397, 71, 325, 327, 338, 408, 416, 473, 474, 475, 476, 23, 24, 244, 374, 375, 377, 378, 209, 72, 420, 478, 479, 244, 374, 209, 73, 425, 481, 482, 209, 74, 429, 484, 485, 51, 52, 244, 432, 433, 435, 436, 209, 65, 469, 470, 487, 488, 529, 75, 76, 492, 493, 79, 506, 507, 509, 506, 509, 506, 509, 42, 511, 512, 173, 186, 156, 174, 185, 178, 210, 245, 210, 323, 326, 208, 208, 210, 208, 210, 208, 208, 210, 210, 210, 210, 210, 210, 210, 210, 373, 210, 208, 208, 210, 393, 208, 208, 210, 210, 210, 208, 210, 265, 210, 208, 210, 208, 210, 210, 208, 265, 210, 210, 210, 208, 210, 210, 208, 265, 265, 208, 210, 265, 208, 210, 208, 210, 208, 210, 502, 208, 210, 210, 519, 210, 210, 524, 210, 210, 208, 209, 179, 182, 183, 187, 186, 33, 34, 175, 211, 249, 250, 251, 253, 254, 209, 63, 329, 334, 335, 359, 209, 209, 211, 332, 328, 370, 58, 340, 341, 16, 274, 275, 277, 279, 280, 282, 354, 365, 211, 390, 390, 49, 438, 440, 438, 370, 354, 438, 438, 178, 364, 177, 179, 368, 209, 392, 390, 390, 9, 244, 399, 401, 209, 211, 398, 328, 416, 282, 409, 438, 390, 244, 244, 377, 211, 376, 244, 186, 379, 274, 438, 390, 244, 274, 438, 390, 274, 438, 390, 186, 190, 192, 211, 434, 432, 211, 437, 438, 390, 488, 186, 494, 211, 508, 511, 26, 442, 443, 511, 48, 531, 535, 173, 186, 210, 210, 208, 208, 323, 326, 210, 324, 208, 210, 210, 330, 210, 210, 210, 343, 208, 208, 209, 210, 210, 210, 210, 208, 210, 210, 209, 210, 210, 210, 360, 210, 265, 178, 209, 210, 210, 210, 265, 393, 208, 265, 210, 210, 208, 209, 210, 210, 265, 265, 210, 209, 265, 174, 209, 209, 210, 210, 265, 209, 210, 210, 209, 210, 210, 161, 163, 189, 191, 195, 198, 209, 265, 209, 210, 210, 210, 489, 174, 209, 209, 210, 210, 520, 208, 210, 210, 213, 208, 209, 250, 253, 211, 252, 211, 255, 244, 337, 175, 336, 334, 244, 333, 209, 329, 354, 59, 60, 344, 346, 209, 186, 342, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 283, 284, 285, 274, 338, 358, 338, 358, 274, 211, 441, 274, 354, 274, 274, 7, 11, 244, 266, 270, 209, 7, 12, 264, 269, 274, 338, 358, 338, 358, 211, 402, 209, 329, 409, 283, 274, 338, 416, 244, 186, 274, 420, 274, 425, 274, 429, 186, 193, 186, 199, 274, 461, 463, 464, 465, 471, 27, 30, 31, 32, 54, 55, 56, 214, 216, 217, 218, 219, 220, 221, 222, 225, 226, 227, 229, 230, 235, 237, 240, 241, 244, 256, 257, 488, 209, 186, 442, 39, 44, 214, 401, 445, 450, 451, 515, 516, 209, 211, 444, 46, 528, 214, 209, 505, 210, 209, 209, 324, 209, 324, 330, 210, 209, 208, 174, 209, 210, 210, 210, 210, 210, 210, 462, 210, 462, 209, 210, 209, 209, 209, 209, 265, 265, 208, 265, 208, 209, 210, 210, 384, 210, 384, 210, 210, 209, 210, 209, 210, 265, 265, 209, 265, 209, 265, 209, 265, 191, 189, 162, 164, 187, 188, 196, 199, 204, 205, 206, 209, 210, 210, 208, 210, 215, 208, 210, 215, 208, 210, 215, 208, 210, 215, 208, 210, 215, 208, 215, 208, 489, 210, 503, 208, 520, 520, 208, 213, 208, 210, 345, 208, 210, 532, 533, 253, 329, 211, 347, 186, 157, 158, 159, 286, 286, 286, 286, 370, 244, 365, 209, 370, 209, 442, 211, 272, 272, 370, 244, 264, 365, 391, 209, 370, 209, 177, 403, 329, 286, 416, 209, 209, 209, 209, 186, 194, 199, 186, 200, 188, 207, 392, 218, 244, 256, 221, 225, 244, 256, 211, 223, 229, 235, 240, 211, 228, 235, 240, 175, 231, 240, 175, 238, 190, 211, 242, 153, 212, 43, 214, 445, 450, 513, 514, 515, 209, 402, 402, 336, 244, 209, 392, 438, 500, 521, 525, 442, 506, 345, 265, 265, 265, 265, 462, 265, 265, 462, 210, 439, 210, 210, 384, 265, 210, 265, 265, 384, 210, 400, 265, 265, 191, 207, 188, 197, 204, 200, 265, 215, 210, 215, 209, 210, 215, 210, 215, 215, 209, 210, 215, 215, 210, 215, 210, 210, 209, 503, 503, 210, 213, 208, 213, 210, 210, 209, 209, 210, 534, 210, 533, 209, 209, 209, 209, 209, 209, 209, 244, 445, 450, 209, 178, 273, 273, 209, 391, 209, 7, 11, 12, 13, 244, 262, 263, 404, 209, 209, 209, 186, 201, 202, 209, 224, 226, 229, 235, 240, 235, 240, 240, 240, 175, 232, 175, 239, 190, 211, 243, 515, 173, 403, 211, 452, 210, 214, 401, 450, 536, 209, 210, 210, 210, 210, 265, 439, 439, 265, 265, 265, 265, 208, 265, 210, 174, 204, 209, 210, 210, 210, 210, 215, 215, 215, 215, 210, 210, 236, 209, 213, 209, 210, 446, 345, 528, 208, 534, 534, 8, 288, 290, 287, 290, 288, 289, 290, 209, 209, 272, 287, 186, 203, 204, 229, 235, 240, 235, 240, 240, 240, 175, 233, 266, 209, 7, 11, 12, 13, 14, 70, 244, 447, 448, 449, 209, 209, 208, 402, 210, 278, 208, 210, 276, 208, 213, 210, 281, 208, 210, 210, 410, 204, 210, 210, 210, 215, 210, 265, 265, 208, 525, 210, 7, 11, 12, 13, 14, 70, 95, 214, 258, 259, 260, 261, 267, 271, 320, 211, 291, 214, 287, 320, 291, 214, 289, 291, 273, 37, 214, 320, 412, 413, 235, 240, 240, 240, 175, 234, 272, 209, 403, 208, 208, 210, 210, 276, 213, 210, 281, 210, 265, 210, 213, 210, 411, 208, 210, 209, 210, 268, 210, 526, 265, 272, 272, 214, 114, 115, 116, 117, 118, 119, 120, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 148, 149, 150, 151, 152, 304, 113, 121, 146, 147, 292, 295, 304, 113, 121, 146, 147, 297, 300, 304, 209, 412, 214, 412, 211, 414, 240, 273, 209, 214, 515, 528, 209, 209, 210, 268, 210, 302, 210, 210, 210, 210, 209, 210, 210, 210, 210, 210, 209, 210, 411, 411, 345, 265, 213, 208, 273, 209, 22, 80, 81, 244, 267, 303, 309, 310, 311, 313, 314, 315, 316, 209, 20, 244, 259, 293, 305, 306, 309, 293, 21, 244, 259, 294, 307, 308, 309, 294, 244, 259, 296, 309, 311, 244, 298, 305, 309, 293, 244, 299, 307, 309, 299, 244, 301, 309, 311, 209, 525, 265, 265, 210, 312, 210, 312, 208, 210, 265, 208, 265, 208, 265, 265, 210, 265, 208, 210, 265, 265, 265, 210, 265, 208, 210, 265, 265, 312, 210, 312, 265, 210, 265, 265, 265, 210, 265, 265, 265, 312, 209, 209, 313, 315, 267, 186, 315, 175, 175, 259, 309, 175, 259, 259, 309, 175, 259, 259, 309, 309, 526, 210, 265, 265, 312, 209, 210, 265, 209, 209, 265, 210, 265, 210, 265, 265, 210, 265, 209, 265, 312, 265, 265, 315, 82, 317, 318, 259, 264, 259, 210, 265, 265, 208, 265, 209, 265, 317, 83, 84, 319, 265, 209 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_int16 yyr1[] = { 0, 170, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 172, 172, 172, 172, 172, 172, 173, 173, 174, 175, 175, 176, 177, 178, 178, 179, 179, 180, 181, 182, 183, 184, 184, 185, 185, 186, 186, 186, 186, 187, 187, 188, 189, 190, 190, 190, 191, 191, 192, 193, 194, 195, 196, 196, 197, 197, 198, 199, 200, 201, 201, 201, 202, 203, 204, 204, 205, 206, 206, 207, 207, 208, 208, 209, 209, 210, 211, 212, 213, 213, 214, 214, 214, 215, 215, 215, 216, 216, 217, 217, 217, 218, 218, 218, 218, 219, 220, 221, 222, 223, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 236, 237, 238, 239, 240, 241, 242, 242, 243, 243, 244, 245, 245, 245, 245, 245, 245, 245, 246, 247, 248, 248, 249, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 258, 259, 260, 261, 261, 261, 261, 261, 262, 263, 263, 263, 263, 264, 265, 265, 266, 267, 268, 268, 269, 269, 270, 270, 271, 271, 272, 273, 274, 274, 274, 274, 275, 276, 276, 276, 276, 277, 278, 278, 278, 278, 279, 280, 281, 281, 281, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 285, 285, 286, 286, 286, 287, 288, 289, 290, 291, 292, 292, 292, 292, 292, 292, 292, 292, 292, 293, 293, 293, 293, 293, 293, 293, 293, 294, 294, 294, 294, 294, 294, 294, 294, 295, 295, 296, 296, 296, 296, 296, 297, 297, 297, 297, 297, 297, 297, 297, 297, 298, 298, 298, 298, 299, 299, 299, 299, 300, 300, 301, 301, 301, 302, 302, 303, 303, 303, 303, 303, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 305, 306, 307, 308, 309, 310, 311, 311, 311, 311, 312, 312, 312, 312, 312, 313, 314, 315, 316, 317, 318, 319, 319, 320, 321, 321, 322, 323, 323, 324, 324, 325, 326, 326, 327, 328, 329, 330, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 342, 342, 343, 343, 344, 345, 345, 346, 346, 347, 348, 348, 348, 349, 349, 350, 351, 352, 353, 354, 354, 355, 356, 356, 357, 357, 358, 358, 359, 360, 360, 360, 361, 361, 362, 363, 364, 365, 366, 366, 367, 368, 368, 369, 369, 370, 371, 371, 371, 372, 373, 373, 373, 373, 373, 373, 373, 373, 374, 375, 376, 377, 378, 379, 379, 379, 380, 381, 381, 382, 382, 382, 382, 383, 384, 384, 384, 384, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 393, 393, 394, 395, 396, 397, 397, 398, 399, 400, 400, 400, 401, 402, 403, 404, 405, 405, 406, 407, 408, 408, 409, 410, 410, 410, 410, 410, 411, 411, 411, 412, 413, 414, 415, 415, 416, 417, 417, 417, 418, 419, 419, 420, 421, 421, 422, 422, 422, 422, 423, 424, 425, 426, 426, 427, 428, 429, 430, 430, 430, 430, 430, 431, 431, 432, 433, 434, 434, 435, 436, 437, 438, 439, 439, 439, 439, 440, 441, 442, 443, 444, 445, 446, 446, 446, 447, 448, 449, 449, 449, 449, 449, 449, 450, 451, 452, 453, 453, 453, 454, 454, 455, 456, 456, 457, 458, 458, 459, 460, 461, 462, 462, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 471, 471, 471, 472, 473, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 488, 488, 489, 489, 489, 490, 491, 492, 493, 493, 494, 494, 494, 495, 496, 496, 497, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 499, 499, 499, 499, 499, 499, 499, 500, 501, 501, 502, 503, 503, 503, 503, 503, 503, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 518, 519, 520, 520, 520, 520, 520, 521, 522, 523, 523, 524, 525, 525, 525, 525, 526, 526, 526, 526, 527, 528, 529, 530, 531, 532, 532, 533, 534, 534, 534, 534, 535, 536 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_int8 yyr2[] = { 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 0, 1, 3, 1, 1, 2, 2, 2, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 6, 0, 1, 1, 1, 1, 3, 3, 1, 2, 1, 1, 1, 1, 3, 4, 2, 1, 1, 1, 1, 1, 3, 2, 0, 2, 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, 2, 1, 0, 3, 2, 1, 1, 3, 2, 1, 1, 3, 4, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 7, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 8, 4, 1, 1, 10, 1, 1, 1, 1, 1, 7, 0, 2, 1, 1, 1, 6, 1, 1, 1, 1, 1, 7, 0, 2, 4, 6, 2, 4, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 4, 1, 1, 4, 1, 1, 1, 1, 7, 1, 1, 1, 1, 1, 7, 1, 1, 1, 1, 7, 0, 3, 7, 5, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 0, 3, 3, 2, 10, 0, 2, 4, 2, 10, 10, 0, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 7, 6, 1, 1, 1, 1, 3, 1, 3, 1, 3, 1, 3, 2, 4, 6, 4, 2, 4, 2, 2, 2, 4, 6, 4, 2, 4, 2, 2, 1, 3, 2, 1, 2, 4, 2, 1, 1, 3, 1, 3, 1, 3, 1, 3, 2, 4, 2, 2, 2, 4, 2, 2, 1, 3, 2, 2, 1, 0, 2, 2, 1, 2, 4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 4, 1, 4, 1, 2, 2, 4, 6, 0, 3, 3, 5, 7, 4, 1, 4, 1, 4, 1, 1, 1, 1, 1, 1, 7, 5, 3, 0, 3, 7, 3, 3, 1, 1, 5, 0, 3, 1, 1, 1, 4, 1, 1, 1, 5, 1, 4, 1, 1, 2, 3, 0, 2, 5, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 8, 10, 8, 10, 3, 1, 1, 1, 1, 1, 1, 1, 1, 9, 0, 3, 3, 1, 1, 1, 1, 1, 6, 1, 1, 1, 4, 2, 1, 3, 7, 1, 1, 1, 1, 0, 2, 2, 4, 3, 5, 5, 7, 4, 1, 1, 4, 1, 1, 2, 3, 10, 1, 1, 1, 1, 1, 1, 7, 0, 3, 5, 3, 3, 9, 7, 9, 1, 1, 1, 1, 7, 0, 3, 3, 1, 1, 5, 1, 1, 1, 7, 0, 3, 3, 1, 1, 1, 1, 1, 1, 8, 10, 1, 1, 10, 0, 3, 5, 3, 2, 0, 3, 2, 5, 1, 1, 1, 1, 5, 1, 1, 1, 8, 1, 1, 5, 1, 1, 0, 2, 3, 5, 8, 1, 5, 1, 1, 8, 1, 5, 0, 3, 5, 3, 3, 1, 1, 4, 1, 1, 1, 4, 1, 1, 7, 0, 3, 3, 3, 1, 1, 5, 1, 1, 7, 0, 3, 3, 1, 5, 1, 1, 1, 1, 1, 1, 7, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 10, 1, 1, 10, 10, 7, 0, 3, 3, 9, 7, 9, 10, 1, 1, 9, 1, 1, 1, 1, 1, 10, 1, 1, 7, 9, 1, 10, 7, 1, 10, 7, 1, 10, 7, 1, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 2, 1, 1, 4, 1, 1, 1, 2, 3, 4, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 3, 1, 8, 0, 3, 3, 3, 5, 3, 2, 1, 1, 4, 1, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 3, 1, 6, 0, 3, 3, 3, 2, 1, 4, 3, 1, 16, 1, 1, 1, 1, 0, 6, 3, 2, 1, 1, 9, 1, 4, 3, 1, 4, 0, 3, 3, 2, 1, 7 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, pj_wkt2_parse_context *context) { FILE *yyoutput = yyo; YYUSE (yyoutput); YYUSE (context); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyo, yytoknum[yytype], *yyvaluep); # endif YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, pj_wkt2_parse_context *context) { YYFPRINTF (yyo, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); yy_symbol_value_print (yyo, yytype, yyvaluep, context); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp, int yyrule, pj_wkt2_parse_context *context) { int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[+yyssp[yyi + 1 - yynrhs]], &yyvsp[(yyi + 1) - (yynrhs)] , context); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule, context); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen(S) (YY_CAST (YYPTRDIFF_T, strlen (S))) # else /* Return the length of YYSTR. */ static YYPTRDIFF_T yystrlen (const char *yystr) { YYPTRDIFF_T yylen; for (yylen = 0; yystr && yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYPTRDIFF_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYPTRDIFF_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; else goto append; append: default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (yyres) return (YYPTRDIFF_T)(yystpcpy (yyres, yystr) - yyres); else return yystrlen (yystr); } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYPTRDIFF_T *yymsg_alloc, char **yymsg, yy_state_t *yyssp, int yytoken) { enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat: reported tokens (one for the "unexpected", one per "expected"). */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Actual size of YYARG. */ int yycount = 0; /* Cumulated lengths of YYARG. */ YYPTRDIFF_T yysize = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[+*yyssp]; YYPTRDIFF_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); yysize = yysize0; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYPTRDIFF_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) yysize = yysize1; else return 2; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { /* Don't count the "%s"s in the final size, but reserve room for the terminator. */ YYPTRDIFF_T yysize1 = yysize + (yystrlen (yyformat) - 2 * yycount) + 1; if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) yysize = yysize1; else return 2; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { ++yyp; ++yyformat; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, pj_wkt2_parse_context *context) { YYUSE (yyvaluep); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (pj_wkt2_parse_context *context) { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ /* int yynerrs; */ yy_state_fast_t yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yy_state_t yyssa[YYINITDEPTH]; yy_state_t *yyss; yy_state_t *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYPTRDIFF_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYPTRDIFF_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; /* yynerrs = 0; */ yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; /*--------------------------------------------------------------------. | yysetstate -- set current state (the top of the stack) to yystate. | `--------------------------------------------------------------------*/ yysetstate: YYDPRINTF ((stderr, "Entering state %d\n", yystate)); YY_ASSERT (0 <= yystate && yystate < YYNSTATES); YY_IGNORE_USELESS_CAST_BEGIN *yyssp = YY_CAST (yy_state_t, yystate); YY_IGNORE_USELESS_CAST_END if (yyss + yystacksize - 1 <= yyssp) #if !defined yyoverflow && !defined YYSTACK_RELOCATE goto yyexhaustedlab; #else { /* Get the current used size of the three stacks, in elements. */ YYPTRDIFF_T yysize = (YYPTRDIFF_T)(yyssp - yyss + 1); # if defined yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ yy_state_t *yyss1 = yyss; YYSTYPE *yyvs1 = yyvs; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * YYSIZEOF (*yyssp), &yyvs1, yysize * YYSIZEOF (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } # else /* defined YYSTACK_RELOCATE */ /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yy_state_t *yyss1 = yyss; union yyalloc *yyptr = YY_CAST (union yyalloc *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize)))); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YY_IGNORE_USELESS_CAST_BEGIN YYDPRINTF ((stderr, "Stack size increased to %ld\n", YY_CAST (long, yystacksize))); YY_IGNORE_USELESS_CAST_END if (yyss + yystacksize - 1 <= yyssp) YYABORT; } #endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, context); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Discard the shifted token. */ yychar = YYEMPTY; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { /* ++yynerrs; */ #if ! YYERROR_VERBOSE yyerror (context, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = YY_CAST (char *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, yymsg_alloc))); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (context, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, context); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ #if 0 yyerrorlab: /* Pacify compilers when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (0) YYERROR; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ #endif yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif /*-----------------------------------------------------. | yyreturn -- parsing is finished, return the result. | `-----------------------------------------------------*/ yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, context); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[+*yyssp], yyvsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; }
c
PROJ
data/projects/PROJ/src/zpoly1.cpp
/* evaluate complex polynomial */ #include "proj.h" #include "proj_internal.h" /* note: coefficients are always from C_1 to C_n ** i.e. C_0 == (0., 0) ** n should always be >= 1 though no checks are made */ COMPLEX pj_zpoly1(COMPLEX z, const COMPLEX *C, int n) { COMPLEX a; double t; a = *(C += n); while (n-- > 0) { a.r = (--C)->r + z.r * (t = a.r) - z.i * a.i; a.i = C->i + z.r * a.i + z.i * t; } a.r = z.r * (t = a.r) - z.i * a.i; a.i = z.r * a.i + z.i * t; return a; } /* evaluate complex polynomial and derivative */ COMPLEX pj_zpolyd1(COMPLEX z, const COMPLEX *C, int n, COMPLEX *der) { COMPLEX a, b; double t; int first = 1; a = *(C += n); b = a; while (n-- > 0) { if (first) { first = 0; } else { b.r = a.r + z.r * (t = b.r) - z.i * b.i; b.i = a.i + z.r * b.i + z.i * t; } a.r = (--C)->r + z.r * (t = a.r) - z.i * a.i; a.i = C->i + z.r * a.i + z.i * t; } b.r = a.r + z.r * (t = b.r) - z.i * b.i; b.i = a.i + z.r * b.i + z.i * t; a.r = z.r * (t = a.r) - z.i * a.i; a.i = z.r * a.i + z.i * t; *der = b; return a; }
cpp
PROJ
data/projects/PROJ/src/strerrno.cpp
/* list of projection system errno values */ #include <stddef.h> #include <stdio.h> #include <string.h> #include "proj.h" #include "proj_config.h" #include "proj_internal.h" const char *proj_errno_string(int err) { return proj_context_errno_string(pj_get_default_ctx(), err); } static const struct { int num; const char *str; } error_strings[] = { {PROJ_ERR_INVALID_OP_WRONG_SYNTAX, _("Invalid PROJ string syntax")}, {PROJ_ERR_INVALID_OP_MISSING_ARG, _("Missing argument")}, {PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE, _("Invalid value for an argument")}, {PROJ_ERR_INVALID_OP_MUTUALLY_EXCLUSIVE_ARGS, _("Mutually exclusive arguments")}, {PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID, _("File not found or invalid")}, {PROJ_ERR_COORD_TRANSFM_INVALID_COORD, _("Invalid coordinate")}, {PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN, _("Point outside of projection domain")}, {PROJ_ERR_COORD_TRANSFM_NO_OPERATION, _("No operation matching criteria found for coordinate")}, {PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID, _("Coordinate to transform falls outside grid")}, {PROJ_ERR_COORD_TRANSFM_GRID_AT_NODATA, _("Coordinate to transform falls into a grid cell that evaluates to " "nodata")}, {PROJ_ERR_COORD_TRANSFM_NO_CONVERGENCE, _("Iterative method fails to converge on coordinate to transform")}, {PROJ_ERR_OTHER_API_MISUSE, _("API misuse")}, {PROJ_ERR_OTHER_NO_INVERSE_OP, _("No inverse operation")}, {PROJ_ERR_OTHER_NETWORK_ERROR, _("Network error when accessing a remote resource")}, }; const char *proj_context_errno_string(PJ_CONTEXT *ctx, int err) { if (ctx == nullptr) ctx = pj_get_default_ctx(); if (0 == err) return nullptr; const char *str = nullptr; for (const auto &num_str_pair : error_strings) { if (err == num_str_pair.num) { str = num_str_pair.str; break; } } if (str == nullptr && err > 0 && (err & PROJ_ERR_INVALID_OP) != 0) { str = _( "Unspecified error related to coordinate operation initialization"); } if (str == nullptr && err > 0 && (err & PROJ_ERR_COORD_TRANSFM) != 0) { str = _("Unspecified error related to coordinate transformation"); } if (str) { ctx->lastFullErrorMessage = str; } else { ctx->lastFullErrorMessage.resize(50); snprintf(&ctx->lastFullErrorMessage[0], ctx->lastFullErrorMessage.size(), _("Unknown error (code %d)"), err); ctx->lastFullErrorMessage.resize( strlen(ctx->lastFullErrorMessage.data())); } return ctx->lastFullErrorMessage.c_str(); }
cpp
PROJ
data/projects/PROJ/src/geodesic.h
/** * \file geodesic.h * \brief API for the geodesic routines in C * * These routines are a simple transcription of the corresponding C++ classes * in <a href="https://geographiclib.sourceforge.io"> GeographicLib</a>. The * "class data" is represented by the structs geod_geodesic, geod_geodesicline, * geod_polygon and pointers to these objects are passed as initial arguments * to the member functions. Most of the internal comments have been retained. * However, in the process of transcription some documentation has been lost * and the documentation for the C++ classes, GeographicLib::Geodesic, * GeographicLib::GeodesicLine, and GeographicLib::PolygonAreaT, should be * consulted. The C++ code remains the "reference implementation". Think * twice about restructuring the internals of the C code since this may make * porting fixes from the C++ code more difficult. * * Copyright (c) Charles Karney (2012-2022) <[email protected]> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ #if !defined(GEODESIC_H) #define GEODESIC_H 1 /** * The major version of the geodesic library. (This tracks the version of * GeographicLib.) **********************************************************************/ #define GEODESIC_VERSION_MAJOR 2 /** * The minor version of the geodesic library. (This tracks the version of * GeographicLib.) **********************************************************************/ #define GEODESIC_VERSION_MINOR 1 /** * The patch level of the geodesic library. (This tracks the version of * GeographicLib.) **********************************************************************/ #define GEODESIC_VERSION_PATCH 0 /** * Pack the version components into a single integer. Users should not rely on * this particular packing of the components of the version number; see the * documentation for ::GEODESIC_VERSION, below. **********************************************************************/ #define GEODESIC_VERSION_NUM(a,b,c) ((((a) * 10000 + (b)) * 100) + (c)) /** * The version of the geodesic library as a single integer, packed as MMmmmmpp * where MM is the major version, mmmm is the minor version, and pp is the * patch level. Users should not rely on this particular packing of the * components of the version number. Instead they should use a test such as * @code{.c} #if GEODESIC_VERSION >= GEODESIC_VERSION_NUM(1,40,0) ... #endif * @endcode **********************************************************************/ #define GEODESIC_VERSION \ GEODESIC_VERSION_NUM(GEODESIC_VERSION_MAJOR, \ GEODESIC_VERSION_MINOR, \ GEODESIC_VERSION_PATCH) #if !defined(GEOD_DLL) #if defined(_MSC_VER) && defined(PROJ_MSVC_DLL_EXPORT) #define GEOD_DLL __declspec(dllexport) #elif defined(__GNUC__) #define GEOD_DLL __attribute__ ((visibility("default"))) #else #define GEOD_DLL #endif #endif #if defined(PROJ_RENAME_SYMBOLS) #include "proj_symbol_rename.h" #endif #if defined(__cplusplus) extern "C" { #endif /** * The struct containing information about the ellipsoid. This must be * initialized by geod_init() before use. **********************************************************************/ struct geod_geodesic { double a; /**< the equatorial radius */ double f; /**< the flattening */ /**< @cond SKIP */ double f1, e2, ep2, n, b, c2, etol2; double A3x[6], C3x[15], C4x[21]; /**< @endcond */ }; /** * The struct containing information about a single geodesic. This must be * initialized by geod_lineinit(), geod_directline(), geod_gendirectline(), * or geod_inverseline() before use. **********************************************************************/ struct geod_geodesicline { double lat1; /**< the starting latitude */ double lon1; /**< the starting longitude */ double azi1; /**< the starting azimuth */ double a; /**< the equatorial radius */ double f; /**< the flattening */ double salp1; /**< sine of \e azi1 */ double calp1; /**< cosine of \e azi1 */ double a13; /**< arc length to reference point */ double s13; /**< distance to reference point */ /**< @cond SKIP */ double b, c2, f1, salp0, calp0, k2, ssig1, csig1, dn1, stau1, ctau1, somg1, comg1, A1m1, A2m1, A3c, B11, B21, B31, A4, B41; double C1a[6+1], C1pa[6+1], C2a[6+1], C3a[6], C4a[6]; /**< @endcond */ unsigned caps; /**< the capabilities */ }; /** * The struct for accumulating information about a geodesic polygon. This is * used for computing the perimeter and area of a polygon. This must be * initialized by geod_polygon_init() before use. **********************************************************************/ struct geod_polygon { double lat; /**< the current latitude */ double lon; /**< the current longitude */ /**< @cond SKIP */ double lat0; double lon0; double A[2]; double P[2]; int polyline; int crossings; /**< @endcond */ unsigned num; /**< the number of points so far */ }; /** * Initialize a geod_geodesic object. * * @param[out] g a pointer to the object to be initialized. * @param[in] a the equatorial radius (meters). * @param[in] f the flattening. **********************************************************************/ void GEOD_DLL geod_init(struct geod_geodesic* g, double a, double f); /** * Solve the direct geodesic problem. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] azi1 azimuth at point 1 (degrees). * @param[in] s12 distance from point 1 to point 2 (meters); it can be * negative. * @param[out] plat2 pointer to the latitude of point 2 (degrees). * @param[out] plon2 pointer to the longitude of point 2 (degrees). * @param[out] pazi2 pointer to the (forward) azimuth at point 2 (degrees). * * \e g must have been initialized with a call to geod_init(). \e lat1 * should be in the range [&minus;90&deg;, 90&deg;]. The values of \e lon2 * and \e azi2 returned are in the range [&minus;180&deg;, 180&deg;]. Any of * the "return" arguments \e plat2, etc., may be replaced by 0, if you do not * need some quantities computed. * * If either point is at a pole, the azimuth is defined by keeping the * longitude fixed, writing \e lat = &plusmn;(90&deg; &minus; &epsilon;), and * taking the limit &epsilon; &rarr; 0+. An arc length greater that 180&deg; * signifies a geodesic which is not a shortest path. (For a prolate * ellipsoid, an additional condition is necessary for a shortest path: the * longitudinal extent must not exceed of 180&deg;.) * * Example, determine the point 10000 km NE of JFK: @code{.c} struct geod_geodesic g; double lat, lon; geod_init(&g, 6378137, 1/298.257223563); geod_direct(&g, 40.64, -73.78, 45.0, 10e6, &lat, &lon, 0); printf("%.5f %.5f\n", lat, lon); @endcode **********************************************************************/ void GEOD_DLL geod_direct(const struct geod_geodesic* g, double lat1, double lon1, double azi1, double s12, double* plat2, double* plon2, double* pazi2); /** * The general direct geodesic problem. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] azi1 azimuth at point 1 (degrees). * @param[in] flags bitor'ed combination of ::geod_flags; \e flags & * ::GEOD_ARCMODE determines the meaning of \e s12_a12 and \e flags & * ::GEOD_LONG_UNROLL "unrolls" \e lon2. * @param[in] s12_a12 if \e flags & ::GEOD_ARCMODE is 0, this is the distance * from point 1 to point 2 (meters); otherwise it is the arc length * from point 1 to point 2 (degrees); it can be negative. * @param[out] plat2 pointer to the latitude of point 2 (degrees). * @param[out] plon2 pointer to the longitude of point 2 (degrees). * @param[out] pazi2 pointer to the (forward) azimuth at point 2 (degrees). * @param[out] ps12 pointer to the distance from point 1 to point 2 * (meters). * @param[out] pm12 pointer to the reduced length of geodesic (meters). * @param[out] pM12 pointer to the geodesic scale of point 2 relative to * point 1 (dimensionless). * @param[out] pM21 pointer to the geodesic scale of point 1 relative to * point 2 (dimensionless). * @param[out] pS12 pointer to the area under the geodesic * (meters<sup>2</sup>). * @return \e a12 arc length from point 1 to point 2 (degrees). * * \e g must have been initialized with a call to geod_init(). \e lat1 * should be in the range [&minus;90&deg;, 90&deg;]. The function value \e * a12 equals \e s12_a12 if \e flags & ::GEOD_ARCMODE. Any of the "return" * arguments, \e plat2, etc., may be replaced by 0, if you do not need some * quantities computed. * * With \e flags & ::GEOD_LONG_UNROLL bit set, the longitude is "unrolled" so * that the quantity \e lon2 &minus; \e lon1 indicates how many times and in * what sense the geodesic encircles the ellipsoid. **********************************************************************/ double GEOD_DLL geod_gendirect(const struct geod_geodesic* g, double lat1, double lon1, double azi1, unsigned flags, double s12_a12, double* plat2, double* plon2, double* pazi2, double* ps12, double* pm12, double* pM12, double* pM21, double* pS12); /** * Solve the inverse geodesic problem. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] lat2 latitude of point 2 (degrees). * @param[in] lon2 longitude of point 2 (degrees). * @param[out] ps12 pointer to the distance from point 1 to point 2 * (meters). * @param[out] pazi1 pointer to the azimuth at point 1 (degrees). * @param[out] pazi2 pointer to the (forward) azimuth at point 2 (degrees). * * \e g must have been initialized with a call to geod_init(). \e lat1 and * \e lat2 should be in the range [&minus;90&deg;, 90&deg;]. The values of * \e azi1 and \e azi2 returned are in the range [&minus;180&deg;, 180&deg;]. * Any of the "return" arguments, \e ps12, etc., may be replaced by 0, if you * do not need some quantities computed. * * If either point is at a pole, the azimuth is defined by keeping the * longitude fixed, writing \e lat = &plusmn;(90&deg; &minus; &epsilon;), and * taking the limit &epsilon; &rarr; 0+. * * The solution to the inverse problem is found using Newton's method. If * this fails to converge (this is very unlikely in geodetic applications * but does occur for very eccentric ellipsoids), then the bisection method * is used to refine the solution. * * Example, determine the distance between JFK and Singapore Changi Airport: @code{.c} struct geod_geodesic g; double s12; geod_init(&g, 6378137, 1/298.257223563); geod_inverse(&g, 40.64, -73.78, 1.36, 103.99, &s12, 0, 0); printf("%.3f\n", s12); @endcode **********************************************************************/ void GEOD_DLL geod_inverse(const struct geod_geodesic* g, double lat1, double lon1, double lat2, double lon2, double* ps12, double* pazi1, double* pazi2); /** * The general inverse geodesic calculation. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] lat2 latitude of point 2 (degrees). * @param[in] lon2 longitude of point 2 (degrees). * @param[out] ps12 pointer to the distance from point 1 to point 2 * (meters). * @param[out] pazi1 pointer to the azimuth at point 1 (degrees). * @param[out] pazi2 pointer to the (forward) azimuth at point 2 (degrees). * @param[out] pm12 pointer to the reduced length of geodesic (meters). * @param[out] pM12 pointer to the geodesic scale of point 2 relative to * point 1 (dimensionless). * @param[out] pM21 pointer to the geodesic scale of point 1 relative to * point 2 (dimensionless). * @param[out] pS12 pointer to the area under the geodesic * (meters<sup>2</sup>). * @return \e a12 arc length from point 1 to point 2 (degrees). * * \e g must have been initialized with a call to geod_init(). \e lat1 and * \e lat2 should be in the range [&minus;90&deg;, 90&deg;]. Any of the * "return" arguments \e ps12, etc., may be replaced by 0, if you do not need * some quantities computed. **********************************************************************/ double GEOD_DLL geod_geninverse(const struct geod_geodesic* g, double lat1, double lon1, double lat2, double lon2, double* ps12, double* pazi1, double* pazi2, double* pm12, double* pM12, double* pM21, double* pS12); /** * Initialize a geod_geodesicline object. * * @param[out] l a pointer to the object to be initialized. * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] azi1 azimuth at point 1 (degrees). * @param[in] caps bitor'ed combination of ::geod_mask values specifying the * capabilities the geod_geodesicline object should possess, i.e., which * quantities can be returned in calls to geod_position() and * geod_genposition(). * * \e g must have been initialized with a call to geod_init(). \e lat1 * should be in the range [&minus;90&deg;, 90&deg;]. * * The ::geod_mask values are: * - \e caps |= ::GEOD_LATITUDE for the latitude \e lat2; this is * added automatically, * - \e caps |= ::GEOD_LONGITUDE for the latitude \e lon2, * - \e caps |= ::GEOD_AZIMUTH for the latitude \e azi2; this is * added automatically, * - \e caps |= ::GEOD_DISTANCE for the distance \e s12, * - \e caps |= ::GEOD_REDUCEDLENGTH for the reduced length \e m12, * - \e caps |= ::GEOD_GEODESICSCALE for the geodesic scales \e M12 * and \e M21, * - \e caps |= ::GEOD_AREA for the area \e S12, * - \e caps |= ::GEOD_DISTANCE_IN permits the length of the * geodesic to be given in terms of \e s12; without this capability the * length can only be specified in terms of arc length. * . * A value of \e caps = 0 is treated as ::GEOD_LATITUDE | ::GEOD_LONGITUDE | * ::GEOD_AZIMUTH | ::GEOD_DISTANCE_IN (to support the solution of the * "standard" direct problem). * * When initialized by this function, point 3 is undefined (l->s13 = l->a13 = * NaN). **********************************************************************/ void GEOD_DLL geod_lineinit(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double azi1, unsigned caps); /** * Initialize a geod_geodesicline object in terms of the direct geodesic * problem. * * @param[out] l a pointer to the object to be initialized. * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] azi1 azimuth at point 1 (degrees). * @param[in] s12 distance from point 1 to point 2 (meters); it can be * negative. * @param[in] caps bitor'ed combination of ::geod_mask values specifying the * capabilities the geod_geodesicline object should possess, i.e., which * quantities can be returned in calls to geod_position() and * geod_genposition(). * * This function sets point 3 of the geod_geodesicline to correspond to point * 2 of the direct geodesic problem. See geod_lineinit() for more * information. **********************************************************************/ void GEOD_DLL geod_directline(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double azi1, double s12, unsigned caps); /** * Initialize a geod_geodesicline object in terms of the direct geodesic * problem specified in terms of either distance or arc length. * * @param[out] l a pointer to the object to be initialized. * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] azi1 azimuth at point 1 (degrees). * @param[in] flags either ::GEOD_NOFLAGS or ::GEOD_ARCMODE to determining * the meaning of the \e s12_a12. * @param[in] s12_a12 if \e flags = ::GEOD_NOFLAGS, this is the distance * from point 1 to point 2 (meters); if \e flags = ::GEOD_ARCMODE, it is * the arc length from point 1 to point 2 (degrees); it can be * negative. * @param[in] caps bitor'ed combination of ::geod_mask values specifying the * capabilities the geod_geodesicline object should possess, i.e., which * quantities can be returned in calls to geod_position() and * geod_genposition(). * * This function sets point 3 of the geod_geodesicline to correspond to point * 2 of the direct geodesic problem. See geod_lineinit() for more * information. **********************************************************************/ void GEOD_DLL geod_gendirectline(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double azi1, unsigned flags, double s12_a12, unsigned caps); /** * Initialize a geod_geodesicline object in terms of the inverse geodesic * problem. * * @param[out] l a pointer to the object to be initialized. * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lat1 latitude of point 1 (degrees). * @param[in] lon1 longitude of point 1 (degrees). * @param[in] lat2 latitude of point 2 (degrees). * @param[in] lon2 longitude of point 2 (degrees). * @param[in] caps bitor'ed combination of ::geod_mask values specifying the * capabilities the geod_geodesicline object should possess, i.e., which * quantities can be returned in calls to geod_position() and * geod_genposition(). * * This function sets point 3 of the geod_geodesicline to correspond to point * 2 of the inverse geodesic problem. See geod_lineinit() for more * information. **********************************************************************/ void GEOD_DLL geod_inverseline(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double lat2, double lon2, unsigned caps); /** * Compute the position along a geod_geodesicline. * * @param[in] l a pointer to the geod_geodesicline object specifying the * geodesic line. * @param[in] s12 distance from point 1 to point 2 (meters); it can be * negative. * @param[out] plat2 pointer to the latitude of point 2 (degrees). * @param[out] plon2 pointer to the longitude of point 2 (degrees); requires * that \e l was initialized with \e caps |= ::GEOD_LONGITUDE. * @param[out] pazi2 pointer to the (forward) azimuth at point 2 (degrees). * * \e l must have been initialized with a call, e.g., to geod_lineinit(), * with \e caps |= ::GEOD_DISTANCE_IN (or \e caps = 0). The values of \e * lon2 and \e azi2 returned are in the range [&minus;180&deg;, 180&deg;]. * Any of the "return" arguments \e plat2, etc., may be replaced by 0, if you * do not need some quantities computed. * * Example, compute way points between JFK and Singapore Changi Airport * the "obvious" way using geod_direct(): @code{.c} struct geod_geodesic g; double s12, azi1, lat[101], lon[101]; int i; geod_init(&g, 6378137, 1/298.257223563); geod_inverse(&g, 40.64, -73.78, 1.36, 103.99, &s12, &azi1, 0); for (i = 0; i < 101; ++i) { geod_direct(&g, 40.64, -73.78, azi1, i * s12 * 0.01, lat + i, lon + i, 0); printf("%.5f %.5f\n", lat[i], lon[i]); } @endcode * A faster way using geod_position(): @code{.c} struct geod_geodesic g; struct geod_geodesicline l; double lat[101], lon[101]; int i; geod_init(&g, 6378137, 1/298.257223563); geod_inverseline(&l, &g, 40.64, -73.78, 1.36, 103.99, 0); for (i = 0; i <= 100; ++i) { geod_position(&l, i * l.s13 * 0.01, lat + i, lon + i, 0); printf("%.5f %.5f\n", lat[i], lon[i]); } @endcode **********************************************************************/ void GEOD_DLL geod_position(const struct geod_geodesicline* l, double s12, double* plat2, double* plon2, double* pazi2); /** * The general position function. * * @param[in] l a pointer to the geod_geodesicline object specifying the * geodesic line. * @param[in] flags bitor'ed combination of ::geod_flags; \e flags & * ::GEOD_ARCMODE determines the meaning of \e s12_a12 and \e flags & * ::GEOD_LONG_UNROLL "unrolls" \e lon2; if \e flags & ::GEOD_ARCMODE is 0, * then \e l must have been initialized with \e caps |= ::GEOD_DISTANCE_IN. * @param[in] s12_a12 if \e flags & ::GEOD_ARCMODE is 0, this is the * distance from point 1 to point 2 (meters); otherwise it is the * arc length from point 1 to point 2 (degrees); it can be * negative. * @param[out] plat2 pointer to the latitude of point 2 (degrees). * @param[out] plon2 pointer to the longitude of point 2 (degrees); requires * that \e l was initialized with \e caps |= ::GEOD_LONGITUDE. * @param[out] pazi2 pointer to the (forward) azimuth at point 2 (degrees). * @param[out] ps12 pointer to the distance from point 1 to point 2 * (meters); requires that \e l was initialized with \e caps |= * ::GEOD_DISTANCE. * @param[out] pm12 pointer to the reduced length of geodesic (meters); * requires that \e l was initialized with \e caps |= ::GEOD_REDUCEDLENGTH. * @param[out] pM12 pointer to the geodesic scale of point 2 relative to * point 1 (dimensionless); requires that \e l was initialized with \e caps * |= ::GEOD_GEODESICSCALE. * @param[out] pM21 pointer to the geodesic scale of point 1 relative to * point 2 (dimensionless); requires that \e l was initialized with \e caps * |= ::GEOD_GEODESICSCALE. * @param[out] pS12 pointer to the area under the geodesic * (meters<sup>2</sup>); requires that \e l was initialized with \e caps |= * ::GEOD_AREA. * @return \e a12 arc length from point 1 to point 2 (degrees). * * \e l must have been initialized with a call to geod_lineinit() with \e * caps |= ::GEOD_DISTANCE_IN. The value \e azi2 returned is in the range * [&minus;180&deg;, 180&deg;]. Any of the "return" arguments \e plat2, * etc., may be replaced by 0, if you do not need some quantities * computed. Requesting a value which \e l is not capable of computing * is not an error; the corresponding argument will not be altered. * * With \e flags & ::GEOD_LONG_UNROLL bit set, the longitude is "unrolled" so * that the quantity \e lon2 &minus; \e lon1 indicates how many times and in * what sense the geodesic encircles the ellipsoid. * * Example, compute way points between JFK and Singapore Changi Airport using * geod_genposition(). In this example, the points are evenly spaced in arc * length (and so only approximately equally spaced in distance). This is * faster than using geod_position() and would be appropriate if drawing the * path on a map. @code{.c} struct geod_geodesic g; struct geod_geodesicline l; double lat[101], lon[101]; int i; geod_init(&g, 6378137, 1/298.257223563); geod_inverseline(&l, &g, 40.64, -73.78, 1.36, 103.99, GEOD_LATITUDE | GEOD_LONGITUDE); for (i = 0; i <= 100; ++i) { geod_genposition(&l, GEOD_ARCMODE, i * l.a13 * 0.01, lat + i, lon + i, 0, 0, 0, 0, 0, 0); printf("%.5f %.5f\n", lat[i], lon[i]); } @endcode **********************************************************************/ double GEOD_DLL geod_genposition(const struct geod_geodesicline* l, unsigned flags, double s12_a12, double* plat2, double* plon2, double* pazi2, double* ps12, double* pm12, double* pM12, double* pM21, double* pS12); /** * Specify position of point 3 in terms of distance. * * @param[in,out] l a pointer to the geod_geodesicline object. * @param[in] s13 the distance from point 1 to point 3 (meters); it * can be negative. * * This is only useful if the geod_geodesicline object has been constructed * with \e caps |= ::GEOD_DISTANCE_IN. **********************************************************************/ void GEOD_DLL geod_setdistance(struct geod_geodesicline* l, double s13); /** * Specify position of point 3 in terms of either distance or arc length. * * @param[in,out] l a pointer to the geod_geodesicline object. * @param[in] flags either ::GEOD_NOFLAGS or ::GEOD_ARCMODE to determining * the meaning of the \e s13_a13. * @param[in] s13_a13 if \e flags = ::GEOD_NOFLAGS, this is the distance * from point 1 to point 3 (meters); if \e flags = ::GEOD_ARCMODE, it is * the arc length from point 1 to point 3 (degrees); it can be * negative. * * If flags = ::GEOD_NOFLAGS, this calls geod_setdistance(). If flags = * ::GEOD_ARCMODE, the \e s13 is only set if the geod_geodesicline object has * been constructed with \e caps |= ::GEOD_DISTANCE. **********************************************************************/ void GEOD_DLL geod_gensetdistance(struct geod_geodesicline* l, unsigned flags, double s13_a13); /** * Initialize a geod_polygon object. * * @param[out] p a pointer to the object to be initialized. * @param[in] polylinep non-zero if a polyline instead of a polygon. * * If \e polylinep is zero, then the sequence of vertices and edges added by * geod_polygon_addpoint() and geod_polygon_addedge() define a polygon and * the perimeter and area are returned by geod_polygon_compute(). If \e * polylinep is non-zero, then the vertices and edges define a polyline and * only the perimeter is returned by geod_polygon_compute(). * * The area and perimeter are accumulated at two times the standard floating * point precision to guard against the loss of accuracy with many-sided * polygons. At any point you can ask for the perimeter and area so far. * * An example of the use of this function is given in the documentation for * geod_polygon_compute(). **********************************************************************/ void GEOD_DLL geod_polygon_init(struct geod_polygon* p, int polylinep); /** * Clear the polygon, allowing a new polygon to be started. * * @param[in,out] p a pointer to the object to be cleared. **********************************************************************/ void GEOD_DLL geod_polygon_clear(struct geod_polygon* p); /** * Add a point to the polygon or polyline. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in,out] p a pointer to the geod_polygon object specifying the * polygon. * @param[in] lat the latitude of the point (degrees). * @param[in] lon the longitude of the point (degrees). * * \e g and \e p must have been initialized with calls to geod_init() and * geod_polygon_init(), respectively. The same \e g must be used for all the * points and edges in a polygon. \e lat should be in the range * [&minus;90&deg;, 90&deg;]. * * An example of the use of this function is given in the documentation for * geod_polygon_compute(). **********************************************************************/ void GEOD_DLL geod_polygon_addpoint(const struct geod_geodesic* g, struct geod_polygon* p, double lat, double lon); /** * Add an edge to the polygon or polyline. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in,out] p a pointer to the geod_polygon object specifying the * polygon. * @param[in] azi azimuth at current point (degrees). * @param[in] s distance from current point to next point (meters). * * \e g and \e p must have been initialized with calls to geod_init() and * geod_polygon_init(), respectively. The same \e g must be used for all the * points and edges in a polygon. This does nothing if no points have been * added yet. The \e lat and \e lon fields of \e p give the location of the * new vertex. **********************************************************************/ void GEOD_DLL geod_polygon_addedge(const struct geod_geodesic* g, struct geod_polygon* p, double azi, double s); /** * Return the results for a polygon. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] p a pointer to the geod_polygon object specifying the polygon. * @param[in] reverse if non-zero then clockwise (instead of * counter-clockwise) traversal counts as a positive area. * @param[in] sign if non-zero then return a signed result for the area if * the polygon is traversed in the "wrong" direction instead of returning * the area for the rest of the earth. * @param[out] pA pointer to the area of the polygon (meters<sup>2</sup>); * only set if \e polyline is non-zero in the call to geod_polygon_init(). * @param[out] pP pointer to the perimeter of the polygon or length of the * polyline (meters). * @return the number of points. * * The area and perimeter are accumulated at two times the standard floating * point precision to guard against the loss of accuracy with many-sided * polygons. Arbitrarily complex polygons are allowed. In the case of * self-intersecting polygons the area is accumulated "algebraically", e.g., * the areas of the 2 loops in a figure-8 polygon will partially cancel. * There's no need to "close" the polygon by repeating the first vertex. Set * \e pA or \e pP to zero, if you do not want the corresponding quantity * returned. * * More points can be added to the polygon after this call. * * Example, compute the perimeter and area of the geodesic triangle with * vertices (0&deg;N,0&deg;E), (0&deg;N,90&deg;E), (90&deg;N,0&deg;E). @code{.c} double A, P; int n; struct geod_geodesic g; struct geod_polygon p; geod_init(&g, 6378137, 1/298.257223563); geod_polygon_init(&p, 0); geod_polygon_addpoint(&g, &p, 0, 0); geod_polygon_addpoint(&g, &p, 0, 90); geod_polygon_addpoint(&g, &p, 90, 0); n = geod_polygon_compute(&g, &p, 0, 1, &A, &P); printf("%d %.8f %.3f\n", n, P, A); @endcode **********************************************************************/ unsigned GEOD_DLL geod_polygon_compute(const struct geod_geodesic* g, const struct geod_polygon* p, int reverse, int sign, double* pA, double* pP); /** * Return the results assuming a tentative final test point is added; * however, the data for the test point is not saved. This lets you report a * running result for the perimeter and area as the user moves the mouse * cursor. Ordinary floating point arithmetic is used to accumulate the data * for the test point; thus the area and perimeter returned are less accurate * than if geod_polygon_addpoint() and geod_polygon_compute() are used. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] p a pointer to the geod_polygon object specifying the polygon. * @param[in] lat the latitude of the test point (degrees). * @param[in] lon the longitude of the test point (degrees). * @param[in] reverse if non-zero then clockwise (instead of * counter-clockwise) traversal counts as a positive area. * @param[in] sign if non-zero then return a signed result for the area if * the polygon is traversed in the "wrong" direction instead of returning * the area for the rest of the earth. * @param[out] pA pointer to the area of the polygon (meters<sup>2</sup>); * only set if \e polyline is non-zero in the call to geod_polygon_init(). * @param[out] pP pointer to the perimeter of the polygon or length of the * polyline (meters). * @return the number of points. * * \e lat should be in the range [&minus;90&deg;, 90&deg;]. **********************************************************************/ unsigned GEOD_DLL geod_polygon_testpoint(const struct geod_geodesic* g, const struct geod_polygon* p, double lat, double lon, int reverse, int sign, double* pA, double* pP); /** * Return the results assuming a tentative final test point is added via an * azimuth and distance; however, the data for the test point is not saved. * This lets you report a running result for the perimeter and area as the * user moves the mouse cursor. Ordinary floating point arithmetic is used * to accumulate the data for the test point; thus the area and perimeter * returned are less accurate than if geod_polygon_addedge() and * geod_polygon_compute() are used. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] p a pointer to the geod_polygon object specifying the polygon. * @param[in] azi azimuth at current point (degrees). * @param[in] s distance from current point to final test point (meters). * @param[in] reverse if non-zero then clockwise (instead of * counter-clockwise) traversal counts as a positive area. * @param[in] sign if non-zero then return a signed result for the area if * the polygon is traversed in the "wrong" direction instead of returning * the area for the rest of the earth. * @param[out] pA pointer to the area of the polygon (meters<sup>2</sup>); * only set if \e polyline is non-zero in the call to geod_polygon_init(). * @param[out] pP pointer to the perimeter of the polygon or length of the * polyline (meters). * @return the number of points. **********************************************************************/ unsigned GEOD_DLL geod_polygon_testedge(const struct geod_geodesic* g, const struct geod_polygon* p, double azi, double s, int reverse, int sign, double* pA, double* pP); /** * A simple interface for computing the area of a geodesic polygon. * * @param[in] g a pointer to the geod_geodesic object specifying the * ellipsoid. * @param[in] lats an array of latitudes of the polygon vertices (degrees). * @param[in] lons an array of longitudes of the polygon vertices (degrees). * @param[in] n the number of vertices. * @param[out] pA pointer to the area of the polygon (meters<sup>2</sup>). * @param[out] pP pointer to the perimeter of the polygon (meters). * * \e lats should be in the range [&minus;90&deg;, 90&deg;]. * * Arbitrarily complex polygons are allowed. In the case self-intersecting * of polygons the area is accumulated "algebraically", e.g., the areas of * the 2 loops in a figure-8 polygon will partially cancel. There's no need * to "close" the polygon by repeating the first vertex. The area returned * is signed with counter-clockwise traversal being treated as positive. * * Example, compute the area of Antarctica: @code{.c} double lats[] = {-72.9, -71.9, -74.9, -74.3, -77.5, -77.4, -71.7, -65.9, -65.7, -66.6, -66.9, -69.8, -70.0, -71.0, -77.3, -77.9, -74.7}, lons[] = {-74, -102, -102, -131, -163, 163, 172, 140, 113, 88, 59, 25, -4, -14, -33, -46, -61}; struct geod_geodesic g; double A, P; geod_init(&g, 6378137, 1/298.257223563); geod_polygonarea(&g, lats, lons, (sizeof lats) / (sizeof lats[0]), &A, &P); printf("%.0f %.2f\n", A, P); @endcode **********************************************************************/ void GEOD_DLL geod_polygonarea(const struct geod_geodesic* g, double lats[], double lons[], int n, double* pA, double* pP); /** * mask values for the \e caps argument to geod_lineinit(). **********************************************************************/ enum geod_mask { GEOD_NONE = 0U, /**< Calculate nothing */ GEOD_LATITUDE = 1U<<7 | 0U, /**< Calculate latitude */ GEOD_LONGITUDE = 1U<<8 | 1U<<3, /**< Calculate longitude */ GEOD_AZIMUTH = 1U<<9 | 0U, /**< Calculate azimuth */ GEOD_DISTANCE = 1U<<10 | 1U<<0, /**< Calculate distance */ GEOD_DISTANCE_IN = 1U<<11 | 1U<<0 | 1U<<1,/**< Allow distance as input */ GEOD_REDUCEDLENGTH= 1U<<12 | 1U<<0 | 1U<<2,/**< Calculate reduced length */ GEOD_GEODESICSCALE= 1U<<13 | 1U<<0 | 1U<<2,/**< Calculate geodesic scale */ GEOD_AREA = 1U<<14 | 1U<<4, /**< Calculate reduced length */ GEOD_ALL = 0x7F80U| 0x1FU /**< Calculate everything */ }; /** * flag values for the \e flags argument to geod_gendirect() and * geod_genposition() **********************************************************************/ enum geod_flags { GEOD_NOFLAGS = 0U, /**< No flags */ GEOD_ARCMODE = 1U<<0, /**< Position given in terms of arc distance */ GEOD_LONG_UNROLL = 1U<<15 /**< Unroll the longitude */ }; #if defined(__cplusplus) } #endif #endif
h
PROJ
data/projects/PROJ/src/malloc.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Memory management for proj.4. * This version includes an implementation of generic destructors, * for memory deallocation for the large majority of PJ-objects * that do not allocate anything else than the PJ-object itself, * and its associated opaque object - i.e. no additional malloc'ed * memory inside the opaque object. * * Author: Gerald I. Evenden (Original proj.4 author), * Frank Warmerdam (2000) pj_malloc? * Thomas Knudsen (2016) - freeup/dealloc parts * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * Copyright (c) 2016, 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. *****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif /* allocate and deallocate memory */ /* These routines are used so that applications can readily replace ** projection system memory allocation/deallocation call with custom ** application procedures. */ #include <errno.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <new> #include "proj/internal/io_internal.hpp" #include "filemanager.hpp" #include "grids.hpp" #include "proj.h" #include "proj_internal.h" using namespace NS_PROJ; /**********************************************************************/ char *pj_strdup(const char *str) /**********************************************************************/ { size_t len = strlen(str) + 1; char *dup = static_cast<char *>(malloc(len)); if (dup) memcpy(dup, str, len); return dup; } /*****************************************************************************/ void *free_params(PJ_CONTEXT *ctx, paralist *start, int errlev) { /***************************************************************************** Companion to pj_default_destructor (below). Deallocates a linked list of "+proj=xxx" initialization parameters. Also called from pj_init_ctx when encountering errors before the PJ proper is allocated. ******************************************************************************/ paralist *t, *n; for (t = start; t; t = n) { n = t->next; free(t); } proj_context_errno_set(ctx, errlev); return (void *)nullptr; } /************************************************************************/ /* proj_destroy() */ /* */ /* This is the application callable entry point for destroying */ /* a projection definition. It does work generic to all */ /* projection types, and then calls the projection specific */ /* free function, P->destructor(), to do local work. */ /* In most cases P->destructor()==pj_default_destructor. */ /************************************************************************/ PJ *proj_destroy(PJ *P) { if (nullptr == P || !P->destructor) return nullptr; /* free projection parameters - all the hard work is done by */ /* pj_default_destructor, which is supposed */ /* to be called as the last step of the local destructor */ /* pointed to by P->destructor. In most cases, */ /* pj_default_destructor actually *is* what is pointed to */ P->destructor(P, proj_errno(P)); return nullptr; } /*****************************************************************************/ // cppcheck-suppress uninitMemberVar PJconsts::PJconsts() : destructor(pj_default_destructor) {} /*****************************************************************************/ /*****************************************************************************/ PJ *pj_new() { /*****************************************************************************/ return new (std::nothrow) PJ(); } /*****************************************************************************/ PJ *pj_default_destructor(PJ *P, int errlev) { /* Destructor */ /***************************************************************************** Does memory deallocation for "plain" PJ objects, i.e. that vast majority of PJs where the opaque object does not contain any additionally allocated memory below the P->opaque level. ******************************************************************************/ /* Even if P==0, we set the errlev on pj_error and the default context */ /* Note that both, in the multithreaded case, may then contain undefined */ /* values. This is expected behavior. For MT have one ctx per thread */ if (0 != errlev) proj_context_errno_set(pj_get_ctx(P), errlev); if (nullptr == P) return nullptr; free(P->def_size); free(P->def_shape); free(P->def_spherification); free(P->def_ellps); delete static_cast<ListOfHGrids *>(P->hgrids_legacy); delete static_cast<ListOfVGrids *>(P->vgrids_legacy); /* We used to call free( P->catalog ), but this will leak */ /* memory. The safe way to clear catalog and grid is to call */ /* pj_gc_unloadall(pj_get_default_ctx()); and freeate_grids(); */ /* TODO: we should probably have a public pj_cleanup() method to do all */ /* that */ /* free the interface to Charles Karney's geodesic library */ free(P->geod); /* free parameter list elements */ free_params(pj_get_ctx(P), P->params, errlev); free(P->def_full); /* free the cs2cs emulation elements */ proj_destroy(P->axisswap); proj_destroy(P->helmert); proj_destroy(P->cart); proj_destroy(P->cart_wgs84); proj_destroy(P->hgridshift); proj_destroy(P->vgridshift); free(static_cast<struct pj_opaque *>(P->opaque)); delete P; return nullptr; } /*****************************************************************************/ void proj_cleanup() { /*****************************************************************************/ // Close the database context of the default PJ_CONTEXT auto ctx = pj_get_default_ctx(); ctx->iniFileLoaded = false; auto cpp_context = ctx->cpp_context; if (cpp_context) { cpp_context->closeDb(); } pj_clear_initcache(); FileManager::clearMemoryCache(); pj_clear_hgridshift_knowngrids_cache(); pj_clear_vgridshift_knowngrids_cache(); pj_clear_gridshift_knowngrids_cache(); pj_clear_sqlite_cache(); }
cpp
PROJ
data/projects/PROJ/src/mlfn.cpp
#include "proj_internal.h" #include <math.h> /* meridional distance for ellipsoid and inverse using 6th-order expansion in ** the third flattening n. This gives full double precision accuracy for |f| ** <= 1/150. */ #define Lmax 6 // Evaluation sum(p[i] * x^i, i, 0, N) via Horner's method. N.B. p is of // length N+1. static double polyval(double x, const double p[], int N) { double y = N < 0 ? 0 : p[N]; for (; N > 0;) y = y * x + p[--N]; return y; } // Evaluate y = sum(c[k] * sin((2*k+2) * zeta), k, 0, K-1) static double clenshaw(double szeta, double czeta, const double c[], int K) { // Approx operation count = (K + 5) mult and (2 * K + 2) add double u0 = 0, u1 = 0, // accumulators for sum X = 2 * (czeta - szeta) * (czeta + szeta); // 2 * cos(2*zeta) for (; K > 0;) { double t = X * u0 - u1 + c[--K]; u1 = u0; u0 = t; } return 2 * szeta * czeta * u0; // sin(2*zeta) * u0 } double *pj_enfn(double n) { // Expansion of (quarter meridian) / ((a+b)/2 * pi/2) as series in n^2; // these coefficients are ( (2*k - 3)!! / (2*k)!! )^2 for k = 0..3 static const double coeff_rad[] = {1, 1.0 / 4, 1.0 / 64, 1.0 / 256}; // Coefficients to convert phi to mu, Eq. A5 in arXiv:2212.05818 // with 0 terms dropped static const double coeff_mu_phi[] = { -3.0 / 2, 9.0 / 16, -3.0 / 32, 15.0 / 16, -15.0 / 32, 135.0 / 2048, -35.0 / 48, 105.0 / 256, 315.0 / 512, -189.0 / 512, -693.0 / 1280, 1001.0 / 2048, }; // Coefficients to convert mu to phi, Eq. A6 in arXiv:2212.05818 // with 0 terms dropped static const double coeff_phi_mu[] = { 3.0 / 2, -27.0 / 32, 269.0 / 512, 21.0 / 16, -55.0 / 32, 6759.0 / 4096, 151.0 / 96, -417.0 / 128, 1097.0 / 512, -15543.0 / 2560, 8011.0 / 2560, 293393.0 / 61440, }; double n2 = n * n, d = n, *en; // 2*Lmax for the Fourier coeffs for each direction of conversion + 1 for // overall multiplier. en = (double *)malloc((2 * Lmax + 1) * sizeof(double)); if (nullptr == en) return nullptr; en[0] = polyval(n2, coeff_rad, Lmax / 2) / (1 + n); for (int l = 0, o = 0; l < Lmax; ++l) { int m = (Lmax - l - 1) / 2; en[l + 1] = d * polyval(n2, coeff_mu_phi + o, m); en[l + 1 + Lmax] = d * polyval(n2, coeff_phi_mu + o, m); d *= n; o += m + 1; } return en; } double pj_mlfn(double phi, double sphi, double cphi, const double *en) { return en[0] * (phi + clenshaw(sphi, cphi, en + 1, Lmax)); } double pj_inv_mlfn(double mu, const double *en) { mu /= en[0]; return mu + clenshaw(sin(mu), cos(mu), en + 1 + Lmax, Lmax); }
cpp
PROJ
data/projects/PROJ/src/dmstor.cpp
/* Convert DMS string to radians */ #include <ctype.h> #include <math.h> #include <stdlib.h> #include <string.h> #include "proj.h" #include "proj_internal.h" static double proj_strtod(char *nptr, char **endptr); /* following should be sufficient for all but the ridiculous */ #define MAX_WORK 64 static const char *sym = "NnEeSsWw"; static const double vm[] = {DEG_TO_RAD, .0002908882086657216, .0000048481368110953599}; /* byte sequence for Degree Sign U+00B0 in UTF-8. */ static constexpr char DEG_SIGN1 = '\xc2'; static constexpr char DEG_SIGN2 = '\xb0'; double dmstor(const char *is, char **rs) { return dmstor_ctx(pj_get_default_ctx(), is, rs); } double dmstor_ctx(PJ_CONTEXT *ctx, const char *is, char **rs) { int n, nl; char *s, work[MAX_WORK]; const char *p; double v, tv; if (rs) *rs = (char *)is; /* copy string into work space */ while (isspace(*is)) ++is; n = MAX_WORK; s = work; p = (char *)is; /* * Copy characters into work until we hit a non-printable character or run * out of space in the buffer. Make a special exception for the bytes of * the Degree Sign in UTF-8. * * It is possible that a really odd input (like lots of leading zeros) * could be truncated in copying into work. But ... */ while ((isgraph(*p) || *p == DEG_SIGN1 || *p == DEG_SIGN2) && --n) *s++ = *p++; *s = '\0'; int sign = *(s = work); if (sign == '+' || sign == '-') s++; else sign = '+'; v = 0.; for (nl = 0; nl < 3; nl = n + 1) { if (!(isdigit(*s) || *s == '.')) break; if ((tv = proj_strtod(s, &s)) == HUGE_VAL) return tv; int adv = 1; if (*s == 'D' || *s == 'd' || *s == DEG_SIGN2) { /* * Accept \xb0 as a single-byte degree symbol. This byte is the * degree symbol in various single-byte encodings: multiple ISO * 8859 parts, several Windows code pages and others. */ n = 0; } else if (*s == '\'') { n = 1; } else if (*s == '"') { n = 2; } else if (s[0] == DEG_SIGN1 && s[1] == DEG_SIGN2) { /* degree symbol in UTF-8 */ n = 0; adv = 2; } else if (*s == 'r' || *s == 'R') { if (nl) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return HUGE_VAL; } ++s; v = tv; n = 4; continue; } else { v += tv * vm[nl]; n = 4; continue; } if (n < nl) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); return HUGE_VAL; } v += tv * vm[n]; s += adv; } /* postfix sign */ if (*s && (p = strchr(sym, *s))) { sign = (p - sym) >= 4 ? '-' : '+'; ++s; } if (sign == '-') v = -v; if (rs) /* return point of next char after valid string */ *rs = (char *)is + (s - work); return v; } static double proj_strtod(char *nptr, char **endptr) { char c, *cp = nptr; double result; /* * Scan for characters which cause problems with VC++ strtod() */ while ((c = *cp) != '\0') { if (c == 'd' || c == 'D') { /* * Found one, so NUL it out, call strtod(), * then restore it and return */ *cp = '\0'; result = strtod(nptr, endptr); *cp = c; return result; } ++cp; } /* no offending characters, just handle normally */ return pj_strtod(nptr, endptr); }
cpp
PROJ
data/projects/PROJ/src/wkt_parser.hpp
/****************************************************************************** * Project: PROJ * Purpose: WKT parser common routines * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2018 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. ****************************************************************************/ #ifndef PJ_WKT_PARSER_H_INCLUDED #define PJ_WKT_PARSER_H_INCLUDED //! @cond Doxygen_Suppress #include <string> struct pj_wkt_parse_context { const char *pszInput = nullptr; const char *pszLastSuccess = nullptr; const char *pszNext = nullptr; std::string errorMsg{}; pj_wkt_parse_context() = default; pj_wkt_parse_context(const pj_wkt_parse_context &) = delete; pj_wkt_parse_context &operator=(const pj_wkt_parse_context &) = delete; }; void pj_wkt_error(pj_wkt_parse_context *context, const char *msg); //! @endcond #endif // PJ_WKT_PARSER_H_INCLUDED
hpp
PROJ
data/projects/PROJ/src/wkt2_parser.cpp
/****************************************************************************** * Project: PROJ * Purpose: WKT2 parser grammar * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2018 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. ****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/internal/internal.hpp" #include <algorithm> #include <cctype> #include <cstring> #include <string> #include "proj_constants.h" #include "wkt2_parser.h" #include "wkt_parser.hpp" using namespace NS_PROJ::internal; //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- struct pj_wkt2_parse_context : public pj_wkt_parse_context {}; // --------------------------------------------------------------------------- void pj_wkt2_error(pj_wkt2_parse_context *context, const char *msg) { pj_wkt_error(context, msg); } // --------------------------------------------------------------------------- std::string pj_wkt2_parse(const std::string &wkt) { pj_wkt2_parse_context context; context.pszInput = wkt.c_str(); context.pszLastSuccess = wkt.c_str(); context.pszNext = wkt.c_str(); if (pj_wkt2_parse(&context) != 0) { return context.errorMsg; } return std::string(); } // --------------------------------------------------------------------------- typedef struct { const char *pszToken; int nTokenVal; } wkt2_tokens; #define PAIR(X) \ { \ #X, T_##X \ } static const wkt2_tokens tokens[] = { PAIR(PARAMETER), PAIR(PROJECTION), PAIR(DATUM), PAIR(SPHEROID), PAIR(PRIMEM), PAIR(UNIT), PAIR(AXIS), PAIR(GEODCRS), PAIR(LENGTHUNIT), PAIR(ANGLEUNIT), PAIR(SCALEUNIT), PAIR(TIMEUNIT), PAIR(ELLIPSOID), PAIR(CS), PAIR(ID), PAIR(PROJCRS), PAIR(BASEGEODCRS), PAIR(MERIDIAN), PAIR(BEARING), PAIR(ORDER), PAIR(ANCHOR), PAIR(ANCHOREPOCH), PAIR(CONVERSION), PAIR(METHOD), PAIR(REMARK), PAIR(GEOGCRS), PAIR(BASEGEOGCRS), PAIR(SCOPE), PAIR(AREA), PAIR(BBOX), PAIR(CITATION), PAIR(URI), PAIR(VERTCRS), PAIR(VDATUM), PAIR(GEOIDMODEL), PAIR(COMPOUNDCRS), PAIR(PARAMETERFILE), PAIR(COORDINATEOPERATION), PAIR(SOURCECRS), PAIR(TARGETCRS), PAIR(INTERPOLATIONCRS), PAIR(OPERATIONACCURACY), PAIR(CONCATENATEDOPERATION), PAIR(STEP), PAIR(BOUNDCRS), PAIR(ABRIDGEDTRANSFORMATION), PAIR(DERIVINGCONVERSION), PAIR(TDATUM), PAIR(CALENDAR), PAIR(TIMEORIGIN), PAIR(TIMECRS), PAIR(VERTICALEXTENT), PAIR(TIMEEXTENT), PAIR(USAGE), PAIR(DYNAMIC), PAIR(FRAMEEPOCH), PAIR(MODEL), PAIR(VELOCITYGRID), PAIR(ENSEMBLE), PAIR(MEMBER), PAIR(ENSEMBLEACCURACY), PAIR(DERIVEDPROJCRS), PAIR(BASEPROJCRS), PAIR(EDATUM), PAIR(ENGCRS), PAIR(PDATUM), PAIR(PARAMETRICCRS), PAIR(PARAMETRICUNIT), PAIR(BASEVERTCRS), PAIR(BASEENGCRS), PAIR(BASEPARAMCRS), PAIR(BASETIMECRS), PAIR(GEODETICCRS), PAIR(GEODETICDATUM), PAIR(PROJECTEDCRS), PAIR(PRIMEMERIDIAN), PAIR(GEOGRAPHICCRS), PAIR(TRF), PAIR(VERTICALCRS), PAIR(VERTICALDATUM), PAIR(VRF), PAIR(TIMEDATUM), PAIR(TEMPORALQUANTITY), PAIR(ENGINEERINGDATUM), PAIR(ENGINEERINGCRS), PAIR(PARAMETRICDATUM), PAIR(EPOCH), PAIR(COORDEPOCH), PAIR(COORDINATEMETADATA), PAIR(POINTMOTIONOPERATION), PAIR(VERSION), PAIR(AXISMINVALUE), PAIR(AXISMAXVALUE), PAIR(RANGEMEANING), PAIR(exact), PAIR(wraparound), // CS types PAIR(AFFINE), PAIR(CARTESIAN), PAIR(CYLINDRICAL), PAIR(ELLIPSOIDAL), PAIR(LINEAR), PAIR(PARAMETRIC), PAIR(POLAR), PAIR(SPHERICAL), PAIR(VERTICAL), PAIR(TEMPORAL), PAIR(TEMPORALCOUNT), PAIR(TEMPORALMEASURE), PAIR(ORDINAL), PAIR(TEMPORALDATETIME), // Axis directions PAIR(NORTH), PAIR(NORTHNORTHEAST), PAIR(NORTHEAST), PAIR(EASTNORTHEAST), PAIR(EAST), PAIR(EASTSOUTHEAST), PAIR(SOUTHEAST), PAIR(SOUTHSOUTHEAST), PAIR(SOUTH), PAIR(SOUTHSOUTHWEST), PAIR(SOUTHWEST), PAIR(WESTSOUTHWEST), PAIR(WEST), PAIR(WESTNORTHWEST), PAIR(NORTHWEST), PAIR(NORTHNORTHWEST), PAIR(UP), PAIR(DOWN), PAIR(GEOCENTRICX), PAIR(GEOCENTRICY), PAIR(GEOCENTRICZ), PAIR(COLUMNPOSITIVE), PAIR(COLUMNNEGATIVE), PAIR(ROWPOSITIVE), PAIR(ROWNEGATIVE), PAIR(DISPLAYRIGHT), PAIR(DISPLAYLEFT), PAIR(DISPLAYUP), PAIR(DISPLAYDOWN), PAIR(FORWARD), PAIR(AFT), PAIR(PORT), PAIR(STARBOARD), PAIR(CLOCKWISE), PAIR(COUNTERCLOCKWISE), PAIR(TOWARDS), PAIR(AWAYFROM), PAIR(FUTURE), PAIR(PAST), PAIR(UNSPECIFIED), }; // --------------------------------------------------------------------------- int pj_wkt2_lex(YYSTYPE * /*pNode */, pj_wkt2_parse_context *context) { size_t i; const char *pszInput = context->pszNext; /* -------------------------------------------------------------------- */ /* Skip white space. */ /* -------------------------------------------------------------------- */ while (*pszInput == ' ' || *pszInput == '\t' || *pszInput == 10 || *pszInput == 13) pszInput++; context->pszLastSuccess = pszInput; if (*pszInput == '\0') { context->pszNext = pszInput; return EOF; } /* -------------------------------------------------------------------- */ /* Recognize node names. */ /* -------------------------------------------------------------------- */ if (isalpha(*pszInput)) { for (i = 0; i < sizeof(tokens) / sizeof(tokens[0]); i++) { if (ci_starts_with(pszInput, tokens[i].pszToken) && !isalpha(pszInput[strlen(tokens[i].pszToken)])) { context->pszNext = pszInput + strlen(tokens[i].pszToken); return tokens[i].nTokenVal; } } } /* -------------------------------------------------------------------- */ /* Recognize unsigned integer */ /* -------------------------------------------------------------------- */ if (*pszInput >= '0' && *pszInput <= '9') { // Special case for 1, 2, 3 if ((*pszInput == '1' || *pszInput == '2' || *pszInput == '3') && !(pszInput[1] >= '0' && pszInput[1] <= '9')) { context->pszNext = pszInput + 1; return *pszInput; } pszInput++; while (*pszInput >= '0' && *pszInput <= '9') pszInput++; context->pszNext = pszInput; return T_UNSIGNED_INTEGER_DIFFERENT_ONE_TWO_THREE; } /* -------------------------------------------------------------------- */ /* Recognize double quoted strings. */ /* -------------------------------------------------------------------- */ if (*pszInput == '"') { pszInput++; while (*pszInput != '\0') { if (*pszInput == '"') { if (pszInput[1] == '"') pszInput++; else break; } pszInput++; } if (*pszInput == '\0') { context->pszNext = pszInput; return EOF; } context->pszNext = pszInput + 1; return T_STRING; } // As used in examples of OGC 12-063r5 const char *startPrintedQuote = "\xE2\x80\x9C"; const char *endPrintedQuote = "\xE2\x80\x9D"; if (strncmp(pszInput, startPrintedQuote, 3) == 0) { context->pszNext = strstr(pszInput, endPrintedQuote); if (context->pszNext == nullptr) { context->pszNext = pszInput + strlen(pszInput); return EOF; } context->pszNext += 3; return T_STRING; } /* -------------------------------------------------------------------- */ /* Handle special tokens. */ /* -------------------------------------------------------------------- */ context->pszNext = pszInput + 1; return *pszInput; } //! @endcond
cpp
PROJ
data/projects/PROJ/src/deriv.cpp
/* dervative of (*P->fwd) projection */ #include <math.h> #include "proj.h" #include "proj_internal.h" int pj_deriv(PJ_LP lp, double h, const PJ *P, struct DERIVS *der) { PJ_XY t; /* get rid of constness until we can do it for real */ PJ *Q = (PJ *)P; if (nullptr == Q->fwd) return 1; lp.lam += h; lp.phi += h; if (fabs(lp.phi) > M_HALFPI) return 1; h += h; t = (*Q->fwd)(lp, Q); if (t.x == HUGE_VAL) return 1; der->x_l = t.x; der->y_p = t.y; der->x_p = t.x; der->y_l = t.y; lp.phi -= h; if (fabs(lp.phi) > M_HALFPI) return 1; t = (*Q->fwd)(lp, Q); if (t.x == HUGE_VAL) return 1; der->x_l += t.x; der->y_p -= t.y; der->x_p -= t.x; der->y_l += t.y; lp.lam -= h; t = (*Q->fwd)(lp, Q); if (t.x == HUGE_VAL) return 1; der->x_l -= t.x; der->y_p -= t.y; der->x_p -= t.x; der->y_l -= t.y; lp.phi += h; t = (*Q->fwd)(lp, Q); if (t.x == HUGE_VAL) return 1; der->x_l -= t.x; der->y_p += t.y; der->x_p += t.x; der->y_l -= t.y; h += h; der->x_l /= h; der->y_p /= h; der->x_p /= h; der->y_l /= h; return 0; }
cpp
PROJ
data/projects/PROJ/src/log.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of pj_log() function. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2010, 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. *****************************************************************************/ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proj.h" #include "proj_internal.h" /************************************************************************/ /* pj_stderr_logger() */ /************************************************************************/ void pj_stderr_logger(void *app_data, int level, const char *msg) { (void)app_data; (void)level; fprintf(stderr, "%s\n", msg); } /************************************************************************/ /* pj_log_active() */ /************************************************************************/ bool pj_log_active(PJ_CONTEXT *ctx, int level) { int debug_level = ctx->debug_level; int shutup_unless_errno_set = debug_level < 0; /* For negative debug levels, we first start logging when errno is set */ if (ctx->last_errno == 0 && shutup_unless_errno_set) return false; if (debug_level < 0) debug_level = -debug_level; if (level > debug_level) return false; return true; } /************************************************************************/ /* pj_vlog() */ /************************************************************************/ static void pj_vlog(PJ_CONTEXT *ctx, int level, const PJ *P, const char *fmt, va_list args) { char *msg_buf; if (!pj_log_active(ctx, level)) return; constexpr size_t BUF_SIZE = 100000; msg_buf = (char *)malloc(BUF_SIZE); if (msg_buf == nullptr) return; if (P == nullptr || P->short_name == nullptr) vsnprintf(msg_buf, BUF_SIZE, fmt, args); else { std::string fmt_with_P_short_name(P->short_name); fmt_with_P_short_name += ": "; fmt_with_P_short_name += fmt; vsnprintf(msg_buf, BUF_SIZE, fmt_with_P_short_name.c_str(), args); } msg_buf[BUF_SIZE - 1] = '\0'; ctx->logger(ctx->logger_app_data, level, msg_buf); free(msg_buf); } /************************************************************************/ /* pj_log() */ /************************************************************************/ void pj_log(PJ_CONTEXT *ctx, int level, const char *fmt, ...) { va_list args; if (level > ctx->debug_level) return; va_start(args, fmt); pj_vlog(ctx, level, nullptr, fmt, args); va_end(args); } /***************************************************************************************/ PJ_LOG_LEVEL proj_log_level(PJ_CONTEXT *ctx, PJ_LOG_LEVEL log_level) { /**************************************************************************************** Set logging level 0-3. Higher number means more debug info. 0 turns it off ****************************************************************************************/ PJ_LOG_LEVEL previous; if (nullptr == ctx) ctx = pj_get_default_ctx(); if (nullptr == ctx) return PJ_LOG_TELL; previous = static_cast<PJ_LOG_LEVEL>(abs(ctx->debug_level)); if (PJ_LOG_TELL == log_level) return previous; ctx->debug_level = log_level; return previous; } /*****************************************************************************/ void proj_log_error(const PJ *P, const char *fmt, ...) { /****************************************************************************** For reporting the most severe events. ******************************************************************************/ va_list args; va_start(args, fmt); pj_vlog(pj_get_ctx((PJ *)P), PJ_LOG_ERROR, P, fmt, args); va_end(args); } /*****************************************************************************/ void proj_log_debug(PJ *P, const char *fmt, ...) { /****************************************************************************** For reporting debugging information. ******************************************************************************/ va_list args; va_start(args, fmt); pj_vlog(pj_get_ctx(P), PJ_LOG_DEBUG, P, fmt, args); va_end(args); } /*****************************************************************************/ void proj_context_log_debug(PJ_CONTEXT *ctx, const char *fmt, ...) { /****************************************************************************** For reporting debugging information. ******************************************************************************/ va_list args; va_start(args, fmt); pj_vlog(ctx, PJ_LOG_DEBUG, nullptr, fmt, args); va_end(args); } /*****************************************************************************/ void proj_log_trace(PJ *P, const char *fmt, ...) { /****************************************************************************** For reporting embarrassingly detailed debugging information. ******************************************************************************/ va_list args; va_start(args, fmt); pj_vlog(pj_get_ctx(P), PJ_LOG_TRACE, P, fmt, args); va_end(args); } /*****************************************************************************/ void proj_log_func(PJ_CONTEXT *ctx, void *app_data, PJ_LOG_FUNCTION logf) { /****************************************************************************** Put a new logging function into P's context. The opaque object app_data is passed as first arg at each call to the logger ******************************************************************************/ if (nullptr == ctx) ctx = pj_get_default_ctx(); ctx->logger_app_data = app_data; if (nullptr != logf) ctx->logger = logf; }
cpp
PROJ
data/projects/PROJ/src/geodesic.c
/** * \file geodesic.c * \brief Implementation of the geodesic routines in C * * For the full documentation see geodesic.h. **********************************************************************/ /** @cond SKIP */ /* * This is a C implementation of the geodesic algorithms described in * * C. F. F. Karney, * Algorithms for geodesics, * J. Geodesy <b>87</b>, 43--55 (2013); * https://doi.org/10.1007/s00190-012-0578-z * Addenda: https://geographiclib.sourceforge.io/geod-addenda.html * * See the comments in geodesic.h for documentation. * * Copyright (c) Charles Karney (2012-2022) <[email protected]> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ */ #include "geodesic.h" #include <math.h> #include <float.h> #if !defined(__cplusplus) #define nullptr 0 #endif #define GEOGRAPHICLIB_GEODESIC_ORDER 6 #define nA1 GEOGRAPHICLIB_GEODESIC_ORDER #define nC1 GEOGRAPHICLIB_GEODESIC_ORDER #define nC1p GEOGRAPHICLIB_GEODESIC_ORDER #define nA2 GEOGRAPHICLIB_GEODESIC_ORDER #define nC2 GEOGRAPHICLIB_GEODESIC_ORDER #define nA3 GEOGRAPHICLIB_GEODESIC_ORDER #define nA3x nA3 #define nC3 GEOGRAPHICLIB_GEODESIC_ORDER #define nC3x ((nC3 * (nC3 - 1)) / 2) #define nC4 GEOGRAPHICLIB_GEODESIC_ORDER #define nC4x ((nC4 * (nC4 + 1)) / 2) #define nC (GEOGRAPHICLIB_GEODESIC_ORDER + 1) typedef int boolx; enum booly { FALSE = 0, TRUE = 1 }; /* qd = quarter turn / degree * hd = half turn / degree * td = full turn / degree */ enum dms { qd = 90, hd = 2 * qd, td = 2 * hd }; static unsigned init = 0; static unsigned digits, maxit1, maxit2; static double epsilon, realmin, pi, degree, NaN, tiny, tol0, tol1, tol2, tolb, xthresh; static void Init(void) { if (!init) { digits = DBL_MANT_DIG; epsilon = DBL_EPSILON; realmin = DBL_MIN; #if defined(M_PI) pi = M_PI; #else pi = atan2(0.0, -1.0); #endif maxit1 = 20; maxit2 = maxit1 + digits + 10; tiny = sqrt(realmin); tol0 = epsilon; /* Increase multiplier in defn of tol1 from 100 to 200 to fix inverse case * 52.784459512564 0 -52.784459512563990912 179.634407464943777557 * which otherwise failed for Visual Studio 10 (Release and Debug) */ tol1 = 200 * tol0; tol2 = sqrt(tol0); /* Check on bisection interval */ tolb = tol0; xthresh = 1000 * tol2; degree = pi/hd; NaN = nan("0"); init = 1; } } enum captype { CAP_NONE = 0U, CAP_C1 = 1U<<0, CAP_C1p = 1U<<1, CAP_C2 = 1U<<2, CAP_C3 = 1U<<3, CAP_C4 = 1U<<4, CAP_ALL = 0x1FU, OUT_ALL = 0x7F80U }; static double sq(double x) { return x * x; } static double sumx(double u, double v, double* t) { volatile double s = u + v; volatile double up = s - v; volatile double vpp = s - up; up -= u; vpp -= v; if (t) *t = s != 0 ? 0 - (up + vpp) : s; /* error-free sum: * u + v = s + t * = round(u + v) + t */ return s; } static double polyvalx(int N, const double p[], double x) { double y = N < 0 ? 0 : *p++; while (--N >= 0) y = y * x + *p++; return y; } static void swapx(double* x, double* y) { double t = *x; *x = *y; *y = t; } static void norm2(double* sinx, double* cosx) { #if defined(_MSC_VER) && defined(_M_IX86) /* hypot for Visual Studio (A=win32) fails monotonicity, e.g., with * x = 0.6102683302836215 * y1 = 0.7906090004346522 * y2 = y1 + 1e-16 * the test * hypot(x, y2) >= hypot(x, y1) * fails. See also * https://bugs.python.org/issue43088 */ double r = sqrt(*sinx * *sinx + *cosx * *cosx); #else double r = hypot(*sinx, *cosx); #endif *sinx /= r; *cosx /= r; } static double AngNormalize(double x) { double y = remainder(x, (double)td); return fabs(y) == hd ? copysign((double)hd, x) : y; } static double LatFix(double x) { return fabs(x) > qd ? NaN : x; } static double AngDiff(double x, double y, double* e) { /* Use remainder instead of AngNormalize, since we treat boundary cases * later taking account of the error */ double t, d = sumx(remainder(-x, (double)td), remainder( y, (double)td), &t); /* This second sum can only change d if abs(d) < 128, so don't need to * apply remainder yet again. */ d = sumx(remainder(d, (double)td), t, &t); /* Fix the sign if d = -180, 0, 180. */ if (d == 0 || fabs(d) == hd) /* If t == 0, take sign from y - x * else (t != 0, implies d = +/-180), d and t must have opposite signs */ d = copysign(d, t == 0 ? y - x : -t); if (e) *e = t; return d; } static double AngRound(double x) { /* False positive in cppcheck requires "1.0" instead of "1" */ const double z = 1.0/16.0; volatile double y = fabs(x); volatile double w = z - y; /* The compiler mustn't "simplify" z - (z - y) to y */ y = w > 0 ? z - w : y; return copysign(y, x); } static void sincosdx(double x, double* sinx, double* cosx) { /* In order to minimize round-off errors, this function exactly reduces * the argument to the range [-45, 45] before converting it to radians. */ double r, s, c; int q = 0; r = remquo(x, (double)qd, &q); /* now abs(r) <= 45 */ r *= degree; /* Possibly could call the gnu extension sincos */ s = sin(r); c = cos(r); switch ((unsigned)q & 3U) { case 0U: *sinx = s; *cosx = c; break; case 1U: *sinx = c; *cosx = -s; break; case 2U: *sinx = -s; *cosx = -c; break; default: *sinx = -c; *cosx = s; break; /* case 3U */ } /* http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1950.pdf */ *cosx += 0; /* special values from F.10.1.12 */ /* special values from F.10.1.13 */ if (*sinx == 0) *sinx = copysign(*sinx, x); } static void sincosde(double x, double t, double* sinx, double* cosx) { /* In order to minimize round-off errors, this function exactly reduces * the argument to the range [-45, 45] before converting it to radians. */ double r, s, c; int q = 0; r = AngRound(remquo(x, (double)qd, &q) + t); /* now abs(r) <= 45 */ r *= degree; /* Possibly could call the gnu extension sincos */ s = sin(r); c = cos(r); switch ((unsigned)q & 3U) { case 0U: *sinx = s; *cosx = c; break; case 1U: *sinx = c; *cosx = -s; break; case 2U: *sinx = -s; *cosx = -c; break; default: *sinx = -c; *cosx = s; break; /* case 3U */ } /* http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1950.pdf */ *cosx += 0; /* special values from F.10.1.12 */ /* special values from F.10.1.13 */ if (*sinx == 0) *sinx = copysign(*sinx, x); } static double atan2dx(double y, double x) { /* In order to minimize round-off errors, this function rearranges the * arguments so that result of atan2 is in the range [-pi/4, pi/4] before * converting it to degrees and mapping the result to the correct * quadrant. */ int q = 0; double ang; if (fabs(y) > fabs(x)) { swapx(&x, &y); q = 2; } if (signbit(x)) { x = -x; ++q; } /* here x >= 0 and x >= abs(y), so angle is in [-pi/4, pi/4] */ ang = atan2(y, x) / degree; switch (q) { case 1: ang = copysign((double)hd, y) - ang; break; case 2: ang = qd - ang; break; case 3: ang = -qd + ang; break; default: break; } return ang; } static void A3coeff(struct geod_geodesic* g); static void C3coeff(struct geod_geodesic* g); static void C4coeff(struct geod_geodesic* g); static double SinCosSeries(boolx sinp, double sinx, double cosx, const double c[], int n); static void Lengths(const struct geod_geodesic* g, double eps, double sig12, double ssig1, double csig1, double dn1, double ssig2, double csig2, double dn2, double cbet1, double cbet2, double* ps12b, double* pm12b, double* pm0, double* pM12, double* pM21, /* Scratch area of the right size */ double Ca[]); static double Astroid(double x, double y); static double InverseStart(const struct geod_geodesic* g, double sbet1, double cbet1, double dn1, double sbet2, double cbet2, double dn2, double lam12, double slam12, double clam12, double* psalp1, double* pcalp1, /* Only updated if return val >= 0 */ double* psalp2, double* pcalp2, /* Only updated for short lines */ double* pdnm, /* Scratch area of the right size */ double Ca[]); static double Lambda12(const struct geod_geodesic* g, double sbet1, double cbet1, double dn1, double sbet2, double cbet2, double dn2, double salp1, double calp1, double slam120, double clam120, double* psalp2, double* pcalp2, double* psig12, double* pssig1, double* pcsig1, double* pssig2, double* pcsig2, double* peps, double* pdomg12, boolx diffp, double* pdlam12, /* Scratch area of the right size */ double Ca[]); static double A3f(const struct geod_geodesic* g, double eps); static void C3f(const struct geod_geodesic* g, double eps, double c[]); static void C4f(const struct geod_geodesic* g, double eps, double c[]); static double A1m1f(double eps); static void C1f(double eps, double c[]); static void C1pf(double eps, double c[]); static double A2m1f(double eps); static void C2f(double eps, double c[]); static int transit(double lon1, double lon2); static int transitdirect(double lon1, double lon2); static void accini(double s[]); static void acccopy(const double s[], double t[]); static void accadd(double s[], double y); static double accsum(const double s[], double y); static void accneg(double s[]); static void accrem(double s[], double y); static double areareduceA(double area[], double area0, int crossings, boolx reverse, boolx sign); static double areareduceB(double area, double area0, int crossings, boolx reverse, boolx sign); void geod_init(struct geod_geodesic* g, double a, double f) { if (!init) Init(); g->a = a; g->f = f; g->f1 = 1 - g->f; g->e2 = g->f * (2 - g->f); g->ep2 = g->e2 / sq(g->f1); /* e2 / (1 - e2) */ g->n = g->f / ( 2 - g->f); g->b = g->a * g->f1; g->c2 = (sq(g->a) + sq(g->b) * (g->e2 == 0 ? 1 : (g->e2 > 0 ? atanh(sqrt(g->e2)) : atan(sqrt(-g->e2))) / sqrt(fabs(g->e2))))/2; /* authalic radius squared */ /* The sig12 threshold for "really short". Using the auxiliary sphere * solution with dnm computed at (bet1 + bet2) / 2, the relative error in the * azimuth consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2. (Error * measured for 1/100 < b/a < 100 and abs(f) >= 1/1000. For a given f and * sig12, the max error occurs for lines near the pole. If the old rule for * computing dnm = (dn1 + dn2)/2 is used, then the error increases by a * factor of 2.) Setting this equal to epsilon gives sig12 = etol2. Here * 0.1 is a safety factor (error decreased by 100) and max(0.001, abs(f)) * stops etol2 getting too large in the nearly spherical case. */ g->etol2 = 0.1 * tol2 / sqrt( fmax(0.001, fabs(g->f)) * fmin(1.0, 1 - g->f/2) / 2 ); A3coeff(g); C3coeff(g); C4coeff(g); } static void geod_lineinit_int(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double azi1, double salp1, double calp1, unsigned caps) { double cbet1, sbet1, eps; l->a = g->a; l->f = g->f; l->b = g->b; l->c2 = g->c2; l->f1 = g->f1; /* If caps is 0 assume the standard direct calculation */ l->caps = (caps ? caps : GEOD_DISTANCE_IN | GEOD_LONGITUDE) | /* always allow latitude and azimuth and unrolling of longitude */ GEOD_LATITUDE | GEOD_AZIMUTH | GEOD_LONG_UNROLL; l->lat1 = LatFix(lat1); l->lon1 = lon1; l->azi1 = azi1; l->salp1 = salp1; l->calp1 = calp1; sincosdx(AngRound(l->lat1), &sbet1, &cbet1); sbet1 *= l->f1; /* Ensure cbet1 = +epsilon at poles */ norm2(&sbet1, &cbet1); cbet1 = fmax(tiny, cbet1); l->dn1 = sqrt(1 + g->ep2 * sq(sbet1)); /* Evaluate alp0 from sin(alp1) * cos(bet1) = sin(alp0), */ l->salp0 = l->salp1 * cbet1; /* alp0 in [0, pi/2 - |bet1|] */ /* Alt: calp0 = hypot(sbet1, calp1 * cbet1). The following * is slightly better (consider the case salp1 = 0). */ l->calp0 = hypot(l->calp1, l->salp1 * sbet1); /* Evaluate sig with tan(bet1) = tan(sig1) * cos(alp1). * sig = 0 is nearest northward crossing of equator. * With bet1 = 0, alp1 = pi/2, we have sig1 = 0 (equatorial line). * With bet1 = pi/2, alp1 = -pi, sig1 = pi/2 * With bet1 = -pi/2, alp1 = 0 , sig1 = -pi/2 * Evaluate omg1 with tan(omg1) = sin(alp0) * tan(sig1). * With alp0 in (0, pi/2], quadrants for sig and omg coincide. * No atan2(0,0) ambiguity at poles since cbet1 = +epsilon. * With alp0 = 0, omg1 = 0 for alp1 = 0, omg1 = pi for alp1 = pi. */ l->ssig1 = sbet1; l->somg1 = l->salp0 * sbet1; l->csig1 = l->comg1 = sbet1 != 0 || l->calp1 != 0 ? cbet1 * l->calp1 : 1; norm2(&l->ssig1, &l->csig1); /* sig1 in (-pi, pi] */ /* norm2(somg1, comg1); -- don't need to normalize! */ l->k2 = sq(l->calp0) * g->ep2; eps = l->k2 / (2 * (1 + sqrt(1 + l->k2)) + l->k2); if (l->caps & CAP_C1) { double s, c; l->A1m1 = A1m1f(eps); C1f(eps, l->C1a); l->B11 = SinCosSeries(TRUE, l->ssig1, l->csig1, l->C1a, nC1); s = sin(l->B11); c = cos(l->B11); /* tau1 = sig1 + B11 */ l->stau1 = l->ssig1 * c + l->csig1 * s; l->ctau1 = l->csig1 * c - l->ssig1 * s; /* Not necessary because C1pa reverts C1a * B11 = -SinCosSeries(TRUE, stau1, ctau1, C1pa, nC1p); */ } if (l->caps & CAP_C1p) C1pf(eps, l->C1pa); if (l->caps & CAP_C2) { l->A2m1 = A2m1f(eps); C2f(eps, l->C2a); l->B21 = SinCosSeries(TRUE, l->ssig1, l->csig1, l->C2a, nC2); } if (l->caps & CAP_C3) { C3f(g, eps, l->C3a); l->A3c = -l->f * l->salp0 * A3f(g, eps); l->B31 = SinCosSeries(TRUE, l->ssig1, l->csig1, l->C3a, nC3-1); } if (l->caps & CAP_C4) { C4f(g, eps, l->C4a); /* Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0) */ l->A4 = sq(l->a) * l->calp0 * l->salp0 * g->e2; l->B41 = SinCosSeries(FALSE, l->ssig1, l->csig1, l->C4a, nC4); } l->a13 = l->s13 = NaN; } void geod_lineinit(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double azi1, unsigned caps) { double salp1, calp1; azi1 = AngNormalize(azi1); /* Guard against underflow in salp0 */ sincosdx(AngRound(azi1), &salp1, &calp1); geod_lineinit_int(l, g, lat1, lon1, azi1, salp1, calp1, caps); } void geod_gendirectline(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double azi1, unsigned flags, double s12_a12, unsigned caps) { geod_lineinit(l, g, lat1, lon1, azi1, caps); geod_gensetdistance(l, flags, s12_a12); } void geod_directline(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double azi1, double s12, unsigned caps) { geod_gendirectline(l, g, lat1, lon1, azi1, GEOD_NOFLAGS, s12, caps); } double geod_genposition(const struct geod_geodesicline* l, unsigned flags, double s12_a12, double* plat2, double* plon2, double* pazi2, double* ps12, double* pm12, double* pM12, double* pM21, double* pS12) { double lat2 = 0, lon2 = 0, azi2 = 0, s12 = 0, m12 = 0, M12 = 0, M21 = 0, S12 = 0; /* Avoid warning about uninitialized B12. */ double sig12, ssig12, csig12, B12 = 0, AB1 = 0; double omg12, lam12, lon12; double ssig2, csig2, sbet2, cbet2, somg2, comg2, salp2, calp2, dn2; unsigned outmask = (plat2 ? GEOD_LATITUDE : GEOD_NONE) | (plon2 ? GEOD_LONGITUDE : GEOD_NONE) | (pazi2 ? GEOD_AZIMUTH : GEOD_NONE) | (ps12 ? GEOD_DISTANCE : GEOD_NONE) | (pm12 ? GEOD_REDUCEDLENGTH : GEOD_NONE) | (pM12 || pM21 ? GEOD_GEODESICSCALE : GEOD_NONE) | (pS12 ? GEOD_AREA : GEOD_NONE); outmask &= l->caps & OUT_ALL; if (!( (flags & GEOD_ARCMODE || (l->caps & (GEOD_DISTANCE_IN & OUT_ALL))) )) /* Impossible distance calculation requested */ return NaN; if (flags & GEOD_ARCMODE) { /* Interpret s12_a12 as spherical arc length */ sig12 = s12_a12 * degree; sincosdx(s12_a12, &ssig12, &csig12); } else { /* Interpret s12_a12 as distance */ double tau12 = s12_a12 / (l->b * (1 + l->A1m1)), s = sin(tau12), c = cos(tau12); /* tau2 = tau1 + tau12 */ B12 = - SinCosSeries(TRUE, l->stau1 * c + l->ctau1 * s, l->ctau1 * c - l->stau1 * s, l->C1pa, nC1p); sig12 = tau12 - (B12 - l->B11); ssig12 = sin(sig12); csig12 = cos(sig12); if (fabs(l->f) > 0.01) { /* Reverted distance series is inaccurate for |f| > 1/100, so correct * sig12 with 1 Newton iteration. The following table shows the * approximate maximum error for a = WGS_a() and various f relative to * GeodesicExact. * erri = the error in the inverse solution (nm) * errd = the error in the direct solution (series only) (nm) * errda = the error in the direct solution (series + 1 Newton) (nm) * * f erri errd errda * -1/5 12e6 1.2e9 69e6 * -1/10 123e3 12e6 765e3 * -1/20 1110 108e3 7155 * -1/50 18.63 200.9 27.12 * -1/100 18.63 23.78 23.37 * -1/150 18.63 21.05 20.26 * 1/150 22.35 24.73 25.83 * 1/100 22.35 25.03 25.31 * 1/50 29.80 231.9 30.44 * 1/20 5376 146e3 10e3 * 1/10 829e3 22e6 1.5e6 * 1/5 157e6 3.8e9 280e6 */ double serr; ssig2 = l->ssig1 * csig12 + l->csig1 * ssig12; csig2 = l->csig1 * csig12 - l->ssig1 * ssig12; B12 = SinCosSeries(TRUE, ssig2, csig2, l->C1a, nC1); serr = (1 + l->A1m1) * (sig12 + (B12 - l->B11)) - s12_a12 / l->b; sig12 = sig12 - serr / sqrt(1 + l->k2 * sq(ssig2)); ssig12 = sin(sig12); csig12 = cos(sig12); /* Update B12 below */ } } /* sig2 = sig1 + sig12 */ ssig2 = l->ssig1 * csig12 + l->csig1 * ssig12; csig2 = l->csig1 * csig12 - l->ssig1 * ssig12; dn2 = sqrt(1 + l->k2 * sq(ssig2)); if (outmask & (GEOD_DISTANCE | GEOD_REDUCEDLENGTH | GEOD_GEODESICSCALE)) { if (flags & GEOD_ARCMODE || fabs(l->f) > 0.01) B12 = SinCosSeries(TRUE, ssig2, csig2, l->C1a, nC1); AB1 = (1 + l->A1m1) * (B12 - l->B11); } /* sin(bet2) = cos(alp0) * sin(sig2) */ sbet2 = l->calp0 * ssig2; /* Alt: cbet2 = hypot(csig2, salp0 * ssig2); */ cbet2 = hypot(l->salp0, l->calp0 * csig2); if (cbet2 == 0) /* I.e., salp0 = 0, csig2 = 0. Break the degeneracy in this case */ cbet2 = csig2 = tiny; /* tan(alp0) = cos(sig2)*tan(alp2) */ salp2 = l->salp0; calp2 = l->calp0 * csig2; /* No need to normalize */ if (outmask & GEOD_DISTANCE) s12 = (flags & GEOD_ARCMODE) ? l->b * ((1 + l->A1m1) * sig12 + AB1) : s12_a12; if (outmask & GEOD_LONGITUDE) { double E = copysign(1, l->salp0); /* east or west going? */ /* tan(omg2) = sin(alp0) * tan(sig2) */ somg2 = l->salp0 * ssig2; comg2 = csig2; /* No need to normalize */ /* omg12 = omg2 - omg1 */ omg12 = (flags & GEOD_LONG_UNROLL) ? E * (sig12 - (atan2( ssig2, csig2) - atan2( l->ssig1, l->csig1)) + (atan2(E * somg2, comg2) - atan2(E * l->somg1, l->comg1))) : atan2(somg2 * l->comg1 - comg2 * l->somg1, comg2 * l->comg1 + somg2 * l->somg1); lam12 = omg12 + l->A3c * ( sig12 + (SinCosSeries(TRUE, ssig2, csig2, l->C3a, nC3-1) - l->B31)); lon12 = lam12 / degree; lon2 = (flags & GEOD_LONG_UNROLL) ? l->lon1 + lon12 : AngNormalize(AngNormalize(l->lon1) + AngNormalize(lon12)); } if (outmask & GEOD_LATITUDE) lat2 = atan2dx(sbet2, l->f1 * cbet2); if (outmask & GEOD_AZIMUTH) azi2 = atan2dx(salp2, calp2); if (outmask & (GEOD_REDUCEDLENGTH | GEOD_GEODESICSCALE)) { double B22 = SinCosSeries(TRUE, ssig2, csig2, l->C2a, nC2), AB2 = (1 + l->A2m1) * (B22 - l->B21), J12 = (l->A1m1 - l->A2m1) * sig12 + (AB1 - AB2); if (outmask & GEOD_REDUCEDLENGTH) /* Add parens around (csig1 * ssig2) and (ssig1 * csig2) to ensure * accurate cancellation in the case of coincident points. */ m12 = l->b * ((dn2 * (l->csig1 * ssig2) - l->dn1 * (l->ssig1 * csig2)) - l->csig1 * csig2 * J12); if (outmask & GEOD_GEODESICSCALE) { double t = l->k2 * (ssig2 - l->ssig1) * (ssig2 + l->ssig1) / (l->dn1 + dn2); M12 = csig12 + (t * ssig2 - csig2 * J12) * l->ssig1 / l->dn1; M21 = csig12 - (t * l->ssig1 - l->csig1 * J12) * ssig2 / dn2; } } if (outmask & GEOD_AREA) { double B42 = SinCosSeries(FALSE, ssig2, csig2, l->C4a, nC4); double salp12, calp12; if (l->calp0 == 0 || l->salp0 == 0) { /* alp12 = alp2 - alp1, used in atan2 so no need to normalize */ salp12 = salp2 * l->calp1 - calp2 * l->salp1; calp12 = calp2 * l->calp1 + salp2 * l->salp1; } else { /* tan(alp) = tan(alp0) * sec(sig) * tan(alp2-alp1) = (tan(alp2) -tan(alp1)) / (tan(alp2)*tan(alp1)+1) * = calp0 * salp0 * (csig1-csig2) / (salp0^2 + calp0^2 * csig1*csig2) * If csig12 > 0, write * csig1 - csig2 = ssig12 * (csig1 * ssig12 / (1 + csig12) + ssig1) * else * csig1 - csig2 = csig1 * (1 - csig12) + ssig12 * ssig1 * No need to normalize */ salp12 = l->calp0 * l->salp0 * (csig12 <= 0 ? l->csig1 * (1 - csig12) + ssig12 * l->ssig1 : ssig12 * (l->csig1 * ssig12 / (1 + csig12) + l->ssig1)); calp12 = sq(l->salp0) + sq(l->calp0) * l->csig1 * csig2; } S12 = l->c2 * atan2(salp12, calp12) + l->A4 * (B42 - l->B41); } /* In the pattern * * if ((outmask & GEOD_XX) && pYY) * *pYY = YY; * * the second check "&& pYY" is redundant. It's there to make the CLang * static analyzer happy. */ if ((outmask & GEOD_LATITUDE) && plat2) *plat2 = lat2; if ((outmask & GEOD_LONGITUDE) && plon2) *plon2 = lon2; if ((outmask & GEOD_AZIMUTH) && pazi2) *pazi2 = azi2; if ((outmask & GEOD_DISTANCE) && ps12) *ps12 = s12; if ((outmask & GEOD_REDUCEDLENGTH) && pm12) *pm12 = m12; if (outmask & GEOD_GEODESICSCALE) { if (pM12) *pM12 = M12; if (pM21) *pM21 = M21; } if ((outmask & GEOD_AREA) && pS12) *pS12 = S12; return (flags & GEOD_ARCMODE) ? s12_a12 : sig12 / degree; } void geod_setdistance(struct geod_geodesicline* l, double s13) { l->s13 = s13; l->a13 = geod_genposition(l, GEOD_NOFLAGS, l->s13, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); } static void geod_setarc(struct geod_geodesicline* l, double a13) { l->a13 = a13; l->s13 = NaN; geod_genposition(l, GEOD_ARCMODE, l->a13, nullptr, nullptr, nullptr, &l->s13, nullptr, nullptr, nullptr, nullptr); } void geod_gensetdistance(struct geod_geodesicline* l, unsigned flags, double s13_a13) { (flags & GEOD_ARCMODE) ? geod_setarc(l, s13_a13) : geod_setdistance(l, s13_a13); } void geod_position(const struct geod_geodesicline* l, double s12, double* plat2, double* plon2, double* pazi2) { geod_genposition(l, FALSE, s12, plat2, plon2, pazi2, nullptr, nullptr, nullptr, nullptr, nullptr); } double geod_gendirect(const struct geod_geodesic* g, double lat1, double lon1, double azi1, unsigned flags, double s12_a12, double* plat2, double* plon2, double* pazi2, double* ps12, double* pm12, double* pM12, double* pM21, double* pS12) { struct geod_geodesicline l; unsigned outmask = (plat2 ? GEOD_LATITUDE : GEOD_NONE) | (plon2 ? GEOD_LONGITUDE : GEOD_NONE) | (pazi2 ? GEOD_AZIMUTH : GEOD_NONE) | (ps12 ? GEOD_DISTANCE : GEOD_NONE) | (pm12 ? GEOD_REDUCEDLENGTH : GEOD_NONE) | (pM12 || pM21 ? GEOD_GEODESICSCALE : GEOD_NONE) | (pS12 ? GEOD_AREA : GEOD_NONE); geod_lineinit(&l, g, lat1, lon1, azi1, /* Automatically supply GEOD_DISTANCE_IN if necessary */ outmask | ((flags & GEOD_ARCMODE) ? GEOD_NONE : GEOD_DISTANCE_IN)); return geod_genposition(&l, flags, s12_a12, plat2, plon2, pazi2, ps12, pm12, pM12, pM21, pS12); } void geod_direct(const struct geod_geodesic* g, double lat1, double lon1, double azi1, double s12, double* plat2, double* plon2, double* pazi2) { geod_gendirect(g, lat1, lon1, azi1, GEOD_NOFLAGS, s12, plat2, plon2, pazi2, nullptr, nullptr, nullptr, nullptr, nullptr); } static double geod_geninverse_int(const struct geod_geodesic* g, double lat1, double lon1, double lat2, double lon2, double* ps12, double* psalp1, double* pcalp1, double* psalp2, double* pcalp2, double* pm12, double* pM12, double* pM21, double* pS12) { double s12 = 0, m12 = 0, M12 = 0, M21 = 0, S12 = 0; double lon12, lon12s; int latsign, lonsign, swapp; double sbet1, cbet1, sbet2, cbet2, s12x = 0, m12x = 0; double dn1, dn2, lam12, slam12, clam12; double a12 = 0, sig12, calp1 = 0, salp1 = 0, calp2 = 0, salp2 = 0; double Ca[nC]; boolx meridian; /* somg12 == 2 marks that it needs to be calculated */ double omg12 = 0, somg12 = 2, comg12 = 0; unsigned outmask = (ps12 ? GEOD_DISTANCE : GEOD_NONE) | (pm12 ? GEOD_REDUCEDLENGTH : GEOD_NONE) | (pM12 || pM21 ? GEOD_GEODESICSCALE : GEOD_NONE) | (pS12 ? GEOD_AREA : GEOD_NONE); outmask &= OUT_ALL; /* Compute longitude difference (AngDiff does this carefully). Result is * in [-180, 180] but -180 is only for west-going geodesics. 180 is for * east-going and meridional geodesics. */ lon12 = AngDiff(lon1, lon2, &lon12s); /* Make longitude difference positive. */ lonsign = signbit(lon12) ? -1 : 1; lon12 *= lonsign; lon12s *= lonsign; lam12 = lon12 * degree; /* Calculate sincos of lon12 + error (this applies AngRound internally). */ sincosde(lon12, lon12s, &slam12, &clam12); lon12s = (hd - lon12) - lon12s; /* the supplementary longitude difference */ /* If really close to the equator, treat as on equator. */ lat1 = AngRound(LatFix(lat1)); lat2 = AngRound(LatFix(lat2)); /* Swap points so that point with higher (abs) latitude is point 1 * If one latitude is a nan, then it becomes lat1. */ swapp = fabs(lat1) < fabs(lat2) || lat2 != lat2 ? -1 : 1; if (swapp < 0) { lonsign *= -1; swapx(&lat1, &lat2); } /* Make lat1 <= -0 */ latsign = signbit(lat1) ? 1 : -1; lat1 *= latsign; lat2 *= latsign; /* Now we have * * 0 <= lon12 <= 180 * -90 <= lat1 <= -0 * lat1 <= lat2 <= -lat1 * * longsign, swapp, latsign register the transformation to bring the * coordinates to this canonical form. In all cases, 1 means no change was * made. We make these transformations so that there are few cases to * check, e.g., on verifying quadrants in atan2. In addition, this * enforces some symmetries in the results returned. */ sincosdx(lat1, &sbet1, &cbet1); sbet1 *= g->f1; /* Ensure cbet1 = +epsilon at poles */ norm2(&sbet1, &cbet1); cbet1 = fmax(tiny, cbet1); sincosdx(lat2, &sbet2, &cbet2); sbet2 *= g->f1; /* Ensure cbet2 = +epsilon at poles */ norm2(&sbet2, &cbet2); cbet2 = fmax(tiny, cbet2); /* If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure of the * |bet1| - |bet2|. Alternatively (cbet1 >= -sbet1), abs(sbet2) + sbet1 is * a better measure. This logic is used in assigning calp2 in Lambda12. * Sometimes these quantities vanish and in that case we force bet2 = +/- * bet1 exactly. An example where is is necessary is the inverse problem * 48.522876735459 0 -48.52287673545898293 179.599720456223079643 * which failed with Visual Studio 10 (Release and Debug) */ if (cbet1 < -sbet1) { if (cbet2 == cbet1) sbet2 = copysign(sbet1, sbet2); } else { if (fabs(sbet2) == -sbet1) cbet2 = cbet1; } dn1 = sqrt(1 + g->ep2 * sq(sbet1)); dn2 = sqrt(1 + g->ep2 * sq(sbet2)); meridian = lat1 == -qd || slam12 == 0; if (meridian) { /* Endpoints are on a single full meridian, so the geodesic might lie on * a meridian. */ double ssig1, csig1, ssig2, csig2; calp1 = clam12; salp1 = slam12; /* Head to the target longitude */ calp2 = 1; salp2 = 0; /* At the target we're heading north */ /* tan(bet) = tan(sig) * cos(alp) */ ssig1 = sbet1; csig1 = calp1 * cbet1; ssig2 = sbet2; csig2 = calp2 * cbet2; /* sig12 = sig2 - sig1 */ sig12 = atan2(fmax(0.0, csig1 * ssig2 - ssig1 * csig2) + 0, csig1 * csig2 + ssig1 * ssig2); Lengths(g, g->n, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2, &s12x, &m12x, nullptr, (outmask & GEOD_GEODESICSCALE) ? &M12 : nullptr, (outmask & GEOD_GEODESICSCALE) ? &M21 : nullptr, Ca); /* Add the check for sig12 since zero length geodesics might yield m12 < * 0. Test case was * * echo 20.001 0 20.001 0 | GeodSolve -i * * In fact, we will have sig12 > pi/2 for meridional geodesic which is * not a shortest path. */ if (sig12 < 1 || m12x >= 0) { /* Need at least 2, to handle 90 0 90 180 */ if (sig12 < 3 * tiny || /* Prevent negative s12 or m12 for short lines */ (sig12 < tol0 && (s12x < 0 || m12x < 0))) sig12 = m12x = s12x = 0; m12x *= g->b; s12x *= g->b; a12 = sig12 / degree; } else /* m12 < 0, i.e., prolate and too close to anti-podal */ meridian = FALSE; } if (!meridian && sbet1 == 0 && /* and sbet2 == 0 */ /* Mimic the way Lambda12 works with calp1 = 0 */ (g->f <= 0 || lon12s >= g->f * hd)) { /* Geodesic runs along equator */ calp1 = calp2 = 0; salp1 = salp2 = 1; s12x = g->a * lam12; sig12 = omg12 = lam12 / g->f1; m12x = g->b * sin(sig12); if (outmask & GEOD_GEODESICSCALE) M12 = M21 = cos(sig12); a12 = lon12 / g->f1; } else if (!meridian) { /* Now point1 and point2 belong within a hemisphere bounded by a * meridian and geodesic is neither meridional or equatorial. */ /* Figure a starting point for Newton's method */ double dnm = 0; sig12 = InverseStart(g, sbet1, cbet1, dn1, sbet2, cbet2, dn2, lam12, slam12, clam12, &salp1, &calp1, &salp2, &calp2, &dnm, Ca); if (sig12 >= 0) { /* Short lines (InverseStart sets salp2, calp2, dnm) */ s12x = sig12 * g->b * dnm; m12x = sq(dnm) * g->b * sin(sig12 / dnm); if (outmask & GEOD_GEODESICSCALE) M12 = M21 = cos(sig12 / dnm); a12 = sig12 / degree; omg12 = lam12 / (g->f1 * dnm); } else { /* Newton's method. This is a straightforward solution of f(alp1) = * lambda12(alp1) - lam12 = 0 with one wrinkle. f(alp) has exactly one * root in the interval (0, pi) and its derivative is positive at the * root. Thus f(alp) is positive for alp > alp1 and negative for alp < * alp1. During the course of the iteration, a range (alp1a, alp1b) is * maintained which brackets the root and with each evaluation of * f(alp) the range is shrunk, if possible. Newton's method is * restarted whenever the derivative of f is negative (because the new * value of alp1 is then further from the solution) or if the new * estimate of alp1 lies outside (0,pi); in this case, the new starting * guess is taken to be (alp1a + alp1b) / 2. */ double ssig1 = 0, csig1 = 0, ssig2 = 0, csig2 = 0, eps = 0, domg12 = 0; unsigned numit = 0; /* Bracketing range */ double salp1a = tiny, calp1a = 1, salp1b = tiny, calp1b = -1; boolx tripn = FALSE; boolx tripb = FALSE; for (;; ++numit) { /* the WGS84 test set: mean = 1.47, sd = 1.25, max = 16 * WGS84 and random input: mean = 2.85, sd = 0.60 */ double dv = 0, v = Lambda12(g, sbet1, cbet1, dn1, sbet2, cbet2, dn2, salp1, calp1, slam12, clam12, &salp2, &calp2, &sig12, &ssig1, &csig1, &ssig2, &csig2, &eps, &domg12, numit < maxit1, &dv, Ca); if (tripb || /* Reversed test to allow escape with NaNs */ !(fabs(v) >= (tripn ? 8 : 1) * tol0) || /* Enough bisections to get accurate result */ numit == maxit2) break; /* Update bracketing values */ if (v > 0 && (numit > maxit1 || calp1/salp1 > calp1b/salp1b)) { salp1b = salp1; calp1b = calp1; } else if (v < 0 && (numit > maxit1 || calp1/salp1 < calp1a/salp1a)) { salp1a = salp1; calp1a = calp1; } if (numit < maxit1 && dv > 0) { double dalp1 = -v/dv; if (fabs(dalp1) < pi) { double sdalp1 = sin(dalp1), cdalp1 = cos(dalp1), nsalp1 = salp1 * cdalp1 + calp1 * sdalp1; if (nsalp1 > 0) { calp1 = calp1 * cdalp1 - salp1 * sdalp1; salp1 = nsalp1; norm2(&salp1, &calp1); /* In some regimes we don't get quadratic convergence because * slope -> 0. So use convergence conditions based on epsilon * instead of sqrt(epsilon). */ tripn = fabs(v) <= 16 * tol0; continue; } } } /* Either dv was not positive or updated value was outside legal * range. Use the midpoint of the bracket as the next estimate. * This mechanism is not needed for the WGS84 ellipsoid, but it does * catch problems with more eccentric ellipsoids. Its efficacy is * such for the WGS84 test set with the starting guess set to alp1 = * 90deg: * the WGS84 test set: mean = 5.21, sd = 3.93, max = 24 * WGS84 and random input: mean = 4.74, sd = 0.99 */ salp1 = (salp1a + salp1b)/2; calp1 = (calp1a + calp1b)/2; norm2(&salp1, &calp1); tripn = FALSE; tripb = (fabs(salp1a - salp1) + (calp1a - calp1) < tolb || fabs(salp1 - salp1b) + (calp1 - calp1b) < tolb); } Lengths(g, eps, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2, &s12x, &m12x, nullptr, (outmask & GEOD_GEODESICSCALE) ? &M12 : nullptr, (outmask & GEOD_GEODESICSCALE) ? &M21 : nullptr, Ca); m12x *= g->b; s12x *= g->b; a12 = sig12 / degree; if (outmask & GEOD_AREA) { /* omg12 = lam12 - domg12 */ double sdomg12 = sin(domg12), cdomg12 = cos(domg12); somg12 = slam12 * cdomg12 - clam12 * sdomg12; comg12 = clam12 * cdomg12 + slam12 * sdomg12; } } } if (outmask & GEOD_DISTANCE) s12 = 0 + s12x; /* Convert -0 to 0 */ if (outmask & GEOD_REDUCEDLENGTH) m12 = 0 + m12x; /* Convert -0 to 0 */ if (outmask & GEOD_AREA) { double /* From Lambda12: sin(alp1) * cos(bet1) = sin(alp0) */ salp0 = salp1 * cbet1, calp0 = hypot(calp1, salp1 * sbet1); /* calp0 > 0 */ double alp12; if (calp0 != 0 && salp0 != 0) { double /* From Lambda12: tan(bet) = tan(sig) * cos(alp) */ ssig1 = sbet1, csig1 = calp1 * cbet1, ssig2 = sbet2, csig2 = calp2 * cbet2, k2 = sq(calp0) * g->ep2, eps = k2 / (2 * (1 + sqrt(1 + k2)) + k2), /* Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0). */ A4 = sq(g->a) * calp0 * salp0 * g->e2; double B41, B42; norm2(&ssig1, &csig1); norm2(&ssig2, &csig2); C4f(g, eps, Ca); B41 = SinCosSeries(FALSE, ssig1, csig1, Ca, nC4); B42 = SinCosSeries(FALSE, ssig2, csig2, Ca, nC4); S12 = A4 * (B42 - B41); } else /* Avoid problems with indeterminate sig1, sig2 on equator */ S12 = 0; if (!meridian && somg12 == 2) { somg12 = sin(omg12); comg12 = cos(omg12); } if (!meridian && /* omg12 < 3/4 * pi */ comg12 > -0.7071 && /* Long difference not too big */ sbet2 - sbet1 < 1.75) { /* Lat difference not too big */ /* Use tan(Gamma/2) = tan(omg12/2) * * (tan(bet1/2)+tan(bet2/2))/(1+tan(bet1/2)*tan(bet2/2)) * with tan(x/2) = sin(x)/(1+cos(x)) */ double domg12 = 1 + comg12, dbet1 = 1 + cbet1, dbet2 = 1 + cbet2; alp12 = 2 * atan2( somg12 * ( sbet1 * dbet2 + sbet2 * dbet1 ), domg12 * ( sbet1 * sbet2 + dbet1 * dbet2 ) ); } else { /* alp12 = alp2 - alp1, used in atan2 so no need to normalize */ double salp12 = salp2 * calp1 - calp2 * salp1, calp12 = calp2 * calp1 + salp2 * salp1; /* The right thing appears to happen if alp1 = +/-180 and alp2 = 0, viz * salp12 = -0 and alp12 = -180. However this depends on the sign * being attached to 0 correctly. The following ensures the correct * behavior. */ if (salp12 == 0 && calp12 < 0) { salp12 = tiny * calp1; calp12 = -1; } alp12 = atan2(salp12, calp12); } S12 += g->c2 * alp12; S12 *= swapp * lonsign * latsign; /* Convert -0 to 0 */ S12 += 0; } /* Convert calp, salp to azimuth accounting for lonsign, swapp, latsign. */ if (swapp < 0) { swapx(&salp1, &salp2); swapx(&calp1, &calp2); if (outmask & GEOD_GEODESICSCALE) swapx(&M12, &M21); } salp1 *= swapp * lonsign; calp1 *= swapp * latsign; salp2 *= swapp * lonsign; calp2 *= swapp * latsign; if (psalp1) *psalp1 = salp1; if (pcalp1) *pcalp1 = calp1; if (psalp2) *psalp2 = salp2; if (pcalp2) *pcalp2 = calp2; if (outmask & GEOD_DISTANCE) *ps12 = s12; if (outmask & GEOD_REDUCEDLENGTH) *pm12 = m12; if (outmask & GEOD_GEODESICSCALE) { if (pM12) *pM12 = M12; if (pM21) *pM21 = M21; } if (outmask & GEOD_AREA) *pS12 = S12; /* Returned value in [0, 180] */ return a12; } double geod_geninverse(const struct geod_geodesic* g, double lat1, double lon1, double lat2, double lon2, double* ps12, double* pazi1, double* pazi2, double* pm12, double* pM12, double* pM21, double* pS12) { double salp1, calp1, salp2, calp2, a12 = geod_geninverse_int(g, lat1, lon1, lat2, lon2, ps12, &salp1, &calp1, &salp2, &calp2, pm12, pM12, pM21, pS12); if (pazi1) *pazi1 = atan2dx(salp1, calp1); if (pazi2) *pazi2 = atan2dx(salp2, calp2); return a12; } void geod_inverseline(struct geod_geodesicline* l, const struct geod_geodesic* g, double lat1, double lon1, double lat2, double lon2, unsigned caps) { double salp1, calp1, a12 = geod_geninverse_int(g, lat1, lon1, lat2, lon2, nullptr, &salp1, &calp1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr), azi1 = atan2dx(salp1, calp1); caps = caps ? caps : GEOD_DISTANCE_IN | GEOD_LONGITUDE; /* Ensure that a12 can be converted to a distance */ if (caps & (OUT_ALL & GEOD_DISTANCE_IN)) caps |= GEOD_DISTANCE; geod_lineinit_int(l, g, lat1, lon1, azi1, salp1, calp1, caps); geod_setarc(l, a12); } void geod_inverse(const struct geod_geodesic* g, double lat1, double lon1, double lat2, double lon2, double* ps12, double* pazi1, double* pazi2) { geod_geninverse(g, lat1, lon1, lat2, lon2, ps12, pazi1, pazi2, nullptr, nullptr, nullptr, nullptr); } double SinCosSeries(boolx sinp, double sinx, double cosx, const double c[], int n) { /* Evaluate * y = sinp ? sum(c[i] * sin( 2*i * x), i, 1, n) : * sum(c[i] * cos((2*i+1) * x), i, 0, n-1) * using Clenshaw summation. N.B. c[0] is unused for sin series * Approx operation count = (n + 5) mult and (2 * n + 2) add */ double ar, y0, y1; c += (n + sinp); /* Point to one beyond last element */ ar = 2 * (cosx - sinx) * (cosx + sinx); /* 2 * cos(2 * x) */ y0 = (n & 1) ? *--c : 0; y1 = 0; /* accumulators for sum */ /* Now n is even */ n /= 2; while (n--) { /* Unroll loop x 2, so accumulators return to their original role */ y1 = ar * y0 - y1 + *--c; y0 = ar * y1 - y0 + *--c; } return sinp ? 2 * sinx * cosx * y0 /* sin(2 * x) * y0 */ : cosx * (y0 - y1); /* cos(x) * (y0 - y1) */ } void Lengths(const struct geod_geodesic* g, double eps, double sig12, double ssig1, double csig1, double dn1, double ssig2, double csig2, double dn2, double cbet1, double cbet2, double* ps12b, double* pm12b, double* pm0, double* pM12, double* pM21, /* Scratch area of the right size */ double Ca[]) { double m0 = 0, J12 = 0, A1 = 0, A2 = 0; double Cb[nC]; /* Return m12b = (reduced length)/b; also calculate s12b = distance/b, * and m0 = coefficient of secular term in expression for reduced length. */ boolx redlp = pm12b || pm0 || pM12 || pM21; if (ps12b || redlp) { A1 = A1m1f(eps); C1f(eps, Ca); if (redlp) { A2 = A2m1f(eps); C2f(eps, Cb); m0 = A1 - A2; A2 = 1 + A2; } A1 = 1 + A1; } if (ps12b) { double B1 = SinCosSeries(TRUE, ssig2, csig2, Ca, nC1) - SinCosSeries(TRUE, ssig1, csig1, Ca, nC1); /* Missing a factor of b */ *ps12b = A1 * (sig12 + B1); if (redlp) { double B2 = SinCosSeries(TRUE, ssig2, csig2, Cb, nC2) - SinCosSeries(TRUE, ssig1, csig1, Cb, nC2); J12 = m0 * sig12 + (A1 * B1 - A2 * B2); } } else if (redlp) { /* Assume here that nC1 >= nC2 */ int l; for (l = 1; l <= nC2; ++l) Cb[l] = A1 * Ca[l] - A2 * Cb[l]; J12 = m0 * sig12 + (SinCosSeries(TRUE, ssig2, csig2, Cb, nC2) - SinCosSeries(TRUE, ssig1, csig1, Cb, nC2)); } if (pm0) *pm0 = m0; if (pm12b) /* Missing a factor of b. * Add parens around (csig1 * ssig2) and (ssig1 * csig2) to ensure * accurate cancellation in the case of coincident points. */ *pm12b = dn2 * (csig1 * ssig2) - dn1 * (ssig1 * csig2) - csig1 * csig2 * J12; if (pM12 || pM21) { double csig12 = csig1 * csig2 + ssig1 * ssig2; double t = g->ep2 * (cbet1 - cbet2) * (cbet1 + cbet2) / (dn1 + dn2); if (pM12) *pM12 = csig12 + (t * ssig2 - csig2 * J12) * ssig1 / dn1; if (pM21) *pM21 = csig12 - (t * ssig1 - csig1 * J12) * ssig2 / dn2; } } double Astroid(double x, double y) { /* Solve k^4+2*k^3-(x^2+y^2-1)*k^2-2*y^2*k-y^2 = 0 for positive root k. * This solution is adapted from Geocentric::Reverse. */ double k; double p = sq(x), q = sq(y), r = (p + q - 1) / 6; if ( !(q == 0 && r <= 0) ) { double /* Avoid possible division by zero when r = 0 by multiplying equations * for s and t by r^3 and r, resp. */ S = p * q / 4, /* S = r^3 * s */ r2 = sq(r), r3 = r * r2, /* The discriminant of the quadratic equation for T3. This is zero on * the evolute curve p^(1/3)+q^(1/3) = 1 */ disc = S * (S + 2 * r3); double u = r; double v, uv, w; if (disc >= 0) { double T3 = S + r3, T; /* Pick the sign on the sqrt to maximize abs(T3). This minimizes loss * of precision due to cancellation. The result is unchanged because * of the way the T is used in definition of u. */ T3 += T3 < 0 ? -sqrt(disc) : sqrt(disc); /* T3 = (r * t)^3 */ /* N.B. cbrt always returns the double root. cbrt(-8) = -2. */ T = cbrt(T3); /* T = r * t */ /* T can be zero; but then r2 / T -> 0. */ u += T + (T != 0 ? r2 / T : 0); } else { /* T is complex, but the way u is defined the result is double. */ double ang = atan2(sqrt(-disc), -(S + r3)); /* There are three possible cube roots. We choose the root which * avoids cancellation. Note that disc < 0 implies that r < 0. */ u += 2 * r * cos(ang / 3); } v = sqrt(sq(u) + q); /* guaranteed positive */ /* Avoid loss of accuracy when u < 0. */ uv = u < 0 ? q / (v - u) : u + v; /* u+v, guaranteed positive */ w = (uv - q) / (2 * v); /* positive? */ /* Rearrange expression for k to avoid loss of accuracy due to * subtraction. Division by 0 not possible because uv > 0, w >= 0. */ k = uv / (sqrt(uv + sq(w)) + w); /* guaranteed positive */ } else { /* q == 0 && r <= 0 */ /* y = 0 with |x| <= 1. Handle this case directly. * for y small, positive root is k = abs(y)/sqrt(1-x^2) */ k = 0; } return k; } double InverseStart(const struct geod_geodesic* g, double sbet1, double cbet1, double dn1, double sbet2, double cbet2, double dn2, double lam12, double slam12, double clam12, double* psalp1, double* pcalp1, /* Only updated if return val >= 0 */ double* psalp2, double* pcalp2, /* Only updated for short lines */ double* pdnm, /* Scratch area of the right size */ double Ca[]) { double salp1 = 0, calp1 = 0, salp2 = 0, calp2 = 0, dnm = 0; /* Return a starting point for Newton's method in salp1 and calp1 (function * value is -1). If Newton's method doesn't need to be used, return also * salp2 and calp2 and function value is sig12. */ double sig12 = -1, /* Return value */ /* bet12 = bet2 - bet1 in [0, pi); bet12a = bet2 + bet1 in (-pi, 0] */ sbet12 = sbet2 * cbet1 - cbet2 * sbet1, cbet12 = cbet2 * cbet1 + sbet2 * sbet1; double sbet12a; boolx shortline = cbet12 >= 0 && sbet12 < 0.5 && cbet2 * lam12 < 0.5; double somg12, comg12, ssig12, csig12; sbet12a = sbet2 * cbet1 + cbet2 * sbet1; if (shortline) { double sbetm2 = sq(sbet1 + sbet2), omg12; /* sin((bet1+bet2)/2)^2 * = (sbet1 + sbet2)^2 / ((sbet1 + sbet2)^2 + (cbet1 + cbet2)^2) */ sbetm2 /= sbetm2 + sq(cbet1 + cbet2); dnm = sqrt(1 + g->ep2 * sbetm2); omg12 = lam12 / (g->f1 * dnm); somg12 = sin(omg12); comg12 = cos(omg12); } else { somg12 = slam12; comg12 = clam12; } salp1 = cbet2 * somg12; calp1 = comg12 >= 0 ? sbet12 + cbet2 * sbet1 * sq(somg12) / (1 + comg12) : sbet12a - cbet2 * sbet1 * sq(somg12) / (1 - comg12); ssig12 = hypot(salp1, calp1); csig12 = sbet1 * sbet2 + cbet1 * cbet2 * comg12; if (shortline && ssig12 < g->etol2) { /* really short lines */ salp2 = cbet1 * somg12; calp2 = sbet12 - cbet1 * sbet2 * (comg12 >= 0 ? sq(somg12) / (1 + comg12) : 1 - comg12); norm2(&salp2, &calp2); /* Set return value */ sig12 = atan2(ssig12, csig12); } else if (fabs(g->n) > 0.1 || /* No astroid calc if too eccentric */ csig12 >= 0 || ssig12 >= 6 * fabs(g->n) * pi * sq(cbet1)) { /* Nothing to do, zeroth order spherical approximation is OK */ } else { /* Scale lam12 and bet2 to x, y coordinate system where antipodal point * is at origin and singular point is at y = 0, x = -1. */ double x, y, lamscale, betscale; double lam12x = atan2(-slam12, -clam12); /* lam12 - pi */ if (g->f >= 0) { /* In fact f == 0 does not get here */ /* x = dlong, y = dlat */ { double k2 = sq(sbet1) * g->ep2, eps = k2 / (2 * (1 + sqrt(1 + k2)) + k2); lamscale = g->f * cbet1 * A3f(g, eps) * pi; } betscale = lamscale * cbet1; x = lam12x / lamscale; y = sbet12a / betscale; } else { /* f < 0 */ /* x = dlat, y = dlong */ double cbet12a = cbet2 * cbet1 - sbet2 * sbet1, bet12a = atan2(sbet12a, cbet12a); double m12b, m0; /* In the case of lon12 = 180, this repeats a calculation made in * Inverse. */ Lengths(g, g->n, pi + bet12a, sbet1, -cbet1, dn1, sbet2, cbet2, dn2, cbet1, cbet2, nullptr, &m12b, &m0, nullptr, nullptr, Ca); x = -1 + m12b / (cbet1 * cbet2 * m0 * pi); betscale = x < -0.01 ? sbet12a / x : -g->f * sq(cbet1) * pi; lamscale = betscale / cbet1; y = lam12x / lamscale; } if (y > -tol1 && x > -1 - xthresh) { /* strip near cut */ if (g->f >= 0) { salp1 = fmin(1.0, -x); calp1 = - sqrt(1 - sq(salp1)); } else { calp1 = fmax(x > -tol1 ? 0.0 : -1.0, x); salp1 = sqrt(1 - sq(calp1)); } } else { /* Estimate alp1, by solving the astroid problem. * * Could estimate alpha1 = theta + pi/2, directly, i.e., * calp1 = y/k; salp1 = -x/(1+k); for f >= 0 * calp1 = x/(1+k); salp1 = -y/k; for f < 0 (need to check) * * However, it's better to estimate omg12 from astroid and use * spherical formula to compute alp1. This reduces the mean number of * Newton iterations for astroid cases from 2.24 (min 0, max 6) to 2.12 * (min 0 max 5). The changes in the number of iterations are as * follows: * * change percent * 1 5 * 0 78 * -1 16 * -2 0.6 * -3 0.04 * -4 0.002 * * The histogram of iterations is (m = number of iterations estimating * alp1 directly, n = number of iterations estimating via omg12, total * number of trials = 148605): * * iter m n * 0 148 186 * 1 13046 13845 * 2 93315 102225 * 3 36189 32341 * 4 5396 7 * 5 455 1 * 6 56 0 * * Because omg12 is near pi, estimate work with omg12a = pi - omg12 */ double k = Astroid(x, y); double omg12a = lamscale * ( g->f >= 0 ? -x * k/(1 + k) : -y * (1 + k)/k ); somg12 = sin(omg12a); comg12 = -cos(omg12a); /* Update spherical estimate of alp1 using omg12 instead of lam12 */ salp1 = cbet2 * somg12; calp1 = sbet12a - cbet2 * sbet1 * sq(somg12) / (1 - comg12); } } /* Sanity check on starting guess. Backwards check allows NaN through. */ if (!(salp1 <= 0)) norm2(&salp1, &calp1); else { salp1 = 1; calp1 = 0; } *psalp1 = salp1; *pcalp1 = calp1; if (shortline) *pdnm = dnm; if (sig12 >= 0) { *psalp2 = salp2; *pcalp2 = calp2; } return sig12; } double Lambda12(const struct geod_geodesic* g, double sbet1, double cbet1, double dn1, double sbet2, double cbet2, double dn2, double salp1, double calp1, double slam120, double clam120, double* psalp2, double* pcalp2, double* psig12, double* pssig1, double* pcsig1, double* pssig2, double* pcsig2, double* peps, double* pdomg12, boolx diffp, double* pdlam12, /* Scratch area of the right size */ double Ca[]) { double salp2 = 0, calp2 = 0, sig12 = 0, ssig1 = 0, csig1 = 0, ssig2 = 0, csig2 = 0, eps = 0, domg12 = 0, dlam12 = 0; double salp0, calp0; double somg1, comg1, somg2, comg2, somg12, comg12, lam12; double B312, eta, k2; if (sbet1 == 0 && calp1 == 0) /* Break degeneracy of equatorial line. This case has already been * handled. */ calp1 = -tiny; /* sin(alp1) * cos(bet1) = sin(alp0) */ salp0 = salp1 * cbet1; calp0 = hypot(calp1, salp1 * sbet1); /* calp0 > 0 */ /* tan(bet1) = tan(sig1) * cos(alp1) * tan(omg1) = sin(alp0) * tan(sig1) = tan(omg1)=tan(alp1)*sin(bet1) */ ssig1 = sbet1; somg1 = salp0 * sbet1; csig1 = comg1 = calp1 * cbet1; norm2(&ssig1, &csig1); /* norm2(&somg1, &comg1); -- don't need to normalize! */ /* Enforce symmetries in the case abs(bet2) = -bet1. Need to be careful * about this case, since this can yield singularities in the Newton * iteration. * sin(alp2) * cos(bet2) = sin(alp0) */ salp2 = cbet2 != cbet1 ? salp0 / cbet2 : salp1; /* calp2 = sqrt(1 - sq(salp2)) * = sqrt(sq(calp0) - sq(sbet2)) / cbet2 * and subst for calp0 and rearrange to give (choose positive sqrt * to give alp2 in [0, pi/2]). */ calp2 = cbet2 != cbet1 || fabs(sbet2) != -sbet1 ? sqrt(sq(calp1 * cbet1) + (cbet1 < -sbet1 ? (cbet2 - cbet1) * (cbet1 + cbet2) : (sbet1 - sbet2) * (sbet1 + sbet2))) / cbet2 : fabs(calp1); /* tan(bet2) = tan(sig2) * cos(alp2) * tan(omg2) = sin(alp0) * tan(sig2). */ ssig2 = sbet2; somg2 = salp0 * sbet2; csig2 = comg2 = calp2 * cbet2; norm2(&ssig2, &csig2); /* norm2(&somg2, &comg2); -- don't need to normalize! */ /* sig12 = sig2 - sig1, limit to [0, pi] */ sig12 = atan2(fmax(0.0, csig1 * ssig2 - ssig1 * csig2) + 0, csig1 * csig2 + ssig1 * ssig2); /* omg12 = omg2 - omg1, limit to [0, pi] */ somg12 = fmax(0.0, comg1 * somg2 - somg1 * comg2) + 0; comg12 = comg1 * comg2 + somg1 * somg2; /* eta = omg12 - lam120 */ eta = atan2(somg12 * clam120 - comg12 * slam120, comg12 * clam120 + somg12 * slam120); k2 = sq(calp0) * g->ep2; eps = k2 / (2 * (1 + sqrt(1 + k2)) + k2); C3f(g, eps, Ca); B312 = (SinCosSeries(TRUE, ssig2, csig2, Ca, nC3-1) - SinCosSeries(TRUE, ssig1, csig1, Ca, nC3-1)); domg12 = -g->f * A3f(g, eps) * salp0 * (sig12 + B312); lam12 = eta + domg12; if (diffp) { if (calp2 == 0) dlam12 = - 2 * g->f1 * dn1 / sbet1; else { Lengths(g, eps, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2, nullptr, &dlam12, nullptr, nullptr, nullptr, Ca); dlam12 *= g->f1 / (calp2 * cbet2); } } *psalp2 = salp2; *pcalp2 = calp2; *psig12 = sig12; *pssig1 = ssig1; *pcsig1 = csig1; *pssig2 = ssig2; *pcsig2 = csig2; *peps = eps; *pdomg12 = domg12; if (diffp) *pdlam12 = dlam12; return lam12; } double A3f(const struct geod_geodesic* g, double eps) { /* Evaluate A3 */ return polyvalx(nA3 - 1, g->A3x, eps); } void C3f(const struct geod_geodesic* g, double eps, double c[]) { /* Evaluate C3 coeffs * Elements c[1] through c[nC3 - 1] are set */ double mult = 1; int o = 0, l; for (l = 1; l < nC3; ++l) { /* l is index of C3[l] */ int m = nC3 - l - 1; /* order of polynomial in eps */ mult *= eps; c[l] = mult * polyvalx(m, g->C3x + o, eps); o += m + 1; } } void C4f(const struct geod_geodesic* g, double eps, double c[]) { /* Evaluate C4 coeffs * Elements c[0] through c[nC4 - 1] are set */ double mult = 1; int o = 0, l; for (l = 0; l < nC4; ++l) { /* l is index of C4[l] */ int m = nC4 - l - 1; /* order of polynomial in eps */ c[l] = mult * polyvalx(m, g->C4x + o, eps); o += m + 1; mult *= eps; } } /* The scale factor A1-1 = mean value of (d/dsigma)I1 - 1 */ double A1m1f(double eps) { static const double coeff[] = { /* (1-eps)*A1-1, polynomial in eps2 of order 3 */ 1, 4, 64, 0, 256, }; int m = nA1/2; double t = polyvalx(m, coeff, sq(eps)) / coeff[m + 1]; return (t + eps) / (1 - eps); } /* The coefficients C1[l] in the Fourier expansion of B1 */ void C1f(double eps, double c[]) { static const double coeff[] = { /* C1[1]/eps^1, polynomial in eps2 of order 2 */ -1, 6, -16, 32, /* C1[2]/eps^2, polynomial in eps2 of order 2 */ -9, 64, -128, 2048, /* C1[3]/eps^3, polynomial in eps2 of order 1 */ 9, -16, 768, /* C1[4]/eps^4, polynomial in eps2 of order 1 */ 3, -5, 512, /* C1[5]/eps^5, polynomial in eps2 of order 0 */ -7, 1280, /* C1[6]/eps^6, polynomial in eps2 of order 0 */ -7, 2048, }; double eps2 = sq(eps), d = eps; int o = 0, l; for (l = 1; l <= nC1; ++l) { /* l is index of C1p[l] */ int m = (nC1 - l) / 2; /* order of polynomial in eps^2 */ c[l] = d * polyvalx(m, coeff + o, eps2) / coeff[o + m + 1]; o += m + 2; d *= eps; } } /* The coefficients C1p[l] in the Fourier expansion of B1p */ void C1pf(double eps, double c[]) { static const double coeff[] = { /* C1p[1]/eps^1, polynomial in eps2 of order 2 */ 205, -432, 768, 1536, /* C1p[2]/eps^2, polynomial in eps2 of order 2 */ 4005, -4736, 3840, 12288, /* C1p[3]/eps^3, polynomial in eps2 of order 1 */ -225, 116, 384, /* C1p[4]/eps^4, polynomial in eps2 of order 1 */ -7173, 2695, 7680, /* C1p[5]/eps^5, polynomial in eps2 of order 0 */ 3467, 7680, /* C1p[6]/eps^6, polynomial in eps2 of order 0 */ 38081, 61440, }; double eps2 = sq(eps), d = eps; int o = 0, l; for (l = 1; l <= nC1p; ++l) { /* l is index of C1p[l] */ int m = (nC1p - l) / 2; /* order of polynomial in eps^2 */ c[l] = d * polyvalx(m, coeff + o, eps2) / coeff[o + m + 1]; o += m + 2; d *= eps; } } /* The scale factor A2-1 = mean value of (d/dsigma)I2 - 1 */ double A2m1f(double eps) { static const double coeff[] = { /* (eps+1)*A2-1, polynomial in eps2 of order 3 */ -11, -28, -192, 0, 256, }; int m = nA2/2; double t = polyvalx(m, coeff, sq(eps)) / coeff[m + 1]; return (t - eps) / (1 + eps); } /* The coefficients C2[l] in the Fourier expansion of B2 */ void C2f(double eps, double c[]) { static const double coeff[] = { /* C2[1]/eps^1, polynomial in eps2 of order 2 */ 1, 2, 16, 32, /* C2[2]/eps^2, polynomial in eps2 of order 2 */ 35, 64, 384, 2048, /* C2[3]/eps^3, polynomial in eps2 of order 1 */ 15, 80, 768, /* C2[4]/eps^4, polynomial in eps2 of order 1 */ 7, 35, 512, /* C2[5]/eps^5, polynomial in eps2 of order 0 */ 63, 1280, /* C2[6]/eps^6, polynomial in eps2 of order 0 */ 77, 2048, }; double eps2 = sq(eps), d = eps; int o = 0, l; for (l = 1; l <= nC2; ++l) { /* l is index of C2[l] */ int m = (nC2 - l) / 2; /* order of polynomial in eps^2 */ c[l] = d * polyvalx(m, coeff + o, eps2) / coeff[o + m + 1]; o += m + 2; d *= eps; } } /* The scale factor A3 = mean value of (d/dsigma)I3 */ void A3coeff(struct geod_geodesic* g) { static const double coeff[] = { /* A3, coeff of eps^5, polynomial in n of order 0 */ -3, 128, /* A3, coeff of eps^4, polynomial in n of order 1 */ -2, -3, 64, /* A3, coeff of eps^3, polynomial in n of order 2 */ -1, -3, -1, 16, /* A3, coeff of eps^2, polynomial in n of order 2 */ 3, -1, -2, 8, /* A3, coeff of eps^1, polynomial in n of order 1 */ 1, -1, 2, /* A3, coeff of eps^0, polynomial in n of order 0 */ 1, 1, }; int o = 0, k = 0, j; for (j = nA3 - 1; j >= 0; --j) { /* coeff of eps^j */ int m = nA3 - j - 1 < j ? nA3 - j - 1 : j; /* order of polynomial in n */ g->A3x[k++] = polyvalx(m, coeff + o, g->n) / coeff[o + m + 1]; o += m + 2; } } /* The coefficients C3[l] in the Fourier expansion of B3 */ void C3coeff(struct geod_geodesic* g) { static const double coeff[] = { /* C3[1], coeff of eps^5, polynomial in n of order 0 */ 3, 128, /* C3[1], coeff of eps^4, polynomial in n of order 1 */ 2, 5, 128, /* C3[1], coeff of eps^3, polynomial in n of order 2 */ -1, 3, 3, 64, /* C3[1], coeff of eps^2, polynomial in n of order 2 */ -1, 0, 1, 8, /* C3[1], coeff of eps^1, polynomial in n of order 1 */ -1, 1, 4, /* C3[2], coeff of eps^5, polynomial in n of order 0 */ 5, 256, /* C3[2], coeff of eps^4, polynomial in n of order 1 */ 1, 3, 128, /* C3[2], coeff of eps^3, polynomial in n of order 2 */ -3, -2, 3, 64, /* C3[2], coeff of eps^2, polynomial in n of order 2 */ 1, -3, 2, 32, /* C3[3], coeff of eps^5, polynomial in n of order 0 */ 7, 512, /* C3[3], coeff of eps^4, polynomial in n of order 1 */ -10, 9, 384, /* C3[3], coeff of eps^3, polynomial in n of order 2 */ 5, -9, 5, 192, /* C3[4], coeff of eps^5, polynomial in n of order 0 */ 7, 512, /* C3[4], coeff of eps^4, polynomial in n of order 1 */ -14, 7, 512, /* C3[5], coeff of eps^5, polynomial in n of order 0 */ 21, 2560, }; int o = 0, k = 0, l, j; for (l = 1; l < nC3; ++l) { /* l is index of C3[l] */ for (j = nC3 - 1; j >= l; --j) { /* coeff of eps^j */ int m = nC3 - j - 1 < j ? nC3 - j - 1 : j; /* order of polynomial in n */ g->C3x[k++] = polyvalx(m, coeff + o, g->n) / coeff[o + m + 1]; o += m + 2; } } } /* The coefficients C4[l] in the Fourier expansion of I4 */ void C4coeff(struct geod_geodesic* g) { static const double coeff[] = { /* C4[0], coeff of eps^5, polynomial in n of order 0 */ 97, 15015, /* C4[0], coeff of eps^4, polynomial in n of order 1 */ 1088, 156, 45045, /* C4[0], coeff of eps^3, polynomial in n of order 2 */ -224, -4784, 1573, 45045, /* C4[0], coeff of eps^2, polynomial in n of order 3 */ -10656, 14144, -4576, -858, 45045, /* C4[0], coeff of eps^1, polynomial in n of order 4 */ 64, 624, -4576, 6864, -3003, 15015, /* C4[0], coeff of eps^0, polynomial in n of order 5 */ 100, 208, 572, 3432, -12012, 30030, 45045, /* C4[1], coeff of eps^5, polynomial in n of order 0 */ 1, 9009, /* C4[1], coeff of eps^4, polynomial in n of order 1 */ -2944, 468, 135135, /* C4[1], coeff of eps^3, polynomial in n of order 2 */ 5792, 1040, -1287, 135135, /* C4[1], coeff of eps^2, polynomial in n of order 3 */ 5952, -11648, 9152, -2574, 135135, /* C4[1], coeff of eps^1, polynomial in n of order 4 */ -64, -624, 4576, -6864, 3003, 135135, /* C4[2], coeff of eps^5, polynomial in n of order 0 */ 8, 10725, /* C4[2], coeff of eps^4, polynomial in n of order 1 */ 1856, -936, 225225, /* C4[2], coeff of eps^3, polynomial in n of order 2 */ -8448, 4992, -1144, 225225, /* C4[2], coeff of eps^2, polynomial in n of order 3 */ -1440, 4160, -4576, 1716, 225225, /* C4[3], coeff of eps^5, polynomial in n of order 0 */ -136, 63063, /* C4[3], coeff of eps^4, polynomial in n of order 1 */ 1024, -208, 105105, /* C4[3], coeff of eps^3, polynomial in n of order 2 */ 3584, -3328, 1144, 315315, /* C4[4], coeff of eps^5, polynomial in n of order 0 */ -128, 135135, /* C4[4], coeff of eps^4, polynomial in n of order 1 */ -2560, 832, 405405, /* C4[5], coeff of eps^5, polynomial in n of order 0 */ 128, 99099, }; int o = 0, k = 0, l, j; for (l = 0; l < nC4; ++l) { /* l is index of C4[l] */ for (j = nC4 - 1; j >= l; --j) { /* coeff of eps^j */ int m = nC4 - j - 1; /* order of polynomial in n */ g->C4x[k++] = polyvalx(m, coeff + o, g->n) / coeff[o + m + 1]; o += m + 2; } } } int transit(double lon1, double lon2) { double lon12; /* Return 1 or -1 if crossing prime meridian in east or west direction. * Otherwise return zero. */ /* Compute lon12 the same way as Geodesic::Inverse. */ lon12 = AngDiff(lon1, lon2, nullptr); lon1 = AngNormalize(lon1); lon2 = AngNormalize(lon2); return lon12 > 0 && ((lon1 < 0 && lon2 >= 0) || (lon1 > 0 && lon2 == 0)) ? 1 : (lon12 < 0 && lon1 >= 0 && lon2 < 0 ? -1 : 0); } int transitdirect(double lon1, double lon2) { /* Compute exactly the parity of * int(floor(lon2 / 360)) - int(floor(lon1 / 360)) */ lon1 = remainder(lon1, 2.0 * td); lon2 = remainder(lon2, 2.0 * td); return ( (lon2 >= 0 && lon2 < td ? 0 : 1) - (lon1 >= 0 && lon1 < td ? 0 : 1) ); } void accini(double s[]) { /* Initialize an accumulator; this is an array with two elements. */ s[0] = s[1] = 0; } void acccopy(const double s[], double t[]) { /* Copy an accumulator; t = s. */ t[0] = s[0]; t[1] = s[1]; } void accadd(double s[], double y) { /* Add y to an accumulator. */ double u, z = sumx(y, s[1], &u); s[0] = sumx(z, s[0], &s[1]); if (s[0] == 0) s[0] = u; else s[1] = s[1] + u; } double accsum(const double s[], double y) { /* Return accumulator + y (but don't add to accumulator). */ double t[2]; acccopy(s, t); accadd(t, y); return t[0]; } void accneg(double s[]) { /* Negate an accumulator. */ s[0] = -s[0]; s[1] = -s[1]; } void accrem(double s[], double y) { /* Reduce to [-y/2, y/2]. */ s[0] = remainder(s[0], y); accadd(s, 0.0); } void geod_polygon_init(struct geod_polygon* p, boolx polylinep) { p->polyline = (polylinep != 0); geod_polygon_clear(p); } void geod_polygon_clear(struct geod_polygon* p) { p->lat0 = p->lon0 = p->lat = p->lon = NaN; accini(p->P); accini(p->A); p->num = p->crossings = 0; } void geod_polygon_addpoint(const struct geod_geodesic* g, struct geod_polygon* p, double lat, double lon) { if (p->num == 0) { p->lat0 = p->lat = lat; p->lon0 = p->lon = lon; } else { double s12, S12 = 0; /* Initialize S12 to stop Visual Studio warning */ geod_geninverse(g, p->lat, p->lon, lat, lon, &s12, nullptr, nullptr, nullptr, nullptr, nullptr, p->polyline ? nullptr : &S12); accadd(p->P, s12); if (!p->polyline) { accadd(p->A, S12); p->crossings += transit(p->lon, lon); } p->lat = lat; p->lon = lon; } ++p->num; } void geod_polygon_addedge(const struct geod_geodesic* g, struct geod_polygon* p, double azi, double s) { if (p->num) { /* Do nothing is num is zero */ /* Initialize S12 to stop Visual Studio warning. Initialization of lat and * lon is to make CLang static analyzer happy. */ double lat = 0, lon = 0, S12 = 0; geod_gendirect(g, p->lat, p->lon, azi, GEOD_LONG_UNROLL, s, &lat, &lon, nullptr, nullptr, nullptr, nullptr, nullptr, p->polyline ? nullptr : &S12); accadd(p->P, s); if (!p->polyline) { accadd(p->A, S12); p->crossings += transitdirect(p->lon, lon); } p->lat = lat; p->lon = lon; ++p->num; } } unsigned geod_polygon_compute(const struct geod_geodesic* g, const struct geod_polygon* p, boolx reverse, boolx sign, double* pA, double* pP) { double s12, S12, t[2]; if (p->num < 2) { if (pP) *pP = 0; if (!p->polyline && pA) *pA = 0; return p->num; } if (p->polyline) { if (pP) *pP = p->P[0]; return p->num; } geod_geninverse(g, p->lat, p->lon, p->lat0, p->lon0, &s12, nullptr, nullptr, nullptr, nullptr, nullptr, &S12); if (pP) *pP = accsum(p->P, s12); acccopy(p->A, t); accadd(t, S12); if (pA) *pA = areareduceA(t, 4 * pi * g->c2, p->crossings + transit(p->lon, p->lon0), reverse, sign); return p->num; } unsigned geod_polygon_testpoint(const struct geod_geodesic* g, const struct geod_polygon* p, double lat, double lon, boolx reverse, boolx sign, double* pA, double* pP) { double perimeter, tempsum; int crossings, i; unsigned num = p->num + 1; if (num == 1) { if (pP) *pP = 0; if (!p->polyline && pA) *pA = 0; return num; } perimeter = p->P[0]; tempsum = p->polyline ? 0 : p->A[0]; crossings = p->crossings; for (i = 0; i < (p->polyline ? 1 : 2); ++i) { double s12, S12 = 0; /* Initialize S12 to stop Visual Studio warning */ geod_geninverse(g, i == 0 ? p->lat : lat, i == 0 ? p->lon : lon, i != 0 ? p->lat0 : lat, i != 0 ? p->lon0 : lon, &s12, nullptr, nullptr, nullptr, nullptr, nullptr, p->polyline ? nullptr : &S12); perimeter += s12; if (!p->polyline) { tempsum += S12; crossings += transit(i == 0 ? p->lon : lon, i != 0 ? p->lon0 : lon); } } if (pP) *pP = perimeter; if (p->polyline) return num; if (pA) *pA = areareduceB(tempsum, 4 * pi * g->c2, crossings, reverse, sign); return num; } unsigned geod_polygon_testedge(const struct geod_geodesic* g, const struct geod_polygon* p, double azi, double s, boolx reverse, boolx sign, double* pA, double* pP) { double perimeter, tempsum; int crossings; unsigned num = p->num + 1; if (num == 1) { /* we don't have a starting point! */ if (pP) *pP = NaN; if (!p->polyline && pA) *pA = NaN; return 0; } perimeter = p->P[0] + s; if (p->polyline) { if (pP) *pP = perimeter; return num; } tempsum = p->A[0]; crossings = p->crossings; { /* Initialization of lat, lon, and S12 is to make CLang static analyzer * happy. */ double lat = 0, lon = 0, s12, S12 = 0; geod_gendirect(g, p->lat, p->lon, azi, GEOD_LONG_UNROLL, s, &lat, &lon, nullptr, nullptr, nullptr, nullptr, nullptr, &S12); tempsum += S12; crossings += transitdirect(p->lon, lon); geod_geninverse(g, lat, lon, p->lat0, p->lon0, &s12, nullptr, nullptr, nullptr, nullptr, nullptr, &S12); perimeter += s12; tempsum += S12; crossings += transit(lon, p->lon0); } if (pP) *pP = perimeter; if (pA) *pA = areareduceB(tempsum, 4 * pi * g->c2, crossings, reverse, sign); return num; } void geod_polygonarea(const struct geod_geodesic* g, double lats[], double lons[], int n, double* pA, double* pP) { int i; struct geod_polygon p; geod_polygon_init(&p, FALSE); for (i = 0; i < n; ++i) geod_polygon_addpoint(g, &p, lats[i], lons[i]); geod_polygon_compute(g, &p, FALSE, TRUE, pA, pP); } double areareduceA(double area[], double area0, int crossings, boolx reverse, boolx sign) { accrem(area, area0); if (crossings & 1) accadd(area, (area[0] < 0 ? 1 : -1) * area0/2); /* area is with the clockwise sense. If !reverse convert to * counter-clockwise convention. */ if (!reverse) accneg(area); /* If sign put area in (-area0/2, area0/2], else put area in [0, area0) */ if (sign) { if (area[0] > area0/2) accadd(area, -area0); else if (area[0] <= -area0/2) accadd(area, +area0); } else { if (area[0] >= area0) accadd(area, -area0); else if (area[0] < 0) accadd(area, +area0); } return 0 + area[0]; } double areareduceB(double area, double area0, int crossings, boolx reverse, boolx sign) { area = remainder(area, area0); if (crossings & 1) area += (area < 0 ? 1 : -1) * area0/2; /* area is with the clockwise sense. If !reverse convert to * counter-clockwise convention. */ if (!reverse) area *= -1; /* If sign put area in (-area0/2, area0/2], else put area in [0, area0) */ if (sign) { if (area > area0/2) area -= area0; else if (area <= -area0/2) area += area0; } else { if (area >= area0) area -= area0; else if (area < 0) area += area0; } return 0 + area; } /** @endcond */
c
PROJ
data/projects/PROJ/src/tracing.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Tracing/profiling * 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. ****************************************************************************/ #ifdef ENABLE_TRACING #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include <stdlib.h> #include "proj/internal/internal.hpp" #include "proj/internal/tracing.hpp" //! @cond Doxygen_Suppress #if defined(_WIN32) && !defined(__CYGWIN__) #include <sys/timeb.h> #else #include <sys/time.h> /* for gettimeofday() */ #define CPLTimeVal timeval #define CPLGettimeofday(t, u) gettimeofday(t, u) #endif NS_PROJ_START using namespace internal; namespace tracing { #if defined(_WIN32) && !defined(__CYGWIN__) struct CPLTimeVal { time_t tv_sec; /* seconds */ long tv_usec; /* and microseconds */ }; // --------------------------------------------------------------------------- static void CPLGettimeofday(struct CPLTimeVal *tp, void * /* timezonep*/) { struct _timeb theTime; _ftime(&theTime); tp->tv_sec = static_cast<time_t>(theTime.time); tp->tv_usec = theTime.millitm * 1000; } #endif struct Singleton { FILE *f = nullptr; int callLevel = 0; int minDelayMicroSec = 10 * 1000; // 10 millisec long long startTimeStamp = 0; std::string componentsWhiteList{}; std::string componentsBlackList{}; Singleton(); ~Singleton(); Singleton(const Singleton &) = delete; Singleton &operator=(const Singleton &) = delete; void logTraceRaw(const std::string &str); }; // --------------------------------------------------------------------------- Singleton::Singleton() { const char *traceFile = getenv("PROJ_TRACE_FILE"); if (traceFile) f = fopen(traceFile, "wb"); if (!f) f = stderr; const char *minDelay = getenv("PROJ_TRACE_MIN_DELAY"); if (minDelay) { minDelayMicroSec = atoi(minDelay); } const char *whiteList = getenv("PROJ_TRACE_WHITE_LIST"); if (whiteList) { componentsWhiteList = whiteList; } const char *blackList = getenv("PROJ_TRACE_BLACK_LIST"); if (blackList) { componentsBlackList = blackList; } CPLTimeVal ts; CPLGettimeofday(&ts, nullptr); startTimeStamp = static_cast<long long>(ts.tv_sec) * 1000000 + ts.tv_usec; logTraceRaw("<log>"); ++callLevel; } // --------------------------------------------------------------------------- Singleton::~Singleton() { --callLevel; logTraceRaw("</log>"); fflush(f); if (f != stderr) fclose(f); } // --------------------------------------------------------------------------- static Singleton &getSingleton() { static Singleton singleton; return singleton; } // --------------------------------------------------------------------------- void Singleton::logTraceRaw(const std::string &str) { CPLTimeVal ts; CPLGettimeofday(&ts, nullptr); const auto ts_usec = static_cast<long long>(ts.tv_sec) * 1000000 + ts.tv_usec; fprintf(f, "<!-- %03d.%06d --> ", static_cast<int>((ts_usec - startTimeStamp) / 1000000), static_cast<int>((ts_usec - startTimeStamp) % 1000000)); for (int i = 0; i < callLevel; i++) fprintf(f, " "); fprintf(f, "%s\n", str.c_str()); fflush(f); } // --------------------------------------------------------------------------- void logTrace(const std::string &str, const std::string &component) { auto &singleton = getSingleton(); if (!singleton.componentsWhiteList.empty() && (component.empty() || singleton.componentsWhiteList.find(component) == std::string::npos)) { return; } if (!singleton.componentsBlackList.empty() && !component.empty() && singleton.componentsBlackList.find(component) != std::string::npos) { return; } std::string rawStr("<trace"); if (!component.empty()) { rawStr += " component='" + component + '\''; } rawStr += '>'; rawStr += str; rawStr += "</trace>"; singleton.logTraceRaw(rawStr); } // --------------------------------------------------------------------------- struct EnterBlock::Private { std::string msg_{}; CPLTimeVal startTimeStamp_{}; }; // --------------------------------------------------------------------------- EnterBlock::EnterBlock(const std::string &msg) : d(new Private()) { auto &singleton = getSingleton(); d->msg_ = msg; CPLGettimeofday(&d->startTimeStamp_, nullptr); singleton.logTraceRaw("<block_level_" + toString(singleton.callLevel) + ">"); ++singleton.callLevel; singleton.logTraceRaw("<enter>" + d->msg_ + "</enter>"); } // --------------------------------------------------------------------------- EnterBlock::~EnterBlock() { auto &singleton = getSingleton(); CPLTimeVal endTimeStamp; CPLGettimeofday(&endTimeStamp, nullptr); int delayMicroSec = static_cast<int>( (endTimeStamp.tv_usec - d->startTimeStamp_.tv_usec) + 1000000 * (endTimeStamp.tv_sec - d->startTimeStamp_.tv_sec)); std::string lengthStr; if (delayMicroSec >= singleton.minDelayMicroSec) { lengthStr = " length='" + toString(delayMicroSec / 1000) + "." + toString((delayMicroSec % 1000) / 100) + " msec'"; } singleton.logTraceRaw("<leave" + lengthStr + ">" + d->msg_ + "</leave>"); --singleton.callLevel; singleton.logTraceRaw("</block_level_" + toString(singleton.callLevel) + ">"); } } // namespace tracing NS_PROJ_END //! @endcond #endif // ENABLE_TRACING
cpp
PROJ
data/projects/PROJ/src/sqlite3_utils.cpp
/****************************************************************************** * Project: PROJ * Purpose: SQLite3 related utilities * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2019, 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. *****************************************************************************/ #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #endif #include "sqlite3_utils.hpp" #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #include <cstdlib> #include <cstring> #include <sstream> // std::ostringstream NS_PROJ_START // --------------------------------------------------------------------------- SQLite3VFS::SQLite3VFS(pj_sqlite3_vfs *vfs) : vfs_(vfs) {} // --------------------------------------------------------------------------- SQLite3VFS::~SQLite3VFS() { if (vfs_) { sqlite3_vfs_unregister(vfs_); delete vfs_; } } // --------------------------------------------------------------------------- const char *SQLite3VFS::name() const { return vfs_->namePtr.c_str(); } // --------------------------------------------------------------------------- typedef int (*ClosePtr)(sqlite3_file *); // --------------------------------------------------------------------------- static int VFSClose(sqlite3_file *file) { sqlite3_vfs *defaultVFS = sqlite3_vfs_find(nullptr); assert(defaultVFS); ClosePtr defaultClosePtr; std::memcpy(&defaultClosePtr, reinterpret_cast<char *>(file) + defaultVFS->szOsFile, sizeof(ClosePtr)); void *methods = const_cast<sqlite3_io_methods *>(file->pMethods); int ret = defaultClosePtr(file); std::free(methods); return ret; } // --------------------------------------------------------------------------- static int VSFNoOpLockUnlockSync(sqlite3_file *, int) { return SQLITE_OK; } // --------------------------------------------------------------------------- static int VFSCustomOpen(sqlite3_vfs *vfs, const char *name, sqlite3_file *file, int flags, int *outFlags) { auto realVFS = static_cast<pj_sqlite3_vfs *>(vfs); sqlite3_vfs *defaultVFS = static_cast<sqlite3_vfs *>(vfs->pAppData); int ret = defaultVFS->xOpen(defaultVFS, name, file, flags, outFlags); if (ret == SQLITE_OK) { ClosePtr defaultClosePtr = file->pMethods->xClose; assert(defaultClosePtr); sqlite3_io_methods *methods = static_cast<sqlite3_io_methods *>( std::malloc(sizeof(sqlite3_io_methods))); if (!methods) { file->pMethods->xClose(file); return SQLITE_NOMEM; } memcpy(methods, file->pMethods, sizeof(sqlite3_io_methods)); methods->xClose = VFSClose; if (realVFS->fakeSync) { // Disable xSync because it can be significantly slow and we don't // need // that level of data integrity guarantee for the cache. methods->xSync = VSFNoOpLockUnlockSync; } if (realVFS->fakeLock) { methods->xLock = VSFNoOpLockUnlockSync; methods->xUnlock = VSFNoOpLockUnlockSync; } file->pMethods = methods; // Save original xClose pointer at end of file structure std::memcpy(reinterpret_cast<char *>(file) + defaultVFS->szOsFile, &defaultClosePtr, sizeof(ClosePtr)); } return ret; } // --------------------------------------------------------------------------- static int VFSCustomAccess(sqlite3_vfs *vfs, const char *zName, int flags, int *pResOut) { sqlite3_vfs *defaultVFS = static_cast<sqlite3_vfs *>(vfs->pAppData); // Do not bother stat'ing for journal or wal files if (std::strstr(zName, "-journal") || std::strstr(zName, "-wal")) { *pResOut = false; return SQLITE_OK; } return defaultVFS->xAccess(defaultVFS, zName, flags, pResOut); } // --------------------------------------------------------------------------- // SQLite3 logging infrastructure static void projSqlite3LogCallback(void *, int iErrCode, const char *zMsg) { fprintf(stderr, "SQLite3 message: (code %d) %s\n", iErrCode, zMsg); } std::unique_ptr<SQLite3VFS> SQLite3VFS::create(bool fakeSync, bool fakeLock, bool skipStatJournalAndWAL) { // Install SQLite3 logger if PROJ_LOG_SQLITE3 env var is defined struct InstallSqliteLogger { InstallSqliteLogger() { if (getenv("PROJ_LOG_SQLITE3") != nullptr) { sqlite3_config(SQLITE_CONFIG_LOG, projSqlite3LogCallback, nullptr); } } }; static InstallSqliteLogger installSqliteLogger; // Call to sqlite3_initialize() is normally not needed, except for // people building SQLite3 with -DSQLITE_OMIT_AUTOINIT sqlite3_initialize(); sqlite3_vfs *defaultVFS = sqlite3_vfs_find(nullptr); assert(defaultVFS); auto vfs = new pj_sqlite3_vfs(); vfs->fakeSync = fakeSync; vfs->fakeLock = fakeLock; auto vfsUnique = std::unique_ptr<SQLite3VFS>(new SQLite3VFS(vfs)); std::ostringstream buffer; buffer << vfs; vfs->namePtr = buffer.str(); vfs->iVersion = 1; vfs->szOsFile = defaultVFS->szOsFile + sizeof(ClosePtr); vfs->mxPathname = defaultVFS->mxPathname; vfs->zName = vfs->namePtr.c_str(); vfs->pAppData = defaultVFS; vfs->xOpen = VFSCustomOpen; vfs->xDelete = defaultVFS->xDelete; vfs->xAccess = skipStatJournalAndWAL ? VFSCustomAccess : defaultVFS->xAccess; vfs->xFullPathname = defaultVFS->xFullPathname; vfs->xDlOpen = defaultVFS->xDlOpen; vfs->xDlError = defaultVFS->xDlError; vfs->xDlSym = defaultVFS->xDlSym; vfs->xDlClose = defaultVFS->xDlClose; vfs->xRandomness = defaultVFS->xRandomness; vfs->xSleep = defaultVFS->xSleep; vfs->xCurrentTime = defaultVFS->xCurrentTime; vfs->xGetLastError = defaultVFS->xGetLastError; vfs->xCurrentTimeInt64 = defaultVFS->xCurrentTimeInt64; if (sqlite3_vfs_register(vfs, false) == SQLITE_OK) { return vfsUnique; } delete vfsUnique->vfs_; vfsUnique->vfs_ = nullptr; return nullptr; } // --------------------------------------------------------------------------- SQLiteStatement::SQLiteStatement(sqlite3_stmt *hStmtIn) : hStmt(hStmtIn) {} // --------------------------------------------------------------------------- NS_PROJ_END
cpp
PROJ
data/projects/PROJ/src/proj_json_streaming_writer.hpp
/****************************************************************************** * * Project: CPL - Common Portability Library * Purpose: JSon streaming writer * Author: Even Rouault, even.rouault at spatialys.com * ****************************************************************************** * Copyright (c) 2019, 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. ****************************************************************************/ #ifndef PROJ_JSON_STREAMING_WRITER_H #define PROJ_JSON_STREAMING_WRITER_H /*! @cond Doxygen_Suppress */ #include <cstdint> #include <string> #include <vector> #define CPL_DLL #include "proj/util.hpp" NS_PROJ_START typedef std::int64_t GIntBig; typedef std::uint64_t GUInt64; class CPL_DLL CPLJSonStreamingWriter { public: typedef void (*SerializationFuncType)(const char *pszTxt, void *pUserData); private: CPLJSonStreamingWriter(const CPLJSonStreamingWriter &) = delete; CPLJSonStreamingWriter &operator=(const CPLJSonStreamingWriter &) = delete; std::string m_osStr{}; SerializationFuncType m_pfnSerializationFunc = nullptr; void *m_pUserData = nullptr; bool m_bPretty = true; std::string m_osIndent = std::string(" "); std::string m_osIndentAcc{}; int m_nLevel = 0; bool m_bNewLineEnabled = true; struct State { bool bIsObj = false; bool bFirstChild = true; explicit State(bool bIsObjIn) : bIsObj(bIsObjIn) {} }; std::vector<State> m_states{}; bool m_bWaitForValue = false; void Print(const std::string &text); void IncIndent(); void DecIndent(); static std::string FormatString(const std::string &str); void EmitCommaIfNeeded(); public: CPLJSonStreamingWriter(SerializationFuncType pfnSerializationFunc, void *pUserData); ~CPLJSonStreamingWriter(); void SetPrettyFormatting(bool bPretty) { m_bPretty = bPretty; } void SetIndentationSize(int nSpaces); // cppcheck-suppress functionStatic const std::string &GetString() const { return m_osStr; } void Add(const std::string &str); void Add(const char *pszStr); void AddUnquoted(const char *pszStr); void Add(bool bVal); void Add(int nVal) { Add(static_cast<GIntBig>(nVal)); } void Add(unsigned int nVal) { Add(static_cast<GIntBig>(nVal)); } void Add(GIntBig nVal); void Add(GUInt64 nVal); void Add(float fVal, int nPrecision = 9); void Add(double dfVal, int nPrecision = 18); void AddNull(); void StartObj(); void EndObj(); void AddObjKey(const std::string &key); struct CPL_DLL ObjectContext { CPLJSonStreamingWriter &m_serializer; ObjectContext(const ObjectContext &) = delete; ObjectContext(ObjectContext &&) = default; explicit inline ObjectContext(CPLJSonStreamingWriter &serializer) : m_serializer(serializer) { m_serializer.StartObj(); } ~ObjectContext() { m_serializer.EndObj(); } }; inline ObjectContext MakeObjectContext() { return ObjectContext(*this); } void StartArray(); void EndArray(); struct CPL_DLL ArrayContext { CPLJSonStreamingWriter &m_serializer; bool m_bForceSingleLine; bool m_bNewLineEnabledBackup; ArrayContext(const ArrayContext &) = delete; ArrayContext(ArrayContext &&) = default; inline explicit ArrayContext(CPLJSonStreamingWriter &serializer, bool bForceSingleLine = false) : m_serializer(serializer), m_bForceSingleLine(bForceSingleLine), m_bNewLineEnabledBackup(serializer.GetNewLine()) { if (m_bForceSingleLine) serializer.SetNewline(false); m_serializer.StartArray(); } ~ArrayContext() { m_serializer.EndArray(); if (m_bForceSingleLine) m_serializer.SetNewline(m_bNewLineEnabledBackup); } }; inline ArrayContext MakeArrayContext(bool bForceSingleLine = false) { return ArrayContext(*this, bForceSingleLine); } bool GetNewLine() const { return m_bNewLineEnabled; } void SetNewline(bool bEnabled) { m_bNewLineEnabled = bEnabled; } }; NS_PROJ_END /*! @endcond */ #endif // PROJ_JSON_STREAMING_WRITER_H
hpp
PROJ
data/projects/PROJ/src/wkt2_parser.h
/****************************************************************************** * Project: PROJ * Purpose: WKT2 parser grammar * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2018 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. ****************************************************************************/ #ifndef PJ_WKT2_PARSER_H_INCLUDED #define PJ_WKT2_PARSER_H_INCLUDED #ifndef DOXYGEN_SKIP #ifdef __cplusplus extern "C" { #endif typedef struct pj_wkt2_parse_context pj_wkt2_parse_context; #include "wkt2_generated_parser.h" void pj_wkt2_error(pj_wkt2_parse_context *context, const char *msg); int pj_wkt2_lex(YYSTYPE *pNode, pj_wkt2_parse_context *context); int pj_wkt2_parse(pj_wkt2_parse_context *context); #ifdef __cplusplus } std::string pj_wkt2_parse(const std::string &wkt); #endif #endif /* #ifndef DOXYGEN_SKIP */ #endif /* PJ_WKT2_PARSER_H_INCLUDED */
h
PROJ
data/projects/PROJ/src/release.cpp
/* <<< Release Notice for library >>> */ #include "proj.h" #include "proj_internal.h" #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) char const pj_release[] = "Rel. " STR(PROJ_VERSION_MAJOR) "." STR( PROJ_VERSION_MINOR) "." STR(PROJ_VERSION_PATCH) ", " "September 1st, 2024"; const char *pj_get_release() { return pj_release; }
cpp
PROJ
data/projects/PROJ/src/param.cpp
/* put parameters in linked list and retrieve */ #include <ctype.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proj.h" #include "proj_internal.h" /* create parameter list entry */ paralist *pj_mkparam(const char *str) { paralist *newitem; if ((newitem = (paralist *)malloc(sizeof(paralist) + strlen(str))) != nullptr) { newitem->used = 0; newitem->next = nullptr; if (*str == '+') ++str; (void)strcpy(newitem->param, str); } return newitem; } /* As pj_mkparam, but payload ends at first whitespace, rather than at end of * <str> */ paralist *pj_mkparam_ws(const char *str, const char **next_str) { paralist *newitem; size_t len = 0; if (nullptr == str) return nullptr; /* Find start and length of string */ while (isspace(*str)) str++; if (*str == '+') str++; bool in_string = false; for (; str[len] != '\0'; len++) { if (in_string) { if (str[len] == '"' && str[len + 1] == '"') { len++; } else if (str[len] == '"') { in_string = false; } } else if (str[len] == '=' && str[len + 1] == '"') { in_string = true; } else if (isspace(str[len])) { break; } } if (next_str) *next_str = str + len; /* Use calloc to automagically 0-terminate the copy */ newitem = (paralist *)calloc(1, sizeof(paralist) + len + 1); if (nullptr == newitem) return nullptr; memcpy(newitem->param, str, len); newitem->used = 0; newitem->next = nullptr; return newitem; } /**************************************************************************************/ paralist *pj_param_exists(paralist *list, const char *parameter) { /*************************************************************************************** Determine whether a given parameter exists in a paralist. If it does, return a pointer to the corresponding list element - otherwise return 0. In support of the pipeline syntax, the search is terminated once a "+step" list element is reached, in which case a 0 is returned, unless the parameter searched for is actually "step", in which case a pointer to the "step" list element is returned. This function is equivalent to the pj_param (...) call with the "opt" argument set to the parameter name preceeeded by a 't'. But by using this one, one avoids writing the code allocating memory for a new copy of parameter name, and prepending the t (for compile time known names, this is obviously not an issue). ***************************************************************************************/ paralist *next = list; const char *c = strchr(parameter, '='); size_t len = strlen(parameter); if (c) len = c - parameter; if (list == nullptr) return nullptr; for (next = list; next; next = next->next) { if (0 == strncmp(parameter, next->param, len) && (next->param[len] == '=' || next->param[len] == 0)) { next->used = 1; return next; } if (0 == strcmp(parameter, "step")) return nullptr; } return nullptr; } /************************************************************************/ /* pj_param() */ /* */ /* Test for presence or get parameter value. The first */ /* character in `opt' is a parameter type which can take the */ /* values: */ /* */ /* `t' - test for presence, return TRUE/FALSE in PROJVALUE.i */ /* `i' - integer value returned in PROJVALUE.i */ /* `d' - simple valued real input returned in PROJVALUE.f */ /* `r' - degrees (DMS translation applied), returned as */ /* radians in PROJVALUE.f */ /* `s' - string returned in PROJVALUE.s */ /* `b' - test for t/T/f/F, return in PROJVALUE.i */ /* */ /* Search is terminated when "step" is found, in which case */ /* 0 is returned, unless "step" was the target searched for. */ /* */ /************************************************************************/ PROJVALUE pj_param(PJ_CONTEXT *ctx, paralist *pl, const char *opt) { int type; unsigned l; PROJVALUE value = {0}; if (ctx == nullptr) ctx = pj_get_default_ctx(); type = *opt++; if (nullptr == strchr("tbirds", type)) { fprintf(stderr, "invalid request to pj_param, fatal\n"); exit(1); } pl = pj_param_exists(pl, opt); if (type == 't') { value.i = pl != nullptr; return value; } /* Not found */ if (nullptr == pl) { /* Return value after the switch, so that the return path is */ /* taken in all cases */ switch (type) { case 'b': case 'i': value.i = 0; break; case 'd': case 'r': value.f = 0.; break; case 's': value.s = nullptr; break; } return value; } /* Found parameter - now find its value */ pl->used |= 1; l = (int)strlen(opt); opt = pl->param + l; if (*opt == '=') ++opt; switch (type) { case 'i': /* integer input */ value.i = atoi(opt); for (const char *ptr = opt; *ptr != '\0'; ++ptr) { if (!(*ptr >= '0' && *ptr <= '9')) { proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); value.i = 0; } } break; case 'd': /* simple real input */ value.f = pj_atof(opt); break; case 'r': /* degrees input */ value.f = dmstor_ctx(ctx, opt, nullptr); break; case 's': /* char string */ value.s = (char *)opt; break; case 'b': /* boolean */ switch (*opt) { case 'F': case 'f': value.i = 0; break; case '\0': case 'T': case 't': value.i = 1; break; default: proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); value.i = 0; break; } break; } return value; }
cpp
PROJ
data/projects/PROJ/src/pr_list.cpp
/* print projection's list of parameters */ #include <stddef.h> #include <stdio.h> #include <string.h> #include "proj.h" #include "proj_internal.h" #define LINE_LEN 72 static int pr_list(PJ *P, int not_used) { paralist *t; int l, n = 1, flag = 0; (void)putchar('#'); for (t = P->params; t; t = t->next) if ((!not_used && t->used) || (not_used && !t->used)) { l = (int)strlen(t->param) + 1; if (n + l > LINE_LEN) { (void)fputs("\n#", stdout); n = 2; } (void)putchar(' '); if (*(t->param) != '+') (void)putchar('+'); (void)fputs(t->param, stdout); n += l; } else flag = 1; if (n > 1) (void)putchar('\n'); return flag; } void /* print link list of projection parameters */ pj_pr_list(PJ *P) { char const *s; (void)putchar('#'); for (s = P->descr; *s; ++s) { (void)putchar(*s); if (*s == '\n') (void)putchar('#'); } (void)putchar('\n'); if (pr_list(P, 0)) { (void)fputs("#--- following specified but NOT used\n", stdout); (void)pr_list(P, 1); } } /************************************************************************/ /* pj_get_def() */ /* */ /* Returns the PROJ.4 command string that would produce this */ /* definition expanded as much as possible. For instance, */ /* +init= calls and +datum= definitions would be expanded. */ /************************************************************************/ char *pj_get_def(PJ *P, int options) { paralist *t; int l; char *definition; size_t def_max = 10; (void)options; definition = (char *)malloc(def_max); if (!definition) return nullptr; definition[0] = '\0'; for (t = P->params; t; t = t->next) { /* skip unused parameters ... mostly appended defaults and stuff */ if (!t->used) continue; /* grow the resulting string if needed */ l = (int)strlen(t->param) + 1; if (strlen(definition) + l + 5 > def_max) { char *def2; def_max = def_max * 2 + l + 5; def2 = (char *)malloc(def_max); if (def2) { strcpy(def2, definition); free(definition); definition = def2; } else { free(definition); return nullptr; } } /* append this parameter */ strcat(definition, " +"); strcat(definition, t->param); } return definition; }
cpp
PROJ
data/projects/PROJ/src/datums.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Built in datum list. * 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. *****************************************************************************/ #include <stddef.h> #include "proj.h" #define PJ_DATUMS_ #include "proj_internal.h" /* * The ellipse code must match one from pj_ellps.c. The datum id should * be kept to 12 characters or less if possible. Use the official OGC * datum name for the comments if available. */ static const struct PJ_DATUMS pj_datums[] = { /* id definition ellipse comments */ /* -- ---------- ------- -------- */ {"WGS84", "towgs84=0,0,0", "WGS84", ""}, {"GGRS87", "towgs84=-199.87,74.79,246.62", "GRS80", "Greek_Geodetic_Reference_System_1987"}, {"NAD83", "towgs84=0,0,0", "GRS80", "North_American_Datum_1983"}, {"NAD27", "nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat", "clrk66", "North_American_Datum_1927"}, {"potsdam", /*"towgs84=598.1,73.7,418.2,0.202,0.045,-2.455,6.7",*/ "[email protected]", "bessel", "Potsdam Rauenberg 1950 DHDN"}, {"carthage", "towgs84=-263.0,6.0,431.0", "clrk80ign", "Carthage 1934 Tunisia"}, {"hermannskogel", "towgs84=577.326,90.129,463.919,5.137,1.474,5.297,2.4232", "bessel", "Hermannskogel"}, {"ire65", "towgs84=482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15", "mod_airy", "Ireland 1965"}, {"nzgd49", "towgs84=59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993", "intl", "New Zealand Geodetic Datum 1949"}, {"OSGB36", "towgs84=446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894", "airy", "Airy 1830"}, {nullptr, nullptr, nullptr, nullptr}}; const struct PJ_DATUMS *pj_get_datums_ref() { return pj_datums; } /* * This list is no longer updated, and some values may conflict with * other sources. */ static const struct PJ_PRIME_MERIDIANS pj_prime_meridians[] = { /* id definition */ /* -- ---------- */ {"greenwich", "0dE"}, {"lisbon", "9d07'54.862\"W"}, {"paris", "2d20'14.025\"E"}, {"bogota", "74d04'51.3\"W"}, {"madrid", "3d41'16.58\"W"}, /* EPSG:8905 is 3d41'14.55"W */ {"rome", "12d27'8.4\"E"}, {"bern", "7d26'22.5\"E"}, {"jakarta", "106d48'27.79\"E"}, {"ferro", "17d40'W"}, {"brussels", "4d22'4.71\"E"}, {"stockholm", "18d3'29.8\"E"}, {"athens", "23d42'58.815\"E"}, {"oslo", "10d43'22.5\"E"}, {"copenhagen", "12d34'40.35\"E"}, /* EPSG:1026 is 12d34'39.9"E */ {nullptr, nullptr}}; const PJ_PRIME_MERIDIANS *proj_list_prime_meridians(void) { return pj_prime_meridians; }
cpp
PROJ
data/projects/PROJ/src/filemanager.cpp
/****************************************************************************** * Project: PROJ * Purpose: File manager * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2019, 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. *****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif // proj_config.h must be included before testing HAVE_LIBDL #include "proj_config.h" #if defined(HAVE_LIBDL) && !defined(_GNU_SOURCE) // Required for dladdr() on Cygwin #define _GNU_SOURCE #endif #include <errno.h> #include <stdlib.h> #include <algorithm> #include <limits> #include <string> #include "filemanager.hpp" #include "proj.h" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" #include "proj/io.hpp" #include "proj_internal.h" #include <sys/stat.h> #ifdef _WIN32 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) #define UWP 1 #else #define UWP 0 #endif #include <shlobj.h> #include <windows.h> #else #ifdef HAVE_LIBDL #include <dlfcn.h> #endif #include <sys/types.h> #include <unistd.h> #endif //! @cond Doxygen_Suppress using namespace NS_PROJ::internal; NS_PROJ_START // --------------------------------------------------------------------------- File::File(const std::string &filename) : name_(filename) {} // --------------------------------------------------------------------------- File::~File() = default; // --------------------------------------------------------------------------- std::string File::read_line(size_t maxLen, bool &maxLenReached, bool &eofReached) { constexpr size_t MAX_MAXLEN = 1024 * 1024; maxLen = std::min(maxLen, MAX_MAXLEN); while (true) { // Consume existing lines in buffer size_t pos = readLineBuffer_.find_first_of("\r\n"); if (pos != std::string::npos) { if (pos > maxLen) { std::string ret(readLineBuffer_.substr(0, maxLen)); readLineBuffer_ = readLineBuffer_.substr(maxLen); maxLenReached = true; eofReached = false; return ret; } std::string ret(readLineBuffer_.substr(0, pos)); if (readLineBuffer_[pos] == '\r' && readLineBuffer_[pos + 1] == '\n') { pos += 1; } readLineBuffer_ = readLineBuffer_.substr(pos + 1); maxLenReached = false; eofReached = false; return ret; } const size_t prevSize = readLineBuffer_.size(); if (maxLen <= prevSize) { std::string ret(readLineBuffer_.substr(0, maxLen)); readLineBuffer_ = readLineBuffer_.substr(maxLen); maxLenReached = true; eofReached = false; return ret; } if (eofReadLine_) { std::string ret = readLineBuffer_; readLineBuffer_.clear(); maxLenReached = false; eofReached = ret.empty(); return ret; } readLineBuffer_.resize(maxLen); const size_t nRead = read(&readLineBuffer_[prevSize], maxLen - prevSize); if (nRead < maxLen - prevSize) eofReadLine_ = true; readLineBuffer_.resize(prevSize + nRead); } } // --------------------------------------------------------------------------- #ifdef _WIN32 /* The bulk of utf8towc()/utf8fromwc() is derived from the utf.c module from * FLTK. It was originally downloaded from: * http://svn.easysw.com/public/fltk/fltk/trunk/src/utf.c * And already used by GDAL */ /************************************************************************/ /* ==================================================================== */ /* UTF.C code from FLTK with some modifications. */ /* ==================================================================== */ /************************************************************************/ /* Set to 1 to turn bad UTF8 bytes into ISO-8859-1. If this is to zero they are instead turned into the Unicode REPLACEMENT CHARACTER, of value 0xfffd. If this is on utf8decode will correctly map most (perhaps all) human-readable text that is in ISO-8859-1. This may allow you to completely ignore character sets in your code because virtually everything is either ISO-8859-1 or UTF-8. */ #define ERRORS_TO_ISO8859_1 1 /* Set to 1 to turn bad UTF8 bytes in the 0x80-0x9f range into the Unicode index for Microsoft's CP1252 character set. You should also set ERRORS_TO_ISO8859_1. With this a huge amount of more available text (such as all web pages) are correctly converted to Unicode. */ #define ERRORS_TO_CP1252 1 /* A number of Unicode code points are in fact illegal and should not be produced by a UTF-8 converter. Turn this on will replace the bytes in those encodings with errors. If you do this then converting arbitrary 16-bit data to UTF-8 and then back is not an identity, which will probably break a lot of software. */ #define STRICT_RFC3629 0 #if ERRORS_TO_CP1252 // Codes 0x80..0x9f from the Microsoft CP1252 character set, translated // to Unicode: constexpr unsigned short cp1252[32] = { 0x20ac, 0x0081, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f, 0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178}; #endif /************************************************************************/ /* utf8decode() */ /************************************************************************/ /* Decode a single UTF-8 encoded character starting at \e p. The resulting Unicode value (in the range 0-0x10ffff) is returned, and \e len is set the number of bytes in the UTF-8 encoding (adding \e len to \e p will point at the next character). If \a p points at an illegal UTF-8 encoding, including one that would go past \e end, or where a code is uses more bytes than necessary, then *reinterpret_cast<const unsigned char*>(p) is translated as though it is in the Microsoft CP1252 character set and \e len is set to 1. Treating errors this way allows this to decode almost any ISO-8859-1 or CP1252 text that has been mistakenly placed where UTF-8 is expected, and has proven very useful. If you want errors to be converted to error characters (as the standards recommend), adding a test to see if the length is unexpectedly 1 will work: \code if( *p & 0x80 ) { // What should be a multibyte encoding. code = utf8decode(p, end, &len); if( len<2 ) code = 0xFFFD; // Turn errors into REPLACEMENT CHARACTER. } else { // Handle the 1-byte utf8 encoding: code = *p; len = 1; } \endcode Direct testing for the 1-byte case (as shown above) will also speed up the scanning of strings where the majority of characters are ASCII. */ static unsigned utf8decode(const char *p, const char *end, int *len) { unsigned char c = *reinterpret_cast<const unsigned char *>(p); if (c < 0x80) { *len = 1; return c; #if ERRORS_TO_CP1252 } else if (c < 0xa0) { *len = 1; return cp1252[c - 0x80]; #endif } else if (c < 0xc2) { goto FAIL; } if (p + 1 >= end || (p[1] & 0xc0) != 0x80) goto FAIL; if (c < 0xe0) { *len = 2; return ((p[0] & 0x1f) << 6) + ((p[1] & 0x3f)); } else if (c == 0xe0) { if ((reinterpret_cast<const unsigned char *>(p))[1] < 0xa0) goto FAIL; goto UTF8_3; #if STRICT_RFC3629 } else if (c == 0xed) { // RFC 3629 says surrogate chars are illegal. if ((reinterpret_cast<const unsigned char *>(p))[1] >= 0xa0) goto FAIL; goto UTF8_3; } else if (c == 0xef) { // 0xfffe and 0xffff are also illegal characters. if ((reinterpret_cast<const unsigned char *>(p))[1] == 0xbf && (reinterpret_cast<const unsigned char *>(p))[2] >= 0xbe) goto FAIL; goto UTF8_3; #endif } else if (c < 0xf0) { UTF8_3: if (p + 2 >= end || (p[2] & 0xc0) != 0x80) goto FAIL; *len = 3; return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + ((p[2] & 0x3f)); } else if (c == 0xf0) { if ((reinterpret_cast<const unsigned char *>(p))[1] < 0x90) goto FAIL; goto UTF8_4; } else if (c < 0xf4) { UTF8_4: if (p + 3 >= end || (p[2] & 0xc0) != 0x80 || (p[3] & 0xc0) != 0x80) goto FAIL; *len = 4; #if STRICT_RFC3629 // RFC 3629 says all codes ending in fffe or ffff are illegal: if ((p[1] & 0xf) == 0xf && (reinterpret_cast<const unsigned char *>(p))[2] == 0xbf && (reinterpret_cast<const unsigned char *>(p))[3] >= 0xbe) goto FAIL; #endif return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12) + ((p[2] & 0x3f) << 6) + ((p[3] & 0x3f)); } else if (c == 0xf4) { if ((reinterpret_cast<const unsigned char *>(p))[1] > 0x8f) goto FAIL; // After 0x10ffff. goto UTF8_4; } else { FAIL: *len = 1; #if ERRORS_TO_ISO8859_1 return c; #else return 0xfffd; // Unicode REPLACEMENT CHARACTER #endif } } /************************************************************************/ /* utf8towc() */ /************************************************************************/ /* Convert a UTF-8 sequence into an array of wchar_t. These are used by some system calls, especially on Windows. \a src points at the UTF-8, and \a srclen is the number of bytes to convert. \a dst points at an array to write, and \a dstlen is the number of locations in this array. At most \a dstlen-1 words will be written there, plus a 0 terminating word. Thus this function will never overwrite the buffer and will always return a zero-terminated string. If \a dstlen is zero then \a dst can be null and no data is written, but the length is returned. The return value is the number of words that \e would be written to \a dst if it were long enough, not counting the terminating zero. If the return value is greater or equal to \a dstlen it indicates truncation, you can then allocate a new array of size return+1 and call this again. Errors in the UTF-8 are converted as though each byte in the erroneous string is in the Microsoft CP1252 encoding. This allows ISO-8859-1 text mistakenly identified as UTF-8 to be printed correctly. Notice that sizeof(wchar_t) is 2 on Windows and is 4 on Linux and most other systems. Where wchar_t is 16 bits, Unicode characters in the range 0x10000 to 0x10ffff are converted to "surrogate pairs" which take two words each (this is called UTF-16 encoding). If wchar_t is 32 bits this rather nasty problem is avoided. */ static unsigned utf8towc(const char *src, unsigned srclen, wchar_t *dst, unsigned dstlen) { const char *p = src; const char *e = src + srclen; unsigned count = 0; if (dstlen) while (true) { if (p >= e) { dst[count] = 0; return count; } if (!(*p & 0x80)) { // ASCII dst[count] = *p++; } else { int len = 0; unsigned ucs = utf8decode(p, e, &len); p += len; #ifdef _WIN32 if (ucs < 0x10000) { dst[count] = static_cast<wchar_t>(ucs); } else { // Make a surrogate pair: if (count + 2 >= dstlen) { dst[count] = 0; count += 2; break; } dst[count] = static_cast<wchar_t>( (((ucs - 0x10000u) >> 10) & 0x3ff) | 0xd800); dst[++count] = static_cast<wchar_t>((ucs & 0x3ff) | 0xdc00); } #else dst[count] = static_cast<wchar_t>(ucs); #endif } if (++count == dstlen) { dst[count - 1] = 0; break; } } // We filled dst, measure the rest: while (p < e) { if (!(*p & 0x80)) { p++; } else { int len = 0; #ifdef _WIN32 const unsigned ucs = utf8decode(p, e, &len); p += len; if (ucs >= 0x10000) ++count; #else utf8decode(p, e, &len); p += len; #endif } ++count; } return count; } // --------------------------------------------------------------------------- struct NonValidUTF8Exception : public std::exception {}; // May throw exceptions static std::wstring UTF8ToWString(const std::string &str) { std::wstring wstr; wstr.resize(str.size()); wstr.resize(utf8towc(str.data(), static_cast<unsigned>(str.size()), &wstr[0], static_cast<unsigned>(wstr.size()) + 1)); for (const auto ch : wstr) { if (ch == 0xfffd) { throw NonValidUTF8Exception(); } } return wstr; } // --------------------------------------------------------------------------- /************************************************************************/ /* utf8fromwc() */ /************************************************************************/ /* Turn "wide characters" as returned by some system calls (especially on Windows) into UTF-8. Up to \a dstlen bytes are written to \a dst, including a null terminator. The return value is the number of bytes that would be written, not counting the null terminator. If greater or equal to \a dstlen then if you malloc a new array of size n+1 you will have the space needed for the entire string. If \a dstlen is zero then nothing is written and this call just measures the storage space needed. \a srclen is the number of words in \a src to convert. On Windows this is not necessarily the number of characters, due to there possibly being "surrogate pairs" in the UTF-16 encoding used. On Unix wchar_t is 32 bits and each location is a character. On Unix if a src word is greater than 0x10ffff then this is an illegal character according to RFC 3629. These are converted as though they are 0xFFFD (REPLACEMENT CHARACTER). Characters in the range 0xd800 to 0xdfff, or ending with 0xfffe or 0xffff are also illegal according to RFC 3629. However I encode these as though they are legal, so that utf8towc will return the original data. On Windows "surrogate pairs" are converted to a single character and UTF-8 encoded (as 4 bytes). Mismatched halves of surrogate pairs are converted as though they are individual characters. */ static unsigned int utf8fromwc(char *dst, unsigned dstlen, const wchar_t *src, unsigned srclen) { unsigned int i = 0; unsigned int count = 0; if (dstlen) while (true) { if (i >= srclen) { dst[count] = 0; return count; } unsigned int ucs = src[i++]; if (ucs < 0x80U) { dst[count++] = static_cast<char>(ucs); if (count >= dstlen) { dst[count - 1] = 0; break; } } else if (ucs < 0x800U) { // 2 bytes. if (count + 2 >= dstlen) { dst[count] = 0; count += 2; break; } dst[count++] = 0xc0 | static_cast<char>(ucs >> 6); dst[count++] = 0x80 | static_cast<char>(ucs & 0x3F); #ifdef _WIN32 } else if (ucs >= 0xd800 && ucs <= 0xdbff && i < srclen && src[i] >= 0xdc00 && src[i] <= 0xdfff) { // Surrogate pair. unsigned int ucs2 = src[i++]; ucs = 0x10000U + ((ucs & 0x3ff) << 10) + (ucs2 & 0x3ff); // All surrogate pairs turn into 4-byte utf8. #else } else if (ucs >= 0x10000) { if (ucs > 0x10ffff) { ucs = 0xfffd; goto J1; } #endif if (count + 4 >= dstlen) { dst[count] = 0; count += 4; break; } dst[count++] = 0xf0 | static_cast<char>(ucs >> 18); dst[count++] = 0x80 | static_cast<char>((ucs >> 12) & 0x3F); dst[count++] = 0x80 | static_cast<char>((ucs >> 6) & 0x3F); dst[count++] = 0x80 | static_cast<char>(ucs & 0x3F); } else { #ifndef _WIN32 J1: #endif // All others are 3 bytes: if (count + 3 >= dstlen) { dst[count] = 0; count += 3; break; } dst[count++] = 0xe0 | static_cast<char>(ucs >> 12); dst[count++] = 0x80 | static_cast<char>((ucs >> 6) & 0x3F); dst[count++] = 0x80 | static_cast<char>(ucs & 0x3F); } } // We filled dst, measure the rest: while (i < srclen) { unsigned int ucs = src[i++]; if (ucs < 0x80U) { count++; } else if (ucs < 0x800U) { // 2 bytes. count += 2; #ifdef _WIN32 } else if (ucs >= 0xd800 && ucs <= 0xdbff && i < srclen - 1 && src[i + 1] >= 0xdc00 && src[i + 1] <= 0xdfff) { // Surrogate pair. ++i; #else } else if (ucs >= 0x10000 && ucs <= 0x10ffff) { #endif count += 4; } else { count += 3; } } return count; } // --------------------------------------------------------------------------- static std::string WStringToUTF8(const std::wstring &wstr) { std::string str; str.resize(wstr.size()); str.resize(utf8fromwc(&str[0], static_cast<unsigned>(str.size() + 1), wstr.data(), static_cast<unsigned>(wstr.size()))); return str; } // --------------------------------------------------------------------------- static std::string Win32Recode(const char *src, unsigned src_code_page, unsigned dst_code_page) { // Convert from source code page to Unicode. // Compute the length in wide characters. int wlen = MultiByteToWideChar(src_code_page, MB_ERR_INVALID_CHARS, src, -1, nullptr, 0); if (wlen == 0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION) { return std::string(); } // Do the actual conversion. std::wstring wbuf; wbuf.resize(wlen); MultiByteToWideChar(src_code_page, 0, src, -1, &wbuf[0], wlen); // Convert from Unicode to destination code page. // Compute the length in chars. int len = WideCharToMultiByte(dst_code_page, 0, &wbuf[0], -1, nullptr, 0, nullptr, nullptr); // Do the actual conversion. std::string out; out.resize(len); WideCharToMultiByte(dst_code_page, 0, &wbuf[0], -1, &out[0], len, nullptr, nullptr); out.resize(strlen(out.c_str())); return out; } // --------------------------------------------------------------------------- class FileWin32 : public File { PJ_CONTEXT *m_ctx; HANDLE m_handle; FileWin32(const FileWin32 &) = delete; FileWin32 &operator=(const FileWin32 &) = delete; protected: FileWin32(const std::string &name, PJ_CONTEXT *ctx, HANDLE handle) : File(name), m_ctx(ctx), m_handle(handle) {} public: ~FileWin32() override; size_t read(void *buffer, size_t sizeBytes) override; size_t write(const void *buffer, size_t sizeBytes) override; bool seek(unsigned long long offset, int whence = SEEK_SET) override; unsigned long long tell() override; void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; } // We may lie, but the real use case is only for network files bool hasChanged() const override { return false; } static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename, FileAccess access); }; // --------------------------------------------------------------------------- FileWin32::~FileWin32() { CloseHandle(m_handle); } // --------------------------------------------------------------------------- size_t FileWin32::read(void *buffer, size_t sizeBytes) { DWORD dwSizeRead = 0; size_t nResult = 0; if (!ReadFile(m_handle, buffer, static_cast<DWORD>(sizeBytes), &dwSizeRead, nullptr)) nResult = 0; else nResult = dwSizeRead; return nResult; } // --------------------------------------------------------------------------- size_t FileWin32::write(const void *buffer, size_t sizeBytes) { DWORD dwSizeWritten = 0; size_t nResult = 0; if (!WriteFile(m_handle, buffer, static_cast<DWORD>(sizeBytes), &dwSizeWritten, nullptr)) nResult = 0; else nResult = dwSizeWritten; return nResult; } // --------------------------------------------------------------------------- bool FileWin32::seek(unsigned long long offset, int whence) { LONG dwMoveMethod, dwMoveHigh; uint32_t nMoveLow; LARGE_INTEGER li; switch (whence) { case SEEK_CUR: dwMoveMethod = FILE_CURRENT; break; case SEEK_END: dwMoveMethod = FILE_END; break; case SEEK_SET: default: dwMoveMethod = FILE_BEGIN; break; } li.QuadPart = offset; nMoveLow = li.LowPart; dwMoveHigh = li.HighPart; SetLastError(0); SetFilePointer(m_handle, nMoveLow, &dwMoveHigh, dwMoveMethod); return GetLastError() == NO_ERROR; } // --------------------------------------------------------------------------- unsigned long long FileWin32::tell() { LARGE_INTEGER li; li.HighPart = 0; li.LowPart = SetFilePointer(m_handle, 0, &(li.HighPart), FILE_CURRENT); return static_cast<unsigned long long>(li.QuadPart); } // --------------------------------------------------------------------------- std::unique_ptr<File> FileWin32::open(PJ_CONTEXT *ctx, const char *filename, FileAccess access) { DWORD dwDesiredAccess = access == FileAccess::READ_ONLY ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE; DWORD dwCreationDisposition = access == FileAccess::CREATE ? CREATE_ALWAYS : OPEN_EXISTING; DWORD dwFlagsAndAttributes = (dwDesiredAccess == GENERIC_READ) ? FILE_ATTRIBUTE_READONLY : FILE_ATTRIBUTE_NORMAL; try { #if UWP CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; ZeroMemory(&extendedParameters, sizeof(extendedParameters)); extendedParameters.dwSize = sizeof(extendedParameters); extendedParameters.dwFileAttributes = dwFlagsAndAttributes; HANDLE hFile = CreateFile2( UTF8ToWString(std::string(filename)).c_str(), dwDesiredAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, dwCreationDisposition, &extendedParameters); #else // UWP HANDLE hFile = CreateFileW( UTF8ToWString(std::string(filename)).c_str(), dwDesiredAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, dwCreationDisposition, dwFlagsAndAttributes, nullptr); #endif // UWP return std::unique_ptr<File>(hFile != INVALID_HANDLE_VALUE ? new FileWin32(filename, ctx, hFile) : nullptr); } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return nullptr; } } #else // --------------------------------------------------------------------------- class FileStdio : public File { PJ_CONTEXT *m_ctx; FILE *m_fp; FileStdio(const FileStdio &) = delete; FileStdio &operator=(const FileStdio &) = delete; protected: FileStdio(const std::string &filename, PJ_CONTEXT *ctx, FILE *fp) : File(filename), m_ctx(ctx), m_fp(fp) {} public: ~FileStdio() override; size_t read(void *buffer, size_t sizeBytes) override; size_t write(const void *buffer, size_t sizeBytes) override; bool seek(unsigned long long offset, int whence = SEEK_SET) override; unsigned long long tell() override; void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; } // We may lie, but the real use case is only for network files bool hasChanged() const override { return false; } static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename, FileAccess access); }; // --------------------------------------------------------------------------- FileStdio::~FileStdio() { fclose(m_fp); } // --------------------------------------------------------------------------- size_t FileStdio::read(void *buffer, size_t sizeBytes) { return fread(buffer, 1, sizeBytes, m_fp); } // --------------------------------------------------------------------------- size_t FileStdio::write(const void *buffer, size_t sizeBytes) { return fwrite(buffer, 1, sizeBytes, m_fp); } // --------------------------------------------------------------------------- bool FileStdio::seek(unsigned long long offset, int whence) { // TODO one day: use 64-bit offset compatible API if (offset != static_cast<unsigned long long>(static_cast<long>(offset))) { pj_log(m_ctx, PJ_LOG_ERROR, "Attempt at seeking to a 64 bit offset. Not supported yet"); return false; } return fseek(m_fp, static_cast<long>(offset), whence) == 0; } // --------------------------------------------------------------------------- unsigned long long FileStdio::tell() { // TODO one day: use 64-bit offset compatible API return ftell(m_fp); } // --------------------------------------------------------------------------- std::unique_ptr<File> FileStdio::open(PJ_CONTEXT *ctx, const char *filename, FileAccess access) { auto fp = fopen(filename, access == FileAccess::READ_ONLY ? "rb" : access == FileAccess::READ_UPDATE ? "r+b" : "w+b"); return std::unique_ptr<File>(fp ? new FileStdio(filename, ctx, fp) : nullptr); } #endif // _WIN32 // --------------------------------------------------------------------------- class FileApiAdapter : public File { PJ_CONTEXT *m_ctx; PROJ_FILE_HANDLE *m_fp; FileApiAdapter(const FileApiAdapter &) = delete; FileApiAdapter &operator=(const FileApiAdapter &) = delete; protected: FileApiAdapter(const std::string &filename, PJ_CONTEXT *ctx, PROJ_FILE_HANDLE *fp) : File(filename), m_ctx(ctx), m_fp(fp) {} public: ~FileApiAdapter() override; size_t read(void *buffer, size_t sizeBytes) override; size_t write(const void *, size_t) override; bool seek(unsigned long long offset, int whence = SEEK_SET) override; unsigned long long tell() override; void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; } // We may lie, but the real use case is only for network files bool hasChanged() const override { return false; } static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename, FileAccess access); }; // --------------------------------------------------------------------------- FileApiAdapter::~FileApiAdapter() { m_ctx->fileApi.close_cbk(m_ctx, m_fp, m_ctx->fileApi.user_data); } // --------------------------------------------------------------------------- size_t FileApiAdapter::read(void *buffer, size_t sizeBytes) { return m_ctx->fileApi.read_cbk(m_ctx, m_fp, buffer, sizeBytes, m_ctx->fileApi.user_data); } // --------------------------------------------------------------------------- size_t FileApiAdapter::write(const void *buffer, size_t sizeBytes) { return m_ctx->fileApi.write_cbk(m_ctx, m_fp, buffer, sizeBytes, m_ctx->fileApi.user_data); } // --------------------------------------------------------------------------- bool FileApiAdapter::seek(unsigned long long offset, int whence) { return m_ctx->fileApi.seek_cbk(m_ctx, m_fp, static_cast<long long>(offset), whence, m_ctx->fileApi.user_data) != 0; } // --------------------------------------------------------------------------- unsigned long long FileApiAdapter::tell() { return m_ctx->fileApi.tell_cbk(m_ctx, m_fp, m_ctx->fileApi.user_data); } // --------------------------------------------------------------------------- std::unique_ptr<File> FileApiAdapter::open(PJ_CONTEXT *ctx, const char *filename, FileAccess eAccess) { PROJ_OPEN_ACCESS eCAccess = PROJ_OPEN_ACCESS_READ_ONLY; switch (eAccess) { case FileAccess::READ_ONLY: // Initialized above break; case FileAccess::READ_UPDATE: eCAccess = PROJ_OPEN_ACCESS_READ_UPDATE; break; case FileAccess::CREATE: eCAccess = PROJ_OPEN_ACCESS_CREATE; break; } auto fp = ctx->fileApi.open_cbk(ctx, filename, eCAccess, ctx->fileApi.user_data); return std::unique_ptr<File>(fp ? new FileApiAdapter(filename, ctx, fp) : nullptr); } // --------------------------------------------------------------------------- std::unique_ptr<File> FileManager::open(PJ_CONTEXT *ctx, const char *filename, FileAccess access) { if (starts_with(filename, "http://") || starts_with(filename, "https://")) { if (!proj_context_is_network_enabled(ctx)) { pj_log( ctx, PJ_LOG_ERROR, "Attempt at accessing remote resource not authorized. Either " "set PROJ_NETWORK=ON or " "proj_context_set_enable_network(ctx, TRUE)"); return nullptr; } return pj_network_file_open(ctx, filename); } if (ctx->fileApi.open_cbk != nullptr) { return FileApiAdapter::open(ctx, filename, access); } #ifdef _WIN32 return FileWin32::open(ctx, filename, access); #else return FileStdio::open(ctx, filename, access); #endif } // --------------------------------------------------------------------------- bool FileManager::exists(PJ_CONTEXT *ctx, const char *filename) { if (ctx->fileApi.exists_cbk) { return ctx->fileApi.exists_cbk(ctx, filename, ctx->fileApi.user_data) != 0; } #ifdef _WIN32 struct __stat64 buf; try { return _wstat64(UTF8ToWString(filename).c_str(), &buf) == 0; } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return false; } #else (void)ctx; struct stat sStat; return stat(filename, &sStat) == 0; #endif } // --------------------------------------------------------------------------- bool FileManager::mkdir(PJ_CONTEXT *ctx, const char *filename) { if (ctx->fileApi.mkdir_cbk) { return ctx->fileApi.mkdir_cbk(ctx, filename, ctx->fileApi.user_data) != 0; } #ifdef _WIN32 try { return _wmkdir(UTF8ToWString(filename).c_str()) == 0; } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return false; } #else (void)ctx; return ::mkdir(filename, 0755) == 0; #endif } // --------------------------------------------------------------------------- bool FileManager::unlink(PJ_CONTEXT *ctx, const char *filename) { if (ctx->fileApi.unlink_cbk) { return ctx->fileApi.unlink_cbk(ctx, filename, ctx->fileApi.user_data) != 0; } #ifdef _WIN32 try { return _wunlink(UTF8ToWString(filename).c_str()) == 0; } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return false; } #else (void)ctx; return ::unlink(filename) == 0; #endif } // --------------------------------------------------------------------------- bool FileManager::rename(PJ_CONTEXT *ctx, const char *oldPath, const char *newPath) { if (ctx->fileApi.rename_cbk) { return ctx->fileApi.rename_cbk(ctx, oldPath, newPath, ctx->fileApi.user_data) != 0; } #ifdef _WIN32 try { return _wrename(UTF8ToWString(oldPath).c_str(), UTF8ToWString(newPath).c_str()) == 0; } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return false; } #else (void)ctx; return ::rename(oldPath, newPath) == 0; #endif } // --------------------------------------------------------------------------- std::string FileManager::getProjDataEnvVar(PJ_CONTEXT *ctx) { if (!ctx->env_var_proj_data.empty()) { return ctx->env_var_proj_data; } (void)ctx; std::string str; const char *envvar = getenv("PROJ_DATA"); if (!envvar) { envvar = getenv("PROJ_LIB"); // Legacy name. We should probably keep it // for a long time for nostalgic people :-) if (envvar) { pj_log(ctx, PJ_LOG_DEBUG, "PROJ_LIB environment variable is deprecated, and will be " "removed in a future release. You are encouraged to set " "PROJ_DATA instead"); } } if (!envvar) return str; str = envvar; #ifdef _WIN32 // Assume this is UTF-8. If not try to convert from ANSI page bool looksLikeUTF8 = false; try { UTF8ToWString(envvar); looksLikeUTF8 = true; } catch (const std::exception &) { } if (!looksLikeUTF8 || !exists(ctx, envvar)) { str = Win32Recode(envvar, CP_ACP, CP_UTF8); if (str.empty() || !exists(ctx, str.c_str())) str = envvar; } #endif ctx->env_var_proj_data = str; return str; } NS_PROJ_END // --------------------------------------------------------------------------- static void CreateDirectoryRecursively(PJ_CONTEXT *ctx, const std::string &path) { if (NS_PROJ::FileManager::exists(ctx, path.c_str())) return; auto pos = path.find_last_of("/\\"); if (pos == 0 || pos == std::string::npos) return; CreateDirectoryRecursively(ctx, path.substr(0, pos)); NS_PROJ::FileManager::mkdir(ctx, path.c_str()); } //! @endcond // --------------------------------------------------------------------------- /** Set a file API * * All callbacks should be provided (non NULL pointers). If read-only usage * is intended, then the callbacks might have a dummy implementation. * * \note Those callbacks will not be used for SQLite3 database access. If * custom I/O is desired for that, then proj_context_set_sqlite3_vfs_name() * should be used. * * @param ctx PROJ context, or NULL * @param fileapi Pointer to file API structure (content will be copied). * @param user_data Arbitrary pointer provided by the user, and passed to the * above callbacks. May be NULL. * @return TRUE in case of success. * @since 7.0 */ int proj_context_set_fileapi(PJ_CONTEXT *ctx, const PROJ_FILE_API *fileapi, void *user_data) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } if (!fileapi) { return false; } if (fileapi->version != 1) { return false; } if (!fileapi->open_cbk || !fileapi->close_cbk || !fileapi->read_cbk || !fileapi->write_cbk || !fileapi->seek_cbk || !fileapi->tell_cbk || !fileapi->exists_cbk || !fileapi->mkdir_cbk || !fileapi->unlink_cbk || !fileapi->rename_cbk) { return false; } ctx->fileApi.open_cbk = fileapi->open_cbk; ctx->fileApi.close_cbk = fileapi->close_cbk; ctx->fileApi.read_cbk = fileapi->read_cbk; ctx->fileApi.write_cbk = fileapi->write_cbk; ctx->fileApi.seek_cbk = fileapi->seek_cbk; ctx->fileApi.tell_cbk = fileapi->tell_cbk; ctx->fileApi.exists_cbk = fileapi->exists_cbk; ctx->fileApi.mkdir_cbk = fileapi->mkdir_cbk; ctx->fileApi.unlink_cbk = fileapi->unlink_cbk; ctx->fileApi.rename_cbk = fileapi->rename_cbk; ctx->fileApi.user_data = user_data; return true; } // --------------------------------------------------------------------------- /** Set the name of a custom SQLite3 VFS. * * This should be a valid SQLite3 VFS name, such as the one passed to the * sqlite3_vfs_register(). See https://www.sqlite.org/vfs.html * * It will be used to read proj.db or create&access the cache.db file in the * PROJ user writable directory. * * @param ctx PROJ context, or NULL * @param name SQLite3 VFS name. If NULL is passed, default implementation by * SQLite will be used. * @since 7.0 */ void proj_context_set_sqlite3_vfs_name(PJ_CONTEXT *ctx, const char *name) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } ctx->custom_sqlite3_vfs_name = name ? name : std::string(); } // --------------------------------------------------------------------------- /** Get the PROJ user writable directory for datumgrid files. * * @param ctx PROJ context, or NULL * @param create If set to TRUE, create the directory if it does not exist * already. * @return The path to the PROJ user writable directory. * @since 7.1 */ const char *proj_context_get_user_writable_directory(PJ_CONTEXT *ctx, int create) { if (!ctx) ctx = pj_get_default_ctx(); if (ctx->user_writable_directory.empty()) { // For testing purposes only const char *env_var_PROJ_USER_WRITABLE_DIRECTORY = getenv("PROJ_USER_WRITABLE_DIRECTORY"); if (env_var_PROJ_USER_WRITABLE_DIRECTORY && env_var_PROJ_USER_WRITABLE_DIRECTORY[0] != '\0') { ctx->user_writable_directory = env_var_PROJ_USER_WRITABLE_DIRECTORY; } } if (ctx->user_writable_directory.empty()) { std::string path; #ifdef _WIN32 #ifdef __MINGW32__ std::wstring wPath; wPath.resize(MAX_PATH); if (SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, &wPath[0]) == S_OK) { wPath.resize(wcslen(wPath.data())); path = NS_PROJ::WStringToUTF8(wPath); #else #if UWP if (false) { #else // UWP wchar_t *wPath; if (SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &wPath) == S_OK) { std::wstring ws(wPath); std::string str = NS_PROJ::WStringToUTF8(ws); path = str; CoTaskMemFree(wPath); #endif // UWP #endif } else { const char *local_app_data = getenv("LOCALAPPDATA"); if (!local_app_data) { local_app_data = getenv("TEMP"); if (!local_app_data) { local_app_data = "c:/users"; } } path = local_app_data; } #else const char *xdg_data_home = getenv("XDG_DATA_HOME"); if (xdg_data_home != nullptr) { path = xdg_data_home; } else { const char *home = getenv("HOME"); if (home && access(home, W_OK) == 0) { #if defined(__MACH__) && defined(__APPLE__) path = std::string(home) + "/Library/Application Support"; #else path = std::string(home) + "/.local/share"; #endif } else { path = "/tmp"; } } #endif path += "/proj"; ctx->user_writable_directory = std::move(path); } if (create != FALSE) { CreateDirectoryRecursively(ctx, ctx->user_writable_directory); } return ctx->user_writable_directory.c_str(); } /** Get the URL endpoint to query for remote grids. * * @param ctx PROJ context, or NULL * @return Endpoint URL. The returned pointer would be invalidated * by a later call to proj_context_set_url_endpoint() * @since 7.1 */ const char *proj_context_get_url_endpoint(PJ_CONTEXT *ctx) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } if (!ctx->endpoint.empty()) { return ctx->endpoint.c_str(); } pj_load_ini(ctx); return ctx->endpoint.c_str(); } // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress // --------------------------------------------------------------------------- void pj_context_set_user_writable_directory(PJ_CONTEXT *ctx, const std::string &path) { if (!ctx) ctx = pj_get_default_ctx(); ctx->user_writable_directory = path; } // --------------------------------------------------------------------------- #ifdef WIN32 static const char dir_chars[] = "/\\"; #else static const char dir_chars[] = "/"; #endif static bool is_tilde_slash(const char *name) { return *name == '~' && strchr(dir_chars, name[1]); } static bool is_rel_or_absolute_filename(const char *name) { return strchr(dir_chars, *name) || (*name == '.' && strchr(dir_chars, name[1])) || (!strncmp(name, "..", 2) && strchr(dir_chars, name[2])) || (name[0] != '\0' && name[1] == ':' && strchr(dir_chars, name[2])); } // --------------------------------------------------------------------------- static std::string pj_get_relative_share_proj_internal_no_check() { #if defined(_WIN32) || defined(HAVE_LIBDL) #ifdef _WIN32 HMODULE hm = NULL; #if !UWP if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)&pj_get_relative_share_proj, &hm) == 0) { return std::string(); } #endif // UWP DWORD path_size = 1024; std::wstring wout; for (;;) { wout.clear(); wout.resize(path_size); DWORD result = GetModuleFileNameW(hm, &wout[0], path_size - 1); DWORD last_error = GetLastError(); if (result == 0) { return std::string(); } else if (result == path_size - 1) { if (ERROR_INSUFFICIENT_BUFFER != last_error) { return std::string(); } path_size = path_size * 2; } else { break; } } wout.resize(wcslen(wout.c_str())); std::string out = NS_PROJ::WStringToUTF8(wout); constexpr char dir_sep = '\\'; #else Dl_info info; if (!dladdr((void *)pj_get_relative_share_proj, &info)) { return std::string(); } std::string out(info.dli_fname); constexpr char dir_sep = '/'; // "optimization" for cmake builds where RUNPATH is set to ${prefix}/lib out = replaceAll(out, "/bin/../", "/"); #ifdef __linux // If we get a filename without any path, this is most likely a static // binary. Resolve the executable name if (out.find(dir_sep) == std::string::npos) { constexpr size_t BUFFER_SIZE = 1024; std::vector<char> path(BUFFER_SIZE + 1); ssize_t nResultLen = readlink("/proc/self/exe", &path[0], BUFFER_SIZE); if (nResultLen >= 0 && static_cast<size_t>(nResultLen) < BUFFER_SIZE) { out.assign(path.data(), static_cast<size_t>(nResultLen)); } } #endif if (starts_with(out, "./")) out = out.substr(2); #endif auto pos = out.find_last_of(dir_sep); if (pos == std::string::npos) { // The initial path was something like libproj.so" out = "../share/proj"; return out; } out.resize(pos); pos = out.find_last_of(dir_sep); if (pos == std::string::npos) { // The initial path was something like bin/libproj.so" out = "share/proj"; return out; } out.resize(pos); // The initial path was something like foo/bin/libproj.so" out += "/share/proj"; return out; #else return std::string(); #endif } static std::string pj_get_relative_share_proj_internal_check_exists(PJ_CONTEXT *ctx) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } std::string path(pj_get_relative_share_proj_internal_no_check()); if (!path.empty() && NS_PROJ::FileManager::exists(ctx, path.c_str())) { return path; } return std::string(); } std::string pj_get_relative_share_proj(PJ_CONTEXT *ctx) { static std::string path( pj_get_relative_share_proj_internal_check_exists(ctx)); return path; } // --------------------------------------------------------------------------- static bool get_path_from_relative_share_proj(PJ_CONTEXT *ctx, const char *name, std::string &out) { out = pj_get_relative_share_proj(ctx); if (out.empty()) { return false; } out += '/'; out += name; return NS_PROJ::FileManager::exists(ctx, out.c_str()); } /************************************************************************/ /* pj_open_lib_internal() */ /************************************************************************/ #ifdef WIN32 static const char dirSeparator = ';'; #else static const char dirSeparator = ':'; #endif static const char *proj_data_name = #ifdef PROJ_DATA PROJ_DATA; #else nullptr; #endif #ifdef PROJ_DATA_ENV_VAR_TRIED_LAST static bool gbPROJ_DATA_ENV_VAR_TRIED_LAST = true; #else static bool gbPROJ_DATA_ENV_VAR_TRIED_LAST = false; #endif static bool dontReadUserWritableDirectory() { // Env var mostly for testing purposes and being independent from // an existing installation const char *envVar = getenv("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY"); return envVar != nullptr && envVar[0] != '\0'; } static void *pj_open_lib_internal( PJ_CONTEXT *ctx, const char *name, const char *mode, void *(*open_file)(PJ_CONTEXT *, const char *, const char *), char *out_full_filename, size_t out_full_filename_size) { try { std::string fname; void *fid = nullptr; const char *tmpname = nullptr; std::string projLib; if (ctx == nullptr) { ctx = pj_get_default_ctx(); } if (out_full_filename != nullptr && out_full_filename_size > 0) out_full_filename[0] = '\0'; auto open_lib_from_paths = [&ctx, open_file, &name, &fname, &mode](const std::string &projLibPaths) { void *lib_fid = nullptr; auto paths = NS_PROJ::internal::split(projLibPaths, dirSeparator); for (const auto &path : paths) { fname = NS_PROJ::internal::stripQuotes(path); fname += DIR_CHAR; fname += name; lib_fid = open_file(ctx, fname.c_str(), mode); if (lib_fid) break; } return lib_fid; }; /* check if ~/name */ if (is_tilde_slash(name)) if (const char *home = getenv("HOME")) { fname = home; fname += DIR_CHAR; fname += name; } else return nullptr; /* or fixed path: /name, ./name or ../name */ else if (is_rel_or_absolute_filename(name)) { fname = name; #ifdef _WIN32 try { NS_PROJ::UTF8ToWString(name); } catch (const std::exception &) { fname = NS_PROJ::Win32Recode(name, CP_ACP, CP_UTF8); } #endif } else if (starts_with(name, "http://") || starts_with(name, "https://")) fname = name; /* or try to use application provided file finder */ else if (ctx->file_finder != nullptr && (tmpname = ctx->file_finder( ctx, name, ctx->file_finder_user_data)) != nullptr) { fname = tmpname; } /* The user has search paths set */ else if (!ctx->search_paths.empty()) { for (const auto &path : ctx->search_paths) { try { fname = path; fname += DIR_CHAR; fname += name; fid = open_file(ctx, fname.c_str(), mode); } catch (const std::exception &) { } if (fid) break; } } else if (!dontReadUserWritableDirectory() && (fid = open_file( ctx, (std::string(proj_context_get_user_writable_directory( ctx, false)) + DIR_CHAR + name) .c_str(), mode)) != nullptr) { fname = proj_context_get_user_writable_directory(ctx, false); fname += DIR_CHAR; fname += name; } /* if the environment PROJ_DATA defined, and *not* tried as last possibility */ else if (!gbPROJ_DATA_ENV_VAR_TRIED_LAST && !(projLib = NS_PROJ::FileManager::getProjDataEnvVar(ctx)) .empty()) { fid = open_lib_from_paths(projLib); } else if (get_path_from_relative_share_proj(ctx, name, fname)) { /* check if it lives in a ../share/proj dir of the proj dll */ } else if (proj_data_name != nullptr && (fid = open_file( ctx, (std::string(proj_data_name) + DIR_CHAR + name).c_str(), mode)) != nullptr) { /* or hardcoded path */ fname = proj_data_name; fname += DIR_CHAR; fname += name; } /* if the environment PROJ_DATA defined, and tried as last possibility */ else if (gbPROJ_DATA_ENV_VAR_TRIED_LAST && !(projLib = NS_PROJ::FileManager::getProjDataEnvVar(ctx)) .empty()) { fid = open_lib_from_paths(projLib); } else { /* just try it bare bones */ fname = name; } if (fid != nullptr || (fid = open_file(ctx, fname.c_str(), mode)) != nullptr) { if (out_full_filename != nullptr && out_full_filename_size > 0) { // cppcheck-suppress nullPointer strncpy(out_full_filename, fname.c_str(), out_full_filename_size); out_full_filename[out_full_filename_size - 1] = '\0'; } errno = 0; } if (ctx->last_errno == 0 && errno != 0) proj_context_errno_set(ctx, errno); pj_log(ctx, PJ_LOG_DEBUG, "pj_open_lib(%s): call fopen(%s) - %s", name, fname.c_str(), fid == nullptr ? "failed" : "succeeded"); return (fid); } catch (const std::exception &) { pj_log(ctx, PJ_LOG_DEBUG, "pj_open_lib(%s): out of memory", name); return nullptr; } } /************************************************************************/ /* pj_get_default_searchpaths() */ /************************************************************************/ std::vector<std::string> pj_get_default_searchpaths(PJ_CONTEXT *ctx) { std::vector<std::string> ret; // Env var mostly for testing purposes and being independent from // an existing installation const char *ignoreUserWritableDirectory = getenv("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY"); if (ignoreUserWritableDirectory == nullptr || ignoreUserWritableDirectory[0] == '\0') { ret.push_back(proj_context_get_user_writable_directory(ctx, false)); } const std::string envPROJ_DATA = NS_PROJ::FileManager::getProjDataEnvVar(ctx); const std::string relativeSharedProj = pj_get_relative_share_proj(ctx); if (gbPROJ_DATA_ENV_VAR_TRIED_LAST) { /* Situation where PROJ_DATA environment variable is tried in last */ #ifdef PROJ_DATA ret.push_back(PROJ_DATA); #endif if (!relativeSharedProj.empty()) { ret.push_back(relativeSharedProj); } if (!envPROJ_DATA.empty()) { ret.push_back(envPROJ_DATA); } } else { /* Situation where PROJ_DATA environment variable is used if defined */ if (!envPROJ_DATA.empty()) { ret.push_back(envPROJ_DATA); } else { if (!relativeSharedProj.empty()) { ret.push_back(relativeSharedProj); } #ifdef PROJ_DATA ret.push_back(PROJ_DATA); #endif } } return ret; } /************************************************************************/ /* pj_open_file_with_manager() */ /************************************************************************/ static void *pj_open_file_with_manager(PJ_CONTEXT *ctx, const char *name, const char * /* mode */) { return NS_PROJ::FileManager::open(ctx, name, NS_PROJ::FileAccess::READ_ONLY) .release(); } // --------------------------------------------------------------------------- static NS_PROJ::io::DatabaseContextPtr getDBcontext(PJ_CONTEXT *ctx) { try { return ctx->get_cpp_context()->getDatabaseContext().as_nullable(); } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return nullptr; } } /************************************************************************/ /* FileManager::open_resource_file() */ /************************************************************************/ std::unique_ptr<NS_PROJ::File> NS_PROJ::FileManager::open_resource_file(PJ_CONTEXT *ctx, const char *name, char *out_full_filename, size_t out_full_filename_size) { if (ctx == nullptr) { ctx = pj_get_default_ctx(); } auto file = std::unique_ptr<NS_PROJ::File>(reinterpret_cast<NS_PROJ::File *>( pj_open_lib_internal(ctx, name, "rb", pj_open_file_with_manager, out_full_filename, out_full_filename_size))); // Retry with the new proj grid name if the file name doesn't end with .tif std::string tmpString; // keep it in this upper scope ! if (file == nullptr && !is_tilde_slash(name) && !is_rel_or_absolute_filename(name) && !starts_with(name, "http://") && !starts_with(name, "https://") && strcmp(name, "proj.db") != 0 && strstr(name, ".tif") == nullptr) { auto dbContext = getDBcontext(ctx); if (dbContext) { try { const auto filename = dbContext->getProjGridName(name); if (!filename.empty()) { file.reset(reinterpret_cast<NS_PROJ::File *>( pj_open_lib_internal(ctx, filename.c_str(), "rb", pj_open_file_with_manager, out_full_filename, out_full_filename_size))); if (file) { proj_context_errno_set(ctx, 0); } else { // For final network access attempt, use the new // name. tmpString = filename; name = tmpString.c_str(); } } } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return nullptr; } } } // Retry with the old proj grid name if the file name ends with .tif else if (file == nullptr && !is_tilde_slash(name) && !is_rel_or_absolute_filename(name) && !starts_with(name, "http://") && !starts_with(name, "https://") && strstr(name, ".tif") != nullptr) { auto dbContext = getDBcontext(ctx); if (dbContext) { try { const auto filename = dbContext->getOldProjGridName(name); if (!filename.empty()) { file.reset(reinterpret_cast<NS_PROJ::File *>( pj_open_lib_internal(ctx, filename.c_str(), "rb", pj_open_file_with_manager, out_full_filename, out_full_filename_size))); if (file) { proj_context_errno_set(ctx, 0); } } } catch (const std::exception &e) { pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what()); return nullptr; } } } if (file == nullptr && !is_tilde_slash(name) && !is_rel_or_absolute_filename(name) && !starts_with(name, "http://") && !starts_with(name, "https://") && proj_context_is_network_enabled(ctx)) { std::string remote_file(proj_context_get_url_endpoint(ctx)); if (!remote_file.empty()) { if (remote_file.back() != '/') { remote_file += '/'; } remote_file += name; file = open(ctx, remote_file.c_str(), NS_PROJ::FileAccess::READ_ONLY); if (file) { if (out_full_filename) { strncpy(out_full_filename, remote_file.c_str(), out_full_filename_size); out_full_filename[out_full_filename_size - 1] = '\0'; } pj_log(ctx, PJ_LOG_DEBUG, "Using %s", remote_file.c_str()); proj_context_errno_set(ctx, 0); } } } return file; } /************************************************************************/ /* pj_find_file() */ /************************************************************************/ /** Returns the full filename corresponding to a proj resource file specified * as a short filename. * * @param ctx context. * @param short_filename short filename (e.g. us_nga_egm96_15.tif). * Must not be NULL. * @param out_full_filename output buffer, of size out_full_filename_size, that * will receive the full filename on success. * Will be zero-terminated. * @param out_full_filename_size size of out_full_filename. * @return 1 if the file was found, 0 otherwise. */ int pj_find_file(PJ_CONTEXT *ctx, const char *short_filename, char *out_full_filename, size_t out_full_filename_size) { const bool old_network_enabled = proj_context_is_network_enabled(ctx) != FALSE; if (old_network_enabled) proj_context_set_enable_network(ctx, false); auto file = NS_PROJ::FileManager::open_resource_file( ctx, short_filename, out_full_filename, out_full_filename_size); if (old_network_enabled) proj_context_set_enable_network(ctx, true); return file != nullptr; } /************************************************************************/ /* trim() */ /************************************************************************/ static std::string trim(const std::string &s) { const auto first = s.find_first_not_of(' '); const auto last = s.find_last_not_of(' '); if (first == std::string::npos || last == std::string::npos) { return std::string(); } return s.substr(first, last - first + 1); } /************************************************************************/ /* pj_load_ini() */ /************************************************************************/ void pj_load_ini(PJ_CONTEXT *ctx) { if (ctx->iniFileLoaded) return; // Start reading environment variables that have priority over the // .ini file const char *proj_network = getenv("PROJ_NETWORK"); if (proj_network && proj_network[0] != '\0') { ctx->networking.enabled = ci_equal(proj_network, "ON") || ci_equal(proj_network, "YES") || ci_equal(proj_network, "TRUE"); } else { proj_network = nullptr; } const char *endpoint_from_env = getenv("PROJ_NETWORK_ENDPOINT"); if (endpoint_from_env && endpoint_from_env[0] != '\0') { ctx->endpoint = endpoint_from_env; } // Custom path to SSL certificates. const char *ca_bundle_path = getenv("PROJ_CURL_CA_BUNDLE"); if (ca_bundle_path == nullptr) { // Name of environment variable used by the curl binary ca_bundle_path = getenv("CURL_CA_BUNDLE"); } if (ca_bundle_path == nullptr) { // Name of environment variable used by the curl binary (tested // after CURL_CA_BUNDLE ca_bundle_path = getenv("SSL_CERT_FILE"); } if (ca_bundle_path != nullptr) { ctx->ca_bundle_path = ca_bundle_path; } // Load default value for errorIfBestTransformationNotAvailableDefault // from environment first const char *proj_only_best_default = getenv("PROJ_ONLY_BEST_DEFAULT"); if (proj_only_best_default && proj_only_best_default[0] != '\0') { ctx->warnIfBestTransformationNotAvailableDefault = false; ctx->errorIfBestTransformationNotAvailableDefault = ci_equal(proj_only_best_default, "ON") || ci_equal(proj_only_best_default, "YES") || ci_equal(proj_only_best_default, "TRUE"); } ctx->iniFileLoaded = true; auto file = std::unique_ptr<NS_PROJ::File>( reinterpret_cast<NS_PROJ::File *>(pj_open_lib_internal( ctx, "proj.ini", "rb", pj_open_file_with_manager, nullptr, 0))); if (!file) return; file->seek(0, SEEK_END); const auto filesize = file->tell(); if (filesize == 0 || filesize > 100 * 1024U) return; file->seek(0, SEEK_SET); std::string content; content.resize(static_cast<size_t>(filesize)); const auto nread = file->read(&content[0], content.size()); if (nread != content.size()) return; content += '\n'; size_t pos = 0; while (pos != std::string::npos) { const auto eol = content.find_first_of("\r\n", pos); if (eol == std::string::npos) { break; } const auto equal = content.find('=', pos); if (equal < eol) { const auto key = trim(content.substr(pos, equal - pos)); const auto value = trim(content.substr(equal + 1, eol - (equal + 1))); if (ctx->endpoint.empty() && key == "cdn_endpoint") { ctx->endpoint = value; } else if (proj_network == nullptr && key == "network") { ctx->networking.enabled = ci_equal(value, "ON") || ci_equal(value, "YES") || ci_equal(value, "TRUE"); } else if (key == "cache_enabled") { ctx->gridChunkCache.enabled = ci_equal(value, "ON") || ci_equal(value, "YES") || ci_equal(value, "TRUE"); } else if (key == "cache_size_MB") { const int val = atoi(value.c_str()); ctx->gridChunkCache.max_size = val > 0 ? static_cast<long long>(val) * 1024 * 1024 : -1; } else if (key == "cache_ttl_sec") { ctx->gridChunkCache.ttl = atoi(value.c_str()); } else if (key == "tmerc_default_algo") { if (value == "auto") { ctx->defaultTmercAlgo = TMercAlgo::AUTO; } else if (value == "evenden_snyder") { ctx->defaultTmercAlgo = TMercAlgo::EVENDEN_SNYDER; } else if (value == "poder_engsager") { ctx->defaultTmercAlgo = TMercAlgo::PODER_ENGSAGER; } else { pj_log( ctx, PJ_LOG_ERROR, "pj_load_ini(): Invalid value for tmerc_default_algo"); } } else if (ca_bundle_path == nullptr && key == "ca_bundle_path") { ctx->ca_bundle_path = value; } else if (proj_only_best_default == nullptr && key == "only_best_default") { ctx->warnIfBestTransformationNotAvailableDefault = false; ctx->errorIfBestTransformationNotAvailableDefault = ci_equal(value, "ON") || ci_equal(value, "YES") || ci_equal(value, "TRUE"); } } pos = content.find_first_not_of("\r\n", eol); } } //! @endcond /************************************************************************/ /* proj_context_set_file_finder() */ /************************************************************************/ /** \brief Assign a file finder callback to a context. * * This callback will be used whenever PROJ must open one of its resource files * (proj.db database, grids, etc...) * * The callback will be called with the context currently in use at the moment * where it is used (not necessarily the one provided during this call), and * with the provided user_data (which may be NULL). * The user_data must remain valid during the whole lifetime of the context. * * A finder set on the default context will be inherited by contexts created * later. * * @param ctx PROJ context, or NULL for the default context. * @param finder Finder callback. May be NULL * @param user_data User data provided to the finder callback. May be NULL. * * @since PROJ 6.0 */ void proj_context_set_file_finder(PJ_CONTEXT *ctx, proj_file_finder finder, void *user_data) { if (!ctx) ctx = pj_get_default_ctx(); if (!ctx) return; ctx->file_finder = finder; ctx->file_finder_user_data = user_data; } /************************************************************************/ /* proj_context_set_search_paths() */ /************************************************************************/ /** \brief Sets search paths. * * Those search paths will be used whenever PROJ must open one of its resource * files * (proj.db database, grids, etc...) * * If set on the default context, they will be inherited by contexts created * later. * * Starting with PROJ 7.0, the path(s) should be encoded in UTF-8. * * @param ctx PROJ context, or NULL for the default context. * @param count_paths Number of paths. 0 if paths == NULL. * @param paths Paths. May be NULL. * * @since PROJ 6.0 */ void proj_context_set_search_paths(PJ_CONTEXT *ctx, int count_paths, const char *const *paths) { if (!ctx) ctx = pj_get_default_ctx(); if (!ctx) return; try { std::vector<std::string> vector_of_paths; for (int i = 0; i < count_paths; i++) { vector_of_paths.emplace_back(paths[i]); } ctx->set_search_paths(vector_of_paths); } catch (const std::exception &) { } } /************************************************************************/ /* proj_context_set_ca_bundle_path() */ /************************************************************************/ /** \brief Sets CA Bundle path. * * Those CA Bundle path will be used by PROJ when curl and PROJ_NETWORK * are enabled. * * If set on the default context, they will be inherited by contexts created * later. * * The path should be encoded in UTF-8. * * @param ctx PROJ context, or NULL for the default context. * @param path Path. May be NULL. * * @since PROJ 7.2 */ void proj_context_set_ca_bundle_path(PJ_CONTEXT *ctx, const char *path) { if (!ctx) ctx = pj_get_default_ctx(); if (!ctx) return; pj_load_ini(ctx); try { ctx->set_ca_bundle_path(path != nullptr ? path : ""); } catch (const std::exception &) { } } // --------------------------------------------------------------------------- void pj_stderr_proj_lib_deprecation_warning() { if (getenv("PROJ_LIB") != nullptr && getenv("PROJ_DATA") == nullptr) { fprintf(stderr, "DeprecationWarning: PROJ_LIB environment variable is " "deprecated, and will be removed in a future release. " "You are encouraged to set PROJ_DATA instead.\n"); } }
cpp
PROJ
data/projects/PROJ/src/transformations/xyzgridshift.cpp
/****************************************************************************** * Project: PROJ * Purpose: Geocentric translation using a grid * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2019, 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. *****************************************************************************/ #include <errno.h> #include <stddef.h> #include <string.h> #include <time.h> #include "grids.hpp" #include "proj_internal.h" #include <algorithm> PROJ_HEAD(xyzgridshift, "Geocentric grid shift"); using namespace NS_PROJ; namespace { // anonymous namespace struct xyzgridshiftData { PJ *cart = nullptr; bool grid_ref_is_input = true; ListOfGenericGrids grids{}; bool defer_grid_opening = false; double multiplier = 1.0; }; } // anonymous namespace // --------------------------------------------------------------------------- static bool get_grid_values(PJ *P, xyzgridshiftData *Q, const PJ_LP &lp, double &dx, double &dy, double &dz) { if (Q->defer_grid_opening) { Q->defer_grid_opening = false; Q->grids = pj_generic_grid_init(P, "grids"); if (proj_errno(P)) { return false; } } GenericShiftGridSet *gridset = nullptr; auto grid = pj_find_generic_grid(Q->grids, lp, gridset); if (!grid) { return false; } if (grid->isNullGrid()) { dx = 0; dy = 0; dz = 0; return true; } const auto samplesPerPixel = grid->samplesPerPixel(); if (samplesPerPixel < 3) { proj_log_error(P, "xyzgridshift: grid has not enough samples"); return false; } int sampleX = 0; int sampleY = 1; int sampleZ = 2; for (int i = 0; i < samplesPerPixel; i++) { const auto desc = grid->description(i); if (desc == "x_translation") { sampleX = i; } else if (desc == "y_translation") { sampleY = i; } else if (desc == "z_translation") { sampleZ = i; } } const auto unit = grid->unit(sampleX); if (!unit.empty() && unit != "metre") { proj_log_error(P, "xyzgridshift: Only unit=metre currently handled"); return false; } bool must_retry = false; if (!pj_bilinear_interpolation_three_samples(P->ctx, grid, lp, sampleX, sampleY, sampleZ, dx, dy, dz, must_retry)) { if (must_retry) return get_grid_values(P, Q, lp, dx, dy, dz); return false; } dx *= Q->multiplier; dy *= Q->multiplier; dz *= Q->multiplier; return true; } // --------------------------------------------------------------------------- #define SQUARE(x) ((x) * (x)) // --------------------------------------------------------------------------- static PJ_COORD iterative_adjustment(PJ *P, xyzgridshiftData *Q, const PJ_COORD &pointInit, double factor) { PJ_COORD point = pointInit; for (int i = 0; i < 10; i++) { PJ_COORD geodetic; geodetic.lpz = pj_inv3d(point.xyz, Q->cart); double dx, dy, dz; if (!get_grid_values(P, Q, geodetic.lp, dx, dy, dz)) { return proj_coord_error(); } dx *= factor; dy *= factor; dz *= factor; const double err = SQUARE((point.xyz.x - pointInit.xyz.x) - dx) + SQUARE((point.xyz.y - pointInit.xyz.y) - dy) + SQUARE((point.xyz.z - pointInit.xyz.z) - dz); point.xyz.x = pointInit.xyz.x + dx; point.xyz.y = pointInit.xyz.y + dy; point.xyz.z = pointInit.xyz.z + dz; if (err < 1e-10) { break; } } return point; } // --------------------------------------------------------------------------- static PJ_COORD direct_adjustment(PJ *P, xyzgridshiftData *Q, PJ_COORD point, double factor) { PJ_COORD geodetic; geodetic.lpz = pj_inv3d(point.xyz, Q->cart); double dx, dy, dz; if (!get_grid_values(P, Q, geodetic.lp, dx, dy, dz)) { return proj_coord_error(); } point.xyz.x += factor * dx; point.xyz.y += factor * dy; point.xyz.z += factor * dz; return point; } // --------------------------------------------------------------------------- static PJ_XYZ pj_xyzgridshift_forward_3d(PJ_LPZ lpz, PJ *P) { auto Q = static_cast<xyzgridshiftData *>(P->opaque); PJ_COORD point = {{0, 0, 0, 0}}; point.lpz = lpz; if (Q->grid_ref_is_input) { point = direct_adjustment(P, Q, point, 1.0); } else { point = iterative_adjustment(P, Q, point, 1.0); } return point.xyz; } static PJ_LPZ pj_xyzgridshift_reverse_3d(PJ_XYZ xyz, PJ *P) { auto Q = static_cast<xyzgridshiftData *>(P->opaque); PJ_COORD point = {{0, 0, 0, 0}}; point.xyz = xyz; if (Q->grid_ref_is_input) { point = iterative_adjustment(P, Q, point, -1.0); } else { point = direct_adjustment(P, Q, point, -1.0); } return point.lpz; } static PJ *pj_xyzgridshift_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; auto Q = static_cast<struct xyzgridshiftData *>(P->opaque); if (Q) { if (Q->cart) Q->cart->destructor(Q->cart, errlev); delete Q; } P->opaque = nullptr; return pj_default_destructor(P, errlev); } static void pj_xyzgridshift_reassign_context(PJ *P, PJ_CONTEXT *ctx) { auto Q = (struct xyzgridshiftData *)P->opaque; for (auto &grid : Q->grids) { grid->reassign_context(ctx); } } PJ *PJ_TRANSFORMATION(xyzgridshift, 0) { auto Q = new xyzgridshiftData; P->opaque = (void *)Q; P->destructor = pj_xyzgridshift_destructor; P->reassign_context = pj_xyzgridshift_reassign_context; P->fwd4d = nullptr; P->inv4d = nullptr; P->fwd3d = pj_xyzgridshift_forward_3d; P->inv3d = pj_xyzgridshift_reverse_3d; P->fwd = nullptr; P->inv = nullptr; P->left = PJ_IO_UNITS_CARTESIAN; P->right = PJ_IO_UNITS_CARTESIAN; // Pass a dummy ellipsoid definition that will be overridden just afterwards Q->cart = proj_create(P->ctx, "+proj=cart +a=1"); if (Q->cart == nullptr) return pj_xyzgridshift_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); /* inherit ellipsoid definition from P to Q->cart */ pj_inherit_ellipsoid_def(P, Q->cart); const char *grid_ref = pj_param(P->ctx, P->params, "sgrid_ref").s; if (grid_ref) { if (strcmp(grid_ref, "input_crs") == 0) { // default } else if (strcmp(grid_ref, "output_crs") == 0) { // Convention use for example for NTF->RGF93 grid that contains // delta x,y,z from NTF to RGF93, but the grid itself is referenced // in RGF93 Q->grid_ref_is_input = false; } else { proj_log_error(P, _("unusupported value for grid_ref")); return pj_xyzgridshift_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (0 == pj_param(P->ctx, P->params, "tgrids").i) { proj_log_error(P, _("+grids parameter missing.")); return pj_xyzgridshift_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } /* multiplier for delta x,y,z */ if (pj_param(P->ctx, P->params, "tmultiplier").i) { Q->multiplier = pj_param(P->ctx, P->params, "dmultiplier").f; } if (P->ctx->defer_grid_opening) { Q->defer_grid_opening = true; } else { Q->grids = pj_generic_grid_init(P, "grids"); /* Was gridlist compiled properly? */ if (proj_errno(P)) { proj_log_error(P, _("could not find required grid(s).")); return pj_xyzgridshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } } return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/tinshift.hpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to TIN based transformations * 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. *****************************************************************************/ #ifndef TINSHIFT_HPP #define TINSHIFT_HPP #ifdef PROJ_COMPILATION #include "proj/internal/include_nlohmann_json.hpp" #else #include "nlohmann/json.hpp" #endif #include <algorithm> #include <cmath> #include <exception> #include <functional> #include <limits> #include <memory> #include <string> #include <vector> #include "quadtree.hpp" #ifndef TINSHIFT_NAMESPACE #define TINSHIFT_NAMESPACE TINShift #endif #include "tinshift_exceptions.hpp" namespace TINSHIFT_NAMESPACE { enum FallbackStrategy { FALLBACK_NONE, FALLBACK_NEAREST_SIDE, FALLBACK_NEAREST_CENTROID, }; using json = nlohmann::json; // --------------------------------------------------------------------------- /** Content of a TINShift file. */ class TINShiftFile { public: /** Parse the provided serialized JSON content and return an object. * * @throws ParsingException */ static std::unique_ptr<TINShiftFile> parse(const std::string &text); /** Get file type. Should always be "triangulation_file" */ const std::string &fileType() const { return mFileType; } /** Get the version of the format. At time of writing, only "1.0" is known */ const std::string &formatVersion() const { return mFormatVersion; } /** Get brief descriptive name of the deformation model. */ const std::string &name() const { return mName; } /** Get a string identifying the version of the deformation model. * The format for specifying version is defined by the agency * responsible for the deformation model. */ const std::string &version() const { return mVersion; } /** Get a string identifying the license of the file. * e.g "Create Commons Attribution 4.0 International" */ const std::string &license() const { return mLicense; } /** Get a text description of the model. Intended to be longer than name() */ const std::string &description() const { return mDescription; } /** Get a text description of the model. Intended to be longer than name() */ const std::string &publicationDate() const { return mPublicationDate; } const enum FallbackStrategy &fallbackStrategy() const { return mFallbackStrategy; } /** Basic information on the agency responsible for the model. */ struct Authority { std::string name{}; std::string url{}; std::string address{}; std::string email{}; }; /** Get basic information on the agency responsible for the model. */ const Authority &authority() const { return mAuthority; } /** Hyperlink related to the model. */ struct Link { /** URL holding the information */ std::string href{}; /** Relationship to the dataset. e.g. "about", "source", "license", * "metadata" */ std::string rel{}; /** Mime type */ std::string type{}; /** Description of the link */ std::string title{}; }; /** Get links to related information. */ const std::vector<Link> links() const { return mLinks; } /** Get a string identifying the CRS of source coordinates in the * vertices. Typically "EPSG:XXXX". If the transformation is for vertical * component, this should be the code for a compound CRS (can be * EPSG:XXXX+YYYY where XXXX is the code of the horizontal CRS and YYYY * the code of the vertical CRS). * For example, for the KKJ->ETRS89 transformation, this is EPSG:2393 * ("KKJ / Finland Uniform Coordinate System"). * The input coordinates are assumed to * be passed in the "normalized for visualisation" / "GIS friendly" order, * that is longitude, latitude for geographic coordinates and * easting, northing for projected coordinates. * This may be empty for unspecified CRS. */ const std::string &inputCRS() const { return mInputCRS; } /** Get a string identifying the CRS of target coordinates in the * vertices. Typically "EPSG:XXXX". If the transformation is for vertical * component, this should be the code for a compound CRS (can be * EPSG:XXXX+YYYY where XXXX is the code of the horizontal CRS and YYYY * the code of the vertical CRS). * For example, for the KKJ->ETRS89 transformation, this is EPSG:3067 * ("ETRS89 / TM35FIN(E,N)"). * The output coordinates will be * returned in the "normalized for visualisation" / "GIS friendly" order, * that is longitude, latitude for geographic coordinates and * easting, northing for projected coordinates. * This may be empty for unspecified CRS. */ const std::string &outputCRS() const { return mOutputCRS; } /** Return whether horizontal coordinates are transformed. */ bool transformHorizontalComponent() const { return mTransformHorizontalComponent; } /** Return whether vertical coordinates are transformed. */ bool transformVerticalComponent() const { return mTransformVerticalComponent; } /** Indices of vertices of a triangle */ struct VertexIndices { /** Index of first vertex */ unsigned idx1; /** Index of second vertex */ unsigned idx2; /** Index of third vertex */ unsigned idx3; }; /** Return number of elements per vertex of vertices() */ unsigned verticesColumnCount() const { return mVerticesColumnCount; } /** Return description of triangulation vertices. * Each vertex is described by verticesColumnCount() consecutive values. * They are respectively: * - the source X value * - the source Y value * - (if transformHorizontalComponent() is true) the target X value * - (if transformHorizontalComponent() is true) the target Y value * - (if transformVerticalComponent() is true) the delta Z value (to go from * source to target Z) * * X is assumed to be a longitude (in degrees) or easting value. * Y is assumed to be a latitude (in degrees) or northing value. */ const std::vector<double> &vertices() const { return mVertices; } /** Return triangles*/ const std::vector<VertexIndices> &triangles() const { return mTriangles; } private: TINShiftFile() = default; std::string mFileType{}; std::string mFormatVersion{}; std::string mName{}; std::string mVersion{}; std::string mLicense{}; std::string mDescription{}; std::string mPublicationDate{}; enum FallbackStrategy mFallbackStrategy {}; Authority mAuthority{}; std::vector<Link> mLinks{}; std::string mInputCRS{}; std::string mOutputCRS{}; bool mTransformHorizontalComponent = false; bool mTransformVerticalComponent = false; unsigned mVerticesColumnCount = 0; std::vector<double> mVertices{}; std::vector<VertexIndices> mTriangles{}; }; // --------------------------------------------------------------------------- /** Class to evaluate the transformation of a coordinate */ class Evaluator { public: /** Constructor. */ explicit Evaluator(std::unique_ptr<TINShiftFile> &&fileIn); /** Get file */ const TINShiftFile &file() const { return *(mFile.get()); } /** Evaluate displacement of a position given by (x,y,z,t) and * return it in (x_out,y_out_,z_out). */ bool forward(double x, double y, double z, double &x_out, double &y_out, double &z_out); /** Apply inverse transformation. */ bool inverse(double x, double y, double z, double &x_out, double &y_out, double &z_out); private: std::unique_ptr<TINShiftFile> mFile; // Reused between invocations to save memory allocations std::vector<unsigned> mTriangleIndices{}; std::unique_ptr<NS_PROJ::QuadTree::QuadTree<unsigned>> mQuadTreeForward{}; std::unique_ptr<NS_PROJ::QuadTree::QuadTree<unsigned>> mQuadTreeInverse{}; }; // --------------------------------------------------------------------------- } // namespace TINSHIFT_NAMESPACE // --------------------------------------------------------------------------- #include "tinshift_impl.hpp" #endif // TINSHIFT_HPP
hpp
PROJ
data/projects/PROJ/src/transformations/deformation.cpp
/*********************************************************************** Kinematic datum shifting utilizing a deformation model Kristian Evers, 2017-10-29 ************************************************************************ Perform datum shifts by means of a deformation/velocity model. X_out = X_in + (T_obs - T_epoch) * DX Y_out = Y_in + (T_obs - T_epoch) * DY Z_out = Z_in + (T_obs - T_epoch) * DZ The deformation operation takes cartesian coordinates as input and returns cartesian coordinates as well. Corrections in the gridded model are in east, north, up (ENU) space. Hence the input coordinates need to be converted to ENU-space when searching for corrections in the grid. The corrections are then converted to cartesian PJ_XYZ-space and applied to the input coordinates (also in cartesian space). A full deformation model is preferably represented as a 3 channel Geodetic TIFF Grid, but was historically described by a set of two grids: One for the horizontal components and one for the vertical component. The east and north components are (were) stored using the CTable/CTable2 format, up component is (was) stored in the GTX format. Both grids are (were) expected to contain grid-values in units of mm/year in ENU-space. ************************************************************************ * Copyright (c) 2017, 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. * ***********************************************************************/ #include "grids.hpp" #include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> #include <algorithm> PROJ_HEAD(deformation, "Kinematic grid shift"); #define TOL 1e-8 #define MAX_ITERATIONS 10 using namespace NS_PROJ; namespace { // anonymous namespace struct deformationData { double dt = 0; double t_epoch = 0; PJ *cart = nullptr; ListOfGenericGrids grids{}; ListOfHGrids hgrids{}; ListOfVGrids vgrids{}; }; } // anonymous namespace // --------------------------------------------------------------------------- static bool pj_deformation_get_grid_values(PJ *P, deformationData *Q, const PJ_LP &lp, double &vx, double &vy, double &vz) { GenericShiftGridSet *gridset = nullptr; auto grid = pj_find_generic_grid(Q->grids, lp, gridset); if (!grid) { return false; } if (grid->isNullGrid()) { vx = 0; vy = 0; vz = 0; return true; } const auto samplesPerPixel = grid->samplesPerPixel(); if (samplesPerPixel < 3) { proj_log_error(P, "grid has not enough samples"); return false; } int sampleE = 0; int sampleN = 1; int sampleU = 2; for (int i = 0; i < samplesPerPixel; i++) { const auto desc = grid->description(i); if (desc == "east_velocity") { sampleE = i; } else if (desc == "north_velocity") { sampleN = i; } else if (desc == "up_velocity") { sampleU = i; } } const auto unit = grid->unit(sampleE); if (!unit.empty() && unit != "millimetres per year") { proj_log_error(P, "Only unit=millimetres per year currently handled"); return false; } bool must_retry = false; if (!pj_bilinear_interpolation_three_samples(P->ctx, grid, lp, sampleE, sampleN, sampleU, vx, vy, vz, must_retry)) { if (must_retry) return pj_deformation_get_grid_values(P, Q, lp, vx, vy, vz); return false; } // divide by 1000 to get m/year vx /= 1000; vy /= 1000; vz /= 1000; return true; } /********************************************************************************/ static PJ_XYZ pj_deformation_get_grid_shift(PJ *P, const PJ_XYZ &cartesian) { /******************************************************************************** Read correction values from grid. The cartesian input coordinates are converted to geodetic coordinates in order look up the correction values in the grid. Once the grid corrections are read we need to convert them from ENU-space to cartesian PJ_XYZ-space. ENU -> PJ_XYZ formula described in: Nørbech, T., et al, 2003(?), "Transformation from a Common Nordic Reference Frame to ETRS89 in Denmark, Finland, Norway, and Sweden – status report" ********************************************************************************/ PJ_COORD geodetic, shift, temp; double sp, cp, sl, cl; int previous_errno = proj_errno_reset(P); auto Q = static_cast<deformationData *>(P->opaque); /* cartesian to geodetic */ geodetic.lpz = pj_inv3d(cartesian, Q->cart); /* look up correction values in grids */ if (!Q->grids.empty()) { double vx = 0; double vy = 0; double vz = 0; if (!pj_deformation_get_grid_values(P, Q, geodetic.lp, vx, vy, vz)) { return proj_coord_error().xyz; } shift.xyz.x = vx; shift.xyz.y = vy; shift.xyz.z = vz; } else { shift.lp = pj_hgrid_value(P, Q->hgrids, geodetic.lp); shift.enu.u = pj_vgrid_value(P, Q->vgrids, geodetic.lp, 1.0); if (proj_errno(P) == PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID) proj_log_debug( P, "coordinate (%.3f, %.3f) outside deformation model", proj_todeg(geodetic.lpz.lam), proj_todeg(geodetic.lpz.phi)); /* grid values are stored as mm/yr, we need m/yr */ shift.xyz.x /= 1000; shift.xyz.y /= 1000; shift.xyz.z /= 1000; } /* pre-calc cosines and sines */ sp = sin(geodetic.lpz.phi); cp = cos(geodetic.lpz.phi); sl = sin(geodetic.lpz.lam); cl = cos(geodetic.lpz.lam); /* ENU -> PJ_XYZ */ temp.xyz.x = -sp * cl * shift.enu.n - sl * shift.enu.e + cp * cl * shift.enu.u; temp.xyz.y = -sp * sl * shift.enu.n + cl * shift.enu.e + cp * sl * shift.enu.u; temp.xyz.z = cp * shift.enu.n + sp * shift.enu.u; shift.xyz = temp.xyz; proj_errno_restore(P, previous_errno); return shift.xyz; } /********************************************************************************/ static PJ_XYZ pj_deformation_reverse_shift(PJ *P, PJ_XYZ input, double dt) { /******************************************************************************** Iteratively determine the reverse grid shift correction values. *********************************************************************************/ PJ_XYZ out, delta, dif; double z0; int i = MAX_ITERATIONS; delta = pj_deformation_get_grid_shift(P, input); if (delta.x == HUGE_VAL) { return delta; } /* Store the original z shift for later application */ z0 = delta.z; /* When iterating to find the best horizontal coordinate we also carry */ /* along the z-component, since we need it for the cartesian -> geodetic */ /* conversion. The z-component adjustment is overwritten with z0 after */ /* the loop has finished. */ out.x = input.x - dt * delta.x; out.y = input.y - dt * delta.y; out.z = input.z + dt * delta.z; do { delta = pj_deformation_get_grid_shift(P, out); if (delta.x == HUGE_VAL) break; dif.x = out.x + dt * delta.x - input.x; dif.y = out.y + dt * delta.y - input.y; dif.z = out.z - dt * delta.z - input.z; out.x += dif.x; out.y += dif.y; out.z += dif.z; } while (--i && hypot(dif.x, dif.y) > TOL); out.z = input.z - dt * z0; return out; } static PJ_XYZ pj_deformation_forward_3d(PJ_LPZ lpz, PJ *P) { struct deformationData *Q = (struct deformationData *)P->opaque; PJ_COORD out, in; PJ_XYZ shift; in.lpz = lpz; out = in; if (Q->dt == HUGE_VAL) { out = proj_coord_error(); /* in the 3D case +t_obs must be specified */ proj_log_debug(P, "+dt must be specified"); return out.xyz; } shift = pj_deformation_get_grid_shift(P, in.xyz); if (shift.x == HUGE_VAL) { return shift; } out.xyz.x += Q->dt * shift.x; out.xyz.y += Q->dt * shift.y; out.xyz.z += Q->dt * shift.z; return out.xyz; } static void pj_deformation_forward_4d(PJ_COORD &coo, PJ *P) { struct deformationData *Q = (struct deformationData *)P->opaque; double dt; PJ_XYZ shift; if (Q->dt != HUGE_VAL) { dt = Q->dt; } else { dt = coo.xyzt.t - Q->t_epoch; } shift = pj_deformation_get_grid_shift(P, coo.xyz); coo.xyzt.x += dt * shift.x; coo.xyzt.y += dt * shift.y; coo.xyzt.z += dt * shift.z; } static PJ_LPZ pj_deformation_reverse_3d(PJ_XYZ in, PJ *P) { struct deformationData *Q = (struct deformationData *)P->opaque; PJ_COORD out; out.xyz = in; if (Q->dt == HUGE_VAL) { out = proj_coord_error(); /* in the 3D case +t_obs must be specified */ proj_log_debug(P, "+dt must be specified"); return out.lpz; } out.xyz = pj_deformation_reverse_shift(P, in, Q->dt); return out.lpz; } static void pj_deformation_reverse_4d(PJ_COORD &coo, PJ *P) { struct deformationData *Q = (struct deformationData *)P->opaque; double dt; if (Q->dt != HUGE_VAL) { dt = Q->dt; } else { dt = coo.xyzt.t - Q->t_epoch; } coo.xyz = pj_deformation_reverse_shift(P, coo.xyz, dt); } static PJ *pj_deformation_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; auto Q = static_cast<struct deformationData *>(P->opaque); if (Q) { if (Q->cart) Q->cart->destructor(Q->cart, errlev); delete Q; } P->opaque = nullptr; return pj_default_destructor(P, errlev); } PJ *PJ_TRANSFORMATION(deformation, 1) { auto Q = new deformationData; P->opaque = (void *)Q; P->destructor = pj_deformation_destructor; // Pass a dummy ellipsoid definition that will be overridden just afterwards Q->cart = proj_create(P->ctx, "+proj=cart +a=1"); if (Q->cart == nullptr) return pj_deformation_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); /* inherit ellipsoid definition from P to Q->cart */ pj_inherit_ellipsoid_def(P, Q->cart); int has_xy_grids = pj_param(P->ctx, P->params, "txy_grids").i; int has_z_grids = pj_param(P->ctx, P->params, "tz_grids").i; int has_grids = pj_param(P->ctx, P->params, "tgrids").i; /* Build gridlists. Both horizontal and vertical grids are mandatory. */ if (!has_grids && (!has_xy_grids || !has_z_grids)) { proj_log_error(P, _("Either +grids or (+xy_grids and +z_grids) should " "be specified.")); return pj_deformation_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (has_grids) { Q->grids = pj_generic_grid_init(P, "grids"); /* Was gridlist compiled properly? */ if (proj_errno(P)) { proj_log_error(P, _("could not find required grid(s).)")); return pj_deformation_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } } else { Q->hgrids = pj_hgrid_init(P, "xy_grids"); if (proj_errno(P)) { proj_log_error(P, _("could not find requested xy_grid(s).")); return pj_deformation_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } Q->vgrids = pj_vgrid_init(P, "z_grids"); if (proj_errno(P)) { proj_log_error(P, _("could not find requested z_grid(s).")); return pj_deformation_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } } Q->dt = HUGE_VAL; if (pj_param(P->ctx, P->params, "tdt").i) { Q->dt = pj_param(P->ctx, P->params, "ddt").f; } if (pj_param_exists(P->params, "t_obs")) { proj_log_error(P, _("+t_obs parameter is deprecated. Use +dt instead.")); return pj_deformation_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->t_epoch = HUGE_VAL; if (pj_param(P->ctx, P->params, "tt_epoch").i) { Q->t_epoch = pj_param(P->ctx, P->params, "dt_epoch").f; } if (Q->dt == HUGE_VAL && Q->t_epoch == HUGE_VAL) { proj_log_error(P, _("either +dt or +t_epoch needs to be set.")); return pj_deformation_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (Q->dt != HUGE_VALL && Q->t_epoch != HUGE_VALL) { proj_log_error(P, _("+dt or +t_epoch are mutually exclusive.")); return pj_deformation_destructor( P, PROJ_ERR_INVALID_OP_MUTUALLY_EXCLUSIVE_ARGS); } P->fwd4d = pj_deformation_forward_4d; P->inv4d = pj_deformation_reverse_4d; P->fwd3d = pj_deformation_forward_3d; P->inv3d = pj_deformation_reverse_3d; P->fwd = nullptr; P->inv = nullptr; P->left = PJ_IO_UNITS_CARTESIAN; P->right = PJ_IO_UNITS_CARTESIAN; return P; } #undef TOL #undef MAX_ITERATIONS
cpp
PROJ
data/projects/PROJ/src/transformations/gridshift.cpp
/****************************************************************************** * Project: PROJ * Purpose: Generic grid shifting, in particular Geographic 3D offsets * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2022, 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. *****************************************************************************/ #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include <errno.h> #include <mutex> #include <stddef.h> #include <string.h> #include <time.h> #include "grids.hpp" #include "proj/internal/internal.hpp" #include "proj_internal.h" #include <algorithm> #include <cmath> #include <limits> #include <map> #include <utility> PROJ_HEAD(gridshift, "Generic grid shift"); static std::mutex gMutex{}; // Map of (name, isProjected) static std::map<std::string, bool> gKnownGrids{}; using namespace NS_PROJ; namespace { // anonymous namespace struct IXY { int32_t x, y; inline bool operator!=(const IXY &other) const { return x != other.x || y != other.y; } }; struct GridInfo { int idxSampleX = -1; int idxSampleY = -1; int idxSampleZ = -1; bool eastingNorthingOffset = false; bool bilinearInterpolation = true; std::vector<float> shifts{}; bool swapXYInRes = false; std::vector<int> idxSampleXYZ{-1, -1, -1}; IXY lastIdxXY = IXY{-1, -1}; }; // --------------------------------------------------------------------------- struct gridshiftData { ListOfGenericGrids m_grids{}; bool m_defer_grid_opening = false; bool m_bHasHorizontalOffset = false; bool m_bHasGeographic3DOffset = false; bool m_bHasEllipsoidalHeightOffset = false; bool m_bHasVerticalToVertical = false; bool m_bHasGeographicToVertical = false; bool m_mainGridTypeIsGeographic3DOffset = false; bool m_skip_z_transform = false; std::string m_mainGridType{}; std::string m_auxGridType{}; std::string m_interpolation{}; std::map<const GenericShiftGrid *, GridInfo> m_cacheGridInfo{}; //! Offset in X to add in the forward direction, after the correction // has been applied. (and reciprocally to subtract in the inverse direction // before reading the grid). Used typically for the S-JTSK --> S-JTSK/05 // grid double m_offsetX = 0; //! Offset in Y to add in the forward direction, after the correction // has been applied. (and reciprocally to subtract in the inverse direction // before reading the grid). Used typically for the S-JTSK --> S-JTSK/05 // grid double m_offsetY = 0; bool checkGridTypes(PJ *P, bool &isProjectedCoord); bool loadGridsIfNeeded(PJ *P); const GenericShiftGrid *findGrid(const std::string &type, const PJ_XYZ &input, GenericShiftGridSet *&gridSetOut) const; PJ_XYZ grid_interpolate(PJ_CONTEXT *ctx, const std::string &type, PJ_XY xy, const GenericShiftGrid *grid, bool &biquadraticInterpolationOut); PJ_XYZ grid_apply_internal(PJ_CONTEXT *ctx, const std::string &type, bool isVerticalOnly, const PJ_XYZ in, PJ_DIRECTION direction, const GenericShiftGrid *grid, GenericShiftGridSet *gridset, bool &shouldRetry); PJ_XYZ apply(PJ *P, PJ_DIRECTION dir, PJ_XYZ xyz); }; // --------------------------------------------------------------------------- bool gridshiftData::checkGridTypes(PJ *P, bool &isProjectedCoord) { std::string offsetX, offsetY; int gridCount = 0; isProjectedCoord = false; for (const auto &gridset : m_grids) { for (const auto &grid : gridset->grids()) { ++gridCount; const auto &type = grid->metadataItem("TYPE"); if (type == "HORIZONTAL_OFFSET") { m_bHasHorizontalOffset = true; if (offsetX.empty()) { offsetX = grid->metadataItem("constant_offset", 0); } if (offsetY.empty()) { offsetY = grid->metadataItem("constant_offset", 1); } } else if (type == "GEOGRAPHIC_3D_OFFSET") m_bHasGeographic3DOffset = true; else if (type == "ELLIPSOIDAL_HEIGHT_OFFSET") m_bHasEllipsoidalHeightOffset = true; else if (type == "VERTICAL_OFFSET_VERTICAL_TO_VERTICAL") m_bHasVerticalToVertical = true; else if (type == "VERTICAL_OFFSET_GEOGRAPHIC_TO_VERTICAL") m_bHasGeographicToVertical = true; else if (type.empty()) { proj_log_error(P, _("Missing TYPE metadata item in grid(s).")); return false; } else { proj_log_error( P, _("Unhandled value for TYPE metadata item in grid(s).")); return false; } isProjectedCoord = !grid->extentAndRes().isGeographic; } } if (!offsetX.empty() || !offsetY.empty()) { if (gridCount > 1) { // Makes life easier... proj_log_error(P, _("Shift offset found in one grid. Only one grid " "with shift offset is supported at a time.")); return false; } try { m_offsetX = NS_PROJ::internal::c_locale_stod(offsetX); } catch (const std::exception &) { proj_log_error(P, _("Invalid offset value")); return false; } try { m_offsetY = NS_PROJ::internal::c_locale_stod(offsetY); } catch (const std::exception &) { proj_log_error(P, _("Invalid offset value")); return false; } } if (((m_bHasEllipsoidalHeightOffset ? 1 : 0) + (m_bHasVerticalToVertical ? 1 : 0) + (m_bHasGeographicToVertical ? 1 : 0)) > 1) { proj_log_error(P, _("Unsupported mix of grid types.")); return false; } if (m_bHasGeographic3DOffset) { m_mainGridTypeIsGeographic3DOffset = true; m_mainGridType = "GEOGRAPHIC_3D_OFFSET"; } else if (!m_bHasHorizontalOffset) { if (m_bHasEllipsoidalHeightOffset) m_mainGridType = "ELLIPSOIDAL_HEIGHT_OFFSET"; else if (m_bHasGeographicToVertical) m_mainGridType = "VERTICAL_OFFSET_GEOGRAPHIC_TO_VERTICAL"; else { assert(m_bHasVerticalToVertical); m_mainGridType = "VERTICAL_OFFSET_VERTICAL_TO_VERTICAL"; } } else { assert(m_bHasHorizontalOffset); m_mainGridType = "HORIZONTAL_OFFSET"; } if (m_bHasHorizontalOffset) { if (m_bHasEllipsoidalHeightOffset) m_auxGridType = "ELLIPSOIDAL_HEIGHT_OFFSET"; else if (m_bHasGeographicToVertical) m_auxGridType = "VERTICAL_OFFSET_GEOGRAPHIC_TO_VERTICAL"; else if (m_bHasVerticalToVertical) { m_auxGridType = "VERTICAL_OFFSET_VERTICAL_TO_VERTICAL"; } } return true; } // --------------------------------------------------------------------------- const GenericShiftGrid * gridshiftData::findGrid(const std::string &type, const PJ_XYZ &input, GenericShiftGridSet *&gridSetOut) const { for (const auto &gridset : m_grids) { auto grid = gridset->gridAt(type, input.x, input.y); if (grid) { gridSetOut = gridset.get(); return grid; } } return nullptr; } // --------------------------------------------------------------------------- #define REL_TOLERANCE_HGRIDSHIFT 1e-5 PJ_XYZ gridshiftData::grid_interpolate(PJ_CONTEXT *ctx, const std::string &type, PJ_XY xy, const GenericShiftGrid *grid, bool &biquadraticInterpolationOut) { PJ_XYZ val; val.x = val.y = HUGE_VAL; val.z = 0; const bool isProjectedCoord = !grid->extentAndRes().isGeographic; auto iterCache = m_cacheGridInfo.find(grid); if (iterCache == m_cacheGridInfo.end()) { bool eastingNorthingOffset = false; const auto samplesPerPixel = grid->samplesPerPixel(); int idxSampleY = -1; int idxSampleX = -1; int idxSampleZ = -1; for (int i = 0; i < samplesPerPixel; i++) { const auto desc = grid->description(i); if (!isProjectedCoord && desc == "latitude_offset") { idxSampleY = i; const auto unit = grid->unit(idxSampleY); if (!unit.empty() && unit != "arc-second") { pj_log(ctx, PJ_LOG_ERROR, "gridshift: Only unit=arc-second currently handled"); return val; } } else if (!isProjectedCoord && desc == "longitude_offset") { idxSampleX = i; const auto unit = grid->unit(idxSampleX); if (!unit.empty() && unit != "arc-second") { pj_log(ctx, PJ_LOG_ERROR, "gridshift: Only unit=arc-second currently handled"); return val; } } else if (isProjectedCoord && desc == "easting_offset") { eastingNorthingOffset = true; idxSampleX = i; const auto unit = grid->unit(idxSampleX); if (!unit.empty() && unit != "metre") { pj_log(ctx, PJ_LOG_ERROR, "gridshift: Only unit=metre currently handled"); return val; } } else if (isProjectedCoord && desc == "northing_offset") { eastingNorthingOffset = true; idxSampleY = i; const auto unit = grid->unit(idxSampleY); if (!unit.empty() && unit != "metre") { pj_log(ctx, PJ_LOG_ERROR, "gridshift: Only unit=metre currently handled"); return val; } } else if (desc == "ellipsoidal_height_offset" || desc == "geoid_undulation" || desc == "hydroid_height" || desc == "vertical_offset") { idxSampleZ = i; const auto unit = grid->unit(idxSampleZ); if (!unit.empty() && unit != "metre") { pj_log(ctx, PJ_LOG_ERROR, "gridshift: Only unit=metre currently handled"); return val; } } } if (samplesPerPixel >= 2 && idxSampleY < 0 && idxSampleX < 0 && type == "HORIZONTAL_OFFSET") { if (isProjectedCoord) { eastingNorthingOffset = true; idxSampleX = 0; idxSampleY = 1; } else { // X=longitude assumed to be the second component if metadata // lacking idxSampleX = 1; // Y=latitude assumed to be the first component if metadata // lacking idxSampleY = 0; } } if (type == "HORIZONTAL_OFFSET" || type == "GEOGRAPHIC_3D_OFFSET") { if (idxSampleY < 0 || idxSampleX < 0) { pj_log(ctx, PJ_LOG_ERROR, "gridshift: grid has not expected samples"); return val; } } if (type == "ELLIPSOIDAL_HEIGHT_OFFSET" || type == "VERTICAL_OFFSET_GEOGRAPHIC_TO_VERTICAL" || type == "VERTICAL_OFFSET_VERTICAL_TO_VERTICAL" || type == "GEOGRAPHIC_3D_OFFSET") { if (idxSampleZ < 0) { pj_log(ctx, PJ_LOG_ERROR, "gridshift: grid has not expected samples"); return val; } } std::string interpolation(m_interpolation); if (interpolation.empty()) interpolation = grid->metadataItem("interpolation_method"); if (interpolation.empty()) interpolation = "bilinear"; if (interpolation != "bilinear" && interpolation != "biquadratic") { pj_log(ctx, PJ_LOG_ERROR, "gridshift: Unsupported interpolation_method in grid"); return val; } GridInfo gridInfo; gridInfo.idxSampleX = idxSampleX; gridInfo.idxSampleY = idxSampleY; gridInfo.idxSampleZ = m_skip_z_transform ? -1 : idxSampleZ; gridInfo.eastingNorthingOffset = eastingNorthingOffset; gridInfo.bilinearInterpolation = (interpolation == "bilinear" || grid->width() < 3 || grid->height() < 3); gridInfo.shifts.resize(3 * 3 * 3); if (idxSampleX == 1 && idxSampleY == 0) { // Little optimization for the common of grids storing shifts in // latitude, longitude, in that order. // We want to request data in the order it is stored in the grid, // which triggers a read optimization. // But we must compensate for that by switching the role of x and y // after computation. gridInfo.swapXYInRes = true; gridInfo.idxSampleXYZ[0] = 0; gridInfo.idxSampleXYZ[1] = 1; } else { gridInfo.idxSampleXYZ[0] = idxSampleX; gridInfo.idxSampleXYZ[1] = idxSampleY; } gridInfo.idxSampleXYZ[2] = idxSampleZ; iterCache = m_cacheGridInfo.emplace(grid, std::move(gridInfo)).first; } GridInfo &gridInfo = iterCache->second; const int idxSampleX = gridInfo.idxSampleX; const int idxSampleY = gridInfo.idxSampleY; const int idxSampleZ = gridInfo.idxSampleZ; const bool bilinearInterpolation = gridInfo.bilinearInterpolation; biquadraticInterpolationOut = !bilinearInterpolation; IXY indxy; const auto &extent = grid->extentAndRes(); double x = (xy.x - extent.west) / extent.resX; indxy.x = std::isnan(x) ? 0 : (int32_t)lround(floor(x)); double y = (xy.y - extent.south) / extent.resY; indxy.y = std::isnan(y) ? 0 : (int32_t)lround(floor(y)); PJ_XY frct; frct.x = x - indxy.x; frct.y = y - indxy.y; int tmpInt; if (indxy.x < 0) { if (indxy.x == -1 && frct.x > 1 - 10 * REL_TOLERANCE_HGRIDSHIFT) { ++indxy.x; frct.x = 0.; } else return val; } else if ((tmpInt = indxy.x + 1) >= grid->width()) { if (tmpInt == grid->width() && frct.x < 10 * REL_TOLERANCE_HGRIDSHIFT) { --indxy.x; frct.x = 1.; } else return val; } if (indxy.y < 0) { if (indxy.y == -1 && frct.y > 1 - 10 * REL_TOLERANCE_HGRIDSHIFT) { ++indxy.y; frct.y = 0.; } else return val; } else if ((tmpInt = indxy.y + 1) >= grid->height()) { if (tmpInt == grid->height() && frct.y < 10 * REL_TOLERANCE_HGRIDSHIFT) { --indxy.y; frct.y = 1.; } else return val; } bool nodataFound = false; if (bilinearInterpolation) { double m10 = frct.x; double m11 = m10; double m01 = 1. - frct.x; double m00 = m01; m11 *= frct.y; m01 *= frct.y; frct.y = 1. - frct.y; m00 *= frct.y; m10 *= frct.y; if (idxSampleX >= 0 && idxSampleY >= 0) { if (gridInfo.lastIdxXY != indxy) { if (!grid->valuesAt(indxy.x, indxy.y, 2, 2, idxSampleZ >= 0 ? 3 : 2, gridInfo.idxSampleXYZ.data(), gridInfo.shifts.data(), nodataFound) || nodataFound) { return val; } gridInfo.lastIdxXY = indxy; } if (idxSampleZ >= 0) { val.x = (m00 * gridInfo.shifts[0] + m10 * gridInfo.shifts[3] + m01 * gridInfo.shifts[6] + m11 * gridInfo.shifts[9]); val.y = (m00 * gridInfo.shifts[1] + m10 * gridInfo.shifts[4] + m01 * gridInfo.shifts[7] + m11 * gridInfo.shifts[10]); val.z = m00 * gridInfo.shifts[2] + m10 * gridInfo.shifts[5] + m01 * gridInfo.shifts[8] + m11 * gridInfo.shifts[11]; } else { val.x = (m00 * gridInfo.shifts[0] + m10 * gridInfo.shifts[2] + m01 * gridInfo.shifts[4] + m11 * gridInfo.shifts[6]); val.y = (m00 * gridInfo.shifts[1] + m10 * gridInfo.shifts[3] + m01 * gridInfo.shifts[5] + m11 * gridInfo.shifts[7]); } } else { val.x = 0; val.y = 0; if (idxSampleZ >= 0) { if (gridInfo.lastIdxXY != indxy) { if (!grid->valuesAt(indxy.x, indxy.y, 2, 2, 1, &idxSampleZ, gridInfo.shifts.data(), nodataFound) || nodataFound) { return val; } gridInfo.lastIdxXY = indxy; } val.z = m00 * gridInfo.shifts[0] + m10 * gridInfo.shifts[1] + m01 * gridInfo.shifts[2] + m11 * gridInfo.shifts[3]; } } } else // biquadratic { // Cf https://geodesy.noaa.gov/library/pdfs/NOAA_TM_NOS_NGS_0084.pdf // Depending if we are before or after half-pixel, shift the 3x3 window // of interpolation if ((frct.x <= 0.5 && indxy.x > 0) || (indxy.x + 2 == grid->width())) { indxy.x -= 1; frct.x += 1; } if ((frct.y <= 0.5 && indxy.y > 0) || (indxy.y + 2 == grid->height())) { indxy.y -= 1; frct.y += 1; } // Port of qterp() Fortran function from NOAA // xToInterp must be in [0,2] range // f0 must be f(0), f1 must be f(1), f2 must be f(2) // Returns f(xToInterp) interpolated value along the parabolic function const auto quadraticInterpol = [](double xToInterp, double f0, double f1, double f2) { const double df0 = f1 - f0; const double df1 = f2 - f1; const double d2f0 = df1 - df0; return f0 + xToInterp * df0 + 0.5 * xToInterp * (xToInterp - 1.0) * d2f0; }; if (idxSampleX >= 0 && idxSampleY >= 0) { if (gridInfo.lastIdxXY != indxy) { if (!grid->valuesAt(indxy.x, indxy.y, 3, 3, idxSampleZ >= 0 ? 3 : 2, gridInfo.idxSampleXYZ.data(), gridInfo.shifts.data(), nodataFound) || nodataFound) { return val; } gridInfo.lastIdxXY = indxy; } const auto *shifts_ptr = gridInfo.shifts.data(); if (idxSampleZ >= 0) { double xyz_shift[3][4]; for (int j = 0; j <= 2; ++j) { xyz_shift[j][0] = quadraticInterpol( frct.x, shifts_ptr[0], shifts_ptr[3], shifts_ptr[6]); xyz_shift[j][1] = quadraticInterpol( frct.x, shifts_ptr[1], shifts_ptr[4], shifts_ptr[7]); xyz_shift[j][2] = quadraticInterpol( frct.x, shifts_ptr[2], shifts_ptr[5], shifts_ptr[8]); shifts_ptr += 9; } val.x = quadraticInterpol(frct.y, xyz_shift[0][0], xyz_shift[1][0], xyz_shift[2][0]); val.y = quadraticInterpol(frct.y, xyz_shift[0][1], xyz_shift[1][1], xyz_shift[2][1]); val.z = quadraticInterpol(frct.y, xyz_shift[0][2], xyz_shift[1][2], xyz_shift[2][2]); } else { double xy_shift[3][2]; for (int j = 0; j <= 2; ++j) { xy_shift[j][0] = quadraticInterpol( frct.x, shifts_ptr[0], shifts_ptr[2], shifts_ptr[4]); xy_shift[j][1] = quadraticInterpol( frct.x, shifts_ptr[1], shifts_ptr[3], shifts_ptr[5]); shifts_ptr += 6; } val.x = quadraticInterpol(frct.y, xy_shift[0][0], xy_shift[1][0], xy_shift[2][0]); val.y = quadraticInterpol(frct.y, xy_shift[0][1], xy_shift[1][1], xy_shift[2][1]); } } else { val.x = 0; val.y = 0; if (idxSampleZ >= 0) { if (gridInfo.lastIdxXY != indxy) { if (!grid->valuesAt(indxy.x, indxy.y, 3, 3, 1, &idxSampleZ, gridInfo.shifts.data(), nodataFound) || nodataFound) { return val; } gridInfo.lastIdxXY = indxy; } double z_shift[3]; const auto *shifts_ptr = gridInfo.shifts.data(); for (int j = 0; j <= 2; ++j) { z_shift[j] = quadraticInterpol( frct.x, shifts_ptr[0], shifts_ptr[1], shifts_ptr[2]); shifts_ptr += 3; } val.z = quadraticInterpol(frct.y, z_shift[0], z_shift[1], z_shift[2]); } } } if (idxSampleX >= 0 && idxSampleY >= 0 && !gridInfo.eastingNorthingOffset) { constexpr double convFactorXY = 1. / 3600 / 180 * M_PI; val.x *= convFactorXY; val.y *= convFactorXY; } if (gridInfo.swapXYInRes) { std::swap(val.x, val.y); } return val; } // --------------------------------------------------------------------------- static PJ_XY normalizeX(const GenericShiftGrid *grid, const PJ_XYZ in, const NS_PROJ::ExtentAndRes *&extentOut) { PJ_XY normalized; normalized.x = in.x; normalized.y = in.y; extentOut = &(grid->extentAndRes()); if (extentOut->isGeographic) { const double epsilon = (extentOut->resX + extentOut->resY) * REL_TOLERANCE_HGRIDSHIFT; if (normalized.x < extentOut->west - epsilon) normalized.x += 2 * M_PI; else if (normalized.x > extentOut->east + epsilon) normalized.x -= 2 * M_PI; } return normalized; } // --------------------------------------------------------------------------- #define MAX_ITERATIONS 10 #define TOL 1e-12 PJ_XYZ gridshiftData::grid_apply_internal( PJ_CONTEXT *ctx, const std::string &type, bool isVerticalOnly, const PJ_XYZ in, PJ_DIRECTION direction, const GenericShiftGrid *grid, GenericShiftGridSet *gridset, bool &shouldRetry) { shouldRetry = false; if (in.x == HUGE_VAL) return in; /* normalized longitude of input */ const NS_PROJ::ExtentAndRes *extent; PJ_XY normalized_in = normalizeX(grid, in, extent); bool biquadraticInterpolationOut = false; PJ_XYZ shift = grid_interpolate(ctx, type, normalized_in, grid, biquadraticInterpolationOut); if (grid->hasChanged()) { shouldRetry = gridset->reopen(ctx); PJ_XYZ out; out.x = out.y = out.z = HUGE_VAL; return out; } if (shift.x == HUGE_VAL) return shift; if (direction == PJ_FWD) { PJ_XYZ out = in; out.x += shift.x; out.y += shift.y; out.z += shift.z; return out; } if (isVerticalOnly) { PJ_XYZ out = in; out.z -= shift.z; return out; } PJ_XY guess; guess.x = normalized_in.x - shift.x; guess.y = normalized_in.y - shift.y; // NOAA NCAT transformer tool doesn't do iteration in the reverse path. // Do the same (only for biquadratic, although NCAT applies this logic to // bilinear too) // Cf // https://github.com/noaa-ngs/ncat-lib/blob/77bcff1ce4a78fe06d0312102ada008aefcc2c62/src/gov/noaa/ngs/grid/Transformer.java#L374 // When trying to do iterative reverse path with biquadratic, we can // get convergence failures on points that are close to the boundary of // cells or half-cells. For example with // echo -122.4250009683 37.8286740788 0 | bin/cct -I +proj=gridshift // +grids=tests/us_noaa_nadcon5_nad83_1986_nad83_harn_conus_extract_sanfrancisco.tif // +interpolation=biquadratic if (!biquadraticInterpolationOut) { int i = MAX_ITERATIONS; const double toltol = TOL * TOL; PJ_XY diff; do { shift = grid_interpolate(ctx, type, guess, grid, biquadraticInterpolationOut); if (grid->hasChanged()) { shouldRetry = gridset->reopen(ctx); PJ_XYZ out; out.x = out.y = out.z = HUGE_VAL; return out; } /* We can possibly go outside of the initial guessed grid, so try */ /* to fetch a new grid into which iterate... */ if (shift.x == HUGE_VAL) { PJ_XYZ lp; lp.x = guess.x; lp.y = guess.y; auto newGrid = findGrid(type, lp, gridset); if (newGrid == nullptr || newGrid == grid || newGrid->isNullGrid()) break; pj_log(ctx, PJ_LOG_TRACE, "Switching from grid %s to grid %s", grid->name().c_str(), newGrid->name().c_str()); grid = newGrid; normalized_in = normalizeX(grid, in, extent); diff.x = std::numeric_limits<double>::max(); diff.y = std::numeric_limits<double>::max(); continue; } diff.x = guess.x + shift.x - normalized_in.x; diff.y = guess.y + shift.y - normalized_in.y; guess.x -= diff.x; guess.y -= diff.y; } while (--i && (diff.x * diff.x + diff.y * diff.y > toltol)); /* prob. slightly faster than hypot() */ if (i == 0) { pj_log(ctx, PJ_LOG_TRACE, "Inverse grid shift iterator failed to converge."); proj_context_errno_set(ctx, PROJ_ERR_COORD_TRANSFM_NO_CONVERGENCE); PJ_XYZ out; out.x = out.y = out.z = HUGE_VAL; return out; } if (shift.x == HUGE_VAL) { pj_log( ctx, PJ_LOG_TRACE, "Inverse grid shift iteration failed, presumably at grid edge. " "Using first approximation."); } } PJ_XYZ out; out.x = extent->isGeographic ? adjlon(guess.x) : guess.x; out.y = guess.y; out.z = in.z - shift.z; return out; } // --------------------------------------------------------------------------- bool gridshiftData::loadGridsIfNeeded(PJ *P) { if (m_defer_grid_opening) { m_defer_grid_opening = false; m_grids = pj_generic_grid_init(P, "grids"); if (proj_errno(P)) { return false; } bool isProjectedCoord; if (!checkGridTypes(P, isProjectedCoord)) { return false; } } return true; } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- static const std::string sHORIZONTAL_OFFSET("HORIZONTAL_OFFSET"); PJ_XYZ gridshiftData::apply(PJ *P, PJ_DIRECTION direction, PJ_XYZ xyz) { PJ_XYZ out; out.x = HUGE_VAL; out.y = HUGE_VAL; out.z = HUGE_VAL; std::string &type = m_mainGridType; bool bFoundGeog3DOffset = false; while (true) { GenericShiftGridSet *gridset = nullptr; const GenericShiftGrid *grid = findGrid(type, xyz, gridset); if (!grid) { if (m_mainGridTypeIsGeographic3DOffset && m_bHasHorizontalOffset) { // If we have a mix of grids with GEOGRAPHIC_3D_OFFSET // and HORIZONTAL_OFFSET+ELLIPSOIDAL_HEIGHT_OFFSET type = sHORIZONTAL_OFFSET; grid = findGrid(type, xyz, gridset); } if (!grid) { proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return out; } } else { if (m_mainGridTypeIsGeographic3DOffset) bFoundGeog3DOffset = true; } if (grid->isNullGrid()) { out = xyz; break; } bool shouldRetry = false; out = grid_apply_internal( P->ctx, type, !(m_bHasGeographic3DOffset || m_bHasHorizontalOffset), xyz, direction, grid, gridset, shouldRetry); if (!shouldRetry) { break; } } if (out.x == HUGE_VAL || out.y == HUGE_VAL) { if (proj_context_errno(P->ctx) == 0) { proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); } return out; } // Second pass to apply vertical transformation, if it is in a // separate grid than lat-lon offsets. if (!bFoundGeog3DOffset && !m_auxGridType.empty()) { xyz = out; while (true) { GenericShiftGridSet *gridset = nullptr; const auto grid = findGrid(m_auxGridType, xyz, gridset); if (!grid) { proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return out; } if (grid->isNullGrid()) { break; } bool shouldRetry = false; out = grid_apply_internal(P->ctx, m_auxGridType, true, xyz, direction, grid, gridset, shouldRetry); if (!shouldRetry) { break; } } if (out.x == HUGE_VAL || out.y == HUGE_VAL) { proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_GRID); return out; } } return out; } } // anonymous namespace // --------------------------------------------------------------------------- static PJ_XYZ pj_gridshift_forward_3d(PJ_LPZ lpz, PJ *P) { auto Q = static_cast<gridshiftData *>(P->opaque); if (!Q->loadGridsIfNeeded(P)) { return proj_coord_error().xyz; } PJ_XYZ xyz; xyz.x = lpz.lam; xyz.y = lpz.phi; xyz.z = lpz.z; xyz = Q->apply(P, PJ_FWD, xyz); xyz.x += Q->m_offsetX; xyz.y += Q->m_offsetY; return xyz; } // --------------------------------------------------------------------------- static PJ_LPZ pj_gridshift_reverse_3d(PJ_XYZ xyz, PJ *P) { auto Q = static_cast<gridshiftData *>(P->opaque); // Must be done before using m_offsetX ! if (!Q->loadGridsIfNeeded(P)) { return proj_coord_error().lpz; } xyz.x -= Q->m_offsetX; xyz.y -= Q->m_offsetY; PJ_XYZ xyz_out = Q->apply(P, PJ_INV, xyz); PJ_LPZ lpz; lpz.lam = xyz_out.x; lpz.phi = xyz_out.y; lpz.z = xyz_out.z; return lpz; } // --------------------------------------------------------------------------- static PJ *pj_gridshift_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; delete static_cast<struct gridshiftData *>(P->opaque); P->opaque = nullptr; return pj_default_destructor(P, errlev); } // --------------------------------------------------------------------------- static void pj_gridshift_reassign_context(PJ *P, PJ_CONTEXT *ctx) { auto Q = (struct gridshiftData *)P->opaque; for (auto &grid : Q->m_grids) { grid->reassign_context(ctx); } } // --------------------------------------------------------------------------- PJ *PJ_TRANSFORMATION(gridshift, 0) { auto Q = new gridshiftData; P->opaque = (void *)Q; P->destructor = pj_gridshift_destructor; P->reassign_context = pj_gridshift_reassign_context; P->fwd3d = pj_gridshift_forward_3d; P->inv3d = pj_gridshift_reverse_3d; P->fwd = nullptr; P->inv = nullptr; if (0 == pj_param(P->ctx, P->params, "tgrids").i) { proj_log_error(P, _("+grids parameter missing.")); return pj_gridshift_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } bool isProjectedCoord = false; if (P->ctx->defer_grid_opening) { Q->m_defer_grid_opening = true; } else { const char *gridnames = pj_param(P->ctx, P->params, "sgrids").s; gMutex.lock(); const auto iter = gKnownGrids.find(gridnames); const bool isKnownGrid = iter != gKnownGrids.end(); if (isKnownGrid) { isProjectedCoord = iter->second; } gMutex.unlock(); if (isKnownGrid) { Q->m_defer_grid_opening = true; } else { Q->m_grids = pj_generic_grid_init(P, "grids"); /* Was gridlist compiled properly? */ if (proj_errno(P)) { proj_log_error(P, _("could not find required grid(s).")); return pj_gridshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } if (!Q->checkGridTypes(P, isProjectedCoord)) { return pj_gridshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } gMutex.lock(); gKnownGrids[gridnames] = isProjectedCoord; gMutex.unlock(); } } if (pj_param(P->ctx, P->params, "tinterpolation").i) { const char *interpolation = pj_param(P->ctx, P->params, "sinterpolation").s; if (strcmp(interpolation, "bilinear") == 0 || strcmp(interpolation, "biquadratic") == 0) { Q->m_interpolation = interpolation; } else { proj_log_error(P, _("Unsupported value for +interpolation.")); return pj_gridshift_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (pj_param(P->ctx, P->params, "tno_z_transform").i) { Q->m_skip_z_transform = true; } // +coord_type not advertized in documentation on purpose for now. // It is probably useless to do it, as the only potential use case of it // would be for PROJ itself when generating pipelines with defered grid // opening. if (pj_param(P->ctx, P->params, "tcoord_type").i) { // Check the coordinate type (projected/geographic) from the explicit // +coord_type switch. This is mostly only useful in defered grid // opening, otherwise we have figured it out above in checkGridTypes() const char *coord_type = pj_param(P->ctx, P->params, "scoord_type").s; if (coord_type) { if (strcmp(coord_type, "projected") == 0) { if (!P->ctx->defer_grid_opening && !isProjectedCoord) { proj_log_error(P, _("+coord_type=projected specified, but the " "grid is known to not be projected")); return pj_gridshift_destructor( P, PROJ_ERR_INVALID_OP_MISSING_ARG); } isProjectedCoord = true; } else if (strcmp(coord_type, "geographic") == 0) { if (!P->ctx->defer_grid_opening && isProjectedCoord) { proj_log_error(P, _("+coord_type=geographic specified, but " "the grid is known to be projected")); return pj_gridshift_destructor( P, PROJ_ERR_INVALID_OP_MISSING_ARG); } } else { proj_log_error(P, _("Unsupported value for +coord_type: valid " "values are 'geographic' or 'projected'")); return pj_gridshift_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } } } if (isProjectedCoord) { P->left = PJ_IO_UNITS_PROJECTED; P->right = PJ_IO_UNITS_PROJECTED; } else { P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; } return P; } // --------------------------------------------------------------------------- void pj_clear_gridshift_knowngrids_cache() { std::lock_guard<std::mutex> lock(gMutex); gKnownGrids.clear(); }
cpp
PROJ
data/projects/PROJ/src/transformations/horner.cpp
/*********************************************************************** Interfacing to a classic piece of geodetic software ************************************************************************ gen_pol is a highly efficient, classic implementation of a generic 2D Horner's Scheme polynomial evaluation routine by Knud Poder and Karsten Engsager, originating in the vivid geodetic environment at what was then (1960-ish) the Danish Geodetic Institute. The original Poder/Engsager gen_pol implementation (where the polynomial degree and two sets of polynomial coefficients are packed together in one compound array, handled via a plain double pointer) is compelling and "true to the code history": It has a beautiful classical 1960s ring to it, not unlike the original fft implementations, which revolutionized spectral analysis in twenty lines of code. The Poder coding sound, as classic 1960s as Phil Spector's Wall of Sound, is beautiful and inimitable. On the other hand: For the uninitiated, the gen_pol code is hard to follow, despite being compact. Also, since adding metadata and improving maintainability of the code are among the implied goals of a current SDFE/DTU Space project, the material in this file introduces a version with a more modern (or at least 1990s) look, introducing a "double 2D polynomial" data type, HORNER. Despite introducing a new data type for handling the polynomial coefficients, great care has been taken to keep the coefficient array organization identical to that of gen_pol. Hence, on one hand, the HORNER data type helps improving the long term maintainability of the code by making the data organization more mentally accessible. On the other hand, it allows us to preserve the business end of the original gen_pol implementation - although not including the famous "Poder dual autocheck" in all its enigmatic elegance. ********************************************************************** The material included here was written by Knud Poder, starting around 1960, and Karsten Engsager, starting around 1970. It was originally written in Algol 60, later (1980s) reimplemented in C. The HORNER data type interface, and the organization as a header library was implemented by Thomas Knudsen, starting around 2015. *********************************************************************** * * Copyright (c) 2016, SDFE http://www.sdfe.dk / Thomas Knudsen / Karsten Engsager * * 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 <cassert> #include <complex> #include <cstdint> #include <errno.h> #include <math.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(horner, "Horner polynomial evaluation"); /* make horner.h interface with proj's memory management */ #define horner_dealloc(x) free(x) #define horner_calloc(n, x) calloc(n, x) namespace { // anonymous namespace struct horner { int uneg; /* u axis negated? */ int vneg; /* v axis negated? */ uint32_t order; /* maximum degree of polynomium */ double range; /* radius of the region of validity */ bool has_inv; /* inv parameters are specified */ double inverse_tolerance; /* in the units of the destination coords, specifies when to stop iterating if !has_inv and direction is reverse */ double *fwd_u; /* coefficients for the forward transformations */ double *fwd_v; /* i.e. latitude/longitude to northing/easting */ double *inv_u; /* coefficients for the inverse transformations */ double *inv_v; /* i.e. northing/easting to latitude/longitude */ double *fwd_c; /* coefficients for the complex forward transformations */ double *inv_c; /* coefficients for the complex inverse transformations */ PJ_UV *fwd_origin; /* False longitude/latitude */ PJ_UV *inv_origin; /* False easting/northing */ }; } // anonymous namespace typedef struct horner HORNER; /* e.g. degree = 2: a + bx + cy + dxx + eyy + fxy, i.e. 6 coefficients */ constexpr uint32_t horner_number_of_real_coefficients(uint32_t order) { return (order + 1) * (order + 2) / 2; } constexpr uint32_t horner_number_of_complex_coefficients(uint32_t order) { return 2 * order + 2; } static void horner_free(HORNER *h) { horner_dealloc(h->inv_v); horner_dealloc(h->inv_u); horner_dealloc(h->fwd_v); horner_dealloc(h->fwd_u); horner_dealloc(h->fwd_c); horner_dealloc(h->inv_c); horner_dealloc(h->fwd_origin); horner_dealloc(h->inv_origin); horner_dealloc(h); } static HORNER *horner_alloc(uint32_t order, bool complex_polynomia) { /* uint32_t is unsigned, so we need not check for order > 0 */ bool polynomia_ok = false; HORNER *h = static_cast<HORNER *>(horner_calloc(1, sizeof(HORNER))); if (nullptr == h) return nullptr; uint32_t n = complex_polynomia ? horner_number_of_complex_coefficients(order) : horner_number_of_real_coefficients(order); h->order = order; if (complex_polynomia) { h->fwd_c = static_cast<double *>(horner_calloc(n, sizeof(double))); h->inv_c = static_cast<double *>(horner_calloc(n, sizeof(double))); if (h->fwd_c && h->inv_c) polynomia_ok = true; } else { h->fwd_u = static_cast<double *>(horner_calloc(n, sizeof(double))); h->fwd_v = static_cast<double *>(horner_calloc(n, sizeof(double))); h->inv_u = static_cast<double *>(horner_calloc(n, sizeof(double))); h->inv_v = static_cast<double *>(horner_calloc(n, sizeof(double))); if (h->fwd_u && h->fwd_v && h->inv_u && h->inv_v) polynomia_ok = true; } h->fwd_origin = static_cast<PJ_UV *>(horner_calloc(1, sizeof(PJ_UV))); h->inv_origin = static_cast<PJ_UV *>(horner_calloc(1, sizeof(PJ_UV))); if (polynomia_ok && h->fwd_origin && h->inv_origin) return h; /* safe, since all pointers are null-initialized (by calloc) */ horner_free(h); return nullptr; } inline static PJ_UV double_real_horner_eval(uint32_t order, const double *cx, const double *cy, PJ_UV en, uint32_t order_offset = 0) { /* The melody of this block is straight out of the great Engsager/Poder songbook. For numerical stability, the summation is carried out backwards, summing the tiny high order elements first. Double Horner's scheme: N = n*Cy*e -> yout, E = e*Cx*n -> xout */ const double n = en.v; const double e = en.u; const uint32_t sz = horner_number_of_real_coefficients(order); cx += sz; cy += sz; double N = *--cy; double E = *--cx; for (uint32_t r = order; r > order_offset; r--) { double u = *--cy; double v = *--cx; for (uint32_t c = order; c >= r; c--) { u = n * u + *--cy; v = e * v + *--cx; } N = e * N + u; E = n * E + v; } return {E, N}; } inline static double single_real_horner_eval(uint32_t order, const double *cx, double x, uint32_t order_offset = 0) { const uint32_t sz = order + 1; /* Number of coefficients per polynomial */ cx += sz; double u = *--cx; for (uint32_t r = order; r > order_offset; r--) { u = x * u + *--cx; } return u; } inline static PJ_UV complex_horner_eval(uint32_t order, const double *c, PJ_UV en, uint32_t order_offset = 0) { // the coefficients are ordered like this: // (Cn0+i*Ce0, Cn1+i*Ce1, ...) const uint32_t sz = horner_number_of_complex_coefficients(order); const double e = en.u; const double n = en.v; const double *cbeg = c + order_offset * 2; c += sz; double E = *--c; double N = *--c; double w; while (c > cbeg) { w = n * E + e * N + *--c; N = n * N - e * E + *--c; E = w; } return {E, N}; } inline static PJ_UV generate_error_coords() { PJ_UV uv_error; uv_error.u = uv_error.v = HUGE_VAL; return uv_error; } inline static bool coords_out_of_range(PJ *P, const HORNER *transformation, double n, double e) { const double range = transformation->range; if ((fabs(n) > range) || (fabs(e) > range)) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return true; } return false; } static PJ_UV real_default_impl(PJ *P, const HORNER *transformation, PJ_DIRECTION direction, PJ_UV position) { /*********************************************************************** A reimplementation of the classic Engsager/Poder 2D Horner polynomial evaluation engine "gen_pol". This version omits the inimitable Poder "dual autocheck"-machinery, which here is intended to be implemented at a higher level of the library: We separate the polynomial evaluation from the quality control (which, given the limited MTBF for "computing machinery", typical when Knud Poder invented the dual autocheck method, was not defensible at that time). Another difference from the original version is that we return the result on the stack, rather than accepting pointers to result variables as input. This results in code that is easy to read: projected = horner (s34j, 1, geographic); geographic = horner (s34j, -1, projected ); and experiments have shown that on contemporary architectures, the time taken for returning even comparatively large objects on the stack (and the UV is not that large - typically only 16 bytes) is negligibly different from passing two pointers (i.e. typically also 16 bytes) the other way. The polynomium has the form: P = sum (i = [0 : order]) sum (j = [0 : order - i]) pow(par_1, i) * pow(par_2, j) * coef(index(order, i, j)) ***********************************************************************/ assert(direction == PJ_FWD || direction == PJ_INV); double n, e; if (direction == PJ_FWD) { /* forward */ e = position.u - transformation->fwd_origin->u; n = position.v - transformation->fwd_origin->v; } else { /* inverse */ e = position.u - transformation->inv_origin->u; n = position.v - transformation->inv_origin->v; } if (coords_out_of_range(P, transformation, n, e)) { return generate_error_coords(); } const double *tcx = direction == PJ_FWD ? transformation->fwd_u : transformation->inv_u; const double *tcy = direction == PJ_FWD ? transformation->fwd_v : transformation->inv_v; PJ_UV en = {e, n}; position = double_real_horner_eval(transformation->order, tcx, tcy, en); return position; } static PJ_UV real_iterative_inverse_impl(PJ *P, const HORNER *transformation, PJ_UV position) { double n, e; // in this case fwd_origin needs to be added in the end e = position.u; n = position.v; if (coords_out_of_range(P, transformation, n, e)) { return generate_error_coords(); } /* * solve iteratively * * | E | | u00 | | u01 + u02*x + ... ' u10 + u11*x + u20*y + ... * | | x | | | = | | + |-------------------------- ' * --------------------------| | | | N | | v00 | | v10 + v11*y + v20*x * + * ... ' v01 + v02*y + ... | | y | * * | x | | Ma ' Mb |-1 | E-u00 | * | | = |-------- | | | * | y | | Mc ' Md | | N-v00 | */ const uint32_t order = transformation->order; const double tol = transformation->inverse_tolerance; const double de = e - transformation->fwd_u[0]; const double dn = n - transformation->fwd_v[0]; double x0 = 0.0; double y0 = 0.0; int loops = 32; // usually converges really fast (1-2 loops) bool converged = false; while (loops-- > 0 && !converged) { double Ma = 0.0; double Mb = 0.0; double Mc = 0.0; double Md = 0.0; { const double *tcx = transformation->fwd_u; const double *tcy = transformation->fwd_v; PJ_UV x0y0 = {x0, y0}; // sum the i > 0 coefficients PJ_UV Mbc = double_real_horner_eval(order, tcx, tcy, x0y0, 1); Mb = Mbc.u; Mc = Mbc.v; // sum the i = 0, j > 0 coefficients Ma = single_real_horner_eval(order, tcx, x0, 1); Md = single_real_horner_eval(order, tcy, y0, 1); } double idet = 1.0 / (Ma * Md - Mb * Mc); double x = idet * (Md * de - Mb * dn); double y = idet * (Ma * dn - Mc * de); converged = (fabs(x - x0) < tol) && (fabs(y - y0) < tol); x0 = x; y0 = y; } // if loops have been exhausted and we have not converged yet, // we are never going to converge if (!converged) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM); return generate_error_coords(); } else { position.u = x0 + transformation->fwd_origin->u; position.v = y0 + transformation->fwd_origin->v; return position; } } static void horner_forward_4d(PJ_COORD &point, PJ *P) { const HORNER *transformation = reinterpret_cast<const HORNER *>(P->opaque); point.uv = real_default_impl(P, transformation, PJ_FWD, point.uv); } static void horner_inverse_4d(PJ_COORD &point, PJ *P) { const HORNER *transformation = reinterpret_cast<const HORNER *>(P->opaque); point.uv = real_default_impl(P, transformation, PJ_INV, point.uv); } static void horner_iterative_inverse_4d(PJ_COORD &point, PJ *P) { const HORNER *transformation = reinterpret_cast<const HORNER *>(P->opaque); point.uv = real_iterative_inverse_impl(P, transformation, point.uv); } static PJ_UV complex_default_impl(PJ *P, const HORNER *transformation, PJ_DIRECTION direction, PJ_UV position) { /*********************************************************************** A reimplementation of a classic Engsager/Poder Horner complex polynomial evaluation engine. ***********************************************************************/ assert(direction == PJ_FWD || direction == PJ_INV); double n, e; if (direction == PJ_FWD) { /* forward */ e = position.u - transformation->fwd_origin->u; n = position.v - transformation->fwd_origin->v; } else { /* inverse */ e = position.u - transformation->inv_origin->u; n = position.v - transformation->inv_origin->v; } if (transformation->uneg) e = -e; if (transformation->vneg) n = -n; if (coords_out_of_range(P, transformation, n, e)) { return generate_error_coords(); } // coefficient pointers double *cb = direction == PJ_FWD ? transformation->fwd_c : transformation->inv_c; PJ_UV en = {e, n}; position = complex_horner_eval(transformation->order, cb, en); return position; } static PJ_UV complex_iterative_inverse_impl(PJ *P, const HORNER *transformation, PJ_UV position) { double n, e; // in this case fwd_origin and any existing flipping needs to be added in // the end e = position.u; n = position.v; if (coords_out_of_range(P, transformation, n, e)) { return generate_error_coords(); } { // complex real part corresponds to Northing, imag part to Easting const double tol = transformation->inverse_tolerance; const std::complex<double> dZ(n - transformation->fwd_c[0], e - transformation->fwd_c[1]); std::complex<double> w0(0.0, 0.0); int loops = 32; // usually converges really fast (1-2 loops) bool converged = false; while (loops-- > 0 && !converged) { // sum coefficient pointers from back to front until the first // complex pair (fwd_c0+i*fwd_c1) const double *c = transformation->fwd_c; PJ_UV en = {w0.imag(), w0.real()}; en = complex_horner_eval(transformation->order, c, en, 1); std::complex<double> det(en.v, en.u); std::complex<double> w1 = dZ / det; converged = (fabs(w1.real() - w0.real()) < tol) && (fabs(w1.imag() - w0.imag()) < tol); w0 = w1; } // if loops have been exhausted and we have not converged yet, // we are never going to converge if (!converged) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM); position = generate_error_coords(); } else { double E = w0.imag(); double N = w0.real(); if (transformation->uneg) E = -E; if (transformation->vneg) N = -N; position.u = E + transformation->fwd_origin->u; position.v = N + transformation->fwd_origin->v; } return position; } } static void complex_horner_forward_4d(PJ_COORD &point, PJ *P) { const HORNER *transformation = reinterpret_cast<const HORNER *>(P->opaque); point.uv = complex_default_impl(P, transformation, PJ_FWD, point.uv); } static void complex_horner_inverse_4d(PJ_COORD &point, PJ *P) { const HORNER *transformation = reinterpret_cast<const HORNER *>(P->opaque); point.uv = complex_default_impl(P, transformation, PJ_INV, point.uv); } static void complex_horner_iterative_inverse_4d(PJ_COORD &point, PJ *P) { const HORNER *transformation = reinterpret_cast<const HORNER *>(P->opaque); point.uv = complex_iterative_inverse_impl(P, transformation, point.uv); } static PJ *horner_freeup(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); horner_free((HORNER *)P->opaque); P->opaque = nullptr; return pj_default_destructor(P, errlev); } static int parse_coefs(PJ *P, double *coefs, const char *param, int ncoefs) { char *buf, *init, *next = nullptr; int i; size_t buf_size = strlen(param) + 2; buf = static_cast<char *>(calloc(buf_size, sizeof(char))); if (nullptr == buf) { proj_log_error(P, "No memory left"); return 0; } snprintf(buf, buf_size, "t%s", param); if (0 == pj_param(P->ctx, P->params, buf).i) { free(buf); return 0; } snprintf(buf, buf_size, "s%s", param); init = pj_param(P->ctx, P->params, buf).s; free(buf); for (i = 0; i < ncoefs; i++) { if (i > 0) { if (next == nullptr || ',' != *next) { proj_log_error(P, "Malformed polynomium set %s. need %d coefs", param, ncoefs); return 0; } init = ++next; } coefs[i] = pj_strtod(init, &next); } return 1; } /*********************************************************************/ PJ *PJ_PROJECTION(horner) { /*********************************************************************/ int degree = 0; HORNER *Q; P->fwd3d = nullptr; P->inv3d = nullptr; P->fwd = nullptr; P->inv = nullptr; P->left = P->right = PJ_IO_UNITS_WHATEVER; P->destructor = horner_freeup; /* Polynomial degree specified? */ if (pj_param(P->ctx, P->params, "tdeg").i) { /* degree specified? */ degree = pj_param(P->ctx, P->params, "ideg").i; if (degree < 0 || degree > 10000) { /* What are reasonable minimum and maximums for degree? */ proj_log_error(P, _("Degree is unreasonable: %d"), degree); return horner_freeup(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } else { proj_log_error(P, _("Must specify polynomial degree, (+deg=n)")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } bool complex_polynomia = false; if (pj_param(P->ctx, P->params, "tfwd_c").i || pj_param(P->ctx, P->params, "tinv_c").i) /* complex polynomium? */ complex_polynomia = true; Q = horner_alloc(degree, complex_polynomia); if (Q == nullptr) return horner_freeup(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; bool has_inv = false; if (!complex_polynomia) { has_inv = pj_param_exists(P->params, "inv_u") || pj_param_exists(P->params, "inv_v") || pj_param_exists(P->params, "inv_origin"); } else { has_inv = pj_param_exists(P->params, "inv_c") || pj_param_exists(P->params, "inv_origin"); } Q->has_inv = has_inv; // setup callbacks if (complex_polynomia) { P->fwd4d = complex_horner_forward_4d; P->inv4d = has_inv ? complex_horner_inverse_4d : complex_horner_iterative_inverse_4d; } else { P->fwd4d = horner_forward_4d; P->inv4d = has_inv ? horner_inverse_4d : horner_iterative_inverse_4d; } if (complex_polynomia) { /* Westings and/or southings? */ Q->uneg = pj_param_exists(P->params, "uneg") ? 1 : 0; Q->vneg = pj_param_exists(P->params, "vneg") ? 1 : 0; const int n = static_cast<int>(horner_number_of_complex_coefficients(degree)); if (0 == parse_coefs(P, Q->fwd_c, "fwd_c", n)) { proj_log_error(P, _("missing fwd_c")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (has_inv && 0 == parse_coefs(P, Q->inv_c, "inv_c", n)) { proj_log_error(P, _("missing inv_c")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } } else { const int n = static_cast<int>(horner_number_of_real_coefficients(degree)); if (0 == parse_coefs(P, Q->fwd_u, "fwd_u", n)) { proj_log_error(P, _("missing fwd_u")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (0 == parse_coefs(P, Q->fwd_v, "fwd_v", n)) { proj_log_error(P, _("missing fwd_v")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (has_inv && 0 == parse_coefs(P, Q->inv_u, "inv_u", n)) { proj_log_error(P, _("missing inv_u")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (has_inv && 0 == parse_coefs(P, Q->inv_v, "inv_v", n)) { proj_log_error(P, _("missing inv_v")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } } if (0 == parse_coefs(P, (double *)(Q->fwd_origin), "fwd_origin", 2)) { proj_log_error(P, _("missing fwd_origin")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (has_inv && 0 == parse_coefs(P, (double *)(Q->inv_origin), "inv_origin", 2)) { proj_log_error(P, _("missing inv_origin")); return horner_freeup(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (0 == parse_coefs(P, &Q->range, "range", 1)) Q->range = 500000; if (0 == parse_coefs(P, &Q->inverse_tolerance, "inv_tolerance", 1)) Q->inverse_tolerance = 0.001; return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/defmodel.hpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to deformation model * 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. *****************************************************************************/ /** This file implements the gridded deformation model proposol of * https://docs.google.com/document/d/1wiyrAmzqh8MZlzHSp3wf594Ob_M1LeFtDA5swuzvLZY * It is written in a generic way, independent of the rest of PROJ * infrastructure. * * Verbose debugging info can be turned on by setting the DEBUG_DEFMODEL macro */ #ifndef DEFMODEL_HPP #define DEFMODEL_HPP #ifdef PROJ_COMPILATION #include "proj/internal/include_nlohmann_json.hpp" #else #include "nlohmann/json.hpp" #endif #include <algorithm> #include <cmath> #include <exception> #include <limits> #include <memory> #include <string> #include <vector> #ifndef DEFORMATON_MODEL_NAMESPACE #define DEFORMATON_MODEL_NAMESPACE DeformationModel #endif #include "defmodel_exceptions.hpp" namespace DEFORMATON_MODEL_NAMESPACE { using json = nlohmann::json; // --------------------------------------------------------------------------- /** Spatial extent as a bounding box. */ class SpatialExtent { public: /** Parse the provided object as an extent. * * @throws ParsingException */ static SpatialExtent parse(const json &j); double minx() const { return mMinx; } double miny() const { return mMiny; } double maxx() const { return mMaxx; } double maxy() const { return mMaxy; } double minxNormalized(bool bIsGeographic) const { return bIsGeographic ? mMinxRad : mMinx; } double minyNormalized(bool bIsGeographic) const { return bIsGeographic ? mMinyRad : mMiny; } double maxxNormalized(bool bIsGeographic) const { return bIsGeographic ? mMaxxRad : mMaxx; } double maxyNormalized(bool bIsGeographic) const { return bIsGeographic ? mMaxyRad : mMaxy; } protected: friend class MasterFile; friend class Component; SpatialExtent() = default; private: double mMinx = std::numeric_limits<double>::quiet_NaN(); double mMiny = std::numeric_limits<double>::quiet_NaN(); double mMaxx = std::numeric_limits<double>::quiet_NaN(); double mMaxy = std::numeric_limits<double>::quiet_NaN(); double mMinxRad = std::numeric_limits<double>::quiet_NaN(); double mMinyRad = std::numeric_limits<double>::quiet_NaN(); double mMaxxRad = std::numeric_limits<double>::quiet_NaN(); double mMaxyRad = std::numeric_limits<double>::quiet_NaN(); }; // --------------------------------------------------------------------------- /** Epoch */ class Epoch { public: /** Constructor from a ISO 8601 date-time. May throw ParsingException */ explicit Epoch(const std::string &dt = std::string()); /** Return ISO 8601 date-time */ const std::string &toString() const { return mDt; } /** Return decimal year */ double toDecimalYear() const; private: std::string mDt{}; double mDecimalYear = 0; }; // --------------------------------------------------------------------------- /** Component of a deformation model. */ class Component { public: /** Parse the provided object as a component. * * @throws ParsingException */ static Component parse(const json &j); /** Get a text description of the component. */ const std::string &description() const { return mDescription; } /** Get the region within which the component is defined. Outside this * region the component evaluates to 0. */ const SpatialExtent &extent() const { return mSpatialExtent; } /** Get the displacement parameters defined by the component, one of * "none", "horizontal", "vertical", and "3d". The "none" option allows * for a component which defines uncertainty with different grids to those * defining displacement. */ const std::string &displacementType() const { return mDisplacementType; } /** Get the uncertainty parameters defined by the component, * one of "none", "horizontal", "vertical", "3d". */ const std::string &uncertaintyType() const { return mUncertaintyType; } /** Get the horizontal uncertainty to use if it is not defined explicitly * in the spatial model. */ double horizontalUncertainty() const { return mHorizontalUncertainty; } /** Get the vertical uncertainty to use if it is not defined explicitly in * the spatial model. */ double verticalUncertainty() const { return mVerticalUncertainty; } struct SpatialModel { /** Specifies the type of the spatial model data file. Initially it * is proposed that only "GeoTIFF" is supported. */ std::string type{}; /** How values in model should be interpolated. This proposal will * support "bilinear" and "geocentric_bilinear". */ std::string interpolationMethod{}; /** Specifies location of the spatial model GeoTIFF file relative to * the master JSON file. */ std::string filename{}; /** A hex encoded MD5 checksum of the grid file that can be used to * validate that it is the correct version of the file. */ std::string md5Checksum{}; }; /** Get the spatial model. */ const SpatialModel &spatialModel() const { return mSpatialModel; } /** Generic type for a type function */ struct TimeFunction { std::string type{}; virtual ~TimeFunction(); virtual double evaluateAt(double dt) const = 0; protected: TimeFunction() = default; }; struct ConstantTimeFunction : public TimeFunction { virtual double evaluateAt(double dt) const override; }; struct VelocityTimeFunction : public TimeFunction { /** Date/time at which the velocity function is zero. */ Epoch referenceEpoch{}; virtual double evaluateAt(double dt) const override; }; struct StepTimeFunction : public TimeFunction { /** Epoch at which the step function transitions from 0 to 1. */ Epoch stepEpoch{}; virtual double evaluateAt(double dt) const override; }; struct ReverseStepTimeFunction : public TimeFunction { /** Epoch at which the reverse step function transitions from 1. to 0 */ Epoch stepEpoch{}; virtual double evaluateAt(double dt) const override; }; struct PiecewiseTimeFunction : public TimeFunction { /** One of "zero", "constant", and "linear", defines the behavior of * the function before the first defined epoch */ std::string beforeFirst{}; /** One of "zero", "constant", and "linear", defines the behavior of * the function after the last defined epoch */ std::string afterLast{}; struct EpochScaleFactorTuple { /** Defines the date/time of the data point. */ Epoch epoch{}; /** Function value at the above epoch */ double scaleFactor = std::numeric_limits<double>::quiet_NaN(); }; /** A sorted array data points each defined by two elements. * The array is sorted in order of increasing epoch. * Note: where the time function includes a step it is represented by * two consecutive data points with the same epoch. The first defines * the scale factor that applies before the epoch and the second the * scale factor that applies after the epoch. */ std::vector<EpochScaleFactorTuple> model{}; virtual double evaluateAt(double dt) const override; }; struct ExponentialTimeFunction : public TimeFunction { /** The date/time at which the exponential decay starts. */ Epoch referenceEpoch{}; /** The date/time at which the exponential decay ends. */ Epoch endEpoch{}; /** The relaxation constant in years. */ double relaxationConstant = std::numeric_limits<double>::quiet_NaN(); /** The scale factor that applies before the reference epoch. */ double beforeScaleFactor = std::numeric_limits<double>::quiet_NaN(); /** Initial scale factor. */ double initialScaleFactor = std::numeric_limits<double>::quiet_NaN(); /** The scale factor the exponential function approaches. */ double finalScaleFactor = std::numeric_limits<double>::quiet_NaN(); virtual double evaluateAt(double dt) const override; }; /** Get the time function. */ const TimeFunction *timeFunction() const { return mTimeFunction.get(); } private: Component() = default; std::string mDescription{}; SpatialExtent mSpatialExtent{}; std::string mDisplacementType{}; std::string mUncertaintyType{}; double mHorizontalUncertainty = std::numeric_limits<double>::quiet_NaN(); double mVerticalUncertainty = std::numeric_limits<double>::quiet_NaN(); SpatialModel mSpatialModel{}; std::unique_ptr<TimeFunction> mTimeFunction{}; }; Component::TimeFunction::~TimeFunction() = default; // --------------------------------------------------------------------------- /** Master file of a deformation model. */ class MasterFile { public: /** Parse the provided serialized JSON content and return an object. * * @throws ParsingException */ static std::unique_ptr<MasterFile> parse(const std::string &text); /** Get file type. Should always be "deformation_model_master_file" */ const std::string &fileType() const { return mFileType; } /** Get the version of the format. At time of writing, only "1.0" is known */ const std::string &formatVersion() const { return mFormatVersion; } /** Get brief descriptive name of the deformation model. */ const std::string &name() const { return mName; } /** Get a string identifying the version of the deformation model. * The format for specifying version is defined by the agency * responsible for the deformation model. */ const std::string &version() const { return mVersion; } /** Get a string identifying the license of the file. * e.g "Create Commons Attribution 4.0 International" */ const std::string &license() const { return mLicense; } /** Get a text description of the model. Intended to be longer than name() */ const std::string &description() const { return mDescription; } /** Get a text description of the model. Intended to be longer than name() */ const std::string &publicationDate() const { return mPublicationDate; } /** Basic information on the agency responsible for the model. */ struct Authority { std::string name{}; std::string url{}; std::string address{}; std::string email{}; }; /** Get basic information on the agency responsible for the model. */ const Authority &authority() const { return mAuthority; } /** Hyperlink related to the model. */ struct Link { /** URL holding the information */ std::string href{}; /** Relationship to the dataset. e.g. "about", "source", "license", * "metadata" */ std::string rel{}; /** Mime type */ std::string type{}; /** Description of the link */ std::string title{}; }; /** Get links to related information. */ const std::vector<Link> links() const { return mLinks; } /** Get a string identifying the source CRS. That is the coordinate * reference system to which the deformation model applies. Typically * "EPSG:XXXX" */ const std::string &sourceCRS() const { return mSourceCRS; } /** Get a string identifying the target CRS. That is, for a time * dependent coordinate transformation, the coordinate reference * system resulting from applying the deformation. * Typically "EPSG:XXXX" */ const std::string &targetCRS() const { return mTargetCRS; } /** Get a string identifying the definition CRS. That is, the * coordinate reference system used to define the component spatial * models. Typically "EPSG:XXXX" */ const std::string &definitionCRS() const { return mDefinitionCRS; } /** Get the nominal reference epoch of the deformation model. Formatted * as a ISO-8601 date-time. This is not necessarily used to calculate * the deformation model - each component defines its own time function. */ const std::string &referenceEpoch() const { return mReferenceEpoch; } /** Get the epoch at which the uncertainties of the deformation model * are calculated. Formatted as a ISO-8601 date-time. */ const std::string &uncertaintyReferenceEpoch() const { return mUncertaintyReferenceEpoch; } /** Unit of horizontal offsets. Only "metre" and "degree" are supported. */ const std::string &horizontalOffsetUnit() const { return mHorizontalOffsetUnit; } /** Unit of vertical offsets. Only "metre" is supported. */ const std::string &verticalOffsetUnit() const { return mVerticalOffsetUnit; } /** Type of horizontal uncertainty. e.g "circular 95% confidence limit" */ const std::string &horizontalUncertaintyType() const { return mHorizontalUncertaintyType; } /** Unit of horizontal uncertainty. Only "metre" is supported. */ const std::string &horizontalUncertaintyUnit() const { return mHorizontalUncertaintyUnit; } /** Type of vertical uncertainty. e.g "circular 95% confidence limit" */ const std::string &verticalUncertaintyType() const { return mVerticalUncertaintyType; } /** Unit of vertical uncertainty. Only "metre" is supported. */ const std::string &verticalUncertaintyUnit() const { return mVerticalUncertaintyUnit; } /** Defines how the horizontal offsets are applied to geographic * coordinates. Only "addition" and "geocentric" are supported */ const std::string &horizontalOffsetMethod() const { return mHorizontalOffsetMethod; } /** Get the region within which the deformation model is defined. * It cannot be calculated outside this region */ const SpatialExtent &extent() const { return mSpatialExtent; } /** Defines the range of times for which the model is valid, specified * by a first and a last value. The deformation model is undefined for * dates outside this range. */ struct TimeExtent { Epoch first{}; Epoch last{}; }; /** Get the range of times for which the model is valid. */ const TimeExtent &timeExtent() const { return mTimeExtent; } /** Get an array of the components comprising the deformation model. */ const std::vector<Component> &components() const { return mComponents; } private: MasterFile() = default; std::string mFileType{}; std::string mFormatVersion{}; std::string mName{}; std::string mVersion{}; std::string mLicense{}; std::string mDescription{}; std::string mPublicationDate{}; Authority mAuthority{}; std::vector<Link> mLinks{}; std::string mSourceCRS{}; std::string mTargetCRS{}; std::string mDefinitionCRS{}; std::string mReferenceEpoch{}; std::string mUncertaintyReferenceEpoch{}; std::string mHorizontalOffsetUnit{}; std::string mVerticalOffsetUnit{}; std::string mHorizontalUncertaintyType{}; std::string mHorizontalUncertaintyUnit{}; std::string mVerticalUncertaintyType{}; std::string mVerticalUncertaintyUnit{}; std::string mHorizontalOffsetMethod{}; SpatialExtent mSpatialExtent{}; TimeExtent mTimeExtent{}; std::vector<Component> mComponents{}; }; // --------------------------------------------------------------------------- /** Prototype for a Grid used by GridSet. Intended to be implemented * by user code */ struct GridPrototype { double minx = 0; double miny = 0; double resx = 0; double resy = 0; int width = 0; int height = 0; // cppcheck-suppress functionStatic bool getLongLatOffset(int /*ix*/, int /*iy*/, double & /*longOffsetRadian*/, double & /*latOffsetRadian*/) const { throw UnimplementedException("getLongLatOffset unimplemented"); } // cppcheck-suppress functionStatic bool getZOffset(int /*ix*/, int /*iy*/, double & /*zOffset*/) const { throw UnimplementedException("getZOffset unimplemented"); } // cppcheck-suppress functionStatic bool getEastingNorthingOffset(int /*ix*/, int /*iy*/, double & /*eastingOffset*/, double & /*northingOffset*/) const { throw UnimplementedException("getEastingNorthingOffset unimplemented"); } // cppcheck-suppress functionStatic bool getLongLatZOffset(int /*ix*/, int /*iy*/, double & /*longOffsetRadian*/, double & /*latOffsetRadian*/, double & /*zOffset*/) const { throw UnimplementedException("getLongLatZOffset unimplemented"); #if 0 return getLongLatOffset(ix, iy, longOffsetRadian, latOffsetRadian) && getZOffset(ix, iy, zOffset); #endif } // cppcheck-suppress functionStatic bool getEastingNorthingZOffset(int /*ix*/, int /*iy*/, double & /*eastingOffset*/, double & /*northingOffset*/, double & /*zOffset*/) const { throw UnimplementedException("getEastingNorthingOffset unimplemented"); #if 0 return getEastingNorthingOffset(ix, iy, eastingOffset, northingOffset) && getZOffset(ix, iy, zOffset); #endif } #ifdef DEBUG_DEFMODEL std::string name() const { throw UnimplementedException("name() unimplemented"); } #endif }; // --------------------------------------------------------------------------- /** Prototype for a GridSet used by EvaluatorIface. Intended to be implemented * by user code */ template <class Grid = GridPrototype> struct GridSetPrototype { // The return pointer should remain "stable" over time for a given grid // of a GridSet. // cppcheck-suppress functionStatic const Grid *gridAt(double /*x */, double /* y */) { throw UnimplementedException("gridAt unimplemented"); } }; // --------------------------------------------------------------------------- /** Prototype for a EvaluatorIface used by Evaluator. Intended to be implemented * by user code */ template <class Grid = GridPrototype, class GridSet = GridSetPrototype<>> struct EvaluatorIfacePrototype { std::unique_ptr<GridSet> open(const std::string & /* filename*/) { throw UnimplementedException("open unimplemented"); } // cppcheck-suppress functionStatic void geographicToGeocentric(double /* lam */, double /* phi */, double /* height*/, double /* a */, double /* b */, double /*es*/, double & /* X */, double & /* Y */, double & /* Z */) { throw UnimplementedException("geographicToGeocentric unimplemented"); } // cppcheck-suppress functionStatic void geocentricToGeographic(double /* X */, double /* Y */, double /* Z */, double /* a */, double /* b */, double /*es*/, double & /* lam */, double & /* phi */, double & /* height*/) { throw UnimplementedException("geocentricToGeographic unimplemented"); } // cppcheck-suppress functionStatic bool isGeographicCRS(const std::string & /* crsDef */) { throw UnimplementedException("isGeographicCRS unimplemented"); } #ifdef DEBUG_DEFMODEL void log(const std::string & /* msg */) { throw UnimplementedException("log unimplemented"); } #endif }; // --------------------------------------------------------------------------- /** Internal class to offer caching services over a Component */ template <class Grid, class GridSet> struct ComponentEx; // --------------------------------------------------------------------------- /** Class to evaluate the transformation of a coordinate */ template <class Grid = GridPrototype, class GridSet = GridSetPrototype<>, class EvaluatorIface = EvaluatorIfacePrototype<>> class Evaluator { public: /** Constructor. May throw EvaluatorException */ explicit Evaluator(std::unique_ptr<MasterFile> &&model, EvaluatorIface &iface, double a, double b); /** Evaluate displacement of a position given by (x,y,z,t) and * return it in (x_out,y_out_,z_out). * For geographic CRS (only supported at that time), x must be a * longitude, and y a latitude. */ bool forward(EvaluatorIface &iface, double x, double y, double z, double t, double &x_out, double &y_out, double &z_out) { return forward(iface, x, y, z, t, false, x_out, y_out, z_out); } /** Apply inverse transformation. */ bool inverse(EvaluatorIface &iface, double x, double y, double z, double t, double &x_out, double &y_out, double &z_out); /** Clear grid cache */ void clearGridCache(); /** Return whether the definition CRS is a geographic CRS */ bool isGeographicCRS() const { return mIsGeographicCRS; } private: std::unique_ptr<MasterFile> mModel; const double mA; const double mB; const double mEs; const bool mIsHorizontalUnitDegree; /* degree vs metre */ const bool mIsAddition; /* addition vs geocentric */ const bool mIsGeographicCRS; bool forward(EvaluatorIface &iface, double x, double y, double z, double t, bool forInverseComputation, double &x_out, double &y_out, double &z_out); std::vector<std::unique_ptr<ComponentEx<Grid, GridSet>>> mComponents{}; }; // --------------------------------------------------------------------------- } // namespace DEFORMATON_MODEL_NAMESPACE // --------------------------------------------------------------------------- #include "defmodel_impl.hpp" #endif // DEFMODEL_HPP
hpp
PROJ
data/projects/PROJ/src/transformations/defmodel_exceptions.hpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to deformation model * 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. *****************************************************************************/ #ifndef DEFORMATON_MODEL_NAMESPACE #error "Should be included only by defmodel.hpp" #endif #include <exception> namespace DEFORMATON_MODEL_NAMESPACE { // --------------------------------------------------------------------------- /** Parsing exception. */ class ParsingException : public std::exception { public: explicit ParsingException(const std::string &msg) : msg_(msg) {} const char *what() const noexcept override; private: std::string msg_; }; const char *ParsingException::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- class UnimplementedException : public std::exception { public: explicit UnimplementedException(const std::string &msg) : msg_(msg) {} const char *what() const noexcept override; private: std::string msg_; }; const char *UnimplementedException::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- /** Evaluator exception. */ class EvaluatorException : public std::exception { public: explicit EvaluatorException(const std::string &msg) : msg_(msg) {} const char *what() const noexcept override; private: std::string msg_; }; const char *EvaluatorException::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- } // namespace DEFORMATON_MODEL_NAMESPACE
hpp
PROJ
data/projects/PROJ/src/transformations/affine.cpp
/************************************************************************ * Copyright (c) 2018, 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. * ***********************************************************************/ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(affine, "Affine transformation"); PROJ_HEAD(geogoffset, "Geographic Offset"); namespace { // anonymous namespace struct pj_affine_coeffs { double s11; double s12; double s13; double s21; double s22; double s23; double s31; double s32; double s33; double tscale; }; } // anonymous namespace namespace { // anonymous namespace struct pj_opaque_affine { double xoff; double yoff; double zoff; double toff; struct pj_affine_coeffs forward; struct pj_affine_coeffs reverse; }; } // anonymous namespace static void forward_4d(PJ_COORD &coo, PJ *P) { const struct pj_opaque_affine *Q = (const struct pj_opaque_affine *)P->opaque; const struct pj_affine_coeffs *C = &(Q->forward); const double x = coo.xyz.x; const double y = coo.xyz.y; const double z = coo.xyz.z; coo.xyzt.x = Q->xoff + C->s11 * x + C->s12 * y + C->s13 * z; coo.xyzt.y = Q->yoff + C->s21 * x + C->s22 * y + C->s23 * z; coo.xyzt.z = Q->zoff + C->s31 * x + C->s32 * y + C->s33 * z; coo.xyzt.t = Q->toff + C->tscale * coo.xyzt.t; } static PJ_XYZ forward_3d(PJ_LPZ lpz, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.lpz = lpz; forward_4d(point, P); return point.xyz; } static PJ_XY forward_2d(PJ_LP lp, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.lp = lp; forward_4d(point, P); return point.xy; } static void reverse_4d(PJ_COORD &coo, PJ *P) { const struct pj_opaque_affine *Q = (const struct pj_opaque_affine *)P->opaque; const struct pj_affine_coeffs *C = &(Q->reverse); double x = coo.xyzt.x - Q->xoff; double y = coo.xyzt.y - Q->yoff; double z = coo.xyzt.z - Q->zoff; coo.xyzt.x = C->s11 * x + C->s12 * y + C->s13 * z; coo.xyzt.y = C->s21 * x + C->s22 * y + C->s23 * z; coo.xyzt.z = C->s31 * x + C->s32 * y + C->s33 * z; coo.xyzt.t = C->tscale * (coo.xyzt.t - Q->toff); } static PJ_LPZ reverse_3d(PJ_XYZ xyz, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.xyz = xyz; reverse_4d(point, P); return point.lpz; } static PJ_LP reverse_2d(PJ_XY xy, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.xy = xy; reverse_4d(point, P); return point.lp; } static struct pj_opaque_affine *initQ() { struct pj_opaque_affine *Q = static_cast<struct pj_opaque_affine *>( calloc(1, sizeof(struct pj_opaque_affine))); if (nullptr == Q) return nullptr; /* default values */ Q->forward.s11 = 1.0; Q->forward.s22 = 1.0; Q->forward.s33 = 1.0; Q->forward.tscale = 1.0; Q->reverse.s11 = 1.0; Q->reverse.s22 = 1.0; Q->reverse.s33 = 1.0; Q->reverse.tscale = 1.0; return Q; } static void computeReverseParameters(PJ *P) { struct pj_opaque_affine *Q = (struct pj_opaque_affine *)P->opaque; /* cf * https://en.wikipedia.org/wiki/Invertible_matrix#Inversion_of_3_%C3%97_3_matrices */ const double a = Q->forward.s11; const double b = Q->forward.s12; const double c = Q->forward.s13; const double d = Q->forward.s21; const double e = Q->forward.s22; const double f = Q->forward.s23; const double g = Q->forward.s31; const double h = Q->forward.s32; const double i = Q->forward.s33; const double A = e * i - f * h; const double B = -(d * i - f * g); const double C = (d * h - e * g); const double D = -(b * i - c * h); const double E = (a * i - c * g); const double F = -(a * h - b * g); const double G = b * f - c * e; const double H = -(a * f - c * d); const double I = a * e - b * d; const double det = a * A + b * B + c * C; if (det == 0.0 || Q->forward.tscale == 0.0) { if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_DEBUG) { proj_log_debug(P, "matrix non invertible"); } P->inv4d = nullptr; P->inv3d = nullptr; P->inv = nullptr; } else { Q->reverse.s11 = A / det; Q->reverse.s12 = D / det; Q->reverse.s13 = G / det; Q->reverse.s21 = B / det; Q->reverse.s22 = E / det; Q->reverse.s23 = H / det; Q->reverse.s31 = C / det; Q->reverse.s32 = F / det; Q->reverse.s33 = I / det; Q->reverse.tscale = 1.0 / Q->forward.tscale; } } PJ *PJ_TRANSFORMATION(affine, 0 /* no need for ellipsoid */) { struct pj_opaque_affine *Q = initQ(); 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; /* read args */ Q->xoff = pj_param(P->ctx, P->params, "dxoff").f; Q->yoff = pj_param(P->ctx, P->params, "dyoff").f; Q->zoff = pj_param(P->ctx, P->params, "dzoff").f; Q->toff = pj_param(P->ctx, P->params, "dtoff").f; if (pj_param(P->ctx, P->params, "ts11").i) { Q->forward.s11 = pj_param(P->ctx, P->params, "ds11").f; } Q->forward.s12 = pj_param(P->ctx, P->params, "ds12").f; Q->forward.s13 = pj_param(P->ctx, P->params, "ds13").f; Q->forward.s21 = pj_param(P->ctx, P->params, "ds21").f; if (pj_param(P->ctx, P->params, "ts22").i) { Q->forward.s22 = pj_param(P->ctx, P->params, "ds22").f; } Q->forward.s23 = pj_param(P->ctx, P->params, "ds23").f; Q->forward.s31 = pj_param(P->ctx, P->params, "ds31").f; Q->forward.s32 = pj_param(P->ctx, P->params, "ds32").f; if (pj_param(P->ctx, P->params, "ts33").i) { Q->forward.s33 = pj_param(P->ctx, P->params, "ds33").f; } if (pj_param(P->ctx, P->params, "ttscale").i) { Q->forward.tscale = pj_param(P->ctx, P->params, "dtscale").f; } computeReverseParameters(P); return P; } /* Arcsecond to radians */ #define ARCSEC_TO_RAD (DEG_TO_RAD / 3600.0) PJ *PJ_TRANSFORMATION(geogoffset, 0 /* no need for ellipsoid */) { struct pj_opaque_affine *Q = initQ(); 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_RADIANS; P->right = PJ_IO_UNITS_RADIANS; /* read args */ Q->xoff = pj_param(P->ctx, P->params, "ddlon").f * ARCSEC_TO_RAD; Q->yoff = pj_param(P->ctx, P->params, "ddlat").f * ARCSEC_TO_RAD; Q->zoff = pj_param(P->ctx, P->params, "ddh").f; return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/tinshift.cpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to triangulation transformation * 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. *****************************************************************************/ #define PROJ_COMPILATION #include "tinshift.hpp" #include "filemanager.hpp" #include "proj_internal.h" PROJ_HEAD(tinshift, "Triangulation based transformation"); using namespace TINSHIFT_NAMESPACE; namespace { struct tinshiftData { std::unique_ptr<Evaluator> evaluator{}; tinshiftData() = default; tinshiftData(const tinshiftData &) = delete; tinshiftData &operator=(const tinshiftData &) = delete; }; } // namespace static PJ *pj_tinshift_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; auto Q = static_cast<struct tinshiftData *>(P->opaque); delete Q; P->opaque = nullptr; return pj_default_destructor(P, errlev); } static void tinshift_forward_4d(PJ_COORD &coo, PJ *P) { auto *Q = (struct tinshiftData *)P->opaque; if (!Q->evaluator->forward(coo.xyz.x, coo.xyz.y, coo.xyz.z, coo.xyz.x, coo.xyz.y, coo.xyz.z)) { coo = proj_coord_error(); } } static void tinshift_reverse_4d(PJ_COORD &coo, PJ *P) { auto *Q = (struct tinshiftData *)P->opaque; if (!Q->evaluator->inverse(coo.xyz.x, coo.xyz.y, coo.xyz.z, coo.xyz.x, coo.xyz.y, coo.xyz.z)) { coo = proj_coord_error(); } } PJ *PJ_TRANSFORMATION(tinshift, 1) { const char *filename = pj_param(P->ctx, P->params, "sfile").s; if (!filename) { proj_log_error(P, _("+file= should be specified.")); return pj_tinshift_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } auto file = NS_PROJ::FileManager::open_resource_file(P->ctx, filename); if (nullptr == file) { proj_log_error(P, _("Cannot open %s"), filename); return pj_tinshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } file->seek(0, SEEK_END); unsigned long long size = file->tell(); // Arbitrary threshold to avoid ingesting an arbitrarily large JSON file, // that could be a denial of service risk. 100 MB should be sufficiently // large for any valid use ! if (size > 100 * 1024 * 1024) { proj_log_error(P, _("File %s too large"), filename); return pj_tinshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } file->seek(0); std::string jsonStr; try { jsonStr.resize(static_cast<size_t>(size)); } catch (const std::bad_alloc &) { proj_log_error(P, _("Cannot read %s. Not enough memory"), filename); return pj_tinshift_destructor(P, PROJ_ERR_OTHER); } if (file->read(&jsonStr[0], jsonStr.size()) != jsonStr.size()) { proj_log_error(P, _("Cannot read %s"), filename); return pj_tinshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } auto Q = new tinshiftData(); P->opaque = (void *)Q; P->destructor = pj_tinshift_destructor; try { Q->evaluator.reset(new Evaluator(TINShiftFile::parse(jsonStr))); } catch (const std::exception &e) { proj_log_error(P, _("invalid model: %s"), e.what()); return pj_tinshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } P->fwd4d = tinshift_forward_4d; P->inv4d = tinshift_reverse_4d; P->left = PJ_IO_UNITS_WHATEVER; P->right = PJ_IO_UNITS_WHATEVER; return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/tinshift_impl.hpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to TIN based transformations * 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. *****************************************************************************/ #ifndef TINSHIFT_NAMESPACE #error "Should be included only by tinshift.hpp" #endif #include <limits> namespace TINSHIFT_NAMESPACE { // --------------------------------------------------------------------------- static std::string getString(const json &j, const char *key, bool optional) { if (!j.contains(key)) { if (optional) { return std::string(); } throw ParsingException(std::string("Missing \"") + key + "\" key"); } const json v = j[key]; if (!v.is_string()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a string"); } return v.get<std::string>(); } static std::string getReqString(const json &j, const char *key) { return getString(j, key, false); } static std::string getOptString(const json &j, const char *key) { return getString(j, key, true); } // --------------------------------------------------------------------------- static json getArrayMember(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } const json obj = j[key]; if (!obj.is_array()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a array"); } return obj; } // --------------------------------------------------------------------------- std::unique_ptr<TINShiftFile> TINShiftFile::parse(const std::string &text) { std::unique_ptr<TINShiftFile> tinshiftFile(new TINShiftFile()); json j; try { j = json::parse(text); } catch (const std::exception &e) { throw ParsingException(e.what()); } if (!j.is_object()) { throw ParsingException("Not an object"); } tinshiftFile->mFileType = getReqString(j, "file_type"); tinshiftFile->mFormatVersion = getReqString(j, "format_version"); tinshiftFile->mName = getOptString(j, "name"); tinshiftFile->mVersion = getOptString(j, "version"); tinshiftFile->mLicense = getOptString(j, "license"); tinshiftFile->mDescription = getOptString(j, "description"); tinshiftFile->mPublicationDate = getOptString(j, "publication_date"); tinshiftFile->mFallbackStrategy = FALLBACK_NONE; if (j.contains("fallback_strategy")) { if (tinshiftFile->mFormatVersion != "1.1") { throw ParsingException( "fallback_strategy needs format_version 1.1"); } const auto fallback_strategy = getOptString(j, "fallback_strategy"); if (fallback_strategy == "nearest_side") { tinshiftFile->mFallbackStrategy = FALLBACK_NEAREST_SIDE; } else if (fallback_strategy == "nearest_centroid") { tinshiftFile->mFallbackStrategy = FALLBACK_NEAREST_CENTROID; } else if (fallback_strategy == "none") { tinshiftFile->mFallbackStrategy = FALLBACK_NONE; } else { throw ParsingException("invalid fallback_strategy"); } } if (j.contains("authority")) { const json jAuthority = j["authority"]; if (!jAuthority.is_object()) { throw ParsingException("authority is not a object"); } tinshiftFile->mAuthority.name = getOptString(jAuthority, "name"); tinshiftFile->mAuthority.url = getOptString(jAuthority, "url"); tinshiftFile->mAuthority.address = getOptString(jAuthority, "address"); tinshiftFile->mAuthority.email = getOptString(jAuthority, "email"); } if (j.contains("links")) { const json jLinks = j["links"]; if (!jLinks.is_array()) { throw ParsingException("links is not an array"); } for (const json &jLink : jLinks) { if (!jLink.is_object()) { throw ParsingException("links[] item is not an object"); } Link link; link.href = getOptString(jLink, "href"); link.rel = getOptString(jLink, "rel"); link.type = getOptString(jLink, "type"); link.title = getOptString(jLink, "title"); tinshiftFile->mLinks.emplace_back(std::move(link)); } } tinshiftFile->mInputCRS = getOptString(j, "input_crs"); tinshiftFile->mOutputCRS = getOptString(j, "output_crs"); const auto jTransformedComponents = getArrayMember(j, "transformed_components"); for (const json &jComp : jTransformedComponents) { if (!jComp.is_string()) { throw ParsingException( "transformed_components[] item is not a string"); } const auto jCompStr = jComp.get<std::string>(); if (jCompStr == "horizontal") { tinshiftFile->mTransformHorizontalComponent = true; } else if (jCompStr == "vertical") { tinshiftFile->mTransformVerticalComponent = true; } else { throw ParsingException("transformed_components[] = " + jCompStr + " is not handled"); } } const auto jVerticesColumns = getArrayMember(j, "vertices_columns"); int sourceXCol = -1; int sourceYCol = -1; int sourceZCol = -1; int targetXCol = -1; int targetYCol = -1; int targetZCol = -1; int offsetZCol = -1; for (size_t i = 0; i < jVerticesColumns.size(); ++i) { const json &jColumn = jVerticesColumns[i]; if (!jColumn.is_string()) { throw ParsingException("vertices_columns[] item is not a string"); } const auto jColumnStr = jColumn.get<std::string>(); if (jColumnStr == "source_x") { sourceXCol = static_cast<int>(i); } else if (jColumnStr == "source_y") { sourceYCol = static_cast<int>(i); } else if (jColumnStr == "source_z") { sourceZCol = static_cast<int>(i); } else if (jColumnStr == "target_x") { targetXCol = static_cast<int>(i); } else if (jColumnStr == "target_y") { targetYCol = static_cast<int>(i); } else if (jColumnStr == "target_z") { targetZCol = static_cast<int>(i); } else if (jColumnStr == "offset_z") { offsetZCol = static_cast<int>(i); } } if (sourceXCol < 0) { throw ParsingException( "source_x must be specified in vertices_columns[]"); } if (sourceYCol < 0) { throw ParsingException( "source_y must be specified in vertices_columns[]"); } if (tinshiftFile->mTransformHorizontalComponent) { if (targetXCol < 0) { throw ParsingException( "target_x must be specified in vertices_columns[]"); } if (targetYCol < 0) { throw ParsingException( "target_y must be specified in vertices_columns[]"); } } if (tinshiftFile->mTransformVerticalComponent) { if (offsetZCol >= 0) { // do nothing } else { if (sourceZCol < 0) { throw ParsingException("source_z or delta_z must be specified " "in vertices_columns[]"); } if (targetZCol < 0) { throw ParsingException( "target_z must be specified in vertices_columns[]"); } } } const auto jTrianglesColumns = getArrayMember(j, "triangles_columns"); int idxVertex1Col = -1; int idxVertex2Col = -1; int idxVertex3Col = -1; for (size_t i = 0; i < jTrianglesColumns.size(); ++i) { const json &jColumn = jTrianglesColumns[i]; if (!jColumn.is_string()) { throw ParsingException("triangles_columns[] item is not a string"); } const auto jColumnStr = jColumn.get<std::string>(); if (jColumnStr == "idx_vertex1") { idxVertex1Col = static_cast<int>(i); } else if (jColumnStr == "idx_vertex2") { idxVertex2Col = static_cast<int>(i); } else if (jColumnStr == "idx_vertex3") { idxVertex3Col = static_cast<int>(i); } } if (idxVertex1Col < 0) { throw ParsingException( "idx_vertex1 must be specified in triangles_columns[]"); } if (idxVertex2Col < 0) { throw ParsingException( "idx_vertex2 must be specified in triangles_columns[]"); } if (idxVertex3Col < 0) { throw ParsingException( "idx_vertex3 must be specified in triangles_columns[]"); } const auto jVertices = getArrayMember(j, "vertices"); tinshiftFile->mVerticesColumnCount = 2; if (tinshiftFile->mTransformHorizontalComponent) tinshiftFile->mVerticesColumnCount += 2; if (tinshiftFile->mTransformVerticalComponent) tinshiftFile->mVerticesColumnCount += 1; tinshiftFile->mVertices.reserve(tinshiftFile->mVerticesColumnCount * jVertices.size()); for (const auto &jVertex : jVertices) { if (!jVertex.is_array()) { throw ParsingException("vertices[] item is not an array"); } if (jVertex.size() != jVerticesColumns.size()) { throw ParsingException( "vertices[] item has not expected number of elements"); } if (!jVertex[sourceXCol].is_number()) { throw ParsingException("vertices[][] item is not a number"); } tinshiftFile->mVertices.push_back(jVertex[sourceXCol].get<double>()); if (!jVertex[sourceYCol].is_number()) { throw ParsingException("vertices[][] item is not a number"); } tinshiftFile->mVertices.push_back(jVertex[sourceYCol].get<double>()); if (tinshiftFile->mTransformHorizontalComponent) { if (!jVertex[targetXCol].is_number()) { throw ParsingException("vertices[][] item is not a number"); } tinshiftFile->mVertices.push_back( jVertex[targetXCol].get<double>()); if (!jVertex[targetYCol].is_number()) { throw ParsingException("vertices[][] item is not a number"); } tinshiftFile->mVertices.push_back( jVertex[targetYCol].get<double>()); } if (tinshiftFile->mTransformVerticalComponent) { if (offsetZCol >= 0) { if (!jVertex[offsetZCol].is_number()) { throw ParsingException("vertices[][] item is not a number"); } tinshiftFile->mVertices.push_back( jVertex[offsetZCol].get<double>()); } else { if (!jVertex[sourceZCol].is_number()) { throw ParsingException("vertices[][] item is not a number"); } const double sourceZ = jVertex[sourceZCol].get<double>(); if (!jVertex[targetZCol].is_number()) { throw ParsingException("vertices[][] item is not a number"); } const double targetZ = jVertex[targetZCol].get<double>(); tinshiftFile->mVertices.push_back(targetZ - sourceZ); } } } const auto jTriangles = getArrayMember(j, "triangles"); tinshiftFile->mTriangles.reserve(jTriangles.size()); for (const auto &jTriangle : jTriangles) { if (!jTriangle.is_array()) { throw ParsingException("triangles[] item is not an array"); } if (jTriangle.size() != jTrianglesColumns.size()) { throw ParsingException( "triangles[] item has not expected number of elements"); } if (jTriangle[idxVertex1Col].type() != json::value_t::number_unsigned) { throw ParsingException("triangles[][] item is not an integer"); } const unsigned vertex1 = jTriangle[idxVertex1Col].get<unsigned>(); if (vertex1 >= jVertices.size()) { throw ParsingException("Invalid value for a vertex index"); } if (jTriangle[idxVertex2Col].type() != json::value_t::number_unsigned) { throw ParsingException("triangles[][] item is not an integer"); } const unsigned vertex2 = jTriangle[idxVertex2Col].get<unsigned>(); if (vertex2 >= jVertices.size()) { throw ParsingException("Invalid value for a vertex index"); } if (jTriangle[idxVertex3Col].type() != json::value_t::number_unsigned) { throw ParsingException("triangles[][] item is not an integer"); } const unsigned vertex3 = jTriangle[idxVertex3Col].get<unsigned>(); if (vertex3 >= jVertices.size()) { throw ParsingException("Invalid value for a vertex index"); } VertexIndices vi; vi.idx1 = vertex1; vi.idx2 = vertex2; vi.idx3 = vertex3; tinshiftFile->mTriangles.push_back(vi); } return tinshiftFile; } // --------------------------------------------------------------------------- static NS_PROJ::QuadTree::RectObj GetBounds(const TINShiftFile &file, bool forward) { NS_PROJ::QuadTree::RectObj rect; rect.minx = std::numeric_limits<double>::max(); rect.miny = std::numeric_limits<double>::max(); rect.maxx = -std::numeric_limits<double>::max(); rect.maxy = -std::numeric_limits<double>::max(); const auto &vertices = file.vertices(); const unsigned colCount = file.verticesColumnCount(); const int idxX = file.transformHorizontalComponent() && !forward ? 2 : 0; const int idxY = file.transformHorizontalComponent() && !forward ? 3 : 1; for (size_t i = 0; i + colCount - 1 < vertices.size(); i += colCount) { const double x = vertices[i + idxX]; const double y = vertices[i + idxY]; rect.minx = std::min(rect.minx, x); rect.miny = std::min(rect.miny, y); rect.maxx = std::max(rect.maxx, x); rect.maxy = std::max(rect.maxy, y); } return rect; } // --------------------------------------------------------------------------- static std::unique_ptr<NS_PROJ::QuadTree::QuadTree<unsigned>> BuildQuadTree(const TINShiftFile &file, bool forward) { auto quadtree = std::unique_ptr<NS_PROJ::QuadTree::QuadTree<unsigned>>( new NS_PROJ::QuadTree::QuadTree<unsigned>(GetBounds(file, forward))); const auto &triangles = file.triangles(); const auto &vertices = file.vertices(); const int idxX = file.transformHorizontalComponent() && !forward ? 2 : 0; const int idxY = file.transformHorizontalComponent() && !forward ? 3 : 1; const unsigned colCount = file.verticesColumnCount(); for (size_t i = 0; i < triangles.size(); ++i) { const unsigned i1 = triangles[i].idx1; const unsigned i2 = triangles[i].idx2; const unsigned i3 = triangles[i].idx3; const double x1 = vertices[i1 * colCount + idxX]; const double y1 = vertices[i1 * colCount + idxY]; const double x2 = vertices[i2 * colCount + idxX]; const double y2 = vertices[i2 * colCount + idxY]; const double x3 = vertices[i3 * colCount + idxX]; const double y3 = vertices[i3 * colCount + idxY]; NS_PROJ::QuadTree::RectObj rect; rect.minx = x1; rect.miny = y1; rect.maxx = x1; rect.maxy = y1; rect.minx = std::min(rect.minx, x2); rect.miny = std::min(rect.miny, y2); rect.maxx = std::max(rect.maxx, x2); rect.maxy = std::max(rect.maxy, y2); rect.minx = std::min(rect.minx, x3); rect.miny = std::min(rect.miny, y3); rect.maxx = std::max(rect.maxx, x3); rect.maxy = std::max(rect.maxy, y3); quadtree->insert(static_cast<unsigned>(i), rect); } return quadtree; } // --------------------------------------------------------------------------- Evaluator::Evaluator(std::unique_ptr<TINShiftFile> &&fileIn) : mFile(std::move(fileIn)) {} // --------------------------------------------------------------------------- static inline double sqr(double x) { return x * x; } static inline double squared_distance(double x1, double y1, double x2, double y2) { return sqr(x1 - x2) + sqr(y1 - y2); } static double distance_point_segment(double x, double y, double x1, double y1, double x2, double y2, double dist12) { // squared distance of point x/y to line segment x1/y1 -- x2/y2 double t = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / dist12; if (t <= 0.0) { // closest to x1/y1 return squared_distance(x, y, x1, y1); } if (t >= 1.0) { // closest to y2/y2 return squared_distance(x, y, x2, y2); } // closest to line segment x1/y1 -- x2/y2 return squared_distance(x, y, x1 + t * (x2 - x1), y1 + t * (y2 - y1)); } static const TINShiftFile::VertexIndices * FindTriangle(const TINShiftFile &file, const NS_PROJ::QuadTree::QuadTree<unsigned> &quadtree, std::vector<unsigned> &triangleIndices, double x, double y, bool forward, double &lambda1, double &lambda2, double &lambda3) { #define USE_QUADTREE #ifdef USE_QUADTREE triangleIndices.clear(); quadtree.search(x, y, triangleIndices); #endif const auto &triangles = file.triangles(); const auto &vertices = file.vertices(); constexpr double EPS = 1e-10; const int idxX = file.transformHorizontalComponent() && !forward ? 2 : 0; const int idxY = file.transformHorizontalComponent() && !forward ? 3 : 1; const unsigned colCount = file.verticesColumnCount(); #ifdef USE_QUADTREE for (unsigned i : triangleIndices) #else for (size_t i = 0; i < triangles.size(); ++i) #endif { const auto &triangle = triangles[i]; const unsigned i1 = triangle.idx1; const unsigned i2 = triangle.idx2; const unsigned i3 = triangle.idx3; const double x1 = vertices[i1 * colCount + idxX]; const double y1 = vertices[i1 * colCount + idxY]; const double x2 = vertices[i2 * colCount + idxX]; const double y2 = vertices[i2 * colCount + idxY]; const double x3 = vertices[i3 * colCount + idxX]; const double y3 = vertices[i3 * colCount + idxY]; const double det_T = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3); lambda1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3)) / det_T; lambda2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3)) / det_T; if (lambda1 >= -EPS && lambda1 <= 1 + EPS && lambda2 >= -EPS && lambda2 <= 1 + EPS) { lambda3 = 1 - lambda1 - lambda2; if (lambda3 >= 0) { return &triangle; } } } if (file.fallbackStrategy() == FALLBACK_NONE) { return nullptr; } // find triangle with the shortest squared distance // // TODO: extend quadtree to support nearest neighbor search double closest_dist = std::numeric_limits<double>::infinity(); double closest_dist2 = std::numeric_limits<double>::infinity(); size_t closest_i = 0; for (size_t i = 0; i < triangles.size(); ++i) { const auto &triangle = triangles[i]; const unsigned i1 = triangle.idx1; const unsigned i2 = triangle.idx2; const unsigned i3 = triangle.idx3; const double x1 = vertices[i1 * colCount + idxX]; const double y1 = vertices[i1 * colCount + idxY]; const double x2 = vertices[i2 * colCount + idxX]; const double y2 = vertices[i2 * colCount + idxY]; const double x3 = vertices[i3 * colCount + idxX]; const double y3 = vertices[i3 * colCount + idxY]; // don't check this triangle if the query point plusminus the // currently closest found distance is outside the triangle's AABB if (x + closest_dist < std::min(x1, std::min(x2, x3)) || x - closest_dist > std::max(x1, std::max(x2, x3)) || y + closest_dist < std::min(y1, std::min(y2, y3)) || y - closest_dist > std::max(y1, std::max(y2, y3))) { continue; } double dist12 = squared_distance(x1, y1, x2, y2); double dist23 = squared_distance(x2, y2, x3, y3); double dist13 = squared_distance(x1, y1, x3, y3); if (dist12 < EPS || dist23 < EPS || dist13 < EPS) { // do not use degenerate triangles continue; } double dist2; if (file.fallbackStrategy() == FALLBACK_NEAREST_SIDE) { // we don't know whether the points of the triangle are given // clockwise or counter-clockwise, so we have to check the distance // of the point to all three sides of the triangle dist2 = distance_point_segment(x, y, x1, y1, x2, y2, dist12); if (dist2 < closest_dist2) { closest_dist2 = dist2; closest_dist = sqrt(dist2); closest_i = i; } dist2 = distance_point_segment(x, y, x2, y2, x3, y3, dist23); if (dist2 < closest_dist2) { closest_dist2 = dist2; closest_dist = sqrt(dist2); closest_i = i; } dist2 = distance_point_segment(x, y, x1, y1, x3, y3, dist13); if (dist2 < closest_dist2) { closest_dist2 = dist2; closest_dist = sqrt(dist2); closest_i = i; } } else if (file.fallbackStrategy() == FALLBACK_NEAREST_CENTROID) { double c_x = (x1 + x2 + x3) / 3.0; double c_y = (y1 + y2 + y3) / 3.0; dist2 = squared_distance(x, y, c_x, c_y); if (dist2 < closest_dist2) { closest_dist2 = dist2; closest_dist = sqrt(dist2); closest_i = i; } } } if (std::isinf(closest_dist)) { // nothing was found due to empty triangle list or only degenerate // triangles return nullptr; } const auto &triangle = triangles[closest_i]; const unsigned i1 = triangle.idx1; const unsigned i2 = triangle.idx2; const unsigned i3 = triangle.idx3; const double x1 = vertices[i1 * colCount + idxX]; const double y1 = vertices[i1 * colCount + idxY]; const double x2 = vertices[i2 * colCount + idxX]; const double y2 = vertices[i2 * colCount + idxY]; const double x3 = vertices[i3 * colCount + idxX]; const double y3 = vertices[i3 * colCount + idxY]; const double det_T = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3); if (std::fabs(det_T) < EPS) { // the nearest triangle is degenerate return nullptr; } lambda1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3)) / det_T; lambda2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3)) / det_T; lambda3 = 1 - lambda1 - lambda2; return &triangle; } // --------------------------------------------------------------------------- bool Evaluator::forward(double x, double y, double z, double &x_out, double &y_out, double &z_out) { if (!mQuadTreeForward) mQuadTreeForward = BuildQuadTree(*(mFile.get()), true); double lambda1 = 0.0; double lambda2 = 0.0; double lambda3 = 0.0; const auto *triangle = FindTriangle(*mFile, *mQuadTreeForward, mTriangleIndices, x, y, true, lambda1, lambda2, lambda3); if (!triangle) return false; const auto &vertices = mFile->vertices(); const unsigned i1 = triangle->idx1; const unsigned i2 = triangle->idx2; const unsigned i3 = triangle->idx3; const unsigned colCount = mFile->verticesColumnCount(); if (mFile->transformHorizontalComponent()) { constexpr unsigned idxTargetColX = 2; constexpr unsigned idxTargetColY = 3; x_out = vertices[i1 * colCount + idxTargetColX] * lambda1 + vertices[i2 * colCount + idxTargetColX] * lambda2 + vertices[i3 * colCount + idxTargetColX] * lambda3; y_out = vertices[i1 * colCount + idxTargetColY] * lambda1 + vertices[i2 * colCount + idxTargetColY] * lambda2 + vertices[i3 * colCount + idxTargetColY] * lambda3; } else { x_out = x; y_out = y; } if (mFile->transformVerticalComponent()) { const int idxCol = mFile->transformHorizontalComponent() ? 4 : 2; z_out = z + (vertices[i1 * colCount + idxCol] * lambda1 + vertices[i2 * colCount + idxCol] * lambda2 + vertices[i3 * colCount + idxCol] * lambda3); } else { z_out = z; } return true; } // --------------------------------------------------------------------------- bool Evaluator::inverse(double x, double y, double z, double &x_out, double &y_out, double &z_out) { NS_PROJ::QuadTree::QuadTree<unsigned> *quadtree; if (!mFile->transformHorizontalComponent() && mFile->transformVerticalComponent()) { if (!mQuadTreeForward) mQuadTreeForward = BuildQuadTree(*(mFile.get()), true); quadtree = mQuadTreeForward.get(); } else { if (!mQuadTreeInverse) mQuadTreeInverse = BuildQuadTree(*(mFile.get()), false); quadtree = mQuadTreeInverse.get(); } double lambda1 = 0.0; double lambda2 = 0.0; double lambda3 = 0.0; const auto *triangle = FindTriangle(*mFile, *quadtree, mTriangleIndices, x, y, false, lambda1, lambda2, lambda3); if (!triangle) return false; const auto &vertices = mFile->vertices(); const unsigned i1 = triangle->idx1; const unsigned i2 = triangle->idx2; const unsigned i3 = triangle->idx3; const unsigned colCount = mFile->verticesColumnCount(); if (mFile->transformHorizontalComponent()) { constexpr unsigned idxTargetColX = 0; constexpr unsigned idxTargetColY = 1; x_out = vertices[i1 * colCount + idxTargetColX] * lambda1 + vertices[i2 * colCount + idxTargetColX] * lambda2 + vertices[i3 * colCount + idxTargetColX] * lambda3; y_out = vertices[i1 * colCount + idxTargetColY] * lambda1 + vertices[i2 * colCount + idxTargetColY] * lambda2 + vertices[i3 * colCount + idxTargetColY] * lambda3; } else { x_out = x; y_out = y; } if (mFile->transformVerticalComponent()) { const int idxCol = mFile->transformHorizontalComponent() ? 4 : 2; z_out = z - (vertices[i1 * colCount + idxCol] * lambda1 + vertices[i2 * colCount + idxCol] * lambda2 + vertices[i3 * colCount + idxCol] * lambda3); } else { z_out = z; } return true; } } // namespace TINSHIFT_NAMESPACE
hpp
PROJ
data/projects/PROJ/src/transformations/defmodel_impl.hpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to deformation model * 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. *****************************************************************************/ #ifndef DEFORMATON_MODEL_NAMESPACE #error "Should be included only by defmodel.hpp" #endif namespace DEFORMATON_MODEL_NAMESPACE { // --------------------------------------------------------------------------- static const std::string STR_DEGREE("degree"); static const std::string STR_METRE("metre"); static const std::string STR_ADDITION("addition"); static const std::string STR_GEOCENTRIC("geocentric"); static const std::string STR_BILINEAR("bilinear"); static const std::string STR_GEOCENTRIC_BILINEAR("geocentric_bilinear"); static const std::string STR_NONE("none"); static const std::string STR_HORIZONTAL("horizontal"); static const std::string STR_VERTICAL("vertical"); static const std::string STR_3D("3d"); constexpr double DEFMODEL_PI = 3.14159265358979323846; constexpr double DEG_TO_RAD_CONSTANT = 3.14159265358979323846 / 180.; inline constexpr double DegToRad(double d) { return d * DEG_TO_RAD_CONSTANT; } // --------------------------------------------------------------------------- enum class DisplacementType { NONE, HORIZONTAL, VERTICAL, THREE_D }; // --------------------------------------------------------------------------- /** Internal class to offer caching services over a Grid */ template <class Grid> struct GridEx { const Grid *grid; bool smallResx; // lesser than one degree double sinhalfresx; double coshalfresx; double sinresy; double cosresy; int last_ix0 = -1; int last_iy0 = -1; double dX00 = 0; double dY00 = 0; double dZ00 = 0; double dX01 = 0; double dY01 = 0; double dZ01 = 0; double dX10 = 0; double dY10 = 0; double dZ10 = 0; double dX11 = 0; double dY11 = 0; double dZ11 = 0; double sinphi0 = 0; double cosphi0 = 0; double sinphi1 = 0; double cosphi1 = 0; explicit GridEx(const Grid *gridIn) : grid(gridIn), smallResx(grid->resx < DegToRad(1)), sinhalfresx(sin(grid->resx / 2)), coshalfresx(cos(grid->resx / 2)), sinresy(sin(grid->resy)), cosresy(cos(grid->resy)) {} // Return geocentric offset (dX, dY, dZ) relative to a point // where x0 = -resx / 2 inline void getBilinearGeocentric(int ix0, int iy0, double de00, double dn00, double de01, double dn01, double de10, double dn10, double de11, double dn11, double m00, double m01, double m10, double m11, double &dX, double &dY, double &dZ) { // If interpolating in the same cell as before, then we can skip // the recomputation of dXij, dYij and dZij if (ix0 != last_ix0 || iy0 != last_iy0) { last_ix0 = ix0; if (iy0 != last_iy0) { const double y0 = grid->miny + iy0 * grid->resy; sinphi0 = sin(y0); cosphi0 = cos(y0); // Use trigonometric formulas to avoid new calls to sin/cos sinphi1 = /* sin(y0+grid->resyRad) = */ sinphi0 * cosresy + cosphi0 * sinresy; cosphi1 = /* cos(y0+grid->resyRad) = */ cosphi0 * cosresy - sinphi0 * sinresy; last_iy0 = iy0; } // Using "traditional" formulas to convert from easting, northing // offsets to geocentric offsets const double sinlam00 = -sinhalfresx; const double coslam00 = coshalfresx; const double sinphi00 = sinphi0; const double cosphi00 = cosphi0; const double dn00sinphi00 = dn00 * sinphi00; dX00 = -de00 * sinlam00 - dn00sinphi00 * coslam00; dY00 = de00 * coslam00 - dn00sinphi00 * sinlam00; dZ00 = dn00 * cosphi00; const double sinlam01 = -sinhalfresx; const double coslam01 = coshalfresx; const double sinphi01 = sinphi1; const double cosphi01 = cosphi1; const double dn01sinphi01 = dn01 * sinphi01; dX01 = -de01 * sinlam01 - dn01sinphi01 * coslam01; dY01 = de01 * coslam01 - dn01sinphi01 * sinlam01; dZ01 = dn01 * cosphi01; const double sinlam10 = sinhalfresx; const double coslam10 = coshalfresx; const double sinphi10 = sinphi0; const double cosphi10 = cosphi0; const double dn10sinphi10 = dn10 * sinphi10; dX10 = -de10 * sinlam10 - dn10sinphi10 * coslam10; dY10 = de10 * coslam10 - dn10sinphi10 * sinlam10; dZ10 = dn10 * cosphi10; const double sinlam11 = sinhalfresx; const double coslam11 = coshalfresx; const double sinphi11 = sinphi1; const double cosphi11 = cosphi1; const double dn11sinphi11 = dn11 * sinphi11; dX11 = -de11 * sinlam11 - dn11sinphi11 * coslam11; dY11 = de11 * coslam11 - dn11sinphi11 * sinlam11; dZ11 = dn11 * cosphi11; } dX = m00 * dX00 + m01 * dX01 + m10 * dX10 + m11 * dX11; dY = m00 * dY00 + m01 * dY01 + m10 * dY10 + m11 * dY11; dZ = m00 * dZ00 + m01 * dZ01 + m10 * dZ10 + m11 * dZ11; } }; // --------------------------------------------------------------------------- /** Internal class to offer caching services over a Component */ template <class Grid, class GridSet> struct ComponentEx { const Component &component; const bool isBilinearInterpolation; /* bilinear vs geocentric_bilinear */ const DisplacementType displacementType; // Cache std::unique_ptr<GridSet> gridSet{}; std::map<const Grid *, GridEx<Grid>> mapGrids{}; private: mutable double mCachedDt = 0; mutable double mCachedValue = 0; static DisplacementType getDisplacementType(const std::string &s) { if (s == STR_HORIZONTAL) return DisplacementType::HORIZONTAL; if (s == STR_VERTICAL) return DisplacementType::VERTICAL; if (s == STR_3D) return DisplacementType::THREE_D; return DisplacementType::NONE; } public: explicit ComponentEx(const Component &componentIn) : component(componentIn), isBilinearInterpolation( componentIn.spatialModel().interpolationMethod == STR_BILINEAR), displacementType(getDisplacementType(component.displacementType())) {} double evaluateAt(double dt) const { if (dt == mCachedDt) return mCachedValue; mCachedDt = dt; mCachedValue = component.timeFunction()->evaluateAt(dt); return mCachedValue; } void clearGridCache() { gridSet.reset(); mapGrids.clear(); } }; // --------------------------------------------------------------------------- /** Converts a ISO8601 date-time string, formatted as "YYYY-MM-DDTHH:MM:SSZ", * into a decimal year. * Leap years are taken into account, but not leap seconds. */ static double ISO8601ToDecimalYear(const std::string &dt) { int year, month, day, hour, min, sec; if (sscanf(dt.c_str(), "%04d-%02d-%02dT%02d:%02d:%02dZ", &year, &month, &day, &hour, &min, &sec) != 6 || year < 1582 || // Start of Gregorian calendar month < 1 || month > 12 || day < 1 || day > 31 || hour < 0 || hour >= 24 || min < 0 || min >= 60 || sec < 0 || sec >= 61) { throw ParsingException("Wrong formatting / invalid date-time for " + dt); } const bool isLeapYear = (((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0); // Given the intended use, we omit leap seconds... const int month_table[2][12] = { {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; int dayInYear = day - 1; for (int m = 1; m < month; m++) { dayInYear += month_table[isLeapYear ? 1 : 0][m - 1]; } if (day > month_table[isLeapYear ? 1 : 0][month - 1]) { throw ParsingException("Wrong formatting / invalid date-time for " + dt); } return year + (dayInYear * 86400 + hour * 3600 + min * 60 + sec) / (isLeapYear ? 86400. * 366 : 86400. * 365); } // --------------------------------------------------------------------------- Epoch::Epoch(const std::string &dt) : mDt(dt) { if (!dt.empty()) { mDecimalYear = ISO8601ToDecimalYear(dt); } } // --------------------------------------------------------------------------- double Epoch::toDecimalYear() const { return mDecimalYear; } // --------------------------------------------------------------------------- static std::string getString(const json &j, const char *key, bool optional) { if (!j.contains(key)) { if (optional) { return std::string(); } throw ParsingException(std::string("Missing \"") + key + "\" key"); } const json v = j[key]; if (!v.is_string()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a string"); } return v.get<std::string>(); } static std::string getReqString(const json &j, const char *key) { return getString(j, key, false); } static std::string getOptString(const json &j, const char *key) { return getString(j, key, true); } // --------------------------------------------------------------------------- static double getDouble(const json &j, const char *key, bool optional) { if (!j.contains(key)) { if (optional) { return std::numeric_limits<double>::quiet_NaN(); } throw ParsingException(std::string("Missing \"") + key + "\" key"); } const json v = j[key]; if (!v.is_number()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a number"); } return v.get<double>(); } static double getReqDouble(const json &j, const char *key) { return getDouble(j, key, false); } static double getOptDouble(const json &j, const char *key) { return getDouble(j, key, true); } // --------------------------------------------------------------------------- static json getObjectMember(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } const json obj = j[key]; if (!obj.is_object()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a object"); } return obj; } // --------------------------------------------------------------------------- static json getArrayMember(const json &j, const char *key) { if (!j.contains(key)) { throw ParsingException(std::string("Missing \"") + key + "\" key"); } const json obj = j[key]; if (!obj.is_array()) { throw ParsingException(std::string("The value of \"") + key + "\" should be a array"); } return obj; } // --------------------------------------------------------------------------- std::unique_ptr<MasterFile> MasterFile::parse(const std::string &text) { std::unique_ptr<MasterFile> dmmf(new MasterFile()); json j; try { j = json::parse(text); } catch (const std::exception &e) { throw ParsingException(e.what()); } if (!j.is_object()) { throw ParsingException("Not an object"); } dmmf->mFileType = getReqString(j, "file_type"); dmmf->mFormatVersion = getReqString(j, "format_version"); dmmf->mName = getOptString(j, "name"); dmmf->mVersion = getOptString(j, "version"); dmmf->mLicense = getOptString(j, "license"); dmmf->mDescription = getOptString(j, "description"); dmmf->mPublicationDate = getOptString(j, "publication_date"); if (j.contains("authority")) { const json jAuthority = j["authority"]; if (!jAuthority.is_object()) { throw ParsingException("authority is not a object"); } dmmf->mAuthority.name = getOptString(jAuthority, "name"); dmmf->mAuthority.url = getOptString(jAuthority, "url"); dmmf->mAuthority.address = getOptString(jAuthority, "address"); dmmf->mAuthority.email = getOptString(jAuthority, "email"); } if (j.contains("links")) { const json jLinks = j["links"]; if (!jLinks.is_array()) { throw ParsingException("links is not an array"); } for (const json &jLink : jLinks) { if (!jLink.is_object()) { throw ParsingException("links[] item is not an object"); } Link link; link.href = getOptString(jLink, "href"); link.rel = getOptString(jLink, "rel"); link.type = getOptString(jLink, "type"); link.title = getOptString(jLink, "title"); dmmf->mLinks.emplace_back(std::move(link)); } } dmmf->mSourceCRS = getReqString(j, "source_crs"); dmmf->mTargetCRS = getReqString(j, "target_crs"); dmmf->mDefinitionCRS = getReqString(j, "definition_crs"); if (dmmf->mSourceCRS != dmmf->mDefinitionCRS) { throw ParsingException( "source_crs != definition_crs not currently supported"); } dmmf->mReferenceEpoch = getOptString(j, "reference_epoch"); dmmf->mUncertaintyReferenceEpoch = getOptString(j, "uncertainty_reference_epoch"); dmmf->mHorizontalOffsetUnit = getOptString(j, "horizontal_offset_unit"); if (!dmmf->mHorizontalOffsetUnit.empty() && dmmf->mHorizontalOffsetUnit != STR_METRE && dmmf->mHorizontalOffsetUnit != STR_DEGREE) { throw ParsingException("Unsupported value for horizontal_offset_unit"); } dmmf->mVerticalOffsetUnit = getOptString(j, "vertical_offset_unit"); if (!dmmf->mVerticalOffsetUnit.empty() && dmmf->mVerticalOffsetUnit != STR_METRE) { throw ParsingException("Unsupported value for vertical_offset_unit"); } dmmf->mHorizontalUncertaintyType = getOptString(j, "horizontal_uncertainty_type"); dmmf->mHorizontalUncertaintyUnit = getOptString(j, "horizontal_uncertainty_unit"); dmmf->mVerticalUncertaintyType = getOptString(j, "vertical_uncertainty_type"); dmmf->mVerticalUncertaintyUnit = getOptString(j, "vertical_uncertainty_unit"); dmmf->mHorizontalOffsetMethod = getOptString(j, "horizontal_offset_method"); if (!dmmf->mHorizontalOffsetMethod.empty() && dmmf->mHorizontalOffsetMethod != STR_ADDITION && dmmf->mHorizontalOffsetMethod != STR_GEOCENTRIC) { throw ParsingException( "Unsupported value for horizontal_offset_method"); } dmmf->mSpatialExtent = SpatialExtent::parse(getObjectMember(j, "extent")); const json jTimeExtent = getObjectMember(j, "time_extent"); dmmf->mTimeExtent.first = Epoch(getReqString(jTimeExtent, "first")); dmmf->mTimeExtent.last = Epoch(getReqString(jTimeExtent, "last")); const json jComponents = getArrayMember(j, "components"); for (const json &jComponent : jComponents) { dmmf->mComponents.emplace_back(Component::parse(jComponent)); const auto &comp = dmmf->mComponents.back(); if (comp.displacementType() == STR_HORIZONTAL || comp.displacementType() == STR_3D) { if (dmmf->mHorizontalOffsetUnit.empty()) { throw ParsingException("horizontal_offset_unit should be " "defined as there is a component with " "displacement_type = horizontal/3d"); } if (dmmf->mHorizontalOffsetMethod.empty()) { throw ParsingException("horizontal_offset_method should be " "defined as there is a component with " "displacement_type = horizontal/3d"); } } if (comp.displacementType() == STR_VERTICAL || comp.displacementType() == STR_3D) { if (dmmf->mVerticalOffsetUnit.empty()) { throw ParsingException("vertical_offset_unit should be defined " "as there is a component with " "displacement_type = vertical/3d"); } } if (dmmf->mHorizontalOffsetUnit == STR_DEGREE && comp.spatialModel().interpolationMethod != STR_BILINEAR) { throw ParsingException("horizontal_offset_unit = degree can only " "be used with interpolation_method = " "bilinear"); } } if (dmmf->mHorizontalOffsetUnit == STR_DEGREE && dmmf->mHorizontalOffsetMethod != STR_ADDITION) { throw ParsingException("horizontal_offset_unit = degree can only be " "used with horizontal_offset_method = addition"); } return dmmf; } // --------------------------------------------------------------------------- SpatialExtent SpatialExtent::parse(const json &j) { SpatialExtent ex; const std::string type = getReqString(j, "type"); if (type != "bbox") { throw ParsingException("unsupported type of extent"); } const json jParameter = getObjectMember(j, "parameters"); const json jBbox = getArrayMember(jParameter, "bbox"); if (jBbox.size() != 4) { throw ParsingException("bbox is not an array of 4 numeric elements"); } for (int i = 0; i < 4; i++) { if (!jBbox[i].is_number()) { throw ParsingException( "bbox is not an array of 4 numeric elements"); } } ex.mMinx = jBbox[0].get<double>(); ex.mMiny = jBbox[1].get<double>(); ex.mMaxx = jBbox[2].get<double>(); ex.mMaxy = jBbox[3].get<double>(); ex.mMinxRad = DegToRad(ex.mMinx); ex.mMinyRad = DegToRad(ex.mMiny); ex.mMaxxRad = DegToRad(ex.mMaxx); ex.mMaxyRad = DegToRad(ex.mMaxy); return ex; } // --------------------------------------------------------------------------- Component Component::parse(const json &j) { Component comp; if (!j.is_object()) { throw ParsingException("component is not an object"); } comp.mDescription = getOptString(j, "description"); comp.mSpatialExtent = SpatialExtent::parse(getObjectMember(j, "extent")); comp.mDisplacementType = getReqString(j, "displacement_type"); if (comp.mDisplacementType != STR_NONE && comp.mDisplacementType != STR_HORIZONTAL && comp.mDisplacementType != STR_VERTICAL && comp.mDisplacementType != STR_3D) { throw ParsingException("Unsupported value for displacement_type"); } comp.mUncertaintyType = getReqString(j, "uncertainty_type"); comp.mHorizontalUncertainty = getOptDouble(j, "horizontal_uncertainty"); comp.mVerticalUncertainty = getOptDouble(j, "vertical_uncertainty"); const json jSpatialModel = getObjectMember(j, "spatial_model"); comp.mSpatialModel.type = getReqString(jSpatialModel, "type"); comp.mSpatialModel.interpolationMethod = getReqString(jSpatialModel, "interpolation_method"); if (comp.mSpatialModel.interpolationMethod != STR_BILINEAR && comp.mSpatialModel.interpolationMethod != STR_GEOCENTRIC_BILINEAR) { throw ParsingException("Unsupported value for interpolation_method"); } comp.mSpatialModel.filename = getReqString(jSpatialModel, "filename"); comp.mSpatialModel.md5Checksum = getOptString(jSpatialModel, "md5_checksum"); const json jTimeFunction = getObjectMember(j, "time_function"); const std::string timeFunctionType = getReqString(jTimeFunction, "type"); const json jParameters = timeFunctionType == "constant" ? json() : getObjectMember(jTimeFunction, "parameters"); if (timeFunctionType == "constant") { std::unique_ptr<ConstantTimeFunction> tf(new ConstantTimeFunction()); tf->type = timeFunctionType; comp.mTimeFunction = std::move(tf); } else if (timeFunctionType == "velocity") { std::unique_ptr<VelocityTimeFunction> tf(new VelocityTimeFunction()); tf->type = timeFunctionType; tf->referenceEpoch = Epoch(getReqString(jParameters, "reference_epoch")); comp.mTimeFunction = std::move(tf); } else if (timeFunctionType == "step") { std::unique_ptr<StepTimeFunction> tf(new StepTimeFunction()); tf->type = timeFunctionType; tf->stepEpoch = Epoch(getReqString(jParameters, "step_epoch")); comp.mTimeFunction = std::move(tf); } else if (timeFunctionType == "reverse_step") { std::unique_ptr<ReverseStepTimeFunction> tf( new ReverseStepTimeFunction()); tf->type = timeFunctionType; tf->stepEpoch = Epoch(getReqString(jParameters, "step_epoch")); comp.mTimeFunction = std::move(tf); } else if (timeFunctionType == "piecewise") { std::unique_ptr<PiecewiseTimeFunction> tf(new PiecewiseTimeFunction()); tf->type = timeFunctionType; tf->beforeFirst = getReqString(jParameters, "before_first"); if (tf->beforeFirst != "zero" && tf->beforeFirst != "constant" && tf->beforeFirst != "linear") { throw ParsingException("Unsupported value for before_first"); } tf->afterLast = getReqString(jParameters, "after_last"); if (tf->afterLast != "zero" && tf->afterLast != "constant" && tf->afterLast != "linear") { throw ParsingException("Unsupported value for afterLast"); } const json jModel = getArrayMember(jParameters, "model"); for (const json &jModelElt : jModel) { if (!jModelElt.is_object()) { throw ParsingException("model[] element is not an object"); } PiecewiseTimeFunction::EpochScaleFactorTuple tuple; tuple.epoch = Epoch(getReqString(jModelElt, "epoch")); tuple.scaleFactor = getReqDouble(jModelElt, "scale_factor"); tf->model.emplace_back(std::move(tuple)); } comp.mTimeFunction = std::move(tf); } else if (timeFunctionType == "exponential") { std::unique_ptr<ExponentialTimeFunction> tf( new ExponentialTimeFunction()); tf->type = timeFunctionType; tf->referenceEpoch = Epoch(getReqString(jParameters, "reference_epoch")); tf->endEpoch = Epoch(getOptString(jParameters, "end_epoch")); tf->relaxationConstant = getReqDouble(jParameters, "relaxation_constant"); if (tf->relaxationConstant <= 0.0) { throw ParsingException("Invalid value for relaxation_constant"); } tf->beforeScaleFactor = getReqDouble(jParameters, "before_scale_factor"); tf->initialScaleFactor = getReqDouble(jParameters, "initial_scale_factor"); tf->finalScaleFactor = getReqDouble(jParameters, "final_scale_factor"); comp.mTimeFunction = std::move(tf); } else { throw ParsingException("Unsupported type of time function: " + timeFunctionType); } return comp; } // --------------------------------------------------------------------------- double Component::ConstantTimeFunction::evaluateAt(double) const { return 1.0; } // --------------------------------------------------------------------------- double Component::VelocityTimeFunction::evaluateAt(double dt) const { return dt - referenceEpoch.toDecimalYear(); } // --------------------------------------------------------------------------- double Component::StepTimeFunction::evaluateAt(double dt) const { if (dt < stepEpoch.toDecimalYear()) return 0.0; return 1.0; } // --------------------------------------------------------------------------- double Component::ReverseStepTimeFunction::evaluateAt(double dt) const { if (dt < stepEpoch.toDecimalYear()) return -1.0; return 0.0; } // --------------------------------------------------------------------------- double Component::PiecewiseTimeFunction::evaluateAt(double dt) const { if (model.empty()) { return 0.0; } const double dt1 = model[0].epoch.toDecimalYear(); if (dt < dt1) { if (beforeFirst == "zero") return 0.0; if (beforeFirst == "constant" || model.size() == 1) return model[0].scaleFactor; // linear const double f1 = model[0].scaleFactor; const double dt2 = model[1].epoch.toDecimalYear(); const double f2 = model[1].scaleFactor; if (dt1 == dt2) return f1; return (f1 * (dt2 - dt) + f2 * (dt - dt1)) / (dt2 - dt1); } for (size_t i = 1; i < model.size(); i++) { const double dtip1 = model[i].epoch.toDecimalYear(); if (dt < dtip1) { const double dti = model[i - 1].epoch.toDecimalYear(); const double fip1 = model[i].scaleFactor; const double fi = model[i - 1].scaleFactor; return (fi * (dtip1 - dt) + fip1 * (dt - dti)) / (dtip1 - dti); } } if (afterLast == "zero") { return 0.0; } if (afterLast == "constant" || model.size() == 1) return model.back().scaleFactor; // linear const double dtnm1 = model[model.size() - 2].epoch.toDecimalYear(); const double fnm1 = model[model.size() - 2].scaleFactor; const double dtn = model.back().epoch.toDecimalYear(); const double fn = model.back().scaleFactor; if (dtnm1 == dtn) return fn; return (fnm1 * (dtn - dt) + fn * (dt - dtnm1)) / (dtn - dtnm1); } // --------------------------------------------------------------------------- double Component::ExponentialTimeFunction::evaluateAt(double dt) const { const double t0 = referenceEpoch.toDecimalYear(); if (dt < t0) return beforeScaleFactor; if (!endEpoch.toString().empty()) { dt = std::min(dt, endEpoch.toDecimalYear()); } return initialScaleFactor + (finalScaleFactor - initialScaleFactor) * (1.0 - std::exp(-(dt - t0) / relaxationConstant)); } // --------------------------------------------------------------------------- inline void DeltaEastingNorthingToLongLat(double cosphi, double de, double dn, double a, double b, double es, double &dlam, double &dphi) { const double oneMinuX = es * (1 - cosphi * cosphi); const double X = 1 - oneMinuX; const double sqrtX = sqrt(X); #if 0 // With es of Earth, absolute/relative error is at most 2e-8 // const double sqrtX = 1 - 0.5 * oneMinuX * (1 + 0.25 * oneMinuX); #endif dlam = de * sqrtX / (a * cosphi); dphi = dn * a * sqrtX * X / (b * b); } // --------------------------------------------------------------------------- template <class Grid, class GridSet, class EvaluatorIface> Evaluator<Grid, GridSet, EvaluatorIface>::Evaluator( std::unique_ptr<MasterFile> &&model, EvaluatorIface &iface, double a, double b) : mModel(std::move(model)), mA(a), mB(b), mEs(1 - (b * b) / (a * a)), mIsHorizontalUnitDegree(mModel->horizontalOffsetUnit() == STR_DEGREE), mIsAddition(mModel->horizontalOffsetMethod() == STR_ADDITION), mIsGeographicCRS(iface.isGeographicCRS(mModel->definitionCRS())) { if (!mIsGeographicCRS && mIsHorizontalUnitDegree) { throw EvaluatorException( "definition_crs = projected CRS and " "horizontal_offset_unit = degree are incompatible"); } if (!mIsGeographicCRS && !mIsAddition) { throw EvaluatorException( "definition_crs = projected CRS and " "horizontal_offset_method = geocentric are incompatible"); } mComponents.reserve(mModel->components().size()); for (const auto &comp : mModel->components()) { mComponents.emplace_back(std::unique_ptr<ComponentEx<Grid, GridSet>>( new ComponentEx<Grid, GridSet>(comp))); if (!mIsGeographicCRS && !mComponents.back()->isBilinearInterpolation) { throw EvaluatorException( "definition_crs = projected CRS and " "interpolation_method = geocentric_bilinear are incompatible"); } } } // --------------------------------------------------------------------------- template <class Grid, class GridSet, class EvaluatorIface> void Evaluator<Grid, GridSet, EvaluatorIface>::clearGridCache() { for (auto &comp : mComponents) { comp->clearGridCache(); } } // --------------------------------------------------------------------------- #ifdef DEBUG_DEFMODEL static std::string shortName(const Component &comp) { const auto &desc = comp.description(); return desc.substr(0, desc.find('\n')) + " (" + comp.spatialModel().filename + ")"; } static std::string toString(double val) { char buffer[32]; snprintf(buffer, sizeof(buffer), "%.9g", val); return buffer; } #endif // --------------------------------------------------------------------------- static bool bboxCheck(double &x, double &y, bool forInverseComputation, const double minx, const double miny, const double maxx, const double maxy, const double EPS, const double extraMarginForInverse) { if (x < minx - EPS || x > maxx + EPS || y < miny - EPS || y > maxy + EPS) { if (!forInverseComputation) { return false; } // In case of iterative computation for inverse, allow to be a // slightly bit outside of the grid and clamp to the edges bool xOk = false; if (x >= minx - EPS && x <= maxx + EPS) { xOk = true; } else if (x > minx - extraMarginForInverse && x < minx) { x = minx; xOk = true; } else if (x < maxx + extraMarginForInverse && x > maxx) { x = maxx; xOk = true; } bool yOk = false; if (y >= miny - EPS && y <= maxy + EPS) { yOk = true; } else if (y > miny - extraMarginForInverse && y < miny) { y = miny; yOk = true; } else if (y < maxy + extraMarginForInverse && y > maxy) { y = maxy; yOk = true; } return xOk && yOk; } return true; } // --------------------------------------------------------------------------- template <class Grid, class GridSet, class EvaluatorIface> bool Evaluator<Grid, GridSet, EvaluatorIface>::forward( EvaluatorIface &iface, double x, double y, double z, double t, bool forInverseComputation, double &x_out, double &y_out, double &z_out) { x_out = x; y_out = y; z_out = z; const double EPS = mIsGeographicCRS ? 1e-10 : 1e-5; // Check against global model spatial extent, potentially wrapping // longitude to match { const auto &extent = mModel->extent(); const double minx = extent.minxNormalized(mIsGeographicCRS); const double maxx = extent.maxxNormalized(mIsGeographicCRS); if (mIsGeographicCRS) { while (x < minx - EPS) { x += 2.0 * DEFMODEL_PI; } while (x > maxx + EPS) { x -= 2.0 * DEFMODEL_PI; } } const double miny = extent.minyNormalized(mIsGeographicCRS); const double maxy = extent.maxyNormalized(mIsGeographicCRS); const double extraMarginForInverse = mIsGeographicCRS ? DegToRad(0.1) : 10000; if (!bboxCheck(x, y, forInverseComputation, minx, miny, maxx, maxy, EPS, extraMarginForInverse)) { #ifdef DEBUG_DEFMODEL iface.log("Calculation point " + toString(x) + "," + toString(y) + " is outside the extents of the deformation model"); #endif return false; } } // Check against global model temporal extent { const auto &timeExtent = mModel->timeExtent(); if (t < timeExtent.first.toDecimalYear() || t > timeExtent.last.toDecimalYear()) { #ifdef DEBUG_DEFMODEL iface.log("Calculation epoch " + toString(t) + " is not valid for the deformation model"); #endif return false; } } // For mIsHorizontalUnitDegree double dlam = 0; double dphi = 0; // For !mIsHorizontalUnitDegree double de = 0; double dn = 0; double dz = 0; bool sincosphiInitialized = false; double sinphi = 0; double cosphi = 0; for (auto &compEx : mComponents) { const auto &comp = compEx->component; if (compEx->displacementType == DisplacementType::NONE) { continue; } const auto &extent = comp.extent(); double xForGrid = x; double yForGrid = y; const double minx = extent.minxNormalized(mIsGeographicCRS); const double maxx = extent.maxxNormalized(mIsGeographicCRS); const double miny = extent.minyNormalized(mIsGeographicCRS); const double maxy = extent.maxyNormalized(mIsGeographicCRS); const double extraMarginForInverse = 0; if (!bboxCheck(xForGrid, yForGrid, forInverseComputation, minx, miny, maxx, maxy, EPS, extraMarginForInverse)) { #ifdef DEBUG_DEFMODEL iface.log( "Skipping component " + shortName(comp) + " due to point being outside of its declared spatial extent."); #endif continue; } xForGrid = std::max(xForGrid, minx); yForGrid = std::max(yForGrid, miny); xForGrid = std::min(xForGrid, maxx); yForGrid = std::min(yForGrid, maxy); const auto tfactor = compEx->evaluateAt(t); if (tfactor == 0.0) { #ifdef DEBUG_DEFMODEL iface.log("Skipping component " + shortName(comp) + " due to time function evaluating to 0."); #endif continue; } #ifdef DEBUG_DEFMODEL iface.log("Entering component " + shortName(comp) + " with time function evaluating to " + toString(tfactor) + "."); #endif if (compEx->gridSet == nullptr) { compEx->gridSet = iface.open(comp.spatialModel().filename); if (compEx->gridSet == nullptr) { return false; } } const Grid *grid = compEx->gridSet->gridAt(xForGrid, yForGrid); if (grid == nullptr) { #ifdef DEBUG_DEFMODEL iface.log("Skipping component " + shortName(comp) + " due to no grid found for this point in the grid set."); #endif continue; } if (grid->width < 2 || grid->height < 2) { return false; } const double ix_d = (xForGrid - grid->minx) / grid->resx; const double iy_d = (yForGrid - grid->miny) / grid->resy; if (ix_d < -EPS || iy_d < -EPS || ix_d + 1 >= grid->width + EPS || iy_d + 1 >= grid->height + EPS) { #ifdef DEBUG_DEFMODEL iface.log("Skipping component " + shortName(comp) + " due to point being outside of actual spatial extent of " "grid " + grid->name() + "."); #endif continue; } const int ix0 = std::min(static_cast<int>(ix_d), grid->width - 2); const int iy0 = std::min(static_cast<int>(iy_d), grid->height - 2); const int ix1 = ix0 + 1; const int iy1 = iy0 + 1; const double frct_x = ix_d - ix0; const double frct_y = iy_d - iy0; const double one_minus_frct_x = 1. - frct_x; const double one_minus_frct_y = 1. - frct_y; const double m00 = one_minus_frct_x * one_minus_frct_y; const double m10 = frct_x * one_minus_frct_y; const double m01 = one_minus_frct_x * frct_y; const double m11 = frct_x * frct_y; if (compEx->displacementType == DisplacementType::VERTICAL) { double dz00 = 0; double dz01 = 0; double dz10 = 0; double dz11 = 0; if (!grid->getZOffset(ix0, iy0, dz00) || !grid->getZOffset(ix1, iy0, dz10) || !grid->getZOffset(ix0, iy1, dz01) || !grid->getZOffset(ix1, iy1, dz11)) { return false; } const double dzInterp = dz00 * m00 + dz01 * m01 + dz10 * m10 + dz11 * m11; #ifdef DEBUG_DEFMODEL iface.log("tfactor * dzInterp = " + toString(tfactor) + " * " + toString(dzInterp) + "."); #endif dz += tfactor * dzInterp; } else if (mIsHorizontalUnitDegree) { double dx00 = 0; double dy00 = 0; double dx01 = 0; double dy01 = 0; double dx10 = 0; double dy10 = 0; double dx11 = 0; double dy11 = 0; if (compEx->displacementType == DisplacementType::HORIZONTAL) { if (!grid->getLongLatOffset(ix0, iy0, dx00, dy00) || !grid->getLongLatOffset(ix1, iy0, dx10, dy10) || !grid->getLongLatOffset(ix0, iy1, dx01, dy01) || !grid->getLongLatOffset(ix1, iy1, dx11, dy11)) { return false; } } else /* if (compEx->displacementType == DisplacementType::THREE_D) */ { double dz00 = 0; double dz01 = 0; double dz10 = 0; double dz11 = 0; if (!grid->getLongLatZOffset(ix0, iy0, dx00, dy00, dz00) || !grid->getLongLatZOffset(ix1, iy0, dx10, dy10, dz10) || !grid->getLongLatZOffset(ix0, iy1, dx01, dy01, dz01) || !grid->getLongLatZOffset(ix1, iy1, dx11, dy11, dz11)) { return false; } const double dzInterp = dz00 * m00 + dz01 * m01 + dz10 * m10 + dz11 * m11; #ifdef DEBUG_DEFMODEL iface.log("tfactor * dzInterp = " + toString(tfactor) + " * " + toString(dzInterp) + "."); #endif dz += tfactor * dzInterp; } const double dlamInterp = dx00 * m00 + dx01 * m01 + dx10 * m10 + dx11 * m11; const double dphiInterp = dy00 * m00 + dy01 * m01 + dy10 * m10 + dy11 * m11; #ifdef DEBUG_DEFMODEL iface.log("tfactor * dlamInterp = " + toString(tfactor) + " * " + toString(dlamInterp) + "."); iface.log("tfactor * dphiInterp = " + toString(tfactor) + " * " + toString(dphiInterp) + "."); #endif dlam += tfactor * dlamInterp; dphi += tfactor * dphiInterp; } else /* horizontal unit is metre */ { double de00 = 0; double dn00 = 0; double de01 = 0; double dn01 = 0; double de10 = 0; double dn10 = 0; double de11 = 0; double dn11 = 0; if (compEx->displacementType == DisplacementType::HORIZONTAL) { if (!grid->getEastingNorthingOffset(ix0, iy0, de00, dn00) || !grid->getEastingNorthingOffset(ix1, iy0, de10, dn10) || !grid->getEastingNorthingOffset(ix0, iy1, de01, dn01) || !grid->getEastingNorthingOffset(ix1, iy1, de11, dn11)) { return false; } } else /* if (compEx->displacementType == DisplacementType::THREE_D) */ { double dz00 = 0; double dz01 = 0; double dz10 = 0; double dz11 = 0; if (!grid->getEastingNorthingZOffset(ix0, iy0, de00, dn00, dz00) || !grid->getEastingNorthingZOffset(ix1, iy0, de10, dn10, dz10) || !grid->getEastingNorthingZOffset(ix0, iy1, de01, dn01, dz01) || !grid->getEastingNorthingZOffset(ix1, iy1, de11, dn11, dz11)) { return false; } const double dzInterp = dz00 * m00 + dz01 * m01 + dz10 * m10 + dz11 * m11; #ifdef DEBUG_DEFMODEL iface.log("tfactor * dzInterp = " + toString(tfactor) + " * " + toString(dzInterp) + "."); #endif dz += tfactor * dzInterp; } if (compEx->isBilinearInterpolation) { const double deInterp = de00 * m00 + de01 * m01 + de10 * m10 + de11 * m11; const double dnInterp = dn00 * m00 + dn01 * m01 + dn10 * m10 + dn11 * m11; #ifdef DEBUG_DEFMODEL iface.log("tfactor * deInterp = " + toString(tfactor) + " * " + toString(deInterp) + "."); iface.log("tfactor * dnInterp = " + toString(tfactor) + " * " + toString(dnInterp) + "."); #endif de += tfactor * deInterp; dn += tfactor * dnInterp; } else /* geocentric_bilinear */ { double dX; double dY; double dZ; auto iter = compEx->mapGrids.find(grid); if (iter == compEx->mapGrids.end()) { GridEx<Grid> gridWithCache(grid); iter = compEx->mapGrids .insert(std::pair<const Grid *, GridEx<Grid>>( grid, std::move(gridWithCache))) .first; } GridEx<Grid> &gridwithCacheRef = iter->second; gridwithCacheRef.getBilinearGeocentric( ix0, iy0, de00, dn00, de01, dn01, de10, dn10, de11, dn11, m00, m01, m10, m11, dX, dY, dZ); if (!sincosphiInitialized) { sincosphiInitialized = true; sinphi = sin(y); cosphi = cos(y); } const double lam_rel_to_cell_center = (frct_x - 0.5) * grid->resx; // Use small-angle approximation of sin/cos when reasonable // Max abs/rel error on cos is 3.9e-9 and on sin 1.3e-11 const double sinlam = gridwithCacheRef.smallResx ? lam_rel_to_cell_center * (1 - (1. / 6) * (lam_rel_to_cell_center * lam_rel_to_cell_center)) : sin(lam_rel_to_cell_center); const double coslam = gridwithCacheRef.smallResx ? (1 - 0.5 * (lam_rel_to_cell_center * lam_rel_to_cell_center)) : cos(lam_rel_to_cell_center); // Convert back from geocentric deltas to easting, northing // deltas const double deInterp = -dX * sinlam + dY * coslam; const double dnInterp = (-dX * coslam - dY * sinlam) * sinphi + dZ * cosphi; #ifdef DEBUG_DEFMODEL iface.log("After geocentric_bilinear interpolation: tfactor * " "deInterp = " + toString(tfactor) + " * " + toString(deInterp) + "."); iface.log("After geocentric_bilinear interpolation: tfactor * " "dnInterp = " + toString(tfactor) + " * " + toString(dnInterp) + "."); #endif de += tfactor * deInterp; dn += tfactor * dnInterp; } } } // Apply shifts depending on horizontal_offset_unit and // horizontal_offset_method if (mIsHorizontalUnitDegree) { x_out += dlam; y_out += dphi; } else { #ifdef DEBUG_DEFMODEL iface.log("Total sum of de: " + toString(de)); iface.log("Total sum of dn: " + toString(dn)); #endif if (mIsAddition && !mIsGeographicCRS) { x_out += de; y_out += dn; } else if (mIsAddition) { // Simple way of adding the offset if (!sincosphiInitialized) { cosphi = cos(y); } DeltaEastingNorthingToLongLat(cosphi, de, dn, mA, mB, mEs, dlam, dphi); #ifdef DEBUG_DEFMODEL iface.log("Result dlam: " + toString(dlam)); iface.log("Result dphi: " + toString(dphi)); #endif x_out += dlam; y_out += dphi; } else { // Geocentric way of adding the offset if (!sincosphiInitialized) { sinphi = sin(y); cosphi = cos(y); } const double sinlam = sin(x); const double coslam = cos(x); const double dnsinphi = dn * sinphi; const double dX = -de * sinlam - dnsinphi * coslam; const double dY = de * coslam - dnsinphi * sinlam; const double dZ = dn * cosphi; double X; double Y; double Z; iface.geographicToGeocentric(x, y, 0, mA, mB, mEs, X, Y, Z); #ifdef DEBUG_DEFMODEL iface.log("Geocentric coordinate before: " + toString(X) + "," + toString(Y) + "," + toString(Z)); iface.log("Geocentric shift: " + toString(dX) + "," + toString(dY) + "," + toString(dZ)); #endif X += dX; Y += dY; Z += dZ; #ifdef DEBUG_DEFMODEL iface.log("Geocentric coordinate after: " + toString(X) + "," + toString(Y) + "," + toString(Z)); #endif double h_out_ignored; iface.geocentricToGeographic(X, Y, Z, mA, mB, mEs, x_out, y_out, h_out_ignored); } } #ifdef DEBUG_DEFMODEL iface.log("Total sum of dz: " + toString(dz)); #endif z_out += dz; return true; } // --------------------------------------------------------------------------- template <class Grid, class GridSet, class EvaluatorIface> bool Evaluator<Grid, GridSet, EvaluatorIface>::inverse( EvaluatorIface &iface, double x, double y, double z, double t, double &x_out, double &y_out, double &z_out) { x_out = x; y_out = y; z_out = z; constexpr double EPS_HORIZ = 1e-12; constexpr double EPS_VERT = 1e-3; constexpr bool forInverseComputation = true; for (int i = 0; i < 10; i++) { #ifdef DEBUG_DEFMODEL iface.log("Iteration " + std::to_string(i) + ": before forward: x=" + toString(x_out) + ", y=" + toString(y_out)); #endif double x_new; double y_new; double z_new; if (!forward(iface, x_out, y_out, z_out, t, forInverseComputation, x_new, y_new, z_new)) { return false; } #ifdef DEBUG_DEFMODEL iface.log("After forward: x=" + toString(x_new) + ", y=" + toString(y_new)); #endif const double dx = x_new - x; const double dy = y_new - y; const double dz = z_new - z; x_out -= dx; y_out -= dy; z_out -= dz; if (std::max(std::fabs(dx), std::fabs(dy)) < EPS_HORIZ && std::fabs(dz) < EPS_VERT) { return true; } } return false; } // --------------------------------------------------------------------------- } // namespace DEFORMATON_MODEL_NAMESPACE
hpp
PROJ
data/projects/PROJ/src/transformations/vgridshift.cpp
#include <errno.h> #include <mutex> #include <stddef.h> #include <string.h> #include <time.h> #include "grids.hpp" #include "proj_internal.h" PROJ_HEAD(vgridshift, "Vertical grid shift"); static std::mutex gMutexVGridShift{}; static std::set<std::string> gKnownGridsVGridShift{}; using namespace NS_PROJ; namespace { // anonymous namespace struct vgridshiftData { double t_final = 0; double t_epoch = 0; double forward_multiplier = 0; ListOfVGrids grids{}; bool defer_grid_opening = false; }; } // anonymous namespace static void deal_with_vertcon_gtx_hack(PJ *P) { struct vgridshiftData *Q = (struct vgridshiftData *)P->opaque; // The .gtx VERTCON files stored millimeters, but the .tif files // are in metres. if (Q->forward_multiplier != 0.001) { return; } const char *gridname = pj_param(P->ctx, P->params, "sgrids").s; if (!gridname) { return; } if (strcmp(gridname, "vertconw.gtx") != 0 && strcmp(gridname, "vertconc.gtx") != 0 && strcmp(gridname, "vertcone.gtx") != 0) { return; } if (Q->grids.empty()) { return; } const auto &grids = Q->grids[0]->grids(); if (!grids.empty() && grids[0]->name().find(".tif") != std::string::npos) { Q->forward_multiplier = 1.0; } } static PJ_XYZ pj_vgridshift_forward_3d(PJ_LPZ lpz, PJ *P) { struct vgridshiftData *Q = (struct vgridshiftData *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; point.lpz = lpz; if (Q->defer_grid_opening) { Q->defer_grid_opening = false; Q->grids = pj_vgrid_init(P, "grids"); deal_with_vertcon_gtx_hack(P); if (proj_errno(P)) { return proj_coord_error().xyz; } } if (!Q->grids.empty()) { /* Only try the gridshift if at least one grid is loaded, * otherwise just pass the coordinate through unchanged. */ point.xyz.z += pj_vgrid_value(P, Q->grids, point.lp, Q->forward_multiplier); } return point.xyz; } static PJ_LPZ pj_vgridshift_reverse_3d(PJ_XYZ xyz, PJ *P) { struct vgridshiftData *Q = (struct vgridshiftData *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; point.xyz = xyz; if (Q->defer_grid_opening) { Q->defer_grid_opening = false; Q->grids = pj_vgrid_init(P, "grids"); deal_with_vertcon_gtx_hack(P); if (proj_errno(P)) { return proj_coord_error().lpz; } } if (!Q->grids.empty()) { /* Only try the gridshift if at least one grid is loaded, * otherwise just pass the coordinate through unchanged. */ point.xyz.z -= pj_vgrid_value(P, Q->grids, point.lp, Q->forward_multiplier); } return point.lpz; } static void pj_vgridshift_forward_4d(PJ_COORD &coo, PJ *P) { struct vgridshiftData *Q = (struct vgridshiftData *)P->opaque; /* If transformation is not time restricted, we always call it */ if (Q->t_final == 0 || Q->t_epoch == 0) { // 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 = pj_vgridshift_forward_3d(coo.lpz, P); coo.xyz = xyz; return; } /* Time restricted - only apply transform if within time bracket */ if (coo.lpzt.t < Q->t_epoch && Q->t_final > Q->t_epoch) { // 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 = pj_vgridshift_forward_3d(coo.lpz, P); coo.xyz = xyz; } } static void pj_vgridshift_reverse_4d(PJ_COORD &coo, PJ *P) { struct vgridshiftData *Q = (struct vgridshiftData *)P->opaque; /* If transformation is not time restricted, we always call it */ if (Q->t_final == 0 || Q->t_epoch == 0) { // 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 = pj_vgridshift_reverse_3d(coo.xyz, P); coo.lpz = lpz; return; } /* Time restricted - only apply transform if within time bracket */ if (coo.lpzt.t < Q->t_epoch && Q->t_final > Q->t_epoch) { // 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 = pj_vgridshift_reverse_3d(coo.xyz, P); coo.lpz = lpz; } } static PJ *pj_vgridshift_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; delete static_cast<struct vgridshiftData *>(P->opaque); P->opaque = nullptr; return pj_default_destructor(P, errlev); } static void pj_vgridshift_reassign_context(PJ *P, PJ_CONTEXT *ctx) { auto Q = (struct vgridshiftData *)P->opaque; for (auto &grid : Q->grids) { grid->reassign_context(ctx); } } PJ *PJ_TRANSFORMATION(vgridshift, 0) { auto Q = new vgridshiftData; P->opaque = (void *)Q; P->destructor = pj_vgridshift_destructor; P->reassign_context = pj_vgridshift_reassign_context; if (!pj_param(P->ctx, P->params, "tgrids").i) { proj_log_error(P, _("+grids parameter missing.")); return pj_vgridshift_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } /* TODO: Refactor into shared function that can be used */ /* by both vgridshift and hgridshift */ if (pj_param(P->ctx, P->params, "tt_final").i) { Q->t_final = pj_param(P->ctx, P->params, "dt_final").f; if (Q->t_final == 0) { /* a number wasn't passed to +t_final, let's see if it was "now" */ /* and set the time accordingly. */ if (!strcmp("now", pj_param(P->ctx, P->params, "st_final").s)) { time_t now; struct tm *date; time(&now); date = localtime(&now); Q->t_final = 1900.0 + date->tm_year + date->tm_yday / 365.0; } } } if (pj_param(P->ctx, P->params, "tt_epoch").i) Q->t_epoch = pj_param(P->ctx, P->params, "dt_epoch").f; /* historical: the forward direction subtracts the grid offset. */ Q->forward_multiplier = -1.0; if (pj_param(P->ctx, P->params, "tmultiplier").i) { Q->forward_multiplier = pj_param(P->ctx, P->params, "dmultiplier").f; } if (P->ctx->defer_grid_opening) { Q->defer_grid_opening = true; } else { const char *gridnames = pj_param(P->ctx, P->params, "sgrids").s; gMutexVGridShift.lock(); const bool isKnownGrid = gKnownGridsVGridShift.find(gridnames) != gKnownGridsVGridShift.end(); gMutexVGridShift.unlock(); if (isKnownGrid) { Q->defer_grid_opening = true; } else { /* Build gridlist. P->vgridlist_geoid can be empty if +grids only * ask for optional grids. */ Q->grids = pj_vgrid_init(P, "grids"); /* Was gridlist compiled properly? */ if (proj_errno(P)) { proj_log_error(P, _("could not find required grid(s).")); return pj_vgridshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } gMutexVGridShift.lock(); gKnownGridsVGridShift.insert(gridnames); gMutexVGridShift.unlock(); } } P->fwd4d = pj_vgridshift_forward_4d; P->inv4d = pj_vgridshift_reverse_4d; P->fwd3d = pj_vgridshift_forward_3d; P->inv3d = pj_vgridshift_reverse_3d; P->fwd = nullptr; P->inv = nullptr; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; return P; } void pj_clear_vgridshift_knowngrids_cache() { std::lock_guard<std::mutex> lock(gMutexVGridShift); gKnownGridsVGridShift.clear(); }
cpp
PROJ
data/projects/PROJ/src/transformations/defmodel.cpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to deformation model * 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. *****************************************************************************/ #define PROJ_COMPILATION #include "defmodel.hpp" #include "filemanager.hpp" #include "grids.hpp" #include "proj_internal.h" #include <assert.h> #include <map> #include <memory> #include <utility> PROJ_HEAD(defmodel, "Deformation model"); using namespace DeformationModel; namespace { struct Grid : public GridPrototype { PJ_CONTEXT *ctx; const NS_PROJ::GenericShiftGrid *realGrid; mutable bool checkedHorizontal = false; mutable bool checkedVertical = false; mutable int sampleX = 0; mutable int sampleY = 1; mutable int sampleZ = 2; Grid(PJ_CONTEXT *ctxIn, const NS_PROJ::GenericShiftGrid *realGridIn) : ctx(ctxIn), realGrid(realGridIn) { minx = realGridIn->extentAndRes().west; miny = realGridIn->extentAndRes().south; resx = realGridIn->extentAndRes().resX; resy = realGridIn->extentAndRes().resY; width = realGridIn->width(); height = realGridIn->height(); } bool checkHorizontal(const std::string &expectedUnit) const { if (!checkedHorizontal) { const auto samplesPerPixel = realGrid->samplesPerPixel(); if (samplesPerPixel < 2) { pj_log(ctx, PJ_LOG_ERROR, "grid %s has not enough samples", realGrid->name().c_str()); return false; } bool foundDescX = false; bool foundDescY = false; bool foundDesc = false; for (int i = 0; i < samplesPerPixel; i++) { const auto desc = realGrid->description(i); if (desc == "east_offset") { sampleX = i; foundDescX = true; } else if (desc == "north_offset") { sampleY = i; foundDescY = true; } if (!desc.empty()) { foundDesc = true; } } if (foundDesc && (!foundDescX || !foundDescY)) { pj_log(ctx, PJ_LOG_ERROR, "grid %s : Found band description, " "but not the ones expected", realGrid->name().c_str()); return false; } const auto unit = realGrid->unit(sampleX); if (!unit.empty() && unit != expectedUnit) { pj_log(ctx, PJ_LOG_ERROR, "grid %s : Only unit=%s " "currently handled for this mode", realGrid->name().c_str(), expectedUnit.c_str()); return false; } checkedHorizontal = true; } return true; } bool getLongLatOffset(int ix, int iy, double &longOffsetRadian, double &latOffsetRadian) const { if (!checkHorizontal(STR_DEGREE)) { return false; } float longOffsetDeg; float latOffsetDeg; if (!realGrid->valueAt(ix, iy, sampleX, longOffsetDeg) || !realGrid->valueAt(ix, iy, sampleY, latOffsetDeg)) { return false; } longOffsetRadian = longOffsetDeg * DEG_TO_RAD; latOffsetRadian = latOffsetDeg * DEG_TO_RAD; return true; } bool getZOffset(int ix, int iy, double &zOffset) const { if (!checkedVertical) { const auto samplesPerPixel = realGrid->samplesPerPixel(); if (samplesPerPixel == 1) { sampleZ = 0; } else if (samplesPerPixel < 3) { pj_log(ctx, PJ_LOG_ERROR, "grid %s has not enough samples", realGrid->name().c_str()); return false; } bool foundDesc = false; bool foundDescZ = false; for (int i = 0; i < samplesPerPixel; i++) { const auto desc = realGrid->description(i); if (desc == "vertical_offset") { sampleZ = i; foundDescZ = true; } if (!desc.empty()) { foundDesc = true; } } if (foundDesc && !foundDescZ) { pj_log(ctx, PJ_LOG_ERROR, "grid %s : Found band description, " "but not the ones expected", realGrid->name().c_str()); return false; } const auto unit = realGrid->unit(sampleZ); if (!unit.empty() && unit != STR_METRE) { pj_log(ctx, PJ_LOG_ERROR, "grid %s : Only unit=metre currently " "handled for this mode", realGrid->name().c_str()); return false; } checkedVertical = true; } float zOffsetFloat = 0.0f; const bool ret = realGrid->valueAt(ix, iy, sampleZ, zOffsetFloat); zOffset = zOffsetFloat; return ret; } bool getEastingNorthingOffset(int ix, int iy, double &eastingOffset, double &northingOffset) const { if (!checkHorizontal(STR_METRE)) { return false; } float eastingOffsetFloat = 0.0f; float northingOffsetFloat = 0.0f; const bool ret = realGrid->valueAt(ix, iy, sampleX, eastingOffsetFloat) && realGrid->valueAt(ix, iy, sampleY, northingOffsetFloat); eastingOffset = eastingOffsetFloat; northingOffset = northingOffsetFloat; return ret; } bool getLongLatZOffset(int ix, int iy, double &longOffsetRadian, double &latOffsetRadian, double &zOffset) const { return getLongLatOffset(ix, iy, longOffsetRadian, latOffsetRadian) && getZOffset(ix, iy, zOffset); } bool getEastingNorthingZOffset(int ix, int iy, double &eastingOffset, double &northingOffset, double &zOffset) const { return getEastingNorthingOffset(ix, iy, eastingOffset, northingOffset) && getZOffset(ix, iy, zOffset); } #ifdef DEBUG_DEFMODEL std::string name() const { return realGrid->name(); } #endif private: Grid(const Grid &) = delete; Grid &operator=(const Grid &) = delete; }; struct GridSet : public GridSetPrototype<Grid> { PJ_CONTEXT *ctx; std::unique_ptr<NS_PROJ::GenericShiftGridSet> realGridSet; std::map<const NS_PROJ::GenericShiftGrid *, std::unique_ptr<Grid>> mapGrids{}; GridSet(PJ_CONTEXT *ctxIn, std::unique_ptr<NS_PROJ::GenericShiftGridSet> &&realGridSetIn) : ctx(ctxIn), realGridSet(std::move(realGridSetIn)) {} const Grid *gridAt(double x, double y) { const NS_PROJ::GenericShiftGrid *realGrid = realGridSet->gridAt(x, y); if (!realGrid) { return nullptr; } auto iter = mapGrids.find(realGrid); if (iter == mapGrids.end()) { iter = mapGrids .insert(std::pair<const NS_PROJ::GenericShiftGrid *, std::unique_ptr<Grid>>( realGrid, std::unique_ptr<Grid>(new Grid(ctx, realGrid)))) .first; } return iter->second.get(); } private: GridSet(const GridSet &) = delete; GridSet &operator=(const GridSet &) = delete; }; struct EvaluatorIface : public EvaluatorIfacePrototype<Grid, GridSet> { PJ_CONTEXT *ctx; PJ *cart; EvaluatorIface(PJ_CONTEXT *ctxIn, PJ *cartIn) : ctx(ctxIn), cart(cartIn) {} ~EvaluatorIface() { if (cart) cart->destructor(cart, 0); } std::unique_ptr<GridSet> open(const std::string &filename) { auto realGridSet = NS_PROJ::GenericShiftGridSet::open(ctx, filename); if (!realGridSet) { pj_log(ctx, PJ_LOG_ERROR, "cannot open %s", filename.c_str()); return nullptr; } return std::unique_ptr<GridSet>( new GridSet(ctx, std::move(realGridSet))); } bool isGeographicCRS(const std::string &crsDef) { PJ *P = proj_create(ctx, crsDef.c_str()); if (P == nullptr) { return true; // reasonable default value } const auto type = proj_get_type(P); bool ret = (type == PJ_TYPE_GEOGRAPHIC_2D_CRS || type == PJ_TYPE_GEOGRAPHIC_3D_CRS); proj_destroy(P); return ret; } void geographicToGeocentric(double lam, double phi, double height, double a, double b, double /*es*/, double &X, double &Y, double &Z) { (void)a; (void)b; assert(cart->a == a); assert(cart->b == b); PJ_LPZ lpz; lpz.lam = lam; lpz.phi = phi; lpz.z = height; PJ_XYZ xyz = cart->fwd3d(lpz, cart); X = xyz.x; Y = xyz.y; Z = xyz.z; } void geocentricToGeographic(double X, double Y, double Z, double a, double b, double /*es*/, double &lam, double &phi, double &height) { (void)a; (void)b; assert(cart->a == a); assert(cart->b == b); PJ_XYZ xyz; xyz.x = X; xyz.y = Y; xyz.z = Z; PJ_LPZ lpz = cart->inv3d(xyz, cart); lam = lpz.lam; phi = lpz.phi; height = lpz.z; } #ifdef DEBUG_DEFMODEL void log(const std::string &msg) { pj_log(ctx, PJ_LOG_TRACE, "%s", msg.c_str()); } #endif private: EvaluatorIface(const EvaluatorIface &) = delete; EvaluatorIface &operator=(const EvaluatorIface &) = delete; }; struct defmodelData { std::unique_ptr<Evaluator<Grid, GridSet, EvaluatorIface>> evaluator{}; EvaluatorIface evaluatorIface; explicit defmodelData(PJ_CONTEXT *ctx, PJ *cart) : evaluatorIface(ctx, cart) {} defmodelData(const defmodelData &) = delete; defmodelData &operator=(const defmodelData &) = delete; }; } // namespace static PJ *destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; auto Q = static_cast<struct defmodelData *>(P->opaque); delete Q; P->opaque = nullptr; return pj_default_destructor(P, errlev); } static void forward_4d(PJ_COORD &coo, PJ *P) { auto *Q = (struct defmodelData *)P->opaque; if (!Q->evaluator->forward(Q->evaluatorIface, coo.xyzt.x, coo.xyzt.y, coo.xyzt.z, coo.xyzt.t, coo.xyzt.x, coo.xyzt.y, coo.xyzt.z)) { coo = proj_coord_error(); } } static void reverse_4d(PJ_COORD &coo, PJ *P) { auto *Q = (struct defmodelData *)P->opaque; if (!Q->evaluator->inverse(Q->evaluatorIface, coo.xyzt.x, coo.xyzt.y, coo.xyzt.z, coo.xyzt.t, coo.xyzt.x, coo.xyzt.y, coo.xyzt.z)) { coo = proj_coord_error(); } } // Function called by proj_assign_context() when a new context is assigned to // an existing PJ object. Mostly to deal with objects being passed between // threads. static void reassign_context(PJ *P, PJ_CONTEXT *ctx) { auto *Q = (struct defmodelData *)P->opaque; if (Q->evaluatorIface.ctx != ctx) { Q->evaluator->clearGridCache(); Q->evaluatorIface.ctx = ctx; } } PJ *PJ_TRANSFORMATION(defmodel, 1) { // Pass a dummy ellipsoid definition that will be overridden just afterwards auto cart = proj_create(P->ctx, "+proj=cart +a=1"); if (cart == nullptr) return destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); /* inherit ellipsoid definition from P to Q->cart */ pj_inherit_ellipsoid_def(P, cart); auto Q = new defmodelData(P->ctx, cart); P->opaque = (void *)Q; P->destructor = destructor; P->reassign_context = reassign_context; const char *model = pj_param(P->ctx, P->params, "smodel").s; if (!model) { proj_log_error(P, _("+model= should be specified.")); return destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } auto file = NS_PROJ::FileManager::open_resource_file(P->ctx, model); if (nullptr == file) { proj_log_error(P, _("Cannot open %s"), model); return destructor(P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } file->seek(0, SEEK_END); unsigned long long size = file->tell(); // Arbitrary threshold to avoid ingesting an arbitrarily large JSON file, // that could be a denial of service risk. 10 MB should be sufficiently // large for any valid use ! if (size > 10 * 1024 * 1024) { proj_log_error(P, _("File %s too large"), model); return destructor(P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } file->seek(0); std::string jsonStr; jsonStr.resize(static_cast<size_t>(size)); if (file->read(&jsonStr[0], jsonStr.size()) != jsonStr.size()) { proj_log_error(P, _("Cannot read %s"), model); return destructor(P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } try { Q->evaluator.reset(new Evaluator<Grid, GridSet, EvaluatorIface>( MasterFile::parse(jsonStr), Q->evaluatorIface, P->a, P->b)); } catch (const std::exception &e) { proj_log_error(P, _("invalid model: %s"), e.what()); return destructor(P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } P->fwd4d = forward_4d; P->inv4d = reverse_4d; if (Q->evaluator->isGeographicCRS()) { P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; } else { P->left = PJ_IO_UNITS_PROJECTED; P->right = PJ_IO_UNITS_PROJECTED; } return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/helmert.cpp
/*********************************************************************** 3-, 4-and 7-parameter shifts, and their 6-, 8- and 14-parameter kinematic counterparts. Thomas Knudsen, 2016-05-24 ************************************************************************ Implements 3(6)-, 4(8) and 7(14)-parameter Helmert transformations for 3D data. Also incorporates Molodensky-Badekas variant of 7-parameter Helmert transformation, where the rotation is not applied regarding the centre of the spheroid, but given a reference point. Primarily useful for implementation of datum shifts in transformation pipelines. ************************************************************************ Thomas Knudsen, [email protected], 2016-05-24/06-05 Kristian Evers, [email protected], 2017-05-01 Even Rouault, [email protected] Last update: 2018-10-26 ************************************************************************ * Copyright (c) 2016, 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. * ***********************************************************************/ #include <errno.h> #include <math.h> #include "proj_internal.h" PROJ_HEAD(helmert, "3(6)-, 4(8)- and 7(14)-parameter Helmert shift"); PROJ_HEAD(molobadekas, "Molodensky-Badekas transformation"); static PJ_XYZ helmert_forward_3d(PJ_LPZ lpz, PJ *P); static PJ_LPZ helmert_reverse_3d(PJ_XYZ xyz, PJ *P); /***********************************************************************/ namespace { // anonymous namespace struct pj_opaque_helmert { /************************************************************************ Projection specific elements for the "helmert" PJ object ************************************************************************/ PJ_XYZ xyz; PJ_XYZ xyz_0; PJ_XYZ dxyz; PJ_XYZ refp; PJ_OPK opk; PJ_OPK opk_0; PJ_OPK dopk; double scale; double scale_0; double dscale; double theta; double theta_0; double dtheta; double R[3][3]; double t_epoch, t_obs; int no_rotation, exact, fourparam; int is_position_vector; /* 1 = position_vector, 0 = coordinate_frame */ }; } // anonymous namespace /* Make the maths of the rotation operations somewhat more readable and textbook * like */ #define R00 (Q->R[0][0]) #define R01 (Q->R[0][1]) #define R02 (Q->R[0][2]) #define R10 (Q->R[1][0]) #define R11 (Q->R[1][1]) #define R12 (Q->R[1][2]) #define R20 (Q->R[2][0]) #define R21 (Q->R[2][1]) #define R22 (Q->R[2][2]) /**************************************************************************/ static void update_parameters(PJ *P) { /*************************************************************************** Update transformation parameters. --------------------------------- The 14-parameter Helmert transformation is at it's core the same as the 7-parameter transformation, since the transformation parameters are projected forward or backwards in time via the rate of changes of the parameters. The transformation parameters are calculated for a specific epoch before the actual Helmert transformation is carried out. The transformation parameters are updated with the following equation [0]: . P(t) = P(EPOCH) + P * (t - EPOCH) . where EPOCH is the epoch indicated in the above table and P is the rate of that parameter. [0] http://itrf.ign.fr/doc_ITRF/Transfo-ITRF2008_ITRFs.txt *******************************************************************************/ struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; double dt = Q->t_obs - Q->t_epoch; Q->xyz.x = Q->xyz_0.x + Q->dxyz.x * dt; Q->xyz.y = Q->xyz_0.y + Q->dxyz.y * dt; Q->xyz.z = Q->xyz_0.z + Q->dxyz.z * dt; Q->opk.o = Q->opk_0.o + Q->dopk.o * dt; Q->opk.p = Q->opk_0.p + Q->dopk.p * dt; Q->opk.k = Q->opk_0.k + Q->dopk.k * dt; Q->scale = Q->scale_0 + Q->dscale * dt; Q->theta = Q->theta_0 + Q->dtheta * dt; /* debugging output */ if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_TRACE) { proj_log_trace(P, "Transformation parameters for observation " "t_obs=%g (t_epoch=%g):", Q->t_obs, Q->t_epoch); proj_log_trace(P, "x: %g", Q->xyz.x); proj_log_trace(P, "y: %g", Q->xyz.y); proj_log_trace(P, "z: %g", Q->xyz.z); proj_log_trace(P, "s: %g", Q->scale * 1e-6); proj_log_trace(P, "rx: %g", Q->opk.o); proj_log_trace(P, "ry: %g", Q->opk.p); proj_log_trace(P, "rz: %g", Q->opk.k); proj_log_trace(P, "theta: %g", Q->theta); } } /**************************************************************************/ static void build_rot_matrix(PJ *P) { /*************************************************************************** Build rotation matrix. ---------------------- Here we rename rotation indices from omega, phi, kappa (opk), to fi (i.e. phi), theta, psi (ftp), in order to reduce the mental agility needed to implement the expression for the rotation matrix derived over at https://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions The relevant section is Euler angles ( z-’-x" intrinsic) -> Rotation matrix By default small angle approximations are used: The matrix elements are approximated by expanding the trigonometric functions to linear order (i.e. cos(x) = 1, sin(x) = x), and discarding products of second order. This was a useful hack when calculating by hand was the only option, but in general, today, should be avoided because: 1. It does not save much computation time, as the rotation matrix is built only once and probably used many times (except when transforming spatio-temporal coordinates). 2. The error induced may be too large for ultra high accuracy applications: the Earth is huge and the linear error is approximately the angular error multiplied by the Earth radius. However, in many cases the approximation is necessary, since it has been used historically: Rotation angles from older published datum shifts may actually be a least squares fit to the linearized rotation approximation, hence not being strictly valid for deriving the exact rotation matrix. In fact, most publicly available transformation parameters are based on the approximate Helmert transform, which is why we use that as the default setting, even though it is more correct to use the exact form of the equations. So in order to fit historically derived coordinates, the access to the approximate rotation matrix is necessary - at least in principle. Also, when using any published datum transformation information, one should always check which convention (exact or approximate rotation matrix) is expected, and whether the induced error for selecting the opposite convention is acceptable (which it often is). Sign conventions ---------------- Take care: Two different sign conventions exist for the rotation terms. Conceptually they relate to whether we rotate the coordinate system or the "position vector" (the vector going from the coordinate system origin to the point being transformed, i.e. the point coordinates interpreted as vector coordinates). Switching between the "position vector" and "coordinate system" conventions is simply a matter of switching the sign of the rotation angles, which algebraically also translates into a transposition of the rotation matrix. Hence, as geodetic constants should preferably be referred to exactly as published, the "convention" option provides the ability to switch between the conventions. ***************************************************************************/ struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; double f, t, p; /* phi/fi , theta, psi */ double cf, ct, cp; /* cos (fi, theta, psi) */ double sf, st, sp; /* sin (fi, theta, psi) */ /* rename (omega, phi, kappa) to (fi, theta, psi) */ f = Q->opk.o; t = Q->opk.p; p = Q->opk.k; /* Those equations are given assuming coordinate frame convention. */ /* For the position vector convention, we transpose the matrix just after. */ if (Q->exact) { cf = cos(f); sf = sin(f); ct = cos(t); st = sin(t); cp = cos(p); sp = sin(p); R00 = ct * cp; R01 = cf * sp + sf * st * cp; R02 = sf * sp - cf * st * cp; R10 = -ct * sp; R11 = cf * cp - sf * st * sp; R12 = sf * cp + cf * st * sp; R20 = st; R21 = -sf * ct; R22 = cf * ct; } else { R00 = 1; R01 = p; R02 = -t; R10 = -p; R11 = 1; R12 = f; R20 = t; R21 = -f; R22 = 1; } /* For comparison: Description from Engsager/Poder implementation in set_dtm_1.c (trlib) DATUM SHIFT: TO = scale * ROTZ * ROTY * ROTX * FROM + TRANSLA ( cz sz 0) (cy 0 -sy) (1 0 0) ROTZ=(-sz cz 0), ROTY=(0 1 0), ROTX=(0 cx sx) ( 0 0 1) (sy 0 cy) (0 -sx cx) trp->r11 = cos_ry*cos_rz; trp->r12 = cos_rx*sin_rz + sin_rx*sin_ry*cos_rz; trp->r13 = sin_rx*sin_rz - cos_rx*sin_ry*cos_rz; trp->r21 = -cos_ry*sin_rz; trp->r22 = cos_rx*cos_rz - sin_rx*sin_ry*sin_rz; trp->r23 = sin_rx*cos_rz + cos_rx*sin_ry*sin_rz; trp->r31 = sin_ry; trp->r32 = -sin_rx*cos_ry; trp->r33 = cos_rx*cos_ry; trp->scale = 1.0 + scale; */ if (Q->is_position_vector) { double r; r = R01; R01 = R10; R10 = r; r = R02; R02 = R20; R20 = r; r = R12; R12 = R21; R21 = r; } /* some debugging output */ if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_TRACE) { proj_log_trace(P, "Rotation Matrix:"); proj_log_trace(P, " | % 6.6g % 6.6g % 6.6g |", R00, R01, R02); proj_log_trace(P, " | % 6.6g % 6.6g % 6.6g |", R10, R11, R12); proj_log_trace(P, " | % 6.6g % 6.6g % 6.6g |", R20, R21, R22); } } /***********************************************************************/ static PJ_XY helmert_forward(PJ_LP lp, PJ *P) { /***********************************************************************/ struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; double x, y, cr, sr; point.lp = lp; cr = cos(Q->theta) * Q->scale; sr = sin(Q->theta) * Q->scale; x = point.xy.x; y = point.xy.y; point.xy.x = cr * x + sr * y + Q->xyz_0.x; point.xy.y = -sr * x + cr * y + Q->xyz_0.y; return point.xy; } /***********************************************************************/ static PJ_LP helmert_reverse(PJ_XY xy, PJ *P) { /***********************************************************************/ struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; double x, y, sr, cr; point.xy = xy; cr = cos(Q->theta) / Q->scale; sr = sin(Q->theta) / Q->scale; x = point.xy.x - Q->xyz_0.x; y = point.xy.y - Q->xyz_0.y; point.xy.x = x * cr - y * sr; point.xy.y = x * sr + y * cr; return point.lp; } /***********************************************************************/ static PJ_XYZ helmert_forward_3d(PJ_LPZ lpz, PJ *P) { /***********************************************************************/ struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; double X, Y, Z, scale; point.lpz = lpz; if (Q->fourparam) { const auto xy = helmert_forward(point.lp, P); point.xy = xy; return point.xyz; } if (Q->no_rotation && Q->scale == 0) { point.xyz.x = lpz.lam + Q->xyz.x; point.xyz.y = lpz.phi + Q->xyz.y; point.xyz.z = lpz.z + Q->xyz.z; return point.xyz; } scale = 1 + Q->scale * 1e-6; X = lpz.lam - Q->refp.x; Y = lpz.phi - Q->refp.y; Z = lpz.z - Q->refp.z; point.xyz.x = scale * (R00 * X + R01 * Y + R02 * Z); point.xyz.y = scale * (R10 * X + R11 * Y + R12 * Z); point.xyz.z = scale * (R20 * X + R21 * Y + R22 * Z); point.xyz.x += Q->xyz.x; /* for Molodensky-Badekas, Q->xyz already incorporates the Q->refp offset */ point.xyz.y += Q->xyz.y; point.xyz.z += Q->xyz.z; return point.xyz; } /***********************************************************************/ static PJ_LPZ helmert_reverse_3d(PJ_XYZ xyz, PJ *P) { /***********************************************************************/ struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; double X, Y, Z, scale; point.xyz = xyz; if (Q->fourparam) { const auto lp = helmert_reverse(point.xy, P); point.lp = lp; return point.lpz; } if (Q->no_rotation && Q->scale == 0) { point.xyz.x = xyz.x - Q->xyz.x; point.xyz.y = xyz.y - Q->xyz.y; point.xyz.z = xyz.z - Q->xyz.z; return point.lpz; } scale = 1 + Q->scale * 1e-6; /* Unscale and deoffset */ X = (xyz.x - Q->xyz.x) / scale; Y = (xyz.y - Q->xyz.y) / scale; Z = (xyz.z - Q->xyz.z) / scale; /* Inverse rotation through transpose multiplication */ point.xyz.x = (R00 * X + R10 * Y + R20 * Z) + Q->refp.x; point.xyz.y = (R01 * X + R11 * Y + R21 * Z) + Q->refp.y; point.xyz.z = (R02 * X + R12 * Y + R22 * Z) + Q->refp.z; return point.lpz; } static void helmert_forward_4d(PJ_COORD &point, PJ *P) { struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; /* We only need to rebuild the rotation matrix if the * observation time is different from the last call */ double t_obs = (point.xyzt.t == HUGE_VAL) ? Q->t_epoch : point.xyzt.t; if (t_obs != Q->t_obs) { Q->t_obs = t_obs; update_parameters(P); build_rot_matrix(P); } // 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 = helmert_forward_3d(point.lpz, P); point.xyz = xyz; } static void helmert_reverse_4d(PJ_COORD &point, PJ *P) { struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; /* We only need to rebuild the rotation matrix if the * observation time is different from the last call */ double t_obs = (point.xyzt.t == HUGE_VAL) ? Q->t_epoch : point.xyzt.t; if (t_obs != Q->t_obs) { Q->t_obs = t_obs; update_parameters(P); build_rot_matrix(P); } // 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 = helmert_reverse_3d(point.xyz, P); point.lpz = lpz; } /* Arcsecond to radians */ #define ARCSEC_TO_RAD (DEG_TO_RAD / 3600.0) static PJ *init_helmert_six_parameters(PJ *P) { struct pj_opaque_helmert *Q = static_cast<struct pj_opaque_helmert *>( calloc(1, sizeof(struct pj_opaque_helmert))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = (void *)Q; /* In most cases, we work on 3D cartesian coordinates */ P->left = PJ_IO_UNITS_CARTESIAN; P->right = PJ_IO_UNITS_CARTESIAN; /* Translations */ if (pj_param(P->ctx, P->params, "tx").i) Q->xyz_0.x = pj_param(P->ctx, P->params, "dx").f; if (pj_param(P->ctx, P->params, "ty").i) Q->xyz_0.y = pj_param(P->ctx, P->params, "dy").f; if (pj_param(P->ctx, P->params, "tz").i) Q->xyz_0.z = pj_param(P->ctx, P->params, "dz").f; /* Rotations */ if (pj_param(P->ctx, P->params, "trx").i) Q->opk_0.o = pj_param(P->ctx, P->params, "drx").f * ARCSEC_TO_RAD; if (pj_param(P->ctx, P->params, "try").i) Q->opk_0.p = pj_param(P->ctx, P->params, "dry").f * ARCSEC_TO_RAD; if (pj_param(P->ctx, P->params, "trz").i) Q->opk_0.k = pj_param(P->ctx, P->params, "drz").f * ARCSEC_TO_RAD; /* Use small angle approximations? */ if (pj_param(P->ctx, P->params, "bexact").i) Q->exact = 1; return P; } static PJ *read_convention(PJ *P) { struct pj_opaque_helmert *Q = (struct pj_opaque_helmert *)P->opaque; /* In case there are rotational terms, we require an explicit convention * to be provided. */ if (!Q->no_rotation) { const char *convention = pj_param(P->ctx, P->params, "sconvention").s; if (!convention) { proj_log_error(P, _("helmert: missing 'convention' argument")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (strcmp(convention, "position_vector") == 0) { Q->is_position_vector = 1; } else if (strcmp(convention, "coordinate_frame") == 0) { Q->is_position_vector = 0; } else { proj_log_error( P, _("helmert: invalid value for 'convention' argument")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* historically towgs84 in PROJ has always been using position_vector * convention. Accepting coordinate_frame would be confusing. */ if (pj_param_exists(P->params, "towgs84")) { if (!Q->is_position_vector) { proj_log_error(P, _("helmert: towgs84 should only be used with " "convention=position_vector")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } } return P; } /***********************************************************************/ PJ *PJ_TRANSFORMATION(helmert, 0) { /***********************************************************************/ struct pj_opaque_helmert *Q; if (!init_helmert_six_parameters(P)) { return nullptr; } /* In the 2D case, the coordinates are projected */ if (pj_param_exists(P->params, "theta")) { P->left = PJ_IO_UNITS_PROJECTED; P->right = PJ_IO_UNITS_PROJECTED; P->fwd = helmert_forward; P->inv = helmert_reverse; } P->fwd4d = helmert_forward_4d; P->inv4d = helmert_reverse_4d; P->fwd3d = helmert_forward_3d; P->inv3d = helmert_reverse_3d; Q = (struct pj_opaque_helmert *)P->opaque; /* Detect obsolete transpose flag and error out if found */ if (pj_param(P->ctx, P->params, "ttranspose").i) { proj_log_error(P, _("helmert: 'transpose' argument is no longer valid. " "Use convention=position_vector/coordinate_frame")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* Support the classic PROJ towgs84 parameter, but allow later overrides.*/ /* Note that if towgs84 is specified, the datum_params array is set up */ /* for us automagically by the pj_datum_set call in pj_init_ctx */ if (pj_param_exists(P->params, "towgs84")) { Q->xyz_0.x = P->datum_params[0]; Q->xyz_0.y = P->datum_params[1]; Q->xyz_0.z = P->datum_params[2]; Q->opk_0.o = P->datum_params[3]; Q->opk_0.p = P->datum_params[4]; Q->opk_0.k = P->datum_params[5]; /* We must undo conversion to absolute scale from pj_datum_set */ if (0 == P->datum_params[6]) Q->scale_0 = 0; else Q->scale_0 = (P->datum_params[6] - 1) * 1e6; } if (pj_param(P->ctx, P->params, "ttheta").i) { Q->theta_0 = pj_param(P->ctx, P->params, "dtheta").f * ARCSEC_TO_RAD; Q->fourparam = 1; Q->scale_0 = 1.0; /* default scale for the 4-param shift */ } /* Scale */ if (pj_param(P->ctx, P->params, "ts").i) { Q->scale_0 = pj_param(P->ctx, P->params, "ds").f; if (Q->scale_0 <= -1.0e6) { proj_log_error(P, _("helmert: invalid value for s.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (pj_param(P->ctx, P->params, "ttheta").i && Q->scale_0 == 0.0) { proj_log_error(P, _("helmert: invalid value for s.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } /* Translation rates */ if (pj_param(P->ctx, P->params, "tdx").i) Q->dxyz.x = pj_param(P->ctx, P->params, "ddx").f; if (pj_param(P->ctx, P->params, "tdy").i) Q->dxyz.y = pj_param(P->ctx, P->params, "ddy").f; if (pj_param(P->ctx, P->params, "tdz").i) Q->dxyz.z = pj_param(P->ctx, P->params, "ddz").f; /* Rotations rates */ if (pj_param(P->ctx, P->params, "tdrx").i) Q->dopk.o = pj_param(P->ctx, P->params, "ddrx").f * ARCSEC_TO_RAD; if (pj_param(P->ctx, P->params, "tdry").i) Q->dopk.p = pj_param(P->ctx, P->params, "ddry").f * ARCSEC_TO_RAD; if (pj_param(P->ctx, P->params, "tdrz").i) Q->dopk.k = pj_param(P->ctx, P->params, "ddrz").f * ARCSEC_TO_RAD; if (pj_param(P->ctx, P->params, "tdtheta").i) Q->dtheta = pj_param(P->ctx, P->params, "ddtheta").f * ARCSEC_TO_RAD; /* Scale rate */ if (pj_param(P->ctx, P->params, "tds").i) Q->dscale = pj_param(P->ctx, P->params, "dds").f; /* Epoch */ if (pj_param(P->ctx, P->params, "tt_epoch").i) Q->t_epoch = pj_param(P->ctx, P->params, "dt_epoch").f; Q->xyz = Q->xyz_0; Q->opk = Q->opk_0; Q->scale = Q->scale_0; Q->theta = Q->theta_0; if ((Q->opk.o == 0) && (Q->opk.p == 0) && (Q->opk.k == 0) && (Q->dopk.o == 0) && (Q->dopk.p == 0) && (Q->dopk.k == 0)) { Q->no_rotation = 1; } if (!read_convention(P)) { return nullptr; } /* Let's help with debugging */ if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_TRACE) { proj_log_trace(P, "Helmert parameters:"); proj_log_trace(P, "x= %8.5f y= %8.5f z= %8.5f", Q->xyz.x, Q->xyz.y, Q->xyz.z); proj_log_trace(P, "rx= %8.5f ry= %8.5f rz= %8.5f", Q->opk.o / ARCSEC_TO_RAD, Q->opk.p / ARCSEC_TO_RAD, Q->opk.k / ARCSEC_TO_RAD); proj_log_trace(P, "s= %8.5f exact=%d%s", Q->scale, Q->exact, Q->no_rotation ? "" : Q->is_position_vector ? " convention=position_vector" : " convention=coordinate_frame"); proj_log_trace(P, "dx= %8.5f dy= %8.5f dz= %8.5f", Q->dxyz.x, Q->dxyz.y, Q->dxyz.z); proj_log_trace(P, "drx=%8.5f dry=%8.5f drz=%8.5f", Q->dopk.o, Q->dopk.p, Q->dopk.k); proj_log_trace(P, "ds= %8.5f t_epoch=%8.5f", Q->dscale, Q->t_epoch); } update_parameters(P); build_rot_matrix(P); return P; } /***********************************************************************/ PJ *PJ_TRANSFORMATION(molobadekas, 0) { /***********************************************************************/ struct pj_opaque_helmert *Q; if (!init_helmert_six_parameters(P)) { return nullptr; } P->fwd3d = helmert_forward_3d; P->inv3d = helmert_reverse_3d; Q = (struct pj_opaque_helmert *)P->opaque; /* Scale */ if (pj_param(P->ctx, P->params, "ts").i) { Q->scale_0 = pj_param(P->ctx, P->params, "ds").f; } Q->opk = Q->opk_0; Q->scale = Q->scale_0; if (!read_convention(P)) { return nullptr; } /* Reference point */ if (pj_param(P->ctx, P->params, "tpx").i) Q->refp.x = pj_param(P->ctx, P->params, "dpx").f; if (pj_param(P->ctx, P->params, "tpy").i) Q->refp.y = pj_param(P->ctx, P->params, "dpy").f; if (pj_param(P->ctx, P->params, "tpz").i) Q->refp.z = pj_param(P->ctx, P->params, "dpz").f; /* Let's help with debugging */ if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_TRACE) { proj_log_trace(P, "Molodensky-Badekas parameters:"); proj_log_trace(P, "x= %8.5f y= %8.5f z= %8.5f", Q->xyz_0.x, Q->xyz_0.y, Q->xyz_0.z); proj_log_trace(P, "rx= %8.5f ry= %8.5f rz= %8.5f", Q->opk.o / ARCSEC_TO_RAD, Q->opk.p / ARCSEC_TO_RAD, Q->opk.k / ARCSEC_TO_RAD); proj_log_trace(P, "s= %8.5f exact=%d%s", Q->scale, Q->exact, Q->is_position_vector ? " convention=position_vector" : " convention=coordinate_frame"); proj_log_trace(P, "px= %8.5f py= %8.5f pz= %8.5f", Q->refp.x, Q->refp.y, Q->refp.z); } /* as an optimization, we incorporate the refp in the translation terms */ Q->xyz_0.x += Q->refp.x; Q->xyz_0.y += Q->refp.y; Q->xyz_0.z += Q->refp.z; Q->xyz = Q->xyz_0; build_rot_matrix(P); return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/vertoffset.cpp
/************************************************************************ * Copyright (c) 2022, 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. * ***********************************************************************/ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(vertoffset, "Vertical Offset and Slope") "\n\tTransformation" "\n\tlat_0= lon_0= dh= slope_lat= slope_lon="; namespace { // anonymous namespace struct pj_opaque_vertoffset { double slope_lon; double slope_lat; double zoff; double rho0; double nu0; }; } // anonymous namespace // Cf EPSG Dataset coordinate operation method code 1046 "Vertical Offset and // Slope" static double get_forward_offset(const PJ *P, double phi, double lam) { const struct pj_opaque_vertoffset *Q = (const struct pj_opaque_vertoffset *)P->opaque; return Q->zoff + Q->slope_lat * Q->rho0 * (phi - P->phi0) + Q->slope_lon * Q->nu0 * lam * cos(phi); } static PJ_XYZ forward_3d(PJ_LPZ lpz, PJ *P) { PJ_XYZ xyz; // We need to add lam0 (+lon_0) since it is subtracted in fwd_prepare(), // which is desirable for map projections, but not // for that method which modifies only the Z component. xyz.x = lpz.lam + P->lam0; xyz.y = lpz.phi; xyz.z = lpz.z + get_forward_offset(P, lpz.phi, lpz.lam); return xyz; } static PJ_LPZ reverse_3d(PJ_XYZ xyz, PJ *P) { PJ_LPZ lpz; // We need to subtract lam0 (+lon_0) since it is added in inv_finalize(), // which is desirable for map projections, but not // for that method which modifies only the Z component. lpz.lam = xyz.x - P->lam0; lpz.phi = xyz.y; lpz.z = xyz.z - get_forward_offset(P, lpz.phi, lpz.lam); return lpz; } /* Arcsecond to radians */ #define ARCSEC_TO_RAD (DEG_TO_RAD / 3600.0) PJ *PJ_TRANSFORMATION(vertoffset, 1) { struct pj_opaque_vertoffset *Q = static_cast<struct pj_opaque_vertoffset *>( calloc(1, sizeof(struct pj_opaque_vertoffset))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = (void *)Q; P->fwd3d = forward_3d; P->inv3d = reverse_3d; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; /* read args */ Q->slope_lon = pj_param(P->ctx, P->params, "dslope_lon").f * ARCSEC_TO_RAD; Q->slope_lat = pj_param(P->ctx, P->params, "dslope_lat").f * ARCSEC_TO_RAD; Q->zoff = pj_param(P->ctx, P->params, "ddh").f; const double sinlat0 = sin(P->phi0); const double oneMinusEsSinlat0Square = 1 - P->es * (sinlat0 * sinlat0); Q->rho0 = P->a * (1 - P->es) / (oneMinusEsSinlat0Square * sqrt(oneMinusEsSinlat0Square)); Q->nu0 = P->a / sqrt(oneMinusEsSinlat0Square); return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/molodensky.cpp
/*********************************************************************** (Abridged) Molodensky Transform Kristian Evers, 2017-07-07 ************************************************************************ Implements the (abridged) Molodensky transformations for 2D and 3D data. Primarily useful for implementation of datum shifts in transformation pipelines. The code in this file is mostly based on The Standard and Abridged Molodensky Coordinate Transformation Formulae, 2004, R.E. Deakin, http://www.mygeodesy.id.au/documents/Molodensky%20V2.pdf ************************************************************************ * 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 "proj.h" #include "proj_internal.h" PROJ_HEAD(molodensky, "Molodensky transform"); static PJ_XYZ pj_molodensky_forward_3d(PJ_LPZ lpz, PJ *P); static PJ_LPZ pj_molodensky_reverse_3d(PJ_XYZ xyz, PJ *P); namespace { // anonymous namespace struct pj_opaque_molodensky { double dx; double dy; double dz; double da; double df; int abridged; }; } // anonymous namespace static double RN(double a, double es, double phi) { /********************************************************** N(phi) - prime vertical radius of curvature ------------------------------------------- This is basically the same function as in PJ_cart.c should probably be refactored into it's own file at some point. **********************************************************/ double s = sin(phi); if (es == 0) return a; return a / sqrt(1 - es * s * s); } static double RM(double a, double es, double phi) { /********************************************************** M(phi) - Meridian radius of curvature ------------------------------------- Source: E.J Krakiwsky & D.B. Thomson, 1974, GEODETIC POSITION COMPUTATIONS, Fredericton NB, Canada: University of New Brunswick, Department of Geodesy and Geomatics Engineering, Lecture Notes No. 39, 99 pp. http://www2.unb.ca/gge/Pubs/LN39.pdf **********************************************************/ double s = sin(phi); if (es == 0) return a; /* eq. 13a */ if (phi == 0) return a * (1 - es); /* eq. 13b */ if (fabs(phi) == M_PI_2) return a / sqrt(1 - es); /* eq. 13 */ return (a * (1 - es)) / pow(1 - es * s * s, 1.5); } static PJ_LPZ calc_standard_params(PJ_LPZ lpz, PJ *P) { struct pj_opaque_molodensky *Q = (struct pj_opaque_molodensky *)P->opaque; double dphi, dlam, dh; /* sines and cosines */ double slam = sin(lpz.lam); double clam = cos(lpz.lam); double sphi = sin(lpz.phi); double cphi = cos(lpz.phi); /* ellipsoid parameters and differences */ double f = P->f, a = P->a; double dx = Q->dx, dy = Q->dy, dz = Q->dz; double da = Q->da, df = Q->df; /* ellipsoid radii of curvature */ double rho = RM(a, P->es, lpz.phi); double nu = RN(a, P->es, lpz.phi); /* delta phi */ dphi = (-dx * sphi * clam) - (dy * sphi * slam) + (dz * cphi) + ((nu * P->es * sphi * cphi * da) / a) + (sphi * cphi * (rho / (1 - f) + nu * (1 - f)) * df); const double dphi_denom = rho + lpz.z; if (dphi_denom == 0.0) { lpz.lam = HUGE_VAL; return lpz; } dphi /= dphi_denom; /* delta lambda */ const double dlam_denom = (nu + lpz.z) * cphi; if (dlam_denom == 0.0) { lpz.lam = HUGE_VAL; return lpz; } dlam = (-dx * slam + dy * clam) / dlam_denom; /* delta h */ dh = dx * cphi * clam + dy * cphi * slam + dz * sphi - (a / nu) * da + nu * (1 - f) * sphi * sphi * df; lpz.phi = dphi; lpz.lam = dlam; lpz.z = dh; return lpz; } static PJ_LPZ calc_abridged_params(PJ_LPZ lpz, PJ *P) { struct pj_opaque_molodensky *Q = (struct pj_opaque_molodensky *)P->opaque; double dphi, dlam, dh; /* sines and cosines */ double slam = sin(lpz.lam); double clam = cos(lpz.lam); double sphi = sin(lpz.phi); double cphi = cos(lpz.phi); /* ellipsoid parameters and differences */ double dx = Q->dx, dy = Q->dy, dz = Q->dz; double da = Q->da, df = Q->df; double adffda = (P->a * df + P->f * da); /* delta phi */ dphi = -dx * sphi * clam - dy * sphi * slam + dz * cphi + adffda * sin(2 * lpz.phi); dphi /= RM(P->a, P->es, lpz.phi); /* delta lambda */ dlam = -dx * slam + dy * clam; const double dlam_denom = RN(P->a, P->es, lpz.phi) * cphi; if (dlam_denom == 0.0) { lpz.lam = HUGE_VAL; return lpz; } dlam /= dlam_denom; /* delta h */ dh = dx * cphi * clam + dy * cphi * slam + dz * sphi - da + adffda * sphi * sphi; /* offset coordinate */ lpz.phi = dphi; lpz.lam = dlam; lpz.z = dh; return lpz; } static PJ_XY pj_molodensky_forward_2d(PJ_LP lp, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.lp = lp; // 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 = pj_molodensky_forward_3d(point.lpz, P); point.xyz = xyz; return point.xy; } static PJ_LP pj_molodensky_reverse_2d(PJ_XY xy, PJ *P) { PJ_COORD point = {{0, 0, 0, 0}}; point.xy = xy; point.xyz.z = 0; // 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 = pj_molodensky_reverse_3d(point.xyz, P); point.lpz = lpz; return point.lp; } static PJ_XYZ pj_molodensky_forward_3d(PJ_LPZ lpz, PJ *P) { struct pj_opaque_molodensky *Q = (struct pj_opaque_molodensky *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; point.lpz = lpz; /* calculate parameters depending on the mode we are in */ if (Q->abridged) { lpz = calc_abridged_params(lpz, P); } else { lpz = calc_standard_params(lpz, P); } if (lpz.lam == HUGE_VAL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xyz; } /* offset coordinate */ point.lpz.phi += lpz.phi; point.lpz.lam += lpz.lam; point.lpz.z += lpz.z; return point.xyz; } static void pj_molodensky_forward_4d(PJ_COORD &obs, PJ *P) { // 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 = pj_molodensky_forward_3d(obs.lpz, P); obs.xyz = xyz; } static PJ_LPZ pj_molodensky_reverse_3d(PJ_XYZ xyz, PJ *P) { struct pj_opaque_molodensky *Q = (struct pj_opaque_molodensky *)P->opaque; PJ_COORD point = {{0, 0, 0, 0}}; PJ_LPZ lpz; /* calculate parameters depending on the mode we are in */ point.xyz = xyz; if (Q->abridged) lpz = calc_abridged_params(point.lpz, P); else lpz = calc_standard_params(point.lpz, P); if (lpz.lam == HUGE_VAL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().lpz; } /* offset coordinate */ point.lpz.phi -= lpz.phi; point.lpz.lam -= lpz.lam; point.lpz.z -= lpz.z; return point.lpz; } static void pj_molodensky_reverse_4d(PJ_COORD &obs, PJ *P) { // 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 = pj_molodensky_reverse_3d(obs.xyz, P); obs.lpz = lpz; } PJ *PJ_TRANSFORMATION(molodensky, 1) { struct pj_opaque_molodensky *Q = static_cast<struct pj_opaque_molodensky *>( calloc(1, sizeof(struct pj_opaque_molodensky))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = (void *)Q; P->fwd4d = pj_molodensky_forward_4d; P->inv4d = pj_molodensky_reverse_4d; P->fwd3d = pj_molodensky_forward_3d; P->inv3d = pj_molodensky_reverse_3d; P->fwd = pj_molodensky_forward_2d; P->inv = pj_molodensky_reverse_2d; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; /* read args */ if (!pj_param(P->ctx, P->params, "tdx").i) { proj_log_error(P, _("missing dx")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->dx = pj_param(P->ctx, P->params, "ddx").f; if (!pj_param(P->ctx, P->params, "tdy").i) { proj_log_error(P, _("missing dy")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->dy = pj_param(P->ctx, P->params, "ddy").f; if (!pj_param(P->ctx, P->params, "tdz").i) { proj_log_error(P, _("missing dz")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->dz = pj_param(P->ctx, P->params, "ddz").f; if (!pj_param(P->ctx, P->params, "tda").i) { proj_log_error(P, _("missing da")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->da = pj_param(P->ctx, P->params, "dda").f; if (!pj_param(P->ctx, P->params, "tdf").i) { proj_log_error(P, _("missing df")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->df = pj_param(P->ctx, P->params, "ddf").f; Q->abridged = pj_param(P->ctx, P->params, "tabridged").i; return P; }
cpp
PROJ
data/projects/PROJ/src/transformations/hgridshift.cpp
#include <errno.h> #include <mutex> #include <stddef.h> #include <string.h> #include <time.h> #include "grids.hpp" #include "proj_internal.h" PROJ_HEAD(hgridshift, "Horizontal grid shift"); static std::mutex gMutexHGridShift{}; static std::set<std::string> gKnownGridsHGridShift{}; using namespace NS_PROJ; namespace { // anonymous namespace struct hgridshiftData { double t_final = 0; double t_epoch = 0; ListOfHGrids grids{}; bool defer_grid_opening = false; }; } // anonymous namespace static PJ_XYZ pj_hgridshift_forward_3d(PJ_LPZ lpz, PJ *P) { auto Q = static_cast<hgridshiftData *>(P->opaque); PJ_COORD point = {{0, 0, 0, 0}}; point.lpz = lpz; if (Q->defer_grid_opening) { Q->defer_grid_opening = false; Q->grids = pj_hgrid_init(P, "grids"); if (proj_errno(P)) { return proj_coord_error().xyz; } } if (!Q->grids.empty()) { /* Only try the gridshift if at least one grid is loaded, * otherwise just pass the coordinate through unchanged. */ point.lp = pj_hgrid_apply(P->ctx, Q->grids, point.lp, PJ_FWD); } return point.xyz; } static PJ_LPZ pj_hgridshift_reverse_3d(PJ_XYZ xyz, PJ *P) { auto Q = static_cast<hgridshiftData *>(P->opaque); PJ_COORD point = {{0, 0, 0, 0}}; point.xyz = xyz; if (Q->defer_grid_opening) { Q->defer_grid_opening = false; Q->grids = pj_hgrid_init(P, "grids"); if (proj_errno(P)) { return proj_coord_error().lpz; } } if (!Q->grids.empty()) { /* Only try the gridshift if at least one grid is loaded, * otherwise just pass the coordinate through unchanged. */ point.lp = pj_hgrid_apply(P->ctx, Q->grids, point.lp, PJ_INV); } return point.lpz; } static void pj_hgridshift_forward_4d(PJ_COORD &coo, PJ *P) { struct hgridshiftData *Q = (struct hgridshiftData *)P->opaque; /* If transformation is not time restricted, we always call it */ if (Q->t_final == 0 || Q->t_epoch == 0) { // 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 = pj_hgridshift_forward_3d(coo.lpz, P); coo.xyz = xyz; return; } /* Time restricted - only apply transform if within time bracket */ if (coo.lpzt.t < Q->t_epoch && Q->t_final > Q->t_epoch) { // 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 = pj_hgridshift_forward_3d(coo.lpz, P); coo.xyz = xyz; } } static void pj_hgridshift_reverse_4d(PJ_COORD &coo, PJ *P) { struct hgridshiftData *Q = (struct hgridshiftData *)P->opaque; /* If transformation is not time restricted, we always call it */ if (Q->t_final == 0 || Q->t_epoch == 0) { // 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 = pj_hgridshift_reverse_3d(coo.xyz, P); coo.lpz = lpz; return; } /* Time restricted - only apply transform if within time bracket */ if (coo.lpzt.t < Q->t_epoch && Q->t_final > Q->t_epoch) { // 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 = pj_hgridshift_reverse_3d(coo.xyz, P); coo.lpz = lpz; } } static PJ *pj_hgridshift_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; delete static_cast<struct hgridshiftData *>(P->opaque); P->opaque = nullptr; return pj_default_destructor(P, errlev); } static void pj_hgridshift_reassign_context(PJ *P, PJ_CONTEXT *ctx) { auto Q = (struct hgridshiftData *)P->opaque; for (auto &grid : Q->grids) { grid->reassign_context(ctx); } } PJ *PJ_TRANSFORMATION(hgridshift, 0) { auto Q = new hgridshiftData; P->opaque = (void *)Q; P->destructor = pj_hgridshift_destructor; P->reassign_context = pj_hgridshift_reassign_context; P->fwd4d = pj_hgridshift_forward_4d; P->inv4d = pj_hgridshift_reverse_4d; P->fwd3d = pj_hgridshift_forward_3d; P->inv3d = pj_hgridshift_reverse_3d; P->fwd = nullptr; P->inv = nullptr; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; if (0 == pj_param(P->ctx, P->params, "tgrids").i) { proj_log_error(P, _("+grids parameter missing.")); return pj_hgridshift_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } /* TODO: Refactor into shared function that can be used */ /* by both vgridshift and hgridshift */ if (pj_param(P->ctx, P->params, "tt_final").i) { Q->t_final = pj_param(P->ctx, P->params, "dt_final").f; if (Q->t_final == 0) { /* a number wasn't passed to +t_final, let's see if it was "now" */ /* and set the time accordingly. */ if (!strcmp("now", pj_param(P->ctx, P->params, "st_final").s)) { time_t now; struct tm *date; time(&now); date = localtime(&now); Q->t_final = 1900.0 + date->tm_year + date->tm_yday / 365.0; } } } if (pj_param(P->ctx, P->params, "tt_epoch").i) Q->t_epoch = pj_param(P->ctx, P->params, "dt_epoch").f; if (P->ctx->defer_grid_opening) { Q->defer_grid_opening = true; } else { const char *gridnames = pj_param(P->ctx, P->params, "sgrids").s; gMutexHGridShift.lock(); const bool isKnownGrid = gKnownGridsHGridShift.find(gridnames) != gKnownGridsHGridShift.end(); gMutexHGridShift.unlock(); if (isKnownGrid) { Q->defer_grid_opening = true; } else { Q->grids = pj_hgrid_init(P, "grids"); /* Was gridlist compiled properly? */ if (proj_errno(P)) { proj_log_error(P, _("could not find required grid(s).")); return pj_hgridshift_destructor( P, PROJ_ERR_INVALID_OP_FILE_NOT_FOUND_OR_INVALID); } gMutexHGridShift.lock(); gKnownGridsHGridShift.insert(gridnames); gMutexHGridShift.unlock(); } } return P; } void pj_clear_hgridshift_knowngrids_cache() { std::lock_guard<std::mutex> lock(gMutexHGridShift); gKnownGridsHGridShift.clear(); }
cpp
PROJ
data/projects/PROJ/src/transformations/tinshift_exceptions.hpp
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to TIN based transformations * 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. *****************************************************************************/ #ifndef TINSHIFT_NAMESPACE #error "Should be included only by tinshift.hpp" #endif #include <exception> namespace TINSHIFT_NAMESPACE { // --------------------------------------------------------------------------- /** Parsing exception. */ class ParsingException : public std::exception { public: explicit ParsingException(const std::string &msg) : msg_(msg) {} const char *what() const noexcept override; private: std::string msg_; }; const char *ParsingException::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- } // namespace TINSHIFT_NAMESPACE
hpp
PROJ
data/projects/PROJ/src/tests/multistresstest.cpp
/****************************************************************************** * * Project: PROJ.4 * Purpose: Mainline program to stress test multithreaded PROJ.4 processing. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2010, 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. *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proj.h" #ifdef _WIN32 #include <windows.h> #else #include <pthread.h> #include <unistd.h> #endif #define num_threads 10 static int num_iterations = 1000000; static int reinit_every_iteration = 0; typedef struct { const char *src_def; const char *dst_def; PJ_COORD src; PJ_COORD dst; int dst_error; int skip; } TestItem; static TestItem test_list[] = { {"+proj=utm +zone=11 +datum=WGS84", "+proj=latlong +datum=WGS84", proj_coord(150000.0, 3000000.0, 0.0, 0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=utm +zone=11 +datum=NAD83", "+proj=latlong +datum=NAD27", proj_coord(150000.0, 3000000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=utm +zone=11 +datum=NAD83", "+proj=latlong +nadgrids=@null +ellps=WGS84", proj_coord(150000.0, 3000000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=utm +zone=11 +datum=WGS84", "+proj=merc +datum=potsdam", proj_coord(150000.0, 3000000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=latlong +nadgrids=nzgd2kgrid0005.gsb", "+proj=latlong +datum=WGS84", proj_coord(150000.0, 3000000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=latlong +nadgrids=nzgd2kgrid0005.gsb", "+proj=latlong +datum=WGS84", proj_coord(170, -40, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=latlong +ellps=GRS80 +towgs84=2,3,5", "+proj=latlong +ellps=intl +towgs84=10,12,15", proj_coord(170, -40, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=eqc +lat_0=11 +lon_0=12 +x_0=100000 +y_0=200000 +datum=WGS84 ", "+proj=stere +lat_0=11 +lon_0=12 +x_0=100000 +y_0=200000 +datum=WGS84 ", proj_coord(150000.0, 250000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=cea +lat_ts=11 +lon_0=12 +y_0=200000 +datum=WGS84 ", "+proj=merc +lon_0=12 +k=0.999 +x_0=100000 +y_0=200000 +datum=WGS84 ", proj_coord(150000.0, 250000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=bonne +lat_1=11 +lon_0=12 +y_0=200000 +datum=WGS84 ", "+proj=cass +lat_0=11 +lon_0=12 +x_0=100000 +y_0=200000 +datum=WGS84 ", proj_coord(150000.0, 250000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=nzmg +lat_0=11 +lon_0=12 +y_0=200000 +datum=WGS84 ", "+proj=gnom +lat_0=11 +lon_0=12 +x_0=100000 +y_0=200000 +datum=WGS84 ", proj_coord(150000.0, 250000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=ortho +lat_0=11 +lon_0=12 +y_0=200000 +datum=WGS84 ", "+proj=laea +lat_0=11 +lon_0=12 +x_0=100000 +y_0=200000 +datum=WGS84 ", proj_coord(150000.0, 250000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=aeqd +lat_0=11 +lon_0=12 +y_0=200000 +datum=WGS84 ", "+proj=eqdc +lat_1=20 +lat_2=5 +lat_0=11 +lon_0=12 +x_0=100000 " "+y_0=200000 +datum=WGS84 ", proj_coord(150000.0, 250000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+proj=mill +lat_0=11 +lon_0=12 +y_0=200000 +datum=WGS84 ", "+proj=moll +lon_0=12 +x_0=100000 +y_0=200000 +datum=WGS84 ", proj_coord(150000.0, 250000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {"+init=epsg:3309", "+init=epsg:4326", proj_coord(150000.0, 30000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}, {/* Bad projection (invalid ellipsoid parameter +R_A=0) */ "+proj=utm +zone=11 +datum=WGS84", "+proj=merc +datum=potsdam +R_A=0", proj_coord(150000.0, 3000000.0, 0.0, 0.0), proj_coord(0.0, 0.0, 0.0, 0.0), 0, 0}}; static volatile int active_thread_count = 0; /************************************************************************/ /* TestThread() */ /************************************************************************/ static void TestThread() { int i, test_count = sizeof(test_list) / sizeof(TestItem); int repeat_count = num_iterations; int i_iter; /* -------------------------------------------------------------------- */ /* Initialize coordinate system definitions. */ /* -------------------------------------------------------------------- */ PJ **pj_list; PJ_CONTEXT *ctx = proj_context_create(); pj_list = (PJ **)calloc(test_count, sizeof(PJ *)); if (!reinit_every_iteration) { for (i = 0; i < test_count; i++) { TestItem *test = test_list + i; pj_list[i] = proj_create_crs_to_crs(ctx, test->src_def, test->dst_def, nullptr); } } /* -------------------------------------------------------------------- */ /* Perform tests - over and over. */ /* -------------------------------------------------------------------- */ for (i_iter = 0; i_iter < repeat_count; i_iter++) { for (i = 0; i < test_count; i++) { TestItem *test = test_list + i; if (reinit_every_iteration) { proj_context_use_proj4_init_rules(nullptr, true); pj_list[i] = proj_create_crs_to_crs(ctx, test->src_def, test->dst_def, nullptr); { int skipTest = (pj_list[i] == nullptr); if (skipTest != test->skip) fprintf( stderr, "Threaded projection initialization does not match " "unthreaded initialization\n"); if (skipTest) { proj_destroy(pj_list[i]); continue; } } } if (test->skip) continue; PJ_COORD out = proj_trans(pj_list[i], PJ_FWD, test->src); int error = proj_errno(pj_list[i]); if (error != test->dst_error) { fprintf(stderr, "Got error %d, expected %d\n", error, test->dst_error); } proj_errno_reset(pj_list[i]); if (out.xyz.x != test->dst.xyz.x || out.xyz.y != test->dst.xyz.y || out.xyz.z != test->dst.xyz.z) // if( x != test->dst_x || y != test->dst_y || z != test->dst_z ) { fprintf(stderr, "Got %.15g,%.15g,%.15g\n" "Expected %.15g,%.15g,%.15g\n" "Diff %.15g,%.15g,%.15g\n", out.xyz.x, out.xyz.y, out.xyz.z, test->dst.xyz.x, test->dst.xyz.y, test->dst.xyz.z, out.xyz.x - test->dst.xyz.x, out.xyz.y - test->dst.xyz.y, out.xyz.z - test->dst.xyz.z); } if (reinit_every_iteration) { proj_destroy(pj_list[i]); } } } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ if (!reinit_every_iteration) { for (i = 0; i < test_count; i++) { proj_destroy(pj_list[i]); } } free(pj_list); proj_context_destroy(ctx); printf("%d iterations of the %d tests complete in thread X\n", repeat_count, test_count); active_thread_count--; } #ifdef _WIN32 /************************************************************************/ /* WinTestThread() */ /************************************************************************/ static DWORD WINAPI WinTestThread(LPVOID lpParameter) { TestThread(); return 0; } #else /************************************************************************/ /* PosixTestThread() */ /************************************************************************/ static void *PosixTestThread(void *pData) { (void)pData; TestThread(); return nullptr; } #endif /************************************************************************/ /* main() */ /************************************************************************/ #ifdef _WIN32 static DWORD WINAPI do_main(LPVOID unused) #else static int do_main(void) #endif { /* -------------------------------------------------------------------- */ /* Our first pass is to establish the correct answers for all */ /* the tests. */ /* -------------------------------------------------------------------- */ int i, test_count = sizeof(test_list) / sizeof(TestItem); for (i = 0; i < test_count; i++) { TestItem *test = test_list + i; PJ *pj; proj_context_use_proj4_init_rules(nullptr, true); pj = proj_create_crs_to_crs(nullptr, test->src_def, test->dst_def, nullptr); if (pj == nullptr) { printf("Unable to translate:\n%s\n or\n%s\n", test->src_def, test->dst_def); test->skip = 1; proj_destroy(pj); continue; } PJ_COORD out = proj_trans(pj, PJ_FWD, test->src); test->dst = out; test->dst_error = proj_errno(pj); proj_destroy(pj); test->skip = 0; #ifdef nodef printf("Test %d - output %.14g,%.14g,%g\n", i, test->dst.xyz.x, test->dst.xyz.y, test->dst.xyz.z); #endif } printf("%d tests initialized.\n", test_count); /* -------------------------------------------------------------------- */ /* Now launch a bunch of threads to repeat the tests. */ /* -------------------------------------------------------------------- */ #ifdef _WIN32 { // Scoped to workaround lack of c99 support in VS HANDLE ahThread[num_threads]; for (i = 0; i < num_threads; i++) { active_thread_count++; ahThread[i] = CreateThread(NULL, 0, WinTestThread, NULL, 0, NULL); if (ahThread[i] == 0) { printf("Thread creation failed."); return 1; } } printf("%d test threads launched.\n", num_threads); WaitForMultipleObjects(num_threads, ahThread, TRUE, INFINITE); } #else { pthread_t ahThread[num_threads]; pthread_attr_t hThreadAttr; pthread_attr_init(&hThreadAttr); pthread_attr_setdetachstate(&hThreadAttr, PTHREAD_CREATE_DETACHED); for (i = 0; i < num_threads; i++) { active_thread_count++; pthread_create(&(ahThread[i]), &hThreadAttr, PosixTestThread, nullptr); } printf("%d test threads launched.\n", num_threads); while (active_thread_count > 0) sleep(1); } #endif printf("all tests complete.\n"); return 0; } int main(int argc, char **argv) { int i; for (i = 0; i < argc; i++) { if (strcmp(argv[i], "-reinit") == 0) reinit_every_iteration = 1; else if (strcmp(argv[i], "-num_iterations") == 0 && i + 1 < argc) { num_iterations = atoi(argv[i + 1]); i++; } } #ifdef _WIN32 /* This is an incredible weirdness but with mingw cross-compiler */ /* 1. - b/a; where double a = 6378206.4; and double b = 6356583.8; */ /* does not evaluate the same in the main thread or in a thread forked */ /* by CreateThread(), so run the main in a thread... */ { HANDLE thread = CreateThread(NULL, 0, do_main, NULL, 0, NULL); WaitForSingleObject(thread, INFINITE); CloseHandle(thread); } #else do_main(); #endif return 0; }
cpp
PROJ
data/projects/PROJ/src/tests/geodtest.c
/** * \file geodtest.c * \brief Test suite for the geodesic routines in C * * Run these tests by configuring with cmake and running "make test". * * Copyright (c) Charles Karney (2015-2022) <[email protected]> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ #include "geodesic.h" #include <stdio.h> #include <math.h> #if defined(_MSC_VER) /* Squelch warnings about assignment within conditional expression */ # pragma warning (disable: 4706) #endif #if !defined(__cplusplus) #define nullptr 0 #endif static const double wgs84_a = 6378137, wgs84_f = 1/298.257223563; /* WGS84 */ static int checkEquals(double x, double y, double d) { if (fabs(x - y) <= d) return 0; printf("checkEquals fails: %.7g != %.7g +/- %.7g\n", x, y, d); return 1; } static int checkNaN(double x) { /* cppcheck-suppress duplicateExpression */ if (isnan(x)) return 0; printf("checkNaN fails: %.7g\n", x); return 1; } static const int ncases = 20; static const double testcases[20][12] = { {35.60777, -139.44815, 111.098748429560326, -11.17491, -69.95921, 129.289270889708762, 8935244.5604818305, 80.50729714281974, 6273170.2055303837, 0.16606318447386067, 0.16479116945612937, 12841384694976.432}, {55.52454, 106.05087, 22.020059880982801, 77.03196, 197.18234, 109.112041110671519, 4105086.1713924406, 36.892740690445894, 3828869.3344387607, 0.80076349608092607, 0.80101006984201008, 61674961290615.615}, {-21.97856, 142.59065, -32.44456876433189, 41.84138, 98.56635, -41.84359951440466, 8394328.894657671, 75.62930491011522, 6161154.5773110616, 0.24816339233950381, 0.24930251203627892, -6637997720646.717}, {-66.99028, 112.2363, 173.73491240878403, -12.70631, 285.90344, 2.512956620913668, 11150344.2312080241, 100.278634181155759, 6289939.5670446687, -0.17199490274700385, -0.17722569526345708, -121287239862139.744}, {-17.42761, 173.34268, -159.033557661192928, -15.84784, 5.93557, -20.787484651536988, 16076603.1631180673, 144.640108810286253, 3732902.1583877189, -0.81273638700070476, -0.81299800519154474, 97825992354058.708}, {32.84994, 48.28919, 150.492927788121982, -56.28556, 202.29132, 48.113449399816759, 16727068.9438164461, 150.565799985466607, 3147838.1910180939, -0.87334918086923126, -0.86505036767110637, -72445258525585.010}, {6.96833, 52.74123, 92.581585386317712, -7.39675, 206.17291, 90.721692165923907, 17102477.2496958388, 154.147366239113561, 2772035.6169917581, -0.89991282520302447, -0.89986892177110739, -1311796973197.995}, {-50.56724, -16.30485, -105.439679907590164, -33.56571, -94.97412, -47.348547835650331, 6455670.5118668696, 58.083719495371259, 5409150.7979815838, 0.53053508035997263, 0.52988722644436602, 41071447902810.047}, {-58.93002, -8.90775, 140.965397902500679, -8.91104, 133.13503, 19.255429433416599, 11756066.0219864627, 105.755691241406877, 6151101.2270708536, -0.26548622269867183, -0.27068483874510741, -86143460552774.735}, {-68.82867, -74.28391, 93.774347763114881, -50.63005, -8.36685, 34.65564085411343, 3956936.926063544, 35.572254987389284, 3708890.9544062657, 0.81443963736383502, 0.81420859815358342, -41845309450093.787}, {-10.62672, -32.0898, -86.426713286747751, 5.883, -134.31681, -80.473780971034875, 11470869.3864563009, 103.387395634504061, 6184411.6622659713, -0.23138683500430237, -0.23155097622286792, 4198803992123.548}, {-21.76221, 166.90563, 29.319421206936428, 48.72884, 213.97627, 43.508671946410168, 9098627.3986554915, 81.963476716121964, 6299240.9166992283, 0.13965943368590333, 0.14152969707656796, 10024709850277.476}, {-19.79938, -174.47484, 71.167275780171533, -11.99349, -154.35109, 65.589099775199228, 2319004.8601169389, 20.896611684802389, 2267960.8703918325, 0.93427001867125849, 0.93424887135032789, -3935477535005.785}, {-11.95887, -116.94513, 92.712619830452549, 4.57352, 7.16501, 78.64960934409585, 13834722.5801401374, 124.688684161089762, 5228093.177931598, -0.56879356755666463, -0.56918731952397221, -9919582785894.853}, {-87.85331, 85.66836, -65.120313040242748, 66.48646, 16.09921, -4.888658719272296, 17286615.3147144645, 155.58592449699137, 2635887.4729110181, -0.90697975771398578, -0.91095608883042767, 42667211366919.534}, {1.74708, 128.32011, -101.584843631173858, -11.16617, 11.87109, -86.325793296437476, 12942901.1241347408, 116.650512484301857, 5682744.8413270572, -0.44857868222697644, -0.44824490340007729, 10763055294345.653}, {-25.72959, -144.90758, -153.647468693117198, -57.70581, -269.17879, -48.343983158876487, 9413446.7452453107, 84.664533838404295, 6356176.6898881281, 0.09492245755254703, 0.09737058264766572, 74515122850712.444}, {-41.22777, 122.32875, 14.285113402275739, -7.57291, 130.37946, 10.805303085187369, 3812686.035106021, 34.34330804743883, 3588703.8812128856, 0.82605222593217889, 0.82572158200920196, -2456961531057.857}, {11.01307, 138.25278, 79.43682622782374, 6.62726, 247.05981, 103.708090215522657, 11911190.819018408, 107.341669954114577, 6070904.722786735, -0.29767608923657404, -0.29785143390252321, 17121631423099.696}, {-29.47124, 95.14681, -163.779130441688382, -27.46601, -69.15955, -15.909335945554969, 13487015.8381145492, 121.294026715742277, 5481428.9945736388, -0.51527225545373252, -0.51556587964721788, 104679964020340.318}}; static int testinverse() { double lat1, lon1, azi1, lat2, lon2, azi2, s12, a12, m12, M12, M21, S12; double azi1a, azi2a, s12a, a12a, m12a, M12a, M21a, S12a; struct geod_geodesic g; int i, result = 0; geod_init(&g, wgs84_a, wgs84_f); for (i = 0; i < ncases; ++i) { lat1 = testcases[i][0]; lon1 = testcases[i][1]; azi1 = testcases[i][2]; lat2 = testcases[i][3]; lon2 = testcases[i][4]; azi2 = testcases[i][5]; s12 = testcases[i][6]; a12 = testcases[i][7]; m12 = testcases[i][8]; M12 = testcases[i][9]; M21 = testcases[i][10]; S12 = testcases[i][11]; a12a = geod_geninverse(&g, lat1, lon1, lat2, lon2, &s12a, &azi1a, &azi2a, &m12a, &M12a, &M21a, &S12a); result += checkEquals(azi1, azi1a, 1e-13); result += checkEquals(azi2, azi2a, 1e-13); result += checkEquals(s12, s12a, 1e-8); result += checkEquals(a12, a12a, 1e-13); result += checkEquals(m12, m12a, 1e-8); result += checkEquals(M12, M12a, 1e-15); result += checkEquals(M21, M21a, 1e-15); result += checkEquals(S12, S12a, 0.1); } return result; } static int testdirect() { double lat1, lon1, azi1, lat2, lon2, azi2, s12, a12, m12, M12, M21, S12; double lat2a, lon2a, azi2a, s12a, a12a, m12a, M12a, M21a, S12a; struct geod_geodesic g; int i, result = 0; unsigned flags = GEOD_LONG_UNROLL; geod_init(&g, wgs84_a, wgs84_f); for (i = 0; i < ncases; ++i) { lat1 = testcases[i][0]; lon1 = testcases[i][1]; azi1 = testcases[i][2]; lat2 = testcases[i][3]; lon2 = testcases[i][4]; azi2 = testcases[i][5]; s12 = testcases[i][6]; a12 = testcases[i][7]; m12 = testcases[i][8]; M12 = testcases[i][9]; M21 = testcases[i][10]; S12 = testcases[i][11]; a12a = geod_gendirect(&g, lat1, lon1, azi1, flags, s12, &lat2a, &lon2a, &azi2a, &s12a, &m12a, &M12a, &M21a, &S12a); result += checkEquals(lat2, lat2a, 1e-13); result += checkEquals(lon2, lon2a, 1e-13); result += checkEquals(azi2, azi2a, 1e-13); result += checkEquals(s12, s12a, 0); result += checkEquals(a12, a12a, 1e-13); result += checkEquals(m12, m12a, 1e-8); result += checkEquals(M12, M12a, 1e-15); result += checkEquals(M21, M21a, 1e-15); result += checkEquals(S12, S12a, 0.1); } return result; } static int testarcdirect() { double lat1, lon1, azi1, lat2, lon2, azi2, s12, a12, m12, M12, M21, S12; double lat2a, lon2a, azi2a, s12a, a12a, m12a, M12a, M21a, S12a; struct geod_geodesic g; int i, result = 0; unsigned flags = GEOD_ARCMODE | GEOD_LONG_UNROLL; geod_init(&g, wgs84_a, wgs84_f); for (i = 0; i < ncases; ++i) { lat1 = testcases[i][0]; lon1 = testcases[i][1]; azi1 = testcases[i][2]; lat2 = testcases[i][3]; lon2 = testcases[i][4]; azi2 = testcases[i][5]; s12 = testcases[i][6]; a12 = testcases[i][7]; m12 = testcases[i][8]; M12 = testcases[i][9]; M21 = testcases[i][10]; S12 = testcases[i][11]; a12a = geod_gendirect(&g, lat1, lon1, azi1, flags, a12, &lat2a, &lon2a, &azi2a, &s12a, &m12a, &M12a, &M21a, &S12a); result += checkEquals(lat2, lat2a, 1e-13); result += checkEquals(lon2, lon2a, 1e-13); result += checkEquals(azi2, azi2a, 1e-13); result += checkEquals(s12, s12a, 1e-8); result += checkEquals(a12, a12a, 0); result += checkEquals(s12, s12a, 1e-8); result += checkEquals(m12, m12a, 1e-8); result += checkEquals(M12, M12a, 1e-15); result += checkEquals(M21, M21a, 1e-15); result += checkEquals(S12, S12a, 0.1); } return result; } static int GeodSolve0() { double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 40.6, -73.8, 49.01666667, 2.55, &s12, &azi1, &azi2); result += checkEquals(azi1, 53.47022, 0.5e-5); result += checkEquals(azi2, 111.59367, 0.5e-5); result += checkEquals(s12, 5853226, 0.5); return result; } static int GeodSolve1() { double lat2, lon2, azi2; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_direct(&g, 40.63972222, -73.77888889, 53.5, 5850e3, &lat2, &lon2, &azi2); result += checkEquals(lat2, 49.01467, 0.5e-5); result += checkEquals(lon2, 2.56106, 0.5e-5); result += checkEquals(azi2, 111.62947, 0.5e-5); return result; } static int GeodSolve2() { /* Check fix for antipodal prolate bug found 2010-09-04 */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, 6.4e6, -1/150.0); geod_inverse(&g, 0.07476, 0, -0.07476, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 90.00078, 0.5e-5); result += checkEquals(azi2, 90.00078, 0.5e-5); result += checkEquals(s12, 20106193, 0.5); geod_inverse(&g, 0.1, 0, -0.1, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 90.00105, 0.5e-5); result += checkEquals(azi2, 90.00105, 0.5e-5); result += checkEquals(s12, 20106193, 0.5); return result; } static int GeodSolve4() { /* Check fix for short line bug found 2010-05-21 */ double s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 36.493349428792, 0, 36.49334942879201, .0000008, &s12, nullptr, nullptr); result += checkEquals(s12, 0.072, 0.5e-3); return result; } static int GeodSolve5() { /* Check fix for point2=pole bug found 2010-05-03 */ double lat2, lon2, azi2; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_direct(&g, 0.01777745589997, 30, 0, 10e6, &lat2, &lon2, &azi2); result += checkEquals(lat2, 90, 0.5e-5); if (lon2 < 0) { result += checkEquals(lon2, -150, 0.5e-5); result += checkEquals(fabs(azi2), 180, 0.5e-5); } else { result += checkEquals(lon2, 30, 0.5e-5); result += checkEquals(azi2, 0, 0.5e-5); } return result; } static int GeodSolve6() { /* Check fix for volatile sbet12a bug found 2011-06-25 (gcc 4.4.4 * x86 -O3). Found again on 2012-03-27 with tdm-mingw32 (g++ 4.6.1). */ double s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 88.202499451857, 0, -88.202499451857, 179.981022032992859592, &s12, nullptr, nullptr); result += checkEquals(s12, 20003898.214, 0.5e-3); geod_inverse(&g, 89.262080389218, 0, -89.262080389218, 179.992207982775375662, &s12, nullptr, nullptr); result += checkEquals(s12, 20003925.854, 0.5e-3); geod_inverse(&g, 89.333123580033, 0, -89.333123580032997687, 179.99295812360148422, &s12, nullptr, nullptr); result += checkEquals(s12, 20003926.881, 0.5e-3); return result; } static int GeodSolve9() { /* Check fix for volatile x bug found 2011-06-25 (gcc 4.4.4 x86 -O3) */ double s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 56.320923501171, 0, -56.320923501171, 179.664747671772880215, &s12, nullptr, nullptr); result += checkEquals(s12, 19993558.287, 0.5e-3); return result; } static int GeodSolve10() { /* Check fix for adjust tol1_ bug found 2011-06-25 (Visual Studio * 10 rel + debug) */ double s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 52.784459512564, 0, -52.784459512563990912, 179.634407464943777557, &s12, nullptr, nullptr); result += checkEquals(s12, 19991596.095, 0.5e-3); return result; } static int GeodSolve11() { /* Check fix for bet2 = -bet1 bug found 2011-06-25 (Visual Studio * 10 rel + debug) */ double s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 48.522876735459, 0, -48.52287673545898293, 179.599720456223079643, &s12, nullptr, nullptr); result += checkEquals(s12, 19989144.774, 0.5e-3); return result; } static int GeodSolve12() { /* Check fix for inverse geodesics on extreme prolate/oblate * ellipsoids Reported 2012-08-29 Stefan Guenther * <[email protected]>; fixed 2012-10-07 */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, 89.8, -1.83); geod_inverse(&g, 0, 0, -10, 160, &s12, &azi1, &azi2); result += checkEquals(azi1, 120.27, 1e-2); result += checkEquals(azi2, 105.15, 1e-2); result += checkEquals(s12, 266.7, 1e-1); return result; } static int GeodSolve14() { /* Check fix for inverse ignoring lon12 = nan */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 0, 0, 1, nan("0"), &s12, &azi1, &azi2); result += checkNaN(azi1); result += checkNaN(azi2); result += checkNaN(s12); return result; } static int GeodSolve15() { /* Initial implementation of Math::eatanhe was wrong for e^2 < 0. This * checks that this is fixed. */ double S12; struct geod_geodesic g; int result = 0; geod_init(&g, 6.4e6, -1/150.0); geod_gendirect(&g, 1, 2, 3, 0, 4, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &S12); result += checkEquals(S12, 23700, 0.5); return result; } static int GeodSolve17() { /* Check fix for LONG_UNROLL bug found on 2015-05-07 */ double lat2, lon2, azi2; struct geod_geodesic g; struct geod_geodesicline l; int result = 0; unsigned flags = GEOD_LONG_UNROLL; geod_init(&g, wgs84_a, wgs84_f); geod_gendirect(&g, 40, -75, -10, flags, 2e7, &lat2, &lon2, &azi2, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkEquals(lat2, -39, 1); result += checkEquals(lon2, -254, 1); result += checkEquals(azi2, -170, 1); geod_lineinit(&l, &g, 40, -75, -10, 0); geod_genposition(&l, flags, 2e7, &lat2, &lon2, &azi2, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkEquals(lat2, -39, 1); result += checkEquals(lon2, -254, 1); result += checkEquals(azi2, -170, 1); geod_direct(&g, 40, -75, -10, 2e7, &lat2, &lon2, &azi2); result += checkEquals(lat2, -39, 1); result += checkEquals(lon2, 105, 1); result += checkEquals(azi2, -170, 1); geod_position(&l, 2e7, &lat2, &lon2, &azi2); result += checkEquals(lat2, -39, 1); result += checkEquals(lon2, 105, 1); result += checkEquals(azi2, -170, 1); return result; } static int GeodSolve26() { /* Check 0/0 problem with area calculation on sphere 2015-09-08 */ double S12; struct geod_geodesic g; int result = 0; geod_init(&g, 6.4e6, 0); geod_geninverse(&g, 1, 2, 3, 4, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &S12); result += checkEquals(S12, 49911046115.0, 0.5); return result; } static int GeodSolve28() { /* Check for bad placement of assignment of r.a12 with |f| > 0.01 (bug in * Java implementation fixed on 2015-05-19). */ double a12; struct geod_geodesic g; int result = 0; geod_init(&g, 6.4e6, 0.1); a12 = geod_gendirect(&g, 1, 2, 10, 0, 5e6, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkEquals(a12, 48.55570690, 0.5e-8); return result; } static int GeodSolve33() { /* Check max(-0.0,+0.0) issues 2015-08-22 (triggered by bugs in Octave -- * sind(-0.0) = +0.0 -- and in some version of Visual Studio -- * fmod(-0.0, 360.0) = +0.0. */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 0, 0, 0, 179, &s12, &azi1, &azi2); result += checkEquals(azi1, 90.00000, 0.5e-5); result += checkEquals(azi2, 90.00000, 0.5e-5); result += checkEquals(s12, 19926189, 0.5); geod_inverse(&g, 0, 0, 0, 179.5, &s12, &azi1, &azi2); result += checkEquals(azi1, 55.96650, 0.5e-5); result += checkEquals(azi2, 124.03350, 0.5e-5); result += checkEquals(s12, 19980862, 0.5); geod_inverse(&g, 0, 0, 0, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 0.00000, 0.5e-5); result += checkEquals(fabs(azi2), 180.00000, 0.5e-5); result += checkEquals(s12, 20003931, 0.5); geod_inverse(&g, 0, 0, 1, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 0.00000, 0.5e-5); result += checkEquals(fabs(azi2), 180.00000, 0.5e-5); result += checkEquals(s12, 19893357, 0.5); geod_init(&g, 6.4e6, 0); geod_inverse(&g, 0, 0, 0, 179, &s12, &azi1, &azi2); result += checkEquals(azi1, 90.00000, 0.5e-5); result += checkEquals(azi2, 90.00000, 0.5e-5); result += checkEquals(s12, 19994492, 0.5); geod_inverse(&g, 0, 0, 0, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 0.00000, 0.5e-5); result += checkEquals(fabs(azi2), 180.00000, 0.5e-5); result += checkEquals(s12, 20106193, 0.5); geod_inverse(&g, 0, 0, 1, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 0.00000, 0.5e-5); result += checkEquals(fabs(azi2), 180.00000, 0.5e-5); result += checkEquals(s12, 19994492, 0.5); geod_init(&g, 6.4e6, -1/300.0); geod_inverse(&g, 0, 0, 0, 179, &s12, &azi1, &azi2); result += checkEquals(azi1, 90.00000, 0.5e-5); result += checkEquals(azi2, 90.00000, 0.5e-5); result += checkEquals(s12, 19994492, 0.5); geod_inverse(&g, 0, 0, 0, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 90.00000, 0.5e-5); result += checkEquals(azi2, 90.00000, 0.5e-5); result += checkEquals(s12, 20106193, 0.5); geod_inverse(&g, 0, 0, 0.5, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 33.02493, 0.5e-5); result += checkEquals(azi2, 146.97364, 0.5e-5); result += checkEquals(s12, 20082617, 0.5); geod_inverse(&g, 0, 0, 1, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 0.00000, 0.5e-5); result += checkEquals(fabs(azi2), 180.00000, 0.5e-5); result += checkEquals(s12, 20027270, 0.5); return result; } static int GeodSolve55() { /* Check fix for nan + point on equator or pole not returning all nans in * Geodesic::Inverse, found 2015-09-23. */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, nan("0"), 0, 0, 90, &s12, &azi1, &azi2); result += checkNaN(azi1); result += checkNaN(azi2); result += checkNaN(s12); geod_inverse(&g, nan("0"), 0, 90, 9, &s12, &azi1, &azi2); result += checkNaN(azi1); result += checkNaN(azi2); result += checkNaN(s12); return result; } static int GeodSolve59() { /* Check for points close with longitudes close to 180 deg apart. */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 5, 0.00000000000001, 10, 180, &s12, &azi1, &azi2); result += checkEquals(azi1, 0.000000000000035, 1.5e-14); result += checkEquals(azi2, 179.99999999999996, 1.5e-14); result += checkEquals(s12, 18345191.174332713, 5e-9); return result; } static int GeodSolve61() { /* Make sure small negative azimuths are west-going */ double lat2, lon2, azi2; struct geod_geodesic g; struct geod_geodesicline l; int result = 0; unsigned flags = GEOD_LONG_UNROLL; geod_init(&g, wgs84_a, wgs84_f); geod_gendirect(&g, 45, 0, -0.000000000000000003, flags, 1e7, &lat2, &lon2, &azi2, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkEquals(lat2, 45.30632, 0.5e-5); result += checkEquals(lon2, -180, 0.5e-5); result += checkEquals(fabs(azi2), 180, 0.5e-5); geod_inverseline(&l, &g, 45, 0, 80, -0.000000000000000003, 0); geod_genposition(&l, flags, 1e7, &lat2, &lon2, &azi2, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkEquals(lat2, 45.30632, 0.5e-5); result += checkEquals(lon2, -180, 0.5e-5); result += checkEquals(fabs(azi2), 180, 0.5e-5); return result; } static int GeodSolve65() { /* Check for bug in east-going check in GeodesicLine (needed to check for * sign of 0) and sign error in area calculation due to a bogus override of * the code for alp12. Found/fixed on 2015-12-19. */ double lat2, lon2, azi2, s12, a12, m12, M12, M21, S12; struct geod_geodesic g; struct geod_geodesicline l; int result = 0; unsigned flags = GEOD_LONG_UNROLL, caps = GEOD_ALL; geod_init(&g, wgs84_a, wgs84_f); geod_inverseline(&l, &g, 30, -0.000000000000000001, -31, 180, caps); a12 = geod_genposition(&l, flags, 1e7, &lat2, &lon2, &azi2, &s12, &m12, &M12, &M21, &S12); result += checkEquals(lat2, -60.23169, 0.5e-5); result += checkEquals(lon2, -0.00000, 0.5e-5); result += checkEquals(fabs(azi2), 180.00000, 0.5e-5); result += checkEquals(s12, 10000000, 0.5); result += checkEquals(a12, 90.06544, 0.5e-5); result += checkEquals(m12, 6363636, 0.5); result += checkEquals(M12, -0.0012834, 0.5e-7); result += checkEquals(M21, 0.0013749, 0.5e-7); result += checkEquals(S12, 0, 0.5); a12 = geod_genposition(&l, flags, 2e7, &lat2, &lon2, &azi2, &s12, &m12, &M12, &M21, &S12); result += checkEquals(lat2, -30.03547, 0.5e-5); result += checkEquals(lon2, -180.00000, 0.5e-5); result += checkEquals(azi2, -0.00000, 0.5e-5); result += checkEquals(s12, 20000000, 0.5); result += checkEquals(a12, 179.96459, 0.5e-5); result += checkEquals(m12, 54342, 0.5); result += checkEquals(M12, -1.0045592, 0.5e-7); result += checkEquals(M21, -0.9954339, 0.5e-7); result += checkEquals(S12, 127516405431022.0, 0.5); return result; } static int GeodSolve67() { /* Check for InverseLine if line is slightly west of S and that s13 is * correctly set. */ double lat2, lon2, azi2; struct geod_geodesic g; struct geod_geodesicline l; int result = 0; unsigned flags = GEOD_LONG_UNROLL; geod_init(&g, wgs84_a, wgs84_f); geod_inverseline(&l, &g, -5, -0.000000000000002, -10, 180, 0); geod_genposition(&l, flags, 2e7, &lat2, &lon2, &azi2, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkEquals(lat2, 4.96445, 0.5e-5); result += checkEquals(lon2, -180.00000, 0.5e-5); result += checkEquals(azi2, -0.00000, 0.5e-5); geod_genposition(&l, flags, 0.5 * l.s13, &lat2, &lon2, &azi2, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkEquals(lat2, -87.52461, 0.5e-5); result += checkEquals(lon2, -0.00000, 0.5e-5); result += checkEquals(azi2, -180.00000, 0.5e-5); return result; } static int GeodSolve71() { /* Check that DirectLine sets s13. */ double lat2, lon2, azi2; struct geod_geodesic g; struct geod_geodesicline l; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_directline(&l, &g, 1, 2, 45, 1e7, 0); geod_position(&l, 0.5 * l.s13, &lat2, &lon2, &azi2); result += checkEquals(lat2, 30.92625, 0.5e-5); result += checkEquals(lon2, 37.54640, 0.5e-5); result += checkEquals(azi2, 55.43104, 0.5e-5); return result; } static int GeodSolve73() { /* Check for backwards from the pole bug reported by Anon on 2016-02-13. * This only affected the Java implementation. It was introduced in Java * version 1.44 and fixed in 1.46-SNAPSHOT on 2016-01-17. * Also the + sign on azi2 is a check on the normalizing of azimuths * (converting -0.0 to +0.0). */ double lat2, lon2, azi2; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_direct(&g, 90, 10, 180, -1e6, &lat2, &lon2, &azi2); result += checkEquals(lat2, 81.04623, 0.5e-5); result += checkEquals(lon2, -170, 0.5e-5); result += azi2 == 0 ? 0 : 1; result += 1/azi2 > 0 ? 0 : 1; /* Check that azi2 = +0.0 not -0.0 */ return result; } static void planimeter(const struct geod_geodesic* g, double points[][2], int N, double* perimeter, double* area) { struct geod_polygon p; int i; geod_polygon_init(&p, 0); for (i = 0; i < N; ++i) geod_polygon_addpoint(g, &p, points[i][0], points[i][1]); geod_polygon_compute(g, &p, 0, 1, area, perimeter); } static void polylength(const struct geod_geodesic* g, double points[][2], int N, double* perimeter) { struct geod_polygon p; int i; geod_polygon_init(&p, 1); for (i = 0; i < N; ++i) geod_polygon_addpoint(g, &p, points[i][0], points[i][1]); geod_polygon_compute(g, &p, 0, 1, nullptr, perimeter); } static int GeodSolve74() { /* Check fix for inaccurate areas, bug introduced in v1.46, fixed * 2015-10-16. */ double a12, s12, azi1, azi2, m12, M12, M21, S12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); a12 = geod_geninverse(&g, 54.1589, 15.3872, 54.1591, 15.3877, &s12, &azi1, &azi2, &m12, &M12, &M21, &S12); result += checkEquals(azi1, 55.723110355, 5e-9); result += checkEquals(azi2, 55.723515675, 5e-9); result += checkEquals(s12, 39.527686385, 5e-9); result += checkEquals(a12, 0.000355495, 5e-9); result += checkEquals(m12, 39.527686385, 5e-9); result += checkEquals(M12, 0.999999995, 5e-9); result += checkEquals(M21, 0.999999995, 5e-9); result += checkEquals(S12, 286698586.30197, 5e-4); return result; } static int GeodSolve76() { /* The distance from Wellington and Salamanca (a classic failure of * Vincenty) */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, -(41+19/60.0), 174+49/60.0, 40+58/60.0, -(5+30/60.0), &s12, &azi1, &azi2); result += checkEquals(azi1, 160.39137649664, 0.5e-11); result += checkEquals(azi2, 19.50042925176, 0.5e-11); result += checkEquals(s12, 19960543.857179, 0.5e-6); return result; } static int GeodSolve78() { /* An example where the NGS calculator fails to converge */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 27.2, 0.0, -27.1, 179.5, &s12, &azi1, &azi2); result += checkEquals(azi1, 45.82468716758, 0.5e-11); result += checkEquals(azi2, 134.22776532670, 0.5e-11); result += checkEquals(s12, 19974354.765767, 0.5e-6); return result; } static int GeodSolve80() { /* Some tests to add code coverage: computing scale in special cases + zero * length geodesic (includes GeodSolve80 - GeodSolve83) + using an incapable * line. */ double a12, s12, azi1, azi2, m12, M12, M21, S12; struct geod_geodesic g; struct geod_geodesicline l; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_geninverse(&g, 0, 0, 0, 90, nullptr, nullptr, nullptr, nullptr, &M12, &M21, nullptr); result += checkEquals(M12, -0.00528427534, 0.5e-10); result += checkEquals(M21, -0.00528427534, 0.5e-10); geod_geninverse(&g, 0, 0, 1e-6, 1e-6, nullptr, nullptr, nullptr, nullptr, &M12, &M21, nullptr); result += checkEquals(M12, 1, 0.5e-10); result += checkEquals(M21, 1, 0.5e-10); a12 = geod_geninverse(&g, 20.001, 0, 20.001, 0, &s12, &azi1, &azi2, &m12, &M12, &M21, &S12); result += checkEquals(a12, 0, 1e-13); result += checkEquals(s12, 0, 1e-8); result += checkEquals(azi1, 180, 1e-13); result += checkEquals(azi2, 180, 1e-13); result += checkEquals(m12, 0, 1e-8); result += checkEquals(M12, 1, 1e-15); result += checkEquals(M21, 1, 1e-15); result += checkEquals(S12, 0, 1e-10); result += 1/a12 > 0 ? 0 : 1; result += 1/s12 > 0 ? 0 : 1; result += 1/m12 > 0 ? 0 : 1; a12 = geod_geninverse(&g, 90, 0, 90, 180, &s12, &azi1, &azi2, &m12, &M12, &M21, &S12); result += checkEquals(a12, 0, 1e-13); result += checkEquals(s12, 0, 1e-8); result += checkEquals(azi1, 0, 1e-13); result += checkEquals(azi2, 180, 1e-13); result += checkEquals(m12, 0, 1e-8); result += checkEquals(M12, 1, 1e-15); result += checkEquals(M21, 1, 1e-15); result += checkEquals(S12, 127516405431022.0, 0.5); /* An incapable line which can't take distance as input */ geod_lineinit(&l, &g, 1, 2, 90, GEOD_LATITUDE); a12 = geod_genposition(&l, 0, 1000, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); result += checkNaN(a12); return result; } static int GeodSolve84() { /* Tests for python implementation to check fix for range errors with * {fmod,sin,cos}(inf) (includes GeodSolve84 - GeodSolve86). */ double lat2, lon2, azi2, inf; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); { /* a round about way to set inf = 0 */ geod_direct(&g, 0, 0, 90, 0, &inf, nullptr, nullptr); /* so that this doesn't give a compiler time error on Windows */ inf = 1.0/inf; } geod_direct(&g, 0, 0, 90, inf, &lat2, &lon2, &azi2); result += checkNaN(lat2); result += checkNaN(lon2); result += checkNaN(azi2); geod_direct(&g, 0, 0, 90, nan("0"), &lat2, &lon2, &azi2); result += checkNaN(lat2); result += checkNaN(lon2); result += checkNaN(azi2); geod_direct(&g, 0, 0, inf, 1000, &lat2, &lon2, &azi2); result += checkNaN(lat2); result += checkNaN(lon2); result += checkNaN(azi2); geod_direct(&g, 0, 0, nan("0"), 1000, &lat2, &lon2, &azi2); result += checkNaN(lat2); result += checkNaN(lon2); result += checkNaN(azi2); geod_direct(&g, 0, inf, 90, 1000, &lat2, &lon2, &azi2); result += lat2 == 0 ? 0 : 1; result += checkNaN(lon2); result += azi2 == 90 ? 0 : 1; geod_direct(&g, 0, nan("0"), 90, 1000, &lat2, &lon2, &azi2); result += lat2 == 0 ? 0 : 1; result += checkNaN(lon2); result += azi2 == 90 ? 0 : 1; geod_direct(&g, inf, 0, 90, 1000, &lat2, &lon2, &azi2); result += checkNaN(lat2); result += checkNaN(lon2); result += checkNaN(azi2); geod_direct(&g, nan("0"), 0, 90, 1000, &lat2, &lon2, &azi2); result += checkNaN(lat2); result += checkNaN(lon2); result += checkNaN(azi2); return result; } static int GeodSolve92() { /* Check fix for inaccurate hypot with python 3.[89]. Problem reported * by agdhruv https://github.com/geopy/geopy/issues/466 ; see * https://bugs.python.org/issue43088 */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 37.757540000000006, -122.47018, 37.75754, -122.470177, &s12, &azi1, &azi2); result += checkEquals(azi1, 89.99999923, 1e-7 ); result += checkEquals(azi2, 90.00000106, 1e-7 ); result += checkEquals(s12, 0.264, 0.5e-3); return result; } static int GeodSolve94() { /* Check fix for lat2 = nan being treated as lat2 = 0 (bug found * 2021-07-26) */ double azi1, azi2, s12; struct geod_geodesic g; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_inverse(&g, 0, 0, nan("0"), 90, &s12, &azi1, &azi2); result += checkNaN(azi1); result += checkNaN(azi2); result += checkNaN(s12); return result; } static int GeodSolve96() { /* Failure with long doubles found with test case from Nowak + Nowak Da * Costa (2022). Problem was using somg12 > 1 as a test that it needed * to be set when roundoff could result in somg12 slightly bigger that 1. * Found + fixed 2022-03-30. */ double S12; struct geod_geodesic g; int result = 0; geod_init(&g, 6378137, 1/298.257222101); geod_geninverse(&g, 0, 0, 60.0832522871723, 89.8492185074635, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &S12); result += checkEquals(S12, 42426932221845, 0.5); return result; } static int Planimeter0() { /* Check fix for pole-encircling bug found 2011-03-16 */ double pa[4][2] = {{89, 0}, {89, 90}, {89, 180}, {89, 270}}; double pb[4][2] = {{-89, 0}, {-89, 90}, {-89, 180}, {-89, 270}}; double pc[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; double pd[3][2] = {{90, 0}, {0, 0}, {0, 90}}; struct geod_geodesic g; double perimeter, area; int result = 0; geod_init(&g, wgs84_a, wgs84_f); planimeter(&g, pa, 4, &perimeter, &area); result += checkEquals(perimeter, 631819.8745, 1e-4); result += checkEquals(area, 24952305678.0, 1); planimeter(&g, pb, 4, &perimeter, &area); result += checkEquals(perimeter, 631819.8745, 1e-4); result += checkEquals(area, -24952305678.0, 1); planimeter(&g, pc, 4, &perimeter, &area); result += checkEquals(perimeter, 627598.2731, 1e-4); result += checkEquals(area, 24619419146.0, 1); planimeter(&g, pd, 3, &perimeter, &area); result += checkEquals(perimeter, 30022685, 1); result += checkEquals(area, 63758202715511.0, 1); polylength(&g, pd, 3, &perimeter); result += checkEquals(perimeter, 20020719, 1); return result; } static int Planimeter5() { /* Check fix for Planimeter pole crossing bug found 2011-06-24 */ double points[3][2] = {{89, 0.1}, {89, 90.1}, {89, -179.9}}; struct geod_geodesic g; double perimeter, area; int result = 0; geod_init(&g, wgs84_a, wgs84_f); planimeter(&g, points, 3, &perimeter, &area); result += checkEquals(perimeter, 539297, 1); result += checkEquals(area, 12476152838.5, 1); return result; } static int Planimeter6() { /* Check fix for Planimeter lon12 rounding bug found 2012-12-03 */ double pa[3][2] = {{9, -0.00000000000001}, {9, 180}, {9, 0}}; double pb[3][2] = {{9, 0.00000000000001}, {9, 0}, {9, 180}}; double pc[3][2] = {{9, 0.00000000000001}, {9, 180}, {9, 0}}; double pd[3][2] = {{9, -0.00000000000001}, {9, 0}, {9, 180}}; struct geod_geodesic g; double perimeter, area; int result = 0; geod_init(&g, wgs84_a, wgs84_f); planimeter(&g, pa, 3, &perimeter, &area); result += checkEquals(perimeter, 36026861, 1); result += checkEquals(area, 0, 1); planimeter(&g, pb, 3, &perimeter, &area); result += checkEquals(perimeter, 36026861, 1); result += checkEquals(area, 0, 1); planimeter(&g, pc, 3, &perimeter, &area); result += checkEquals(perimeter, 36026861, 1); result += checkEquals(area, 0, 1); planimeter(&g, pd, 3, &perimeter, &area); result += checkEquals(perimeter, 36026861, 1); result += checkEquals(area, 0, 1); return result; } static int Planimeter12() { /* Area of arctic circle (not really -- adjunct to rhumb-area test) */ double points[3][2] = {{66.562222222, 0}, {66.562222222, 180}, {66.562222222, 360}}; struct geod_geodesic g; double perimeter, area; int result = 0; geod_init(&g, wgs84_a, wgs84_f); planimeter(&g, points, 3, &perimeter, &area); result += checkEquals(perimeter, 10465729, 1); result += checkEquals(area, 0, 1); return result; } static int Planimeter12r() { /* Area of arctic circle (not really -- adjunct to rhumb-area test) */ double points[3][2] = {{66.562222222, -0}, {66.562222222, -180}, {66.562222222, -360}}; struct geod_geodesic g; double perimeter, area; int result = 0; geod_init(&g, wgs84_a, wgs84_f); planimeter(&g, points, 3, &perimeter, &area); result += checkEquals(perimeter, 10465729, 1); result += checkEquals(area, 0, 1); return result; } static int Planimeter13() { /* Check encircling pole twice */ double points[6][2] = {{89,-360}, {89,-240}, {89,-120}, {89,0}, {89,120}, {89,240}}; struct geod_geodesic g; double perimeter, area; int result = 0; geod_init(&g, wgs84_a, wgs84_f); planimeter(&g, points, 6, &perimeter, &area); result += checkEquals(perimeter, 1160741, 1); result += checkEquals(area, 32415230256.0, 1); return result; } static int Planimeter15() { /* Coverage tests, includes Planimeter15 - Planimeter18 (combinations of * reverse and sign) + calls to testpoint, testedge, geod_polygonarea. */ struct geod_geodesic g; struct geod_polygon p; double lat[] = {2, 1, 3}, lon[] = {1, 2, 3}; double area, s12, azi1; double r = 18454562325.45119, a0 = 510065621724088.5093; /* ellipsoid area */ int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_polygon_init(&p, 0); geod_polygon_addpoint(&g, &p, lat[0], lon[0]); geod_polygon_addpoint(&g, &p, lat[1], lon[1]); geod_polygon_testpoint(&g, &p, lat[2], lon[2], 0, 1, &area, nullptr); result += checkEquals(area, r, 0.5); geod_polygon_testpoint(&g, &p, lat[2], lon[2], 0, 0, &area, nullptr); result += checkEquals(area, r, 0.5); geod_polygon_testpoint(&g, &p, lat[2], lon[2], 1, 1, &area, nullptr); result += checkEquals(area, -r, 0.5); geod_polygon_testpoint(&g, &p, lat[2], lon[2], 1, 0, &area, nullptr); result += checkEquals(area, a0-r, 0.5); geod_inverse(&g, lat[1], lon[1], lat[2], lon[2], &s12, &azi1, nullptr); geod_polygon_testedge(&g, &p, azi1, s12, 0, 1, &area, nullptr); result += checkEquals(area, r, 0.5); geod_polygon_testedge(&g, &p, azi1, s12, 0, 0, &area, nullptr); result += checkEquals(area, r, 0.5); geod_polygon_testedge(&g, &p, azi1, s12, 1, 1, &area, nullptr); result += checkEquals(area, -r, 0.5); geod_polygon_testedge(&g, &p, azi1, s12, 1, 0, &area, nullptr); result += checkEquals(area, a0-r, 0.5); geod_polygon_addpoint(&g, &p, lat[2], lon[2]); geod_polygon_compute(&g, &p, 0, 1, &area, nullptr); result += checkEquals(area, r, 0.5); geod_polygon_compute(&g, &p, 0, 0, &area, nullptr); result += checkEquals(area, r, 0.5); geod_polygon_compute(&g, &p, 1, 1, &area, nullptr); result += checkEquals(area, -r, 0.5); geod_polygon_compute(&g, &p, 1, 0, &area, nullptr); result += checkEquals(area, a0-r, 0.5); geod_polygonarea(&g, lat, lon, 3, &area, nullptr); result += checkEquals(area, r, 0.5); return result; } static int Planimeter19() { /* Coverage tests, includes Planimeter19 - Planimeter20 (degenerate * polygons) + extra cases. */ struct geod_geodesic g; struct geod_polygon p; double area, perim; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_polygon_init(&p, 0); geod_polygon_compute(&g, &p, 0, 1, &area, &perim); result += area == 0 ? 0 : 1; result += perim == 0 ? 0 : 1; geod_polygon_testpoint(&g, &p, 1, 1, 0, 1, &area, &perim); result += area == 0 ? 0 : 1; result += perim == 0 ? 0 : 1; geod_polygon_testedge(&g, &p, 90, 1000, 0, 1, &area, &perim); result += checkNaN(area); result += checkNaN(perim); geod_polygon_addpoint(&g, &p, 1, 1); geod_polygon_compute(&g, &p, 0, 1, &area, &perim); result += area == 0 ? 0 : 1; result += perim == 0 ? 0 : 1; geod_polygon_init(&p, 1); geod_polygon_compute(&g, &p, 0, 1, nullptr, &perim); result += perim == 0 ? 0 : 1; geod_polygon_testpoint(&g, &p, 1, 1, 0, 1, nullptr, &perim); result += perim == 0 ? 0 : 1; geod_polygon_testedge(&g, &p, 90, 1000, 0, 1, nullptr, &perim); result += checkNaN(perim); geod_polygon_addpoint(&g, &p, 1, 1); geod_polygon_compute(&g, &p, 0, 1, nullptr, &perim); result += perim == 0 ? 0 : 1; geod_polygon_addpoint(&g, &p, 1, 1); geod_polygon_testedge(&g, &p, 90, 1000, 0, 1, nullptr, &perim); result += checkEquals(perim, 1000, 1e-10); geod_polygon_testpoint(&g, &p, 2, 2, 0, 1, nullptr, &perim); result += checkEquals(perim, 156876.149, 0.5e-3); return result; } static int Planimeter21() { /* Some tests to add code coverage: multiple circlings of pole (includes * Planimeter21 - Planimeter28) + invocations via testpoint and testedge. */ struct geod_geodesic g; struct geod_polygon p; double area, lat = 45, a = 39.2144607176828184218, s = 8420705.40957178156285, r = 39433884866571.4277, /* Area for one circuit */ a0 = 510065621724088.5093; /* Ellipsoid area */ int result = 0, i; geod_init(&g, wgs84_a, wgs84_f); geod_polygon_init(&p, 0); geod_polygon_addpoint(&g, &p, lat, 60); geod_polygon_addpoint(&g, &p, lat, 180); geod_polygon_addpoint(&g, &p, lat, -60); geod_polygon_addpoint(&g, &p, lat, 60); geod_polygon_addpoint(&g, &p, lat, 180); geod_polygon_addpoint(&g, &p, lat, -60); for (i = 3; i <= 4; ++i) { geod_polygon_addpoint(&g, &p, lat, 60); geod_polygon_addpoint(&g, &p, lat, 180); geod_polygon_testpoint(&g, &p, lat, -60, 0, 1, &area, nullptr); result += checkEquals(area, i*r, 0.5); geod_polygon_testpoint(&g, &p, lat, -60, 0, 0, &area, nullptr); result += checkEquals(area, i*r, 0.5); geod_polygon_testpoint(&g, &p, lat, -60, 1, 1, &area, nullptr); result += checkEquals(area, -i*r, 0.5); geod_polygon_testpoint(&g, &p, lat, -60, 1, 0, &area, nullptr); result += checkEquals(area, -i*r + a0, 0.5); geod_polygon_testedge(&g, &p, a, s, 0, 1, &area, nullptr); result += checkEquals(area, i*r, 0.5); geod_polygon_testedge(&g, &p, a, s, 0, 0, &area, nullptr); result += checkEquals(area, i*r, 0.5); geod_polygon_testedge(&g, &p, a, s, 1, 1, &area, nullptr); result += checkEquals(area, -i*r, 0.5); geod_polygon_testedge(&g, &p, a, s, 1, 0, &area, nullptr); result += checkEquals(area, -i*r + a0, 0.5); geod_polygon_addpoint(&g, &p, lat, -60); geod_polygon_compute(&g, &p, 0, 1, &area, nullptr); result += checkEquals(area, i*r, 0.5); geod_polygon_compute(&g, &p, 0, 0, &area, nullptr); result += checkEquals(area, i*r, 0.5); geod_polygon_compute(&g, &p, 1, 1, &area, nullptr); result += checkEquals(area, -i*r, 0.5); geod_polygon_compute(&g, &p, 1, 0, &area, nullptr); result += checkEquals(area, -i*r + a0, 0.5); } return result; } static int Planimeter29() { /* Check fix to transitdirect vs transit zero handling inconsistency */ struct geod_geodesic g; struct geod_polygon p; double area; int result = 0; geod_init(&g, wgs84_a, wgs84_f); geod_polygon_init(&p, 0); geod_polygon_addpoint(&g, &p, 0, 0); geod_polygon_addedge(&g, &p, 90, 1000); geod_polygon_addedge(&g, &p, 0, 1000); geod_polygon_addedge(&g, &p, -90, 1000); geod_polygon_compute(&g, &p, 0, 1, &area, nullptr); /* The area should be 1e6. Prior to the fix it was 1e6 - A/2, where * A = ellipsoid area. */ result += checkEquals(area, 1000000.0, 0.01); return result; } int main() { int n = 0, i; if ((i = testinverse())) {++n; printf("testinverse fail: %d\n", i);} if ((i = testdirect())) {++n; printf("testdirect fail: %d\n", i);} if ((i = testarcdirect())) {++n; printf("testarcdirect fail: %d\n", i);} if ((i = GeodSolve0())) {++n; printf("GeodSolve0 fail: %d\n", i);} if ((i = GeodSolve1())) {++n; printf("GeodSolve1 fail: %d\n", i);} if ((i = GeodSolve2())) {++n; printf("GeodSolve2 fail: %d\n", i);} if ((i = GeodSolve4())) {++n; printf("GeodSolve4 fail: %d\n", i);} if ((i = GeodSolve5())) {++n; printf("GeodSolve5 fail: %d\n", i);} if ((i = GeodSolve6())) {++n; printf("GeodSolve6 fail: %d\n", i);} if ((i = GeodSolve9())) {++n; printf("GeodSolve9 fail: %d\n", i);} if ((i = GeodSolve10())) {++n; printf("GeodSolve10 fail: %d\n", i);} if ((i = GeodSolve11())) {++n; printf("GeodSolve11 fail: %d\n", i);} if ((i = GeodSolve12())) {++n; printf("GeodSolve12 fail: %d\n", i);} if ((i = GeodSolve14())) {++n; printf("GeodSolve14 fail: %d\n", i);} if ((i = GeodSolve15())) {++n; printf("GeodSolve15 fail: %d\n", i);} if ((i = GeodSolve17())) {++n; printf("GeodSolve17 fail: %d\n", i);} if ((i = GeodSolve26())) {++n; printf("GeodSolve26 fail: %d\n", i);} if ((i = GeodSolve28())) {++n; printf("GeodSolve28 fail: %d\n", i);} if ((i = GeodSolve33())) {++n; printf("GeodSolve33 fail: %d\n", i);} if ((i = GeodSolve55())) {++n; printf("GeodSolve55 fail: %d\n", i);} if ((i = GeodSolve59())) {++n; printf("GeodSolve59 fail: %d\n", i);} if ((i = GeodSolve61())) {++n; printf("GeodSolve61 fail: %d\n", i);} if ((i = GeodSolve65())) {++n; printf("GeodSolve65 fail: %d\n", i);} if ((i = GeodSolve67())) {++n; printf("GeodSolve67 fail: %d\n", i);} if ((i = GeodSolve71())) {++n; printf("GeodSolve71 fail: %d\n", i);} if ((i = GeodSolve73())) {++n; printf("GeodSolve73 fail: %d\n", i);} if ((i = GeodSolve74())) {++n; printf("GeodSolve74 fail: %d\n", i);} if ((i = GeodSolve76())) {++n; printf("GeodSolve76 fail: %d\n", i);} if ((i = GeodSolve78())) {++n; printf("GeodSolve78 fail: %d\n", i);} if ((i = GeodSolve80())) {++n; printf("GeodSolve80 fail: %d\n", i);} if ((i = GeodSolve84())) {++n; printf("GeodSolve84 fail: %d\n", i);} if ((i = GeodSolve92())) {++n; printf("GeodSolve92 fail: %d\n", i);} if ((i = GeodSolve94())) {++n; printf("GeodSolve94 fail: %d\n", i);} if ((i = GeodSolve96())) {++n; printf("GeodSolve96 fail: %d\n", i);} if ((i = Planimeter0())) {++n; printf("Planimeter0 fail: %d\n", i);} if ((i = Planimeter5())) {++n; printf("Planimeter5 fail: %d\n", i);} if ((i = Planimeter6())) {++n; printf("Planimeter6 fail: %d\n", i);} if ((i = Planimeter12())) {++n; printf("Planimeter12 fail: %d\n", i);} if ((i = Planimeter12r())) {++n; printf("Planimeter12r fail: %d\n", i);} if ((i = Planimeter13())) {++n; printf("Planimeter13 fail: %d\n", i);} if ((i = Planimeter15())) {++n; printf("Planimeter15 fail: %d\n", i);} if ((i = Planimeter19())) {++n; printf("Planimeter19 fail: %d\n", i);} if ((i = Planimeter21())) {++n; printf("Planimeter21 fail: %d\n", i);} if ((i = Planimeter29())) {++n; printf("Planimeter29 fail: %d\n", i);} return n; }
c
PROJ
data/projects/PROJ/src/tests/geodsigntest.c
/** * \file geodsigntest.c * \brief Test treatment of +/-0 and +/-180 * * Copyright (c) Charles Karney (2022) <[email protected]> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ #include <stdio.h> #include <math.h> #include <float.h> /* Include the source file for the library directly so we can access the * internal (static) functions. */ #include "geodesic.c" /* Define function names with the "geod_" prefix. */ #define geod_Init Init #define geod_sum sumx #define geod_AngNormalize AngNormalize #define geod_AngDiff AngDiff #define geod_AngRound AngRound #define geod_sincosd sincosdx #define geod_atan2d atan2dx typedef double T; #if !defined(__cplusplus) #define nullptr 0 #endif #if !defined(OLD_BUGGY_REMQUO) /* * glibc prior to version 2.22 had a bug in remquo. This was reported in 2014 * and fixed in 2015. See * https://sourceware.org/bugzilla/show_bug.cgi?id=17569 * * The bug causes some of the tests here to fail. The failures aren't terribly * serious (just a loss of accuracy). If you're still using the buggy glibc, * then define OLD_BUGGY_REMQUO to be 1. */ #define OLD_BUGGY_REMQUO 0 #endif static const T wgs84_a = 6378137, wgs84_f = 1/298.257223563; /* WGS84 */ static int equiv(T x, T y) { return ( (isnan(x) && isnan(y)) || (x == y && signbit(x) == signbit(y)) ) ? 0 : 1; } static int checkEquals(T x, T y, T d) { if (fabs(x - y) <= d) return 0; printf("checkEquals fails: %.7g != %.7g +/- %.7g\n", x, y, d); return 1; } /* use "do { } while (false)" idiom so it can be punctuated like a * statement. */ #define check(expr, r) do { \ T s = (T)(r), t = expr; \ if (equiv(s, t)) { \ printf("Line %d : %s != %s (%g)\n", \ __LINE__, #expr, #r, t); \ ++n; \ } \ } while (0) #define checksincosd(x, s, c) do { \ T sx, cx; \ geod_sincosd(x, &sx, &cx); \ if (equiv(s, sx)) { \ printf("Line %d: sin(%g) != %g (%g)\n", \ __LINE__, x, s, sx); \ ++n; \ } \ if (equiv(c, cx)) { \ printf("Line %d: cos(%g) != %g (%g)\n", \ __LINE__, x, c, cx); \ ++n; \ } \ } while (0) int main() { T inf = INFINITY, nan = NAN, eps = DBL_EPSILON, e; int n = 0; geod_Init(); check( geod_AngRound(-eps/32), -eps/32); check( geod_AngRound(-eps/64), -0.0 ); check( geod_AngRound(- 0.0 ), -0.0 ); check( geod_AngRound( 0.0 ), +0.0 ); check( geod_AngRound( eps/64), +0.0 ); check( geod_AngRound( eps/32), +eps/32); check( geod_AngRound((1-2*eps)/64), (1-2*eps)/64); check( geod_AngRound((1-eps )/64), 1.0 /64); check( geod_AngRound((1-eps/2)/64), 1.0 /64); check( geod_AngRound((1-eps/4)/64), 1.0 /64); check( geod_AngRound( 1.0 /64), 1.0 /64); check( geod_AngRound((1+eps/2)/64), 1.0 /64); check( geod_AngRound((1+eps )/64), 1.0 /64); check( geod_AngRound((1+2*eps)/64), (1+2*eps)/64); check( geod_AngRound((1-eps )/32), (1-eps )/32); check( geod_AngRound((1-eps/2)/32), 1.0 /32); check( geod_AngRound((1-eps/4)/32), 1.0 /32); check( geod_AngRound( 1.0 /32), 1.0 /32); check( geod_AngRound((1+eps/2)/32), 1.0 /32); check( geod_AngRound((1+eps )/32), (1+eps )/32); check( geod_AngRound((1-eps )/16), (1-eps )/16); check( geod_AngRound((1-eps/2)/16), (1-eps/2)/16); check( geod_AngRound((1-eps/4)/16), 1.0 /16); check( geod_AngRound( 1.0 /16), 1.0 /16); check( geod_AngRound((1+eps/4)/16), 1.0 /16); check( geod_AngRound((1+eps/2)/16), 1.0 /16); check( geod_AngRound((1+eps )/16), (1+eps )/16); check( geod_AngRound((1-eps )/ 8), (1-eps )/ 8); check( geod_AngRound((1-eps/2)/ 8), (1-eps/2)/ 8); check( geod_AngRound((1-eps/4)/ 8), 1.0 / 8); check( geod_AngRound((1+eps/2)/ 8), 1.0 / 8); check( geod_AngRound((1+eps )/ 8), (1+eps )/ 8); check( geod_AngRound( 1-eps ), 1-eps ); check( geod_AngRound( 1-eps/2 ), 1-eps/2 ); check( geod_AngRound( 1-eps/4 ), 1 ); check( geod_AngRound( 1.0 ), 1 ); check( geod_AngRound( 1+eps/4 ), 1 ); check( geod_AngRound( 1+eps/2 ), 1 ); check( geod_AngRound( 1+eps ), 1+ eps ); check( geod_AngRound( 90.0-64*eps), 90-64*eps ); check( geod_AngRound( 90.0-32*eps), 90 ); check( geod_AngRound( 90.0 ), 90 ); checksincosd(- inf, nan, nan); #if !OLD_BUGGY_REMQUO checksincosd(-810.0, -1.0, +0.0); #endif checksincosd(-720.0, -0.0, +1.0); checksincosd(-630.0, +1.0, +0.0); checksincosd(-540.0, -0.0, -1.0); checksincosd(-450.0, -1.0, +0.0); checksincosd(-360.0, -0.0, +1.0); checksincosd(-270.0, +1.0, +0.0); checksincosd(-180.0, -0.0, -1.0); checksincosd(- 90.0, -1.0, +0.0); checksincosd(- 0.0, -0.0, +1.0); checksincosd(+ 0.0, +0.0, +1.0); checksincosd(+ 90.0, +1.0, +0.0); checksincosd(+180.0, +0.0, -1.0); checksincosd(+270.0, -1.0, +0.0); checksincosd(+360.0, +0.0, +1.0); checksincosd(+450.0, +1.0, +0.0); checksincosd(+540.0, +0.0, -1.0); checksincosd(+630.0, -1.0, +0.0); checksincosd(+720.0, +0.0, +1.0); #if !OLD_BUGGY_REMQUO checksincosd(+810.0, +1.0, +0.0); #endif checksincosd(+ inf, nan, nan); checksincosd( nan, nan, nan); #if !OLD_BUGGY_REMQUO { T s1, c1, s2, c2, s3, c3; geod_sincosd( 9.0, &s1, &c1); geod_sincosd( 81.0, &s2, &c2); geod_sincosd(-123456789.0, &s3, &c3); if ( equiv(s1, c2) + equiv(s1, s3) + equiv(c1, s2) + equiv(c1, -c3) ) { printf("Line %d : sincos accuracy fail\n", __LINE__); ++n; } } #endif check( geod_atan2d(+0.0 , -0.0 ), +180 ); check( geod_atan2d(-0.0 , -0.0 ), -180 ); check( geod_atan2d(+0.0 , +0.0 ), +0.0 ); check( geod_atan2d(-0.0 , +0.0 ), -0.0 ); check( geod_atan2d(+0.0 , -1.0 ), +180 ); check( geod_atan2d(-0.0 , -1.0 ), -180 ); check( geod_atan2d(+0.0 , +1.0 ), +0.0 ); check( geod_atan2d(-0.0 , +1.0 ), -0.0 ); check( geod_atan2d(-1.0 , +0.0 ), -90 ); check( geod_atan2d(-1.0 , -0.0 ), -90 ); check( geod_atan2d(+1.0 , +0.0 ), +90 ); check( geod_atan2d(+1.0 , -0.0 ), +90 ); check( geod_atan2d(+1.0 , -inf), +180 ); check( geod_atan2d(-1.0 , -inf), -180 ); check( geod_atan2d(+1.0 , +inf), +0.0 ); check( geod_atan2d(-1.0 , +inf), -0.0 ); check( geod_atan2d( +inf, +1.0 ), +90 ); check( geod_atan2d( +inf, -1.0 ), +90 ); check( geod_atan2d( -inf, +1.0 ), -90 ); check( geod_atan2d( -inf, -1.0 ), -90 ); check( geod_atan2d( +inf, -inf), +135 ); check( geod_atan2d( -inf, -inf), -135 ); check( geod_atan2d( +inf, +inf), +45 ); check( geod_atan2d( -inf, +inf), -45 ); check( geod_atan2d( nan, +1.0 ), nan ); check( geod_atan2d(+1.0 , nan), nan ); { T s = 7e-16; if ( equiv( geod_atan2d(s, -1.0), 180 - geod_atan2d(s, 1.0) ) ) { printf("Line %d : atan2d accuracy fail\n", __LINE__); ++n; } } check( geod_sum(+9.0, -9.0, &e), +0.0 ); check( geod_sum(-9.0, +9.0, &e), +0.0 ); check( geod_sum(-0.0, +0.0, &e), +0.0 ); check( geod_sum(+0.0, -0.0, &e), +0.0 ); check( geod_sum(-0.0, -0.0, &e), -0.0 ); check( geod_sum(+0.0, +0.0, &e), +0.0 ); check( geod_AngNormalize(-900.0), -180 ); check( geod_AngNormalize(-720.0), -0.0 ); check( geod_AngNormalize(-540.0), -180 ); check( geod_AngNormalize(-360.0), -0.0 ); check( geod_AngNormalize(-180.0), -180 ); check( geod_AngNormalize( -0.0), -0.0 ); check( geod_AngNormalize( +0.0), +0.0 ); check( geod_AngNormalize( 180.0), +180 ); check( geod_AngNormalize( 360.0), +0.0 ); check( geod_AngNormalize( 540.0), +180 ); check( geod_AngNormalize( 720.0), +0.0 ); check( geod_AngNormalize( 900.0), +180 ); check( geod_AngDiff(+ 0.0, + 0.0, &e), +0.0 ); check( geod_AngDiff(+ 0.0, - 0.0, &e), -0.0 ); check( geod_AngDiff(- 0.0, + 0.0, &e), +0.0 ); check( geod_AngDiff(- 0.0, - 0.0, &e), +0.0 ); check( geod_AngDiff(+ 5.0, +365.0, &e), +0.0 ); check( geod_AngDiff(+365.0, + 5.0, &e), -0.0 ); check( geod_AngDiff(+ 5.0, +185.0, &e), +180.0 ); check( geod_AngDiff(+185.0, + 5.0, &e), -180.0 ); check( geod_AngDiff( +eps , +180.0, &e), +180.0 ); check( geod_AngDiff( -eps , +180.0, &e), -180.0 ); check( geod_AngDiff( +eps , -180.0, &e), +180.0 ); check( geod_AngDiff( -eps , -180.0, &e), -180.0 ); { T x = 138 + 128 * eps, y = -164; if ( equiv( geod_AngDiff(x, y, &e), 58 - 128 * eps ) ) { printf("Line %d : AngDiff accuracy fail\n", __LINE__); ++n; } } { /* azimuth of geodesic line with points on equator determined by signs of * latitude * lat1 lat2 azi1/2 */ T C[2][3] = { { +0.0, -0.0, 180 }, { -0.0, +0.0, 0 } }; struct geod_geodesic g; geod_init(&g, wgs84_a, wgs84_f); T azi1, azi2; int i = 0; for (int k = 0; k < 2; ++k) { geod_inverse(&g, C[k][0], 0.0, C[k][1], 0.0, nullptr, &azi1, &azi2); if ( equiv(azi1, C[k][2]) + equiv(azi2, C[k][2]) ) ++i; } if (i) { printf("Line %d: inverse coincident points on equator fail\n", __LINE__); ++n; } } { /* Does the nearly antipodal equatorial solution go north or south? * lat1 lat2 azi1 azi2 */ T C[2][4] = { { +0.0, +0.0, 56, 124}, { -0.0, -0.0, 124, 56} }; struct geod_geodesic g; geod_init(&g, wgs84_a, wgs84_f); T azi1, azi2; int i = 0; for (int k = 0; k < 2; ++k) { geod_inverse(&g, C[k][0], 0.0, C[k][1], 179.5, nullptr, &azi1, &azi2); i += checkEquals(azi1, C[k][2], 1) + checkEquals(azi2, C[k][3], 1); } if (i) { printf("Line %d: inverse nearly antipodal points on equator fail\n", __LINE__);; ++n; } } { /* How does the exact antipodal equatorial path go N/S + E/W * lat1 lat2 lon2 azi1 azi2 */ T C[4][5] = { { +0.0, +0.0, +180, +0.0, +180}, { -0.0, -0.0, +180, +180, +0.0}, { +0.0, +0.0, -180, -0.0, -180}, { -0.0, -0.0, -180, -180, -0.0} }; struct geod_geodesic g; geod_init(&g, wgs84_a, wgs84_f); T azi1, azi2; int i = 0; for (int k = 0; k < 4; ++k) { geod_inverse(&g, C[k][0], 0.0, C[k][1], C[k][2], nullptr, &azi1, &azi2); if ( equiv(azi1, C[k][3]) + equiv(azi2, C[k][4]) ) ++i; } if (i) { printf("Line %d: inverse antipodal points on equator fail\n", __LINE__); ++n; } } { /* Antipodal points on the equator with prolate ellipsoid * lon2 azi1/2 */ T C[2][2] = { { +180, +90 }, { -180, -90 } }; struct geod_geodesic g; geod_init(&g, 6.4e6, -1/300.0); T azi1, azi2; int i = 0; for (int k = 0; k < 2; ++k) { geod_inverse(&g, 0.0, 0.0, 0.0, C[k][0], nullptr, &azi1, &azi2); if ( equiv(azi1, C[k][1]) + equiv(azi2, C[k][1]) ) ++i; } if (i) { printf("Line %d: inverse antipodal points on equator, prolate, fail\n", __LINE__); ++n; } } { /* azimuths = +/-0 and +/-180 for the direct problem * azi1, lon2, azi2 */ T C[4][3] = { { +0.0, +180, +180 }, { -0.0, -180, -180 }, { +180 , +180, +0.0 }, { -180 , -180, -0.0 } }; struct geod_geodesic g; geod_init(&g, wgs84_a, wgs84_f); T lon2, azi2; int i = 0; for (int k = 0; k < 4; ++k) { geod_gendirect(&g, 0.0, 0.0, C[k][0], GEOD_LONG_UNROLL, 15e6, nullptr, &lon2, &azi2, nullptr, nullptr, nullptr, nullptr, nullptr); if ( equiv(lon2, C[k][1]) + equiv(azi2, C[k][2]) ) ++i; } if (i) { printf("Line %d: direct azi1 = +/-0 +/-180, fail\n", __LINE__); ++n; } } if (n) { printf("%d %s%s\n", n, "failure", (n > 1 ? "s" : "")); return 1; } }
c
PROJ
data/projects/PROJ/src/conversions/noop.cpp
#include "proj_internal.h" PROJ_HEAD(noop, "No operation"); static void noop(PJ_COORD &, PJ *) {} PJ *PJ_CONVERSION(noop, 0) { P->fwd4d = noop; P->inv4d = noop; P->left = PJ_IO_UNITS_WHATEVER; P->right = PJ_IO_UNITS_WHATEVER; return P; }
cpp
PROJ
data/projects/PROJ/src/conversions/axisswap.cpp
/*********************************************************************** Axis order operation for use with transformation pipelines. Kristian Evers, [email protected], 2017-10-31 ************************************************************************ Change the order and sign of 2,3 or 4 axes. Each of the possible four axes are numbered with 1-4, such that the first input axis is 1, the second is 2 and so on. The output ordering is controlled by a list of the input axes re-ordered to the new mapping. Examples: Reversing the order of the axes: +proj=axisswap +order=4,3,2,1 Swapping the first two axes (x and y): +proj=axisswap +order=2,1,3,4 The direction, or sign, of an axis can be changed by adding a minus in front of the axis-number: +proj=axisswap +order=1,-2,3,4 It is only necessary to specify the axes that are affected by the swap operation: +proj=axisswap +order=2,1 ************************************************************************ * 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 <stdlib.h> #include <string.h> #include <algorithm> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(axisswap, "Axis ordering"); namespace { // anonymous namespace struct pj_axisswap_data { unsigned int axis[4]; int sign[4]; }; } // anonymous namespace static int sign(int x) { return (x > 0) - (x < 0); } static PJ_XY pj_axisswap_forward_2d(PJ_LP lp, PJ *P) { struct pj_axisswap_data *Q = (struct pj_axisswap_data *)P->opaque; PJ_XY xy; double in[2] = {lp.lam, lp.phi}; xy.x = in[Q->axis[0]] * Q->sign[0]; xy.y = in[Q->axis[1]] * Q->sign[1]; return xy; } static PJ_LP pj_axisswap_reverse_2d(PJ_XY xy, PJ *P) { struct pj_axisswap_data *Q = (struct pj_axisswap_data *)P->opaque; unsigned int i; PJ_COORD out, in; in.v[0] = xy.x; in.v[1] = xy.y; out = proj_coord_error(); for (i = 0; i < 2; i++) out.v[Q->axis[i]] = in.v[i] * Q->sign[i]; return out.lp; } static PJ_XYZ pj_axisswap_forward_3d(PJ_LPZ lpz, PJ *P) { struct pj_axisswap_data *Q = (struct pj_axisswap_data *)P->opaque; unsigned int i; PJ_COORD out, in; in.v[0] = lpz.lam; in.v[1] = lpz.phi; in.v[2] = lpz.z; out = proj_coord_error(); for (i = 0; i < 3; i++) out.v[i] = in.v[Q->axis[i]] * Q->sign[i]; return out.xyz; } static PJ_LPZ pj_axisswap_reverse_3d(PJ_XYZ xyz, PJ *P) { struct pj_axisswap_data *Q = (struct pj_axisswap_data *)P->opaque; unsigned int i; PJ_COORD in, out; out = proj_coord_error(); in.v[0] = xyz.x; in.v[1] = xyz.y; in.v[2] = xyz.z; for (i = 0; i < 3; i++) out.v[Q->axis[i]] = in.v[i] * Q->sign[i]; return out.lpz; } static void swap_xy_4d(PJ_COORD &coo, PJ *) { std::swap(coo.xyzt.x, coo.xyzt.y); } static void pj_axisswap_forward_4d(PJ_COORD &coo, PJ *P) { struct pj_axisswap_data *Q = (struct pj_axisswap_data *)P->opaque; unsigned int i; PJ_COORD out; for (i = 0; i < 4; i++) out.v[i] = coo.v[Q->axis[i]] * Q->sign[i]; coo = out; } static void pj_axisswap_reverse_4d(PJ_COORD &coo, PJ *P) { struct pj_axisswap_data *Q = (struct pj_axisswap_data *)P->opaque; unsigned int i; PJ_COORD out; for (i = 0; i < 4; i++) out.v[Q->axis[i]] = coo.v[i] * Q->sign[i]; coo = out; } /***********************************************************************/ PJ *PJ_CONVERSION(axisswap, 0) { /***********************************************************************/ struct pj_axisswap_data *Q = static_cast<struct pj_axisswap_data *>( calloc(1, sizeof(struct pj_axisswap_data))); char *s; unsigned int i, j, n = 0; if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = (void *)Q; /* +order and +axis are mutually exclusive */ if (!pj_param_exists(P->params, "order") == !pj_param_exists(P->params, "axis")) { proj_log_error(P, _("must provide EITHER 'order' OR 'axis' parameter.")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_MUTUALLY_EXCLUSIVE_ARGS); } /* fill axis list with indices from 4-7 to simplify duplicate search further * down */ for (i = 0; i < 4; i++) { Q->axis[i] = i + 4; Q->sign[i] = 1; } /* if the "order" parameter is used */ if (pj_param_exists(P->params, "order")) { /* read axis order */ char *order = pj_param(P->ctx, P->params, "sorder").s; /* check that all characters are valid */ for (i = 0; i < strlen(order); i++) if (strchr("1234-,", order[i]) == nullptr) { proj_log_error(P, _("unknown axis '%c'"), order[i]); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* read axes numbers and signs */ s = order; n = 0; while (*s != '\0' && n < 4) { Q->axis[n] = abs(atoi(s)) - 1; if (Q->axis[n] > 3) { proj_log_error(P, _("invalid axis '%d'"), Q->axis[n]); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->sign[n++] = sign(atoi(s)); while (*s != '\0' && *s != ',') s++; if (*s == ',') s++; } } /* if the "axis" parameter is used */ if (pj_param_exists(P->params, "axis")) { /* parse the classic PROJ.4 enu axis specification */ for (i = 0; i < 3; i++) { switch (P->axis[i]) { case 'w': Q->sign[i] = -1; Q->axis[i] = 0; break; case 'e': Q->sign[i] = 1; Q->axis[i] = 0; break; case 's': Q->sign[i] = -1; Q->axis[i] = 1; break; case 'n': Q->sign[i] = 1; Q->axis[i] = 1; break; case 'd': Q->sign[i] = -1; Q->axis[i] = 2; break; case 'u': Q->sign[i] = 1; Q->axis[i] = 2; break; default: proj_log_error(P, _("unknown axis '%c'"), P->axis[i]); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } n = 3; } /* check for duplicate axes */ for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) { if (i == j) continue; if (Q->axis[i] == Q->axis[j]) { proj_log_error(P, _("axisswap: duplicate axes specified")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } /* only map fwd/inv functions that are possible with the given axis setup */ if (n == 4) { P->fwd4d = pj_axisswap_forward_4d; P->inv4d = pj_axisswap_reverse_4d; } if (n == 3 && Q->axis[0] < 3 && Q->axis[1] < 3 && Q->axis[2] < 3) { P->fwd3d = pj_axisswap_forward_3d; P->inv3d = pj_axisswap_reverse_3d; } if (n == 2) { if (Q->axis[0] == 1 && Q->sign[0] == 1 && Q->axis[1] == 0 && Q->sign[1] == 1) { P->fwd4d = swap_xy_4d; P->inv4d = swap_xy_4d; } else if (Q->axis[0] < 2 && Q->axis[1] < 2) { P->fwd = pj_axisswap_forward_2d; P->inv = pj_axisswap_reverse_2d; } } if (P->fwd4d == nullptr && P->fwd3d == nullptr && P->fwd == nullptr) { proj_log_error(P, _("axisswap: bad axis order")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (pj_param(P->ctx, P->params, "tangularunits").i) { P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; } else { P->left = PJ_IO_UNITS_WHATEVER; P->right = PJ_IO_UNITS_WHATEVER; } /* Preparation and finalization steps are skipped, since the reason */ /* d'etre of axisswap is to bring input coordinates in line with the */ /* the internally expected order (ENU), such that handling of offsets */ /* etc. can be done correctly in a later step of a pipeline */ P->skip_fwd_prepare = 1; P->skip_fwd_finalize = 1; P->skip_inv_prepare = 1; P->skip_inv_finalize = 1; return P; }
cpp
PROJ
data/projects/PROJ/src/conversions/topocentric.cpp
/****************************************************************************** * Project: PROJ * Purpose: Convert between geocentric coordinates and topocentric (ENU) *coordinates * ****************************************************************************** * 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. *****************************************************************************/ #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(topocentric, "Geocentric/Topocentric conversion"); // Notations and formulas taken from IOGP Publication 373-7-2 - // Geomatics Guidance Note number 7, part 2 - October 2020 namespace { // anonymous namespace struct pj_opaque { double X0; double Y0; double Z0; double sinphi0; double cosphi0; double sinlam0; double coslam0; }; } // anonymous namespace // Convert from geocentric to topocentric static void topocentric_fwd(PJ_COORD &coo, PJ *P) { struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); const double dX = coo.xyz.x - Q->X0; const double dY = coo.xyz.y - Q->Y0; const double dZ = coo.xyz.z - Q->Z0; coo.xyz.x = -dX * Q->sinlam0 + dY * Q->coslam0; coo.xyz.y = -dX * Q->sinphi0 * Q->coslam0 - dY * Q->sinphi0 * Q->sinlam0 + dZ * Q->cosphi0; coo.xyz.z = dX * Q->cosphi0 * Q->coslam0 + dY * Q->cosphi0 * Q->sinlam0 + dZ * Q->sinphi0; } // Convert from topocentric to geocentric static void topocentric_inv(PJ_COORD &coo, PJ *P) { struct pj_opaque *Q = static_cast<struct pj_opaque *>(P->opaque); const double x = coo.xyz.x; const double y = coo.xyz.y; const double z = coo.xyz.z; coo.xyz.x = Q->X0 - x * Q->sinlam0 - y * Q->sinphi0 * Q->coslam0 + z * Q->cosphi0 * Q->coslam0; coo.xyz.y = Q->Y0 + x * Q->coslam0 - y * Q->sinphi0 * Q->sinlam0 + z * Q->cosphi0 * Q->sinlam0; coo.xyz.z = Q->Z0 + y * Q->cosphi0 + z * Q->sinphi0; } /*********************************************************************/ PJ *PJ_CONVERSION(topocentric, 1) { /*********************************************************************/ 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 = static_cast<void *>(Q); // The topocentric origin can be specified either in geocentric coordinates // (X_0,Y_0,Z_0) or as geographic coordinates (lon_0,lat_0,h_0) // Checks: // - X_0 or lon_0 must be specified // - If X_0 is specified, the Y_0 and Z_0 must also be // - If lon_0 is specified, then lat_0 must also be // - If any of X_0, Y_0, Z_0 is specified, then any of lon_0,lat_0,h_0 must // not be, and vice versa. const auto hasX0 = pj_param_exists(P->params, "X_0"); const auto hasY0 = pj_param_exists(P->params, "Y_0"); const auto hasZ0 = pj_param_exists(P->params, "Z_0"); const auto hasLon0 = pj_param_exists(P->params, "lon_0"); const auto hasLat0 = pj_param_exists(P->params, "lat_0"); const auto hash0 = pj_param_exists(P->params, "h_0"); if (!hasX0 && !hasLon0) { proj_log_error(P, _("missing X_0 or lon_0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if ((hasX0 || hasY0 || hasZ0) && (hasLon0 || hasLat0 || hash0)) { proj_log_error( P, _("(X_0,Y_0,Z_0) and (lon_0,lat_0,h_0) are mutually exclusive")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_MUTUALLY_EXCLUSIVE_ARGS); } if (hasX0 && (!hasY0 || !hasZ0)) { proj_log_error(P, _("missing Y_0 and/or Z_0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } if (hasLon0 && !hasLat0) // allow missing h_0 { proj_log_error(P, _("missing lat_0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } // Pass a dummy ellipsoid definition that will be overridden just afterwards PJ *cart = proj_create(P->ctx, "+proj=cart +a=1"); if (cart == nullptr) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); /* inherit ellipsoid definition from P to cart */ pj_inherit_ellipsoid_def(P, cart); if (hasX0) { Q->X0 = pj_param(P->ctx, P->params, "dX_0").f; Q->Y0 = pj_param(P->ctx, P->params, "dY_0").f; Q->Z0 = pj_param(P->ctx, P->params, "dZ_0").f; // Compute lam0, phi0 from X0,Y0,Z0 PJ_XYZ xyz; xyz.x = Q->X0; xyz.y = Q->Y0; xyz.z = Q->Z0; const auto lpz = pj_inv3d(xyz, cart); Q->sinphi0 = sin(lpz.phi); Q->cosphi0 = cos(lpz.phi); Q->sinlam0 = sin(lpz.lam); Q->coslam0 = cos(lpz.lam); } else { // Compute X0,Y0,Z0 from lam0, phi0, h0 PJ_LPZ lpz; lpz.lam = P->lam0; lpz.phi = P->phi0; lpz.z = pj_param(P->ctx, P->params, "dh_0").f; const auto xyz = pj_fwd3d(lpz, cart); Q->X0 = xyz.x; Q->Y0 = xyz.y; Q->Z0 = xyz.z; Q->sinphi0 = sin(P->phi0); Q->cosphi0 = cos(P->phi0); Q->sinlam0 = sin(P->lam0); Q->coslam0 = cos(P->lam0); } proj_destroy(cart); P->fwd4d = topocentric_fwd; P->inv4d = topocentric_inv; P->left = PJ_IO_UNITS_CARTESIAN; P->right = PJ_IO_UNITS_CARTESIAN; return P; }
cpp
PROJ
data/projects/PROJ/src/conversions/set.cpp
#include "proj_internal.h" #include <errno.h> PROJ_HEAD(set, "Set coordinate value"); /* Projection specific elements for the PJ object */ namespace { // anonymous namespace struct Set { bool v1; bool v2; bool v3; bool v4; double v1_val; double v2_val; double v3_val; double v4_val; }; } // anonymous namespace static void set_fwd_inv(PJ_COORD &point, PJ *P) { struct Set *set = static_cast<struct Set *>(P->opaque); if (set->v1) point.v[0] = set->v1_val; if (set->v2) point.v[1] = set->v2_val; if (set->v3) point.v[2] = set->v3_val; if (set->v4) point.v[3] = set->v4_val; } PJ *OPERATION(set, 0) { P->inv4d = set_fwd_inv; P->fwd4d = set_fwd_inv; auto set = static_cast<struct Set *>(calloc(1, sizeof(struct Set))); P->opaque = set; if (nullptr == P->opaque) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); if (pj_param_exists(P->params, "v_1")) { set->v1 = true; set->v1_val = pj_param(P->ctx, P->params, "dv_1").f; } if (pj_param_exists(P->params, "v_2")) { set->v2 = true; set->v2_val = pj_param(P->ctx, P->params, "dv_2").f; } if (pj_param_exists(P->params, "v_3")) { set->v3 = true; set->v3_val = pj_param(P->ctx, P->params, "dv_3").f; } if (pj_param_exists(P->params, "v_4")) { set->v4 = true; set->v4_val = pj_param(P->ctx, P->params, "dv_4").f; } P->left = PJ_IO_UNITS_WHATEVER; P->right = PJ_IO_UNITS_WHATEVER; return P; }
cpp
PROJ
data/projects/PROJ/src/conversions/geoc.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Conversion from geographic to geocentric latitude and back. * Author: Thomas Knudsen (2017) * ****************************************************************************** * Copyright (c) 2017, SDFE, http://www.sdfe.dk * Copyright (c) 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 <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(geoc, "Geocentric Latitude"); /* Geographical to geocentric */ static void forward(PJ_COORD &coo, PJ *P) { coo = pj_geocentric_latitude(P, PJ_FWD, coo); } /* Geocentric to geographical */ static void inverse(PJ_COORD &coo, PJ *P) { coo = pj_geocentric_latitude(P, PJ_INV, coo); } static PJ *PJ_CONVERSION(geoc, 1) { P->inv4d = inverse; P->fwd4d = forward; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; P->is_latlong = 1; return P; }
cpp
PROJ
data/projects/PROJ/src/conversions/geocent.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Stub projection for geocentric. The transformation isn't * really done here since this code is 2D. The real transformation * is handled by pj_transform.c. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2002, 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. *****************************************************************************/ #include "proj.h" #include "proj_internal.h" PROJ_HEAD(geocent, "Geocentric") "\n\t"; static PJ_XY forward(PJ_LP lp, PJ *P) { PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = lp.lam; xy.y = lp.phi; return xy; } static PJ_LP inverse(PJ_XY xy, PJ *P) { PJ_LP lp = {0.0, 0.0}; (void)P; lp.phi = xy.y; lp.lam = xy.x; return lp; } PJ *PJ_CONVERSION(geocent, 0) { P->is_geocent = 1; P->x0 = 0.0; P->y0 = 0.0; P->inv = inverse; P->fwd = forward; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_CARTESIAN; return P; }
cpp
PROJ
data/projects/PROJ/src/conversions/cart.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Convert between ellipsoidal, geodetic coordinates and * cartesian, geocentric coordinates. * * Formally, this functionality is also found in the PJ_geocent.c * code. * * Actually, however, the PJ_geocent transformations are carried * out in concert between 2D stubs in PJ_geocent.c and 3D code * placed in pj_transform.c. * * For pipeline-style datum shifts, we do need direct access * to the full 3D interface for this functionality. * * Hence this code, which may look like "just another PJ_geocent" * but really is something substantially different. * * Author: Thomas Knudsen, [email protected] * ****************************************************************************** * Copyright (c) 2016, 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. *****************************************************************************/ #include "proj_internal.h" #include <math.h> PROJ_HEAD(cart, "Geodetic/cartesian conversions"); /************************************************************** CARTESIAN / GEODETIC CONVERSIONS *************************************************************** This material follows: Bernhard Hofmann-Wellenhof & Helmut Moritz: Physical Geodesy, 2nd edition. Springer, 2005. chapter 5.6: Coordinate transformations (HM, below), and Wikipedia: Geographic Coordinate Conversion, https://en.wikipedia.org/wiki/Geographic_coordinate_conversion (WP, below). The cartesian-to-geodetic conversion is based on Bowring's celebrated method: B. R. Bowring: Transformation from spatial to geographical coordinates Survey Review 23(181), pp. 323-327, 1976 (BB, below), but could probably use some TLC from a newer and faster algorithm: Toshio Fukushima: Transformation from Cartesian to Geodetic Coordinates Accelerated by Halley’s Method Journal of Geodesy, February 2006 (TF, below). Close to the poles, we avoid singularities by switching to an approximation requiring knowledge of the geocentric radius at the given latitude. For this, we use an adaptation of the formula given in: Wikipedia: Earth Radius https://en.wikipedia.org/wiki/Earth_radius#Radius_at_a_given_geodetic_latitude (Derivation and commentary at https://gis.stackexchange.com/q/20200) (WP2, below) These routines are probably not as robust at those in geocent.c, at least they haven't been through as heavy use as their geocent sisters. Some care has been taken to avoid singularities, but extreme cases (e.g. setting es, the squared eccentricity, to 1), will cause havoc. **************************************************************/ /*********************************************************************/ static double normal_radius_of_curvature(double a, double es, double sinphi) { /*********************************************************************/ if (es == 0) return a; /* This is from WP. HM formula 2-149 gives an a,b version */ return a / sqrt(1 - es * sinphi * sinphi); } /*********************************************************************/ static double geocentric_radius(double a, double b, double cosphi, double sinphi) { /********************************************************************* Return the geocentric radius at latitude phi, of an ellipsoid with semimajor axis a and semiminor axis b. This is from WP2, but uses hypot() for potentially better numerical robustness ***********************************************************************/ return hypot(a * a * cosphi, b * b * sinphi) / hypot(a * cosphi, b * sinphi); } /*********************************************************************/ static PJ_XYZ cartesian(PJ_LPZ geod, PJ *P) { /*********************************************************************/ PJ_XYZ xyz; const double cosphi = cos(geod.phi); const double sinphi = sin(geod.phi); const double N = normal_radius_of_curvature(P->a, P->es, sinphi); /* HM formula 5-27 (z formula follows WP) */ xyz.x = (N + geod.z) * cosphi * cos(geod.lam); xyz.y = (N + geod.z) * cosphi * sin(geod.lam); xyz.z = (N * (1 - P->es) + geod.z) * sinphi; return xyz; } /*********************************************************************/ static PJ_LPZ geodetic(PJ_XYZ cart, PJ *P) { /*********************************************************************/ PJ_LPZ lpz; /* Perpendicular distance from point to Z-axis (HM eq. 5-28) */ const double p = hypot(cart.x, cart.y); #if 0 /* HM eq. (5-37) */ const double theta = atan2 (cart.z * P->a, p * P->b); /* HM eq. (5-36) (from BB, 1976) */ const double c = cos(theta); const double s = sin(theta); #else const double y_theta = cart.z * P->a; const double x_theta = p * P->b; const double norm = hypot(y_theta, x_theta); const double c = norm == 0 ? 1 : x_theta / norm; const double s = norm == 0 ? 0 : y_theta / norm; #endif const double y_phi = cart.z + P->e2s * P->b * s * s * s; const double x_phi = p - P->es * P->a * c * c * c; const double norm_phi = hypot(y_phi, x_phi); double cosphi = norm_phi == 0 ? 1 : x_phi / norm_phi; double sinphi = norm_phi == 0 ? 0 : y_phi / norm_phi; if (x_phi <= 0) { // this happen on non-sphere ellipsoid when x,y,z is very close to 0 // there is no single solution to the cart->geodetic conversion in // that case, clamp to -90/90 deg and avoid a discontinuous boundary // near the poles lpz.phi = cart.z >= 0 ? M_HALFPI : -M_HALFPI; cosphi = 0; sinphi = cart.z >= 0 ? 1 : -1; } else { lpz.phi = atan(y_phi / x_phi); } lpz.lam = atan2(cart.y, cart.x); if (cosphi < 1e-6) { /* poleward of 89.99994 deg, we avoid division by zero */ /* by computing the height as the cartesian z value */ /* minus the geocentric radius of the Earth at the given */ /* latitude */ const double r = geocentric_radius(P->a, P->b, cosphi, sinphi); lpz.z = fabs(cart.z) - r; } else { const double N = normal_radius_of_curvature(P->a, P->es, sinphi); lpz.z = p / cosphi - N; } return lpz; } /* In effect, 2 cartesian coordinates of a point on the ellipsoid. Rather * pointless, but... */ static PJ_XY cart_forward(PJ_LP lp, PJ *P) { PJ_COORD point; point.lp = lp; point.lpz.z = 0; const auto xyz = cartesian(point.lpz, P); point.xyz = xyz; return point.xy; } /* And the other way round. Still rather pointless, but... */ static PJ_LP cart_reverse(PJ_XY xy, PJ *P) { PJ_COORD point; point.xy = xy; point.xyz.z = 0; const auto lpz = geodetic(point.xyz, P); point.lpz = lpz; return point.lp; } /*********************************************************************/ PJ *PJ_CONVERSION(cart, 1) { /*********************************************************************/ P->fwd3d = cartesian; P->inv3d = geodetic; P->fwd = cart_forward; P->inv = cart_reverse; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_CARTESIAN; return P; }
cpp