33#include <QApplication>
49QReadWriteLock QgsCoordinateTransform::sCacheLock;
51bool QgsCoordinateTransform::sDisableCache =
false;
55 const QString &desiredOperation )> QgsCoordinateTransform::sFallbackOperationOccurredHandler =
nullptr;
59 d =
new QgsCoordinateTransformPrivate();
65 d =
new QgsCoordinateTransformPrivate( source, destination, mContext );
68 mIgnoreImpossible =
true;
80 if ( !d->checkValidity() )
84 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
92 mBallparkTransformsAreAppropriate =
true;
98 d =
new QgsCoordinateTransformPrivate( source, destination, mContext );
105 mIgnoreImpossible =
true;
113 if ( !d->checkValidity() )
117 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
125 mBallparkTransformsAreAppropriate =
true;
130 d =
new QgsCoordinateTransformPrivate( source, destination, sourceDatumTransform, destinationDatumTransform );
135 if ( !d->checkValidity() )
139 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
148 : mContext( o.mContext )
150 , mHasContext( o.mHasContext )
156 , mIgnoreImpossible( false )
157 , mBallparkTransformsAreAppropriate( false )
158 , mDisableFallbackHandler( false )
159 , mFallbackOperationOccurred( false )
168 mHasContext = o.mHasContext;
170 mContext = o.mContext;
171 mLastError = QString();
179 return d->mSourceCRS == other.d->mSourceCRS
180 && d->mDestCRS == other.d->mDestCRS
181 && mBallparkTransformsAreAppropriate == other.mBallparkTransformsAreAppropriate
182 && d->mProjCoordinateOperation == other.d->mProjCoordinateOperation
188 return !( *
this == other );
196#if PROJ_VERSION_MAJOR>8 || (PROJ_VERSION_MAJOR==8 && PROJ_VERSION_MINOR>=1)
215 if ( !d->checkValidity() )
218 d->calculateTransforms( mContext );
220 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
238 if ( !d->checkValidity() )
241 d->calculateTransforms( mContext );
243 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
265 if ( !d->checkValidity() )
268 d->calculateTransforms( mContext );
270 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
285 return d->mSourceCRS;
295 if ( !d->mIsValid || d->mShortCircuit )
299 double x = point.
x();
300 double y = point.
y();
333 if ( !d->mIsValid || d->mShortCircuit )
357#ifdef COORDINATE_TRANSFORM_VERBOSE
369 double x = point.
x();
370 double y = point.
y();
371 double z = point.
z();
388 if ( !d->mIsValid || d->mShortCircuit )
409 double xd =
static_cast< double >( x ), yd =
static_cast< double >( y );
418 if ( !d->mIsValid || d->mShortCircuit )
444 if ( !d->mIsValid || d->mShortCircuit )
450 const int nVertices = poly.size();
452 QVector<double> x( nVertices );
453 QVector<double> y( nVertices );
454 QVector<double> z( nVertices );
455 double *destX = x.data();
456 double *destY = y.data();
457 double *destZ = z.data();
459 const QPointF *polyData = poly.constData();
460 for (
int i = 0; i < nVertices; ++i )
462 *destX++ = polyData->x();
463 *destY++ = polyData->y();
479 QPointF *destPoint = poly.data();
480 const double *srcX = x.constData();
481 const double *srcY = y.constData();
482 for (
int i = 0; i < nVertices; ++i )
484 destPoint->rx() = *srcX++;
485 destPoint->ry() = *srcY++;
490 if ( !err.isEmpty() )
498 if ( !d->mIsValid || d->mShortCircuit )
501 Q_ASSERT( x.size() == y.size() );
524 if ( !d->mIsValid || d->mShortCircuit )
527 Q_ASSERT( x.size() == y.size() );
537 const int vectorSize = x.size();
538 QVector<double> xd( x.size() );
539 QVector<double> yd( y.size() );
540 QVector<double> zd( z.size() );
542 double *destX = xd.data();
543 double *destY = yd.data();
544 double *destZ = zd.data();
546 const float *srcX = x.constData();
547 const float *srcY = y.constData();
548 const float *srcZ = z.constData();
550 for (
int i = 0; i < vectorSize; ++i )
552 *destX++ =
static_cast< double >( *srcX++ );
553 *destY++ =
static_cast< double >( *srcY++ );
554 *destZ++ =
static_cast< double >( *srcZ++ );
560 float *destFX = x.data();
561 float *destFY = y.data();
562 float *destFZ = z.data();
563 const double *srcXD = xd.constData();
564 const double *srcYD = yd.constData();
565 const double *srcZD = zd.constData();
566 for (
int i = 0; i < vectorSize; ++i )
568 *destFX++ =
static_cast< float >( *srcXD++ );
569 *destFY++ =
static_cast< float >( *srcYD++ );
570 *destFZ++ =
static_cast< float >( *srcZD++ );
588 if ( !d->mIsValid || d->mShortCircuit )
599 if ( d->mGeographicToWebMercator &&
608 constexpr double EPS = 1e-1;
609 if ( yMin < -90 + EPS )
611 if ( yMax < -90 + EPS )
612 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
615 if ( yMax > 90 - EPS )
617 if ( yMin > 90 - EPS )
618 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
627 const int nPoints = 1000;
628 const double dst = std::sqrt( ( rect.
width() * ( yMax - yMin ) ) / std::pow( std::sqrt(
static_cast< double >( nPoints ) ) - 1, 2.0 ) );
629 const int nXPoints = std::min(
static_cast< int >( std::ceil( rect.
width() / dst ) ) + 1, 1000 );
630 const int nYPoints = std::min(
static_cast< int >( std::ceil( ( yMax - yMin ) / dst ) ) + 1, 1000 );
635 std::vector<double> x( nXPoints *
static_cast< std::size_t
>( nYPoints ) );
636 std::vector<double> y( nXPoints *
static_cast< std::size_t
>( nYPoints ) );
637 std::vector<double> z( nXPoints *
static_cast< std::size_t
>( nYPoints ) );
639 QgsDebugMsgLevel( QStringLiteral(
"Entering transformBoundingBox..." ), 4 );
643 const double dx = rect.
width() /
static_cast< double >( nXPoints - 1 );
644 const double dy = ( yMax - yMin ) /
static_cast< double >( nYPoints - 1 );
646 double pointY = yMin;
648 for (
int i = 0; i < nYPoints ; i++ )
654 for (
int j = 0; j < nXPoints; j++ )
656 x[( i * nXPoints ) + j] = pointX;
657 y[( i * nXPoints ) + j] = pointY;
659 z[( i * nXPoints ) + j] = 0.0;
670 transformCoords( nXPoints * nYPoints, x.data(), y.data(), z.data(), direction );
680 bool doHandle180Crossover =
false;
683 const double xMin = std::fmod( x[0], 180.0 );
684 const double xMax = std::fmod( x[nXPoints - 1], 180.0 );
685 if ( handle180Crossover
688 && xMin > 0.0 && xMin <= 180.0 && xMax < 0.0 && xMax >= -180.0 )
690 doHandle180Crossover =
true;
695 for (
int i = 0; i < nXPoints * nYPoints; i++ )
697 if ( !std::isfinite( x[i] ) || !std::isfinite( y[i] ) )
702 if ( doHandle180Crossover )
716 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
719 if ( doHandle180Crossover )
740 if ( !d->mIsValid || d->mShortCircuit )
743 if ( !d->mSourceCRS.isValid() )
746 "The coordinates can not be reprojected. The CRS is: %1" )
747 .arg( d->mSourceCRS.toProj() ), QObject::tr(
"CRS" ) );
750 if ( !d->mDestCRS.isValid() )
753 "The coordinates can not be reprojected. The CRS is: %1" ).arg( d->mDestCRS.toProj() ), QObject::tr(
"CRS" ) );
757 std::vector< int > zNanPositions;
758 for (
int i = 0; i < numPoints; i++ )
760 if ( std::isnan( z[i] ) )
762 zNanPositions.push_back( i );
767 std::vector< double > xprev( numPoints );
768 memcpy( xprev.data(), x,
sizeof(
double ) * numPoints );
769 std::vector< double > yprev( numPoints );
770 memcpy( yprev.data(), y,
sizeof(
double ) * numPoints );
771 std::vector< double > zprev( numPoints );
772 memcpy( zprev.data(), z,
sizeof(
double ) * numPoints );
774 const bool useTime = !std::isnan( d->mDefaultTime );
775 std::vector< double > t( useTime ? numPoints : 0, d->mDefaultTime );
777#ifdef COORDINATE_TRANSFORM_VERBOSE
780 QgsDebugMsgLevel( QStringLiteral(
"[[[[[[ Number of points to transform: %1 ]]]]]]" ).arg( numPoints ), 2 );
786 QgsDebugMsgLevel( QStringLiteral(
"No QgsCoordinateTransformContext context set for transform" ), 4 );
794 ProjData projData = d->threadLocalProjData();
798 proj_errno_reset( projData );
800 x,
sizeof( double ), numPoints,
801 y,
sizeof(
double ), numPoints,
802 z,
sizeof( double ), numPoints,
803 useTime ? t.data() :
nullptr,
sizeof( double ), useTime ? numPoints : 0 );
813 if ( numPoints == 1 )
815 projResult = proj_errno( projData );
816 actualRes = projResult;
820 actualRes = proj_errno( projData );
822 if ( actualRes == 0 )
826 if ( std::any_of( x, x + numPoints, [](
double v ) {
return std::isinf( v ); } )
827 || std::any_of( y, y + numPoints, [](
double v ) {
return std::isinf( v ); } )
828 || std::any_of( z, z + numPoints, [](
double v ) {
return std::isinf( v ); } ) )
834 mFallbackOperationOccurred =
false;
835 bool errorOccurredDuringFallbackOperation =
false;
837 && ( d->mAvailableOpCount > 1 || d->mAvailableOpCount == -1 )
838 && ( d->mAllowFallbackTransforms || mBallparkTransformsAreAppropriate ) )
841 if (
PJ *
transform = d->threadLocalFallbackProjData() )
845 memcpy( x, xprev.data(),
sizeof(
double ) * numPoints );
846 memcpy( y, yprev.data(),
sizeof(
double ) * numPoints );
847 memcpy( z, zprev.data(),
sizeof(
double ) * numPoints );
849 x,
sizeof( double ), numPoints,
850 y,
sizeof(
double ), numPoints,
851 z,
sizeof( double ), numPoints,
852 useTime ? t.data() :
nullptr,
sizeof( double ), useTime ? numPoints : 0 );
861 if ( numPoints == 1 )
867 errorOccurredDuringFallbackOperation = std::isinf( x[0] ) || std::isinf( y[0] ) || std::isinf( z[0] );
870 if ( !errorOccurredDuringFallbackOperation )
872 mFallbackOperationOccurred =
true;
875 if ( !mBallparkTransformsAreAppropriate && !mDisableFallbackHandler && sFallbackOperationOccurredHandler )
877 sFallbackOperationOccurredHandler( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation );
879 const QString warning = QStringLiteral(
"A fallback coordinate operation was used between %1 and %2" ).arg( d->mSourceCRS.authid(),
880 d->mDestCRS.authid() );
881 qWarning(
"%s", warning.toLatin1().constData() );
887 for (
const int &pos : zNanPositions )
889 z[pos] = std::numeric_limits<double>::quiet_NaN();
892 if ( projResult != 0 || errorOccurredDuringFallbackOperation )
897 const QChar delim = numPoints > 1 ?
'\n' :
' ';
898 for (
int i = 0; i < numPoints; ++i )
900 points += QStringLiteral(
"(%1, %2)" ).arg( xprev[i], 0,
'f' ).arg( yprev[i], 0,
'f' ) + delim;
905#if PROJ_VERSION_MAJOR>=8
907 const QString projError = !errorOccurredDuringFallbackOperation ? QString::fromUtf8( proj_context_errno_string( projContext, projResult ) ) : QObject::tr(
"Fallback transform failed" );
909 const QString projError = !errorOccurredDuringFallbackOperation ? QString::fromUtf8( proj_errno_string( projResult ) ) : QObject::tr(
"Fallback transform failed" );
912 const QString msg = QObject::tr(
"%1 (%2 to %3) of%4%5Error: %6" )
921 if ( msg != mLastError )
923 QgsDebugError(
"Projection failed emitting invalid transform signal: " + msg );
931#ifdef COORDINATE_TRANSFORM_VERBOSE
932 QgsDebugMsgLevel( QStringLiteral(
"[[[[[[ Projected %1, %2 to %3, %4 ]]]]]]" )
933 .arg( xorg, 0,
'g', 15 ).arg( yorg, 0,
'g', 15 )
934 .arg( *x, 0,
'g', 15 ).arg( *y, 0,
'g', 15 ), 2 );
945 return !d->mIsValid || d->mShortCircuit;
950 return d->mIsValid && d->mHasVerticalComponent;
955 return d->mProjCoordinateOperation;
960 ProjData projData = d->threadLocalProjData();
967 d->mProjCoordinateOperation = operation;
968 d->mShouldReverseCoordinateOperation =
false;
974 d->mAllowFallbackTransforms = allowed;
979 return d->mAllowFallbackTransforms;
984 mBallparkTransformsAreAppropriate = appropriate;
989 mDisableFallbackHandler = disabled;
994 return mFallbackOperationOccurred;
1001 proj = QApplication::applicationDirPath()
1002 +
"/share/proj/" + QString( name );
1006 return proj.toUtf8();
1014 const QString sourceKey = src.
authid().isEmpty() ?
1016 const QString destKey = dest.
authid().isEmpty() ?
1019 if ( sourceKey.isEmpty() || destKey.isEmpty() )
1023 if ( sDisableCache )
1026 const QList< QgsCoordinateTransform > values = sTransforms.values( qMakePair( sourceKey, destKey ) );
1027 for (
auto valIt = values.constBegin(); valIt != values.constEnd(); ++valIt )
1029 if ( ( *valIt ).coordinateOperation() == coordinateOperationProj
1030 && ( *valIt ).allowFallbackTransforms() == allowFallback
1038 const bool hasContext = mHasContext;
1045 mHasContext = hasContext;
1054void QgsCoordinateTransform::addToCache()
1056 if ( !d->mSourceCRS.isValid() || !d->mDestCRS.isValid() )
1059 const QString sourceKey = d->mSourceCRS.authid().isEmpty() ?
1061 const QString destKey = d->mDestCRS.authid().isEmpty() ?
1064 if ( sourceKey.isEmpty() || destKey.isEmpty() )
1068 if ( sDisableCache )
1071 sTransforms.insert( qMakePair( sourceKey, destKey ), *
this );
1077 return d->mSourceDatumTransform;
1085 d->mSourceDatumTransform = dt;
1092 return d->mDestinationDatumTransform;
1100 d->mDestinationDatumTransform = dt;
1107 if ( sDisableCache )
1112 sDisableCache =
true;
1115 sTransforms.clear();
1118void QgsCoordinateTransform::removeFromCacheObjectsBelongingToCurrentThread(
void *pj_context )
1124 if ( sDisableCache )
1129 if ( sDisableCache )
1132 for (
auto it = sTransforms.begin(); it != sTransforms.end(); )
1134 auto &v = it.value();
1135 if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
1136 it = sTransforms.erase( it );
1146 const double distSourceUnits = std::sqrt( source1.
sqrDist( source2 ) );
1149 const double distDestUnits = std::sqrt( dest1.
sqrDist( dest2 ) );
1150 return distDestUnits / distSourceUnits;
1155 QgsCoordinateTransformPrivate::setCustomMissingRequiredGridHandler( handler );
1160 QgsCoordinateTransformPrivate::setCustomMissingPreferredGridHandler( handler );
1165 QgsCoordinateTransformPrivate::setCustomCoordinateOperationCreationErrorHandler( handler );
1170 QgsCoordinateTransformPrivate::setCustomMissingGridUsedByContextHandler( handler );
1175 sFallbackOperationOccurredHandler = handler;
1180 QgsCoordinateTransformPrivate::setDynamicCrsToDynamicCrsWarningHandler( handler );
QFlags< CoordinateTransformationFlag > CoordinateTransformationFlags
Coordinate transformation flags.
@ Preferred
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
@ BallparkTransformsAreAppropriate
Indicates that approximate "ballpark" results are appropriate for this coordinate transform....
@ IgnoreImpossibleTransformations
Indicates that impossible transformations (such as those which attempt to transform between two diffe...
TransformDirection
Indicates the direction (forward or inverse) of a transform.
@ Forward
Forward transform (from source to destination)
@ Reverse
Reverse/inverse transform (from destination to source)
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QString toWkt(Qgis::CrsWktVariant variant=Qgis::CrsWktVariant::Wkt1Gdal, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
QString celestialBodyName() const
Attempts to retrieve the name of the celestial body associated with the CRS (e.g.
double coordinateEpoch() const
Returns the coordinate epoch, as a decimal year.
Contains information about the context in which a coordinate transform is executed.
Custom exception class for Coordinate Reference System related exceptions.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
A class to represent a 2D point.
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
static PJ_CONTEXT * get()
Returns a thread local instance of a proj context, safe for use in the current thread.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QgsCoordinateTransformContext transformContext
The QgsReadWriteLocker class is a convenience class that simplifies locking and unlocking QReadWriteL...
A rectangle specified with double values.
Q_INVOKABLE QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
void setXMinimum(double x)
Set the minimum x value.
void setXMaximum(double x)
Set the maximum x value.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
void setNull()
Mark a rectangle as being null (holding no spatial information).
Class for storage of 3D vectors similar to QVector3D, with the difference that it uses double precisi...
double y() const
Returns Y coordinate.
double z() const
Returns Z coordinate.
double x() const
Returns X coordinate.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
bool qgsNanCompatibleEquals(double a, double b)
Compare two doubles, treating nan values as equal.
struct projCtx_t PJ_CONTEXT
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
const QgsCoordinateReferenceSystem & crs