Use c++17 std::clamp instead of qBound

This commit is contained in:
Nyall Dawson 2021-03-21 08:44:08 +10:00
parent f3a81ebda8
commit 08ca000e71
29 changed files with 119 additions and 90 deletions

View File

@ -64,14 +64,14 @@ static QByteArray createPlaneVertexData( int res, float side, float vertScale, f
// Iterate over z // Iterate over z
for ( int j = -1; j <= resolution.height(); ++j ) for ( int j = -1; j <= resolution.height(); ++j )
{ {
int jBound = qBound( 0, j, jMax ); int jBound = std::clamp( j, 0, jMax );
const float z = z0 + static_cast<float>( jBound ) * dz; const float z = z0 + static_cast<float>( jBound ) * dz;
const float v = static_cast<float>( jBound ) * dv; const float v = static_cast<float>( jBound ) * dv;
// Iterate over x // Iterate over x
for ( int i = -1; i <= resolution.width(); ++i ) for ( int i = -1; i <= resolution.width(); ++i )
{ {
int iBound = qBound( 0, i, iMax ); int iBound = std::clamp( i, 0, iMax );
const float x = x0 + static_cast<float>( iBound ) * dx; const float x = x0 + static_cast<float>( iBound ) * dx;
const float u = static_cast<float>( iBound ) * du; const float u = static_cast<float>( iBound ) * du;
@ -95,10 +95,10 @@ static QByteArray createPlaneVertexData( int res, float side, float vertScale, f
// calculate normal coordinates // calculate normal coordinates
#define zAt( ii, jj ) zData[ jj * resolution.width() + ii ] * vertScale #define zAt( ii, jj ) zData[ jj * resolution.width() + ii ] * vertScale
float zi0 = zAt( qBound( 0, i - 1, iMax ), jBound ); float zi0 = zAt( std::clamp( i - 1, 0, iMax ), jBound );
float zi1 = zAt( qBound( 0, i + 1, iMax ), jBound ); float zi1 = zAt( std::clamp( i + 1, 0, iMax ), jBound );
float zj0 = zAt( iBound, qBound( 0, j - 1, jMax ) ); float zj0 = zAt( iBound, std::clamp( j - 1, 0, jMax ) );
float zj1 = zAt( iBound, qBound( 0, j + 1, jMax ) ); float zj1 = zAt( iBound, std::clamp( j + 1, 0, jMax ) );
QVector3D n; QVector3D n;
if ( std::isnan( zi0 ) || std::isnan( zi1 ) || std::isnan( zj0 ) || std::isnan( zj1 ) ) if ( std::isnan( zi0 ) || std::isnan( zi1 ) || std::isnan( zj0 ) || std::isnan( zj1 ) )
@ -137,8 +137,8 @@ static QByteArray createPlaneVertexData( int res, float side, float vertScale, f
inline int ijToHeightMapIndex( int i, int j, int resX, int resZ ) inline int ijToHeightMapIndex( int i, int j, int resX, int resZ )
{ {
i = qBound( 1, i, resX ) - 1; i = std::clamp( i, 1, resX ) - 1;
j = qBound( 1, j, resZ ) - 1; j = std::clamp( j, 1, resZ ) - 1;
return j * resX + i; return j * resX + i;
} }

View File

@ -293,8 +293,8 @@ float QgsDemHeightMapGenerator::heightAt( double x, double y )
int cellX = ( int )( ( x - rect.xMinimum() ) / rect.width() * res + .5f ); int cellX = ( int )( ( x - rect.xMinimum() ) / rect.width() * res + .5f );
int cellY = ( int )( ( rect.yMaximum() - y ) / rect.height() * res + .5f ); int cellY = ( int )( ( rect.yMaximum() - y ) / rect.height() * res + .5f );
cellX = qBound( 0, cellX, res - 1 ); cellX = std::clamp( cellX, 0, res - 1 );
cellY = qBound( 0, cellY, res - 1 ); cellY = std::clamp( cellY, 0, res - 1 );
const float *data = ( const float * ) mDtmCoarseData.constData(); const float *data = ( const float * ) mDtmCoarseData.constData();
return data[cellX + cellY * res]; return data[cellX + cellY * res];

View File

@ -142,7 +142,7 @@ void QgsClassificationMethod::setSymmetricMode( bool enabled, double symmetryPoi
void QgsClassificationMethod::setLabelPrecision( int precision ) void QgsClassificationMethod::setLabelPrecision( int precision )
{ {
// Limit the range of decimal places to a reasonable range // Limit the range of decimal places to a reasonable range
precision = qBound( MIN_PRECISION, precision, MAX_PRECISION ); precision = std::clamp( precision, MIN_PRECISION, MAX_PRECISION );
mLabelPrecision = precision; mLabelPrecision = precision;
mLabelNumberScale = 1.0; mLabelNumberScale = 1.0;
mLabelNumberSuffix.clear(); mLabelNumberSuffix.clear();

View File

@ -18,6 +18,7 @@
#include "qgscoloreffect.h" #include "qgscoloreffect.h"
#include "qgsimageoperation.h" #include "qgsimageoperation.h"
#include "qgssymbollayerutils.h" #include "qgssymbollayerutils.h"
#include <algorithm>
QgsPaintEffect *QgsColorEffect::create( const QVariantMap &map ) QgsPaintEffect *QgsColorEffect::create( const QVariantMap &map )
{ {
@ -119,6 +120,16 @@ QgsColorEffect *QgsColorEffect::clone() const
return newEffect; return newEffect;
} }
void QgsColorEffect::setBrightness( int brightness )
{
mBrightness = std::clamp( brightness, -255, 255 );
}
void QgsColorEffect::setContrast( int contrast )
{
mContrast = std::clamp( contrast, -100, 100 );
}
void QgsColorEffect::setColorizeColor( const QColor &colorizeColor ) void QgsColorEffect::setColorizeColor( const QColor &colorizeColor )
{ {
mColorizeColor = colorizeColor; mColorizeColor = colorizeColor;

View File

@ -58,7 +58,7 @@ class CORE_EXPORT QgsColorEffect : public QgsPaintEffect SIP_NODEFAULTCTORS
* lightening * lightening
* \see setBrightness * \see setBrightness
*/ */
void setBrightness( int brightness ) { mBrightness = qBound( -255, brightness, 255 ); } void setBrightness( int brightness );
/** /**
* Returns the brightness modification for the effect. * Returns the brightness modification for the effect.
@ -76,7 +76,7 @@ class CORE_EXPORT QgsColorEffect : public QgsPaintEffect SIP_NODEFAULTCTORS
* greater contrast * greater contrast
* \see setContrast * \see setContrast
*/ */
void setContrast( int contrast ) { mContrast = qBound( -100, contrast, 100 ); } void setContrast( int contrast );
/** /**
* Returns the contrast modification for the effect. * Returns the contrast modification for the effect.

View File

@ -260,7 +260,7 @@ void QgsImageOperation::BrightnessContrastPixelOperation::operator()( QRgb &rgb,
int QgsImageOperation::adjustColorComponent( int colorComponent, int brightness, double contrastFactor ) int QgsImageOperation::adjustColorComponent( int colorComponent, int brightness, double contrastFactor )
{ {
return qBound( 0, static_cast< int >( ( ( ( ( ( colorComponent / 255.0 ) - 0.5 ) * contrastFactor ) + 0.5 ) * 255 ) + brightness ), 255 ); return std::clamp( static_cast< int >( ( ( ( ( ( colorComponent / 255.0 ) - 0.5 ) * contrastFactor ) + 0.5 ) * 255 ) + brightness ), 0, 255 );
} }
//hue/saturation //hue/saturation
@ -348,7 +348,7 @@ void QgsImageOperation::MultiplyOpacityPixelOperation::operator()( QRgb &rgb, co
{ {
Q_UNUSED( x ) Q_UNUSED( x )
Q_UNUSED( y ) Q_UNUSED( y )
rgb = qRgba( qRed( rgb ), qGreen( rgb ), qBlue( rgb ), qBound( 0.0, std::round( mFactor * qAlpha( rgb ) ), 255.0 ) ); rgb = qRgba( qRed( rgb ), qGreen( rgb ), qBlue( rgb ), std::clamp( std::round( mFactor * qAlpha( rgb ) ), 0.0, 255.0 ) );
} }
// overlay color // overlay color
@ -694,7 +694,7 @@ inline QRgb QgsImageOperation::GaussianBlurOperation::gaussianBlurVertical( cons
for ( int i = 0; i <= mRadius * 2; ++i ) for ( int i = 0; i <= mRadius * 2; ++i )
{ {
y = qBound( 0, posy + ( i - mRadius ), height - 1 ); y = std::clamp( posy + ( i - mRadius ), 0, height - 1 );
ref = sourceFirstLine + sourceBpl * y; ref = sourceFirstLine + sourceBpl * y;
QRgb *refRgb = reinterpret_cast< QRgb * >( ref ); QRgb *refRgb = reinterpret_cast< QRgb * >( ref );
@ -718,7 +718,7 @@ inline QRgb QgsImageOperation::GaussianBlurOperation::gaussianBlurHorizontal( co
for ( int i = 0; i <= mRadius * 2; ++i ) for ( int i = 0; i <= mRadius * 2; ++i )
{ {
x = qBound( 0, posx + ( i - mRadius ), width - 1 ); x = std::clamp( posx + ( i - mRadius ), 0, width - 1 );
ref = sourceFirstLine + x * 4; ref = sourceFirstLine + x * 4;
QRgb *refRgb = reinterpret_cast< QRgb * >( ref ); QRgb *refRgb = reinterpret_cast< QRgb * >( ref );

View File

@ -2741,9 +2741,9 @@ static QVariant fcnSmooth( const QVariantList &values, const QgsExpressionContex
return QVariant(); return QVariant();
int iterations = std::min( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), 10 ); int iterations = std::min( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), 10 );
double offset = qBound( 0.0, QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ), 0.5 ); double offset = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ), 0.0, 0.5 );
double minLength = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ); double minLength = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
double maxAngle = qBound( 0.0, QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent ), 180.0 ); double maxAngle = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent ), 0.0, 180.0 );
QgsGeometry smoothed = geom.smooth( static_cast<unsigned int>( iterations ), offset, minLength, maxAngle ); QgsGeometry smoothed = geom.smooth( static_cast<unsigned int>( iterations ), offset, minLength, maxAngle );
if ( smoothed.isNull() ) if ( smoothed.isNull() )
@ -4055,7 +4055,7 @@ static QVariant fcnHausdorffDistance( const QVariantList &values, const QgsExpre
if ( values.length() == 3 && values.at( 2 ).isValid() ) if ( values.length() == 3 && values.at( 2 ).isValid() )
{ {
double densify = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ); double densify = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
densify = qBound( 0.0, densify, 1.0 ); densify = std::clamp( densify, 0.0, 1.0 );
res = g1.hausdorffDistanceDensify( g2, densify ); res = g1.hausdorffDistanceDensify( g2, densify );
} }
else else

View File

@ -40,7 +40,7 @@ void QgsLabelObstacleSettings::updateDataDefinedProperties( const QgsPropertyCol
double factorD = exprVal.toDouble( &ok ); double factorD = exprVal.toDouble( &ok );
if ( ok ) if ( ok )
{ {
factorD = qBound( 0.0, factorD, 10.0 ); factorD = std::clamp( factorD, 0.0, 10.0 );
factorD = factorD / 5.0 + 0.0001; // convert 0 -> 10 to 0.0001 -> 2.0 factorD = factorD / 5.0 + 0.0001; // convert 0 -> 10 to 0.0001 -> 2.0
mObstacleFactor = factorD; mObstacleFactor = factorD;
} }

View File

@ -1937,8 +1937,8 @@ void QgsPalLayerSettings::registerFeature( const QgsFeature &f, QgsRenderContext
const QPointF maxcharanglePt = QgsSymbolLayerUtils::toPoint( exprVal, &ok ); const QPointF maxcharanglePt = QgsSymbolLayerUtils::toPoint( exprVal, &ok );
if ( ok ) if ( ok )
{ {
maxcharanglein = qBound( 20.0, static_cast< double >( maxcharanglePt.x() ), 60.0 ); maxcharanglein = std::clamp( static_cast< double >( maxcharanglePt.x() ), 20.0, 60.0 );
maxcharangleout = qBound( 20.0, static_cast< double >( maxcharanglePt.y() ), 95.0 ); maxcharangleout = std::clamp( static_cast< double >( maxcharanglePt.y() ), 20.0, 95.0 );
} }
} }
// make sure maxcharangleout is always negative // make sure maxcharangleout is always negative
@ -2592,7 +2592,7 @@ void QgsPalLayerSettings::registerFeature( const QgsFeature &f, QgsRenderContext
double priorityD = exprVal.toDouble( &ok ); double priorityD = exprVal.toDouble( &ok );
if ( ok ) if ( ok )
{ {
priorityD = qBound( 0.0, priorityD, 10.0 ); priorityD = std::clamp( priorityD, 0.0, 10.0 );
priorityD = 1 - priorityD / 10.0; // convert 0..10 --> 1..0 priorityD = 1 - priorityD / 10.0; // convert 0..10 --> 1..0
( *labelFeature )->setPriority( priorityD ); ( *labelFeature )->setPriority( priorityD );
} }

View File

@ -411,9 +411,9 @@ QList<QColor> QgsLimitedRandomColorRamp::randomColors( int count,
//see http://basecase.org/env/on-rainbows for more details //see http://basecase.org/env/on-rainbows for more details
currentHueAngle += 137.50776; currentHueAngle += 137.50776;
//scale hue to between hueMax and hueMin //scale hue to between hueMax and hueMin
h = qBound( 0.0, std::round( ( std::fmod( currentHueAngle, 360.0 ) / 360.0 ) * ( safeHueMax - safeHueMin ) + safeHueMin ), 359.0 ); h = std::clamp( std::round( ( std::fmod( currentHueAngle, 360.0 ) / 360.0 ) * ( safeHueMax - safeHueMin ) + safeHueMin ), 0.0, 359.0 );
s = qBound( 0, ( qrand() % ( safeSatMax - safeSatMin + 1 ) ) + safeSatMin, 255 ); s = std::clamp( ( qrand() % ( safeSatMax - safeSatMin + 1 ) ) + safeSatMin, 0, 255 );
v = qBound( 0, ( qrand() % ( safeValMax - safeValMin + 1 ) ) + safeValMin, 255 ); v = std::clamp( ( qrand() % ( safeValMax - safeValMin + 1 ) ) + safeValMin, 0, 255 );
colors.append( QColor::fromHsv( h, s, v ) ); colors.append( QColor::fromHsv( h, s, v ) );
} }
return colors; return colors;

View File

@ -178,13 +178,13 @@ bool QgsGenericNumericTransformer::loadVariant( const QVariant &transformer )
double QgsGenericNumericTransformer::value( double input ) const double QgsGenericNumericTransformer::value( double input ) const
{ {
if ( qgsDoubleNear( mMaxValue, mMinValue ) ) if ( qgsDoubleNear( mMaxValue, mMinValue ) )
return qBound( mMinOutput, input, mMaxOutput ); return std::clamp( input, mMinOutput, mMaxOutput );
input = transformNumeric( input ); input = transformNumeric( input );
if ( qgsDoubleNear( mExponent, 1.0 ) ) if ( qgsDoubleNear( mExponent, 1.0 ) )
return mMinOutput + ( qBound( mMinValue, input, mMaxValue ) - mMinValue ) * ( mMaxOutput - mMinOutput ) / ( mMaxValue - mMinValue ); return mMinOutput + ( std::clamp( input, mMinValue, mMaxValue ) - mMinValue ) * ( mMaxOutput - mMinOutput ) / ( mMaxValue - mMinValue );
else else
return mMinOutput + std::pow( qBound( mMinValue, input, mMaxValue ) - mMinValue, mExponent ) * ( mMaxOutput - mMinOutput ) / std::pow( mMaxValue - mMinValue, mExponent ); return mMinOutput + std::pow( std::clamp( input, mMinValue, mMaxValue ) - mMinValue, mExponent ) * ( mMaxOutput - mMinOutput ) / std::pow( mMaxValue - mMinValue, mExponent );
} }
QVariant QgsGenericNumericTransformer::transform( const QgsExpressionContext &context, const QVariant &v ) const QVariant QgsGenericNumericTransformer::transform( const QgsExpressionContext &context, const QVariant &v ) const
@ -360,12 +360,12 @@ double QgsSizeScaleTransformer::size( double value ) const
switch ( mType ) switch ( mType )
{ {
case Linear: case Linear:
return mMinSize + ( qBound( mMinValue, value, mMaxValue ) - mMinValue ) * ( mMaxSize - mMinSize ) / ( mMaxValue - mMinValue ); return mMinSize + ( std::clamp( value, mMinValue, mMaxValue ) - mMinValue ) * ( mMaxSize - mMinSize ) / ( mMaxValue - mMinValue );
case Area: case Area:
case Flannery: case Flannery:
case Exponential: case Exponential:
return mMinSize + std::pow( qBound( mMinValue, value, mMaxValue ) - mMinValue, mExponent ) * ( mMaxSize - mMinSize ) / std::pow( mMaxValue - mMinValue, mExponent ); return mMinSize + std::pow( std::clamp( value, mMinValue, mMaxValue ) - mMinValue, mExponent ) * ( mMaxSize - mMinSize ) / std::pow( mMaxValue - mMinValue, mExponent );
} }
return 0; return 0;
@ -631,7 +631,7 @@ QString QgsColorRampTransformer::toExpression( const QString &baseExpression ) c
QColor QgsColorRampTransformer::color( double value ) const QColor QgsColorRampTransformer::color( double value ) const
{ {
value = transformNumeric( value ); value = transformNumeric( value );
double scaledVal = qBound( 0.0, ( value - mMinValue ) / ( mMaxValue - mMinValue ), 1.0 ); double scaledVal = std::clamp( ( value - mMinValue ) / ( mMaxValue - mMinValue ), 0.0, 1.0 );
if ( !mGradientRamp ) if ( !mGradientRamp )
return mNullColor; return mNullColor;
@ -708,8 +708,8 @@ void QgsCurveTransform::setControlPoints( const QList<QgsPointXY> &points )
std::sort( mControlPoints.begin(), mControlPoints.end(), sortByX ); std::sort( mControlPoints.begin(), mControlPoints.end(), sortByX );
for ( int i = 0; i < mControlPoints.count(); ++i ) for ( int i = 0; i < mControlPoints.count(); ++i )
{ {
mControlPoints[ i ] = QgsPointXY( qBound( 0.0, mControlPoints.at( i ).x(), 1.0 ), mControlPoints[ i ] = QgsPointXY( std::clamp( mControlPoints.at( i ).x(), 0.0, 1.0 ),
qBound( 0.0, mControlPoints.at( i ).y(), 1.0 ) ); std::clamp( mControlPoints.at( i ).y(), 0.0, 1.0 ) );
} }
calcSecondDerivativeArray(); calcSecondDerivativeArray();
} }
@ -747,27 +747,27 @@ double QgsCurveTransform::y( double x ) const
{ {
int n = mControlPoints.count(); int n = mControlPoints.count();
if ( n < 2 ) if ( n < 2 )
return qBound( 0.0, x, 1.0 ); // invalid return std::clamp( x, 0.0, 1.0 ); // invalid
else if ( n < 3 ) else if ( n < 3 )
{ {
// linear // linear
if ( x <= mControlPoints.at( 0 ).x() ) if ( x <= mControlPoints.at( 0 ).x() )
return qBound( 0.0, mControlPoints.at( 0 ).y(), 1.0 ); return std::clamp( mControlPoints.at( 0 ).y(), 0.0, 1.0 );
else if ( x >= mControlPoints.at( n - 1 ).x() ) else if ( x >= mControlPoints.at( n - 1 ).x() )
return qBound( 0.0, mControlPoints.at( 1 ).y(), 1.0 ); return std::clamp( mControlPoints.at( 1 ).y(), 0.0, 1.0 );
else else
{ {
double dx = mControlPoints.at( 1 ).x() - mControlPoints.at( 0 ).x(); double dx = mControlPoints.at( 1 ).x() - mControlPoints.at( 0 ).x();
double dy = mControlPoints.at( 1 ).y() - mControlPoints.at( 0 ).y(); double dy = mControlPoints.at( 1 ).y() - mControlPoints.at( 0 ).y();
return qBound( 0.0, ( x - mControlPoints.at( 0 ).x() ) * ( dy / dx ) + mControlPoints.at( 0 ).y(), 1.0 ); return std::clamp( ( x - mControlPoints.at( 0 ).x() ) * ( dy / dx ) + mControlPoints.at( 0 ).y(), 0.0, 1.0 );
} }
} }
// safety check // safety check
if ( x <= mControlPoints.at( 0 ).x() ) if ( x <= mControlPoints.at( 0 ).x() )
return qBound( 0.0, mControlPoints.at( 0 ).y(), 1.0 ); return std::clamp( mControlPoints.at( 0 ).y(), 0.0, 1.0 );
if ( x >= mControlPoints.at( n - 1 ).x() ) if ( x >= mControlPoints.at( n - 1 ).x() )
return qBound( 0.0, mControlPoints.at( n - 1 ).y(), 1.0 ); return std::clamp( mControlPoints.at( n - 1 ).y(), 0.0, 1.0 );
// find corresponding segment // find corresponding segment
QList<QgsPointXY>::const_iterator pointIt = mControlPoints.constBegin(); QList<QgsPointXY>::const_iterator pointIt = mControlPoints.constBegin();
@ -785,8 +785,8 @@ double QgsCurveTransform::y( double x ) const
double a = 1 - t; double a = 1 - t;
return qBound( 0.0, a * currentControlPoint.y() + t * nextControlPoint.y() + ( h * h / 6 ) * ( ( a * a * a - a ) * mSecondDerivativeArray[i] + ( t * t * t - t ) * mSecondDerivativeArray[i + 1] ), return std::clamp( a * currentControlPoint.y() + t * nextControlPoint.y() + ( h * h / 6 ) * ( ( a * a * a - a ) * mSecondDerivativeArray[i] + ( t * t * t - t ) * mSecondDerivativeArray[i + 1] ),
1.0 ); 0.0, 1.0 );
} }
++pointIt; ++pointIt;
@ -798,7 +798,7 @@ double QgsCurveTransform::y( double x ) const
} }
//should not happen //should not happen
return qBound( 0.0, x, 1.0 ); return std::clamp( x, 0.0, 1.0 );
} }
// this code is adapted from https://github.com/OpenFibers/Photoshop-Curves // this code is adapted from https://github.com/OpenFibers/Photoshop-Curves
@ -831,7 +831,7 @@ QVector<double> QgsCurveTransform::y( const QVector<double> &x ) const
// safety check // safety check
while ( currentX <= currentControlPoint.x() ) while ( currentX <= currentControlPoint.x() )
{ {
result << qBound( 0.0, currentControlPoint.y(), 1.0 ); result << std::clamp( currentControlPoint.y(), 0.0, 1.0 );
xIndex++; xIndex++;
currentX = x.at( xIndex ); currentX = x.at( xIndex );
} }
@ -847,7 +847,7 @@ QVector<double> QgsCurveTransform::y( const QVector<double> &x ) const
double a = 1 - t; double a = 1 - t;
result << qBound( 0.0, a * currentControlPoint.y() + t * nextControlPoint.y() + ( h * h / 6 ) * ( ( a * a * a - a )*mSecondDerivativeArray[i] + ( t * t * t - t )*mSecondDerivativeArray[i + 1] ), 1.0 ); result << std::clamp( a * currentControlPoint.y() + t * nextControlPoint.y() + ( h * h / 6 ) * ( ( a * a * a - a )*mSecondDerivativeArray[i] + ( t * t * t - t )*mSecondDerivativeArray[i + 1] ), 0.0, 1.0 );
xIndex++; xIndex++;
if ( xIndex == x.count() ) if ( xIndex == x.count() )
return result; return result;
@ -866,7 +866,7 @@ QVector<double> QgsCurveTransform::y( const QVector<double> &x ) const
// safety check // safety check
while ( xIndex < x.count() ) while ( xIndex < x.count() )
{ {
result << qBound( 0.0, nextControlPoint.y(), 1.0 ); result << std::clamp( nextControlPoint.y(), 0.0, 1.0 );
xIndex++; xIndex++;
} }

View File

@ -53,10 +53,10 @@ QgsPointXY QgsTileMatrix::tileCenter( QgsTileXYZ id ) const
QgsTileRange QgsTileMatrix::tileRangeFromExtent( const QgsRectangle &r ) QgsTileRange QgsTileMatrix::tileRangeFromExtent( const QgsRectangle &r )
{ {
double x0 = qBound( mExtent.xMinimum(), r.xMinimum(), mExtent.xMaximum() ); double x0 = std::clamp( r.xMinimum(), mExtent.xMinimum(), mExtent.xMaximum() );
double y0 = qBound( mExtent.yMinimum(), r.yMinimum(), mExtent.yMaximum() ); double y0 = std::clamp( r.yMinimum(), mExtent.yMinimum(), mExtent.yMaximum() );
double x1 = qBound( mExtent.xMinimum(), r.xMaximum(), mExtent.xMaximum() ); double x1 = std::clamp( r.xMaximum(), mExtent.xMinimum(), mExtent.xMaximum() );
double y1 = qBound( mExtent.yMinimum(), r.yMaximum(), mExtent.yMaximum() ); double y1 = std::clamp( r.yMaximum(), mExtent.yMinimum(), mExtent.yMaximum() );
if ( x0 >= x1 || y0 >= y1 ) if ( x0 >= x1 || y0 >= y1 )
return QgsTileRange(); // nothing to display return QgsTileRange(); // nothing to display
@ -68,10 +68,10 @@ QgsTileRange QgsTileMatrix::tileRangeFromExtent( const QgsRectangle &r )
QgsDebugMsgLevel( QStringLiteral( "Tile range of edges [%1,%2] - [%3,%4]" ).arg( tileX1 ).arg( tileY1 ).arg( tileX2 ).arg( tileY2 ), 2 ); QgsDebugMsgLevel( QStringLiteral( "Tile range of edges [%1,%2] - [%3,%4]" ).arg( tileX1 ).arg( tileY1 ).arg( tileX2 ).arg( tileY2 ), 2 );
// figure out tile range from zoom // figure out tile range from zoom
int startColumn = qBound( 0, static_cast<int>( floor( tileX1 ) ), mMatrixWidth - 1 ); int startColumn = std::clamp( static_cast<int>( floor( tileX1 ) ), 0, mMatrixWidth - 1 );
int endColumn = qBound( 0, static_cast<int>( floor( tileX2 ) ), mMatrixWidth - 1 ); int endColumn = std::clamp( static_cast<int>( floor( tileX2 ) ), 0, mMatrixWidth - 1 );
int startRow = qBound( 0, static_cast<int>( floor( tileY1 ) ), mMatrixHeight - 1 ); int startRow = std::clamp( static_cast<int>( floor( tileY1 ) ), 0, mMatrixHeight - 1 );
int endRow = qBound( 0, static_cast<int>( floor( tileY2 ) ), mMatrixHeight - 1 ); int endRow = std::clamp( static_cast<int>( floor( tileY2 ) ), 0, mMatrixHeight - 1 );
return QgsTileRange( startColumn, endColumn, startRow, endRow ); return QgsTileRange( startColumn, endColumn, startRow, endRow );
} }

View File

@ -163,12 +163,27 @@ QgsRasterBlock *QgsBrightnessContrastFilter::block( int bandNo, QgsRectangle co
return outputBlock.release(); return outputBlock.release();
} }
void QgsBrightnessContrastFilter::setBrightness( int brightness )
{
mBrightness = std::clamp( brightness, -255, 255 );
}
void QgsBrightnessContrastFilter::setContrast( int contrast )
{
mContrast = std::clamp( contrast, -100, 100 );
}
void QgsBrightnessContrastFilter::setGamma( double gamma )
{
mGamma = std::clamp( gamma, 0.1, 10.0 );
}
int QgsBrightnessContrastFilter::adjustColorComponent( int colorComponent, int alpha, int brightness, double contrastFactor, double gammaCorrection ) const int QgsBrightnessContrastFilter::adjustColorComponent( int colorComponent, int alpha, int brightness, double contrastFactor, double gammaCorrection ) const
{ {
if ( alpha == 255 ) if ( alpha == 255 )
{ {
// Opaque pixel, do simpler math // Opaque pixel, do simpler math
return qBound( 0, ( int )( 255 * std::pow( ( ( ( ( ( ( colorComponent / 255.0 ) - 0.5 ) * contrastFactor ) + 0.5 ) * 255 ) + brightness ) / 255.0, gammaCorrection ) ), 255 ); return std::clamp( ( int )( 255 * std::pow( ( ( ( ( ( ( colorComponent / 255.0 ) - 0.5 ) * contrastFactor ) + 0.5 ) * 255 ) + brightness ) / 255.0, gammaCorrection ) ), 0, 255 );
} }
else if ( alpha == 0 ) else if ( alpha == 0 )
{ {
@ -183,7 +198,7 @@ int QgsBrightnessContrastFilter::adjustColorComponent( int colorComponent, int a
double adjustedColor = colorComponent / alphaFactor; double adjustedColor = colorComponent / alphaFactor;
// Make sure to return a premultiplied color // Make sure to return a premultiplied color
return alphaFactor * qBound( 0., 255 * std::pow( ( ( ( ( ( ( adjustedColor / 255.0 ) - 0.5 ) * contrastFactor ) + 0.5 ) * 255 ) + brightness ) / 255, gammaCorrection ), 255. ); return alphaFactor * std::clamp( 255 * std::pow( ( ( ( ( ( ( adjustedColor / 255.0 ) - 0.5 ) * contrastFactor ) + 0.5 ) * 255 ) + brightness ) / 255, gammaCorrection ), 0., 255. );
} }
} }

View File

@ -64,7 +64,7 @@ class CORE_EXPORT QgsBrightnessContrastFilter : public QgsRasterInterface
* Set brightness level. Acceptable value range is -255255 * Set brightness level. Acceptable value range is -255255
* \see brightness() * \see brightness()
*/ */
void setBrightness( int brightness ) { mBrightness = qBound( -255, brightness, 255 ); } void setBrightness( int brightness );
/** /**
* Returns current brightness level. * Returns current brightness level.
@ -76,7 +76,7 @@ class CORE_EXPORT QgsBrightnessContrastFilter : public QgsRasterInterface
* Set contrast level. Acceptable value range is -100100 * Set contrast level. Acceptable value range is -100100
* \see contrast() * \see contrast()
*/ */
void setContrast( int contrast ) { mContrast = qBound( -100, contrast, 100 ); } void setContrast( int contrast );
/** /**
* Returns current contrast level. * Returns current contrast level.
@ -90,7 +90,7 @@ class CORE_EXPORT QgsBrightnessContrastFilter : public QgsRasterInterface
* *
* \since QGIS 3.16 * \since QGIS 3.16
*/ */
void setGamma( double gamma ) { mGamma = qBound( 0.1, gamma, 10.0 ); } void setGamma( double gamma );
/** /**
* Returns current gamma value. * Returns current gamma value.

View File

@ -448,11 +448,11 @@ QgsRasterBlock *QgsHillshadeRenderer::block( int bandNo, const QgsRectangle &ext
if ( !mMultiDirectional ) if ( !mMultiDirectional )
{ {
// Standard single direction hillshade // Standard single direction hillshade
grayValue = qBound( 0.0, ( sin_altRadians_mul_254 - grayValue = std::clamp( ( sin_altRadians_mul_254 -
( derY * cos_az_mul_cos_alt_mul_z_mul_254 - ( derY * cos_az_mul_cos_alt_mul_z_mul_254 -
derX * sin_az_mul_cos_alt_mul_z_mul_254 ) ) / derX * sin_az_mul_cos_alt_mul_z_mul_254 ) ) /
std::sqrt( 1 + square_z * ( derX * derX + derY * derY ) ) std::sqrt( 1 + square_z * ( derX * derX + derY * derY ) ),
, 255.0 ); 0.0, 255.0 );
} }
else else
{ {
@ -464,7 +464,7 @@ QgsRasterBlock *QgsHillshadeRenderer::block( int bandNo, const QgsRectangle &ext
// Flat? // Flat?
if ( xx_plus_yy == 0.0 ) if ( xx_plus_yy == 0.0 )
{ {
grayValue = qBound( 0.0f, static_cast<float>( 1.0 + sin_altRadians_mul_254 ), 255.0f ); grayValue = std::clamp( static_cast<float>( 1.0 + sin_altRadians_mul_254 ), 0.0f, 255.0f );
} }
else else
{ {
@ -494,7 +494,7 @@ QgsRasterBlock *QgsHillshadeRenderer::block( int bandNo, const QgsRectangle &ext
weight_360 * val360_mul_127 ) / xx_plus_yy ) / weight_360 * val360_mul_127 ) / xx_plus_yy ) /
( 1 + square_z * xx_plus_yy ); ( 1 + square_z * xx_plus_yy );
grayValue = qBound( 0.0f, 1.0f + cang_mul_127, 255.0f ); grayValue = std::clamp( 1.0f + cang_mul_127, 0.0f, 255.0f );
} }
} }

View File

@ -313,7 +313,7 @@ void QgsHueSaturationFilter::processSaturation( int &r, int &g, int &b, int &h,
void QgsHueSaturationFilter::setSaturation( int saturation ) void QgsHueSaturationFilter::setSaturation( int saturation )
{ {
mSaturation = qBound( -100, saturation, 100 ); mSaturation = std::clamp( saturation, -100, 100 );
// Scale saturation value to [0-2], where 0 = desaturated // Scale saturation value to [0-2], where 0 = desaturated
mSaturationScale = ( ( double ) mSaturation / 100 ) + 1; mSaturationScale = ( ( double ) mSaturation / 100 ) + 1;

View File

@ -193,7 +193,7 @@ bool QgsRendererRangeLabelFormat::operator!=( const QgsRendererRangeLabelFormat
void QgsRendererRangeLabelFormat::setPrecision( int precision ) void QgsRendererRangeLabelFormat::setPrecision( int precision )
{ {
// Limit the range of decimal places to a reasonable range // Limit the range of decimal places to a reasonable range
precision = qBound( MIN_PRECISION, precision, MAX_PRECISION ); precision = std::clamp( precision, MIN_PRECISION, MAX_PRECISION );
mPrecision = precision; mPrecision = precision;
mNumberScale = 1.0; mNumberScale = 1.0;
mNumberSuffix.clear(); mNumberSuffix.clear();

View File

@ -314,7 +314,7 @@ QgsLabelFeature *QgsVectorLayerDiagramProvider::registerDiagram( QgsFeature &fea
{ {
context.expressionContext().setOriginalValueVariable( mSettings.priority() ); context.expressionContext().setOriginalValueVariable( mSettings.priority() );
double priorityD = mSettings.dataDefinedProperties().valueAsDouble( QgsDiagramLayerSettings::Priority, context.expressionContext(), mSettings.priority() ); double priorityD = mSettings.dataDefinedProperties().valueAsDouble( QgsDiagramLayerSettings::Priority, context.expressionContext(), mSettings.priority() );
priorityD = qBound( 0.0, priorityD, 10.0 ); priorityD = std::clamp( priorityD, 0.0, 10.0 );
priorityD = 1 - priorityD / 10.0; // convert 0..10 --> 1..0 priorityD = 1 - priorityD / 10.0; // convert 0..10 --> 1..0
lf->setPriority( priorityD ); lf->setPriority( priorityD );
} }

View File

@ -190,7 +190,7 @@ void QgsLayoutView::scaleSafe( double scale )
{ {
double currentScale = transform().m11(); double currentScale = transform().m11();
scale *= currentScale; scale *= currentScale;
scale = qBound( MIN_VIEW_SCALE, scale, MAX_VIEW_SCALE ); scale = std::clamp( scale, MIN_VIEW_SCALE, MAX_VIEW_SCALE );
setTransform( QTransform::fromScale( scale, scale ) ); setTransform( QTransform::fromScale( scale, scale ) );
emit zoomLevelChanged(); emit zoomLevelChanged();
viewChanged(); viewChanged();
@ -213,7 +213,7 @@ void QgsLayoutView::setZoomLevel( double level )
dpi = 72; dpi = 72;
//desired pixel width for 1mm on screen //desired pixel width for 1mm on screen
level = qBound( MIN_VIEW_SCALE, level, MAX_VIEW_SCALE ); level = std::clamp( level, MIN_VIEW_SCALE, MAX_VIEW_SCALE );
double mmLevel = currentLayout()->convertFromLayoutUnits( level, QgsUnitTypes::LayoutMillimeters ).length() * dpi / 25.4; double mmLevel = currentLayout()->convertFromLayoutUnits( level, QgsUnitTypes::LayoutMillimeters ).length() * dpi / 25.4;
setTransform( QTransform::fromScale( mmLevel, mmLevel ) ); setTransform( QTransform::fromScale( mmLevel, mmLevel ) );
} }

View File

@ -170,7 +170,7 @@ void QgsModelGraphicsView::scaleSafe( double scale )
{ {
double currentScale = transform().m11(); double currentScale = transform().m11();
scale *= currentScale; scale *= currentScale;
scale = qBound( MIN_VIEW_SCALE, scale, MAX_VIEW_SCALE ); scale = std::clamp( scale, MIN_VIEW_SCALE, MAX_VIEW_SCALE );
setTransform( QTransform::fromScale( scale, scale ) ); setTransform( QTransform::fromScale( scale, scale ) );
} }

View File

@ -183,7 +183,7 @@ void QgsFloatingWidget::onAnchorPointChanged()
} }
// constrain x so that widget floats within parent widget // constrain x so that widget floats within parent widget
anchorX = qBound( 0, anchorX, parentWidget()->width() - width() ); anchorX = std::clamp( anchorX, 0, parentWidget()->width() - width() );
move( anchorX, anchorY ); move( anchorX, anchorY );
} }

View File

@ -445,15 +445,15 @@ void QgsGradientColorRampDialog::plotMouseMove( QPointF point )
QColor newColor = mStopEditor->selectedStop().color; QColor newColor = mStopEditor->selectedStop().color;
if ( mCurrentPlotColorComponent == 0 ) if ( mCurrentPlotColorComponent == 0 )
newColor = QColor::fromHslF( qBound( qreal( 0.0 ), point.y(), qreal( 1.0 ) ), newColor.hslSaturationF(), newColor.lightnessF(), newColor.alphaF() ); newColor = QColor::fromHslF( std::clamp( point.y(), qreal( 0.0 ), qreal( 1.0 ) ), newColor.hslSaturationF(), newColor.lightnessF(), newColor.alphaF() );
else if ( mCurrentPlotColorComponent == 1 ) else if ( mCurrentPlotColorComponent == 1 )
newColor = QColor::fromHslF( newColor.hslHueF(), newColor.hslSaturationF(), qBound( qreal( 0.0 ), point.y(), qreal( 1.0 ) ), newColor.alphaF() ); newColor = QColor::fromHslF( newColor.hslHueF(), newColor.hslSaturationF(), std::clamp( point.y(), qreal( 0.0 ), qreal( 1.0 ) ), newColor.alphaF() );
else if ( mCurrentPlotColorComponent == 2 ) else if ( mCurrentPlotColorComponent == 2 )
newColor = QColor::fromHslF( newColor.hslHueF(), qBound( qreal( 0.0 ), point.y(), qreal( 1.0 ) ), newColor.lightnessF(), newColor.alphaF() ); newColor = QColor::fromHslF( newColor.hslHueF(), std::clamp( point.y(), qreal( 0.0 ), qreal( 1.0 ) ), newColor.lightnessF(), newColor.alphaF() );
else if ( mCurrentPlotColorComponent == 3 ) else if ( mCurrentPlotColorComponent == 3 )
newColor = QColor::fromHslF( newColor.hslHueF(), newColor.hslSaturationF(), newColor.lightnessF(), qBound( qreal( 0.0 ), point.y(), qreal( 1.0 ) ) ); newColor = QColor::fromHslF( newColor.hslHueF(), newColor.hslSaturationF(), newColor.lightnessF(), std::clamp( point.y(), qreal( 0.0 ), qreal( 1.0 ) ) );
mStopEditor->setSelectedStopDetails( newColor, qBound( qreal( 0.0 ), point.x(), qreal( 1.0 ) ) ); mStopEditor->setSelectedStopDetails( newColor, std::clamp( point.x(), qreal( 0.0 ), qreal( 1.0 ) ) );
} }
bool byX( QPointF p1, QPointF p2 ) bool byX( QPointF p1, QPointF p2 )

View File

@ -365,7 +365,7 @@ void QgsGradientStopEditor::keyPressEvent( QKeyEvent *e )
if ( e->key() == Qt::Key_Left ) if ( e->key() == Qt::Key_Left )
offsetDiff *= -1; offsetDiff *= -1;
mStops[ mSelectedStop - 1 ].offset = qBound( 0.0, mStops[ mSelectedStop - 1 ].offset + offsetDiff, 1.0 ); mStops[ mSelectedStop - 1 ].offset = std::clamp( mStops[ mSelectedStop - 1 ].offset + offsetDiff, 0.0, 1.0 );
mGradient.setStops( mStops ); mGradient.setStops( mStops );
update(); update();
e->accept(); e->accept();

View File

@ -372,7 +372,7 @@ void QgsHighlight::paint( QPainter *p )
if ( alpha > 0 ) if ( alpha > 0 )
{ {
int green = qGreen( line[c] ); int green = qGreen( line[c] );
line[c] = qRgba( penRed, penGreen, penBlue, qBound<int>( 0, alpha - ( green * k ), 255 ) ); line[c] = qRgba( penRed, penGreen, penBlue, std::clamp( static_cast< int >( alpha - ( green * k ) ), 0, 255 ) );
} }
} }
} }

View File

@ -290,7 +290,7 @@ void QgsMapCanvas::setMagnificationFactor( double factor, const QgsPointXY *cent
// do not go higher or lower than min max magnification ratio // do not go higher or lower than min max magnification ratio
double magnifierMin = QgsGuiUtils::CANVAS_MAGNIFICATION_MIN; double magnifierMin = QgsGuiUtils::CANVAS_MAGNIFICATION_MIN;
double magnifierMax = QgsGuiUtils::CANVAS_MAGNIFICATION_MAX; double magnifierMax = QgsGuiUtils::CANVAS_MAGNIFICATION_MAX;
factor = qBound( magnifierMin, factor, magnifierMax ); factor = std::clamp( factor, magnifierMin, magnifierMax );
// the magnifier widget is in integer percent // the magnifier widget is in integer percent
if ( !qgsDoubleNear( factor, mSettings.magnificationFactor(), 0.01 ) ) if ( !qgsDoubleNear( factor, mSettings.magnificationFactor(), 0.01 ) )
@ -1151,7 +1151,7 @@ void QgsMapCanvas::setExtent( const QgsRectangle &r, bool magnified )
ScaleRestorer restorer( this ); ScaleRestorer restorer( this );
const double ratio { extent().width() / extent().height() }; const double ratio { extent().width() / extent().height() };
const double factor { r.width() / r.height() > ratio ? extent().width() / r.width() : extent().height() / r.height() }; const double factor { r.width() / r.height() > ratio ? extent().width() / r.width() : extent().height() / r.height() };
const double scaleFactor { qBound( QgsGuiUtils::CANVAS_MAGNIFICATION_MIN, mSettings.magnificationFactor() * factor, QgsGuiUtils::CANVAS_MAGNIFICATION_MAX ) }; const double scaleFactor { std::clamp( mSettings.magnificationFactor() * factor, QgsGuiUtils::CANVAS_MAGNIFICATION_MIN, QgsGuiUtils::CANVAS_MAGNIFICATION_MAX ) };
const QgsPointXY newCenter { r.center() }; const QgsPointXY newCenter { r.center() };
mSettings.setMagnificationFactor( scaleFactor, &newCenter ); mSettings.setMagnificationFactor( scaleFactor, &newCenter );
emit magnificationChanged( scaleFactor ); emit magnificationChanged( scaleFactor );

View File

@ -1364,8 +1364,8 @@ void QgsTableEditorTextEdit::resizeToContents()
int parentWidth = parent->width(); int parentWidth = parent->width();
int maxWidth = isRightToLeft() ? position.x() + oldWidth : parentWidth - position.x(); int maxWidth = isRightToLeft() ? position.x() + oldWidth : parentWidth - position.x();
int maxHeight = parent->height() - position.y(); int maxHeight = parent->height() - position.y();
int newWidth = qBound( mOriginalWidth, hintWidth, maxWidth ); int newWidth = std::clamp( hintWidth, mOriginalWidth, maxWidth );
int newHeight = qBound( mOriginalHeight, hintHeight, maxHeight ); int newHeight = std::clamp( hintHeight, mOriginalHeight, maxHeight );
if ( mWidgetOwnsGeometry ) if ( mWidgetOwnsGeometry )
{ {

View File

@ -2567,10 +2567,10 @@ void QgsWmtsTileMatrix::viewExtentIntersection( const QgsRectangle &viewExtent,
maxTileRow = tml->maxTileRow; maxTileRow = tml->maxTileRow;
} }
col0 = qBound( minTileCol, ( int ) std::floor( ( viewExtent.xMinimum() - topLeft.x() ) / twMap ), maxTileCol ); col0 = std::clamp( ( int ) std::floor( ( viewExtent.xMinimum() - topLeft.x() ) / twMap ), minTileCol, maxTileCol );
row0 = qBound( minTileRow, ( int ) std::floor( ( topLeft.y() - viewExtent.yMaximum() ) / thMap ), maxTileRow ); row0 = std::clamp( ( int ) std::floor( ( topLeft.y() - viewExtent.yMaximum() ) / thMap ), minTileRow, maxTileRow );
col1 = qBound( minTileCol, ( int ) std::floor( ( viewExtent.xMaximum() - topLeft.x() ) / twMap ), maxTileCol ); col1 = std::clamp( ( int ) std::floor( ( viewExtent.xMaximum() - topLeft.x() ) / twMap ), minTileCol, maxTileCol );
row1 = qBound( minTileRow, ( int ) std::floor( ( topLeft.y() - viewExtent.yMinimum() ) / thMap ), maxTileRow ); row1 = std::clamp( ( int ) std::floor( ( topLeft.y() - viewExtent.yMinimum() ) / thMap ), minTileRow, maxTileRow );
} }
const QgsWmtsTileMatrix *QgsWmtsTileMatrixSet::findNearestResolution( double vres ) const const QgsWmtsTileMatrix *QgsWmtsTileMatrixSet::findNearestResolution( double vres ) const

View File

@ -137,6 +137,9 @@ HINTS[37]="Use range based for loops instead"
KEYWORDS[38]="foreach" KEYWORDS[38]="foreach"
HINTS[38]="Use range based for loops instead" HINTS[38]="Use range based for loops instead"
KEYWORDS[39]="\bqBound("
HINTS[39]="Use std::clamp instead (but be careful of the different argument order!!)"
RES= RES=
DIR=$(git rev-parse --show-toplevel) DIR=$(git rev-parse --show-toplevel)

View File

@ -511,7 +511,7 @@ void ModelTest::rowsInserted( const QModelIndex &parent, int start, int end )
void ModelTest::layoutAboutToBeChanged() void ModelTest::layoutAboutToBeChanged()
{ {
for ( int i = 0; i < qBound( 0, model->rowCount(), 100 ); ++i ) for ( int i = 0; i < std::clamp( model->rowCount(), 0, 100 ); ++i )
changing.append( QPersistentModelIndex( model->index( i, 0 ) ) ); changing.append( QPersistentModelIndex( model->index( i, 0 ) ) );
} }