Merge branch 'clamp' into 'master'

Make better use of std::clamp

See merge request OpenMW/openmw!1357
pull/3222/head
Evil Eye 3 years ago
commit 5fbfbb3d84

@ -308,7 +308,7 @@ osg::ref_ptr<osg::Node> CSVRender::Object::makeRotateMarker (int axis)
const float OuterRadius = InnerRadius + MarkerShaftWidth;
const float SegmentDistance = 100.f;
const size_t SegmentCount = std::min(64, std::max(24, (int)(OuterRadius * 2 * osg::PI / SegmentDistance)));
const size_t SegmentCount = std::clamp<int>(OuterRadius * 2 * osg::PI / SegmentDistance, 24, 64);
const size_t VerticesPerSegment = 4;
const size_t IndicesPerSegment = 24;

@ -421,7 +421,7 @@ namespace MWDialogue
// Clamp permanent disposition change so that final disposition doesn't go below 0 (could happen with intimidate)
npcStats.setBaseDisposition(0);
int zero = MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mActor, false);
int disposition = std::min(100 - zero, std::max(mOriginalDisposition + mPermanentDispositionChange, -zero));
int disposition = std::clamp(mOriginalDisposition + mPermanentDispositionChange, -zero, 100 - zero);
npcStats.setBaseDisposition(disposition);
}

@ -347,8 +347,7 @@ namespace MWGui
{
if (!mScrollBar->getVisible())
return;
mScrollBar->setScrollPosition(std::min(static_cast<int>(mScrollBar->getScrollRange()-1),
std::max(0, static_cast<int>(mScrollBar->getScrollPosition() - _rel*0.3))));
mScrollBar->setScrollPosition(std::clamp<int>(mScrollBar->getScrollPosition() - _rel*0.3, 0, mScrollBar->getScrollRange() - 1));
onScrollbarMoved(mScrollBar, mScrollBar->getScrollPosition());
}

@ -109,7 +109,7 @@ namespace MWGui
{
mEnchantmentPoints->setCaption(std::to_string(static_cast<int>(mEnchanting.getEnchantPoints(false))) + " / " + std::to_string(mEnchanting.getMaxEnchantValue()));
mCharge->setCaption(std::to_string(mEnchanting.getGemCharge()));
mSuccessChance->setCaption(std::to_string(std::max(0, std::min(100, mEnchanting.getEnchantChance()))));
mSuccessChance->setCaption(std::to_string(std::clamp(mEnchanting.getEnchantChance(), 0, 100)));
mCastCost->setCaption(std::to_string(mEnchanting.getEffectiveCastCost()));
mPrice->setCaption(std::to_string(mEnchanting.getEnchantPrice()));

@ -610,7 +610,7 @@ namespace MWGui
static const float fNPCHealthBarFade = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fNPCHealthBarFade")->mValue.getFloat();
if (fNPCHealthBarFade > 0.f)
mEnemyHealth->setAlpha(std::max(0.f, std::min(1.f, mEnemyHealthTimer/fNPCHealthBarFade)));
mEnemyHealth->setAlpha(std::clamp(mEnemyHealthTimer / fNPCHealthBarFade, 0.f, 1.f));
}

@ -273,7 +273,7 @@ bool KeyboardNavigation::switchFocus(int direction, bool wrap)
if (wrap)
index = (index + keyFocusList.size())%keyFocusList.size();
else
index = std::min(std::max(0, index), static_cast<int>(keyFocusList.size())-1);
index = std::clamp<int>(index, 0, keyFocusList.size() - 1);
MyGUI::Widget* next = keyFocusList[index];
int vertdiff = next->getTop() - focus->getTop();

@ -171,7 +171,7 @@ namespace MWGui
else
valueStr = MyGUI::utility::toString(int(value));
value = std::max(min, std::min(value, max));
value = std::clamp(value, min, max);
value = (value-min)/(max-min);
scroll->setScrollPosition(static_cast<size_t>(value * (scroll->getScrollRange() - 1)));
@ -306,7 +306,7 @@ namespace MWGui
mWaterTextureSize->setIndexSelected(2);
int waterReflectionDetail = Settings::Manager::getInt("reflection detail", "Water");
waterReflectionDetail = std::min(5, std::max(0, waterReflectionDetail));
waterReflectionDetail = std::clamp(waterReflectionDetail, 0, 5);
mWaterReflectionDetail->setIndexSelected(waterReflectionDetail);
updateMaxLightsComboBox(mMaxLights);

