OpenTTD
Functions
math_func.hpp File Reference

Integer math functions. More...

Go to the source code of this file.

Functions

template<typename T >
static T max (const T a, const T b)
 Returns the maximum of two values. More...
 
template<typename T >
static T min (const T a, const T b)
 Returns the minimum of two values. More...
 
static int min (const int a, const int b)
 Returns the minimum of two integer. More...
 
static uint minu (const uint a, const uint b)
 Returns the minimum of two unsigned integers. More...
 
template<typename T >
static T abs (const T a)
 Returns the absolute value of (scalar) variable. More...
 
template<typename T >
static T Align (const T x, uint n)
 Return the smallest multiple of n equal or greater than x. More...
 
template<typename T >
static T * AlignPtr (T *x, uint n)
 Return the smallest multiple of n equal or greater than x Applies to pointers only. More...
 
template<typename T >
static T Clamp (const T a, const T min, const T max)
 Clamp a value between an interval. More...
 
static int Clamp (const int a, const int min, const int max)
 Clamp an integer between an interval. More...
 
static uint ClampU (const uint a, const uint min, const uint max)
 Clamp an unsigned integer between an interval. More...
 
static int32 ClampToI32 (const int64 a)
 Reduce a signed 64-bit int to a signed 32-bit one. More...
 
static uint16 ClampToU16 (const uint64 a)
 Reduce an unsigned 64-bit int to an unsigned 16-bit one. More...
 
template<typename T >
static T Delta (const T a, const T b)
 Returns the (absolute) difference between two (scalar) variables. More...
 
template<typename T >
static bool IsInsideBS (const T x, const uint base, const uint size)
 Checks if a value is between a window started at some base point. More...
 
template<typename T >
static bool IsInsideMM (const T x, const uint min, const uint max)
 Checks if a value is in an interval. More...
 
template<typename T >
static void Swap (T &a, T &b)
 Type safe swap operation. More...
 
static uint ToPercent8 (uint i)
 Converts a "fract" value 0..255 to "percent" value 0..100. More...
 
static uint ToPercent16 (uint i)
 Converts a "fract" value 0..65535 to "percent" value 0..100. More...
 
int LeastCommonMultiple (int a, int b)
 Compute least common multiple (lcm) of arguments a and b, the smallest integer value that is a multiple of both a and b. More...
 
int GreatestCommonDivisor (int a, int b)
 Compute greatest common divisor (gcd) of a and b. More...
 
int DivideApprox (int a, int b)
 Deterministic approximate division. More...
 
static uint CeilDiv (uint a, uint b)
 Computes ceil(a / b) for non-negative a and b. More...
 
static uint Ceil (uint a, uint b)
 Computes ceil(a / b) * b for non-negative a and b. More...
 
static int RoundDivSU (int a, uint b)
 Computes round(a / b) for signed a and unsigned b. More...
 
uint32 IntSqrt (uint32 num)
 Compute the integer square root. More...
 

Detailed Description

Integer math functions.

Definition in file math_func.hpp.

Function Documentation

◆ abs()

template<typename T >
static T abs ( const T  a)
inlinestatic

◆ Align()

template<typename T >
static T Align ( const T  x,
uint  n 
)
inlinestatic

Return the smallest multiple of n equal or greater than x.

Note
n must be a power of 2
Parameters
xThe min value
nThe base of the number we are searching
Returns
The smallest multiple of n equal or greater than x

Definition at line 97 of file math_func.hpp.

Referenced by SmallVector< SmallPair< uint32, SmallPair< size_t, const void *> >, 16 >::Compact(), and SmallVector< SmallPair< uint32, SmallPair< size_t, const void *> >, 16 >::Resize().

◆ AlignPtr()

template<typename T >
static T* AlignPtr ( T *  x,
uint  n 
)
inlinestatic

Return the smallest multiple of n equal or greater than x Applies to pointers only.

Note
n must be a power of 2
Parameters
xThe min value
nThe base of the number we are searching
Returns
The smallest multiple of n equal or greater than x
See also
Align()

