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();
182#if PROJ_VERSION_MAJOR>8 || (PROJ_VERSION_MAJOR==8 && PROJ_VERSION_MINOR>=1)
201 if ( !d->checkValidity() )
204 d->calculateTransforms( mContext );
206 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
224 if ( !d->checkValidity() )
227 d->calculateTransforms( mContext );
229 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
251 if ( !d->checkValidity() )
254 d->calculateTransforms( mContext );
256 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
271 return d->mSourceCRS;
281 if ( !d->mIsValid || d->mShortCircuit )
285 double x = point.
x();
286 double y = point.
y();
319 if ( !d->mIsValid || d->mShortCircuit )
343#ifdef COORDINATE_TRANSFORM_VERBOSE
355 double x = point.
x();
356 double y = point.
y();
357 double z = point.
z();
374 if ( !d->mIsValid || d->mShortCircuit )
395 double xd =
static_cast< double >( x ), yd =
static_cast< double >( y );
404 if ( !d->mIsValid || d->mShortCircuit )
430 if ( !d->mIsValid || d->mShortCircuit )
436 const int nVertices = poly.size();
438 QVector<double> x( nVertices );
439 QVector<double> y( nVertices );
440 QVector<double> z( nVertices );
441 double *destX = x.data();
442 double *destY = y.data();
443 double *destZ = z.data();
445 const QPointF *polyData = poly.constData();
446 for (
int i = 0; i < nVertices; ++i )
448 *destX++ = polyData->x();
449 *destY++ = polyData->y();
465 QPointF *destPoint = poly.data();
466 const double *srcX = x.constData();
467 const double *srcY = y.constData();
468 for (
int i = 0; i < nVertices; ++i )
470 destPoint->rx() = *srcX++;
471 destPoint->ry() = *srcY++;
476 if ( !err.isEmpty() )
484 if ( !d->mIsValid || d->mShortCircuit )
487 Q_ASSERT( x.size() == y.size() );
510 if ( !d->mIsValid || d->mShortCircuit )
513 Q_ASSERT( x.size() == y.size() );
523 const int vectorSize = x.size();
524 QVector<double> xd( x.size() );
525 QVector<double> yd( y.size() );
526 QVector<double> zd( z.size() );
528 double *destX = xd.data();
529 double *destY = yd.data();
530 double *destZ = zd.data();
532 const float *srcX = x.constData();
533 const float *srcY = y.constData();
534 const float *srcZ = z.constData();
536 for (
int i = 0; i < vectorSize; ++i )
538 *destX++ =
static_cast< double >( *srcX++ );
539 *destY++ =
static_cast< double >( *srcY++ );
540 *destZ++ =
static_cast< double >( *srcZ++ );
546 float *destFX = x.data();
547 float *destFY = y.data();
548 float *destFZ = z.data();
549 const double *srcXD = xd.constData();
550 const double *srcYD = yd.constData();
551 const double *srcZD = zd.constData();
552 for (
int i = 0; i < vectorSize; ++i )
554 *destFX++ =
static_cast< float >( *srcXD++ );
555 *destFY++ =
static_cast< float >( *srcYD++ );
556 *destFZ++ =
static_cast< float >( *srcZD++ );
574 if ( !d->mIsValid || d->mShortCircuit )
585 if ( d->mGeographicToWebMercator &&
586 ( ( direction == Qgis::TransformDirection::Forward && !d->mIsReversed ) ||
587 ( direction == Qgis::TransformDirection::Reverse && d->mIsReversed ) ) )
594 constexpr double EPS = 1e-1;
595 if ( yMin < -90 + EPS )
597 if ( yMax < -90 + EPS )
598 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
601 if ( yMax > 90 - EPS )
603 if ( yMin > 90 - EPS )
604 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
613 const int nPoints = 1000;
614 const double d = std::sqrt( ( rect.
width() * ( yMax - yMin ) ) / std::pow( std::sqrt(
static_cast< double >( nPoints ) ) - 1, 2.0 ) );
615 const int nXPoints = std::min(
static_cast< int >( std::ceil( rect.
width() / d ) ) + 1, 1000 );
616 const int nYPoints = std::min(
static_cast< int >( std::ceil( ( yMax - yMin ) / d ) ) + 1, 1000 );
623 QVector<double> x( nXPoints * nYPoints );
624 QVector<double> y( nXPoints * nYPoints );
625 QVector<double> z( nXPoints * nYPoints );
627 QgsDebugMsgLevel( QStringLiteral(
"Entering transformBoundingBox..." ), 4 );
631 const double dx = rect.
width() /
static_cast< double >( nXPoints - 1 );
632 const double dy = ( yMax - yMin ) /
static_cast< double >( nYPoints - 1 );
634 double pointY = yMin;
636 for (
int i = 0; i < nYPoints ; i++ )
642 for (
int j = 0; j < nXPoints; j++ )
644 x[( i * nXPoints ) + j] = pointX;
645 y[( i * nXPoints ) + j] = pointY;
647 z[( i * nXPoints ) + j] = 0.0;
658 transformCoords( nXPoints * nYPoints, x.data(), y.data(), z.data(), direction );
669 for (
int i = 0; i < nXPoints * nYPoints; i++ )
671 if ( !std::isfinite( x[i] ) || !std::isfinite( y[i] ) )
676 if ( handle180Crossover )
690 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
693 if ( handle180Crossover )
714 if ( !d->mIsValid || d->mShortCircuit )
717 if ( !d->mSourceCRS.isValid() )
720 "The coordinates can not be reprojected. The CRS is: %1" )
721 .arg( d->mSourceCRS.toProj() ), QObject::tr(
"CRS" ) );
724 if ( !d->mDestCRS.isValid() )
727 "The coordinates can not be reprojected. The CRS is: %1" ).arg( d->mDestCRS.toProj() ), QObject::tr(
"CRS" ) );
731 std::vector< int > zNanPositions;
732 for (
int i = 0; i < numPoints; i++ )
734 if ( std::isnan( z[i] ) )
736 zNanPositions.push_back( i );
741 std::vector< double > xprev( numPoints );
742 memcpy( xprev.data(), x,
sizeof(
double ) * numPoints );
743 std::vector< double > yprev( numPoints );
744 memcpy( yprev.data(), y,
sizeof(
double ) * numPoints );
745 std::vector< double > zprev( numPoints );
746 memcpy( zprev.data(), z,
sizeof(
double ) * numPoints );
748 const bool useTime = !std::isnan( d->mDefaultTime );
749 std::vector< double > t( useTime ? numPoints : 0, d->mDefaultTime );
751#ifdef COORDINATE_TRANSFORM_VERBOSE
754 QgsDebugMsgLevel( QStringLiteral(
"[[[[[[ Number of points to transform: %1 ]]]]]]" ).arg( numPoints ), 2 );
759 QgsDebugMsgLevel( QStringLiteral(
"No QgsCoordinateTransformContext context set for transform" ), 4 );
766 ProjData projData = d->threadLocalProjData();
770 proj_errno_reset( projData );
771 proj_trans_generic( projData, ( direction == Qgis::TransformDirection::Forward && !d->mIsReversed ) || ( direction == Qgis::TransformDirection::Reverse && d->mIsReversed ) ? PJ_FWD : PJ_INV,
772 x,
sizeof(
double ), numPoints,
773 y,
sizeof(
double ), numPoints,
774 z,
sizeof(
double ), numPoints,
775 useTime ? t.data() :
nullptr,
sizeof(
double ), useTime ? numPoints : 0 );
785 if ( numPoints == 1 )
787 projResult = proj_errno( projData );
788 actualRes = projResult;
792 actualRes = proj_errno( projData );
794 if ( actualRes == 0 )
798 if ( std::any_of( x, x + numPoints, [](
double v ) {
return std::isinf( v ); } )
799 || std::any_of( y, y + numPoints, [](
double v ) {
return std::isinf( v ); } )
800 || std::any_of( z, z + numPoints, [](
double v ) {
return std::isinf( v ); } ) )
806 mFallbackOperationOccurred =
false;
808 && ( d->mAvailableOpCount > 1 || d->mAvailableOpCount == -1 )
809 && ( d->mAllowFallbackTransforms || mBallparkTransformsAreAppropriate ) )
812 if (
PJ *
transform = d->threadLocalFallbackProjData() )
816 proj_trans_generic(
transform, direction == Qgis::TransformDirection::Forward ? PJ_FWD : PJ_INV,
817 xprev.data(),
sizeof(
double ), numPoints,
818 yprev.data(),
sizeof(
double ), numPoints,
819 zprev.data(),
sizeof(
double ), numPoints,
820 useTime ? t.data() :
nullptr,
sizeof(
double ), useTime ? numPoints : 0 );
829 if ( numPoints == 1 )
834 projResult = std::isinf( xprev[0] ) || std::isinf( yprev[0] ) || std::isinf( zprev[0] ) ? 1 : 0;
837 if ( projResult == 0 )
839 memcpy( x, xprev.data(),
sizeof(
double ) * numPoints );
840 memcpy( y, yprev.data(),
sizeof(
double ) * numPoints );
841 memcpy( z, zprev.data(),
sizeof(
double ) * numPoints );
842 mFallbackOperationOccurred =
true;
845 if ( !mBallparkTransformsAreAppropriate && !mDisableFallbackHandler && sFallbackOperationOccurredHandler )
847 sFallbackOperationOccurredHandler( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation );
849 const QString warning = QStringLiteral(
"A fallback coordinate operation was used between %1 and %2" ).arg( d->mSourceCRS.authid(),
850 d->mDestCRS.authid() );
851 qWarning(
"%s", warning.toLatin1().constData() );
857 for (
const int &pos : zNanPositions )
859 z[pos] = std::numeric_limits<double>::quiet_NaN();
862 if ( projResult != 0 )
867 for (
int i = 0; i < numPoints; ++i )
869 points += QStringLiteral(
"(%1, %2)\n" ).arg( x[i], 0,
'f' ).arg( y[i], 0,
'f' );
872 const QString dir = ( direction == Qgis::TransformDirection::Forward ) ? QObject::tr(
"forward transform" ) : QObject::tr(
"inverse transform" );
874 const QString msg = QObject::tr(
"%1 of\n"
879 projResult < 0 ? QString::fromUtf8( proj_errno_string( projResult ) ) : QObject::tr(
"Fallback transform failed" ) );
883 if ( msg != mLastError )
885 QgsDebugError(
"Projection failed emitting invalid transform signal: " + msg );
893#ifdef COORDINATE_TRANSFORM_VERBOSE
894 QgsDebugMsgLevel( QStringLiteral(
"[[[[[[ Projected %1, %2 to %3, %4 ]]]]]]" )
895 .arg( xorg, 0,
'g', 15 ).arg( yorg, 0,
'g', 15 )
896 .arg( *x, 0,
'g', 15 ).arg( *y, 0,
'g', 15 ), 2 );
907 return !d->mIsValid || d->mShortCircuit;
912 return d->mProjCoordinateOperation;
917 ProjData projData = d->threadLocalProjData();
924 d->mProjCoordinateOperation = operation;
925 d->mShouldReverseCoordinateOperation =
false;
931 d->mAllowFallbackTransforms = allowed;
936 return d->mAllowFallbackTransforms;
941 mBallparkTransformsAreAppropriate = appropriate;
946 mDisableFallbackHandler = disabled;
951 return mFallbackOperationOccurred;
958 proj = QApplication::applicationDirPath()
959 +
"/share/proj/" + QString( name );
963 return proj.toUtf8();
971 const QString sourceKey = src.
authid().isEmpty() ?
973 const QString destKey = dest.
authid().isEmpty() ?
976 if ( sourceKey.isEmpty() || destKey.isEmpty() )
983 const QList< QgsCoordinateTransform > values = sTransforms.values( qMakePair( sourceKey, destKey ) );
984 for (
auto valIt = values.constBegin(); valIt != values.constEnd(); ++valIt )
986 if ( ( *valIt ).coordinateOperation() == coordinateOperationProj
987 && ( *valIt ).allowFallbackTransforms() == allowFallback
995 const bool hasContext = mHasContext;
1002 mHasContext = hasContext;
1011void QgsCoordinateTransform::addToCache()
1013 if ( !d->mSourceCRS.isValid() || !d->mDestCRS.isValid() )
1016 const QString sourceKey = d->mSourceCRS.authid().isEmpty() ?
1018 const QString destKey = d->mDestCRS.authid().isEmpty() ?
1021 if ( sourceKey.isEmpty() || destKey.isEmpty() )
1025 if ( sDisableCache )
1028 sTransforms.insert( qMakePair( sourceKey, destKey ), *
this );
1034 return d->mSourceDatumTransform;
1042 d->mSourceDatumTransform = dt;
1049 return d->mDestinationDatumTransform;
1057 d->mDestinationDatumTransform = dt;
1064 if ( sDisableCache )
1069 sDisableCache =
true;
1072 sTransforms.clear();
1075void QgsCoordinateTransform::removeFromCacheObjectsBelongingToCurrentThread(
void *pj_context )
1081 if ( sDisableCache )
1086 if ( sDisableCache )
1089 for (
auto it = sTransforms.begin(); it != sTransforms.end(); )
1091 auto &v = it.value();
1092 if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
1093 it = sTransforms.erase( it );
1103 const double distSourceUnits = std::sqrt( source1.
sqrDist( source2 ) );
1106 const double distDestUnits = std::sqrt( dest1.
sqrDist( dest2 ) );
1107 return distDestUnits / distSourceUnits;
1112 QgsCoordinateTransformPrivate::setCustomMissingRequiredGridHandler( handler );
1117 QgsCoordinateTransformPrivate::setCustomMissingPreferredGridHandler( handler );
1122 QgsCoordinateTransformPrivate::setCustomCoordinateOperationCreationErrorHandler( handler );
1127 QgsCoordinateTransformPrivate::setCustomMissingGridUsedByContextHandler( handler );
1132 sFallbackOperationOccurredHandler = handler;
1137 QgsCoordinateTransformPrivate::setDynamicCrsToDynamicCrsWarningHandler( handler );
@ 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
Flags for raster layer temporal capabilities.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
double coordinateEpoch() const
Returns the coordinate epoch, as a decimal year.
QString toWkt(WktVariant variant=WKT1_GDAL, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
QString celestialBodyName() const SIP_THROW(QgsNotSupportedException)
Attempts to retrieve the name of the celestial body associated with the CRS (e.g.
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 SIP_HOLDGIL
Returns the squared distance between this point a specified x, y coordinate.
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.
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
void setXMaximum(double x) SIP_HOLDGIL
Set the maximum x value.
void setXMinimum(double x) SIP_HOLDGIL
Set the minimum x value.
void setMinimal() SIP_HOLDGIL
Set a rectangle so that min corner is at max and max corner is at min.
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
bool isEmpty() const
Returns true if the rectangle is empty.
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.
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
const QgsCoordinateReferenceSystem & crs