@ -599,8 +599,7 @@ namespace MWGui
text += "\n#{fontcolourhtml=normal}#{sExpelled}";
else
{
int rank = factionPair.second;
rank = std::max(0, std::min(9, rank));
const int rank = std::clamp(factionPair.second, 0, 9);
text += std::string("\n#{fontcolourhtml=normal}") + faction->mRanks[rank];
if (rank < 9)

@ -70,7 +70,7 @@ namespace MWInput
}
float deadZoneRadius = Settings::Manager::getFloat("joystick dead zone", "Input");
deadZoneRadius = std::min(std::max(deadZoneRadius, 0.0f), 0.5f);
deadZoneRadius = std::clamp(deadZoneRadius, 0.f, 0.5f);
mBindingsManager->setJoystickDeadZone(deadZoneRadius);
}

@ -245,8 +245,8 @@ namespace MWInput
mMouseWheel += mouseWheelMove;
const MyGUI::IntSize& viewSize = MyGUI::RenderManager::getInstance().getViewSize();
mGuiCursorX = std::max(0.f, std::min(mGuiCursorX, float(viewSize.width - 1)));
mGuiCursorY = std::max(0.f, std::min(mGuiCursorY, float(viewSize.height - 1)));
mGuiCursorX = std::clamp<float>(mGuiCursorX, 0.f, viewSize.width - 1);
mGuiCursorY = std::clamp<float>(mGuiCursorY, 0.f, viewSize.height - 1);
MyGUI::InputManager::getInstance().injectMouseMove(static_cast<int>(mGuiCursorX), static_cast<int>(mGuiCursorY), static_cast<int>(mMouseWheel));
}

@ -1013,13 +1013,10 @@ namespace MWMechanics
void Actors::updateProcessingRange()
{
// We have to cap it since using high values (larger than 7168) will make some quests harder or impossible to complete (bug #1876)
static const float maxProcessingRange = 7168.f;
static const float minProcessingRange = maxProcessingRange / 2.f;
static const float maxRange = 7168.f;
static const float minRange = maxRange / 2.f;
float actorsProcessingRange = Settings::Manager::getFloat("actors processing range", "Game");
actorsProcessingRange = std::min(actorsProcessingRange, maxProcessingRange);
actorsProcessingRange = std::max(actorsProcessingRange, minProcessingRange);
mActorsProcessingRange = actorsProcessingRange;
mActorsProcessingRange = std::clamp(Settings::Manager::getFloat("actors processing range", "Game"), minRange, maxRange);
}
void Actors::addActor (const MWWorld::Ptr& ptr, bool updateImmediately)
@ -1315,7 +1312,7 @@ namespace MWMechanics
angleToApproachingActor = std::atan2(deltaPos.x(), deltaPos.y());
osg::Vec2f posAtT = relPos + relSpeed * t;
float coef = (posAtT.x() * relSpeed.x() + posAtT.y() * relSpeed.y()) / (collisionDist * collisionDist * maxSpeed);
coef *= osg::clampBetween((maxDistForPartialAvoiding - dist) / (maxDistForPartialAvoiding - maxDistForStrictAvoiding), 0.f, 1.f);
coef *= std::clamp((maxDistForPartialAvoiding - dist) / (maxDistForPartialAvoiding - maxDistForStrictAvoiding), 0.f, 1.f);
movementCorrection = posAtT * coef;
if (otherPtr.getClass().getCreatureStats(otherPtr).isDead())
// In case of dead body still try to go around (it looks natural), but reduce the correction twice.