Definition at line 115 of file math_func.hpp.

◆ Ceil()

static uint Ceil ( uint  a,
uint  b 
)
inlinestatic

Computes ceil(a / b) * b for non-negative a and b.

Parameters
aNumerator
bDenominator
Returns
a rounded up to the nearest multiple of b.

Definition at line 327 of file math_func.hpp.

References CeilDiv().

Referenced by ResizeWindow(), and VehicleGroupWindow::UpdateWidgetSize().

◆ CeilDiv()

static uint CeilDiv ( uint  a,
uint  b 
)
inlinestatic

Computes ceil(a / b) for non-negative a and b.

Parameters
aNumerator
bDenominator
Returns
Quotient, rounded up

Definition at line 316 of file math_func.hpp.

Referenced by BuildLandLegend(), Ceil(), IndustryCargoesWindow::ComputeCargoDisplay(), IndustryCargoesWindow::ComputeIndustryDisplay(), GetLoadAmount(), SmallMapWindow::GetNumberRowsLegend(), ScaleByMapSize(), ScaleByMapSize1D(), and NWidgetMatrix::SetCount().

◆ Clamp() [1/2]

template<typename T >
static T Clamp ( const T  a,
const T  min,
const T  max 
)
inlinestatic

Clamp a value between an interval.

This function returns a value which is between the given interval of min and max. If the given value is in this interval the value itself is returned otherwise the border of the interval is returned, according which side of the interval was 'left'.

Note
The min value must be less or equal of max or you get some unexpected results.
Parameters
aThe value to clamp/truncate.
minThe minimum of the interval.
maxthe maximum of the interval.
Returns
A value between min and max which is closest to a.
See also
ClampU(uint, uint, uint)
Clamp(int, int, int)

Definition at line 139 of file math_func.hpp.

Referenced by BridgeChangeInfo(), BuildAirportWindow::BuildAirportClassDropDown(), ClickChangeDateCheat(), ClickChangeMaxHlCheat(), EnsureVisibleCaption(), GetAmplitude(), Path::GetCapacityRatio(), GetGlobalVariable(), GetNearbyTileInformation(), GetSavegameFormat(), GetServiceIntervalClamped(), GetTileHeightBelowAircraft(), IndustriesScopeResolver::GetVariable(), AirportScopeResolver::GetVariable(), VehicleScopeResolver::GetVariable(), GenerateLandscapeWindow::OnDropdownSelect(), BuildBridgeWindow::OnInitialPosition(), TooltipsWindow::OnInitialPosition(), CreateScenarioWindow::OnQueryTextFinished(), OrdersWindow::OnQueryTextFinished(), NetworkUDPSocketHandler::ReceiveNetworkGameInfo(), SearchMapEdge(), AIConfig::SetSetting(), ScriptConfig::SetSetting(), SetStartingYear(), Scrollbar::UpdatePosition(), and VpSelectTilesWithMethod().

◆ Clamp() [2/2]

static int Clamp ( const int  a,
const int  min,
const int  max 
)
inlinestatic

Clamp an integer between an interval.

This function returns a value which is between the given interval of min and max. If the given value is in this interval the value itself is returned otherwise the border of the interval is returned, according which side of the interval was 'left'.

Note
The min value must be less or equal of max or you get some unexpected results.
Parameters
aThe value to clamp/truncate.
minThe minimum of the interval.
maxthe maximum of the interval.
Returns
A value between min and max which is closest to a.
See also
ClampU(uint, uint, uint)

Definition at line 163 of file math_func.hpp.

References max(), and min().

◆ ClampToI32()

static int32 ClampToI32 ( const int64  a)
inlinestatic

Reduce a signed 64-bit int to a signed 32-bit one.