@ -2044,7 +2044,7 @@ void CharacterController::update(float duration)
mIsMovingBackward = vec.y() < 0;
float maxDelta = osg::PI * duration * (2.5f - cosDelta);
delta = osg::clampBetween(delta, -maxDelta, maxDelta);
delta = std::clamp(delta, -maxDelta, maxDelta);
stats.setSideMovementAngle(stats.getSideMovementAngle() + delta);
effectiveRotation += delta;
}
@ -2286,7 +2286,7 @@ void CharacterController::update(float duration)
float swimmingPitch = mAnimation->getBodyPitchRadians();
float targetSwimmingPitch = -mPtr.getRefData().getPosition().rot[0];
float maxSwimPitchDelta = 3.0f * duration;
swimmingPitch += osg::clampBetween(targetSwimmingPitch - swimmingPitch, -maxSwimPitchDelta, maxSwimPitchDelta);
swimmingPitch += std::clamp(targetSwimmingPitch - swimmingPitch, -maxSwimPitchDelta, maxSwimPitchDelta);
mAnimation->setBodyPitchRadians(swimmingPitch);
}
else
@ -2522,7 +2522,7 @@ void CharacterController::unpersistAnimationState()
{
float start = mAnimation->getTextKeyTime(anim.mGroup+": start");
float stop = mAnimation->getTextKeyTime(anim.mGroup+": stop");
float time = std::max(start, std::min(stop, anim.mTime));
float time = std::clamp(anim.mTime, start, stop);
complete = (time - start) / (stop - start);
}
@ -2746,7 +2746,7 @@ void CharacterController::setVisibility(float visibility)
float chameleon = mPtr.getClass().getCreatureStats(mPtr).getMagicEffects().get(ESM::MagicEffect::Chameleon).getMagnitude();
if (chameleon)
{
alpha *= std::min(0.75f, std::max(0.25f, (100.f - chameleon)/100.f));
alpha *= std::clamp(1.f - chameleon / 100.f, 0.25f, 0.75f);
}
visibility = std::min(visibility, alpha);
@ -2965,8 +2965,8 @@ void CharacterController::updateHeadTracking(float duration)
const double xLimit = osg::DegreesToRadians(40.0);
const double zLimit = osg::DegreesToRadians(30.0);
double zLimitOffset = mAnimation->getUpperBodyYawRadians();
xAngleRadians = osg::clampBetween(xAngleRadians, -xLimit, xLimit);
zAngleRadians = osg::clampBetween(zAngleRadians, -zLimit + zLimitOffset, zLimit + zLimitOffset);
xAngleRadians = std::clamp(xAngleRadians, -xLimit, xLimit);
zAngleRadians = std::clamp(zAngleRadians, -zLimit + zLimitOffset, zLimit + zLimitOffset);
float factor = duration*5;
factor = std::min(factor, 1.f);

@ -113,10 +113,9 @@ namespace MWMechanics
+ 0.1f * attackerStats.getAttribute(ESM::Attribute::Luck).getModified();
attackerTerm *= attackerStats.getFatigueTerm();
int x = int(blockerTerm - attackerTerm);
int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger();
int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger();
x = std::min(iBlockMaxChance, std::max(iBlockMinChance, x));
const int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger();
const int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger();
int x = std::clamp<int>(blockerTerm - attackerTerm, iBlockMinChance, iBlockMaxChance);
if (Misc::Rng::roll0to99() < x)
{

@ -13,9 +13,7 @@ float scaleDamage(float damage, const MWWorld::Ptr& attacker, const MWWorld::Ptr
const MWWorld::Ptr& player = MWMechanics::getPlayer();
// [-500, 500]
int difficultySetting = Settings::Manager::getInt("difficulty", "Game");
difficultySetting = std::min(difficultySetting, 500);
difficultySetting = std::max(difficultySetting, -500);
const int difficultySetting = std::clamp(Settings::Manager::getInt("difficulty", "Game"), -500, 500);
static const float fDifficultyMult = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fDifficultyMult")->mValue.getFloat();

@ -356,10 +356,10 @@ namespace MWMechanics
ESM::WeaponType::Class weapclass = MWMechanics::getWeaponType(mWeaponType)->mWeaponClass;
if (weapclass == ESM::WeaponType::Thrown || weapclass == ESM::WeaponType::Ammo)
{
static const float multiplier = std::max(0.f, std::min(1.0f, Settings::Manager::getFloat("projectiles enchant multiplier", "Game")));
static const float multiplier = std::clamp(Settings::Manager::getFloat("projectiles enchant multiplier", "Game"), 0.f, 1.f);
MWWorld::Ptr player = getPlayer();
int itemsInInventoryCount = player.getClass().getContainerStore(player).count(mOldItemPtr.getCellRef().getRefId());
count = std::min(itemsInInventoryCount, std::max(1, int(getGemCharge() * multiplier / enchantPoints)));
count = player.getClass().getContainerStore(player).count(mOldItemPtr.getCellRef().getRefId());
count = std::clamp<int>(getGemCharge() * multiplier / enchantPoints, 1, count);
}
}

@ -545,9 +545,9 @@ namespace MWMechanics
x += ptr.getClass().getCreatureStats(ptr).getMagicEffects().get(ESM::MagicEffect::Charm).getMagnitude();
if(clamp)
return std::max(0,std::min(int(x),100));//, normally clamped to [0..100] when used
return int(x);
if (clamp)
return std::clamp<int>(x, 0, 100);//, normally clamped to [0..100] when used
return static_cast<int>(x);
}
int MechanicsManager::getBarterOffer(const MWWorld::Ptr& ptr,int basePrice, bool buying)
@ -649,9 +649,9 @@ namespace MWMechanics
int flee = npcStats.getAiSetting(MWMechanics::CreatureStats::AI_Flee).getBase();
int fight = npcStats.getAiSetting(MWMechanics::CreatureStats::AI_Fight).getBase();
npcStats.setAiSetting (MWMechanics::CreatureStats::AI_Flee,
std::max(0, std::min(100, flee + int(std::max(iPerMinChange, s)))));
std::clamp(flee + int(std::max(iPerMinChange, s)), 0, 100));
npcStats.setAiSetting (MWMechanics::CreatureStats::AI_Fight,
std::max(0, std::min(100, fight + int(std::min(-iPerMinChange, -s)))));
std::clamp(fight + int(std::min(-iPerMinChange, -s)), 0, 100));
}
float c = -std::abs(floor(r * fPerDieRollMult));
@ -689,10 +689,10 @@ namespace MWMechanics
float s = c * fPerDieRollMult * fPerTempMult;
int flee = npcStats.getAiSetting (CreatureStats::AI_Flee).getBase();
int fight = npcStats.getAiSetting (CreatureStats::AI_Fight).getBase();
npcStats.setAiSetting (CreatureStats::AI_Flee,
std::max(0, std::min(100, flee + std::min(-int(iPerMinChange), int(-s)))));
npcStats.setAiSetting (CreatureStats::AI_Fight,
std::max(0, std::min(100, fight + std::max(int(iPerMinChange), int(s)))));
npcStats.setAiSetting(CreatureStats::AI_Flee,
std::clamp(flee + std::min(-int(iPerMinChange), int(-s)), 0, 100));
npcStats.setAiSetting(CreatureStats::AI_Fight,
std::clamp(fight + std::max(int(iPerMinChange), int(s)), 0, 100));
}
x = floor(-c * fPerDieRollMult);

@ -371,7 +371,7 @@ int MWMechanics::NpcStats::getReputation() const
void MWMechanics::NpcStats::setReputation(int reputation)
{
// Reputation is capped in original engine
mReputation = std::min(255, std::max(0, reputation));
mReputation = std::clamp(reputation, 0, 255);
}
int MWMechanics::NpcStats::getCrimeId() const

@ -631,7 +631,7 @@ void applyMagicEffect(const MWWorld::Ptr& target, const MWWorld::Ptr& caster, co
if (!target.isInCell() || !target.getCell()->isExterior() || godmode)
break;
float time = world->getTimeStamp().getHour();
float timeDiff = std::min(7.f, std::max(0.f, std::abs(time - 13)));
float timeDiff = std::clamp(std::abs(time - 13.f), 0.f, 7.f);
float damageScale = 1.f - timeDiff / 7.f;
// When cloudy, the sun damage effect is halved
static float fMagicSunBlockedMult = world->getStore().get<ESM::GameSetting>().find("fMagicSunBlockedMult")->mValue.getFloat();

@ -162,7 +162,10 @@ namespace MWMechanics
float castChance = baseChance + castBonus;
castChance *= stats.getFatigueTerm();
return std::max(0.f, cap ? std::min(100.f, castChance) : castChance);
if (cap)
return std::clamp(castChance, 0.f, 100.f);
return std::max(castChance, 0.f);
}
float getSpellSuccessChance (const std::string& spellId, const MWWorld::Ptr& actor, int* effectiveSchool, bool cap, bool checkMagicka)