This function clamps a 64-bit integer to a 32-bit integer. If the 64-bit value is smaller than the smallest 32-bit integer value 0x80000000 this value is returned (the left one bit is the sign bit). If the 64-bit value is greater than the greatest 32-bit integer value 0x7FFFFFFF this value is returned. In all other cases the 64-bit value 'fits' in a 32-bits integer field and so the value is casted to int32 and returned.

Parameters
aThe 64-bit value to clamps
Returns
The 64-bit value reduced to a 32-bit value
See also
Clamp(int, int, int)

Definition at line 203 of file math_func.hpp.

Referenced by EngineCostSorter(), EnginePowerVsRunningCostSorter(), EngineRunningCostSorter(), ParseIntList(), VehicleProfitLastYearSorter(), VehicleProfitThisYearSorter(), VehicleTimeToLiveSorter(), and VehicleValueSorter().

◆ ClampToU16()

static uint16 ClampToU16 ( const uint64  a)
inlinestatic

Reduce an unsigned 64-bit int to an unsigned 16-bit one.

Parameters
aThe 64-bit value to clamp
Returns
The 64-bit value reduced to a 16-bit value
See also
ClampU(uint, uint, uint)

Definition at line 215 of file math_func.hpp.

Referenced by TownScopeResolver::GetVariable(), and FileStringReader::ReadLine().

◆ ClampU()

static uint ClampU ( const uint  a,
const uint  min,
const uint  max 
)
inlinestatic

Clamp an unsigned integer between an interval.

This function returns a value which is between the given interval of min and max. If the given value is in this interval the value itself is returned otherwise the border of the interval is returned, according which side of the interval was 'left'.

Note
The min value must be less or equal of max or you get some unexpected results.
Parameters
aThe value to clamp/truncate.
minThe minimum of the interval.
maxthe maximum of the interval.
Returns
A value between min and max which is closest to a.
See also
Clamp(int, int, int)

Definition at line 184 of file math_func.hpp.

References max(), and min().

Referenced by ConvertFromOldCompanyManagerFace(), and SavePresetWindow::UpdateWidgetSize().

◆ Delta()

template<typename T >
static T Delta ( const T  a,
const T  b 
)
inlinestatic

Returns the (absolute) difference between two (scalar) variables.

Parameters
aThe first scalar
bThe second scalar
Returns
The absolute difference between the given scalars

Definition at line 232 of file math_func.hpp.

Referenced by DistanceManhattan(), DistanceMax(), DistanceMaxPlusManhattan(), NPFDistanceTrack(), and VpSelectTilesWithMethod().

◆ DivideApprox()

int DivideApprox ( int  a,
int  b 
)

Deterministic approximate division.

Cancels out division errors stemming from the integer nature of the division over multiple runs.

Parameters
aDividend.
bDivisor.
Returns
a/b or (a/b)+1.

Definition at line 59 of file math_func.cpp.

References abs().

◆ GreatestCommonDivisor()

int GreatestCommonDivisor ( int  a,
int  b 
)

Compute greatest common divisor (gcd) of a and b.

Parameters
aFirst number.
bsecond number.
Returns
Greatest common divisor of a and b.

Definition at line 41 of file math_func.cpp.

Referenced by LeastCommonMultiple().

◆ IntSqrt()

uint32 IntSqrt ( uint32  num)

Compute the integer square root.

Parameters
numRadicand.
Returns
Rounded integer square root.
Note
Algorithm taken from http://en.wikipedia.org/wiki/Methods_of_computing_square_roots

Definition at line 79 of file math_func.cpp.

Referenced by RoundDivSU().

◆ IsInsideBS()

template<typename T >
static bool IsInsideBS ( const T  x,
const uint  base,
const uint  size 
)
inlinestatic

Checks if a value is between a window started at some base point.

This function checks if the value x is between the value of base and base+size. If x equals base this returns true. If x equals base+size this returns false.

Parameters
xThe value to check
baseThe base value of the interval
sizeThe size of the interval
Returns
True if the value is in the interval, false else.

Definition at line 250 of file math_func.hpp.