@ -128,8 +128,7 @@ namespace MWMechanics
}
// Take hit chance in account, but do not allow rating become negative.
float chance = getHitChance(actor, enemy, value) / 100.f;
rating *= std::min(1.f, std::max(0.01f, chance));
rating *= std::clamp(getHitChance(actor, enemy, value) / 100.f, 0.01f, 1.f);
if (weapclass != ESM::WeaponType::Ammo)
rating *= weapon->mData.mSpeed;

@ -15,9 +15,9 @@ namespace MWPhysics
const btVector3& position, const btScalar radius)
{
const btVector3 nearest(
std::max(aabbMin.x(), std::min(aabbMax.x(), position.x())),
std::max(aabbMin.y(), std::min(aabbMax.y(), position.y())),
std::max(aabbMin.z(), std::min(aabbMax.z(), position.z()))
std::clamp(position.x(), aabbMin.x(), aabbMax.x()),
std::clamp(position.y(), aabbMin.y(), aabbMax.y()),
std::clamp(position.z(), aabbMin.z(), aabbMax.z())
);
return nearest.distance(position) < radius;
}

@ -718,7 +718,7 @@ namespace MWPhysics
physicActor->setCanWaterWalk(waterCollision);
// Slow fall reduces fall speed by a factor of (effect magnitude / 200)
const float slowFall = 1.f - std::max(0.f, std::min(1.f, effects.get(ESM::MagicEffect::SlowFall).getMagnitude() * 0.005f));
const float slowFall = 1.f - std::clamp(effects.get(ESM::MagicEffect::SlowFall).getMagnitude() * 0.005f, 0.f, 1.f);
const bool godmode = ptr == world->getPlayerConstPtr() && world->getGodModeState();
const bool inert = stats.isDead() || (!godmode && stats.getMagicEffects().get(ESM::MagicEffect::Paralyze).getModifier() > 0);

@ -236,7 +236,7 @@ namespace MWRender
mTotalMovement += speed * duration;
speed /= (1.f + speed / 500.f);
float maxDelta = 300.f * duration;
mSmoothedSpeed += osg::clampBetween(speed - mSmoothedSpeed, -maxDelta, maxDelta);
mSmoothedSpeed += std::clamp(speed - mSmoothedSpeed, -maxDelta, maxDelta);
mMaxNextCameraDistance = mCameraDistance + duration * (100.f + mBaseCameraDistance);
updateStandingPreviewMode();
@ -434,7 +434,7 @@ namespace MWRender
{
const float epsilon = 0.000001f;
float limit = static_cast<float>(osg::PI_2) - epsilon;
mPitch = osg::clampBetween(angle, -limit, limit);
mPitch = std::clamp(angle, -limit, limit);
}
float Camera::getCameraDistance() const
@ -460,7 +460,7 @@ namespace MWRender
}
mIsNearest = mBaseCameraDistance <= mNearest;
mBaseCameraDistance = osg::clampBetween(mBaseCameraDistance, mNearest, mFurthest);
mBaseCameraDistance = std::clamp(mBaseCameraDistance, mNearest, mFurthest);
Settings::Manager::setFloat("third person camera distance", "Camera", mBaseCameraDistance);
}

@ -562,8 +562,8 @@ bool LocalMap::isPositionExplored (float nX, float nY, int x, int y)
if (!segment.mFogOfWarImage)
return false;
nX = std::max(0.f, std::min(1.f, nX));
nY = std::max(0.f, std::min(1.f, nY));
nX = std::clamp(nX, 0.f, 1.f);
nY = std::clamp(nY, 0.f, 1.f);
int texU = static_cast<int>((sFogOfWarResolution - 1) * nX);
int texV = static_cast<int>((sFogOfWarResolution - 1) * nY);
@ -648,7 +648,7 @@ void LocalMap::updatePlayer (const osg::Vec3f& position, const osg::Quat& orient
uint32_t clr = *(uint32_t*)data;
uint8_t alpha = (clr >> 24);
alpha = std::min( alpha, (uint8_t) (std::max(0.f, std::min(1.f, (sqrDist/sqrExploreRadius)))*255) );
alpha = std::min( alpha, (uint8_t) (std::clamp((sqrDist/sqrExploreRadius)*255, 0.f, 1.f)));
uint32_t val = (uint32_t) (alpha << 24);
if ( *data != val)
{

@ -733,12 +733,8 @@ namespace MWRender
}
void clampToCell(osg::Vec3f& cellPos)
{
osg::Vec2i min (mCell.x(), mCell.y());
osg::Vec2i max (mCell.x()+1, mCell.y()+1);
if (cellPos.x() < min.x()) cellPos.x() = min.x();
if (cellPos.x() > max.x()) cellPos.x() = max.x();
if (cellPos.y() < min.y()) cellPos.y() = min.y();
if (cellPos.y() > max.y()) cellPos.y() = max.y();
cellPos.x() = std::clamp<float>(cellPos.x(), mCell.x(), mCell.x() + 1);
cellPos.y() = std::clamp<float>(cellPos.y(), mCell.y(), mCell.y() + 1);
}
osg::Vec3f mPosition;
osg::Vec2i mCell;

@ -297,7 +297,8 @@ namespace MWRender
, mViewDistance(Settings::Manager::getFloat("viewing distance", "Camera"))
, mFieldOfViewOverridden(false)
, mFieldOfViewOverride(0.f)
, mFieldOfView(std::min(std::max(1.f, Settings::Manager::getFloat("field of view", "Camera")), 179.f))
, mFieldOfView(std::clamp(Settings::Manager::getFloat("field of view", "Camera"), 1.f, 179.f))
, mFirstPersonFieldOfView(std::clamp(Settings::Manager::getFloat("first person field of view", "Camera"), 1.f, 179.f))
{
bool reverseZ = SceneUtil::getReverseZ();
@ -517,8 +518,6 @@ namespace MWRender
NifOsg::Loader::setIntersectionDisabledNodeMask(Mask_Effect);
Nif::NIFFile::setLoadUnsupportedFiles(Settings::Manager::getBool("load unsupported nif files", "Models"));
float firstPersonFov = Settings::Manager::getFloat("first person field of view", "Camera");
mFirstPersonFieldOfView = std::min(std::max(1.f, firstPersonFov), 179.f);
mStateUpdater->setFogEnd(mViewDistance);
mRootNode->getOrCreateStateSet()->addUniform(new osg::Uniform("simpleWater", false));

@ -305,8 +305,7 @@ public:
void setWaterLevel(float waterLevel)
{
const float refractionScale = std::min(1.0f, std::max(0.0f,
Settings::Manager::getFloat("refraction scale", "Water")));
const float refractionScale = std::clamp(Settings::Manager::getFloat("refraction scale", "Water"), 0.f, 1.f);
mViewMatrix = osg::Matrix::scale(1, 1, refractionScale) *
osg::Matrix::translate(0, 0, (1.0 - refractionScale) * waterLevel);
@ -400,7 +399,7 @@ private:
unsigned int calcNodeMask()
{
int reflectionDetail = Settings::Manager::getInt("reflection detail", "Water");
reflectionDetail = std::min(5, std::max(mInterior ? 2 : 0, reflectionDetail));
reflectionDetail = std::clamp(reflectionDetail, mInterior ? 2 : 0, 5);
unsigned int extraMask = 0;
if(reflectionDetail >= 1) extraMask |= Mask_Terrain;
if(reflectionDetail >= 2) extraMask |= Mask_Static;
@ -583,7 +582,7 @@ void Water::createSimpleWaterStateSet(osg::Node* node, float alpha)
// Add animated textures
std::vector<osg::ref_ptr<osg::Texture2D> > textures;
int frameCount = std::max(0, std::min(Fallback::Map::getInt("Water_SurfaceFrameCount"), 320));
const int frameCount = std::clamp(Fallback::Map::getInt("Water_SurfaceFrameCount"), 0, 320);
const std::string& texture = Fallback::Map::getString("Water_SurfaceTexture");
for (int i=0; i<frameCount; ++i)
{
@ -724,7 +723,7 @@ Water::~Water()
void Water::listAssetsToPreload(std::vector<std::string> &textures)
{
int frameCount = std::max(0, std::min(Fallback::Map::getInt("Water_SurfaceFrameCount"), 320));
const int frameCount = std::clamp(Fallback::Map::getInt("Water_SurfaceFrameCount"), 0, 320);
const std::string& texture = Fallback::Map::getString("Water_SurfaceTexture");
for (int i=0; i<frameCount; ++i)
{

@ -208,8 +208,7 @@ namespace MWScript
{
if(!repeat)
repeat = true;
Interpreter::Type_Integer idleValue = runtime[0].mInteger;
idleValue = std::min(255, std::max(0, idleValue));
Interpreter::Type_Integer idleValue = std::clamp(runtime[0].mInteger, 0, 255);
idleList.push_back(idleValue);
runtime.pop();
--arg0;

@ -108,7 +108,7 @@ namespace MWScript
chances.reserve(10);
while(arg0 > 0)
{
chances.push_back(std::max(0, std::min(127, runtime[0].mInteger)));
chances.push_back(std::clamp(runtime[0].mInteger, 0, 127));
runtime.pop();
arg0--;
}

@ -40,7 +40,7 @@ void Sound_Loudness::analyzeLoudness(const std::vector< char >& data)
else if (mSampleType == SampleType_Float32)
{
value = *reinterpret_cast<const float*>(&mQueue[sample*advance]);
value = std::max(-1.f, std::min(1.f, value)); // Float samples *should* be scaled to [-1,1] already.
value = std::clamp(value, -1.f, 1.f); // Float samples *should* be scaled to [-1,1] already.
}
sum += value*value;
@ -64,8 +64,7 @@ float Sound_Loudness::getLoudnessAtTime(float sec) const
if(mSamplesPerSec <= 0.0f || mSamples.empty() || sec < 0.0f)
return 0.0f;
size_t index = static_cast<size_t>(sec * mSamplesPerSec);
index = std::max<size_t>(0, std::min(index, mSamples.size()-1));
size_t index = std::clamp<size_t>(sec * mSamplesPerSec, 0, mSamples.size() - 1);
return mSamples[index];
}

@ -10,7 +10,7 @@ namespace MWSound
{
float clamp(float value)
{
return std::max(0.0f, std::min(1.0f, value));
return std::clamp(value, 0.f, 1.f);
}
}

@ -1334,7 +1334,7 @@ namespace MWWorld
* currently it's done so for rotating the camera, which needs
* clamping.
*/
objRot[0] = osg::clampBetween<float>(objRot[0], -osg::PI_2, osg::PI_2);
objRot[0] = std::clamp<float>(objRot[0], -osg::PI_2, osg::PI_2);
objRot[1] = Misc::normalizeAngle(objRot[1]);
objRot[2] = Misc::normalizeAngle(objRot[2]);
}
@ -1901,7 +1901,7 @@ namespace MWWorld
const auto& magicEffects = player.getClass().getCreatureStats(player).getMagicEffects();
if (!mGodMode)
blind = static_cast<int>(magicEffects.get(ESM::MagicEffect::Blind).getMagnitude());
MWBase::Environment::get().getWindowManager()->setBlindness(std::max(0, std::min(100, blind)));
MWBase::Environment::get().getWindowManager()->setBlindness(std::clamp(blind, 0, 100));
int nightEye = static_cast<int>(magicEffects.get(ESM::MagicEffect::NightEye).getMagnitude());
mRendering->setNightEyeFactor(std::min(1.f, (nightEye/100.f)));

@ -169,7 +169,7 @@ namespace ESM
{
float height = mLandData->mHeights[int(row * vertMult) * ESM::Land::LAND_SIZE + int(col * vertMult)];
height /= height > 0 ? 128.f : 16.f;
height = std::min(max, std::max(min, height));
height = std::clamp(height, min, max);
wnam[row * LAND_GLOBAL_MAP_LOD_SIZE_SQRT + col] = static_cast<signed char>(height);
}
}

@ -145,7 +145,7 @@ namespace Gui
FontLoader::FontLoader(ToUTF8::FromType encoding, const VFS::Manager* vfs, const std::string& userDataPath, float scalingFactor)
: mVFS(vfs)
, mUserDataPath(userDataPath)
, mFontHeight(16)
, mFontHeight(std::clamp(Settings::Manager::getInt("font size", "GUI"), 12, 20))
, mScalingFactor(scalingFactor)
{
if (encoding == ToUTF8::WINDOWS_1252)
@ -153,9 +153,6 @@ namespace Gui
else
mEncoding = encoding;
int fontSize = Settings::Manager::getInt("font size", "GUI");
mFontHeight = std::min(std::max(12, fontSize), 20);
MyGUI::ResourceManager::getInstance().unregisterLoadXmlDelegate("Resource");
MyGUI::ResourceManager::getInstance().registerLoadXmlDelegate("Resource") = MyGUI::newDelegate(this, &FontLoader::loadFontFromXml);
}
@ -549,7 +546,7 @@ namespace Gui
// to allow to configure font size via config file, without need to edit XML files.
// Also we should take UI scaling factor in account.
int resolution = Settings::Manager::getInt("ttf resolution", "GUI");
resolution = std::min(960, std::max(48, resolution)) * mScalingFactor;
resolution = std::clamp(resolution, 48, 960) * mScalingFactor;
MyGUI::xml::ElementPtr resolutionNode = resourceNode->createChild("Property");
resolutionNode->addAttribute("key", "Resolution");
@ -591,7 +588,7 @@ namespace Gui
// setup separate fonts with different Resolution to fit these windows.
// These fonts have an internal prefix.
int resolution = Settings::Manager::getInt("ttf resolution", "GUI");
resolution = std::min(960, std::max(48, resolution));
resolution = std::clamp(resolution, 48, 960);
float currentX = Settings::Manager::getInt("resolution x", "Video");
float currentY = Settings::Manager::getInt("resolution y", "Video");

@ -57,7 +57,7 @@ float ControllerFunction::calculate(float value) const
}
case Constant:
default:
return std::min(mStopTime, std::max(mStartTime, time));
return std::clamp(time, mStartTime, mStopTime);
}
}

@ -27,8 +27,7 @@ namespace SceneUtil
mShadowSettings->setLightNum(0);
mShadowSettings->setReceivesShadowTraversalMask(~0u);
int numberOfShadowMapsPerLight = Settings::Manager::getInt("number of shadow maps", "Shadows");
numberOfShadowMapsPerLight = std::max(1, std::min(numberOfShadowMapsPerLight, 8));
const int numberOfShadowMapsPerLight = std::clamp(Settings::Manager::getInt("number of shadow maps", "Shadows"), 1, 8);
mShadowSettings->setNumShadowMapsPerLight(numberOfShadowMapsPerLight);
mShadowSettings->setBaseShadowTextureUnit(8 - numberOfShadowMapsPerLight);
@ -36,7 +35,7 @@ namespace SceneUtil
const float maximumShadowMapDistance = Settings::Manager::getFloat("maximum shadow map distance", "Shadows");
if (maximumShadowMapDistance > 0)
{
const float shadowFadeStart = std::min(std::max(0.f, Settings::Manager::getFloat("shadow fade start", "Shadows")), 1.f);
const float shadowFadeStart = std::clamp(Settings::Manager::getFloat("shadow fade start", "Shadows"), 0.f, 1.f);
mShadowSettings->setMaximumShadowMapDistance(maximumShadowMapDistance);
mShadowTechnique->setShadowFadeStart(maximumShadowMapDistance * shadowFadeStart);
}
@ -78,8 +77,7 @@ namespace SceneUtil
if (!Settings::Manager::getBool("enable shadows", "Shadows"))
return;
int numberOfShadowMapsPerLight = Settings::Manager::getInt("number of shadow maps", "Shadows");
numberOfShadowMapsPerLight = std::max(1, std::min(numberOfShadowMapsPerLight, 8));
const int numberOfShadowMapsPerLight = std::clamp(Settings::Manager::getInt("number of shadow maps", "Shadows"), 1, 8);
int baseShadowTextureUnit = 8 - numberOfShadowMapsPerLight;

@ -31,15 +31,11 @@ namespace Gui
}
private:
static int clamp(const int& value, const int& lowBound, const int& highBound)
{
return std::min(std::max(lowBound, value), highBound);
}
std::string getFontSize()
{
// Note: we can not use the FontLoader here, so there is a code duplication a bit.
static const std::string fontSize = std::to_string(clamp(Settings::Manager::getInt("font size", "GUI"), 12, 20));
static const std::string fontSize = std::to_string(std::clamp(Settings::Manager::getInt("font size", "GUI"), 12, 20));
return fontSize;
}
};

@ -31,7 +31,7 @@ namespace Gui
try
{
mValue = std::stoi(newCaption);
int capped = std::min(mMaxValue, std::max(mValue, mMinValue));
int capped = std::clamp(mValue, mMinValue, mMaxValue);
if (capped != mValue)
{
mValue = capped;

Loading…
Cancel
Save