Referenced by CmdPlantTree(), DrawTileSelection(), NewGRFInspectWindow::HasVariableParameter(), Scrollbar::IsVisible(), and IndustryViewWindow::OnClick().

◆ IsInsideMM()

template<typename T >
static bool IsInsideMM ( const T  x,
const uint  min,
const uint  max 
)
inlinestatic

◆ LeastCommonMultiple()

int LeastCommonMultiple ( int  a,
int  b 
)

Compute least common multiple (lcm) of arguments a and b, the smallest integer value that is a multiple of both a and b.

Parameters
aFirst number.
bsecond number.
Returns
Least common multiple of values a and b.
Note
This function only works for non-negative values of a and b.

Definition at line 26 of file math_func.cpp.

References GreatestCommonDivisor().

◆ max()

template<typename T >
static T max ( const T  a,
const T  b 
)
inlinestatic

Returns the maximum of two values.

This function returns the greater value of two given values. If they are equal the value of a is returned.

Parameters
aThe first value
bThe second value
Returns
The greater value or a if equals

Definition at line 26 of file math_func.hpp.

Referenced by OrthogonalTileArea::Add(), LinkGraph::AddNode(), LinkGraphOverlay::AddStats(), CalcEngineReliability(), CalcPercentVehicleFilled(), ChangeTownRating(), CheckBridgeAvailability(), CheckIfFarEnoughFromConflictingIndustry(), GraphicsSet::CheckMD5(), CheckOverflow(), Clamp(), ClampU(), ClampXYToMap(), CmdDecreaseLoan(), IndustryCargoesWindow::ComputeCargoDisplay(), VehicleGroupWindow::ComputeGroupInfoSize(), IndustryCargoesWindow::ComputeIndustryDisplay(), ConvertFromOldCompanyManagerFace(), SimplePool< Titem, Tindex, Tgrowth_step, Tmax_size >::Create(), DistanceMax(), StoryBookWindow::DrawActionElement(), DrawButtonDropdown(), DrawCaption(), LinkGraphOverlay::DrawContent(), NetworkContentListWindow::DrawMatrix(), DrawString(), DrawText(), CompanyStationsWindow::DrawWidget(), SymmetricScaler::EffectiveSupply(), EnginePowerVsRunningCostSorter(), HeaderFileWriter::Finalise(), Window::FindWindowPlacementAndResize(), GamelogInfo(), GetAmplitude(), Path::GetCapacityRatio(), GetGlobalVariable(), FallbackParagraphLayout::FallbackLine::GetLeading(), SettingsContainer::GetMaxHelpHeight(), SmallMapWindow::GetNumberRowsLegend(), GetTileSlopeGivenHeight(), GetTrainDetailsWndVScroll(), GetVehicleListHeight(), IsCloseToTown(), LinkGraph::EdgeWrapper< BaseEdge >::LastUpdate(), LocalGetWindowPlacement(), MakeNWidget(), MarkViewportDirty(), maxdim(), NewGRFDisplay(), IndustryViewWindow::OnClick(), IConsoleWindow::OnHundredthTick(), CompanyFinancesWindow::OnHundredthTick(), IndustryCargoesWindow::OnInit(), ReplaceVehicleWindow::OnPaint(), RefitWindow::OnPaint(), AIDebugWindow::OnPaint(), BuildVehicleWindow::OnPaint(), NewsWindow::OnTick(), ParseResolution(), RailConvertCost(), Station::RecomputeIndustriesNear(), ResizeWindow(), SanitizeSpriteOffset(), LinkGraph::Scale(), SeedModChance(), SymmetricScaler::SetDemandPerNode(), SymmetricScaler::SetDemands(), SetDParamMaxValue(), NWidgetResizeBase::SetMinimalSize(), SetSnowLine(), TextfileWindow::SetupScrollbars(), NWidgetServerListHeader::SetupSmallestSize(), NWidgetHorizontal::SetupSmallestSize(), NWidgetVertical::SetupSmallestSize(), NWidgetToolbarContainer::SetupSmallestSize(), NewsWindow::SetWindowTop(), LinkGraph::ShiftDates(), SmallMapWindow::SmallMapCenterOnCurrentPos(), TruncateCargo(), UpdateAircraftSpeed(), UpdateLoadUnloadTicks(), Scrollbar::UpdatePosition(), TextfileWindow::UpdateWidgetSize(), LandInfoWindow::UpdateWidgetSize(), BuildObjectWindow::UpdateWidgetSize(), ErrmsgWindow::UpdateWidgetSize(), TimetableWindow::UpdateWidgetSize(), NewGRFParametersWindow::UpdateWidgetSize(), BuildAirportWindow::UpdateWidgetSize(), CompanyFinancesWindow::UpdateWidgetSize(), MusicTrackSelectionWindow::UpdateWidgetSize(), AISettingsWindow::UpdateWidgetSize(), GameOptionsWindow::UpdateWidgetSize(), VehicleGroupWindow::UpdateWidgetSize(), BaseGraphWindow::UpdateWidgetSize(), NetworkGameWindow::UpdateWidgetSize(), NetworkContentListWindow::UpdateWidgetSize(), SpriteAlignerWindow::UpdateWidgetSize(), MessageHistoryWindow::UpdateWidgetSize(), BuildRailStationWindow::UpdateWidgetSize(), CompanyLeagueWindow::UpdateWidgetSize(), StationViewWindow::UpdateWidgetSize(), BuildVehicleWindow::UpdateWidgetSize(), BuildSignalWindow::UpdateWidgetSize(), CompanyInfrastructureWindow::UpdateWidgetSize(), GameSettingsWindow::UpdateWidgetSize(), NetworkClientListWindow::UpdateWidgetSize(), SavePresetWindow::UpdateWidgetSize(), IndustryCargoesWindow::UpdateWidgetSize(), ScanProgressWindow::UpdateWidgetSize(), ScenarioEditorToolbarWindow::UpdateWidgetSize(), and VehicleViewWindow::UpdateWidgetSize().

◆ min() [1/2]

template<typename T >
static T min ( const T  a,
const T  b 
)
inlinestatic

Returns the minimum of two values.

This function returns the smaller value of two given values. If they are equal the value of b is returned.

Parameters
aThe first value
bThe second value
Returns
The smaller value or b if equals

Definition at line 42 of file math_func.hpp.

Referenced by OrthogonalTileArea::Add(), OutputBuffer::Add(), Path::AddFlow(), CalcGRFMD5Sum(), CHashTableT< Titem_, Thash_bits_open_ >::CalcHash(), CheckBridgeAvailability(), CheckIfFarEnoughFromConflictingIndustry(), MD5File::CheckMD5(), ChopLumberMillTrees(), Clamp(), ClampU(), ClampXYToMap(), CmdDecreaseLoan(), CmdGiveMoney(), DeliverGoodsToIndustry(), SimplePool< Titem, Tindex, Tgrowth_step, Tmax_size >::Destroy(), DistanceFromEdge(), DoCreateNewIndustry(), ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(), LinkGraphOverlay::DrawContent(), LinkGraphOverlay::DrawStationDots(), CompanyFinancesWindow::DrawWidget(), CompanyStationsWindow::DrawWidget(), BuildVehicleWindow::DrawWidget(), MCF1stPass::FindCycleFlow(), FioSkipBytes(), MemoryDumper::Flush(), Path::Fork(), GetAircraftFlightLevelBounds(), IConsoleWindow::GetCaretPosition(), GetCountAndDistanceOfClosestInstance(), Ship::GetCurrentMaxSpeed(), GetMinimalAirportDistanceToTile(), GetOtherAqueductEnd(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::GetSpeedLimit(), IConsoleWindow::GetTextBoundingRect(), IConsoleWindow::GetTextCharacterAtPosition(), GetTileSlopeGivenHeight(), GetTileZ(), IndustriesScopeResolver::GetVariable(), ObjectScopeResolver::GetVariable(), HeightMapCoastLines(), IncreaseStats(), CapacityAnnotation::IsBetter(), IsCloseToTown(), StationCargoList::Load(), Blitter_32bppBase::MakeGrey(), IndustryBuildData::MonthlyLoop(), NetworkServer_Tick(), NPFDistanceTrack(), NewGRFWindow::OnDragDrop(), NewGRFWindow::OnMouseDrag(), CYapfDestinationTileT< Types >::PfCalcEstimate(), CYapfDestinationTileOrStationRailT< Types >::PfCalcEstimate(), CYapfDestinationTileRoadT< Types >::PfCalcEstimate(), PlaceTree(), RailConvertCost(), PacketReader::Read(), NetworkHTTPSocketHandler::Receive(), ServerNetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(), ClientNetworkContentSocketHandler::RequestContentList(), VehicleCargoList::Reroute(), VehicleCargoList::Return(), BuildObjectWindow::SelectOtherObject(), SetSnowLine(), NewsWindow::SetWindowTop(), VehicleCargoList::Shift(), SlCalcNetStringLen(), StartupEngines(), CompanyStationsWindow::StationRatingMinSorter(), TGPGetMaxHeight(), TileLoopClearAlps(), TransportIndustryGoods(), TriggerIndustryProduction(), VehicleCargoList::Truncate(), StationCargoList::Truncate(), VehicleCargoList::Unload(), UpdateAircraftSpeed(), UpdateIndustryStatistics(), LandInfoWindow::UpdateWidgetSize(), TooltipsWindow::UpdateWidgetSize(), VehicleCargoList::Reassign< VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER >(), vseprintf(), and PacketWriter::Write().

◆ min() [2/2]

static int min ( const int  a,
const int  b 
)
inlinestatic

Returns the minimum of two integer.

This function returns the smaller value of two given integers.

Parameters
aThe first integer
bThe second integer
Returns
The smaller value

Definition at line 56 of file math_func.hpp.

◆ minu()

static uint minu ( const uint  a,
const uint  b 
)
inlinestatic

Returns the minimum of two unsigned integers.

This function returns the smaller value of two given unsigned integers.

Parameters
aThe first unsigned integer
bThe second unsigned integer
Returns
The smaller value

Definition at line 70 of file math_func.hpp.

Referenced by IndustryViewWindow::OnClick(), and TimetableWindow::OnQueryTextFinished().

◆ RoundDivSU()

static int RoundDivSU ( int  a,
uint  b 
)
inlinestatic

Computes round(a / b) for signed a and unsigned b.

Parameters
aNumerator
bDenominator
Returns
Quotient, rounded to nearest

Definition at line 338 of file math_func.hpp.

References IntSqrt().

Referenced by ScenarioEditorLandscapeGenerationWindow::DrawWidget().

◆ Swap()

template<typename T >
static void Swap ( T &  a,
T &  b 
)
inlinestatic

Type safe swap operation.

Parameters
avariable to swap with b
bvariable to swap with a

Definition at line 277 of file math_func.hpp.

Referenced by CalcHeightdiff(), IndustryDirectoryWindow::GetCargoTransportedSortValue(), IsInRangeInclusive(), ReverseTrainSwapVeh(), FontState::SetPreviousColour(), FlowStat::SwapShares(), and UpdateTileSelection().

◆ ToPercent16()

static uint ToPercent16 ( uint  i)
inlinestatic

Converts a "fract" value 0..65535 to "percent" value 0..100.

Parameters
ivalue to convert, range 0..65535
Returns
value in range 0..100

Definition at line 300 of file math_func.hpp.

◆ ToPercent8()

static uint ToPercent8 ( uint  i)
inlinestatic

Converts a "fract" value 0..255 to "percent" value 0..100.

Parameters
ivalue to convert, range 0..255
Returns
value in range 0..100

Definition at line 289 of file math_func.hpp.

Referenced by IndustryDirectoryWindow::GetIndustryString().